@raytrace-cli/cli 0.5.0 → 0.7.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 (59) hide show
  1. package/README.md +54 -2
  2. package/bin/raytrace.mjs +81 -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/api.mjs +57 -0
  44. package/src/auth.mjs +35 -1
  45. package/src/beta.mjs +96 -0
  46. package/src/claude-code.mjs +38 -1
  47. package/src/commands.mjs +69 -25
  48. package/src/config.mjs +16 -7
  49. package/src/export.mjs +200 -0
  50. package/src/lima.mjs +42 -1
  51. package/src/local-sandbox.mjs +19 -4
  52. package/src/paths.mjs +8 -8
  53. package/src/proxy-process.mjs +26 -3
  54. package/src/sandbox.mjs +73 -40
  55. package/src/upload.mjs +198 -0
  56. package/worker/sandbox/claude-hook.mjs +50 -17
  57. package/worker/sandbox/projects.py +3 -2
  58. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  59. package/worker/sandbox/viewer.py +21 -2
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;
@@ -9,10 +9,11 @@ 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';
12
13
 
13
14
  // The proxy API this CLI's dashboard needs (proxy/raytace-proxy.mjs PROXY_API).
14
15
  // A proxy from an older install answers without it, or with less.
15
- export const PROXY_API = 2;
16
+ export const PROXY_API = 4;
16
17
 
17
18
  /** The running proxy's API version: 0 for one from before it said. */
18
19
  export async function proxyApi(port) {
@@ -22,13 +23,25 @@ export async function proxyApi(port) {
22
23
  } catch { return 0; }
23
24
  }
24
25
 
26
+ const signedIn = () => ({ authorization: `Bearer ${readToken(paths.home)}` });
27
+
25
28
  export async function healthy(port) {
26
29
  try {
27
- 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) });
28
31
  return response.ok;
29
32
  } catch { return false; }
30
33
  }
31
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
+
32
45
  /** True when anything at all is listening on the port. */
33
46
  export function portInUse(port) {
34
47
  return new Promise((done) => {
@@ -42,6 +55,16 @@ function alive(pid) {
42
55
  try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
43
56
  }
44
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
+
45
68
  /** The pid this CLI started, if that process is still running. */
46
69
  export function runningPid() {
47
70
  if (!existsSync(paths.proxyPid)) return null;
@@ -79,7 +102,7 @@ export async function start() {
79
102
  return { ...(await start()), replaced: true };
80
103
  }
81
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}.`);
82
- 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.`);
83
106
 
84
107
  mkdirSync(paths.logs, { recursive: true });
85
108
  mkdirSync(paths.run, { recursive: true });
package/src/sandbox.mjs CHANGED
@@ -13,8 +13,9 @@ import { lstatSync } from 'node:fs';
13
13
  import { request as httpRequest } from 'node:http';
14
14
  import { request as httpsRequest } from 'node:https';
15
15
  import { basename, join } from 'node:path';
16
- import { accessToken, account, login } from './auth.mjs';
17
- import { readConfig } from './config.mjs';
16
+ import { account } from './auth.mjs';
17
+ import { api, call, ApiError, unreachable } from './api.mjs';
18
+ import { betaStatus, formatCreditDeadline } from './beta.mjs';
18
19
  import { ask, confirm, interactive } from './prompt.mjs';
19
20
  import * as local from './local-sandbox.mjs';
20
21
 
@@ -27,9 +28,6 @@ const MAX_BYTES = 200 * MIB; // all files, before compression
27
28
  const MAX_FILES = 20_000;
28
29
  const MAX_ARCHIVE = 100 * MIB; // the packed upload
29
30
  const ID = /^rtp-[a-f0-9]{32}$/;
30
- const API = 'https://api.raytracer.si';
31
- const unreachable = (url) => new Error(`Cannot reach RayTrace at ${url.origin}. Check your connection; `
32
- + 'networks that inspect HTTPS (some company Wi-Fi) may block it.');
33
31
 
34
32
  // Never packed: version control, dependencies and build output (rebuilt in the
35
33
  // sandbox), and files that usually hold credentials.
@@ -45,34 +43,6 @@ export function packable(path) {
45
43
  && !name.startsWith('.env') && !SECRET_EXTENSIONS.test(name) && !SECRET_NAMES.has(name);
46
44
  }
47
45
 
48
- async function api() {
49
- const config = readConfig();
50
- const url = process.env.RAYTRACE_API_URL || config.RAYTRACE_API_URL || API;
51
- let key = process.env.RAYTRACE_API_KEY || config.RAYTRACE_API_KEY || await accessToken();
52
- if (!key) {
53
- if (!interactive()) throw new Error('Not signed in. Run: raytrace auth login');
54
- say('You are not signed in to RayTrace yet.');
55
- await login();
56
- key = await accessToken();
57
- if (!key) throw new Error('Not signed in. Run: raytrace auth login');
58
- say();
59
- }
60
- return { url: new URL(url), key };
61
- }
62
-
63
- async function call(method, path, { body, headers = {} } = {}) {
64
- const { url, key } = await api();
65
- let response;
66
- try {
67
- response = await fetch(new URL(path, url), { method, body, headers: { authorization: `Bearer ${key}`, ...headers } });
68
- } catch {
69
- throw unreachable(url);
70
- }
71
- const data = await response.json().catch(() => ({}));
72
- if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
73
- return data;
74
- }
75
-
76
46
  /** The project's files git would track, minus what must not leave this machine. */
77
47
  function projectFiles(root) {
78
48
  const listed = spawnSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { maxBuffer: 256 * 1024 * 1024 });
@@ -135,15 +105,52 @@ export async function create(flags) {
135
105
  if (!files.length) throw new Error('Nothing to upload.');
136
106
  // The same files, packed the same way, as a cloud sandbox gets: only the copy stays here.
137
107
  if (flags.local) return local.create(localName, { root, files, skipped, total, archive: await pack(root, files) });
108
+
109
+ // Beta credit: consumed by the first cloud sandbox created after
110
+ // redemption, only before its hard 3-day deadline. A local sandbox never
111
+ // uses it; an older backend (or no entitlement) never blocks a plain one.
112
+ let useCredit = false;
113
+ try {
114
+ const beta = await betaStatus();
115
+ const deadlinePassed = beta?.credit_expires_at && Date.parse(beta.credit_expires_at) <= Date.now();
116
+ if (beta && !beta.sandbox_consumed && deadlinePassed && (beta.entitled || beta.credit_usd)) {
117
+ say('Your $10 beta credit has expired: the 3 days ran out, and unused credit does not carry over.');
118
+ if (!interactive()) throw new Error('Beta credit expired; no sandbox was created. Ask RayTrace for a new code to try again.');
119
+ if (!(await confirm('Create a plain sandbox without beta credit?', false))) { say('Not created.'); return; }
120
+ } else if (beta?.entitled && !beta.sandbox_consumed) {
121
+ useCredit = true;
122
+ say(`Using your $${beta.credit_usd ?? 10} beta credit (OpenRouter) on this sandbox`
123
+ + `${beta.credit_expires_at ? ` — credit ends ${formatCreditDeadline(beta.credit_expires_at)}` : ''}.`);
124
+ }
125
+ } catch (error) {
126
+ if (/Beta credit expired/.test(error.message)) throw error;
127
+ // No beta answer (old backend, signed out, unreachable): proceed plain;
128
+ // the create call below surfaces any real auth/network failure.
129
+ }
138
130
  say(`Packing ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root}`);
139
131
  if (skipped.length) say(`Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
140
132
  const archive = await pack(root, files);
141
133
  if (archive.length > MAX_ARCHIVE) throw new Error(`The packed project is ${Math.round(archive.length / MIB)} MiB; the most is ${MAX_ARCHIVE / MIB} MiB.`);
142
134
  say('Creating the sandbox (the first one on a host takes a little longer)...');
143
- const box = await call('POST', '/v1/sandboxes', {
144
- body: archive, headers: { 'content-type': 'application/gzip', 'x-raytrace-name': name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) },
145
- });
135
+ const headers = { 'content-type': 'application/gzip', 'x-raytrace-name': name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) };
136
+ let box;
137
+ try {
138
+ box = await call('POST', '/v1/sandboxes', {
139
+ body: archive, headers: useCredit ? { ...headers, 'x-raytrace-beta-credit': '1' } : headers,
140
+ });
141
+ } catch (error) {
142
+ if (!useCredit || !(error instanceof ApiError) || ![409, 410].includes(error.status)) throw error;
143
+ say(error.status === 410 ? 'Your beta credit expired before the sandbox was created.'
144
+ : 'Your beta credit was already used on another sandbox.');
145
+ if (!interactive() || !(await confirm('Create a plain sandbox without beta credit?', false))) {
146
+ throw new Error('Beta credit not applied; no sandbox was created.');
147
+ }
148
+ box = await call('POST', '/v1/sandboxes', { body: archive, headers });
149
+ }
146
150
  say(`\nSandbox ${box.id} is running.`);
151
+ if (box.credit_applied) {
152
+ say(`Beta credit applied: $${box.credit_usd ?? 10} (OpenRouter)${box.credit_expires_at ? `, ends ${formatCreditDeadline(box.credit_expires_at)}` : ''}. This sandbox shows as Beta in the dashboard.`);
153
+ }
147
154
  say(box.transcripts ? 'Claude Code sessions in it are recorded.'
148
155
  : `Claude Code transcripts are off: ${box.transcripts_off}. Commands are still recorded.`);
149
156
  say(`Open it: raytrace connect ${box.id}`);
@@ -157,7 +164,8 @@ export async function list(flags = {}) {
157
164
  // The sandbox's creation time (seconds), or its container's once that is known.
158
165
  const created = typeof box.created === 'number' ? box.created * 1000 : Date.parse(box.created);
159
166
  const age = Math.round((Date.now() - created) / 60000);
160
- say(`${box.id} ${String(box.status).padEnd(8)} ${box.name} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
167
+ const beta = box.beta ? ` Beta${typeof box.credit_usd === 'number' ? ` ($${Math.max(0, box.credit_usd - (box.credit_spent_usd ?? 0)).toFixed(2)} of $${box.credit_usd} left${box.credit_expires_at ? `, ends ${formatCreditDeadline(box.credit_expires_at)}` : ''})` : ''}` : '';
168
+ say(`${box.id} ${String(box.status).padEnd(8)} ${box.name}${beta} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
161
169
  }
162
170
  }
163
171
 
@@ -173,13 +181,34 @@ export async function stop(id, flags = {}) {
173
181
  export async function destroy(id, flags) {
174
182
  if (flags.local || local.isLocal(id)) return local.destroy(id, flags, { ask, interactive });
175
183
  id = await pickId(id);
184
+ const me = await call('GET', '/v1/me').catch(() => ({}));
185
+ const plan = me.plan ?? {};
186
+ const paid = plan.plan && plan.plan !== 'beta';
187
+ let keep = Boolean(flags['keep-traces']);
176
188
  if (!flags.yes) {
177
- if (!interactive()) throw new Error('Pass --yes to destroy without a prompt.');
178
- say(`This deletes ${id}: its files, and any sign-in made inside it. Recorded evidence is kept.`);
189
+ if (!interactive()) throw new Error('Pass --yes to destroy without a prompt (with --yes, traces are deleted unless --keep-traces is passed).');
190
+ say(`This deletes ${id}: its files, and any sign-in made inside it.`);
191
+ 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');
179
192
  if ((await ask('Type the sandbox id to confirm: ')) !== id) { say('Not destroyed.'); return; }
193
+ if (paid && !keep) {
194
+ 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());
195
+ }
180
196
  }
181
- await call('DELETE', `/v1/sandboxes/${id}`);
197
+ const result = await call('DELETE', `/v1/sandboxes/${id}${keep ? '?keep_traces=1' : ''}`);
182
198
  say(`${id} destroyed.`);
199
+ if (result.traces_kept) say(`Its traces are kept until ${new Date(result.traces_kept_until * 1000).toLocaleDateString()}.`);
200
+ else if (result.traces_deleted === false) say('Note: its traces could not be deleted; they may still show on the dashboard.');
201
+ }
202
+
203
+ /** Exported for tests: the warning shown when connecting to a beta sandbox
204
+ * whose 3 days are up, or null. Model calls inside are refused by the
205
+ * backend; the sandbox itself still opens. */
206
+ export function betaExpiryWarning(beta, id, now = Date.now()) {
207
+ if (!beta || beta.credited_sandbox_id !== id) return null;
208
+ const deadline = beta.credit_expires_at ? Date.parse(beta.credit_expires_at) : NaN;
209
+ if (!beta.expired && !(deadline <= now)) return null;
210
+ return `Warning: your beta credit for this sandbox expired${beta.credit_expires_at ? ` (${formatCreditDeadline(beta.credit_expires_at, now)})` : ''}; `
211
+ + 'model calls in this sandbox will be refused. The sandbox itself still opens.';
183
212
  }
184
213
 
185
214
  /** An interactive terminal in the sandbox, carried over one upgraded HTTP request.
@@ -189,6 +218,10 @@ export async function shell(id, flags = {}) {
189
218
  // With no id and no cloud sign-in, the one local sandbox is the likely one.
190
219
  if (flags.local || local.isLocal(id) || (!id && Object.keys(local.registry()).length && !account())) return local.shell(id);
191
220
  id = await pickId(id);
221
+ try {
222
+ const warning = betaExpiryWarning(await betaStatus(), id);
223
+ if (warning) say(warning);
224
+ } catch { /* no beta answer: connecting must not depend on it */ }
192
225
  const { url, key } = await api();
193
226
  const { stdin, stdout } = process;
194
227
  const path = `/v1/sandboxes/${id}/shell?rows=${stdout.rows || 24}&cols=${stdout.columns || 80}`;