personal-eval 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,138 @@
1
+ // Claude Code: ~/.claude/projects/<project>/<session>.jsonl
2
+ // One JSON record per line. Assistant records carry message.model; each
3
+ // content block is usually its own record sharing message.id. Tool results come
4
+ // back as user records with tool_result blocks (plus a structured toolUseResult).
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { readLines, tryJSON } from '../lines.js';
8
+ import { walk } from './fs.js';
9
+ import {
10
+ humanText, isInterruptText, toolKind, classifyToolError, diffLines, toMs,
11
+ } from '../text.js';
12
+
13
+ export const id = 'claude';
14
+ export const label = 'Claude Code';
15
+
16
+ export function roots() {
17
+ const base = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
18
+ return [path.join(base, 'projects')];
19
+ }
20
+
21
+ export async function discover() {
22
+ const units = [];
23
+ for (const root of roots()) {
24
+ for await (const f of walk(root, (p) => p.endsWith('.jsonl'), (d) => path.basename(d) === 'subagents')) {
25
+ units.push(f);
26
+ }
27
+ }
28
+ return units;
29
+ }
30
+
31
+ function blockText(content) {
32
+ if (typeof content === 'string') return content;
33
+ if (!Array.isArray(content)) return '';
34
+ return content.map((b) => (typeof b === 'string' ? b : b?.type === 'text' ? b.text || '' : '')).join('\n');
35
+ }
36
+
37
+ export async function parse(file) {
38
+ const events = [];
39
+ const pending = new Map(); // tool_use id -> { name, input, model }
40
+ let cwd = null;
41
+ let sessionId = path.basename(file, '.jsonl');
42
+ let lastMsgId = null;
43
+
44
+ for await (const line of readLines(file)) {
45
+ if (!line.includes('"type":"user"') && !line.includes('"type":"assistant"')) continue;
46
+ const d = tryJSON(line);
47
+ if (!d || (d.type !== 'user' && d.type !== 'assistant')) continue;
48
+ if (d.isSidechain) continue;
49
+ const m = d.message;
50
+ if (!m || typeof m !== 'object') continue;
51
+ const t = toMs(d.timestamp);
52
+ cwd ||= d.cwd || null;
53
+ if (d.sessionId) sessionId = d.sessionId;
54
+
55
+ if (d.type === 'assistant') {
56
+ const model = m.model;
57
+ if (!model || model === '<synthetic>') continue;
58
+ const content = Array.isArray(m.content) ? m.content : [];
59
+ let text = '';
60
+ let tools = 0;
61
+ for (const b of content) {
62
+ if (b?.type === 'text') text += b.text || '';
63
+ else if (b?.type === 'tool_use') {
64
+ tools++;
65
+ pending.set(b.id, { name: b.name, input: b.input || {}, model });
66
+ }
67
+ }
68
+ // Streaming writes one record per block; merge records of the same message.
69
+ const msgId = m.id || d.uuid;
70
+ if (msgId && msgId === lastMsgId && events.length && events[events.length - 1].type === 'assistant') {
71
+ const prev = events[events.length - 1];
72
+ prev.text += text;
73
+ prev.tools += tools;
74
+ prev.t = t ?? prev.t;
75
+ } else {
76
+ events.push({ type: 'assistant', t, model, text, tools });
77
+ }
78
+ lastMsgId = msgId;
79
+ continue;
80
+ }
81
+
82
+ // user record
83
+ lastMsgId = null;
84
+ const content = m.content;
85
+ const results = Array.isArray(content) ? content.filter((b) => b?.type === 'tool_result') : [];
86
+ if (results.length) {
87
+ for (const r of results) {
88
+ const call = pending.get(r.tool_use_id);
89
+ if (!call) continue;
90
+ pending.delete(r.tool_use_id);
91
+ const kind = toolKind(call.name);
92
+ const status = r.is_error ? classifyToolError(blockText(r.content)) : 'ok';
93
+ const ev = { type: 'tool', t, model: call.model, name: call.name, kind, status };
94
+ if (kind === 'edit' && status === 'ok') {
95
+ ev.edits = editsFor(call, results.length === 1 ? d.toolUseResult : null);
96
+ }
97
+ events.push(ev);
98
+ }
99
+ continue;
100
+ }
101
+ if (d.isMeta) continue;
102
+ if (d.turnOrigin === 'task_notification' || d.turnOrigin === 'scheduled') continue;
103
+ const raw = blockText(content);
104
+ if (isInterruptText(raw)) {
105
+ events.push({ type: 'interrupt', t });
106
+ continue;
107
+ }
108
+ const text = humanText(raw);
109
+ if (text == null) continue;
110
+ events.push({ type: 'prompt', t, text, key: d.uuid ? `claude:${d.uuid}` : null });
111
+ }
112
+
113
+ return [{ agent: id, id: sessionId, cwd, file, events }];
114
+ }
115
+
116
+ function editsFor(call, result) {
117
+ const input = call.input || {};
118
+ const name = String(call.name).toLowerCase();
119
+ const filePath = input.file_path || input.path || input.notebook_path || result?.filePath;
120
+ if (!filePath) return [];
121
+ if (name === 'edit' || name === 'str_replace_based_edit_tool' || name === 'str_replace_editor') {
122
+ if (input.command && input.command !== 'str_replace' && input.command !== 'create' && input.command !== 'insert') return [];
123
+ if (input.command === 'create') return [{ path: filePath, mode: 'write', removed: [], added: diffLines('', input.file_text).added }];
124
+ if (input.command === 'insert') return [{ path: filePath, mode: 'patch', removed: [], added: diffLines('', input.new_str).added }];
125
+ return [{ path: filePath, mode: 'patch', ...diffLines(input.old_string ?? input.old_str, input.new_string ?? input.new_str) }];
126
+ }
127
+ if (name === 'multiedit') {
128
+ return (input.edits || []).map((e) => ({ path: filePath, mode: 'patch', ...diffLines(e.old_string, e.new_string) }));
129
+ }
130
+ if (name === 'write') {
131
+ if (result && typeof result.originalFile === 'string') {
132
+ return [{ path: filePath, mode: 'patch', ...diffLines(result.originalFile, input.content) }];
133
+ }
134
+ // Unknown prior content: a full overwrite replaces everything we tracked.
135
+ return [{ path: filePath, mode: 'write', removed: [], added: diffLines('', input.content).added }];
136
+ }
137
+ return [];
138
+ }
@@ -0,0 +1,246 @@
1
+ // Codex: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl (newer builds: .jsonl.zst)
2
+ // Records are {timestamp, type, payload}. The model comes from turn_context.
3
+ //
4
+ // Two dialects exist:
5
+ // - newer: event_msg/item_completed with typed items (UserMessage, AgentMessage,
6
+ // CommandExecution{exit_code}, FileChange{changes}, McpToolCall)
7
+ // - older: event_msg user_message/agent_message + response_item function_call /
8
+ // function_call_output (+ exec_command_end / patch_apply_end events)
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { readLines, tryJSON } from '../lines.js';
12
+ import { walk } from './fs.js';
13
+ import {
14
+ humanText, toolKind, isMalformedText, isRejectedText, applyPatchEdits, unifiedDiffLines, diffLines, toMs,
15
+ } from '../text.js';
16
+
17
+ export const id = 'codex';
18
+ export const label = 'Codex';
19
+
20
+ export function roots() {
21
+ const base = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
22
+ return [path.join(base, 'sessions'), path.join(base, 'archived_sessions')];
23
+ }
24
+
25
+ export async function discover() {
26
+ const units = [];
27
+ for (const root of roots()) {
28
+ for await (const f of walk(root, (p) => /rollout-.*\.jsonl(\.zst)?$/.test(p))) units.push(f);
29
+ }
30
+ return units;
31
+ }
32
+
33
+ const INTERESTING = [
34
+ '"session_meta"', '"turn_context"', '"item_completed"', '"turn_aborted"', '"user_message"',
35
+ '"agent_message"', '"function_call"', '"custom_tool_call"', '"local_shell_call"', '_call_output"',
36
+ '"exec_command_end"', '"patch_apply_end"',
37
+ ];
38
+
39
+ const SKIP_RECORDS = new Set(['compacted', 'token_usage_record', 'world_state', 'inter_agent_communication_metadata']);
40
+ const SKIP_RESPONSE = new Set(['reasoning', 'message', 'additional_tools', 'agent_message', 'configuration_update', 'web_search_call', 'image_generation_call']);
41
+ const KEEP_EVENTS = new Set(['item_completed', 'turn_aborted', 'user_message', 'agent_message', 'exec_command_end', 'patch_apply_end']);
42
+ const KEEP_ITEMS = new Set(['UserMessage', 'AgentMessage', 'CommandExecution', 'FileChange', 'McpToolCall']);
43
+
44
+ function textOf(content) {
45
+ if (typeof content === 'string') return content;
46
+ if (!Array.isArray(content)) return '';
47
+ return content.map((c) => (typeof c === 'string' ? c : c?.text || '')).join('\n');
48
+ }
49
+
50
+ export async function parse(file) {
51
+ const modern = [];
52
+ const legacy = [];
53
+ let isModern = false;
54
+ let sessionId = null;
55
+ let cwd = null;
56
+ let skipBefore = -1;
57
+ let curModel = null;
58
+ const turnModel = new Map();
59
+ const pending = new Map(); // legacy call_id -> { name, kind, model, input, ev }
60
+ const modelFor = (turnId) => (turnId && turnModel.get(turnId)) || curModel;
61
+
62
+ const skip = (head) => {
63
+ const m = head.match(/"type":"(\w+)","payload":\{(?:"type":"(\w+)")?/);
64
+ if (!m) return false;
65
+ const [, rec, ptype] = m;
66
+ if (SKIP_RECORDS.has(rec)) return true;
67
+ if (rec === 'response_item') {
68
+ if (SKIP_RESPONSE.has(ptype)) return true;
69
+ if (isModern && (ptype === 'function_call' || ptype === 'custom_tool_call' || ptype === 'local_shell_call')) return true;
70
+ return false;
71
+ }
72
+ if (rec === 'event_msg') {
73
+ if (ptype === 'item_completed') {
74
+ const it = head.match(/"item":\{"type":"(\w+)"/);
75
+ return !!it && !KEEP_ITEMS.has(it[1]);
76
+ }
77
+ return !KEEP_EVENTS.has(ptype);
78
+ }
79
+ return false;
80
+ };
81
+
82
+ for await (const line of readLines(file, { skip })) {
83
+ if (!INTERESTING.some((s) => line.includes(s))) continue;
84
+ // Cheap skip: in the modern dialect, raw call outputs only matter if they look malformed.
85
+ if (isModern && line.includes('_call_output"') && !/Script failed|failed to parse|unsupported call|Invalid params|missing field|InputValidation|apply_patch verification failed/i.test(line)) continue;
86
+ if (isModern && (line.includes('"type":"function_call"') || line.includes('"type":"custom_tool_call"'))) continue;
87
+ const d = tryJSON(line);
88
+ if (!d) continue;
89
+ if (typeof d.ordinal === 'number' && d.ordinal < skipBefore) continue;
90
+ const p = d.payload || {};
91
+ const t = toMs(d.timestamp);
92
+
93
+ if (d.type === 'session_meta') {
94
+ if (p.source && typeof p.source === 'object' && p.source.subagent) return [];
95
+ if (typeof p.subagent_history_start_ordinal === 'number') skipBefore = p.subagent_history_start_ordinal;
96
+ sessionId ||= p.id || p.session_id;
97
+ cwd ||= p.cwd || null;
98
+ continue;
99
+ }
100
+ if (d.type === 'turn_context') {
101
+ if (p.model) {
102
+ curModel = p.model;
103
+ if (p.turn_id) turnModel.set(p.turn_id, p.model);
104
+ }
105
+ cwd ||= p.cwd || null;
106
+ continue;
107
+ }
108
+
109
+ if (d.type === 'event_msg') {
110
+ if (p.type === 'item_completed' && p.item) {
111
+ isModern = true;
112
+ const ev = modernEvent(p.item, modelFor(p.turn_id), toMs(p.completed_at_ms) ?? t);
113
+ if (ev) modern.push(ev);
114
+ continue;
115
+ }
116
+ if (p.type === 'turn_aborted') {
117
+ if (!p.reason || p.reason === 'interrupted') {
118
+ modern.push({ type: 'interrupt', t });
119
+ legacy.push({ type: 'interrupt', t });
120
+ }
121
+ continue;
122
+ }
123
+ if (isModern) continue;
124
+ if (p.type === 'user_message') {
125
+ const text = humanText(textOf(p.message));
126
+ if (text != null) legacy.push({ type: 'prompt', t, text, key: null });
127
+ } else if (p.type === 'agent_message') {
128
+ legacy.push({ type: 'assistant', t, model: curModel, text: textOf(p.message), tools: 0 });
129
+ } else if (p.type === 'exec_command_end') {
130
+ const c = pending.get(p.call_id);
131
+ if (c?.ev) c.ev.status = p.exit_code === 0 ? 'ok' : 'error';
132
+ } else if (p.type === 'patch_apply_end') {
133
+ const c = pending.get(p.call_id);
134
+ if (c?.ev) {
135
+ c.ev.status = p.success ? 'ok' : 'error';
136
+ if (!p.success) delete c.ev.edits;
137
+ }
138
+ }
139
+ continue;
140
+ }
141
+
142
+ if (d.type !== 'response_item') continue;
143
+ if (isModern) {
144
+ // Only malformed-call detection is taken from raw outputs in the modern dialect.
145
+ if (p.type === 'function_call_output' || p.type === 'custom_tool_call_output') {
146
+ const out = textOf(p.output);
147
+ const turnId = p.internal_chat_message_metadata_passthrough?.turn_id;
148
+ // Failed patches never become FileChange items; they only show up in the call output.
149
+ const failedPatches = out.match(/apply_patch verification failed/g)?.length || 0;
150
+ for (let i = 0; i < failedPatches; i++) {
151
+ modern.push({ type: 'tool', t, model: modelFor(turnId), name: 'apply_patch', kind: 'edit', status: 'error' });
152
+ }
153
+ if (isMalformedText(out) || (/^Script failed/.test(out) && /SyntaxError/.test(out.slice(0, 600)))) {
154
+ modern.push({ type: 'tool', t, model: modelFor(turnId), name: 'call', kind: 'other', status: 'malformed' });
155
+ }
156
+ }
157
+ continue;
158
+ }
159
+ if (p.type === 'function_call' || p.type === 'custom_tool_call' || p.type === 'local_shell_call') {
160
+ const name = p.type === 'local_shell_call' ? 'local_shell' : p.name;
161
+ let input = p.type === 'custom_tool_call' ? p.input : p.arguments;
162
+ if (typeof input === 'string' && p.type === 'function_call') input = tryJSON(input) ?? input;
163
+ if (p.type === 'local_shell_call') input = p.action;
164
+ const kind = toolKind(name);
165
+ const ev = { type: 'tool', t, model: curModel, name, kind, status: 'ok' };
166
+ if (kind === 'edit') {
167
+ const patch = typeof input === 'string' ? input : input?.input || input?.patch || '';
168
+ ev.edits = applyPatchEdits(patch);
169
+ }
170
+ legacy.push({ type: 'assistant', t, model: curModel, text: '', tools: 1, toolOnly: true });
171
+ legacy.push(ev);
172
+ pending.set(p.call_id || p.id, { ev });
173
+ continue;
174
+ }
175
+ if (p.type === 'function_call_output' || p.type === 'custom_tool_call_output') {
176
+ const c = pending.get(p.call_id);
177
+ if (!c) continue;
178
+ const out = typeof p.output === 'string' ? p.output : textOf(p.output?.content ?? p.output);
179
+ c.ev.status = legacyStatus(c.ev.kind, out);
180
+ if (c.ev.status !== 'ok') delete c.ev.edits;
181
+ }
182
+ }
183
+
184
+ const events = isModern ? modern : legacy;
185
+ return [{ agent: id, id: sessionId || path.basename(file), cwd, file, events }];
186
+ }
187
+
188
+ function modernEvent(item, model, t) {
189
+ switch (item.type) {
190
+ case 'UserMessage': {
191
+ const text = humanText(textOf(item.content));
192
+ return text == null ? null : { type: 'prompt', t, text, key: item.id ? `codex:${item.id}` : null };
193
+ }
194
+ case 'AgentMessage':
195
+ return { type: 'assistant', t, model, text: textOf(item.content), tools: 0 };
196
+ case 'CommandExecution': {
197
+ let status = 'ok';
198
+ if (item.status === 'declined') status = 'rejected';
199
+ else if (item.status === 'failed' || (typeof item.exit_code === 'number' && item.exit_code !== 0)) status = 'error';
200
+ return { type: 'tool', t, model, name: 'exec_command', kind: 'shell', status };
201
+ }
202
+ case 'FileChange': {
203
+ let status = 'ok';
204
+ if (item.status === 'declined') status = 'rejected';
205
+ else if (item.status && item.status !== 'completed') status = 'error';
206
+ const ev = { type: 'tool', t, model, name: 'apply_patch', kind: 'edit', status };
207
+ if (status === 'ok') {
208
+ ev.edits = Object.entries(item.changes || {}).map(([p, ch]) => {
209
+ if (ch?.type === 'add') return { path: p, mode: 'write', removed: [], added: diffLines('', ch.content).added };
210
+ if (ch?.type === 'delete') return { path: p, mode: 'delete', removed: [], added: [] };
211
+ return { path: ch?.move_path || p, mode: 'patch', ...unifiedDiffLines(ch?.unified_diff) };
212
+ });
213
+ }
214
+ return ev;
215
+ }
216
+ case 'McpToolCall': {
217
+ const failed = item.status === 'failed' || item.status === 'error';
218
+ const errText = failed ? JSON.stringify(item.error ?? item.result ?? '').slice(0, 2000) : '';
219
+ const status = !failed ? 'ok' : isMalformedText(errText) ? 'malformed' : isRejectedText(errText) ? 'rejected' : 'error';
220
+ return { type: 'tool', t, model, name: `${item.server}.${item.tool}`, kind: 'other', status };
221
+ }
222
+ default:
223
+ return null;
224
+ }
225
+ }
226
+
227
+ function legacyStatus(kind, out) {
228
+ const text = String(out || '');
229
+ if (isMalformedText(text)) return 'malformed';
230
+ if (isRejectedText(text)) return 'rejected';
231
+ if (kind === 'shell') {
232
+ const j = tryJSON(text);
233
+ const code = j?.metadata?.exit_code ?? j?.exit_code ?? matchExit(text);
234
+ return code == null || code === 0 ? 'ok' : 'error';
235
+ }
236
+ if (kind === 'edit') {
237
+ if (/^Success|^Done!|Updated the following files/m.test(text)) return 'ok';
238
+ if (/verification failed|failed to apply|error|invalid hunk|could not find/i.test(text.slice(0, 500))) return 'error';
239
+ }
240
+ return 'ok';
241
+ }
242
+
243
+ function matchExit(text) {
244
+ const m = text.match(/(?:exit(?:ed with)?[ _]code|Process exited with code)["\s:]*(-?\d+)/i);
245
+ return m ? Number(m[1]) : null;
246
+ }
@@ -0,0 +1,30 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ /** Recursively yield files under root matching `want`, skipping dirs matching `skipDir`. */
5
+ export async function* walk(root, want, skipDir = () => false) {
6
+ let entries;
7
+ try {
8
+ entries = await fs.readdir(root, { withFileTypes: true });
9
+ } catch {
10
+ return;
11
+ }
12
+ for (const e of entries) {
13
+ const p = path.join(root, e.name);
14
+ if (e.isDirectory()) {
15
+ if (skipDir(p)) continue;
16
+ yield* walk(p, want, skipDir);
17
+ } else if (e.isFile() && want(p)) {
18
+ yield p;
19
+ }
20
+ }
21
+ }
22
+
23
+ export async function exists(p) {
24
+ try {
25
+ await fs.access(p);
26
+ return true;
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
@@ -0,0 +1,171 @@
1
+ // fx (fx.sh): ~/.fx/sessions/v2/<id>/log.jsonl (v0.0.15+), or the older
2
+ // ~/.fx/sessions/<id>/events.jsonl + session.json (v0.0.8–0.0.14).
3
+ //
4
+ // v2 lines: {"v":1,"seq","ts","kind", …,"crc"}. Conversation pieces are
5
+ // kind:"item" with {type, data}; data over 256 KiB is {"$blob": sha} stored in
6
+ // <id>/blobs/<sha>. Older logs carry the same payloads as {"event":{<type>:{…}}}.
7
+ import fs from 'node:fs/promises';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { readLines, tryJSON } from '../lines.js';
11
+ import { toolKind, classifyToolError, diffLines, toMs } from '../text.js';
12
+
13
+ export const id = 'fx';
14
+ export const label = 'fx';
15
+
16
+ export function roots() {
17
+ const base = process.env.FX_HOME || path.join(os.homedir(), '.fx');
18
+ return [path.join(base, 'sessions')];
19
+ }
20
+
21
+ export async function discover() {
22
+ const units = [];
23
+ for (const root of roots()) {
24
+ const v2 = path.join(root, 'v2');
25
+ for (const dir of await subdirs(v2)) units.push(path.join(v2, dir, 'log.jsonl'));
26
+ for (const dir of await subdirs(root)) {
27
+ if (dir === 'v2') continue;
28
+ units.push(path.join(root, dir, 'events.jsonl'));
29
+ }
30
+ }
31
+ const out = [];
32
+ for (const u of units) {
33
+ try {
34
+ await fs.access(u);
35
+ out.push(u);
36
+ } catch {}
37
+ }
38
+ return out;
39
+ }
40
+
41
+ async function subdirs(p) {
42
+ try {
43
+ return (await fs.readdir(p, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => e.name);
44
+ } catch {
45
+ return [];
46
+ }
47
+ }
48
+
49
+ async function loadBlob(dir, data) {
50
+ if (!data || typeof data !== 'object' || !data.$blob) return data;
51
+ try {
52
+ return tryJSON(await fs.readFile(path.join(dir, 'blobs', data.$blob), 'utf8')) ?? {};
53
+ } catch {
54
+ return {};
55
+ }
56
+ }
57
+
58
+ const shortModel = (m) => (typeof m === 'string' ? m : m?.model || m?.id || null);
59
+
60
+ export async function parse(file) {
61
+ const dir = path.dirname(file);
62
+ const legacy = path.basename(file) === 'events.jsonl';
63
+ let curModel = null;
64
+ let sessionId = path.basename(dir);
65
+ let cwd = null;
66
+ if (legacy) {
67
+ const meta = tryJSON(await fs.readFile(path.join(dir, 'session.json'), 'utf8').catch(() => 'null'));
68
+ if (meta?.subagent_child) return [];
69
+ curModel = shortModel(meta?.model);
70
+ cwd = meta?.workspace || meta?.cwd || null;
71
+ }
72
+
73
+ const events = [];
74
+ const pending = new Map(); // call_id -> { name, args, model }
75
+ let lastPrompt = null; // index of the last user prompt event, until we know who wrote it
76
+
77
+ for await (const line of readLines(file)) {
78
+ const d = tryJSON(line);
79
+ if (!d) continue; // torn tail after a crash is normal
80
+ const t = toMs(d.ts ?? d.timestamp_ms);
81
+ let type;
82
+ let data;
83
+ if (legacy) {
84
+ if (!d.event || typeof d.event !== 'object') continue;
85
+ [type] = Object.keys(d.event);
86
+ data = d.event[type];
87
+ if (type === 'interrupted') type = 'interruption';
88
+ } else {
89
+ if (d.kind === 'session_created') {
90
+ if (d.role === 'child') return [];
91
+ sessionId = d.id || sessionId;
92
+ cwd = d.workspace || null;
93
+ continue;
94
+ }
95
+ if (d.kind === 'set' && d.key === 'prefs') {
96
+ curModel = shortModel(d.value?.model) || curModel;
97
+ continue;
98
+ }
99
+ if (d.kind === 'turn_interrupted') {
100
+ if (d.reason === 'cancel') events.push({ type: 'interrupt', t });
101
+ continue;
102
+ }
103
+ if (d.kind !== 'item') continue;
104
+ type = d.type;
105
+ data = await loadBlob(dir, d.data);
106
+ }
107
+ if (!data || typeof data !== 'object') continue;
108
+
109
+ switch (type) {
110
+ case 'user': {
111
+ if (data.work_id) break; // written by a parent agent
112
+ const text = String(data.text || '').trim();
113
+ if (!text) break;
114
+ lastPrompt = events.length;
115
+ events.push({ type: 'prompt', t, text, key: `fx:${sessionId}:${d.seq ?? events.length}` });
116
+ break;
117
+ }
118
+ case 'author':
119
+ // A user item followed by author {by: child|parent} wasn't typed by the human.
120
+ if ((data.by === 'child' || data.by === 'parent') && lastPrompt != null && events[lastPrompt]?.type === 'prompt') {
121
+ events.splice(lastPrompt, 1);
122
+ }
123
+ lastPrompt = null;
124
+ break;
125
+ case 'model_call':
126
+ if (data.model) curModel = data.model;
127
+ break;
128
+ case 'assistant': {
129
+ lastPrompt = null;
130
+ const model = data.provider_replay?.source?.model || curModel;
131
+ if (!model) break;
132
+ events.push({ type: 'assistant', t, model, text: String(data.text || ''), tools: 0 });
133
+ break;
134
+ }
135
+ case 'tool_call': {
136
+ lastPrompt = null;
137
+ const model = curModel;
138
+ if (data.argument_integrity === 'malformed_json' || data.argument_integrity === 'non_object_json') {
139
+ events.push({ type: 'tool', t, model, name: data.tool_name, kind: 'other', status: 'malformed' });
140
+ break;
141
+ }
142
+ pending.set(data.call_id, { name: data.tool_name, args: tryJSON(data.arguments_json) || {}, model });
143
+ const last = events[events.length - 1];
144
+ if (last?.type === 'assistant') last.tools++;
145
+ break;
146
+ }
147
+ case 'tool_result': {
148
+ const call = pending.get(data.call_id) || { name: data.tool_name, args: {}, model: curModel };
149
+ pending.delete(data.call_id);
150
+ const kind = toolKind(call.name);
151
+ let status = data.status === 'failure' ? classifyToolError(data.preview) : 'ok';
152
+ const proc = data.command_process_presentation;
153
+ if (kind === 'shell' && proc && typeof proc === 'object' && typeof proc.exit_code === 'number' && proc.exit_code !== 0) status = 'error';
154
+ const ev = { type: 'tool', t, model: call.model, name: call.name, kind, status };
155
+ if (kind === 'edit' && status === 'ok') {
156
+ const a = call.args;
157
+ if (call.name === 'write_file' && a.path) ev.edits = [{ path: a.path, mode: 'write', removed: [], added: diffLines('', a.content).added }];
158
+ else if (a.path) ev.edits = [{ path: a.path, mode: 'patch', ...diffLines(a.old_string, a.new_string) }];
159
+ }
160
+ events.push(ev);
161
+ break;
162
+ }
163
+ case 'interruption':
164
+ if (legacy && (data.reason === 'cancelled' || data.reason === 'cancel')) events.push({ type: 'interrupt', t });
165
+ break;
166
+ default:
167
+ break;
168
+ }
169
+ }
170
+ return [{ agent: id, id: sessionId, cwd, file, events }];
171
+ }