@agentshouse/kit 0.2.1-cf6a92e13f031 → 0.2.1-cfbadfb5b5e28

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 (48) hide show
  1. package/README.md +14 -15
  2. package/dist/acp.js +58 -7
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +58 -32
  5. package/dist/authority-main.js +3 -3
  6. package/dist/bridge.js +4 -4
  7. package/dist/building.js +50 -0
  8. package/dist/calls.js +12 -4
  9. package/dist/chunks.js +49 -0
  10. package/dist/clis.js +41 -42
  11. package/dist/connection.js +27 -33
  12. package/dist/content.js +63 -0
  13. package/dist/conversations.js +348 -126
  14. package/dist/copies.js +294 -148
  15. package/dist/end.js +8 -2
  16. package/dist/events.js +742 -210
  17. package/dist/files.js +35 -19
  18. package/dist/git.js +46 -12
  19. package/dist/grok.js +39 -0
  20. package/dist/home.js +0 -7
  21. package/dist/house-cli.js +26 -13
  22. package/dist/house-main.js +3 -3
  23. package/dist/instructions.js +5 -7
  24. package/dist/kit-cli.js +3 -6
  25. package/dist/kit-main.js +3 -3
  26. package/dist/login.js +5 -3
  27. package/dist/logout.js +1 -1
  28. package/dist/mcp.js +2 -0
  29. package/dist/placement.js +10 -18
  30. package/dist/relay.js +21 -0
  31. package/dist/resident.js +47 -32
  32. package/dist/scope.js +12 -4
  33. package/dist/scripts.js +255 -0
  34. package/dist/secret-input.js +1 -1
  35. package/dist/sign-in.js +3 -2
  36. package/dist/silence.js +28 -0
  37. package/dist/skills.js +38 -12
  38. package/dist/transcription.js +37 -25
  39. package/dist/translate.js +18 -9
  40. package/dist/update.js +109 -120
  41. package/dist/wire.js +23 -5
  42. package/dist/work.js +9 -2
  43. package/package.json +18 -17
  44. package/dist/bootstrap.json +0 -24
  45. package/dist/chatgpt.js +0 -32
  46. package/dist/clis-main.js +0 -23
  47. package/dist/parts.js +0 -82
  48. package/dist/web-wizard.js +0 -100
package/dist/events.js CHANGED
@@ -1,8 +1,23 @@
1
- const COMMAND = { shown: 'command' };
2
- const HIDDEN = { shown: 'hidden' };
3
- const FINISHED = new Set(['completed', 'failed']);
1
+ import { firstPart, keptDiff, lastLines } from '@agentshouse/session-content';
2
+ const AUTONOMOUS_ORIGINS = new Set(['task-notification', 'peer', 'coordinator', 'observer', 'observer-activity']);
3
+ const FINISHED = new Set(['completed', 'failed', 'stopped']);
4
4
  export const RUNNING_JOB = new Set(['running', 'paused']);
5
- const MESSAGE_TARGETS = { send_routine_request: 'access', cancel_routine_request: 'request', send_mail: 'request' };
5
+ const MESSAGE_TARGETS = new Map([
6
+ ['agent-functions/send', ['agent_function', 'agent']],
7
+ ['agent-functions/cancel', ['request']],
8
+ ['agent-functions/mail/send', ['conversation', 'request']],
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
+ }
6
21
  function words(line) {
7
22
  const found = [];
8
23
  let word = null;
@@ -37,7 +52,7 @@ function words(line) {
37
52
  found.push(word);
38
53
  return found;
39
54
  }
40
- export function houseMessage(line) {
55
+ function houseMessage(line) {
41
56
  const [program, verb, json] = words(line.trim());
42
57
  if (program !== 'house' || verb !== 'run_command' || json === undefined)
43
58
  return null;
@@ -48,27 +63,111 @@ export function houseMessage(line) {
48
63
  catch {
49
64
  return null;
50
65
  }
51
- const argument = MESSAGE_TARGETS[call.command];
52
- if (argument === undefined)
66
+ if (call === null)
67
+ return null;
68
+ const targets = MESSAGE_TARGETS.get(call.command);
69
+ if (targets === undefined)
53
70
  return null;
54
- const target = call.arguments?.[argument];
55
- return { shown: 'message', command: call.command, target: typeof target === 'string' ? target : null };
71
+ const target = targets.map((argument) => call.arguments?.[argument]).find((value) => typeof value === 'string');
72
+ return { command: call.command, target: target ?? null };
56
73
  }
57
- function decidedByLine(command, final) {
74
+ function lineOf(command) {
58
75
  const line = typeof command === 'string' ? command : Array.isArray(command) ? command.at(-1) : undefined;
59
- if (typeof line !== 'string')
60
- return final ? COMMAND : null;
61
- return houseMessage(line) ?? COMMAND;
76
+ return typeof line === 'string' ? line : undefined;
62
77
  }
63
78
  function contentText(content) {
64
- const text = (content ?? [])
79
+ return (content ?? [])
65
80
  .map((entry) => (entry.type === 'content' && entry.content?.type === 'text' ? entry.content.text : ''))
66
81
  .filter((part) => part !== '')
67
82
  .join('\n');
68
- return text === '' ? null : text;
69
83
  }
70
- function plan(entries) {
71
- 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
+ });
72
171
  }
73
172
  function merged(into, from) {
74
173
  if (from === null || from === undefined)
@@ -82,22 +181,38 @@ function merged(into, from) {
82
181
  }
83
182
  return result;
84
183
  }
85
- function names(input, ids) {
86
- const values = JSON.stringify(input ?? {});
87
- for (const id of ids)
88
- if (values.includes(id))
89
- return true;
90
- 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}`;
91
203
  }
92
204
  class Reader {
93
205
  session = null;
94
206
  calls = new Map();
95
- subagents = new Set();
96
- done = new Set();
207
+ subagents = new Map();
208
+ owners = new Map();
209
+ backgrounds = new Map();
210
+ work = new Map();
97
211
  seenOptions = new Map();
98
212
  requestedOptions = new Map();
99
213
  compactions = new Set();
100
- jobs = new Map();
214
+ turns = new Set();
215
+ edits = new Map();
101
216
  read(message) {
102
217
  if (message.method === undefined)
103
218
  return this.answered(message.result);
@@ -107,20 +222,29 @@ class Reader {
107
222
  }
108
223
  return this.own(message);
109
224
  }
225
+ tap(_message) {
226
+ return [];
227
+ }
110
228
  requested(option, value) {
111
229
  this.requestedOptions.set(option, value);
112
230
  }
113
231
  refused(option) {
114
232
  this.requestedOptions.delete(option);
115
233
  }
234
+ began() {
235
+ this.edits.clear();
236
+ return this.editedFiles();
237
+ }
116
238
  closeTurn() {
117
239
  const events = [];
118
- for (const [id, call] of this.calls) {
119
- if (call.decided?.shown === 'subagent')
240
+ for (const [id, held] of this.calls) {
241
+ if (held.shown === 'subagent')
120
242
  continue;
121
- if (call.decided === null)
122
- events.push(...this.shown(call, this.decide(call, true)));
123
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));
124
248
  }
125
249
  return events;
126
250
  }
@@ -139,28 +263,28 @@ class Reader {
139
263
  own(message) {
140
264
  if (message.method !== 'session/update')
141
265
  return this.extension(message);
142
- return this.update(message.params.update);
266
+ return this.update(message.params.update, null);
143
267
  }
144
268
  extension(_message) {
145
269
  return [];
146
270
  }
147
- update(update) {
271
+ update(update, parent) {
148
272
  switch (update.sessionUpdate) {
149
273
  case 'agent_message_chunk':
150
274
  if (update.content.type === 'image')
151
- return [{ kind: 'image', data: update.content.data, mediaType: update.content.mimeType }];
152
- 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 }] : [];
153
277
  case 'agent_thought_chunk':
154
- 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 }] : [];
155
279
  case 'tool_call':
156
280
  case 'tool_call_update':
157
- return this.tool(update);
281
+ return this.tool(update, parent);
158
282
  case 'plan':
159
- return [{ kind: 'plan', entries: plan(update.entries) }];
283
+ return [{ kind: 'plan', entries: update.entries.map((entry) => ({ content: entry.content, status: PLANNED[entry.status] ?? 'pending' })) }];
160
284
  case 'usage_update':
161
- return [{ kind: 'context', used: update.used, window: update.size }];
285
+ return [{ kind: 'state', state: this.used(update) }];
162
286
  case 'current_mode_update':
163
- return [{ kind: 'marker', marker: 'mode', text: update.currentModeId }];
287
+ return [{ kind: 'notice', notice: 'mode', text: update.currentModeId }];
164
288
  case 'available_commands_update':
165
289
  return [{ kind: 'commands', commands: update.availableCommands }];
166
290
  case 'config_option_update':
@@ -169,208 +293,513 @@ class Reader {
169
293
  if (update.status !== 'completed' || this.compactions.has(update.compactionId))
170
294
  return [];
171
295
  this.compactions.add(update.compactionId);
172
- 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
+ }
173
303
  case 'async_task_spawned':
174
- 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
+ }
175
319
  case 'async_task_state_update':
176
- 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');
177
328
  default:
178
329
  return [];
179
330
  }
180
331
  }
181
- job(id, name, state) {
182
- if (name !== null)
183
- this.jobs.set(id, name);
184
- const label = this.jobs.get(id) ?? '';
185
- if (state !== 'running')
186
- this.jobs.delete(id);
187
- 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 } }];
188
373
  }
189
374
  optionsChanged(options) {
190
375
  const events = [];
191
376
  for (const option of options) {
192
- const marker = this.watchedOptions[option.id];
377
+ const notice = this.watchedOptions[option.id];
193
378
  const before = this.seenOptions.get(option.id);
194
379
  this.seenOptions.set(option.id, option.currentValue);
195
- if (marker === undefined || before === undefined || before === option.currentValue)
380
+ if (notice === undefined || before === undefined || before === option.currentValue)
196
381
  continue;
197
382
  if (this.requestedOptions.get(option.id) === option.currentValue) {
198
383
  this.requestedOptions.delete(option.id);
199
384
  continue;
200
385
  }
201
- events.push({ kind: 'marker', marker, text: String(option.currentValue) });
386
+ events.push({ kind: 'notice', notice, text: String(option.currentValue) });
202
387
  }
203
388
  return events;
204
389
  }
205
- tool(update) {
206
- let call = this.calls.get(update.toolCallId);
207
- if (call === undefined) {
390
+ tool(update, parent) {
391
+ let held = this.calls.get(update.toolCallId);
392
+ if (held === undefined) {
208
393
  if (update.sessionUpdate !== 'tool_call')
209
394
  return [];
210
- call = { id: update.toolCallId, decided: null, meta: {}, imaged: false, status: 'in_progress' };
211
- 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);
212
397
  }
213
398
  if (update.kind !== undefined)
214
- call.kind = update.kind;
399
+ held.kind = update.kind;
215
400
  if (update.title !== undefined)
216
- call.title = update.title;
217
- if (update.status !== undefined)
218
- call.status = update.status;
401
+ held.title = update.title;
402
+ if (update.status !== undefined && !FINISHED.has(held.status))
403
+ held.status = update.status;
219
404
  if (update.rawInput !== undefined)
220
- 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;
221
408
  if (update.content !== undefined)
222
- call.content = update.content;
223
- call.meta = merged(call.meta, update._meta);
224
- const events = [];
225
- const finished = FINISHED.has(call.status);
226
- if (call.decided === null) {
227
- const decided = this.decide(call, finished);
228
- if (decided !== null)
229
- events.push(...this.shown(call, decided));
230
- }
231
- events.push(...this.produced(call));
232
- if (call.decided?.shown === 'subagent' && finished)
233
- events.push(...this.subagentFinished(call));
234
- else if (finished)
235
- this.calls.delete(call.id);
236
- 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);
237
417
  }
238
- shown(call, decided) {
239
- call.decided = decided;
240
- switch (decided.shown) {
241
- case 'command':
242
- return [{ kind: 'command' }];
243
- case 'hidden':
244
- return [];
245
- case 'message':
246
- return [{ kind: 'message', command: decided.command, target: decided.target }];
247
- case 'marker':
248
- return [{ kind: 'marker', marker: decided.marker, text: decided.text }];
249
- case 'subagent':
250
- this.subagents.add(call.id);
251
- 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 } }];
252
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)];
253
430
  }
254
- produced(_call) {
255
- 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
+ ];
256
442
  }
257
- subagentFinished(call) {
258
- this.calls.delete(call.id);
259
- return this.finish(call.id, contentText(call.content));
443
+ filesFromEdits() {
444
+ return true;
260
445
  }
261
- finish(id, result) {
262
- if (!this.subagents.has(id) || this.done.has(id))
446
+ edited(key, part) {
447
+ if (part.type !== 'call' || part.kind !== 'edit' || !this.filesFromEdits())
263
448
  return [];
264
- this.done.add(id);
265
- this.calls.delete(id);
266
- 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 [];
267
467
  }
268
468
  }
269
469
  class ClaudeReader extends Reader {
270
470
  watchedOptions = { model: 'model' };
271
- 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 = [];
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
+ }
272
495
  own(message) {
273
- if (message.params?.update?._meta?.claudeCode?.parentToolUseId !== undefined)
274
- return [];
275
- 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) : [];
276
501
  }
277
- 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) {
278
510
  if (update.sessionUpdate === 'usage_update' && update._meta?.['_claude/origin'] !== undefined) {
279
- return [...super.update(update), { kind: 'ended' }];
511
+ const stop = this.stop;
512
+ this.stop = null;
513
+ return [...super.update(update, parent), { kind: 'ended', stop }];
280
514
  }
281
515
  if (update.sessionUpdate === 'session_info_update' && update._meta?.jetbrains?.air?.sessionFailure !== undefined) {
282
- 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 }];
283
517
  }
284
- return super.update(update);
518
+ return super.update(update, parent);
285
519
  }
286
520
  extension(message) {
287
521
  if (message.method !== '_claude/sdkMessage')
288
522
  return [];
289
523
  const sdk = message.params.message;
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);
537
+ }
538
+ if (typeof sdk.tool_use_id !== 'string')
539
+ return [];
290
540
  switch (sdk.subtype) {
291
541
  case 'task_started':
292
- if (sdk.tool_use_id !== undefined)
293
- this.tasks.set(sdk.task_id, sdk.tool_use_id);
294
- return [];
542
+ return typeof sdk.subagent_type === 'string' ? this.figured(sdk.tool_use_id, { name: sdk.subagent_type }) : [];
543
+ case 'task_progress':
544
+ return this.figured(sdk.tool_use_id, { step: typeof sdk.description === 'string' ? sdk.description : null, ...this.usage(sdk.usage) });
295
545
  case 'task_notification':
296
- return sdk.tool_use_id === undefined ? [] : this.finish(sdk.tool_use_id, sdk.summary ?? null);
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
+ });
297
551
  default:
298
552
  return [];
299
553
  }
300
554
  }
301
- decide(call, final) {
302
- const tool = call.meta.claudeCode?.toolName;
303
- if (tool === 'Agent' || tool === 'Task' || call.meta.jetbrains?.air?.subagent === true) {
304
- const description = call.rawInput?.description;
305
- if (description === undefined && !final)
306
- return null;
307
- 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 } } });
574
+ }
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
+ });
308
614
  }
309
- if (tool === 'TodoWrite' || tool === 'CronCreate')
310
- return HIDDEN;
311
- if (tool === 'ScheduleWakeup') {
312
- if (call.rawInput === undefined)
313
- return final ? COMMAND : null;
314
- return call.rawInput.stop === true ? COMMAND : HIDDEN;
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';
315
624
  }
316
- if (call.kind === 'switch_mode')
317
- return { shown: 'marker', marker: 'mode', text: call.title ?? '' };
318
625
  if (tool === 'Bash')
319
- return decidedByLine(call.rawInput?.command, final);
320
- if (tool === 'SendMessage' || tool === 'TaskStop') {
321
- if (call.rawInput === undefined)
322
- return final ? COMMAND : null;
323
- 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);
324
668
  }
325
- 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);
326
676
  }
327
- produced(call) {
328
- const tool = call.meta.claudeCode?.toolName;
329
- if (call.status !== 'completed')
677
+ claudeFiles(held, result) {
678
+ const path = result.filePath ?? held.rawInput?.file_path;
679
+ if (typeof path !== 'string')
330
680
  return [];
331
- if (tool === 'CronCreate' || (tool === 'ScheduleWakeup' && call.rawInput?.stop !== true)) {
332
- return [{ kind: 'marker', marker: 'job', text: `${call.rawInput?.prompt ?? call.title ?? ''}: scheduled` }];
333
- }
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)];
334
685
  return [];
335
686
  }
336
- subagentFinished(call) {
337
- 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)
338
711
  return [];
339
- 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));
340
715
  }
341
716
  }
342
- const COLLABORATION = new Set(['spawnAgent', 'sendInput', 'resumeAgent', 'wait', 'closeAgent', 'followupTask']);
343
717
  class CodexReader extends Reader {
344
718
  watchedOptions = { mode: 'mode', collaboration_mode: 'mode' };
345
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
+ }
346
773
  own(message) {
347
774
  if (message.method === 'session/request_permission' && message.params.toolCall?.kind === 'switch_mode') {
348
- 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 ?? '' }];
349
776
  }
350
777
  return super.own(message);
351
778
  }
352
- update(update) {
779
+ update(update, parent) {
353
780
  switch (update.sessionUpdate) {
354
781
  case 'session_info_update': {
355
782
  const codex = update._meta?.codex;
356
783
  if (codex?.threadStatus?.type === 'active')
357
784
  return [{ kind: 'started' }];
358
785
  if (codex?.threadStatus?.type === 'idle')
359
- return [{ kind: 'ended' }];
786
+ return [{ kind: 'ended', stop: null }];
360
787
  if (codex?.error !== undefined)
361
- return [{ kind: 'marker', marker: 'retry', text: codex.error.message ?? '' }];
362
- return [];
788
+ return [{ kind: 'notice', notice: 'retry', text: codex.error.message ?? '' }];
789
+ return super.update(update, parent);
363
790
  }
364
- case 'notice':
365
- return update.severity === 'info' ? [{ kind: 'marker', marker: 'model', text: update.description ?? update.title }] : [];
366
791
  case 'subagent_spawned':
367
792
  this.children.set(update.subagentSessionId, { id: null, text: '' });
368
- this.subagents.add(update.subagentSessionId);
369
- return [{ kind: 'subagent', id: update.subagentSessionId, description: update.name }];
370
- case 'subagent_state_update':
371
- 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
+ }
372
801
  default:
373
- return super.update(update);
802
+ return super.update(update, parent);
374
803
  }
375
804
  }
376
805
  elsewhere(session, message) {
@@ -385,35 +814,80 @@ class CodexReader extends Reader {
385
814
  child.id = id;
386
815
  child.text += update.content.text;
387
816
  }
388
- 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 };
389
864
  }
390
- decide(call) {
391
- const air = call.meta.jetbrains?.air;
392
- if (COLLABORATION.has(call.title ?? ''))
393
- return HIDDEN;
394
- if (air?.subagent !== undefined)
395
- return { shown: 'subagent', description: call.title ?? '' };
396
- if (call.kind === 'switch_mode')
397
- return { shown: 'marker', marker: 'mode', text: call.title ?? '' };
398
- if (call.kind === 'execute')
399
- return decidedByLine(call.rawInput?.command, true);
400
- if (call.title === 'Image generation')
401
- return HIDDEN;
402
- return COMMAND;
403
- }
404
- produced(call) {
405
- if (call.imaged || call.kind === 'read')
865
+ codexFiles(item) {
866
+ if (item?.type !== 'fileChange')
406
867
  return [];
407
- 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');
408
880
  if (image === undefined)
409
881
  return [];
410
- call.imaged = true;
411
- 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 }];
412
884
  }
413
885
  }
414
886
  class GrokReader extends Reader {
415
887
  watchedOptions = {};
416
888
  children = new Map();
889
+ figures = new Map();
890
+ schedules = new Set();
417
891
  models = [];
418
892
  model = null;
419
893
  answered(result) {
@@ -429,7 +903,9 @@ class GrokReader extends Reader {
429
903
  return (message.params.runningPromptId ?? null) !== null && session === this.session ? [{ kind: 'started' }] : [];
430
904
  }
431
905
  if (message.params?.update?.sessionUpdate === 'turn_completed') {
432
- return session === this.session ? [{ kind: 'ended' }] : [];
906
+ if (session !== this.session)
907
+ return [];
908
+ return [...this.spent(message.params.update.usage), { kind: 'ended', stop: null }];
433
909
  }
434
910
  if (message.method === '_x.ai/models/update') {
435
911
  this.offered(message.params);
@@ -437,6 +913,20 @@ class GrokReader extends Reader {
437
913
  }
438
914
  return super.read(message);
439
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
+ }
440
930
  offered(models) {
441
931
  this.models = models.availableModels ?? this.models;
442
932
  this.model = models.currentModelId ?? this.model;
@@ -448,11 +938,18 @@ class GrokReader extends Reader {
448
938
  const update = message.params?.update;
449
939
  switch (message.method) {
450
940
  case '_x.ai/task_backgrounded':
451
- return this.job(update.task_id, update.description ?? update.command ?? '', 'running');
452
- case '_x.ai/task_completed':
453
- return this.job(update.task_snapshot.task_id, null, update.task_snapshot.exit_code === 0 ? 'completed' : 'failed');
454
- case '_x.ai/scheduled_task_created':
455
- 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') : [];
456
953
  case '_x.ai/session_notification':
457
954
  return this.notification(update);
458
955
  default:
@@ -467,49 +964,84 @@ class GrokReader extends Reader {
467
964
  if (window === null)
468
965
  return [];
469
966
  const used = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + usage.output_tokens;
470
- return [{ kind: 'context', used, window }];
967
+ return [{ kind: 'state', state: { context: { used, window, breakdown: [] } } }];
471
968
  }
472
969
  case 'subagent_spawned': {
473
- const call = [...this.calls.values()].find((candidate) => candidate.decided?.shown === 'subagent' &&
474
- ![...this.children.values()].includes(candidate.id) &&
475
- candidate.decided.description === update.description) ??
476
- [...this.calls.values()].find((candidate) => candidate.decided?.shown === 'subagent' && ![...this.children.values()].includes(candidate.id));
477
- this.children.set(update.child_session_id, call?.id ?? null);
478
- 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) }) : [];
479
979
  }
480
980
  case 'subagent_finished': {
481
- const call = this.children.get(update.child_session_id);
482
- 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
+ });
483
991
  }
484
992
  case 'auto_compact_completed':
485
- return [{ kind: 'marker', marker: 'compaction', text: '' }];
993
+ return [{ kind: 'notice', notice: 'compaction', text: '' }];
486
994
  case 'model_auto_switched':
487
995
  this.model = update.new_model_id;
488
- return [{ kind: 'marker', marker: 'model', text: update.new_model_id }];
996
+ return [{ kind: 'notice', notice: 'model', text: update.new_model_id }];
489
997
  case 'retry_state':
490
- 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 ?? '' }];
491
999
  default:
492
1000
  return [];
493
1001
  }
494
1002
  }
495
- decide(call) {
496
- const tool = (call.meta['x.ai/tool'] ?? {});
497
- if (tool.name === 'spawn_subagent' || tool.kind === 'task') {
498
- return { shown: 'subagent', description: call.rawInput?.description ?? call.title ?? '' };
499
- }
500
- if (tool.name === 'todo_write' || tool.name === 'scheduler_create')
501
- return HIDDEN;
502
- if (tool.name === 'enter_plan_mode' || tool.name === 'exit_plan_mode') {
503
- return { shown: 'marker', marker: 'mode', text: tool.name };
504
- }
505
- if (tool.name === 'kill_command_or_subagent')
506
- 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';
507
1015
  if (tool.name === 'run_terminal_command')
508
- return decidedByLine(call.rawInput?.command, true);
509
- return COMMAND;
1016
+ return this.decideLine(lineOf(held.rawInput?.command), true);
1017
+ return 'call';
510
1018
  }
511
- subagentFinished(_call) {
512
- 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
+ }
513
1045
  }
514
1046
  }
515
1047
  export function answeredFailure(answer) {