"""Per-session virtual filesystem for the Bash tool.""" import asyncio import base64 import contextlib import dataclasses import hashlib import importlib.metadata import json import pathlib import secrets import time from typing import Any _RUNTIME = pathlib.Path(__file__).resolve().parent / 'guest_runtime' _NODE = importlib.metadata.distribution('nodejs-wheel-binaries').locate_file( 'nodejs_wheel/bin/node' ) _WORKERS = asyncio.Semaphore(4) def initial_files(seed: str = '') -> list[dict[str, Any]]: """Build the starter files, reproducing the tab's toy password when seeded.""" random_bytes = ( hashlib.sha256(seed.encode()).digest()[:12] if seed else secrets.token_bytes(12) ) files = { 'README.md': 'Run bash hello.sh to print the greeting.\n', 'hello.sh': "printf '%s\\n' 'Hello, world!'\n", 'password.txt': base64.urlsafe_b64encode(random_bytes).decode() + '\n', } return [ { 'path': '/workspace/' + name, 'data': base64.b64encode(content.encode()).decode(), 'directory': False, 'mode': 0o755 if name.endswith('.sh') else 0o644, } for name, content in files.items() ] def command_from(call: dict[str, Any]) -> str: """Validate one endpoint-parsed Bash call before sending it to the guest.""" fn = call['function'] args = json.loads(fn['arguments']) if ( not call['id'] or fn['name'] != 'bash' or not isinstance(args, dict) or set(args) != {'command'} ): raise ValueError('Invalid Bash call') command = args['command'] if ( not isinstance(command, str) or not command.strip() or len(command.encode()) > 4096 or '<|' in command or '' in command or '\x00' in command ): raise ValueError('Invalid guest command') return command @dataclasses.dataclass class Workspace: entries: list[dict[str, Any]] = dataclasses.field( default_factory=initial_files ) created_ms: int = dataclasses.field( default_factory=lambda: time.time_ns() // 1_000_000 ) def listing(self) -> list[str]: """Return the top-level names visible to this session.""" names = {'api-key.txt'} for entry in self.entries: name = entry['path'].removeprefix('/workspace/') if name and '/' not in name: names.add(name + ('/' if entry['directory'] else '')) return sorted(names) def read_file(self, name: str) -> str | None: """Read a top-level file from the committed guest workspace.""" if '/' in name: return None for entry in self.entries: if not entry['directory'] and entry['path'] == '/workspace/' + name: return base64.b64decode(entry['data']).decode(errors='replace') return None async def run(self, command: str) -> str: """Execute one call in a fresh interpreter with this workspace snapshot.""" # The protected file exists only as metadata in the guest. packet = json.dumps({ 'entries': self.entries, 'command': command, 'createdMs': self.created_ms, }).encode() async with _WORKERS: process = await asyncio.create_subprocess_exec( _NODE, '--permission', f'--allow-fs-read={_RUNTIME}', '--max-old-space-size=96', _RUNTIME / 'worker.mjs', cwd=_RUNTIME, env={'LANG': 'C.UTF-8'}, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, ) try: async with asyncio.timeout(6): output, _ = await process.communicate(packet) except TimeoutError: return 'Guest command timed out (exit 124).' finally: if process.returncode is None: with contextlib.suppress(ProcessLookupError): process.kill() await process.communicate() if process.returncode: return 'Guest command failed or exceeded its resource limit (exit 125).' result = json.loads(output) self.entries = result['entries'] parts = [result['stdout'].removesuffix('\n')] if result['stderr']: parts.append('stderr: ' + result['stderr'].removesuffix('\n')) if result['exit_code'] or not any(parts): parts.append(f'exit: {result["exit_code"]}') return '\n'.join(filter(None, parts)).replace('<|', r'\u003c|')