File size: 4,289 Bytes
baa274b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""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 '</rfl:parameter>' 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|')