@agentshouse/kit 0.2.1-ceeaf32286734 → 0.2.1-ceffdba88db37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/events.js CHANGED
@@ -1,13 +1,23 @@
1
+ import { firstPart, keptDiff, lastLines } from '@agentshouse/session-content';
1
2
  const AUTONOMOUS_ORIGINS = new Set(['task-notification', 'peer', 'coordinator', 'observer', 'observer-activity']);
2
- const COMMAND = { shown: 'command' };
3
- const HIDDEN = { shown: 'hidden' };
4
- const FINISHED = new Set(['completed', 'failed']);
3
+ const FINISHED = new Set(['completed', 'failed', 'stopped']);
5
4
  export const RUNNING_JOB = new Set(['running', 'paused']);
6
5
  const MESSAGE_TARGETS = new Map([
7
- ['send_routine_request', ['routine', 'agent']],
8
- ['cancel_routine_request', ['request']],
9
- ['send_mail', ['conversation', 'request']],
6
+ ['agent-functions/send', ['agent_function', 'agent']],
7
+ ['agent-functions/cancel', ['request']],
8
+ ['agent-functions/mail/send', ['conversation', 'request']],
10
9
  ]);
10
+ const PLANNED = { pending: 'pending', in_progress: 'running', completed: 'done' };
11
+ const ENDED = { completed: 'done', failed: 'failed', stopped: 'stopped', killed: 'stopped', cancelled: 'stopped' };
12
+ const NOTICES = { info: 'info', warning: 'warning', error: 'error' };
13
+ // Claude Code names its limit windows without their length, so the Kit holds the length each name stands for.
14
+ const WINDOW_MINUTES = { five_hour: 300, seven_day: 10_080 };
15
+ const WAKEUP = /Next wakeup scheduled for \d\d:\d\d:\d\d \(in (\d+)s\)/;
16
+ const CHILD_UPDATES = new Set(['tool_call', 'tool_call_update', 'agent_message_chunk', 'agent_thought_chunk']);
17
+ function counted(reports) {
18
+ const whole = reports.every((tokens) => Object.values(tokens).every((count) => Number.isSafeInteger(count) && count >= 0));
19
+ return whole ? reports.map((tokens) => ({ kind: 'tokens', tokens })) : [];
20
+ }
11
21
  function words(line) {
12
22
  const found = [];
13
23
  let word = null;
@@ -42,7 +52,7 @@ function words(line) {
42
52
  found.push(word);
43
53
  return found;
44
54
  }
45
- export function houseMessage(line) {
55
+ function houseMessage(line) {
46
56
  const [program, verb, json] = words(line.trim());
47
57
  if (program !== 'house' || verb !== 'run_command' || json === undefined)
48
58
  return null;
@@ -59,23 +69,105 @@ export function houseMessage(line) {
59
69
  if (targets === undefined)
60
70
  return null;
61
71
  const target = targets.map((argument) => call.arguments?.[argument]).find((value) => typeof value === 'string');
62
- return { shown: 'message', command: call.command, target: target ?? null };
72
+ return { command: call.command, target: target ?? null };
63
73
  }
64
- function decidedByLine(command, final) {
74
+ function lineOf(command) {
65
75
  const line = typeof command === 'string' ? command : Array.isArray(command) ? command.at(-1) : undefined;
66
- if (typeof line !== 'string')
67
- return final ? COMMAND : null;
68
- return houseMessage(line) ?? COMMAND;
76
+ return typeof line === 'string' ? line : undefined;
69
77
  }
70
78
  function contentText(content) {
71
- const text = (content ?? [])
79
+ return (content ?? [])
72
80
  .map((entry) => (entry.type === 'content' && entry.content?.type === 'text' ? entry.content.text : ''))
73
81
  .filter((part) => part !== '')
74
82
  .join('\n');
75
- return text === '' ? null : text;
76
83
  }
77
- function plan(entries) {
78
- return entries.map((entry) => ({ content: entry.content, status: entry.status }));
84
+ function blocksText(content) {
85
+ if (typeof content === 'string')
86
+ return content;
87
+ if (!Array.isArray(content))
88
+ return '';
89
+ return content
90
+ .map((block) => (block.type === 'text' ? block.text : ''))
91
+ .filter((part) => part !== '')
92
+ .join('\n');
93
+ }
94
+ function linesOf(text) {
95
+ return text === '' ? [] : text.replace(/\n$/, '').split('\n');
96
+ }
97
+ function count(value) {
98
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
99
+ }
100
+ function statusOf(acp) {
101
+ if (acp === 'completed')
102
+ return 'done';
103
+ if (acp === 'failed' || acp === 'stopped')
104
+ return acp;
105
+ return 'running';
106
+ }
107
+ function instant(milliseconds) {
108
+ return new Date(milliseconds).toISOString();
109
+ }
110
+ function changeCounts(diff) {
111
+ let added = 0;
112
+ let removed = 0;
113
+ for (const line of diff.split('\n')) {
114
+ if (line.startsWith('+') && !line.startsWith('+++'))
115
+ added++;
116
+ if (line.startsWith('-') && !line.startsWith('---'))
117
+ removed++;
118
+ }
119
+ return { added, removed };
120
+ }
121
+ function fileChange(path, diff) {
122
+ return { path, ...changeCounts(diff), diff: keptDiff(diff) };
123
+ }
124
+ function wholeFile(path, sign, text) {
125
+ const lines = linesOf(text);
126
+ const range = sign === '+' ? `-0,0 +1,${lines.length}` : `-1,${lines.length} +0,0`;
127
+ return fileChange(path, lines.length === 0 ? '' : `@@ ${range} @@\n${lines.map((line) => `${sign}${line}\n`).join('')}`);
128
+ }
129
+ function hunks(patch) {
130
+ return patch
131
+ .map((hunk) => `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@\n${hunk.lines.join('\n')}\n`)
132
+ .join('');
133
+ }
134
+ function replacement(site) {
135
+ const before = linesOf((site.line_prefix ?? '') + (site.old_string ?? ''));
136
+ const after = linesOf((site.line_prefix ?? '') + (site.new_string ?? ''));
137
+ let head = 0;
138
+ while (head < before.length && head < after.length && before[head] === after[head])
139
+ head++;
140
+ let tail = 0;
141
+ while (tail < before.length - head && tail < after.length - head && before.at(-1 - tail) === after.at(-1 - tail))
142
+ tail++;
143
+ const removed = before.slice(head, before.length - tail);
144
+ const added = after.slice(head, after.length - tail);
145
+ const lines = [...removed.map((line) => `-${line}\n`), ...added.map((line) => `+${line}\n`)].join('');
146
+ const from = (line, kept) => (line ?? 1) + head - (kept.length === 0 ? 1 : 0);
147
+ const header = `@@ -${from(site.old_line, removed)},${removed.length} +${from(site.new_line, added)},${added.length} @@\n`;
148
+ return { added: added.length, removed: removed.length, diff: lines === '' ? '' : header + lines };
149
+ }
150
+ function replaced(entry) {
151
+ const sites = entry._meta?.details ?? [
152
+ { old_string: entry.oldText, new_string: entry.newText, old_line: entry._meta?.old_line, new_line: entry._meta?.new_line },
153
+ ];
154
+ const hunks = sites.map(replacement);
155
+ return {
156
+ path: entry.path,
157
+ added: hunks.reduce((sum, hunk) => sum + hunk.added, 0),
158
+ removed: hunks.reduce((sum, hunk) => sum + hunk.removed, 0),
159
+ diff: keptDiff(hunks.map((hunk) => hunk.diff).join('')),
160
+ };
161
+ }
162
+ function turnDiffFiles(diff) {
163
+ return diff
164
+ .split(/^diff --git /m)
165
+ .filter((section) => section.trim() !== '')
166
+ .map((section) => {
167
+ const header = section.split('\n')[0];
168
+ const path = /^\+\+\+ b\/(.+)$/m.exec(section)?.[1] ?? header.slice(header.indexOf(' b/') + 3);
169
+ return { path, ...changeCounts(section) };
170
+ });
79
171
  }
80
172
  function merged(into, from) {
81
173
  if (from === null || from === undefined)
@@ -89,22 +181,38 @@ function merged(into, from) {
89
181
  }
90
182
  return result;
91
183
  }
92
- function names(input, ids) {
93
- const values = JSON.stringify(input ?? {});
94
- for (const id of ids)
95
- if (values.includes(id))
96
- return true;
97
- return false;
184
+ function call(held, line, detail, duration = null) {
185
+ const base = { type: 'call', line, status: statusOf(held.status), duration };
186
+ switch (detail.kind) {
187
+ case 'command':
188
+ return { ...base, kind: 'command', exit: held.exit, output: held.output };
189
+ case 'read':
190
+ case 'search':
191
+ return { ...base, kind: detail.kind, returned: detail.returned };
192
+ case 'edit':
193
+ return { ...base, kind: 'edit', files: detail.files };
194
+ default:
195
+ return { ...base, kind: detail.kind, output: firstPart(detail.output) };
196
+ }
197
+ }
198
+ function startedAgent(task, name = null) {
199
+ return { type: 'subagent', kind: 'agent', name, task, status: 'running', step: null, report: null, tokens: null, calls: null, duration: null };
200
+ }
201
+ function backgroundKey(id) {
202
+ return `background ${id}`;
98
203
  }
99
204
  class Reader {
100
205
  session = null;
101
206
  calls = new Map();
102
- subagents = new Set();
103
- done = new Set();
207
+ subagents = new Map();
208
+ owners = new Map();
209
+ backgrounds = new Map();
210
+ work = new Map();
104
211
  seenOptions = new Map();
105
212
  requestedOptions = new Map();
106
213
  compactions = new Set();
107
- jobs = new Map();
214
+ turns = new Set();
215
+ edits = new Map();
108
216
  read(message) {
109
217
  if (message.method === undefined)
110
218
  return this.answered(message.result);
@@ -114,20 +222,29 @@ class Reader {
114
222
  }
115
223
  return this.own(message);
116
224
  }
225
+ tap(_message) {
226
+ return [];
227
+ }
117
228
  requested(option, value) {
118
229
  this.requestedOptions.set(option, value);
119
230
  }
120
231
  refused(option) {
121
232
  this.requestedOptions.delete(option);
122
233
  }
234
+ began() {
235
+ this.edits.clear();
236
+ return this.editedFiles();
237
+ }
123
238
  closeTurn() {
124
239
  const events = [];
125
- for (const [id, call] of this.calls) {
126
- if (call.decided?.shown === 'subagent')
240
+ for (const [id, held] of this.calls) {
241
+ if (held.shown === 'subagent')
127
242
  continue;
128
- if (call.decided === null)
129
- events.push(...this.shown(call, this.decide(call, true)));
130
243
  this.calls.delete(id);
244
+ held.shown ??= this.decide(held, true);
245
+ if (!FINISHED.has(held.status))
246
+ held.status = 'stopped';
247
+ events.push(...this.shown(held));
131
248
  }
132
249
  return events;
133
250
  }
@@ -146,28 +263,28 @@ class Reader {
146
263
  own(message) {
147
264
  if (message.method !== 'session/update')
148
265
  return this.extension(message);
149
- return this.update(message.params.update);
266
+ return this.update(message.params.update, null);
150
267
  }
151
268
  extension(_message) {
152
269
  return [];
153
270
  }
154
- update(update) {
271
+ update(update, parent) {
155
272
  switch (update.sessionUpdate) {
156
273
  case 'agent_message_chunk':
157
274
  if (update.content.type === 'image')
158
- return [{ kind: 'image', data: update.content.data, mediaType: update.content.mimeType }];
159
- return update.content.type === 'text' ? [{ kind: 'text', id: update.messageId ?? null, text: update.content.text }] : [];
275
+ return [{ kind: 'image', data: update.content.data, mediaType: update.content.mimeType, parent }];
276
+ return update.content.type === 'text' ? [{ kind: 'text', id: update.messageId ?? null, parent, text: update.content.text }] : [];
160
277
  case 'agent_thought_chunk':
161
- return update.content.type === 'text' ? [{ kind: 'reasoning', id: update.messageId ?? null, text: update.content.text }] : [];
278
+ return update.content.type === 'text' ? [{ kind: 'reasoning', id: update.messageId ?? null, parent, text: update.content.text }] : [];
162
279
  case 'tool_call':
163
280
  case 'tool_call_update':
164
- return this.tool(update);
281
+ return this.tool(update, parent);
165
282
  case 'plan':
166
- return [{ kind: 'plan', entries: plan(update.entries) }];
283
+ return [{ kind: 'plan', entries: update.entries.map((entry) => ({ content: entry.content, status: PLANNED[entry.status] ?? 'pending' })) }];
167
284
  case 'usage_update':
168
- return [{ kind: 'context', used: update.used, window: update.size }];
285
+ return [{ kind: 'state', state: this.used(update) }];
169
286
  case 'current_mode_update':
170
- return [{ kind: 'marker', marker: 'mode', text: update.currentModeId }];
287
+ return [{ kind: 'notice', notice: 'mode', text: update.currentModeId }];
171
288
  case 'available_commands_update':
172
289
  return [{ kind: 'commands', commands: update.availableCommands }];
173
290
  case 'config_option_update':
@@ -176,201 +293,490 @@ class Reader {
176
293
  if (update.status !== 'completed' || this.compactions.has(update.compactionId))
177
294
  return [];
178
295
  this.compactions.add(update.compactionId);
179
- return [{ kind: 'marker', marker: 'compaction', text: '' }];
296
+ return [{ kind: 'notice', notice: 'compaction', text: '' }];
297
+ case 'session_info_update':
298
+ return this.info(update);
299
+ case 'notice': {
300
+ const said = [update.title, update.description].filter((text) => typeof text === 'string' && text !== '');
301
+ return [{ kind: 'notice', notice: NOTICES[update.severity] ?? 'info', text: said.join('\n') }];
302
+ }
180
303
  case 'async_task_spawned':
181
- return this.job(update.asyncTaskId, update.name ?? update.description ?? '', 'running');
304
+ if (update.taskType === 'turn') {
305
+ this.turns.add(update.asyncTaskId);
306
+ return [];
307
+ }
308
+ return [
309
+ ...this.handedOff(update.toolCallId),
310
+ ...this.background(update.asyncTaskId, update.taskType === 'shell' || update.taskType === 'monitor' ? update.taskType : 'task', update.name ?? update.description ?? '', 'running'),
311
+ ];
312
+ case 'async_task_progress': {
313
+ const held = this.backgrounds.get(update.asyncTaskId);
314
+ const progress = update.description ?? update.summary;
315
+ if (held === undefined || typeof progress !== 'string')
316
+ return [];
317
+ return this.runs(backgroundKey(update.asyncTaskId), { kind: held.kind, label: held.label, progress, next: null });
318
+ }
182
319
  case 'async_task_state_update':
183
- return RUNNING_JOB.has(update.state) ? [] : this.job(update.asyncTaskId, null, update.state);
320
+ if (this.turns.has(update.asyncTaskId)) {
321
+ if (!RUNNING_JOB.has(update.state))
322
+ this.turns.delete(update.asyncTaskId);
323
+ return [];
324
+ }
325
+ if (RUNNING_JOB.has(update.state) || !this.backgrounds.has(update.asyncTaskId))
326
+ return [];
327
+ return this.background(update.asyncTaskId, this.backgrounds.get(update.asyncTaskId).kind, null, ENDED[update.state] ?? 'done');
184
328
  default:
185
329
  return [];
186
330
  }
187
331
  }
188
- job(id, name, state) {
189
- if (name !== null)
190
- this.jobs.set(id, name);
191
- const label = this.jobs.get(id) ?? '';
192
- if (state !== 'running')
193
- this.jobs.delete(id);
194
- return [{ kind: 'marker', marker: 'job', text: `${label}: ${state}` }];
332
+ used(update) {
333
+ return { context: { used: update.used, window: update.size, breakdown: [] } };
334
+ }
335
+ info(update) {
336
+ const suggestion = update._meta?.promptSuggestions?.suggestions?.[0]?.text;
337
+ const state = {
338
+ ...(typeof update.title === 'string' ? { title: update.title } : {}),
339
+ ...(typeof suggestion === 'string' ? { suggestion } : {}),
340
+ };
341
+ return Object.keys(state).length === 0 ? [] : [{ kind: 'state', state }];
342
+ }
343
+ handedOff(id) {
344
+ const held = id === undefined ? undefined : this.calls.get(id);
345
+ if (held === undefined || FINISHED.has(held.status))
346
+ return [];
347
+ held.status = 'completed';
348
+ return this.shown(held);
349
+ }
350
+ background(id, kind, label, status, next = null) {
351
+ const part = { type: 'background', kind, label: label ?? this.backgrounds.get(id)?.label ?? '', status };
352
+ if (status === 'running')
353
+ this.backgrounds.set(id, part);
354
+ else
355
+ this.backgrounds.delete(id);
356
+ return [
357
+ { kind: 'part', key: backgroundKey(id), parent: null, part },
358
+ ...this.runs(backgroundKey(id), status === 'running' ? { kind, label: part.label, progress: null, next } : null),
359
+ ];
360
+ }
361
+ forget(id) {
362
+ this.backgrounds.delete(id);
363
+ return this.runs(backgroundKey(id), null);
364
+ }
365
+ runs(key, running) {
366
+ const before = JSON.stringify([...this.work.values()]);
367
+ if (running === null)
368
+ this.work.delete(key);
369
+ else
370
+ this.work.set(key, running);
371
+ const now = [...this.work.values()];
372
+ return JSON.stringify(now) === before ? [] : [{ kind: 'state', state: { running: now } }];
195
373
  }
196
374
  optionsChanged(options) {
197
375
  const events = [];
198
376
  for (const option of options) {
199
- const marker = this.watchedOptions[option.id];
377
+ const notice = this.watchedOptions[option.id];
200
378
  const before = this.seenOptions.get(option.id);
201
379
  this.seenOptions.set(option.id, option.currentValue);
202
- if (marker === undefined || before === undefined || before === option.currentValue)
380
+ if (notice === undefined || before === undefined || before === option.currentValue)
203
381
  continue;
204
382
  if (this.requestedOptions.get(option.id) === option.currentValue) {
205
383
  this.requestedOptions.delete(option.id);
206
384
  continue;
207
385
  }
208
- events.push({ kind: 'marker', marker, text: String(option.currentValue) });
386
+ events.push({ kind: 'notice', notice, text: String(option.currentValue) });
209
387
  }
210
388
  return events;
211
389
  }
212
- tool(update) {
213
- let call = this.calls.get(update.toolCallId);
214
- if (call === undefined) {
390
+ tool(update, parent) {
391
+ let held = this.calls.get(update.toolCallId);
392
+ if (held === undefined) {
215
393
  if (update.sessionUpdate !== 'tool_call')
216
394
  return [];
217
- call = { id: update.toolCallId, decided: null, meta: {}, imaged: false, status: 'in_progress' };
218
- this.calls.set(call.id, call);
395
+ held = { id: update.toolCallId, parent, shown: null, meta: {}, output: '', exit: null, imaged: false, status: 'in_progress' };
396
+ this.calls.set(held.id, held);
219
397
  }
220
398
  if (update.kind !== undefined)
221
- call.kind = update.kind;
399
+ held.kind = update.kind;
222
400
  if (update.title !== undefined)
223
- call.title = update.title;
224
- if (update.status !== undefined)
225
- call.status = update.status;
401
+ held.title = update.title;
402
+ if (update.status !== undefined && !FINISHED.has(held.status))
403
+ held.status = update.status;
226
404
  if (update.rawInput !== undefined)
227
- call.rawInput = merged(call.rawInput ?? {}, update.rawInput);
405
+ held.rawInput = merged(held.rawInput ?? {}, update.rawInput);
406
+ if (update.rawOutput !== undefined)
407
+ held.rawOutput = update.rawOutput;
228
408
  if (update.content !== undefined)
229
- call.content = update.content;
230
- call.meta = merged(call.meta, update._meta);
231
- const events = [];
232
- const finished = FINISHED.has(call.status);
233
- if (call.decided === null) {
234
- const decided = this.decide(call, finished);
235
- if (decided !== null)
236
- events.push(...this.shown(call, decided));
237
- }
238
- events.push(...this.produced(call));
239
- if (call.decided?.shown === 'subagent' && finished)
240
- events.push(...this.subagentFinished(call));
241
- else if (finished)
242
- this.calls.delete(call.id);
243
- return events;
409
+ held.content = update.content;
410
+ const meta = (update._meta ?? {});
411
+ if (typeof meta.terminal_output?.data === 'string')
412
+ held.output = lastLines(held.output + meta.terminal_output.data);
413
+ if (meta.terminal_exit !== undefined)
414
+ held.exit = meta.terminal_exit.exit_code ?? null;
415
+ held.meta = merged(held.meta, meta);
416
+ return this.shown(held);
244
417
  }
245
- shown(call, decided) {
246
- call.decided = decided;
247
- switch (decided.shown) {
248
- case 'command':
249
- return [{ kind: 'command' }];
250
- case 'hidden':
251
- return [];
252
- case 'message':
253
- return [{ kind: 'message', command: decided.command, target: decided.target }];
254
- case 'marker':
255
- return [{ kind: 'marker', marker: decided.marker, text: decided.text }];
256
- case 'subagent':
257
- this.subagents.add(call.id);
258
- return [{ kind: 'subagent', id: call.id, description: decided.description }];
418
+ shown(held) {
419
+ held.shown ??= this.decide(held, FINISHED.has(held.status));
420
+ if (held.shown === null)
421
+ return [];
422
+ if (held.shown === 'subagent')
423
+ return this.subagent(held.id, held.parent, this.subagentOf(held));
424
+ if (held.shown === 'message') {
425
+ const message = houseMessage(lineOf(held.rawInput?.command) ?? held.title ?? '');
426
+ return [{ kind: 'part', key: held.id, parent: held.parent, part: { type: 'message', command: message.command, target: message.target } }];
259
427
  }
428
+ const part = this.callOf(held);
429
+ return [{ kind: 'part', key: held.id, parent: held.parent, part }, ...this.edited(held.id, part), ...this.produced(held)];
260
430
  }
261
- produced(_call) {
262
- return [];
431
+ subagent(key, parent, part) {
432
+ if (!this.owners.has(key))
433
+ this.owners.set(key, parent);
434
+ if (part.status === 'running')
435
+ this.subagents.set(key, part);
436
+ else
437
+ this.subagents.delete(key);
438
+ return [
439
+ { kind: 'part', key, parent: this.owners.get(key), part },
440
+ ...this.runs(key, part.status === 'running' ? { kind: 'subagent', label: part.task, progress: part.step, next: null } : null),
441
+ ];
263
442
  }
264
- subagentFinished(call) {
265
- this.calls.delete(call.id);
266
- return this.finish(call.id, contentText(call.content));
443
+ filesFromEdits() {
444
+ return true;
267
445
  }
268
- finish(id, result) {
269
- if (!this.subagents.has(id) || this.done.has(id))
446
+ edited(key, part) {
447
+ if (part.type !== 'call' || part.kind !== 'edit' || !this.filesFromEdits())
270
448
  return [];
271
- this.done.add(id);
272
- this.calls.delete(id);
273
- return [{ kind: 'subagent-done', id, result }];
449
+ this.edits.set(key, part.files);
450
+ return this.editedFiles();
451
+ }
452
+ editedFiles() {
453
+ const files = new Map();
454
+ for (const change of [...this.edits.values()].flat()) {
455
+ const held = files.get(change.path);
456
+ files.set(change.path, { path: change.path, added: (held?.added ?? 0) + change.added, removed: (held?.removed ?? 0) + change.removed });
457
+ }
458
+ return [{ kind: 'state', state: { files: [...files.values()] } }];
459
+ }
460
+ decideLine(line, final) {
461
+ if (line === undefined)
462
+ return final ? 'call' : null;
463
+ return houseMessage(line) === null ? 'call' : 'message';
464
+ }
465
+ produced(_call) {
466
+ return [];
274
467
  }
275
468
  }
276
469
  class ClaudeReader extends Reader {
277
470
  watchedOptions = { model: 'model' };
278
- tasks = new Map();
471
+ figures = new Map();
472
+ answers = new Map();
473
+ asked = new Map();
474
+ windows = new Map();
475
+ crons = new Map();
476
+ wakeups = new Map();
477
+ breakdown = [];
279
478
  stop = null;
479
+ answered(result) {
480
+ const models = (result?._meta?.quota?.model_usage ?? []);
481
+ const spent = counted(models.map(({ token_count: count }) => ({
482
+ input: count?.inputTokens,
483
+ output: count?.outputTokens,
484
+ cache_read: count?.cachedInputTokens,
485
+ cache_write: count?.cachedWriteTokens,
486
+ })));
487
+ return [...spent, ...super.answered(result)];
488
+ }
489
+ began() {
490
+ const fired = [...this.wakeups].filter(([, next]) => next <= Date.now()).map(([id]) => id);
491
+ for (const id of fired)
492
+ this.wakeups.delete(id);
493
+ return [...super.began(), ...fired.flatMap((id) => this.forget(id))];
494
+ }
280
495
  own(message) {
281
- if (message.params?.update?._meta?.claudeCode?.parentToolUseId !== undefined)
282
- return [];
283
- return super.own(message);
496
+ const update = message.params?.update;
497
+ const parent = update?._meta?.claudeCode?.parentToolUseId;
498
+ if (parent === undefined)
499
+ return super.own(message);
500
+ return update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update' ? this.tool(update, parent) : [];
284
501
  }
285
- update(update) {
502
+ used(update) {
503
+ const cost = update.cost;
504
+ return {
505
+ context: { used: update.used, window: update.size, breakdown: this.breakdown },
506
+ ...(typeof cost?.amount === 'number' ? { cost: { amount: cost.amount, currency: cost.currency } } : {}),
507
+ };
508
+ }
509
+ update(update, parent) {
286
510
  if (update.sessionUpdate === 'usage_update' && update._meta?.['_claude/origin'] !== undefined) {
287
511
  const stop = this.stop;
288
512
  this.stop = null;
289
- return [...super.update(update), { kind: 'ended', stop }];
513
+ return [...super.update(update, parent), { kind: 'ended', stop }];
290
514
  }
291
515
  if (update.sessionUpdate === 'session_info_update' && update._meta?.jetbrains?.air?.sessionFailure !== undefined) {
292
- return [{ kind: 'marker', marker: 'retry', text: update._meta.jetbrains.air.sessionFailure.title }];
516
+ return [{ kind: 'notice', notice: 'retry', text: update._meta.jetbrains.air.sessionFailure.title }];
293
517
  }
294
- return super.update(update);
518
+ return super.update(update, parent);
295
519
  }
296
520
  extension(message) {
297
521
  if (message.method !== '_claude/sdkMessage')
298
522
  return [];
299
523
  const sdk = message.params.message;
300
- if (sdk.type === 'result') {
301
- if (AUTONOMOUS_ORIGINS.has(sdk.origin?.kind))
302
- this.stop = null;
303
- else
304
- this.stop = sdk.stop_reason === 'refusal' ? 'refusal' : sdk.is_error === true ? null : 'end_turn';
305
- return [];
524
+ switch (sdk.type) {
525
+ case 'result':
526
+ if (AUTONOMOUS_ORIGINS.has(sdk.origin?.kind))
527
+ this.stop = null;
528
+ else
529
+ this.stop = sdk.stop_reason === 'refusal' ? 'refusal' : sdk.is_error === true ? null : 'end_turn';
530
+ return count(sdk.duration_ms) === null ? [] : [{ kind: 'state', state: { duration: sdk.duration_ms } }];
531
+ case 'assistant':
532
+ return this.assistant(sdk);
533
+ case 'user':
534
+ return this.user(sdk);
535
+ case 'rate_limit_event':
536
+ return this.limited(sdk.rate_limit_info);
306
537
  }
538
+ if (typeof sdk.tool_use_id !== 'string')
539
+ return [];
307
540
  switch (sdk.subtype) {
308
541
  case 'task_started':
309
- if (sdk.tool_use_id !== undefined)
310
- this.tasks.set(sdk.task_id, sdk.tool_use_id);
311
- return [];
312
- case 'task_notification':
313
- return sdk.tool_use_id === undefined ? [] : this.finish(sdk.tool_use_id, sdk.summary ?? null);
542
+ return typeof sdk.subagent_type === 'string' ? this.figured(sdk.tool_use_id, { name: sdk.subagent_type }) : [];
314
543
  case 'task_progress':
315
- if (!this.subagents.has(sdk.tool_use_id) || this.done.has(sdk.tool_use_id) || typeof sdk.description !== 'string')
316
- return [];
317
- return [{ kind: 'subagent-activity', id: sdk.tool_use_id, activity: sdk.description }];
544
+ return this.figured(sdk.tool_use_id, { step: typeof sdk.description === 'string' ? sdk.description : null, ...this.usage(sdk.usage) });
545
+ case 'task_notification':
546
+ return this.figured(sdk.tool_use_id, {
547
+ status: ENDED[sdk.status] ?? 'done',
548
+ ...(typeof sdk.summary === 'string' ? { report: sdk.summary } : {}),
549
+ ...this.usage(sdk.usage),
550
+ });
318
551
  default:
319
552
  return [];
320
553
  }
321
554
  }
322
- decide(call, final) {
323
- const tool = call.meta.claudeCode?.toolName;
324
- if (tool === 'Agent' || tool === 'Task' || call.meta.jetbrains?.air?.subagent === true) {
325
- const description = call.rawInput?.description;
326
- if (description === undefined && !final)
327
- return null;
328
- return { shown: 'subagent', description: description ?? call.title ?? '' };
555
+ usage(usage) {
556
+ if (usage === undefined)
557
+ return {};
558
+ return { tokens: count(usage.total_tokens), calls: count(usage.tool_uses), duration: count(usage.duration_ms) };
559
+ }
560
+ figured(key, figures) {
561
+ const held = this.calls.get(key);
562
+ if (held?.shown !== 'subagent' && held !== undefined)
563
+ return [];
564
+ this.figures.set(key, { ...this.figures.get(key), ...figures });
565
+ return held === undefined ? [] : this.shown(held);
566
+ }
567
+ assistant(sdk) {
568
+ const at = Date.parse(sdk.timestamp);
569
+ const events = [];
570
+ const usage = sdk.context_usage;
571
+ if (usage !== undefined) {
572
+ this.breakdown = usage.categories.map((category) => ({ name: category.name, tokens: category.tokens }));
573
+ events.push({ kind: 'state', state: { context: { used: usage.total_tokens, window: usage.raw_max_tokens, breakdown: this.breakdown } } });
329
574
  }
330
- if (tool === 'TodoWrite' || tool === 'CronCreate')
331
- return HIDDEN;
332
- if (tool === 'ScheduleWakeup') {
333
- if (call.rawInput === undefined)
334
- return final ? COMMAND : null;
335
- return call.rawInput.stop === true ? COMMAND : HIDDEN;
575
+ const parent = sdk.parent_tool_use_id;
576
+ for (const block of (sdk.message?.content ?? [])) {
577
+ if (block.type === 'tool_use' && !Number.isNaN(at))
578
+ this.asked.set(block.id, at);
579
+ if (parent === null)
580
+ continue;
581
+ if (block.type === 'text')
582
+ events.push({ kind: 'text', id: sdk.message.id ?? null, parent, text: block.text });
583
+ if (block.type === 'thinking')
584
+ events.push({ kind: 'reasoning', id: sdk.message.id ?? null, parent, text: block.thinking });
585
+ }
586
+ return events;
587
+ }
588
+ user(sdk) {
589
+ const content = sdk.message?.content;
590
+ if (!Array.isArray(content))
591
+ return [];
592
+ const events = [];
593
+ for (const block of content) {
594
+ if (block.type !== 'tool_result')
595
+ continue;
596
+ this.answers.set(block.tool_use_id, { result: (sdk.tool_use_result ?? {}), content: block.content, at: Date.parse(sdk.timestamp) });
597
+ const held = this.calls.get(block.tool_use_id);
598
+ if (held !== undefined)
599
+ events.push(...this.shown(held));
600
+ }
601
+ return events;
602
+ }
603
+ limited(info) {
604
+ for (const [name, window] of Object.entries((info?.unifiedWindows ?? {}))) {
605
+ const minutes = WINDOW_MINUTES[name] ?? WINDOW_MINUTES[name.replace(/_[a-z]+$/, '')];
606
+ if (typeof window.utilization !== 'number' || minutes === undefined)
607
+ continue;
608
+ this.windows.set(name, {
609
+ name: name in WINDOW_MINUTES ? null : name,
610
+ minutes,
611
+ percent: Math.round(window.utilization * 1000) / 10,
612
+ resets: typeof window.resetsAt === 'number' ? instant(window.resetsAt * 1000) : null,
613
+ });
614
+ }
615
+ return this.windows.size === 0 ? [] : [{ kind: 'state', state: { limits: [...this.windows.values()] } }];
616
+ }
617
+ toolName(held) {
618
+ return held.meta.claudeCode?.toolName ?? '';
619
+ }
620
+ decide(held, final) {
621
+ const tool = this.toolName(held);
622
+ if (tool === 'Agent' || tool === 'Task' || held.meta.jetbrains?.air?.subagent === true) {
623
+ return held.rawInput?.description === undefined && !final ? null : 'subagent';
336
624
  }
337
- if (call.kind === 'switch_mode')
338
- return { shown: 'marker', marker: 'mode', text: call.title ?? '' };
339
625
  if (tool === 'Bash')
340
- return decidedByLine(call.rawInput?.command, final);
341
- if (tool === 'SendMessage' || tool === 'TaskStop') {
342
- if (call.rawInput === undefined)
343
- return final ? COMMAND : null;
344
- return names(call.rawInput, this.tasks.keys()) ? HIDDEN : COMMAND;
626
+ return this.decideLine(lineOf(held.rawInput?.command), final);
627
+ return 'call';
628
+ }
629
+ subagentOf(held) {
630
+ const answered = this.answers.get(held.id)?.result;
631
+ const launched = held.meta.claudeCode?.toolResponse?.isAsync === true || answered?.status === 'async_launched';
632
+ const reported = (Array.isArray(answered?.content) ? answered.content : []).filter((block) => block.type === 'text').at(-1)?.text;
633
+ const finished = launched || (!FINISHED.has(held.status) && answered === undefined)
634
+ ? {}
635
+ : {
636
+ status: held.status === 'failed' ? 'failed' : 'done',
637
+ report: reported ?? (contentText(held.content) || null),
638
+ tokens: count(answered?.totalTokens),
639
+ calls: count(answered?.totalToolUseCount),
640
+ duration: count(answered?.totalDurationMs),
641
+ };
642
+ return { ...startedAgent(held.rawInput?.description ?? held.title ?? '', held.rawInput?.subagent_type ?? null), ...finished, ...this.figures.get(held.id) };
643
+ }
644
+ callOf(held) {
645
+ const tool = this.toolName(held);
646
+ const title = held.title ?? tool;
647
+ const answered = this.answers.get(held.id);
648
+ const result = answered?.result ?? {};
649
+ const output = contentText(held.content) || blocksText(answered?.content);
650
+ const asked = this.asked.get(held.id);
651
+ const took = answered === undefined || asked === undefined || Number.isNaN(answered.at) ? null : Math.max(0, answered.at - asked);
652
+ if (tool.startsWith('mcp__'))
653
+ return call(held, title, { kind: 'tool', output }, took);
654
+ switch (tool) {
655
+ case 'Bash':
656
+ return call(held, lineOf(held.rawInput?.command) ?? title, { kind: 'command' }, took);
657
+ case 'Read':
658
+ return call(held, title, { kind: 'read', returned: count(result.file?.numLines) }, took);
659
+ case 'Grep':
660
+ case 'Glob':
661
+ return call(held, title, { kind: 'search', returned: count(result.numLines) ?? count(result.numFiles) }, took);
662
+ case 'WebSearch': {
663
+ const found = Array.isArray(result.results) ? result.results.flatMap((entry) => (Array.isArray(entry?.content) ? entry.content : [])).length : null;
664
+ return call(held, title, { kind: 'search', returned: found }, typeof result.durationSeconds === 'number' ? Math.round(result.durationSeconds * 1000) : took);
665
+ }
666
+ case 'WebFetch':
667
+ return call(held, title, { kind: 'fetch', output: typeof result.result === 'string' ? result.result : output }, count(result.durationMs) ?? took);
345
668
  }
346
- return COMMAND;
669
+ if (held.kind === 'edit')
670
+ return call(held, title, { kind: 'edit', files: this.claudeFiles(held, result) }, took);
671
+ if (held.kind === 'read' || held.kind === 'search')
672
+ return call(held, title, { kind: held.kind, returned: null }, took);
673
+ if (held.kind === 'fetch')
674
+ return call(held, title, { kind: 'fetch', output }, took);
675
+ return call(held, title, { kind: 'other', output }, took);
347
676
  }
348
- produced(call) {
349
- const tool = call.meta.claudeCode?.toolName;
350
- if (call.status !== 'completed')
677
+ claudeFiles(held, result) {
678
+ const path = result.filePath ?? held.rawInput?.file_path;
679
+ if (typeof path !== 'string')
351
680
  return [];
352
- if (tool === 'CronCreate' || (tool === 'ScheduleWakeup' && call.rawInput?.stop !== true)) {
353
- return [{ kind: 'marker', marker: 'job', text: `${call.rawInput?.prompt ?? call.title ?? ''}: scheduled` }];
354
- }
681
+ if (Array.isArray(result.structuredPatch) && result.structuredPatch.length > 0)
682
+ return [fileChange(path, hunks(result.structuredPatch))];
683
+ if (result.type === 'create' && typeof result.content === 'string')
684
+ return [wholeFile(path, '+', result.content)];
355
685
  return [];
356
686
  }
357
- subagentFinished(call) {
358
- if (call.meta.claudeCode?.toolResponse?.isAsync === true)
687
+ produced(held) {
688
+ if (held.status !== 'completed')
689
+ return [];
690
+ const tool = this.toolName(held);
691
+ const result = this.answers.get(held.id)?.result ?? {};
692
+ if (tool === 'CronCreate' && typeof result.id === 'string' && !this.crons.has(result.id)) {
693
+ this.crons.set(result.id, held.id);
694
+ const next = typeof result.nextFireAt === 'number' ? instant(result.nextFireAt) : null;
695
+ return this.background(held.id, 'schedule', held.rawInput?.prompt ?? held.title ?? '', 'running', next);
696
+ }
697
+ if (tool === 'CronDelete' && typeof held.rawInput?.id === 'string' && this.crons.has(held.rawInput.id)) {
698
+ const created = this.crons.get(held.rawInput.id);
699
+ this.crons.delete(held.rawInput.id);
700
+ return this.background(created, 'schedule', null, 'stopped');
701
+ }
702
+ if (tool !== 'ScheduleWakeup' || this.wakeups.has(held.id))
703
+ return [];
704
+ if (held.rawInput?.stop === true) {
705
+ const stopped = [...this.wakeups.keys()];
706
+ this.wakeups.clear();
707
+ return stopped.flatMap((id) => this.background(id, 'schedule', null, 'stopped'));
708
+ }
709
+ const seconds = WAKEUP.exec(contentText(held.content))?.[1];
710
+ if (seconds === undefined)
359
711
  return [];
360
- return super.subagentFinished(call);
712
+ const next = Date.now() + Number(seconds) * 1000;
713
+ this.wakeups.set(held.id, next);
714
+ return this.background(held.id, 'schedule', held.rawInput?.prompt ?? held.rawInput?.reason ?? held.title ?? '', 'running', instant(next));
361
715
  }
362
716
  }
363
- const COLLABORATION = new Set(['spawnAgent', 'sendInput', 'resumeAgent', 'wait', 'closeAgent', 'followupTask']);
364
717
  class CodexReader extends Reader {
365
718
  watchedOptions = { mode: 'mode', collaboration_mode: 'mode' };
366
719
  children = new Map();
720
+ items = new Map();
721
+ answered(result) {
722
+ const usage = result?.usage;
723
+ const spent = usage === null || usage === undefined
724
+ ? []
725
+ : counted([
726
+ {
727
+ input: usage.inputTokens,
728
+ output: usage.outputTokens,
729
+ cache_read: usage.cachedReadTokens,
730
+ cache_write: usage.cachedWriteTokens,
731
+ },
732
+ ]);
733
+ return [...spent, ...super.answered(result)];
734
+ }
735
+ filesFromEdits() {
736
+ return false;
737
+ }
738
+ tap(message) {
739
+ const params = (message.params ?? {});
740
+ if (message.method === 'account/rateLimits/updated')
741
+ return this.limited(params.rateLimits);
742
+ if (params.threadId !== this.session && !this.children.has(params.threadId))
743
+ return [];
744
+ switch (message.method) {
745
+ case 'item/started':
746
+ case 'item/completed': {
747
+ this.items.set(params.item.id, params.item);
748
+ const held = this.calls.get(params.item.id);
749
+ return held === undefined ? [] : this.shown(held);
750
+ }
751
+ case 'turn/completed':
752
+ return params.threadId === this.session && count(params.turn?.durationMs) !== null ? [{ kind: 'state', state: { duration: params.turn.durationMs } }] : [];
753
+ case 'turn/diff/updated':
754
+ return params.threadId === this.session ? [{ kind: 'state', state: { files: turnDiffFiles(params.diff) } }] : [];
755
+ default:
756
+ return [];
757
+ }
758
+ }
759
+ limited(limits) {
760
+ const windows = [limits?.primary, limits?.secondary].filter((window) => typeof window?.usedPercent === 'number');
761
+ if (windows.length === 0)
762
+ return [];
763
+ const name = typeof limits.limitName === 'string' ? limits.limitName : null;
764
+ const limited = windows.map((window) => ({
765
+ name,
766
+ // Codex sends each window's length; a limit always carries one, so a window Codex sends without it has 0.
767
+ minutes: count(window.windowDurationMins) ?? 0,
768
+ percent: window.usedPercent,
769
+ resets: typeof window.resetsAt === 'number' ? instant(window.resetsAt * 1000) : null,
770
+ }));
771
+ return [{ kind: 'state', state: { limits: limited } }];
772
+ }
367
773
  own(message) {
368
774
  if (message.method === 'session/request_permission' && message.params.toolCall?.kind === 'switch_mode') {
369
- return [{ kind: 'started' }, { kind: 'marker', marker: 'mode', text: message.params.toolCall.title ?? '' }];
775
+ return [{ kind: 'started' }, { kind: 'notice', notice: 'mode', text: message.params.toolCall.title ?? '' }];
370
776
  }
371
777
  return super.own(message);
372
778
  }
373
- update(update) {
779
+ update(update, parent) {
374
780
  switch (update.sessionUpdate) {
375
781
  case 'session_info_update': {
376
782
  const codex = update._meta?.codex;
@@ -379,19 +785,21 @@ class CodexReader extends Reader {
379
785
  if (codex?.threadStatus?.type === 'idle')
380
786
  return [{ kind: 'ended', stop: null }];
381
787
  if (codex?.error !== undefined)
382
- return [{ kind: 'marker', marker: 'retry', text: codex.error.message ?? '' }];
383
- return [];
788
+ return [{ kind: 'notice', notice: 'retry', text: codex.error.message ?? '' }];
789
+ return super.update(update, parent);
384
790
  }
385
- case 'notice':
386
- return update.severity === 'info' ? [{ kind: 'marker', marker: 'model', text: update.description ?? update.title }] : [];
387
791
  case 'subagent_spawned':
388
792
  this.children.set(update.subagentSessionId, { id: null, text: '' });
389
- this.subagents.add(update.subagentSessionId);
390
- return [{ kind: 'subagent', id: update.subagentSessionId, description: update.name }];
391
- case 'subagent_state_update':
392
- return this.finish(update.subagentSessionId, this.children.get(update.subagentSessionId)?.text || null);
793
+ return this.subagent(update.subagentSessionId, parent, startedAgent(update.name));
794
+ case 'subagent_state_update': {
795
+ const held = this.subagents.get(update.subagentSessionId);
796
+ if (held === undefined)
797
+ return [];
798
+ const report = this.children.get(update.subagentSessionId)?.text || null;
799
+ return this.subagent(update.subagentSessionId, parent, { ...held, status: ENDED[update.state] ?? 'failed', report });
800
+ }
393
801
  default:
394
- return super.update(update);
802
+ return super.update(update, parent);
395
803
  }
396
804
  }
397
805
  elsewhere(session, message) {
@@ -406,35 +814,80 @@ class CodexReader extends Reader {
406
814
  child.id = id;
407
815
  child.text += update.content.text;
408
816
  }
409
- return [];
817
+ if (update.sessionUpdate === 'subagent_spawned' || update.sessionUpdate === 'subagent_state_update')
818
+ return this.update(update, session);
819
+ if (!CHILD_UPDATES.has(update.sessionUpdate))
820
+ return [];
821
+ const events = this.update(update, session);
822
+ const step = events.findLast((event) => event.kind === 'part' && event.part.type === 'call');
823
+ const held = this.subagents.get(session);
824
+ if (step?.kind !== 'part' || step.part.type !== 'call' || held === undefined || held.step === step.part.line)
825
+ return events;
826
+ return [...events, ...this.subagent(session, null, { ...held, step: step.part.line })];
827
+ }
828
+ decide(held) {
829
+ if (held.kind === 'execute' && held.meta.is_mcp_tool_call !== true)
830
+ return this.decideLine(lineOf(held.rawInput?.command) ?? held.title, true);
831
+ return 'call';
832
+ }
833
+ subagentOf(held) {
834
+ return startedAgent(held.title ?? '');
835
+ }
836
+ callOf(held) {
837
+ const item = this.items.get(held.id);
838
+ const title = held.title ?? '';
839
+ const took = count(item?.durationMs) ?? (count(item?.startedAtMs) !== null && count(item?.completedAtMs) !== null ? item.completedAtMs - item.startedAtMs : null);
840
+ if (held.meta.is_mcp_tool_call === true) {
841
+ return call(held, title, { kind: 'tool', output: blocksText(held.rawOutput?.result?.content) || contentText(held.content) }, took);
842
+ }
843
+ switch (held.kind) {
844
+ case 'execute':
845
+ return call(held, lineOf(held.rawInput?.command) ?? title, { kind: 'command' }, took);
846
+ case 'read':
847
+ return call(held, title, { kind: 'read', returned: typeof item?.aggregatedOutput === 'string' ? linesOf(item.aggregatedOutput).length : null }, took);
848
+ case 'search':
849
+ return call(held, title, this.searched(held, item), took);
850
+ case 'edit':
851
+ return call(held, title, { kind: 'edit', files: this.codexFiles(item) }, took);
852
+ default:
853
+ return call(held, title, { kind: 'other', output: contentText(held.content) }, took);
854
+ }
855
+ }
856
+ searched(held, item) {
857
+ if (item?.type !== 'webSearch')
858
+ return { kind: 'search', returned: typeof held.rawOutput === 'string' ? linesOf(held.rawOutput).length : null };
859
+ const results = Array.isArray(item.results) ? item.results : null;
860
+ if (item.action?.type === 'openPage' || item.action?.type === 'findInPage') {
861
+ return { kind: 'fetch', output: (results ?? []).map((found) => found.snippet ?? found.title ?? '').join('\n') };
862
+ }
863
+ return { kind: 'search', returned: results === null ? null : results.length };
410
864
  }
411
- decide(call) {
412
- const air = call.meta.jetbrains?.air;
413
- if (COLLABORATION.has(call.title ?? ''))
414
- return HIDDEN;
415
- if (air?.subagent !== undefined)
416
- return { shown: 'subagent', description: call.title ?? '' };
417
- if (call.kind === 'switch_mode')
418
- return { shown: 'marker', marker: 'mode', text: call.title ?? '' };
419
- if (call.kind === 'execute')
420
- return decidedByLine(call.rawInput?.command, true);
421
- if (call.title === 'Image generation')
422
- return HIDDEN;
423
- return COMMAND;
424
- }
425
- produced(call) {
426
- if (call.imaged || call.kind === 'read')
865
+ codexFiles(item) {
866
+ if (item?.type !== 'fileChange')
427
867
  return [];
428
- const image = (call.content ?? []).find((entry) => entry.type === 'content' && entry.content?.type === 'image');
868
+ return item.changes.map((change) => {
869
+ if (change.kind?.type === 'add')
870
+ return wholeFile(change.path, '+', change.diff);
871
+ if (change.kind?.type === 'delete')
872
+ return wholeFile(change.path, '-', change.diff);
873
+ return fileChange(change.kind?.move_path ?? change.path, change.diff);
874
+ });
875
+ }
876
+ produced(held) {
877
+ if (held.imaged || held.kind === 'read')
878
+ return [];
879
+ const image = (held.content ?? []).find((entry) => entry.type === 'content' && entry.content?.type === 'image');
429
880
  if (image === undefined)
430
881
  return [];
431
- call.imaged = true;
432
- return [{ kind: 'image', data: image.content.data, mediaType: image.content.mimeType }];
882
+ held.imaged = true;
883
+ return [{ kind: 'image', data: image.content.data, mediaType: image.content.mimeType, parent: held.parent }];
433
884
  }
434
885
  }
435
886
  class GrokReader extends Reader {
436
887
  watchedOptions = {};
437
888
  children = new Map();
889
+ figures = new Map();
890
+ schedules = new Set();
438
891
  models = [];
439
892
  model = null;
440
893
  answered(result) {
@@ -450,7 +903,9 @@ class GrokReader extends Reader {
450
903
  return (message.params.runningPromptId ?? null) !== null && session === this.session ? [{ kind: 'started' }] : [];
451
904
  }
452
905
  if (message.params?.update?.sessionUpdate === 'turn_completed') {
453
- return session === this.session ? [{ kind: 'ended', stop: null }] : [];
906
+ if (session !== this.session)
907
+ return [];
908
+ return [...this.spent(message.params.update.usage), { kind: 'ended', stop: null }];
454
909
  }
455
910
  if (message.method === '_x.ai/models/update') {
456
911
  this.offered(message.params);
@@ -458,6 +913,20 @@ class GrokReader extends Reader {
458
913
  }
459
914
  return super.read(message);
460
915
  }
916
+ elsewhere(session, message) {
917
+ const parent = this.children.get(session);
918
+ const update = message.params?.update;
919
+ if (typeof parent !== 'string' || message.method !== 'session/update' || !CHILD_UPDATES.has(update?.sessionUpdate))
920
+ return [];
921
+ return this.update(update, parent);
922
+ }
923
+ spent(usage) {
924
+ if (usage === null || usage === undefined)
925
+ return [];
926
+ const { inputTokens, outputTokens, cachedReadTokens, cacheCreationTokens } = usage;
927
+ const input = inputTokens - cachedReadTokens - cacheCreationTokens;
928
+ return counted([{ input, output: outputTokens, cache_read: cachedReadTokens, cache_write: cacheCreationTokens }]);
929
+ }
461
930
  offered(models) {
462
931
  this.models = models.availableModels ?? this.models;
463
932
  this.model = models.currentModelId ?? this.model;
@@ -469,11 +938,18 @@ class GrokReader extends Reader {
469
938
  const update = message.params?.update;
470
939
  switch (message.method) {
471
940
  case '_x.ai/task_backgrounded':
472
- return this.job(update.task_id, update.description ?? update.command ?? '', 'running');
473
- case '_x.ai/task_completed':
474
- return this.job(update.task_snapshot.task_id, null, update.task_snapshot.exit_code === 0 ? 'completed' : 'failed');
475
- case '_x.ai/scheduled_task_created':
476
- return [{ kind: 'marker', marker: 'job', text: `${update.prompt}: next run ${update.next_fire_at}` }];
941
+ return [...this.handedOff(update.tool_call_id), ...this.background(update.task_id, 'shell', update.description ?? update.command ?? '', 'running')];
942
+ case '_x.ai/task_completed': {
943
+ const snapshot = update.task_snapshot;
944
+ return this.background(snapshot.task_id, 'shell', null, snapshot.exit_code === 0 ? 'done' : 'failed');
945
+ }
946
+ case '_x.ai/scheduled_task_created': {
947
+ this.schedules.add(update.task_id);
948
+ const next = Date.parse(update.next_fire_at);
949
+ return this.background(update.task_id, 'schedule', update.prompt ?? '', 'running', Number.isNaN(next) ? null : instant(next));
950
+ }
951
+ case '_x.ai/scheduled_task_deleted':
952
+ return this.schedules.delete(update.task_id) ? this.background(update.task_id, 'schedule', null, 'stopped') : [];
477
953
  case '_x.ai/session_notification':
478
954
  return this.notification(update);
479
955
  default:
@@ -488,49 +964,84 @@ class GrokReader extends Reader {
488
964
  if (window === null)
489
965
  return [];
490
966
  const used = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + usage.output_tokens;
491
- return [{ kind: 'context', used, window }];
967
+ return [{ kind: 'state', state: { context: { used, window, breakdown: [] } } }];
492
968
  }
493
969
  case 'subagent_spawned': {
494
- const call = [...this.calls.values()].find((candidate) => candidate.decided?.shown === 'subagent' &&
495
- ![...this.children.values()].includes(candidate.id) &&
496
- candidate.decided.description === update.description) ??
497
- [...this.calls.values()].find((candidate) => candidate.decided?.shown === 'subagent' && ![...this.children.values()].includes(candidate.id));
498
- this.children.set(update.child_session_id, call?.id ?? null);
499
- return [];
970
+ const linked = [...this.children.values()];
971
+ const unlinked = [...this.calls.values()].filter((candidate) => candidate.shown === 'subagent' && !linked.includes(candidate.id));
972
+ const held = unlinked.find((candidate) => candidate.rawInput?.description === update.description);
973
+ this.children.set(update.child_session_id, held?.id ?? null);
974
+ return held === undefined ? [] : this.figured(held.id, { name: update.subagent_type ?? null });
975
+ }
976
+ case 'subagent_progress': {
977
+ const key = this.children.get(update.child_session_id);
978
+ return typeof key === 'string' ? this.figured(key, { tokens: count(update.tokens_used), calls: count(update.tool_call_count), duration: count(update.duration_ms) }) : [];
500
979
  }
501
980
  case 'subagent_finished': {
502
- const call = this.children.get(update.child_session_id);
503
- return typeof call === 'string' ? this.finish(call, update.output ?? null) : [];
981
+ const key = this.children.get(update.child_session_id);
982
+ if (typeof key !== 'string')
983
+ return [];
984
+ return this.figured(key, {
985
+ status: ENDED[update.status] ?? 'failed',
986
+ report: update.output ?? null,
987
+ tokens: count(update.tokens_used),
988
+ calls: count(update.tool_calls),
989
+ duration: count(update.duration_ms),
990
+ });
504
991
  }
505
992
  case 'auto_compact_completed':
506
- return [{ kind: 'marker', marker: 'compaction', text: '' }];
993
+ return [{ kind: 'notice', notice: 'compaction', text: '' }];
507
994
  case 'model_auto_switched':
508
995
  this.model = update.new_model_id;
509
- return [{ kind: 'marker', marker: 'model', text: update.new_model_id }];
996
+ return [{ kind: 'notice', notice: 'model', text: update.new_model_id }];
510
997
  case 'retry_state':
511
- return [{ kind: 'marker', marker: 'retry', text: update.message ?? update.reason ?? update.error_type ?? '' }];
998
+ return [{ kind: 'notice', notice: 'retry', text: update.message ?? update.reason ?? update.error_type ?? '' }];
512
999
  default:
513
1000
  return [];
514
1001
  }
515
1002
  }
516
- decide(call) {
517
- const tool = (call.meta['x.ai/tool'] ?? {});
518
- if (tool.name === 'spawn_subagent' || tool.kind === 'task') {
519
- return { shown: 'subagent', description: call.rawInput?.description ?? call.title ?? '' };
520
- }
521
- if (tool.name === 'todo_write' || tool.name === 'scheduler_create')
522
- return HIDDEN;
523
- if (tool.name === 'enter_plan_mode' || tool.name === 'exit_plan_mode') {
524
- return { shown: 'marker', marker: 'mode', text: tool.name };
525
- }
526
- if (tool.name === 'kill_command_or_subagent')
527
- return names(call.rawInput, this.children.keys()) ? HIDDEN : COMMAND;
1003
+ figured(key, figures) {
1004
+ this.figures.set(key, { ...this.figures.get(key), ...figures });
1005
+ const held = this.calls.get(key);
1006
+ return held === undefined ? [] : this.shown(held);
1007
+ }
1008
+ xai(held) {
1009
+ return (held.meta['x.ai/tool'] ?? {});
1010
+ }
1011
+ decide(held) {
1012
+ const tool = this.xai(held);
1013
+ if (tool.name === 'spawn_subagent' || tool.kind === 'task')
1014
+ return 'subagent';
528
1015
  if (tool.name === 'run_terminal_command')
529
- return decidedByLine(call.rawInput?.command, true);
530
- return COMMAND;
1016
+ return this.decideLine(lineOf(held.rawInput?.command), true);
1017
+ return 'call';
531
1018
  }
532
- subagentFinished(_call) {
533
- return [];
1019
+ subagentOf(held) {
1020
+ return { ...startedAgent(held.rawInput?.description ?? held.title ?? ''), ...this.figures.get(held.id) };
1021
+ }
1022
+ callOf(held) {
1023
+ const tool = this.xai(held);
1024
+ const title = held.title ?? tool.name ?? '';
1025
+ const output = contentText(held.content);
1026
+ switch (tool.kind ?? held.kind) {
1027
+ case 'execute': {
1028
+ const exit = typeof held.rawOutput?.exit_code === 'number' && FINISHED.has(held.status) ? held.rawOutput.exit_code : null;
1029
+ return call({ status: held.status, exit, output: lastLines(output) }, lineOf(held.rawInput?.command) ?? title, { kind: 'command' });
1030
+ }
1031
+ case 'read':
1032
+ return call(held, title, { kind: 'read', returned: count(held.rawOutput?.FileContent?.total_lines) });
1033
+ case 'search':
1034
+ return call(held, title, { kind: 'search', returned: null });
1035
+ case 'write':
1036
+ case 'edit': {
1037
+ const diffs = (held.content ?? []).filter((entry) => entry.type === 'diff');
1038
+ return call(held, title, { kind: 'edit', files: diffs.map(replaced) });
1039
+ }
1040
+ case 'fetch':
1041
+ return call(held, title, { kind: 'fetch', output });
1042
+ default:
1043
+ return call(held, title, { kind: 'other', output });
1044
+ }
534
1045
  }
535
1046
  }
536
1047
  export function answeredFailure(answer) {