@raytrace-cli/cli 0.15.1 → 0.17.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.
- package/bin/raytrace.mjs +9 -0
- package/package.json +1 -1
- package/proxy/raytace-proxy.mjs +2 -1
- package/src/local-sandbox.mjs +54 -1
- package/src/sandbox.mjs +7 -0
- package/worker/sandbox/claude-hook.mjs +28 -2
- package/worker/sandbox/engine.py +40 -0
- package/worker/sandbox/projects.py +25 -4
- package/worker/sandbox/test_capture.py +39 -0
package/bin/raytrace.mjs
CHANGED
|
@@ -48,6 +48,11 @@ Local sandboxes (your project stays on this machine):
|
|
|
48
48
|
raytrace sandbox destroy <name> [--delete-logs | --keep-logs]
|
|
49
49
|
asks whether to delete its captured logs too;
|
|
50
50
|
kept logs move to ~/.raytrace/archive
|
|
51
|
+
raytrace sandbox files <name> show the files the agent may not change (Restrict)
|
|
52
|
+
and the files whose every read is recorded (Report)
|
|
53
|
+
raytrace sandbox files <name> --restrict <path> | --report <path> | --clear <path>
|
|
54
|
+
change them; paths are from the project's root,
|
|
55
|
+
and each option can be repeated
|
|
51
56
|
Recorded commands, files and connections: raytrace open, then Sandbox evidence.
|
|
52
57
|
macOS and Linux; Windows is experimental. raytrace doctor shows what is missing.
|
|
53
58
|
|
|
@@ -170,6 +175,9 @@ if (command === 'sandbox') {
|
|
|
170
175
|
'delete-logs': { type: 'boolean' },
|
|
171
176
|
'keep-logs': { type: 'boolean' },
|
|
172
177
|
'keep-traces': { type: 'boolean' },
|
|
178
|
+
restrict: { type: 'string', multiple: true },
|
|
179
|
+
report: { type: 'string', multiple: true },
|
|
180
|
+
clear: { type: 'string', multiple: true },
|
|
173
181
|
} });
|
|
174
182
|
} catch (error) { console.error(`${error.message}\n\nRun \`raytrace help\` for usage.`); process.exit(2); }
|
|
175
183
|
const [sub, id] = parsed.positionals;
|
|
@@ -180,6 +188,7 @@ if (command === 'sandbox') {
|
|
|
180
188
|
start: () => sandbox.start(id, parsed.values),
|
|
181
189
|
stop: () => sandbox.stop(id, parsed.values),
|
|
182
190
|
destroy: () => sandbox.destroy(id, parsed.values),
|
|
191
|
+
files: () => sandbox.files(id, parsed.values),
|
|
183
192
|
}[sub];
|
|
184
193
|
if (!action) { console.error(`Unknown sandbox command: ${sub ?? '(none)'}\n\n${HELP}`); process.exit(2); }
|
|
185
194
|
try { await action(); process.exit(0); }
|
package/package.json
CHANGED
package/proxy/raytace-proxy.mjs
CHANGED
|
@@ -460,7 +460,8 @@ const server = createServer(async (req, res) => {
|
|
|
460
460
|
return json(200, { id: box.id, name: box.name, ...(await sandboxes.activity(box.id, window)) });
|
|
461
461
|
} catch { return json(503, { error: NO_VM }); }
|
|
462
462
|
}
|
|
463
|
-
// The initial scan
|
|
463
|
+
// The initial scan and alerts are not kept for local sandboxes yet. Their restricted and
|
|
464
|
+
// reported files are set from the CLI: raytrace sandbox files <name> (src/local-sandbox.mjs).
|
|
464
465
|
if (/^\/raytace\/(sandboxes\/rtp-[a-f0-9]{32}(\/files)?|alerts(\?sandbox=rtp-[a-f0-9]{32})?|alerts\/seen)$/.test(req.url ?? '')) {
|
|
465
466
|
if (req.method === 'GET' && req.url.startsWith('/raytace/alerts')) return json(200, { alerts: [] });
|
|
466
467
|
return json(404, { error: 'Not available for local sandboxes yet. Destroy one with: raytrace sandbox destroy <name>' });
|
package/src/local-sandbox.mjs
CHANGED
|
@@ -245,14 +245,66 @@ export async function list() {
|
|
|
245
245
|
if (!running) say(`\nThe RayTrace VM is stopped; \`raytrace sandbox start <name>\` starts it.`);
|
|
246
246
|
}
|
|
247
247
|
|
|
248
|
+
/** Starts a sandbox and gives it this version's hook: the VM keeps the copy
|
|
249
|
+
* the sandbox was created with, which a newer RayTrace has since changed. */
|
|
250
|
+
function startWithHook(id) {
|
|
251
|
+
projects(['start', id]);
|
|
252
|
+
projects(['enable-claude', id], { input: readFileSync(HOOK) });
|
|
253
|
+
}
|
|
254
|
+
|
|
248
255
|
export async function start(id) {
|
|
249
256
|
id = pickId(id);
|
|
250
257
|
ensureVm();
|
|
251
|
-
|
|
258
|
+
startWithHook(id);
|
|
252
259
|
await ensureBridge();
|
|
253
260
|
say(`${registry()[id].name} running`);
|
|
254
261
|
}
|
|
255
262
|
|
|
263
|
+
/** A path as the lists keep it: from the project's root, with no ./ or trailing slash. */
|
|
264
|
+
const listPath = (path) => String(path).trim().replace(/^(\.\/)+/, '').replace(/\/+$/, '');
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* The two lists after a change. A file is on one list at most: restricting a
|
|
268
|
+
* reported file moves it, and the other way round. `clear` takes it off both.
|
|
269
|
+
*/
|
|
270
|
+
export function changedLists(current, { restrict = [], report = [], clear = [] } = {}) {
|
|
271
|
+
const [toRestrict, toReport, toClear] = [restrict, report, clear].map((paths) => paths.map(listPath).filter(Boolean));
|
|
272
|
+
const both = toRestrict.filter((path) => toReport.includes(path));
|
|
273
|
+
if (both.length) throw new Error(`${both[0]} is given to both --restrict and --report; pick one.`);
|
|
274
|
+
const gone = new Set([...toClear, ...toRestrict, ...toReport]);
|
|
275
|
+
const keep = (list) => (list ?? []).filter((path) => !gone.has(path));
|
|
276
|
+
const unique = (list) => [...new Set(list)].sort();
|
|
277
|
+
return { restricted: unique([...keep(current.restricted), ...toRestrict]), watched: unique([...keep(current.watched), ...toReport]) };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Shows or changes a local sandbox's two file lists.
|
|
282
|
+
* Restrict: the agent's file tools are refused at once, and the file is locked
|
|
283
|
+
* read-only for every program from the sandbox's next start.
|
|
284
|
+
* Report: every read and change of the file is recorded as its own line.
|
|
285
|
+
*/
|
|
286
|
+
export async function files(ref, change = {}) {
|
|
287
|
+
const id = pickId(ref);
|
|
288
|
+
ensureVm();
|
|
289
|
+
const { name } = registry()[id];
|
|
290
|
+
const read = (args, options) => JSON.parse(projects(args, options).stdout);
|
|
291
|
+
let lists = read(['guardrails', id]);
|
|
292
|
+
const changing = ['restrict', 'report', 'clear'].some((key) => change[key]?.length);
|
|
293
|
+
if (changing) {
|
|
294
|
+
const wanted = changedLists(lists, change);
|
|
295
|
+
lists = read(['set-guardrails', id], { input: JSON.stringify(wanted) });
|
|
296
|
+
}
|
|
297
|
+
const show = (title, list, none) => say(`${title}\n${list.length ? list.map((path) => ` ${path}${lists.missing.includes(path) ? ' (no such file in the sandbox yet)' : ''}`).join('\n') : ` ${none}`}`);
|
|
298
|
+
say(`${name}${changing ? ': lists updated' : ''}\n`);
|
|
299
|
+
show('Restrict (the agent cannot change these):', lists.restricted, 'none');
|
|
300
|
+
show('\nReport (every read and change is recorded):', lists.watched, 'none');
|
|
301
|
+
const unlocked = lists.restricted.filter((path) => !lists.read_only.includes(path) && !lists.missing.includes(path));
|
|
302
|
+
if (unlocked.length) {
|
|
303
|
+
say(`\nNot locked yet: ${unlocked.join(', ')}\nThe agent's file tools are refused now. To lock ${unlocked.length === 1 ? 'it' : 'them'} against every program: raytrace sandbox stop ${name} && raytrace sandbox start ${name}`);
|
|
304
|
+
}
|
|
305
|
+
if (!changing) say(`\nChange them: raytrace sandbox files ${name} --restrict <path> | --report <path> | --clear <path>`);
|
|
306
|
+
}
|
|
307
|
+
|
|
256
308
|
export async function stop(id) {
|
|
257
309
|
id = pickId(id);
|
|
258
310
|
if (vmStatus() === 'Running') projects(['stop', id]);
|
|
@@ -350,6 +402,7 @@ export const promptsLink = (id) => `http://127.0.0.1:${portOf(readConfig())}/?bo
|
|
|
350
402
|
export async function shell(id, { agent } = {}) {
|
|
351
403
|
id = pickId(id);
|
|
352
404
|
ensureVm();
|
|
405
|
+
startWithHook(id);
|
|
353
406
|
await ensureBridge();
|
|
354
407
|
const { name } = registry()[id];
|
|
355
408
|
say(agent ? `Connected to ${name}, starting ${AGENTS[agent].name} without approval prompts (the sandbox is what contains it); when it exits you are in the sandbox's shell. The sandbox keeps running.`
|
package/src/sandbox.mjs
CHANGED
|
@@ -221,6 +221,13 @@ export async function stop(id, flags = {}) {
|
|
|
221
221
|
const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/stop`); say(`${box.id} stopped; its files are kept`);
|
|
222
222
|
}
|
|
223
223
|
|
|
224
|
+
export async function files(id, flags = {}) {
|
|
225
|
+
if (id && !flags.local && !local.isLocal(id)) {
|
|
226
|
+
throw new Error('File lists are set here for local sandboxes only. For a cloud sandbox, use Initial scan in the dashboard.');
|
|
227
|
+
}
|
|
228
|
+
return local.files(id, flags);
|
|
229
|
+
}
|
|
230
|
+
|
|
224
231
|
export async function destroy(id, flags) {
|
|
225
232
|
if (flags.local || local.isLocal(id)) return local.destroy(id, flags, { ask, interactive });
|
|
226
233
|
id = await pickId(id);
|
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
* (collector.py MARKER_KEYS): the evidence joins the call exactly instead of
|
|
11
11
|
* by command text.
|
|
12
12
|
*
|
|
13
|
+
* PreToolUse and PostToolUse (a file tool): tells the sandbox's recorder which
|
|
14
|
+
* call is at the file, before and after (announce() below).
|
|
15
|
+
*
|
|
13
16
|
* PreToolUse (a file tool): refuses an edit to a file the project's owner
|
|
14
17
|
* restricted (the list projects.py guardrails() writes beside this script),
|
|
15
18
|
* saying why. From the sandbox's next start the file is locked on the host
|
|
@@ -109,15 +112,34 @@ function queue(event) {
|
|
|
109
112
|
} catch { /* never disturb Claude Code */ }
|
|
110
113
|
}
|
|
111
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Tells the sandbox's recorder which tool call is at a file. A file tool runs
|
|
117
|
+
* inside Claude Code itself, which carries no call id, so the recorder sees
|
|
118
|
+
* the agent open or replace the file and cannot say for which call. A program
|
|
119
|
+
* started here carries the id in its environment and the file in its
|
|
120
|
+
* arguments, and the recorder reads both (engine.py TOOL_MARK). It does nothing.
|
|
121
|
+
*/
|
|
122
|
+
function announce(phase, path) {
|
|
123
|
+
if (!path || !/^[A-Za-z0-9_-]{1,128}$/.test(input.tool_use_id ?? '') || typeof input.tool_name !== 'string') return;
|
|
124
|
+
try {
|
|
125
|
+
execFileSync('/bin/true', ['raytrace-tool', phase, input.tool_name, path],
|
|
126
|
+
{ env: { ...process.env, RAYTRACE_CALL_ID: input.tool_use_id }, stdio: 'ignore', timeout: 2000 });
|
|
127
|
+
} catch { /* never disturb Claude Code */ }
|
|
128
|
+
}
|
|
129
|
+
|
|
112
130
|
if (input.hook_event_name === 'PreToolUse') {
|
|
113
131
|
const named = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
|
|
114
132
|
if (input.tool_name !== 'Bash' && typeof named === 'string') {
|
|
115
133
|
const path = inside(named);
|
|
116
|
-
|
|
134
|
+
// A read is never refused here: the file lock on the host decides that.
|
|
135
|
+
const refused = path && input.tool_name !== 'Read' && restricted.includes(path);
|
|
136
|
+
if (path && !refused) announce('begin', path);
|
|
137
|
+
if (refused) {
|
|
117
138
|
queue({ kind: 'blocked', path });
|
|
118
139
|
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
|
|
119
140
|
permissionDecisionReason: `RayTrace: ${path} is restricted by this project's owner and cannot be changed. `
|
|
120
|
-
+ 'Do not try another way to write it; tell the user it has to be unlocked under Initial scan in the RayTrace dashboard
|
|
141
|
+
+ 'Do not try another way to write it; tell the user it has to be unlocked: under Initial scan in the RayTrace dashboard, '
|
|
142
|
+
+ `or for a local sandbox with \`raytrace sandbox files <name> --clear ${path}\`.` } }));
|
|
121
143
|
}
|
|
122
144
|
process.exit(0);
|
|
123
145
|
}
|
|
@@ -306,6 +328,10 @@ if (!/^[0-9a-f-]{36}$/.test(session ?? '') || typeof transcript !== 'string'
|
|
|
306
328
|
|| !transcript.startsWith(join(home, '.claude', 'projects') + '/')) process.exit(0);
|
|
307
329
|
|
|
308
330
|
const callId = /^[A-Za-z0-9_-]{1,128}$/.test(input.tool_use_id ?? '') ? input.tool_use_id : null;
|
|
331
|
+
// The file tool is done: what the agent does to the file after this is not this call's.
|
|
332
|
+
if (input.hook_event_name === 'PostToolUse' && input.tool_name !== 'Bash') {
|
|
333
|
+
announce('end', inside(input.tool_input?.file_path ?? input.tool_input?.notebook_path));
|
|
334
|
+
}
|
|
309
335
|
// A read of a file the owner restricted or watches. A write that went through
|
|
310
336
|
// is in the snapshot below, with its size; a refused one was queued above.
|
|
311
337
|
if (input.hook_event_name === 'PostToolUse' && READ_ONLY.has(input.tool_name)) {
|
package/worker/sandbox/engine.py
CHANGED
|
@@ -106,6 +106,11 @@ CALL_MARKER = re.compile(r'(?:^|[\s;\'"])export RAYTRACE_CALL_ID=([A-Za-z0-9_-]{
|
|
|
106
106
|
# RayTrace's own hook in the sandbox: after each tool call it runs git over the
|
|
107
107
|
# whole project to keep a snapshot. What it and its children do is not the agent's doing.
|
|
108
108
|
OWN_HOOK = '/opt/raytace-claude/hook.mjs'
|
|
109
|
+
# The hook announces a file tool's call around the tool, as a program it starts:
|
|
110
|
+
# `true raytrace-tool begin|end <tool> <path>`, with the call id in its environment.
|
|
111
|
+
# The agent's file tools run inside the agent itself, which carries no call id.
|
|
112
|
+
TOOL_MARK = 'raytrace-tool'
|
|
113
|
+
TOOL_SLACK = (200_000_000, 2_000_000_000) # ns a file event may precede the begin, or follow the end
|
|
109
114
|
SANDBOX_ID = re.compile(r'rt[pf]-[a-f0-9]{32}')
|
|
110
115
|
|
|
111
116
|
|
|
@@ -330,6 +335,7 @@ class Sandbox:
|
|
|
330
335
|
self.final = {} # path -> when to stop waiting for a change
|
|
331
336
|
self.causes = {} # path -> what the watcher saw of it since the last look
|
|
332
337
|
self.raw = collections.deque(maxlen=512) # recent delete, rename, resize and mode calls: they carry no path
|
|
338
|
+
self.tools = collections.deque(maxlen=256) # file tool calls the hook announced: {call_id, path, pids, begin_ns, end_ns}
|
|
333
339
|
self.aliases = collections.deque(maxlen=256) # recent opens for writing of files not kept: one may be a link to a kept file
|
|
334
340
|
self.watches = {} # folder -> inotify watch
|
|
335
341
|
self.counts = {} # step -> opens that were only counted
|
|
@@ -611,10 +617,40 @@ class Engine(threading.Thread):
|
|
|
611
617
|
'call_id': marker or known.get('call_id') or parent.get('call_id'),
|
|
612
618
|
'own': bool(known.get('own') or parent.get('own')
|
|
613
619
|
or (len(argv) > 1 and argv[1] == OWN_HOOK and posixpath.basename(argv[0]) == 'node'))}
|
|
620
|
+
if box.processes[pid]['own'] and argv[1:2] == [TOOL_MARK] and len(argv) == 5 and marker:
|
|
621
|
+
self.announced(box, pid, marker, argv[2], argv[4], int(event.get('timestamp_ns') or 0) or time.time_ns())
|
|
614
622
|
if len(box.processes) > 20_000: # exits that never arrived: forget the oldest half
|
|
615
623
|
for stale in list(box.processes)[:10_000]:
|
|
616
624
|
del box.processes[stale]
|
|
617
625
|
|
|
626
|
+
def announced(self, box, pid, call_id, phase, path, at_ns):
|
|
627
|
+
"""The hook saying a file tool is about to touch `path`, or has."""
|
|
628
|
+
if phase == 'end':
|
|
629
|
+
for tool in reversed(box.tools):
|
|
630
|
+
if tool['call_id'] == call_id and tool['path'] == path:
|
|
631
|
+
tool['end_ns'] = at_ns
|
|
632
|
+
break
|
|
633
|
+
return
|
|
634
|
+
# Whoever started the hook is the agent: the tool runs in that process.
|
|
635
|
+
pids, at = set(), pid
|
|
636
|
+
for _ in range(8):
|
|
637
|
+
at = (box.processes.get(at) or {}).get('ppid')
|
|
638
|
+
if not at or at in pids:
|
|
639
|
+
break
|
|
640
|
+
pids.add(at)
|
|
641
|
+
box.tools.append({'call_id': call_id, 'path': path, 'pids': pids, 'begin_ns': at_ns, 'end_ns': None})
|
|
642
|
+
|
|
643
|
+
def called(self, box, who, path, at_ns):
|
|
644
|
+
"""`who`, with the tool call the hook announced for this file about
|
|
645
|
+
then, when the process carries none of its own."""
|
|
646
|
+
if who.get('call_id') or who.get('own') or not who.get('pid'):
|
|
647
|
+
return who
|
|
648
|
+
for tool in reversed(box.tools): # the latest to begin first
|
|
649
|
+
if (tool['path'] == path and who['pid'] in tool['pids'] and tool['begin_ns'] - TOOL_SLACK[0] <= at_ns
|
|
650
|
+
and (tool['end_ns'] is None or at_ns <= tool['end_ns'] + TOOL_SLACK[1])):
|
|
651
|
+
return {**who, 'call_id': tool['call_id'], 'call_from': 'tool_report'}
|
|
652
|
+
return who
|
|
653
|
+
|
|
618
654
|
def exited(self, box, event):
|
|
619
655
|
gone = box.processes.pop(event.get('pid'), None)
|
|
620
656
|
# A process that has exited writes nothing more. Whatever it did to a
|
|
@@ -656,6 +692,8 @@ class Engine(threading.Thread):
|
|
|
656
692
|
'fact_id': fact_id, 'container_id': box.container, 'kind': kind, 'count': 0, 'first_ns': str(at_ns),
|
|
657
693
|
'pid': who.get('pid'), 'process_start_ns': who.get('start_ns'), 'process': who.get('name'),
|
|
658
694
|
'command': ' '.join(who.get('argv') or [])[:160] or None, 'call_id': who.get('call_id'), **body}
|
|
695
|
+
if who.get('call_from'): # not carried by the process: the hook said which call was at this file
|
|
696
|
+
fact['call_from'] = who['call_from']
|
|
659
697
|
if box.fork:
|
|
660
698
|
fact['fork'] = True
|
|
661
699
|
fact['count'] += 1
|
|
@@ -745,6 +783,7 @@ class Engine(threading.Thread):
|
|
|
745
783
|
if writing and not errno and box.guarded:
|
|
746
784
|
box.aliases.append({'path': path, 'who': who, 'at_ns': at_ns, 'syscall': self.calls.get(event.get('sysno'), ('open', 'open'))[0]})
|
|
747
785
|
return self.counted(box, who, top, at_ns)
|
|
786
|
+
who = self.called(box, who, path, at_ns)
|
|
748
787
|
call = self.calls.get(event.get('sysno'), ('open', 'open'))[0]
|
|
749
788
|
basis = {'syscall': call, 'flags': flags, 'resolution': 'lexical'}
|
|
750
789
|
if errno:
|
|
@@ -950,6 +989,7 @@ class Engine(threading.Thread):
|
|
|
950
989
|
if link:
|
|
951
990
|
found, via = [(link['who'], link['syscall'])], link['path']
|
|
952
991
|
who, call = found[0] if found else ({}, None)
|
|
992
|
+
who = self.called(box, who, path, cause['at_ns'])
|
|
953
993
|
certainty = 'unattributed' if not found else 'confirmed' if len(found) == 1 else 'one_of'
|
|
954
994
|
basis = {'syscall': call, 'watcher': sorted(cause['events']), 'before': before, 'after': after, 'resolution': 'lexical'}
|
|
955
995
|
if via:
|
|
@@ -127,8 +127,9 @@ def install_claude_hooks(container, hook):
|
|
|
127
127
|
# No permission prompts for any Claude Code session here: the sandbox is
|
|
128
128
|
# what contains the agent, and the hook still refuses restricted files.
|
|
129
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
|
-
|
|
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}]}],
|
|
132
133
|
**{event: [{**({'matcher': '*'} if event == 'PostToolUse' else {}),
|
|
133
134
|
'hooks': [{'type': 'command', 'command': command, 'timeout': 15}]}]
|
|
134
135
|
for event in ('UserPromptSubmit', 'PostToolUse', 'Stop', 'SubagentStop', 'SessionEnd')}}}, indent=2).encode()
|
|
@@ -186,6 +187,24 @@ def lock(root, path, on):
|
|
|
186
187
|
finally:
|
|
187
188
|
os.close(at)
|
|
188
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
|
+
|
|
189
208
|
def guardrails(sid, state, restricted=None, watched=None, blocked=None):
|
|
190
209
|
"""Applies a sandbox's restricted files: the new list, or the stored one
|
|
191
210
|
again. The Claude Code hook gets the list at once and refuses the edit
|
|
@@ -196,7 +215,8 @@ def guardrails(sid, state, restricted=None, watched=None, blocked=None):
|
|
|
196
215
|
owner wants to hear of a read or a change: the hook reports an attempt on
|
|
197
216
|
them and nothing is locked. `blocked` are the programs the hook refuses
|
|
198
217
|
to start (None keeps the stored list). Returns {hook: the hook has the
|
|
199
|
-
list, read_only: the files locked
|
|
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}."""
|
|
200
220
|
GUARDRAILS.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
201
221
|
stored = GUARDRAILS / (sid+'.json')
|
|
202
222
|
kept = json.loads(stored.read_text()) if stored.exists() else {}
|
|
@@ -216,7 +236,8 @@ def guardrails(sid, state, restricted=None, watched=None, blocked=None):
|
|
|
216
236
|
stored.write_text(lists)
|
|
217
237
|
if running and (restricted or before or watched or kept.get('watched') or blocked or kept.get('blocked')):
|
|
218
238
|
write_as_root(sid, GUARDRAILS_IN_SANDBOX, lists.encode())
|
|
219
|
-
return {'hook': bool(running), 'read_only': read_only
|
|
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)]}
|
|
220
241
|
|
|
221
242
|
def as_node(container, *command, data=None, check=True):
|
|
222
243
|
"""Runs a command in a sandbox as its agent user, never root."""
|
|
@@ -348,6 +348,45 @@ class EveryProjectFile(unittest.TestCase):
|
|
|
348
348
|
self.engine.executed(self.box, {'pid': 50, 'ppid': 1, 'process_start_ns': '50', 'executable': '/bin/bash', 'argv': [
|
|
349
349
|
'/bin/bash', '-c', "source /home/node/snap.sh || true && eval 'export RAYTRACE_CALL_ID=toolu_01ABC\necho hi > src/app.js' < /dev/null"]})
|
|
350
350
|
self.assertEqual(self.box.processes[50]['call_id'], 'toolu_01ABC')
|
|
351
|
+
def hook(self, pid, phase, call_id, path, at_ns):
|
|
352
|
+
"""The hook, started by the agent (pid 10), announcing a file tool's call."""
|
|
353
|
+
self.engine.executed(self.box, {'pid': pid, 'ppid': 10, 'process_start_ns': str(pid), 'executable': '/usr/local/bin/node',
|
|
354
|
+
'argv': ['node', engine.OWN_HOOK]})
|
|
355
|
+
self.engine.executed(self.box, {'pid': pid + 1, 'ppid': pid, 'process_start_ns': str(pid + 1), 'executable': '/usr/bin/true',
|
|
356
|
+
'argv': ['true', engine.TOOL_MARK, phase, 'Write', path], 'timestamp_ns': str(at_ns),
|
|
357
|
+
'markers': {'RAYTRACE_CALL_ID': call_id}})
|
|
358
|
+
|
|
359
|
+
def test_the_agents_own_file_tool_is_joined_to_the_call_the_hook_announced(self):
|
|
360
|
+
self.engine.refresh(self.box)
|
|
361
|
+
self.box.processes[10] = {'start_ns': '10', 'ppid': 1, 'name': 'claude.exe', 'argv': ['claude'], 'call_id': None}
|
|
362
|
+
read = {'kind': 'open', 'pathname': '/workspace/config/payment-keys.js', 'flags': 0, 'errno': 0, 'pid': 10, 'ppid': 1,
|
|
363
|
+
'process_start_ns': '10', 'sysno': 56}
|
|
364
|
+
now = time.time_ns()
|
|
365
|
+
# Before any call is announced, the agent's read names no call.
|
|
366
|
+
self.engine.opened(self.box, {**read, 'timestamp_ns': str(now - 60_000_000_000)})
|
|
367
|
+
self.hook(60, 'begin', 'toolu_read', 'config/payment-keys.js', now)
|
|
368
|
+
self.engine.opened(self.box, {**read, 'timestamp_ns': str(now + 1_000_000)})
|
|
369
|
+
self.hook(62, 'end', 'toolu_read', 'config/payment-keys.js', now + 2_000_000)
|
|
370
|
+
# Long after the call ended, it is not that call's read.
|
|
371
|
+
self.engine.opened(self.box, {**read, 'timestamp_ns': str(now + 30_000_000_000)})
|
|
372
|
+
self.assertEqual({(fact['call_id'], fact.get('call_from'), fact['count']) for fact in self.engine.facts.values()},
|
|
373
|
+
{(None, None, 2), ('toolu_read', 'tool_report', 1)})
|
|
374
|
+
self.engine.facts.clear()
|
|
375
|
+
# A file the Write tool saves: written under another name and moved here.
|
|
376
|
+
self.hook(64, 'begin', 'toolu_write', 'src/app.js', time.time_ns())
|
|
377
|
+
self.write('src/app.js', 'saved by the tool')
|
|
378
|
+
self.engine.numbered_call(self.box, {**self.RENAME, 'pid': 10, 'process_start_ns': '10', 'timestamp_ns': str(time.time_ns())})
|
|
379
|
+
self.looked('src/app.js', 'moved_to')
|
|
380
|
+
(fact,) = self.engine.facts.values()
|
|
381
|
+
self.assertEqual((fact['effect'], fact['certainty'], fact['pid'], fact['call_id']), ('changed', 'confirmed', 10, 'toolu_write'))
|
|
382
|
+
|
|
383
|
+
def test_only_the_hook_can_announce_a_call(self):
|
|
384
|
+
self.engine.refresh(self.box)
|
|
385
|
+
self.box.processes[10] = {'start_ns': '10', 'ppid': 1, 'name': 'claude.exe', 'argv': ['claude'], 'call_id': None}
|
|
386
|
+
self.engine.executed(self.box, {'pid': 70, 'ppid': 10, 'process_start_ns': '70', 'executable': '/usr/bin/true',
|
|
387
|
+
'argv': ['true', engine.TOOL_MARK, 'begin', 'Read', 'config/payment-keys.js'],
|
|
388
|
+
'timestamp_ns': str(time.time_ns()), 'markers': {'RAYTRACE_CALL_ID': 'made_up'}})
|
|
389
|
+
self.assertEqual(len(self.box.tools), 0)
|
|
351
390
|
|
|
352
391
|
def test_a_write_through_a_link_is_still_the_writers(self):
|
|
353
392
|
os.symlink('app.js', Path(self.folder.name) / 'src/alias.js')
|