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