@raytrace-cli/cli 0.5.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 (56) hide show
  1. package/README.md +27 -1
  2. package/bin/raytrace.mjs +69 -2
  3. package/dist/dashboard/assets/{index-jyV5iYHJ.js → index-Dc3LTk8b.js} +4 -4
  4. package/dist/dashboard/index.html +1 -1
  5. package/package.json +2 -1
  6. package/proxy/agent-intent-schema.test.mjs +142 -0
  7. package/proxy/call-assessment.test.mjs +167 -0
  8. package/proxy/capture.mjs +11 -4
  9. package/proxy/capture.test.mjs +49 -0
  10. package/proxy/claude-code-adapter.mjs +19 -0
  11. package/proxy/claude-code-hook.mjs +3 -1
  12. package/proxy/codex-config.mjs +5 -0
  13. package/proxy/codex.mjs +3 -2
  14. package/proxy/evidence-schema.test.mjs +233 -0
  15. package/proxy/evidence-store.mjs +91 -22
  16. package/proxy/evidence-store.test.mjs +304 -0
  17. package/proxy/exec-narrative.test.mjs +262 -0
  18. package/proxy/execution-correlation.test.mjs +146 -0
  19. package/proxy/execution-runner.test.mjs +38 -0
  20. package/proxy/experiment-engine.test.mjs +93 -0
  21. package/proxy/explanations.test.mjs +20 -0
  22. package/proxy/gvisor-forwarder.test.mjs +368 -0
  23. package/proxy/init-evidence-db.mjs +30 -0
  24. package/proxy/local-token.mjs +30 -0
  25. package/proxy/playground-recovery.test.mjs +130 -0
  26. package/proxy/playground.mjs +31 -3
  27. package/proxy/prompt-traces.test.mjs +32 -0
  28. package/proxy/providers.test.mjs +76 -0
  29. package/proxy/proxy.integration.test.mjs +135 -0
  30. package/proxy/raytace-proxy.mjs +58 -18
  31. package/proxy/request-metrics.test.mjs +19 -0
  32. package/proxy/request-policy.mjs +45 -0
  33. package/proxy/request-policy.test.mjs +47 -0
  34. package/proxy/sandbox-bridge.mjs +3 -0
  35. package/proxy/search.test.mjs +161 -0
  36. package/proxy/smoke.test.mjs +93 -0
  37. package/proxy/step-lab.test.mjs +38 -0
  38. package/proxy/summaries.test.mjs +69 -0
  39. package/proxy/tool-metadata.test.mjs +38 -0
  40. package/proxy/trace-view.mjs +50 -18
  41. package/proxy/trace-view.test.mjs +72 -0
  42. package/proxy/typesafe.test.mjs +39 -0
  43. package/src/claude-code.mjs +38 -1
  44. package/src/commands.mjs +69 -25
  45. package/src/config.mjs +16 -7
  46. package/src/export.mjs +200 -0
  47. package/src/lima.mjs +42 -1
  48. package/src/local-sandbox.mjs +19 -4
  49. package/src/paths.mjs +8 -8
  50. package/src/proxy-process.mjs +26 -3
  51. package/src/sandbox.mjs +13 -3
  52. package/src/upload.mjs +198 -0
  53. package/worker/sandbox/claude-hook.mjs +50 -17
  54. package/worker/sandbox/projects.py +3 -2
  55. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  56. package/worker/sandbox/viewer.py +21 -2
@@ -0,0 +1,39 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { typesafeConfig, systemOne } from './typesafe.mjs';
4
+
5
+ const reply = (status, body = {}, headers = {}) => new Response(JSON.stringify(body), { status, headers });
6
+
7
+ test('disabled without a key; defaults to jev-latest', () => {
8
+ assert.equal(typesafeConfig({}).enabled, false);
9
+ const config = typesafeConfig({ TYPESAFE_API_KEY: ' k ', RAYTACE_TYPESAFE_URL: 'http://x/' });
10
+ assert.deepEqual(config, { enabled: true, apiKey: 'k', model: 'jev-latest', url: 'http://x' });
11
+ });
12
+
13
+ test('sends the documented request shape with a bearer key', async () => {
14
+ let seen;
15
+ const fetchImpl = async (url, init) => { seen = { url, init }; return reply(200, { model: 'jev-1.13.0', answers: {}, usage: { input_tokens: 10 } }); };
16
+ const config = typesafeConfig({ TYPESAFE_API_KEY: 'k' });
17
+ const result = await systemOne(config, { state: { a: 1 }, questions: { q: { type: 'noul', instructions: 'x?' } } }, { fetchImpl });
18
+ assert.equal(seen.url, 'https://api.typesafe.ai/v1/systemone');
19
+ assert.equal(seen.init.headers.authorization, 'Bearer k');
20
+ assert.deepEqual(JSON.parse(seen.init.body), { model: 'jev-latest', state: { a: 1 }, questions: { q: { type: 'noul', instructions: 'x?' } } });
21
+ assert.equal(result.model, 'jev-1.13.0');
22
+ });
23
+
24
+ test('retries 429 and 529, but not other errors', async () => {
25
+ const config = typesafeConfig({ TYPESAFE_API_KEY: 'k' });
26
+ let calls = 0;
27
+ const flaky = async () => (++calls < 3 ? reply(calls === 1 ? 429 : 529, {}, { 'retry-after': '0.01' }) : reply(200, { answers: {} }));
28
+ await systemOne(config, { state: '', questions: {} }, { fetchImpl: flaky });
29
+ assert.equal(calls, 3);
30
+
31
+ calls = 0;
32
+ const invalid = async () => { calls += 1; return reply(422, { detail: 'bad question' }); };
33
+ await assert.rejects(systemOne(config, { state: '', questions: {} }, { fetchImpl: invalid }), (error) => error.status === 422 && /bad question/.test(error.message));
34
+ assert.equal(calls, 1);
35
+ });
36
+
37
+ test('refuses to call without a key', async () => {
38
+ await assert.rejects(systemOne(typesafeConfig({}), { state: '', questions: {} }), /TYPESAFE_API_KEY/);
39
+ });
@@ -33,7 +33,44 @@ function allHooks(settings) {
33
33
  export function hookState() {
34
34
  const settings = readSettings();
35
35
  const hooks = allHooks(settings);
36
- return { file: settingsFile(), installed: EVENTS.every((event) => (settings.hooks?.[event] ?? []).some((group) => (group.hooks ?? []).some(isOurs))), repoHook: hooks.some(isRepoHook) };
36
+ const repoHook = hooks.some(isRepoHook);
37
+
38
+ const missingEvents = [];
39
+ let invalidType = false;
40
+ let invalidMatcher = false;
41
+ let duplicates = false;
42
+
43
+ for (const event of EVENTS) {
44
+ const groups = settings.hooks?.[event] ?? [];
45
+ let count = 0;
46
+
47
+ for (const group of groups) {
48
+ for (const hook of group.hooks ?? []) {
49
+ if (isOurs(hook)) {
50
+ count += 1;
51
+ if (hook.type !== 'command') invalidType = true;
52
+ if (event === 'PostToolUse' && group.matcher && group.matcher !== '*') invalidMatcher = true;
53
+ }
54
+ }
55
+ }
56
+
57
+ if (count === 0) missingEvents.push(event);
58
+ else if (count > 1) duplicates = true;
59
+ }
60
+
61
+ const installed = missingEvents.length === 0;
62
+ const valid = installed && !invalidType && !invalidMatcher && !duplicates;
63
+
64
+ return {
65
+ file: settingsFile(),
66
+ installed,
67
+ valid,
68
+ missingEvents,
69
+ invalidType,
70
+ invalidMatcher,
71
+ duplicates,
72
+ repoHook
73
+ };
37
74
  }
38
75
 
39
76
  /** Installs (or with remove, removes) the hook. Returns the settings file. */
package/src/commands.mjs CHANGED
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { delimiter, join } from 'node:path';
5
5
  import { paths } from './paths.mjs';
6
6
  import { portOf, proxyEnv, readConfig, writeConfig } from './config.mjs';
7
- import { healthy, portInUse, runningPid, start, status, stop } from './proxy-process.mjs';
7
+ import { checkRunningPid, dashboardLink, healthy, portInUse, PROXY_API, proxyApi, runningPid, start, status, stop } from './proxy-process.mjs';
8
8
  import { HOOK_COMMAND, hookState, setHook } from './claude-code.mjs';
9
9
  import { askSecret, confirm, interactive } from './prompt.mjs';
10
10
 
@@ -60,7 +60,7 @@ export async function setup(flags) {
60
60
 
61
61
  if (hookClaude && !onPath('raytrace')) {
62
62
  say(`\n Warning: \`raytrace\` is not on your PATH, and Claude Code's hook runs \`${HOOK_COMMAND}\`.`);
63
- say(' Install it globally so the hook can find it: npm install -g @raytrace/cli');
63
+ say(' Install it globally so the hook can find it: npm install -g @raytrace-cli/cli');
64
64
  }
65
65
 
66
66
  // A proxy this CLI started is restarted so the new settings apply.
@@ -80,7 +80,8 @@ export async function startCommand({ open = false } = {}) {
80
80
  : result.started ? `RayTrace is running: ${url}` : `RayTrace was already running: ${url}`);
81
81
  if (!result.started && !result.pid) say(' (started outside this CLI, e.g. from the RayTrace repo; `raytrace stop` will not stop it)');
82
82
  say(` Logs: ${paths.proxyLog}`);
83
- if (open) openUrl(url);
83
+ if (open) openUrl(await dashboardLink(result.port));
84
+ else say(' Open the dashboard with: raytrace open');
84
85
  }
85
86
 
86
87
  export async function stopCommand() {
@@ -101,7 +102,8 @@ export async function statusCommand() {
101
102
  export async function openCommand() {
102
103
  const state = await status();
103
104
  if (!state.healthy) { say('RayTrace is not running. Start it with `raytrace start`.'); process.exitCode = 1; return; }
104
- openUrl(state.url);
105
+ if (state.pid && await proxyApi(state.port) < PROXY_API) await start();
106
+ openUrl(await dashboardLink(state.port));
105
107
  say(`Opening ${state.url}`);
106
108
  }
107
109
 
@@ -160,40 +162,82 @@ export async function keyCommand(which, flags) {
160
162
  export async function doctor() {
161
163
  let problems = 0;
162
164
  const line = (ok, label, detail) => { if (ok === false) problems += 1; say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}`); };
163
- const config = readConfig();
165
+ let config;
166
+ try { config = readConfig(); } catch (err) { config = {}; line(false, 'settings', `malformed config: ${err.message}`); }
164
167
  const port = portOf(config);
165
168
 
166
169
  line(true, 'node', process.version);
167
170
  if (!existsSync(paths.config)) line(false, 'settings', `missing; run \`raytrace setup\``);
168
171
  else {
169
- const mode = statSync(paths.config).mode & 0o777;
170
- line(process.platform === 'win32' || (mode & 0o077) === 0, 'settings', `${paths.config}${(mode & 0o077) && process.platform !== 'win32' ? ` is readable by others (chmod 600 it)` : ''}`);
172
+ try {
173
+ const mode = statSync(paths.config).mode & 0o777;
174
+ line(process.platform === 'win32' || (mode & 0o077) === 0, 'settings', `${paths.config}${(mode & 0o077) && process.platform !== 'win32' ? ` is readable by others (chmod 600 it)` : ''}`);
175
+ } catch (err) {
176
+ line(false, 'settings', `cannot inspect ${paths.config}: ${err.message}`);
177
+ }
171
178
  }
172
179
  line(existsSync(paths.dashboard) ? true : false, 'dashboard', existsSync(paths.dashboard) ? 'built' : `missing from ${paths.dashboard}; reinstall`);
173
- line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : 'no: Claude Code\'s hook cannot run it (npm install -g @raytrace/cli)');
174
-
175
- const hooks = hookState();
176
- line(hooks.installed ? true : null, 'claude code hook', hooks.installed ? `installed in ${hooks.file}` : 'not installed (raytrace setup)');
177
- if (hooks.repoHook) line(null, 'repo hook', 'the RayTrace repo\'s hook is also installed; sessions are reported twice');
180
+ line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : 'no: Claude Code\'s hook cannot run it (npm install -g @raytrace-cli/cli)');
181
+
182
+ try {
183
+ const hooks = hookState();
184
+ if (!hooks.installed) {
185
+ line(null, 'claude code hook', `not installed (${hooks.file}); run \`raytrace setup\``);
186
+ } else if (!hooks.valid) {
187
+ const issues = [];
188
+ if (hooks.missingEvents.length) issues.push(`missing: ${hooks.missingEvents.join(', ')}`);
189
+ if (hooks.invalidType) issues.push('invalid hook type (expected command)');
190
+ if (hooks.invalidMatcher) issues.push('restricted PostToolUse matcher (must be *)');
191
+ if (hooks.duplicates) issues.push('duplicate hooks detected');
192
+ line(false, 'claude code hook', `misconfigured in ${hooks.file} (${issues.join('; ')}); run \`raytrace setup\``);
193
+ } else {
194
+ line(true, 'claude code hook', `installed and valid in ${hooks.file}`);
195
+ }
196
+ if (hooks.repoHook) line(null, 'repo hook', 'the RayTrace repo\'s hook is also installed; sessions are reported twice');
197
+ } catch (error) {
198
+ line(false, 'claude code hook', `cannot read settings: ${error.message}`);
199
+ }
178
200
 
179
201
  line(config.OPENROUTER_API_KEY ? true : null, 'openrouter', config.OPENROUTER_API_KEY ? 'key set: AI features on' : 'no key: AI features off (raytrace key openrouter)');
180
202
 
181
- const pid = runningPid();
182
- if (await healthy(port)) line(true, 'proxy', `running on :${port}${pid ? ` (pid ${pid})` : ' (started outside this CLI)'}`);
183
- else if (await portInUse(port)) line(false, 'proxy', `port ${port} is held by something that is not RayTrace`);
184
- else line(null, 'proxy', `stopped (port ${port} free)`);
203
+ const pid = checkRunningPid();
204
+ try {
205
+ if (await healthy(port)) line(true, 'proxy', `running on :${port}${pid ? ` (pid ${pid})` : ' (started outside this CLI)'}`);
206
+ else if (await portInUse(port)) line(false, 'proxy', `port ${port} is held by something that is not RayTrace`);
207
+ else line(null, 'proxy', `stopped (port ${port} free)`);
208
+ } catch (err) {
209
+ line(false, 'proxy', `connectivity check failed: ${err.message}`);
210
+ }
211
+
212
+ const bridgePort = Number(process.env.RAYTRACE_BRIDGE_PORT || 8799);
213
+ try {
214
+ const res = await fetch(`http://127.0.0.1:${bridgePort}/raytace/identity`, { signal: AbortSignal.timeout(1000) });
215
+ if (res.ok) {
216
+ const info = await res.json();
217
+ line(true, 'sandbox bridge', `listening on :${bridgePort} (${info.service} v${info.version})`);
218
+ } else {
219
+ line(false, 'sandbox bridge', `port ${bridgePort} returned HTTP ${res.status}`);
220
+ }
221
+ } catch {
222
+ line(null, 'sandbox bridge', `not responding on :${bridgePort} (starts with proxy)`);
223
+ }
224
+
185
225
  line(existsSync(paths.database) ? true : null, 'database', existsSync(paths.database) ? `${paths.database} (${(statSync(paths.database).size / 1e6).toFixed(1)} MB)` : 'not created yet; it is made on first start');
186
226
 
187
227
  // Local sandboxes are optional: what they lack is shown, not counted as a problem.
188
228
  say('\nLocal sandboxes (raytrace sandbox create --local):');
189
- const { checks } = await import('./lima.mjs');
190
- const { vmStatus } = await import('./local-sandbox.mjs');
191
- let vm = null;
192
- try { vm = vmStatus(); } catch { /* no Lima yet */ }
193
- const rows = await checks({ vmRunning: vm === 'Running' });
194
- for (const { ok, label, detail, fix } of rows) say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}${fix ? `\n ${''.padEnd(22)} fix: ${fix}` : ''}`);
195
- if (vm) say(`· ${'vm'.padEnd(22)} raytrace: ${vm.toLowerCase()}`);
196
- else if (rows.every((row) => row.ok !== false)) say(`· ${'vm'.padEnd(22)} not created yet; the first local sandbox makes it`);
229
+ try {
230
+ const { checks } = await import('./lima.mjs');
231
+ const { vmStatus, inVm } = await import('./local-sandbox.mjs');
232
+ let vm = null;
233
+ try { vm = vmStatus(); } catch { /* no Lima yet */ }
234
+ const rows = await checks({ vmRunning: vm === 'Running', runInVm: inVm });
235
+ for (const { ok, label, detail, fix } of rows) say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}${fix ? `\n ${''.padEnd(22)} fix: ${fix}` : ''}`);
236
+ if (vm) say(`· ${'vm'.padEnd(22)} raytrace: ${vm.toLowerCase()}`);
237
+ else if (rows.every((row) => row.ok !== false)) say(`· ${'vm'.padEnd(22)} not created yet; the first local sandbox makes it`);
238
+ } catch (err) {
239
+ say(`· ${'vm checks'.padEnd(22)} skipped (${err.message})`);
240
+ }
197
241
 
198
242
  say(problems ? `\n${problems} problem${problems === 1 ? '' : 's'} found.` : '\nNo problems found.');
199
243
  if (problems) process.exitCode = 1;
@@ -237,5 +281,5 @@ export async function uninstall(flags) {
237
281
  }
238
282
  else say(`Kept ${paths.home}.`);
239
283
  }
240
- say('To remove the command itself: npm uninstall -g @raytrace/cli');
284
+ say('To remove the command itself: npm uninstall -g @raytrace-cli/cli');
241
285
  }
package/src/config.mjs CHANGED
@@ -11,19 +11,28 @@ export function readConfig() {
11
11
  }
12
12
 
13
13
  export function writeConfig(values) {
14
- mkdirSync(paths.home, { recursive: true });
15
- const lines = Object.entries(values)
14
+ const entries = Object.entries(values)
16
15
  .filter(([, value]) => value !== undefined && value !== '')
17
- .map(([key, value]) => `${key}=${quote(String(value))}`);
18
- writeFileSync(paths.config, `# RayTrace settings. Restart with \`raytrace stop && raytrace start\` after editing.\n${lines.join('\n')}\n`, { mode: 0o600 });
16
+ .map(([key, value]) => [key, String(value)]);
17
+ const lines = entries.map(([key, value]) => `${key}=${quote(value)}`);
18
+ const text = `# RayTrace settings. Restart with \`raytrace stop && raytrace start\` after editing.\n${lines.join('\n')}\n`;
19
+ const parsed = parseEnv(text);
20
+ // Validate before touching the existing settings. dotenv has no general
21
+ // quote-escaping syntax, so some values cannot be represented losslessly.
22
+ for (const [key, value] of entries) {
23
+ if (parsed[key] !== value) throw new Error(`Cannot save setting ${key} without changing its value.`);
24
+ }
25
+ mkdirSync(paths.home, { recursive: true });
26
+ writeFileSync(paths.config, text, { mode: 0o600 });
19
27
  chmodSync(paths.config, 0o600); // the mode above only applies when the file is new
20
28
  }
21
29
 
22
- // Single quotes are taken literally by parseEnv, so JSON values (a custom
23
- // RAYTACE_OPENROUTER_MODELS) survive a round trip; double quotes otherwise.
30
+ // Choose a delimiter absent from the value. Backslash does not escape a
31
+ // delimiter in parseEnv; double quotes also expand literal backslash-n.
24
32
  function quote(value) {
25
33
  if (!/[\s#"'`]/.test(value)) return value;
26
- return value.includes("'") ? `"${value}"` : `'${value}'`;
34
+ const delimiter = ["'", '`', '"'].find((candidate) => !value.includes(candidate));
35
+ return delimiter ? `${delimiter}${value}${delimiter}` : value;
27
36
  }
28
37
 
29
38
  export const portOf = (config) => Number(config.RAYTACE_PORT || DEFAULT_PORT);
package/src/export.mjs ADDED
@@ -0,0 +1,200 @@
1
+ import { existsSync, writeFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { paths } from './paths.mjs';
4
+ import { openEvidenceStore } from '../proxy/evidence-store.mjs';
5
+ import { readTraces } from '../proxy/trace-view.mjs';
6
+
7
+ const VERSION = '1.0.0';
8
+
9
+ function escapeHtml(str) {
10
+ if (typeof str !== 'string') return '';
11
+ return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
12
+ }
13
+
14
+ function safeCodeBlock(content, lang = '') {
15
+ const text = String(content ?? '');
16
+ const matches = text.match(/`+/g) || [];
17
+ let maxBackticks = 3;
18
+ for (const m of matches) {
19
+ if (m.length >= maxBackticks) maxBackticks = m.length + 1;
20
+ }
21
+ const fence = '`'.repeat(maxBackticks);
22
+ return `${fence}${lang}\n${text}\n${fence}`;
23
+ }
24
+
25
+ export function formatTraceJson(trace) {
26
+ const exported = {
27
+ version: VERSION,
28
+ exported_at: new Date().toISOString(),
29
+ trace: {
30
+ id: trace.id,
31
+ provider: trace.provider,
32
+ model: trace.model,
33
+ status: trace.status ?? 'unknown',
34
+ title: trace.title ?? null,
35
+ prompt: trace.promptRaw ?? null,
36
+ answer: trace.answer ?? null,
37
+ started_at: trace.startedAt ?? null,
38
+ ended_at: trace.endedAt ?? null,
39
+ sandbox_id: trace.sandboxId ?? null,
40
+ fork_id: trace.forkId ?? null,
41
+ requests: (trace.requests ?? []).map((r) => ({
42
+ id: r.id,
43
+ model: r.model,
44
+ started_at: r.startedAt,
45
+ completed_at: r.completedAt,
46
+ cost: r.cost ?? null,
47
+ input_tokens: r.input_tokens ?? null,
48
+ output_tokens: r.output_tokens ?? null,
49
+ })),
50
+ events: (trace.events ?? []).map((e) => {
51
+ let raw = null;
52
+ if (e.raw) {
53
+ try { raw = typeof e.raw === 'string' ? JSON.parse(e.raw) : e.raw; } catch { raw = e.raw; }
54
+ }
55
+ return {
56
+ kind: e.kind,
57
+ title: e.title,
58
+ status: e.status,
59
+ timestamp: e.timestamp,
60
+ raw,
61
+ };
62
+ }),
63
+ evidence: trace.evidence ?? [],
64
+ call_verifications: trace.callVerifications ?? [],
65
+ },
66
+ };
67
+ return JSON.stringify(exported, null, 2);
68
+ }
69
+
70
+ export function formatTraceMarkdown(trace) {
71
+ const lines = [];
72
+ lines.push(`# Trace ${trace.id}`);
73
+ lines.push('');
74
+ lines.push(`- **Exported:** ${new Date().toISOString()}`);
75
+ lines.push(`- **Format Version:** ${VERSION}`);
76
+ lines.push(`- **Status:** \`${trace.status ?? 'unknown'}\``);
77
+ lines.push(`- **Model:** \`${trace.model ?? 'unknown'}\``);
78
+ lines.push(`- **Provider:** \`${trace.provider ?? 'unknown'}\``);
79
+ lines.push(`- **Started At:** ${trace.startedAt ?? 'unknown'}`);
80
+ lines.push(`- **Ended At:** ${trace.endedAt ?? 'unknown'}`);
81
+
82
+ let totalCost = null;
83
+ let totalInputTokens = 0;
84
+ let totalOutputTokens = 0;
85
+ let hasTokenData = false;
86
+
87
+ for (const r of trace.requests ?? []) {
88
+ if (r.cost != null) totalCost = (totalCost ?? 0) + r.cost;
89
+ if (r.input_tokens != null) { totalInputTokens += r.input_tokens; hasTokenData = true; }
90
+ if (r.output_tokens != null) { totalOutputTokens += r.output_tokens; hasTokenData = true; }
91
+ }
92
+
93
+ lines.push(`- **Cost:** \`${totalCost != null ? `$${totalCost.toFixed(4)}` : 'unknown'}\``);
94
+ if (hasTokenData) {
95
+ lines.push(`- **Tokens:** ${totalInputTokens} input · ${totalOutputTokens} output`);
96
+ }
97
+
98
+ lines.push('');
99
+ lines.push('## Prompt');
100
+ lines.push('');
101
+ lines.push(escapeHtml(trace.promptRaw || trace.title || '(no prompt recorded)'));
102
+ lines.push('');
103
+
104
+ if (trace.answer) {
105
+ lines.push('## Final Answer');
106
+ lines.push('');
107
+ lines.push(escapeHtml(trace.answer));
108
+ lines.push('');
109
+ }
110
+
111
+ lines.push('## Timeline & Tool Calls');
112
+ lines.push('');
113
+
114
+ if (!trace.events || !trace.events.length) {
115
+ lines.push('*(No events recorded)*');
116
+ } else {
117
+ for (const ev of trace.events) {
118
+ lines.push(`### ${escapeHtml(ev.title)}`);
119
+ lines.push(`- **Kind:** \`${ev.kind}\``);
120
+ lines.push(`- **Status:** \`${ev.status || 'unknown'}\``);
121
+ lines.push(`- **Timestamp:** ${ev.timestamp || 'unknown'}`);
122
+
123
+ let rawObj = null;
124
+ if (ev.raw) {
125
+ try { rawObj = typeof ev.raw === 'string' ? JSON.parse(ev.raw) : ev.raw; } catch { rawObj = ev.raw; }
126
+ }
127
+
128
+ if (rawObj?.call_id) {
129
+ lines.push(`- **Call ID:** \`${rawObj.call_id}\``);
130
+ }
131
+ if (rawObj?.output !== undefined) {
132
+ lines.push('');
133
+ lines.push('**Output:**');
134
+ lines.push(safeCodeBlock(rawObj.output));
135
+ } else if (rawObj?.arguments || rawObj?.input) {
136
+ lines.push('');
137
+ lines.push('**Arguments:**');
138
+ lines.push(safeCodeBlock(rawObj.arguments || rawObj.input, 'json'));
139
+ }
140
+ lines.push('');
141
+ }
142
+ }
143
+
144
+ if (trace.callVerifications && trace.callVerifications.length) {
145
+ lines.push('## Observed Execution');
146
+ lines.push('');
147
+ for (const v of trace.callVerifications) {
148
+ lines.push(`- **${escapeHtml(v.name || 'tool')}** (\`${v.call_id}\`): ` +
149
+ `status=\`${v.status || (v.verified ? 'verified' : 'unverified')}\`` +
150
+ `${v.proposed ? ` · proposed: \`${escapeHtml(v.proposed)}\`` : ''}` +
151
+ `${v.error ? ` · error: \`${escapeHtml(v.error)}\`` : ''}`);
152
+ }
153
+ lines.push('');
154
+ }
155
+
156
+ return lines.join('\n');
157
+ }
158
+
159
+ export async function exportCommand(traceId, { format = 'markdown', output = null } = {}) {
160
+ if (!traceId || !traceId.trim()) {
161
+ throw new Error('Trace ID is required. Usage: raytrace export <trace-id> [--format json|markdown] [--output <file>]');
162
+ }
163
+ const cleanId = traceId.trim();
164
+ const cleanFormat = format?.toLowerCase() ?? 'markdown';
165
+ if (cleanFormat !== 'markdown' && cleanFormat !== 'json') {
166
+ throw new Error(`Invalid format: ${format}. Expected 'markdown' or 'json'.`);
167
+ }
168
+
169
+ const dbPath = paths.database;
170
+ if (!existsSync(dbPath)) {
171
+ throw new Error(`No evidence database found at ${dbPath}. Has raytrace been started?`);
172
+ }
173
+
174
+ const store = openEvidenceStore(dbPath, { readOnly: true });
175
+ let trace;
176
+ try {
177
+ const traces = await readTraces(store, { turnId: cleanId, includeHistory: true, evidence: true });
178
+ trace = traces.find((t) => t.id === cleanId) || traces[0];
179
+ } finally {
180
+ store.close();
181
+ }
182
+
183
+ if (!trace) {
184
+ throw new Error(`Trace not found: ${cleanId}`);
185
+ }
186
+
187
+ const content = cleanFormat === 'json' ? formatTraceJson(trace) : formatTraceMarkdown(trace);
188
+
189
+ if (output) {
190
+ const outPath = resolve(output);
191
+ if (existsSync(outPath)) {
192
+ throw new Error(`File already exists: ${outPath}. Refusing to overwrite.`);
193
+ }
194
+ writeFileSync(outPath, content, { mode: 0o600 });
195
+ return content;
196
+ }
197
+
198
+ console.log(content);
199
+ return content;
200
+ }
package/src/lima.mjs CHANGED
@@ -93,7 +93,16 @@ const qemu = () => (process.arch === 'arm64' ? 'qemu-system-aarch64' : 'qemu-sys
93
93
  * {ok: true | false | null (a warning), label, detail, fix?}. Lima itself is
94
94
  * reported, not fetched: create offers the download.
95
95
  */
96
- export async function checks({ vmRunning = false } = {}) {
96
+ /** What the VM's firewall leaves a sandbox able to reach beyond the bridge
97
+ * (:8799). Lima maps its host address to this machine's localhost, so these
98
+ * rules are all that keeps a sandbox off the proxy. */
99
+ export function sandboxReach(rules) {
100
+ const lines = rules.split('\n').filter((line) => line.includes('-i br-raytace'));
101
+ if (!lines.some((line) => line.includes('-d 192.168.0.0/16') && line.includes('-j REJECT'))) return ['every local port'];
102
+ return lines.filter((line) => line.includes('-j ACCEPT') && !line.includes('--dport 8799')).map((line) => line.match(/--dport (\d+)/)?.[1] ?? 'every local port');
103
+ }
104
+
105
+ export async function checks({ vmRunning = false, runInVm = null } = {}) {
97
106
  const rows = [];
98
107
  const row = (ok, label, detail, fix) => rows.push({ ok, label, detail, fix });
99
108
  const platform = process.platform;
@@ -131,5 +140,37 @@ export async function checks({ vmRunning = false } = {}) {
131
140
  }
132
141
  const gib = totalmem() / 1024 ** 3;
133
142
  if (gib < 8) row(null, 'memory', `${gib.toFixed(0)} GiB; the VM takes 4 GiB while it runs`);
143
+
144
+ if (vmRunning && typeof runInVm === 'function') {
145
+ try {
146
+ const docker = runInVm(['docker', 'info', '--format', '{{json .Runtimes}}'], { check: false });
147
+ if (docker?.status === 0) {
148
+ row(true, 'docker (in VM)', 'responding');
149
+ const hasGvisor = typeof docker.stdout === 'string' && docker.stdout.includes('raytace-gvisor');
150
+ row(hasGvisor ? true : false, 'raytace-gvisor', hasGvisor ? 'runtime registered' : 'runtime missing from Docker', 'run setup in VM');
151
+ } else {
152
+ row(false, 'docker (in VM)', 'not responding or daemon down', 'sudo systemctl restart docker in VM');
153
+ }
154
+
155
+ const runsc = runInVm(['/usr/local/bin/runsc', '--version'], { check: false });
156
+ row(runsc?.status === 0 ? true : false, 'runsc (in VM)', runsc?.status === 0 ? String(runsc.stdout).trim().split('\n')[0] : 'missing from /usr/local/bin/runsc');
157
+
158
+ for (const svc of ['collector', 'viewer', 'dns']) {
159
+ const active = runInVm(['systemctl', 'is-active', `raytace-${svc}`], { check: false });
160
+ const isOk = active?.status === 0 && String(active.stdout).trim() === 'active';
161
+ row(isOk ? true : false, `raytace-${svc}`, isOk ? 'active' : `inactive (${String(active?.stdout ?? '').trim() || 'failed'})`, `sudo systemctl restart raytace-${svc}`);
162
+ }
163
+
164
+ const sock = runInVm(['test', '-S', '/run/raytace/events.sock'], { check: false });
165
+ row(sock?.status === 0 ? true : false, 'collector socket', sock?.status === 0 ? '/run/raytace/events.sock exists' : 'missing /run/raytace/events.sock');
166
+
167
+ const firewall = runInVm(['sudo', 'iptables', '-S', 'DOCKER-USER'], { check: false });
168
+ const open = firewall?.status === 0 ? sandboxReach(String(firewall.stdout)) : null;
169
+ row(open?.length === 0, 'sandbox firewall', !open ? 'could not read the rules' : open.length ? `sandboxes can reach ${open.join(', ')} on this machine` : 'sandboxes reach only the bridge', 'sudo python3 /opt/raytace/network.py in VM');
170
+ } catch (err) {
171
+ row(false, 'vm diagnostics', `could not inspect VM: ${err.message}`);
172
+ }
173
+ }
174
+
134
175
  return rows;
135
176
  }
@@ -3,7 +3,7 @@
3
3
  // Your project never leaves the machine. The VM runs each sandbox as a Docker
4
4
  // container under gVisor; the collector beside it (worker/sandbox) records the
5
5
  // commands, files and connections it makes, independently of the agent, and the
6
- // evidence viewer shows them on http://localhost:8798. The sandbox's Claude Code
6
+ // dashboard shows them, read from the evidence viewer. The sandbox's Claude Code
7
7
  // hook sends its transcript to this CLI's proxy through the sandbox bridge
8
8
  // (proxy/sandbox-bridge.mjs), so its sessions show in the local dashboard.
9
9
  //
@@ -17,6 +17,8 @@ import { basename, join } from 'node:path';
17
17
  import { paths } from './paths.mjs';
18
18
  import { portInUse, runningPid, start as startProxy, stop as stopProxy } from './proxy-process.mjs';
19
19
  import { readConfig } from './config.mjs';
20
+ import { ensureToken } from '../proxy/local-token.mjs';
21
+ import { viewerTokenFor } from '../proxy/request-policy.mjs';
20
22
  import { LIMA_VERSION, canDownload, checks, downloadLima, findLima } from './lima.mjs';
21
23
 
22
24
  const say = (line = '') => console.log(line);
@@ -87,7 +89,7 @@ function limactl(args, { input, inherit = false, log = false, check = true } = {
87
89
  }
88
90
 
89
91
  /** A command in the VM as root: projects.py and setup.py run there. */
90
- const inVm = (args, options) => limactl(['shell', '--workdir', '/', VM, 'sudo', ...args], options);
92
+ export const inVm = (args, options) => limactl(['shell', '--workdir', '/', VM, 'sudo', ...args], options);
91
93
  const projects = (args, options) => inVm(['python3', '/opt/raytace/projects.py', ...args], options);
92
94
 
93
95
  /** Removes the RayTrace VM and every local sandbox in it; false when there was none. */
@@ -121,7 +123,13 @@ function ensureVm() {
121
123
  }
122
124
  const version = setupVersion();
123
125
  const installed = inVm(['cat', SETUP_MARK], { check: false }).stdout?.trim();
124
- if (installed === version) return;
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) {
125
133
  say(`Installing gVisor, the evidence collector and the sandbox image in the VM (a few minutes; progress in ${VM_LOG})...`);
126
134
  inVm(['rm', '-rf', '/tmp/raytrace-sandbox-source']);
127
135
  limactl(['shell', '--workdir', '/', VM, 'mkdir', '-p', '/tmp/raytrace-sandbox-source']);
@@ -258,6 +266,13 @@ export async function destroy(ref, flags, { ask, interactive }) {
258
266
  say(`This deletes local sandbox ${box.name}: its files, and any sign-in made inside it.`);
259
267
  if ((await ask('Type the sandbox name to confirm: ')) !== box.name) { say('Not destroyed.'); return; }
260
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
+ }
261
276
  let deleteLogs = flags['delete-logs'] ? true : flags['keep-logs'] ? false : null;
262
277
  if (deleteLogs === null) {
263
278
  deleteLogs = interactive()
@@ -318,7 +333,7 @@ export async function shell(id) {
318
333
  await ensureBridge();
319
334
  const { name } = registry()[id];
320
335
  say(`Connected to ${name}. Run \`claude\` (or codex) here; exit to leave. The sandbox keeps running.`);
321
- say('Recorded commands, files and connections: http://localhost:8798\n');
336
+ say('Recorded commands, files and connections: raytrace open, then Sandbox evidence\n');
322
337
  projects(['shell', id], { inherit: true, check: false });
323
338
  say(`\nLeft ${name}. It is still running. Back in: raytrace connect ${name} Stop it: raytrace sandbox stop ${name}`);
324
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;