@raytrace-cli/cli 0.17.16 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,882 @@
1
+ """The sandbox core's container mechanics: trusted host-side lifecycle of
2
+ gVisor sandboxes. Never mounted into workloads.
3
+
4
+ This module *applies* what it is given (limits, image, hooks, files); it
5
+ decides none of it. Callers are adapters: `projects.py` (the local adapter,
6
+ also the command line every host runs) and any other host layer that imports
7
+ it. What a caller may rely on is written down in CORE_API.md; change that file
8
+ and CORE_API in core/__init__.py together.
9
+ """
10
+ import argparse
11
+ from datetime import datetime
12
+ import fcntl
13
+ import io
14
+ import json
15
+ import os
16
+ from pathlib import Path, PurePosixPath
17
+ import re
18
+ import shutil
19
+ import stat
20
+ import struct
21
+ import subprocess
22
+ import sys
23
+ import tarfile
24
+ import time
25
+
26
+ from core import release
27
+
28
+ LABEL = 'io.raytace.project'
29
+ FORK_OF = 'io.raytace.fork-of'
30
+ PROJECT_ID = r'rtp-[a-f0-9]{32}'
31
+ FORK_ID = r'rtf-[a-f0-9]{32}'
32
+ SNAPSHOTS = '/home/node/.raytace/snapshots.git'
33
+ # Each sandbox's Claude Code hook, as enable-claude last installed it, root-only.
34
+ HOOKS = Path('/var/lib/raytace/hooks')
35
+ # Each sandbox's restricted files, as set-guardrails last left them, root-only.
36
+ GUARDRAILS = Path('/var/lib/raytace/guardrails')
37
+ GUARDRAILS_IN_SANDBOX = '/opt/raytace-claude/guardrails.json'
38
+ # Which sandbox each container is, for the fact engine (engine.py), root-only.
39
+ CONTAINERS = Path('/var/lib/raytace/containers')
40
+ # The file attribute `chattr +i` sets, and the calls that read and write it.
41
+ IMMUTABLE, GET_FLAGS, SET_FLAGS = 0x10, 0x80086601, 0x40086602
42
+ # Where this core is installed: network.py, collector.py and the rest sit
43
+ # beside the core/ package (/opt/raytace locally, a release directory elsewhere).
44
+ ROOT = Path(__file__).resolve().parent.parent
45
+ # The image sandboxes are made from when the caller names none: what setup.py's
46
+ # image step last built and wrote here, or the name it has always had.
47
+ IMAGE_FILE = Path('/etc/raytace/image')
48
+ DEFAULT_IMAGE = 'raytace-gvisor-agent'
49
+
50
+
51
+ class Limits:
52
+ """What one sandbox may use. The core enforces these; it never picks them."""
53
+ def __init__(self, cpus='2', memory='2g', pids=256, tmp='512m'):
54
+ if not re.fullmatch(r'\d{1,3}(\.\d{1,2})?', str(cpus)) or not re.fullmatch(r'\d{1,6}[kmg]', str(memory)) \
55
+ or not 0 < int(pids) <= 65536 or not re.fullmatch(r'\d{1,6}[kmg]', str(tmp)):
56
+ raise ValueError('Invalid sandbox limits')
57
+ self.cpus, self.memory, self.pids, self.tmp = str(cpus), str(memory), int(pids), str(tmp)
58
+
59
+ def args(self):
60
+ return [f'--memory={self.memory}', f'--cpus={self.cpus}', f'--pids-limit={self.pids}',
61
+ f'--tmpfs=/tmp:rw,nosuid,nodev,size={self.tmp}']
62
+
63
+
64
+ DEFAULT_LIMITS = Limits()
65
+
66
+
67
+ def image():
68
+ """The image a new sandbox is made from when its caller names none: the
69
+ active release's (core/release.py), or the one setup.py last built here."""
70
+ active = release.active()
71
+ if active:
72
+ return active['image']
73
+ if IMAGE_FILE.exists():
74
+ named = IMAGE_FILE.read_text().strip()
75
+ if re.fullmatch(r'[a-z0-9][a-z0-9._/-]{0,127}(:[A-Za-z0-9._-]{1,128})?', named):
76
+ return named
77
+ return DEFAULT_IMAGE
78
+
79
+ def bridge():
80
+ # The manager's model and transcript bridge as sandboxes reach it (network.py).
81
+ path = Path('/etc/raytace/bridge')
82
+ return path.read_text().strip() if path.exists() else 'http://192.168.5.2:8799'
83
+
84
+ def run(*args, **kwargs):
85
+ return subprocess.run(args, check=True, **kwargs)
86
+
87
+ def inspect(name):
88
+ if not re.fullmatch(PROJECT_ID, name) and not re.fullmatch(FORK_ID, name):
89
+ raise ValueError('Invalid sandbox ID')
90
+ data = json.loads(subprocess.check_output(['docker', 'inspect', name]))[0]
91
+ if data['Config'].get('Labels', {}).get(LABEL) != name:
92
+ raise ValueError('Container is not a managed RayTrace project')
93
+ if data['HostConfig']['Runtime'] != 'raytace-gvisor':
94
+ raise ValueError('Unexpected runtime; refusing operation')
95
+ return data
96
+
97
+ def preflight():
98
+ # No sandbox runs unrecorded, or with names it cannot resolve.
99
+ for unit, does in (('raytace-collector', 'records what a sandbox runs'), ('raytace-dns', 'resolves names for sandboxes')):
100
+ if subprocess.run(['systemctl', 'is-active', '--quiet', unit]).returncode:
101
+ sys.exit(f'RayTrace: {unit}, which {does}, is not running on this host; no sandbox is started without it.')
102
+ run('python3', str(ROOT / 'network.py'))
103
+
104
+ def remember(name):
105
+ """Tells the fact engine which sandbox a container is: where its project
106
+ and home folders are on this host and, once it runs, its address on the
107
+ sandbox network (which is how a DNS lookup is known to be its own). gVisor
108
+ names a container by its id alone, so without this the engine sees calls
109
+ and cannot tell whose files they are. Written again at every start: the
110
+ address is given then."""
111
+ state = inspect(name)
112
+ mount = lambda suffix: subprocess.check_output(['docker', 'volume', 'inspect', '-f', '{{.Mountpoint}}', name+'-'+suffix], text=True).strip()
113
+ addresses = [joined.get('IPAddress') for joined in (state.get('NetworkSettings', {}).get('Networks') or {}).values()]
114
+ record = {'id': name, 'workspace': mount('workspace'), 'home': mount('home'),
115
+ 'ip': next(filter(None, addresses), None), 'fork_of': state['Config'].get('Labels', {}).get(FORK_OF)}
116
+ CONTAINERS.mkdir(parents=True, exist_ok=True, mode=0o700)
117
+ staged = CONTAINERS / (state['Id']+'.new')
118
+ staged.write_text(json.dumps(record))
119
+ staged.replace(CONTAINERS / (state['Id']+'.json'))
120
+
121
+ def predates_collector(state):
122
+ """Whether a running sandbox started before the collector did. gVisor
123
+ connects to the collector once, at start, and never reconnects, so such a
124
+ sandbox reports nothing: its commands would run unrecorded."""
125
+ if not state['State']['Running']:
126
+ return False
127
+ shown = subprocess.check_output(['systemctl', 'show', 'raytace-collector', '-p', 'ActiveEnterTimestamp',
128
+ '--timestamp=unix'], text=True).strip()
129
+ collector = float(shown.partition('@')[2] or 0)
130
+ # Docker's RFC 3339 time, nanoseconds cut to what fromisoformat reads.
131
+ started = re.sub(r'(\.\d{6})\d*', r'\1', state['State']['StartedAt']).replace('Z', '+00:00')
132
+ return datetime.fromisoformat(started).timestamp() < collector
133
+
134
+ def validate_archive(path):
135
+ total = 0
136
+ with tarfile.open(path, 'r:gz') as archive:
137
+ for item in archive:
138
+ parts = PurePosixPath(item.name)
139
+ if parts.is_absolute() or '..' in parts.parts or not item.isfile():
140
+ raise ValueError('Archive contains unsafe path or non-regular file')
141
+ total += item.size
142
+ if total > 256 * 1024 * 1024:
143
+ raise ValueError('Import exceeds 256 MiB')
144
+
145
+ def stage_archive(sid):
146
+ """The import archive from stdin, written once to /tmp/<id>.tar.gz."""
147
+ path = '/tmp/'+sid+'.tar.gz'
148
+ limit = 300 * 1024 * 1024
149
+ with open(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'wb') as out:
150
+ total = 0
151
+ while chunk := sys.stdin.buffer.read(1024 * 1024):
152
+ total += len(chunk)
153
+ if total > limit:
154
+ raise ValueError('Import archive exceeds 300 MiB')
155
+ out.write(chunk)
156
+ return path
157
+
158
+ # Codex the same: no approval prompts, and none of its own sandboxing, which
159
+ # the sandbox already is (and gVisor would not let it set up).
160
+ # What `shell --agent` starts: the agent's name and its command line.
161
+ AGENTS = {'claude': ('Claude Code', 'claude --dangerously-skip-permissions'),
162
+ 'codex': ('Codex', 'codex --dangerously-bypass-approvals-and-sandbox')}
163
+ CODEX_MANAGED = b'approval_policy = "never"\nsandbox_mode = "danger-full-access"\n'
164
+
165
+ def install_claude_hooks(container, hook):
166
+ """The hook script, root-owned, with Claude Code's managed settings, which
167
+ user and project settings cannot override, and Codex's managed config: the
168
+ agent can read them, not change them. Re-running replaces them with the
169
+ current version."""
170
+ if not 0 < len(hook) <= 262144:
171
+ raise ValueError('Expected the hook script')
172
+ command = 'node /opt/raytace-claude/hook.mjs'
173
+ # No permission prompts for any Claude Code session here: the sandbox is
174
+ # what contains the agent, and the hook still refuses restricted files.
175
+ settings = json.dumps({'permissions': {'defaultMode': 'bypassPermissions'}, 'skipDangerousModePermissionPrompt': True, 'hooks': {
176
+ # Bash for the call id; the file tools so an edit to a restricted file is refused (see guardrails())
177
+ # and so the recorder knows which call is at the file (Read as well: claude-hook.mjs announce()).
178
+ 'PreToolUse': [{'matcher': 'Bash|Read|Write|Edit|MultiEdit|NotebookEdit', 'hooks': [{'type': 'command', 'command': command, 'timeout': 5}]}],
179
+ **{event: [{**({'matcher': '*'} if event == 'PostToolUse' else {}),
180
+ 'hooks': [{'type': 'command', 'command': command, 'timeout': 15}]}]
181
+ for event in ('UserPromptSubmit', 'PostToolUse', 'Stop', 'SubagentStop', 'SessionEnd')}}}, indent=2).encode()
182
+ # Written by root from inside the container: docker cp does not keep
183
+ # owners under gVisor, and a node-owned hook is one the agent can edit.
184
+ # Needs the container running. Files an older install left node-owned
185
+ # are emptied by node, then their directories removed by root.
186
+ subprocess.run(['docker', 'exec', '-u', '1000', container, 'sh', '-c',
187
+ 'rm -rf /opt/raytace-claude/* /etc/claude-code/* /etc/codex/*'], stderr=subprocess.DEVNULL)
188
+ for path, content in (('/opt/raytace-claude/hook.mjs', hook), ('/etc/claude-code/managed-settings.json', settings),
189
+ ('/etc/codex/managed_config.toml', CODEX_MANAGED)):
190
+ write_as_root(container, path, content)
191
+
192
+ def write_as_root(container, path, content):
193
+ """A root-owned file inside a running sandbox, which its agent can read and not change."""
194
+ directory = path.rsplit('/', 1)[0]
195
+ run('docker', 'exec', '-i', '-u', '0', container, 'sh', '-c',
196
+ f'if [ -O {directory} ]; then :; else rm -rf {directory}; fi; mkdir -p -m 755 {directory} && '
197
+ f'cat > {path}.new && chmod 644 {path}.new && mv {path}.new {path}', input=content)
198
+
199
+ def lock(root, path, on):
200
+ """Locks or unlocks one project file from the host, or with on=None only
201
+ looks. Locked is root's, read-only and immutable: nothing in the sandbox
202
+ can write, replace, rename or delete it, whatever tool tries, and it still
203
+ reads. Returns whether the file is now locked. The agent names its own
204
+ folders, so every step of the path is opened without following links: a
205
+ link out of the project is never touched."""
206
+ at = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
207
+ try:
208
+ parts = PurePosixPath(path).parts
209
+ for index, part in enumerate(parts):
210
+ last = index == len(parts) - 1
211
+ below = os.open(part, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | (0 if last else os.O_DIRECTORY), dir_fd=at)
212
+ os.close(at)
213
+ at = below
214
+ mode = os.fstat(at).st_mode
215
+ if not stat.S_ISREG(mode):
216
+ return False
217
+ flags = struct.unpack('i', fcntl.ioctl(at, GET_FLAGS, struct.pack('i', 0)))[0]
218
+ locked = bool(flags & IMMUTABLE)
219
+ if on is None or on == locked:
220
+ return locked
221
+ runs = mode & 0o111
222
+ if on:
223
+ os.fchown(at, 0, 0)
224
+ os.fchmod(at, 0o555 if runs else 0o444)
225
+ fcntl.ioctl(at, SET_FLAGS, struct.pack('i', flags | IMMUTABLE))
226
+ else:
227
+ fcntl.ioctl(at, SET_FLAGS, struct.pack('i', flags & ~IMMUTABLE))
228
+ os.fchown(at, 1000, 1000)
229
+ os.fchmod(at, 0o755 if runs else 0o644)
230
+ return on
231
+ except OSError:
232
+ return False
233
+ finally:
234
+ os.close(at)
235
+
236
+ def present(root, path):
237
+ """Whether a project path is a regular file, without following a link at any step."""
238
+ try:
239
+ at = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
240
+ except OSError:
241
+ return False
242
+ try:
243
+ parts = PurePosixPath(path).parts
244
+ for part in parts[:-1]:
245
+ below = os.open(part, os.O_RDONLY | os.O_NOFOLLOW | os.O_DIRECTORY, dir_fd=at)
246
+ os.close(at)
247
+ at = below
248
+ return bool(parts) and stat.S_ISREG(os.stat(parts[-1], dir_fd=at, follow_symlinks=False).st_mode)
249
+ except OSError:
250
+ return False
251
+ finally:
252
+ os.close(at)
253
+
254
+ def guardrails(sid, state, restricted=None, watched=None, blocked=None):
255
+ """Applies a sandbox's restricted files: the new list, or the stored one
256
+ again. The Claude Code hook gets the list at once and refuses the edit
257
+ with the reason. The lock that holds for every tool is put on only while
258
+ the sandbox is stopped, so from its next start: gVisor keeps what it knows
259
+ of a file while it runs, and a file locked under it stops being readable.
260
+ A file no longer restricted is unlocked now. `watched` are the files whose
261
+ owner wants to hear of a read or a change: the hook reports an attempt on
262
+ them and nothing is locked. `blocked` are the programs the hook refuses
263
+ to start (None keeps the stored list). Returns {hook: the hook has the
264
+ list, read_only: the files locked, restricted and watched: the lists as
265
+ they now are, missing: listed paths that are not a file in the project}."""
266
+ GUARDRAILS.mkdir(parents=True, exist_ok=True, mode=0o700)
267
+ stored = GUARDRAILS / (sid+'.json')
268
+ kept = json.loads(stored.read_text()) if stored.exists() else {}
269
+ before = kept.get('restricted', [])
270
+ if restricted is None:
271
+ restricted = before
272
+ if watched is None:
273
+ watched = kept.get('watched', [])
274
+ if blocked is None:
275
+ blocked = kept.get('blocked', [])
276
+ root = subprocess.check_output(['docker', 'volume', 'inspect', '-f', '{{.Mountpoint}}', sid+'-workspace'], text=True).strip()
277
+ running = state['State']['Running']
278
+ for path in set(before) - set(restricted):
279
+ lock(root, path, False)
280
+ read_only = [path for path in restricted if lock(root, path, None if running else True)]
281
+ lists = json.dumps({'restricted': restricted, 'watched': watched, 'blocked': blocked})
282
+ stored.write_text(lists)
283
+ if running and (restricted or before or watched or kept.get('watched') or blocked or kept.get('blocked')):
284
+ write_as_root(sid, GUARDRAILS_IN_SANDBOX, lists.encode())
285
+ return {'hook': bool(running), 'read_only': read_only, 'restricted': restricted, 'watched': watched,
286
+ 'missing': [path for path in [*restricted, *watched] if not present(root, path)]}
287
+
288
+ def as_node(container, *command, data=None, check=True):
289
+ """Runs a command in a sandbox as its agent user, never root."""
290
+ return subprocess.run(['docker', 'exec', *(['-i'] if data is not None else []), '-u', '1000', container, *command],
291
+ input=data, check=check, capture_output=True).stdout
292
+
293
+ def start_container(name):
294
+ """docker exec needs a running container. A sandbox stopped since it
295
+ was recorded (host restart, idle stop) is started again for the work
296
+ below; starting one that already runs is a no-op."""
297
+ run('docker', 'start', name, stdout=subprocess.DEVNULL)
298
+
299
+ def container_args(name, labels, limits=None, image_name=None):
300
+ """`docker create` arguments for one sandbox: gVisor, the sandbox network,
301
+ no capabilities, the agent user, the given limits, its two volumes and the
302
+ host's resolver. Projects and forks are made the same way."""
303
+ limits = limits or DEFAULT_LIMITS
304
+ return ['docker', 'create', '--name', name, *labels, '--runtime=raytace-gvisor',
305
+ '--label', 'io.raytace.storage=volumes-v1',
306
+ '--network=raytace-egress', '--cap-drop=ALL', '--security-opt=no-new-privileges',
307
+ '--user=1000:1000', *limits.args(),
308
+ '--mount=type=volume,src='+name+'-workspace,dst=/workspace',
309
+ '--mount=type=volume,src='+name+'-home,dst=/home/node',
310
+ '--mount=type=bind,src=/etc/raytace/resolv.conf,dst=/etc/resolv.conf,readonly',
311
+ # Session marker on PID 1: env is inherited across fork/exec, so
312
+ # every process in this sandbox carries it without the collector
313
+ # reconstructing a process tree. Read back by the allowlist in
314
+ # collector.py. Session scope only -- a per-call RAYTRACE_CALL_ID
315
+ # has to be stamped by whatever spawns the command, and inside
316
+ # this sandbox that is Codex, not RayTrace.
317
+ '--env', 'RAYTRACE_SESSION='+name, '--env', 'RAYTRACE_BROKER='+bridge(),
318
+ '--workdir=/workspace', '--entrypoint=/bin/sleep',
319
+ image_name or image(), 'infinity']
320
+
321
+ def create_container(name, labels, limits=None, image_name=None):
322
+ """The sandbox's two volumes and its container (not started); its container id."""
323
+ for suffix in ('workspace', 'home'):
324
+ run('docker', 'volume', 'create', *labels, name+'-'+suffix, stdout=subprocess.DEVNULL)
325
+ return subprocess.check_output(container_args(name, labels, limits, image_name), text=True).strip()
326
+
327
+ def fork_container(fork, parent, limits=None, image_name=None):
328
+ """A sandbox like the project's own, for one Playground fork: same image,
329
+ limits and network, its own volumes, labelled with the project it forks."""
330
+ return create_container(fork, ['--label', LABEL+'='+fork, '--label', FORK_OF+'='+parent], limits, image_name)
331
+
332
+ def image_of(name):
333
+ """The image a sandbox was made from, so its forks match it (None: image())."""
334
+ return inspect(name).get('Config', {}).get('Image') or None
335
+
336
+ def fork_state(fork):
337
+ state = inspect(fork)
338
+ parent = state['Config'].get('Labels', {}).get(FORK_OF, '')
339
+ if not re.fullmatch(FORK_ID, fork) or not re.fullmatch(PROJECT_ID, parent):
340
+ raise ValueError('Not a Playground fork')
341
+ return state, parent
342
+
343
+ def safe_path(path):
344
+ parts = PurePosixPath(path)
345
+ if not path or len(path) > 1024 or parts.is_absolute() or '..' in parts.parts or '\0' in path:
346
+ raise ValueError('Invalid workspace path: ' + path[:80])
347
+ return '/workspace/' + str(parts)
348
+
349
+ def fork_action(action, fork, forget=False, credentials=None):
350
+ """One Playground fork action. `credentials` says whether fork-create copies
351
+ the parent's sign-ins into the fork: a function of the request (the
352
+ caller's policy), or None to copy them unless the request says
353
+ credentials: false."""
354
+ if not re.fullmatch(FORK_ID, fork):
355
+ raise ValueError('Invalid fork ID')
356
+ if action == 'fork-create':
357
+ # stdin: {parent, commit, session, transcript, files: {path: text}, delete: [path], hook}
358
+ data = json.loads(sys.stdin.buffer.read(40 * 1024 * 1024))
359
+ parent, commit, session = data['parent'], data['commit'], data['session']
360
+ if not re.fullmatch(PROJECT_ID, parent) or not re.fullmatch(r'[0-9a-f]{40}', commit) \
361
+ or not re.fullmatch(r'[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}', session):
362
+ raise ValueError('Invalid fork request')
363
+ inspect(parent)
364
+ preflight()
365
+ copy_credentials = credentials(data) if credentials else data.get('credentials') is not False
366
+ cid = fork_container(fork, parent, image_name=image_of(parent))
367
+ run('docker', 'start', fork, stdout=subprocess.DEVNULL)
368
+ remember(fork)
369
+ # The parent is read from below, so it must be running too: it is
370
+ # often stopped by fork time, and exec into it exits 1.
371
+ start_container(parent)
372
+ # The project folder as the snapshot has it, and nothing else.
373
+ archive = as_node(parent, 'git', '--git-dir='+SNAPSHOTS, 'archive', '--format=tar', commit)
374
+ as_node(fork, 'tar', '-x', '-C', '/workspace', data=archive)
375
+ # The user's Claude Code sign-in and the sandbox's RayTrace token (a
376
+ # local sandbox keeps it in .raytace/sandbox-token, a hosted one in its Codex config).
377
+ wanted = ['.claude/.credentials.json', '.claude.json', '.claude/settings.json', '.raytace/sandbox-token', '.raytace-codex/config.toml']
378
+ if not copy_credentials:
379
+ wanted = []
380
+ present = [path for path in wanted if subprocess.run(['docker', 'exec', '-u', '1000', parent, 'test', '-f', '/home/node/'+path]).returncode == 0]
381
+ if present:
382
+ as_node(fork, 'tar', '-x', '-C', '/home/node', data=as_node(parent, 'tar', '-c', '-C', '/home/node', *present))
383
+ # The session cut at the forked step, where `claude --resume` finds it.
384
+ as_node(fork, 'sh', '-c', 'mkdir -p "$(dirname "$1")" && cat > "$1"', 'sh',
385
+ '/home/node/.claude/projects/-workspace/'+session+'.jsonl', data=data['transcript'].encode())
386
+ for path, text in (data.get('files') or {}).items():
387
+ as_node(fork, 'sh', '-c', 'mkdir -p "$(dirname "$1")" && cat > "$1"', 'sh', safe_path(path), data=text.encode())
388
+ # Excluded files: not in the fork's copy of the project at all.
389
+ for path in (data.get('delete') or [])[:200]:
390
+ as_node(fork, 'rm', '-rf', '--', safe_path(path))
391
+ install_claude_hooks(fork, data['hook'].encode())
392
+ print(json.dumps({'container_id': cid}))
393
+ elif action == 'fork-run':
394
+ # stdin: {session, model, prompt}. Claude's stream-json events go to stdout.
395
+ state, parent = fork_state(fork)
396
+ data = json.loads(sys.stdin.buffer.read(65536))
397
+ if not re.fullmatch(r'[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}', data['session']) \
398
+ or not re.fullmatch(r'[A-Za-z0-9_.:/\[\]-]{1,100}', data['model']) or not 0 < len(data['prompt']) <= 4000:
399
+ raise ValueError('Invalid run request')
400
+ # gVisor is the sandbox, as for the project's own session.
401
+ sys.exit(subprocess.call(['docker', 'exec', '-u', '1000', '-w', '/workspace', fork,
402
+ 'claude', '-p', '--resume', data['session'], '--model', data['model'],
403
+ '--dangerously-skip-permissions', '--output-format', 'stream-json', '--verbose', data['prompt']]))
404
+ elif action == 'fork-check':
405
+ # stdin: {command, seconds}. The user's pass/fail check, run where the
406
+ # fork left the project, as the agent user: exit 0 passes. Prints
407
+ # {exit_code, timed_out, output (its last 20 KB, stdout and stderr)}.
408
+ state, parent = fork_state(fork)
409
+ data = json.loads(sys.stdin.buffer.read(65536))
410
+ command, seconds = data.get('command'), data.get('seconds')
411
+ if not isinstance(command, str) or not 0 < len(command) <= 2000 or not isinstance(seconds, int) or not 0 < seconds <= 1800:
412
+ raise ValueError('Invalid check request')
413
+ # timeout(1) inside the sandbox, so the check's own processes end with
414
+ # it, not only the docker exec client; -k for one that ignores TERM.
415
+ result = subprocess.run(['docker', 'exec', '-u', '1000', '-w', '/workspace', fork,
416
+ 'timeout', '-k', '5', str(seconds), 'sh', '-c', command], stdin=subprocess.DEVNULL,
417
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
418
+ output = result.stdout[-20000:].decode('utf-8', 'replace')
419
+ print(json.dumps({'exit_code': result.returncode, 'timed_out': result.returncode in (124, 137), 'output': output}))
420
+ elif action == 'fork-collect':
421
+ # stdin: {original}. The fork's snapshot history goes into the project's
422
+ # own (refs/forks/<id>/*), so its files outlive the fork, and its last
423
+ # snapshot is compared with the original run's last one.
424
+ state, parent = fork_state(fork)
425
+ data = json.loads(sys.stdin.buffer.read(4096))
426
+ if not re.fullmatch(r'[0-9a-f]{40}', data['original']):
427
+ raise ValueError('Invalid original commit')
428
+ # Both containers are read from below; either may have stopped
429
+ # since the run (see start_container).
430
+ start_container(parent)
431
+ start_container(fork)
432
+ # A fork that answered without a tool call never snapshots, so its
433
+ # store has no refs (or does not exist) and `git bundle` exits 128
434
+ # there. That is a fork with nothing to collect, not a failure:
435
+ # report no final snapshot and let the fork's check still run.
436
+ refs = as_node(fork, 'git', '--git-dir='+SNAPSHOTS, 'for-each-ref', '--format=%(refname)', check=False)
437
+ if not refs.strip():
438
+ print(json.dumps({'final': None, 'changes': []}))
439
+ return
440
+ bundle = as_node(fork, 'sh', '-c', 'git --git-dir="$1" bundle create - --all 2>/dev/null', 'sh', SNAPSHOTS)
441
+ if not bundle:
442
+ print(json.dumps({'final': None, 'changes': []}))
443
+ return
444
+ as_node(parent, 'sh', '-c', 'cat > /tmp/fork.bundle && git --git-dir="$1" fetch -q /tmp/fork.bundle "+refs/heads/*:refs/forks/$2/*"; '
445
+ 'status=$?; rm -f /tmp/fork.bundle; exit $status', 'sh', SNAPSHOTS, fork, data=bundle)
446
+ final = as_node(parent, 'sh', '-c', 'git --git-dir="$1" for-each-ref --format="%(objectname)" "refs/forks/$2/"', 'sh', SNAPSHOTS, fork).decode().split()[0]
447
+ stats = as_node(parent, 'git', '--git-dir='+SNAPSHOTS, 'diff', '--no-renames', '-z', '--numstat', data['original'], final).decode()
448
+ statuses = as_node(parent, 'git', '--git-dir='+SNAPSHOTS, 'diff', '--no-renames', '-z', '--name-status', data['original'], final).decode().split('\0')
449
+ counts = {}
450
+ for entry in filter(None, stats.split('\0')):
451
+ added, removed, path = entry.split('\t', 2)
452
+ counts[path] = (None if added == '-' else int(added), None if removed == '-' else int(removed))
453
+ changes = [{'path': statuses[i + 1], 'status': statuses[i], 'added': counts.get(statuses[i + 1], (None, None))[0],
454
+ 'removed': counts.get(statuses[i + 1], (None, None))[1]} for i in range(0, len(statuses) - 1, 2) if statuses[i]]
455
+ print(json.dumps({'final': final, 'changes': changes[:500]}))
456
+ elif action == 'fork-stop':
457
+ # Kept for looking around, not running: stops whatever is still going.
458
+ fork_state(fork)
459
+ subprocess.run(['docker', 'stop', '-t', '3', fork], stdout=subprocess.DEVNULL, check=True)
460
+ print(json.dumps({'stopped': fork}))
461
+ elif action == 'fork-delete':
462
+ # Only ever a fork: fork_state refuses anything without the fork label.
463
+ state, parent = fork_state(fork)
464
+ subprocess.run(['docker', 'rm', '-f', fork], stdout=subprocess.DEVNULL, check=True)
465
+ (CONTAINERS / (state['Id']+'.json')).unlink(missing_ok=True)
466
+ # With --forget-evidence (its project destroyed with its logs), what the collector recorded of it too.
467
+ if forget:
468
+ evidence(state['Id'], forget=True)
469
+ for suffix in ('workspace', 'home'):
470
+ volume = fork+'-'+suffix
471
+ result = subprocess.run(['docker', 'volume', 'inspect', volume], capture_output=True, text=True)
472
+ if result.returncode == 0:
473
+ if json.loads(result.stdout)[0].get('Labels', {}).get(FORK_OF) != parent:
474
+ raise ValueError('Unexpected volume ownership; volume retained')
475
+ run('docker', 'volume', 'rm', volume, stdout=subprocess.DEVNULL)
476
+ print(json.dumps({'deleted': fork}))
477
+
478
+ SNAPSHOT_REF = r'[0-9a-f]{40}|refs/forks/rtf-[a-f0-9]{32}/[A-Za-z0-9_-]{1,40}'
479
+
480
+ def snapshot_read(project):
481
+ """Read-only views of a project's snapshot history, for the Playground:
482
+ stdin {op: list|show|diff, commit, to?, path?}. Never writes."""
483
+ data = json.loads(sys.stdin.buffer.read(8192))
484
+ op, commit = data.get('op'), data.get('commit', '')
485
+ if op not in ('list', 'show', 'diff') or not re.fullmatch(SNAPSHOT_REF, commit) \
486
+ or (op == 'diff' and not re.fullmatch(SNAPSHOT_REF, data.get('to', ''))):
487
+ raise ValueError('Invalid snapshot request')
488
+ path = safe_path(data['path'])[len('/workspace/'):] if data.get('path') else None
489
+ git = ['git', '--git-dir='+SNAPSHOTS]
490
+ if op == 'list':
491
+ names = as_node(project, *git, 'ls-tree', '-r', '-z', '--name-only', commit).decode().split('\0')
492
+ print(json.dumps({'files': [name for name in names if name][:20000]}))
493
+ elif op == 'show':
494
+ if not path:
495
+ raise ValueError('A path is required')
496
+ result = subprocess.run(['docker', 'exec', '-u', '1000', project, *git, 'show', commit+':'+path], capture_output=True)
497
+ if result.returncode != 0:
498
+ print(json.dumps({'missing': True}))
499
+ return
500
+ content = result.stdout
501
+ binary = b'\0' in content[:8000]
502
+ print(json.dumps({'binary': binary, 'size': len(content), 'truncated': len(content) > 1_000_000,
503
+ 'text': None if binary else content[:1_000_000].decode('utf-8', 'replace')}))
504
+ else:
505
+ text = as_node(project, *git, 'diff', '--no-renames', '--no-color', commit, data['to'], *(['--', path] if path else [])).decode('utf-8', 'replace')
506
+ print(json.dumps({'diff': text[:500_000], 'truncated': len(text) > 500_000}))
507
+
508
+ def read_snapshot(project, running):
509
+ """snapshot_read for a project in whatever state it was found.
510
+
511
+ The snapshot history lives inside the sandbox, so reading it needs the
512
+ container up. A stopped one is started for the read and stopped again
513
+ after: looking at an old run's diff must not need its owner to start the
514
+ sandbox first, and must not leave it running behind their back either
515
+ (no agent runs in between, so nothing is recorded or changed). A failed
516
+ read leaves as one plain sentence, not a traceback: the line reaches a
517
+ dashboard, whose reader cannot act on a raw docker command."""
518
+ try:
519
+ if running:
520
+ return snapshot_read(project)
521
+ run('docker', 'start', project, stdout=subprocess.DEVNULL)
522
+ try:
523
+ return snapshot_read(project)
524
+ finally:
525
+ try:
526
+ run('docker', 'stop', '-t', '10', project, stdout=subprocess.DEVNULL)
527
+ except subprocess.CalledProcessError:
528
+ pass # left running; the read's own outcome is what matters
529
+ except subprocess.CalledProcessError:
530
+ raise SystemExit("RayTrace: this sandbox's snapshot history could not be read.") from None
531
+
532
+ def create(sid, archive, limits=None, expect_release=None):
533
+ """A new project sandbox from a staged import archive; its container id.
534
+
535
+ With `expect_release`, the sandbox is made only from that active release
536
+ (core/release.py): the release lock is held, shared, from the check until
537
+ the container exists, so an activation cannot switch releases in between,
538
+ and the container is made from that release's image."""
539
+ if not re.fullmatch(PROJECT_ID, sid):
540
+ raise ValueError('Invalid sandbox ID')
541
+ if not archive or not re.fullmatch(r'/tmp/rtp-[a-f0-9]{32}\.tar\.gz', archive):
542
+ raise ValueError('Expected staged import archive')
543
+ validate_archive(archive)
544
+ preflight()
545
+ if expect_release is None:
546
+ return finish_create(sid, archive, create_container(sid, ['--label', LABEL+'='+sid], limits))
547
+ with release.lock(shared=True):
548
+ active = release.active()
549
+ if not active or active.get('id') != expect_release:
550
+ raise SystemExit(f'RayTrace: this host runs release {(active or {}).get("id") or "none"}, '
551
+ f'not {expect_release}; no sandbox was created.')
552
+ cid = create_container(sid, ['--label', LABEL+'='+sid, '--label', release.LABEL+'='+expect_release],
553
+ limits, active['image'])
554
+ return finish_create(sid, archive, cid)
555
+
556
+ def finish_create(sid, archive, cid):
557
+ import_archive(cid, archive)
558
+ remember(sid)
559
+ return cid
560
+
561
+ def import_archive(cid, archive):
562
+ """The project files of a validated import archive into /workspace, owned by the agent user."""
563
+ # docker cp -a honors the deliberately normalized uid/gid in this tar.
564
+ with tarfile.open(archive, 'r:gz') as source:
565
+ with io.BytesIO() as buffer:
566
+ with tarfile.open(fileobj=buffer, mode='w') as dest:
567
+ made = set()
568
+ for item in source:
569
+ # The upload holds files only. Without its folders named here, docker
570
+ # would make them root's, and the agent could add nothing inside them.
571
+ for parent in reversed(PurePosixPath(item.name).parents[:-1]):
572
+ if str(parent) not in made:
573
+ made.add(str(parent))
574
+ folder = tarfile.TarInfo(str(parent))
575
+ folder.type, folder.mode = tarfile.DIRTYPE, 0o755
576
+ folder.uid = folder.gid = 1000
577
+ folder.uname = folder.gname = 'node'
578
+ folder.mtime = item.mtime
579
+ dest.addfile(folder)
580
+ item.uid = item.gid = 1000
581
+ item.uname = item.gname = 'node'
582
+ item.mode = 0o755 if item.mode & 0o111 else 0o644
583
+ # Names, sizes and modes only: no extended attributes or other pax records.
584
+ item.pax_headers = {}
585
+ dest.addfile(item, source.extractfile(item))
586
+ run('docker', 'cp', '-a', '-', cid+':/workspace', input=buffer.getvalue())
587
+
588
+ RUNTIME_DB = '/var/lib/raytace/runtime.db'
589
+
590
+ def evidence(container, forget=False):
591
+ """What the collector recorded for one sandbox's container: its process
592
+ events and the fact engine's file and network facts. Printed as JSON lines,
593
+ or with `forget` deleted, for when its owner destroys it with its logs.
594
+ Called once the sandbox is stopped: its last events (its exit, the
595
+ connection closing) come just after, and the collector commits every
596
+ quarter second, so they are waited for."""
597
+ import sqlite3
598
+ time.sleep(1.5)
599
+ if not Path(RUNTIME_DB).exists():
600
+ return
601
+ with sqlite3.connect(RUNTIME_DB, timeout=30) as db:
602
+ tables = {name for (name,) in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
603
+ if 'capture_streams' in tables:
604
+ if forget:
605
+ db.execute('DELETE FROM capture_streams WHERE container_id=?', (container,))
606
+ else:
607
+ for row in db.execute('SELECT id,collector_id,started_ms,ended_ms,heartbeat_ms,dropped,errors,capabilities_json FROM capture_streams WHERE container_id=?', (container,)):
608
+ names=('id','collector_id','started_ms','ended_ms','heartbeat_ms','dropped','errors','capabilities')
609
+ body=dict(zip(names,row)); body['capabilities']=json.loads(body['capabilities'])
610
+ print(json.dumps({'table':'capture_streams','body':body}))
611
+ for table, columns in (('runtime_events', 'kind, received_ms, body'), ('facts', 'kind, at_ns, received_ms, body')):
612
+ if table not in tables:
613
+ continue
614
+ if forget:
615
+ db.execute(f'DELETE FROM {table} WHERE container_id = ?', (container,))
616
+ continue
617
+ names = [column.strip() for column in columns.split(',')]
618
+ for row in db.execute(f'SELECT {columns} FROM {table} WHERE container_id = ? ORDER BY id', (container,)):
619
+ record = dict(zip(names, row))
620
+ record['body'] = json.loads(record['body'])
621
+ print(json.dumps({'table': table, **record}))
622
+
623
+ # What the dashboard calls each kind of fact, and how many of each it is shown.
624
+ FACT_KINDS = {'file': 'files', 'network': 'network', 'dns': 'lookups', 'package': 'packages', 'identity': 'identity', 'summary': 'bulk'}
625
+ FACT_LIMITS = {'file': 500, 'network': 500, 'dns': 300, 'package': 100, 'identity': 100, 'summary': 100}
626
+
627
+ def activity(container, since_ms=0, until_ms=0):
628
+ """What the fact engine saw one sandbox do, newest first, by kind -- the
629
+ shape RayTrace's hosted dashboard reads -- each list capped, with `more`
630
+ naming the kinds that were. since/until (epoch ms) scope it to one prompt."""
631
+ import sqlite3
632
+ found, more = {name: [] for name in FACT_KINDS.values()}, []
633
+ if not Path(RUNTIME_DB).exists():
634
+ return {**found, 'more': more}
635
+ where, args = ['container_id = ?', 'kind = ?'], [container]
636
+ if since_ms:
637
+ where.append('CAST(at_ns AS INTEGER) >= ?'); args.append(since_ms * 1_000_000)
638
+ if until_ms:
639
+ where.append('CAST(at_ns AS INTEGER) <= ?'); args.append(until_ms * 1_000_000)
640
+ with sqlite3.connect(f'file:{RUNTIME_DB}?mode=ro', uri=True, timeout=30) as db:
641
+ if not db.execute("SELECT 1 FROM sqlite_master WHERE name = 'facts'").fetchone():
642
+ return {**found, 'more': more}
643
+ for kind, name in FACT_KINDS.items():
644
+ limit = FACT_LIMITS[kind]
645
+ rows = db.execute('SELECT fact_id, at_ns, body FROM facts WHERE ' + ' AND '.join(where) + ' ORDER BY id DESC LIMIT ?',
646
+ (args[0], kind, *args[1:], limit + 1)).fetchall()
647
+ for fact_id, at_ns, body in rows[:limit]:
648
+ fact = json.loads(body)
649
+ last = fact.get('last_ns') or at_ns
650
+ try:
651
+ at = int(last) / 1e9
652
+ except (TypeError, ValueError):
653
+ at = None
654
+ found[name].append({**fact, 'id': fact_id, 'at': at})
655
+ if len(rows) > limit:
656
+ more.append(name)
657
+ return {**found, 'more': more}
658
+
659
+ def write_home_files(sid, files):
660
+ """Files into the sandbox user's home, each (folder, name, bytes), the
661
+ folders 0700 and the files 0600, owned by the agent user."""
662
+ with io.BytesIO() as buffer:
663
+ with tarfile.open(fileobj=buffer, mode='w') as archive:
664
+ for folder, name, content in files:
665
+ if not re.fullmatch(r'\.?[A-Za-z0-9_-]{1,40}', folder) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,60}', name):
666
+ raise ValueError('Invalid home file')
667
+ directory = tarfile.TarInfo(folder); directory.type = tarfile.DIRTYPE
668
+ directory.uid = directory.gid = 1000; directory.mode = 0o700
669
+ archive.addfile(directory)
670
+ entry = tarfile.TarInfo(folder+'/'+name); entry.uid = entry.gid = 1000
671
+ entry.mode = 0o600; entry.size = len(content)
672
+ archive.addfile(entry, io.BytesIO(content))
673
+ run('docker', 'cp', '-a', '-', sid+':/home/node', input=buffer.getvalue())
674
+
675
+ TOKEN = re.compile(r'[A-Za-z0-9_-]{40,100}')
676
+
677
+ def set_token(sid, token):
678
+ """The token the sandbox's Claude Code hook (claude-hook.mjs) sends its
679
+ transcript with, to whatever bridge the host names (network.py)."""
680
+ if not TOKEN.fullmatch(token):
681
+ raise ValueError('Invalid sandbox token')
682
+ write_home_files(sid, [('.raytace', 'sandbox-token', token.encode())])
683
+
684
+ def enable_claude(sid, hook):
685
+ """Installs the hook now and keeps the host's copy, which every start puts back."""
686
+ install_claude_hooks(sid, hook)
687
+ HOOKS.mkdir(parents=True, exist_ok=True, mode=0o700)
688
+ (HOOKS / (sid+'.mjs')).write_bytes(hook)
689
+
690
+ def start(sid):
691
+ """Starts a project sandbox so that it is recorded: the host's recorder and
692
+ resolver up, the collector reconnected (a sandbox that predates it is
693
+ restarted), restricted files locked, the hook and its lists put back, and
694
+ the engine told which container it is. Starting a running one is safe."""
695
+ state = inspect(sid)
696
+ preflight()
697
+ if predates_collector(state):
698
+ # Files and sign-in are on volumes; only running processes end.
699
+ print('RayTrace: the evidence collector restarted since this sandbox started; '
700
+ 'restarting the sandbox so its commands are recorded again.', file=sys.stderr)
701
+ run('docker', 'stop', '-t', '10', sid, stdout=subprocess.DEVNULL)
702
+ state = inspect(sid)
703
+ restricts = (GUARDRAILS / (sid+'.json')).exists()
704
+ if not state['State']['Running']:
705
+ # Stopped is when restricted files are locked (see guardrails()).
706
+ if restricts:
707
+ guardrails(sid, state)
708
+ run('docker', 'start', sid, stdout=subprocess.DEVNULL)
709
+ # Outside its volumes a sandbox's files last until it restarts, so the
710
+ # hook is put back every time, from the host's copy.
711
+ hook = HOOKS / (sid+'.mjs')
712
+ if hook.exists():
713
+ install_claude_hooks(sid, hook.read_bytes())
714
+ # The hook's list of restricted files goes the same way.
715
+ if restricts:
716
+ guardrails(sid, inspect(sid))
717
+ remember(sid)
718
+
719
+ def shell(sid, agent=None):
720
+ """An interactive shell in a started sandbox (start() first); with `agent`,
721
+ that agent first, without approval prompts. Returns the shell's exit code.
722
+ Exiting never stops or removes the sandbox."""
723
+ line = 'if [ -f /home/node/.raytace-codex/config.toml ]; then export CODEX_HOME=/home/node/.raytace-codex; fi; '
724
+ if agent:
725
+ name, command = AGENTS[agent]
726
+ line += f'cd /workspace 2>/dev/null; if command -v {agent} >/dev/null; then {command}; else echo "{name} is not installed in this sandbox."; fi; '
727
+ return subprocess.run(['docker', 'exec', '-it', sid, '/bin/bash', '-c', line+'exec /bin/bash'], check=False).returncode
728
+
729
+ def stop(sid):
730
+ inspect(sid)
731
+ run('docker', 'stop', '-t', '10', sid)
732
+
733
+ # Called with the sandbox id by delete(), after its container is gone: a host
734
+ # layer adds its own per-sandbox state here (register_delete_cleanup).
735
+ DELETE_CLEANUP = []
736
+
737
+ def register_delete_cleanup(function):
738
+ DELETE_CLEANUP.append(function)
739
+ return function
740
+
741
+ def delete(sid, forget_evidence=False):
742
+ """Deletes a stopped project sandbox: its container, its two volumes (only
743
+ ones labelled as its own), the host's copies of its hook and lists, and
744
+ with `forget_evidence` what the collector recorded of it."""
745
+ state = inspect(sid)
746
+ if state['State']['Running']:
747
+ raise ValueError('Stop the sandbox before deleting it')
748
+ run('docker', 'rm', sid)
749
+ if forget_evidence:
750
+ evidence(state['Id'], forget=True)
751
+ (CONTAINERS / (state['Id']+'.json')).unlink(missing_ok=True)
752
+ (HOOKS / (sid+'.mjs')).unlink(missing_ok=True)
753
+ # An immutable file cannot be removed with its volume; chattr -R follows no links.
754
+ if (GUARDRAILS / (sid+'.json')).exists():
755
+ root = subprocess.run(['docker', 'volume', 'inspect', '-f', '{{.Mountpoint}}', sid+'-workspace'], capture_output=True, text=True)
756
+ if root.returncode == 0:
757
+ subprocess.run(['chattr', '-R', '-f', '-i', root.stdout.strip()], stderr=subprocess.DEVNULL)
758
+ (GUARDRAILS / (sid+'.json')).unlink(missing_ok=True)
759
+ for cleanup in DELETE_CLEANUP:
760
+ cleanup(sid)
761
+ for suffix in ('workspace', 'home'):
762
+ volume = sid+'-'+suffix
763
+ result = subprocess.run(['docker', 'volume', 'inspect', volume], capture_output=True, text=True)
764
+ if result.returncode == 0:
765
+ item = json.loads(result.stdout)[0]
766
+ if item.get('Labels', {}).get(LABEL) != sid:
767
+ raise ValueError('Unexpected volume ownership; volume retained')
768
+ run('docker', 'volume', 'rm', volume)
769
+
770
+ def listing():
771
+ """Every managed container on this host."""
772
+ ids = subprocess.check_output(['docker', 'ps', '-aq', '--filter', 'label='+LABEL], text=True).split()
773
+ result = []
774
+ for cid in ids:
775
+ d = json.loads(subprocess.check_output(['docker', 'inspect', '--size', cid]))[0]
776
+ labels = d['Config'].get('Labels', {})
777
+ result.append({'id': d['Name'].lstrip('/'), 'container_id': d['Id'],
778
+ 'status': d['State']['Status'], 'created': d['Created'],
779
+ 'persistent_volumes': labels.get('io.raytace.storage') == 'volumes-v1',
780
+ 'size_bytes': d.get('SizeRw', 0), 'fork_of': labels.get(FORK_OF),
781
+ 'release': labels.get(release.LABEL), 'image': d['Config'].get('Image')})
782
+ return result
783
+
784
+ def set_guardrails(sid, state, sent):
785
+ """set-guardrails' request checked: {restricted, watched?, blocked?}, the whole lists each time."""
786
+ lists = {}
787
+ for key, cap in (('restricted', 20000), ('watched', 2000)):
788
+ if key == 'watched' and key not in sent:
789
+ lists[key] = None # an older caller: keep the list the host has
790
+ continue
791
+ if not isinstance(sent.get(key), list) or len(sent[key]) > cap:
792
+ raise ValueError('Invalid '+key+' list')
793
+ lists[key] = [safe_path(path)[len('/workspace/'):] for path in sent[key]]
794
+ # blocked?: program names. Absent (an older caller, or a change to files only): keep the host's.
795
+ blocked = sent.get('blocked')
796
+ if blocked is not None and not (isinstance(blocked, list) and len(blocked) <= 200 and all(
797
+ isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9._+-]{1,64}', name) and name not in ('.', '..') for name in blocked)):
798
+ raise ValueError('Invalid blocked list')
799
+ return guardrails(sid, state, lists['restricted'], lists['watched'], blocked)
800
+
801
+ ACTIONS = ['create', 'list', 'start', 'shell', 'stop', 'delete', 'set-token', 'enable-claude', 'evidence', 'activity',
802
+ 'fork-create', 'fork-run', 'fork-check', 'fork-collect', 'fork-stop', 'fork-delete', 'snapshot',
803
+ 'set-guardrails', 'guardrails', 'version']
804
+
805
+ def version_payload():
806
+ """What this host actually runs: the core, and the active release when there is one."""
807
+ from core import CORE_API, EVIDENCE_SCHEMA, version
808
+ return {'core': version(), 'core_api': CORE_API, 'evidence_schema': EVIDENCE_SCHEMA,
809
+ 'release': release.active(), 'image': image()}
810
+
811
+ def main(extra_actions=None, fork_credentials=None, argv=None):
812
+ """The host command line: `projects.py <action> [id] ...`.
813
+
814
+ `extra_actions` maps further action names to functions(opts, state), for a
815
+ host layer that adds its own (state is the sandbox's inspect(), or None for
816
+ an action without an id). `fork_credentials` is fork_action's `credentials`."""
817
+ extra_actions = extra_actions or {}
818
+ parser = argparse.ArgumentParser()
819
+ parser.add_argument('action', choices=ACTIONS + sorted(extra_actions))
820
+ parser.add_argument('id', nargs='?')
821
+ parser.add_argument('--archive')
822
+ parser.add_argument('--confirm')
823
+ parser.add_argument('--release', help='create: only from this active release (core/release.py)')
824
+ parser.add_argument('--since', type=int, default=0, help='activity: from this epoch ms')
825
+ parser.add_argument('--until', type=int, default=0, help='activity: up to this epoch ms')
826
+ parser.add_argument('--forget-evidence', action='store_true', help='delete: also delete what the collector recorded for it')
827
+ parser.add_argument('--agent', choices=sorted(AGENTS), help='shell: start this agent first, without approval prompts; its exit leaves the shell')
828
+ opts = parser.parse_args(argv)
829
+ if opts.action in extra_actions and not opts.id:
830
+ return extra_actions[opts.action](opts, None)
831
+ if opts.action == 'list':
832
+ return print(json.dumps(listing()))
833
+ if opts.action == 'version':
834
+ return print(json.dumps(version_payload()))
835
+ if opts.action.startswith('fork-'):
836
+ return fork_action(opts.action, opts.id or '', opts.forget_evidence, fork_credentials)
837
+ if not opts.id or not re.fullmatch(PROJECT_ID, opts.id):
838
+ parser.error('Invalid sandbox ID')
839
+ if opts.action == 'create':
840
+ if opts.release is not None and not re.fullmatch(release.ID, opts.release):
841
+ parser.error('Invalid release id')
842
+ # Over SSH the archive arrives on stdin; staged where a copied one would be.
843
+ staged = opts.archive == '-'
844
+ if staged:
845
+ opts.archive = stage_archive(opts.id)
846
+ try:
847
+ return print(create(opts.id, opts.archive, expect_release=opts.release))
848
+ finally:
849
+ if staged:
850
+ Path(opts.archive).unlink(missing_ok=True)
851
+ state = inspect(opts.id)
852
+ if opts.action in extra_actions:
853
+ return extra_actions[opts.action](opts, state)
854
+ if opts.action == 'evidence':
855
+ return evidence(state['Id'])
856
+ if opts.action == 'activity':
857
+ return print(json.dumps(activity(state['Id'], opts.since, opts.until)))
858
+ if opts.action == 'snapshot':
859
+ return read_snapshot(opts.id, state['State']['Running'])
860
+ if opts.action == 'set-guardrails':
861
+ return print(json.dumps(set_guardrails(opts.id, state, json.loads(sys.stdin.buffer.read(4 * 1024 * 1024)))))
862
+ if opts.action == 'guardrails':
863
+ return print(json.dumps(guardrails(opts.id, state)))
864
+ if opts.action == 'set-token':
865
+ set_token(opts.id, sys.stdin.buffer.read(201).decode().strip())
866
+ print('Sandbox token set')
867
+ elif opts.action == 'enable-claude':
868
+ enable_claude(opts.id, sys.stdin.buffer.read(262145))
869
+ print('Claude Code hooks installed')
870
+ elif opts.action in ('shell', 'start'):
871
+ start(opts.id)
872
+ if opts.action == 'shell':
873
+ sys.exit(shell(opts.id, opts.agent))
874
+ elif opts.action == 'stop':
875
+ stop(opts.id)
876
+ elif opts.action == 'delete':
877
+ if opts.confirm != opts.id:
878
+ parser.error('Deletion requires --confirm with the exact sandbox ID')
879
+ try:
880
+ delete(opts.id, opts.forget_evidence)
881
+ except ValueError as error:
882
+ parser.error(str(error))