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.
- raytrace/__init__.py +1 -0
- raytrace/__main__.py +33 -0
- raytrace/app/LICENSE +21 -0
- raytrace/app/README.md +599 -0
- raytrace/app/bin/raytrace.mjs +297 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
- raytrace/app/dist/dashboard/assets/index-DepcI8Fi.js +38 -0
- raytrace/app/dist/dashboard/assets/index-H97VLD5l.css +1 -0
- raytrace/app/dist/dashboard/favicon.svg +6 -0
- raytrace/app/dist/dashboard/index.html +15 -0
- raytrace/app/package.json +48 -0
- raytrace/app/proxy/agent-intent-schema.test.mjs +142 -0
- raytrace/app/proxy/call-assessment.mjs +385 -0
- raytrace/app/proxy/call-assessment.test.mjs +167 -0
- raytrace/app/proxy/call-category.mjs +461 -0
- raytrace/app/proxy/capture-health.mjs +30 -0
- raytrace/app/proxy/capture-health.test.mjs +44 -0
- raytrace/app/proxy/capture.mjs +38 -0
- raytrace/app/proxy/capture.test.mjs +49 -0
- raytrace/app/proxy/claude-code-adapter.mjs +301 -0
- raytrace/app/proxy/claude-code-hook.mjs +22 -0
- raytrace/app/proxy/codex-config.mjs +36 -0
- raytrace/app/proxy/codex.mjs +14 -0
- raytrace/app/proxy/evidence-schema.test.mjs +240 -0
- raytrace/app/proxy/evidence-store.mjs +993 -0
- raytrace/app/proxy/evidence-store.test.mjs +301 -0
- raytrace/app/proxy/exec-narrative.mjs +625 -0
- raytrace/app/proxy/exec-narrative.test.mjs +262 -0
- raytrace/app/proxy/execution-correlation.mjs +185 -0
- raytrace/app/proxy/execution-correlation.test.mjs +146 -0
- raytrace/app/proxy/execution-runner.mjs +89 -0
- raytrace/app/proxy/execution-runner.test.mjs +38 -0
- raytrace/app/proxy/experiment-engine.mjs +195 -0
- raytrace/app/proxy/experiment-engine.test.mjs +93 -0
- raytrace/app/proxy/explanations.mjs +36 -0
- raytrace/app/proxy/explanations.test.mjs +20 -0
- raytrace/app/proxy/failure-signature.mjs +56 -0
- raytrace/app/proxy/gvisor-forwarder.mjs +493 -0
- raytrace/app/proxy/gvisor-forwarder.test.mjs +433 -0
- raytrace/app/proxy/init-evidence-db.mjs +227 -0
- raytrace/app/proxy/local-sandboxes.mjs +94 -0
- raytrace/app/proxy/local-token.mjs +30 -0
- raytrace/app/proxy/playground-recovery.test.mjs +130 -0
- raytrace/app/proxy/playground.mjs +439 -0
- raytrace/app/proxy/prompt-context.mjs +278 -0
- raytrace/app/proxy/prompt-traces.mjs +40 -0
- raytrace/app/proxy/prompt-traces.test.mjs +32 -0
- raytrace/app/proxy/providers.mjs +65 -0
- raytrace/app/proxy/providers.test.mjs +76 -0
- raytrace/app/proxy/proxy.integration.test.mjs +135 -0
- raytrace/app/proxy/raytace-proxy.mjs +941 -0
- raytrace/app/proxy/request-metrics.mjs +13 -0
- raytrace/app/proxy/request-metrics.test.mjs +19 -0
- raytrace/app/proxy/request-policy.mjs +45 -0
- raytrace/app/proxy/request-policy.test.mjs +47 -0
- raytrace/app/proxy/run-recap.mjs +139 -0
- raytrace/app/proxy/runtime-attribution.mjs +110 -0
- raytrace/app/proxy/sandbox-bridge.mjs +49 -0
- raytrace/app/proxy/schema/EVIDENCE_DATABASE.md +276 -0
- raytrace/app/proxy/schema/agent_intent.sql +101 -0
- raytrace/app/proxy/schema/auxiliary.sql +90 -0
- raytrace/app/proxy/schema/capture_health.sql +14 -0
- raytrace/app/proxy/schema/classification.sql +89 -0
- raytrace/app/proxy/schema/file_context.sql +53 -0
- raytrace/app/proxy/schema/runtime_evidence.sql +201 -0
- raytrace/app/proxy/schema/search.sql +66 -0
- raytrace/app/proxy/schema/shared_storage.sql +21 -0
- raytrace/app/proxy/search.mjs +418 -0
- raytrace/app/proxy/search.test.mjs +161 -0
- raytrace/app/proxy/smoke.test.mjs +93 -0
- raytrace/app/proxy/step-attribution.mjs +380 -0
- raytrace/app/proxy/step-lab.mjs +78 -0
- raytrace/app/proxy/step-lab.test.mjs +38 -0
- raytrace/app/proxy/summaries.mjs +151 -0
- raytrace/app/proxy/summaries.test.mjs +69 -0
- raytrace/app/proxy/tool-metadata.mjs +111 -0
- raytrace/app/proxy/tool-metadata.test.mjs +38 -0
- raytrace/app/proxy/trace-view.mjs +324 -0
- raytrace/app/proxy/trace-view.test.mjs +92 -0
- raytrace/app/proxy/typesafe.mjs +63 -0
- raytrace/app/proxy/typesafe.test.mjs +39 -0
- raytrace/app/src/agents.mjs +7 -0
- raytrace/app/src/api.mjs +57 -0
- raytrace/app/src/auth.mjs +205 -0
- raytrace/app/src/beta.mjs +96 -0
- raytrace/app/src/claude-code.mjs +93 -0
- raytrace/app/src/commands.mjs +285 -0
- raytrace/app/src/config.mjs +49 -0
- raytrace/app/src/export.mjs +200 -0
- raytrace/app/src/lima.mjs +176 -0
- raytrace/app/src/local-sandbox.mjs +358 -0
- raytrace/app/src/mcp.mjs +688 -0
- raytrace/app/src/paths.mjs +33 -0
- raytrace/app/src/prompt.mjs +42 -0
- raytrace/app/src/proxy-process.mjs +143 -0
- raytrace/app/src/sandbox.mjs +306 -0
- raytrace/app/src/share.mjs +86 -0
- raytrace/app/src/terminal.mjs +68 -0
- raytrace/app/src/upload.mjs +198 -0
- raytrace/app/worker/sandbox/Dockerfile +8 -0
- raytrace/app/worker/sandbox/SYSCALL_CATALOG.md +197 -0
- raytrace/app/worker/sandbox/claude-hook.mjs +364 -0
- raytrace/app/worker/sandbox/collector.py +405 -0
- raytrace/app/worker/sandbox/dns_forwarder.py +255 -0
- raytrace/app/worker/sandbox/engine.py +940 -0
- raytrace/app/worker/sandbox/file_scan.py +491 -0
- raytrace/app/worker/sandbox/lima.yaml +29 -0
- raytrace/app/worker/sandbox/network.py +90 -0
- raytrace/app/worker/sandbox/projects.py +702 -0
- raytrace/app/worker/sandbox/setup.py +159 -0
- raytrace/app/worker/sandbox/syscall_catalog.sql +985 -0
- raytrace/app/worker/sandbox/transcript-delivery.test.mjs +153 -0
- raytrace/app/worker/sandbox/viewer.py +195 -0
- raytrace/node/LICENSE +2946 -0
- raytrace/node/node.exe +4 -0
- raytrace_cli-0.11.1.dist-info/LICENSE +21 -0
- raytrace_cli-0.11.1.dist-info/METADATA +42 -0
- raytrace_cli-0.11.1.dist-info/RECORD +165 -0
- raytrace_cli-0.11.1.dist-info/WHEEL +4 -0
- raytrace_cli-0.11.1.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Recording health describes selected events, never certifies completeness. */
|
|
2
|
+
export const sourceStreamId = (sandbox, raw) => raw?.source_instance_id && raw?.source_connection_id
|
|
3
|
+
? `gvisor:${sandbox}:${raw.source_instance_id}:${raw.source_connection_id}` : `gvisor:${sandbox}`;
|
|
4
|
+
export function captureHealth({sessionId,streams=[],checkpoints=[],events=[],since,until,now=Date.now()}) {
|
|
5
|
+
const applicable=/^rt[pf]-[a-f0-9]{32}$/.test(sessionId ?? '');
|
|
6
|
+
const base={live:applicable?'unknown':'not_applicable',history:applicable?'unknown':'not_applicable',issues:[],lastHeartbeatAt:null,checkedAt:now,scope:'Selected recorded events; completeness is not certified'};
|
|
7
|
+
if(!applicable) return base;
|
|
8
|
+
const from=Number(since), to=Number(until);
|
|
9
|
+
const latest=[...checkpoints].sort((a,b)=>(b.checked_at_ms??0)-(a.checked_at_ms??0))[0];
|
|
10
|
+
const current=streams.filter(s=>s.collector_id===latest?.source_instance_id && !s.ended_ms);
|
|
11
|
+
const beat=Math.max(0,...current.map(s=>Number(s.heartbeat_ms)||0));
|
|
12
|
+
base.lastHeartbeatAt=beat||null;
|
|
13
|
+
const described=streams.filter(s=>s.capabilities);
|
|
14
|
+
base.capabilities=described.length?Object.fromEntries(['processes','files','network'].map(key=>[key,described.every(s=>s.capabilities[key]===true)])):null;
|
|
15
|
+
if(latest?.imported || current.some(s=>!s.clock_measured)) base.live='unknown';
|
|
16
|
+
else if(latest?.unavailable || (beat && now-beat>15000)) base.live='not_reporting';
|
|
17
|
+
else if(current.length && beat && now-beat<=15000) base.live=Number(latest?.cursor)<Number(latest?.latest)?'catching_up':'reporting';
|
|
18
|
+
else if(streams.some(s=>!s.ended_ms) && latest?.source_instance_id) base.live='not_reporting';
|
|
19
|
+
else if(streams.length && streams.every(s=>s.ended_ms)) base.live='ended';
|
|
20
|
+
if(!Number.isFinite(from)||!Number.isFinite(to)||to<from) return base;
|
|
21
|
+
const markers=events.filter(e=>Number.isFinite(e.recorded_at_ms)&&e.recorded_at_ms>=from && (e.kind==='collection_gap' && Number.isFinite(e.gap_from_ms) ? e.gap_from_ms : e.recorded_at_ms)<=to);
|
|
22
|
+
base.issues=markers.map(e=>({reason:e.kind,eventId:e.event_id,at:e.recorded_at_ms,dropped:e.kind==='collection_gap'?e.dropped_delta:null}));
|
|
23
|
+
if(markers.some(e=>['collection_gap','collection_error'].includes(e.kind))) base.history='gaps_detected';
|
|
24
|
+
else {
|
|
25
|
+
const covering=streams.filter(s=>s.clock_measured && s.started_ms<=from && Math.min(s.ended_ms??Infinity,s.heartbeat_ms)>=to);
|
|
26
|
+
const synced=covering.length && covering.every(s=>checkpoints.some(c=>c.source_instance_id===s.collector_id && Number(c.forwarded_through_ms)>=to));
|
|
27
|
+
if(synced && !markers.some(e=>e.kind==='collector_disconnected')) base.history='no_known_gaps';
|
|
28
|
+
}
|
|
29
|
+
return base;
|
|
30
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import {captureHealth,sourceStreamId} from './capture-health.mjs';
|
|
4
|
+
import {openEvidenceStore} from './evidence-store.mjs';
|
|
5
|
+
import {mkdtempSync,rmSync} from 'node:fs';
|
|
6
|
+
import {tmpdir} from 'node:os';
|
|
7
|
+
import {join} from 'node:path';
|
|
8
|
+
const sessionId='rtp-'+'a'.repeat(32);
|
|
9
|
+
const stream={id:'conn',collector_id:'boot',started_ms:100,heartbeat_ms:1000,ended_ms:null,clock_measured:true};
|
|
10
|
+
const checkpoint={source_instance_id:'boot',checked_at_ms:1000,latest:5,cursor:5,forwarded_through_ms:1000};
|
|
11
|
+
const sample=(extra={})=>captureHealth({sessionId,streams:[stream],checkpoints:[checkpoint],events:[],since:200,until:800,now:1100,...extra});
|
|
12
|
+
test('live liveness and historic interval are independent',()=>{
|
|
13
|
+
assert.equal(sample().live,'reporting');assert.equal(sample().history,'no_known_gaps');
|
|
14
|
+
const old=sample({now:17000});assert.equal(old.live,'not_reporting');assert.equal(old.history,'no_known_gaps');
|
|
15
|
+
assert.equal(sample({checkpoints:[{...checkpoint,cursor:4}]}).live,'catching_up');
|
|
16
|
+
});
|
|
17
|
+
test('unknown start, missing clock, legacy recording and imported data never claim live health',()=>{
|
|
18
|
+
assert.equal(sample({streams:[]}).history,'unknown');
|
|
19
|
+
assert.equal(sample({streams:[{...stream,clock_measured:false}]}).history,'unknown');
|
|
20
|
+
assert.equal(sample({checkpoints:[{...checkpoint,imported:true}]}).live,'unknown');
|
|
21
|
+
assert.equal(captureHealth({sessionId:'host-session'}).history,'not_applicable');
|
|
22
|
+
});
|
|
23
|
+
test('gaps are scoped to the run, including the interval before the dropped-count report',()=>{
|
|
24
|
+
assert.equal(sample({events:[{kind:'collection_gap',recorded_at_ms:900,gap_from_ms:700,dropped_delta:2}]}).history,'gaps_detected');
|
|
25
|
+
assert.equal(sample({events:[{kind:'collection_gap',recorded_at_ms:1100,gap_from_ms:1001}]}).history,'no_known_gaps');
|
|
26
|
+
assert.equal(sample({events:[{kind:'collector_disconnected',recorded_at_ms:700}]}).history,'unknown');
|
|
27
|
+
});
|
|
28
|
+
test('source identities survive event-id reuse after a collector restart',()=>{
|
|
29
|
+
assert.notEqual(sourceStreamId('box',{source_instance_id:'a',source_connection_id:'c'}),sourceStreamId('box',{source_instance_id:'b',source_connection_id:'c'}));
|
|
30
|
+
});
|
|
31
|
+
test('SQLite progress survives reopening and deleting one sandbox removes its metadata only',()=>{
|
|
32
|
+
const dir=mkdtempSync(join(tmpdir(),'recording-health-'));const file=join(dir,'evidence.db');let db=openEvidenceStore(file);
|
|
33
|
+
try {
|
|
34
|
+
db.saveCaptureProgress({containerId:'box',projectId:sessionId,sourceId:'boot',cursor:5,coverage:{...checkpoint,streams:[stream]}});
|
|
35
|
+
db.saveCaptureProgress({containerId:'other',projectId:'rtp-'+'b'.repeat(32),sourceId:'boot',cursor:3,coverage:{...checkpoint,streams:[{...stream,id:'other'}]}});
|
|
36
|
+
db.close();db=openEvidenceStore(file);assert.equal(db.captureCheckpoint('box','boot'),5);
|
|
37
|
+
assert.equal(db.captureHealth(sessionId,{since:200,until:800,now:1100}).history,'no_known_gaps');
|
|
38
|
+
db.forgetSessions([sessionId]);assert.equal(db.captureCheckpoint('box','boot'),0);assert.equal(db.captureCheckpoint('other','boot'),3);
|
|
39
|
+
}finally{db.close();rmSync(dir,{recursive:true,force:true});}
|
|
40
|
+
});
|
|
41
|
+
test('a current outage or later backlog cannot invalidate a previously forwarded historical interval',()=>{
|
|
42
|
+
const health=sample({checkpoints:[{...checkpoint,unavailable:true,latest:100}],now:50000});
|
|
43
|
+
assert.equal(health.live,'not_reporting');assert.equal(health.history,'no_known_gaps');
|
|
44
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the proxy keeps of a model request and its response, shared by the
|
|
3
|
+
* local proxy (raytace-proxy.mjs) and RayTrace's hosted evidence service.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// A count is not a credential: usage reports token counts (input_tokens,
|
|
7
|
+
// output_tokens_details) under names that look like tokens.
|
|
8
|
+
const isCount = (value) => value === null || typeof value === 'number'
|
|
9
|
+
|| (typeof value === 'object' && Object.values(value).every(isCount));
|
|
10
|
+
const isCredential = (key, value) => /authorization|api[-_]?key|secret|password/i.test(key)
|
|
11
|
+
|| (/token/i.test(key) && !isCount(value));
|
|
12
|
+
|
|
13
|
+
/** The value with every credential-looking field replaced, at any depth. */
|
|
14
|
+
export function redact(value) {
|
|
15
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
16
|
+
if (!value || typeof value !== 'object') return value;
|
|
17
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) =>
|
|
18
|
+
isCredential(key, item) ? [key, '[REDACTED]'] : [key, redact(item)],
|
|
19
|
+
));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A streamed response as the final response object when the stream carried
|
|
23
|
+
* one (Responses API), else its events; null when nothing parsed. */
|
|
24
|
+
export function parseSseResponse(body) {
|
|
25
|
+
const events = [];
|
|
26
|
+
let terminalResponse = null;
|
|
27
|
+
for (const frame of body.toString('utf8').replace(/\r\n/g, '\n').split('\n\n')) {
|
|
28
|
+
const data = frame.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trimStart()).join('\n');
|
|
29
|
+
if (!data || data === '[DONE]') continue;
|
|
30
|
+
try {
|
|
31
|
+
const event = JSON.parse(data);
|
|
32
|
+
events.push(event);
|
|
33
|
+
if (['response.completed', 'response.failed', 'response.incomplete'].includes(event.type) && event.response) terminalResponse = event.response;
|
|
34
|
+
} catch { /* retain the raw response hash when an SSE event is not JSON */ }
|
|
35
|
+
}
|
|
36
|
+
if (terminalResponse) return terminalResponse;
|
|
37
|
+
return events.length ? { stream: true, events } : null;
|
|
38
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { parseSseResponse } from './capture.mjs';
|
|
4
|
+
import { splitExchange } from './trace-view.mjs';
|
|
5
|
+
|
|
6
|
+
const sse = (events) => Buffer.from(events.map((event) => `data: ${JSON.stringify(event)}\r\n\r\n`).join('') + 'data: [DONE]\r\n\r\n');
|
|
7
|
+
const exchange = (payload, input = []) => ({
|
|
8
|
+
span_id: 'test-span', timestamp: '2026-10-28T00:00:00Z',
|
|
9
|
+
request: { payload: { input } }, response: { status: 200, payload },
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
test('all supported tool result types reach the timeline with their content and identity', () => {
|
|
13
|
+
const input = [
|
|
14
|
+
{ type: 'function_call_output', call_id: 'function-1', output: 'ordinary result' },
|
|
15
|
+
{ type: 'custom_tool_call_output', call_id: 'custom-1', output: 'patch result' },
|
|
16
|
+
{ type: 'tool_result', call_id: 'native-1', content: 'native result' },
|
|
17
|
+
];
|
|
18
|
+
const events = splitExchange(exchange({ status: 'completed', output: [] }, input))
|
|
19
|
+
.filter((event) => event.title.startsWith('Tool result:'));
|
|
20
|
+
assert.deepEqual(events.map((event) => JSON.parse(event.raw)), input);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
for (const status of ['completed', 'failed', 'incomplete']) {
|
|
24
|
+
test(`streamed ${status} response preserves terminal status, details and output for the dashboard`, () => {
|
|
25
|
+
const response = {
|
|
26
|
+
status,
|
|
27
|
+
output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'partial or final answer' }] }],
|
|
28
|
+
...(status === 'failed' ? { error: { code: 'server_error', message: 'synthetic failure' } } : {}),
|
|
29
|
+
...(status === 'incomplete' ? { incomplete_details: { reason: 'max_output_tokens' } } : {}),
|
|
30
|
+
};
|
|
31
|
+
const parsed = parseSseResponse(sse([
|
|
32
|
+
{ type: 'response.created', response: { status: 'in_progress', output: [] } },
|
|
33
|
+
{ type: `response.${status}`, response },
|
|
34
|
+
]));
|
|
35
|
+
assert.deepEqual(parsed, response);
|
|
36
|
+
const events = splitExchange(exchange(parsed));
|
|
37
|
+
assert.equal(JSON.parse(events.at(-1).raw).response_status, status);
|
|
38
|
+
assert.ok(events.some((event) => event.title === 'Model answer'));
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
test('a stream without a terminal response retains raw events without claiming a completed model response', () => {
|
|
43
|
+
const events = [{ type: 'response.created', response: { status: 'in_progress', output: [] } },
|
|
44
|
+
{ type: 'response.output_text.delta', delta: 'unfinished' }];
|
|
45
|
+
const parsed = parseSseResponse(sse(events));
|
|
46
|
+
assert.deepEqual(parsed, { stream: true, events });
|
|
47
|
+
assert.equal(parsed.status, undefined);
|
|
48
|
+
assert.equal(parseSseResponse(Buffer.from('data: [DONE]\n\n')), null);
|
|
49
|
+
});
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code without the proxy: rebuilds each model call from a Claude Code
|
|
3
|
+
* session transcript (~/.claude/projects/<project>/<session>.jsonl) in the
|
|
4
|
+
* shape the proxy records, so the store and dashboard take it unchanged.
|
|
5
|
+
*
|
|
6
|
+
* The transcript is Claude Code's own record, not the wire. Each assistant
|
|
7
|
+
* message carries the API `requestId` it came from, and everything that went
|
|
8
|
+
* into the model's context is written ahead of it: the user's prompt, tool
|
|
9
|
+
* results, and "attachment" lines for what the harness injected (files,
|
|
10
|
+
* environment, skills, the system prompt snapshot). A call's input is that
|
|
11
|
+
* conversation so far; its output is its assistant lines. What Claude Code
|
|
12
|
+
* actually sent can differ (it drops old thinking, renders attachments its
|
|
13
|
+
* own way), so rows are marked `source: claude-code-transcript`.
|
|
14
|
+
*
|
|
15
|
+
* Items are translated to the Responses shape the rest of RayTrace reads:
|
|
16
|
+
* tool_use -> function_call, tool_result -> function_call_output, text ->
|
|
17
|
+
* message, harness injections -> developer messages, the system prompt ->
|
|
18
|
+
* `instructions`.
|
|
19
|
+
*
|
|
20
|
+
* The transcript format is internal to Claude Code and not a stable API:
|
|
21
|
+
* unknown line and attachment types are skipped, never guessed at.
|
|
22
|
+
*/
|
|
23
|
+
import { createHash } from 'node:crypto';
|
|
24
|
+
|
|
25
|
+
// Attachments that are account data or bookkeeping, not model context.
|
|
26
|
+
const SKIPPED_ATTACHMENTS = new Set(['session_context', 'credential_org', 'remote_session_change', 'deferred_tools_record',
|
|
27
|
+
'thinking_drop', 'prompt_snapshot']);
|
|
28
|
+
|
|
29
|
+
// USD per million tokens (Anthropic first-party rates). Cache writes bill at
|
|
30
|
+
// 1.25x input for a 5-minute entry and 2x for a 1-hour one; cache reads at
|
|
31
|
+
// each model's own rate. Fast mode doubles every rate. Longest prefix wins.
|
|
32
|
+
const PRICES = [
|
|
33
|
+
['claude-opus-5-5', { input: 4, output: 20, cacheRead: 0.2 }],
|
|
34
|
+
['claude-opus-5', { input: 5, output: 25, cacheRead: 0.5 }],
|
|
35
|
+
['claude-opus-4', { input: 5, output: 25, cacheRead: 0.5 }],
|
|
36
|
+
['claude-sonnet-5', { input: 2, output: 10, cacheRead: 0.2 }],
|
|
37
|
+
['claude-sonnet-4', { input: 3, output: 15, cacheRead: 0.3 }],
|
|
38
|
+
['claude-haiku-4-5', { input: 1, output: 5, cacheRead: 0.1 }],
|
|
39
|
+
['claude-fable-5-1', { input: 10, output: 50, cacheRead: 0.25 }],
|
|
40
|
+
['claude-fable-5', { input: 10, output: 50, cacheRead: 1 }],
|
|
41
|
+
].sort((a, b) => b[0].length - a[0].length);
|
|
42
|
+
|
|
43
|
+
const num = (value) => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0);
|
|
44
|
+
const toMs = (value) => { const parsed = Date.parse(value ?? ''); return Number.isFinite(parsed) ? parsed : null; };
|
|
45
|
+
|
|
46
|
+
/** A stable UUID-shaped id, so re-reading a transcript never records a call twice. */
|
|
47
|
+
function stableId(...parts) {
|
|
48
|
+
const hex = createHash('sha256').update(parts.join('\0')).digest('hex');
|
|
49
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Estimated USD for one call's usage, or null for a model not in the table. */
|
|
53
|
+
export function estimateCost(model, usage) {
|
|
54
|
+
const price = PRICES.find(([prefix]) => String(model ?? '').startsWith(prefix))?.[1];
|
|
55
|
+
if (!price || !usage) return null;
|
|
56
|
+
const writes = usage.cache_creation;
|
|
57
|
+
const write1h = writes ? num(writes.ephemeral_1h_input_tokens) : 0;
|
|
58
|
+
const write5m = writes ? num(writes.ephemeral_5m_input_tokens) : num(usage.cache_creation_input_tokens);
|
|
59
|
+
const dollars = num(usage.input_tokens) * price.input + write5m * price.input * 1.25 + write1h * price.input * 2
|
|
60
|
+
+ num(usage.cache_read_input_tokens) * price.cacheRead + num(usage.output_tokens) * price.output;
|
|
61
|
+
return (dollars / 1_000_000) * (usage.speed === 'fast' ? 2 : 1);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Token counts and estimated cost in the dashboard's metric shape. `input`
|
|
65
|
+
* counts every prompt token, cached or not, as OpenRouter reports it. */
|
|
66
|
+
export function claudeCodeMetrics(model, usage, startedMs, completedMs) {
|
|
67
|
+
if (!usage) return { input: null, output: null, cost: null, durationMs: null };
|
|
68
|
+
const cacheRead = num(usage.cache_read_input_tokens);
|
|
69
|
+
const cacheWrite = num(usage.cache_creation_input_tokens);
|
|
70
|
+
return {
|
|
71
|
+
input: num(usage.input_tokens) + cacheRead + cacheWrite,
|
|
72
|
+
output: num(usage.output_tokens),
|
|
73
|
+
cacheRead, cacheWrite,
|
|
74
|
+
cost: estimateCost(model, usage),
|
|
75
|
+
costEstimated: true,
|
|
76
|
+
// From transcript timestamps: the last user or tool-result line to the
|
|
77
|
+
// answer. Approximate (includes harness time), not the API's latency.
|
|
78
|
+
durationMs: Number.isFinite(startedMs) && Number.isFinite(completedMs) ? Math.max(0, completedMs - startedMs) : null,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const textParts = (content) => (typeof content === 'string' ? content
|
|
83
|
+
: Array.isArray(content) ? content.map((part) => (part?.type === 'text' ? part.text : part?.type === 'image' ? '[image]' : '')).filter(Boolean).join('\n') : '');
|
|
84
|
+
|
|
85
|
+
// A slash command's own output and markers are harness text, not a prompt.
|
|
86
|
+
const HARNESS_TEXT = /^\s*<(local-command-|command-name|command-message|command-args|system-reminder)/;
|
|
87
|
+
|
|
88
|
+
function toolOutput(content) {
|
|
89
|
+
if (typeof content === 'string') return content;
|
|
90
|
+
if (Array.isArray(content)) return content.map((part) => (part?.type === 'text' ? part.text : part?.type === 'image' ? '[image]' : '')).join('\n');
|
|
91
|
+
return JSON.stringify(content ?? '');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** One user line -> Responses items. */
|
|
95
|
+
function userItems(line) {
|
|
96
|
+
const content = line.message?.content;
|
|
97
|
+
const items = [];
|
|
98
|
+
const text = textParts(Array.isArray(content) ? content.filter((part) => part?.type !== 'tool_result') : content).trim();
|
|
99
|
+
if (text) {
|
|
100
|
+
const injected = line.isMeta || line.isCompactSummary || HARNESS_TEXT.test(text);
|
|
101
|
+
items.push({ type: 'message', role: injected ? 'developer' : 'user', content: [{ type: 'input_text', text }] });
|
|
102
|
+
}
|
|
103
|
+
if (Array.isArray(content)) {
|
|
104
|
+
for (const part of content) {
|
|
105
|
+
if (part?.type !== 'tool_result') continue;
|
|
106
|
+
items.push({ type: 'function_call_output', call_id: part.tool_use_id, output: toolOutput(part.content), ...(part.is_error ? { is_error: true } : {}) });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return items;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** One attachment line -> a developer message, or null when it is not context. */
|
|
113
|
+
function attachmentItem(attachment) {
|
|
114
|
+
const kind = attachment?.type;
|
|
115
|
+
if (!kind || SKIPPED_ATTACHMENTS.has(kind)) return null;
|
|
116
|
+
let text;
|
|
117
|
+
if (kind === 'file') {
|
|
118
|
+
const file = attachment.content?.file;
|
|
119
|
+
text = `File ${attachment.displayPath ?? attachment.filename ?? ''}:\n${file?.content ?? textParts(attachment.content) ?? ''}`;
|
|
120
|
+
} else if (kind === 'compact_file_reference') {
|
|
121
|
+
text = `Read before the conversation was compacted: ${attachment.displayPath ?? attachment.filename ?? ''}`;
|
|
122
|
+
} else if (typeof attachment.text === 'string') text = attachment.text;
|
|
123
|
+
else if (typeof attachment.content === 'string') text = attachment.content;
|
|
124
|
+
else if (Array.isArray(attachment.addedBlocks)) text = attachment.addedBlocks.join('\n\n');
|
|
125
|
+
else if (Array.isArray(attachment.addedLines)) text = attachment.addedLines.join('\n');
|
|
126
|
+
else if (attachment.snapshot && typeof attachment.snapshot === 'object') text = JSON.stringify(attachment.snapshot, null, 2);
|
|
127
|
+
else return null;
|
|
128
|
+
if (!text?.trim()) return null;
|
|
129
|
+
return { type: 'message', role: 'developer', content: [{ type: 'input_text', text: `<claude-code:${kind}>\n${text}` }] };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** One assistant content block -> a Responses output item, or null. */
|
|
133
|
+
function outputItem(block, messageId, index) {
|
|
134
|
+
if (block?.type === 'text' && block.text) return { type: 'message', role: 'assistant', id: `${messageId}-${index}`, status: 'completed', content: [{ type: 'output_text', text: block.text }] };
|
|
135
|
+
if (block?.type === 'tool_use') return { type: 'function_call', call_id: block.id, name: block.name, arguments: JSON.stringify(block.input ?? {}), status: 'completed' };
|
|
136
|
+
if (block?.type === 'thinking' || block?.type === 'redacted_thinking') return { type: 'reasoning', summary: block.thinking ? [{ type: 'summary_text', text: block.thinking }] : [] };
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function toolResultsFromTranscript(lines) {
|
|
141
|
+
const results = new Map();
|
|
142
|
+
for (const line of lines) {
|
|
143
|
+
if (line?.type === 'user' && Array.isArray(line.message?.content)) {
|
|
144
|
+
for (const part of line.message.content) {
|
|
145
|
+
if (part?.type === 'tool_result' && part.tool_use_id) {
|
|
146
|
+
results.set(part.tool_use_id, {
|
|
147
|
+
type: 'function_call_output',
|
|
148
|
+
call_id: part.tool_use_id,
|
|
149
|
+
output: toolOutput(part.content),
|
|
150
|
+
...(part.is_error ? { is_error: true } : {})
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return results;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Parses JSONL text; a partial last line (still being written) is dropped. */
|
|
160
|
+
export function parseTranscript(text) {
|
|
161
|
+
const lines = [];
|
|
162
|
+
for (const raw of String(text).split('\n')) {
|
|
163
|
+
if (!raw.trim()) continue;
|
|
164
|
+
try { lines.push(JSON.parse(raw)); } catch { /* partial or corrupt line */ }
|
|
165
|
+
}
|
|
166
|
+
return lines;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Transcript lines -> proxy-shaped `model.exchange` rows, oldest first.
|
|
171
|
+
*
|
|
172
|
+
* Claude Code starts a tool while the answer is still streaming, so one
|
|
173
|
+
* call's assistant lines can have that tool's result written between them.
|
|
174
|
+
* A call is therefore every assistant line with its requestId up to the next
|
|
175
|
+
* call's first line, and it is complete once that next call exists, or when
|
|
176
|
+
* `final` (the session stopped): a call is never recorded half-written.
|
|
177
|
+
* Subagent (sidechain) lines are left out.
|
|
178
|
+
*
|
|
179
|
+
* `sessionId` / `sessionStartedAt` file the rows under another session than
|
|
180
|
+
* the transcript's own (a sandbox's rtp- id, so its evidence joins them).
|
|
181
|
+
*/
|
|
182
|
+
export function exchangesFromTranscript(lines, { final = false, version = null, sessionId: filedUnder = null, sessionStartedAt = null } = {}) {
|
|
183
|
+
const main = lines.filter((line) => !line.isSidechain);
|
|
184
|
+
const transcriptSession = main.find((line) => line.sessionId)?.sessionId ?? null;
|
|
185
|
+
const sessionId = filedUnder ?? transcriptSession;
|
|
186
|
+
const sessionStarted = sessionStartedAt ?? main.find((line) => line.timestamp)?.timestamp ?? null;
|
|
187
|
+
const callOf = (line) => (line?.type === 'assistant' && line.message ? line.requestId ?? line.message.id : null);
|
|
188
|
+
const grouped = new Set(); // indexes already emitted as part of an earlier line's call
|
|
189
|
+
const rows = [];
|
|
190
|
+
let conversation = [];
|
|
191
|
+
let instructions = null;
|
|
192
|
+
let lastWrittenMs = null;
|
|
193
|
+
|
|
194
|
+
for (let i = 0; i < main.length; i++) {
|
|
195
|
+
if (grouped.has(i)) continue;
|
|
196
|
+
const line = main[i];
|
|
197
|
+
if (line.type === 'system' && line.subtype === 'compact_boundary') { conversation = []; continue; }
|
|
198
|
+
if (line.type === 'attachment') {
|
|
199
|
+
const attachment = line.attachment;
|
|
200
|
+
if (attachment?.type === 'prompt_snapshot' && Array.isArray(attachment.systemPrompt)) instructions = attachment.systemPrompt.join('\n\n');
|
|
201
|
+
const item = attachmentItem(attachment);
|
|
202
|
+
// Attachments are stamped when flushed, often with the answer itself,
|
|
203
|
+
// so they do not move the call's start time.
|
|
204
|
+
if (item) conversation.push(item);
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (line.type === 'user') {
|
|
208
|
+
conversation.push(...userItems(line));
|
|
209
|
+
lastWrittenMs = toMs(line.timestamp) ?? lastWrittenMs;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (line.type !== 'assistant' || !line.message) continue;
|
|
213
|
+
|
|
214
|
+
// One API call: its assistant lines up to the next call's first line.
|
|
215
|
+
// Lines between them (tool results, attachments) are read after it.
|
|
216
|
+
const requestId = callOf(line);
|
|
217
|
+
let next = i + 1;
|
|
218
|
+
const members = [i];
|
|
219
|
+
for (; next < main.length; next++) {
|
|
220
|
+
const call = callOf(main[next]);
|
|
221
|
+
if (call === requestId) members.push(next);
|
|
222
|
+
else if (call) break;
|
|
223
|
+
}
|
|
224
|
+
if (!final && next === main.length) break;
|
|
225
|
+
for (const index of members) grouped.add(index);
|
|
226
|
+
const group = members.map((index) => main[index]);
|
|
227
|
+
|
|
228
|
+
const last = group.at(-1).message;
|
|
229
|
+
const output = group.flatMap((entry, index) => (entry.message.content ?? []).map((block, part) => outputItem(block, entry.message.id, `${index}.${part}`))).filter(Boolean);
|
|
230
|
+
const model = last.model ?? null;
|
|
231
|
+
const startedMs = lastWrittenMs ?? toMs(line.timestamp);
|
|
232
|
+
const completedMs = toMs(group.at(-1).timestamp) ?? startedMs;
|
|
233
|
+
rows.push({
|
|
234
|
+
event_type: 'model.exchange',
|
|
235
|
+
session_id: sessionId, session_started_at: sessionStarted,
|
|
236
|
+
// Claude Code's own session, whatever session the row is filed under.
|
|
237
|
+
agent_session_id: transcriptSession,
|
|
238
|
+
trace_id: stableId('trace', transcriptSession, requestId),
|
|
239
|
+
span_id: stableId('claude-code', transcriptSession, requestId),
|
|
240
|
+
parent_span_id: null,
|
|
241
|
+
timestamp: new Date(startedMs ?? Date.now()).toISOString(),
|
|
242
|
+
completed_at: new Date(completedMs ?? Date.now()).toISOString(),
|
|
243
|
+
provider: 'claude-code',
|
|
244
|
+
route: '/claude-code/v1/messages', method: 'POST',
|
|
245
|
+
metrics: claudeCodeMetrics(model, last.usage, startedMs, completedMs),
|
|
246
|
+
source: { kind: 'claude-code-transcript', version: group.at(-1).version ?? version, request_id: requestId },
|
|
247
|
+
request: { headers: null, bytes: null, sha256: null,
|
|
248
|
+
payload: { model, ...(instructions ? { instructions } : {}), input: structuredClone(conversation) } },
|
|
249
|
+
response: { status: 200, headers: null, bytes: null, sha256: null,
|
|
250
|
+
payload: { id: last.id, model, status: 'completed', stop_reason: last.stop_reason ?? null, output, usage: last.usage ?? null } },
|
|
251
|
+
});
|
|
252
|
+
conversation.push(...output.filter((item) => item.type !== 'reasoning'));
|
|
253
|
+
lastWrittenMs = completedMs;
|
|
254
|
+
}
|
|
255
|
+
return rows;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** The span id a Claude Code call is recorded under (see exchangesFromTranscript). */
|
|
259
|
+
export function claudeCodeSpanId(transcriptSession, requestId) {
|
|
260
|
+
return stableId('claude-code', transcriptSession, requestId);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* A transcript cut just before one model call, for a Playground fork to
|
|
265
|
+
* resume from: every line before that call's first line, byte for byte,
|
|
266
|
+
* except the tool results being edited. `results` maps a tool call id to the
|
|
267
|
+
* text its result is replaced with. Returns null when the call is not in
|
|
268
|
+
* this transcript.
|
|
269
|
+
*
|
|
270
|
+
* Claude Code resumes from these lines as they are, so what the forked model
|
|
271
|
+
* is asked is the original request with only the edits changed.
|
|
272
|
+
*/
|
|
273
|
+
export function forkTranscript(text, { spanId, results = {} }) {
|
|
274
|
+
const raw = String(text).split('\n');
|
|
275
|
+
const parsed = raw.map((line) => { try { return line.trim() ? JSON.parse(line) : null; } catch { return null; } });
|
|
276
|
+
const session = parsed.find((line) => line?.sessionId && !line.isSidechain)?.sessionId ?? null;
|
|
277
|
+
const cut = parsed.findIndex((line) => line?.type === 'assistant' && !line.isSidechain && line.message
|
|
278
|
+
&& claudeCodeSpanId(session, line.requestId ?? line.message.id) === spanId);
|
|
279
|
+
if (!session || cut < 0) return null;
|
|
280
|
+
const edited = new Set();
|
|
281
|
+
const kept = raw.slice(0, cut).map((line, index) => {
|
|
282
|
+
const entry = parsed[index];
|
|
283
|
+
const content = entry?.type === 'user' ? entry.message?.content : null;
|
|
284
|
+
if (!Array.isArray(content) || !content.some((part) => part?.type === 'tool_result' && part.tool_use_id in results)) return line;
|
|
285
|
+
const copy = structuredClone(entry);
|
|
286
|
+
for (const part of copy.message.content) {
|
|
287
|
+
if (part?.type !== 'tool_result' || !(part.tool_use_id in results)) continue;
|
|
288
|
+
part.content = String(results[part.tool_use_id]);
|
|
289
|
+
delete part.is_error;
|
|
290
|
+
edited.add(part.tool_use_id);
|
|
291
|
+
}
|
|
292
|
+
// Claude Code's structured copy of the result would contradict the edit.
|
|
293
|
+
delete copy.toolUseResult;
|
|
294
|
+
return JSON.stringify(copy);
|
|
295
|
+
}).filter((line) => line.trim());
|
|
296
|
+
const priorCalls = parsed.slice(0, cut).filter((line) => line?.type === 'assistant' && !line.isSidechain)
|
|
297
|
+
.flatMap((line) => (line.message?.content ?? []).filter((block) => block?.type === 'tool_use').map((block) => block.id));
|
|
298
|
+
return { text: `${kept.join('\n')}\n`, session, model: parsed[cut].message.model ?? null,
|
|
299
|
+
startedAt: parsed.slice(0, cut).reverse().find((line) => line?.timestamp && ['user', 'assistant'].includes(line.type))?.timestamp ?? null,
|
|
300
|
+
priorCalls, edited: [...edited], missing: Object.keys(results).filter((id) => !edited.has(id)) };
|
|
301
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Claude Code hook: tells RayTrace a session's transcript has new lines.
|
|
4
|
+
* Claude Code runs this on each hook event with the event JSON on stdin; only
|
|
5
|
+
* the session id, transcript path and event name are forwarded -- RayTrace
|
|
6
|
+
* reads the transcript itself. Always exits 0 with no output, fast, so a
|
|
7
|
+
* stopped RayTrace never slows or blocks Claude Code.
|
|
8
|
+
*/
|
|
9
|
+
import { readToken } from './local-token.mjs';
|
|
10
|
+
|
|
11
|
+
const port = process.env.RAYTACE_PORT || '8797';
|
|
12
|
+
const chunks = [];
|
|
13
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
14
|
+
try {
|
|
15
|
+
const event = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
16
|
+
await fetch(`http://127.0.0.1:${port}/raytace/ingest/claude-code`, {
|
|
17
|
+
method: 'POST',
|
|
18
|
+
headers: { 'content-type': 'application/json', 'x-raytace-hook': '1', authorization: `Bearer ${readToken()}` },
|
|
19
|
+
body: JSON.stringify({ session_id: event.session_id, transcript_path: event.transcript_path, hook_event_name: event.hook_event_name }),
|
|
20
|
+
signal: AbortSignal.timeout(800),
|
|
21
|
+
});
|
|
22
|
+
} catch { /* RayTrace not running, or a malformed event: stay silent */ }
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { selectModel } from './providers.mjs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
// Where `raytrace codex` hands Codex the local API token (codex.mjs).
|
|
5
|
+
export const TOKEN_ENV = 'RAYTRACE_API_TOKEN';
|
|
6
|
+
|
|
7
|
+
export function codexArgs(config, args, port = '8797') {
|
|
8
|
+
if (config.mode !== 'openrouter') return args;
|
|
9
|
+
const forwarded = [];
|
|
10
|
+
let hasModel = false;
|
|
11
|
+
for (let i = 0; i < args.length; i++) {
|
|
12
|
+
const arg = args[i];
|
|
13
|
+
if (arg === '--') { forwarded.push(...args.slice(i)); break; }
|
|
14
|
+
if (arg === '-m' || arg === '--model') {
|
|
15
|
+
hasModel = true;
|
|
16
|
+
forwarded.push(arg, selectModel(config, args[++i]));
|
|
17
|
+
} else if (arg.startsWith('--model=') || arg.startsWith('-m=')) {
|
|
18
|
+
hasModel = true;
|
|
19
|
+
forwarded.push('--model', selectModel(config, arg.slice(arg.indexOf('=') + 1)));
|
|
20
|
+
} else {
|
|
21
|
+
forwarded.push(arg);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return [
|
|
25
|
+
'-c', 'model_provider="raytace_openrouter"',
|
|
26
|
+
'-c', 'model_providers.raytace_openrouter.name="OpenRouter via RayTrace"',
|
|
27
|
+
'-c', 'model_providers.raytace_openrouter.wire_api="responses"',
|
|
28
|
+
'-c', 'model_providers.raytace_openrouter.requires_openai_auth=false',
|
|
29
|
+
// By name, not value: arguments are visible to every account in `ps`.
|
|
30
|
+
'-c', `model_providers.raytace_openrouter.env_key="${TOKEN_ENV}"`,
|
|
31
|
+
'-c', `model_providers.raytace_openrouter.http_headers={ "x-raytace-session-id" = "${randomUUID()}", "x-raytace-session-started-at" = "${new Date().toISOString()}" }`,
|
|
32
|
+
'-c', `model_providers.raytace_openrouter.base_url=${JSON.stringify(`http://127.0.0.1:${port}/v1`)}`,
|
|
33
|
+
...(hasModel ? [] : ['-m', config.defaultModel]),
|
|
34
|
+
...forwarded,
|
|
35
|
+
];
|
|
36
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { loadEnvFile } from 'node:process';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { providerConfig } from './providers.mjs';
|
|
4
|
+
import { codexArgs, TOKEN_ENV } from './codex-config.mjs';
|
|
5
|
+
import { readToken } from './local-token.mjs';
|
|
6
|
+
|
|
7
|
+
try { loadEnvFile(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
8
|
+
const config = providerConfig();
|
|
9
|
+
const port = process.env.RAYTACE_PORT || '8797';
|
|
10
|
+
|
|
11
|
+
// Codex itself, pointed at RayTrace's proxy so every model call is recorded.
|
|
12
|
+
const child = spawn('codex', codexArgs(config, process.argv.slice(2), port), { stdio: 'inherit', env: { ...process.env, [TOKEN_ENV]: readToken() ?? '' } });
|
|
13
|
+
child.on('error', (error) => { console.error(`Could not launch Codex: ${error.message}`); process.exitCode = 1; });
|
|
14
|
+
child.on('exit', (code, signal) => { if (signal) process.kill(process.pid, signal); else process.exitCode = code ?? 1; });
|