@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
@@ -0,0 +1,76 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { providerConfig, routeRequest, openrouterModels } from './providers.mjs';
4
+ import { codexArgs, TOKEN_ENV } from './codex-config.mjs';
5
+
6
+ const config = providerConfig({ RAYTACE_PROVIDER: 'openrouter', OPENROUTER_API_KEY: 'router-test' });
7
+ const request = { method: 'POST', url: '/v1/responses', headers: { authorization: 'Bearer native-secret', 'openai-organization': 'private-org', 'x-api-key': 'private-key' } };
8
+ const body = (model, extra = {}) => Buffer.from(JSON.stringify({ model, input: [], ...extra }));
9
+
10
+ test('all aliases and IDs route to the configured model with isolated credentials', () => {
11
+ for (const [alias, id] of Object.entries(openrouterModels)) for (const model of [alias, id]) {
12
+ const routed = routeRequest(config, request, body(model));
13
+ assert.equal(routed.payload.model, id);
14
+ assert.equal(routed.url, 'https://openrouter.ai/api/v1/responses');
15
+ assert.deepEqual(routed.headers, { 'content-type': 'application/json', authorization: 'Bearer router-test' });
16
+ assert.equal(JSON.parse(routed.body).model, id);
17
+ }
18
+ assert.equal(routeRequest(config, request, body('native-model')).payload.model, openrouterModels.coder);
19
+ const chat = routeRequest(config, { ...request, url: '/v1/chat/completions' }, body('flash', { messages: [] }));
20
+ assert.equal(chat.payload.model, openrouterModels.flash);
21
+ });
22
+
23
+ test('disabled configuration preserves native requests and Anthropic stays native', () => {
24
+ const native = providerConfig({ OPENROUTER_API_KEY: 'unused', RAYTACE_OPENROUTER_MODEL: 'flash' });
25
+ const input = body('native-model');
26
+ const routed = routeRequest(native, request, input);
27
+ assert.equal(routed.provider, 'openai');
28
+ assert.equal(routed.body, input);
29
+ assert.equal(routed.headers.authorization, 'Bearer native-secret');
30
+ assert.equal(routeRequest(config, { ...request, url: '/v1/messages' }, input).provider, 'anthropic');
31
+ });
32
+
33
+ test('invalid configuration and incompatible requests fail without provider fallback', () => {
34
+ assert.throws(() => providerConfig({ RAYTACE_PROVIDER: 'openrouter' }), /OPENROUTER_API_KEY/);
35
+ assert.throws(() => providerConfig({ RAYTACE_PROVIDER: 'typo' }), /native or openrouter/);
36
+ assert.throws(() => routeRequest(config, request, body('unlisted/expensive-model')), /not in/);
37
+ assert.throws(() => routeRequest(config, request, Buffer.from('invalid')), /JSON object/);
38
+ assert.throws(() => routeRequest(config, { ...request, url: '/v1/responses/compact' }, body('coder')), /supports POST/);
39
+ for (const extra of [{ store: true }, { previous_response_id: 'old' }, { conversation: 'old' }]) {
40
+ assert.throws(() => routeRequest(config, request, body('coder', extra)), /full conversation/);
41
+ }
42
+ });
43
+
44
+ test('custom model catalogs replace defaults and support aliases and full IDs', () => {
45
+ const custom = providerConfig({ RAYTACE_PROVIDER: 'openrouter', OPENROUTER_API_KEY: 'test',
46
+ RAYTACE_OPENROUTER_MODELS: '{"x":"example/model-x","y":"example/model-y"}' });
47
+ assert.equal(custom.defaultModel, 'example/model-x');
48
+ for (const model of ['y', 'example/model-y']) {
49
+ assert.equal(routeRequest(custom, request, body(model)).payload.model, 'example/model-y');
50
+ }
51
+ assert.throws(() => routeRequest(custom, request, body(openrouterModels.coder)), /not in/);
52
+ for (const catalog of ['invalid', '[]', '{}', 'null', '{"x":42}', '{"x":"missing-provider"}', '{"bad alias":"a/b"}']) {
53
+ assert.throws(() => providerConfig({ RAYTACE_PROVIDER: 'openrouter', OPENROUTER_API_KEY: 'test', RAYTACE_OPENROUTER_MODELS: catalog }), /RAYTACE_OPENROUTER_MODELS/);
54
+ }
55
+ assert.throws(() => providerConfig({ RAYTACE_PROVIDER: 'openrouter', OPENROUTER_API_KEY: 'test',
56
+ RAYTACE_OPENROUTER_MODELS: '{"x":"example/model-x"}', RAYTACE_OPENROUTER_MODEL: 'coder' }), /configured alias/);
57
+ assert.equal(providerConfig({ RAYTACE_OPENROUTER_MODELS: 'invalid' }).mode, 'native');
58
+ });
59
+
60
+ test('Codex launcher resolves model flags without injecting duplicate model flags', () => {
61
+ for (const flags of [['--model', 'deepseek'], ['-m', 'deepseek'], ['--model=deepseek'], ['-m=deepseek']]) {
62
+ const args = codexArgs(config, ['exec', ...flags, 'Fix login']);
63
+ assert.equal(args.filter((arg) => arg === '-m' || arg === '--model').length, 1);
64
+ assert.ok(args.includes(openrouterModels.deepseek));
65
+ assert.equal(args.at(-1), 'Fix login');
66
+ }
67
+ assert.throws(() => codexArgs(config, ['--model', 'typo']), /not in/);
68
+ assert.throws(() => codexArgs(config, ['--model']), /not in/);
69
+ assert.deepEqual(codexArgs(config, ['--', '--model=literal-prompt']).slice(-2), ['--', '--model=literal-prompt']);
70
+ const nativeArgs = ['--model', 'native-model'];
71
+ assert.deepEqual(codexArgs(providerConfig({}), nativeArgs), nativeArgs);
72
+ });
73
+
74
+ test('Codex is told where to find the local API token, never the token itself', () => {
75
+ assert.ok(codexArgs(config, ['exec']).includes(`model_providers.raytace_openrouter.env_key="${TOKEN_ENV}"`));
76
+ });
@@ -0,0 +1,135 @@
1
+ import { gzipSync } from 'node:zlib';
2
+ import test from 'node:test';
3
+ import assert from 'node:assert/strict';
4
+ import { createServer } from 'node:http';
5
+ import { spawn } from 'node:child_process';
6
+ import { once } from 'node:events';
7
+ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
8
+ import { readToken } from './local-token.mjs';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+
12
+ for (const mode of ['native', 'openrouter']) test(`${mode}: HTTP capture → async trials → persistence; streams/settings preserved and writes origin-gated`, { timeout: 20000 }, async (t) => {
13
+ const directory = await mkdtemp(join(tmpdir(),'raytace-trials-'));
14
+ t.after(() => rm(directory,{recursive:true,force:true}));
15
+ const received = [];
16
+ const upstream = createServer(async (req,res) => {
17
+ let body = ''; for await (const part of req) body += part;
18
+ const payload = JSON.parse(body); received.push({payload,authorization:req.headers.authorization,url:req.url,headers:req.headers});
19
+ const kept = Array.isArray(payload.input) && payload.input.some((item)=>item.content === 'Search result: auth.ts');
20
+ const result = { id:'fixture-response',status:'completed',output:[{type:'function_call',name:kept?'read_file':'search',arguments:kept?'{"path":"auth.ts"}':'{"query":"login"}'}] };
21
+ if (payload.instructions?.startsWith('You analyze a captured model action')) {
22
+ const source = JSON.parse(payload.input).earlier_context_excerpts[0];
23
+ result.output = [{ type: 'message', content: [{ type: 'output_text', text: JSON.stringify({hypotheses:[{evidence_id:source.evidence_id,title:'A context reference guided the action',explanation:'The prior context provided this reference.',excerpt:source.text.slice(0,40)}]}) }] }];
24
+ }
25
+ res.writeHead(200,{'content-type':'text/event-stream','content-encoding':'gzip'});
26
+ res.end(gzipSync(`event: response.completed\ndata: ${JSON.stringify({type:'response.completed',response:result})}\n\n`));
27
+ });
28
+ upstream.listen(0,'127.0.0.1'); await once(upstream,'listening');
29
+ t.after(()=>{upstream.closeAllConnections();upstream.close();});
30
+ async function launch() {
31
+ const child = spawn(process.execPath,['--disable-warning=ExperimentalWarning','proxy/raytace-proxy.mjs'],{env:{...process.env,RAYTACE_PORT:'0',RAYTACE_PROVIDER:mode,OPENROUTER_API_KEY:'router-secret',RAYTACE_OPENROUTER_MODEL:'coder',RAYTACE_OPENROUTER_UPSTREAM:`http://127.0.0.1:${upstream.address().port}/api`,RAYTACE_DATA_DIR:directory,RAYTACE_STORE:join(directory,'events.jsonl'),RAYTACE_OPENAI_UPSTREAM:`http://127.0.0.1:${upstream.address().port}`},stdio:['ignore','pipe','pipe']});
32
+ const exited = once(child,'exit');
33
+ t.after(async()=>{ if(child.exitCode===null)child.kill('SIGTERM'); await exited; });
34
+ const url = await new Promise((resolve,reject)=>{
35
+ child.stdout.on('data',(data)=>{const match=String(data).match(/http:\/\/127\.0\.0\.1:\d+/);if(match)resolve(match[0]);});
36
+ child.stderr.on('data',(data)=>reject(new Error(String(data))));
37
+ child.on('exit',(code)=>reject(new Error(`Proxy exited: ${code}`)));
38
+ });
39
+ return {child,exited,url};
40
+ }
41
+ const first = await launch();
42
+ const token = readToken(directory);
43
+ const fetch = (address,init={}) => globalThis.fetch(address,{...init,headers:{authorization:`Bearer ${token}`,...init.headers}});
44
+ // Nothing recorded, and no key, without the token or the session it signs in.
45
+ const outsider = {host:'127.0.0.1',authorization:''};
46
+ for (const path of ['/raytace/traces','/raytace/traces?scope=history','/raytace/prompt-context/x','/raytace/runtime?sandbox=x','/raytace/snapshots/rtp-00000000000000000000000000000000/files?commit=x','/raytace/models','/raytace/viewer/','/raytace/viewer/events']) {
47
+ assert.equal((await fetch(`${first.url}${path}`,{headers:outsider})).status,401,path);
48
+ }
49
+ assert.equal((await fetch(`${first.url}/raytace/version`,{headers:outsider})).status,200);
50
+ assert.equal((await stat(join(directory,'api-token'))).mode & 0o777,0o600);
51
+ assert.equal((await stat(directory)).mode & 0o777,0o700);
52
+ const {ticket} = await (await fetch(`${first.url}/raytace/session`,{method:'POST'})).json();
53
+ const signIn = await globalThis.fetch(`${first.url}/raytace/session?ticket=${ticket}`,{redirect:'manual'});
54
+ assert.equal(signIn.status,302);
55
+ const cookie = signIn.headers.get('set-cookie').split(';')[0];
56
+ assert.match(signIn.headers.get('set-cookie'),/HttpOnly; SameSite=Strict/);
57
+ assert.equal(cookie.includes(token),false);
58
+ assert.equal((await globalThis.fetch(`${first.url}/raytace/session?ticket=${ticket}`,{redirect:'manual'})).status,403);
59
+ assert.equal((await globalThis.fetch(`${first.url}/raytace/traces`,{headers:{cookie}})).status,200);
60
+ assert.equal((await globalThis.fetch(`${first.url}/raytace/traces`,{headers:{cookie,origin:'http://localhost:3000'}})).status,401);
61
+ if (mode==='openrouter') for (const headers of [{cookie},{authorization:'Bearer wrong'}]) {
62
+ assert.equal((await globalThis.fetch(`${first.url}/v1/responses`,{method:'POST',headers:{'content-type':'application/json',...headers},body:'{"model":"coder","input":[]}'})).status,401);
63
+ assert.equal(received.length,0);
64
+ }
65
+ const headers = {'content-type':'application/json','x-raytace-experiment':'1',origin:'http://localhost:3000'};
66
+ let res = await fetch(`${first.url}/raytace/experiments`,{method:'POST',headers:{...headers,origin:'https://untrusted.example'},body:'{}'});
67
+ assert.equal(res.status,403);
68
+ res = await fetch(`${first.url}/raytace/experiments`,{method:'POST',headers:{'content-type':'application/json'},body:'{}'});
69
+ assert.equal(res.status,403); assert.equal(received.length,0);
70
+ const payload = {model:'fixture-model',stream:true,reasoning:{effort:'medium'},tools:[{type:'function',name:'read_file'}],input:[{type:'message',role:'user',content:'Search result: auth.ts'},{type:'message',role:'user',content:'Fix login'}]};
71
+ res = await fetch(`${first.url}/v1/responses`,{method:'POST',headers:{'content-type':'application/json',...(mode==='native'?{authorization:'Bearer fixture-secret'}:{})},body:JSON.stringify(payload)});
72
+ assert.equal(res.status,200); assert.match(await res.text(),/response.completed/);
73
+ const traces = await fetch(`${first.url}/raytace/traces`).then((r)=>r.json());
74
+ const trace = traces.traces[0]; const snapshot = JSON.parse(trace.events[0].raw);
75
+ assert.equal(snapshot.replay_reason,null);assert.equal(trace.provider,mode === 'native' ? 'openai' : 'openrouter');
76
+ const config = {exchange_id:snapshot.exchange_id,evidence_id:trace.evidence[0].id,repetitions:2,target:{type:'tool_contains',name:'read_file',contains:'auth.ts'}};
77
+ res = await fetch(`${first.url}/raytace/experiments`,{method:'POST',headers,body:JSON.stringify(config)});
78
+ assert.equal(res.status,202); assert.equal(res.headers.get('access-control-allow-origin'),'http://localhost:3000');
79
+ let job = await res.json();
80
+ for (let i=0; i<100 && ['running','queued'].includes(job.status); i++) { await new Promise((resolve)=>setTimeout(resolve,20)); job=await fetch(`${first.url}/raytace/experiments/${job.id}`).then((r)=>r.json()); }
81
+ assert.equal(job.status,'completed'); assert.equal(job.trials.length,4);
82
+ assert.equal(job.summary.baseline.rate,1); assert.equal(job.summary.intervention.rate,0);
83
+ assert.equal(received.length,5);
84
+ for(const item of received) {assert.equal(item.payload.stream,true);assert.deepEqual(item.payload.reasoning,payload.reasoning);assert.equal(item.authorization,mode === 'native' ? 'Bearer fixture-secret' : 'Bearer router-secret');assert.equal(item.payload.model,mode === 'native' ? 'fixture-model' : 'qwen/qwen3-coder');assert.equal(item.url,mode === 'native' ? '/v1/responses' : '/api/v1/responses');}
85
+ // Persistence completes after the final progress update. Everything now lands
86
+ // in SQLite, so scan the database bytes directly: that also proves no
87
+ // credential reached disk through any table, blob, or journal.
88
+ const onDisk = async () => (await Promise.all(['evidence.db','evidence.db-wal','evidence.db-journal']
89
+ .map((name)=>readFile(join(directory,name),'utf8').catch(()=>'')))).join('');
90
+ let saved=''; for(let i=0;i<100;i++){saved=await onDisk();if(saved.includes('"status":"completed"'))break;await new Promise((r)=>setTimeout(r,20));}
91
+ assert.match(saved,/"status":"completed"/);
92
+ assert.equal(saved.includes('fixture-secret'),false);
93
+ assert.equal(saved.includes('router-secret'),false);
94
+ first.child.kill('SIGTERM'); await first.exited;
95
+ const second = await launch();
96
+ const archivedStepResponse = await fetch(`${second.url}/raytace/steps/${snapshot.exchange_id}/0`);
97
+ assert.equal(archivedStepResponse.status, 200);
98
+ const archivedStep = await archivedStepResponse.json();
99
+ assert.equal(archivedStep.decision.calls[0].name, 'read_file');
100
+ assert.ok(archivedStep.evidence.length > 0);
101
+ assert.match(archivedStep.replay_reason, /Saved log/);
102
+ assert.equal(received.length, 5); // Inspection never invokes a provider.
103
+ const history = await fetch(`${second.url}/raytace/experiments`).then((r)=>r.json());
104
+ assert.equal(history.experiments[0].status,'completed');
105
+ res=await fetch(`${second.url}/raytace/experiments`,{method:'POST',headers,body:JSON.stringify(config)});
106
+ assert.equal(res.status,409); assert.equal(received.length,5);
107
+ await fetch(`${second.url}/v1/responses`,{method:'POST',headers:{'content-type':'application/json',...(mode==='native'?{authorization:'Bearer fixture-secret'}:{})},body:JSON.stringify(payload)});
108
+ const fresh = await fetch(`${second.url}/raytace/traces`).then(r=>r.json());
109
+ assert.equal(fresh.traces.length,1);
110
+ const allRuns = await fetch(`${second.url}/raytace/traces?scope=history`).then(r=>r.json());
111
+ assert.equal(allRuns.traces.length,2);
112
+ assert.ok(allRuns.traces.some(t=>t.id===trace.id));
113
+ assert.ok(allRuns.traces.some(t=>t.id===fresh.traces[0].id));
114
+ assert.equal(received.length,6); // Reading history makes no upstream calls.
115
+ const selected = fresh.traces[0].events.find(event=>event.output_index === 0);
116
+ assert.ok(selected?.exchange_id);
117
+ const step = await fetch(`${second.url}/raytace/steps/${selected.exchange_id}/0`).then(r=>r.json());
118
+ assert.equal(step.decision.calls[0].name,'read_file');
119
+ res = await fetch(`${second.url}/raytace/step-runs`,{method:'POST',headers:{...headers,origin:'https://untrusted.example'},body:'{}'});
120
+ assert.equal(res.status,403);
121
+ res = await fetch(`${second.url}/raytace/step-runs`,{method:'POST',headers,body:JSON.stringify({exchange_id:selected.exchange_id,output_index:0,evidence_id:step.evidence[0].id,context:'No search result',model:mode === 'native' ? 'fixture-model' : 'coder',mode:'decision',repetitions:2,max_requests:1})});
122
+ assert.equal(res.status,202); let stepJob = await res.json();
123
+ for(let i=0;i<100 && ['queued','running'].includes(stepJob.status);i++){await new Promise(r=>setTimeout(r,20));stepJob=await fetch(`${second.url}/raytace/experiments/${stepJob.id}`).then(r=>r.json());}
124
+ assert.equal(stepJob.status,'completed');assert.equal(stepJob.summary.baseline.rate,1);assert.equal(stepJob.summary.intervention.rate,0);
125
+ if(mode === 'openrouter') {
126
+ const before = received.length;
127
+ const explain = () => fetch(`${second.url}/raytace/explanations`,{method:'POST',headers,body:JSON.stringify({exchange_id:selected.exchange_id,output_index:0})});
128
+ const generated = await explain(); assert.equal(generated.status,200); assert.equal((await generated.json()).hypotheses.length,1);
129
+ assert.equal((await explain()).status,200); assert.equal(received.length,before+1);
130
+ assert.equal(received.at(-1).payload.model,'qwen/qwen3-coder');
131
+ const reopened = await fetch(`${second.url}/raytace/steps/${selected.exchange_id}/0`).then(r=>r.json());
132
+ assert.equal(reopened.explanation_generated,true);assert.equal(reopened.hypotheses.length,1);
133
+ }
134
+
135
+ });
@@ -1,14 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { requestMetrics } from './request-metrics.mjs';
3
3
  import { redact, parseSseResponse } from './capture.mjs';
4
+ import { trustedOrigin as originAllowed, trustedRequest, hasToken, hasSession, sessionFor, sessionCookie, viewerTokenFor } from './request-policy.mjs';
5
+ import { ensureToken } from './local-token.mjs';
4
6
  /** Local API recorder. Point a compatible client at http://127.0.0.1:8797. */
5
7
  import { createServer } from 'node:http';
6
8
  import { appendFile, mkdir, readFile, stat } from 'node:fs/promises';
7
9
  import { realpathSync, readFileSync } from 'node:fs';
8
10
  import { homedir } from 'node:os';
9
- import { randomUUID, createHash } from 'node:crypto';
11
+ import { randomBytes, randomUUID, createHash } from 'node:crypto';
10
12
  import { join, dirname, resolve, extname, sep } from 'node:path';
11
- import { exchangesFromTranscript, parseTranscript } from './claude-code-adapter.mjs';
13
+ import { exchangesFromTranscript, parseTranscript, toolResultsFromTranscript } from './claude-code-adapter.mjs';
12
14
  import { replayEligibility, createExperiment, runExperiment } from './experiment-engine.mjs';
13
15
  import { loadEnvFile } from 'node:process';
14
16
  import { providerConfig, routeRequest, selectModel } from './providers.mjs';
@@ -41,7 +43,7 @@ const summaryModel = process.env.RAYTACE_SUMMARY_MODEL
41
43
  : (routing.models.oss || routing.defaultModel);
42
44
  // Bumped whenever the dashboard needs endpoints an older proxy lacks; the
43
45
  // CLI restarts a proxy it started that reports less (src/proxy-process.mjs).
44
- const PROXY_API = 2;
46
+ const PROXY_API = 4;
45
47
  const fallbackSession = { session_id: randomUUID(), session_started_at: new Date().toISOString() };
46
48
 
47
49
  const port = Number(process.env.RAYTACE_PORT || 8797);
@@ -51,6 +53,14 @@ const EVIDENCE_VIEWER = process.env.RAYTACE_EVIDENCE_VIEWER || 'http://127.0.0.1
51
53
  // The CLI sets RAYTACE_DATA_DIR (~/.raytrace); run by hand it keeps ./.raytace.
52
54
  const dataDir = process.env.RAYTACE_DATA_DIR || join(process.cwd(), '.raytace');
53
55
  const store = process.env.RAYTACE_STORE || join(dataDir, 'events.jsonl');
56
+ // Who may use the local API (local-token.mjs). `raytrace open` trades it for a
57
+ // one-time ticket, so the link it hands the browser is worth nothing afterwards.
58
+ const apiToken = ensureToken(dataDir);
59
+ const TICKET_MS = 2 * 60 * 1000;
60
+ const SESSION_SECONDS = 30 * 24 * 60 * 60;
61
+ const tickets = new Set();
62
+ const NOT_SIGNED_IN = { error: 'Not signed in to this RayTrace. Run: raytrace open', code: 'not_signed_in' };
63
+ const fromViewer = (url, init = {}) => fetch(url, { ...init, headers: { authorization: `Bearer ${viewerTokenFor(apiToken)}` } });
54
64
  // The local sandboxes (raytrace sandbox create --local): in place of raytace's sandbox manager.
55
65
  const sandboxes = localSandboxes({ dataDir });
56
66
  const NO_VM = `Local sandbox VM (${VM}) not reachable. Start a sandbox with: raytrace sandbox start <name>`;
@@ -62,11 +72,7 @@ const dbFile = process.env.RAYTACE_DB || join(dirname(store), 'evidence.db');
62
72
  const archiveJsonl = process.env.RAYTACE_ARCHIVE_JSONL === '1';
63
73
  const db = openEvidenceStore(dbFile);
64
74
  const allowedOrigins = new Set((process.env.RAYTACE_UI_ORIGINS || '').split(',').filter(Boolean));
65
- function trustedOrigin(origin) {
66
- if (!origin) return true;
67
- if (allowedOrigins.has(origin)) return true;
68
- try { const url = new URL(origin); return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname); } catch { return false; }
69
- }
75
+ const trustedOrigin = (origin) => originAllowed(origin, allowedOrigins);
70
76
  const hash = (value) => createHash('sha256').update(value).digest('hex');
71
77
  // Command severity (Jev). Without TYPESAFE_API_KEY, or when a request fails,
72
78
  // only the rule floor is shown -- and only where a rule actually fired.
@@ -310,11 +316,15 @@ function serially(path, job) {
310
316
  * transcript's own session, and ties its processes to them afterwards. */
311
317
  function ingestClaudeCode(path, { final, session = null }) {
312
318
  serially(path, async () => {
313
- const rows = exchangesFromTranscript(parseTranscript(await readFile(path, 'utf8')),
319
+ const lines = parseTranscript(await readFile(path, 'utf8'));
320
+ const rows = exchangesFromTranscript(lines,
314
321
  { final, sessionId: session?.id ?? null, sessionStartedAt: session?.startedAt ?? null });
315
322
  for (const row of rows) {
316
323
  await record({ ...row, request: { ...row.request, payload: redact(row.request.payload) }, response: { ...row.response, payload: redact(row.response.payload) } });
317
324
  }
325
+ for (const [callId, item] of toolResultsFromTranscript(lines)) {
326
+ db.recordToolResult?.(callId, item);
327
+ }
318
328
  if (session) await attributeLateProcesses(db, session.id);
319
329
  }).catch((error) => console.error(`Claude Code transcript ${path} could not be read: ${error.message}`));
320
330
  }
@@ -333,7 +343,7 @@ const playground = startPlayground({ db, transcriptsDir: sandboxTranscripts,
333
343
  hookSource: () => readFileSync(new URL('../worker/sandbox/claude-hook.mjs', import.meta.url), 'utf8') });
334
344
  async function appendSandboxTranscript(sandbox, note) {
335
345
  if (!CLAUDE_SESSION_ID.test(note?.session_id ?? '') || !Number.isInteger(note.offset) || note.offset < 0
336
- || typeof note.text !== 'string' || (note.text && !note.text.endsWith('\n'))) return { status: 400, body: { error: 'Expected session_id, offset and whole transcript lines.' } };
346
+ || typeof note.text !== 'string' || (note.more !== undefined && typeof note.more !== 'boolean')) return { status: 400, body: { error: 'Expected session_id, offset and a text fragment with optional more flag.' } };
337
347
  const directory = join(sandboxTranscripts, sandbox);
338
348
  const path = join(directory, `${note.session_id}.jsonl`);
339
349
  return serially(path, async () => {
@@ -397,25 +407,40 @@ async function ingestFromSandbox(sandbox, note) {
397
407
  try { db.recordSnapshot({ sessionId: filedUnder, agentSessionId: note.session_id, snapshot }); }
398
408
  catch (error) { console.error(`Snapshot for ${filedUnder} could not be recorded: ${error.message}`); }
399
409
  }
400
- if (written.path) ingestClaudeCode(written.path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name),
410
+ if (written.path) ingestClaudeCode(written.path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) && note.more !== true,
401
411
  session: { id: filedUnder, startedAt: fork ? fork.created_at : await sandboxes.createdAt(sandbox) } });
402
412
  return written;
403
413
  }
404
414
 
405
415
  const server = createServer(async (req, res) => {
416
+ // Guard every route before either dashboard assets or paid provider calls.
417
+ if (!trustedRequest(req, allowedOrigins)) {
418
+ res.writeHead(403); return res.end('Untrusted dashboard origin or host.');
419
+ }
406
420
  const fromAgent = req.headers.authorization || req.headers['x-api-key'] || req.headers['anthropic-version'];
407
421
  if (dashboardDir && req.method === 'GET' && !fromAgent && !req.url?.startsWith('/raytace/') && !req.url?.startsWith('/v1/')) {
408
422
  try { return await serveDashboard(req, res); }
409
423
  catch { res.writeHead(404); return res.end('Dashboard not built.'); }
410
424
  }
411
425
  const localApi = req.url?.startsWith('/raytace/');
412
- // Paid replay endpoints require a preflighted custom header and trusted origin.
413
- if (localApi && (!trustedOrigin(req.headers.origin) || !/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/.test(req.headers.host || ''))) {
414
- res.writeHead(403); return res.end('Untrusted dashboard origin or host.');
415
- }
416
- const corsHeaders = { ...(req.headers.origin && trustedOrigin(req.headers.origin) ? { 'access-control-allow-origin': req.headers.origin } : {}), vary: 'Origin', 'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS', 'access-control-allow-headers': 'content-type,x-raytace-experiment,if-none-match', 'access-control-allow-private-network': 'true' };
426
+ const corsHeaders = { ...(req.headers.origin && trustedOrigin(req.headers.origin) ? { 'access-control-allow-origin': req.headers.origin } : {}), vary: 'Origin', 'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS', 'access-control-allow-headers': 'authorization,content-type,x-raytace-experiment,if-none-match', 'access-control-allow-private-network': 'true' };
417
427
  const json = (status, value) => { res.writeHead(status, { 'content-type': 'application/json', ...corsHeaders, 'cache-control': 'no-store' }); res.end(JSON.stringify(redact(omitToolChunkIds(value)))); };
418
428
  if (req.method === 'OPTIONS') { res.writeHead(204, corsHeaders); return res.end(); }
429
+ const ticket = req.url?.match(/^\/raytace\/session\?ticket=([a-f0-9]{64})$/)?.[1];
430
+ if (req.method === 'GET' && ticket) {
431
+ if (!tickets.delete(ticket)) { res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }); return res.end('This link was used already, or has expired. Run: raytrace open\n'); }
432
+ res.writeHead(302, { location: '/', 'cache-control': 'no-store', 'set-cookie': `${sessionCookie(req.socket.localPort)}=${sessionFor(apiToken)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_SECONDS}` });
433
+ return res.end();
434
+ }
435
+ // Only the API version is public: the CLI and dashboard read it to spot an outdated proxy.
436
+ if (localApi && req.url !== '/raytace/version' && !hasToken(req, apiToken) && !hasSession(req, apiToken, req.socket.localPort)) return json(401, NOT_SIGNED_IN);
437
+ if (req.method === 'POST' && req.url === '/raytace/session') {
438
+ if (!hasToken(req, apiToken)) return json(401, NOT_SIGNED_IN);
439
+ const issued = randomBytes(32).toString('hex');
440
+ tickets.add(issued);
441
+ setTimeout(() => tickets.delete(issued), TICKET_MS).unref();
442
+ return json(201, { ticket: issued });
443
+ }
419
444
  // This machine's local sandboxes. With the VM stopped they are still listed,
420
445
  // from the CLI's records, as stopped. Prompt history comes from the traces.
421
446
  if (req.method === 'GET' && req.url === '/raytace/sandboxes') {
@@ -440,6 +465,17 @@ const server = createServer(async (req, res) => {
440
465
  if (req.method === 'GET' && req.url.startsWith('/raytace/alerts')) return json(200, { alerts: [] });
441
466
  return json(404, { error: 'Not available for local sandboxes yet. Destroy one with: raytrace sandbox destroy <name>' });
442
467
  }
468
+ // The collector's raw feed, behind this API's sign-in (worker/sandbox/viewer.py).
469
+ const feedRoute = req.url?.match(/^\/raytace\/viewer\/(events)?$/);
470
+ if (req.method === 'GET' && feedRoute) {
471
+ try {
472
+ const feed = await fromViewer(`${EVIDENCE_VIEWER}/${feedRoute[1] ?? ''}`, { signal: AbortSignal.timeout(10000) });
473
+ if (!feed.ok) throw new Error('Runtime collector unavailable');
474
+ if (feedRoute[1]) return json(200, await feed.json());
475
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
476
+ return res.end(await feed.text());
477
+ } catch { return json(503, { error: NO_VM }); }
478
+ }
443
479
  if (req.method === 'GET' && req.url?.startsWith('/raytace/runtime?')) {
444
480
  const query = new URL(req.url, 'http://localhost').searchParams;
445
481
  const sandbox = query.get('sandbox');
@@ -459,7 +495,7 @@ const server = createServer(async (req, res) => {
459
495
  // A windowed page wants everything in the window, not the newest 100:
460
496
  // folding turns hundreds of raw events into a handful of commands.
461
497
  const limit = since !== '0' || until !== '0' ? 500 : 100;
462
- const evidence = await fetch(`${EVIDENCE_VIEWER}/events?container=${project.container_id}&before=${before}${window}&limit=${limit}&processes=1`, { signal: AbortSignal.timeout(10000) });
498
+ const evidence = await fromViewer(`${EVIDENCE_VIEWER}/events?container=${project.container_id}&before=${before}${window}&limit=${limit}&processes=1`, { signal: AbortSignal.timeout(10000) });
463
499
  if (!evidence.ok) throw new Error('Runtime collector unavailable');
464
500
  const page = await evidence.json();
465
501
  const base = { ...page, sandbox, container_id: project.container_id };
@@ -644,7 +680,7 @@ const server = createServer(async (req, res) => {
644
680
  const path = claudeCodeTranscriptPath(note?.transcript_path);
645
681
  if (!path) return json(400, { error: 'transcript_path must be a Claude Code transcript under ~/.claude/projects.' });
646
682
  json(202, { accepted: true });
647
- ingestClaudeCode(path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) });
683
+ ingestClaudeCode(path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) && note.more !== true });
648
684
  return;
649
685
  }
650
686
  if (localApi && (req.method !== 'POST' || !['/raytace/experiments', '/raytace/step-runs','/raytace/explanations', '/raytace/attribution', '/raytace/summaries', '/raytace/prompt-context/summary', '/raytace/forks', '/raytace/recap'].includes(req.url))) return json(404, { error: 'Unknown local endpoint.' });
@@ -809,6 +845,9 @@ const server = createServer(async (req, res) => {
809
845
  let routed;
810
846
  try { routed = routeRequest(routing, req, requestBody); }
811
847
  catch (error) { return json(400, { error: error.message }); }
848
+ // OpenRouter runs on this proxy's own key; the other providers on the
849
+ // client's, which it brought with it.
850
+ if (routed.provider === 'openrouter' && !hasToken(req, apiToken)) return json(401, NOT_SIGNED_IN);
812
851
  const traceId = req.headers['x-raytace-trace-id'] || req.headers['x-request-id'] || randomUUID(); const started = new Date().toISOString(); const selectedProvider = routed.provider;
813
852
  const spanId = randomUUID();
814
853
  const sessionId = req.headers['x-raytace-session-id'];
@@ -868,6 +907,7 @@ server.listen(port, '127.0.0.1', () => {
868
907
  const gvisorForwarder = process.env.RAYTACE_GVISOR_FORWARDER === '0' ? null : startGvisorForwarder({
869
908
  listProjects: () => sandboxes.list(),
870
909
  viewerBase: EVIDENCE_VIEWER,
910
+ fetchImpl: fromViewer,
871
911
  ingest: (events, { sessionId }) => ingestExecutions(db, events, { sessionId }),
872
912
  // Exits, found by the process's own identity (pid + start time), so an
873
913
  // exit closes its process even after a proxy restart or for a process the
@@ -0,0 +1,19 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { requestMetrics } from './request-metrics.mjs';
4
+ const row = usage => ({ provider: 'openrouter', timestamp: '2026-09-10T00:00:00Z', completed_at: '2026-09-10T00:00:02Z', response: { payload: { usage } } });
5
+ test('normalizes provider usage, preserving free responses', () => {
6
+ assert.deepEqual(requestMetrics(row({ input_tokens: 100, output_tokens: 20, cost: 0 })), { input: 100, output: 20, cost: 0, durationMs: 2000 });
7
+ assert.equal(requestMetrics(row({ prompt_tokens: 50, completion_tokens: 10, cost: .01 })).input, 50);
8
+ });
9
+ test('unknown and previously redacted values never become zero', () => {
10
+ assert.deepEqual(requestMetrics({}), { input: null, output: null, cost: null, durationMs: null });
11
+ assert.equal(requestMetrics(row({ input_tokens: '[REDACTED]' })).input, null);
12
+ assert.equal(requestMetrics({ ...row({ cost: 5 }), provider: 'openai' }).cost, null);
13
+ });
14
+ test('uses terminal streaming usage rather than summing cumulative frames', () => {
15
+ const data = row({}); data.response.payload = { events: [{ usage: { prompt_tokens: 1 } }, { usage: { prompt_tokens: 10, cost: .2 } }] };
16
+ assert.equal(requestMetrics(data).input, 10);
17
+ data.response.payload = { events: [{ response: { usage: { input_tokens: 15 } } }] };
18
+ assert.equal(requestMetrics(data).input, 15);
19
+ });
@@ -0,0 +1,45 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+
3
+ /** Browser requests must satisfy the same policy before any local API or
4
+ * provider route runs. A CORS denial alone does not stop a simple POST from
5
+ * spending the proxy's configured provider key. */
6
+ export function trustedOrigin(origin, allowedOrigins = new Set()) {
7
+ if (!origin) return true; // Native CLI clients do not send Origin.
8
+ if (allowedOrigins.has(origin)) return true;
9
+ try {
10
+ const url = new URL(origin);
11
+ return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
12
+ } catch { return false; }
13
+ }
14
+
15
+ export function trustedRequest(req, allowedOrigins = new Set()) {
16
+ return trustedOrigin(req.headers.origin, allowedOrigins)
17
+ && /^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/.test(req.headers.host || '');
18
+ }
19
+
20
+ const digest = (value) => createHash('sha256').update(String(value)).digest();
21
+ const same = (a, b) => timingSafeEqual(digest(a), digest(b));
22
+
23
+ /** What the dashboard's browser holds in place of the token itself. */
24
+ export const sessionFor = (token) => digest(`dashboard:${token}`).toString('hex');
25
+ export const sessionCookie = (port) => `raytrace_session_${port}`;
26
+ /** What the sandbox VM's evidence viewer holds: one-way, so a copy in the VM opens only the viewer. */
27
+ export const viewerTokenFor = (token) => digest(`viewer:${token}`).toString('hex');
28
+
29
+ /** A client that read the token file: the CLI, the hook, `raytrace codex`. */
30
+ export function hasToken(req, token) {
31
+ const given = /^Bearer (.+)$/.exec(req.headers.authorization || '')?.[1];
32
+ return Boolean(given) && same(given, token);
33
+ }
34
+
35
+ /** The dashboard, in a browser `raytrace open` signed in. Cookies are shared
36
+ * between the ports of a host, so a page on another localhost port sends this
37
+ * one too: it counts only from this origin, and only on the local API
38
+ * (hasToken, not this, guards the provider routes). */
39
+ export function hasSession(req, token, port) {
40
+ const { origin, host, cookie } = req.headers;
41
+ if (origin && origin !== `http://${host}`) return false;
42
+ const name = `${sessionCookie(port)}=`;
43
+ const value = (cookie || '').split(/;\s*/).find((part) => part.startsWith(name))?.slice(name.length);
44
+ return Boolean(value) && same(value, sessionFor(token));
45
+ }
@@ -0,0 +1,47 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { hasSession, hasToken, sessionCookie, sessionFor, trustedRequest, viewerTokenFor } from './request-policy.mjs';
4
+
5
+ const request = (url, headers) => ({method: 'POST', url, headers: {host: '127.0.0.1:8797', ...headers}});
6
+ test('simple browser POSTs from untrusted origins are refused on provider and dashboard routes', () => {
7
+ for (const url of ['/v1/responses', '/v1/chat/completions', '/v1/messages', '/raytace/experiments']) {
8
+ assert.equal(trustedRequest(request(url, {origin: 'http://untrusted.invalid', 'content-type': 'text/plain'})), false);
9
+ assert.equal(trustedRequest(request(url, {origin: 'null'})), false);
10
+ }
11
+ });
12
+ test('provider requests reject non-loopback Host values, including rebinding names', () => {
13
+ for (const host of ['untrusted.invalid:8797', 'localhost.untrusted.invalid:8797', '192.0.2.1:8797', '']) {
14
+ assert.equal(trustedRequest(request('/v1/responses', {host})), false);
15
+ }
16
+ });
17
+ test('native clients and local dashboards retain access', () => {
18
+ for (const host of ['127.0.0.1:8797', 'localhost:8797', '[::1]:8797']) {
19
+ assert.equal(trustedRequest(request('/v1/responses', {host})), true);
20
+ assert.equal(trustedRequest(request('/raytace/traces', {host, origin: 'http://localhost:3000'})), true);
21
+ }
22
+ });
23
+ test('explicit UI origin permissions do not permit a non-loopback Host', () => {
24
+ const origins = new Set(['https://dashboard.example']);
25
+ assert.equal(trustedRequest(request('/v1/responses', {origin: 'https://dashboard.example'}), origins), true);
26
+ assert.equal(trustedRequest(request('/v1/responses', {host: 'untrusted.invalid', origin: 'https://dashboard.example'}), origins), false);
27
+ });
28
+ test('only the token file\'s value authorizes a client, whatever Origin and Host it sends', () => {
29
+ const headers = (authorization) => ({headers: {authorization}});
30
+ assert.equal(hasToken(headers('Bearer right'), 'right'), true);
31
+ for (const value of ['Bearer wrong', 'Bearer ', 'right', undefined]) assert.equal(hasToken(headers(value), 'right'), false);
32
+ });
33
+ test('the dashboard cookie counts only from the dashboard\'s own origin', () => {
34
+ const cookie = `other=1; ${sessionCookie(8797)}=${sessionFor('right')}`;
35
+ const seen = (headers) => hasSession({headers: {host: '127.0.0.1:8797', ...headers}}, 'right', 8797);
36
+ assert.equal(seen({cookie}), true);
37
+ assert.equal(seen({cookie, origin: 'http://127.0.0.1:8797'}), true);
38
+ assert.equal(seen({cookie, origin: 'http://127.0.0.1:3000'}), false);
39
+ assert.equal(seen({cookie: `${sessionCookie(8797)}=right`}), false);
40
+ assert.equal(seen({}), false);
41
+ assert.equal(hasSession({headers: {host: '127.0.0.1:18797', cookie}}, 'right', 18797), false);
42
+ });
43
+ test('the VM\'s viewer token is neither the API token nor the dashboard session', () => {
44
+ assert.notEqual(viewerTokenFor('right'), 'right');
45
+ assert.notEqual(viewerTokenFor('right'), sessionFor('right'));
46
+ assert.equal(hasToken({headers: {authorization: `Bearer ${viewerTokenFor('right')}`}}, 'right'), false);
47
+ });
@@ -28,6 +28,9 @@ export function startSandboxBridge({ dataDir, port, ingest }) {
28
28
 
29
29
  const server = createServer(async (req, res) => {
30
30
  const json = (status, body) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
31
+ if (req.method === 'GET' && req.url === '/raytace/identity') {
32
+ return json(200, { service: 'raytrace-bridge', version: 1 });
33
+ }
31
34
  if (req.method !== 'POST' || req.url !== '/raytace/ingest/claude-code') return json(404, { error: 'Unknown endpoint.' });
32
35
  const sandbox = await sandboxFor(req.headers['x-raytace-sandbox-token']);
33
36
  if (!sandbox) return json(403, { error: 'Unknown sandbox token.' });