@agentshouse/kit 0.2.1-cd9cbd8b6428c → 0.2.1-ce0af1aee9a57

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 (138) hide show
  1. package/README.md +46 -46
  2. package/dist/acp.js +102 -108
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +218 -63
  5. package/dist/api.js +34 -2
  6. package/dist/app-git.js +48 -0
  7. package/dist/authority-main.js +3 -3
  8. package/dist/bridge.js +42 -62
  9. package/dist/building.js +50 -0
  10. package/dist/calls.js +71 -0
  11. package/dist/chunks.js +49 -0
  12. package/dist/clis.js +169 -95
  13. package/dist/codex-main.js +58 -0
  14. package/dist/connection.js +120 -0
  15. package/dist/content.js +63 -0
  16. package/dist/conversations.js +853 -333
  17. package/dist/copies.js +451 -251
  18. package/dist/end.js +33 -0
  19. package/dist/enrol-main.js +7 -1
  20. package/dist/events.js +1057 -0
  21. package/dist/files.js +139 -17
  22. package/dist/git.js +57 -21
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +89 -7
  25. package/dist/house-cli.js +299 -0
  26. package/dist/house-main.js +7 -159
  27. package/dist/instructions.js +7 -11
  28. package/dist/kit-cli.js +65 -0
  29. package/dist/kit-main.js +8 -19
  30. package/dist/login.js +117 -102
  31. package/dist/logout.js +14 -13
  32. package/dist/mcp.js +6 -2
  33. package/dist/placement.js +31 -0
  34. package/dist/refusals.js +12 -0
  35. package/dist/relay.js +33 -2
  36. package/dist/resident.js +138 -61
  37. package/dist/scope.js +214 -0
  38. package/dist/scripts.js +255 -0
  39. package/dist/secret-input.js +5 -2
  40. package/dist/service-main.js +9 -0
  41. package/dist/service.js +55 -0
  42. package/dist/shell.js +3 -0
  43. package/dist/sign-in.js +40 -32
  44. package/dist/silence.js +28 -0
  45. package/dist/skills.js +49 -35
  46. package/dist/transcription.js +131 -40
  47. package/dist/translate.js +19 -16
  48. package/dist/update.js +113 -103
  49. package/dist/wire.js +40 -0
  50. package/dist/work.js +353 -0
  51. package/package.json +22 -20
  52. package/dist/blocks.js +0 -51
  53. package/dist/bootstrap.json +0 -24
  54. package/dist/clis-main.js +0 -23
  55. package/dist/stream.js +0 -47
  56. package/how-we-work.md +0 -23
  57. package/skills/ask-matt/LICENSE +0 -21
  58. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  59. package/skills/ask-matt/SKILL.md +0 -91
  60. package/skills/ask-matt/agents/openai.yaml +0 -4
  61. package/skills/code-review/LICENSE +0 -21
  62. package/skills/code-review/SKILL.md +0 -89
  63. package/skills/code-review/agents/openai.yaml +0 -3
  64. package/skills/codebase-design/DEEPENING.md +0 -37
  65. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  66. package/skills/codebase-design/LICENSE +0 -21
  67. package/skills/codebase-design/SKILL.md +0 -116
  68. package/skills/codebase-design/agents/openai.yaml +0 -3
  69. package/skills/diagnosing-bugs/LICENSE +0 -21
  70. package/skills/diagnosing-bugs/SKILL.md +0 -140
  71. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  72. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  73. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  74. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  75. package/skills/domain-modeling/LICENSE +0 -21
  76. package/skills/domain-modeling/SKILL.md +0 -76
  77. package/skills/domain-modeling/agents/openai.yaml +0 -3
  78. package/skills/grill-me/LICENSE +0 -21
  79. package/skills/grill-me/SKILL.md +0 -8
  80. package/skills/grill-me/agents/openai.yaml +0 -4
  81. package/skills/grill-with-docs/LICENSE +0 -21
  82. package/skills/grill-with-docs/SKILL.md +0 -8
  83. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  84. package/skills/grilling/LICENSE +0 -21
  85. package/skills/grilling/SKILL.md +0 -30
  86. package/skills/grilling/agents/openai.yaml +0 -3
  87. package/skills/handoff/LICENSE +0 -21
  88. package/skills/handoff/SKILL.md +0 -17
  89. package/skills/handoff/agents/openai.yaml +0 -4
  90. package/skills/implement/LICENSE +0 -21
  91. package/skills/implement/SKILL.md +0 -16
  92. package/skills/implement/agents/openai.yaml +0 -4
  93. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  94. package/skills/improve-codebase-architecture/LICENSE +0 -21
  95. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  96. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  97. package/skills/prototype/LICENSE +0 -21
  98. package/skills/prototype/LOGIC.md +0 -67
  99. package/skills/prototype/SKILL.md +0 -28
  100. package/skills/prototype/UI.md +0 -112
  101. package/skills/prototype/agents/openai.yaml +0 -3
  102. package/skills/research/LICENSE +0 -21
  103. package/skills/research/SKILL.md +0 -14
  104. package/skills/research/agents/openai.yaml +0 -3
  105. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  106. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  107. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  108. package/skills/tdd/LICENSE +0 -21
  109. package/skills/tdd/SKILL.md +0 -40
  110. package/skills/tdd/agents/openai.yaml +0 -3
  111. package/skills/tdd/mocking.md +0 -59
  112. package/skills/tdd/tests.md +0 -77
  113. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  114. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  115. package/skills/teach/LICENSE +0 -21
  116. package/skills/teach/MISSION-FORMAT.md +0 -31
  117. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  118. package/skills/teach/SKILL.md +0 -141
  119. package/skills/teach/agents/openai.yaml +0 -4
  120. package/skills/to-questionnaire/LICENSE +0 -21
  121. package/skills/to-questionnaire/SKILL.md +0 -55
  122. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  123. package/skills/to-spec/LICENSE +0 -21
  124. package/skills/to-spec/SKILL.md +0 -76
  125. package/skills/to-spec/agents/openai.yaml +0 -4
  126. package/skills/to-tickets/LICENSE +0 -21
  127. package/skills/to-tickets/SKILL.md +0 -106
  128. package/skills/to-tickets/agents/openai.yaml +0 -4
  129. package/skills/wait-what/LICENSE +0 -21
  130. package/skills/wait-what/SKILL.md +0 -8
  131. package/skills/wait-what/agents/openai.yaml +0 -4
  132. package/skills/wayfinder/LICENSE +0 -21
  133. package/skills/wayfinder/SKILL.md +0 -129
  134. package/skills/wayfinder/agents/openai.yaml +0 -4
  135. package/skills/writing-for-agents/LICENSE +0 -21
  136. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  137. package/skills/writing-for-agents/SKILL.md +0 -83
  138. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/events.js ADDED
@@ -0,0 +1,1057 @@
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
+ export const RUNNING_JOB = new Set(['running', 'paused']);
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
+ }
21
+ function words(line) {
22
+ const found = [];
23
+ let word = null;
24
+ let quote = null;
25
+ for (let index = 0; index < line.length; index++) {
26
+ const character = line[index];
27
+ if (quote !== null) {
28
+ if (character === quote)
29
+ quote = null;
30
+ else if (character === '\\' && quote === '"')
31
+ word += line[++index] ?? '';
32
+ else
33
+ word += character;
34
+ }
35
+ else if (character === "'" || character === '"') {
36
+ quote = character;
37
+ word ??= '';
38
+ }
39
+ else if (character === '\\') {
40
+ word = (word ?? '') + (line[++index] ?? '');
41
+ }
42
+ else if (/\s/.test(character)) {
43
+ if (word !== null)
44
+ found.push(word);
45
+ word = null;
46
+ }
47
+ else {
48
+ word = (word ?? '') + character;
49
+ }
50
+ }
51
+ if (word !== null)
52
+ found.push(word);
53
+ return found;
54
+ }
55
+ function houseMessage(line) {
56
+ const [program, verb, json] = words(line.trim());
57
+ if (program !== 'house' || verb !== 'run_command' || json === undefined)
58
+ return null;
59
+ let call;
60
+ try {
61
+ call = JSON.parse(json);
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ if (call === null)
67
+ return null;
68
+ const targets = MESSAGE_TARGETS.get(call.command);
69
+ if (targets === undefined)
70
+ return null;
71
+ const target = targets.map((argument) => call.arguments?.[argument]).find((value) => typeof value === 'string');
72
+ return { command: call.command, target: target ?? null };
73
+ }
74
+ function lineOf(command) {
75
+ const line = typeof command === 'string' ? command : Array.isArray(command) ? command.at(-1) : undefined;
76
+ return typeof line === 'string' ? line : undefined;
77
+ }
78
+ function contentText(content) {
79
+ return (content ?? [])
80
+ .map((entry) => (entry.type === 'content' && entry.content?.type === 'text' ? entry.content.text : ''))
81
+ .filter((part) => part !== '')
82
+ .join('\n');
83
+ }
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
+ });
171
+ }
172
+ function merged(into, from) {
173
+ if (from === null || from === undefined)
174
+ return into;
175
+ const result = { ...into };
176
+ for (const [key, value] of Object.entries(from)) {
177
+ result[key] =
178
+ typeof value === 'object' && value !== null && !Array.isArray(value) && typeof into[key] === 'object'
179
+ ? merged(into[key], value)
180
+ : value;
181
+ }
182
+ return result;
183
+ }
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}`;
203
+ }
204
+ class Reader {
205
+ session = null;
206
+ calls = new Map();
207
+ subagents = new Map();
208
+ owners = new Map();
209
+ backgrounds = new Map();
210
+ work = new Map();
211
+ seenOptions = new Map();
212
+ requestedOptions = new Map();
213
+ compactions = new Set();
214
+ turns = new Set();
215
+ edits = new Map();
216
+ read(message) {
217
+ if (message.method === undefined)
218
+ return this.answered(message.result);
219
+ const session = message.params?.sessionId;
220
+ if (session !== undefined && this.session !== null && session !== this.session) {
221
+ return this.elsewhere(session, message);
222
+ }
223
+ return this.own(message);
224
+ }
225
+ tap(_message) {
226
+ return [];
227
+ }
228
+ requested(option, value) {
229
+ this.requestedOptions.set(option, value);
230
+ }
231
+ refused(option) {
232
+ this.requestedOptions.delete(option);
233
+ }
234
+ began() {
235
+ this.edits.clear();
236
+ return this.editedFiles();
237
+ }
238
+ closeTurn() {
239
+ const events = [];
240
+ for (const [id, held] of this.calls) {
241
+ if (held.shown === 'subagent')
242
+ continue;
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));
248
+ }
249
+ return events;
250
+ }
251
+ answered(result) {
252
+ if (typeof result?.sessionId === 'string' && this.session === null)
253
+ this.session = result.sessionId;
254
+ for (const option of (result?.configOptions ?? [])) {
255
+ this.seenOptions.set(option.id, option.currentValue);
256
+ this.requestedOptions.delete(option.id);
257
+ }
258
+ return [];
259
+ }
260
+ elsewhere(_session, _message) {
261
+ return [];
262
+ }
263
+ own(message) {
264
+ if (message.method !== 'session/update')
265
+ return this.extension(message);
266
+ return this.update(message.params.update, null);
267
+ }
268
+ extension(_message) {
269
+ return [];
270
+ }
271
+ update(update, parent) {
272
+ switch (update.sessionUpdate) {
273
+ case 'agent_message_chunk':
274
+ if (update.content.type === 'image')
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 }] : [];
277
+ case 'agent_thought_chunk':
278
+ return update.content.type === 'text' ? [{ kind: 'reasoning', id: update.messageId ?? null, parent, text: update.content.text }] : [];
279
+ case 'tool_call':
280
+ case 'tool_call_update':
281
+ return this.tool(update, parent);
282
+ case 'plan':
283
+ return [{ kind: 'plan', entries: update.entries.map((entry) => ({ content: entry.content, status: PLANNED[entry.status] ?? 'pending' })) }];
284
+ case 'usage_update':
285
+ return [{ kind: 'state', state: this.used(update) }];
286
+ case 'current_mode_update':
287
+ return [{ kind: 'notice', notice: 'mode', text: update.currentModeId }];
288
+ case 'available_commands_update':
289
+ return [{ kind: 'commands', commands: update.availableCommands }];
290
+ case 'config_option_update':
291
+ return [{ kind: 'options', options: update.configOptions }, ...this.optionsChanged(update.configOptions)];
292
+ case 'compaction_update':
293
+ if (update.status !== 'completed' || this.compactions.has(update.compactionId))
294
+ return [];
295
+ this.compactions.add(update.compactionId);
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
+ }
303
+ case 'async_task_spawned':
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
+ }
319
+ case 'async_task_state_update':
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');
328
+ default:
329
+ return [];
330
+ }
331
+ }
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 } }];
373
+ }
374
+ optionsChanged(options) {
375
+ const events = [];
376
+ for (const option of options) {
377
+ const notice = this.watchedOptions[option.id];
378
+ const before = this.seenOptions.get(option.id);
379
+ this.seenOptions.set(option.id, option.currentValue);
380
+ if (notice === undefined || before === undefined || before === option.currentValue)
381
+ continue;
382
+ if (this.requestedOptions.get(option.id) === option.currentValue) {
383
+ this.requestedOptions.delete(option.id);
384
+ continue;
385
+ }
386
+ events.push({ kind: 'notice', notice, text: String(option.currentValue) });
387
+ }
388
+ return events;
389
+ }
390
+ tool(update, parent) {
391
+ let held = this.calls.get(update.toolCallId);
392
+ if (held === undefined) {
393
+ if (update.sessionUpdate !== 'tool_call')
394
+ return [];
395
+ held = { id: update.toolCallId, parent, shown: null, meta: {}, output: '', exit: null, imaged: false, status: 'in_progress' };
396
+ this.calls.set(held.id, held);
397
+ }
398
+ if (update.kind !== undefined)
399
+ held.kind = update.kind;
400
+ if (update.title !== undefined)
401
+ held.title = update.title;
402
+ if (update.status !== undefined && !FINISHED.has(held.status))
403
+ held.status = update.status;
404
+ if (update.rawInput !== undefined)
405
+ held.rawInput = merged(held.rawInput ?? {}, update.rawInput);
406
+ if (update.rawOutput !== undefined)
407
+ held.rawOutput = update.rawOutput;
408
+ if (update.content !== undefined)
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);
417
+ }
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 } }];
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)];
430
+ }
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
+ ];
442
+ }
443
+ filesFromEdits() {
444
+ return true;
445
+ }
446
+ edited(key, part) {
447
+ if (part.type !== 'call' || part.kind !== 'edit' || !this.filesFromEdits())
448
+ return [];
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 [];
467
+ }
468
+ }
469
+ class ClaudeReader extends Reader {
470
+ watchedOptions = { model: 'model' };
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
+ }
495
+ 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) : [];
501
+ }
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) {
510
+ if (update.sessionUpdate === 'usage_update' && update._meta?.['_claude/origin'] !== undefined) {
511
+ const stop = this.stop;
512
+ this.stop = null;
513
+ return [...super.update(update, parent), { kind: 'ended', stop }];
514
+ }
515
+ if (update.sessionUpdate === 'session_info_update' && update._meta?.jetbrains?.air?.sessionFailure !== undefined) {
516
+ return [{ kind: 'notice', notice: 'retry', text: update._meta.jetbrains.air.sessionFailure.title }];
517
+ }
518
+ return super.update(update, parent);
519
+ }
520
+ extension(message) {
521
+ if (message.method !== '_claude/sdkMessage')
522
+ return [];
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 [];
540
+ switch (sdk.subtype) {
541
+ case 'task_started':
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) });
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
+ });
551
+ default:
552
+ return [];
553
+ }
554
+ }
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
+ });
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';
624
+ }
625
+ if (tool === 'Bash')
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);
668
+ }
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);
676
+ }
677
+ claudeFiles(held, result) {
678
+ const path = result.filePath ?? held.rawInput?.file_path;
679
+ if (typeof path !== 'string')
680
+ return [];
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)];
685
+ return [];
686
+ }
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)
711
+ return [];
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));
715
+ }
716
+ }
717
+ class CodexReader extends Reader {
718
+ watchedOptions = { mode: 'mode', collaboration_mode: 'mode' };
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
+ }
773
+ own(message) {
774
+ if (message.method === 'session/request_permission' && message.params.toolCall?.kind === 'switch_mode') {
775
+ return [{ kind: 'started' }, { kind: 'notice', notice: 'mode', text: message.params.toolCall.title ?? '' }];
776
+ }
777
+ return super.own(message);
778
+ }
779
+ update(update, parent) {
780
+ switch (update.sessionUpdate) {
781
+ case 'session_info_update': {
782
+ const codex = update._meta?.codex;
783
+ if (codex?.threadStatus?.type === 'active')
784
+ return [{ kind: 'started' }];
785
+ if (codex?.threadStatus?.type === 'idle')
786
+ return [{ kind: 'ended', stop: null }];
787
+ if (codex?.error !== undefined)
788
+ return [{ kind: 'notice', notice: 'retry', text: codex.error.message ?? '' }];
789
+ return super.update(update, parent);
790
+ }
791
+ case 'subagent_spawned':
792
+ this.children.set(update.subagentSessionId, { id: null, text: '' });
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
+ }
801
+ default:
802
+ return super.update(update, parent);
803
+ }
804
+ }
805
+ elsewhere(session, message) {
806
+ const child = this.children.get(session);
807
+ const update = message.params?.update;
808
+ if (child === undefined || update === undefined)
809
+ return [];
810
+ if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
811
+ const id = update.messageId ?? null;
812
+ if (child.id !== id)
813
+ child.text = '';
814
+ child.id = id;
815
+ child.text += update.content.text;
816
+ }
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 };
864
+ }
865
+ codexFiles(item) {
866
+ if (item?.type !== 'fileChange')
867
+ return [];
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');
880
+ if (image === undefined)
881
+ return [];
882
+ held.imaged = true;
883
+ return [{ kind: 'image', data: image.content.data, mediaType: image.content.mimeType, parent: held.parent }];
884
+ }
885
+ }
886
+ class GrokReader extends Reader {
887
+ watchedOptions = {};
888
+ children = new Map();
889
+ figures = new Map();
890
+ schedules = new Set();
891
+ models = [];
892
+ model = null;
893
+ answered(result) {
894
+ if (result?.models !== undefined)
895
+ this.offered(result.models);
896
+ return super.answered(result);
897
+ }
898
+ read(message) {
899
+ const session = message.params?.sessionId;
900
+ if (this.session !== null && session !== undefined && session !== this.session && !this.children.has(session))
901
+ return [];
902
+ if (message.method === '_x.ai/queue/changed') {
903
+ return (message.params.runningPromptId ?? null) !== null && session === this.session ? [{ kind: 'started' }] : [];
904
+ }
905
+ if (message.params?.update?.sessionUpdate === 'turn_completed') {
906
+ if (session !== this.session)
907
+ return [];
908
+ return [...this.spent(message.params.update.usage), { kind: 'ended', stop: null }];
909
+ }
910
+ if (message.method === '_x.ai/models/update') {
911
+ this.offered(message.params);
912
+ return [];
913
+ }
914
+ return super.read(message);
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
+ }
930
+ offered(models) {
931
+ this.models = models.availableModels ?? this.models;
932
+ this.model = models.currentModelId ?? this.model;
933
+ }
934
+ window() {
935
+ return this.models.find((model) => model.modelId === this.model)?._meta?.totalContextTokens ?? null;
936
+ }
937
+ extension(message) {
938
+ const update = message.params?.update;
939
+ switch (message.method) {
940
+ case '_x.ai/task_backgrounded':
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') : [];
953
+ case '_x.ai/session_notification':
954
+ return this.notification(update);
955
+ default:
956
+ return [];
957
+ }
958
+ }
959
+ notification(update) {
960
+ switch (update.sessionUpdate) {
961
+ case 'response_completed': {
962
+ const usage = update.usage;
963
+ const window = this.window();
964
+ if (window === null)
965
+ return [];
966
+ const used = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + usage.output_tokens;
967
+ return [{ kind: 'state', state: { context: { used, window, breakdown: [] } } }];
968
+ }
969
+ case 'subagent_spawned': {
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) }) : [];
979
+ }
980
+ case 'subagent_finished': {
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
+ });
991
+ }
992
+ case 'auto_compact_completed':
993
+ return [{ kind: 'notice', notice: 'compaction', text: '' }];
994
+ case 'model_auto_switched':
995
+ this.model = update.new_model_id;
996
+ return [{ kind: 'notice', notice: 'model', text: update.new_model_id }];
997
+ case 'retry_state':
998
+ return [{ kind: 'notice', notice: 'retry', text: update.message ?? update.reason ?? update.error_type ?? '' }];
999
+ default:
1000
+ return [];
1001
+ }
1002
+ }
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';
1015
+ if (tool.name === 'run_terminal_command')
1016
+ return this.decideLine(lineOf(held.rawInput?.command), true);
1017
+ return 'call';
1018
+ }
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
+ }
1045
+ }
1046
+ }
1047
+ export function answeredFailure(answer) {
1048
+ const failure = answer._meta?.jetbrains?.air?.sessionFailure;
1049
+ return typeof failure?.title === 'string' ? { title: failure.title, limit: failure.category === 'limit' } : null;
1050
+ }
1051
+ export function readerFor(kind) {
1052
+ if (kind === 'claude-agent-acp')
1053
+ return new ClaudeReader();
1054
+ if (kind === 'grok-build')
1055
+ return new GrokReader();
1056
+ return new CodexReader();
1057
+ }