@skillstech/thunderlang 1.0.4 → 1.2.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2568 -462
  4. package/dist/index.cjs +7562 -5084
  5. package/dist/learn.cjs +16994 -8339
  6. package/intent-graph.schema.json +11 -0
  7. package/package.json +6 -2
  8. package/src/cli-home.mjs +242 -0
  9. package/src/cli.mjs +241 -89
  10. package/src/codegen.mjs +145 -55
  11. package/src/conformance.mjs +15 -6
  12. package/src/core/check.mjs +725 -0
  13. package/src/core/cli.mjs +184 -0
  14. package/src/core/diagnostics.mjs +82 -0
  15. package/src/core/engine-core.mjs +572 -0
  16. package/src/core/engine-values.mjs +1054 -0
  17. package/src/core/engine-worker.mjs +15 -0
  18. package/src/core/engine.mjs +63 -0
  19. package/src/core/format.mjs +20 -0
  20. package/src/core/from-python.mjs +645 -0
  21. package/src/core/index.mjs +39 -0
  22. package/src/core/lexer.mjs +115 -0
  23. package/src/core/parser.mjs +742 -0
  24. package/src/core/project.mjs +177 -0
  25. package/src/core/round-trip.mjs +150 -0
  26. package/src/core/runtime-python.mjs +801 -0
  27. package/src/core/runtime-typescript.mjs +119 -0
  28. package/src/core/target-python.mjs +487 -0
  29. package/src/core/target-typescript.mjs +466 -0
  30. package/src/core/typescript-run.mjs +114 -0
  31. package/src/core.d.ts +5 -2
  32. package/src/core.mjs +5 -2
  33. package/src/data-schema.mjs +8 -1
  34. package/src/emit.mjs +1 -1
  35. package/src/evidence.mjs +1 -1
  36. package/src/expr.mjs +81 -4
  37. package/src/form-words.mjs +2 -0
  38. package/src/index.d.ts +8 -1
  39. package/src/index.mjs +5 -1
  40. package/src/intent-schema.mjs +1 -0
  41. package/src/learn-lessons.mjs +245 -1
  42. package/src/learn.d.mts +8 -0
  43. package/src/learn.mjs +40 -4
  44. package/src/mcp.mjs +23 -0
  45. package/src/meaning.mjs +45 -6
  46. package/src/model.d.mts +7 -3
  47. package/src/model.mjs +19 -6
  48. package/src/money.d.mts +18 -0
  49. package/src/money.mjs +124 -0
  50. package/src/plain-contract.mjs +18 -2
  51. package/src/read-level.mjs +146 -0
  52. package/src/read.d.mts +11 -0
  53. package/src/read.mjs +40 -6
  54. package/src/review-comment.d.mts +16 -0
  55. package/src/review-comment.mjs +145 -0
  56. package/src/say-less.mjs +1432 -0
  57. package/src/system.mjs +153 -44
  58. package/src/target-cs.mjs +39 -34
  59. package/src/target-elixir.mjs +40 -30
  60. package/src/target-go.mjs +41 -36
  61. package/src/target-java.mjs +34 -27
  62. package/src/target-kotlin.mjs +43 -35
  63. package/src/target-py.mjs +57 -55
  64. package/src/target-result.d.mts +48 -0
  65. package/src/target-result.mjs +112 -0
  66. package/src/target-rust.mjs +42 -38
  67. package/src/target-scala.mjs +45 -35
  68. package/src/target-ts.mjs +37 -45
  69. package/src/target-types.mjs +41 -5
  70. package/src/target-util.mjs +55 -2
  71. package/src/term.mjs +89 -0
  72. package/src/trace-cli.mjs +58 -0
  73. package/src/trace-fs.mjs +76 -0
  74. package/src/trace.mjs +261 -0
  75. package/src/translate.d.mts +3 -0
  76. package/src/translate.mjs +62 -32
  77. package/src/try-cli.mjs +225 -0
  78. package/src/why-cli.mjs +41 -0
  79. package/src/why.d.mts +38 -0
  80. package/src/why.mjs +613 -0
  81. package/src/write-steps.mjs +22 -5
package/src/why.mjs ADDED
@@ -0,0 +1,613 @@
1
+ // Thunder Why: an AI agent's run, explained in plain words (docs/why.md).
2
+ //
3
+ // Input: the record an agent run leaves behind, as OpenTelemetry spans. Accepted shapes:
4
+ // - an OTLP/JSON export ({ resourceSpans: [...] }), or one such object per line (the collector's file exporter);
5
+ // - the Python SDK's console exporter (pretty JSON objects one after another, or a JSON array of them);
6
+ // - a JSON array of spans with `attributes` as a plain object.
7
+ // Spans are read with the OpenTelemetry GenAI conventions (gen_ai.*), the OpenInference conventions
8
+ // (openinference.span.kind, used by Phoenix and others), and the plain HTTP and database conventions.
9
+ //
10
+ // Output: what the agent was asked, what it did step by step, what it changed, what went wrong and what happened
11
+ // just before, and how sure Thunder is. Nothing is run and no AI is used: every sentence comes from the record,
12
+ // and each step cites its span. Values that look like secrets are hidden.
13
+
14
+ // ── Reading the record ────────────────────────────────────────────────────────────────────────────────────────
15
+
16
+ /** Split text holding JSON objects one after another (pretty-printed or not) into the objects. */
17
+ function jsonObjects(text) {
18
+ const out = [];
19
+ let depth = 0, start = -1, inStr = false, esc = false;
20
+ for (let i = 0; i < text.length; i++) {
21
+ const c = text[i];
22
+ if (inStr) { if (esc) esc = false; else if (c === '\\') esc = true; else if (c === '"') inStr = false; continue; }
23
+ if (c === '"') inStr = true;
24
+ else if (c === '{') { if (depth === 0) start = i; depth++; }
25
+ else if (c === '}' && depth > 0) { depth--; if (depth === 0) { try { out.push(JSON.parse(text.slice(start, i + 1))); } catch { /* not JSON */ } } }
26
+ }
27
+ return out;
28
+ }
29
+
30
+ function parseInput(input) {
31
+ if (typeof input !== 'string') return Array.isArray(input) ? input : [input];
32
+ const t = input.trim();
33
+ if (!t) return [];
34
+ try { const v = JSON.parse(t); return Array.isArray(v) ? v : [v]; } catch { return jsonObjects(t); }
35
+ }
36
+
37
+ const otlpValue = (v) => {
38
+ if (v == null || typeof v !== 'object') return v;
39
+ if ('stringValue' in v) return v.stringValue;
40
+ if ('intValue' in v) return Number(v.intValue);
41
+ if ('doubleValue' in v) return Number(v.doubleValue);
42
+ if ('boolValue' in v) return v.boolValue;
43
+ if (v.arrayValue) return (v.arrayValue.values || []).map(otlpValue);
44
+ if (v.kvlistValue) return Object.fromEntries((v.kvlistValue.values || []).map((a) => [a.key, otlpValue(a.value)]));
45
+ return undefined;
46
+ };
47
+ const attrsOf = (x) => (Array.isArray(x) ? Object.fromEntries(x.map((a) => [a.key, otlpValue(a.value)])) : (x && typeof x === 'object' ? x : {}));
48
+
49
+ const nanos = (v) => {
50
+ if (v == null) return null;
51
+ if (typeof v === 'number') return v > 1e15 ? v : v * 1e6; // already nanoseconds, or milliseconds
52
+ if (/^\d+$/.test(String(v))) return Number(v);
53
+ const ms = Date.parse(v);
54
+ return Number.isFinite(ms) ? ms * 1e6 : null;
55
+ };
56
+ const hexId = (v) => (v == null ? null : String(v).replace(/^0x/i, '').toLowerCase() || null);
57
+
58
+ /** One raw span (any accepted shape) as { id, parent, trace, name, start, end, attrs, status, events }. */
59
+ function rawSpan(sp) {
60
+ const ctx = sp.context || {};
61
+ const statusCode = sp.status?.code ?? sp.status?.status_code ?? sp.status?.statusCode;
62
+ return {
63
+ id: hexId(sp.spanId ?? sp.span_id ?? ctx.span_id ?? sp.id),
64
+ parent: hexId(sp.parentSpanId ?? sp.parent_span_id ?? sp.parent_id ?? sp.parentId) || null,
65
+ trace: hexId(sp.traceId ?? sp.trace_id ?? ctx.trace_id),
66
+ name: String(sp.name ?? ''),
67
+ start: nanos(sp.startTimeUnixNano ?? sp.start_time ?? sp.startTime),
68
+ end: nanos(sp.endTimeUnixNano ?? sp.end_time ?? sp.endTime),
69
+ attrs: attrsOf(sp.attributes),
70
+ failed: statusCode === 2 || /ERROR/i.test(String(statusCode ?? '')),
71
+ statusMessage: sp.status?.message ?? sp.status?.description ?? null,
72
+ events: (sp.events || []).map((e) => ({ name: e.name, attrs: attrsOf(e.attributes) })),
73
+ };
74
+ }
75
+
76
+ function collectSpans(docs) {
77
+ const out = [];
78
+ for (const d of docs) {
79
+ if (!d || typeof d !== 'object') continue;
80
+ if (Array.isArray(d.resourceSpans)) {
81
+ for (const rs of d.resourceSpans) {
82
+ const service = attrsOf(rs.resource?.attributes)['service.name'];
83
+ for (const ss of [...(rs.scopeSpans || []), ...(rs.instrumentationLibrarySpans || [])]) {
84
+ for (const sp of ss.spans || []) out.push({ ...rawSpan(sp), service });
85
+ }
86
+ }
87
+ } else if (Array.isArray(d.spans)) out.push(...collectSpans(d.spans));
88
+ else if (d.name != null && (d.spanId || d.span_id || d.context || d.id)) out.push({ ...rawSpan(d), service: attrsOf(d.resource?.attributes)['service.name'] });
89
+ }
90
+ return out;
91
+ }
92
+
93
+ // ── Secrets and long values ───────────────────────────────────────────────────────────────────────────────────
94
+
95
+ const SECRET_KEY = /pass(word|wd)?$|secret|token|api[_-]?key|authori[sz]ation|^auth$|cookie|credential|private[_-]?key|card[_-]?number|cvv|ssn/i;
96
+ const SECRET_VALUE = /\b(sk-[A-Za-z0-9_-]{8,}|ghp_[A-Za-z0-9]{10,}|xox[abp]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+)|Bearer\s+[A-Za-z0-9._~+/=-]{8,}/g;
97
+ const HIDDEN = '(hidden)';
98
+
99
+ function hide(v, key = '') {
100
+ if (key && SECRET_KEY.test(key)) return HIDDEN;
101
+ if (typeof v === 'string') return v.replace(SECRET_VALUE, HIDDEN);
102
+ if (Array.isArray(v)) return v.map((x) => hide(x));
103
+ if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, hide(x, k)]));
104
+ return v;
105
+ }
106
+ const maybeJson = (v) => { if (typeof v !== 'string') return v; const t = v.trim(); if (!/^[[{]/.test(t)) return v; try { return JSON.parse(t); } catch { return v; } };
107
+ const short = (s, n = 90) => { s = String(s).replace(/\s+/g, ' ').trim(); return s.length > n ? `${s.slice(0, n - 1)}…` : s; };
108
+
109
+ /** Arguments as "order_id 1042, amount 40" (at most four, secrets hidden). */
110
+ function argText(v) {
111
+ v = hide(maybeJson(v));
112
+ if (v == null || v === '') return '';
113
+ if (typeof v !== 'object' || Array.isArray(v)) return short(typeof v === 'string' ? v : JSON.stringify(v), 70);
114
+ const ks = Object.keys(v);
115
+ const parts = ks.slice(0, 4).map((k) => `${k} ${short(typeof v[k] === 'string' ? v[k] : JSON.stringify(v[k]), 30)}`);
116
+ return parts.join(', ') + (ks.length > 4 ? `, and ${ks.length - 4} more` : '');
117
+ }
118
+
119
+ // ── What each span is ─────────────────────────────────────────────────────────────────────────────────────────
120
+
121
+ /** Text of the messages in gen_ai.input.messages / gen_ai.output.messages (or OpenInference's flattened form). */
122
+ function messagesOf(a, which) {
123
+ const raw = maybeJson(a[`gen_ai.${which}.messages`]);
124
+ const out = [];
125
+ if (Array.isArray(raw)) {
126
+ for (const m of raw) {
127
+ const text = typeof m.content === 'string' ? m.content
128
+ : (m.parts || (Array.isArray(m.content) ? m.content : [])).filter((p) => p.type === 'text').map((p) => p.content ?? p.text).join(' ');
129
+ const tools = [...(m.parts || []).filter((p) => p.type === 'tool_call').map((p) => p.name), ...(m.tool_calls || []).map((t) => t.function?.name ?? t.name)].filter(Boolean);
130
+ out.push({ role: m.role, text: text || '', tools });
131
+ }
132
+ return out;
133
+ }
134
+ const oi = which === 'input' ? 'llm.input_messages' : 'llm.output_messages';
135
+ for (let i = 0; i < 50; i++) {
136
+ const role = a[`${oi}.${i}.message.role`];
137
+ if (role == null) break;
138
+ const tools = [];
139
+ for (let j = 0; j < 20 && a[`${oi}.${i}.message.tool_calls.${j}.tool_call.function.name`] != null; j++) tools.push(a[`${oi}.${i}.message.tool_calls.${j}.tool_call.function.name`]);
140
+ out.push({ role, text: String(a[`${oi}.${i}.message.content`] ?? ''), tools });
141
+ }
142
+ return out;
143
+ }
144
+
145
+ // ── What a step does to the world ─────────────────────────────────────────────────────────────────────────────
146
+ // Kinds, most serious first. A step's effect comes from the strongest evidence the record has:
147
+ // declared the tool says so (MCP annotations from --tools, or a thunder.effect attribute on the span)
148
+ // method the HTTP request method operation the database operation
149
+ // name the tool's name: every word counts, and the most serious one wins (get_and_delete deletes)
150
+ export const EFFECT_KINDS = ['money', 'delete', 'send', 'create', 'change', 'read'];
151
+ const VERBS = {
152
+ money: 'charge pay payment refund transfer payout withdraw deposit purchase buy checkout bill',
153
+ delete: 'delete remove drop purge destroy erase truncate wipe unlink rm del',
154
+ send: 'send email mail notify message sms text tweet reply publish broadcast page post dm alert',
155
+ create: 'create add insert new make book reserve schedule upload register submit open issue generate',
156
+ change: 'update set edit modify change write save store cancel approve reject close assign grant revoke rename move archive restore reset deploy merge push apply patch enable disable mark replace upsert',
157
+ read: 'get list search find lookup look fetch read query retrieve check view show describe count load browse inspect peek verify validate calculate compute estimate summarize download scan',
158
+ };
159
+ const VERB_KIND = new Map();
160
+ for (const k of [...EFFECT_KINDS].reverse()) for (const v of VERBS[k].split(' ')) VERB_KIND.set(v, k);
161
+
162
+ /** MCP tool annotations (from --tools) as an effect kind, or null when they say nothing. */
163
+ function declaredFromAnnotations(ann) {
164
+ if (!ann || typeof ann !== 'object') return null;
165
+ if (ann.readOnlyHint === true) return 'read';
166
+ if (ann.readOnlyHint === false || ann.destructiveHint != null) return ann.destructiveHint === false ? 'change' : 'delete'; // the MCP default for a tool that writes is "may be destructive"
167
+ return null;
168
+ }
169
+
170
+ /** What this step does to the world: { effect, basis, resource }. */
171
+ function effectOf(s, tools) {
172
+ if (s.kind === 'model' || s.kind === 'agent') return { effect: 'none', basis: 'kind' };
173
+ if (s.declared && EFFECT_KINDS.includes(s.declared)) return { effect: s.declared, basis: 'declared' };
174
+ if (s.kind === 'tool') {
175
+ const d = declaredFromAnnotations(tools?.get(s.tool));
176
+ if (d) return { effect: d, basis: 'declared' };
177
+ }
178
+ if (s.kind === 'retrieve') return { effect: 'read', basis: 'kind' };
179
+ if (s.kind === 'http') {
180
+ const m = String(s.method).toUpperCase();
181
+ const kind = { GET: 'read', HEAD: 'read', OPTIONS: 'read', POST: 'change', PUT: 'change', PATCH: 'change', DELETE: 'delete' }[m];
182
+ return { effect: kind ?? 'unknown', basis: 'method' };
183
+ }
184
+ if (s.kind === 'db') {
185
+ const op = String(s.dbOp || '').toUpperCase();
186
+ if (/^(SELECT|FIND|GET|SCAN|QUERY|COUNT|AGGREGATE|SHOW|DESCRIBE|EXPLAIN|MGET|HGET|HGETALL|EXISTS)/.test(op)) return { effect: 'read', basis: 'operation' };
187
+ if (/^(DELETE|DROP|TRUNCATE|DEL\b|DEL$|HDEL|UNLINK)/.test(op)) return { effect: 'delete', basis: 'operation' };
188
+ if (/^(INSERT|CREATE|LPUSH|RPUSH|SADD|XADD)/.test(op)) return { effect: 'create', basis: 'operation' };
189
+ if (/^(UPDATE|UPSERT|MERGE|REPLACE|ALTER|SET|HSET|PUT|INCR|DECR)/.test(op)) return { effect: 'change', basis: 'operation' };
190
+ return { effect: 'unknown', basis: 'operation' };
191
+ }
192
+ if (s.kind === 'tool') {
193
+ const words = String(s.tool).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
194
+ const kinds = words.map((w) => VERB_KIND.get(w)).filter(Boolean);
195
+ const worst = EFFECT_KINDS.find((k) => kinds.includes(k));
196
+ return { effect: worst ?? 'unknown', basis: 'name' };
197
+ }
198
+ return { effect: 'unknown', basis: 'kind' };
199
+ }
200
+
201
+ /** A raw span as a step: what kind of thing happened, with the facts the story needs. */
202
+ function stepOf(r, tools) {
203
+ const a = r.attrs;
204
+ const op = String(a['gen_ai.operation.name'] ?? '').toLowerCase();
205
+ const oi = String(a['openinference.span.kind'] ?? '').toUpperCase();
206
+ const tool = a['gen_ai.tool.name'] ?? a['tool.name'] ?? (oi === 'TOOL' ? r.name : null);
207
+ const method = a['http.request.method'] ?? a['http.method'];
208
+ const db = a['db.system.name'] ?? a['db.system'];
209
+ let kind = 'other';
210
+ if (op === 'invoke_agent' || op === 'create_agent' || oi === 'AGENT') kind = 'agent';
211
+ else if (op === 'execute_tool' || oi === 'TOOL' || tool) kind = 'tool';
212
+ else if (['chat', 'text_completion', 'generate_content', 'embeddings'].includes(op) || oi === 'LLM' || oi === 'EMBEDDING' || a['gen_ai.request.model'] || a['llm.model_name']) kind = 'model';
213
+ else if (oi === 'RETRIEVER') kind = 'retrieve';
214
+ else if (method) kind = 'http';
215
+ else if (db) kind = 'db';
216
+ const s = {
217
+ id: r.id, parent: r.parent, trace: r.trace, name: r.name, start: r.start, end: r.end, service: r.service ?? null,
218
+ durationMs: r.start != null && r.end != null && r.end >= r.start ? (r.end - r.start) / 1e6 : null,
219
+ kind,
220
+ };
221
+ if (a['thunder.effect'] != null) s.declared = String(a['thunder.effect']).toLowerCase();
222
+ if (kind === 'agent') s.agent = a['gen_ai.agent.name'] ?? (r.name.replace(/^invoke_agent\s*/i, '') || r.name);
223
+ if (kind === 'tool') { s.tool = String(tool ?? r.name.replace(/^execute_tool\s*/i, '')); s.args = a['gen_ai.tool.call.arguments'] ?? a['tool.parameters'] ?? a['input.value']; s.result = a['gen_ai.tool.call.result'] ?? a['output.value']; }
224
+ if (kind === 'model') {
225
+ s.model = a['gen_ai.response.model'] ?? a['gen_ai.request.model'] ?? a['llm.model_name'] ?? null;
226
+ const outMsgs = messagesOf(a, 'output');
227
+ s.decidedTools = [...new Set(outMsgs.flatMap((m) => m.tools))];
228
+ s.said = outMsgs.map((m) => m.text).filter(Boolean).join(' ') || (typeof a['output.value'] === 'string' && !/^[[{]/.test(a['output.value'].trim()) ? a['output.value'] : '');
229
+ const ins = messagesOf(a, 'input').filter((m) => m.role === 'user' && m.text);
230
+ s.ask = ins.length ? ins[ins.length - 1].text : null;
231
+ const fr = a['gen_ai.response.finish_reasons'];
232
+ s.finish = Array.isArray(fr) ? fr[0] : fr ?? null;
233
+ }
234
+ if (kind === 'agent' && typeof a['input.value'] === 'string') s.ask = a['input.value'];
235
+ if (kind === 'http') {
236
+ s.method = String(method).toUpperCase();
237
+ s.url = a['url.full'] ?? a['http.url'] ?? [a['server.address'] ?? a['net.peer.name'] ?? a['http.host'], a['url.path'] ?? a['http.target']].filter(Boolean).join('') ?? null;
238
+ s.status = a['http.response.status_code'] ?? a['http.status_code'] ?? null;
239
+ }
240
+ if (kind === 'db') {
241
+ const q = a['db.query.text'] ?? a['db.statement'];
242
+ s.db = String(db);
243
+ s.dbOp = a['db.operation.name'] ?? a['db.operation'] ?? (typeof q === 'string' ? q.trim().split(/\s+/)[0] : null);
244
+ s.table = a['db.collection.name'] ?? a['db.sql.table'] ?? (typeof q === 'string' ? (q.match(/\b(?:from|into|update|table)\s+["`]?([\w.]+)/i) || [])[1] : null) ?? null;
245
+ }
246
+ // Failure: the span's status, an error.type, or (for a request) a 4xx/5xx answer.
247
+ const exc = r.events.find((e) => e.name === 'exception');
248
+ const httpBad = kind === 'http' && Number(s.status) >= 400;
249
+ s.failed = r.failed || a['error.type'] != null || !!exc || httpBad;
250
+ if (s.failed) {
251
+ s.error = {
252
+ type: exc?.attrs['exception.type'] ?? a['error.type'] ?? null,
253
+ message: exc?.attrs['exception.message'] ?? r.statusMessage ?? null,
254
+ status: s.status ?? a['http.response.status_code'] ?? null,
255
+ };
256
+ }
257
+ if (kind === 'model' && !s.failed && ['length', 'max_tokens', 'content_filter'].includes(String(s.finish))) s.warning = String(s.finish);
258
+ Object.assign(s, effectOf(s, tools));
259
+ return s;
260
+ }
261
+
262
+ // ── Errors in plain words ─────────────────────────────────────────────────────────────────────────────────────
263
+
264
+ /**
265
+ * An error as plain words: { what, next? }. `what` never contains codes or jargon; the original stays in the
266
+ * step's details.
267
+ */
268
+ export function plainError({ type, message, status, finish } = {}) {
269
+ const t = String(type ?? ''), m = String(message ?? ''), both = `${t} ${m}`;
270
+ const st = Number(status);
271
+ if (finish === 'length' || finish === 'max_tokens') return { what: "The AI's answer was cut off: it reached its length limit.", next: 'Allow a longer answer, or ask for a shorter one.' };
272
+ if (finish === 'content_filter') return { what: "The AI's answer was held back by a safety filter.", next: 'Look at what was asked; rephrase it if the filter was wrong.' };
273
+ if (/time ?out|timed out|deadline exceeded|ETIMEDOUT/i.test(both) || st === 408 || st === 504) return { what: 'It waited too long for an answer and gave up.', next: 'Check that the service is up and fast enough, or allow a longer wait.' };
274
+ if (/ECONNREFUSED|connection ?refused|ConnectionError|ConnectError|ENOTFOUND|getaddrinfo|name or service not known|unreachable|ECONNRESET|connection reset/i.test(both)) return { what: "It couldn't reach the service.", next: 'Check that the service is running and its address is right.' };
275
+ if (st === 401 || /unauthori[sz]ed|invalid api key|authentication/i.test(both)) return { what: "The service didn't accept its sign-in.", next: 'Check the key or sign-in it uses.' };
276
+ if (st === 403 || /forbidden|permission denied|PermissionError|not allowed|access denied/i.test(both)) return { what: "It wasn't allowed to do that.", next: 'Check what this agent is permitted to do.' };
277
+ if (st === 404 || /FileNotFoundError|ENOENT|no such file/i.test(both)) return { what: "What it asked for wasn't there.", next: 'Check the name or number it used.' };
278
+ if (st === 409 || /conflict/i.test(both)) return { what: 'It clashed with a change made at the same time.', next: 'Try again once the other change is done.' };
279
+ if (st === 429 || /rate.?limit|too many requests|quota/i.test(both)) return { what: 'It asked too often, and the service told it to slow down.', next: 'Wait and try again, or raise the limit.' };
280
+ if (st >= 500 && st < 600) return { what: 'The service had a problem on its side.', next: "Look at the service's own logs for this time." };
281
+ if (st === 400 || st === 422 || /validation|invalid (argument|input|request|parameter)/i.test(both)) return { what: "The service didn't accept what it sent.", next: 'Compare what was sent with what the service expects.' };
282
+ if (/KeyError/.test(t)) return { what: `A name it looked for wasn't there${m ? `: ${short(m.replace(/^['"]|['"]$/g, ''), 40)}` : ''}.`, next: 'Check that the data has that name.' };
283
+ if (/NoneType|undefined is not|of undefined|of null|null pointer|NullPointer|nil pointer/i.test(both)) return { what: 'A value it needed was empty.', next: 'Find where that value should have been set.' };
284
+ if (/ZeroDivision|divide by zero|division by zero/i.test(both)) return { what: 'It tried to divide by zero.', next: 'Check the number it divided by.' };
285
+ if (/JSONDecodeError|Unexpected token|not valid JSON|invalid json/i.test(both)) return { what: "What came back wasn't in the expected form.", next: 'Look at what the service or the AI actually returned.' };
286
+ if (/ValueError|TypeError|invalid/i.test(both)) return { what: "A value wasn't in the form it expected.", next: 'Look at the value in the details.' };
287
+ return { what: 'Something went wrong.', next: null };
288
+ }
289
+
290
+ // ── Building the story ────────────────────────────────────────────────────────────────────────────────────────
291
+
292
+ const human = (name) => String(name).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
293
+ const hostPath = (u) => { try { const x = new URL(u); return `${x.host}${x.pathname === '/' ? '' : x.pathname}`; } catch { return String(u ?? ''); } };
294
+ const quote = (s, n = 90) => `"${short(hide(String(s)), n)}"`;
295
+ const secs = (ms) => (ms == null ? null : ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(ms < 10000 ? 1 : 0)} seconds`);
296
+ const MEANINGFUL = new Set(['agent', 'model', 'tool', 'http', 'db', 'retrieve']);
297
+
298
+ /** What a step did, as one plain sentence without its outcome. */
299
+ function doing(s) {
300
+ switch (s.kind) {
301
+ case 'agent': return `Handed the work to the agent "${s.agent}"`;
302
+ case 'model': {
303
+ const who = s.model ? `the AI (${s.model})` : 'the AI';
304
+ if (s.decidedTools?.length) return `Asked ${who}, which decided to use ${s.decidedTools.map((t) => `"${t}"`).join(' and ')}`;
305
+ if (s.said) return `Asked ${who}, which answered ${quote(s.said, 70)}`;
306
+ return `Asked ${who}`;
307
+ }
308
+ case 'tool': { const args = argText(s.args); return `Used "${s.tool}"${args ? ` with ${args}` : ''}`; }
309
+ case 'http': return `Called ${s.method} ${hostPath(s.url) || s.name}`;
310
+ case 'db': return `Asked the database (${s.db}) to ${String(s.dbOp || 'run a query').toUpperCase()}${s.table ? ` ${/^(INSERT|UPSERT)/i.test(s.dbOp || '') ? 'into' : /^(SELECT|DELETE)/i.test(s.dbOp || '') ? 'from' : 'on'} ${s.table}` : ''}`;
311
+ case 'retrieve': return 'Searched its documents';
312
+ default: return `Ran "${s.name}"`;
313
+ }
314
+ }
315
+
316
+ /** The outcome of a step (or a group of tries), as a short clause. */
317
+ const lower = (t) => t.charAt(0).toLowerCase() + t.slice(1);
318
+ const ordinal = (n) => ['first', 'second', 'third', 'fourth', 'fifth'][n - 1] ?? `${n}th`;
319
+ function outcome(s) {
320
+ const failedKid = [...(s.children || [])].reverse().find((k) => k.failed);
321
+ if (s.failed && failedKid) return `it stopped because step ${failedKid.n} did not work`;
322
+ if (s.failed) return lower(plainError({ ...s.error, finish: s.finish }).what.replace(/\.$/, ''));
323
+ if (s.warning) return lower(plainError({ finish: s.warning }).what.replace(/\.$/, ''));
324
+ const firstFail = (s.tries || []).find((t) => t.failed);
325
+ if (firstFail) return `it worked on the ${ordinal(s.tries.length)} try (before that, ${lower(plainError(firstFail.error).what.replace(/\.$/, ''))})`;
326
+ if (s.kind === 'http' && s.status != null) return `the service answered ${s.status}`;
327
+ if (s.kind === 'model' || s.kind === 'agent') return '';
328
+ return 'it worked';
329
+ }
330
+ /** A step's name, for short lines: "refund_payment", pay.example.com, the database. */
331
+ const nameOf = (s) => s.kind === 'tool' ? `"${s.tool}"` : s.kind === 'http' ? (() => { try { return new URL(s.url).host; } catch { return s.url || s.name; } })() : s.kind === 'db' ? `the database${s.table ? ` (${s.table})` : ''}` : s.kind === 'model' ? 'the AI' : `"${s.name}"`;
332
+ /** One short line for a step that had trouble but carried on, or a problem: "\"search_web\" worked on the second try; …". */
333
+ function shortTrouble(s) {
334
+ const first = (s.tries || []).find((t) => t.failed);
335
+ if (!s.failed && first) return `${nameOf(s)} worked on the ${ordinal(s.tries.length)} try; the first time, ${lower(plainError(first.error).what)}`;
336
+ return `${nameOf(s)}: ${lower(plainError({ ...s.error, finish: s.finish ?? s.warning }).what)}`;
337
+ }
338
+
339
+ const sentence = (s) => {
340
+ const o = outcome(s);
341
+ const tries = s.tries?.length > 1 && !(s.tries || []).every((t, i, xs) => i === xs.length - 1 || t.failed) ? '' : s.tries?.length > 1 && s.failed ? ` (${s.tries.length} tries)` : '';
342
+ const body = `${doing(s)}${o ? `: ${o}` : ''}${tries}`;
343
+ return /[.!?]["”]$/.test(body) ? body : `${body}.`;
344
+ };
345
+
346
+ /** Steps in time order, keeping the record's nesting but skipping wrappers that say nothing. */
347
+ function arrange(all) {
348
+ const byId = new Map(all.map((s) => [s.id, s]));
349
+ const kids = new Map();
350
+ for (const s of all) {
351
+ const p = s.parent && byId.has(s.parent) ? s.parent : null;
352
+ if (!kids.has(p)) kids.set(p, []);
353
+ kids.get(p).push(s);
354
+ }
355
+ const order = (xs) => xs.sort((x, y) => (x.start ?? 0) - (y.start ?? 0));
356
+ const hasFailedMeaningful = (s) => (kids.get(s.id) || []).some((k) => (MEANINGFUL.has(k.kind) && k.failed) || hasFailedMeaningful(k));
357
+ const build = (pid) => {
358
+ const out = [];
359
+ for (const s of order([...(kids.get(pid) || [])])) {
360
+ const children = build(s.id);
361
+ // A wrapper span (a chain, a function) is shown only if it failed and nothing inside it explains why.
362
+ if (!MEANINGFUL.has(s.kind) && !(s.failed && !hasFailedMeaningful(s))) out.push(...children);
363
+ else out.push({ ...s, children });
364
+ }
365
+ return groupTries(out);
366
+ };
367
+ const top = build(null);
368
+ if (top.length === 1 && top[0].kind === 'agent' && top[0].children.length && (!top[0].failed || hasFailedMeaningful(top[0]))) return top[0].children;
369
+ return top;
370
+ }
371
+
372
+ /** Back-to-back attempts at the same thing, where the earlier ones failed, become one step with `tries`. */
373
+ function groupTries(steps) {
374
+ const key = (s) => `${s.kind}|${s.tool ?? ''}|${s.method ?? ''}|${s.url ?? ''}|${s.db ?? ''}|${s.dbOp ?? ''}|${s.kind === 'other' ? s.name : ''}`;
375
+ const out = [];
376
+ for (const s of steps) {
377
+ const prev = out[out.length - 1];
378
+ if (prev && s.kind !== 'model' && s.kind !== 'agent' && key(prev) === key(s) && prev.failed) {
379
+ const tries = [...(prev.tries || [prev]), s];
380
+ out[out.length - 1] = { ...s, start: tries[0].start, tries, children: tries.flatMap((t) => t.children || []) };
381
+ } else out.push(s);
382
+ }
383
+ return out;
384
+ }
385
+
386
+ const flatten = (steps, depth = 0, out = []) => { for (const s of steps) { out.push({ step: s, depth }); flatten(s.children || [], depth + 1, out); } return out; };
387
+
388
+ /**
389
+ * Explain one agent run. `input` is the record's text (or parsed JSON). Options: { run } picks a trace id when the
390
+ * record holds several runs (default: the latest).
391
+ */
392
+ /** MCP tool definitions (a tools/list result, or an array of tools) as name -> annotations. */
393
+ export function toolAnnotations(input) {
394
+ const v = typeof input === 'string' ? JSON.parse(input) : input;
395
+ const list = Array.isArray(v) ? v : v?.tools ?? v?.result?.tools ?? [];
396
+ return new Map(list.filter((t) => t && t.name).map((t) => [String(t.name), t.annotations ?? null]));
397
+ }
398
+
399
+ export function explainRun(input, { run, tools = null, allow = null } = {}) {
400
+ const raw = collectSpans(parseInput(input)).filter((r) => r.id);
401
+ if (!raw.length) {
402
+ return { ok: false, why: 'Thunder found no steps in this file. It reads OpenTelemetry traces: an OTLP JSON export, the collector\'s file exporter, or the Python console exporter.' };
403
+ }
404
+ const traces = new Map();
405
+ for (const r of raw) { const k = r.trace ?? 'unknown'; if (!traces.has(k)) traces.set(k, []); traces.get(k).push(r); }
406
+ const runs = [...traces.entries()].map(([id, spans]) => ({ id, spans, start: Math.min(...spans.map((s) => s.start ?? Infinity)), end: Math.max(...spans.map((s) => s.end ?? -Infinity)) }))
407
+ .sort((x, y) => x.start - y.start);
408
+ let chosen = runs[runs.length - 1];
409
+ if (run) {
410
+ chosen = runs.find((r) => r.id.startsWith(String(run).toLowerCase()));
411
+ if (!chosen) return { ok: false, why: `No run in this file starts with ${run}. The runs are: ${runs.map((r) => r.id.slice(0, 8)).join(', ')}.` };
412
+ }
413
+ const all = chosen.spans.map((r) => stepOf(r, tools));
414
+ const t0 = Number.isFinite(chosen.start) ? chosen.start : null;
415
+ const tree = arrange(all);
416
+ const flat = flatten(tree);
417
+ flat.forEach((f, i) => { f.step.n = i + 1; f.step.at = t0 != null && f.step.start != null ? (f.step.start - t0) / 1e6 : null; });
418
+
419
+ const agentStep = all.find((s) => s.kind === 'agent');
420
+ const agentName = agentStep?.agent ?? null;
421
+ const ask = all.filter((s) => s.ask).sort((x, y) => (x.start ?? 0) - (y.start ?? 0))[0]?.ask ?? null;
422
+ const roots = all.filter((s) => !s.parent || !all.some((x) => x.id === s.parent));
423
+ const durationMs = Number.isFinite(chosen.start) && Number.isFinite(chosen.end) ? (chosen.end - chosen.start) / 1e6 : null;
424
+
425
+ // The problem: the last failed step that nothing later recovered from. A run whose top step failed stopped;
426
+ // otherwise its failures were recovered from along the way.
427
+ const failedSteps = flat.map((f) => f.step).filter((s) => s.failed && !(s.children || []).some((k) => k.failed));
428
+ const stopped = roots.some((r) => r.failed) || (failedSteps.length > 0 && failedSteps[failedSteps.length - 1] === [...flat].reverse().find((f) => !(f.step.children || []).length)?.step);
429
+ const problemStep = stopped ? failedSteps[failedSteps.length - 1] ?? flat.find((f) => f.step.failed)?.step ?? null : null;
430
+ const lastFinal = [...flat].reverse().find((f) => f.step.kind === 'model' && f.step.said && !f.step.failed)?.step ?? null;
431
+
432
+ let problem = null;
433
+ if (problemStep) {
434
+ const plain = plainError({ ...problemStep.error, finish: problemStep.finish });
435
+ const tries = problemStep.tries?.length ?? 1;
436
+ const ancestors = new Set();
437
+ for (let p = problemStep.parent; p; p = all.find((x) => x.id === p)?.parent) ancestors.add(p);
438
+ const firstTry = problemStep.tries?.[0] ?? problemStep;
439
+ const before = flat.map((f) => f.step).filter((s) => s !== problemStep && !ancestors.has(s.id) && !(problemStep.tries || []).includes(s) && (s.start ?? 0) <= (firstTry.start ?? 0) && s.n < problemStep.n && !(s.children || []).length).pop() ?? null;
440
+ const parentStep = flat.map((f) => f.step).find((s) => s.id === problemStep.parent && MEANINGFUL.has(s.kind) && s.kind !== 'agent');
441
+ problem = {
442
+ step: problemStep.n,
443
+ short: `${lower(plain.what).replace(/\.$/, '')}${problemStep.kind === 'http' ? ` (${nameOf(problemStep)})` : ''}${parentStep?.kind === 'tool' ? `, while using "${parentStep.tool}"` : problemStep.kind === 'tool' ? `, in ${nameOf(problemStep)}` : ''}${tries > 1 ? `. It tried ${tries} times` : ''}.`,
444
+ inside: parentStep ? { step: parentStep.n, text: parentStep.kind === 'tool' ? `"${parentStep.tool}"` : doing(parentStep) } : null,
445
+ what: `${doing(problemStep)}: ${lower(plain.what)}`.replace(/\.?$/, '.'),
446
+ tries,
447
+ before: before ? { step: before.n, text: sentence(before) } : null,
448
+ wouldHaveChanged: tries > 1
449
+ ? `If any of the ${tries} tries had worked, the run would have gone past this step. Thunder can't say what the agent would have done next.`
450
+ : 'If this step had worked, the run would not have stopped here. Thunder can\'t say what the agent would have done next.',
451
+ next: plain.next,
452
+ details: detailsOf(problemStep),
453
+ };
454
+ }
455
+
456
+ const stepById = new Map(flat.map((f) => [f.step.id, f.step]));
457
+ const underChange = (s) => { for (let p = stepById.get(s.parent); p; p = stepById.get(p.parent)) if ((EFFECT_KINDS.includes(p.effect) && p.effect !== 'read') || p.effect === 'unknown') return true; return false; };
458
+ // Effects: what the run did to the world, outermost step only (a tool's own request is not counted again).
459
+ const effects = flat.map((f) => f.step).filter((s) => EFFECT_KINDS.includes(s.effect) && !underChange(s)).map((s) => ({
460
+ step: s.n, kind: s.effect, basis: s.basis, text: doing(s), name: s.tool ?? (s.kind === 'http' ? `${s.method} ${hostPath(s.url)}` : s.kind === 'db' ? `${s.db} ${s.table ?? ''}`.trim() : s.name),
461
+ worked: !s.failed, tries: s.tries?.length ?? 1,
462
+ }));
463
+ const changes = effects.filter((e) => e.kind !== 'read');
464
+ const allowed = allow ? new Set(allow) : null;
465
+ const notAllowed = allowed ? effects.filter((e) => !allowed.has(e.kind)) : [];
466
+ const unknown = flat.map((f) => f.step).filter((s) => s.effect === 'unknown' && !underChange(s)).map((s) => ({ step: s.n, text: doing(s) }));
467
+ const recovered = stopped ? [] : [...failedSteps, ...flat.map((f) => f.step).filter((s) => !s.failed && (s.tries || []).some((t) => t.failed))]
468
+ .sort((x, y) => x.n - y.n).map((s) => ({ step: s.n, text: sentence(s), short: shortTrouble(s) }));
469
+ const warnings = flat.map((f) => f.step).filter((s) => s.warning).map((s) => ({ step: s.n, text: plainError({ finish: s.warning }).what, short: plainError({ finish: s.warning }).what }));
470
+
471
+ const status = stopped ? 'stopped' : recovered.length || warnings.length ? 'finished-with-problems' : 'finished';
472
+ const who = agentName ? `The agent "${agentName}"` : 'The agent';
473
+ const took = durationMs != null ? ` after ${secs(durationMs)}` : '';
474
+ const headline = status === 'stopped' ? `${who} stopped with a problem${took}.`
475
+ : status === 'finished-with-problems' ? `${who} finished${took}, but ${recovered.length + warnings.length === 1 ? 'one step' : `${recovered.length + warnings.length} steps`} had a problem along the way.`
476
+ : `${who} finished${took} with no problems.`;
477
+
478
+ return {
479
+ ok: true,
480
+ run: chosen.id,
481
+ otherRuns: runs.filter((r) => r !== chosen).map((r) => r.id),
482
+ status, headline,
483
+ asked: ask ? short(hide(ask), 200) : null,
484
+ answered: !stopped && lastFinal ? short(hide(lastFinal.said), 200) : null,
485
+ problem, recovered, warnings, effects, changes, unknown,
486
+ ...(allowed ? { allowed: [...allowed], notAllowed } : {}),
487
+ durationMs,
488
+ steps: flat.map(({ step: s, depth }) => ({
489
+ n: s.n, depth, kind: s.kind, text: doing(s), outcome: outcome(s), sentence: sentence(s), failed: !!s.failed, effect: s.effect,
490
+ tries: s.tries?.length ?? 1, atMs: s.at, durationMs: s.durationMs, span: s.id, details: detailsOf(s),
491
+ })),
492
+ spanCount: all.length,
493
+ };
494
+ }
495
+
496
+ /** Everything the record says about one step, for `--step N` (secrets hidden, long text kept). */
497
+ function detailsOf(s) {
498
+ const d = { kind: s.kind, span: s.id, name: s.name };
499
+ for (const k of ['service', 'agent', 'tool', 'model', 'method', 'url', 'status', 'db', 'dbOp', 'table', 'finish']) if (s[k] != null) d[k] = s[k];
500
+ if (s.args != null) d.arguments = hide(maybeJson(s.args));
501
+ if (s.result != null) d.result = hide(maybeJson(s.result));
502
+ if (s.ask) d.asked = hide(s.ask);
503
+ if (s.said) d.answered = hide(s.said);
504
+ if (s.error) d.error = hide(Object.fromEntries(Object.entries(s.error).filter(([, v]) => v != null)));
505
+ if (s.tries) d.tries = s.tries.map((t) => ({ span: t.id, failed: !!t.failed, ...(t.error ? { error: hide(t.error) } : {}) }));
506
+ if (s.durationMs != null) d.durationMs = Math.round(s.durationMs * 10) / 10;
507
+ return d;
508
+ }
509
+
510
+ // ── Printing ──────────────────────────────────────────────────────────────────────────────────────────────────
511
+
512
+ const at = (ms) => (ms == null ? '' : `+${(ms / 1000).toFixed(1)}s`);
513
+ const basisNote = { name: 'guessed from its name', declared: 'the tool says so', method: 'from the request method', operation: 'from the database operation' };
514
+ // What each kind of effect is called, as a past action and as an attempt.
515
+ const DID = { money: 'Moved money', delete: 'Deleted something', send: 'Sent something', create: 'Created something', change: 'Changed something', read: 'Read' };
516
+ const TRIED = { money: 'Tried to move money', delete: 'Tried to delete something', send: 'Tried to send something', create: 'Tried to create something', change: 'Tried to change something', read: 'Tried to read' };
517
+ const effectName = (e) => (/^[A-Z]+ /.test(e.name) ? e.name : `"${e.name}"`);
518
+ const effectLine = (e) => `${e.worked ? DID[e.kind] : TRIED[e.kind]} with ${effectName(e)}${e.basis === 'name' || e.basis === 'declared' ? ` (${basisNote[e.basis]})` : ''}.${e.worked ? '' : ' It did not go through, but may have partly happened.'}`;
519
+ const andList = (xs) => (xs.length > 1 ? `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}` : xs.join(''));
520
+
521
+ /** The short story: a few lines anyone can read. Every step is one flag away (--steps). */
522
+ export function renderWhy(r, { file = 'run.json' } = {}) {
523
+ if (!r.ok) return r.why;
524
+ const who = r.headline.match(/^The agent( "[^"]+")?/)[0];
525
+ const took = r.durationMs != null ? ` ${r.status === 'stopped' ? 'after' : 'in'} ${secs(r.durationMs)}` : '';
526
+ const head = r.status === 'stopped' ? `✗ ${who} stopped${took}.`
527
+ : r.status === 'finished-with-problems' ? `✓ ${who} finished${took}, with ${r.recovered.length + r.warnings.length === 1 ? 'one problem' : `${r.recovered.length + r.warnings.length} problems`} along the way.`
528
+ : `✓ ${who} finished${took}.`;
529
+ const L = [head];
530
+ if (r.asked) L.push(` Asked: ${quote(r.asked, 100)}`);
531
+ if (r.answered) L.push(` Answered: ${quote(r.answered, 100)}`);
532
+ L.push('');
533
+ const row = (label, text) => L.push(` ${label.padEnd(9)} ${text}`);
534
+ if (r.problem) {
535
+ const p = r.problem;
536
+ row('Why:', p.short.charAt(0).toUpperCase() + p.short.slice(1));
537
+ }
538
+ for (const x of [...r.recovered, ...r.warnings]) row('Problem:', `${x.short.charAt(0).toUpperCase()}${x.short.slice(1)}`.replace(/\.?$/, '.'));
539
+ const did = r.changes.length ? r.changes.map(effectLine) : [r.effects.length ? 'Only read things.' : 'Nothing that changes anything.'];
540
+ did.forEach((t, i) => row(i ? '' : 'Did:', t));
541
+ if (r.unknown.length) row('Unclear:', `can't tell what ${r.unknown.map((u) => u.text.replace(/^Used /, '').split(' with ')[0]).join(', ')} does.`);
542
+ for (const e of r.notAllowed ?? []) row('Not OK:', `${effectName(e)} ${e.worked ? DID[e.kind].toLowerCase() : TRIED[e.kind].toLowerCase()}. Only ${andList(r.allowed)} ${r.allowed.length === 1 ? 'is' : 'are'} allowed.`);
543
+ if (r.problem?.next) row('Next:', r.problem.next);
544
+ L.push('', ` Every step: thunder why ${file} --steps`);
545
+ if (r.otherRuns.length) L.push(` This file has ${r.otherRuns.length + 1} runs; this is the latest. Others: --run ${r.otherRuns.map((x) => x.slice(0, 8)).join(', ')}`);
546
+ return L.join('\n');
547
+ }
548
+
549
+ /** The whole story: what happened, what went wrong, what changed, step by step, how sure. */
550
+ export function renderFull(r) {
551
+ if (!r.ok) return r.why;
552
+ const L = [];
553
+ L.push('What happened');
554
+ L.push(` ${r.headline}`);
555
+ if (r.asked) L.push(` It was asked: ${quote(r.asked, 160)}`);
556
+ if (r.answered) L.push(` It answered: ${quote(r.answered, 160)}`);
557
+ L.push('');
558
+
559
+ if (r.problem) {
560
+ const p = r.problem;
561
+ L.push('What went wrong');
562
+ L.push(` Step ${p.step}${p.inside ? `, part of step ${p.inside.step} ${p.inside.text}` : ''}. ${p.what}${p.tries > 1 ? ` It tried ${p.tries} times, then stopped.` : ''}`);
563
+ if (p.before) L.push(` Just before, step ${p.before.step}: ${p.before.text}`);
564
+ L.push(` ${p.wouldHaveChanged}`);
565
+ if (p.next) L.push(` What to do next: ${p.next}`);
566
+ L.push(` Details: ${detailLine(p.details)}`);
567
+ L.push('');
568
+ } else if (r.recovered.length || r.warnings.length) {
569
+ L.push('Problems along the way');
570
+ for (const x of r.recovered) L.push(` Step ${x.step}. ${x.text} The run carried on.`);
571
+ for (const x of r.warnings) L.push(` Step ${x.step}. ${x.text}`);
572
+ L.push('');
573
+ }
574
+
575
+ L.push('What it did');
576
+ if (!r.changes.length) L.push(` Nothing that changes anything${r.unknown.length ? ', but some steps could not be judged (below)' : ''}.`);
577
+ for (const c of r.changes) L.push(` Step ${c.step}. ${effectLine(c)}`);
578
+ for (const e of r.notAllowed ?? []) L.push(` Not allowed: step ${e.step} ${DID[e.kind].toLowerCase()}${e.worked ? '' : ' (tried)'}. Allowed: ${r.allowed.join(', ')}.`);
579
+ if (r.unknown.length) L.push(` Could not judge whether ${r.unknown.length === 1 ? 'this step changes' : 'these steps change'} anything: ${r.unknown.map((u) => `step ${u.step} (${u.text})`).join('; ')}.`);
580
+ L.push('');
581
+
582
+ L.push('Step by step');
583
+ for (const s of r.steps) {
584
+ const mark = s.failed ? '✗' : '✓';
585
+ L.push(` ${' '.repeat(s.depth)}${mark} ${s.n}. ${s.sentence}${s.atMs != null ? ` ${at(s.atMs)}` : ''}`);
586
+ }
587
+ L.push('');
588
+ L.push(`How sure: everything above is read from the agent's record (${r.spanCount} recorded step${r.spanCount === 1 ? '' : 's'}, run ${r.run.slice(0, 8)}). Thunder ran nothing and used no AI. Values that look like secrets are hidden. See one step in full with --step <n>.`);
589
+ if (r.otherRuns.length) L.push(`This file holds ${r.otherRuns.length + 1} runs; this is the latest. Pick another with --run <id>: ${r.otherRuns.map((x) => x.slice(0, 8)).join(', ')}.`);
590
+ return L.join('\n');
591
+ }
592
+
593
+ function detailLine(d) {
594
+ const bits = [];
595
+ if (d.method) bits.push(`${d.method} ${d.url ?? ''}`.trim());
596
+ if (d.status != null) bits.push(`answered ${d.status}`);
597
+ if (d.error?.type) bits.push(String(d.error.type));
598
+ if (d.error?.message) bits.push(short(d.error.message, 120));
599
+ bits.push(`span ${String(d.span).slice(0, 8)}`);
600
+ return bits.join(' · ');
601
+ }
602
+
603
+ /** One step in full, for --step N. */
604
+ export function renderStep(r, n) {
605
+ if (!r.ok) return r.why;
606
+ const s = r.steps.find((x) => x.n === Number(n));
607
+ if (!s) return `There is no step ${n}. This run has steps 1 to ${r.steps.length}.`;
608
+ const L = [`Step ${s.n}. ${s.sentence}`];
609
+ if (s.atMs != null) L.push(` When: ${at(s.atMs)} into the run${s.durationMs != null ? `, took ${secs(s.durationMs)}` : ''}.`);
610
+ const show = (k, v) => L.push(` ${k}: ${typeof v === 'string' ? v : JSON.stringify(v, null, 2).replace(/\n/g, '\n ')}`);
611
+ for (const [k, v] of Object.entries(s.details)) if (!['kind', 'durationMs'].includes(k)) show(k, v);
612
+ return L.join('\n');
613
+ }