@raytrace-cli/cli 0.4.0 → 0.6.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 -123
- package/bin/raytrace.mjs +110 -22
- 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-Dc3LTk8b.js +38 -0
- package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
- package/dist/dashboard/index.html +2 -2
- package/package.json +4 -1
- package/proxy/agent-intent-schema.test.mjs +142 -0
- package/proxy/call-assessment.mjs +385 -0
- package/proxy/call-assessment.test.mjs +167 -0
- package/proxy/call-category.mjs +461 -0
- package/proxy/capture.mjs +38 -0
- package/proxy/capture.test.mjs +49 -0
- package/proxy/claude-code-adapter.mjs +65 -3
- package/proxy/claude-code-hook.mjs +3 -1
- package/proxy/codex-config.mjs +5 -0
- package/proxy/codex.mjs +3 -2
- package/proxy/evidence-schema.test.mjs +233 -0
- package/proxy/evidence-store.mjs +704 -33
- package/proxy/evidence-store.test.mjs +304 -0
- package/proxy/exec-narrative.mjs +625 -0
- package/proxy/exec-narrative.test.mjs +262 -0
- package/proxy/execution-correlation.mjs +185 -0
- package/proxy/execution-correlation.test.mjs +146 -0
- package/proxy/execution-runner.test.mjs +38 -0
- package/proxy/experiment-engine.mjs +7 -4
- package/proxy/experiment-engine.test.mjs +93 -0
- package/proxy/explanations.test.mjs +20 -0
- package/proxy/failure-signature.mjs +56 -0
- package/proxy/gvisor-forwarder.mjs +454 -0
- package/proxy/gvisor-forwarder.test.mjs +368 -0
- package/proxy/init-evidence-db.mjs +166 -12
- package/proxy/local-sandboxes.mjs +94 -0
- package/proxy/local-token.mjs +30 -0
- package/proxy/playground-recovery.test.mjs +130 -0
- package/proxy/playground.mjs +439 -0
- package/proxy/prompt-context.mjs +12 -7
- package/proxy/prompt-traces.mjs +6 -0
- package/proxy/prompt-traces.test.mjs +32 -0
- package/proxy/providers.test.mjs +76 -0
- package/proxy/proxy.integration.test.mjs +135 -0
- package/proxy/raytace-proxy.mjs +512 -188
- package/proxy/request-metrics.test.mjs +19 -0
- package/proxy/request-policy.mjs +45 -0
- package/proxy/request-policy.test.mjs +47 -0
- package/proxy/run-recap.mjs +139 -0
- package/proxy/runtime-attribution.mjs +110 -0
- package/proxy/sandbox-bridge.mjs +49 -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/search.test.mjs +161 -0
- package/proxy/smoke.test.mjs +93 -0
- package/proxy/step-attribution.mjs +380 -0
- package/proxy/step-lab.test.mjs +38 -0
- package/proxy/summaries.test.mjs +69 -0
- package/proxy/tool-metadata.mjs +36 -0
- package/proxy/tool-metadata.test.mjs +38 -0
- package/proxy/trace-view.mjs +308 -0
- package/proxy/trace-view.test.mjs +72 -0
- package/proxy/typesafe.mjs +63 -0
- package/proxy/typesafe.test.mjs +39 -0
- package/src/claude-code.mjs +38 -1
- package/src/commands.mjs +133 -20
- package/src/config.mjs +16 -7
- package/src/export.mjs +200 -0
- package/src/lima.mjs +176 -0
- package/src/local-sandbox.mjs +339 -0
- package/src/paths.mjs +8 -8
- package/src/proxy-process.mjs +45 -3
- package/src/sandbox.mjs +37 -9
- package/src/upload.mjs +198 -0
- package/worker/sandbox/Dockerfile +8 -0
- package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
- package/worker/sandbox/claude-hook.mjs +364 -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 +679 -0
- package/worker/sandbox/setup.py +159 -0
- package/worker/sandbox/syscall_catalog.sql +985 -0
- package/worker/sandbox/transcript-delivery.test.mjs +153 -0
- package/worker/sandbox/viewer.py +151 -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,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { requestMetrics } from './request-metrics.mjs';
|
|
3
|
+
import { redact, parseSseResponse } from './capture.mjs';
|
|
4
|
+
import { trustedOrigin as originAllowed, trustedRequest, hasToken, hasSession, sessionFor, sessionCookie, viewerTokenFor } from './request-policy.mjs';
|
|
5
|
+
import { ensureToken } from './local-token.mjs';
|
|
3
6
|
/** Local API recorder. Point a compatible client at http://127.0.0.1:8797. */
|
|
4
7
|
import { createServer } from 'node:http';
|
|
5
|
-
import { appendFile, mkdir, readFile } from 'node:fs/promises';
|
|
6
|
-
import { realpathSync } from 'node:fs';
|
|
8
|
+
import { appendFile, mkdir, readFile, stat } from 'node:fs/promises';
|
|
9
|
+
import { realpathSync, readFileSync } from 'node:fs';
|
|
7
10
|
import { homedir } from 'node:os';
|
|
8
|
-
import { randomUUID, createHash } from 'node:crypto';
|
|
11
|
+
import { randomBytes, randomUUID, createHash } from 'node:crypto';
|
|
9
12
|
import { join, dirname, resolve, extname, sep } from 'node:path';
|
|
10
|
-
import { exchangesFromTranscript, parseTranscript } from './claude-code-adapter.mjs';
|
|
11
|
-
import {
|
|
13
|
+
import { exchangesFromTranscript, parseTranscript, toolResultsFromTranscript } from './claude-code-adapter.mjs';
|
|
14
|
+
import { replayEligibility, createExperiment, runExperiment } from './experiment-engine.mjs';
|
|
12
15
|
import { loadEnvFile } from 'node:process';
|
|
13
16
|
import { providerConfig, routeRequest, selectModel } from './providers.mjs';
|
|
14
|
-
import { latestSessionRows } from './prompt-traces.mjs';
|
|
15
17
|
import { inspectStep, createStepRun, runDecision } from './step-lab.mjs';
|
|
16
18
|
import { executeSequence } from './execution-runner.mjs';
|
|
17
19
|
import { explanationRequest, parseExplanations } from './explanations.mjs';
|
|
18
20
|
import { summaryRequest, parseSummary, resultText } from './summaries.mjs';
|
|
19
|
-
import {
|
|
21
|
+
import { fold as foldEvents, describeAll, undescribed, describeRequest, parseDescriptions, attributeMarked } from './exec-narrative.mjs';
|
|
22
|
+
import { ingestExecutions, attributeLateProcesses } from './runtime-attribution.mjs';
|
|
23
|
+
import { readTraces as traceView } from './trace-view.mjs';
|
|
24
|
+
import { categoryResolver } from './call-category.mjs';
|
|
25
|
+
import { startGvisorForwarder } from './gvisor-forwarder.mjs';
|
|
26
|
+
import { startPlayground, FORK_ID } from './playground.mjs';
|
|
27
|
+
import { omitToolChunkIds } from './tool-metadata.mjs';
|
|
20
28
|
import { openEvidenceStore } from './evidence-store.mjs';
|
|
29
|
+
import { startSandboxBridge } from './sandbox-bridge.mjs';
|
|
30
|
+
import { localSandboxes, VM } from './local-sandboxes.mjs';
|
|
31
|
+
import { typesafeConfig, systemOne } from './typesafe.mjs';
|
|
21
32
|
import { promptContext, contextItemText, contextSummaryRequest, parseContextSummary } from './prompt-context.mjs';
|
|
33
|
+
import { recapOutline, recapRequest, recapText, parseRecap, DEFAULT_OBSERVER } from './run-recap.mjs';
|
|
34
|
+
import { groupByCall, assessmentRequests, combineGroup, rulesOnly, withProbabilities } from './call-assessment.mjs';
|
|
35
|
+
import { prepareStep, attributionKey, proposerRequest, parseProposals, candidates, jevRequests, combine, withoutJev } from './step-attribution.mjs';
|
|
22
36
|
|
|
23
37
|
try { loadEnvFile(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
24
38
|
const routing = providerConfig();
|
|
@@ -27,12 +41,29 @@ const routing = providerConfig();
|
|
|
27
41
|
const summaryModel = process.env.RAYTACE_SUMMARY_MODEL
|
|
28
42
|
? selectModel(routing, process.env.RAYTACE_SUMMARY_MODEL)
|
|
29
43
|
: (routing.models.oss || routing.defaultModel);
|
|
44
|
+
// Bumped whenever the dashboard needs endpoints an older proxy lacks; the
|
|
45
|
+
// CLI restarts a proxy it started that reports less (src/proxy-process.mjs).
|
|
46
|
+
const PROXY_API = 4;
|
|
30
47
|
const fallbackSession = { session_id: randomUUID(), session_started_at: new Date().toISOString() };
|
|
31
48
|
|
|
32
49
|
const port = Number(process.env.RAYTACE_PORT || 8797);
|
|
50
|
+
// The evidence viewer of the local sandbox VM (worker/sandbox/viewer.py),
|
|
51
|
+
// which Lima forwards here.
|
|
52
|
+
const EVIDENCE_VIEWER = process.env.RAYTACE_EVIDENCE_VIEWER || 'http://127.0.0.1:8798';
|
|
33
53
|
// The CLI sets RAYTACE_DATA_DIR (~/.raytrace); run by hand it keeps ./.raytace.
|
|
34
54
|
const dataDir = process.env.RAYTACE_DATA_DIR || join(process.cwd(), '.raytace');
|
|
35
55
|
const store = process.env.RAYTACE_STORE || join(dataDir, 'events.jsonl');
|
|
56
|
+
// Who may use the local API (local-token.mjs). `raytrace open` trades it for a
|
|
57
|
+
// one-time ticket, so the link it hands the browser is worth nothing afterwards.
|
|
58
|
+
const apiToken = ensureToken(dataDir);
|
|
59
|
+
const TICKET_MS = 2 * 60 * 1000;
|
|
60
|
+
const SESSION_SECONDS = 30 * 24 * 60 * 60;
|
|
61
|
+
const tickets = new Set();
|
|
62
|
+
const NOT_SIGNED_IN = { error: 'Not signed in to this RayTrace. Run: raytrace open', code: 'not_signed_in' };
|
|
63
|
+
const fromViewer = (url, init = {}) => fetch(url, { ...init, headers: { authorization: `Bearer ${viewerTokenFor(apiToken)}` } });
|
|
64
|
+
// The local sandboxes (raytrace sandbox create --local): in place of raytace's sandbox manager.
|
|
65
|
+
const sandboxes = localSandboxes({ dataDir });
|
|
66
|
+
const NO_VM = `Local sandbox VM (${VM}) not reachable. Start a sandbox with: raytrace sandbox start <name>`;
|
|
36
67
|
const maxBodyBytes = Number(process.env.RAYTACE_MAX_BODY_BYTES || 2_000_000);
|
|
37
68
|
const liveExchanges = new Map(); // Credentials stay in process memory, never in the event log.
|
|
38
69
|
const jobs = new Map();
|
|
@@ -41,19 +72,59 @@ const dbFile = process.env.RAYTACE_DB || join(dirname(store), 'evidence.db');
|
|
|
41
72
|
const archiveJsonl = process.env.RAYTACE_ARCHIVE_JSONL === '1';
|
|
42
73
|
const db = openEvidenceStore(dbFile);
|
|
43
74
|
const allowedOrigins = new Set((process.env.RAYTACE_UI_ORIGINS || '').split(',').filter(Boolean));
|
|
44
|
-
|
|
45
|
-
if (!origin) return true;
|
|
46
|
-
if (allowedOrigins.has(origin)) return true;
|
|
47
|
-
try { const url = new URL(origin); return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname); } catch { return false; }
|
|
48
|
-
}
|
|
75
|
+
const trustedOrigin = (origin) => originAllowed(origin, allowedOrigins);
|
|
49
76
|
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
77
|
+
// Command severity (Jev). Without TYPESAFE_API_KEY, or when a request fails,
|
|
78
|
+
// only the rule floor is shown -- and only where a rule actually fired.
|
|
79
|
+
const typesafe = typesafeConfig();
|
|
80
|
+
const pendingAssessments = new Map();
|
|
81
|
+
const ASSESS_CONCURRENCY = 4;
|
|
82
|
+
|
|
83
|
+
async function mapLimit(items, limit, run) {
|
|
84
|
+
const results = Array.from({ length: items.length });
|
|
85
|
+
let next = 0;
|
|
86
|
+
const worker = async () => { while (next < items.length) { const index = next++; results[index] = await run(items[index]); } };
|
|
87
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
88
|
+
return results;
|
|
56
89
|
}
|
|
90
|
+
|
|
91
|
+
async function assessGroup(group, context) {
|
|
92
|
+
if (!typesafe.enabled) return rulesOnly(group);
|
|
93
|
+
const { key, requests } = assessmentRequests(group, context, typesafe.model);
|
|
94
|
+
const cached = db.getCallAssessment(key);
|
|
95
|
+
if (cached) return withProbabilities(cached);
|
|
96
|
+
if (!pendingAssessments.has(key)) {
|
|
97
|
+
const task = (async () => {
|
|
98
|
+
const responses = await Promise.all(requests.map((request) => systemOne(typesafe, { state: request.state, questions: request.questions })));
|
|
99
|
+
const model = responses[0]?.model ?? typesafe.model;
|
|
100
|
+
const input_tokens = responses.reduce((sum, response) => sum + (response.usage?.input_tokens ?? 0), 0);
|
|
101
|
+
const result = { ...combineGroup(group, requests, responses), model, input_tokens };
|
|
102
|
+
db.putCallAssessment(key, group.call_id, model, { ...result, answers: responses.map((response) => response.answers) });
|
|
103
|
+
return result;
|
|
104
|
+
})().finally(() => pendingAssessments.delete(key));
|
|
105
|
+
pendingAssessments.set(key, task);
|
|
106
|
+
}
|
|
107
|
+
try { return await pendingAssessments.get(key); } catch (error) {
|
|
108
|
+
console.error('[raytace] Jev assessment unavailable:', error.message);
|
|
109
|
+
return rulesOnly(group);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Sets `severity` on each top-level command and returns call-level labels
|
|
114
|
+
* keyed by call id. Never throws: severity must not cost us the evidence. */
|
|
115
|
+
async function assessCommands(commands) {
|
|
116
|
+
const groups = groupByCall(commands);
|
|
117
|
+
const contexts = db.toolCallContexts(groups.map((group) => group.call_id));
|
|
118
|
+
const results = await mapLimit(groups, ASSESS_CONCURRENCY, (group) => assessGroup(group, contexts.get(group.call_id) ?? null));
|
|
119
|
+
const labels = {};
|
|
120
|
+
groups.forEach((group, index) => {
|
|
121
|
+
const { severities, labels: callLabels } = results[index];
|
|
122
|
+
group.trees.forEach((tree, position) => { tree.root.severity = severities[position] ?? null; });
|
|
123
|
+
if (callLabels && group.call_id) labels[group.call_id] = callLabels;
|
|
124
|
+
});
|
|
125
|
+
return labels;
|
|
126
|
+
}
|
|
127
|
+
|
|
57
128
|
async function record(event) {
|
|
58
129
|
const row = omitToolChunkIds(event);
|
|
59
130
|
if (row.event_type === 'model.exchange' && row.span_id) db.recordExchange(row);
|
|
@@ -62,36 +133,6 @@ async function record(event) {
|
|
|
62
133
|
if (archiveJsonl) { await mkdir(dirname(store), { recursive: true }); await appendFile(store, `${JSON.stringify(row)}\n`); }
|
|
63
134
|
}
|
|
64
135
|
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
136
|
async function invokeReplay(entry, payload, signal) {
|
|
96
137
|
const headers = Object.fromEntries(Object.entries(entry.headers).filter(([key]) =>
|
|
97
138
|
['authorization', 'content-type', 'openai-organization', 'openai-project', 'openai-beta', 'user-agent'].includes(key.toLowerCase())));
|
|
@@ -106,50 +147,35 @@ async function invokeReplay(entry, payload, signal) {
|
|
|
106
147
|
return response.headers.get('content-type')?.includes('text/event-stream') ? parseSseResponse(body) : JSON.parse(body.toString());
|
|
107
148
|
}
|
|
108
149
|
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
|
-
}
|
|
150
|
+
/** The fields that identify and time the sandbox process a call ran as
|
|
151
|
+
* (db.divergence). All null when nothing was observed for the call. */
|
|
142
152
|
// The trace list takes seconds to build for long sessions and is polled every
|
|
143
153
|
// few seconds, mostly with nothing new: it is rebuilt only when the data
|
|
144
154
|
// behind it changed (db.dataVersion), and one build serves every caller.
|
|
145
155
|
// The body is serialized once per version too, and its version is its ETag,
|
|
146
156
|
// so a poll with nothing new is answered 304 without sending anything.
|
|
157
|
+
/** The trace view over this proxy's store; a replay is offered for exchanges
|
|
158
|
+
* still held in memory (liveExchanges). */
|
|
159
|
+
function readTraces(includeHistory = false, { evidence = true } = {}) {
|
|
160
|
+
return traceView(db, { includeHistory, evidence, replayReason: (spanId) => {
|
|
161
|
+
const live = liveExchanges.get(spanId);
|
|
162
|
+
return live ? replayEligibility(live) : undefined;
|
|
163
|
+
} });
|
|
164
|
+
}
|
|
147
165
|
const traceCache = new Map(); // url -> { version, body: Promise<string> }
|
|
166
|
+
// The Tool column's category for a shell command no rule places (Jev). An
|
|
167
|
+
// answer changes no row dataVersion counts, so each one moves the view's
|
|
168
|
+
// version itself: the next poll is rebuilt and not answered 304.
|
|
169
|
+
const resolveCategories = categoryResolver({ config: typesafe, ask: (request) => systemOne(typesafe, request) });
|
|
170
|
+
let categoryAnswers = 0;
|
|
148
171
|
function cachedTraces(url) {
|
|
149
|
-
const version = db.dataVersion()
|
|
172
|
+
const version = `${db.dataVersion()}:${categoryAnswers}`;
|
|
150
173
|
const hit = traceCache.get(url);
|
|
151
174
|
if (hit?.version === version) return hit;
|
|
152
175
|
const body = readTraces(url !== '/raytace/traces', { evidence: url !== '/raytace/traces?scope=history' })
|
|
176
|
+
.then((traces) => resolveCategories(traces, { get: (key) => db.getCallAssessment(key),
|
|
177
|
+
put: (key, model, value) => db.putCallAssessment(key, null, model, value),
|
|
178
|
+
onSettled: () => { categoryAnswers += 1; } }))
|
|
153
179
|
.then((traces) => JSON.stringify({ traces }));
|
|
154
180
|
const entry = { version, etag: `"${version}"`, body };
|
|
155
181
|
traceCache.set(url, entry);
|
|
@@ -160,95 +186,6 @@ function cachedTraces(url) {
|
|
|
160
186
|
/** `evidence: false` skips building each request's context items, the
|
|
161
187
|
* costliest part (every request resends the conversation so far), for
|
|
162
188
|
* 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
189
|
|
|
253
190
|
|
|
254
191
|
// Context window sizes, from OpenRouter's public model list (no key needed),
|
|
@@ -271,7 +208,24 @@ async function promptContextFor(traceId) {
|
|
|
271
208
|
const last = trace?.requests?.at(-1);
|
|
272
209
|
const entry = last ? await savedOrLive(last.id) : null;
|
|
273
210
|
if (!entry) return null;
|
|
274
|
-
return { trace, context: promptContext(entry, trace.title, trace.answer ?? '') };
|
|
211
|
+
return { trace, context: promptContext(entry, trace.promptRaw ?? trace.title, trace.answer ?? '') };
|
|
212
|
+
}
|
|
213
|
+
// Recap (run-recap.mjs): the observer, a stronger model than the ones that
|
|
214
|
+
// label single steps, reads one prompt's run and says what it did and why.
|
|
215
|
+
// It is asked for by id, outside the sandboxes' model list.
|
|
216
|
+
const observerModel = process.env.RAYTACE_OBSERVER_MODEL || DEFAULT_OBSERVER;
|
|
217
|
+
const pendingRecaps = new Map();
|
|
218
|
+
/** The recap request for one prompt as it stands now, or null (no such prompt, or no tool calls). */
|
|
219
|
+
async function currentRecapRequest(traceId) {
|
|
220
|
+
const trace = (await readTraces(true, { evidence: false })).find((item) => item.id === traceId);
|
|
221
|
+
const outline = trace ? recapOutline(trace) : null;
|
|
222
|
+
return outline ? { outline, ...recapRequest(outline, observerModel) } : null;
|
|
223
|
+
}
|
|
224
|
+
async function askObserver(payload) {
|
|
225
|
+
const response = await fetch(`${routing.upstreams.openrouter}/v1/chat/completions`, { method: 'POST',
|
|
226
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${routing.apiKey}` }, body: JSON.stringify(payload), signal: AbortSignal.timeout(120_000) });
|
|
227
|
+
if (!response.ok) { await response.body?.cancel(); throw new Error(`The observer model returned HTTP ${response.status}.`); }
|
|
228
|
+
return response.json();
|
|
275
229
|
}
|
|
276
230
|
async function savedOrLive(exchangeId) {
|
|
277
231
|
return liveExchanges.get(exchangeId) || db.findExchange(exchangeId);
|
|
@@ -287,10 +241,57 @@ async function currentSummaryRequest(exchangeId) {
|
|
|
287
241
|
const ownResults = ownCalls.map((item) => ({ from: item.name, output: resultText(contexts.get(item.call_id)?.result) }));
|
|
288
242
|
return summaryRequest(entry, exchangeId, summaryModel, ownResults);
|
|
289
243
|
}
|
|
244
|
+
// Chain of thought (step-attribution.mjs): why one tool call was made. Only
|
|
245
|
+
// for prompts run in the sandbox (rtp- sessions); anything else is refused
|
|
246
|
+
// before a model is called.
|
|
247
|
+
const attributionModel = process.env.RAYTACE_ATTRIBUTION_MODEL ? selectModel(routing, process.env.RAYTACE_ATTRIBUTION_MODEL) : routing.defaultModel;
|
|
248
|
+
const SANDBOX_SESSION = /^rtp-[a-f0-9]{32}$/;
|
|
249
|
+
const pendingAttributions = new Map();
|
|
250
|
+
const MAX_CONCURRENT_ATTRIBUTIONS = 4;
|
|
251
|
+
|
|
252
|
+
/** The step and its cache key, or an `{ status, error }` to send back. */
|
|
253
|
+
function attributionStep(exchangeId, outputIndex) {
|
|
254
|
+
const entry = db.findExchange(String(exchangeId ?? ''));
|
|
255
|
+
if (!entry) return { status: 404, error: 'Saved step not found.' };
|
|
256
|
+
if (!SANDBOX_SESSION.test(entry.session_id ?? '')) return { status: 403, error: 'Chain of thought is only available for prompts run in the sandbox.' };
|
|
257
|
+
if (!entry.payload || !entry.response) return { status: 409, error: 'This capture has no saved request or response.' };
|
|
258
|
+
const step = prepareStep(omitToolChunkIds(entry), Number(outputIndex));
|
|
259
|
+
if (!step) return { status: 400, error: 'That output is not a tool call.' };
|
|
260
|
+
const proposer = routing.mode === 'openrouter' ? attributionModel : null;
|
|
261
|
+
return { step, key: attributionKey(step, proposer, typesafe.enabled ? typesafe.model : null), proposer };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function computeAttribution({ step, proposer }) {
|
|
265
|
+
let proposals = [];
|
|
266
|
+
let proposer_error = null;
|
|
267
|
+
if (proposer) {
|
|
268
|
+
try {
|
|
269
|
+
const { payload } = proposerRequest(step, proposer);
|
|
270
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(payload)));
|
|
271
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, payload, new AbortController().signal);
|
|
272
|
+
proposals = parseProposals(response, step.items);
|
|
273
|
+
} catch (error) { proposer_error = error.message; console.error('[raytace] Cause proposer unavailable:', error.message); }
|
|
274
|
+
}
|
|
275
|
+
const cands = candidates(step, proposals);
|
|
276
|
+
let result;
|
|
277
|
+
let jev_model = null;
|
|
278
|
+
if (!typesafe.enabled) result = withoutJev(cands, 'Add a TypeSafe key to rank these: raytrace key typesafe');
|
|
279
|
+
else {
|
|
280
|
+
try {
|
|
281
|
+
const { requests } = jevRequests(step, cands);
|
|
282
|
+
const responses = await Promise.all(requests.map((request) => systemOne(typesafe, request)));
|
|
283
|
+
jev_model = responses[0]?.model ?? typesafe.model;
|
|
284
|
+
result = combine(cands, responses);
|
|
285
|
+
} catch (error) { console.error('[raytace] Jev attribution unavailable:', error.message); result = withoutJev(cands, 'Jev was unavailable.'); }
|
|
286
|
+
}
|
|
287
|
+
return { ...result, action: step.call.name, proposer_model: proposer, proposer_error, jev_model };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
290
|
const pendingExplanations = new Map();
|
|
291
291
|
const pendingSummaries = new Map();
|
|
292
292
|
const MAX_CONCURRENT_SUMMARIES = 4; // cheap+budget-capped calls; safe to run several at once instead of one at a time
|
|
293
293
|
|
|
294
|
+
|
|
294
295
|
// ---------------------------------------------------------------- Claude Code
|
|
295
296
|
// Proxy-free capture: Claude Code's hooks ring, and its session transcript is
|
|
296
297
|
// rebuilt into the same exchange rows the proxy records (claude-code-adapter).
|
|
@@ -311,15 +312,66 @@ function serially(path, job) {
|
|
|
311
312
|
claudeCodeQueues.set(path, settled);
|
|
312
313
|
return next;
|
|
313
314
|
}
|
|
314
|
-
|
|
315
|
+
/** `session` files the rows under a sandbox's rtp- id instead of the
|
|
316
|
+
* transcript's own session, and ties its processes to them afterwards. */
|
|
317
|
+
function ingestClaudeCode(path, { final, session = null }) {
|
|
315
318
|
serially(path, async () => {
|
|
316
|
-
const
|
|
319
|
+
const lines = parseTranscript(await readFile(path, 'utf8'));
|
|
320
|
+
const rows = exchangesFromTranscript(lines,
|
|
321
|
+
{ final, sessionId: session?.id ?? null, sessionStartedAt: session?.startedAt ?? null });
|
|
317
322
|
for (const row of rows) {
|
|
318
323
|
await record({ ...row, request: { ...row.request, payload: redact(row.request.payload) }, response: { ...row.response, payload: redact(row.response.payload) } });
|
|
319
324
|
}
|
|
325
|
+
for (const [callId, item] of toolResultsFromTranscript(lines)) {
|
|
326
|
+
db.recordToolResult?.(callId, item);
|
|
327
|
+
}
|
|
328
|
+
if (session) await attributeLateProcesses(db, session.id);
|
|
320
329
|
}).catch((error) => console.error(`Claude Code transcript ${path} could not be read: ${error.message}`));
|
|
321
330
|
}
|
|
322
331
|
|
|
332
|
+
// A sandboxed Claude Code's transcript lives in the sandbox. Its hook sends
|
|
333
|
+
// the new lines through the sandbox manager, which names the sandbox; they
|
|
334
|
+
// are appended to a copy here and read like any local transcript. `offset`
|
|
335
|
+
// must equal the copy's size, so a lost or repeated send is never spliced in
|
|
336
|
+
// twice: a mismatch answers 409 with the size to resend from.
|
|
337
|
+
const SANDBOX_ID = /^rtp-[a-f0-9]{32}$/;
|
|
338
|
+
const CLAUDE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
339
|
+
const sandboxTranscripts = join(dirname(store), 'claude-code');
|
|
340
|
+
// Playground forks of those sessions (playground.mjs). The hook installed in
|
|
341
|
+
// a fork is read fresh each time, so a fork runs the repo's current version.
|
|
342
|
+
const playground = startPlayground({ db, transcriptsDir: sandboxTranscripts,
|
|
343
|
+
hookSource: () => readFileSync(new URL('../worker/sandbox/claude-hook.mjs', import.meta.url), 'utf8') });
|
|
344
|
+
async function appendSandboxTranscript(sandbox, note) {
|
|
345
|
+
if (!CLAUDE_SESSION_ID.test(note?.session_id ?? '') || !Number.isInteger(note.offset) || note.offset < 0
|
|
346
|
+
|| typeof note.text !== 'string' || (note.more !== undefined && typeof note.more !== 'boolean')) return { status: 400, body: { error: 'Expected session_id, offset and a text fragment with optional more flag.' } };
|
|
347
|
+
const directory = join(sandboxTranscripts, sandbox);
|
|
348
|
+
const path = join(directory, `${note.session_id}.jsonl`);
|
|
349
|
+
return serially(path, async () => {
|
|
350
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
351
|
+
const size = await stat(path).then((info) => info.size, () => 0);
|
|
352
|
+
if (note.offset !== size) return { status: 409, body: { size } };
|
|
353
|
+
await appendFile(path, note.text, { mode: 0o600 }); // creates it when a snapshot arrives before any line
|
|
354
|
+
return { status: 200, body: { size: size + Buffer.byteLength(note.text) }, path };
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** A snapshot as the sandbox hook reports it, checked field by field, or
|
|
359
|
+
* null. Paths are the agent's to name, so they are only bounded, never trusted. */
|
|
360
|
+
function sandboxSnapshot(value) {
|
|
361
|
+
const sha = /^[0-9a-f]{40}$/;
|
|
362
|
+
if (!value || typeof value !== 'object' || !sha.test(value.commit ?? '') || (value.parent != null && !sha.test(value.parent))
|
|
363
|
+
|| !['prompt', 'tool'].includes(value.taken_on) || (value.call_id != null && !/^[A-Za-z0-9_-]{1,128}$/.test(value.call_id))
|
|
364
|
+
|| !Number.isFinite(Date.parse(value.taken_at ?? ''))) return null;
|
|
365
|
+
const path = (item) => typeof item === 'string' && item.length <= 1024;
|
|
366
|
+
const count = (item) => (Number.isInteger(item) && item >= 0 ? item : null);
|
|
367
|
+
const changes = (Array.isArray(value.changes) ? value.changes : []).slice(0, 300).filter((item) => path(item?.path))
|
|
368
|
+
.map((item) => ({ path: item.path, status: /^[ADMTUX]$/.test(item.status ?? '') ? item.status : '?', added: count(item.added), removed: count(item.removed) }));
|
|
369
|
+
return { commit: value.commit, parent: value.parent ?? null, taken_on: value.taken_on, call_id: value.call_id ?? null,
|
|
370
|
+
taken_at: value.taken_at, changed: value.changed === true, changes,
|
|
371
|
+
too_big: (Array.isArray(value.too_big) ? value.too_big : []).slice(0, 300).filter(path) };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
|
|
323
375
|
// The prebuilt dashboard (RAYTACE_DASHBOARD_DIR), served from / so it and the
|
|
324
376
|
// API share one origin. Model traffic is under /v1 and the API under /raytace,
|
|
325
377
|
// so any other GET from a browser (no credentials) is a dashboard file; unknown
|
|
@@ -338,20 +390,158 @@ async function serveDashboard(req, res) {
|
|
|
338
390
|
res.end(body);
|
|
339
391
|
}
|
|
340
392
|
|
|
393
|
+
/** A local sandbox's Claude Code transcript lines, from its hook through the
|
|
394
|
+
* sandbox bridge (sandbox-bridge.mjs), which has named the sandbox by its
|
|
395
|
+
* token: copied here and read like a local transcript, filed under the
|
|
396
|
+
* sandbox's rtp- id so its recorded processes join them. Returns {status, body}. */
|
|
397
|
+
async function ingestFromSandbox(sandbox, note) {
|
|
398
|
+
// A Playground fork sends with the project's token, so the bridge names
|
|
399
|
+
// the project; the fork's own steps are filed under the fork, and only
|
|
400
|
+
// for a fork RayTrace made of that project.
|
|
401
|
+
const fork = note?.fork == null ? null : FORK_ID.test(note.fork) ? playground.forkOf(note.fork, sandbox) : false;
|
|
402
|
+
if (fork === false || (note?.fork != null && !fork)) return { status: 403, body: { error: 'Unknown Playground fork.' } };
|
|
403
|
+
const filedUnder = fork ? fork.id : sandbox;
|
|
404
|
+
const written = await appendSandboxTranscript(filedUnder, note).catch(() => ({ status: 500, body: { error: 'Transcript copy could not be written.' } }));
|
|
405
|
+
const snapshot = written.path ? sandboxSnapshot(note.snapshot) : null;
|
|
406
|
+
if (snapshot) {
|
|
407
|
+
try { db.recordSnapshot({ sessionId: filedUnder, agentSessionId: note.session_id, snapshot }); }
|
|
408
|
+
catch (error) { console.error(`Snapshot for ${filedUnder} could not be recorded: ${error.message}`); }
|
|
409
|
+
}
|
|
410
|
+
if (written.path) ingestClaudeCode(written.path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) && note.more !== true,
|
|
411
|
+
session: { id: filedUnder, startedAt: fork ? fork.created_at : await sandboxes.createdAt(sandbox) } });
|
|
412
|
+
return written;
|
|
413
|
+
}
|
|
414
|
+
|
|
341
415
|
const server = createServer(async (req, res) => {
|
|
416
|
+
// Guard every route before either dashboard assets or paid provider calls.
|
|
417
|
+
if (!trustedRequest(req, allowedOrigins)) {
|
|
418
|
+
res.writeHead(403); return res.end('Untrusted dashboard origin or host.');
|
|
419
|
+
}
|
|
342
420
|
const fromAgent = req.headers.authorization || req.headers['x-api-key'] || req.headers['anthropic-version'];
|
|
343
421
|
if (dashboardDir && req.method === 'GET' && !fromAgent && !req.url?.startsWith('/raytace/') && !req.url?.startsWith('/v1/')) {
|
|
344
422
|
try { return await serveDashboard(req, res); }
|
|
345
423
|
catch { res.writeHead(404); return res.end('Dashboard not built.'); }
|
|
346
424
|
}
|
|
347
425
|
const localApi = req.url?.startsWith('/raytace/');
|
|
348
|
-
|
|
349
|
-
if (localApi && (!trustedOrigin(req.headers.origin) || !/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/.test(req.headers.host || ''))) {
|
|
350
|
-
res.writeHead(403); return res.end('Untrusted dashboard origin or host.');
|
|
351
|
-
}
|
|
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' };
|
|
426
|
+
const corsHeaders = { ...(req.headers.origin && trustedOrigin(req.headers.origin) ? { 'access-control-allow-origin': req.headers.origin } : {}), vary: 'Origin', 'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS', 'access-control-allow-headers': 'authorization,content-type,x-raytace-experiment,if-none-match', 'access-control-allow-private-network': 'true' };
|
|
353
427
|
const json = (status, value) => { res.writeHead(status, { 'content-type': 'application/json', ...corsHeaders, 'cache-control': 'no-store' }); res.end(JSON.stringify(redact(omitToolChunkIds(value)))); };
|
|
354
428
|
if (req.method === 'OPTIONS') { res.writeHead(204, corsHeaders); return res.end(); }
|
|
429
|
+
const ticket = req.url?.match(/^\/raytace\/session\?ticket=([a-f0-9]{64})$/)?.[1];
|
|
430
|
+
if (req.method === 'GET' && ticket) {
|
|
431
|
+
if (!tickets.delete(ticket)) { res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }); return res.end('This link was used already, or has expired. Run: raytrace open\n'); }
|
|
432
|
+
res.writeHead(302, { location: '/', 'cache-control': 'no-store', 'set-cookie': `${sessionCookie(req.socket.localPort)}=${sessionFor(apiToken)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_SECONDS}` });
|
|
433
|
+
return res.end();
|
|
434
|
+
}
|
|
435
|
+
// Only the API version is public: the CLI and dashboard read it to spot an outdated proxy.
|
|
436
|
+
if (localApi && req.url !== '/raytace/version' && !hasToken(req, apiToken) && !hasSession(req, apiToken, req.socket.localPort)) return json(401, NOT_SIGNED_IN);
|
|
437
|
+
if (req.method === 'POST' && req.url === '/raytace/session') {
|
|
438
|
+
if (!hasToken(req, apiToken)) return json(401, NOT_SIGNED_IN);
|
|
439
|
+
const issued = randomBytes(32).toString('hex');
|
|
440
|
+
tickets.add(issued);
|
|
441
|
+
setTimeout(() => tickets.delete(issued), TICKET_MS).unref();
|
|
442
|
+
return json(201, { ticket: issued });
|
|
443
|
+
}
|
|
444
|
+
// This machine's local sandboxes. With the VM stopped they are still listed,
|
|
445
|
+
// from the CLI's records, as stopped. Prompt history comes from the traces.
|
|
446
|
+
if (req.method === 'GET' && req.url === '/raytace/sandboxes') {
|
|
447
|
+
const shape = (box, status) => ({ id: box.id, name: box.name, host: 'lima', on_host: true, status, created: box.created,
|
|
448
|
+
deleted: null, size_bytes: box.size_bytes ?? null, imported_bytes: null, transcripts: true, skipped_count: 0, scan: null });
|
|
449
|
+
try { return json(200, { sandboxes: (await sandboxes.list()).filter((box) => !box.fork_of).map((box) => shape(box, box.status === 'running' ? 'running' : 'stopped')) }); }
|
|
450
|
+
catch { return json(200, { sandboxes: (await sandboxes.known()).map((box) => shape(box, 'stopped')) }); }
|
|
451
|
+
}
|
|
452
|
+
// What the kernel layer saw a sandbox do: the fact engine's records in the VM.
|
|
453
|
+
const activityRoute = req.url?.match(/^\/raytace\/sandboxes\/(rtp-[a-f0-9]{32})\/activity(?:\?([a-z0-9=&]{1,80}))?$/);
|
|
454
|
+
if (req.method === 'GET' && activityRoute) {
|
|
455
|
+
const query = new URLSearchParams(activityRoute[2] ?? '');
|
|
456
|
+
const window = { since: Number(query.get('since')) || 0, until: Number(query.get('until')) || 0 };
|
|
457
|
+
try {
|
|
458
|
+
const box = (await sandboxes.list()).find((item) => item.id === activityRoute[1]);
|
|
459
|
+
if (!box) return json(404, { error: 'No such local sandbox.' });
|
|
460
|
+
return json(200, { id: box.id, name: box.name, ...(await sandboxes.activity(box.id, window)) });
|
|
461
|
+
} catch { return json(503, { error: NO_VM }); }
|
|
462
|
+
}
|
|
463
|
+
// The initial scan, restricted files and alerts are not kept for local sandboxes yet.
|
|
464
|
+
if (/^\/raytace\/(sandboxes\/rtp-[a-f0-9]{32}(\/files)?|alerts(\?sandbox=rtp-[a-f0-9]{32})?|alerts\/seen)$/.test(req.url ?? '')) {
|
|
465
|
+
if (req.method === 'GET' && req.url.startsWith('/raytace/alerts')) return json(200, { alerts: [] });
|
|
466
|
+
return json(404, { error: 'Not available for local sandboxes yet. Destroy one with: raytrace sandbox destroy <name>' });
|
|
467
|
+
}
|
|
468
|
+
// The collector's raw feed, behind this API's sign-in (worker/sandbox/viewer.py).
|
|
469
|
+
const feedRoute = req.url?.match(/^\/raytace\/viewer\/(events)?$/);
|
|
470
|
+
if (req.method === 'GET' && feedRoute) {
|
|
471
|
+
try {
|
|
472
|
+
const feed = await fromViewer(`${EVIDENCE_VIEWER}/${feedRoute[1] ?? ''}`, { signal: AbortSignal.timeout(10000) });
|
|
473
|
+
if (!feed.ok) throw new Error('Runtime collector unavailable');
|
|
474
|
+
if (feedRoute[1]) return json(200, await feed.json());
|
|
475
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
476
|
+
return res.end(await feed.text());
|
|
477
|
+
} catch { return json(503, { error: NO_VM }); }
|
|
478
|
+
}
|
|
479
|
+
if (req.method === 'GET' && req.url?.startsWith('/raytace/runtime?')) {
|
|
480
|
+
const query = new URL(req.url, 'http://localhost').searchParams;
|
|
481
|
+
const sandbox = query.get('sandbox');
|
|
482
|
+
const before = query.get('before') || '0';
|
|
483
|
+
// `since`/`until` scope the page to one agent turn (the prompt through the
|
|
484
|
+
// answer). Without them this returns the whole sandbox's history, which is
|
|
485
|
+
// every prompt ever run in it.
|
|
486
|
+
const since = query.get('since') || '0';
|
|
487
|
+
const until = query.get('until') || '0';
|
|
488
|
+
const raw = query.get('raw') === '1';
|
|
489
|
+
const ok = (value) => /^\d{1,16}$/.test(value);
|
|
490
|
+
if (!/^rtp-[a-f0-9]{32}$/.test(sandbox || '') || ![before, since, until].every(ok)) return json(400, { error: 'Invalid sandbox or cursor' });
|
|
491
|
+
try {
|
|
492
|
+
const project = (await sandboxes.list()).find((p) => p.id === sandbox);
|
|
493
|
+
if (!project?.container_id || !/^[a-f0-9]{64}$/.test(project.container_id)) return json(404, { error: 'Sandbox mapping unavailable' });
|
|
494
|
+
const window = `${since !== '0' ? `&since=${since}` : ''}${until !== '0' ? `&until=${until}` : ''}`;
|
|
495
|
+
// A windowed page wants everything in the window, not the newest 100:
|
|
496
|
+
// folding turns hundreds of raw events into a handful of commands.
|
|
497
|
+
const limit = since !== '0' || until !== '0' ? 500 : 100;
|
|
498
|
+
const evidence = await fromViewer(`${EVIDENCE_VIEWER}/events?container=${project.container_id}&before=${before}${window}&limit=${limit}&processes=1`, { signal: AbortSignal.timeout(10000) });
|
|
499
|
+
if (!evidence.ok) throw new Error('Runtime collector unavailable');
|
|
500
|
+
const page = await evidence.json();
|
|
501
|
+
const base = { ...page, sandbox, container_id: project.container_id };
|
|
502
|
+
// `raw=1` is the "show everything" escape hatch: the folded view must
|
|
503
|
+
// always be auditable against what the collector actually recorded.
|
|
504
|
+
if (raw) return json(200, base);
|
|
505
|
+
|
|
506
|
+
const { commands, folded } = foldEvents(page.events);
|
|
507
|
+
// Which call each process belongs to, by the process's own identity
|
|
508
|
+
// (pid + start time) within this sandbox. `attribution` stays null when
|
|
509
|
+
// the process was not recorded yet -- not the same as unattributed,
|
|
510
|
+
// which is a recorded process that matched no call.
|
|
511
|
+
const known = new Map(db.attributionsForProcesses({ containerId: project.container_id, pids: commands.map((c) => c.pid) })
|
|
512
|
+
.map((row) => [`${row.pid}:${row.start_time_ns}`, row]));
|
|
513
|
+
for (const command of commands) {
|
|
514
|
+
const row = command.process_start_ns ? known.get(`${command.pid}:${command.process_start_ns}`) : null;
|
|
515
|
+
command.attribution = row ? { call_id: row.call_id ?? null, parent_call_id: row.parent_call_id ?? null, tier: row.tier ?? null } : null;
|
|
516
|
+
}
|
|
517
|
+
attributeMarked(commands);
|
|
518
|
+
// Cache first, so a repeat view of the same turn costs nothing. Only
|
|
519
|
+
// commands no rule can describe are ever sent to a model.
|
|
520
|
+
describeAll(commands, (command) => db.getCommandDescription(command));
|
|
521
|
+
const missing = undescribed(commands);
|
|
522
|
+
if (missing.length && routing.mode === 'openrouter') {
|
|
523
|
+
try {
|
|
524
|
+
const request = describeRequest(missing, summaryModel);
|
|
525
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
526
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
527
|
+
const text = (response.output || []).filter((item) => item.type === 'message')
|
|
528
|
+
.map((item) => (item.content || []).map((part) => part.text || '').join('')).join(' ');
|
|
529
|
+
for (const [command, description] of parseDescriptions(text, request.commands)) {
|
|
530
|
+
db.putCommandDescription(command, description, summaryModel);
|
|
531
|
+
}
|
|
532
|
+
describeAll(commands, (command) => db.getCommandDescription(command));
|
|
533
|
+
} catch (error) {
|
|
534
|
+
// A failed description must never cost us the evidence: the commands
|
|
535
|
+
// still render, just verbatim.
|
|
536
|
+
console.error('[raytace] command descriptions unavailable:', error.message);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
let call_labels = {};
|
|
540
|
+
try { call_labels = await assessCommands(commands); }
|
|
541
|
+
catch (error) { console.error('[raytace] command severity unavailable:', error.message); }
|
|
542
|
+
return json(200, { ...base, commands, folded, call_labels, severity_source: typesafe.enabled ? 'jev' : 'rules', events: undefined });
|
|
543
|
+
} catch { return json(503, { error: 'Runtime evidence unavailable: the local sandbox VM is not running. Missing evidence is not proof of non-execution.' }); }
|
|
544
|
+
}
|
|
355
545
|
// The dashboard polls the history every few seconds: its context items
|
|
356
546
|
// (`evidence`) grow with the square of a session's length, so the history
|
|
357
547
|
// carries them only when asked for (&evidence=1, Compare runs). The recent
|
|
@@ -366,8 +556,24 @@ const server = createServer(async (req, res) => {
|
|
|
366
556
|
}
|
|
367
557
|
catch (error) { res.writeHead(500, { 'content-type': 'application/json', ...corsHeaders }); return res.end(JSON.stringify({ error: String(error) })); }
|
|
368
558
|
}
|
|
559
|
+
// Splunk-style search over the derived index (search.mjs). `from`/`to`
|
|
560
|
+
// are epoch ms or ISO dates; the query itself carries fields and pipes.
|
|
561
|
+
if (req.method === 'GET' && (req.url === '/raytace/search' || req.url?.startsWith('/raytace/search?') || req.url?.startsWith('/raytace/search/signatures'))) {
|
|
562
|
+
try {
|
|
563
|
+
const params = new URL(req.url, 'http://localhost').searchParams;
|
|
564
|
+
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; };
|
|
565
|
+
const range = { fromMs: bound('from'), toMs: bound('to') };
|
|
566
|
+
if (req.url.startsWith('/raytace/search/signatures')) {
|
|
567
|
+
return json(200, { signatures: db.failureSignatures({ ...range, limit: Number(params.get('limit')) || 20 }) });
|
|
568
|
+
}
|
|
569
|
+
return json(200, db.search({ q: params.get('q') ?? '', ...range, limit: Number(params.get('limit')) || 50, offset: Number(params.get('offset')) || 0 }));
|
|
570
|
+
} catch (error) { return json(500, { error: `Search failed: ${error.message}` }); }
|
|
571
|
+
}
|
|
369
572
|
// Who is signed in and which paid features they have. Nobody yet: sign-in
|
|
370
573
|
// comes with the RayTrace cloud; the dashboard already reads this shape.
|
|
574
|
+
// Which proxy this is, so the CLI can tell an outdated one still running
|
|
575
|
+
// after an upgrade (src/proxy-process.mjs PROXY_API) and replace it.
|
|
576
|
+
if (req.method === 'GET' && req.url === '/raytace/version') return json(200, { api: PROXY_API });
|
|
371
577
|
if (req.method === 'GET' && req.url === '/raytace/account') return json(200, { signed_in: false, plan: 'free', features: [] });
|
|
372
578
|
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
579
|
const stepRoute = req.url?.match(/^\/raytace\/steps\/([a-f0-9-]+)\/(\d+)$/);
|
|
@@ -407,6 +613,11 @@ const server = createServer(async (req, res) => {
|
|
|
407
613
|
res.writeHead(text == null ? 404 : 200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
408
614
|
return res.end(text ?? 'Not found in the captured context.');
|
|
409
615
|
}
|
|
616
|
+
const recapRoute = req.url?.match(/^\/raytace\/recap\/([A-Za-z0-9_-]{1,80})$/);
|
|
617
|
+
if (req.method === 'GET' && recapRoute) {
|
|
618
|
+
const request = await currentRecapRequest(recapRoute[1]);
|
|
619
|
+
return json(200, { recap: request ? db.getSummary(request.key) : null, available: Boolean(request), model: observerModel });
|
|
620
|
+
}
|
|
410
621
|
const summaryRoute = req.url?.match(/^\/raytace\/summaries\/([a-f0-9-]+)$/);
|
|
411
622
|
// Only a summary of the step as it stands now: one written by an older
|
|
412
623
|
// version, or before the step's own result was known, is not served.
|
|
@@ -414,7 +625,40 @@ const server = createServer(async (req, res) => {
|
|
|
414
625
|
const request = await currentSummaryRequest(summaryRoute[1]);
|
|
415
626
|
return json(200, { summary: request ? db.getSummary(request.key) : null, model: summaryModel });
|
|
416
627
|
}
|
|
628
|
+
const attributionRoute = req.url?.match(/^\/raytace\/attribution\/([A-Za-z0-9_.:-]{1,120})\/(\d{1,5})$/);
|
|
629
|
+
if (req.method === 'GET' && attributionRoute) {
|
|
630
|
+
const found = attributionStep(decodeURIComponent(attributionRoute[1]), attributionRoute[2]);
|
|
631
|
+
if (found.error) return json(found.status, { error: found.error });
|
|
632
|
+
return json(200, { attribution: db.getExplanation(found.key) });
|
|
633
|
+
}
|
|
417
634
|
if (req.method === 'GET' && req.url === '/raytace/experiments') return json(200, { experiments: [...jobs.values()].slice(-30).reverse() });
|
|
635
|
+
// Playground forks (playground.mjs): listed and read freely, changed only
|
|
636
|
+
// with the dashboard's header, like experiments.
|
|
637
|
+
if (req.method === 'GET' && req.url === '/raytace/forks') return json(200, { forks: playground.list() });
|
|
638
|
+
const previewRoute = req.url?.match(/^\/raytace\/forks\/preview\/([a-f0-9-]{36})$/);
|
|
639
|
+
if (req.method === 'GET' && previewRoute) {
|
|
640
|
+
try { return json(200, await playground.preview(previewRoute[1])); } catch (error) { return json(400, { error: error.message }); }
|
|
641
|
+
}
|
|
642
|
+
// A project's snapshot history, read-only: its files at a snapshot, one
|
|
643
|
+
// file, or the diff between two snapshots (a fork's live under refs/forks/).
|
|
644
|
+
const snapRoute = req.url?.match(/^\/raytace\/snapshots\/(rtp-[a-f0-9]{32})\/(files|file|diff)\?(.*)$/);
|
|
645
|
+
if (req.method === 'GET' && snapRoute) {
|
|
646
|
+
const query = new URLSearchParams(snapRoute[3]);
|
|
647
|
+
const request = { op: { files: 'list', file: 'show', diff: 'diff' }[snapRoute[2]], commit: query.get('commit') ?? '',
|
|
648
|
+
...(query.get('to') ? { to: query.get('to') } : {}), ...(query.get('path') ? { path: query.get('path') } : {}) };
|
|
649
|
+
try { return json(200, await playground.snapshot(snapRoute[1], request)); } catch (error) { return json(400, { error: error.message }); }
|
|
650
|
+
}
|
|
651
|
+
const forkRoute = req.url?.match(/^\/raytace\/forks\/(rtf-[a-f0-9]{32})(?:\/(keep|unkeep|delete|stop-all))?$/);
|
|
652
|
+
if (forkRoute) {
|
|
653
|
+
if (req.method === 'GET' && !forkRoute[2]) { const fork = playground.get(forkRoute[1]); return fork ? json(200, fork) : json(404, { error: 'Fork not found.' }); }
|
|
654
|
+
if (req.method !== 'POST' || !forkRoute[2] || req.headers['x-raytace-experiment'] !== '1') return json(403, { error: 'Use the Playground in the dashboard.' });
|
|
655
|
+
try {
|
|
656
|
+
const action = forkRoute[2];
|
|
657
|
+
return json(200, action === 'delete' ? await playground.remove(forkRoute[1]) : action === 'stop-all' ? await playground.stopGroup(forkRoute[1])
|
|
658
|
+
: playground.keep(forkRoute[1], action === 'keep'));
|
|
659
|
+
}
|
|
660
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
661
|
+
}
|
|
418
662
|
const jobRoute = req.url?.match(/^\/raytace\/experiments\/([a-f0-9-]+)(\/cancel)?$/);
|
|
419
663
|
if (jobRoute) {
|
|
420
664
|
const job = jobs.get(jobRoute[1]); if (!job) return json(404, { error: 'Experiment not found.' });
|
|
@@ -425,7 +669,8 @@ const server = createServer(async (req, res) => {
|
|
|
425
669
|
// Claude Code hook doorbell (proxy/claude-code-hook.mjs): "this session's
|
|
426
670
|
// transcript has new lines". Answered at once; the transcript is read
|
|
427
671
|
// 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.
|
|
672
|
+
// not in the CORS allow-list, so a web page cannot ring it. A local
|
|
673
|
+
// sandbox's hook sends its lines to the sandbox bridge instead (ingestFromSandbox).
|
|
429
674
|
if (req.method === 'POST' && req.url === '/raytace/ingest/claude-code') {
|
|
430
675
|
if (req.headers['x-raytace-hook'] !== '1' || !req.headers['content-type']?.includes('application/json')) return json(403, { error: 'Claude Code hook requests only.' });
|
|
431
676
|
const chunks = []; let size = 0;
|
|
@@ -435,17 +680,21 @@ const server = createServer(async (req, res) => {
|
|
|
435
680
|
const path = claudeCodeTranscriptPath(note?.transcript_path);
|
|
436
681
|
if (!path) return json(400, { error: 'transcript_path must be a Claude Code transcript under ~/.claude/projects.' });
|
|
437
682
|
json(202, { accepted: true });
|
|
438
|
-
ingestClaudeCode(path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) });
|
|
683
|
+
ingestClaudeCode(path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) && note.more !== true });
|
|
439
684
|
return;
|
|
440
685
|
}
|
|
441
|
-
if (localApi && (req.method !== 'POST' || !['/raytace/experiments', '/raytace/step-runs',
|
|
686
|
+
if (localApi && (req.method !== 'POST' || !['/raytace/experiments', '/raytace/step-runs','/raytace/explanations', '/raytace/attribution', '/raytace/summaries', '/raytace/prompt-context/summary', '/raytace/forks', '/raytace/recap'].includes(req.url))) return json(404, { error: 'Unknown local endpoint.' });
|
|
442
687
|
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
688
|
const parts = []; let bytes = 0;
|
|
444
689
|
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
690
|
const requestBody = Buffer.concat(parts);
|
|
691
|
+
if (req.method === 'POST' && req.url === '/raytace/forks') {
|
|
692
|
+
try { return json(202, await playground.create(JSON.parse(requestBody))); }
|
|
693
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
694
|
+
}
|
|
446
695
|
if (req.method === 'POST' && req.url === '/raytace/explanations') {
|
|
447
696
|
try {
|
|
448
|
-
if (routing.mode !== 'openrouter') return json(400, { error: '
|
|
697
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Explanations need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
449
698
|
const config = JSON.parse(requestBody);
|
|
450
699
|
const entry = await savedOrLive(config.exchange_id);
|
|
451
700
|
if (!entry) return json(404, { error: 'Saved step not found.' });
|
|
@@ -467,9 +716,49 @@ const server = createServer(async (req, res) => {
|
|
|
467
716
|
try { return json(200, await pendingExplanations.get(request.key)); } finally { pendingExplanations.delete(request.key); }
|
|
468
717
|
} catch (error) { return json(400, { error: error.message }); }
|
|
469
718
|
}
|
|
719
|
+
if (req.method === 'POST' && req.url === '/raytace/attribution') {
|
|
720
|
+
try {
|
|
721
|
+
const config = JSON.parse(requestBody);
|
|
722
|
+
const found = attributionStep(config.exchange_id, config.output_index);
|
|
723
|
+
if (found.error) return json(found.status, { error: found.error });
|
|
724
|
+
const cached = db.getExplanation(found.key);
|
|
725
|
+
if (cached) return json(200, cached);
|
|
726
|
+
if (!pendingAttributions.has(found.key)) {
|
|
727
|
+
if (pendingAttributions.size >= MAX_CONCURRENT_ATTRIBUTIONS) return json(409, { error: 'Too many steps in flight. Try again shortly.' });
|
|
728
|
+
const task = (async () => {
|
|
729
|
+
const result = await computeAttribution(found);
|
|
730
|
+
// A result missing a model only because it failed is not cached, so
|
|
731
|
+
// the next open retries it.
|
|
732
|
+
if (!result.proposer_error && (result.ranked || !typesafe.enabled)) db.putExplanation(found.key, result);
|
|
733
|
+
return result;
|
|
734
|
+
})().finally(() => pendingAttributions.delete(found.key));
|
|
735
|
+
pendingAttributions.set(found.key, task);
|
|
736
|
+
}
|
|
737
|
+
return json(200, await pendingAttributions.get(found.key));
|
|
738
|
+
} catch (error) { console.error('Attribution failed:', error); return json(400, { error: error.message }); }
|
|
739
|
+
}
|
|
740
|
+
if (req.method === 'POST' && req.url === '/raytace/recap') {
|
|
741
|
+
try {
|
|
742
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Recaps need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
743
|
+
const request = await currentRecapRequest(String(JSON.parse(requestBody).trace_id ?? ''));
|
|
744
|
+
if (!request) return json(404, { error: 'Nothing to recap: the prompt was not found, or it made no tool calls.' });
|
|
745
|
+
const cached = db.getSummary(request.key);
|
|
746
|
+
if (cached) return json(200, cached);
|
|
747
|
+
if (!pendingRecaps.has(request.key)) {
|
|
748
|
+
pendingRecaps.set(request.key, (async () => {
|
|
749
|
+
const recap = parseRecap(recapText(await askObserver(request.payload)), request.outline);
|
|
750
|
+
if (!recap) throw new Error('The observer did not return a usable recap. Try again.');
|
|
751
|
+
const result = { ...recap, model: observerModel, created_at: new Date().toISOString() };
|
|
752
|
+
db.putSummary(request.key, null, result);
|
|
753
|
+
return result;
|
|
754
|
+
})().finally(() => pendingRecaps.delete(request.key)));
|
|
755
|
+
}
|
|
756
|
+
return json(200, await pendingRecaps.get(request.key));
|
|
757
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
758
|
+
}
|
|
470
759
|
if (req.method === 'POST' && req.url === '/raytace/prompt-context/summary') {
|
|
471
760
|
try {
|
|
472
|
-
if (routing.mode !== 'openrouter') return json(400, { error: '
|
|
761
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Summaries need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
473
762
|
const found = await promptContextFor(String(JSON.parse(requestBody).trace_id ?? ''));
|
|
474
763
|
if (!found) return json(404, { error: 'Prompt not found in the captured history.' });
|
|
475
764
|
const request = contextSummaryRequest(found.context, summaryModel);
|
|
@@ -491,7 +780,7 @@ const server = createServer(async (req, res) => {
|
|
|
491
780
|
}
|
|
492
781
|
if (req.method === 'POST' && req.url === '/raytace/summaries') {
|
|
493
782
|
try {
|
|
494
|
-
if (routing.mode !== 'openrouter') return json(400, { error: '
|
|
783
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Summaries need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
495
784
|
const config = JSON.parse(requestBody);
|
|
496
785
|
const request = await currentSummaryRequest(config.exchange_id);
|
|
497
786
|
if (!request) return json(404, { error: 'Saved step not found.' });
|
|
@@ -556,11 +845,14 @@ const server = createServer(async (req, res) => {
|
|
|
556
845
|
let routed;
|
|
557
846
|
try { routed = routeRequest(routing, req, requestBody); }
|
|
558
847
|
catch (error) { return json(400, { error: error.message }); }
|
|
848
|
+
// OpenRouter runs on this proxy's own key; the other providers on the
|
|
849
|
+
// client's, which it brought with it.
|
|
850
|
+
if (routed.provider === 'openrouter' && !hasToken(req, apiToken)) return json(401, NOT_SIGNED_IN);
|
|
559
851
|
const traceId = req.headers['x-raytace-trace-id'] || req.headers['x-request-id'] || randomUUID(); const started = new Date().toISOString(); const selectedProvider = routed.provider;
|
|
560
852
|
const spanId = randomUUID();
|
|
561
853
|
const sessionId = req.headers['x-raytace-session-id'];
|
|
562
854
|
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))
|
|
855
|
+
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
856
|
? { session_id: sessionId, session_started_at: new Date(sessionStartedAt).toISOString() } : fallbackSession;
|
|
565
857
|
const requestPayload = routed.payload;
|
|
566
858
|
try {
|
|
@@ -595,6 +887,7 @@ server.on('error', (error) => {
|
|
|
595
887
|
});
|
|
596
888
|
try {
|
|
597
889
|
for (const job of db.loadExperiments(200).reverse()) {
|
|
890
|
+
if (job.kind === 'fork') continue; // Playground forks: playground.mjs
|
|
598
891
|
if (['queued', 'running'].includes(job.status)) job.status = 'interrupted';
|
|
599
892
|
jobs.set(job.id, job);
|
|
600
893
|
}
|
|
@@ -603,6 +896,37 @@ try {
|
|
|
603
896
|
server.listen(port, '127.0.0.1', () => {
|
|
604
897
|
const stats = db.stats();
|
|
605
898
|
console.log(`RayTrace proxy listening on http://127.0.0.1:${server.address().port}`);
|
|
606
|
-
console.
|
|
899
|
+
playground.recover().catch((error) => console.error(`Playground forks could not be checked: ${error.message}`));
|
|
900
|
+
console.log(`Store: ${dbFile} (journal=${db.journal}, ${stats.sessions} sessions, ${stats.turns} turns, ${stats.exchanges} exchanges, ${stats.processes} sandbox processes)`);
|
|
901
|
+
});
|
|
902
|
+
// gVisor sandbox evidence (worker/sandbox/): discovers the local sandboxes from the
|
|
903
|
+
// Mac-side manager (:8799) and tails each one's process events from the
|
|
904
|
+
// evidence viewer (:8798), recording matched execs as the primary witness
|
|
905
|
+
// for those sessions. Best-effort: with neither service running it logs
|
|
906
|
+
// once and idles. RAYTACE_GVISOR_FORWARDER=0 turns it off entirely.
|
|
907
|
+
const gvisorForwarder = process.env.RAYTACE_GVISOR_FORWARDER === '0' ? null : startGvisorForwarder({
|
|
908
|
+
listProjects: () => sandboxes.list(),
|
|
909
|
+
viewerBase: EVIDENCE_VIEWER,
|
|
910
|
+
fetchImpl: fromViewer,
|
|
911
|
+
ingest: (events, { sessionId }) => ingestExecutions(db, events, { sessionId }),
|
|
912
|
+
// Exits, found by the process's own identity (pid + start time), so an
|
|
913
|
+
// exit closes its process even after a proxy restart or for a process the
|
|
914
|
+
// forwarder never tracked.
|
|
915
|
+
finish: (row) => recordExit(row),
|
|
916
|
+
finishByProcess: (row) => recordExit(row),
|
|
917
|
+
// A sandbox whose remaining exits can no longer arrive.
|
|
918
|
+
lose: (row) => db.loseOpenProcesses({ containerId: row.container_id, reason: row.reason, raw: row.raw ?? null, ended: row.ended === true }),
|
|
919
|
+
// Processes that ran underneath a matched call, and ones that matched
|
|
920
|
+
// nothing at all (parent_call_id null): recorded either way.
|
|
921
|
+
descend: ({ exec, parent_call_id, session_id }) => {
|
|
922
|
+
const started = db.recordProcessStart({ containerId: exec.container_id, projectId: session_id ?? null, raw: exec.raw, startedMs: exec.timestamp });
|
|
923
|
+
if (parent_call_id && started?.eventId) db.attribute({ toolCallId: parent_call_id, eventId: started.eventId, method: 'inherited', confidence: 'corroborated' });
|
|
924
|
+
},
|
|
607
925
|
});
|
|
608
|
-
|
|
926
|
+
function recordExit(row) {
|
|
927
|
+
return db.recordProcessExit({ containerId: row.container_id, projectId: row.session_id ?? null, raw: row.raw,
|
|
928
|
+
endedMs: row.ended_ms ?? null, exit_code: row.exit_code ?? null, signal: row.signal ?? null });
|
|
929
|
+
}
|
|
930
|
+
// Local sandboxes' Claude Code transcripts (raytrace sandbox create --local).
|
|
931
|
+
startSandboxBridge({ dataDir, port: Number(process.env.RAYTRACE_BRIDGE_PORT || 8799), ingest: ingestFromSandbox });
|
|
932
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { try { gvisorForwarder?.stop(); db.close(); } finally { process.exit(0); } });
|