raytrace-cli 0.11.1__py3-none-win_amd64.whl

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 (165) hide show
  1. raytrace/__init__.py +1 -0
  2. raytrace/__main__.py +33 -0
  3. raytrace/app/LICENSE +21 -0
  4. raytrace/app/README.md +599 -0
  5. raytrace/app/bin/raytrace.mjs +297 -0
  6. raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  7. raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  8. raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  9. raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  10. raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  11. raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  12. raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  13. raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  14. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  15. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  16. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  17. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  18. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  19. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  20. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  21. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  22. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  23. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  24. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  25. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  26. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  27. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  28. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  29. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  30. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  31. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  32. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  33. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  34. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  35. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  36. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  37. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  38. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  39. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  40. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  41. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  42. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  43. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  44. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  45. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  46. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  47. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  48. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  49. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  50. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  51. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  52. raytrace/app/dist/dashboard/assets/index-DepcI8Fi.js +38 -0
  53. raytrace/app/dist/dashboard/assets/index-H97VLD5l.css +1 -0
  54. raytrace/app/dist/dashboard/favicon.svg +6 -0
  55. raytrace/app/dist/dashboard/index.html +15 -0
  56. raytrace/app/package.json +48 -0
  57. raytrace/app/proxy/agent-intent-schema.test.mjs +142 -0
  58. raytrace/app/proxy/call-assessment.mjs +385 -0
  59. raytrace/app/proxy/call-assessment.test.mjs +167 -0
  60. raytrace/app/proxy/call-category.mjs +461 -0
  61. raytrace/app/proxy/capture-health.mjs +30 -0
  62. raytrace/app/proxy/capture-health.test.mjs +44 -0
  63. raytrace/app/proxy/capture.mjs +38 -0
  64. raytrace/app/proxy/capture.test.mjs +49 -0
  65. raytrace/app/proxy/claude-code-adapter.mjs +301 -0
  66. raytrace/app/proxy/claude-code-hook.mjs +22 -0
  67. raytrace/app/proxy/codex-config.mjs +36 -0
  68. raytrace/app/proxy/codex.mjs +14 -0
  69. raytrace/app/proxy/evidence-schema.test.mjs +240 -0
  70. raytrace/app/proxy/evidence-store.mjs +993 -0
  71. raytrace/app/proxy/evidence-store.test.mjs +301 -0
  72. raytrace/app/proxy/exec-narrative.mjs +625 -0
  73. raytrace/app/proxy/exec-narrative.test.mjs +262 -0
  74. raytrace/app/proxy/execution-correlation.mjs +185 -0
  75. raytrace/app/proxy/execution-correlation.test.mjs +146 -0
  76. raytrace/app/proxy/execution-runner.mjs +89 -0
  77. raytrace/app/proxy/execution-runner.test.mjs +38 -0
  78. raytrace/app/proxy/experiment-engine.mjs +195 -0
  79. raytrace/app/proxy/experiment-engine.test.mjs +93 -0
  80. raytrace/app/proxy/explanations.mjs +36 -0
  81. raytrace/app/proxy/explanations.test.mjs +20 -0
  82. raytrace/app/proxy/failure-signature.mjs +56 -0
  83. raytrace/app/proxy/gvisor-forwarder.mjs +493 -0
  84. raytrace/app/proxy/gvisor-forwarder.test.mjs +433 -0
  85. raytrace/app/proxy/init-evidence-db.mjs +227 -0
  86. raytrace/app/proxy/local-sandboxes.mjs +94 -0
  87. raytrace/app/proxy/local-token.mjs +30 -0
  88. raytrace/app/proxy/playground-recovery.test.mjs +130 -0
  89. raytrace/app/proxy/playground.mjs +439 -0
  90. raytrace/app/proxy/prompt-context.mjs +278 -0
  91. raytrace/app/proxy/prompt-traces.mjs +40 -0
  92. raytrace/app/proxy/prompt-traces.test.mjs +32 -0
  93. raytrace/app/proxy/providers.mjs +65 -0
  94. raytrace/app/proxy/providers.test.mjs +76 -0
  95. raytrace/app/proxy/proxy.integration.test.mjs +135 -0
  96. raytrace/app/proxy/raytace-proxy.mjs +941 -0
  97. raytrace/app/proxy/request-metrics.mjs +13 -0
  98. raytrace/app/proxy/request-metrics.test.mjs +19 -0
  99. raytrace/app/proxy/request-policy.mjs +45 -0
  100. raytrace/app/proxy/request-policy.test.mjs +47 -0
  101. raytrace/app/proxy/run-recap.mjs +139 -0
  102. raytrace/app/proxy/runtime-attribution.mjs +110 -0
  103. raytrace/app/proxy/sandbox-bridge.mjs +49 -0
  104. raytrace/app/proxy/schema/EVIDENCE_DATABASE.md +276 -0
  105. raytrace/app/proxy/schema/agent_intent.sql +101 -0
  106. raytrace/app/proxy/schema/auxiliary.sql +90 -0
  107. raytrace/app/proxy/schema/capture_health.sql +14 -0
  108. raytrace/app/proxy/schema/classification.sql +89 -0
  109. raytrace/app/proxy/schema/file_context.sql +53 -0
  110. raytrace/app/proxy/schema/runtime_evidence.sql +201 -0
  111. raytrace/app/proxy/schema/search.sql +66 -0
  112. raytrace/app/proxy/schema/shared_storage.sql +21 -0
  113. raytrace/app/proxy/search.mjs +418 -0
  114. raytrace/app/proxy/search.test.mjs +161 -0
  115. raytrace/app/proxy/smoke.test.mjs +93 -0
  116. raytrace/app/proxy/step-attribution.mjs +380 -0
  117. raytrace/app/proxy/step-lab.mjs +78 -0
  118. raytrace/app/proxy/step-lab.test.mjs +38 -0
  119. raytrace/app/proxy/summaries.mjs +151 -0
  120. raytrace/app/proxy/summaries.test.mjs +69 -0
  121. raytrace/app/proxy/tool-metadata.mjs +111 -0
  122. raytrace/app/proxy/tool-metadata.test.mjs +38 -0
  123. raytrace/app/proxy/trace-view.mjs +324 -0
  124. raytrace/app/proxy/trace-view.test.mjs +92 -0
  125. raytrace/app/proxy/typesafe.mjs +63 -0
  126. raytrace/app/proxy/typesafe.test.mjs +39 -0
  127. raytrace/app/src/agents.mjs +7 -0
  128. raytrace/app/src/api.mjs +57 -0
  129. raytrace/app/src/auth.mjs +205 -0
  130. raytrace/app/src/beta.mjs +96 -0
  131. raytrace/app/src/claude-code.mjs +93 -0
  132. raytrace/app/src/commands.mjs +285 -0
  133. raytrace/app/src/config.mjs +49 -0
  134. raytrace/app/src/export.mjs +200 -0
  135. raytrace/app/src/lima.mjs +176 -0
  136. raytrace/app/src/local-sandbox.mjs +358 -0
  137. raytrace/app/src/mcp.mjs +688 -0
  138. raytrace/app/src/paths.mjs +33 -0
  139. raytrace/app/src/prompt.mjs +42 -0
  140. raytrace/app/src/proxy-process.mjs +143 -0
  141. raytrace/app/src/sandbox.mjs +306 -0
  142. raytrace/app/src/share.mjs +86 -0
  143. raytrace/app/src/terminal.mjs +68 -0
  144. raytrace/app/src/upload.mjs +198 -0
  145. raytrace/app/worker/sandbox/Dockerfile +8 -0
  146. raytrace/app/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  147. raytrace/app/worker/sandbox/claude-hook.mjs +364 -0
  148. raytrace/app/worker/sandbox/collector.py +405 -0
  149. raytrace/app/worker/sandbox/dns_forwarder.py +255 -0
  150. raytrace/app/worker/sandbox/engine.py +940 -0
  151. raytrace/app/worker/sandbox/file_scan.py +491 -0
  152. raytrace/app/worker/sandbox/lima.yaml +29 -0
  153. raytrace/app/worker/sandbox/network.py +90 -0
  154. raytrace/app/worker/sandbox/projects.py +702 -0
  155. raytrace/app/worker/sandbox/setup.py +159 -0
  156. raytrace/app/worker/sandbox/syscall_catalog.sql +985 -0
  157. raytrace/app/worker/sandbox/transcript-delivery.test.mjs +153 -0
  158. raytrace/app/worker/sandbox/viewer.py +195 -0
  159. raytrace/node/LICENSE +2946 -0
  160. raytrace/node/node.exe +4 -0
  161. raytrace_cli-0.11.1.dist-info/LICENSE +21 -0
  162. raytrace_cli-0.11.1.dist-info/METADATA +42 -0
  163. raytrace_cli-0.11.1.dist-info/RECORD +165 -0
  164. raytrace_cli-0.11.1.dist-info/WHEEL +4 -0
  165. raytrace_cli-0.11.1.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,33 @@
1
+ // Where everything lives. The package's own files are found relative to this
2
+ // one; the user's data in ~/.raytrace (RAYTRACE_HOME overrides it, which is
3
+ // also how to run a second, throwaway install side by side).
4
+ import { homedir } from 'node:os';
5
+ import { basename, dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const root = fileURLToPath(new URL('..', import.meta.url));
9
+ const home = () => process.env.RAYTRACE_HOME || join(homedir(), '.raytrace');
10
+
11
+ export const paths = {
12
+ root,
13
+ proxy: join(root, 'proxy', 'raytace-proxy.mjs'),
14
+ codex: join(root, 'proxy', 'codex.mjs'),
15
+ hook: join(root, 'proxy', 'claude-code-hook.mjs'),
16
+ dashboard: join(root, 'dist', 'dashboard'),
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
+ };
25
+
26
+ // How this copy was installed, for the commands we suggest: pip's wheel keeps
27
+ // the npm package in raytrace/app/ (python/build_wheels.py), next to its own Node.js.
28
+ const fromPip = basename(root) === 'app' && basename(dirname(root)) === 'raytrace';
29
+ export const install = fromPip
30
+ ? { add: 'pip install raytrace-cli', remove: 'pip uninstall raytrace-cli', run: 'uvx --from raytrace-cli raytrace' }
31
+ : { add: 'npm install -g @raytrace-cli/cli', remove: 'npm uninstall -g @raytrace-cli/cli', run: 'npx -y @raytrace-cli/cli' };
32
+
33
+ export const DEFAULT_PORT = 8797;
@@ -0,0 +1,42 @@
1
+ // Terminal questions for `raytrace setup`. Secrets are read with echo off so
2
+ // an API key never lands in the scrollback.
3
+ import { createInterface } from 'node:readline/promises';
4
+
5
+ export const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
6
+
7
+ export async function ask(question, fallback = '') {
8
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
9
+ try { return (await rl.question(question)).trim() || fallback; } finally { rl.close(); }
10
+ }
11
+
12
+ export async function confirm(question, fallback = true) {
13
+ const answer = (await ask(`${question} ${fallback ? '[Y/n]' : '[y/N]'} `)).toLowerCase();
14
+ return answer ? answer.startsWith('y') : fallback;
15
+ }
16
+
17
+ export function askSecret(question) {
18
+ return new Promise((resolve, reject) => {
19
+ const { stdin, stdout } = process;
20
+ let value = '';
21
+ stdout.write(question);
22
+ stdin.setRawMode(true);
23
+ stdin.resume();
24
+ stdin.setEncoding('utf8');
25
+ const done = (error) => {
26
+ stdin.setRawMode(false);
27
+ stdin.pause();
28
+ stdin.off('data', onData);
29
+ stdout.write('\n');
30
+ if (error) reject(error); else resolve(value.trim());
31
+ };
32
+ const onData = (chunk) => {
33
+ for (const char of chunk) {
34
+ if (char === '\r' || char === '\n') return done();
35
+ if (char === '\u0003') return done(new Error('Cancelled.')); // Ctrl-C
36
+ if (char === '\u007f' || char === '\b') { if (value) { value = value.slice(0, -1); stdout.write('\b \b'); } continue; }
37
+ if (char >= ' ') { value += char; stdout.write('*'); }
38
+ }
39
+ };
40
+ stdin.on('data', onData);
41
+ });
42
+ }
@@ -0,0 +1,143 @@
1
+ // Starting, stopping and checking the background proxy. What scripts/lib.sh
2
+ // did in the repo, in Node so it needs neither bash nor curl.
3
+ //
4
+ // Health is an answered HTTP probe, never "a process exists": a wedged proxy,
5
+ // or a port held by something unrelated, both have a pid.
6
+ import { spawn } from 'node:child_process';
7
+ import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, closeSync } from 'node:fs';
8
+ import { createConnection } from 'node:net';
9
+ import { setTimeout as sleep } from 'node:timers/promises';
10
+ import { paths } from './paths.mjs';
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 = 5;
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)}` });
27
+
28
+ export async function healthy(port) {
29
+ try {
30
+ const response = await fetch(`http://127.0.0.1:${port}/raytace/models`, { headers: signedIn(), signal: AbortSignal.timeout(2000) });
31
+ return response.ok;
32
+ } catch { return false; }
33
+ }
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
+
45
+ /** True when anything at all is listening on the port. */
46
+ export function portInUse(port) {
47
+ return new Promise((done) => {
48
+ const socket = createConnection({ host: '127.0.0.1', port });
49
+ socket.once('connect', () => { socket.destroy(); done(true); });
50
+ socket.once('error', () => done(false));
51
+ });
52
+ }
53
+
54
+ function alive(pid) {
55
+ try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
56
+ }
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
+
68
+ /** The pid this CLI started, if that process is still running. */
69
+ export function runningPid() {
70
+ if (!existsSync(paths.proxyPid)) return null;
71
+ const pid = Number(readFileSync(paths.proxyPid, 'utf8').trim());
72
+ if (Number.isInteger(pid) && pid > 0 && alive(pid)) return pid;
73
+ rmSync(paths.proxyPid, { force: true });
74
+ return null;
75
+ }
76
+
77
+ export async function status() {
78
+ const port = portOf(readConfig());
79
+ const pid = runningPid();
80
+ const ok = await healthy(port);
81
+ return { port, pid, healthy: ok, url: `http://127.0.0.1:${port}` };
82
+ }
83
+
84
+ function tail(file, lines = 8) {
85
+ try { return readFileSync(file, 'utf8').trimEnd().split('\n').slice(-lines).join('\n'); } catch { return ''; }
86
+ }
87
+
88
+ /**
89
+ * Starts the proxy detached, logging to ~/.raytrace/logs/proxy.log, and waits
90
+ * until it answers. A healthy proxy already on the port is reused, whoever
91
+ * started it.
92
+ */
93
+ export async function start() {
94
+ const config = readConfig();
95
+ const port = portOf(config);
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
+ }
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}.`);
105
+ if (!existsSync(paths.dashboard)) throw new Error(`The dashboard is missing from ${paths.dashboard}. Reinstall @raytrace-cli/cli.`);
106
+
107
+ mkdirSync(paths.logs, { recursive: true });
108
+ mkdirSync(paths.run, { recursive: true });
109
+ const log = openSync(paths.proxyLog, 'a');
110
+ writeFileSync(log, `\n=== ${new Date().toISOString()} starting on :${port} ===\n`);
111
+ // cwd is the data folder, so the proxy's own .env lookup finds nothing there
112
+ // and every setting comes from config.env through the environment.
113
+ const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', paths.proxy], {
114
+ cwd: paths.home, env: proxyEnv(config), detached: true, stdio: ['ignore', log, log],
115
+ });
116
+ closeSync(log);
117
+ let exited = null;
118
+ child.once('exit', (code) => { exited = code ?? 1; });
119
+ child.unref();
120
+ writeFileSync(paths.proxyPid, `${child.pid}\n`);
121
+
122
+ for (let waited = 0; waited < 20_000; waited += 250) {
123
+ if (exited !== null) break;
124
+ if (await healthy(port)) return { started: true, port, pid: child.pid };
125
+ await sleep(250);
126
+ }
127
+ if (exited === null) try { process.kill(child.pid); } catch { /* already gone */ }
128
+ rmSync(paths.proxyPid, { force: true });
129
+ throw new Error(`The proxy did not come up. Last lines of ${paths.proxyLog}:\n${tail(paths.proxyLog)}`);
130
+ }
131
+
132
+ export async function stop() {
133
+ const pid = runningPid();
134
+ if (!pid) {
135
+ const { port, healthy: up } = await status();
136
+ return { stopped: false, foreign: up, port };
137
+ }
138
+ process.kill(pid, 'SIGTERM');
139
+ for (let waited = 0; waited < 5000 && alive(pid); waited += 100) await sleep(100);
140
+ if (alive(pid)) process.kill(pid, 'SIGKILL');
141
+ rmSync(paths.proxyPid, { force: true });
142
+ return { stopped: true, pid };
143
+ }
@@ -0,0 +1,306 @@
1
+ // `raytrace sandbox`: cloud sandboxes, through RayTrace's API
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.
5
+ //
6
+ // The project is packed here, so files that must stay on this machine never
7
+ // leave it, then uploaded once; RayTrace creates an isolated sandbox from it
8
+ // that records its Claude Code sessions. Requests carry your `raytrace auth
9
+ // login` token; RAYTRACE_API_KEY overrides it for a server running without
10
+ // accounts (development).
11
+ import { spawn, spawnSync } from 'node:child_process';
12
+ import { lstatSync } from 'node:fs';
13
+ import { request as httpRequest } from 'node:http';
14
+ import { request as httpsRequest } from 'node:https';
15
+ import { basename, join } from 'node:path';
16
+ import { account } from './auth.mjs';
17
+ import { api, call, ApiError, unreachable } from './api.mjs';
18
+ import { betaStatus, formatCreditDeadline } from './beta.mjs';
19
+ import { ask, confirm, interactive } from './prompt.mjs';
20
+ import * as local from './local-sandbox.mjs';
21
+ import { AGENTS } from './agents.mjs';
22
+
23
+ const say = (line = '') => console.log(line);
24
+ // What one project upload may be. RayTrace's API holds the dashboard's folder
25
+ // upload to the same numbers and checks them again; saying so here saves the upload.
26
+ const MIB = 1024 * 1024;
27
+ const MAX_FILE = 25 * MIB; // any one file
28
+ const MAX_BYTES = 200 * MIB; // all files, before compression
29
+ const MAX_FILES = 20_000;
30
+ const MAX_ARCHIVE = 100 * MIB; // the packed upload
31
+ const ID = /^rtp-[a-f0-9]{32}$/;
32
+
33
+ // Never packed: version control, dependencies and build output (rebuilt in the
34
+ // sandbox), and files that usually hold credentials.
35
+ const EXCLUDED = new Set(['.git', '.raytace', '.raytrace', '.ssh', '.aws', '.azure', '.config', '.claude', 'node_modules', '.venv',
36
+ '__pycache__', '.next', '.vinext', 'dist', 'coverage', '.wrangler', '.DS_Store']);
37
+ const SECRET_NAMES = new Set([
38
+ '.npmrc', '.netrc', '.pypirc', '.htpasswd', '.dockercfg', 'credentials', 'credentials.json', 'credentials.ini',
39
+ 'auth.json', 'service-account.json', 'service_account.json', 'serviceAccountKey.json',
40
+ 'client_secret.json', 'client_secrets.json', 'token.json', 'id_rsa', 'id_dsa', 'id_ecdsa',
41
+ 'id_ed25519', 'id_ecdsa_sk', 'id_ed25519_sk', 'known_hosts',
42
+ ]);
43
+ const SECRET_EXTENSIONS = /\.(pem|key|p12|pfx)$/i;
44
+
45
+ export function packable(path) {
46
+ const parts = path.split('/');
47
+ const name = parts.at(-1);
48
+ const lower = name.toLowerCase();
49
+ return !parts.some((part) => EXCLUDED.has(part) || part === '..') && !path.startsWith('/')
50
+ && !lower.startsWith('.env') && !lower.startsWith('.secret')
51
+ && !SECRET_EXTENSIONS.test(name) && !SECRET_NAMES.has(lower);
52
+ }
53
+
54
+ /** The project's files git would track, minus what must not leave this machine. */
55
+ function projectFiles(root) {
56
+ const listed = spawnSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { maxBuffer: 256 * 1024 * 1024 });
57
+ if (listed.status !== 0) throw new Error(`${root} is not a Git repository. Run this from inside one.`);
58
+ const files = []; const skipped = []; const large = []; let total = 0;
59
+ for (const name of [...new Set(listed.stdout.toString().split('\0').filter(Boolean))].sort()) {
60
+ let stat;
61
+ try { stat = lstatSync(join(root, name)); } catch { continue; } // deleted, still in the index
62
+ if (!packable(name) || !stat.isFile()) { skipped.push(name); continue; } // symlinks too
63
+ if (stat.size > MAX_FILE) { large.push(`${name} (${Math.round(stat.size / MIB)} MiB)`); continue; }
64
+ total += stat.size;
65
+ files.push(name);
66
+ }
67
+ // Refused, never trimmed: a project missing its large files would not be the project.
68
+ if (large.length) {
69
+ throw new Error(`${large.length === 1 ? 'This file is' : 'These files are'} over ${MAX_FILE / MIB} MiB, the most one file may be:\n `
70
+ + `${large.slice(0, 10).join('\n ')}${large.length > 10 ? `\n ... and ${large.length - 10} more` : ''}\nAdd ${large.length === 1 ? 'it' : 'them'} to .gitignore (or remove ${large.length === 1 ? 'it' : 'them'}), then try again.`);
71
+ }
72
+ if (files.length > MAX_FILES) throw new Error(`The project has ${files.length.toLocaleString()} files; the most is ${MAX_FILES.toLocaleString()}. Add generated files to .gitignore first.`);
73
+ if (total > MAX_BYTES) throw new Error(`The project is ${Math.round(total / MIB)} MiB; the most is ${MAX_BYTES / MIB} MiB. Add large generated files to .gitignore first.`);
74
+ return { files, skipped, total };
75
+ }
76
+
77
+ function pack(root, files) {
78
+ return new Promise((resolve, reject) => {
79
+ // Extended attributes stay here: macOS tags nearly every file (com.apple.provenance),
80
+ // and bsdtar would also add AppleDouble files for them.
81
+ const mac = process.platform === 'darwin' ? ['--no-mac-metadata', '--no-xattrs'] : [];
82
+ const tar = spawn('tar', ['-czf', '-', ...mac, '--no-recursion', '--null', '-T', '-'],
83
+ { cwd: root, env: { ...process.env, COPYFILE_DISABLE: '1' }, stdio: ['pipe', 'pipe', 'pipe'] });
84
+ const chunks = []; let error = '';
85
+ tar.stdout.on('data', (chunk) => chunks.push(chunk));
86
+ tar.stderr.on('data', (chunk) => { error += chunk; });
87
+ tar.on('error', reject);
88
+ tar.on('close', (code) => code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`tar failed: ${error.trim()}`)));
89
+ tar.stdin.end(files.map((name) => `${name}\0`).join(''));
90
+ });
91
+ }
92
+
93
+ /** The signed-in workspace's cloud sandboxes, minus deleted ones. */
94
+ export async function liveSandboxes() {
95
+ return (await call('GET', '/v1/sandboxes')).filter((box) => box.status !== 'deleted');
96
+ }
97
+
98
+ export function checkId(id) {
99
+ if (!ID.test(id)) throw new Error(`Not a sandbox id: ${id}`);
100
+ return id;
101
+ }
102
+
103
+ async function pickId(id) {
104
+ if (id) return checkId(id);
105
+ const live = await liveSandboxes();
106
+ if (live.length === 1) return live[0].id;
107
+ throw new Error(live.length ? 'More than one sandbox; name one (raytrace sandbox list).'
108
+ : `No sandboxes${account() ? ` in ${account()}'s workspace` : ''} yet: raytrace sandbox create`);
109
+ }
110
+
111
+ /** The top of the Git repository holding `dir`, or null. */
112
+ export function repoRoot(dir = process.cwd()) {
113
+ const top = spawnSync('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });
114
+ return top.status === 0 ? top.stdout.trim() : null;
115
+ }
116
+
117
+ /** The files of the repository at `root` that may be uploaded, checked against the limits. */
118
+ export function listProject(root) {
119
+ const project = projectFiles(root);
120
+ if (!project.files.length) throw new Error('Nothing to upload.');
121
+ return project;
122
+ }
123
+
124
+ /** Pack listed files into the gzip archive a sandbox is created from. */
125
+ export async function packArchive(root, files) {
126
+ const archive = await pack(root, files);
127
+ 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.`);
128
+ return archive;
129
+ }
130
+
131
+ /** What beta credit does for the next cloud sandbox: 'use' it, it has
132
+ * 'expired' (unused, past its hard 3 days), or 'none'. Credit is consumed by
133
+ * the first cloud sandbox created after redemption. An older backend (or no
134
+ * entitlement) never blocks a plain one, so no answer means 'none'; the
135
+ * create call surfaces any real auth/network failure. */
136
+ export async function creditPlan() {
137
+ let beta;
138
+ try { beta = await betaStatus(); } catch { return { plan: 'none', beta: null }; }
139
+ const deadlinePassed = beta?.credit_expires_at && Date.parse(beta.credit_expires_at) <= Date.now();
140
+ if (beta && !beta.sandbox_consumed && deadlinePassed && (beta.entitled || beta.credit_usd)) return { plan: 'expired', beta };
141
+ if (beta?.entitled && !beta.sandbox_consumed) return { plan: 'use', beta };
142
+ return { plan: 'none', beta };
143
+ }
144
+
145
+ /** Create a cloud sandbox from a packed project. A credit refusal comes back
146
+ * as an ApiError (see isCreditRefusal) for the caller to decide on. */
147
+ export function upload(archive, name, useCredit) {
148
+ const headers = { 'content-type': 'application/gzip', 'x-raytrace-name': name.replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) };
149
+ return call('POST', '/v1/sandboxes', { body: archive, headers: useCredit ? { ...headers, 'x-raytrace-beta-credit': '1' } : headers });
150
+ }
151
+
152
+ /** The API refused the credit: 409 already used on another sandbox, 410 expired. */
153
+ export const isCreditRefusal = (error) => error instanceof ApiError && [409, 410].includes(error.status);
154
+
155
+ export async function create(flags) {
156
+ const root = repoRoot();
157
+ if (!root) throw new Error('Run this from inside a Git repository.');
158
+ const name = flags.name || basename(root);
159
+ // What the machine lacks is said before the project is read, and Lima fetched if agreed.
160
+ const localName = flags.local ? local.sandboxName(flags, root) : null;
161
+ if (flags.local) await local.preflight(flags, { confirm, interactive });
162
+ const { files, skipped, total } = listProject(root);
163
+ // The same files, packed the same way, as a cloud sandbox gets: only the copy stays here.
164
+ if (flags.local) return local.create(localName, { root, files, skipped, total, archive: await pack(root, files) });
165
+
166
+ // A local sandbox never uses beta credit.
167
+ const { plan, beta } = await creditPlan();
168
+ if (plan === 'expired') {
169
+ say('Your $10 beta credit has expired: the 3 days ran out, and unused credit does not carry over.');
170
+ if (!interactive()) throw new Error('Beta credit expired; no sandbox was created. Ask RayTrace for a new code to try again.');
171
+ if (!(await confirm('Create a plain sandbox without beta credit?', false))) { say('Not created.'); return; }
172
+ } else if (plan === 'use') {
173
+ say(`Using your $${beta.credit_usd ?? 10} beta credit (OpenRouter) on this sandbox`
174
+ + `${beta.credit_expires_at ? ` — credit ends ${formatCreditDeadline(beta.credit_expires_at)}` : ''}.`);
175
+ }
176
+ const useCredit = plan === 'use';
177
+ say(`Packing ${files.length} files (${(total / 1048576).toFixed(1)} MiB) from ${root}`);
178
+ if (skipped.length) say(`Not uploaded (${skipped.length}): ${skipped.slice(0, 8).join(', ')}${skipped.length > 8 ? ', ...' : ''}`);
179
+ const archive = await packArchive(root, files);
180
+ say('Creating the sandbox (the first one on a host takes a little longer)...');
181
+ let box;
182
+ try {
183
+ box = await upload(archive, name, useCredit);
184
+ } catch (error) {
185
+ if (!useCredit || !isCreditRefusal(error)) throw error;
186
+ say(error.status === 410 ? 'Your beta credit expired before the sandbox was created.'
187
+ : 'Your beta credit was already used on another sandbox.');
188
+ if (!interactive() || !(await confirm('Create a plain sandbox without beta credit?', false))) {
189
+ throw new Error('Beta credit not applied; no sandbox was created.');
190
+ }
191
+ box = await upload(archive, name, false);
192
+ }
193
+ say(`\nSandbox ${box.id} is running.`);
194
+ if (box.credit_applied) {
195
+ 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.`);
196
+ }
197
+ say(box.transcripts ? 'Claude Code sessions in it are recorded.'
198
+ : `Claude Code transcripts are off: ${box.transcripts_off}. Commands are still recorded.`);
199
+ say(`Open it: raytrace connect ${box.id}`);
200
+ }
201
+
202
+ export async function list(flags = {}) {
203
+ if (flags.local) return local.list();
204
+ const boxes = await liveSandboxes();
205
+ if (!boxes.length) { say('No sandboxes. Create one from a Git repository: raytrace sandbox create'); return; }
206
+ for (const box of boxes) {
207
+ // The sandbox's creation time (seconds), or its container's once that is known.
208
+ const created = typeof box.created === 'number' ? box.created * 1000 : Date.parse(box.created);
209
+ const age = Math.round((Date.now() - created) / 60000);
210
+ 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)}` : ''})` : ''}` : '';
211
+ say(`${box.id} ${String(box.status).padEnd(8)} ${box.name}${beta} (${age < 120 ? `${age} min` : `${Math.round(age / 60)} h`} old)`);
212
+ }
213
+ }
214
+
215
+ export async function start(id, flags = {}) {
216
+ if (flags.local || local.isLocal(id)) return local.start(id);
217
+ const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/start`); say(`${box.id} running`);
218
+ }
219
+ export async function stop(id, flags = {}) {
220
+ if (flags.local || local.isLocal(id)) return local.stop(id);
221
+ const box = await call('POST', `/v1/sandboxes/${await pickId(id)}/stop`); say(`${box.id} stopped; its files are kept`);
222
+ }
223
+
224
+ export async function destroy(id, flags) {
225
+ if (flags.local || local.isLocal(id)) return local.destroy(id, flags, { ask, interactive });
226
+ id = await pickId(id);
227
+ const me = await call('GET', '/v1/me').catch(() => ({}));
228
+ const plan = me.plan ?? {};
229
+ const paid = plan.plan && plan.plan !== 'beta';
230
+ let keep = Boolean(flags['keep-traces']);
231
+ if (!flags.yes) {
232
+ if (!interactive()) throw new Error('Pass --yes to destroy without a prompt (with --yes, traces are deleted unless --keep-traces is passed).');
233
+ say(`This deletes ${id}: its files, and any sign-in made inside it.`);
234
+ 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');
235
+ if ((await ask('Type the sandbox id to confirm: ')) !== id) { say('Not destroyed.'); return; }
236
+ if (paid && !keep) {
237
+ 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());
238
+ }
239
+ }
240
+ const result = await call('DELETE', `/v1/sandboxes/${id}${keep ? '?keep_traces=1' : ''}`);
241
+ say(`${id} destroyed.`);
242
+ if (result.traces_kept) say(`Its traces are kept until ${new Date(result.traces_kept_until * 1000).toLocaleDateString()}.`);
243
+ else if (result.traces_deleted === false) say('Note: its traces could not be deleted; they may still show on the dashboard.');
244
+ }
245
+
246
+ /** Exported for tests: the warning shown when connecting to a beta sandbox
247
+ * whose 3 days are up, or null. Model calls inside are refused by the
248
+ * backend; the sandbox itself still opens. */
249
+ export function betaExpiryWarning(beta, id, now = Date.now()) {
250
+ if (!beta || beta.credited_sandbox_id !== id) return null;
251
+ const deadline = beta.credit_expires_at ? Date.parse(beta.credit_expires_at) : NaN;
252
+ if (!beta.expired && !(deadline <= now)) return null;
253
+ return `Warning: your beta credit for this sandbox expired${beta.credit_expires_at ? ` (${formatCreditDeadline(beta.credit_expires_at, now)})` : ''}; `
254
+ + 'model calls in this sandbox will be refused. The sandbox itself still opens.';
255
+ }
256
+
257
+ /** An interactive terminal in the sandbox, carried over one upgraded HTTP request.
258
+ * `raytrace connect <id>` and `raytrace sandbox shell [id]` are the same thing. */
259
+ export async function shell(id, flags = {}) {
260
+ if (!interactive()) throw new Error('Connecting to a sandbox needs a terminal.');
261
+ // With no id and no cloud sign-in, the one local sandbox is the likely one.
262
+ if (flags.local || local.isLocal(id) || (!id && Object.keys(local.registry()).length && !account())) return local.shell(id, { agent: flags.agent });
263
+ id = await pickId(id);
264
+ try {
265
+ const warning = betaExpiryWarning(await betaStatus(), id);
266
+ if (warning) say(warning);
267
+ } catch { /* no beta answer: connecting must not depend on it */ }
268
+ const { url, key } = await api();
269
+ const { stdin, stdout } = process;
270
+ const path = `/v1/sandboxes/${id}/shell?rows=${stdout.rows || 24}&cols=${stdout.columns || 80}`;
271
+ await new Promise((resolve, reject) => {
272
+ const target = new URL(path, url);
273
+ const request = target.protocol === 'https:' ? httpsRequest : httpRequest;
274
+ const req = request(target, { headers: { authorization: `Bearer ${key}`, connection: 'Upgrade', upgrade: 'raytrace-shell' } });
275
+ req.on('response', (response) => {
276
+ let text = '';
277
+ response.on('data', (chunk) => { text += chunk; });
278
+ response.on('end', () => {
279
+ // The API does not say whether another account has this sandbox; the likely mix-up is worth naming.
280
+ if (response.statusCode === 404 && account()) {
281
+ return reject(new Error(`No sandbox ${id} in ${account()}'s workspace. If it was made under another account `
282
+ + '(for example in the dashboard), sign in as that one: raytrace auth login'));
283
+ }
284
+ try { reject(new Error(JSON.parse(text).error)); } catch { reject(new Error(`HTTP ${response.statusCode}`)); }
285
+ });
286
+ });
287
+ req.on('upgrade', (_response, socket, head) => {
288
+ const agent = AGENTS[flags.agent];
289
+ say(agent ? `Connected to ${id}, starting ${agent.name} without approval prompts (the sandbox is what contains it); when it exits you are in the sandbox's shell. The sandbox keeps running.\n`
290
+ : `Connected to ${id}. Run \`claude\` (or codex) here; exit to leave. The sandbox keeps running.\n`);
291
+ if (head.length) stdout.write(head);
292
+ // The API's shell takes no command: the agent is started by typing it, which the terminal holds until the shell reads it.
293
+ if (agent) socket.write(`${agent.command}\r`);
294
+ stdin.setRawMode(true);
295
+ stdin.resume();
296
+ stdin.pipe(socket);
297
+ socket.pipe(stdout);
298
+ const done = () => { stdin.unpipe(socket); stdin.setRawMode(false); stdin.pause(); resolve(); };
299
+ socket.on('close', done);
300
+ socket.on('error', done);
301
+ });
302
+ req.on('error', () => reject(unreachable(url)));
303
+ req.end();
304
+ });
305
+ say(`\nLeft ${id}. It is still running. Back in: raytrace connect ${id} Stop it: raytrace sandbox stop ${id}`);
306
+ }
@@ -0,0 +1,86 @@
1
+ // `raytrace share`: create, list, and revoke share links for recorded traces.
2
+ // Shares are time-limited links on https://app.raytracer.si/share/<token>.
3
+ import { call, ApiError } from './api.mjs';
4
+ import { liveSandboxes } from './sandbox.mjs';
5
+
6
+ const DASHBOARD = process.env.RAYTRACE_DASHBOARD_URL || 'https://app.raytracer.si';
7
+ const say = (line = '') => console.log(line);
8
+
9
+ export function formatTimeLeft(expiresEpoch) {
10
+ const leftSec = Math.round(expiresEpoch - Date.now() / 1000);
11
+ if (leftSec <= 0) return 'expired';
12
+ const min = Math.round(leftSec / 60);
13
+ if (min < 60) return `${min} min`;
14
+ const hr = Math.round(min / 60);
15
+ return `${hr} h`;
16
+ }
17
+
18
+ export async function sharePrompt(traceId, { sandboxId, allowFork = false } = {}) {
19
+ if (!traceId || !traceId.trim()) {
20
+ throw new Error('Trace ID is required. Usage: raytrace share <trace-id> [--sandbox <id>] [--fork]');
21
+ }
22
+ const cleanTrace = traceId.trim();
23
+
24
+ let targetSandbox = sandboxId?.trim();
25
+ if (!targetSandbox) {
26
+ const sandboxes = await liveSandboxes();
27
+ if (sandboxes.length === 1) {
28
+ targetSandbox = sandboxes[0].id;
29
+ } else if (sandboxes.length === 0) {
30
+ throw new Error('No live cloud sandboxes found. Create one first with: raytrace sandbox create');
31
+ } else {
32
+ throw new Error(`More than one cloud sandbox found. Specify which one with --sandbox <id>:\n ${sandboxes.map((s) => `${s.id} (${s.name})`).join('\n ')}`);
33
+ }
34
+ }
35
+
36
+ const result = await call('POST', '/v1/shares', {
37
+ body: {
38
+ trace_id: cleanTrace,
39
+ sandbox_id: targetSandbox,
40
+ allow_fork: Boolean(allowFork),
41
+ },
42
+ });
43
+
44
+ const fullUrl = `${DASHBOARD}${result.url}`;
45
+ const share = result.share;
46
+ say('Share link created:');
47
+ say(` ${fullUrl}`);
48
+ say();
49
+ say(`- Prompt: ${share.trace_id}`);
50
+ say(`- Sandbox: ${share.sandbox_id}`);
51
+ say(`- Forking: ${share.allow_fork ? 'allowed' : 'view only'}`);
52
+ say(`- Expires in: ${formatTimeLeft(share.expires)}`);
53
+ return { ...result, fullUrl };
54
+ }
55
+
56
+ export async function listShares() {
57
+ const result = await call('GET', '/v1/shares');
58
+ const shares = result.shares ?? [];
59
+ const tier = result.tier === 'enterprise' ? 'Team & Enterprise' : 'Individual';
60
+ say(`Active share links (${shares.length} of ${result.limit} on ${tier}):`);
61
+ if (!shares.length) {
62
+ say(' No active share links. Share a prompt with: raytrace share <trace-id>');
63
+ return result;
64
+ }
65
+ say();
66
+ for (const s of shares) {
67
+ const views = s.views?.length ?? 0;
68
+ const viewStr = views === 1 ? '1 view' : `${views} views`;
69
+ say(`- ${s.trace_id}: ${formatTimeLeft(s.expires)} remaining · ${s.allow_fork ? 'fork allowed' : 'view only'} · ${viewStr}`);
70
+ say(` Link: ${DASHBOARD}/share/${s.id}`);
71
+ say(` ID: ${s.id}`);
72
+ }
73
+ say();
74
+ say('Revoke a link at any time: raytrace share --revoke <id>');
75
+ return result;
76
+ }
77
+
78
+ export async function revokeShare(shareId) {
79
+ if (!shareId || !shareId.trim()) {
80
+ throw new Error('Share ID is required. Usage: raytrace share --revoke <id>');
81
+ }
82
+ const cleanId = shareId.trim();
83
+ await call('POST', `/v1/shares/${cleanId}/revoke`);
84
+ say(`Revoked share link ${cleanId}.`);
85
+ return { revoked: cleanId };
86
+ }