raytrace-cli 0.11.1__py3-none-win_arm64.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,285 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { accessSync, constants, existsSync, mkdirSync, rmSync, statSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { delimiter, join } from 'node:path';
5
+ import { install, paths } from './paths.mjs';
6
+ import { portOf, proxyEnv, readConfig, writeConfig } from './config.mjs';
7
+ import { checkRunningPid, dashboardLink, healthy, portInUse, PROXY_API, proxyApi, runningPid, start, status, stop } from './proxy-process.mjs';
8
+ import { HOOK_COMMAND, hookState, setHook } from './claude-code.mjs';
9
+ import { askSecret, confirm, interactive } from './prompt.mjs';
10
+
11
+ const say = (line = '') => console.log(line);
12
+ const CLOUD_URL = 'https://app.raytracer.si';
13
+
14
+ /** Whether `name` resolves on PATH: the Claude Code hook calls `raytrace` by name. */
15
+ function onPath(name) {
16
+ const exts = process.platform === 'win32' ? ['.cmd', '.exe', ''] : [''];
17
+ return (process.env.PATH || '').split(delimiter).some((dir) => exts.some((ext) => {
18
+ try { accessSync(join(dir, name + ext), constants.X_OK); return true; } catch { return false; }
19
+ }));
20
+ }
21
+
22
+ function openUrl(url) {
23
+ const [command, args] = process.platform === 'darwin' ? ['open', [url]]
24
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
25
+ spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => say(`Open ${url} in your browser.`)).unref();
26
+ }
27
+
28
+ const claudeCodePresent = () => onPath('claude') || existsSync(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'));
29
+
30
+ // ------------------------------------------------------------------ setup
31
+
32
+ export async function setup(flags) {
33
+ const yes = flags.yes || !interactive();
34
+ mkdirSync(paths.home, { recursive: true });
35
+ const config = readConfig();
36
+ say(`RayTrace setup. Settings go in ${paths.config}.\n`);
37
+
38
+ // Claude Code: recorded through its hook, no proxy routing needed.
39
+ const hooks = hookState();
40
+ let hookClaude = !flags['no-claude-code'];
41
+ if (hookClaude && !yes) hookClaude = await confirm(hooks.installed ? 'Keep recording Claude Code sessions?' : 'Record Claude Code sessions?', true);
42
+ else if (hookClaude && !claudeCodePresent()) hookClaude = false;
43
+ if (hookClaude) { const file = setHook(); say(` Claude Code: hook ${hooks.installed ? 'kept' : 'added'} in ${file}`); }
44
+ else if (hooks.installed) { setHook({ remove: true }); say(' Claude Code: hook removed'); }
45
+ else say(' Claude Code: not recorded');
46
+ if (hooks.repoHook) say(' Note: the RayTrace repo\'s own Claude Code hook is also installed; sessions will be reported by both.');
47
+
48
+ // Setup never asks for an OpenRouter key: recording needs none. A key passed
49
+ // with --openrouter-key (or already saved) turns on local step summaries and
50
+ // `raytrace codex`; without one the proxy runs native and those are off.
51
+ const openrouter = flags['openrouter-key'] ?? config.OPENROUTER_API_KEY ?? '';
52
+ writeConfig({
53
+ ...config,
54
+ RAYTACE_PROVIDER: openrouter ? 'openrouter' : 'native',
55
+ OPENROUTER_API_KEY: openrouter,
56
+ });
57
+ say(`\n Settings saved (only you can read ${paths.config}).`);
58
+ say('\n Cloud sandboxes (preview): run your agent on RayTrace\'s servers, no API key to add.');
59
+ say(` raytrace auth login, then in a Git repository: raytrace sandbox create (or on the web: ${CLOUD_URL})`);
60
+
61
+ if (hookClaude && !onPath('raytrace')) {
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: ${install.add}`);
64
+ }
65
+
66
+ // A proxy this CLI started is restarted so the new settings apply.
67
+ const port = portOf(readConfig());
68
+ if (runningPid()) { await stop(); say('\nRestarting RayTrace with the new settings.'); await startCommand(); return; }
69
+ if (await healthy(port)) { say(`\nA RayTrace proxy started outside this CLI is answering on :${port}; stop it to use these settings.`); return; }
70
+ if (flags['no-start'] || (!yes && !(await confirm('\nStart RayTrace now?', true)))) { say('\nRun `raytrace start` when you are ready.'); return; }
71
+ await startCommand({ open: !yes });
72
+ }
73
+
74
+ // --------------------------------------------------------- start / stop / status
75
+
76
+ export async function startCommand({ open = false } = {}) {
77
+ const result = await start();
78
+ const url = `http://127.0.0.1:${result.port}`;
79
+ say(result.replaced ? `RayTrace restarted with this version (an older one was running): ${url}`
80
+ : result.started ? `RayTrace is running: ${url}` : `RayTrace was already running: ${url}`);
81
+ if (!result.started && !result.pid) say(' (started outside this CLI, e.g. from the RayTrace repo; `raytrace stop` will not stop it)');
82
+ say(` Logs: ${paths.proxyLog}`);
83
+ if (open) openUrl(await dashboardLink(result.port));
84
+ else say(' Open the dashboard with: raytrace open');
85
+ }
86
+
87
+ export async function stopCommand() {
88
+ const result = await stop();
89
+ if (result.stopped) say(`RayTrace stopped (pid ${result.pid}).`);
90
+ else if (result.foreign) say(`A RayTrace proxy not started by this CLI is answering on :${result.port}. Stop it where it was started.`);
91
+ else say('RayTrace is not running.');
92
+ }
93
+
94
+ export async function statusCommand() {
95
+ const state = await status();
96
+ const hooks = hookState();
97
+ say(`proxy ${state.healthy ? `running ${state.url}${state.pid ? ` (pid ${state.pid})` : ' (started outside this CLI)'}` : state.pid ? `pid ${state.pid}, not answering` : 'stopped'}`);
98
+ say(`claude code ${hooks.installed ? 'recording' : 'not recorded (raytrace setup)'}`);
99
+ say(`data ${paths.home}`);
100
+ }
101
+
102
+ export async function openCommand() {
103
+ const state = await status();
104
+ if (!state.healthy) { say('RayTrace is not running. Start it with `raytrace start`.'); process.exitCode = 1; return; }
105
+ if (state.pid && await proxyApi(state.port) < PROXY_API) await start();
106
+ openUrl(await dashboardLink(state.port));
107
+ say(`Opening ${state.url}`);
108
+ }
109
+
110
+ // ------------------------------------------------------------------ keys
111
+
112
+ // The keys the dashboard's AI features run on: the user's own, kept in
113
+ // config.env (readable only by them) and used only by the proxy here.
114
+ const KEYS = {
115
+ openrouter: { name: 'OPENROUTER_API_KEY', label: 'OpenRouter', where: 'https://openrouter.ai/keys',
116
+ turnsOn: 'step summaries, command descriptions, run recaps and Chain of thought, and `raytrace codex`',
117
+ models: 'Qwen3 Coder (Chain of thought), gpt-oss-120b (summaries), Claude Sonnet 5.5 (recaps)' },
118
+ typesafe: { name: 'TYPESAFE_API_KEY', label: 'TypeSafe (Jev)', where: 'your TypeSafe account',
119
+ turnsOn: 'ranking Chain of thought\'s causes and rating each command\'s severity' },
120
+ };
121
+ const masked = (value) => (value ? `set (…${value.slice(-4)})` : 'not set');
122
+
123
+ /**
124
+ * `raytrace key` lists the keys; `raytrace key <openrouter|typesafe>` asks for
125
+ * one (typed without echo, or piped in) and saves it; `--remove` deletes it.
126
+ * The key is never taken as an argument, so it stays out of shell history.
127
+ */
128
+ export async function keyCommand(which, flags) {
129
+ const config = readConfig();
130
+ if (!which) {
131
+ for (const [id, key] of Object.entries(KEYS)) say(`${id.padEnd(11)} ${masked(config[key.name])} ${key.turnsOn}`);
132
+ say('\nAdd one: raytrace key openrouter (or typesafe). Remove one: raytrace key openrouter --remove');
133
+ return;
134
+ }
135
+ const key = KEYS[which];
136
+ if (!key) throw new Error(`Unknown key "${which}". Use: raytrace key openrouter | typesafe`);
137
+ let value = '';
138
+ if (!flags.remove) {
139
+ if (interactive()) {
140
+ say(`Your ${key.label} key turns on ${key.turnsOn}. Get one at ${key.where}.`);
141
+ if (key.models) say(`Calls are made on your key and billed to you; models: ${key.models}.`);
142
+ value = await askSecret(`${key.label} key: `);
143
+ } else {
144
+ const chunks = [];
145
+ for await (const chunk of process.stdin) chunks.push(chunk);
146
+ value = Buffer.concat(chunks).toString('utf8').trim();
147
+ }
148
+ if (!value) throw new Error('No key given; nothing changed.');
149
+ if (/\s/.test(value)) throw new Error('That does not look like a key (it has spaces); nothing changed.');
150
+ }
151
+ const next = { ...config, [key.name]: value };
152
+ if (which === 'openrouter') next.RAYTACE_PROVIDER = value ? 'openrouter' : 'native';
153
+ writeConfig(next);
154
+ say(value ? `${key.label} key saved in ${paths.config} (only you can read it).` : `${key.label} key removed.`);
155
+ // A proxy this CLI started is restarted so the key applies.
156
+ if (runningPid()) { await stop(); await start(); say('RayTrace restarted with it.'); }
157
+ else if (await healthy(portOf(readConfig()))) say('A RayTrace proxy started outside this CLI is running; restart it to use this.');
158
+ }
159
+
160
+ // ------------------------------------------------------------------ doctor
161
+
162
+ export async function doctor() {
163
+ let problems = 0;
164
+ const line = (ok, label, detail) => { if (ok === false) problems += 1; say(`${ok === false ? '✗' : ok === null ? '·' : '✓'} ${label.padEnd(22)} ${detail}`); };
165
+ let config;
166
+ try { config = readConfig(); } catch (err) { config = {}; line(false, 'settings', `malformed config: ${err.message}`); }
167
+ const port = portOf(config);
168
+
169
+ line(true, 'node', process.version);
170
+ if (!existsSync(paths.config)) line(false, 'settings', `missing; run \`raytrace setup\``);
171
+ else {
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
+ }
178
+ }
179
+ line(existsSync(paths.dashboard) ? true : false, 'dashboard', existsSync(paths.dashboard) ? 'built' : `missing from ${paths.dashboard}; reinstall`);
180
+ line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : `no: Claude Code's hook cannot run it (${install.add})`);
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
+ }
200
+
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)');
202
+
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
+
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');
226
+
227
+ // Local sandboxes are optional: what they lack is shown, not counted as a problem.
228
+ say('\nLocal sandboxes (raytrace sandbox create --local):');
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
+ }
241
+
242
+ say(problems ? `\n${problems} problem${problems === 1 ? '' : 's'} found.` : '\nNo problems found.');
243
+ if (problems) process.exitCode = 1;
244
+ }
245
+
246
+ // ------------------------------------------------------------------ codex
247
+
248
+ export async function codex(args) {
249
+ const config = readConfig();
250
+ if (!config.OPENROUTER_API_KEY) { say('`raytrace codex` routes Codex through OpenRouter. Add a key first: raytrace setup --openrouter-key <key>'); process.exitCode = 1; return; }
251
+ if (!(await healthy(portOf(config)))) await startCommand();
252
+ const child = spawn(process.execPath, [paths.codex, ...args], { stdio: 'inherit', env: proxyEnv(config) });
253
+ await new Promise((done) => child.on('exit', (code, signal) => { process.exitCode = code ?? (signal ? 1 : 0); done(); }));
254
+ }
255
+
256
+ // ------------------------------------------------------------------ hook
257
+
258
+ /** Called by Claude Code on each hook event; must stay fast and silent. */
259
+ export async function hook(agent) {
260
+ if (agent !== 'claude-code') return;
261
+ try { process.env.RAYTACE_PORT = String(portOf(readConfig())); } catch { /* default port */ }
262
+ await import(paths.hook);
263
+ }
264
+
265
+ // ------------------------------------------------------------------ uninstall
266
+
267
+ export async function uninstall(flags) {
268
+ const yes = flags.yes || !interactive();
269
+ const stopped = await stop();
270
+ if (stopped.stopped) say('Stopped RayTrace.');
271
+ if (hookState().installed) say(`Removed the Claude Code hook from ${setHook({ remove: true })}.`);
272
+ if (existsSync(paths.home)) {
273
+ const purge = flags.purge || (!yes && await confirm(`Delete ${paths.home} (recorded sessions and settings)?`, false));
274
+ if (purge) {
275
+ // Before the folder goes: the Lima that RayTrace downloaded, which removes the VM, is in it.
276
+ const { deleteVm } = await import('./local-sandbox.mjs');
277
+ try { if (deleteVm()) say('Deleted the local sandbox VM (raytrace) and its sandboxes.'); }
278
+ catch (error) { say(`The local sandbox VM was not deleted (${error.message.split('\n')[0]}); limactl delete --force raytrace removes it.`); }
279
+ rmSync(paths.home, { recursive: true, force: true });
280
+ say(`Deleted ${paths.home}.`);
281
+ }
282
+ else say(`Kept ${paths.home}.`);
283
+ }
284
+ say(`To remove the command itself: ${install.remove}`);
285
+ }
@@ -0,0 +1,49 @@
1
+ // ~/.raytrace/config.env: the same KEY=value settings the proxy has always
2
+ // read from .env, kept in one place readable only by the user since it holds
3
+ // API keys.
4
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { parseEnv } from 'node:util';
6
+ import { DEFAULT_PORT, paths } from './paths.mjs';
7
+
8
+ export function readConfig() {
9
+ if (!existsSync(paths.config)) return {};
10
+ return parseEnv(readFileSync(paths.config, 'utf8'));
11
+ }
12
+
13
+ export function writeConfig(values) {
14
+ const entries = Object.entries(values)
15
+ .filter(([, value]) => value !== undefined && value !== '')
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 });
27
+ chmodSync(paths.config, 0o600); // the mode above only applies when the file is new
28
+ }
29
+
30
+ // Choose a delimiter absent from the value. Backslash does not escape a
31
+ // delimiter in parseEnv; double quotes also expand literal backslash-n.
32
+ function quote(value) {
33
+ if (!/[\s#"'`]/.test(value)) return value;
34
+ const delimiter = ["'", '`', '"'].find((candidate) => !value.includes(candidate));
35
+ return delimiter ? `${delimiter}${value}${delimiter}` : value;
36
+ }
37
+
38
+ export const portOf = (config) => Number(config.RAYTACE_PORT || DEFAULT_PORT);
39
+
40
+ /** The environment the proxy and the Codex launcher run with. */
41
+ export function proxyEnv(config = readConfig()) {
42
+ return {
43
+ ...process.env,
44
+ ...config,
45
+ RAYTACE_PORT: String(portOf(config)),
46
+ RAYTACE_DATA_DIR: paths.home,
47
+ RAYTACE_DASHBOARD_DIR: paths.dashboard,
48
+ };
49
+ }
@@ -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
+ }