@skillstech/thunderlang 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/dist/core.cjs +2568 -462
  3. package/dist/index.cjs +7562 -5084
  4. package/dist/learn.cjs +1963 -315
  5. package/intent-graph.schema.json +11 -0
  6. package/package.json +6 -2
  7. package/src/cli.mjs +141 -58
  8. package/src/codegen.mjs +145 -55
  9. package/src/conformance.mjs +15 -6
  10. package/src/core/check.mjs +725 -0
  11. package/src/core/cli.mjs +133 -0
  12. package/src/core/diagnostics.mjs +81 -0
  13. package/src/core/format.mjs +20 -0
  14. package/src/core/from-python.mjs +645 -0
  15. package/src/core/index.mjs +38 -0
  16. package/src/core/lexer.mjs +115 -0
  17. package/src/core/parser.mjs +742 -0
  18. package/src/core/project.mjs +167 -0
  19. package/src/core/round-trip.mjs +150 -0
  20. package/src/core/runtime-python.mjs +801 -0
  21. package/src/core/target-python.mjs +486 -0
  22. package/src/core.d.ts +5 -2
  23. package/src/core.mjs +5 -2
  24. package/src/data-schema.mjs +8 -1
  25. package/src/emit.mjs +1 -1
  26. package/src/evidence.mjs +1 -1
  27. package/src/expr.mjs +81 -4
  28. package/src/form-words.mjs +2 -0
  29. package/src/index.d.ts +8 -1
  30. package/src/index.mjs +5 -1
  31. package/src/intent-schema.mjs +1 -0
  32. package/src/mcp.mjs +23 -0
  33. package/src/meaning.mjs +45 -6
  34. package/src/model.d.mts +7 -3
  35. package/src/model.mjs +19 -6
  36. package/src/money.d.mts +18 -0
  37. package/src/money.mjs +124 -0
  38. package/src/plain-contract.mjs +18 -2
  39. package/src/read.d.mts +11 -0
  40. package/src/read.mjs +40 -6
  41. package/src/review-comment.d.mts +16 -0
  42. package/src/review-comment.mjs +145 -0
  43. package/src/say-less.mjs +1432 -0
  44. package/src/system.mjs +153 -44
  45. package/src/target-cs.mjs +39 -34
  46. package/src/target-elixir.mjs +40 -30
  47. package/src/target-go.mjs +41 -36
  48. package/src/target-java.mjs +34 -27
  49. package/src/target-kotlin.mjs +43 -35
  50. package/src/target-py.mjs +57 -55
  51. package/src/target-result.d.mts +48 -0
  52. package/src/target-result.mjs +112 -0
  53. package/src/target-rust.mjs +42 -38
  54. package/src/target-scala.mjs +45 -35
  55. package/src/target-ts.mjs +37 -45
  56. package/src/target-types.mjs +41 -5
  57. package/src/target-util.mjs +55 -2
  58. package/src/trace-cli.mjs +58 -0
  59. package/src/trace-fs.mjs +76 -0
  60. package/src/trace.mjs +261 -0
  61. package/src/translate.d.mts +3 -0
  62. package/src/translate.mjs +62 -32
  63. package/src/why-cli.mjs +31 -0
  64. package/src/why.d.mts +28 -0
  65. package/src/why.mjs +532 -0
  66. package/src/write-steps.mjs +22 -5
package/src/why.mjs ADDED
@@ -0,0 +1,532 @@
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
+ const READ_VERBS = new Set('get list search find lookup look fetch read query retrieve check view show describe count load browse inspect peek lookup_ verify validate calculate compute estimate summarize'.split(' '));
146
+ const CHANGE_VERBS = new Set('create add insert update set edit modify change delete remove drop cancel send post email notify message sms charge pay refund transfer write save store upload book reserve schedule submit approve reject close issue publish deploy merge push assign grant revoke rename move archive restore reset'.split(' '));
147
+
148
+ /** Does this step change anything? { effect: 'read'|'change'|'unknown'|'none', basis } */
149
+ function effectOf(s) {
150
+ if (s.kind === 'model' || s.kind === 'agent') return { effect: 'none', basis: 'kind' };
151
+ if (s.kind === 'retrieve') return { effect: 'read', basis: 'kind' };
152
+ if (s.kind === 'http') {
153
+ const m = String(s.method).toUpperCase();
154
+ if (['GET', 'HEAD', 'OPTIONS'].includes(m)) return { effect: 'read', basis: 'method' };
155
+ if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(m)) return { effect: 'change', basis: 'method' };
156
+ return { effect: 'unknown', basis: 'method' };
157
+ }
158
+ if (s.kind === 'db') {
159
+ const op = String(s.dbOp || '').toUpperCase();
160
+ if (/^(SELECT|FIND|GET|SCAN|QUERY|COUNT|AGGREGATE|SHOW|DESCRIBE|EXPLAIN|MGET|HGET|HGETALL|EXISTS)/.test(op)) return { effect: 'read', basis: 'operation' };
161
+ if (/^(INSERT|UPDATE|DELETE|UPSERT|MERGE|REPLACE|CREATE|DROP|ALTER|TRUNCATE|SET|DEL|HSET|PUT|INCR|LPUSH|RPUSH)/.test(op)) return { effect: 'change', basis: 'operation' };
162
+ return { effect: 'unknown', basis: 'operation' };
163
+ }
164
+ if (s.kind === 'tool') {
165
+ const words = String(s.tool).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
166
+ for (const w of words) {
167
+ if (CHANGE_VERBS.has(w)) return { effect: 'change', basis: 'name' };
168
+ if (READ_VERBS.has(w)) return { effect: 'read', basis: 'name' };
169
+ }
170
+ return { effect: 'unknown', basis: 'name' };
171
+ }
172
+ return { effect: 'unknown', basis: 'kind' };
173
+ }
174
+
175
+ /** A raw span as a step: what kind of thing happened, with the facts the story needs. */
176
+ function stepOf(r) {
177
+ const a = r.attrs;
178
+ const op = String(a['gen_ai.operation.name'] ?? '').toLowerCase();
179
+ const oi = String(a['openinference.span.kind'] ?? '').toUpperCase();
180
+ const tool = a['gen_ai.tool.name'] ?? a['tool.name'] ?? (oi === 'TOOL' ? r.name : null);
181
+ const method = a['http.request.method'] ?? a['http.method'];
182
+ const db = a['db.system.name'] ?? a['db.system'];
183
+ let kind = 'other';
184
+ if (op === 'invoke_agent' || op === 'create_agent' || oi === 'AGENT') kind = 'agent';
185
+ else if (op === 'execute_tool' || oi === 'TOOL' || tool) kind = 'tool';
186
+ 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';
187
+ else if (oi === 'RETRIEVER') kind = 'retrieve';
188
+ else if (method) kind = 'http';
189
+ else if (db) kind = 'db';
190
+ const s = {
191
+ id: r.id, parent: r.parent, trace: r.trace, name: r.name, start: r.start, end: r.end, service: r.service ?? null,
192
+ durationMs: r.start != null && r.end != null && r.end >= r.start ? (r.end - r.start) / 1e6 : null,
193
+ kind,
194
+ };
195
+ if (kind === 'agent') s.agent = a['gen_ai.agent.name'] ?? (r.name.replace(/^invoke_agent\s*/i, '') || r.name);
196
+ 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']; }
197
+ if (kind === 'model') {
198
+ s.model = a['gen_ai.response.model'] ?? a['gen_ai.request.model'] ?? a['llm.model_name'] ?? null;
199
+ const outMsgs = messagesOf(a, 'output');
200
+ s.decidedTools = [...new Set(outMsgs.flatMap((m) => m.tools))];
201
+ s.said = outMsgs.map((m) => m.text).filter(Boolean).join(' ') || (typeof a['output.value'] === 'string' && !/^[[{]/.test(a['output.value'].trim()) ? a['output.value'] : '');
202
+ const ins = messagesOf(a, 'input').filter((m) => m.role === 'user' && m.text);
203
+ s.ask = ins.length ? ins[ins.length - 1].text : null;
204
+ const fr = a['gen_ai.response.finish_reasons'];
205
+ s.finish = Array.isArray(fr) ? fr[0] : fr ?? null;
206
+ }
207
+ if (kind === 'agent' && typeof a['input.value'] === 'string') s.ask = a['input.value'];
208
+ if (kind === 'http') {
209
+ s.method = String(method).toUpperCase();
210
+ 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;
211
+ s.status = a['http.response.status_code'] ?? a['http.status_code'] ?? null;
212
+ }
213
+ if (kind === 'db') {
214
+ const q = a['db.query.text'] ?? a['db.statement'];
215
+ s.db = String(db);
216
+ s.dbOp = a['db.operation.name'] ?? a['db.operation'] ?? (typeof q === 'string' ? q.trim().split(/\s+/)[0] : null);
217
+ 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;
218
+ }
219
+ // Failure: the span's status, an error.type, or (for a request) a 4xx/5xx answer.
220
+ const exc = r.events.find((e) => e.name === 'exception');
221
+ const httpBad = kind === 'http' && Number(s.status) >= 400;
222
+ s.failed = r.failed || a['error.type'] != null || !!exc || httpBad;
223
+ if (s.failed) {
224
+ s.error = {
225
+ type: exc?.attrs['exception.type'] ?? a['error.type'] ?? null,
226
+ message: exc?.attrs['exception.message'] ?? r.statusMessage ?? null,
227
+ status: s.status ?? a['http.response.status_code'] ?? null,
228
+ };
229
+ }
230
+ if (kind === 'model' && !s.failed && ['length', 'max_tokens', 'content_filter'].includes(String(s.finish))) s.warning = String(s.finish);
231
+ Object.assign(s, effectOf(s));
232
+ return s;
233
+ }
234
+
235
+ // ── Errors in plain words ─────────────────────────────────────────────────────────────────────────────────────
236
+
237
+ /**
238
+ * An error as plain words: { what, next? }. `what` never contains codes or jargon; the original stays in the
239
+ * step's details.
240
+ */
241
+ export function plainError({ type, message, status, finish } = {}) {
242
+ const t = String(type ?? ''), m = String(message ?? ''), both = `${t} ${m}`;
243
+ const st = Number(status);
244
+ 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.' };
245
+ 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.' };
246
+ 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.' };
247
+ 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.' };
248
+ 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.' };
249
+ 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.' };
250
+ 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.' };
251
+ 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.' };
252
+ 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.' };
253
+ 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." };
254
+ 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.' };
255
+ 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.' };
256
+ 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.' };
257
+ 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.' };
258
+ 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.' };
259
+ 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.' };
260
+ return { what: 'Something went wrong.', next: null };
261
+ }
262
+
263
+ // ── Building the story ────────────────────────────────────────────────────────────────────────────────────────
264
+
265
+ const human = (name) => String(name).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
266
+ const hostPath = (u) => { try { const x = new URL(u); return `${x.host}${x.pathname === '/' ? '' : x.pathname}`; } catch { return String(u ?? ''); } };
267
+ const quote = (s, n = 90) => `"${short(hide(String(s)), n)}"`;
268
+ const secs = (ms) => (ms == null ? null : ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(ms < 10000 ? 1 : 0)} seconds`);
269
+ const MEANINGFUL = new Set(['agent', 'model', 'tool', 'http', 'db', 'retrieve']);
270
+
271
+ /** What a step did, as one plain sentence without its outcome. */
272
+ function doing(s) {
273
+ switch (s.kind) {
274
+ case 'agent': return `Handed the work to the agent "${s.agent}"`;
275
+ case 'model': {
276
+ const who = s.model ? `the AI (${s.model})` : 'the AI';
277
+ if (s.decidedTools?.length) return `Asked ${who}, which decided to use ${s.decidedTools.map((t) => `"${t}"`).join(' and ')}`;
278
+ if (s.said) return `Asked ${who}, which answered ${quote(s.said, 70)}`;
279
+ return `Asked ${who}`;
280
+ }
281
+ case 'tool': { const args = argText(s.args); return `Used "${s.tool}"${args ? ` with ${args}` : ''}`; }
282
+ case 'http': return `Called ${s.method} ${hostPath(s.url) || s.name}`;
283
+ 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}` : ''}`;
284
+ case 'retrieve': return 'Searched its documents';
285
+ default: return `Ran "${s.name}"`;
286
+ }
287
+ }
288
+
289
+ /** The outcome of a step (or a group of tries), as a short clause. */
290
+ const lower = (t) => t.charAt(0).toLowerCase() + t.slice(1);
291
+ const ordinal = (n) => ['first', 'second', 'third', 'fourth', 'fifth'][n - 1] ?? `${n}th`;
292
+ function outcome(s) {
293
+ const failedKid = [...(s.children || [])].reverse().find((k) => k.failed);
294
+ if (s.failed && failedKid) return `it stopped because step ${failedKid.n} did not work`;
295
+ if (s.failed) return lower(plainError({ ...s.error, finish: s.finish }).what.replace(/\.$/, ''));
296
+ if (s.warning) return lower(plainError({ finish: s.warning }).what.replace(/\.$/, ''));
297
+ const firstFail = (s.tries || []).find((t) => t.failed);
298
+ if (firstFail) return `it worked on the ${ordinal(s.tries.length)} try (before that, ${lower(plainError(firstFail.error).what.replace(/\.$/, ''))})`;
299
+ if (s.kind === 'http' && s.status != null) return `the service answered ${s.status}`;
300
+ if (s.kind === 'model' || s.kind === 'agent') return '';
301
+ return 'it worked';
302
+ }
303
+ const sentence = (s) => {
304
+ const o = outcome(s);
305
+ 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)` : '';
306
+ const body = `${doing(s)}${o ? `: ${o}` : ''}${tries}`;
307
+ return /[.!?]["”]$/.test(body) ? body : `${body}.`;
308
+ };
309
+
310
+ /** Steps in time order, keeping the record's nesting but skipping wrappers that say nothing. */
311
+ function arrange(all) {
312
+ const byId = new Map(all.map((s) => [s.id, s]));
313
+ const kids = new Map();
314
+ for (const s of all) {
315
+ const p = s.parent && byId.has(s.parent) ? s.parent : null;
316
+ if (!kids.has(p)) kids.set(p, []);
317
+ kids.get(p).push(s);
318
+ }
319
+ const order = (xs) => xs.sort((x, y) => (x.start ?? 0) - (y.start ?? 0));
320
+ const hasFailedMeaningful = (s) => (kids.get(s.id) || []).some((k) => (MEANINGFUL.has(k.kind) && k.failed) || hasFailedMeaningful(k));
321
+ const build = (pid) => {
322
+ const out = [];
323
+ for (const s of order([...(kids.get(pid) || [])])) {
324
+ const children = build(s.id);
325
+ // A wrapper span (a chain, a function) is shown only if it failed and nothing inside it explains why.
326
+ if (!MEANINGFUL.has(s.kind) && !(s.failed && !hasFailedMeaningful(s))) out.push(...children);
327
+ else out.push({ ...s, children });
328
+ }
329
+ return groupTries(out);
330
+ };
331
+ const top = build(null);
332
+ if (top.length === 1 && top[0].kind === 'agent' && top[0].children.length && (!top[0].failed || hasFailedMeaningful(top[0]))) return top[0].children;
333
+ return top;
334
+ }
335
+
336
+ /** Back-to-back attempts at the same thing, where the earlier ones failed, become one step with `tries`. */
337
+ function groupTries(steps) {
338
+ const key = (s) => `${s.kind}|${s.tool ?? ''}|${s.method ?? ''}|${s.url ?? ''}|${s.db ?? ''}|${s.dbOp ?? ''}|${s.kind === 'other' ? s.name : ''}`;
339
+ const out = [];
340
+ for (const s of steps) {
341
+ const prev = out[out.length - 1];
342
+ if (prev && s.kind !== 'model' && s.kind !== 'agent' && key(prev) === key(s) && prev.failed) {
343
+ const tries = [...(prev.tries || [prev]), s];
344
+ out[out.length - 1] = { ...s, start: tries[0].start, tries, children: tries.flatMap((t) => t.children || []) };
345
+ } else out.push(s);
346
+ }
347
+ return out;
348
+ }
349
+
350
+ const flatten = (steps, depth = 0, out = []) => { for (const s of steps) { out.push({ step: s, depth }); flatten(s.children || [], depth + 1, out); } return out; };
351
+
352
+ /**
353
+ * Explain one agent run. `input` is the record's text (or parsed JSON). Options: { run } picks a trace id when the
354
+ * record holds several runs (default: the latest).
355
+ */
356
+ export function explainRun(input, { run } = {}) {
357
+ const raw = collectSpans(parseInput(input)).filter((r) => r.id);
358
+ if (!raw.length) {
359
+ 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.' };
360
+ }
361
+ const traces = new Map();
362
+ for (const r of raw) { const k = r.trace ?? 'unknown'; if (!traces.has(k)) traces.set(k, []); traces.get(k).push(r); }
363
+ 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)) }))
364
+ .sort((x, y) => x.start - y.start);
365
+ let chosen = runs[runs.length - 1];
366
+ if (run) {
367
+ chosen = runs.find((r) => r.id.startsWith(String(run).toLowerCase()));
368
+ 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(', ')}.` };
369
+ }
370
+ const all = chosen.spans.map(stepOf);
371
+ const t0 = Number.isFinite(chosen.start) ? chosen.start : null;
372
+ const tree = arrange(all);
373
+ const flat = flatten(tree);
374
+ flat.forEach((f, i) => { f.step.n = i + 1; f.step.at = t0 != null && f.step.start != null ? (f.step.start - t0) / 1e6 : null; });
375
+
376
+ const agentStep = all.find((s) => s.kind === 'agent');
377
+ const agentName = agentStep?.agent ?? null;
378
+ const ask = all.filter((s) => s.ask).sort((x, y) => (x.start ?? 0) - (y.start ?? 0))[0]?.ask ?? null;
379
+ const roots = all.filter((s) => !s.parent || !all.some((x) => x.id === s.parent));
380
+ const durationMs = Number.isFinite(chosen.start) && Number.isFinite(chosen.end) ? (chosen.end - chosen.start) / 1e6 : null;
381
+
382
+ // The problem: the last failed step that nothing later recovered from. A run whose top step failed stopped;
383
+ // otherwise its failures were recovered from along the way.
384
+ const failedSteps = flat.map((f) => f.step).filter((s) => s.failed && !(s.children || []).some((k) => k.failed));
385
+ const stopped = roots.some((r) => r.failed) || (failedSteps.length > 0 && failedSteps[failedSteps.length - 1] === [...flat].reverse().find((f) => !(f.step.children || []).length)?.step);
386
+ const problemStep = stopped ? failedSteps[failedSteps.length - 1] ?? flat.find((f) => f.step.failed)?.step ?? null : null;
387
+ const lastFinal = [...flat].reverse().find((f) => f.step.kind === 'model' && f.step.said && !f.step.failed)?.step ?? null;
388
+
389
+ let problem = null;
390
+ if (problemStep) {
391
+ const plain = plainError({ ...problemStep.error, finish: problemStep.finish });
392
+ const tries = problemStep.tries?.length ?? 1;
393
+ const ancestors = new Set();
394
+ for (let p = problemStep.parent; p; p = all.find((x) => x.id === p)?.parent) ancestors.add(p);
395
+ const firstTry = problemStep.tries?.[0] ?? problemStep;
396
+ 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;
397
+ const parentStep = flat.map((f) => f.step).find((s) => s.id === problemStep.parent && MEANINGFUL.has(s.kind) && s.kind !== 'agent');
398
+ problem = {
399
+ step: problemStep.n,
400
+ inside: parentStep ? { step: parentStep.n, text: parentStep.kind === 'tool' ? `"${parentStep.tool}"` : doing(parentStep) } : null,
401
+ what: `${doing(problemStep)}: ${lower(plain.what)}`.replace(/\.?$/, '.'),
402
+ tries,
403
+ before: before ? { step: before.n, text: sentence(before) } : null,
404
+ wouldHaveChanged: tries > 1
405
+ ? `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.`
406
+ : 'If this step had worked, the run would not have stopped here. Thunder can\'t say what the agent would have done next.',
407
+ next: plain.next,
408
+ details: detailsOf(problemStep),
409
+ };
410
+ }
411
+
412
+ const stepById = new Map(flat.map((f) => [f.step.id, f.step]));
413
+ const underChange = (s) => { for (let p = stepById.get(s.parent); p; p = stepById.get(p.parent)) if (p.effect === 'change' || p.effect === 'unknown') return true; return false; };
414
+ const changes = flat.map((f) => f.step).filter((s) => s.effect === 'change' && !underChange(s)).map((s) => ({
415
+ step: s.n, text: doing(s), worked: !s.failed, basis: s.basis, tries: s.tries?.length ?? 1,
416
+ }));
417
+ const unknown = flat.map((f) => f.step).filter((s) => s.effect === 'unknown' && !underChange(s)).map((s) => ({ step: s.n, text: doing(s) }));
418
+ const recovered = stopped ? [] : [...failedSteps, ...flat.map((f) => f.step).filter((s) => !s.failed && (s.tries || []).some((t) => t.failed))]
419
+ .sort((x, y) => x.n - y.n).map((s) => ({ step: s.n, text: sentence(s) }));
420
+ const warnings = flat.map((f) => f.step).filter((s) => s.warning).map((s) => ({ step: s.n, text: plainError({ finish: s.warning }).what }));
421
+
422
+ const status = stopped ? 'stopped' : recovered.length || warnings.length ? 'finished-with-problems' : 'finished';
423
+ const who = agentName ? `The agent "${agentName}"` : 'The agent';
424
+ const took = durationMs != null ? ` after ${secs(durationMs)}` : '';
425
+ const headline = status === 'stopped' ? `${who} stopped with a problem${took}.`
426
+ : 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.`
427
+ : `${who} finished${took} with no problems.`;
428
+
429
+ return {
430
+ ok: true,
431
+ run: chosen.id,
432
+ otherRuns: runs.filter((r) => r !== chosen).map((r) => r.id),
433
+ status, headline,
434
+ asked: ask ? short(hide(ask), 200) : null,
435
+ answered: !stopped && lastFinal ? short(hide(lastFinal.said), 200) : null,
436
+ problem, recovered, warnings, changes, unknown,
437
+ durationMs,
438
+ steps: flat.map(({ step: s, depth }) => ({
439
+ n: s.n, depth, kind: s.kind, text: doing(s), outcome: outcome(s), sentence: sentence(s), failed: !!s.failed, effect: s.effect,
440
+ tries: s.tries?.length ?? 1, atMs: s.at, durationMs: s.durationMs, span: s.id, details: detailsOf(s),
441
+ })),
442
+ spanCount: all.length,
443
+ };
444
+ }
445
+
446
+ /** Everything the record says about one step, for `--step N` (secrets hidden, long text kept). */
447
+ function detailsOf(s) {
448
+ const d = { kind: s.kind, span: s.id, name: s.name };
449
+ for (const k of ['service', 'agent', 'tool', 'model', 'method', 'url', 'status', 'db', 'dbOp', 'table', 'finish']) if (s[k] != null) d[k] = s[k];
450
+ if (s.args != null) d.arguments = hide(maybeJson(s.args));
451
+ if (s.result != null) d.result = hide(maybeJson(s.result));
452
+ if (s.ask) d.asked = hide(s.ask);
453
+ if (s.said) d.answered = hide(s.said);
454
+ if (s.error) d.error = hide(Object.fromEntries(Object.entries(s.error).filter(([, v]) => v != null)));
455
+ if (s.tries) d.tries = s.tries.map((t) => ({ span: t.id, failed: !!t.failed, ...(t.error ? { error: hide(t.error) } : {}) }));
456
+ if (s.durationMs != null) d.durationMs = Math.round(s.durationMs * 10) / 10;
457
+ return d;
458
+ }
459
+
460
+ // ── Printing ──────────────────────────────────────────────────────────────────────────────────────────────────
461
+
462
+ const at = (ms) => (ms == null ? '' : `+${(ms / 1000).toFixed(1)}s`);
463
+ const basisNote = { name: "judged from the tool's name", method: 'judged from the request method', operation: 'judged from the database operation' };
464
+
465
+ /** The story as text: what happened, what went wrong, what changed, step by step, how sure. */
466
+ export function renderWhy(r) {
467
+ if (!r.ok) return r.why;
468
+ const L = [];
469
+ L.push('What happened');
470
+ L.push(` ${r.headline}`);
471
+ if (r.asked) L.push(` It was asked: ${quote(r.asked, 160)}`);
472
+ if (r.answered) L.push(` It answered: ${quote(r.answered, 160)}`);
473
+ L.push('');
474
+
475
+ if (r.problem) {
476
+ const p = r.problem;
477
+ L.push('What went wrong');
478
+ 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.` : ''}`);
479
+ if (p.before) L.push(` Just before, step ${p.before.step}: ${p.before.text}`);
480
+ L.push(` ${p.wouldHaveChanged}`);
481
+ if (p.next) L.push(` What to do next: ${p.next}`);
482
+ L.push(` Details: ${detailLine(p.details)}`);
483
+ L.push('');
484
+ } else if (r.recovered.length || r.warnings.length) {
485
+ L.push('Problems along the way');
486
+ for (const x of r.recovered) L.push(` Step ${x.step}. ${x.text} The run carried on.`);
487
+ for (const x of r.warnings) L.push(` Step ${x.step}. ${x.text}`);
488
+ L.push('');
489
+ }
490
+
491
+ L.push('What it changed');
492
+ if (!r.changes.length) L.push(` Nothing. No step in the record changes anything${r.unknown.length ? ', but some steps could not be judged (below)' : ''}.`);
493
+ for (const c of r.changes) {
494
+ const how = basisNote[c.basis] ? ` (${basisNote[c.basis]})` : '';
495
+ L.push(c.worked ? ` Step ${c.step}. Changed: ${c.text}${how}.`
496
+ : ` Step ${c.step}. Tried to change, but it did not work: ${c.text}${how}. The record can't show whether anything was partly done.`);
497
+ }
498
+ 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('; ')}.`);
499
+ L.push('');
500
+
501
+ L.push('Step by step');
502
+ for (const s of r.steps) {
503
+ const mark = s.failed ? '✗' : '✓';
504
+ L.push(` ${' '.repeat(s.depth)}${mark} ${s.n}. ${s.sentence}${s.atMs != null ? ` ${at(s.atMs)}` : ''}`);
505
+ }
506
+ L.push('');
507
+ 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>.`);
508
+ 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(', ')}.`);
509
+ return L.join('\n');
510
+ }
511
+
512
+ function detailLine(d) {
513
+ const bits = [];
514
+ if (d.method) bits.push(`${d.method} ${d.url ?? ''}`.trim());
515
+ if (d.status != null) bits.push(`answered ${d.status}`);
516
+ if (d.error?.type) bits.push(String(d.error.type));
517
+ if (d.error?.message) bits.push(short(d.error.message, 120));
518
+ bits.push(`span ${String(d.span).slice(0, 8)}`);
519
+ return bits.join(' · ');
520
+ }
521
+
522
+ /** One step in full, for --step N. */
523
+ export function renderStep(r, n) {
524
+ if (!r.ok) return r.why;
525
+ const s = r.steps.find((x) => x.n === Number(n));
526
+ if (!s) return `There is no step ${n}. This run has steps 1 to ${r.steps.length}.`;
527
+ const L = [`Step ${s.n}. ${s.sentence}`];
528
+ if (s.atMs != null) L.push(` When: ${at(s.atMs)} into the run${s.durationMs != null ? `, took ${secs(s.durationMs)}` : ''}.`);
529
+ const show = (k, v) => L.push(` ${k}: ${typeof v === 'string' ? v : JSON.stringify(v, null, 2).replace(/\n/g, '\n ')}`);
530
+ for (const [k, v] of Object.entries(s.details)) if (!['kind', 'durationMs'].includes(k)) show(k, v);
531
+ return L.join('\n');
532
+ }
@@ -206,6 +206,16 @@ function findMember(state, ref) {
206
206
  if (!rd) continue;
207
207
  for (const { key, item } of memberKeys(rd.reading)) if (item.name === r.name) candidates.push({ path, key, item, language: rd.language, reading: rd.reading, source: f });
208
208
  }
209
+ // A model id writes a route handler's name without spaces ("POST/api/orders"): match it ignoring spaces.
210
+ if (!candidates.length && r.name) {
211
+ const bare = String(r.name).replace(/\s+/g, '');
212
+ for (const [path, f] of state.files) {
213
+ if (r.file && path !== r.file && !path.endsWith(`/${r.file}`)) continue;
214
+ const rd = state.read(path);
215
+ if (!rd) continue;
216
+ for (const { key, item } of memberKeys(rd.reading)) if (String(item.name).replace(/\s+/g, '') === bare) candidates.push({ path, key, item, language: rd.language, reading: rd.reading, source: f });
217
+ }
218
+ }
209
219
  if (!candidates.length) refuse(`No function named ${r.name}${r.file ? ` in ${r.file}` : ''} was found.`);
210
220
  if (r.line == null && candidates.length > 1) refuse(`${r.name} is in more than one place (${candidates.map((c) => `${c.path}:${c.item.line}`).join(', ')}); say which with its id or line.`);
211
221
  return candidates.reduce((best, c) => (r.line == null || Math.abs(c.item.line - r.line) < Math.abs(best.item.line - r.line) ? c : best));
@@ -1247,17 +1257,24 @@ function applyEdit(state, edit) {
1247
1257
  return {
1248
1258
  files,
1249
1259
  plan: { member: { path: m.path, key: m.key, name: m.item.name, shape: ctx.shape, inputs: ctx.expectInputs ?? null, returns: ctx.expectReturns ?? null } },
1250
- says: reworded(says, ctx.treeEdits, { path: m.path, source, language: m.language }),
1260
+ says: reworded(says, ctx.treeEdits, { path: m.path, source, language: m.language }, m.item),
1251
1261
  };
1252
1262
  }
1253
- /** "…; it now reads "If days_since is more than 10"": the edited steps' new Thunder words, read from the new code. */
1254
- function reworded(says, treeEdits, f) {
1263
+ /** "…; it now reads "If days_since is more than 10"": each edited step's new Thunder words, once, read from the new
1264
+ * code. Only the edited function is looked at, and on a line holding several steps only the step of the same kind. */
1265
+ function reworded(says, treeEdits, f, member) {
1255
1266
  if (!treeEdits.length) return says;
1256
1267
  let reading;
1257
1268
  try { reading = readFile(f).reading; } catch { return says; }
1269
+ const items = membersOf(reading).filter((it) => !member || it.name === member.name);
1270
+ const mine = member && items.length > 1 ? [items.reduce((b, it) => (Math.abs(it.line - member.line) < Math.abs(b.line - member.line) ? it : b))] : items;
1258
1271
  const now = [];
1259
- const walk = (list) => (list || []).forEach((s) => { for (const t of treeEdits) if (s.line === t.step.line && s.says && s.says !== t.step.says) now.push(s.says); walk(s.children); walk(s.otherwise); });
1260
- for (const it of membersOf(reading)) walk(it.steps);
1272
+ for (const t of treeEdits) {
1273
+ let hit = null;
1274
+ const walk = (list) => (list || []).forEach((s) => { if (hit) return; if (s.line === t.step.line && (!t.step.kind || s.kind === t.step.kind)) { hit = s; return; } walk(s.children); walk(s.otherwise); });
1275
+ for (const it of mine) walk(it.steps);
1276
+ if (hit?.says && hit.says !== t.step.says && !now.includes(hit.says)) now.push(hit.says);
1277
+ }
1261
1278
  return now.length ? `${says}; it now reads ${now.map((x) => `"${x}"`).join(', ')}` : says;
1262
1279
  }
1263
1280
  function stepPathOf(steps, step) {