@raytrace-cli/cli 0.11.1 → 0.12.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/README.md +29 -3
- package/bin/raytrace.mjs +30 -0
- package/package.json +1 -1
- package/src/report.mjs +178 -0
- package/worker/sandbox/claude-hook.mjs +40 -0
- package/worker/sandbox/projects.py +14 -6
package/README.md
CHANGED
|
@@ -465,6 +465,25 @@ raytrace key # which keys are set
|
|
|
465
465
|
was.
|
|
466
466
|
- `raytrace key openrouter --remove` removes a key.
|
|
467
467
|
|
|
468
|
+
## Report a run on a pull request
|
|
469
|
+
|
|
470
|
+
`raytrace report <trace-id>` turns one recorded run into a short Markdown
|
|
471
|
+
comment: the commands with their exit codes (failures first), the files changed
|
|
472
|
+
with lines added and removed, the cost and the trace id.
|
|
473
|
+
|
|
474
|
+
```sh
|
|
475
|
+
raytrace report <trace-id> # print the comment
|
|
476
|
+
raytrace report <trace-id> --pr 42 # post it on PR 42 with the GitHub CLI, signed in as you
|
|
477
|
+
raytrace report <trace-id> --pr 42 --dry-run # show what would be posted
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
- **Only command text and file paths go in**, never tool output. API keys,
|
|
481
|
+
tokens and passwords are hidden, and the comment says how many were.
|
|
482
|
+
- **Running it again updates the same comment.** It only ever edits its own.
|
|
483
|
+
- **Cloud runs:** add `--sandbox <rtp-id>` (needs sign-in). `--link` adds a
|
|
484
|
+
share link, which uses one of your plan's expiring links.
|
|
485
|
+
- **No `gh`?** It prints the comment for you to paste.
|
|
486
|
+
|
|
468
487
|
---
|
|
469
488
|
|
|
470
489
|
## Commands
|
|
@@ -481,6 +500,7 @@ raytrace key # which keys are set
|
|
|
481
500
|
| `raytrace auth login\|status\|logout` | your RayTrace sign-in, for cloud sandboxes |
|
|
482
501
|
| `raytrace upload logs [--sandbox <name>]` | send a local sandbox's recorded logs to the cloud dashboard; `raytrace upload status` shows your storage |
|
|
483
502
|
| `raytrace share <trace-id> [--fork]` | a time-limited link to one recorded prompt; `--list`, `--revoke <share-id>` |
|
|
503
|
+
| `raytrace report <trace-id> [--pr <number>]` | a pull-request comment for one run: commands and exit codes, files changed, cost. Prints it, or posts it with `gh`; `--sandbox <rtp-id>` for a cloud run, `--link`, `--dry-run` |
|
|
484
504
|
| `raytrace export <trace-id> [--format json\|markdown] [--output <file>]` | export a recorded prompt to the terminal or a file, even with RayTrace stopped |
|
|
485
505
|
| `raytrace --code <code>` | redeem a beta invite code |
|
|
486
506
|
| `raytrace key [openrouter\|typesafe] [--remove]` | your keys for the dashboard's AI features |
|
|
@@ -582,8 +602,10 @@ RAYTRACE_HOME=/tmp/rt node bin/raytrace.mjs setup --no-claude-code
|
|
|
582
602
|
|
|
583
603
|
### Publishing to pip
|
|
584
604
|
|
|
585
|
-
The pip package
|
|
586
|
-
|
|
605
|
+
The pip package, `raytrace-cli` (PyPI does not allow `raytrace`), is the npm
|
|
606
|
+
package plus an official Node.js build, one wheel per platform. Each release
|
|
607
|
+
goes to both with the same version: bump it (`npm version x.y.z`), push the
|
|
608
|
+
`vx.y.z` tag, `npm publish`, then build the same version's wheels and upload them:
|
|
587
609
|
|
|
588
610
|
```sh
|
|
589
611
|
python3 python/build_wheels.py # all six platforms, into python/dist/
|
|
@@ -592,7 +614,11 @@ twine upload python/dist/*.whl
|
|
|
592
614
|
|
|
593
615
|
The *pip wheels* workflow builds the same wheels on every `v*` tag and installs
|
|
594
616
|
them on Linux, macOS and Windows (x64 and ARM); its `wheels` artifact can be
|
|
595
|
-
uploaded instead. The Node.js version
|
|
617
|
+
uploaded instead (`gh run download <run-id> -n wheels`). The Node.js version
|
|
618
|
+
is `NODE_VERSION` in `python/build_wheels.py`. Run `twine upload` in a real
|
|
619
|
+
terminal, since it asks for the PyPI token (username `__token__`); `--verbose`
|
|
620
|
+
shows why PyPI refuses an upload. A version can only be uploaded once, and the
|
|
621
|
+
PyPI page's description (`python/README.md`) only changes with a new version.
|
|
596
622
|
|
|
597
623
|
## License
|
|
598
624
|
|
package/bin/raytrace.mjs
CHANGED
|
@@ -68,6 +68,15 @@ Share recorded traces (time-limited cloud link):
|
|
|
68
68
|
raytrace share --list list your active share links
|
|
69
69
|
raytrace share --revoke <share-id> revoke an active share link
|
|
70
70
|
|
|
71
|
+
Report a run on a pull request (commands and exit codes, files changed, cost):
|
|
72
|
+
raytrace report <trace-id> print the comment (Markdown); secrets are hidden
|
|
73
|
+
raytrace report <trace-id> --pr <number> post it with the GitHub CLI (gh), signed in as you;
|
|
74
|
+
run again to update the same comment
|
|
75
|
+
--sandbox <rtp-id> a cloud sandbox's run (needs sign-in)
|
|
76
|
+
--link add a share link (cloud runs; uses one of your
|
|
77
|
+
plan's share links, which expire)
|
|
78
|
+
--dry-run print what would be posted, post nothing
|
|
79
|
+
|
|
71
80
|
AI features in the dashboard (summaries, recaps, Chain of thought), on your own key:
|
|
72
81
|
raytrace key which keys are set
|
|
73
82
|
raytrace key openrouter add your OpenRouter key (asked for, not echoed)
|
|
@@ -271,6 +280,27 @@ if (command === 'share') {
|
|
|
271
280
|
}
|
|
272
281
|
}
|
|
273
282
|
|
|
283
|
+
if (command === 'report') {
|
|
284
|
+
const usage = 'Usage: raytrace report <trace-id> [--pr <number>] [--sandbox <rtp-id>] [--link] [--dry-run]';
|
|
285
|
+
let parsed;
|
|
286
|
+
try {
|
|
287
|
+
parsed = parseArgs({ args: rest, strict: true, allowPositionals: true, options: {
|
|
288
|
+
pr: { type: 'string' },
|
|
289
|
+
sandbox: { type: 'string' },
|
|
290
|
+
link: { type: 'boolean' },
|
|
291
|
+
'dry-run': { type: 'boolean' },
|
|
292
|
+
} });
|
|
293
|
+
} catch (error) { console.error(`${error.message}\n\n${usage}`); process.exit(2); }
|
|
294
|
+
const [traceId, ...extra] = parsed.positionals;
|
|
295
|
+
if (!traceId || extra.length) { console.error(usage); process.exit(2); }
|
|
296
|
+
const { reportCommand } = await import('../src/report.mjs');
|
|
297
|
+
try {
|
|
298
|
+
await reportCommand(traceId, { pr: parsed.values.pr ?? null, sandbox: parsed.values.sandbox ?? null,
|
|
299
|
+
link: Boolean(parsed.values.link), dryRun: Boolean(parsed.values['dry-run']) });
|
|
300
|
+
process.exit(0);
|
|
301
|
+
} catch (error) { console.error(`raytrace report: ${error.message}`); process.exit(1); }
|
|
302
|
+
}
|
|
303
|
+
|
|
274
304
|
let flags;
|
|
275
305
|
try {
|
|
276
306
|
({ values: flags } = parseArgs({ args: rest, strict: true, options: {
|
package/package.json
CHANGED
package/src/report.mjs
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// `raytrace report <trace-id> [--pr <n>]`: a short pull-request comment for one
|
|
2
|
+
// recorded prompt: the commands it ran with their exit codes, the files it
|
|
3
|
+
// changed, what failed and what it cost, and (with --link, for a cloud
|
|
4
|
+
// sandbox) a share link. Only command text and file paths go in, never tool
|
|
5
|
+
// output, and the text is scanned for secrets before it leaves this machine.
|
|
6
|
+
//
|
|
7
|
+
// The trace comes from this machine's evidence database, as `raytrace export`
|
|
8
|
+
// reads it, or from RayTrace cloud for a cloud sandbox (--sandbox rtp-…).
|
|
9
|
+
// Posting goes through the GitHub CLI (`gh`), signed in as you: the comment
|
|
10
|
+
// it made before on that pull request is updated, never another comment.
|
|
11
|
+
import { spawnSync } from 'node:child_process';
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
13
|
+
import { paths } from './paths.mjs';
|
|
14
|
+
import { call } from './api.mjs';
|
|
15
|
+
|
|
16
|
+
const SANDBOX = /^rtp-[a-f0-9]{32}$/;
|
|
17
|
+
export const MARKER = '<!-- raytrace-report -->';
|
|
18
|
+
const DASHBOARD = process.env.RAYTRACE_DASHBOARD_URL || 'https://app.raytracer.si';
|
|
19
|
+
const MAX_COMMANDS = 30;
|
|
20
|
+
const MAX_FILES = 40;
|
|
21
|
+
const COMMAND_CHARS = 120;
|
|
22
|
+
const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'apply_patch']);
|
|
23
|
+
|
|
24
|
+
// What a key or token looks like. A `name=value` match keeps the name.
|
|
25
|
+
const SECRETS = [
|
|
26
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
|
|
27
|
+
/\bsk-ant-[A-Za-z0-9_-]{16,}/g,
|
|
28
|
+
/\bsk-or-[A-Za-z0-9_-]{16,}/g,
|
|
29
|
+
/\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}/g,
|
|
30
|
+
/\bgh[pousr]_[A-Za-z0-9]{20,}/g,
|
|
31
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}/g,
|
|
32
|
+
/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,
|
|
33
|
+
/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
|
|
34
|
+
/\b[Bb]earer\s+[A-Za-z0-9._~+/-]{16,}=*/g,
|
|
35
|
+
];
|
|
36
|
+
const NAMED_SECRET = /((?:api[_-]?key|access[_-]?key|token|secret|password|passwd|pwd)["']?\s*[:=]\s*["']?)(?!\[REDACTED\])[^\s"'&]{8,}/gi;
|
|
37
|
+
|
|
38
|
+
/** The text with anything that looks like a secret replaced, and how many were. */
|
|
39
|
+
export function redactSecrets(text) {
|
|
40
|
+
let count = 0;
|
|
41
|
+
let out = String(text ?? '');
|
|
42
|
+
for (const pattern of SECRETS) out = out.replace(pattern, () => { count += 1; return '[REDACTED]'; });
|
|
43
|
+
out = out.replace(NAMED_SECRET, (_, name) => { count += 1; return `${name}[REDACTED]`; });
|
|
44
|
+
return { text: out, count };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const oneLine = (text, max) => {
|
|
48
|
+
const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
49
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
|
|
50
|
+
};
|
|
51
|
+
// Inside a table cell: no pipes or backticks can end the cell or the code.
|
|
52
|
+
const cell = (text) => `<code>${text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\|/g, '|')}</code>`;
|
|
53
|
+
|
|
54
|
+
function outcome(call) {
|
|
55
|
+
if (typeof call.exit_code === 'number') return { label: call.exit_code === 0 ? '✅ 0' : `❌ ${call.exit_code}`, failed: call.exit_code !== 0 };
|
|
56
|
+
if (call.status === 'failed' || call.error) return { label: '❌ failed', failed: true };
|
|
57
|
+
if (!call.verified) return { label: '⚪ not seen', failed: false };
|
|
58
|
+
return { label: '✅ ran', failed: false };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** What the comment says, worked out from a trace (proxy/trace-view.mjs). */
|
|
62
|
+
export function summarize(trace) {
|
|
63
|
+
const calls = trace.callVerifications ?? [];
|
|
64
|
+
const commands = calls.filter((c) => c.kind === 'command' && c.proposed).map((c) => ({ text: c.proposed, ...outcome(c) }));
|
|
65
|
+
const files = new Map();
|
|
66
|
+
for (const c of calls) {
|
|
67
|
+
for (const change of c.snapshot?.changes ?? []) {
|
|
68
|
+
if (typeof change?.path === 'string') files.set(change.path, { status: change.status ?? null, added: change.added ?? null, removed: change.removed ?? null });
|
|
69
|
+
}
|
|
70
|
+
if (c.kind === 'file' && WRITE_TOOLS.has(c.name) && typeof c.proposed === 'string' && !files.has(c.proposed)) files.set(c.proposed, { status: null });
|
|
71
|
+
}
|
|
72
|
+
let cost = null;
|
|
73
|
+
for (const r of trace.requests ?? []) if (r.cost != null) cost = (cost ?? 0) + r.cost;
|
|
74
|
+
return { commands, failed: commands.filter((c) => c.failed).length, files: [...files].map(([path, info]) => ({ path, ...info })), cost };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The comment's Markdown, secrets already removed. `link`: {url, expires} or null. */
|
|
78
|
+
export function formatReport(trace, { link = null, linkNote = null } = {}) {
|
|
79
|
+
const { commands, failed, files, cost } = summarize(trace);
|
|
80
|
+
const lines = [MARKER, '### RayTrace run report', ''];
|
|
81
|
+
lines.push(`**Status:** ${trace.status ?? 'unknown'} · **Model:** ${trace.model ?? 'unknown'} · **Cost:** ${cost != null ? `$${cost.toFixed(4)}` : 'unknown'}`);
|
|
82
|
+
lines.push(`**Commands:** ${commands.length} · **Failed:** ${failed} · **Files changed:** ${files.length}`);
|
|
83
|
+
lines.push('');
|
|
84
|
+
if (commands.length) {
|
|
85
|
+
lines.push('| Exit | Command |', '| --- | --- |');
|
|
86
|
+
// Failures first: they are what a reviewer needs.
|
|
87
|
+
const ordered = [...commands.filter((c) => c.failed), ...commands.filter((c) => !c.failed)];
|
|
88
|
+
for (const c of ordered.slice(0, MAX_COMMANDS)) lines.push(`| ${c.label} | ${cell(oneLine(c.text, COMMAND_CHARS))} |`);
|
|
89
|
+
if (commands.length > MAX_COMMANDS) lines.push('', `…and ${commands.length - MAX_COMMANDS} more commands.`);
|
|
90
|
+
lines.push('');
|
|
91
|
+
} else lines.push('No commands were run.', '');
|
|
92
|
+
if (files.length) {
|
|
93
|
+
lines.push(`<details><summary>Files changed (${files.length})</summary>`, '');
|
|
94
|
+
for (const f of files.slice(0, MAX_FILES)) {
|
|
95
|
+
const size = f.added != null || f.removed != null ? ` +${f.added ?? 0} −${f.removed ?? 0}` : '';
|
|
96
|
+
lines.push(`- ${cell(oneLine(f.path, 200))}${f.status ? ` ${f.status}` : ''}${size}`);
|
|
97
|
+
}
|
|
98
|
+
if (files.length > MAX_FILES) lines.push(`- …and ${files.length - MAX_FILES} more`);
|
|
99
|
+
lines.push('', '</details>', '');
|
|
100
|
+
}
|
|
101
|
+
if (link) {
|
|
102
|
+
const expires = link.expires ? ` (the link expires ${new Date(link.expires * 1000).toISOString().replace('T', ' ').slice(0, 16)} UTC)` : '';
|
|
103
|
+
lines.push(`[Open this run in RayTrace](${link.url})${expires}`, '');
|
|
104
|
+
} else if (linkNote) lines.push(`_${linkNote}_`, '');
|
|
105
|
+
lines.push(`<sub>Trace \`${oneLine(trace.id, 80).replace(/`/g, '')}\` · recorded by RayTrace: commands as the agent ran them, exit codes as the sandbox saw them.</sub>`);
|
|
106
|
+
const { text, count } = redactSecrets(lines.join('\n'));
|
|
107
|
+
return count ? `${text}\n\n_${count} value${count === 1 ? '' : 's'} that looked like secrets ${count === 1 ? 'was' : 'were'} hidden._` : text;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function localTrace(traceId) {
|
|
111
|
+
if (!existsSync(paths.database)) return null;
|
|
112
|
+
const { openEvidenceStore } = await import('../proxy/evidence-store.mjs');
|
|
113
|
+
const { readTraces } = await import('../proxy/trace-view.mjs');
|
|
114
|
+
const store = openEvidenceStore(paths.database, { readOnly: true });
|
|
115
|
+
try {
|
|
116
|
+
return (await readTraces(store, { turnId: traceId, includeHistory: true, evidence: true })).find((t) => t.id === traceId) ?? null;
|
|
117
|
+
} finally { store.close(); }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function cloudTrace(traceId, sandbox, api) {
|
|
121
|
+
const data = await api('GET', `/v1/evidence/traces?sandbox=${sandbox}&scope=history&evidence=1`);
|
|
122
|
+
return (data.traces ?? []).find((t) => t.id === traceId) ?? null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A share link, or why there is none: the link is only ever extra. */
|
|
126
|
+
async function shareLink(trace, api) {
|
|
127
|
+
if (!SANDBOX.test(trace.sandboxId ?? '')) return { link: null, note: 'No share link: this run was in a local sandbox.' };
|
|
128
|
+
try {
|
|
129
|
+
const made = await api('POST', '/v1/shares', { body: JSON.stringify({ trace_id: trace.id, sandbox_id: trace.sandboxId, allow_fork: false }),
|
|
130
|
+
headers: { 'content-type': 'application/json' } });
|
|
131
|
+
return { link: { url: new URL(made.url, DASHBOARD).href, expires: made.share?.expires ?? null }, note: null };
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (error?.data?.code === 'share_limit') return { link: null, note: 'No share link: your plan\'s share links are all in use.' };
|
|
134
|
+
return { link: null, note: `No share link: ${oneLine(error?.message, 120)}.` };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function gh(args, input) {
|
|
139
|
+
const run = spawnSync('gh', args, { input, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
|
|
140
|
+
if (run.error?.code === 'ENOENT') throw Object.assign(new Error('GitHub CLI (gh) not found'), { code: 'ENOENT' });
|
|
141
|
+
if (run.status !== 0) throw new Error(`gh ${args[0]} failed: ${oneLine(run.stderr || run.stdout, 300)}`);
|
|
142
|
+
return run.stdout;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Posts the report on pull request `pr`, or updates the one this user posted there before. */
|
|
146
|
+
export function postComment(pr, body, run = gh) {
|
|
147
|
+
const login = run(['api', 'user', '--jq', '.login']).trim();
|
|
148
|
+
const pages = JSON.parse(run(['api', `repos/{owner}/{repo}/issues/${pr}/comments`, '--paginate', '--slurp']) || '[]');
|
|
149
|
+
const mine = pages.flat().filter((c) => c?.user?.login === login && String(c.body ?? '').startsWith(MARKER)).at(-1);
|
|
150
|
+
const payload = JSON.stringify({ body });
|
|
151
|
+
if (mine) run(['api', '-X', 'PATCH', `repos/{owner}/{repo}/issues/comments/${mine.id}`, '--input', '-', '--silent'], payload);
|
|
152
|
+
else run(['api', '-X', 'POST', `repos/{owner}/{repo}/issues/${pr}/comments`, '--input', '-', '--silent'], payload);
|
|
153
|
+
return mine ? 'updated' : 'created';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function reportCommand(traceId, { pr = null, sandbox = null, link = false, dryRun = false } = {},
|
|
157
|
+
{ loadLocal = localTrace, api = call, post = postComment, say = console.log } = {}) {
|
|
158
|
+
const id = String(traceId ?? '').trim();
|
|
159
|
+
if (!id) throw new Error('Trace ID is required. Usage: raytrace report <trace-id> [--pr <number>] [--sandbox <rtp-id>] [--link] [--dry-run]');
|
|
160
|
+
if (sandbox != null && !SANDBOX.test(sandbox)) throw new Error(`Not a cloud sandbox id: ${sandbox}. It looks like rtp- and 32 letters and digits.`);
|
|
161
|
+
if (pr != null && !/^[1-9]\d{0,9}$/.test(String(pr))) throw new Error(`Not a pull request number: ${pr}`);
|
|
162
|
+
const trace = (await loadLocal(id)) ?? (sandbox ? await cloudTrace(id, sandbox, api) : null);
|
|
163
|
+
if (!trace) throw new Error(sandbox ? `Trace not found in sandbox ${sandbox}: ${id}` : `Trace not found on this machine: ${id}. For a cloud sandbox, add --sandbox <rtp-id>.`);
|
|
164
|
+
// A link uses up one of the plan's share links, so only on request, and never on a dry run.
|
|
165
|
+
const shared = link && !dryRun ? await shareLink(trace, api) : { link: null, note: null };
|
|
166
|
+
const body = formatReport(trace, { link: shared.link, linkNote: shared.note });
|
|
167
|
+
if (!pr || dryRun) { say(body); return { body, posted: null }; }
|
|
168
|
+
try {
|
|
169
|
+
const posted = post(pr, body);
|
|
170
|
+
say(`Report ${posted} on pull request #${pr}.`);
|
|
171
|
+
return { body, posted };
|
|
172
|
+
} catch (error) {
|
|
173
|
+
if (error.code !== 'ENOENT') throw error;
|
|
174
|
+
say('The GitHub CLI (gh) is not installed, so nothing was posted. Here is the comment to paste:\n');
|
|
175
|
+
say(body);
|
|
176
|
+
return { body, posted: null };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -55,12 +55,42 @@ const MAX_QUEUED_BYTES = 128 * 1024;
|
|
|
55
55
|
const listed = (value) => (Array.isArray(value) ? value.filter((file) => typeof file === 'string' && file) : []);
|
|
56
56
|
let restricted = [];
|
|
57
57
|
let watched = [];
|
|
58
|
+
// `blocked`: programs the owner forbids; a command that starts one is refused.
|
|
59
|
+
let blocked = [];
|
|
58
60
|
try {
|
|
59
61
|
const lists = JSON.parse(readFileSync(new URL('./guardrails.json', import.meta.url), 'utf8'));
|
|
60
62
|
restricted = listed(lists.restricted);
|
|
61
63
|
watched = listed(lists.watched);
|
|
64
|
+
blocked = listed(lists.blocked);
|
|
62
65
|
} catch { /* nothing is restricted or watched */ }
|
|
63
66
|
|
|
67
|
+
// Prefixes that start the program after them rather than being the program.
|
|
68
|
+
const WRAPPERS = new Set(['sudo', 'doas', 'env', 'nohup', 'time', 'nice', 'exec', 'command', 'builtin', 'stdbuf']);
|
|
69
|
+
// A wrapper's options that take the next word as their value (sudo -u root, nice -n 5).
|
|
70
|
+
const VALUED = new Set(['-u', '-g', '-n', '-C', '-p']);
|
|
71
|
+
|
|
72
|
+
/** The programs a command line starts, by name: the first word of each part
|
|
73
|
+
* between ; & | ( ) ` and new lines, past VAR=value and wrappers, with any
|
|
74
|
+
* path taken off (/usr/bin/curl is curl). Text only: `sh -c 'curl ...'` names
|
|
75
|
+
* sh, which is why the kernel's view (facts.py) is the check that holds. */
|
|
76
|
+
function firstPrograms(command) {
|
|
77
|
+
const programs = [];
|
|
78
|
+
for (const part of String(command).split(/[;&|()`\n]+/)) {
|
|
79
|
+
let value = false;
|
|
80
|
+
for (const raw of part.trim().split(/\s+/)) {
|
|
81
|
+
const word = raw.replace(/^\\/, '').replace(/^['"]+|['"]+$/g, '');
|
|
82
|
+
if (value) { value = false; continue; }
|
|
83
|
+
if (!word || /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) continue;
|
|
84
|
+
const name = word.split('/').pop();
|
|
85
|
+
if (word.startsWith('-')) { value = VALUED.has(word); continue; }
|
|
86
|
+
if (WRAPPERS.has(name)) continue;
|
|
87
|
+
if (name) programs.push(name);
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return programs;
|
|
92
|
+
}
|
|
93
|
+
|
|
64
94
|
/** A file the tool named, relative to the project; null when it is outside it. */
|
|
65
95
|
const inside = (named) => {
|
|
66
96
|
if (typeof named !== 'string' || !named) return null;
|
|
@@ -97,6 +127,16 @@ if (input.hook_event_name === 'PreToolUse') {
|
|
|
97
127
|
// says what it mentions, not what it does. The file lock is what stops it.
|
|
98
128
|
if (input.tool_name === 'Bash' && typeof command === 'string') {
|
|
99
129
|
for (const path of restricted.slice(0, 200)) if (command.includes(path)) queue({ kind: 'named', path });
|
|
130
|
+
// A program the owner blocked is refused before anything else answers for the command.
|
|
131
|
+
const refused = blocked.length ? firstPrograms(command).find((program) => blocked.includes(program)) : undefined;
|
|
132
|
+
if (refused) {
|
|
133
|
+
queue({ kind: 'command_blocked', path: refused });
|
|
134
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
|
|
135
|
+
permissionDecisionReason: `RayTrace: ${refused} is blocked by this project's owner and cannot be run. `
|
|
136
|
+
+ 'Do not try another way to run it (a full path, sh -c, another tool): the sandbox records every program that runs. '
|
|
137
|
+
+ 'Tell the user it has to be unblocked under Initial scan in the RayTrace dashboard.' } }));
|
|
138
|
+
process.exit(0);
|
|
139
|
+
}
|
|
100
140
|
}
|
|
101
141
|
if (input.tool_name === 'Bash' && /^[A-Za-z0-9_-]{1,128}$/.test(id ?? '') && typeof command === 'string') {
|
|
102
142
|
// An input change needs a decision with it. Only a session that already
|
|
@@ -186,7 +186,7 @@ def lock(root, path, on):
|
|
|
186
186
|
finally:
|
|
187
187
|
os.close(at)
|
|
188
188
|
|
|
189
|
-
def guardrails(sid, state, restricted=None, watched=None):
|
|
189
|
+
def guardrails(sid, state, restricted=None, watched=None, blocked=None):
|
|
190
190
|
"""Applies a sandbox's restricted files: the new list, or the stored one
|
|
191
191
|
again. The Claude Code hook gets the list at once and refuses the edit
|
|
192
192
|
with the reason. The lock that holds for every tool is put on only while
|
|
@@ -194,8 +194,9 @@ def guardrails(sid, state, restricted=None, watched=None):
|
|
|
194
194
|
of a file while it runs, and a file locked under it stops being readable.
|
|
195
195
|
A file no longer restricted is unlocked now. `watched` are the files whose
|
|
196
196
|
owner wants to hear of a read or a change: the hook reports an attempt on
|
|
197
|
-
them and nothing is locked.
|
|
198
|
-
|
|
197
|
+
them and nothing is locked. `blocked` are the programs the hook refuses
|
|
198
|
+
to start (None keeps the stored list). Returns {hook: the hook has the
|
|
199
|
+
list, read_only: the files locked}."""
|
|
199
200
|
GUARDRAILS.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
200
201
|
stored = GUARDRAILS / (sid+'.json')
|
|
201
202
|
kept = json.loads(stored.read_text()) if stored.exists() else {}
|
|
@@ -204,14 +205,16 @@ def guardrails(sid, state, restricted=None, watched=None):
|
|
|
204
205
|
restricted = before
|
|
205
206
|
if watched is None:
|
|
206
207
|
watched = kept.get('watched', [])
|
|
208
|
+
if blocked is None:
|
|
209
|
+
blocked = kept.get('blocked', [])
|
|
207
210
|
root = subprocess.check_output(['docker', 'volume', 'inspect', '-f', '{{.Mountpoint}}', sid+'-workspace'], text=True).strip()
|
|
208
211
|
running = state['State']['Running']
|
|
209
212
|
for path in set(before) - set(restricted):
|
|
210
213
|
lock(root, path, False)
|
|
211
214
|
read_only = [path for path in restricted if lock(root, path, None if running else True)]
|
|
212
|
-
lists = json.dumps({'restricted': restricted, 'watched': watched})
|
|
215
|
+
lists = json.dumps({'restricted': restricted, 'watched': watched, 'blocked': blocked})
|
|
213
216
|
stored.write_text(lists)
|
|
214
|
-
if running and (restricted or before or watched or kept.get('watched')):
|
|
217
|
+
if running and (restricted or before or watched or kept.get('watched') or blocked or kept.get('blocked')):
|
|
215
218
|
write_as_root(sid, GUARDRAILS_IN_SANDBOX, lists.encode())
|
|
216
219
|
return {'hook': bool(running), 'read_only': read_only}
|
|
217
220
|
|
|
@@ -612,7 +615,12 @@ def main():
|
|
|
612
615
|
if not isinstance(sent.get(key), list) or len(sent[key]) > cap:
|
|
613
616
|
raise ValueError('Invalid '+key+' list')
|
|
614
617
|
lists[key] = [safe_path(path)[len('/workspace/'):] for path in sent[key]]
|
|
615
|
-
|
|
618
|
+
# blocked?: program names. Absent (an older caller, or a change to files only): keep the host's.
|
|
619
|
+
blocked = sent.get('blocked')
|
|
620
|
+
if blocked is not None and not (isinstance(blocked, list) and len(blocked) <= 200 and all(
|
|
621
|
+
isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9._+-]{1,64}', name) and name not in ('.', '..') for name in blocked)):
|
|
622
|
+
raise ValueError('Invalid blocked list')
|
|
623
|
+
return print(json.dumps(guardrails(opts.id, state, lists['restricted'], lists['watched'], blocked)))
|
|
616
624
|
if opts.action == 'guardrails':
|
|
617
625
|
return print(json.dumps(guardrails(opts.id, inspect(opts.id))))
|
|
618
626
|
if opts.action == 'set-token':
|