@raytrace-cli/cli 0.3.0 → 0.5.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.
- package/README.md +155 -132
- package/bin/raytrace.mjs +51 -26
- package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
- package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
- package/dist/dashboard/assets/index-jyV5iYHJ.js +38 -0
- package/dist/dashboard/index.html +2 -2
- package/package.json +3 -1
- package/proxy/call-assessment.mjs +385 -0
- package/proxy/call-category.mjs +461 -0
- package/proxy/capture.mjs +31 -0
- package/proxy/claude-code-adapter.mjs +46 -3
- package/proxy/evidence-store.mjs +617 -15
- package/proxy/exec-narrative.mjs +625 -0
- package/proxy/execution-correlation.mjs +185 -0
- package/proxy/experiment-engine.mjs +7 -4
- package/proxy/failure-signature.mjs +56 -0
- package/proxy/gvisor-forwarder.mjs +454 -0
- package/proxy/init-evidence-db.mjs +136 -12
- package/proxy/local-sandboxes.mjs +94 -0
- package/proxy/playground.mjs +411 -0
- package/proxy/prompt-context.mjs +12 -7
- package/proxy/prompt-traces.mjs +6 -0
- package/proxy/raytace-proxy.mjs +460 -176
- package/proxy/run-recap.mjs +139 -0
- package/proxy/runtime-attribution.mjs +110 -0
- package/proxy/sandbox-bridge.mjs +46 -0
- package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
- package/proxy/schema/auxiliary.sql +48 -1
- package/proxy/schema/classification.sql +89 -0
- package/proxy/schema/file_context.sql +53 -0
- package/proxy/schema/runtime_evidence.sql +201 -0
- package/proxy/schema/search.sql +66 -0
- package/proxy/search.mjs +418 -0
- package/proxy/step-attribution.mjs +380 -0
- package/proxy/tool-metadata.mjs +36 -0
- package/proxy/trace-view.mjs +276 -0
- package/proxy/typesafe.mjs +63 -0
- package/src/auth.mjs +8 -1
- package/src/commands.mjs +80 -12
- package/src/lima.mjs +135 -0
- package/src/local-sandbox.mjs +324 -0
- package/src/proxy-process.mjs +20 -1
- package/src/sandbox.mjs +24 -6
- package/worker/sandbox/Dockerfile +8 -0
- package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
- package/worker/sandbox/claude-hook.mjs +331 -0
- package/worker/sandbox/collector.py +357 -0
- package/worker/sandbox/dns_forwarder.py +255 -0
- package/worker/sandbox/engine.py +940 -0
- package/worker/sandbox/file_scan.py +491 -0
- package/worker/sandbox/lima.yaml +29 -0
- package/worker/sandbox/network.py +90 -0
- package/worker/sandbox/projects.py +678 -0
- package/worker/sandbox/setup.py +159 -0
- package/worker/sandbox/syscall_catalog.sql +985 -0
- package/worker/sandbox/viewer.py +132 -0
- package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
- package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
package/proxy/raytace-proxy.mjs
CHANGED
|
@@ -1,24 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { requestMetrics } from './request-metrics.mjs';
|
|
3
|
+
import { redact, parseSseResponse } from './capture.mjs';
|
|
3
4
|
/** Local API recorder. Point a compatible client at http://127.0.0.1:8797. */
|
|
4
5
|
import { createServer } from 'node:http';
|
|
5
|
-
import { appendFile, mkdir, readFile } from 'node:fs/promises';
|
|
6
|
-
import { realpathSync } from 'node:fs';
|
|
6
|
+
import { appendFile, mkdir, readFile, stat } from 'node:fs/promises';
|
|
7
|
+
import { realpathSync, readFileSync } from 'node:fs';
|
|
7
8
|
import { homedir } from 'node:os';
|
|
8
9
|
import { randomUUID, createHash } from 'node:crypto';
|
|
9
10
|
import { join, dirname, resolve, extname, sep } from 'node:path';
|
|
10
11
|
import { exchangesFromTranscript, parseTranscript } from './claude-code-adapter.mjs';
|
|
11
|
-
import {
|
|
12
|
+
import { replayEligibility, createExperiment, runExperiment } from './experiment-engine.mjs';
|
|
12
13
|
import { loadEnvFile } from 'node:process';
|
|
13
14
|
import { providerConfig, routeRequest, selectModel } from './providers.mjs';
|
|
14
|
-
import { latestSessionRows } from './prompt-traces.mjs';
|
|
15
15
|
import { inspectStep, createStepRun, runDecision } from './step-lab.mjs';
|
|
16
16
|
import { executeSequence } from './execution-runner.mjs';
|
|
17
17
|
import { explanationRequest, parseExplanations } from './explanations.mjs';
|
|
18
18
|
import { summaryRequest, parseSummary, resultText } from './summaries.mjs';
|
|
19
|
-
import {
|
|
19
|
+
import { fold as foldEvents, describeAll, undescribed, describeRequest, parseDescriptions, attributeMarked } from './exec-narrative.mjs';
|
|
20
|
+
import { ingestExecutions, attributeLateProcesses } from './runtime-attribution.mjs';
|
|
21
|
+
import { readTraces as traceView } from './trace-view.mjs';
|
|
22
|
+
import { categoryResolver } from './call-category.mjs';
|
|
23
|
+
import { startGvisorForwarder } from './gvisor-forwarder.mjs';
|
|
24
|
+
import { startPlayground, FORK_ID } from './playground.mjs';
|
|
25
|
+
import { omitToolChunkIds } from './tool-metadata.mjs';
|
|
20
26
|
import { openEvidenceStore } from './evidence-store.mjs';
|
|
27
|
+
import { startSandboxBridge } from './sandbox-bridge.mjs';
|
|
28
|
+
import { localSandboxes, VM } from './local-sandboxes.mjs';
|
|
29
|
+
import { typesafeConfig, systemOne } from './typesafe.mjs';
|
|
21
30
|
import { promptContext, contextItemText, contextSummaryRequest, parseContextSummary } from './prompt-context.mjs';
|
|
31
|
+
import { recapOutline, recapRequest, recapText, parseRecap, DEFAULT_OBSERVER } from './run-recap.mjs';
|
|
32
|
+
import { groupByCall, assessmentRequests, combineGroup, rulesOnly, withProbabilities } from './call-assessment.mjs';
|
|
33
|
+
import { prepareStep, attributionKey, proposerRequest, parseProposals, candidates, jevRequests, combine, withoutJev } from './step-attribution.mjs';
|
|
22
34
|
|
|
23
35
|
try { loadEnvFile(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
24
36
|
const routing = providerConfig();
|
|
@@ -27,12 +39,21 @@ const routing = providerConfig();
|
|
|
27
39
|
const summaryModel = process.env.RAYTACE_SUMMARY_MODEL
|
|
28
40
|
? selectModel(routing, process.env.RAYTACE_SUMMARY_MODEL)
|
|
29
41
|
: (routing.models.oss || routing.defaultModel);
|
|
42
|
+
// Bumped whenever the dashboard needs endpoints an older proxy lacks; the
|
|
43
|
+
// CLI restarts a proxy it started that reports less (src/proxy-process.mjs).
|
|
44
|
+
const PROXY_API = 2;
|
|
30
45
|
const fallbackSession = { session_id: randomUUID(), session_started_at: new Date().toISOString() };
|
|
31
46
|
|
|
32
47
|
const port = Number(process.env.RAYTACE_PORT || 8797);
|
|
48
|
+
// The evidence viewer of the local sandbox VM (worker/sandbox/viewer.py),
|
|
49
|
+
// which Lima forwards here.
|
|
50
|
+
const EVIDENCE_VIEWER = process.env.RAYTACE_EVIDENCE_VIEWER || 'http://127.0.0.1:8798';
|
|
33
51
|
// The CLI sets RAYTACE_DATA_DIR (~/.raytrace); run by hand it keeps ./.raytace.
|
|
34
52
|
const dataDir = process.env.RAYTACE_DATA_DIR || join(process.cwd(), '.raytace');
|
|
35
53
|
const store = process.env.RAYTACE_STORE || join(dataDir, 'events.jsonl');
|
|
54
|
+
// The local sandboxes (raytrace sandbox create --local): in place of raytace's sandbox manager.
|
|
55
|
+
const sandboxes = localSandboxes({ dataDir });
|
|
56
|
+
const NO_VM = `Local sandbox VM (${VM}) not reachable. Start a sandbox with: raytrace sandbox start <name>`;
|
|
36
57
|
const maxBodyBytes = Number(process.env.RAYTACE_MAX_BODY_BYTES || 2_000_000);
|
|
37
58
|
const liveExchanges = new Map(); // Credentials stay in process memory, never in the event log.
|
|
38
59
|
const jobs = new Map();
|
|
@@ -47,13 +68,57 @@ function trustedOrigin(origin) {
|
|
|
47
68
|
try { const url = new URL(origin); return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname); } catch { return false; }
|
|
48
69
|
}
|
|
49
70
|
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
71
|
+
// Command severity (Jev). Without TYPESAFE_API_KEY, or when a request fails,
|
|
72
|
+
// only the rule floor is shown -- and only where a rule actually fired.
|
|
73
|
+
const typesafe = typesafeConfig();
|
|
74
|
+
const pendingAssessments = new Map();
|
|
75
|
+
const ASSESS_CONCURRENCY = 4;
|
|
76
|
+
|
|
77
|
+
async function mapLimit(items, limit, run) {
|
|
78
|
+
const results = Array.from({ length: items.length });
|
|
79
|
+
let next = 0;
|
|
80
|
+
const worker = async () => { while (next < items.length) { const index = next++; results[index] = await run(items[index]); } };
|
|
81
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
82
|
+
return results;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function assessGroup(group, context) {
|
|
86
|
+
if (!typesafe.enabled) return rulesOnly(group);
|
|
87
|
+
const { key, requests } = assessmentRequests(group, context, typesafe.model);
|
|
88
|
+
const cached = db.getCallAssessment(key);
|
|
89
|
+
if (cached) return withProbabilities(cached);
|
|
90
|
+
if (!pendingAssessments.has(key)) {
|
|
91
|
+
const task = (async () => {
|
|
92
|
+
const responses = await Promise.all(requests.map((request) => systemOne(typesafe, { state: request.state, questions: request.questions })));
|
|
93
|
+
const model = responses[0]?.model ?? typesafe.model;
|
|
94
|
+
const input_tokens = responses.reduce((sum, response) => sum + (response.usage?.input_tokens ?? 0), 0);
|
|
95
|
+
const result = { ...combineGroup(group, requests, responses), model, input_tokens };
|
|
96
|
+
db.putCallAssessment(key, group.call_id, model, { ...result, answers: responses.map((response) => response.answers) });
|
|
97
|
+
return result;
|
|
98
|
+
})().finally(() => pendingAssessments.delete(key));
|
|
99
|
+
pendingAssessments.set(key, task);
|
|
100
|
+
}
|
|
101
|
+
try { return await pendingAssessments.get(key); } catch (error) {
|
|
102
|
+
console.error('[raytace] Jev assessment unavailable:', error.message);
|
|
103
|
+
return rulesOnly(group);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Sets `severity` on each top-level command and returns call-level labels
|
|
108
|
+
* keyed by call id. Never throws: severity must not cost us the evidence. */
|
|
109
|
+
async function assessCommands(commands) {
|
|
110
|
+
const groups = groupByCall(commands);
|
|
111
|
+
const contexts = db.toolCallContexts(groups.map((group) => group.call_id));
|
|
112
|
+
const results = await mapLimit(groups, ASSESS_CONCURRENCY, (group) => assessGroup(group, contexts.get(group.call_id) ?? null));
|
|
113
|
+
const labels = {};
|
|
114
|
+
groups.forEach((group, index) => {
|
|
115
|
+
const { severities, labels: callLabels } = results[index];
|
|
116
|
+
group.trees.forEach((tree, position) => { tree.root.severity = severities[position] ?? null; });
|
|
117
|
+
if (callLabels && group.call_id) labels[group.call_id] = callLabels;
|
|
118
|
+
});
|
|
119
|
+
return labels;
|
|
56
120
|
}
|
|
121
|
+
|
|
57
122
|
async function record(event) {
|
|
58
123
|
const row = omitToolChunkIds(event);
|
|
59
124
|
if (row.event_type === 'model.exchange' && row.span_id) db.recordExchange(row);
|
|
@@ -62,36 +127,6 @@ async function record(event) {
|
|
|
62
127
|
if (archiveJsonl) { await mkdir(dirname(store), { recursive: true }); await appendFile(store, `${JSON.stringify(row)}\n`); }
|
|
63
128
|
}
|
|
64
129
|
function safeHeaders(headers) { const keep = ['content-type', 'anthropic-version', 'openai-beta', 'user-agent', 'x-request-id']; return Object.fromEntries(Object.entries(headers).filter(([key]) => keep.includes(key.toLowerCase()))); }
|
|
65
|
-
function shortened(value, limit = 104) { const text = typeof value === 'string' ? value : JSON.stringify(value ?? ''); return text.length > limit ? `${text.slice(0, limit - 1)}…` : text; }
|
|
66
|
-
function parseSseResponse(body) {
|
|
67
|
-
const events = [];
|
|
68
|
-
let completedResponse = null;
|
|
69
|
-
for (const frame of body.toString('utf8').replace(/\r\n/g, '\n').split('\n\n')) {
|
|
70
|
-
const data = frame.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trimStart()).join('\n');
|
|
71
|
-
if (!data || data === '[DONE]') continue;
|
|
72
|
-
try {
|
|
73
|
-
const event = JSON.parse(data);
|
|
74
|
-
events.push(event);
|
|
75
|
-
if (event.type === 'response.completed' && event.response) completedResponse = event.response;
|
|
76
|
-
} catch { /* retain the raw response hash when an SSE event is not JSON */ }
|
|
77
|
-
}
|
|
78
|
-
if (completedResponse) return completedResponse;
|
|
79
|
-
return events.length ? { stream: true, events } : null;
|
|
80
|
-
}
|
|
81
|
-
function toolKind(name) { const lower = name.toLowerCase(); return /search|rg|grep/.test(lower) ? 'search' : /read|open|cat|list/.test(lower) ? 'read' : /write|edit|patch|apply/.test(lower) ? 'edit' : 'test'; }
|
|
82
|
-
function event(kind, title, detail, time, raw) { return { kind, title, detail, time, raw: JSON.stringify(raw, null, 2) }; }
|
|
83
|
-
function publicOutput(item) {
|
|
84
|
-
// Reasoning items can contain opaque/private model state. Keep only the
|
|
85
|
-
// configuration and any explicit summary; never present hidden content as a trace.
|
|
86
|
-
if (item?.type === 'reasoning') return { type: 'reasoning', id: item.id, summary: item.summary ?? null, encrypted_content: item.encrypted_content ? '[present]' : undefined };
|
|
87
|
-
return item;
|
|
88
|
-
}
|
|
89
|
-
function extractText(item) {
|
|
90
|
-
const content = item?.content;
|
|
91
|
-
if (typeof content === 'string') return content;
|
|
92
|
-
if (Array.isArray(content)) return content.map((part) => part?.text || part?.content || '').filter(Boolean).join(' ');
|
|
93
|
-
return item?.text || '';
|
|
94
|
-
}
|
|
95
130
|
async function invokeReplay(entry, payload, signal) {
|
|
96
131
|
const headers = Object.fromEntries(Object.entries(entry.headers).filter(([key]) =>
|
|
97
132
|
['authorization', 'content-type', 'openai-organization', 'openai-project', 'openai-beta', 'user-agent'].includes(key.toLowerCase())));
|
|
@@ -106,50 +141,35 @@ async function invokeReplay(entry, payload, signal) {
|
|
|
106
141
|
return response.headers.get('content-type')?.includes('text/event-stream') ? parseSseResponse(body) : JSON.parse(body.toString());
|
|
107
142
|
}
|
|
108
143
|
async function persistExperiment(job) { db.saveExperiment(redact(omitToolChunkIds(job))); }
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
// Preserve the date and UTC offset so each viewer can render their local time.
|
|
112
|
-
const started = new Date(row.timestamp).toISOString(); const completed = new Date(row.completed_at || row.timestamp).toISOString();
|
|
113
|
-
const input = Array.isArray(request.input) ? request.input : Array.isArray(request.messages) ? request.messages : [];
|
|
114
|
-
const output = Array.isArray(response.output) ? response.output : Array.isArray(response.content) ? response.content : [];
|
|
115
|
-
const toolCount = (request.tools || []).length + input.flatMap((item) => item?.tools || []).length;
|
|
116
|
-
const live = liveExchanges.get(row.span_id);
|
|
117
|
-
const reason = live ? replayEligibility(live) : 'Capture a fresh request after starting this proxy. Replay snapshots expire after 30 minutes or a restart.';
|
|
118
|
-
let decision = null; try { decision = outcome(response); } catch { /* incomplete capture */ }
|
|
119
|
-
const steps = [event('model', 'Context assembled', `${request.model || 'unknown model'} · ${input.length} input items · ${toolCount} available tools`, started, { exchange_id: row.span_id, model: request.model, stream: request.stream, input_items: input.length, tool_count: toolCount, reasoning: request.reasoning ?? null, replay_reason: reason, decision })];
|
|
120
|
-
for (const item of input) {
|
|
121
|
-
if (!/function_call_output|tool_result/i.test(item?.type || '')) continue;
|
|
122
|
-
const name = item.name || item.tool_name || item.call_id || 'tool';
|
|
123
|
-
steps.push(event(toolKind(name), `Tool result: ${name}`, toolResultStatus(item), started, item));
|
|
124
|
-
}
|
|
125
|
-
for (const [outputIndex, item] of output.entries()) {
|
|
126
|
-
if (item?.type === 'reasoning') {
|
|
127
|
-
const effort = response.reasoning?.effort || request.reasoning?.effort || 'model default';
|
|
128
|
-
steps.push(event('model', 'Reasoning phase', `Effort: ${effort}. Private reasoning content is intentionally not displayed.`, completed, publicOutput(item)));
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
const name = item?.name || item?.function?.name;
|
|
132
|
-
if (name && /function_call|tool_use|tool_call/i.test(item?.type || '')) {
|
|
133
|
-
const data = item.arguments || item.input || item.function?.arguments || '';
|
|
134
|
-
steps.push({ ...event(toolKind(name), `Tool call: ${name}`, shortened(data), completed, publicOutput(item)), exchange_id: row.span_id, output_index: outputIndex });
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
if (/message|text/i.test(item?.type || '')) steps.push({ ...event('model', 'Model answer', shortened(extractText(item), 180) || 'Message completed', completed, publicOutput(item)), exchange_id: row.span_id, output_index: outputIndex });
|
|
138
|
-
}
|
|
139
|
-
steps.push(event('model', `Exchange complete · ${row.response?.status || 'unknown'}`, `${row.request?.bytes || 0} B sent · ${row.response?.bytes || 0} B received`, completed, { response_status: response.status ?? null, http_status: row.response?.status ?? null, request_bytes: row.request?.bytes || 0, response_bytes: row.response?.bytes || 0, response_reasoning: response.reasoning ?? null }));
|
|
140
|
-
return steps;
|
|
141
|
-
}
|
|
144
|
+
/** The fields that identify and time the sandbox process a call ran as
|
|
145
|
+
* (db.divergence). All null when nothing was observed for the call. */
|
|
142
146
|
// The trace list takes seconds to build for long sessions and is polled every
|
|
143
147
|
// few seconds, mostly with nothing new: it is rebuilt only when the data
|
|
144
148
|
// behind it changed (db.dataVersion), and one build serves every caller.
|
|
145
149
|
// The body is serialized once per version too, and its version is its ETag,
|
|
146
150
|
// so a poll with nothing new is answered 304 without sending anything.
|
|
151
|
+
/** The trace view over this proxy's store; a replay is offered for exchanges
|
|
152
|
+
* still held in memory (liveExchanges). */
|
|
153
|
+
function readTraces(includeHistory = false, { evidence = true } = {}) {
|
|
154
|
+
return traceView(db, { includeHistory, evidence, replayReason: (spanId) => {
|
|
155
|
+
const live = liveExchanges.get(spanId);
|
|
156
|
+
return live ? replayEligibility(live) : undefined;
|
|
157
|
+
} });
|
|
158
|
+
}
|
|
147
159
|
const traceCache = new Map(); // url -> { version, body: Promise<string> }
|
|
160
|
+
// The Tool column's category for a shell command no rule places (Jev). An
|
|
161
|
+
// answer changes no row dataVersion counts, so each one moves the view's
|
|
162
|
+
// version itself: the next poll is rebuilt and not answered 304.
|
|
163
|
+
const resolveCategories = categoryResolver({ config: typesafe, ask: (request) => systemOne(typesafe, request) });
|
|
164
|
+
let categoryAnswers = 0;
|
|
148
165
|
function cachedTraces(url) {
|
|
149
|
-
const version = db.dataVersion()
|
|
166
|
+
const version = `${db.dataVersion()}:${categoryAnswers}`;
|
|
150
167
|
const hit = traceCache.get(url);
|
|
151
168
|
if (hit?.version === version) return hit;
|
|
152
169
|
const body = readTraces(url !== '/raytace/traces', { evidence: url !== '/raytace/traces?scope=history' })
|
|
170
|
+
.then((traces) => resolveCategories(traces, { get: (key) => db.getCallAssessment(key),
|
|
171
|
+
put: (key, model, value) => db.putCallAssessment(key, null, model, value),
|
|
172
|
+
onSettled: () => { categoryAnswers += 1; } }))
|
|
153
173
|
.then((traces) => JSON.stringify({ traces }));
|
|
154
174
|
const entry = { version, etag: `"${version}"`, body };
|
|
155
175
|
traceCache.set(url, entry);
|
|
@@ -160,95 +180,6 @@ function cachedTraces(url) {
|
|
|
160
180
|
/** `evidence: false` skips building each request's context items, the
|
|
161
181
|
* costliest part (every request resends the conversation so far), for
|
|
162
182
|
* callers that do not send them on. */
|
|
163
|
-
async function readTraces(includeHistory = false, { evidence = true } = {}) {
|
|
164
|
-
const rows = db.exchangeRows({ history: includeHistory }).map(omitToolChunkIds);
|
|
165
|
-
// Rows arrive already grouped: each carries its turn as trace_id and the
|
|
166
|
-
// turn's prompt as promptTitle, decided once at capture (evidence-store.mjs).
|
|
167
|
-
const groupedRows = rows;
|
|
168
|
-
// The store already scopes the live view to the newest session; keep the
|
|
169
|
-
// filter so captures made before session tracking behave as they always did.
|
|
170
|
-
const exchangeRows = includeHistory ? groupedRows : (latestSessionRows(groupedRows).length ? latestSessionRows(groupedRows) : groupedRows);
|
|
171
|
-
// A tool call proposed in one captured exchange comes back as evidence (its
|
|
172
|
-
// result) in a later one. Index call_id -> the exchange that first proposed it
|
|
173
|
-
// so the UI can jump from "this evidence" to "the decision that produced it".
|
|
174
|
-
const origins = new Map();
|
|
175
|
-
for (const row of exchangeRows) {
|
|
176
|
-
const output = row.response?.payload?.output;
|
|
177
|
-
if (!Array.isArray(output)) continue;
|
|
178
|
-
for (const [outputIndex, item] of output.entries()) {
|
|
179
|
-
if (item?.call_id && /function_call|tool_use|tool_call/i.test(item?.type || '') && !origins.has(item.call_id)) {
|
|
180
|
-
origins.set(item.call_id, { call_id: item.call_id, trace_id: row.trace_id, exchange_id: row.span_id, output_index: outputIndex, name: item.name,
|
|
181
|
-
proposed: proposedCommand(item.arguments ?? item.input ?? item.function?.arguments ?? '') });
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
const grouped = new Map();
|
|
186
|
-
const shownResultsByTrace = new Map(); // trace_id -> Set(call_id) already rendered once
|
|
187
|
-
for (const row of exchangeRows) {
|
|
188
|
-
const trace = grouped.get(row.trace_id) || { id: row.trace_id, provider: row.provider, model: row.request?.payload?.model || 'unknown model', title: row.promptTitle, startedAt: row.timestamp, status: 'complete', events: [], evidence: [], requests: [] };
|
|
189
|
-
const shownResults = shownResultsByTrace.get(row.trace_id) || new Set();
|
|
190
|
-
shownResultsByTrace.set(row.trace_id, shownResults);
|
|
191
|
-
trace.requests.push({ id: row.span_id, model: row.request?.payload?.model || 'unknown', startedAt: row.timestamp, completedAt: row.completed_at || null, ...(row.metrics || requestMetrics(row)) });
|
|
192
|
-
// Rows are oldest-first, so the last request that produced text is the
|
|
193
|
-
// turn's final answer, and the last completion is when the turn ended.
|
|
194
|
-
trace.endedAt = row.completed_at || row.timestamp;
|
|
195
|
-
try { const text = outcome(row.response?.payload || {}).text; if (text) trace.answer = text; } catch { /* incomplete capture */ }
|
|
196
|
-
trace.events.push(...splitExchange(row).map((step) => {
|
|
197
|
-
if (!step.title.startsWith('Tool result:')) return step;
|
|
198
|
-
const raw = JSON.parse(step.raw); const origin = origins.get(raw.call_id);
|
|
199
|
-
// The tool result carries only a call_id and output, never the tool's
|
|
200
|
-
// name — fall back to the exchange that originally proposed the call,
|
|
201
|
-
// where the real name is known, instead of showing the raw id.
|
|
202
|
-
const label = origin?.name ? `Tool result: ${origin.name}` : step.title;
|
|
203
|
-
// The icon was classified from the same fallback name (usually the raw
|
|
204
|
-
// call_id, which never matches any category) — reclassify once the real
|
|
205
|
-
// tool name is known so the icon matches what the tool actually did.
|
|
206
|
-
const kind = origin?.name ? toolKind(origin.name) : step.kind;
|
|
207
|
-
// Clicking a result investigates the earlier decision to call that tool,
|
|
208
|
-
// using its pre-action context rather than its newly returned contents.
|
|
209
|
-
return { ...step, title: label, kind, ...(origin ? { exchange_id: origin.exchange_id, output_index: origin.output_index } : {}) };
|
|
210
|
-
}).filter((step) => {
|
|
211
|
-
if (!step.title.startsWith('Tool result:')) return true;
|
|
212
|
-
// Full conversation history is resent on every turn, so the same result
|
|
213
|
-
// would otherwise appear again in every later request's input — once is
|
|
214
|
-
// enough; the repeats carry no new information.
|
|
215
|
-
const raw = JSON.parse(step.raw);
|
|
216
|
-
if (!raw.call_id || !shownResults.has(raw.call_id)) { if (raw.call_id) shownResults.add(raw.call_id); return true; }
|
|
217
|
-
return false;
|
|
218
|
-
}));
|
|
219
|
-
for (const item of evidence ? evidenceFor(row.request?.payload, row.span_id) : []) {
|
|
220
|
-
const origin = item.call_id ? origins.get(item.call_id) : null;
|
|
221
|
-
trace.evidence.push({ ...item, origin: origin && origin.exchange_id !== row.span_id ? origin : null });
|
|
222
|
-
}
|
|
223
|
-
grouped.set(row.trace_id, trace);
|
|
224
|
-
}
|
|
225
|
-
// Every call each trace proposed, in order: unlike `evidence`, this is not
|
|
226
|
-
// limited to calls whose result got resent as later input, so it includes
|
|
227
|
-
// a call in the very last response with no later request to resend it into.
|
|
228
|
-
for (const trace of grouped.values()) {
|
|
229
|
-
trace.callVerifications = [...origins.values()].filter((origin) => origin.trace_id === trace.id).map((origin) => ({
|
|
230
|
-
call_id: origin.call_id, exchange_id: origin.exchange_id, name: origin.name, output_index: origin.output_index, proposed: origin.proposed ?? null,
|
|
231
|
-
}));
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// Codex requests include a large tool schema. Return recent traces only so the
|
|
235
|
-
// live dashboard stays responsive instead of repeatedly transferring history.
|
|
236
|
-
const result = [...grouped.values()].sort((a, b) => b.startedAt.localeCompare(a.startedAt)).slice(0, includeHistory ? 100 : 10);
|
|
237
|
-
// Every request resends the whole conversation, so each earlier item comes
|
|
238
|
-
// back once per later request: a long Claude Code session made one prompt
|
|
239
|
-
// tens of MB, fetched every few seconds. An item is sent in full once; a
|
|
240
|
-
// repeat keeps only where it sits and names the item that has the rest
|
|
241
|
-
// (content_of).
|
|
242
|
-
for (const trace of result) {
|
|
243
|
-
const first = new Map();
|
|
244
|
-
trace.evidence = trace.evidence.map((item) => {
|
|
245
|
-
const key = `${item.kind}\0${item.label}\0${item.content ?? item.preview ?? ''}`;
|
|
246
|
-
if (!first.has(key)) { first.set(key, item.id); return item; }
|
|
247
|
-
return { id: item.id, exchange_id: item.exchange_id, index: item.index, kind: item.kind, label: item.label, call_id: item.call_id ?? null, content_of: first.get(key) };
|
|
248
|
-
});
|
|
249
|
-
}
|
|
250
|
-
return result;
|
|
251
|
-
}
|
|
252
183
|
|
|
253
184
|
|
|
254
185
|
// Context window sizes, from OpenRouter's public model list (no key needed),
|
|
@@ -271,7 +202,24 @@ async function promptContextFor(traceId) {
|
|
|
271
202
|
const last = trace?.requests?.at(-1);
|
|
272
203
|
const entry = last ? await savedOrLive(last.id) : null;
|
|
273
204
|
if (!entry) return null;
|
|
274
|
-
return { trace, context: promptContext(entry, trace.title, trace.answer ?? '') };
|
|
205
|
+
return { trace, context: promptContext(entry, trace.promptRaw ?? trace.title, trace.answer ?? '') };
|
|
206
|
+
}
|
|
207
|
+
// Recap (run-recap.mjs): the observer, a stronger model than the ones that
|
|
208
|
+
// label single steps, reads one prompt's run and says what it did and why.
|
|
209
|
+
// It is asked for by id, outside the sandboxes' model list.
|
|
210
|
+
const observerModel = process.env.RAYTACE_OBSERVER_MODEL || DEFAULT_OBSERVER;
|
|
211
|
+
const pendingRecaps = new Map();
|
|
212
|
+
/** The recap request for one prompt as it stands now, or null (no such prompt, or no tool calls). */
|
|
213
|
+
async function currentRecapRequest(traceId) {
|
|
214
|
+
const trace = (await readTraces(true, { evidence: false })).find((item) => item.id === traceId);
|
|
215
|
+
const outline = trace ? recapOutline(trace) : null;
|
|
216
|
+
return outline ? { outline, ...recapRequest(outline, observerModel) } : null;
|
|
217
|
+
}
|
|
218
|
+
async function askObserver(payload) {
|
|
219
|
+
const response = await fetch(`${routing.upstreams.openrouter}/v1/chat/completions`, { method: 'POST',
|
|
220
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${routing.apiKey}` }, body: JSON.stringify(payload), signal: AbortSignal.timeout(120_000) });
|
|
221
|
+
if (!response.ok) { await response.body?.cancel(); throw new Error(`The observer model returned HTTP ${response.status}.`); }
|
|
222
|
+
return response.json();
|
|
275
223
|
}
|
|
276
224
|
async function savedOrLive(exchangeId) {
|
|
277
225
|
return liveExchanges.get(exchangeId) || db.findExchange(exchangeId);
|
|
@@ -287,10 +235,57 @@ async function currentSummaryRequest(exchangeId) {
|
|
|
287
235
|
const ownResults = ownCalls.map((item) => ({ from: item.name, output: resultText(contexts.get(item.call_id)?.result) }));
|
|
288
236
|
return summaryRequest(entry, exchangeId, summaryModel, ownResults);
|
|
289
237
|
}
|
|
238
|
+
// Chain of thought (step-attribution.mjs): why one tool call was made. Only
|
|
239
|
+
// for prompts run in the sandbox (rtp- sessions); anything else is refused
|
|
240
|
+
// before a model is called.
|
|
241
|
+
const attributionModel = process.env.RAYTACE_ATTRIBUTION_MODEL ? selectModel(routing, process.env.RAYTACE_ATTRIBUTION_MODEL) : routing.defaultModel;
|
|
242
|
+
const SANDBOX_SESSION = /^rtp-[a-f0-9]{32}$/;
|
|
243
|
+
const pendingAttributions = new Map();
|
|
244
|
+
const MAX_CONCURRENT_ATTRIBUTIONS = 4;
|
|
245
|
+
|
|
246
|
+
/** The step and its cache key, or an `{ status, error }` to send back. */
|
|
247
|
+
function attributionStep(exchangeId, outputIndex) {
|
|
248
|
+
const entry = db.findExchange(String(exchangeId ?? ''));
|
|
249
|
+
if (!entry) return { status: 404, error: 'Saved step not found.' };
|
|
250
|
+
if (!SANDBOX_SESSION.test(entry.session_id ?? '')) return { status: 403, error: 'Chain of thought is only available for prompts run in the sandbox.' };
|
|
251
|
+
if (!entry.payload || !entry.response) return { status: 409, error: 'This capture has no saved request or response.' };
|
|
252
|
+
const step = prepareStep(omitToolChunkIds(entry), Number(outputIndex));
|
|
253
|
+
if (!step) return { status: 400, error: 'That output is not a tool call.' };
|
|
254
|
+
const proposer = routing.mode === 'openrouter' ? attributionModel : null;
|
|
255
|
+
return { step, key: attributionKey(step, proposer, typesafe.enabled ? typesafe.model : null), proposer };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function computeAttribution({ step, proposer }) {
|
|
259
|
+
let proposals = [];
|
|
260
|
+
let proposer_error = null;
|
|
261
|
+
if (proposer) {
|
|
262
|
+
try {
|
|
263
|
+
const { payload } = proposerRequest(step, proposer);
|
|
264
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(payload)));
|
|
265
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, payload, new AbortController().signal);
|
|
266
|
+
proposals = parseProposals(response, step.items);
|
|
267
|
+
} catch (error) { proposer_error = error.message; console.error('[raytace] Cause proposer unavailable:', error.message); }
|
|
268
|
+
}
|
|
269
|
+
const cands = candidates(step, proposals);
|
|
270
|
+
let result;
|
|
271
|
+
let jev_model = null;
|
|
272
|
+
if (!typesafe.enabled) result = withoutJev(cands, 'Add a TypeSafe key to rank these: raytrace key typesafe');
|
|
273
|
+
else {
|
|
274
|
+
try {
|
|
275
|
+
const { requests } = jevRequests(step, cands);
|
|
276
|
+
const responses = await Promise.all(requests.map((request) => systemOne(typesafe, request)));
|
|
277
|
+
jev_model = responses[0]?.model ?? typesafe.model;
|
|
278
|
+
result = combine(cands, responses);
|
|
279
|
+
} catch (error) { console.error('[raytace] Jev attribution unavailable:', error.message); result = withoutJev(cands, 'Jev was unavailable.'); }
|
|
280
|
+
}
|
|
281
|
+
return { ...result, action: step.call.name, proposer_model: proposer, proposer_error, jev_model };
|
|
282
|
+
}
|
|
283
|
+
|
|
290
284
|
const pendingExplanations = new Map();
|
|
291
285
|
const pendingSummaries = new Map();
|
|
292
286
|
const MAX_CONCURRENT_SUMMARIES = 4; // cheap+budget-capped calls; safe to run several at once instead of one at a time
|
|
293
287
|
|
|
288
|
+
|
|
294
289
|
// ---------------------------------------------------------------- Claude Code
|
|
295
290
|
// Proxy-free capture: Claude Code's hooks ring, and its session transcript is
|
|
296
291
|
// rebuilt into the same exchange rows the proxy records (claude-code-adapter).
|
|
@@ -311,15 +306,62 @@ function serially(path, job) {
|
|
|
311
306
|
claudeCodeQueues.set(path, settled);
|
|
312
307
|
return next;
|
|
313
308
|
}
|
|
314
|
-
|
|
309
|
+
/** `session` files the rows under a sandbox's rtp- id instead of the
|
|
310
|
+
* transcript's own session, and ties its processes to them afterwards. */
|
|
311
|
+
function ingestClaudeCode(path, { final, session = null }) {
|
|
315
312
|
serially(path, async () => {
|
|
316
|
-
const rows = exchangesFromTranscript(parseTranscript(await readFile(path, 'utf8')),
|
|
313
|
+
const rows = exchangesFromTranscript(parseTranscript(await readFile(path, 'utf8')),
|
|
314
|
+
{ final, sessionId: session?.id ?? null, sessionStartedAt: session?.startedAt ?? null });
|
|
317
315
|
for (const row of rows) {
|
|
318
316
|
await record({ ...row, request: { ...row.request, payload: redact(row.request.payload) }, response: { ...row.response, payload: redact(row.response.payload) } });
|
|
319
317
|
}
|
|
318
|
+
if (session) await attributeLateProcesses(db, session.id);
|
|
320
319
|
}).catch((error) => console.error(`Claude Code transcript ${path} could not be read: ${error.message}`));
|
|
321
320
|
}
|
|
322
321
|
|
|
322
|
+
// A sandboxed Claude Code's transcript lives in the sandbox. Its hook sends
|
|
323
|
+
// the new lines through the sandbox manager, which names the sandbox; they
|
|
324
|
+
// are appended to a copy here and read like any local transcript. `offset`
|
|
325
|
+
// must equal the copy's size, so a lost or repeated send is never spliced in
|
|
326
|
+
// twice: a mismatch answers 409 with the size to resend from.
|
|
327
|
+
const SANDBOX_ID = /^rtp-[a-f0-9]{32}$/;
|
|
328
|
+
const CLAUDE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
329
|
+
const sandboxTranscripts = join(dirname(store), 'claude-code');
|
|
330
|
+
// Playground forks of those sessions (playground.mjs). The hook installed in
|
|
331
|
+
// a fork is read fresh each time, so a fork runs the repo's current version.
|
|
332
|
+
const playground = startPlayground({ db, transcriptsDir: sandboxTranscripts,
|
|
333
|
+
hookSource: () => readFileSync(new URL('../worker/sandbox/claude-hook.mjs', import.meta.url), 'utf8') });
|
|
334
|
+
async function appendSandboxTranscript(sandbox, note) {
|
|
335
|
+
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.' } };
|
|
337
|
+
const directory = join(sandboxTranscripts, sandbox);
|
|
338
|
+
const path = join(directory, `${note.session_id}.jsonl`);
|
|
339
|
+
return serially(path, async () => {
|
|
340
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
341
|
+
const size = await stat(path).then((info) => info.size, () => 0);
|
|
342
|
+
if (note.offset !== size) return { status: 409, body: { size } };
|
|
343
|
+
await appendFile(path, note.text, { mode: 0o600 }); // creates it when a snapshot arrives before any line
|
|
344
|
+
return { status: 200, body: { size: size + Buffer.byteLength(note.text) }, path };
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** A snapshot as the sandbox hook reports it, checked field by field, or
|
|
349
|
+
* null. Paths are the agent's to name, so they are only bounded, never trusted. */
|
|
350
|
+
function sandboxSnapshot(value) {
|
|
351
|
+
const sha = /^[0-9a-f]{40}$/;
|
|
352
|
+
if (!value || typeof value !== 'object' || !sha.test(value.commit ?? '') || (value.parent != null && !sha.test(value.parent))
|
|
353
|
+
|| !['prompt', 'tool'].includes(value.taken_on) || (value.call_id != null && !/^[A-Za-z0-9_-]{1,128}$/.test(value.call_id))
|
|
354
|
+
|| !Number.isFinite(Date.parse(value.taken_at ?? ''))) return null;
|
|
355
|
+
const path = (item) => typeof item === 'string' && item.length <= 1024;
|
|
356
|
+
const count = (item) => (Number.isInteger(item) && item >= 0 ? item : null);
|
|
357
|
+
const changes = (Array.isArray(value.changes) ? value.changes : []).slice(0, 300).filter((item) => path(item?.path))
|
|
358
|
+
.map((item) => ({ path: item.path, status: /^[ADMTUX]$/.test(item.status ?? '') ? item.status : '?', added: count(item.added), removed: count(item.removed) }));
|
|
359
|
+
return { commit: value.commit, parent: value.parent ?? null, taken_on: value.taken_on, call_id: value.call_id ?? null,
|
|
360
|
+
taken_at: value.taken_at, changed: value.changed === true, changes,
|
|
361
|
+
too_big: (Array.isArray(value.too_big) ? value.too_big : []).slice(0, 300).filter(path) };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
|
|
323
365
|
// The prebuilt dashboard (RAYTACE_DASHBOARD_DIR), served from / so it and the
|
|
324
366
|
// API share one origin. Model traffic is under /v1 and the API under /raytace,
|
|
325
367
|
// so any other GET from a browser (no credentials) is a dashboard file; unknown
|
|
@@ -338,6 +380,28 @@ async function serveDashboard(req, res) {
|
|
|
338
380
|
res.end(body);
|
|
339
381
|
}
|
|
340
382
|
|
|
383
|
+
/** A local sandbox's Claude Code transcript lines, from its hook through the
|
|
384
|
+
* sandbox bridge (sandbox-bridge.mjs), which has named the sandbox by its
|
|
385
|
+
* token: copied here and read like a local transcript, filed under the
|
|
386
|
+
* sandbox's rtp- id so its recorded processes join them. Returns {status, body}. */
|
|
387
|
+
async function ingestFromSandbox(sandbox, note) {
|
|
388
|
+
// A Playground fork sends with the project's token, so the bridge names
|
|
389
|
+
// the project; the fork's own steps are filed under the fork, and only
|
|
390
|
+
// for a fork RayTrace made of that project.
|
|
391
|
+
const fork = note?.fork == null ? null : FORK_ID.test(note.fork) ? playground.forkOf(note.fork, sandbox) : false;
|
|
392
|
+
if (fork === false || (note?.fork != null && !fork)) return { status: 403, body: { error: 'Unknown Playground fork.' } };
|
|
393
|
+
const filedUnder = fork ? fork.id : sandbox;
|
|
394
|
+
const written = await appendSandboxTranscript(filedUnder, note).catch(() => ({ status: 500, body: { error: 'Transcript copy could not be written.' } }));
|
|
395
|
+
const snapshot = written.path ? sandboxSnapshot(note.snapshot) : null;
|
|
396
|
+
if (snapshot) {
|
|
397
|
+
try { db.recordSnapshot({ sessionId: filedUnder, agentSessionId: note.session_id, snapshot }); }
|
|
398
|
+
catch (error) { console.error(`Snapshot for ${filedUnder} could not be recorded: ${error.message}`); }
|
|
399
|
+
}
|
|
400
|
+
if (written.path) ingestClaudeCode(written.path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name),
|
|
401
|
+
session: { id: filedUnder, startedAt: fork ? fork.created_at : await sandboxes.createdAt(sandbox) } });
|
|
402
|
+
return written;
|
|
403
|
+
}
|
|
404
|
+
|
|
341
405
|
const server = createServer(async (req, res) => {
|
|
342
406
|
const fromAgent = req.headers.authorization || req.headers['x-api-key'] || req.headers['anthropic-version'];
|
|
343
407
|
if (dashboardDir && req.method === 'GET' && !fromAgent && !req.url?.startsWith('/raytace/') && !req.url?.startsWith('/v1/')) {
|
|
@@ -349,9 +413,99 @@ const server = createServer(async (req, res) => {
|
|
|
349
413
|
if (localApi && (!trustedOrigin(req.headers.origin) || !/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/.test(req.headers.host || ''))) {
|
|
350
414
|
res.writeHead(403); return res.end('Untrusted dashboard origin or host.');
|
|
351
415
|
}
|
|
352
|
-
const corsHeaders = { ...(req.headers.origin && trustedOrigin(req.headers.origin) ? { 'access-control-allow-origin': req.headers.origin } : {}), vary: 'Origin', 'access-control-allow-methods': 'GET,POST,OPTIONS', 'access-control-allow-headers': 'content-type,x-raytace-experiment,if-none-match', 'access-control-allow-private-network': 'true' };
|
|
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' };
|
|
353
417
|
const json = (status, value) => { res.writeHead(status, { 'content-type': 'application/json', ...corsHeaders, 'cache-control': 'no-store' }); res.end(JSON.stringify(redact(omitToolChunkIds(value)))); };
|
|
354
418
|
if (req.method === 'OPTIONS') { res.writeHead(204, corsHeaders); return res.end(); }
|
|
419
|
+
// This machine's local sandboxes. With the VM stopped they are still listed,
|
|
420
|
+
// from the CLI's records, as stopped. Prompt history comes from the traces.
|
|
421
|
+
if (req.method === 'GET' && req.url === '/raytace/sandboxes') {
|
|
422
|
+
const shape = (box, status) => ({ id: box.id, name: box.name, host: 'lima', on_host: true, status, created: box.created,
|
|
423
|
+
deleted: null, size_bytes: box.size_bytes ?? null, imported_bytes: null, transcripts: true, skipped_count: 0, scan: null });
|
|
424
|
+
try { return json(200, { sandboxes: (await sandboxes.list()).filter((box) => !box.fork_of).map((box) => shape(box, box.status === 'running' ? 'running' : 'stopped')) }); }
|
|
425
|
+
catch { return json(200, { sandboxes: (await sandboxes.known()).map((box) => shape(box, 'stopped')) }); }
|
|
426
|
+
}
|
|
427
|
+
// What the kernel layer saw a sandbox do: the fact engine's records in the VM.
|
|
428
|
+
const activityRoute = req.url?.match(/^\/raytace\/sandboxes\/(rtp-[a-f0-9]{32})\/activity(?:\?([a-z0-9=&]{1,80}))?$/);
|
|
429
|
+
if (req.method === 'GET' && activityRoute) {
|
|
430
|
+
const query = new URLSearchParams(activityRoute[2] ?? '');
|
|
431
|
+
const window = { since: Number(query.get('since')) || 0, until: Number(query.get('until')) || 0 };
|
|
432
|
+
try {
|
|
433
|
+
const box = (await sandboxes.list()).find((item) => item.id === activityRoute[1]);
|
|
434
|
+
if (!box) return json(404, { error: 'No such local sandbox.' });
|
|
435
|
+
return json(200, { id: box.id, name: box.name, ...(await sandboxes.activity(box.id, window)) });
|
|
436
|
+
} catch { return json(503, { error: NO_VM }); }
|
|
437
|
+
}
|
|
438
|
+
// The initial scan, restricted files and alerts are not kept for local sandboxes yet.
|
|
439
|
+
if (/^\/raytace\/(sandboxes\/rtp-[a-f0-9]{32}(\/files)?|alerts(\?sandbox=rtp-[a-f0-9]{32})?|alerts\/seen)$/.test(req.url ?? '')) {
|
|
440
|
+
if (req.method === 'GET' && req.url.startsWith('/raytace/alerts')) return json(200, { alerts: [] });
|
|
441
|
+
return json(404, { error: 'Not available for local sandboxes yet. Destroy one with: raytrace sandbox destroy <name>' });
|
|
442
|
+
}
|
|
443
|
+
if (req.method === 'GET' && req.url?.startsWith('/raytace/runtime?')) {
|
|
444
|
+
const query = new URL(req.url, 'http://localhost').searchParams;
|
|
445
|
+
const sandbox = query.get('sandbox');
|
|
446
|
+
const before = query.get('before') || '0';
|
|
447
|
+
// `since`/`until` scope the page to one agent turn (the prompt through the
|
|
448
|
+
// answer). Without them this returns the whole sandbox's history, which is
|
|
449
|
+
// every prompt ever run in it.
|
|
450
|
+
const since = query.get('since') || '0';
|
|
451
|
+
const until = query.get('until') || '0';
|
|
452
|
+
const raw = query.get('raw') === '1';
|
|
453
|
+
const ok = (value) => /^\d{1,16}$/.test(value);
|
|
454
|
+
if (!/^rtp-[a-f0-9]{32}$/.test(sandbox || '') || ![before, since, until].every(ok)) return json(400, { error: 'Invalid sandbox or cursor' });
|
|
455
|
+
try {
|
|
456
|
+
const project = (await sandboxes.list()).find((p) => p.id === sandbox);
|
|
457
|
+
if (!project?.container_id || !/^[a-f0-9]{64}$/.test(project.container_id)) return json(404, { error: 'Sandbox mapping unavailable' });
|
|
458
|
+
const window = `${since !== '0' ? `&since=${since}` : ''}${until !== '0' ? `&until=${until}` : ''}`;
|
|
459
|
+
// A windowed page wants everything in the window, not the newest 100:
|
|
460
|
+
// folding turns hundreds of raw events into a handful of commands.
|
|
461
|
+
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) });
|
|
463
|
+
if (!evidence.ok) throw new Error('Runtime collector unavailable');
|
|
464
|
+
const page = await evidence.json();
|
|
465
|
+
const base = { ...page, sandbox, container_id: project.container_id };
|
|
466
|
+
// `raw=1` is the "show everything" escape hatch: the folded view must
|
|
467
|
+
// always be auditable against what the collector actually recorded.
|
|
468
|
+
if (raw) return json(200, base);
|
|
469
|
+
|
|
470
|
+
const { commands, folded } = foldEvents(page.events);
|
|
471
|
+
// Which call each process belongs to, by the process's own identity
|
|
472
|
+
// (pid + start time) within this sandbox. `attribution` stays null when
|
|
473
|
+
// the process was not recorded yet -- not the same as unattributed,
|
|
474
|
+
// which is a recorded process that matched no call.
|
|
475
|
+
const known = new Map(db.attributionsForProcesses({ containerId: project.container_id, pids: commands.map((c) => c.pid) })
|
|
476
|
+
.map((row) => [`${row.pid}:${row.start_time_ns}`, row]));
|
|
477
|
+
for (const command of commands) {
|
|
478
|
+
const row = command.process_start_ns ? known.get(`${command.pid}:${command.process_start_ns}`) : null;
|
|
479
|
+
command.attribution = row ? { call_id: row.call_id ?? null, parent_call_id: row.parent_call_id ?? null, tier: row.tier ?? null } : null;
|
|
480
|
+
}
|
|
481
|
+
attributeMarked(commands);
|
|
482
|
+
// Cache first, so a repeat view of the same turn costs nothing. Only
|
|
483
|
+
// commands no rule can describe are ever sent to a model.
|
|
484
|
+
describeAll(commands, (command) => db.getCommandDescription(command));
|
|
485
|
+
const missing = undescribed(commands);
|
|
486
|
+
if (missing.length && routing.mode === 'openrouter') {
|
|
487
|
+
try {
|
|
488
|
+
const request = describeRequest(missing, summaryModel);
|
|
489
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
490
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
491
|
+
const text = (response.output || []).filter((item) => item.type === 'message')
|
|
492
|
+
.map((item) => (item.content || []).map((part) => part.text || '').join('')).join(' ');
|
|
493
|
+
for (const [command, description] of parseDescriptions(text, request.commands)) {
|
|
494
|
+
db.putCommandDescription(command, description, summaryModel);
|
|
495
|
+
}
|
|
496
|
+
describeAll(commands, (command) => db.getCommandDescription(command));
|
|
497
|
+
} catch (error) {
|
|
498
|
+
// A failed description must never cost us the evidence: the commands
|
|
499
|
+
// still render, just verbatim.
|
|
500
|
+
console.error('[raytace] command descriptions unavailable:', error.message);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
let call_labels = {};
|
|
504
|
+
try { call_labels = await assessCommands(commands); }
|
|
505
|
+
catch (error) { console.error('[raytace] command severity unavailable:', error.message); }
|
|
506
|
+
return json(200, { ...base, commands, folded, call_labels, severity_source: typesafe.enabled ? 'jev' : 'rules', events: undefined });
|
|
507
|
+
} catch { return json(503, { error: 'Runtime evidence unavailable: the local sandbox VM is not running. Missing evidence is not proof of non-execution.' }); }
|
|
508
|
+
}
|
|
355
509
|
// The dashboard polls the history every few seconds: its context items
|
|
356
510
|
// (`evidence`) grow with the square of a session's length, so the history
|
|
357
511
|
// carries them only when asked for (&evidence=1, Compare runs). The recent
|
|
@@ -366,8 +520,24 @@ const server = createServer(async (req, res) => {
|
|
|
366
520
|
}
|
|
367
521
|
catch (error) { res.writeHead(500, { 'content-type': 'application/json', ...corsHeaders }); return res.end(JSON.stringify({ error: String(error) })); }
|
|
368
522
|
}
|
|
523
|
+
// Splunk-style search over the derived index (search.mjs). `from`/`to`
|
|
524
|
+
// are epoch ms or ISO dates; the query itself carries fields and pipes.
|
|
525
|
+
if (req.method === 'GET' && (req.url === '/raytace/search' || req.url?.startsWith('/raytace/search?') || req.url?.startsWith('/raytace/search/signatures'))) {
|
|
526
|
+
try {
|
|
527
|
+
const params = new URL(req.url, 'http://localhost').searchParams;
|
|
528
|
+
const bound = (name) => { const raw = params.get(name); if (!raw) return null; const ms = /^\d+$/.test(raw) ? Number(raw) : Date.parse(raw); return Number.isFinite(ms) ? ms : null; };
|
|
529
|
+
const range = { fromMs: bound('from'), toMs: bound('to') };
|
|
530
|
+
if (req.url.startsWith('/raytace/search/signatures')) {
|
|
531
|
+
return json(200, { signatures: db.failureSignatures({ ...range, limit: Number(params.get('limit')) || 20 }) });
|
|
532
|
+
}
|
|
533
|
+
return json(200, db.search({ q: params.get('q') ?? '', ...range, limit: Number(params.get('limit')) || 50, offset: Number(params.get('offset')) || 0 }));
|
|
534
|
+
} catch (error) { return json(500, { error: `Search failed: ${error.message}` }); }
|
|
535
|
+
}
|
|
369
536
|
// Who is signed in and which paid features they have. Nobody yet: sign-in
|
|
370
537
|
// comes with the RayTrace cloud; the dashboard already reads this shape.
|
|
538
|
+
// Which proxy this is, so the CLI can tell an outdated one still running
|
|
539
|
+
// after an upgrade (src/proxy-process.mjs PROXY_API) and replace it.
|
|
540
|
+
if (req.method === 'GET' && req.url === '/raytace/version') return json(200, { api: PROXY_API });
|
|
371
541
|
if (req.method === 'GET' && req.url === '/raytace/account') return json(200, { signed_in: false, plan: 'free', features: [] });
|
|
372
542
|
if (req.method === 'GET' && req.url === '/raytace/models') return json(200, { models: routing.mode === 'openrouter' ? Object.entries(routing.models).map(([alias, id]) => ({ alias, id })) : [], execution_available: routing.mode === 'openrouter' });
|
|
373
543
|
const stepRoute = req.url?.match(/^\/raytace\/steps\/([a-f0-9-]+)\/(\d+)$/);
|
|
@@ -407,6 +577,11 @@ const server = createServer(async (req, res) => {
|
|
|
407
577
|
res.writeHead(text == null ? 404 : 200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
408
578
|
return res.end(text ?? 'Not found in the captured context.');
|
|
409
579
|
}
|
|
580
|
+
const recapRoute = req.url?.match(/^\/raytace\/recap\/([A-Za-z0-9_-]{1,80})$/);
|
|
581
|
+
if (req.method === 'GET' && recapRoute) {
|
|
582
|
+
const request = await currentRecapRequest(recapRoute[1]);
|
|
583
|
+
return json(200, { recap: request ? db.getSummary(request.key) : null, available: Boolean(request), model: observerModel });
|
|
584
|
+
}
|
|
410
585
|
const summaryRoute = req.url?.match(/^\/raytace\/summaries\/([a-f0-9-]+)$/);
|
|
411
586
|
// Only a summary of the step as it stands now: one written by an older
|
|
412
587
|
// version, or before the step's own result was known, is not served.
|
|
@@ -414,7 +589,40 @@ const server = createServer(async (req, res) => {
|
|
|
414
589
|
const request = await currentSummaryRequest(summaryRoute[1]);
|
|
415
590
|
return json(200, { summary: request ? db.getSummary(request.key) : null, model: summaryModel });
|
|
416
591
|
}
|
|
592
|
+
const attributionRoute = req.url?.match(/^\/raytace\/attribution\/([A-Za-z0-9_.:-]{1,120})\/(\d{1,5})$/);
|
|
593
|
+
if (req.method === 'GET' && attributionRoute) {
|
|
594
|
+
const found = attributionStep(decodeURIComponent(attributionRoute[1]), attributionRoute[2]);
|
|
595
|
+
if (found.error) return json(found.status, { error: found.error });
|
|
596
|
+
return json(200, { attribution: db.getExplanation(found.key) });
|
|
597
|
+
}
|
|
417
598
|
if (req.method === 'GET' && req.url === '/raytace/experiments') return json(200, { experiments: [...jobs.values()].slice(-30).reverse() });
|
|
599
|
+
// Playground forks (playground.mjs): listed and read freely, changed only
|
|
600
|
+
// with the dashboard's header, like experiments.
|
|
601
|
+
if (req.method === 'GET' && req.url === '/raytace/forks') return json(200, { forks: playground.list() });
|
|
602
|
+
const previewRoute = req.url?.match(/^\/raytace\/forks\/preview\/([a-f0-9-]{36})$/);
|
|
603
|
+
if (req.method === 'GET' && previewRoute) {
|
|
604
|
+
try { return json(200, await playground.preview(previewRoute[1])); } catch (error) { return json(400, { error: error.message }); }
|
|
605
|
+
}
|
|
606
|
+
// A project's snapshot history, read-only: its files at a snapshot, one
|
|
607
|
+
// file, or the diff between two snapshots (a fork's live under refs/forks/).
|
|
608
|
+
const snapRoute = req.url?.match(/^\/raytace\/snapshots\/(rtp-[a-f0-9]{32})\/(files|file|diff)\?(.*)$/);
|
|
609
|
+
if (req.method === 'GET' && snapRoute) {
|
|
610
|
+
const query = new URLSearchParams(snapRoute[3]);
|
|
611
|
+
const request = { op: { files: 'list', file: 'show', diff: 'diff' }[snapRoute[2]], commit: query.get('commit') ?? '',
|
|
612
|
+
...(query.get('to') ? { to: query.get('to') } : {}), ...(query.get('path') ? { path: query.get('path') } : {}) };
|
|
613
|
+
try { return json(200, await playground.snapshot(snapRoute[1], request)); } catch (error) { return json(400, { error: error.message }); }
|
|
614
|
+
}
|
|
615
|
+
const forkRoute = req.url?.match(/^\/raytace\/forks\/(rtf-[a-f0-9]{32})(?:\/(keep|unkeep|delete|stop-all))?$/);
|
|
616
|
+
if (forkRoute) {
|
|
617
|
+
if (req.method === 'GET' && !forkRoute[2]) { const fork = playground.get(forkRoute[1]); return fork ? json(200, fork) : json(404, { error: 'Fork not found.' }); }
|
|
618
|
+
if (req.method !== 'POST' || !forkRoute[2] || req.headers['x-raytace-experiment'] !== '1') return json(403, { error: 'Use the Playground in the dashboard.' });
|
|
619
|
+
try {
|
|
620
|
+
const action = forkRoute[2];
|
|
621
|
+
return json(200, action === 'delete' ? await playground.remove(forkRoute[1]) : action === 'stop-all' ? await playground.stopGroup(forkRoute[1])
|
|
622
|
+
: playground.keep(forkRoute[1], action === 'keep'));
|
|
623
|
+
}
|
|
624
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
625
|
+
}
|
|
418
626
|
const jobRoute = req.url?.match(/^\/raytace\/experiments\/([a-f0-9-]+)(\/cancel)?$/);
|
|
419
627
|
if (jobRoute) {
|
|
420
628
|
const job = jobs.get(jobRoute[1]); if (!job) return json(404, { error: 'Experiment not found.' });
|
|
@@ -425,7 +633,8 @@ const server = createServer(async (req, res) => {
|
|
|
425
633
|
// Claude Code hook doorbell (proxy/claude-code-hook.mjs): "this session's
|
|
426
634
|
// transcript has new lines". Answered at once; the transcript is read
|
|
427
635
|
// afterwards so the hook never holds Claude Code up. The custom header is
|
|
428
|
-
// not in the CORS allow-list, so a web page cannot ring it.
|
|
636
|
+
// not in the CORS allow-list, so a web page cannot ring it. A local
|
|
637
|
+
// sandbox's hook sends its lines to the sandbox bridge instead (ingestFromSandbox).
|
|
429
638
|
if (req.method === 'POST' && req.url === '/raytace/ingest/claude-code') {
|
|
430
639
|
if (req.headers['x-raytace-hook'] !== '1' || !req.headers['content-type']?.includes('application/json')) return json(403, { error: 'Claude Code hook requests only.' });
|
|
431
640
|
const chunks = []; let size = 0;
|
|
@@ -438,14 +647,18 @@ const server = createServer(async (req, res) => {
|
|
|
438
647
|
ingestClaudeCode(path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) });
|
|
439
648
|
return;
|
|
440
649
|
}
|
|
441
|
-
if (localApi && (req.method !== 'POST' || !['/raytace/experiments', '/raytace/step-runs',
|
|
650
|
+
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.' });
|
|
442
651
|
if (localApi && (req.headers['x-raytace-experiment'] !== '1' || !req.headers['content-type']?.includes('application/json'))) return json(403, { error: 'Use the experiment control in the dashboard.' });
|
|
443
652
|
const parts = []; let bytes = 0;
|
|
444
653
|
for await (const part of req) { bytes += part.length; if (bytes > (localApi ? 600_000 : 20_000_000)) return json(413, { error: 'Request too large.' }); parts.push(part); }
|
|
445
654
|
const requestBody = Buffer.concat(parts);
|
|
655
|
+
if (req.method === 'POST' && req.url === '/raytace/forks') {
|
|
656
|
+
try { return json(202, await playground.create(JSON.parse(requestBody))); }
|
|
657
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
658
|
+
}
|
|
446
659
|
if (req.method === 'POST' && req.url === '/raytace/explanations') {
|
|
447
660
|
try {
|
|
448
|
-
if (routing.mode !== 'openrouter') return json(400, { error: '
|
|
661
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Explanations need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
449
662
|
const config = JSON.parse(requestBody);
|
|
450
663
|
const entry = await savedOrLive(config.exchange_id);
|
|
451
664
|
if (!entry) return json(404, { error: 'Saved step not found.' });
|
|
@@ -467,9 +680,49 @@ const server = createServer(async (req, res) => {
|
|
|
467
680
|
try { return json(200, await pendingExplanations.get(request.key)); } finally { pendingExplanations.delete(request.key); }
|
|
468
681
|
} catch (error) { return json(400, { error: error.message }); }
|
|
469
682
|
}
|
|
683
|
+
if (req.method === 'POST' && req.url === '/raytace/attribution') {
|
|
684
|
+
try {
|
|
685
|
+
const config = JSON.parse(requestBody);
|
|
686
|
+
const found = attributionStep(config.exchange_id, config.output_index);
|
|
687
|
+
if (found.error) return json(found.status, { error: found.error });
|
|
688
|
+
const cached = db.getExplanation(found.key);
|
|
689
|
+
if (cached) return json(200, cached);
|
|
690
|
+
if (!pendingAttributions.has(found.key)) {
|
|
691
|
+
if (pendingAttributions.size >= MAX_CONCURRENT_ATTRIBUTIONS) return json(409, { error: 'Too many steps in flight. Try again shortly.' });
|
|
692
|
+
const task = (async () => {
|
|
693
|
+
const result = await computeAttribution(found);
|
|
694
|
+
// A result missing a model only because it failed is not cached, so
|
|
695
|
+
// the next open retries it.
|
|
696
|
+
if (!result.proposer_error && (result.ranked || !typesafe.enabled)) db.putExplanation(found.key, result);
|
|
697
|
+
return result;
|
|
698
|
+
})().finally(() => pendingAttributions.delete(found.key));
|
|
699
|
+
pendingAttributions.set(found.key, task);
|
|
700
|
+
}
|
|
701
|
+
return json(200, await pendingAttributions.get(found.key));
|
|
702
|
+
} catch (error) { console.error('Attribution failed:', error); return json(400, { error: error.message }); }
|
|
703
|
+
}
|
|
704
|
+
if (req.method === 'POST' && req.url === '/raytace/recap') {
|
|
705
|
+
try {
|
|
706
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Recaps need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
707
|
+
const request = await currentRecapRequest(String(JSON.parse(requestBody).trace_id ?? ''));
|
|
708
|
+
if (!request) return json(404, { error: 'Nothing to recap: the prompt was not found, or it made no tool calls.' });
|
|
709
|
+
const cached = db.getSummary(request.key);
|
|
710
|
+
if (cached) return json(200, cached);
|
|
711
|
+
if (!pendingRecaps.has(request.key)) {
|
|
712
|
+
pendingRecaps.set(request.key, (async () => {
|
|
713
|
+
const recap = parseRecap(recapText(await askObserver(request.payload)), request.outline);
|
|
714
|
+
if (!recap) throw new Error('The observer did not return a usable recap. Try again.');
|
|
715
|
+
const result = { ...recap, model: observerModel, created_at: new Date().toISOString() };
|
|
716
|
+
db.putSummary(request.key, null, result);
|
|
717
|
+
return result;
|
|
718
|
+
})().finally(() => pendingRecaps.delete(request.key)));
|
|
719
|
+
}
|
|
720
|
+
return json(200, await pendingRecaps.get(request.key));
|
|
721
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
722
|
+
}
|
|
470
723
|
if (req.method === 'POST' && req.url === '/raytace/prompt-context/summary') {
|
|
471
724
|
try {
|
|
472
|
-
if (routing.mode !== 'openrouter') return json(400, { error: '
|
|
725
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Summaries need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
473
726
|
const found = await promptContextFor(String(JSON.parse(requestBody).trace_id ?? ''));
|
|
474
727
|
if (!found) return json(404, { error: 'Prompt not found in the captured history.' });
|
|
475
728
|
const request = contextSummaryRequest(found.context, summaryModel);
|
|
@@ -491,7 +744,7 @@ const server = createServer(async (req, res) => {
|
|
|
491
744
|
}
|
|
492
745
|
if (req.method === 'POST' && req.url === '/raytace/summaries') {
|
|
493
746
|
try {
|
|
494
|
-
if (routing.mode !== 'openrouter') return json(400, { error: '
|
|
747
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Summaries need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
495
748
|
const config = JSON.parse(requestBody);
|
|
496
749
|
const request = await currentSummaryRequest(config.exchange_id);
|
|
497
750
|
if (!request) return json(404, { error: 'Saved step not found.' });
|
|
@@ -560,7 +813,7 @@ const server = createServer(async (req, res) => {
|
|
|
560
813
|
const spanId = randomUUID();
|
|
561
814
|
const sessionId = req.headers['x-raytace-session-id'];
|
|
562
815
|
const sessionStartedAt = req.headers['x-raytace-session-started-at'];
|
|
563
|
-
const session = typeof sessionId === 'string' && /^[a-f0-9-]{36}$/.test(sessionId) && typeof sessionStartedAt === 'string' && Number.isFinite(Date.parse(sessionStartedAt))
|
|
816
|
+
const session = typeof sessionId === 'string' && /^(?:[a-f0-9-]{36}|rtp-[a-f0-9]{32})$/.test(sessionId) && typeof sessionStartedAt === 'string' && Number.isFinite(Date.parse(sessionStartedAt))
|
|
564
817
|
? { session_id: sessionId, session_started_at: new Date(sessionStartedAt).toISOString() } : fallbackSession;
|
|
565
818
|
const requestPayload = routed.payload;
|
|
566
819
|
try {
|
|
@@ -595,6 +848,7 @@ server.on('error', (error) => {
|
|
|
595
848
|
});
|
|
596
849
|
try {
|
|
597
850
|
for (const job of db.loadExperiments(200).reverse()) {
|
|
851
|
+
if (job.kind === 'fork') continue; // Playground forks: playground.mjs
|
|
598
852
|
if (['queued', 'running'].includes(job.status)) job.status = 'interrupted';
|
|
599
853
|
jobs.set(job.id, job);
|
|
600
854
|
}
|
|
@@ -603,6 +857,36 @@ try {
|
|
|
603
857
|
server.listen(port, '127.0.0.1', () => {
|
|
604
858
|
const stats = db.stats();
|
|
605
859
|
console.log(`RayTrace proxy listening on http://127.0.0.1:${server.address().port}`);
|
|
606
|
-
console.
|
|
860
|
+
playground.recover().catch((error) => console.error(`Playground forks could not be checked: ${error.message}`));
|
|
861
|
+
console.log(`Store: ${dbFile} (journal=${db.journal}, ${stats.sessions} sessions, ${stats.turns} turns, ${stats.exchanges} exchanges, ${stats.processes} sandbox processes)`);
|
|
607
862
|
});
|
|
608
|
-
|
|
863
|
+
// gVisor sandbox evidence (worker/sandbox/): discovers the local sandboxes from the
|
|
864
|
+
// Mac-side manager (:8799) and tails each one's process events from the
|
|
865
|
+
// evidence viewer (:8798), recording matched execs as the primary witness
|
|
866
|
+
// for those sessions. Best-effort: with neither service running it logs
|
|
867
|
+
// once and idles. RAYTACE_GVISOR_FORWARDER=0 turns it off entirely.
|
|
868
|
+
const gvisorForwarder = process.env.RAYTACE_GVISOR_FORWARDER === '0' ? null : startGvisorForwarder({
|
|
869
|
+
listProjects: () => sandboxes.list(),
|
|
870
|
+
viewerBase: EVIDENCE_VIEWER,
|
|
871
|
+
ingest: (events, { sessionId }) => ingestExecutions(db, events, { sessionId }),
|
|
872
|
+
// Exits, found by the process's own identity (pid + start time), so an
|
|
873
|
+
// exit closes its process even after a proxy restart or for a process the
|
|
874
|
+
// forwarder never tracked.
|
|
875
|
+
finish: (row) => recordExit(row),
|
|
876
|
+
finishByProcess: (row) => recordExit(row),
|
|
877
|
+
// A sandbox whose remaining exits can no longer arrive.
|
|
878
|
+
lose: (row) => db.loseOpenProcesses({ containerId: row.container_id, reason: row.reason, raw: row.raw ?? null, ended: row.ended === true }),
|
|
879
|
+
// Processes that ran underneath a matched call, and ones that matched
|
|
880
|
+
// nothing at all (parent_call_id null): recorded either way.
|
|
881
|
+
descend: ({ exec, parent_call_id, session_id }) => {
|
|
882
|
+
const started = db.recordProcessStart({ containerId: exec.container_id, projectId: session_id ?? null, raw: exec.raw, startedMs: exec.timestamp });
|
|
883
|
+
if (parent_call_id && started?.eventId) db.attribute({ toolCallId: parent_call_id, eventId: started.eventId, method: 'inherited', confidence: 'corroborated' });
|
|
884
|
+
},
|
|
885
|
+
});
|
|
886
|
+
function recordExit(row) {
|
|
887
|
+
return db.recordProcessExit({ containerId: row.container_id, projectId: row.session_id ?? null, raw: row.raw,
|
|
888
|
+
endedMs: row.ended_ms ?? null, exit_code: row.exit_code ?? null, signal: row.signal ?? null });
|
|
889
|
+
}
|
|
890
|
+
// Local sandboxes' Claude Code transcripts (raytrace sandbox create --local).
|
|
891
|
+
startSandboxBridge({ dataDir, port: Number(process.env.RAYTRACE_BRIDGE_PORT || 8799), ingest: ingestFromSandbox });
|
|
892
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { try { gvisorForwarder?.stop(); db.close(); } finally { process.exit(0); } });
|