raytrace-cli 0.11.1__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- raytrace/__init__.py +1 -0
- raytrace/__main__.py +33 -0
- raytrace/app/LICENSE +21 -0
- raytrace/app/README.md +599 -0
- raytrace/app/bin/raytrace.mjs +297 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
- raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
- raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
- raytrace/app/dist/dashboard/assets/index-DepcI8Fi.js +38 -0
- raytrace/app/dist/dashboard/assets/index-H97VLD5l.css +1 -0
- raytrace/app/dist/dashboard/favicon.svg +6 -0
- raytrace/app/dist/dashboard/index.html +15 -0
- raytrace/app/package.json +48 -0
- raytrace/app/proxy/agent-intent-schema.test.mjs +142 -0
- raytrace/app/proxy/call-assessment.mjs +385 -0
- raytrace/app/proxy/call-assessment.test.mjs +167 -0
- raytrace/app/proxy/call-category.mjs +461 -0
- raytrace/app/proxy/capture-health.mjs +30 -0
- raytrace/app/proxy/capture-health.test.mjs +44 -0
- raytrace/app/proxy/capture.mjs +38 -0
- raytrace/app/proxy/capture.test.mjs +49 -0
- raytrace/app/proxy/claude-code-adapter.mjs +301 -0
- raytrace/app/proxy/claude-code-hook.mjs +22 -0
- raytrace/app/proxy/codex-config.mjs +36 -0
- raytrace/app/proxy/codex.mjs +14 -0
- raytrace/app/proxy/evidence-schema.test.mjs +240 -0
- raytrace/app/proxy/evidence-store.mjs +993 -0
- raytrace/app/proxy/evidence-store.test.mjs +301 -0
- raytrace/app/proxy/exec-narrative.mjs +625 -0
- raytrace/app/proxy/exec-narrative.test.mjs +262 -0
- raytrace/app/proxy/execution-correlation.mjs +185 -0
- raytrace/app/proxy/execution-correlation.test.mjs +146 -0
- raytrace/app/proxy/execution-runner.mjs +89 -0
- raytrace/app/proxy/execution-runner.test.mjs +38 -0
- raytrace/app/proxy/experiment-engine.mjs +195 -0
- raytrace/app/proxy/experiment-engine.test.mjs +93 -0
- raytrace/app/proxy/explanations.mjs +36 -0
- raytrace/app/proxy/explanations.test.mjs +20 -0
- raytrace/app/proxy/failure-signature.mjs +56 -0
- raytrace/app/proxy/gvisor-forwarder.mjs +493 -0
- raytrace/app/proxy/gvisor-forwarder.test.mjs +433 -0
- raytrace/app/proxy/init-evidence-db.mjs +227 -0
- raytrace/app/proxy/local-sandboxes.mjs +94 -0
- raytrace/app/proxy/local-token.mjs +30 -0
- raytrace/app/proxy/playground-recovery.test.mjs +130 -0
- raytrace/app/proxy/playground.mjs +439 -0
- raytrace/app/proxy/prompt-context.mjs +278 -0
- raytrace/app/proxy/prompt-traces.mjs +40 -0
- raytrace/app/proxy/prompt-traces.test.mjs +32 -0
- raytrace/app/proxy/providers.mjs +65 -0
- raytrace/app/proxy/providers.test.mjs +76 -0
- raytrace/app/proxy/proxy.integration.test.mjs +135 -0
- raytrace/app/proxy/raytace-proxy.mjs +941 -0
- raytrace/app/proxy/request-metrics.mjs +13 -0
- raytrace/app/proxy/request-metrics.test.mjs +19 -0
- raytrace/app/proxy/request-policy.mjs +45 -0
- raytrace/app/proxy/request-policy.test.mjs +47 -0
- raytrace/app/proxy/run-recap.mjs +139 -0
- raytrace/app/proxy/runtime-attribution.mjs +110 -0
- raytrace/app/proxy/sandbox-bridge.mjs +49 -0
- raytrace/app/proxy/schema/EVIDENCE_DATABASE.md +276 -0
- raytrace/app/proxy/schema/agent_intent.sql +101 -0
- raytrace/app/proxy/schema/auxiliary.sql +90 -0
- raytrace/app/proxy/schema/capture_health.sql +14 -0
- raytrace/app/proxy/schema/classification.sql +89 -0
- raytrace/app/proxy/schema/file_context.sql +53 -0
- raytrace/app/proxy/schema/runtime_evidence.sql +201 -0
- raytrace/app/proxy/schema/search.sql +66 -0
- raytrace/app/proxy/schema/shared_storage.sql +21 -0
- raytrace/app/proxy/search.mjs +418 -0
- raytrace/app/proxy/search.test.mjs +161 -0
- raytrace/app/proxy/smoke.test.mjs +93 -0
- raytrace/app/proxy/step-attribution.mjs +380 -0
- raytrace/app/proxy/step-lab.mjs +78 -0
- raytrace/app/proxy/step-lab.test.mjs +38 -0
- raytrace/app/proxy/summaries.mjs +151 -0
- raytrace/app/proxy/summaries.test.mjs +69 -0
- raytrace/app/proxy/tool-metadata.mjs +111 -0
- raytrace/app/proxy/tool-metadata.test.mjs +38 -0
- raytrace/app/proxy/trace-view.mjs +324 -0
- raytrace/app/proxy/trace-view.test.mjs +92 -0
- raytrace/app/proxy/typesafe.mjs +63 -0
- raytrace/app/proxy/typesafe.test.mjs +39 -0
- raytrace/app/src/agents.mjs +7 -0
- raytrace/app/src/api.mjs +57 -0
- raytrace/app/src/auth.mjs +205 -0
- raytrace/app/src/beta.mjs +96 -0
- raytrace/app/src/claude-code.mjs +93 -0
- raytrace/app/src/commands.mjs +285 -0
- raytrace/app/src/config.mjs +49 -0
- raytrace/app/src/export.mjs +200 -0
- raytrace/app/src/lima.mjs +176 -0
- raytrace/app/src/local-sandbox.mjs +358 -0
- raytrace/app/src/mcp.mjs +688 -0
- raytrace/app/src/paths.mjs +33 -0
- raytrace/app/src/prompt.mjs +42 -0
- raytrace/app/src/proxy-process.mjs +143 -0
- raytrace/app/src/sandbox.mjs +306 -0
- raytrace/app/src/share.mjs +86 -0
- raytrace/app/src/terminal.mjs +68 -0
- raytrace/app/src/upload.mjs +198 -0
- raytrace/app/worker/sandbox/Dockerfile +8 -0
- raytrace/app/worker/sandbox/SYSCALL_CATALOG.md +197 -0
- raytrace/app/worker/sandbox/claude-hook.mjs +364 -0
- raytrace/app/worker/sandbox/collector.py +405 -0
- raytrace/app/worker/sandbox/dns_forwarder.py +255 -0
- raytrace/app/worker/sandbox/engine.py +940 -0
- raytrace/app/worker/sandbox/file_scan.py +491 -0
- raytrace/app/worker/sandbox/lima.yaml +29 -0
- raytrace/app/worker/sandbox/network.py +90 -0
- raytrace/app/worker/sandbox/projects.py +702 -0
- raytrace/app/worker/sandbox/setup.py +159 -0
- raytrace/app/worker/sandbox/syscall_catalog.sql +985 -0
- raytrace/app/worker/sandbox/transcript-delivery.test.mjs +153 -0
- raytrace/app/worker/sandbox/viewer.py +195 -0
- raytrace/node/LICENSE +2946 -0
- raytrace/node/node.exe +4 -0
- raytrace_cli-0.11.1.dist-info/LICENSE +21 -0
- raytrace_cli-0.11.1.dist-info/METADATA +42 -0
- raytrace_cli-0.11.1.dist-info/RECORD +165 -0
- raytrace_cli-0.11.1.dist-info/WHEEL +4 -0
- raytrace_cli-0.11.1.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,941 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
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';
|
|
6
|
+
/** Local API recorder. Point a compatible client at http://127.0.0.1:8797. */
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
import { appendFile, mkdir, readFile, stat } from 'node:fs/promises';
|
|
9
|
+
import { realpathSync, readFileSync } from 'node:fs';
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
import { randomBytes, randomUUID, createHash } from 'node:crypto';
|
|
12
|
+
import { join, dirname, resolve, extname, sep } from 'node:path';
|
|
13
|
+
import { exchangesFromTranscript, parseTranscript, toolResultsFromTranscript } from './claude-code-adapter.mjs';
|
|
14
|
+
import { replayEligibility, createExperiment, runExperiment } from './experiment-engine.mjs';
|
|
15
|
+
import { loadEnvFile } from 'node:process';
|
|
16
|
+
import { providerConfig, routeRequest, selectModel } from './providers.mjs';
|
|
17
|
+
import { inspectStep, createStepRun, runDecision } from './step-lab.mjs';
|
|
18
|
+
import { executeSequence } from './execution-runner.mjs';
|
|
19
|
+
import { explanationRequest, parseExplanations } from './explanations.mjs';
|
|
20
|
+
import { summaryRequest, parseSummary, resultText } from './summaries.mjs';
|
|
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';
|
|
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';
|
|
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';
|
|
36
|
+
|
|
37
|
+
try { loadEnvFile(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
38
|
+
const routing = providerConfig();
|
|
39
|
+
// Summaries default to the cheapest configured alias so per-step summarizing
|
|
40
|
+
// (many small calls) doesn't rack up cost; override with RAYTACE_SUMMARY_MODEL.
|
|
41
|
+
const summaryModel = process.env.RAYTACE_SUMMARY_MODEL
|
|
42
|
+
? selectModel(routing, process.env.RAYTACE_SUMMARY_MODEL)
|
|
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 = 5;
|
|
47
|
+
const fallbackSession = { session_id: randomUUID(), session_started_at: new Date().toISOString() };
|
|
48
|
+
|
|
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';
|
|
53
|
+
// The CLI sets RAYTACE_DATA_DIR (~/.raytrace); run by hand it keeps ./.raytace.
|
|
54
|
+
const dataDir = process.env.RAYTACE_DATA_DIR || join(process.cwd(), '.raytace');
|
|
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>`;
|
|
67
|
+
const maxBodyBytes = Number(process.env.RAYTACE_MAX_BODY_BYTES || 2_000_000);
|
|
68
|
+
const liveExchanges = new Map(); // Credentials stay in process memory, never in the event log.
|
|
69
|
+
const jobs = new Map();
|
|
70
|
+
const jobControllers = new Map();
|
|
71
|
+
const dbFile = process.env.RAYTACE_DB || join(dirname(store), 'evidence.db');
|
|
72
|
+
const archiveJsonl = process.env.RAYTACE_ARCHIVE_JSONL === '1';
|
|
73
|
+
const db = openEvidenceStore(dbFile);
|
|
74
|
+
const allowedOrigins = new Set((process.env.RAYTACE_UI_ORIGINS || '').split(',').filter(Boolean));
|
|
75
|
+
const trustedOrigin = (origin) => originAllowed(origin, allowedOrigins);
|
|
76
|
+
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
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;
|
|
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
|
+
|
|
128
|
+
async function record(event) {
|
|
129
|
+
const row = omitToolChunkIds(event);
|
|
130
|
+
if (row.event_type === 'model.exchange' && row.span_id) db.recordExchange(row);
|
|
131
|
+
else if (row.event_type === 'proxy.error') db.recordProxyError(row);
|
|
132
|
+
// Opt-in raw archive; the database is the source of truth.
|
|
133
|
+
if (archiveJsonl) { await mkdir(dirname(store), { recursive: true }); await appendFile(store, `${JSON.stringify(row)}\n`); }
|
|
134
|
+
}
|
|
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()))); }
|
|
136
|
+
async function invokeReplay(entry, payload, signal) {
|
|
137
|
+
const headers = Object.fromEntries(Object.entries(entry.headers).filter(([key]) =>
|
|
138
|
+
['authorization', 'content-type', 'openai-organization', 'openai-project', 'openai-beta', 'user-agent'].includes(key.toLowerCase())));
|
|
139
|
+
const response = await fetch(entry.upstreamUrl, {
|
|
140
|
+
method: 'POST', headers, body: JSON.stringify(payload),
|
|
141
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(120_000)]),
|
|
142
|
+
});
|
|
143
|
+
if (!response.ok) { await response.body?.cancel(); throw new Error(`Provider returned HTTP ${response.status}; batch stopped. Credentials may have expired or the intervention may be invalid.`); }
|
|
144
|
+
const chunks = []; let size = 0;
|
|
145
|
+
for await (const chunk of response.body) { size += chunk.length; if (size > maxBodyBytes) throw new Error('Replay response exceeded the capture size limit.'); chunks.push(chunk); }
|
|
146
|
+
const body = Buffer.concat(chunks);
|
|
147
|
+
return response.headers.get('content-type')?.includes('text/event-stream') ? parseSseResponse(body) : JSON.parse(body.toString());
|
|
148
|
+
}
|
|
149
|
+
async function persistExperiment(job) { db.saveExperiment(redact(omitToolChunkIds(job))); }
|
|
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. */
|
|
152
|
+
// The trace list takes seconds to build for long sessions and is polled every
|
|
153
|
+
// few seconds, mostly with nothing new: it is rebuilt only when the data
|
|
154
|
+
// behind it changed (db.dataVersion), and one build serves every caller.
|
|
155
|
+
// The body is serialized once per version too, and its version is its ETag,
|
|
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, turnId = null } = {}) {
|
|
160
|
+
return traceView(db, { includeHistory, evidence, turnId, replayReason: (spanId) => {
|
|
161
|
+
const live = liveExchanges.get(spanId);
|
|
162
|
+
return live ? replayEligibility(live) : undefined;
|
|
163
|
+
} });
|
|
164
|
+
}
|
|
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;
|
|
171
|
+
function cachedTraces(url) {
|
|
172
|
+
const version = `${db.dataVersion()}:${categoryAnswers}:${Math.floor(Date.now()/5000)}`;
|
|
173
|
+
const hit = traceCache.get(url);
|
|
174
|
+
if (hit?.version === version) return hit;
|
|
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; } }))
|
|
179
|
+
.then((traces) => JSON.stringify({ traces }));
|
|
180
|
+
const entry = { version, etag: `"${version}"`, body };
|
|
181
|
+
traceCache.set(url, entry);
|
|
182
|
+
body.catch(() => { if (traceCache.get(url) === entry) traceCache.delete(url); });
|
|
183
|
+
return entry;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** `evidence: false` skips building each request's context items, the
|
|
187
|
+
* costliest part (every request resends the conversation so far), for
|
|
188
|
+
* callers that do not send them on. */
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
// Context window sizes, from OpenRouter's public model list (no key needed),
|
|
192
|
+
// fetched once. Null when the model is not listed or the list is unreachable.
|
|
193
|
+
let contextWindows = null;
|
|
194
|
+
async function contextWindow(model) {
|
|
195
|
+
if (!model) return null;
|
|
196
|
+
if (!contextWindows) {
|
|
197
|
+
contextWindows = fetch('https://openrouter.ai/api/v1/models', { signal: AbortSignal.timeout(5000) })
|
|
198
|
+
.then((response) => (response.ok ? response.json() : { data: [] }))
|
|
199
|
+
.then((body) => new Map((body.data ?? []).map((item) => [item.id, item.context_length ?? null])))
|
|
200
|
+
.catch(() => { contextWindows = null; return new Map(); });
|
|
201
|
+
}
|
|
202
|
+
const windows = await contextWindows;
|
|
203
|
+
return windows.get(model) ?? windows.get(`openai/${model}`) ?? windows.get(`anthropic/${model}`) ?? null;
|
|
204
|
+
}
|
|
205
|
+
/** The context analysis for one prompt, from the last request of its turn. */
|
|
206
|
+
async function promptContextFor(traceId) {
|
|
207
|
+
const trace = (await readTraces(true, { evidence: false })).find((item) => item.id === traceId);
|
|
208
|
+
const last = trace?.requests?.at(-1);
|
|
209
|
+
const entry = last ? await savedOrLive(last.id) : null;
|
|
210
|
+
if (!entry) return null;
|
|
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();
|
|
229
|
+
}
|
|
230
|
+
async function savedOrLive(exchangeId) {
|
|
231
|
+
return liveExchanges.get(exchangeId) || db.findExchange(exchangeId);
|
|
232
|
+
}
|
|
233
|
+
/** The summary request for one step as it stands now, or null. Its key
|
|
234
|
+
* changes with the summary version and with the step's own results, which
|
|
235
|
+
* are recorded once a later request carries them back. */
|
|
236
|
+
async function currentSummaryRequest(exchangeId) {
|
|
237
|
+
const entry = await savedOrLive(exchangeId);
|
|
238
|
+
if (!entry) return null;
|
|
239
|
+
const ownCalls = (entry.response?.output ?? []).filter((item) => item?.call_id);
|
|
240
|
+
const contexts = db.toolCallContexts(ownCalls.map((item) => item.call_id));
|
|
241
|
+
const ownResults = ownCalls.map((item) => ({ from: item.name, output: resultText(contexts.get(item.call_id)?.result) }));
|
|
242
|
+
return summaryRequest(entry, exchangeId, summaryModel, ownResults);
|
|
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
|
+
const pendingExplanations = new Map();
|
|
291
|
+
const pendingSummaries = new Map();
|
|
292
|
+
const MAX_CONCURRENT_SUMMARIES = 4; // cheap+budget-capped calls; safe to run several at once instead of one at a time
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
// ---------------------------------------------------------------- Claude Code
|
|
296
|
+
// Proxy-free capture: Claude Code's hooks ring, and its session transcript is
|
|
297
|
+
// rebuilt into the same exchange rows the proxy records (claude-code-adapter).
|
|
298
|
+
const claudeProjects = resolve(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');
|
|
299
|
+
const CLAUDE_CODE_FINAL_EVENTS = new Set(['Stop', 'SubagentStop', 'SessionEnd']);
|
|
300
|
+
function claudeCodeTranscriptPath(value) {
|
|
301
|
+
if (typeof value !== 'string' || !value.endsWith('.jsonl')) return null;
|
|
302
|
+
try {
|
|
303
|
+
const real = realpathSync(value);
|
|
304
|
+
return real.startsWith(`${realpathSync(claudeProjects)}/`) ? real : null;
|
|
305
|
+
} catch { return null; }
|
|
306
|
+
}
|
|
307
|
+
// One job at a time per transcript (a write, then a read); later rings queue.
|
|
308
|
+
const claudeCodeQueues = new Map();
|
|
309
|
+
function serially(path, job) {
|
|
310
|
+
const next = (claudeCodeQueues.get(path) ?? Promise.resolve()).then(job);
|
|
311
|
+
const settled = next.catch(() => {}).finally(() => { if (claudeCodeQueues.get(path) === settled) claudeCodeQueues.delete(path); });
|
|
312
|
+
claudeCodeQueues.set(path, settled);
|
|
313
|
+
return next;
|
|
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 }) {
|
|
318
|
+
serially(path, async () => {
|
|
319
|
+
const lines = parseTranscript(await readFile(path, 'utf8'));
|
|
320
|
+
const rows = exchangesFromTranscript(lines,
|
|
321
|
+
{ final, sessionId: session?.id ?? null, sessionStartedAt: session?.startedAt ?? null });
|
|
322
|
+
for (const row of rows) {
|
|
323
|
+
await record({ ...row, request: { ...row.request, payload: redact(row.request.payload) }, response: { ...row.response, payload: redact(row.response.payload) } });
|
|
324
|
+
}
|
|
325
|
+
for (const [callId, item] of toolResultsFromTranscript(lines)) {
|
|
326
|
+
db.recordToolResult?.(callId, item);
|
|
327
|
+
}
|
|
328
|
+
if (session) await attributeLateProcesses(db, session.id);
|
|
329
|
+
}).catch((error) => console.error(`Claude Code transcript ${path} could not be read: ${error.message}`));
|
|
330
|
+
}
|
|
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
|
+
|
|
375
|
+
// The prebuilt dashboard (RAYTACE_DASHBOARD_DIR), served from / so it and the
|
|
376
|
+
// API share one origin. Model traffic is under /v1 and the API under /raytace,
|
|
377
|
+
// so any other GET from a browser (no credentials) is a dashboard file; unknown
|
|
378
|
+
// paths get index.html.
|
|
379
|
+
const dashboardDir = process.env.RAYTACE_DASHBOARD_DIR ? resolve(process.env.RAYTACE_DASHBOARD_DIR) : null;
|
|
380
|
+
const CONTENT_TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2', '.json': 'application/json' };
|
|
381
|
+
async function serveDashboard(req, res) {
|
|
382
|
+
const path = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
|
|
383
|
+
let file = resolve(dashboardDir, `.${path}`);
|
|
384
|
+
if (file !== dashboardDir && !file.startsWith(dashboardDir + sep)) { res.writeHead(404); return res.end(); }
|
|
385
|
+
let body;
|
|
386
|
+
try { body = await readFile(file); }
|
|
387
|
+
catch { file = join(dashboardDir, 'index.html'); body = await readFile(file); }
|
|
388
|
+
const immutable = path.startsWith('/assets/');
|
|
389
|
+
res.writeHead(200, { 'content-type': CONTENT_TYPES[extname(file)] || 'application/octet-stream', 'cache-control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache' });
|
|
390
|
+
res.end(body);
|
|
391
|
+
}
|
|
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
|
+
|
|
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
|
+
}
|
|
420
|
+
const fromAgent = req.headers.authorization || req.headers['x-api-key'] || req.headers['anthropic-version'];
|
|
421
|
+
if (dashboardDir && req.method === 'GET' && !fromAgent && !req.url?.startsWith('/raytace/') && !req.url?.startsWith('/v1/')) {
|
|
422
|
+
try { return await serveDashboard(req, res); }
|
|
423
|
+
catch { res.writeHead(404); return res.end('Dashboard not built.'); }
|
|
424
|
+
}
|
|
425
|
+
const localApi = req.url?.startsWith('/raytace/');
|
|
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' };
|
|
427
|
+
const json = (status, value) => { res.writeHead(status, { 'content-type': 'application/json', ...corsHeaders, 'cache-control': 'no-store' }); res.end(JSON.stringify(redact(omitToolChunkIds(value)))); };
|
|
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/traces?') && new URL(req.url,'http://local').searchParams.has('trace')) {
|
|
480
|
+
const id=new URL(req.url,'http://local').searchParams.get('trace');
|
|
481
|
+
if(!/^[A-Za-z0-9_.:-]{1,160}$/.test(id??'')) return json(400,{error:'Invalid trace'});
|
|
482
|
+
const traces=await readTraces(true,{evidence:true,turnId:id});
|
|
483
|
+
return json(traces.length?200:404,{traces});
|
|
484
|
+
}
|
|
485
|
+
if (req.method === 'GET' && req.url?.startsWith('/raytace/runtime?')) {
|
|
486
|
+
const query = new URL(req.url, 'http://localhost').searchParams;
|
|
487
|
+
const sandbox = query.get('sandbox');
|
|
488
|
+
const before = query.get('before') || '0';
|
|
489
|
+
// `since`/`until` scope the page to one agent turn (the prompt through the
|
|
490
|
+
// answer). Without them this returns the whole sandbox's history, which is
|
|
491
|
+
// every prompt ever run in it.
|
|
492
|
+
const since = query.get('since') || '0';
|
|
493
|
+
const until = query.get('until') || '0';
|
|
494
|
+
const raw = query.get('raw') === '1';
|
|
495
|
+
const ok = (value) => /^\d{1,16}$/.test(value);
|
|
496
|
+
if (!/^rtp-[a-f0-9]{32}$/.test(sandbox || '') || ![before, since, until].every(ok)) return json(400, { error: 'Invalid sandbox or cursor' });
|
|
497
|
+
try {
|
|
498
|
+
const project = (await sandboxes.list()).find((p) => p.id === sandbox);
|
|
499
|
+
if (!project?.container_id || !/^[a-f0-9]{64}$/.test(project.container_id)) return json(404, { error: 'Sandbox mapping unavailable' });
|
|
500
|
+
const window = `${since !== '0' ? `&since=${since}` : ''}${until !== '0' ? `&until=${until}` : ''}`;
|
|
501
|
+
// A windowed page wants everything in the window, not the newest 100:
|
|
502
|
+
// folding turns hundreds of raw events into a handful of commands.
|
|
503
|
+
const limit = since !== '0' || until !== '0' ? 500 : 100;
|
|
504
|
+
const evidence = await fromViewer(`${EVIDENCE_VIEWER}/events?container=${project.container_id}&before=${before}${window}&limit=${limit}&processes=1`, { signal: AbortSignal.timeout(10000) });
|
|
505
|
+
if (!evidence.ok) throw new Error('Runtime collector unavailable');
|
|
506
|
+
const page = await evidence.json();
|
|
507
|
+
const base = { ...page, sandbox, container_id: project.container_id, captureHealth:db.captureHealth(sandbox,{since:Number(since)||undefined,until:Number(until)||Date.now()}) };
|
|
508
|
+
// `raw=1` is the "show everything" escape hatch: the folded view must
|
|
509
|
+
// always be auditable against what the collector actually recorded.
|
|
510
|
+
if (raw) return json(200, base);
|
|
511
|
+
|
|
512
|
+
const { commands, folded } = foldEvents(page.events);
|
|
513
|
+
// Which call each process belongs to, by the process's own identity
|
|
514
|
+
// (pid + start time) within this sandbox. `attribution` stays null when
|
|
515
|
+
// the process was not recorded yet -- not the same as unattributed,
|
|
516
|
+
// which is a recorded process that matched no call.
|
|
517
|
+
const known = new Map(db.attributionsForProcesses({ containerId: project.container_id, pids: commands.map((c) => c.pid) })
|
|
518
|
+
.map((row) => [`${row.pid}:${row.start_time_ns}`, row]));
|
|
519
|
+
for (const command of commands) {
|
|
520
|
+
const row = command.process_start_ns ? known.get(`${command.pid}:${command.process_start_ns}`) : null;
|
|
521
|
+
command.attribution = row ? { call_id: row.call_id ?? null, parent_call_id: row.parent_call_id ?? null, tier: row.tier ?? null } : null;
|
|
522
|
+
}
|
|
523
|
+
attributeMarked(commands);
|
|
524
|
+
// Cache first, so a repeat view of the same turn costs nothing. Only
|
|
525
|
+
// commands no rule can describe are ever sent to a model.
|
|
526
|
+
describeAll(commands, (command) => db.getCommandDescription(command));
|
|
527
|
+
const missing = undescribed(commands);
|
|
528
|
+
if (missing.length && routing.mode === 'openrouter') {
|
|
529
|
+
try {
|
|
530
|
+
const request = describeRequest(missing, summaryModel);
|
|
531
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
532
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
533
|
+
const text = (response.output || []).filter((item) => item.type === 'message')
|
|
534
|
+
.map((item) => (item.content || []).map((part) => part.text || '').join('')).join(' ');
|
|
535
|
+
for (const [command, description] of parseDescriptions(text, request.commands)) {
|
|
536
|
+
db.putCommandDescription(command, description, summaryModel);
|
|
537
|
+
}
|
|
538
|
+
describeAll(commands, (command) => db.getCommandDescription(command));
|
|
539
|
+
} catch (error) {
|
|
540
|
+
// A failed description must never cost us the evidence: the commands
|
|
541
|
+
// still render, just verbatim.
|
|
542
|
+
console.error('[raytace] command descriptions unavailable:', error.message);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
let call_labels = {};
|
|
546
|
+
try { call_labels = await assessCommands(commands); }
|
|
547
|
+
catch (error) { console.error('[raytace] command severity unavailable:', error.message); }
|
|
548
|
+
return json(200, { ...base, commands, folded, call_labels, severity_source: typesafe.enabled ? 'jev' : 'rules', events: undefined });
|
|
549
|
+
} catch { return json(503, { error: 'Runtime evidence unavailable: the local sandbox VM is not running. Missing evidence is not proof of non-execution.' }); }
|
|
550
|
+
}
|
|
551
|
+
// The dashboard polls the history every few seconds: its context items
|
|
552
|
+
// (`evidence`) grow with the square of a session's length, so the history
|
|
553
|
+
// carries them only when asked for (&evidence=1, Compare runs). The recent
|
|
554
|
+
// list keeps them.
|
|
555
|
+
if (req.method === 'GET' && ['/raytace/traces', '/raytace/traces?scope=history', '/raytace/traces?scope=history&evidence=1'].includes(req.url)) {
|
|
556
|
+
try {
|
|
557
|
+
const cached = cachedTraces(req.url);
|
|
558
|
+
const headers = { ...corsHeaders, etag: cached.etag, 'cache-control': 'no-cache', 'access-control-expose-headers': 'etag' };
|
|
559
|
+
if (req.headers['if-none-match'] === cached.etag) { res.writeHead(304, headers); return res.end(); }
|
|
560
|
+
const body = await cached.body;
|
|
561
|
+
res.writeHead(200, { 'content-type': 'application/json', ...headers }); return res.end(body);
|
|
562
|
+
}
|
|
563
|
+
catch (error) { res.writeHead(500, { 'content-type': 'application/json', ...corsHeaders }); return res.end(JSON.stringify({ error: String(error) })); }
|
|
564
|
+
}
|
|
565
|
+
// Splunk-style search over the derived index (search.mjs). `from`/`to`
|
|
566
|
+
// are epoch ms or ISO dates; the query itself carries fields and pipes.
|
|
567
|
+
if (req.method === 'GET' && (req.url === '/raytace/search' || req.url?.startsWith('/raytace/search?') || req.url?.startsWith('/raytace/search/signatures'))) {
|
|
568
|
+
try {
|
|
569
|
+
const params = new URL(req.url, 'http://localhost').searchParams;
|
|
570
|
+
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; };
|
|
571
|
+
const range = { fromMs: bound('from'), toMs: bound('to') };
|
|
572
|
+
if (req.url.startsWith('/raytace/search/signatures')) {
|
|
573
|
+
return json(200, { signatures: db.failureSignatures({ ...range, limit: Number(params.get('limit')) || 20 }) });
|
|
574
|
+
}
|
|
575
|
+
return json(200, db.search({ q: params.get('q') ?? '', ...range, limit: Number(params.get('limit')) || 50, offset: Number(params.get('offset')) || 0 }));
|
|
576
|
+
} catch (error) { return json(500, { error: `Search failed: ${error.message}` }); }
|
|
577
|
+
}
|
|
578
|
+
// Who is signed in and which paid features they have. Nobody yet: sign-in
|
|
579
|
+
// comes with the RayTrace cloud; the dashboard already reads this shape.
|
|
580
|
+
// Which proxy this is, so the CLI can tell an outdated one still running
|
|
581
|
+
// after an upgrade (src/proxy-process.mjs PROXY_API) and replace it.
|
|
582
|
+
if (req.method === 'GET' && req.url === '/raytace/version') return json(200, { api: PROXY_API });
|
|
583
|
+
if (req.method === 'GET' && req.url === '/raytace/account') return json(200, { signed_in: false, plan: 'free', features: [] });
|
|
584
|
+
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' });
|
|
585
|
+
const stepRoute = req.url?.match(/^\/raytace\/steps\/([a-f0-9-]+)\/(\d+)$/);
|
|
586
|
+
if (req.method === 'GET' && stepRoute) {
|
|
587
|
+
const live = liveExchanges.get(stepRoute[1]);
|
|
588
|
+
try {
|
|
589
|
+
const entry = await savedOrLive(stepRoute[1]);
|
|
590
|
+
if (!entry) return json(404, { error: 'This step was not found in the saved captures.' });
|
|
591
|
+
if (!entry.payload || !entry.response) return json(409, { error: 'This capture contains only metadata; its full request or response was not saved.' });
|
|
592
|
+
const step = inspectStep(omitToolChunkIds(entry), stepRoute[1], Number(stepRoute[2]));
|
|
593
|
+
if (!live) step.replay_reason = 'Saved log — available to inspect. Rerunning requires a fresh capture: the live snapshot expired after 30 minutes, a proxy restart, or eviction from the latest 10 exchanges.';
|
|
594
|
+
const request = explanationRequest(step, routing.defaultModel);
|
|
595
|
+
const explanation = db.getExplanation(request.key);
|
|
596
|
+
return json(200, { ...step, hypotheses: explanation?.hypotheses || [], explanation_generated: !!explanation, explanation_model: routing.defaultModel });
|
|
597
|
+
}
|
|
598
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
599
|
+
}
|
|
600
|
+
const contextRoute = req.url?.match(/^\/raytace\/prompt-context\/([A-Za-z0-9_-]{1,80})$/);
|
|
601
|
+
if (req.method === 'GET' && contextRoute) {
|
|
602
|
+
try {
|
|
603
|
+
const found = await promptContextFor(contextRoute[1]);
|
|
604
|
+
if (!found) return json(404, { error: 'Prompt not found in the captured history.' });
|
|
605
|
+
const request = contextSummaryRequest(found.context, summaryModel);
|
|
606
|
+
const model = found.trace.requests?.at(-1)?.model ?? found.trace.model;
|
|
607
|
+
return json(200, { ...found.context, model, context_window: await contextWindow(model),
|
|
608
|
+
summary: request ? db.getSummary(request.key) : null, summary_needed: !!request, summary_model: summaryModel });
|
|
609
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
610
|
+
}
|
|
611
|
+
// One context item's full text, as the model received it, for opening in
|
|
612
|
+
// its own tab: /raytace/prompt-context/<trace>/item/<input index | instructions | tools>
|
|
613
|
+
const itemRoute = req.url?.match(/^\/raytace\/prompt-context\/([A-Za-z0-9_-]{1,80})\/item\/(\d{1,6}|instructions|tools)$/);
|
|
614
|
+
if (req.method === 'GET' && itemRoute) {
|
|
615
|
+
const trace = (await readTraces(true, { evidence: false })).find((item) => item.id === itemRoute[1]);
|
|
616
|
+
const last = trace?.requests?.at(-1);
|
|
617
|
+
const entry = last ? await savedOrLive(last.id) : null;
|
|
618
|
+
const text = entry ? contextItemText(entry, itemRoute[2]) : null;
|
|
619
|
+
res.writeHead(text == null ? 404 : 200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
620
|
+
return res.end(text ?? 'Not found in the captured context.');
|
|
621
|
+
}
|
|
622
|
+
const recapRoute = req.url?.match(/^\/raytace\/recap\/([A-Za-z0-9_-]{1,80})$/);
|
|
623
|
+
if (req.method === 'GET' && recapRoute) {
|
|
624
|
+
const request = await currentRecapRequest(recapRoute[1]);
|
|
625
|
+
return json(200, { recap: request ? db.getSummary(request.key) : null, available: Boolean(request), model: observerModel });
|
|
626
|
+
}
|
|
627
|
+
const summaryRoute = req.url?.match(/^\/raytace\/summaries\/([a-f0-9-]+)$/);
|
|
628
|
+
// Only a summary of the step as it stands now: one written by an older
|
|
629
|
+
// version, or before the step's own result was known, is not served.
|
|
630
|
+
if (req.method === 'GET' && summaryRoute) {
|
|
631
|
+
const request = await currentSummaryRequest(summaryRoute[1]);
|
|
632
|
+
return json(200, { summary: request ? db.getSummary(request.key) : null, model: summaryModel });
|
|
633
|
+
}
|
|
634
|
+
const attributionRoute = req.url?.match(/^\/raytace\/attribution\/([A-Za-z0-9_.:-]{1,120})\/(\d{1,5})$/);
|
|
635
|
+
if (req.method === 'GET' && attributionRoute) {
|
|
636
|
+
const found = attributionStep(decodeURIComponent(attributionRoute[1]), attributionRoute[2]);
|
|
637
|
+
if (found.error) return json(found.status, { error: found.error });
|
|
638
|
+
return json(200, { attribution: db.getExplanation(found.key) });
|
|
639
|
+
}
|
|
640
|
+
if (req.method === 'GET' && req.url === '/raytace/experiments') return json(200, { experiments: [...jobs.values()].slice(-30).reverse() });
|
|
641
|
+
// Playground forks (playground.mjs): listed and read freely, changed only
|
|
642
|
+
// with the dashboard's header, like experiments.
|
|
643
|
+
if (req.method === 'GET' && req.url === '/raytace/forks') return json(200, { forks: playground.list() });
|
|
644
|
+
const previewRoute = req.url?.match(/^\/raytace\/forks\/preview\/([a-f0-9-]{36})$/);
|
|
645
|
+
if (req.method === 'GET' && previewRoute) {
|
|
646
|
+
try { return json(200, await playground.preview(previewRoute[1])); } catch (error) { return json(400, { error: error.message }); }
|
|
647
|
+
}
|
|
648
|
+
// A project's snapshot history, read-only: its files at a snapshot, one
|
|
649
|
+
// file, or the diff between two snapshots (a fork's live under refs/forks/).
|
|
650
|
+
const snapRoute = req.url?.match(/^\/raytace\/snapshots\/(rtp-[a-f0-9]{32})\/(files|file|diff)\?(.*)$/);
|
|
651
|
+
if (req.method === 'GET' && snapRoute) {
|
|
652
|
+
const query = new URLSearchParams(snapRoute[3]);
|
|
653
|
+
const request = { op: { files: 'list', file: 'show', diff: 'diff' }[snapRoute[2]], commit: query.get('commit') ?? '',
|
|
654
|
+
...(query.get('to') ? { to: query.get('to') } : {}), ...(query.get('path') ? { path: query.get('path') } : {}) };
|
|
655
|
+
try { return json(200, await playground.snapshot(snapRoute[1], request)); } catch (error) { return json(400, { error: error.message }); }
|
|
656
|
+
}
|
|
657
|
+
const forkRoute = req.url?.match(/^\/raytace\/forks\/(rtf-[a-f0-9]{32})(?:\/(keep|unkeep|delete|stop-all))?$/);
|
|
658
|
+
if (forkRoute) {
|
|
659
|
+
if (req.method === 'GET' && !forkRoute[2]) { const fork = playground.get(forkRoute[1]); return fork ? json(200, fork) : json(404, { error: 'Fork not found.' }); }
|
|
660
|
+
if (req.method !== 'POST' || !forkRoute[2] || req.headers['x-raytace-experiment'] !== '1') return json(403, { error: 'Use the Playground in the dashboard.' });
|
|
661
|
+
try {
|
|
662
|
+
const action = forkRoute[2];
|
|
663
|
+
return json(200, action === 'delete' ? await playground.remove(forkRoute[1]) : action === 'stop-all' ? await playground.stopGroup(forkRoute[1])
|
|
664
|
+
: playground.keep(forkRoute[1], action === 'keep'));
|
|
665
|
+
}
|
|
666
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
667
|
+
}
|
|
668
|
+
const jobRoute = req.url?.match(/^\/raytace\/experiments\/([a-f0-9-]+)(\/cancel)?$/);
|
|
669
|
+
if (jobRoute) {
|
|
670
|
+
const job = jobs.get(jobRoute[1]); if (!job) return json(404, { error: 'Experiment not found.' });
|
|
671
|
+
if (req.method === 'GET' && !jobRoute[2]) return json(200, job);
|
|
672
|
+
if (req.method === 'POST' && jobRoute[2] && req.headers['x-raytace-experiment'] === '1') { jobControllers.get(job.id)?.abort(); return json(200, job); }
|
|
673
|
+
return json(405, { error: 'Unsupported experiment operation.' });
|
|
674
|
+
}
|
|
675
|
+
// Claude Code hook doorbell (proxy/claude-code-hook.mjs): "this session's
|
|
676
|
+
// transcript has new lines". Answered at once; the transcript is read
|
|
677
|
+
// afterwards so the hook never holds Claude Code up. The custom header is
|
|
678
|
+
// not in the CORS allow-list, so a web page cannot ring it. A local
|
|
679
|
+
// sandbox's hook sends its lines to the sandbox bridge instead (ingestFromSandbox).
|
|
680
|
+
if (req.method === 'POST' && req.url === '/raytace/ingest/claude-code') {
|
|
681
|
+
if (req.headers['x-raytace-hook'] !== '1' || !req.headers['content-type']?.includes('application/json')) return json(403, { error: 'Claude Code hook requests only.' });
|
|
682
|
+
const chunks = []; let size = 0;
|
|
683
|
+
for await (const part of req) { size += part.length; if (size > 64_000) return json(413, { error: 'Request too large.' }); chunks.push(part); }
|
|
684
|
+
let note;
|
|
685
|
+
try { note = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return json(400, { error: 'Invalid JSON.' }); }
|
|
686
|
+
const path = claudeCodeTranscriptPath(note?.transcript_path);
|
|
687
|
+
if (!path) return json(400, { error: 'transcript_path must be a Claude Code transcript under ~/.claude/projects.' });
|
|
688
|
+
json(202, { accepted: true });
|
|
689
|
+
ingestClaudeCode(path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) && note.more !== true });
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
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.' });
|
|
693
|
+
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.' });
|
|
694
|
+
const parts = []; let bytes = 0;
|
|
695
|
+
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); }
|
|
696
|
+
const requestBody = Buffer.concat(parts);
|
|
697
|
+
if (req.method === 'POST' && req.url === '/raytace/forks') {
|
|
698
|
+
try { return json(202, await playground.create(JSON.parse(requestBody))); }
|
|
699
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
700
|
+
}
|
|
701
|
+
if (req.method === 'POST' && req.url === '/raytace/explanations') {
|
|
702
|
+
try {
|
|
703
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Explanations need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
704
|
+
const config = JSON.parse(requestBody);
|
|
705
|
+
const entry = await savedOrLive(config.exchange_id);
|
|
706
|
+
if (!entry) return json(404, { error: 'Saved step not found.' });
|
|
707
|
+
const step = inspectStep(omitToolChunkIds(entry), config.exchange_id, config.output_index);
|
|
708
|
+
const request = explanationRequest(step, routing.defaultModel);
|
|
709
|
+
const cached = db.getExplanation(request.key);
|
|
710
|
+
if (cached) return json(200, cached);
|
|
711
|
+
if (!pendingExplanations.has(request.key)) {
|
|
712
|
+
if (pendingExplanations.size) return json(409, { error: 'Another explanation is being generated. Try again shortly.' });
|
|
713
|
+
const task = (async () => {
|
|
714
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
715
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
716
|
+
const result = { ...parseExplanations(response, request.sources), model: routing.defaultModel };
|
|
717
|
+
db.putExplanation(request.key, result);
|
|
718
|
+
return result;
|
|
719
|
+
})();
|
|
720
|
+
pendingExplanations.set(request.key, task);
|
|
721
|
+
}
|
|
722
|
+
try { return json(200, await pendingExplanations.get(request.key)); } finally { pendingExplanations.delete(request.key); }
|
|
723
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
724
|
+
}
|
|
725
|
+
if (req.method === 'POST' && req.url === '/raytace/attribution') {
|
|
726
|
+
try {
|
|
727
|
+
const config = JSON.parse(requestBody);
|
|
728
|
+
const found = attributionStep(config.exchange_id, config.output_index);
|
|
729
|
+
if (found.error) return json(found.status, { error: found.error });
|
|
730
|
+
const cached = db.getExplanation(found.key);
|
|
731
|
+
if (cached) return json(200, cached);
|
|
732
|
+
if (!pendingAttributions.has(found.key)) {
|
|
733
|
+
if (pendingAttributions.size >= MAX_CONCURRENT_ATTRIBUTIONS) return json(409, { error: 'Too many steps in flight. Try again shortly.' });
|
|
734
|
+
const task = (async () => {
|
|
735
|
+
const result = await computeAttribution(found);
|
|
736
|
+
// A result missing a model only because it failed is not cached, so
|
|
737
|
+
// the next open retries it.
|
|
738
|
+
if (!result.proposer_error && (result.ranked || !typesafe.enabled)) db.putExplanation(found.key, result);
|
|
739
|
+
return result;
|
|
740
|
+
})().finally(() => pendingAttributions.delete(found.key));
|
|
741
|
+
pendingAttributions.set(found.key, task);
|
|
742
|
+
}
|
|
743
|
+
return json(200, await pendingAttributions.get(found.key));
|
|
744
|
+
} catch (error) { console.error('Attribution failed:', error); return json(400, { error: error.message }); }
|
|
745
|
+
}
|
|
746
|
+
if (req.method === 'POST' && req.url === '/raytace/recap') {
|
|
747
|
+
try {
|
|
748
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Recaps need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
749
|
+
const request = await currentRecapRequest(String(JSON.parse(requestBody).trace_id ?? ''));
|
|
750
|
+
if (!request) return json(404, { error: 'Nothing to recap: the prompt was not found, or it made no tool calls.' });
|
|
751
|
+
const cached = db.getSummary(request.key);
|
|
752
|
+
if (cached) return json(200, cached);
|
|
753
|
+
if (!pendingRecaps.has(request.key)) {
|
|
754
|
+
pendingRecaps.set(request.key, (async () => {
|
|
755
|
+
const recap = parseRecap(recapText(await askObserver(request.payload)), request.outline);
|
|
756
|
+
if (!recap) throw new Error('The observer did not return a usable recap. Try again.');
|
|
757
|
+
const result = { ...recap, model: observerModel, created_at: new Date().toISOString() };
|
|
758
|
+
db.putSummary(request.key, null, result);
|
|
759
|
+
return result;
|
|
760
|
+
})().finally(() => pendingRecaps.delete(request.key)));
|
|
761
|
+
}
|
|
762
|
+
return json(200, await pendingRecaps.get(request.key));
|
|
763
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
764
|
+
}
|
|
765
|
+
if (req.method === 'POST' && req.url === '/raytace/prompt-context/summary') {
|
|
766
|
+
try {
|
|
767
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Summaries need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
768
|
+
const found = await promptContextFor(String(JSON.parse(requestBody).trace_id ?? ''));
|
|
769
|
+
if (!found) return json(404, { error: 'Prompt not found in the captured history.' });
|
|
770
|
+
const request = contextSummaryRequest(found.context, summaryModel);
|
|
771
|
+
if (!request) return json(200, { prompts: [], answers: '' });
|
|
772
|
+
const cached = db.getSummary(request.key);
|
|
773
|
+
if (cached) return json(200, cached);
|
|
774
|
+
if (!pendingSummaries.has(request.key)) {
|
|
775
|
+
const task = (async () => {
|
|
776
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
777
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
778
|
+
const result = { ...parseContextSummary(response), model: summaryModel };
|
|
779
|
+
db.putSummary(request.key, null, result);
|
|
780
|
+
return result;
|
|
781
|
+
})();
|
|
782
|
+
pendingSummaries.set(request.key, task);
|
|
783
|
+
}
|
|
784
|
+
try { return json(200, await pendingSummaries.get(request.key)); } finally { pendingSummaries.delete(request.key); }
|
|
785
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
786
|
+
}
|
|
787
|
+
if (req.method === 'POST' && req.url === '/raytace/summaries') {
|
|
788
|
+
try {
|
|
789
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Summaries need an OpenRouter key. Add yours: raytrace key openrouter' });
|
|
790
|
+
const config = JSON.parse(requestBody);
|
|
791
|
+
const request = await currentSummaryRequest(config.exchange_id);
|
|
792
|
+
if (!request) return json(404, { error: 'Saved step not found.' });
|
|
793
|
+
const cached = db.getSummary(request.key);
|
|
794
|
+
if (cached) return json(200, cached);
|
|
795
|
+
if (!pendingSummaries.has(request.key)) {
|
|
796
|
+
if (pendingSummaries.size >= MAX_CONCURRENT_SUMMARIES) return json(409, { error: 'Too many summaries in flight. Try again shortly.' });
|
|
797
|
+
const task = (async () => {
|
|
798
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
799
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
800
|
+
const result = { ...parseSummary(response), model: summaryModel };
|
|
801
|
+
db.putSummary(request.key, config.exchange_id, result);
|
|
802
|
+
return result;
|
|
803
|
+
})();
|
|
804
|
+
pendingSummaries.set(request.key, task);
|
|
805
|
+
}
|
|
806
|
+
try { return json(200, await pendingSummaries.get(request.key)); } finally { pendingSummaries.delete(request.key); }
|
|
807
|
+
} catch (error) { console.error('Summary generation failed:', error); return json(400, { error: error.message }); }
|
|
808
|
+
}
|
|
809
|
+
if (req.method === 'POST' && req.url === '/raytace/step-runs') {
|
|
810
|
+
try {
|
|
811
|
+
if (jobControllers.size) return json(409, { error: 'Wait for the active run or cancel it first.' });
|
|
812
|
+
const config = JSON.parse(requestBody); const entry = liveExchanges.get(config.exchange_id);
|
|
813
|
+
if (!entry) return json(409, { error: 'Snapshot expired. Capture a fresh request.' });
|
|
814
|
+
const model = routing.mode === 'openrouter' ? selectModel(routing, config.model) : entry.payload.model;
|
|
815
|
+
if (config.mode === 'execute' && routing.mode !== 'openrouter') return json(400, { error: 'Full execution requires OpenRouter routing.' });
|
|
816
|
+
const { job, baseline, variant } = createStepRun(entry, config, model);
|
|
817
|
+
const controller = new AbortController();
|
|
818
|
+
jobControllers.set(job.id, controller);
|
|
819
|
+
try { await persistExperiment(job); } catch (error) { jobControllers.delete(job.id); throw error; }
|
|
820
|
+
jobs.set(job.id, job); json(202, job);
|
|
821
|
+
const task = job.mode === 'execute'
|
|
822
|
+
? executeSequence(job, variant, routing, process.cwd(), join(dirname(store), 'runs'), controller.signal)
|
|
823
|
+
: runDecision(job, baseline, variant, (payload, signal) => invokeReplay(entry, payload, signal), controller.signal);
|
|
824
|
+
void task.catch((error) => { job.status = controller.signal.aborted ? 'cancelled' : 'failed'; job.error = error.message; })
|
|
825
|
+
.then(() => { job.completed_at = new Date().toISOString(); return persistExperiment(job); })
|
|
826
|
+
.catch(() => { job.persistence_error = 'Could not save this result.'; })
|
|
827
|
+
.finally(() => jobControllers.delete(job.id));
|
|
828
|
+
return;
|
|
829
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
830
|
+
}
|
|
831
|
+
if (req.method === 'POST' && req.url === '/raytace/experiments') {
|
|
832
|
+
try {
|
|
833
|
+
if (jobControllers.size) return json(409, { error: 'Another trial batch is running. Wait or cancel it first.' });
|
|
834
|
+
const config = JSON.parse(requestBody); const entry = liveExchanges.get(config.exchange_id);
|
|
835
|
+
if (!entry) return json(409, { error: 'Snapshot expired. Capture a new request through this proxy.' });
|
|
836
|
+
const job = createExperiment(entry, config); const controller = new AbortController();
|
|
837
|
+
// Persist the declared target and hashes before sending any paid requests.
|
|
838
|
+
jobControllers.set(job.id, controller);
|
|
839
|
+
try { await persistExperiment(job); } catch (error) { jobControllers.delete(job.id); throw error; }
|
|
840
|
+
jobs.set(job.id, job);
|
|
841
|
+
while (jobs.size > 30) jobs.delete(jobs.keys().next().value);
|
|
842
|
+
json(202, job);
|
|
843
|
+
void runExperiment(job, entry, { invoke: (payload, signal) => invokeReplay(entry, payload, signal), signal: controller.signal })
|
|
844
|
+
.catch(() => { job.status = 'failed'; })
|
|
845
|
+
.then(() => persistExperiment(job))
|
|
846
|
+
.catch(() => { job.persistence_error = 'The result could not be saved to disk.'; })
|
|
847
|
+
.finally(() => jobControllers.delete(job.id));
|
|
848
|
+
return;
|
|
849
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
850
|
+
}
|
|
851
|
+
let routed;
|
|
852
|
+
try { routed = routeRequest(routing, req, requestBody); }
|
|
853
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
854
|
+
// OpenRouter runs on this proxy's own key; the other providers on the
|
|
855
|
+
// client's, which it brought with it.
|
|
856
|
+
if (routed.provider === 'openrouter' && !hasToken(req, apiToken)) return json(401, NOT_SIGNED_IN);
|
|
857
|
+
const traceId = req.headers['x-raytace-trace-id'] || req.headers['x-request-id'] || randomUUID(); const started = new Date().toISOString(); const selectedProvider = routed.provider;
|
|
858
|
+
const spanId = randomUUID();
|
|
859
|
+
const sessionId = req.headers['x-raytace-session-id'];
|
|
860
|
+
const sessionStartedAt = req.headers['x-raytace-session-started-at'];
|
|
861
|
+
const session = typeof sessionId === 'string' && /^(?:[a-f0-9-]{36}|rtp-[a-f0-9]{32})$/.test(sessionId) && typeof sessionStartedAt === 'string' && Number.isFinite(Date.parse(sessionStartedAt))
|
|
862
|
+
? { session_id: sessionId, session_started_at: new Date(sessionStartedAt).toISOString() } : fallbackSession;
|
|
863
|
+
const requestPayload = routed.payload;
|
|
864
|
+
try {
|
|
865
|
+
const response = await fetch(routed.url, { method: req.method, headers: routed.headers, body: ['GET', 'HEAD'].includes(req.method || '') ? undefined : routed.body, duplex: 'half' });
|
|
866
|
+
const responseBody = Buffer.from(await response.arrayBuffer()); let responsePayload = null;
|
|
867
|
+
const contentType = response.headers.get('content-type') || '';
|
|
868
|
+
if (responseBody.length <= maxBodyBytes) {
|
|
869
|
+
if (contentType.includes('application/json')) try { responsePayload = JSON.parse(responseBody); } catch { /* record hash */ }
|
|
870
|
+
else if (contentType.includes('text/event-stream')) responsePayload = parseSseResponse(responseBody);
|
|
871
|
+
}
|
|
872
|
+
const replayHeaders = routed.headers;
|
|
873
|
+
if (requestPayload && responsePayload && req.url.endsWith('/responses') && response.ok) {
|
|
874
|
+
liveExchanges.set(spanId, { payload: requestPayload, response: responsePayload, provider: selectedProvider, route: req.url, upstreamUrl: routed.url, headers: replayHeaders });
|
|
875
|
+
while (liveExchanges.size > 10) liveExchanges.delete(liveExchanges.keys().next().value);
|
|
876
|
+
setTimeout(() => liveExchanges.delete(spanId), 30 * 60 * 1000).unref();
|
|
877
|
+
}
|
|
878
|
+
const completedAt = new Date().toISOString();
|
|
879
|
+
const metrics = requestMetrics({ timestamp: started, completed_at: completedAt, provider: selectedProvider, response: { payload: responsePayload } });
|
|
880
|
+
await record({ ...session, metrics, event_type: 'model.exchange', trace_id: traceId, span_id: spanId, parent_span_id: req.headers['x-raytace-parent-span-id'] || null, timestamp: started, completed_at: completedAt, provider: selectedProvider, route: req.url, method: req.method, request: { headers: safeHeaders(routed.headers), bytes: routed.body.length, sha256: hash(routed.body), payload: requestPayload && redact(requestPayload) }, response: { status: response.status, headers: safeHeaders(Object.fromEntries(response.headers)), bytes: responseBody.length, sha256: hash(responseBody), payload: responsePayload && redact(responsePayload) } });
|
|
881
|
+
// fetch decodes compressed bodies; original encoding/length no longer apply.
|
|
882
|
+
const downstreamHeaders = Object.fromEntries(response.headers);
|
|
883
|
+
delete downstreamHeaders['content-encoding'];
|
|
884
|
+
delete downstreamHeaders['transfer-encoding'];
|
|
885
|
+
downstreamHeaders['content-length'] = String(responseBody.length);
|
|
886
|
+
res.writeHead(response.status, downstreamHeaders); res.end(responseBody);
|
|
887
|
+
} catch (error) { await record({ event_type: 'proxy.error', trace_id: traceId, timestamp: started, provider: selectedProvider, route: req.url, error: String(error), cause: error.cause ? { name: error.cause.name, message: error.cause.message, code: error.cause.code } : null }); res.writeHead(502, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'raytace_proxy_upstream_error', trace_id: traceId })); }
|
|
888
|
+
});
|
|
889
|
+
server.on('error', (error) => {
|
|
890
|
+
if (error.code === 'EADDRINUSE') console.error(`RayTrace proxy could not start: port ${port} is already in use. Stop the existing proxy, then try again.`);
|
|
891
|
+
else console.error(`RayTrace proxy could not start: ${error.message}`);
|
|
892
|
+
process.exitCode = 1;
|
|
893
|
+
});
|
|
894
|
+
try {
|
|
895
|
+
for (const job of db.loadExperiments(200).reverse()) {
|
|
896
|
+
if (job.kind === 'fork') continue; // Playground forks: playground.mjs
|
|
897
|
+
if (['queued', 'running'].includes(job.status)) job.status = 'interrupted';
|
|
898
|
+
jobs.set(job.id, job);
|
|
899
|
+
}
|
|
900
|
+
while (jobs.size > 30) jobs.delete(jobs.keys().next().value);
|
|
901
|
+
} catch (error) { console.error(`Experiment history could not be read: ${error.message}`); }
|
|
902
|
+
server.listen(port, '127.0.0.1', () => {
|
|
903
|
+
const stats = db.stats();
|
|
904
|
+
console.log(`RayTrace proxy listening on http://127.0.0.1:${server.address().port}`);
|
|
905
|
+
playground.recover().catch((error) => console.error(`Playground forks could not be checked: ${error.message}`));
|
|
906
|
+
console.log(`Store: ${dbFile} (journal=${db.journal}, ${stats.sessions} sessions, ${stats.turns} turns, ${stats.exchanges} exchanges, ${stats.processes} sandbox processes)`);
|
|
907
|
+
});
|
|
908
|
+
// gVisor sandbox evidence (worker/sandbox/): discovers the local sandboxes from the
|
|
909
|
+
// Mac-side manager (:8799) and tails each one's process events from the
|
|
910
|
+
// evidence viewer (:8798), recording matched execs as the primary witness
|
|
911
|
+
// for those sessions. Best-effort: with neither service running it logs
|
|
912
|
+
// once and idles. RAYTACE_GVISOR_FORWARDER=0 turns it off entirely.
|
|
913
|
+
const gvisorForwarder = process.env.RAYTACE_GVISOR_FORWARDER === '0' ? null : startGvisorForwarder({
|
|
914
|
+
listProjects: () => sandboxes.list(),
|
|
915
|
+
recordCapture: row => db.recordCaptureEvent(row),
|
|
916
|
+
loadCheckpoint: (container,source) => db.captureCheckpoint(container,source),
|
|
917
|
+
saveProgress: row => db.saveCaptureProgress(row),
|
|
918
|
+
viewerBase: EVIDENCE_VIEWER,
|
|
919
|
+
fetchImpl: fromViewer,
|
|
920
|
+
ingest: (events, { sessionId }) => ingestExecutions(db, events, { sessionId }),
|
|
921
|
+
// Exits, found by the process's own identity (pid + start time), so an
|
|
922
|
+
// exit closes its process even after a proxy restart or for a process the
|
|
923
|
+
// forwarder never tracked.
|
|
924
|
+
finish: (row) => recordExit(row),
|
|
925
|
+
finishByProcess: (row) => recordExit(row),
|
|
926
|
+
// A sandbox whose remaining exits can no longer arrive.
|
|
927
|
+
lose: (row) => db.loseOpenProcesses({ containerId: row.container_id, reason: row.reason, raw: row.raw ?? null, ended: row.ended === true }),
|
|
928
|
+
// Processes that ran underneath a matched call, and ones that matched
|
|
929
|
+
// nothing at all (parent_call_id null): recorded either way.
|
|
930
|
+
descend: ({ exec, parent_call_id, session_id }) => {
|
|
931
|
+
const started = db.recordProcessStart({ containerId: exec.container_id, projectId: session_id ?? null, raw: exec.raw, startedMs: exec.timestamp });
|
|
932
|
+
if (parent_call_id && started?.eventId) db.attribute({ toolCallId: parent_call_id, eventId: started.eventId, method: 'inherited', confidence: 'corroborated' });
|
|
933
|
+
},
|
|
934
|
+
});
|
|
935
|
+
function recordExit(row) {
|
|
936
|
+
return db.recordProcessExit({ containerId: row.container_id, projectId: row.session_id ?? null, raw: row.raw,
|
|
937
|
+
endedMs: row.ended_ms ?? null, exit_code: row.exit_code ?? null, signal: row.signal ?? null });
|
|
938
|
+
}
|
|
939
|
+
// Local sandboxes' Claude Code transcripts (raytrace sandbox create --local).
|
|
940
|
+
startSandboxBridge({ dataDir, port: Number(process.env.RAYTRACE_BRIDGE_PORT || 8799), ingest: ingestFromSandbox });
|
|
941
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { try { gvisorForwarder?.stop(); db.close(); } finally { process.exit(0); } });
|