@raytrace-cli/cli 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +155 -123
- package/bin/raytrace.mjs +110 -22
- package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
- package/dist/dashboard/assets/index-Dc3LTk8b.js +38 -0
- package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
- package/dist/dashboard/index.html +2 -2
- package/package.json +4 -1
- package/proxy/agent-intent-schema.test.mjs +142 -0
- package/proxy/call-assessment.mjs +385 -0
- package/proxy/call-assessment.test.mjs +167 -0
- package/proxy/call-category.mjs +461 -0
- package/proxy/capture.mjs +38 -0
- package/proxy/capture.test.mjs +49 -0
- package/proxy/claude-code-adapter.mjs +65 -3
- package/proxy/claude-code-hook.mjs +3 -1
- package/proxy/codex-config.mjs +5 -0
- package/proxy/codex.mjs +3 -2
- package/proxy/evidence-schema.test.mjs +233 -0
- package/proxy/evidence-store.mjs +704 -33
- package/proxy/evidence-store.test.mjs +304 -0
- package/proxy/exec-narrative.mjs +625 -0
- package/proxy/exec-narrative.test.mjs +262 -0
- package/proxy/execution-correlation.mjs +185 -0
- package/proxy/execution-correlation.test.mjs +146 -0
- package/proxy/execution-runner.test.mjs +38 -0
- package/proxy/experiment-engine.mjs +7 -4
- package/proxy/experiment-engine.test.mjs +93 -0
- package/proxy/explanations.test.mjs +20 -0
- package/proxy/failure-signature.mjs +56 -0
- package/proxy/gvisor-forwarder.mjs +454 -0
- package/proxy/gvisor-forwarder.test.mjs +368 -0
- package/proxy/init-evidence-db.mjs +166 -12
- package/proxy/local-sandboxes.mjs +94 -0
- package/proxy/local-token.mjs +30 -0
- package/proxy/playground-recovery.test.mjs +130 -0
- package/proxy/playground.mjs +439 -0
- package/proxy/prompt-context.mjs +12 -7
- package/proxy/prompt-traces.mjs +6 -0
- package/proxy/prompt-traces.test.mjs +32 -0
- package/proxy/providers.test.mjs +76 -0
- package/proxy/proxy.integration.test.mjs +135 -0
- package/proxy/raytace-proxy.mjs +512 -188
- package/proxy/request-metrics.test.mjs +19 -0
- package/proxy/request-policy.mjs +45 -0
- package/proxy/request-policy.test.mjs +47 -0
- package/proxy/run-recap.mjs +139 -0
- package/proxy/runtime-attribution.mjs +110 -0
- package/proxy/sandbox-bridge.mjs +49 -0
- package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
- package/proxy/schema/auxiliary.sql +48 -1
- package/proxy/schema/classification.sql +89 -0
- package/proxy/schema/file_context.sql +53 -0
- package/proxy/schema/runtime_evidence.sql +201 -0
- package/proxy/schema/search.sql +66 -0
- package/proxy/search.mjs +418 -0
- package/proxy/search.test.mjs +161 -0
- package/proxy/smoke.test.mjs +93 -0
- package/proxy/step-attribution.mjs +380 -0
- package/proxy/step-lab.test.mjs +38 -0
- package/proxy/summaries.test.mjs +69 -0
- package/proxy/tool-metadata.mjs +36 -0
- package/proxy/tool-metadata.test.mjs +38 -0
- package/proxy/trace-view.mjs +308 -0
- package/proxy/trace-view.test.mjs +72 -0
- package/proxy/typesafe.mjs +63 -0
- package/proxy/typesafe.test.mjs +39 -0
- package/src/claude-code.mjs +38 -1
- package/src/commands.mjs +133 -20
- package/src/config.mjs +16 -7
- package/src/export.mjs +200 -0
- package/src/lima.mjs +176 -0
- package/src/local-sandbox.mjs +339 -0
- package/src/paths.mjs +8 -8
- package/src/proxy-process.mjs +45 -3
- package/src/sandbox.mjs +37 -9
- package/src/upload.mjs +198 -0
- package/worker/sandbox/Dockerfile +8 -0
- package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
- package/worker/sandbox/claude-hook.mjs +364 -0
- package/worker/sandbox/collector.py +357 -0
- package/worker/sandbox/dns_forwarder.py +255 -0
- package/worker/sandbox/engine.py +940 -0
- package/worker/sandbox/file_scan.py +491 -0
- package/worker/sandbox/lima.yaml +29 -0
- package/worker/sandbox/network.py +90 -0
- package/worker/sandbox/projects.py +679 -0
- package/worker/sandbox/setup.py +159 -0
- package/worker/sandbox/syscall_catalog.sql +985 -0
- package/worker/sandbox/transcript-delivery.test.mjs +153 -0
- package/worker/sandbox/viewer.py +151 -0
- package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
- package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { omitToolChunkIds, toolResultStatus } from './tool-metadata.mjs';
|
|
4
|
+
const output = 'Chunk ID: 259a39\nWall time: 0.001 seconds\nProcess exited with code 0\nOutput:\nChunk ID: actual-file-content';
|
|
5
|
+
test('summarize execution status without exposing output or misreading file contents', () => {
|
|
6
|
+
assert.equal(toolResultStatus({ output }), 'Successful');
|
|
7
|
+
assert.equal(toolResultStatus({ output: output.replace('code 0', 'code 1') }), 'Failed');
|
|
8
|
+
assert.equal(toolResultStatus({ output: 'Wall time: 0.1 seconds\nProcess running with session ID 123\nOutput:\n' }), 'Still running');
|
|
9
|
+
assert.equal(toolResultStatus({ output: 'a file containing\nProcess exited with code 1' }), 'Result received');
|
|
10
|
+
assert.equal(toolResultStatus({ omitted: true }), 'Output omitted');
|
|
11
|
+
assert.equal(toolResultStatus({ output: '' }), 'No output');
|
|
12
|
+
assert.equal(toolResultStatus({ is_error: true, output: 'details' }), 'Failed');
|
|
13
|
+
});
|
|
14
|
+
test('remove runner chunk headers while preserving correlation IDs, content, and original payload', () => {
|
|
15
|
+
const original = { input: [{ type: 'function_call_output', call_id: 'call_123', chunk_id: '259a39', output }, { role: 'user', content: output }] };
|
|
16
|
+
const cleaned = omitToolChunkIds(original);
|
|
17
|
+
assert.equal(cleaned.input[0].call_id, 'call_123'); assert.equal(cleaned.input[0].chunk_id, undefined);
|
|
18
|
+
assert.ok(cleaned.input[0].output.startsWith('Wall time:')); assert.ok(cleaned.input[0].output.endsWith('Chunk ID: actual-file-content'));
|
|
19
|
+
assert.equal(cleaned.input[1].content, output); assert.equal(original.input[0].output, output);
|
|
20
|
+
});
|
|
21
|
+
test('strip evidence previews and structured text tool results', () => {
|
|
22
|
+
const evidence = omitToolChunkIds({ kind: 'tool result', content: output, preview: output });
|
|
23
|
+
assert.ok(evidence.content.startsWith('Wall time:')); assert.ok(evidence.preview.startsWith('Wall time:'));
|
|
24
|
+
const item = omitToolChunkIds({ type: 'tool_result', content: [{ type: 'text', text: output }] });
|
|
25
|
+
assert.ok(item.content[0].text.startsWith('Wall time:'));
|
|
26
|
+
});
|
|
27
|
+
test('toolResultFacts reads exit code and wall time from the runner header only', async () => {
|
|
28
|
+
const { toolResultFacts } = await import('./tool-metadata.mjs');
|
|
29
|
+
assert.deepEqual(toolResultFacts({ output }), { exitCode: 0, wallMs: 1 });
|
|
30
|
+
assert.deepEqual(toolResultFacts({ output: output.replace('code 0', 'code 3').replace('0.001', '1.5') }), { exitCode: 3, wallMs: 1500 });
|
|
31
|
+
// Still running: the wall time is how long Codex waited, not a run time.
|
|
32
|
+
assert.deepEqual(toolResultFacts({ output: 'Wall time: 10.0 seconds\nProcess running with session ID 7\nOutput:\n' }), { exitCode: null, wallMs: null });
|
|
33
|
+
// File contents that look like a header are not a header.
|
|
34
|
+
assert.deepEqual(toolResultFacts({ output: 'a file containing\nProcess exited with code 1' }), { exitCode: null, wallMs: null });
|
|
35
|
+
// The older shell tool's JSON metadata.
|
|
36
|
+
assert.deepEqual(toolResultFacts({ output: JSON.stringify({ output: 'ok', metadata: { exit_code: 2, duration_seconds: 0.25 } }) }), { exitCode: 2, wallMs: 250 });
|
|
37
|
+
assert.deepEqual(toolResultFacts(undefined), { exitCode: null, wallMs: null });
|
|
38
|
+
});
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dashboard's trace view: captured exchanges grouped into turns, each
|
|
3
|
+
* with its steps, its evidence, and what the sandbox observed for every tool
|
|
4
|
+
* call. Shared by the local proxy (raytace-proxy.mjs, its SQLite store) and
|
|
5
|
+
* the hosted evidence service (RayTrace's cloud, a Postgres
|
|
6
|
+
* store bound to one org); `db` is either, every call into it awaited.
|
|
7
|
+
*/
|
|
8
|
+
import { evidenceFor, outcome, proposedCommand } from './experiment-engine.mjs';
|
|
9
|
+
import { callKind } from './tool-metadata.mjs';
|
|
10
|
+
import { callCategory } from './call-category.mjs';
|
|
11
|
+
import { latestSessionRows, promptAsWritten } from './prompt-traces.mjs';
|
|
12
|
+
import { omitToolChunkIds, toolResultStatus, TOOL_RESULT_KINDS } from './tool-metadata.mjs';
|
|
13
|
+
import { requestMetrics } from './request-metrics.mjs';
|
|
14
|
+
import { describeCommand } from './exec-narrative.mjs';
|
|
15
|
+
|
|
16
|
+
function shortened(value, limit = 104) { const text = typeof value === 'string' ? value : JSON.stringify(value ?? ''); return text.length > limit ? `${text.slice(0, limit - 1)}…` : text; }
|
|
17
|
+
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'; }
|
|
18
|
+
function event(kind, title, detail, time, raw) { return { kind, title, detail, time, raw: JSON.stringify(raw, null, 2) }; }
|
|
19
|
+
function publicOutput(item) {
|
|
20
|
+
// Reasoning items can contain opaque/private model state. Keep only the
|
|
21
|
+
// configuration and any explicit summary; never present hidden content as a trace.
|
|
22
|
+
if (item?.type === 'reasoning') return { type: 'reasoning', id: item.id, summary: item.summary ?? null, encrypted_content: item.encrypted_content ? '[present]' : undefined };
|
|
23
|
+
return item;
|
|
24
|
+
}
|
|
25
|
+
function extractText(item) {
|
|
26
|
+
const content = item?.content;
|
|
27
|
+
if (typeof content === 'string') return content;
|
|
28
|
+
if (Array.isArray(content)) return content.map((part) => part?.text || part?.content || '').filter(Boolean).join(' ');
|
|
29
|
+
return item?.text || '';
|
|
30
|
+
}
|
|
31
|
+
export function executionFields(real) {
|
|
32
|
+
return {
|
|
33
|
+
exec_id: real?.exec_id ?? null,
|
|
34
|
+
pid: real?.pid ?? null,
|
|
35
|
+
start_time_ns: real?.start_time_ns ?? null,
|
|
36
|
+
argv: Array.isArray(real?.argv) ? real.argv : null,
|
|
37
|
+
started_at: real?.started_at ?? null,
|
|
38
|
+
ended_at: real?.ended_at ?? null,
|
|
39
|
+
exit_code: real?.exit_code ?? null,
|
|
40
|
+
window_start_ms: real?.window_start_ms ?? null,
|
|
41
|
+
window_end_ms: real?.window_end_ms ?? null,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export function splitExchange(row, replayReason = () => undefined) {
|
|
45
|
+
const request = row.request?.payload || {}; const response = row.response?.payload || {};
|
|
46
|
+
// Preserve the date and UTC offset so each viewer can render their local time.
|
|
47
|
+
const started = new Date(row.timestamp).toISOString(); const completed = new Date(row.completed_at || row.timestamp).toISOString();
|
|
48
|
+
const input = Array.isArray(request.input) ? request.input : Array.isArray(request.messages) ? request.messages : [];
|
|
49
|
+
const output = Array.isArray(response.output) ? response.output : Array.isArray(response.content) ? response.content : [];
|
|
50
|
+
const toolCount = (request.tools || []).length + input.flatMap((item) => item?.tools || []).length;
|
|
51
|
+
// undefined: no replay snapshot held for it; null: replayable.
|
|
52
|
+
const held = replayReason(row.span_id);
|
|
53
|
+
const reason = held === undefined ? 'Capture a fresh request after starting this proxy. Replay snapshots expire after 30 minutes or a restart.' : held;
|
|
54
|
+
let decision = null; try { decision = outcome(response); } catch { /* incomplete capture */ }
|
|
55
|
+
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 })];
|
|
56
|
+
for (const item of input) {
|
|
57
|
+
if (!TOOL_RESULT_KINDS.includes(item?.type)) continue;
|
|
58
|
+
const name = item.name || item.tool_name || item.call_id || 'tool';
|
|
59
|
+
steps.push(event(toolKind(name), `Tool result: ${name}`, toolResultStatus(item), started, item));
|
|
60
|
+
}
|
|
61
|
+
for (const [outputIndex, item] of output.entries()) {
|
|
62
|
+
if (item?.type === 'reasoning') {
|
|
63
|
+
const effort = response.reasoning?.effort || request.reasoning?.effort || 'model default';
|
|
64
|
+
steps.push(event('model', 'Reasoning phase', `Effort: ${effort}. Private reasoning content is intentionally not displayed.`, completed, publicOutput(item)));
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const name = item?.name || item?.function?.name;
|
|
68
|
+
if (name && /function_call|tool_use|tool_call/i.test(item?.type || '')) {
|
|
69
|
+
const data = item.arguments || item.input || item.function?.arguments || '';
|
|
70
|
+
steps.push({ ...event(toolKind(name), `Tool call: ${name}`, shortened(data), completed, publicOutput(item)), exchange_id: row.span_id, output_index: outputIndex });
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
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 });
|
|
74
|
+
}
|
|
75
|
+
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 }));
|
|
76
|
+
return steps;
|
|
77
|
+
}
|
|
78
|
+
export async function readTraces(db, { includeHistory = false, evidence = true, replayReason = () => undefined, turnId = null } = {}) {
|
|
79
|
+
const rows = (turnId && db?.turnExchanges ? await db.turnExchanges(turnId) : await db.exchangeRows({ history: includeHistory })).map(omitToolChunkIds);
|
|
80
|
+
// Rows arrive already grouped: each carries its turn as trace_id and the
|
|
81
|
+
// turn's prompt as promptTitle, decided once at capture (evidence-store.mjs).
|
|
82
|
+
const groupedRows = rows;
|
|
83
|
+
// The store already scopes the live view to the newest session; keep the
|
|
84
|
+
// filter so captures made before session tracking behave as they always did.
|
|
85
|
+
const exchangeRows = (turnId || includeHistory) ? groupedRows : (latestSessionRows(groupedRows).length ? latestSessionRows(groupedRows) : groupedRows);
|
|
86
|
+
// A tool call proposed in one captured exchange comes back as evidence (its
|
|
87
|
+
// result) in a later one. Index call_id -> the exchange that first proposed it
|
|
88
|
+
// so the UI can jump from "this evidence" to "the decision that produced it".
|
|
89
|
+
const origins = new Map();
|
|
90
|
+
for (const row of exchangeRows) {
|
|
91
|
+
const output = row.response?.payload?.output;
|
|
92
|
+
if (!Array.isArray(output)) continue;
|
|
93
|
+
for (const [outputIndex, item] of output.entries()) {
|
|
94
|
+
if (item?.call_id && /function_call|tool_use|tool_call/i.test(item?.type || '')) {
|
|
95
|
+
const scopedKey = `${row.session_id || ''}:${item.call_id}`;
|
|
96
|
+
if (!origins.has(scopedKey) || !origins.has(item.call_id)) {
|
|
97
|
+
const args = item.arguments ?? item.input ?? item.function?.arguments ?? '';
|
|
98
|
+
const info = {
|
|
99
|
+
call_id: item.call_id,
|
|
100
|
+
trace_id: row.trace_id,
|
|
101
|
+
session_id: row.session_id,
|
|
102
|
+
exchange_id: row.span_id,
|
|
103
|
+
output_index: outputIndex,
|
|
104
|
+
name: item.name,
|
|
105
|
+
kind: callKind(item.name),
|
|
106
|
+
// What the call did, for the Tool column; null with its command
|
|
107
|
+
// when only Jev can say (call-category.mjs resolveCategories).
|
|
108
|
+
category: callCategory(item.name, args),
|
|
109
|
+
proposed: proposedCommand(args, item.name)
|
|
110
|
+
};
|
|
111
|
+
if (!origins.has(scopedKey)) origins.set(scopedKey, info);
|
|
112
|
+
if (!origins.has(item.call_id)) origins.set(item.call_id, info);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const grouped = new Map();
|
|
118
|
+
const shownResultsByTrace = new Map(); // trace_id -> Set(call_id) already rendered once
|
|
119
|
+
for (const row of exchangeRows) {
|
|
120
|
+
const trace = grouped.get(row.trace_id) || { id: row.trace_id, provider: row.provider, model: row.request?.payload?.model || 'unknown model', title: promptAsWritten(row.promptTitle), promptRaw: row.promptTitle, startedAt: row.timestamp, status: row.turn_status || 'complete', events: [], evidence: [], requests: [] };
|
|
121
|
+
if (row.turn_status) trace.status = row.turn_status;
|
|
122
|
+
const shownResults = shownResultsByTrace.get(row.trace_id) || new Set();
|
|
123
|
+
// rtp- a project's sandbox; rtf- a Playground fork of one (playground.mjs).
|
|
124
|
+
if (/^rt[pf]-[a-f0-9]{32}$/.test(row.session_id || '')) trace.sandboxId = row.session_id;
|
|
125
|
+
if (/^rtf-[a-f0-9]{32}$/.test(row.session_id || '')) trace.forkId = row.session_id;
|
|
126
|
+
shownResultsByTrace.set(row.trace_id, shownResults);
|
|
127
|
+
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)) });
|
|
128
|
+
// Rows are oldest-first, so the last request that produced text is the
|
|
129
|
+
// turn's final answer, and the last completion is when the turn ended.
|
|
130
|
+
trace.endedAt = row.completed_at || row.timestamp;
|
|
131
|
+
try { const text = outcome(row.response?.payload || {}).text; if (text) trace.answer = text; } catch { /* incomplete capture */ }
|
|
132
|
+
trace.events.push(...splitExchange(row, replayReason).map((step) => {
|
|
133
|
+
if (!step.title.startsWith('Tool result:')) return step;
|
|
134
|
+
const raw = JSON.parse(step.raw); const origin = origins.get(`${row.session_id || ''}:${raw.call_id}`) || origins.get(raw.call_id);
|
|
135
|
+
// The tool result carries only a call_id and output, never the tool's
|
|
136
|
+
// name — fall back to the exchange that originally proposed the call,
|
|
137
|
+
// where the real name is known, instead of showing the raw id.
|
|
138
|
+
const label = origin?.name ? `Tool result: ${origin.name}` : step.title;
|
|
139
|
+
// The icon was classified from the same fallback name (usually the raw
|
|
140
|
+
// call_id, which never matches any category) — reclassify once the real
|
|
141
|
+
// tool name is known so the icon matches what the tool actually did.
|
|
142
|
+
const kind = origin?.name ? toolKind(origin.name) : step.kind;
|
|
143
|
+
// Clicking a result investigates the earlier decision to call that tool,
|
|
144
|
+
// using its pre-action context rather than its newly returned contents.
|
|
145
|
+
return { ...step, title: label, kind, ...(origin ? { exchange_id: origin.exchange_id, output_index: origin.output_index } : {}) };
|
|
146
|
+
}).filter((step) => {
|
|
147
|
+
if (!step.title.startsWith('Tool result:')) return true;
|
|
148
|
+
// Full conversation history is resent on every turn, so the same result
|
|
149
|
+
// would otherwise appear again in every later request's input — once is
|
|
150
|
+
// enough; the repeats carry no new information.
|
|
151
|
+
const raw = JSON.parse(step.raw);
|
|
152
|
+
if (!raw.call_id || !shownResults.has(raw.call_id)) { if (raw.call_id) shownResults.add(raw.call_id); return true; }
|
|
153
|
+
return false;
|
|
154
|
+
}));
|
|
155
|
+
for (const item of evidence ? evidenceFor(row.request?.payload, row.span_id) : []) {
|
|
156
|
+
const origin = item.call_id ? origins.get(item.call_id) : null;
|
|
157
|
+
trace.evidence.push({ ...item, origin: origin && origin.exchange_id !== row.span_id ? origin : null });
|
|
158
|
+
}
|
|
159
|
+
grouped.set(row.trace_id, trace);
|
|
160
|
+
}
|
|
161
|
+
// Overlay observed sandbox execution (runtime_processes + attributions,
|
|
162
|
+
// via db.divergence) onto each tool-result evidence item, keyed by call_id —
|
|
163
|
+
// the one field both sides share. Falls back to evidenceFor's regex
|
|
164
|
+
// heuristic (succeeded, based on scanning the result text) wherever no
|
|
165
|
+
// process was tied to the call, e.g. a session run outside the sandbox.
|
|
166
|
+
for (const trace of grouped.values()) {
|
|
167
|
+
const shownResults = shownResultsByTrace.get(trace.id) || new Set();
|
|
168
|
+
const traceOrigins = [...origins.values()].filter((origin) => origin.trace_id === trace.id);
|
|
169
|
+
for (const origin of traceOrigins) {
|
|
170
|
+
if (!shownResults.has(origin.call_id)) {
|
|
171
|
+
const reported = db?.toolCallResult ? await db.toolCallResult(origin.call_id, { exchangeId: origin.exchange_id, sessionId: origin.session_id || trace.sandboxId }) : null;
|
|
172
|
+
if (reported) {
|
|
173
|
+
const rawItem = (reported && typeof reported === 'object')
|
|
174
|
+
? { ...reported, call_id: origin.call_id }
|
|
175
|
+
: { call_id: origin.call_id, output: reported };
|
|
176
|
+
trace.events.push({
|
|
177
|
+
...event(toolKind(origin.name), `Tool result: ${origin.name}`,
|
|
178
|
+
toolResultStatus(rawItem), trace.endedAt, rawItem),
|
|
179
|
+
exchange_id: origin.exchange_id,
|
|
180
|
+
output_index: origin.output_index
|
|
181
|
+
});
|
|
182
|
+
shownResults.add(origin.call_id);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const spanIds = trace.requests.map((request) => request.id);
|
|
187
|
+
const divergenceRows = (await db.divergence(spanIds)).filter((row) => row.call_id);
|
|
188
|
+
const byCallId = new Map(divergenceRows.map((row) => [row.call_id, row]));
|
|
189
|
+
// Processes that ran underneath each call. divergence() joins on call_id
|
|
190
|
+
// and a descendant's is null by definition, so these need their own query
|
|
191
|
+
// (inherited attributions; see db.descendants in evidence-store.mjs).
|
|
192
|
+
const descendantsByCall = new Map();
|
|
193
|
+
for (const row of await db.descendants(spanIds)) {
|
|
194
|
+
if (!descendantsByCall.has(row.parent_call_id)) descendantsByCall.set(row.parent_call_id, []);
|
|
195
|
+
descendantsByCall.get(row.parent_call_id).push({
|
|
196
|
+
id: row.id, tier: row.tier, pid: row.pid, ppid: row.ppid, start_time_ns: row.start_time_ns ?? null, argv: row.argv,
|
|
197
|
+
status: row.status ?? null, error: row.error ?? null,
|
|
198
|
+
started_at: row.started_at ?? null, ended_at: row.ended_at ?? null,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
trace.evidence = trace.evidence.map((item) => {
|
|
202
|
+
const real = item.call_id ? byCallId.get(item.call_id) : null;
|
|
203
|
+
if (!real) return item;
|
|
204
|
+
// 'not_executed' means no execution row was correlated — this could be
|
|
205
|
+
// a call that genuinely never ran, or one the (deliberately
|
|
206
|
+
// conservative) matcher failed to correlate. Either way, there is no
|
|
207
|
+
// real ground truth to show yet, so this stays "unverified" and keeps
|
|
208
|
+
// the regex-heuristic succeeded value rather than asserting a fact we
|
|
209
|
+
// don't actually have.
|
|
210
|
+
const verified = real.outcome !== 'not_executed';
|
|
211
|
+
return {
|
|
212
|
+
...item,
|
|
213
|
+
real_outcome: real.outcome,
|
|
214
|
+
real_status: real.status ?? null,
|
|
215
|
+
real_error: real.error ?? null,
|
|
216
|
+
match_score: real.match_score ?? null,
|
|
217
|
+
match_basis: real.match_basis ?? null,
|
|
218
|
+
// Which witness observed it (only 'gvisor' now), and whether the
|
|
219
|
+
// runtime layer saw it start. Both drive the badge.
|
|
220
|
+
source: real.source ?? null,
|
|
221
|
+
kernel_confirmed: real.kernel_confirmed === 1,
|
|
222
|
+
// How this call's execution was attributed, recorded at capture (see
|
|
223
|
+
// migration 005). The UI badges this directly instead of re-deriving
|
|
224
|
+
// confidence from kernel_confirmed + match_basis, which is how a
|
|
225
|
+
// text-similarity guess ended up wearing the same badge as an exact
|
|
226
|
+
// join. Null for rows written before 005.
|
|
227
|
+
tier: real.tier ?? null,
|
|
228
|
+
// The call's own process, so the decision chain can say which pid
|
|
229
|
+
// this call ran as and jump to it in the sandbox tree.
|
|
230
|
+
...executionFields(real),
|
|
231
|
+
descendants: descendantsByCall.get(item.call_id) ?? [],
|
|
232
|
+
descendant_count: real.descendant_count ?? 0,
|
|
233
|
+
verified,
|
|
234
|
+
// Whether the agent's own report of the result (exit code, wall
|
|
235
|
+
// time) agrees with what the runtime observed. See migration 007.
|
|
236
|
+
reported_check: real.reported_check ?? null,
|
|
237
|
+
// Real ground truth overrides the text-scanning heuristic once we
|
|
238
|
+
// have it -- except while a sandbox command is still 'running'
|
|
239
|
+
// (gVisor has seen it start but not exit yet) or its outcome is
|
|
240
|
+
// 'unknown' (the evidence that would say was lost): asserting success
|
|
241
|
+
// or failure there would be a fact we don't have, so keep the heuristic.
|
|
242
|
+
succeeded: verified && real.status !== 'running' && real.status !== 'unknown' ? real.status === 'completed' : item.succeeded,
|
|
243
|
+
};
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
// Flat, per-call verification list for the graph view: unlike `evidence`
|
|
247
|
+
// above, this isn't limited to calls whose result got resent as later
|
|
248
|
+
// input — it covers every call this trace ever proposed, including one
|
|
249
|
+
// in the very last response with no later request to resend it into.
|
|
250
|
+
// `origins` already has one entry per call_id with the exchange that
|
|
251
|
+
// proposed it, so this is just that, decorated with whatever real
|
|
252
|
+
// execution data (if any) `divergence()` found for the same call_id.
|
|
253
|
+
// Where a sandboxed Claude Code's project folder stood after each call.
|
|
254
|
+
const snapshots = await db.snapshotsForCalls(traceOrigins.map((origin) => origin.call_id), { sessionId: trace.sandboxId || trace.id });
|
|
255
|
+
trace.callVerifications = traceOrigins.map((origin) => {
|
|
256
|
+
const real = byCallId.get(origin.call_id);
|
|
257
|
+
return {
|
|
258
|
+
call_id: origin.call_id,
|
|
259
|
+
exchange_id: origin.exchange_id,
|
|
260
|
+
name: origin.name,
|
|
261
|
+
kind: origin.kind,
|
|
262
|
+
category: origin.category.category,
|
|
263
|
+
category_source: origin.category.source,
|
|
264
|
+
...(origin.category.command ? { category_command: origin.category.command } : {}),
|
|
265
|
+
verified: real ? real.outcome !== 'not_executed' : false,
|
|
266
|
+
status: real?.status ?? null,
|
|
267
|
+
error: real?.error ?? null,
|
|
268
|
+
match_score: real?.match_score ?? null,
|
|
269
|
+
match_basis: real?.match_basis ?? null,
|
|
270
|
+
source: real?.source ?? null,
|
|
271
|
+
kernel_confirmed: real?.kernel_confirmed === 1,
|
|
272
|
+
tier: real?.tier ?? null,
|
|
273
|
+
reported_check: real?.reported_check ?? null,
|
|
274
|
+
descendant_count: real?.descendant_count ?? 0,
|
|
275
|
+
// Everything the "proposed vs observed" table needs for this row:
|
|
276
|
+
// what the model asked for, and the process that actually ran.
|
|
277
|
+
output_index: origin.output_index,
|
|
278
|
+
proposed: origin.proposed ?? null,
|
|
279
|
+
// The proposed command in plain English, from the same rules Sandbox
|
|
280
|
+
// evidence uses (exec-narrative.mjs). Rule-only here: a model fallback
|
|
281
|
+
// would spend on every trace fetch, and the raw command stays beside it.
|
|
282
|
+
description: origin.kind === 'command' ? describeCommand(origin.proposed) : null,
|
|
283
|
+
...executionFields(real),
|
|
284
|
+
descendants: descendantsByCall.get(origin.call_id) ?? [],
|
|
285
|
+
snapshot: snapshots.get(origin.call_id) ?? null,
|
|
286
|
+
};
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Codex requests include a large tool schema. Return recent traces only so the
|
|
291
|
+
// live dashboard stays responsive instead of repeatedly transferring history.
|
|
292
|
+
const sorted = [...grouped.values()].sort((a, b) => b.startedAt.localeCompare(a.startedAt));
|
|
293
|
+
const result = turnId ? sorted : sorted.slice(0, includeHistory ? 100 : 10);
|
|
294
|
+
// Every request resends the whole conversation, so each earlier item comes
|
|
295
|
+
// back once per later request: a long Claude Code session made one prompt
|
|
296
|
+
// tens of MB, fetched every few seconds. An item is sent in full once; a
|
|
297
|
+
// repeat keeps only where it sits and names the item that has the rest
|
|
298
|
+
// (content_of).
|
|
299
|
+
for (const trace of result) {
|
|
300
|
+
const first = new Map();
|
|
301
|
+
trace.evidence = trace.evidence.map((item) => {
|
|
302
|
+
const key = `${item.kind}\0${item.label}\0${item.content ?? item.preview ?? ''}`;
|
|
303
|
+
if (!first.has(key)) { first.set(key, item.id); return item; }
|
|
304
|
+
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) };
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
return result;
|
|
308
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { readTraces } from './trace-view.mjs';
|
|
4
|
+
|
|
5
|
+
test('synthesizes terminal tool results for proposed calls with no subsequent exchange', async () => {
|
|
6
|
+
const fakeRow = {
|
|
7
|
+
span_id: 'span-1',
|
|
8
|
+
trace_id: 'trace-1',
|
|
9
|
+
session_id: 'rtp-12345678123456781234567812345678',
|
|
10
|
+
provider: 'claude-code',
|
|
11
|
+
timestamp: '2026-10-28T12:00:00.000Z',
|
|
12
|
+
promptTitle: 'test prompt',
|
|
13
|
+
request: {
|
|
14
|
+
payload: {
|
|
15
|
+
model: 'claude-3-5-sonnet',
|
|
16
|
+
input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'run exit 7' }] }]
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
response: {
|
|
20
|
+
payload: {
|
|
21
|
+
output: [
|
|
22
|
+
{
|
|
23
|
+
type: 'function_call',
|
|
24
|
+
call_id: 'toolu_term_1',
|
|
25
|
+
name: 'Bash',
|
|
26
|
+
arguments: JSON.stringify({ command: 'exit 7' })
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const fakeDb = {
|
|
34
|
+
exchangeRows: async () => [fakeRow],
|
|
35
|
+
divergence: async () => [],
|
|
36
|
+
descendants: async () => [],
|
|
37
|
+
snapshotsForCalls: async () => new Map(),
|
|
38
|
+
toolCallResult: async (callId) => {
|
|
39
|
+
if (callId === 'toolu_term_1') {
|
|
40
|
+
return { call_id: 'toolu_term_1', is_error: true, exit_code: 7, output: 'Process exited with code 7' };
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const traces = await readTraces(fakeDb, { includeHistory: true });
|
|
47
|
+
assert.equal(traces.length, 1);
|
|
48
|
+
const trace = traces[0];
|
|
49
|
+
|
|
50
|
+
const resultEvent = trace.events.find((e) => e.title.startsWith('Tool result:') && e.raw.includes('toolu_term_1'));
|
|
51
|
+
assert.ok(resultEvent, 'terminal tool result event was synthesized into trace.events');
|
|
52
|
+
const parsed = JSON.parse(resultEvent.raw);
|
|
53
|
+
assert.equal(parsed.call_id, 'toolu_term_1');
|
|
54
|
+
assert.equal(parsed.exit_code, 7);
|
|
55
|
+
assert.equal(parsed.is_error, true);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('toolResultsFromTranscript extracts tool results from user messages', async () => {
|
|
59
|
+
const { toolResultsFromTranscript } = await import('./claude-code-adapter.mjs');
|
|
60
|
+
const lines = [
|
|
61
|
+
{ type: 'user', message: { content: [{ type: 'text', text: 'hello' }] } },
|
|
62
|
+
{ type: 'assistant', message: { id: 'msg_1', content: [{ type: 'tool_use', id: 'call_99', name: 'Bash', input: { command: 'ls' } }] } },
|
|
63
|
+
{ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'call_99', content: 'file.txt', is_error: false }] } }
|
|
64
|
+
];
|
|
65
|
+
const results = toolResultsFromTranscript(lines);
|
|
66
|
+
assert.equal(results.size, 1);
|
|
67
|
+
assert.deepEqual(results.get('call_99'), {
|
|
68
|
+
type: 'function_call_output',
|
|
69
|
+
call_id: 'call_99',
|
|
70
|
+
output: 'file.txt'
|
|
71
|
+
});
|
|
72
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal client for TypeSafe's System One endpoint (the Jev models).
|
|
3
|
+
*
|
|
4
|
+
* Jev is a decision model, not a text model: it takes `state` plus named,
|
|
5
|
+
* typed questions (score / choice / noul) and returns calibrated
|
|
6
|
+
* probabilities. It never writes prose, so nothing here expects any.
|
|
7
|
+
*
|
|
8
|
+
* Plain fetch rather than @typesafe-ai/sdk, matching how the proxy reaches
|
|
9
|
+
* every other provider (invokeReplay), and because the SDK does not install
|
|
10
|
+
* cleanly next to this repo's React peer ranges.
|
|
11
|
+
* API: https://docs.typesafe.ai/api
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const DEFAULT_URL = 'https://api.typesafe.ai';
|
|
15
|
+
const DEFAULT_MODEL = 'jev-latest';
|
|
16
|
+
const TIMEOUT_MS = 15_000;
|
|
17
|
+
const MAX_ATTEMPTS = 3;
|
|
18
|
+
// 429 = rate limited, 529 = overloaded: the two statuses the API documents as
|
|
19
|
+
// safe to retry with backoff. Everything else is a real error.
|
|
20
|
+
const RETRYABLE = new Set([429, 529]);
|
|
21
|
+
|
|
22
|
+
export function typesafeConfig(env = process.env) {
|
|
23
|
+
const apiKey = env.TYPESAFE_API_KEY?.trim() || null;
|
|
24
|
+
return {
|
|
25
|
+
enabled: Boolean(apiKey),
|
|
26
|
+
apiKey,
|
|
27
|
+
model: env.RAYTACE_TYPESAFE_MODEL?.trim() || DEFAULT_MODEL,
|
|
28
|
+
url: (env.RAYTACE_TYPESAFE_URL || DEFAULT_URL).replace(/\/$/, ''),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const wait = (ms, signal) => new Promise((resolve, reject) => {
|
|
33
|
+
const timer = setTimeout(resolve, ms);
|
|
34
|
+
signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* One System One request. Resolves to `{ model, answers, usage }` exactly as
|
|
39
|
+
* the API returns it; `model` is the concrete version that answered (e.g.
|
|
40
|
+
* jev-1.13.0), which callers should record rather than the alias they sent.
|
|
41
|
+
*/
|
|
42
|
+
export async function systemOne(config, { state, questions }, { signal, fetchImpl = fetch } = {}) {
|
|
43
|
+
if (!config?.enabled) throw new Error('Set TYPESAFE_API_KEY to enable Jev.');
|
|
44
|
+
const body = JSON.stringify({ model: config.model, state, questions });
|
|
45
|
+
let lastError;
|
|
46
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
|
|
47
|
+
const timeout = AbortSignal.timeout(TIMEOUT_MS);
|
|
48
|
+
const response = await fetchImpl(`${config.url}/v1/systemone`, {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
headers: { authorization: `Bearer ${config.apiKey}`, 'content-type': 'application/json' },
|
|
51
|
+
body,
|
|
52
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
|
53
|
+
});
|
|
54
|
+
if (response.ok) return response.json();
|
|
55
|
+
const detail = (await response.text().catch(() => '')).slice(0, 300);
|
|
56
|
+
lastError = new Error(`TypeSafe ${response.status}${detail ? `: ${detail}` : ''}`);
|
|
57
|
+
lastError.status = response.status;
|
|
58
|
+
if (!RETRYABLE.has(response.status) || attempt === MAX_ATTEMPTS) break;
|
|
59
|
+
const retryAfter = Number(response.headers.get('retry-after'));
|
|
60
|
+
await wait(Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 500 * 2 ** (attempt - 1), signal);
|
|
61
|
+
}
|
|
62
|
+
throw lastError;
|
|
63
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { typesafeConfig, systemOne } from './typesafe.mjs';
|
|
4
|
+
|
|
5
|
+
const reply = (status, body = {}, headers = {}) => new Response(JSON.stringify(body), { status, headers });
|
|
6
|
+
|
|
7
|
+
test('disabled without a key; defaults to jev-latest', () => {
|
|
8
|
+
assert.equal(typesafeConfig({}).enabled, false);
|
|
9
|
+
const config = typesafeConfig({ TYPESAFE_API_KEY: ' k ', RAYTACE_TYPESAFE_URL: 'http://x/' });
|
|
10
|
+
assert.deepEqual(config, { enabled: true, apiKey: 'k', model: 'jev-latest', url: 'http://x' });
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test('sends the documented request shape with a bearer key', async () => {
|
|
14
|
+
let seen;
|
|
15
|
+
const fetchImpl = async (url, init) => { seen = { url, init }; return reply(200, { model: 'jev-1.13.0', answers: {}, usage: { input_tokens: 10 } }); };
|
|
16
|
+
const config = typesafeConfig({ TYPESAFE_API_KEY: 'k' });
|
|
17
|
+
const result = await systemOne(config, { state: { a: 1 }, questions: { q: { type: 'noul', instructions: 'x?' } } }, { fetchImpl });
|
|
18
|
+
assert.equal(seen.url, 'https://api.typesafe.ai/v1/systemone');
|
|
19
|
+
assert.equal(seen.init.headers.authorization, 'Bearer k');
|
|
20
|
+
assert.deepEqual(JSON.parse(seen.init.body), { model: 'jev-latest', state: { a: 1 }, questions: { q: { type: 'noul', instructions: 'x?' } } });
|
|
21
|
+
assert.equal(result.model, 'jev-1.13.0');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('retries 429 and 529, but not other errors', async () => {
|
|
25
|
+
const config = typesafeConfig({ TYPESAFE_API_KEY: 'k' });
|
|
26
|
+
let calls = 0;
|
|
27
|
+
const flaky = async () => (++calls < 3 ? reply(calls === 1 ? 429 : 529, {}, { 'retry-after': '0.01' }) : reply(200, { answers: {} }));
|
|
28
|
+
await systemOne(config, { state: '', questions: {} }, { fetchImpl: flaky });
|
|
29
|
+
assert.equal(calls, 3);
|
|
30
|
+
|
|
31
|
+
calls = 0;
|
|
32
|
+
const invalid = async () => { calls += 1; return reply(422, { detail: 'bad question' }); };
|
|
33
|
+
await assert.rejects(systemOne(config, { state: '', questions: {} }, { fetchImpl: invalid }), (error) => error.status === 422 && /bad question/.test(error.message));
|
|
34
|
+
assert.equal(calls, 1);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('refuses to call without a key', async () => {
|
|
38
|
+
await assert.rejects(systemOne(typesafeConfig({}), { state: '', questions: {} }), /TYPESAFE_API_KEY/);
|
|
39
|
+
});
|
package/src/claude-code.mjs
CHANGED
|
@@ -33,7 +33,44 @@ function allHooks(settings) {
|
|
|
33
33
|
export function hookState() {
|
|
34
34
|
const settings = readSettings();
|
|
35
35
|
const hooks = allHooks(settings);
|
|
36
|
-
|
|
36
|
+
const repoHook = hooks.some(isRepoHook);
|
|
37
|
+
|
|
38
|
+
const missingEvents = [];
|
|
39
|
+
let invalidType = false;
|
|
40
|
+
let invalidMatcher = false;
|
|
41
|
+
let duplicates = false;
|
|
42
|
+
|
|
43
|
+
for (const event of EVENTS) {
|
|
44
|
+
const groups = settings.hooks?.[event] ?? [];
|
|
45
|
+
let count = 0;
|
|
46
|
+
|
|
47
|
+
for (const group of groups) {
|
|
48
|
+
for (const hook of group.hooks ?? []) {
|
|
49
|
+
if (isOurs(hook)) {
|
|
50
|
+
count += 1;
|
|
51
|
+
if (hook.type !== 'command') invalidType = true;
|
|
52
|
+
if (event === 'PostToolUse' && group.matcher && group.matcher !== '*') invalidMatcher = true;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (count === 0) missingEvents.push(event);
|
|
58
|
+
else if (count > 1) duplicates = true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const installed = missingEvents.length === 0;
|
|
62
|
+
const valid = installed && !invalidType && !invalidMatcher && !duplicates;
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
file: settingsFile(),
|
|
66
|
+
installed,
|
|
67
|
+
valid,
|
|
68
|
+
missingEvents,
|
|
69
|
+
invalidType,
|
|
70
|
+
invalidMatcher,
|
|
71
|
+
duplicates,
|
|
72
|
+
repoHook
|
|
73
|
+
};
|
|
37
74
|
}
|
|
38
75
|
|
|
39
76
|
/** Installs (or with remove, removes) the hook. Returns the settings file. */
|