raytrace-cli 0.11.1__py3-none-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. raytrace/__init__.py +1 -0
  2. raytrace/__main__.py +33 -0
  3. raytrace/app/LICENSE +21 -0
  4. raytrace/app/README.md +599 -0
  5. raytrace/app/bin/raytrace.mjs +297 -0
  6. raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  7. raytrace/app/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  8. raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  9. raytrace/app/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  10. raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  11. raytrace/app/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  12. raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  13. raytrace/app/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  14. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  15. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  16. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  17. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  18. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  19. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  20. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  21. raytrace/app/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  22. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  23. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  24. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  25. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  26. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  27. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  28. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  29. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  30. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  31. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  32. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  33. raytrace/app/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  34. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  35. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  36. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  37. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  38. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  39. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  40. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  41. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  42. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  43. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  44. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  45. raytrace/app/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  46. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  47. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  48. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  49. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  50. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  51. raytrace/app/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  52. raytrace/app/dist/dashboard/assets/index-DepcI8Fi.js +38 -0
  53. raytrace/app/dist/dashboard/assets/index-H97VLD5l.css +1 -0
  54. raytrace/app/dist/dashboard/favicon.svg +6 -0
  55. raytrace/app/dist/dashboard/index.html +15 -0
  56. raytrace/app/package.json +48 -0
  57. raytrace/app/proxy/agent-intent-schema.test.mjs +142 -0
  58. raytrace/app/proxy/call-assessment.mjs +385 -0
  59. raytrace/app/proxy/call-assessment.test.mjs +167 -0
  60. raytrace/app/proxy/call-category.mjs +461 -0
  61. raytrace/app/proxy/capture-health.mjs +30 -0
  62. raytrace/app/proxy/capture-health.test.mjs +44 -0
  63. raytrace/app/proxy/capture.mjs +38 -0
  64. raytrace/app/proxy/capture.test.mjs +49 -0
  65. raytrace/app/proxy/claude-code-adapter.mjs +301 -0
  66. raytrace/app/proxy/claude-code-hook.mjs +22 -0
  67. raytrace/app/proxy/codex-config.mjs +36 -0
  68. raytrace/app/proxy/codex.mjs +14 -0
  69. raytrace/app/proxy/evidence-schema.test.mjs +240 -0
  70. raytrace/app/proxy/evidence-store.mjs +993 -0
  71. raytrace/app/proxy/evidence-store.test.mjs +301 -0
  72. raytrace/app/proxy/exec-narrative.mjs +625 -0
  73. raytrace/app/proxy/exec-narrative.test.mjs +262 -0
  74. raytrace/app/proxy/execution-correlation.mjs +185 -0
  75. raytrace/app/proxy/execution-correlation.test.mjs +146 -0
  76. raytrace/app/proxy/execution-runner.mjs +89 -0
  77. raytrace/app/proxy/execution-runner.test.mjs +38 -0
  78. raytrace/app/proxy/experiment-engine.mjs +195 -0
  79. raytrace/app/proxy/experiment-engine.test.mjs +93 -0
  80. raytrace/app/proxy/explanations.mjs +36 -0
  81. raytrace/app/proxy/explanations.test.mjs +20 -0
  82. raytrace/app/proxy/failure-signature.mjs +56 -0
  83. raytrace/app/proxy/gvisor-forwarder.mjs +493 -0
  84. raytrace/app/proxy/gvisor-forwarder.test.mjs +433 -0
  85. raytrace/app/proxy/init-evidence-db.mjs +227 -0
  86. raytrace/app/proxy/local-sandboxes.mjs +94 -0
  87. raytrace/app/proxy/local-token.mjs +30 -0
  88. raytrace/app/proxy/playground-recovery.test.mjs +130 -0
  89. raytrace/app/proxy/playground.mjs +439 -0
  90. raytrace/app/proxy/prompt-context.mjs +278 -0
  91. raytrace/app/proxy/prompt-traces.mjs +40 -0
  92. raytrace/app/proxy/prompt-traces.test.mjs +32 -0
  93. raytrace/app/proxy/providers.mjs +65 -0
  94. raytrace/app/proxy/providers.test.mjs +76 -0
  95. raytrace/app/proxy/proxy.integration.test.mjs +135 -0
  96. raytrace/app/proxy/raytace-proxy.mjs +941 -0
  97. raytrace/app/proxy/request-metrics.mjs +13 -0
  98. raytrace/app/proxy/request-metrics.test.mjs +19 -0
  99. raytrace/app/proxy/request-policy.mjs +45 -0
  100. raytrace/app/proxy/request-policy.test.mjs +47 -0
  101. raytrace/app/proxy/run-recap.mjs +139 -0
  102. raytrace/app/proxy/runtime-attribution.mjs +110 -0
  103. raytrace/app/proxy/sandbox-bridge.mjs +49 -0
  104. raytrace/app/proxy/schema/EVIDENCE_DATABASE.md +276 -0
  105. raytrace/app/proxy/schema/agent_intent.sql +101 -0
  106. raytrace/app/proxy/schema/auxiliary.sql +90 -0
  107. raytrace/app/proxy/schema/capture_health.sql +14 -0
  108. raytrace/app/proxy/schema/classification.sql +89 -0
  109. raytrace/app/proxy/schema/file_context.sql +53 -0
  110. raytrace/app/proxy/schema/runtime_evidence.sql +201 -0
  111. raytrace/app/proxy/schema/search.sql +66 -0
  112. raytrace/app/proxy/schema/shared_storage.sql +21 -0
  113. raytrace/app/proxy/search.mjs +418 -0
  114. raytrace/app/proxy/search.test.mjs +161 -0
  115. raytrace/app/proxy/smoke.test.mjs +93 -0
  116. raytrace/app/proxy/step-attribution.mjs +380 -0
  117. raytrace/app/proxy/step-lab.mjs +78 -0
  118. raytrace/app/proxy/step-lab.test.mjs +38 -0
  119. raytrace/app/proxy/summaries.mjs +151 -0
  120. raytrace/app/proxy/summaries.test.mjs +69 -0
  121. raytrace/app/proxy/tool-metadata.mjs +111 -0
  122. raytrace/app/proxy/tool-metadata.test.mjs +38 -0
  123. raytrace/app/proxy/trace-view.mjs +324 -0
  124. raytrace/app/proxy/trace-view.test.mjs +92 -0
  125. raytrace/app/proxy/typesafe.mjs +63 -0
  126. raytrace/app/proxy/typesafe.test.mjs +39 -0
  127. raytrace/app/src/agents.mjs +7 -0
  128. raytrace/app/src/api.mjs +57 -0
  129. raytrace/app/src/auth.mjs +205 -0
  130. raytrace/app/src/beta.mjs +96 -0
  131. raytrace/app/src/claude-code.mjs +93 -0
  132. raytrace/app/src/commands.mjs +285 -0
  133. raytrace/app/src/config.mjs +49 -0
  134. raytrace/app/src/export.mjs +200 -0
  135. raytrace/app/src/lima.mjs +176 -0
  136. raytrace/app/src/local-sandbox.mjs +358 -0
  137. raytrace/app/src/mcp.mjs +688 -0
  138. raytrace/app/src/paths.mjs +33 -0
  139. raytrace/app/src/prompt.mjs +42 -0
  140. raytrace/app/src/proxy-process.mjs +143 -0
  141. raytrace/app/src/sandbox.mjs +306 -0
  142. raytrace/app/src/share.mjs +86 -0
  143. raytrace/app/src/terminal.mjs +68 -0
  144. raytrace/app/src/upload.mjs +198 -0
  145. raytrace/app/worker/sandbox/Dockerfile +8 -0
  146. raytrace/app/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  147. raytrace/app/worker/sandbox/claude-hook.mjs +364 -0
  148. raytrace/app/worker/sandbox/collector.py +405 -0
  149. raytrace/app/worker/sandbox/dns_forwarder.py +255 -0
  150. raytrace/app/worker/sandbox/engine.py +940 -0
  151. raytrace/app/worker/sandbox/file_scan.py +491 -0
  152. raytrace/app/worker/sandbox/lima.yaml +29 -0
  153. raytrace/app/worker/sandbox/network.py +90 -0
  154. raytrace/app/worker/sandbox/projects.py +702 -0
  155. raytrace/app/worker/sandbox/setup.py +159 -0
  156. raytrace/app/worker/sandbox/syscall_catalog.sql +985 -0
  157. raytrace/app/worker/sandbox/transcript-delivery.test.mjs +153 -0
  158. raytrace/app/worker/sandbox/viewer.py +195 -0
  159. raytrace/node/LICENSE +2946 -0
  160. raytrace/node/node.exe +4 -0
  161. raytrace_cli-0.11.1.dist-info/LICENSE +21 -0
  162. raytrace_cli-0.11.1.dist-info/METADATA +42 -0
  163. raytrace_cli-0.11.1.dist-info/RECORD +165 -0
  164. raytrace_cli-0.11.1.dist-info/WHEEL +4 -0
  165. raytrace_cli-0.11.1.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,324 @@
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
+ let rows = (turnId && db?.turnExchanges ? await db.turnExchanges(turnId) : await db.exchangeRows({ history: includeHistory })).map(omitToolChunkIds);
80
+ const truncated=Boolean(turnId && rows.length>2000);
81
+ if(turnId) rows=rows.slice(0,2000);
82
+ // Rows arrive already grouped: each carries its turn as trace_id and the
83
+ // turn's prompt as promptTitle, decided once at capture (evidence-store.mjs).
84
+ const groupedRows = rows;
85
+ // The store already scopes the live view to the newest session; keep the
86
+ // filter so captures made before session tracking behave as they always did.
87
+ const exchangeRows = (turnId || includeHistory) ? groupedRows : (latestSessionRows(groupedRows).length ? latestSessionRows(groupedRows) : groupedRows);
88
+ // A tool call proposed in one captured exchange comes back as evidence (its
89
+ // result) in a later one. Index call_id -> the exchange that first proposed it
90
+ // so the UI can jump from "this evidence" to "the decision that produced it".
91
+ const origins = [];
92
+ const originByCall = new Map();
93
+ for (const row of exchangeRows) {
94
+ const output = row.response?.payload?.output;
95
+ if (!Array.isArray(output)) continue;
96
+ for (const [outputIndex, item] of output.entries()) {
97
+ if (item?.call_id && /function_call|tool_use|tool_call/i.test(item?.type || '')) {
98
+ const scopedKey = `${row.session_id || ''}:${item.call_id}`;
99
+ {
100
+ const args = item.arguments ?? item.input ?? item.function?.arguments ?? '';
101
+ const info = {
102
+ call_id: item.call_id,
103
+ trace_id: row.trace_id,
104
+ session_id: row.session_id,
105
+ exchange_id: row.span_id,
106
+ output_index: outputIndex,
107
+ name: item.name,
108
+ kind: callKind(item.name),
109
+ // What the call did, for the Tool column; null with its command
110
+ // when only Jev can say (call-category.mjs resolveCategories).
111
+ category: callCategory(item.name, args),
112
+ proposed: proposedCommand(args, item.name)
113
+ };
114
+ origins.push(info);
115
+ // Reused IDs inside one session cannot identify a result reliably.
116
+ originByCall.set(scopedKey,originByCall.has(scopedKey)?null:info);
117
+ }
118
+ }
119
+ }
120
+ }
121
+ const grouped = new Map();
122
+ const shownResultsByTrace = new Map(); // trace_id -> Set(call_id) already rendered once
123
+ for (const row of exchangeRows) {
124
+ 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: [], ...(turnId ? {comparisonRequests:[],captureComplete:!truncated} : {}) };
125
+ if (row.turn_status) trace.status = row.turn_status;
126
+ const shownResults = shownResultsByTrace.get(row.trace_id) || new Set();
127
+ // rtp- a project's sandbox; rtf- a Playground fork of one (playground.mjs).
128
+ if (/^rt[pf]-[a-f0-9]{32}$/.test(row.session_id || '')) trace.sandboxId = row.session_id;
129
+ if (/^rtf-[a-f0-9]{32}$/.test(row.session_id || '')) trace.forkId = row.session_id;
130
+ shownResultsByTrace.set(row.trace_id, shownResults);
131
+ if(turnId) {
132
+ const payload=row.request?.payload ?? {};
133
+ trace.comparisonRequests.push({exchangeId:row.span_id,model:payload.model??null,
134
+ settings:Object.fromEntries(Object.entries(payload).filter(([key])=>!['input','messages','instructions','system','tools','stream','store','metadata','previous_response_id','conversation','client_request_id'].includes(key))),
135
+ instructions:payload.instructions??payload.system??null,tools:payload.tools??[],
136
+ context:evidenceFor(payload,row.span_id).filter(item=>item.kind!=='tool result')});
137
+ }
138
+ 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)) });
139
+ // Rows are oldest-first, so the last request that produced text is the
140
+ // turn's final answer, and the last completion is when the turn ended.
141
+ trace.endedAt = row.completed_at || row.timestamp;
142
+ try { const text = outcome(row.response?.payload || {}).text; if (text) trace.answer = text; } catch { /* incomplete capture */ }
143
+ trace.events.push(...splitExchange(row, replayReason).map((step) => {
144
+ if (!step.title.startsWith('Tool result:')) return step;
145
+ const raw = JSON.parse(step.raw); const origin = originByCall.get(`${row.session_id || ''}:${raw.call_id}`);
146
+ // The tool result carries only a call_id and output, never the tool's
147
+ // name — fall back to the exchange that originally proposed the call,
148
+ // where the real name is known, instead of showing the raw id.
149
+ const label = origin?.name ? `Tool result: ${origin.name}` : step.title;
150
+ // The icon was classified from the same fallback name (usually the raw
151
+ // call_id, which never matches any category) — reclassify once the real
152
+ // tool name is known so the icon matches what the tool actually did.
153
+ const kind = origin?.name ? toolKind(origin.name) : step.kind;
154
+ // Clicking a result investigates the earlier decision to call that tool,
155
+ // using its pre-action context rather than its newly returned contents.
156
+ return { ...step, title: label, kind, ...(origin ? { exchange_id: origin.exchange_id, output_index: origin.output_index } : {}) };
157
+ }).filter((step) => {
158
+ if (!step.title.startsWith('Tool result:')) return true;
159
+ // Full conversation history is resent on every turn, so the same result
160
+ // would otherwise appear again in every later request's input — once is
161
+ // enough; the repeats carry no new information.
162
+ const raw = JSON.parse(step.raw);
163
+ if (!raw.call_id || !shownResults.has(raw.call_id)) { if (raw.call_id) shownResults.add(raw.call_id); return true; }
164
+ return false;
165
+ }));
166
+ for (const item of evidence ? evidenceFor(row.request?.payload, row.span_id) : []) {
167
+ const origin = item.call_id ? originByCall.get(`${row.session_id || ''}:${item.call_id}`) : null;
168
+ trace.evidence.push({ ...item, origin: origin && origin.exchange_id !== row.span_id ? origin : null });
169
+ }
170
+ grouped.set(row.trace_id, trace);
171
+ }
172
+ // Overlay observed sandbox execution (runtime_processes + attributions,
173
+ // via db.divergence) onto each tool-result evidence item, keyed by call_id —
174
+ // the one field both sides share. Falls back to evidenceFor's regex
175
+ // heuristic (succeeded, based on scanning the result text) wherever no
176
+ // process was tied to the call, e.g. a session run outside the sandbox.
177
+ for (const trace of grouped.values()) {
178
+ const shownResults = shownResultsByTrace.get(trace.id) || new Set();
179
+ const traceOrigins = [...origins.values()].filter((origin) => origin.trace_id === trace.id);
180
+ for (const origin of traceOrigins) {
181
+ if (!shownResults.has(origin.call_id) && originByCall.get(`${origin.session_id || ''}:${origin.call_id}`)===origin) {
182
+ const reported = db?.toolCallResult ? await db.toolCallResult(origin.call_id, { exchangeId: origin.exchange_id, sessionId: origin.session_id || trace.sandboxId }) : null;
183
+ if (reported) {
184
+ const rawItem = (reported && typeof reported === 'object')
185
+ ? { ...reported, call_id: origin.call_id }
186
+ : { call_id: origin.call_id, output: reported };
187
+ trace.events.push({
188
+ ...event(toolKind(origin.name), `Tool result: ${origin.name}`,
189
+ toolResultStatus(rawItem), trace.endedAt, rawItem),
190
+ exchange_id: origin.exchange_id,
191
+ output_index: origin.output_index
192
+ });
193
+ shownResults.add(origin.call_id);
194
+ }
195
+ }
196
+ }
197
+ const spanIds = trace.requests.map((request) => request.id);
198
+ const divergenceRows = (await db.divergence(spanIds)).filter((row) => row.call_id);
199
+ const byCallId = new Map(divergenceRows.map((row) => [row.call_id, row]));
200
+ // Processes that ran underneath each call. divergence() joins on call_id
201
+ // and a descendant's is null by definition, so these need their own query
202
+ // (inherited attributions; see db.descendants in evidence-store.mjs).
203
+ const descendantsByCall = new Map();
204
+ for (const row of await db.descendants(spanIds)) {
205
+ if (!descendantsByCall.has(row.parent_call_id)) descendantsByCall.set(row.parent_call_id, []);
206
+ descendantsByCall.get(row.parent_call_id).push({
207
+ id: row.id, tier: row.tier, pid: row.pid, ppid: row.ppid, start_time_ns: row.start_time_ns ?? null, argv: row.argv,
208
+ status: row.status ?? null, error: row.error ?? null,
209
+ started_at: row.started_at ?? null, ended_at: row.ended_at ?? null,
210
+ });
211
+ }
212
+ trace.evidence = trace.evidence.map((item) => {
213
+ const real = item.call_id ? byCallId.get(item.call_id) : null;
214
+ if (!real) return item;
215
+ // 'not_executed' means no execution row was correlated — this could be
216
+ // a call that genuinely never ran, or one the (deliberately
217
+ // conservative) matcher failed to correlate. Either way, there is no
218
+ // real ground truth to show yet, so this stays "unverified" and keeps
219
+ // the regex-heuristic succeeded value rather than asserting a fact we
220
+ // don't actually have.
221
+ const verified = real.outcome !== 'not_executed';
222
+ return {
223
+ ...item,
224
+ real_outcome: real.outcome,
225
+ real_status: real.status ?? null,
226
+ real_error: real.error ?? null,
227
+ match_score: real.match_score ?? null,
228
+ match_basis: real.match_basis ?? null,
229
+ // Which witness observed it (only 'gvisor' now), and whether the
230
+ // runtime layer saw it start. Both drive the badge.
231
+ source: real.source ?? null,
232
+ kernel_confirmed: real.kernel_confirmed === 1,
233
+ // How this call's execution was attributed, recorded at capture (see
234
+ // migration 005). The UI badges this directly instead of re-deriving
235
+ // confidence from kernel_confirmed + match_basis, which is how a
236
+ // text-similarity guess ended up wearing the same badge as an exact
237
+ // join. Null for rows written before 005.
238
+ tier: real.tier ?? null,
239
+ // The call's own process, so the decision chain can say which pid
240
+ // this call ran as and jump to it in the sandbox tree.
241
+ ...executionFields(real),
242
+ descendants: descendantsByCall.get(item.call_id) ?? [],
243
+ descendant_count: real.descendant_count ?? 0,
244
+ verified,
245
+ // Whether the agent's own report of the result (exit code, wall
246
+ // time) agrees with what the runtime observed. See migration 007.
247
+ reported_check: real.reported_check ?? null,
248
+ // Real ground truth overrides the text-scanning heuristic once we
249
+ // have it -- except while a sandbox command is still 'running'
250
+ // (gVisor has seen it start but not exit yet) or its outcome is
251
+ // 'unknown' (the evidence that would say was lost): asserting success
252
+ // or failure there would be a fact we don't have, so keep the heuristic.
253
+ succeeded: verified && real.status !== 'running' && real.status !== 'unknown' ? real.status === 'completed' : item.succeeded,
254
+ };
255
+ });
256
+
257
+ // Flat, per-call verification list for the graph view: unlike `evidence`
258
+ // above, this isn't limited to calls whose result got resent as later
259
+ // input — it covers every call this trace ever proposed, including one
260
+ // in the very last response with no later request to resend it into.
261
+ // `origins` already has one entry per call_id with the exchange that
262
+ // proposed it, so this is just that, decorated with whatever real
263
+ // execution data (if any) `divergence()` found for the same call_id.
264
+ // Where a sandboxed Claude Code's project folder stood after each call.
265
+ const snapshots = await db.snapshotsForCalls(traceOrigins.map((origin) => origin.call_id), { sessionId: trace.sandboxId || trace.id });
266
+ trace.callVerifications = traceOrigins.map((origin) => {
267
+ const real = byCallId.get(origin.call_id);
268
+ return {
269
+ call_id: origin.call_id,
270
+ exchange_id: origin.exchange_id,
271
+ name: origin.name,
272
+ kind: origin.kind,
273
+ category: origin.category.category,
274
+ category_source: origin.category.source,
275
+ ...(origin.category.command ? { category_command: origin.category.command } : {}),
276
+ verified: real ? real.outcome !== 'not_executed' : false,
277
+ status: real?.status ?? null,
278
+ error: real?.error ?? null,
279
+ match_score: real?.match_score ?? null,
280
+ match_basis: real?.match_basis ?? null,
281
+ source: real?.source ?? null,
282
+ kernel_confirmed: real?.kernel_confirmed === 1,
283
+ tier: real?.tier ?? null,
284
+ reported_check: real?.reported_check ?? null,
285
+ descendant_count: real?.descendant_count ?? 0,
286
+ // Everything the "proposed vs observed" table needs for this row:
287
+ // what the model asked for, and the process that actually ran.
288
+ output_index: origin.output_index,
289
+ proposed: origin.proposed ?? null,
290
+ // The proposed command in plain English, from the same rules Sandbox
291
+ // evidence uses (exec-narrative.mjs). Rule-only here: a model fallback
292
+ // would spend on every trace fetch, and the raw command stays beside it.
293
+ description: origin.kind === 'command' ? describeCommand(origin.proposed) : null,
294
+ ...executionFields(real),
295
+ descendants: descendantsByCall.get(origin.call_id) ?? [],
296
+ snapshot: snapshots.get(origin.call_id) ?? null,
297
+ };
298
+ });
299
+ }
300
+
301
+ // Codex requests include a large tool schema. Return recent traces only so the
302
+ // live dashboard stays responsive instead of repeatedly transferring history.
303
+ const sorted = [...grouped.values()].sort((a, b) => b.startedAt.localeCompare(a.startedAt));
304
+ const result = turnId ? sorted : sorted.slice(0, includeHistory ? 100 : 10);
305
+ // Every request resends the whole conversation, so each earlier item comes
306
+ // back once per later request: a long Claude Code session made one prompt
307
+ // tens of MB, fetched every few seconds. An item is sent in full once; a
308
+ // repeat keeps only where it sits and names the item that has the rest
309
+ // (content_of).
310
+ for (const trace of result) {
311
+ const first = new Map();
312
+ trace.evidence = trace.evidence.map((item) => {
313
+ const key = `${item.kind}\0${item.label}\0${item.content ?? item.preview ?? ''}`;
314
+ if (!first.has(key)) { first.set(key, item.id); return item; }
315
+ 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) };
316
+ });
317
+ }
318
+ for(const trace of result) {
319
+ if(turnId && ['open','running'].includes(trace.status))trace.captureComplete=false;
320
+ trace.captureHealth=await db.captureHealth?.(trace.sandboxId ?? trace.id,
321
+ {since:Date.parse(trace.startedAt),until:Date.parse(trace.endedAt)});
322
+ }
323
+ return result;
324
+ }
@@ -0,0 +1,92 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { readTraces } from './trace-view.mjs';
4
+
5
+ test('reused call IDs stay session-scoped and ambiguous same-session IDs stay unavailable',async()=>{
6
+ const make=(id,session)=>({span_id:id,trace_id:id,session_id:session,provider:'test',timestamp:'2026-11-03T00:00:00Z',promptTitle:'test',request:{payload:{input:[]}},response:{payload:{output:[{type:'function_call',call_id:'reused',name:id,arguments:'{}'}]}}});
7
+ const rows=[make('one','a'),make('two','b')];
8
+ const db={exchangeRows:async()=>rows,divergence:async()=>[],descendants:async()=>[],snapshotsForCalls:async()=>new Map(),toolCallResult:async(id,{sessionId})=>({output:sessionId})};
9
+ let traces=await readTraces(db,{includeHistory:true});
10
+ assert.equal(JSON.parse(traces[0].events.find(e=>e.title==='Tool result: one').raw).output,'a');
11
+ assert.equal(JSON.parse(traces[1].events.find(e=>e.title==='Tool result: two').raw).output,'b');
12
+ rows[1].session_id='a';traces=await readTraces(db,{includeHistory:true});
13
+ assert.ok(traces.every(t=>!t.events.some(e=>e.title.startsWith('Tool result:'))));
14
+ });
15
+
16
+ test('synthesizes terminal tool results for proposed calls with no subsequent exchange', async () => {
17
+ const fakeRow = {
18
+ span_id: 'span-1',
19
+ trace_id: 'trace-1',
20
+ session_id: 'rtp-12345678123456781234567812345678',
21
+ provider: 'claude-code',
22
+ timestamp: '2026-10-28T12:00:00.000Z',
23
+ promptTitle: 'test prompt',
24
+ request: {
25
+ payload: {
26
+ model: 'claude-3-5-sonnet',
27
+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'run exit 7' }] }]
28
+ }
29
+ },
30
+ response: {
31
+ payload: {
32
+ output: [
33
+ {
34
+ type: 'function_call',
35
+ call_id: 'toolu_term_1',
36
+ name: 'Bash',
37
+ arguments: JSON.stringify({ command: 'exit 7' })
38
+ }
39
+ ]
40
+ }
41
+ }
42
+ };
43
+
44
+ const fakeDb = {
45
+ exchangeRows: async () => [fakeRow],
46
+ divergence: async () => [],
47
+ descendants: async () => [],
48
+ snapshotsForCalls: async () => new Map(),
49
+ toolCallResult: async (callId) => {
50
+ if (callId === 'toolu_term_1') {
51
+ return { call_id: 'toolu_term_1', is_error: true, exit_code: 7, output: 'Process exited with code 7' };
52
+ }
53
+ return null;
54
+ }
55
+ };
56
+
57
+ const traces = await readTraces(fakeDb, { includeHistory: true });
58
+ assert.equal(traces.length, 1);
59
+ const trace = traces[0];
60
+
61
+ const resultEvent = trace.events.find((e) => e.title.startsWith('Tool result:') && e.raw.includes('toolu_term_1'));
62
+ assert.ok(resultEvent, 'terminal tool result event was synthesized into trace.events');
63
+ const parsed = JSON.parse(resultEvent.raw);
64
+ assert.equal(parsed.call_id, 'toolu_term_1');
65
+ assert.equal(parsed.exit_code, 7);
66
+ assert.equal(parsed.is_error, true);
67
+ });
68
+
69
+ test('toolResultsFromTranscript extracts tool results from user messages', async () => {
70
+ const { toolResultsFromTranscript } = await import('./claude-code-adapter.mjs');
71
+ const lines = [
72
+ { type: 'user', message: { content: [{ type: 'text', text: 'hello' }] } },
73
+ { type: 'assistant', message: { id: 'msg_1', content: [{ type: 'tool_use', id: 'call_99', name: 'Bash', input: { command: 'ls' } }] } },
74
+ { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'call_99', content: 'file.txt', is_error: false }] } }
75
+ ];
76
+ const results = toolResultsFromTranscript(lines);
77
+ assert.equal(results.size, 1);
78
+ assert.deepEqual(results.get('call_99'), {
79
+ type: 'function_call_output',
80
+ call_id: 'call_99',
81
+ output: 'file.txt'
82
+ });
83
+ });
84
+
85
+ test('selected-run detail keeps full prompt/settings and signals the 2000-exchange limit',async()=>{
86
+ const rows=Array.from({length:2001},(_,i)=>({span_id:`e${i}`,trace_id:'t',session_id:'host',provider:'test',timestamp:new Date(1000+i).toISOString(),promptTitle:'full prompt',
87
+ request:{payload:{model:'m',instructions:'system',tools:[{name:'tool'}],temperature:0,input:[{role:'user',content:'full prompt'}]}},response:{payload:{output:[]}}}));
88
+ const db={turnExchanges:async()=>rows,exchangeRows:async()=>[],divergence:async()=>[],descendants:async()=>[],snapshotsForCalls:async()=>new Map()};
89
+ const [trace]=await readTraces(db,{turnId:'t',includeHistory:true});
90
+ assert.equal(trace.captureComplete,false);assert.equal(trace.requests.length,2000);assert.equal(trace.promptRaw,'full prompt');
91
+ assert.equal(trace.comparisonRequests[0].instructions,'system');assert.equal(trace.comparisonRequests[0].tools[0].name,'tool');
92
+ });
@@ -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
+ });
@@ -0,0 +1,7 @@
1
+ // The coding agents a sandbox terminal can start (`raytrace connect --claude`
2
+ // or `--codex`): their names, and their command lines inside the sandbox,
3
+ // without approval prompts, because the sandbox is what contains them.
4
+ export const AGENTS = {
5
+ claude: { name: 'Claude Code', command: 'claude --dangerously-skip-permissions' },
6
+ codex: { name: 'Codex', command: 'codex --dangerously-bypass-approvals-and-sandbox' },
7
+ };
@@ -0,0 +1,57 @@
1
+ // Shared client for RayTrace's cloud API (https://api.raytracer.si;
2
+ // RAYTRACE_API_URL points elsewhere). Requests carry your `raytrace auth
3
+ // login` token; RAYTRACE_API_KEY overrides it for a server running without
4
+ // accounts (development).
5
+ import { accessToken, consumeIdleNotice, login } from './auth.mjs';
6
+ import { readConfig } from './config.mjs';
7
+ import { interactive } from './prompt.mjs';
8
+
9
+ const say = (line = '') => console.log(line);
10
+ const API = 'https://api.raytracer.si';
11
+
12
+ export const unreachable = (url) => new Error(`Cannot reach RayTrace at ${url.origin}. Check your connection; `
13
+ + 'networks that inspect HTTPS (some company Wi-Fi) may block it.');
14
+
15
+ export class ApiError extends Error {
16
+ constructor(message, { status = null, data = {} } = {}) {
17
+ super(message);
18
+ this.name = 'ApiError';
19
+ this.status = status;
20
+ this.data = data;
21
+ }
22
+ }
23
+
24
+ /** True when a development API key overrides the signed-in account. */
25
+ export function hasApiKeyOverride() {
26
+ return Boolean(process.env.RAYTRACE_API_KEY || readConfig().RAYTRACE_API_KEY);
27
+ }
28
+
29
+ export async function api({ autoLogin = true } = {}) {
30
+ const config = readConfig();
31
+ const url = process.env.RAYTRACE_API_URL || config.RAYTRACE_API_URL || API;
32
+ let key = process.env.RAYTRACE_API_KEY || config.RAYTRACE_API_KEY || await accessToken();
33
+ if (!key) {
34
+ if (!autoLogin || !interactive()) throw new Error('Not signed in. Run: raytrace auth login');
35
+ say(consumeIdleNotice()
36
+ ? 'You have not used RayTrace cloud for 2 days, so you need to sign in again.'
37
+ : 'You are not signed in to RayTrace yet.');
38
+ await login();
39
+ key = await accessToken();
40
+ if (!key) throw new Error('Not signed in. Run: raytrace auth login');
41
+ say();
42
+ }
43
+ return { url: new URL(url), key };
44
+ }
45
+
46
+ export async function call(method, path, { body, headers = {}, autoLogin = true } = {}) {
47
+ const { url, key } = await api({ autoLogin });
48
+ let response;
49
+ try {
50
+ response = await fetch(new URL(path, url), { method, body, headers: { authorization: `Bearer ${key}`, ...headers } });
51
+ } catch {
52
+ throw unreachable(url);
53
+ }
54
+ const data = await response.json().catch(() => ({}));
55
+ if (!response.ok) throw new ApiError(data.error || `HTTP ${response.status}`, { status: response.status, data });
56
+ return data;
57
+ }