@raytrace-cli/cli 0.4.0 → 0.6.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.
Files changed (137) hide show
  1. package/README.md +155 -123
  2. package/bin/raytrace.mjs +110 -22
  3. package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  4. package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  5. package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  6. package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  7. package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  8. package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  9. package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  10. package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  11. package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  12. package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  13. package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  14. package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  15. package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  16. package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  17. package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  18. package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  19. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  20. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  21. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  22. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  23. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  24. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  25. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  26. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  27. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  28. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  29. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  30. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  31. package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  32. package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  33. package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  34. package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  35. package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  36. package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  37. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  38. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  39. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  40. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  41. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  42. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  43. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  44. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  45. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  46. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  47. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  48. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  49. package/dist/dashboard/assets/index-Dc3LTk8b.js +38 -0
  50. package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
  51. package/dist/dashboard/index.html +2 -2
  52. package/package.json +4 -1
  53. package/proxy/agent-intent-schema.test.mjs +142 -0
  54. package/proxy/call-assessment.mjs +385 -0
  55. package/proxy/call-assessment.test.mjs +167 -0
  56. package/proxy/call-category.mjs +461 -0
  57. package/proxy/capture.mjs +38 -0
  58. package/proxy/capture.test.mjs +49 -0
  59. package/proxy/claude-code-adapter.mjs +65 -3
  60. package/proxy/claude-code-hook.mjs +3 -1
  61. package/proxy/codex-config.mjs +5 -0
  62. package/proxy/codex.mjs +3 -2
  63. package/proxy/evidence-schema.test.mjs +233 -0
  64. package/proxy/evidence-store.mjs +704 -33
  65. package/proxy/evidence-store.test.mjs +304 -0
  66. package/proxy/exec-narrative.mjs +625 -0
  67. package/proxy/exec-narrative.test.mjs +262 -0
  68. package/proxy/execution-correlation.mjs +185 -0
  69. package/proxy/execution-correlation.test.mjs +146 -0
  70. package/proxy/execution-runner.test.mjs +38 -0
  71. package/proxy/experiment-engine.mjs +7 -4
  72. package/proxy/experiment-engine.test.mjs +93 -0
  73. package/proxy/explanations.test.mjs +20 -0
  74. package/proxy/failure-signature.mjs +56 -0
  75. package/proxy/gvisor-forwarder.mjs +454 -0
  76. package/proxy/gvisor-forwarder.test.mjs +368 -0
  77. package/proxy/init-evidence-db.mjs +166 -12
  78. package/proxy/local-sandboxes.mjs +94 -0
  79. package/proxy/local-token.mjs +30 -0
  80. package/proxy/playground-recovery.test.mjs +130 -0
  81. package/proxy/playground.mjs +439 -0
  82. package/proxy/prompt-context.mjs +12 -7
  83. package/proxy/prompt-traces.mjs +6 -0
  84. package/proxy/prompt-traces.test.mjs +32 -0
  85. package/proxy/providers.test.mjs +76 -0
  86. package/proxy/proxy.integration.test.mjs +135 -0
  87. package/proxy/raytace-proxy.mjs +512 -188
  88. package/proxy/request-metrics.test.mjs +19 -0
  89. package/proxy/request-policy.mjs +45 -0
  90. package/proxy/request-policy.test.mjs +47 -0
  91. package/proxy/run-recap.mjs +139 -0
  92. package/proxy/runtime-attribution.mjs +110 -0
  93. package/proxy/sandbox-bridge.mjs +49 -0
  94. package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
  95. package/proxy/schema/auxiliary.sql +48 -1
  96. package/proxy/schema/classification.sql +89 -0
  97. package/proxy/schema/file_context.sql +53 -0
  98. package/proxy/schema/runtime_evidence.sql +201 -0
  99. package/proxy/schema/search.sql +66 -0
  100. package/proxy/search.mjs +418 -0
  101. package/proxy/search.test.mjs +161 -0
  102. package/proxy/smoke.test.mjs +93 -0
  103. package/proxy/step-attribution.mjs +380 -0
  104. package/proxy/step-lab.test.mjs +38 -0
  105. package/proxy/summaries.test.mjs +69 -0
  106. package/proxy/tool-metadata.mjs +36 -0
  107. package/proxy/tool-metadata.test.mjs +38 -0
  108. package/proxy/trace-view.mjs +308 -0
  109. package/proxy/trace-view.test.mjs +72 -0
  110. package/proxy/typesafe.mjs +63 -0
  111. package/proxy/typesafe.test.mjs +39 -0
  112. package/src/claude-code.mjs +38 -1
  113. package/src/commands.mjs +133 -20
  114. package/src/config.mjs +16 -7
  115. package/src/export.mjs +200 -0
  116. package/src/lima.mjs +176 -0
  117. package/src/local-sandbox.mjs +339 -0
  118. package/src/paths.mjs +8 -8
  119. package/src/proxy-process.mjs +45 -3
  120. package/src/sandbox.mjs +37 -9
  121. package/src/upload.mjs +198 -0
  122. package/worker/sandbox/Dockerfile +8 -0
  123. package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  124. package/worker/sandbox/claude-hook.mjs +364 -0
  125. package/worker/sandbox/collector.py +357 -0
  126. package/worker/sandbox/dns_forwarder.py +255 -0
  127. package/worker/sandbox/engine.py +940 -0
  128. package/worker/sandbox/file_scan.py +491 -0
  129. package/worker/sandbox/lima.yaml +29 -0
  130. package/worker/sandbox/network.py +90 -0
  131. package/worker/sandbox/projects.py +679 -0
  132. package/worker/sandbox/setup.py +159 -0
  133. package/worker/sandbox/syscall_catalog.sql +985 -0
  134. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  135. package/worker/sandbox/viewer.py +151 -0
  136. package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
  137. package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
@@ -0,0 +1,339 @@
1
+ // `raytrace sandbox … --local`: sandboxes on this machine, in a Lima Linux VM.
2
+ //
3
+ // Your project never leaves the machine. The VM runs each sandbox as a Docker
4
+ // container under gVisor; the collector beside it (worker/sandbox) records the
5
+ // commands, files and connections it makes, independently of the agent, and the
6
+ // dashboard shows them, read from the evidence viewer. The sandbox's Claude Code
7
+ // hook sends its transcript to this CLI's proxy through the sandbox bridge
8
+ // (proxy/sandbox-bridge.mjs), so its sessions show in the local dashboard.
9
+ //
10
+ // Lima picks the VM type for the host: macOS and Linux work; Windows is
11
+ // experimental. Sign in to Claude Code or Codex inside the sandbox: no key is
12
+ // passed in from here.
13
+ import { spawnSync } from 'node:child_process';
14
+ import { createHash, randomBytes } from 'node:crypto';
15
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
16
+ import { basename, join } from 'node:path';
17
+ import { paths } from './paths.mjs';
18
+ import { portInUse, runningPid, start as startProxy, stop as stopProxy } from './proxy-process.mjs';
19
+ import { readConfig } from './config.mjs';
20
+ import { ensureToken } from '../proxy/local-token.mjs';
21
+ import { viewerTokenFor } from '../proxy/request-policy.mjs';
22
+ import { LIMA_VERSION, canDownload, checks, downloadLima, findLima } from './lima.mjs';
23
+
24
+ const say = (line = '') => console.log(line);
25
+ const VM = 'raytrace';
26
+ const ID = /^rtp-[a-f0-9]{32}$/;
27
+ // How a local sandbox is named on the command line: unique among them.
28
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
29
+ const SOURCE = join(paths.root, 'worker', 'sandbox');
30
+ const HOOK = join(SOURCE, 'claude-hook.mjs');
31
+ const REGISTRY = join(paths.home, 'sandboxes.json');
32
+ // Where the proxy keeps each sandbox's copy of its Claude Code transcripts,
33
+ // and where the first local sandboxes' bridge kept them.
34
+ const transcripts = (id) => join(paths.home, 'claude-code', id);
35
+ const earlierTranscripts = (id) => join(paths.home, 'sandboxes', id, 'claude');
36
+ // Logs kept when a sandbox is destroyed without them.
37
+ const ARCHIVE = join(paths.home, 'archive');
38
+ // What the VM's setup was last run from; a CLI upgrade that changes it runs setup again.
39
+ const SETUP_MARK = '/etc/raytace/cli-setup';
40
+ // Lima's and the VM setup's own output, which is long: shown only when a step fails.
41
+ const VM_LOG = join(paths.logs, 'sandbox-vm.log');
42
+
43
+ /** Local sandboxes this CLI made: id → {name, root, token, created}. */
44
+ export function registry() {
45
+ try { return JSON.parse(readFileSync(REGISTRY, 'utf8')); } catch { return {}; }
46
+ }
47
+ function save(boxes) {
48
+ mkdirSync(paths.home, { recursive: true });
49
+ writeFileSync(REGISTRY, `${JSON.stringify(boxes, null, 2)}\n`, { mode: 0o600 });
50
+ }
51
+ const byName = (boxes, name) => Object.keys(boxes).find((id) => boxes[id].name === name);
52
+ /** Whether a sandbox id or name is one of this machine's local sandboxes. */
53
+ export const isLocal = (ref) => Boolean(ref && (registry()[ref] || byName(registry(), ref)));
54
+
55
+ let lima = null;
56
+ /** The limactl to run: the user's own Lima, or the one RayTrace downloaded. */
57
+ function limactlBinary() {
58
+ lima ??= findLima()?.binary;
59
+ if (!lima) throw new Error('Lima is not set up. `raytrace sandbox create --local` sets it up; `raytrace doctor` says what is missing.');
60
+ return lima;
61
+ }
62
+
63
+ const tail = (file, lines = 25) => { try { return readFileSync(file, 'utf8').trimEnd().split('\n').slice(-lines).join('\n'); } catch { return ''; } };
64
+
65
+ /**
66
+ * Runs limactl. `inherit` gives it the terminal (a shell); `log` sends its
67
+ * output to the VM log instead, and on failure shows the log's last lines.
68
+ */
69
+ function limactl(args, { input, inherit = false, log = false, check = true } = {}) {
70
+ let fd = null;
71
+ if (log) {
72
+ mkdirSync(paths.logs, { recursive: true });
73
+ fd = openSync(VM_LOG, 'a');
74
+ writeFileSync(fd, `\n=== ${new Date().toISOString()} limactl ${args.join(' ')} ===\n`);
75
+ }
76
+ let result;
77
+ try {
78
+ result = spawnSync(limactlBinary(), args, {
79
+ input, stdio: inherit ? 'inherit' : [input === undefined ? 'ignore' : 'pipe', fd ?? 'pipe', fd ?? 'pipe'],
80
+ encoding: inherit || log ? undefined : 'utf8', maxBuffer: 64 * 1024 * 1024,
81
+ });
82
+ } finally { if (fd !== null) closeSync(fd); }
83
+ if (result.error) throw result.error;
84
+ if (check && result.status !== 0) {
85
+ const detail = log ? `${tail(VM_LOG)}\n(full log: ${VM_LOG})` : String(result.stderr ?? '').trim().split('\n').slice(-6).join('\n');
86
+ throw new Error(`limactl ${args[0]} failed${detail ? `:\n${detail}` : ''}`);
87
+ }
88
+ return result;
89
+ }
90
+
91
+ /** A command in the VM as root: projects.py and setup.py run there. */
92
+ export const inVm = (args, options) => limactl(['shell', '--workdir', '/', VM, 'sudo', ...args], options);
93
+ const projects = (args, options) => inVm(['python3', '/opt/raytace/projects.py', ...args], options);
94
+
95
+ /** Removes the RayTrace VM and every local sandbox in it; false when there was none. */
96
+ export function deleteVm() {
97
+ if (!findLima()?.binary || !vmStatus()) return false;
98
+ limactl(['delete', '--force', VM], { log: true });
99
+ return true;
100
+ }
101
+
102
+ export function vmStatus() {
103
+ const listed = limactl(['list', '--format', '{{.Name}} {{.Status}}']).stdout;
104
+ const line = listed.split('\n').find((row) => row.split(' ')[0] === VM);
105
+ return line ? line.split(' ')[1] : null;
106
+ }
107
+
108
+ function setupVersion() {
109
+ const hash = createHash('sha256');
110
+ for (const name of readdirSync(SOURCE).sort()) hash.update(name).update(readFileSync(join(SOURCE, name)));
111
+ return hash.digest('hex').slice(0, 16);
112
+ }
113
+
114
+ /** The VM up, with gVisor, the collector and the sandbox image as this CLI ships them. */
115
+ function ensureVm() {
116
+ const status = vmStatus();
117
+ if (!status) {
118
+ say(`Creating the RayTrace VM "${VM}" (first time only: it downloads Ubuntu, a few minutes)...`);
119
+ limactl(['start', '--name', VM, '--tty=false', join(SOURCE, 'lima.yaml')], { log: true });
120
+ } else if (status !== 'Running') {
121
+ say(`Starting the RayTrace VM "${VM}"...`);
122
+ limactl(['start', '--tty=false', VM], { log: true });
123
+ }
124
+ const version = setupVersion();
125
+ const installed = inVm(['cat', SETUP_MARK], { check: false }).stdout?.trim();
126
+ if (installed !== version) installInVm(version);
127
+ // Through stdin: arguments are visible to every account in `ps`. Written each
128
+ // time, so a new token or a rebuilt VM never leaves the viewer locked.
129
+ inVm(['sh', '-c', 'umask 077; cat > /etc/raytace/viewer-token'], { input: `${viewerTokenFor(ensureToken(paths.home))}\n` });
130
+ }
131
+
132
+ function installInVm(version) {
133
+ say(`Installing gVisor, the evidence collector and the sandbox image in the VM (a few minutes; progress in ${VM_LOG})...`);
134
+ inVm(['rm', '-rf', '/tmp/raytrace-sandbox-source']);
135
+ limactl(['shell', '--workdir', '/', VM, 'mkdir', '-p', '/tmp/raytrace-sandbox-source']);
136
+ limactl(['copy', '-r', `${SOURCE}/.`, `${VM}:/tmp/raytrace-sandbox-source/`]);
137
+ inVm(['python3', '/tmp/raytrace-sandbox-source/setup.py'], { log: true });
138
+ inVm(['sh', '-c', `echo ${version} > ${SETUP_MARK}`]);
139
+ }
140
+
141
+ /** Transcripts reach the dashboard through the proxy's sandbox bridge. */
142
+ async function ensureBridge() {
143
+ try { await startProxy(); } catch (error) {
144
+ say(`Note: the RayTrace proxy did not start (${error.message.split('\n')[0]}). `
145
+ + 'Commands are still recorded in the VM; Claude Code transcripts reach the dashboard once `raytrace start` works.');
146
+ return;
147
+ }
148
+ // A proxy from before local sandboxes is reused as it is, and has no bridge.
149
+ if (!(await portInUse(Number(readConfig().RAYTRACE_BRIDGE_PORT || 8799)))) {
150
+ say('Note: the running RayTrace proxy has no sandbox bridge (it predates local sandboxes). '
151
+ + 'Restart it so Claude Code sessions reach the dashboard: raytrace stop && raytrace start');
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Before anything is packed or started: what this machine lacks for a local
157
+ * sandbox, each with its fix, and Lima downloaded if the user agrees.
158
+ */
159
+ export async function preflight(flags, { confirm, interactive }) {
160
+ let vmRunning = false;
161
+ try { vmRunning = Boolean(findLima()?.binary) && vmStatus() === 'Running'; } catch { /* reported below */ }
162
+ const rows = await checks({ vmRunning });
163
+ for (const { ok, label, detail } of rows) if (ok === null && label !== 'lima') say(`Note (${label}): ${detail}`);
164
+ const failed = rows.filter((row) => row.ok === false);
165
+ if (failed.length) {
166
+ throw new Error(`This machine is not ready for local sandboxes:\n${failed.map((row) => ` ${row.label}: ${row.detail}${row.fix ? `\n fix: ${row.fix}` : ''}`).join('\n')}`);
167
+ }
168
+ if (findLima()?.binary) return;
169
+ if (!canDownload()) throw new Error('Local sandboxes need Lima: https://lima-vm.io/docs/installation/');
170
+ const question = `Local sandboxes run in a Linux VM made with Lima (open source, Apache-2.0), which is not installed. `
171
+ + `Download Lima ${LIMA_VERSION} (about 25-40 MB) into ${join(paths.home, 'lima')}? No admin rights needed.`;
172
+ if (!flags.yes) {
173
+ if (!interactive()) throw new Error(`${question}\nRun again with --yes to download it, or install Lima yourself: https://lima-vm.io/docs/installation/`);
174
+ if (!(await confirm(question, true))) throw new Error('Not downloaded. Install Lima yourself to use local sandboxes: https://lima-vm.io/docs/installation/');
175
+ }
176
+ lima = (await downloadLima(say)).binary;
177
+ }
178
+
179
+ /** A local sandbox's id, from its id or name; with neither, the only one there is. */
180
+ function pickId(ref) {
181
+ const boxes = registry();
182
+ if (ref) {
183
+ const id = boxes[ref] ? ref : byName(boxes, ref);
184
+ if (!id) throw new Error(`No local sandbox named ${ref}: raytrace sandbox list --local`);
185
+ return id;
186
+ }
187
+ const ids = Object.keys(boxes);
188
+ if (ids.length === 1) return ids[0];
189
+ throw new Error(ids.length ? 'More than one local sandbox; name one (raytrace sandbox list --local).'
190
+ : 'No local sandboxes yet: raytrace sandbox create --local');
191
+ }
192
+
193
+ /** The new sandbox's name: --name, or the repository folder's; unique among local sandboxes. */
194
+ export function sandboxName(flags, root) {
195
+ const name = flags.name ?? basename(root).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 64);
196
+ if (!NAME.test(name)) throw new Error(`"${name}" cannot be a sandbox name: use letters, digits, dot, dash and underscore (up to 64), starting with a letter or digit.`);
197
+ if (byName(registry(), name)) throw new Error(`There is already a local sandbox named ${name}. Pick another with --name, or destroy that one: raytrace sandbox destroy ${name}`);
198
+ return name;
199
+ }
200
+
201
+ export async function create(name, { root, files, skipped, total, archive }) {
202
+ ensureVm();
203
+ const id = `rtp-${randomBytes(16).toString('hex')}`;
204
+ const token = randomBytes(32).toString('base64url');
205
+ say(`Copying ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root} into a new sandbox`);
206
+ if (skipped.length) say(`Left out (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
207
+ projects(['create', id, '--archive', '-'], { input: archive });
208
+ // Recorded before anything else can fail, so destroy can always find it.
209
+ save({ ...registry(), [id]: { name, root, token, created: new Date().toISOString() } });
210
+ projects(['start', id]);
211
+ projects(['enable-claude', id], { input: readFileSync(HOOK) });
212
+ projects(['set-token', id], { input: token });
213
+ await ensureBridge();
214
+ say(`\nLocal sandbox ${name} (${id}) is running.`);
215
+ say('Claude Code sessions in it go to your local dashboard; commands, files and connections are recorded in the VM.');
216
+ say(`Open it: raytrace connect ${name}`);
217
+ }
218
+
219
+ export async function list() {
220
+ const boxes = registry();
221
+ if (!Object.keys(boxes).length) { say('No local sandboxes. Create one from a Git repository: raytrace sandbox create --local'); return; }
222
+ const running = vmStatus() === 'Running';
223
+ const states = running ? Object.fromEntries(JSON.parse(projects(['list']).stdout || '[]').map((box) => [box.id, box.status])) : {};
224
+ for (const [id, box] of Object.entries(boxes)) {
225
+ const age = Math.round((Date.now() - Date.parse(box.created)) / 60000);
226
+ const status = running ? (states[id] === 'running' ? 'running' : states[id] ? 'stopped' : 'missing') : 'stopped';
227
+ say(`${box.name.padEnd(20)} ${status.padEnd(8)} ${id} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old, local)`);
228
+ }
229
+ if (!running) say(`\nThe RayTrace VM is stopped; \`raytrace sandbox start <name>\` starts it.`);
230
+ }
231
+
232
+ export async function start(id) {
233
+ id = pickId(id);
234
+ ensureVm();
235
+ projects(['start', id]);
236
+ await ensureBridge();
237
+ say(`${registry()[id].name} running`);
238
+ }
239
+
240
+ export async function stop(id) {
241
+ id = pickId(id);
242
+ if (vmStatus() === 'Running') projects(['stop', id]);
243
+ say(`${registry()[id].name} stopped; its files are kept`);
244
+ }
245
+
246
+ const stamp = () => new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
247
+
248
+ /** The sandbox's Claude Code session ids, from the bridge's transcript copies. */
249
+ function sessionIds(id) {
250
+ const listed = (folder) => { try { return readdirSync(folder).filter((file) => file.endsWith('.jsonl')).map((file) => file.slice(0, -6)); } catch { return []; } };
251
+ return [...listed(transcripts(id)), ...listed(earlierTranscripts(id))];
252
+ }
253
+
254
+ /**
255
+ * Deletes a local sandbox, and asks about the logs captured in it: deleted
256
+ * with it, or moved to ~/.raytrace/archive/<name>-<time>/ (the Claude Code
257
+ * transcripts and the VM's command, file and network evidence), staying in
258
+ * the dashboard. --delete-logs / --keep-logs answer without asking; without a
259
+ * terminal and neither flag, the logs are kept.
260
+ */
261
+ export async function destroy(ref, flags, { ask, interactive }) {
262
+ const id = pickId(ref);
263
+ const box = registry()[id];
264
+ if (!flags.yes) {
265
+ if (!interactive()) throw new Error('Pass --yes to destroy without a prompt.');
266
+ say(`This deletes local sandbox ${box.name}: its files, and any sign-in made inside it.`);
267
+ if ((await ask('Type the sandbox name to confirm: ')) !== box.name) { say('Not destroyed.'); return; }
268
+ }
269
+ // A destroyed sandbox can no longer be uploaded, so this is the last chance:
270
+ // asked once, default no, and a failed upload leaves the sandbox in place.
271
+ if (!flags.yes && interactive()
272
+ && /^y(es)?$/i.test((await ask('Upload its evidences to RayTrace cloud first? (yes/no) [no]: ')).trim())) {
273
+ const { uploadLogs } = await import('./upload.mjs');
274
+ await uploadLogs({ sandbox: id, yes: true });
275
+ }
276
+ let deleteLogs = flags['delete-logs'] ? true : flags['keep-logs'] ? false : null;
277
+ if (deleteLogs === null) {
278
+ deleteLogs = interactive()
279
+ && /^y(es)?$/i.test((await ask('Also delete the logs captured in this sandbox? (yes/no) [no]: ')).trim());
280
+ }
281
+
282
+ ensureVm();
283
+ const inVmNow = JSON.parse(projects(['list']).stdout || '[]');
284
+ const exists = inVmNow.some((item) => item.id === id);
285
+ // Its Playground forks, which are sandboxes of their own in the VM.
286
+ const forks = inVmNow.filter((item) => item.fork_of === id).map((item) => item.id);
287
+ // Stopped first: stopping is recorded too, and must not land after the logs are dealt with.
288
+ if (exists) projects(['stop', id]);
289
+ if (deleteLogs) {
290
+ // Its sessions are filed under its id; ones recorded before that, under their own.
291
+ const { openEvidenceStore } = await import('../proxy/evidence-store.mjs');
292
+ const store = openEvidenceStore(paths.database);
293
+ try { store.forgetSessions([id, ...sessionIds(id)]); } finally { store.close(); }
294
+ rmSync(transcripts(id), { recursive: true, force: true });
295
+ rmSync(join(paths.home, 'sandboxes', id), { recursive: true, force: true });
296
+ } else {
297
+ const folder = join(ARCHIVE, `${box.name}-${stamp()}`);
298
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
299
+ const { token, ...about } = box;
300
+ writeFileSync(join(folder, 'sandbox.json'), `${JSON.stringify({ id, ...about, destroyed: new Date().toISOString() }, null, 2)}\n`);
301
+ if (exists) writeFileSync(join(folder, 'runtime-evidence.jsonl'), projects(['evidence', id]).stdout);
302
+ for (const from of [transcripts(id), earlierTranscripts(id)]) {
303
+ if (existsSync(from)) { renameSync(from, join(folder, 'claude-code')); break; }
304
+ }
305
+ // Forks' transcripts are filed under their own ids; their recorded
306
+ // commands are already in the dashboard, with the forks themselves.
307
+ for (const fork of forks) {
308
+ if (!existsSync(transcripts(fork))) continue;
309
+ mkdirSync(join(folder, 'forks'), { recursive: true, mode: 0o700 });
310
+ renameSync(transcripts(fork), join(folder, 'forks', fork));
311
+ }
312
+ rmSync(join(paths.home, 'sandboxes', id), { recursive: true, force: true });
313
+ say(`Logs moved to ${folder}`);
314
+ say('Its Claude Code sessions stay in your dashboard.');
315
+ }
316
+ // The VM's record of it goes either way: deleted, or by now in the archive.
317
+ for (const fork of forks) projects(['fork-delete', fork, '--forget-evidence']);
318
+ if (deleteLogs) for (const fork of forks) rmSync(transcripts(fork), { recursive: true, force: true });
319
+ if (exists) projects(['delete', id, '--confirm', id, '--forget-evidence']);
320
+ const boxes = registry();
321
+ delete boxes[id];
322
+ save(boxes);
323
+ say(`${box.name} destroyed${forks.length ? `, with its ${forks.length} Playground fork${forks.length === 1 ? '' : 's'}` : ''}${deleteLogs ? ', and its logs' : ''}.`);
324
+ // The proxy keeps the Playground's forks in memory: one this CLI started is
325
+ // restarted, so the forks just deleted are not listed any more.
326
+ if (deleteLogs && forks.length && runningPid()) { await stopProxy(); await startProxy(); }
327
+ }
328
+
329
+ /** A terminal in the sandbox, through the VM. Leaving it keeps the sandbox running. */
330
+ export async function shell(id) {
331
+ id = pickId(id);
332
+ ensureVm();
333
+ await ensureBridge();
334
+ const { name } = registry()[id];
335
+ say(`Connected to ${name}. Run \`claude\` (or codex) here; exit to leave. The sandbox keeps running.`);
336
+ say('Recorded commands, files and connections: raytrace open, then Sandbox evidence\n');
337
+ projects(['shell', id], { inherit: true, check: false });
338
+ say(`\nLeft ${name}. It is still running. Back in: raytrace connect ${name} Stop it: raytrace sandbox stop ${name}`);
339
+ }
package/src/paths.mjs CHANGED
@@ -6,7 +6,7 @@ import { join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
 
8
8
  const root = fileURLToPath(new URL('..', import.meta.url));
9
- const home = process.env.RAYTRACE_HOME || join(homedir(), '.raytrace');
9
+ const home = () => process.env.RAYTRACE_HOME || join(homedir(), '.raytrace');
10
10
 
11
11
  export const paths = {
12
12
  root,
@@ -14,13 +14,13 @@ export const paths = {
14
14
  codex: join(root, 'proxy', 'codex.mjs'),
15
15
  hook: join(root, 'proxy', 'claude-code-hook.mjs'),
16
16
  dashboard: join(root, 'dist', 'dashboard'),
17
- home,
18
- config: join(home, 'config.env'),
19
- logs: join(home, 'logs'),
20
- proxyLog: join(home, 'logs', 'proxy.log'),
21
- run: join(home, 'run'),
22
- proxyPid: join(home, 'run', 'proxy.pid'),
23
- database: join(home, 'evidence.db'),
17
+ get home() { return home(); },
18
+ get config() { return join(home(), 'config.env'); },
19
+ get logs() { return join(home(), 'logs'); },
20
+ get proxyLog() { return join(home(), 'logs', 'proxy.log'); },
21
+ get run() { return join(home(), 'run'); },
22
+ get proxyPid() { return join(home(), 'run', 'proxy.pid'); },
23
+ get database() { return join(home(), 'evidence.db'); },
24
24
  };
25
25
 
26
26
  export const DEFAULT_PORT = 8797;
@@ -9,14 +9,39 @@ import { createConnection } from 'node:net';
9
9
  import { setTimeout as sleep } from 'node:timers/promises';
10
10
  import { paths } from './paths.mjs';
11
11
  import { portOf, proxyEnv, readConfig } from './config.mjs';
12
+ import { readToken } from '../proxy/local-token.mjs';
13
+
14
+ // The proxy API this CLI's dashboard needs (proxy/raytace-proxy.mjs PROXY_API).
15
+ // A proxy from an older install answers without it, or with less.
16
+ export const PROXY_API = 4;
17
+
18
+ /** The running proxy's API version: 0 for one from before it said. */
19
+ export async function proxyApi(port) {
20
+ try {
21
+ const response = await fetch(`http://127.0.0.1:${port}/raytace/version`, { signal: AbortSignal.timeout(2000) });
22
+ return response.ok ? Number((await response.json()).api) || 0 : 0;
23
+ } catch { return 0; }
24
+ }
25
+
26
+ const signedIn = () => ({ authorization: `Bearer ${readToken(paths.home)}` });
12
27
 
13
28
  export async function healthy(port) {
14
29
  try {
15
- const response = await fetch(`http://127.0.0.1:${port}/raytace/models`, { signal: AbortSignal.timeout(2000) });
30
+ const response = await fetch(`http://127.0.0.1:${port}/raytace/models`, { headers: signedIn(), signal: AbortSignal.timeout(2000) });
16
31
  return response.ok;
17
32
  } catch { return false; }
18
33
  }
19
34
 
35
+ /** The dashboard's address, carrying a one-time ticket that signs this browser
36
+ * in. A proxy from before tickets just gets its plain address. */
37
+ export async function dashboardLink(port) {
38
+ const url = `http://127.0.0.1:${port}`;
39
+ try {
40
+ const response = await fetch(`${url}/raytace/session`, { method: 'POST', headers: signedIn(), signal: AbortSignal.timeout(2000) });
41
+ return response.ok ? `${url}/raytace/session?ticket=${(await response.json()).ticket}` : url;
42
+ } catch { return url; }
43
+ }
44
+
20
45
  /** True when anything at all is listening on the port. */
21
46
  export function portInUse(port) {
22
47
  return new Promise((done) => {
@@ -30,6 +55,16 @@ function alive(pid) {
30
55
  try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
31
56
  }
32
57
 
58
+ /** Read-only check for running proxy pid; does not remove stale PID file. */
59
+ export function checkRunningPid() {
60
+ if (!existsSync(paths.proxyPid)) return null;
61
+ try {
62
+ const pid = Number(readFileSync(paths.proxyPid, 'utf8').trim());
63
+ if (Number.isInteger(pid) && pid > 0 && alive(pid)) return pid;
64
+ } catch { /* unreadable */ }
65
+ return null;
66
+ }
67
+
33
68
  /** The pid this CLI started, if that process is still running. */
34
69
  export function runningPid() {
35
70
  if (!existsSync(paths.proxyPid)) return null;
@@ -58,9 +93,16 @@ function tail(file, lines = 8) {
58
93
  export async function start() {
59
94
  const config = readConfig();
60
95
  const port = portOf(config);
61
- if (await healthy(port)) return { started: false, port, pid: runningPid() };
96
+ if (await healthy(port)) {
97
+ if (await proxyApi(port) >= PROXY_API) return { started: false, port, pid: runningPid() };
98
+ // An older proxy, still running from before an upgrade: the dashboard it
99
+ // serves now is the new one, and it would answer it "Unknown local endpoint".
100
+ if (!runningPid()) throw new Error(`An older RayTrace proxy, not started by this CLI, is running on :${port}. Stop it where it was started, then run: raytrace start`);
101
+ await stop();
102
+ return { ...(await start()), replaced: true };
103
+ }
62
104
  if (await portInUse(port)) throw new Error(`Port ${port} is in use by something that is not answering as RayTrace. Free it, or set RAYTACE_PORT in ${paths.config}.`);
63
- if (!existsSync(paths.dashboard)) throw new Error(`The dashboard is missing from ${paths.dashboard}. Reinstall @raytrace/cli.`);
105
+ if (!existsSync(paths.dashboard)) throw new Error(`The dashboard is missing from ${paths.dashboard}. Reinstall @raytrace-cli/cli.`);
64
106
 
65
107
  mkdirSync(paths.logs, { recursive: true });
66
108
  mkdirSync(paths.run, { recursive: true });
package/src/sandbox.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  // `raytrace sandbox`: cloud sandboxes, through RayTrace's API
2
- // (https://api.raytracer.si; RAYTRACE_API_URL points elsewhere).
2
+ // (https://api.raytracer.si; RAYTRACE_API_URL points elsewhere), or with
3
+ // --local on this machine (local-sandbox.mjs). A local sandbox's id is
4
+ // recognised wherever an id is given, so connect/stop/destroy need no flag.
3
5
  //
4
6
  // The project is packed here, so files that must stay on this machine never
5
7
  // leave it, then uploaded once; RayTrace creates an isolated sandbox from it
@@ -13,7 +15,8 @@ import { request as httpsRequest } from 'node:https';
13
15
  import { basename, join } from 'node:path';
14
16
  import { accessToken, account, login } from './auth.mjs';
15
17
  import { readConfig } from './config.mjs';
16
- import { ask, interactive } from './prompt.mjs';
18
+ import { ask, confirm, interactive } from './prompt.mjs';
19
+ import * as local from './local-sandbox.mjs';
17
20
 
18
21
  const say = (line = '') => console.log(line);
19
22
  // What one project upload may be. RayTrace's API holds the dashboard's folder
@@ -125,8 +128,13 @@ export async function create(flags) {
125
128
  if (top.status !== 0) throw new Error('Run this from inside a Git repository.');
126
129
  const root = top.stdout.trim();
127
130
  const name = flags.name || basename(root);
131
+ // What the machine lacks is said before the project is read, and Lima fetched if agreed.
132
+ const localName = flags.local ? local.sandboxName(flags, root) : null;
133
+ if (flags.local) await local.preflight(flags, { confirm, interactive });
128
134
  const { files, skipped, total } = projectFiles(root);
129
135
  if (!files.length) throw new Error('Nothing to upload.');
136
+ // The same files, packed the same way, as a cloud sandbox gets: only the copy stays here.
137
+ if (flags.local) return local.create(localName, { root, files, skipped, total, archive: await pack(root, files) });
130
138
  say(`Packing ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root}`);
131
139
  if (skipped.length) say(`Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
132
140
  const archive = await pack(root, files);
@@ -141,7 +149,8 @@ export async function create(flags) {
141
149
  say(`Open it: raytrace connect ${box.id}`);
142
150
  }
143
151
 
144
- export async function list() {
152
+ export async function list(flags = {}) {
153
+ if (flags.local) return local.list();
145
154
  const boxes = (await call('GET', '/v1/sandboxes')).filter((box) => box.status !== 'deleted');
146
155
  if (!boxes.length) { say('No sandboxes. Create one from a Git repository: raytrace sandbox create'); return; }
147
156
  for (const box of boxes) {
@@ -152,24 +161,43 @@ export async function list() {
152
161
  }
153
162
  }
154
163
 
155
- export async function start(id) { const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/start`); say(`${box.id} running`); }
156
- export async function stop(id) { const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/stop`); say(`${box.id} stopped; its files are kept`); }
164
+ export async function start(id, flags = {}) {
165
+ if (flags.local || local.isLocal(id)) return local.start(id);
166
+ const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/start`); say(`${box.id} running`);
167
+ }
168
+ export async function stop(id, flags = {}) {
169
+ if (flags.local || local.isLocal(id)) return local.stop(id);
170
+ const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/stop`); say(`${box.id} stopped; its files are kept`);
171
+ }
157
172
 
158
173
  export async function destroy(id, flags) {
174
+ if (flags.local || local.isLocal(id)) return local.destroy(id, flags, { ask, interactive });
159
175
  id = await pickId(id);
176
+ const me = await call('GET', '/v1/me').catch(() => ({}));
177
+ const plan = me.plan ?? {};
178
+ const paid = plan.plan && plan.plan !== 'beta';
179
+ let keep = Boolean(flags['keep-traces']);
160
180
  if (!flags.yes) {
161
- if (!interactive()) throw new Error('Pass --yes to destroy without a prompt.');
162
- say(`This deletes ${id}: its files, and any sign-in made inside it. Recorded evidence is kept.`);
181
+ if (!interactive()) throw new Error('Pass --yes to destroy without a prompt (with --yes, traces are deleted unless --keep-traces is passed).');
182
+ say(`This deletes ${id}: its files, and any sign-in made inside it.`);
183
+ if (!paid) say('Free does not keep traces after destroy: its recorded traces are deleted too.\nTo keep them, upgrade to Pro first: https://raytracer.si/pricing');
163
184
  if ((await ask('Type the sandbox id to confirm: ')) !== id) { say('Not destroyed.'); return; }
185
+ if (paid && !keep) {
186
+ keep = /^y(es)?$/i.test((await ask('Keep its traces until your retention date? They stay readable and count against your evidences storage. [y/N] ')).trim());
187
+ }
164
188
  }
165
- await call('DELETE', `/v1/sandboxes/${id}`);
189
+ const result = await call('DELETE', `/v1/sandboxes/${id}${keep ? '?keep_traces=1' : ''}`);
166
190
  say(`${id} destroyed.`);
191
+ if (result.traces_kept) say(`Its traces are kept until ${new Date(result.traces_kept_until * 1000).toLocaleDateString()}.`);
192
+ else if (result.traces_deleted === false) say('Note: its traces could not be deleted; they may still show on the dashboard.');
167
193
  }
168
194
 
169
195
  /** An interactive terminal in the sandbox, carried over one upgraded HTTP request.
170
196
  * `raytrace connect <id>` and `raytrace sandbox shell [id]` are the same thing. */
171
- export async function shell(id) {
197
+ export async function shell(id, flags = {}) {
172
198
  if (!interactive()) throw new Error('Connecting to a sandbox needs a terminal.');
199
+ // With no id and no cloud sign-in, the one local sandbox is the likely one.
200
+ if (flags.local || local.isLocal(id) || (!id && Object.keys(local.registry()).length && !account())) return local.shell(id);
173
201
  id = await pickId(id);
174
202
  const { url, key } = await api();
175
203
  const { stdin, stdout } = process;