@raytrace-cli/cli 0.1.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/LICENSE +21 -0
- package/README.md +132 -0
- package/bin/raytrace.mjs +74 -0
- package/dist/dashboard/assets/index-BQ9_JxGq.js +27 -0
- package/dist/dashboard/assets/index-L5cUAvhE.css +1 -0
- package/dist/dashboard/favicon.svg +6 -0
- package/dist/dashboard/index.html +15 -0
- package/package.json +45 -0
- package/proxy/claude-code-adapter.mjs +239 -0
- package/proxy/claude-code-hook.mjs +20 -0
- package/proxy/codex-config.mjs +31 -0
- package/proxy/codex.mjs +13 -0
- package/proxy/evidence-store.mjs +285 -0
- package/proxy/execution-runner.mjs +89 -0
- package/proxy/experiment-engine.mjs +192 -0
- package/proxy/explanations.mjs +36 -0
- package/proxy/init-evidence-db.mjs +72 -0
- package/proxy/prompt-context.mjs +273 -0
- package/proxy/prompt-traces.mjs +34 -0
- package/proxy/providers.mjs +65 -0
- package/proxy/raytace-proxy.mjs +608 -0
- package/proxy/request-metrics.mjs +13 -0
- package/proxy/schema/agent_intent.sql +101 -0
- package/proxy/schema/auxiliary.sql +43 -0
- package/proxy/schema/shared_storage.sql +21 -0
- package/proxy/step-lab.mjs +78 -0
- package/proxy/summaries.mjs +151 -0
- package/proxy/tool-metadata.mjs +75 -0
- package/src/claude-code.mjs +56 -0
- package/src/commands.mjs +173 -0
- package/src/config.mjs +40 -0
- package/src/paths.mjs +26 -0
- package/src/prompt.mjs +42 -0
- package/src/proxy-process.mjs +101 -0
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { requestMetrics } from './request-metrics.mjs';
|
|
3
|
+
/** Local API recorder. Point a compatible client at http://127.0.0.1:8797. */
|
|
4
|
+
import { createServer } from 'node:http';
|
|
5
|
+
import { appendFile, mkdir, readFile } from 'node:fs/promises';
|
|
6
|
+
import { realpathSync } from 'node:fs';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
9
|
+
import { join, dirname, resolve, extname, sep } from 'node:path';
|
|
10
|
+
import { exchangesFromTranscript, parseTranscript } from './claude-code-adapter.mjs';
|
|
11
|
+
import { evidenceFor, replayEligibility, createExperiment, runExperiment, outcome, proposedCommand } from './experiment-engine.mjs';
|
|
12
|
+
import { loadEnvFile } from 'node:process';
|
|
13
|
+
import { providerConfig, routeRequest, selectModel } from './providers.mjs';
|
|
14
|
+
import { latestSessionRows } from './prompt-traces.mjs';
|
|
15
|
+
import { inspectStep, createStepRun, runDecision } from './step-lab.mjs';
|
|
16
|
+
import { executeSequence } from './execution-runner.mjs';
|
|
17
|
+
import { explanationRequest, parseExplanations } from './explanations.mjs';
|
|
18
|
+
import { summaryRequest, parseSummary, resultText } from './summaries.mjs';
|
|
19
|
+
import { omitToolChunkIds, toolResultStatus } from './tool-metadata.mjs';
|
|
20
|
+
import { openEvidenceStore } from './evidence-store.mjs';
|
|
21
|
+
import { promptContext, contextItemText, contextSummaryRequest, parseContextSummary } from './prompt-context.mjs';
|
|
22
|
+
|
|
23
|
+
try { loadEnvFile(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
24
|
+
const routing = providerConfig();
|
|
25
|
+
// Summaries default to the cheapest configured alias so per-step summarizing
|
|
26
|
+
// (many small calls) doesn't rack up cost; override with RAYTACE_SUMMARY_MODEL.
|
|
27
|
+
const summaryModel = process.env.RAYTACE_SUMMARY_MODEL
|
|
28
|
+
? selectModel(routing, process.env.RAYTACE_SUMMARY_MODEL)
|
|
29
|
+
: (routing.models.oss || routing.defaultModel);
|
|
30
|
+
const fallbackSession = { session_id: randomUUID(), session_started_at: new Date().toISOString() };
|
|
31
|
+
|
|
32
|
+
const port = Number(process.env.RAYTACE_PORT || 8797);
|
|
33
|
+
// The CLI sets RAYTACE_DATA_DIR (~/.raytrace); run by hand it keeps ./.raytace.
|
|
34
|
+
const dataDir = process.env.RAYTACE_DATA_DIR || join(process.cwd(), '.raytace');
|
|
35
|
+
const store = process.env.RAYTACE_STORE || join(dataDir, 'events.jsonl');
|
|
36
|
+
const maxBodyBytes = Number(process.env.RAYTACE_MAX_BODY_BYTES || 2_000_000);
|
|
37
|
+
const liveExchanges = new Map(); // Credentials stay in process memory, never in the event log.
|
|
38
|
+
const jobs = new Map();
|
|
39
|
+
const jobControllers = new Map();
|
|
40
|
+
const dbFile = process.env.RAYTACE_DB || join(dirname(store), 'evidence.db');
|
|
41
|
+
const archiveJsonl = process.env.RAYTACE_ARCHIVE_JSONL === '1';
|
|
42
|
+
const db = openEvidenceStore(dbFile);
|
|
43
|
+
const allowedOrigins = new Set((process.env.RAYTACE_UI_ORIGINS || '').split(',').filter(Boolean));
|
|
44
|
+
function trustedOrigin(origin) {
|
|
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
|
+
}
|
|
49
|
+
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
50
|
+
function redact(value) {
|
|
51
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
52
|
+
if (!value || typeof value !== 'object') return value;
|
|
53
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) =>
|
|
54
|
+
/authorization|api[-_]?key|token|secret|password/i.test(key) ? [key, '[REDACTED]'] : [key, redact(item)],
|
|
55
|
+
));
|
|
56
|
+
}
|
|
57
|
+
async function record(event) {
|
|
58
|
+
const row = omitToolChunkIds(event);
|
|
59
|
+
if (row.event_type === 'model.exchange' && row.span_id) db.recordExchange(row);
|
|
60
|
+
else if (row.event_type === 'proxy.error') db.recordProxyError(row);
|
|
61
|
+
// Opt-in raw archive; the database is the source of truth.
|
|
62
|
+
if (archiveJsonl) { await mkdir(dirname(store), { recursive: true }); await appendFile(store, `${JSON.stringify(row)}\n`); }
|
|
63
|
+
}
|
|
64
|
+
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
|
+
async function invokeReplay(entry, payload, signal) {
|
|
96
|
+
const headers = Object.fromEntries(Object.entries(entry.headers).filter(([key]) =>
|
|
97
|
+
['authorization', 'content-type', 'openai-organization', 'openai-project', 'openai-beta', 'user-agent'].includes(key.toLowerCase())));
|
|
98
|
+
const response = await fetch(entry.upstreamUrl, {
|
|
99
|
+
method: 'POST', headers, body: JSON.stringify(payload),
|
|
100
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(120_000)]),
|
|
101
|
+
});
|
|
102
|
+
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.`); }
|
|
103
|
+
const chunks = []; let size = 0;
|
|
104
|
+
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); }
|
|
105
|
+
const body = Buffer.concat(chunks);
|
|
106
|
+
return response.headers.get('content-type')?.includes('text/event-stream') ? parseSseResponse(body) : JSON.parse(body.toString());
|
|
107
|
+
}
|
|
108
|
+
async function persistExperiment(job) { db.saveExperiment(redact(omitToolChunkIds(job))); }
|
|
109
|
+
function splitExchange(row) {
|
|
110
|
+
const request = row.request?.payload || {}; const response = row.response?.payload || {};
|
|
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
|
+
}
|
|
142
|
+
// The trace list takes seconds to build for long sessions and is polled every
|
|
143
|
+
// few seconds, mostly with nothing new: it is rebuilt only when the data
|
|
144
|
+
// behind it changed (db.dataVersion), and one build serves every caller.
|
|
145
|
+
// The body is serialized once per version too, and its version is its ETag,
|
|
146
|
+
// so a poll with nothing new is answered 304 without sending anything.
|
|
147
|
+
const traceCache = new Map(); // url -> { version, body: Promise<string> }
|
|
148
|
+
function cachedTraces(url) {
|
|
149
|
+
const version = db.dataVersion();
|
|
150
|
+
const hit = traceCache.get(url);
|
|
151
|
+
if (hit?.version === version) return hit;
|
|
152
|
+
const body = readTraces(url !== '/raytace/traces', { evidence: url !== '/raytace/traces?scope=history' })
|
|
153
|
+
.then((traces) => JSON.stringify({ traces }));
|
|
154
|
+
const entry = { version, etag: `"${version}"`, body };
|
|
155
|
+
traceCache.set(url, entry);
|
|
156
|
+
body.catch(() => { if (traceCache.get(url) === entry) traceCache.delete(url); });
|
|
157
|
+
return entry;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** `evidence: false` skips building each request's context items, the
|
|
161
|
+
* costliest part (every request resends the conversation so far), for
|
|
162
|
+
* 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
|
+
|
|
253
|
+
|
|
254
|
+
// Context window sizes, from OpenRouter's public model list (no key needed),
|
|
255
|
+
// fetched once. Null when the model is not listed or the list is unreachable.
|
|
256
|
+
let contextWindows = null;
|
|
257
|
+
async function contextWindow(model) {
|
|
258
|
+
if (!model) return null;
|
|
259
|
+
if (!contextWindows) {
|
|
260
|
+
contextWindows = fetch('https://openrouter.ai/api/v1/models', { signal: AbortSignal.timeout(5000) })
|
|
261
|
+
.then((response) => (response.ok ? response.json() : { data: [] }))
|
|
262
|
+
.then((body) => new Map((body.data ?? []).map((item) => [item.id, item.context_length ?? null])))
|
|
263
|
+
.catch(() => { contextWindows = null; return new Map(); });
|
|
264
|
+
}
|
|
265
|
+
const windows = await contextWindows;
|
|
266
|
+
return windows.get(model) ?? windows.get(`openai/${model}`) ?? windows.get(`anthropic/${model}`) ?? null;
|
|
267
|
+
}
|
|
268
|
+
/** The context analysis for one prompt, from the last request of its turn. */
|
|
269
|
+
async function promptContextFor(traceId) {
|
|
270
|
+
const trace = (await readTraces(true, { evidence: false })).find((item) => item.id === traceId);
|
|
271
|
+
const last = trace?.requests?.at(-1);
|
|
272
|
+
const entry = last ? await savedOrLive(last.id) : null;
|
|
273
|
+
if (!entry) return null;
|
|
274
|
+
return { trace, context: promptContext(entry, trace.title, trace.answer ?? '') };
|
|
275
|
+
}
|
|
276
|
+
async function savedOrLive(exchangeId) {
|
|
277
|
+
return liveExchanges.get(exchangeId) || db.findExchange(exchangeId);
|
|
278
|
+
}
|
|
279
|
+
/** The summary request for one step as it stands now, or null. Its key
|
|
280
|
+
* changes with the summary version and with the step's own results, which
|
|
281
|
+
* are recorded once a later request carries them back. */
|
|
282
|
+
async function currentSummaryRequest(exchangeId) {
|
|
283
|
+
const entry = await savedOrLive(exchangeId);
|
|
284
|
+
if (!entry) return null;
|
|
285
|
+
const ownCalls = (entry.response?.output ?? []).filter((item) => item?.call_id);
|
|
286
|
+
const contexts = db.toolCallContexts(ownCalls.map((item) => item.call_id));
|
|
287
|
+
const ownResults = ownCalls.map((item) => ({ from: item.name, output: resultText(contexts.get(item.call_id)?.result) }));
|
|
288
|
+
return summaryRequest(entry, exchangeId, summaryModel, ownResults);
|
|
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
|
+
// ---------------------------------------------------------------- Claude Code
|
|
295
|
+
// Proxy-free capture: Claude Code's hooks ring, and its session transcript is
|
|
296
|
+
// rebuilt into the same exchange rows the proxy records (claude-code-adapter).
|
|
297
|
+
const claudeProjects = resolve(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');
|
|
298
|
+
const CLAUDE_CODE_FINAL_EVENTS = new Set(['Stop', 'SubagentStop', 'SessionEnd']);
|
|
299
|
+
function claudeCodeTranscriptPath(value) {
|
|
300
|
+
if (typeof value !== 'string' || !value.endsWith('.jsonl')) return null;
|
|
301
|
+
try {
|
|
302
|
+
const real = realpathSync(value);
|
|
303
|
+
return real.startsWith(`${realpathSync(claudeProjects)}/`) ? real : null;
|
|
304
|
+
} catch { return null; }
|
|
305
|
+
}
|
|
306
|
+
// One job at a time per transcript (a write, then a read); later rings queue.
|
|
307
|
+
const claudeCodeQueues = new Map();
|
|
308
|
+
function serially(path, job) {
|
|
309
|
+
const next = (claudeCodeQueues.get(path) ?? Promise.resolve()).then(job);
|
|
310
|
+
const settled = next.catch(() => {}).finally(() => { if (claudeCodeQueues.get(path) === settled) claudeCodeQueues.delete(path); });
|
|
311
|
+
claudeCodeQueues.set(path, settled);
|
|
312
|
+
return next;
|
|
313
|
+
}
|
|
314
|
+
function ingestClaudeCode(path, { final }) {
|
|
315
|
+
serially(path, async () => {
|
|
316
|
+
const rows = exchangesFromTranscript(parseTranscript(await readFile(path, 'utf8')), { final });
|
|
317
|
+
for (const row of rows) {
|
|
318
|
+
await record({ ...row, request: { ...row.request, payload: redact(row.request.payload) }, response: { ...row.response, payload: redact(row.response.payload) } });
|
|
319
|
+
}
|
|
320
|
+
}).catch((error) => console.error(`Claude Code transcript ${path} could not be read: ${error.message}`));
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// The prebuilt dashboard (RAYTACE_DASHBOARD_DIR), served from / so it and the
|
|
324
|
+
// API share one origin. Model traffic is under /v1 and the API under /raytace,
|
|
325
|
+
// so any other GET from a browser (no credentials) is a dashboard file; unknown
|
|
326
|
+
// paths get index.html.
|
|
327
|
+
const dashboardDir = process.env.RAYTACE_DASHBOARD_DIR ? resolve(process.env.RAYTACE_DASHBOARD_DIR) : null;
|
|
328
|
+
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' };
|
|
329
|
+
async function serveDashboard(req, res) {
|
|
330
|
+
const path = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
|
|
331
|
+
let file = resolve(dashboardDir, `.${path}`);
|
|
332
|
+
if (file !== dashboardDir && !file.startsWith(dashboardDir + sep)) { res.writeHead(404); return res.end(); }
|
|
333
|
+
let body;
|
|
334
|
+
try { body = await readFile(file); }
|
|
335
|
+
catch { file = join(dashboardDir, 'index.html'); body = await readFile(file); }
|
|
336
|
+
const immutable = path.startsWith('/assets/');
|
|
337
|
+
res.writeHead(200, { 'content-type': CONTENT_TYPES[extname(file)] || 'application/octet-stream', 'cache-control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache' });
|
|
338
|
+
res.end(body);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const server = createServer(async (req, res) => {
|
|
342
|
+
const fromAgent = req.headers.authorization || req.headers['x-api-key'] || req.headers['anthropic-version'];
|
|
343
|
+
if (dashboardDir && req.method === 'GET' && !fromAgent && !req.url?.startsWith('/raytace/') && !req.url?.startsWith('/v1/')) {
|
|
344
|
+
try { return await serveDashboard(req, res); }
|
|
345
|
+
catch { res.writeHead(404); return res.end('Dashboard not built.'); }
|
|
346
|
+
}
|
|
347
|
+
const localApi = req.url?.startsWith('/raytace/');
|
|
348
|
+
// Paid replay endpoints require a preflighted custom header and trusted origin.
|
|
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' };
|
|
353
|
+
const json = (status, value) => { res.writeHead(status, { 'content-type': 'application/json', ...corsHeaders, 'cache-control': 'no-store' }); res.end(JSON.stringify(redact(omitToolChunkIds(value)))); };
|
|
354
|
+
if (req.method === 'OPTIONS') { res.writeHead(204, corsHeaders); return res.end(); }
|
|
355
|
+
// The dashboard polls the history every few seconds: its context items
|
|
356
|
+
// (`evidence`) grow with the square of a session's length, so the history
|
|
357
|
+
// carries them only when asked for (&evidence=1, Compare runs). The recent
|
|
358
|
+
// list keeps them.
|
|
359
|
+
if (req.method === 'GET' && ['/raytace/traces', '/raytace/traces?scope=history', '/raytace/traces?scope=history&evidence=1'].includes(req.url)) {
|
|
360
|
+
try {
|
|
361
|
+
const cached = cachedTraces(req.url);
|
|
362
|
+
const headers = { ...corsHeaders, etag: cached.etag, 'cache-control': 'no-cache', 'access-control-expose-headers': 'etag' };
|
|
363
|
+
if (req.headers['if-none-match'] === cached.etag) { res.writeHead(304, headers); return res.end(); }
|
|
364
|
+
const body = await cached.body;
|
|
365
|
+
res.writeHead(200, { 'content-type': 'application/json', ...headers }); return res.end(body);
|
|
366
|
+
}
|
|
367
|
+
catch (error) { res.writeHead(500, { 'content-type': 'application/json', ...corsHeaders }); return res.end(JSON.stringify({ error: String(error) })); }
|
|
368
|
+
}
|
|
369
|
+
// Who is signed in and which paid features they have. Nobody yet: sign-in
|
|
370
|
+
// comes with the RayTrace cloud; the dashboard already reads this shape.
|
|
371
|
+
if (req.method === 'GET' && req.url === '/raytace/account') return json(200, { signed_in: false, plan: 'free', features: [] });
|
|
372
|
+
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
|
+
const stepRoute = req.url?.match(/^\/raytace\/steps\/([a-f0-9-]+)\/(\d+)$/);
|
|
374
|
+
if (req.method === 'GET' && stepRoute) {
|
|
375
|
+
const live = liveExchanges.get(stepRoute[1]);
|
|
376
|
+
try {
|
|
377
|
+
const entry = await savedOrLive(stepRoute[1]);
|
|
378
|
+
if (!entry) return json(404, { error: 'This step was not found in the saved captures.' });
|
|
379
|
+
if (!entry.payload || !entry.response) return json(409, { error: 'This capture contains only metadata; its full request or response was not saved.' });
|
|
380
|
+
const step = inspectStep(omitToolChunkIds(entry), stepRoute[1], Number(stepRoute[2]));
|
|
381
|
+
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.';
|
|
382
|
+
const request = explanationRequest(step, routing.defaultModel);
|
|
383
|
+
const explanation = db.getExplanation(request.key);
|
|
384
|
+
return json(200, { ...step, hypotheses: explanation?.hypotheses || [], explanation_generated: !!explanation, explanation_model: routing.defaultModel });
|
|
385
|
+
}
|
|
386
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
387
|
+
}
|
|
388
|
+
const contextRoute = req.url?.match(/^\/raytace\/prompt-context\/([A-Za-z0-9_-]{1,80})$/);
|
|
389
|
+
if (req.method === 'GET' && contextRoute) {
|
|
390
|
+
try {
|
|
391
|
+
const found = await promptContextFor(contextRoute[1]);
|
|
392
|
+
if (!found) return json(404, { error: 'Prompt not found in the captured history.' });
|
|
393
|
+
const request = contextSummaryRequest(found.context, summaryModel);
|
|
394
|
+
const model = found.trace.requests?.at(-1)?.model ?? found.trace.model;
|
|
395
|
+
return json(200, { ...found.context, model, context_window: await contextWindow(model),
|
|
396
|
+
summary: request ? db.getSummary(request.key) : null, summary_needed: !!request, summary_model: summaryModel });
|
|
397
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
398
|
+
}
|
|
399
|
+
// One context item's full text, as the model received it, for opening in
|
|
400
|
+
// its own tab: /raytace/prompt-context/<trace>/item/<input index | instructions | tools>
|
|
401
|
+
const itemRoute = req.url?.match(/^\/raytace\/prompt-context\/([A-Za-z0-9_-]{1,80})\/item\/(\d{1,6}|instructions|tools)$/);
|
|
402
|
+
if (req.method === 'GET' && itemRoute) {
|
|
403
|
+
const trace = (await readTraces(true, { evidence: false })).find((item) => item.id === itemRoute[1]);
|
|
404
|
+
const last = trace?.requests?.at(-1);
|
|
405
|
+
const entry = last ? await savedOrLive(last.id) : null;
|
|
406
|
+
const text = entry ? contextItemText(entry, itemRoute[2]) : null;
|
|
407
|
+
res.writeHead(text == null ? 404 : 200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
408
|
+
return res.end(text ?? 'Not found in the captured context.');
|
|
409
|
+
}
|
|
410
|
+
const summaryRoute = req.url?.match(/^\/raytace\/summaries\/([a-f0-9-]+)$/);
|
|
411
|
+
// Only a summary of the step as it stands now: one written by an older
|
|
412
|
+
// version, or before the step's own result was known, is not served.
|
|
413
|
+
if (req.method === 'GET' && summaryRoute) {
|
|
414
|
+
const request = await currentSummaryRequest(summaryRoute[1]);
|
|
415
|
+
return json(200, { summary: request ? db.getSummary(request.key) : null, model: summaryModel });
|
|
416
|
+
}
|
|
417
|
+
if (req.method === 'GET' && req.url === '/raytace/experiments') return json(200, { experiments: [...jobs.values()].slice(-30).reverse() });
|
|
418
|
+
const jobRoute = req.url?.match(/^\/raytace\/experiments\/([a-f0-9-]+)(\/cancel)?$/);
|
|
419
|
+
if (jobRoute) {
|
|
420
|
+
const job = jobs.get(jobRoute[1]); if (!job) return json(404, { error: 'Experiment not found.' });
|
|
421
|
+
if (req.method === 'GET' && !jobRoute[2]) return json(200, job);
|
|
422
|
+
if (req.method === 'POST' && jobRoute[2] && req.headers['x-raytace-experiment'] === '1') { jobControllers.get(job.id)?.abort(); return json(200, job); }
|
|
423
|
+
return json(405, { error: 'Unsupported experiment operation.' });
|
|
424
|
+
}
|
|
425
|
+
// Claude Code hook doorbell (proxy/claude-code-hook.mjs): "this session's
|
|
426
|
+
// transcript has new lines". Answered at once; the transcript is read
|
|
427
|
+
// 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.
|
|
429
|
+
if (req.method === 'POST' && req.url === '/raytace/ingest/claude-code') {
|
|
430
|
+
if (req.headers['x-raytace-hook'] !== '1' || !req.headers['content-type']?.includes('application/json')) return json(403, { error: 'Claude Code hook requests only.' });
|
|
431
|
+
const chunks = []; let size = 0;
|
|
432
|
+
for await (const part of req) { size += part.length; if (size > 64_000) return json(413, { error: 'Request too large.' }); chunks.push(part); }
|
|
433
|
+
let note;
|
|
434
|
+
try { note = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return json(400, { error: 'Invalid JSON.' }); }
|
|
435
|
+
const path = claudeCodeTranscriptPath(note?.transcript_path);
|
|
436
|
+
if (!path) return json(400, { error: 'transcript_path must be a Claude Code transcript under ~/.claude/projects.' });
|
|
437
|
+
json(202, { accepted: true });
|
|
438
|
+
ingestClaudeCode(path, { final: CLAUDE_CODE_FINAL_EVENTS.has(note.hook_event_name) });
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
if (localApi && (req.method !== 'POST' || !['/raytace/experiments', '/raytace/step-runs', '/raytace/explanations', '/raytace/summaries', '/raytace/prompt-context/summary'].includes(req.url))) return json(404, { error: 'Unknown local endpoint.' });
|
|
442
|
+
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
|
+
const parts = []; let bytes = 0;
|
|
444
|
+
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
|
+
const requestBody = Buffer.concat(parts);
|
|
446
|
+
if (req.method === 'POST' && req.url === '/raytace/explanations') {
|
|
447
|
+
try {
|
|
448
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Enable OpenRouter to generate explanations.' });
|
|
449
|
+
const config = JSON.parse(requestBody);
|
|
450
|
+
const entry = await savedOrLive(config.exchange_id);
|
|
451
|
+
if (!entry) return json(404, { error: 'Saved step not found.' });
|
|
452
|
+
const step = inspectStep(omitToolChunkIds(entry), config.exchange_id, config.output_index);
|
|
453
|
+
const request = explanationRequest(step, routing.defaultModel);
|
|
454
|
+
const cached = db.getExplanation(request.key);
|
|
455
|
+
if (cached) return json(200, cached);
|
|
456
|
+
if (!pendingExplanations.has(request.key)) {
|
|
457
|
+
if (pendingExplanations.size) return json(409, { error: 'Another explanation is being generated. Try again shortly.' });
|
|
458
|
+
const task = (async () => {
|
|
459
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
460
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
461
|
+
const result = { ...parseExplanations(response, request.sources), model: routing.defaultModel };
|
|
462
|
+
db.putExplanation(request.key, result);
|
|
463
|
+
return result;
|
|
464
|
+
})();
|
|
465
|
+
pendingExplanations.set(request.key, task);
|
|
466
|
+
}
|
|
467
|
+
try { return json(200, await pendingExplanations.get(request.key)); } finally { pendingExplanations.delete(request.key); }
|
|
468
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
469
|
+
}
|
|
470
|
+
if (req.method === 'POST' && req.url === '/raytace/prompt-context/summary') {
|
|
471
|
+
try {
|
|
472
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Enable OpenRouter to generate summaries.' });
|
|
473
|
+
const found = await promptContextFor(String(JSON.parse(requestBody).trace_id ?? ''));
|
|
474
|
+
if (!found) return json(404, { error: 'Prompt not found in the captured history.' });
|
|
475
|
+
const request = contextSummaryRequest(found.context, summaryModel);
|
|
476
|
+
if (!request) return json(200, { prompts: [], answers: '' });
|
|
477
|
+
const cached = db.getSummary(request.key);
|
|
478
|
+
if (cached) return json(200, cached);
|
|
479
|
+
if (!pendingSummaries.has(request.key)) {
|
|
480
|
+
const task = (async () => {
|
|
481
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
482
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
483
|
+
const result = { ...parseContextSummary(response), model: summaryModel };
|
|
484
|
+
db.putSummary(request.key, null, result);
|
|
485
|
+
return result;
|
|
486
|
+
})();
|
|
487
|
+
pendingSummaries.set(request.key, task);
|
|
488
|
+
}
|
|
489
|
+
try { return json(200, await pendingSummaries.get(request.key)); } finally { pendingSummaries.delete(request.key); }
|
|
490
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
491
|
+
}
|
|
492
|
+
if (req.method === 'POST' && req.url === '/raytace/summaries') {
|
|
493
|
+
try {
|
|
494
|
+
if (routing.mode !== 'openrouter') return json(400, { error: 'Enable OpenRouter to generate summaries.' });
|
|
495
|
+
const config = JSON.parse(requestBody);
|
|
496
|
+
const request = await currentSummaryRequest(config.exchange_id);
|
|
497
|
+
if (!request) return json(404, { error: 'Saved step not found.' });
|
|
498
|
+
const cached = db.getSummary(request.key);
|
|
499
|
+
if (cached) return json(200, cached);
|
|
500
|
+
if (!pendingSummaries.has(request.key)) {
|
|
501
|
+
if (pendingSummaries.size >= MAX_CONCURRENT_SUMMARIES) return json(409, { error: 'Too many summaries in flight. Try again shortly.' });
|
|
502
|
+
const task = (async () => {
|
|
503
|
+
const routed = routeRequest(routing, { method: 'POST', url: '/v1/responses', headers: {} }, Buffer.from(JSON.stringify(request.payload)));
|
|
504
|
+
const response = await invokeReplay({ headers: routed.headers, upstreamUrl: routed.url }, request.payload, new AbortController().signal);
|
|
505
|
+
const result = { ...parseSummary(response), model: summaryModel };
|
|
506
|
+
db.putSummary(request.key, config.exchange_id, result);
|
|
507
|
+
return result;
|
|
508
|
+
})();
|
|
509
|
+
pendingSummaries.set(request.key, task);
|
|
510
|
+
}
|
|
511
|
+
try { return json(200, await pendingSummaries.get(request.key)); } finally { pendingSummaries.delete(request.key); }
|
|
512
|
+
} catch (error) { console.error('Summary generation failed:', error); return json(400, { error: error.message }); }
|
|
513
|
+
}
|
|
514
|
+
if (req.method === 'POST' && req.url === '/raytace/step-runs') {
|
|
515
|
+
try {
|
|
516
|
+
if (jobControllers.size) return json(409, { error: 'Wait for the active run or cancel it first.' });
|
|
517
|
+
const config = JSON.parse(requestBody); const entry = liveExchanges.get(config.exchange_id);
|
|
518
|
+
if (!entry) return json(409, { error: 'Snapshot expired. Capture a fresh request.' });
|
|
519
|
+
const model = routing.mode === 'openrouter' ? selectModel(routing, config.model) : entry.payload.model;
|
|
520
|
+
if (config.mode === 'execute' && routing.mode !== 'openrouter') return json(400, { error: 'Full execution requires OpenRouter routing.' });
|
|
521
|
+
const { job, baseline, variant } = createStepRun(entry, config, model);
|
|
522
|
+
const controller = new AbortController();
|
|
523
|
+
jobControllers.set(job.id, controller);
|
|
524
|
+
try { await persistExperiment(job); } catch (error) { jobControllers.delete(job.id); throw error; }
|
|
525
|
+
jobs.set(job.id, job); json(202, job);
|
|
526
|
+
const task = job.mode === 'execute'
|
|
527
|
+
? executeSequence(job, variant, routing, process.cwd(), join(dirname(store), 'runs'), controller.signal)
|
|
528
|
+
: runDecision(job, baseline, variant, (payload, signal) => invokeReplay(entry, payload, signal), controller.signal);
|
|
529
|
+
void task.catch((error) => { job.status = controller.signal.aborted ? 'cancelled' : 'failed'; job.error = error.message; })
|
|
530
|
+
.then(() => { job.completed_at = new Date().toISOString(); return persistExperiment(job); })
|
|
531
|
+
.catch(() => { job.persistence_error = 'Could not save this result.'; })
|
|
532
|
+
.finally(() => jobControllers.delete(job.id));
|
|
533
|
+
return;
|
|
534
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
535
|
+
}
|
|
536
|
+
if (req.method === 'POST' && req.url === '/raytace/experiments') {
|
|
537
|
+
try {
|
|
538
|
+
if (jobControllers.size) return json(409, { error: 'Another trial batch is running. Wait or cancel it first.' });
|
|
539
|
+
const config = JSON.parse(requestBody); const entry = liveExchanges.get(config.exchange_id);
|
|
540
|
+
if (!entry) return json(409, { error: 'Snapshot expired. Capture a new request through this proxy.' });
|
|
541
|
+
const job = createExperiment(entry, config); const controller = new AbortController();
|
|
542
|
+
// Persist the declared target and hashes before sending any paid requests.
|
|
543
|
+
jobControllers.set(job.id, controller);
|
|
544
|
+
try { await persistExperiment(job); } catch (error) { jobControllers.delete(job.id); throw error; }
|
|
545
|
+
jobs.set(job.id, job);
|
|
546
|
+
while (jobs.size > 30) jobs.delete(jobs.keys().next().value);
|
|
547
|
+
json(202, job);
|
|
548
|
+
void runExperiment(job, entry, { invoke: (payload, signal) => invokeReplay(entry, payload, signal), signal: controller.signal })
|
|
549
|
+
.catch(() => { job.status = 'failed'; })
|
|
550
|
+
.then(() => persistExperiment(job))
|
|
551
|
+
.catch(() => { job.persistence_error = 'The result could not be saved to disk.'; })
|
|
552
|
+
.finally(() => jobControllers.delete(job.id));
|
|
553
|
+
return;
|
|
554
|
+
} catch (error) { return json(400, { error: error.message }); }
|
|
555
|
+
}
|
|
556
|
+
let routed;
|
|
557
|
+
try { routed = routeRequest(routing, req, requestBody); }
|
|
558
|
+
catch (error) { return json(400, { error: error.message }); }
|
|
559
|
+
const traceId = req.headers['x-raytace-trace-id'] || req.headers['x-request-id'] || randomUUID(); const started = new Date().toISOString(); const selectedProvider = routed.provider;
|
|
560
|
+
const spanId = randomUUID();
|
|
561
|
+
const sessionId = req.headers['x-raytace-session-id'];
|
|
562
|
+
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))
|
|
564
|
+
? { session_id: sessionId, session_started_at: new Date(sessionStartedAt).toISOString() } : fallbackSession;
|
|
565
|
+
const requestPayload = routed.payload;
|
|
566
|
+
try {
|
|
567
|
+
const response = await fetch(routed.url, { method: req.method, headers: routed.headers, body: ['GET', 'HEAD'].includes(req.method || '') ? undefined : routed.body, duplex: 'half' });
|
|
568
|
+
const responseBody = Buffer.from(await response.arrayBuffer()); let responsePayload = null;
|
|
569
|
+
const contentType = response.headers.get('content-type') || '';
|
|
570
|
+
if (responseBody.length <= maxBodyBytes) {
|
|
571
|
+
if (contentType.includes('application/json')) try { responsePayload = JSON.parse(responseBody); } catch { /* record hash */ }
|
|
572
|
+
else if (contentType.includes('text/event-stream')) responsePayload = parseSseResponse(responseBody);
|
|
573
|
+
}
|
|
574
|
+
const replayHeaders = routed.headers;
|
|
575
|
+
if (requestPayload && responsePayload && req.url.endsWith('/responses') && response.ok) {
|
|
576
|
+
liveExchanges.set(spanId, { payload: requestPayload, response: responsePayload, provider: selectedProvider, route: req.url, upstreamUrl: routed.url, headers: replayHeaders });
|
|
577
|
+
while (liveExchanges.size > 10) liveExchanges.delete(liveExchanges.keys().next().value);
|
|
578
|
+
setTimeout(() => liveExchanges.delete(spanId), 30 * 60 * 1000).unref();
|
|
579
|
+
}
|
|
580
|
+
const completedAt = new Date().toISOString();
|
|
581
|
+
const metrics = requestMetrics({ timestamp: started, completed_at: completedAt, provider: selectedProvider, response: { payload: responsePayload } });
|
|
582
|
+
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) } });
|
|
583
|
+
// fetch decodes compressed bodies; original encoding/length no longer apply.
|
|
584
|
+
const downstreamHeaders = Object.fromEntries(response.headers);
|
|
585
|
+
delete downstreamHeaders['content-encoding'];
|
|
586
|
+
delete downstreamHeaders['transfer-encoding'];
|
|
587
|
+
downstreamHeaders['content-length'] = String(responseBody.length);
|
|
588
|
+
res.writeHead(response.status, downstreamHeaders); res.end(responseBody);
|
|
589
|
+
} 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 })); }
|
|
590
|
+
});
|
|
591
|
+
server.on('error', (error) => {
|
|
592
|
+
if (error.code === 'EADDRINUSE') console.error(`RayTrace proxy could not start: port ${port} is already in use. Stop the existing proxy, then try again.`);
|
|
593
|
+
else console.error(`RayTrace proxy could not start: ${error.message}`);
|
|
594
|
+
process.exitCode = 1;
|
|
595
|
+
});
|
|
596
|
+
try {
|
|
597
|
+
for (const job of db.loadExperiments(200).reverse()) {
|
|
598
|
+
if (['queued', 'running'].includes(job.status)) job.status = 'interrupted';
|
|
599
|
+
jobs.set(job.id, job);
|
|
600
|
+
}
|
|
601
|
+
while (jobs.size > 30) jobs.delete(jobs.keys().next().value);
|
|
602
|
+
} catch (error) { console.error(`Experiment history could not be read: ${error.message}`); }
|
|
603
|
+
server.listen(port, '127.0.0.1', () => {
|
|
604
|
+
const stats = db.stats();
|
|
605
|
+
console.log(`RayTrace proxy listening on http://127.0.0.1:${server.address().port}`);
|
|
606
|
+
console.log(`Store: ${dbFile} (journal=${db.journal}, ${stats.sessions} sessions, ${stats.turns} turns, ${stats.exchanges} exchanges)`);
|
|
607
|
+
});
|
|
608
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { try { db.close(); } finally { process.exit(0); } });
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const numeric = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
2
|
+
export function requestMetrics(row) {
|
|
3
|
+
const payload = row.response?.payload;
|
|
4
|
+
const frames = payload?.events || [];
|
|
5
|
+
const usage = payload?.usage || frames.findLast(e => e.usage || e.response?.usage)?.usage || frames.findLast(e => e.response?.usage)?.response?.usage || {};
|
|
6
|
+
const elapsed = row.completed_at ? Date.parse(row.completed_at) - Date.parse(row.timestamp) : NaN;
|
|
7
|
+
return {
|
|
8
|
+
input: numeric(usage.input_tokens ?? usage.prompt_tokens),
|
|
9
|
+
output: numeric(usage.output_tokens ?? usage.completion_tokens),
|
|
10
|
+
cost: row.provider === 'openrouter' ? numeric(usage.cost) : null,
|
|
11
|
+
durationMs: numeric(elapsed),
|
|
12
|
+
};
|
|
13
|
+
}
|