@agentshouse/kit 0.2.1-cd9cbd8b6428c → 0.2.1-cdc3937dea52e

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 (145) hide show
  1. package/README.md +46 -49
  2. package/dist/acp.js +101 -108
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +271 -73
  5. package/dist/api.js +43 -6
  6. package/dist/app-git.js +48 -0
  7. package/dist/bridge.js +42 -62
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +88 -0
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +179 -95
  12. package/dist/codex-main.js +58 -0
  13. package/dist/connect.js +108 -0
  14. package/dist/connection.js +120 -0
  15. package/dist/content.js +106 -0
  16. package/dist/conversations.js +817 -333
  17. package/dist/copies.js +451 -251
  18. package/dist/earlier.js +263 -0
  19. package/dist/end.js +26 -0
  20. package/dist/events.js +793 -0
  21. package/dist/files.js +139 -17
  22. package/dist/git-main.js +24 -29
  23. package/dist/git.js +57 -21
  24. package/dist/grok.js +39 -0
  25. package/dist/home.js +134 -9
  26. package/dist/house-cli.js +362 -0
  27. package/dist/house-main.js +7 -159
  28. package/dist/instructions.js +7 -11
  29. package/dist/keys.js +238 -0
  30. package/dist/kit-cli.js +78 -0
  31. package/dist/kit-main.js +8 -19
  32. package/dist/login.js +133 -104
  33. package/dist/logout.js +15 -14
  34. package/dist/mcp.js +6 -2
  35. package/dist/owner.js +46 -0
  36. package/dist/placement.js +25 -0
  37. package/dist/refusals.js +12 -0
  38. package/dist/relay.js +33 -2
  39. package/dist/resident.js +161 -61
  40. package/dist/scope.js +214 -0
  41. package/dist/scripts.js +303 -0
  42. package/dist/secret-input.js +5 -2
  43. package/dist/settings.js +188 -0
  44. package/dist/shell.js +3 -0
  45. package/dist/sign-in.js +85 -32
  46. package/dist/silence.js +28 -0
  47. package/dist/skills.js +49 -35
  48. package/dist/supervisor.js +163 -0
  49. package/dist/transcription.js +131 -40
  50. package/dist/translate.js +19 -16
  51. package/dist/update.js +119 -100
  52. package/dist/wire.js +32 -0
  53. package/dist/work.js +353 -0
  54. package/dist/workspace.js +103 -0
  55. package/package.json +26 -21
  56. package/dist/authority-main.js +0 -22
  57. package/dist/blocks.js +0 -51
  58. package/dist/bootstrap.json +0 -24
  59. package/dist/clis-main.js +0 -23
  60. package/dist/configure-main.js +0 -6
  61. package/dist/enrol-main.js +0 -4
  62. package/dist/stream.js +0 -47
  63. package/how-we-work.md +0 -23
  64. package/skills/ask-matt/LICENSE +0 -21
  65. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  66. package/skills/ask-matt/SKILL.md +0 -91
  67. package/skills/ask-matt/agents/openai.yaml +0 -4
  68. package/skills/code-review/LICENSE +0 -21
  69. package/skills/code-review/SKILL.md +0 -89
  70. package/skills/code-review/agents/openai.yaml +0 -3
  71. package/skills/codebase-design/DEEPENING.md +0 -37
  72. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  73. package/skills/codebase-design/LICENSE +0 -21
  74. package/skills/codebase-design/SKILL.md +0 -116
  75. package/skills/codebase-design/agents/openai.yaml +0 -3
  76. package/skills/diagnosing-bugs/LICENSE +0 -21
  77. package/skills/diagnosing-bugs/SKILL.md +0 -140
  78. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  79. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  80. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  81. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  82. package/skills/domain-modeling/LICENSE +0 -21
  83. package/skills/domain-modeling/SKILL.md +0 -76
  84. package/skills/domain-modeling/agents/openai.yaml +0 -3
  85. package/skills/grill-me/LICENSE +0 -21
  86. package/skills/grill-me/SKILL.md +0 -8
  87. package/skills/grill-me/agents/openai.yaml +0 -4
  88. package/skills/grill-with-docs/LICENSE +0 -21
  89. package/skills/grill-with-docs/SKILL.md +0 -8
  90. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  91. package/skills/grilling/LICENSE +0 -21
  92. package/skills/grilling/SKILL.md +0 -30
  93. package/skills/grilling/agents/openai.yaml +0 -3
  94. package/skills/handoff/LICENSE +0 -21
  95. package/skills/handoff/SKILL.md +0 -17
  96. package/skills/handoff/agents/openai.yaml +0 -4
  97. package/skills/implement/LICENSE +0 -21
  98. package/skills/implement/SKILL.md +0 -16
  99. package/skills/implement/agents/openai.yaml +0 -4
  100. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  101. package/skills/improve-codebase-architecture/LICENSE +0 -21
  102. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  103. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  104. package/skills/prototype/LICENSE +0 -21
  105. package/skills/prototype/LOGIC.md +0 -67
  106. package/skills/prototype/SKILL.md +0 -28
  107. package/skills/prototype/UI.md +0 -112
  108. package/skills/prototype/agents/openai.yaml +0 -3
  109. package/skills/research/LICENSE +0 -21
  110. package/skills/research/SKILL.md +0 -14
  111. package/skills/research/agents/openai.yaml +0 -3
  112. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  113. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  114. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  115. package/skills/tdd/LICENSE +0 -21
  116. package/skills/tdd/SKILL.md +0 -40
  117. package/skills/tdd/agents/openai.yaml +0 -3
  118. package/skills/tdd/mocking.md +0 -59
  119. package/skills/tdd/tests.md +0 -77
  120. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  121. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  122. package/skills/teach/LICENSE +0 -21
  123. package/skills/teach/MISSION-FORMAT.md +0 -31
  124. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  125. package/skills/teach/SKILL.md +0 -141
  126. package/skills/teach/agents/openai.yaml +0 -4
  127. package/skills/to-questionnaire/LICENSE +0 -21
  128. package/skills/to-questionnaire/SKILL.md +0 -55
  129. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  130. package/skills/to-spec/LICENSE +0 -21
  131. package/skills/to-spec/SKILL.md +0 -76
  132. package/skills/to-spec/agents/openai.yaml +0 -4
  133. package/skills/to-tickets/LICENSE +0 -21
  134. package/skills/to-tickets/SKILL.md +0 -106
  135. package/skills/to-tickets/agents/openai.yaml +0 -4
  136. package/skills/wait-what/LICENSE +0 -21
  137. package/skills/wait-what/SKILL.md +0 -8
  138. package/skills/wait-what/agents/openai.yaml +0 -4
  139. package/skills/wayfinder/LICENSE +0 -21
  140. package/skills/wayfinder/SKILL.md +0 -129
  141. package/skills/wayfinder/agents/openai.yaml +0 -4
  142. package/skills/writing-for-agents/LICENSE +0 -21
  143. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  144. package/skills/writing-for-agents/SKILL.md +0 -83
  145. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/events.js ADDED
@@ -0,0 +1,793 @@
1
+ const AUTONOMOUS_ORIGINS = new Set(['task-notification', 'peer', 'coordinator', 'observer', 'observer-activity']);
2
+ const FINISHED = new Set(['completed', 'failed', 'stopped']);
3
+ export const RUNNING_JOB = new Set(['running', 'paused']);
4
+ const ENDED = { completed: 'done', failed: 'failed', stopped: 'stopped', killed: 'stopped', cancelled: 'stopped' };
5
+ const NOTICES = { info: 'info', warning: 'warning', error: 'error' };
6
+ // Claude Code names its limit windows without their length, so the Kit holds the length each name stands for.
7
+ const WINDOW_MINUTES = { five_hour: 300, seven_day: 10_080 };
8
+ const WAKEUP = /Next wakeup scheduled for \d\d:\d\d:\d\d \(in (\d+)s\)/;
9
+ const CHILD_UPDATES = new Set(['tool_call', 'tool_call_update']);
10
+ function counted(reports) {
11
+ const whole = reports.every((tokens) => Object.values(tokens).every((count) => Number.isSafeInteger(count) && count >= 0));
12
+ return whole ? reports.map((tokens) => ({ kind: 'tokens', tokens })) : [];
13
+ }
14
+ function contentText(content) {
15
+ return (content ?? [])
16
+ .map((entry) => (entry.type === 'content' && entry.content?.type === 'text' ? entry.content.text : ''))
17
+ .filter((part) => part !== '')
18
+ .join('\n');
19
+ }
20
+ function linesOf(text) {
21
+ return text === '' ? [] : text.replace(/\n$/, '').split('\n');
22
+ }
23
+ function count(value) {
24
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
25
+ }
26
+ function instant(milliseconds) {
27
+ return new Date(milliseconds).toISOString();
28
+ }
29
+ function changeCounts(diff) {
30
+ let added = 0;
31
+ let removed = 0;
32
+ for (const line of diff.split('\n')) {
33
+ if (line.startsWith('+') && !line.startsWith('+++'))
34
+ added++;
35
+ if (line.startsWith('-') && !line.startsWith('---'))
36
+ removed++;
37
+ }
38
+ return { added, removed };
39
+ }
40
+ function wholeFile(path, sign, text) {
41
+ const lines = linesOf(text).length;
42
+ return sign === '+' ? { path, added: lines, removed: 0 } : { path, added: 0, removed: lines };
43
+ }
44
+ function patched(path, patch) {
45
+ let added = 0;
46
+ let removed = 0;
47
+ for (const line of patch.flatMap((hunk) => hunk.lines)) {
48
+ if (line.startsWith('+'))
49
+ added++;
50
+ if (line.startsWith('-'))
51
+ removed++;
52
+ }
53
+ return { path, added, removed };
54
+ }
55
+ function replacement(site) {
56
+ const before = linesOf((site.line_prefix ?? '') + (site.old_string ?? ''));
57
+ const after = linesOf((site.line_prefix ?? '') + (site.new_string ?? ''));
58
+ let head = 0;
59
+ while (head < before.length && head < after.length && before[head] === after[head])
60
+ head++;
61
+ let tail = 0;
62
+ while (tail < before.length - head && tail < after.length - head && before.at(-1 - tail) === after.at(-1 - tail))
63
+ tail++;
64
+ return { added: after.length - head - tail, removed: before.length - head - tail };
65
+ }
66
+ function replaced(entry) {
67
+ const sites = entry._meta?.details ?? [{ old_string: entry.oldText, new_string: entry.newText }];
68
+ const hunks = sites.map(replacement);
69
+ return {
70
+ path: entry.path,
71
+ added: hunks.reduce((sum, hunk) => sum + hunk.added, 0),
72
+ removed: hunks.reduce((sum, hunk) => sum + hunk.removed, 0),
73
+ };
74
+ }
75
+ function changedFiles(files) {
76
+ const changes = [...files.values()];
77
+ return {
78
+ count: files.size,
79
+ added: changes.reduce((sum, change) => sum + change.added, 0),
80
+ removed: changes.reduce((sum, change) => sum + change.removed, 0),
81
+ };
82
+ }
83
+ function turnDiffFiles(diff) {
84
+ const files = new Map();
85
+ for (const section of diff.split(/^diff --git /m).filter((one) => one.trim() !== '')) {
86
+ const header = section.split('\n')[0];
87
+ const path = /^\+\+\+ b\/(.+)$/m.exec(section)?.[1] ?? header.slice(header.indexOf(' b/') + 3);
88
+ files.set(path, changeCounts(section));
89
+ }
90
+ return changedFiles(files);
91
+ }
92
+ function merged(into, from) {
93
+ if (from === null || from === undefined)
94
+ return into;
95
+ const result = { ...into };
96
+ for (const [key, value] of Object.entries(from)) {
97
+ result[key] =
98
+ typeof value === 'object' && value !== null && !Array.isArray(value) && typeof into[key] === 'object'
99
+ ? merged(into[key], value)
100
+ : value;
101
+ }
102
+ return result;
103
+ }
104
+ function heldStatus(held) {
105
+ if (!FINISHED.has(held.status))
106
+ return 'running';
107
+ return held.status === 'failed' ? 'failed' : 'done';
108
+ }
109
+ function backgroundKey(id) {
110
+ return `background ${id}`;
111
+ }
112
+ class Reader {
113
+ session = null;
114
+ calls = new Map();
115
+ owners = new Map();
116
+ backgrounds = new Map();
117
+ work = new Map();
118
+ seenOptions = new Map();
119
+ requestedOptions = new Map();
120
+ compactions = new Set();
121
+ turns = new Set();
122
+ edits = new Map();
123
+ read(message) {
124
+ if (message.method === undefined)
125
+ return this.answered(message.result);
126
+ const session = message.params?.sessionId;
127
+ if (session !== undefined && this.session !== null && session !== this.session) {
128
+ return this.elsewhere(session, message);
129
+ }
130
+ return this.own(message);
131
+ }
132
+ tap(_message) {
133
+ return [];
134
+ }
135
+ requested(option, value) {
136
+ this.requestedOptions.set(option, value);
137
+ }
138
+ refused(option) {
139
+ this.requestedOptions.delete(option);
140
+ }
141
+ began() {
142
+ this.edits.clear();
143
+ return this.editedFiles();
144
+ }
145
+ closeTurn() {
146
+ for (const [id, held] of this.calls)
147
+ if (held.counted !== 'subagent')
148
+ this.calls.delete(id);
149
+ }
150
+ answered(result) {
151
+ if (typeof result?.sessionId === 'string' && this.session === null)
152
+ this.session = result.sessionId;
153
+ for (const option of (result?.configOptions ?? [])) {
154
+ this.seenOptions.set(option.id, option.currentValue);
155
+ this.requestedOptions.delete(option.id);
156
+ }
157
+ return [];
158
+ }
159
+ elsewhere(_session, _message) {
160
+ return [];
161
+ }
162
+ own(message) {
163
+ if (message.method !== 'session/update')
164
+ return this.extension(message);
165
+ return this.update(message.params.update, null);
166
+ }
167
+ extension(_message) {
168
+ return [];
169
+ }
170
+ update(update, parent) {
171
+ switch (update.sessionUpdate) {
172
+ case 'agent_message_chunk':
173
+ if (parent !== null)
174
+ return [];
175
+ if (update.content.type === 'image')
176
+ return [{ kind: 'image', data: update.content.data, mediaType: update.content.mimeType }];
177
+ return update.content.type === 'text' ? [{ kind: 'text', id: update.messageId ?? null, text: update.content.text }] : [];
178
+ case 'tool_call':
179
+ case 'tool_call_update':
180
+ return this.tool(update, parent);
181
+ case 'usage_update':
182
+ return [{ kind: 'state', state: this.used(update) }];
183
+ case 'current_mode_update':
184
+ return [{ kind: 'notice', notice: 'mode', text: update.currentModeId }];
185
+ case 'available_commands_update':
186
+ return [{ kind: 'commands', commands: update.availableCommands }];
187
+ case 'config_option_update':
188
+ return [{ kind: 'options', options: update.configOptions }, ...this.optionsChanged(update.configOptions)];
189
+ case 'compaction_update':
190
+ if (update.status !== 'completed' || this.compactions.has(update.compactionId))
191
+ return [];
192
+ this.compactions.add(update.compactionId);
193
+ return [{ kind: 'notice', notice: 'compaction', text: '' }];
194
+ case 'session_info_update':
195
+ return this.info(update);
196
+ case 'notice': {
197
+ const said = [update.title, update.description].filter((text) => typeof text === 'string' && text !== '');
198
+ return [{ kind: 'notice', notice: NOTICES[update.severity] ?? 'info', text: said.join('\n') }];
199
+ }
200
+ case 'async_task_spawned':
201
+ if (update.taskType === 'turn') {
202
+ this.turns.add(update.asyncTaskId);
203
+ return [];
204
+ }
205
+ this.handedOff(update.toolCallId);
206
+ return this.background(update.asyncTaskId, update.taskType === 'shell' || update.taskType === 'monitor' ? update.taskType : 'task', 'running');
207
+ case 'async_task_state_update':
208
+ if (this.turns.has(update.asyncTaskId)) {
209
+ if (!RUNNING_JOB.has(update.state))
210
+ this.turns.delete(update.asyncTaskId);
211
+ return [];
212
+ }
213
+ if (RUNNING_JOB.has(update.state) || !this.backgrounds.has(update.asyncTaskId))
214
+ return [];
215
+ return this.background(update.asyncTaskId, this.backgrounds.get(update.asyncTaskId), ENDED[update.state] ?? 'done');
216
+ default:
217
+ return [];
218
+ }
219
+ }
220
+ used(update) {
221
+ return { context: { used: update.used, window: update.size, breakdown: [] } };
222
+ }
223
+ info(update) {
224
+ const suggestion = update._meta?.promptSuggestions?.suggestions?.[0]?.text;
225
+ const state = {
226
+ ...(typeof update.title === 'string' ? { title: update.title } : {}),
227
+ ...(typeof suggestion === 'string' ? { suggestion } : {}),
228
+ };
229
+ return Object.keys(state).length === 0 ? [] : [{ kind: 'state', state }];
230
+ }
231
+ handedOff(id) {
232
+ const held = id === undefined ? undefined : this.calls.get(id);
233
+ if (held !== undefined && !FINISHED.has(held.status))
234
+ held.status = 'completed';
235
+ }
236
+ background(id, kind, status) {
237
+ if (status === 'running')
238
+ this.backgrounds.set(id, kind);
239
+ else
240
+ this.backgrounds.delete(id);
241
+ return this.runs(backgroundKey(id), status === 'running' ? kind : null);
242
+ }
243
+ forget(id) {
244
+ this.backgrounds.delete(id);
245
+ return this.runs(backgroundKey(id), null);
246
+ }
247
+ runs(key, running) {
248
+ const before = this.work.get(key) ?? null;
249
+ if (running === null)
250
+ this.work.delete(key);
251
+ else
252
+ this.work.set(key, running);
253
+ if (before === running)
254
+ return [];
255
+ const counts = new Map();
256
+ for (const kind of this.work.values())
257
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
258
+ return [{ kind: 'state', state: { running: [...counts].map(([kind, count]) => ({ kind, count })) } }];
259
+ }
260
+ optionsChanged(options) {
261
+ const events = [];
262
+ for (const option of options) {
263
+ const notice = this.watchedOptions[option.id];
264
+ const before = this.seenOptions.get(option.id);
265
+ this.seenOptions.set(option.id, option.currentValue);
266
+ if (notice === undefined || before === undefined || before === option.currentValue)
267
+ continue;
268
+ if (this.requestedOptions.get(option.id) === option.currentValue) {
269
+ this.requestedOptions.delete(option.id);
270
+ continue;
271
+ }
272
+ events.push({ kind: 'notice', notice, text: String(option.currentValue) });
273
+ }
274
+ return events;
275
+ }
276
+ tool(update, parent) {
277
+ let held = this.calls.get(update.toolCallId);
278
+ if (held === undefined) {
279
+ if (update.sessionUpdate !== 'tool_call')
280
+ return [];
281
+ held = { id: update.toolCallId, parent, counted: null, meta: {}, imaged: false, status: 'in_progress' };
282
+ this.calls.set(held.id, held);
283
+ }
284
+ if (update.kind !== undefined)
285
+ held.kind = update.kind;
286
+ if (update.title !== undefined)
287
+ held.title = update.title;
288
+ if (update.status !== undefined && !FINISHED.has(held.status))
289
+ held.status = update.status;
290
+ if (update.rawInput !== undefined)
291
+ held.rawInput = merged(held.rawInput ?? {}, update.rawInput);
292
+ if (update.rawOutput !== undefined)
293
+ held.rawOutput = update.rawOutput;
294
+ if (update.content !== undefined)
295
+ held.content = update.content;
296
+ held.meta = merged(held.meta, (update._meta ?? {}));
297
+ return this.shown(held);
298
+ }
299
+ shown(held) {
300
+ const first = held.counted === null;
301
+ held.counted ??= this.kindOf(held);
302
+ if (held.counted === 'plan')
303
+ return [];
304
+ if (held.counted === 'subagent')
305
+ return this.subagent(held.id, held.parent, this.subagentStatus(held), first);
306
+ const call = { kind: held.counted, files: held.counted === 'edit' ? this.filesOf(held) : [], failed: this.failed(held) };
307
+ return [{ kind: 'call', key: held.id, parent: held.parent, first, call, running: null }, ...this.edited(held.id, call), ...this.produced(held)];
308
+ }
309
+ subagent(key, parent, status, first) {
310
+ if (!this.owners.has(key))
311
+ this.owners.set(key, parent);
312
+ const running = status === 'running';
313
+ const call = { kind: 'other', files: [], failed: status === 'failed' };
314
+ return [
315
+ { kind: 'call', key, parent: this.owners.get(key), first, call, running },
316
+ ...this.runs(key, running ? 'subagent' : null),
317
+ ];
318
+ }
319
+ subagentStatus(held) {
320
+ return heldStatus(held);
321
+ }
322
+ failed(held) {
323
+ if (held.status === 'failed')
324
+ return true;
325
+ const exit = held.rawOutput?.exit_code;
326
+ return held.counted === 'command' && FINISHED.has(held.status) && typeof exit === 'number' && exit !== 0;
327
+ }
328
+ filesFromEdits() {
329
+ return true;
330
+ }
331
+ edited(key, call) {
332
+ if (call.kind !== 'edit' || !this.filesFromEdits())
333
+ return [];
334
+ this.edits.set(key, call.files);
335
+ return this.editedFiles();
336
+ }
337
+ editedFiles() {
338
+ const files = new Map();
339
+ for (const change of [...this.edits.values()].flat()) {
340
+ const held = files.get(change.path);
341
+ files.set(change.path, { added: (held?.added ?? 0) + change.added, removed: (held?.removed ?? 0) + change.removed });
342
+ }
343
+ return [{ kind: 'state', state: { files: changedFiles(files) } }];
344
+ }
345
+ produced(_call) {
346
+ return [];
347
+ }
348
+ }
349
+ class ClaudeReader extends Reader {
350
+ watchedOptions = { model: 'model' };
351
+ settled = new Map();
352
+ answers = new Map();
353
+ windows = new Map();
354
+ crons = new Map();
355
+ wakeups = new Map();
356
+ breakdown = [];
357
+ stop = null;
358
+ answered(result) {
359
+ const models = (result?._meta?.quota?.model_usage ?? []);
360
+ const spent = counted(models.map(({ token_count: count }) => ({
361
+ input: count?.inputTokens,
362
+ output: count?.outputTokens,
363
+ cache_read: count?.cachedInputTokens,
364
+ cache_write: count?.cachedWriteTokens,
365
+ })));
366
+ return [...spent, ...super.answered(result)];
367
+ }
368
+ began() {
369
+ const fired = [...this.wakeups].filter(([, next]) => next <= Date.now()).map(([id]) => id);
370
+ for (const id of fired)
371
+ this.wakeups.delete(id);
372
+ return [...super.began(), ...fired.flatMap((id) => this.forget(id))];
373
+ }
374
+ own(message) {
375
+ const update = message.params?.update;
376
+ const parent = update?._meta?.claudeCode?.parentToolUseId;
377
+ if (parent === undefined)
378
+ return super.own(message);
379
+ return update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update' ? this.tool(update, parent) : [];
380
+ }
381
+ used(update) {
382
+ const cost = update.cost;
383
+ return {
384
+ context: { used: update.used, window: update.size, breakdown: this.breakdown },
385
+ ...(typeof cost?.amount === 'number' ? { cost: { amount: cost.amount, currency: cost.currency } } : {}),
386
+ };
387
+ }
388
+ update(update, parent) {
389
+ if (update.sessionUpdate === 'usage_update' && update._meta?.['_claude/origin'] !== undefined) {
390
+ const stop = this.stop;
391
+ this.stop = null;
392
+ return [...super.update(update, parent), { kind: 'ended', stop }];
393
+ }
394
+ if (update.sessionUpdate === 'session_info_update' && update._meta?.jetbrains?.air?.sessionFailure !== undefined) {
395
+ return [{ kind: 'notice', notice: 'retry', text: update._meta.jetbrains.air.sessionFailure.title }];
396
+ }
397
+ return super.update(update, parent);
398
+ }
399
+ extension(message) {
400
+ if (message.method !== '_claude/sdkMessage')
401
+ return [];
402
+ const sdk = message.params.message;
403
+ switch (sdk.type) {
404
+ case 'result':
405
+ if (AUTONOMOUS_ORIGINS.has(sdk.origin?.kind))
406
+ this.stop = null;
407
+ else
408
+ this.stop = sdk.stop_reason === 'refusal' ? 'refusal' : sdk.is_error === true ? null : 'end_turn';
409
+ return count(sdk.duration_ms) === null ? [] : [{ kind: 'state', state: { duration: sdk.duration_ms } }];
410
+ case 'assistant':
411
+ return this.assistant(sdk);
412
+ case 'user':
413
+ return this.user(sdk);
414
+ case 'rate_limit_event':
415
+ return this.limited(sdk.rate_limit_info);
416
+ }
417
+ if (typeof sdk.tool_use_id !== 'string' || sdk.subtype !== 'task_notification')
418
+ return [];
419
+ return this.settle(sdk.tool_use_id, ENDED[sdk.status] ?? 'done');
420
+ }
421
+ settle(key, status) {
422
+ const held = this.calls.get(key);
423
+ if (held?.counted !== 'subagent' && held !== undefined)
424
+ return [];
425
+ this.settled.set(key, status);
426
+ return held === undefined ? [] : this.shown(held);
427
+ }
428
+ assistant(sdk) {
429
+ const usage = sdk.context_usage;
430
+ if (usage === undefined)
431
+ return [];
432
+ this.breakdown = usage.categories.map((category) => ({ name: category.name, tokens: category.tokens }));
433
+ return [{ kind: 'state', state: { context: { used: usage.total_tokens, window: usage.raw_max_tokens, breakdown: this.breakdown } } }];
434
+ }
435
+ user(sdk) {
436
+ const content = sdk.message?.content;
437
+ if (!Array.isArray(content))
438
+ return [];
439
+ const events = [];
440
+ for (const block of content) {
441
+ if (block.type !== 'tool_result')
442
+ continue;
443
+ this.answers.set(block.tool_use_id, (sdk.tool_use_result ?? {}));
444
+ const held = this.calls.get(block.tool_use_id);
445
+ if (held !== undefined)
446
+ events.push(...this.shown(held));
447
+ }
448
+ return events;
449
+ }
450
+ limited(info) {
451
+ for (const [name, window] of Object.entries((info?.unifiedWindows ?? {}))) {
452
+ const minutes = WINDOW_MINUTES[name] ?? WINDOW_MINUTES[name.replace(/_[a-z]+$/, '')];
453
+ if (typeof window.utilization !== 'number' || minutes === undefined)
454
+ continue;
455
+ this.windows.set(name, {
456
+ name: name in WINDOW_MINUTES ? null : name,
457
+ minutes,
458
+ percent: Math.round(window.utilization * 1000) / 10,
459
+ resets: typeof window.resetsAt === 'number' ? instant(window.resetsAt * 1000) : null,
460
+ });
461
+ }
462
+ return this.windows.size === 0 ? [] : [{ kind: 'state', state: { limits: [...this.windows.values()] } }];
463
+ }
464
+ toolName(held) {
465
+ return held.meta.claudeCode?.toolName ?? '';
466
+ }
467
+ kindOf(held) {
468
+ const tool = this.toolName(held);
469
+ if (tool === 'Agent' || tool === 'Task' || held.meta.jetbrains?.air?.subagent === true)
470
+ return 'subagent';
471
+ if (tool.startsWith('mcp__'))
472
+ return 'other';
473
+ if (tool === 'Bash')
474
+ return 'command';
475
+ return held.kind === 'edit' ? 'edit' : 'other';
476
+ }
477
+ subagentStatus(held) {
478
+ const settled = this.settled.get(held.id);
479
+ if (settled !== undefined)
480
+ return settled;
481
+ const answered = this.answers.get(held.id);
482
+ const launched = held.meta.claudeCode?.toolResponse?.isAsync === true || answered?.status === 'async_launched';
483
+ if (launched || (!FINISHED.has(held.status) && answered === undefined))
484
+ return 'running';
485
+ return held.status === 'failed' ? 'failed' : 'done';
486
+ }
487
+ filesOf(held) {
488
+ const result = this.answers.get(held.id) ?? {};
489
+ const path = result.filePath ?? held.rawInput?.file_path;
490
+ if (typeof path !== 'string')
491
+ return [];
492
+ if (Array.isArray(result.structuredPatch) && result.structuredPatch.length > 0)
493
+ return [patched(path, result.structuredPatch)];
494
+ if (result.type === 'create' && typeof result.content === 'string')
495
+ return [wholeFile(path, '+', result.content)];
496
+ return [{ path, added: 0, removed: 0 }];
497
+ }
498
+ produced(held) {
499
+ if (held.status !== 'completed')
500
+ return [];
501
+ const tool = this.toolName(held);
502
+ const result = this.answers.get(held.id) ?? {};
503
+ if (tool === 'CronCreate' && typeof result.id === 'string' && !this.crons.has(result.id)) {
504
+ this.crons.set(result.id, held.id);
505
+ return this.background(held.id, 'schedule', 'running');
506
+ }
507
+ if (tool === 'CronDelete' && typeof held.rawInput?.id === 'string' && this.crons.has(held.rawInput.id)) {
508
+ const created = this.crons.get(held.rawInput.id);
509
+ this.crons.delete(held.rawInput.id);
510
+ return this.background(created, 'schedule', 'stopped');
511
+ }
512
+ if (tool !== 'ScheduleWakeup' || this.wakeups.has(held.id))
513
+ return [];
514
+ if (held.rawInput?.stop === true) {
515
+ const stopped = [...this.wakeups.keys()];
516
+ this.wakeups.clear();
517
+ return stopped.flatMap((id) => this.background(id, 'schedule', 'stopped'));
518
+ }
519
+ const seconds = WAKEUP.exec(contentText(held.content))?.[1];
520
+ if (seconds === undefined)
521
+ return [];
522
+ const next = Date.now() + Number(seconds) * 1000;
523
+ this.wakeups.set(held.id, next);
524
+ return this.background(held.id, 'schedule', 'running');
525
+ }
526
+ }
527
+ class CodexReader extends Reader {
528
+ watchedOptions = { mode: 'mode', collaboration_mode: 'mode' };
529
+ children = new Set();
530
+ items = new Map();
531
+ answered(result) {
532
+ const usage = result?.usage;
533
+ const spent = usage === null || usage === undefined
534
+ ? []
535
+ : counted([
536
+ {
537
+ input: usage.inputTokens,
538
+ output: usage.outputTokens,
539
+ cache_read: usage.cachedReadTokens,
540
+ cache_write: usage.cachedWriteTokens,
541
+ },
542
+ ]);
543
+ return [...spent, ...super.answered(result)];
544
+ }
545
+ filesFromEdits() {
546
+ return false;
547
+ }
548
+ tap(message) {
549
+ const params = (message.params ?? {});
550
+ if (message.method === 'account/rateLimits/updated')
551
+ return this.limited(params.rateLimits);
552
+ if (params.threadId !== this.session && !this.children.has(params.threadId))
553
+ return [];
554
+ switch (message.method) {
555
+ case 'item/started':
556
+ case 'item/completed': {
557
+ this.items.set(params.item.id, params.item);
558
+ const held = this.calls.get(params.item.id);
559
+ return held === undefined ? [] : this.shown(held);
560
+ }
561
+ case 'turn/completed':
562
+ return params.threadId === this.session && count(params.turn?.durationMs) !== null ? [{ kind: 'state', state: { duration: params.turn.durationMs } }] : [];
563
+ case 'turn/diff/updated':
564
+ return params.threadId === this.session ? [{ kind: 'state', state: { files: turnDiffFiles(params.diff) } }] : [];
565
+ default:
566
+ return [];
567
+ }
568
+ }
569
+ limited(limits) {
570
+ const windows = [limits?.primary, limits?.secondary].filter((window) => typeof window?.usedPercent === 'number');
571
+ if (windows.length === 0)
572
+ return [];
573
+ const name = typeof limits.limitName === 'string' ? limits.limitName : null;
574
+ const limited = windows.map((window) => ({
575
+ name,
576
+ // Codex sends each window's length; a limit always carries one, so a window Codex sends without it has 0.
577
+ minutes: count(window.windowDurationMins) ?? 0,
578
+ percent: window.usedPercent,
579
+ resets: typeof window.resetsAt === 'number' ? instant(window.resetsAt * 1000) : null,
580
+ }));
581
+ return [{ kind: 'state', state: { limits: limited } }];
582
+ }
583
+ own(message) {
584
+ if (message.method === 'session/request_permission' && message.params.toolCall?.kind === 'switch_mode') {
585
+ return [{ kind: 'started' }, { kind: 'notice', notice: 'mode', text: message.params.toolCall.title ?? '' }];
586
+ }
587
+ return super.own(message);
588
+ }
589
+ update(update, parent) {
590
+ switch (update.sessionUpdate) {
591
+ case 'session_info_update': {
592
+ const codex = update._meta?.codex;
593
+ if (codex?.threadStatus?.type === 'active')
594
+ return [{ kind: 'started' }];
595
+ if (codex?.threadStatus?.type === 'idle')
596
+ return [{ kind: 'ended', stop: null }];
597
+ if (codex?.error !== undefined)
598
+ return [{ kind: 'notice', notice: 'retry', text: codex.error.message ?? '' }];
599
+ return super.update(update, parent);
600
+ }
601
+ case 'subagent_spawned': {
602
+ const first = !this.children.has(update.subagentSessionId);
603
+ this.children.add(update.subagentSessionId);
604
+ return this.subagent(update.subagentSessionId, parent, 'running', first);
605
+ }
606
+ case 'subagent_state_update':
607
+ if (!this.children.has(update.subagentSessionId))
608
+ return [];
609
+ return this.subagent(update.subagentSessionId, parent, ENDED[update.state] ?? 'failed', false);
610
+ default:
611
+ return super.update(update, parent);
612
+ }
613
+ }
614
+ elsewhere(session, message) {
615
+ const update = message.params?.update;
616
+ if (!this.children.has(session) || update === undefined)
617
+ return [];
618
+ if (update.sessionUpdate === 'subagent_spawned' || update.sessionUpdate === 'subagent_state_update')
619
+ return this.update(update, session);
620
+ return CHILD_UPDATES.has(update.sessionUpdate) ? this.update(update, session) : [];
621
+ }
622
+ kindOf(held) {
623
+ if (held.meta.is_mcp_tool_call === true)
624
+ return 'other';
625
+ if (held.kind === 'execute')
626
+ return 'command';
627
+ return held.kind === 'edit' ? 'edit' : 'other';
628
+ }
629
+ filesOf(held) {
630
+ const item = this.items.get(held.id);
631
+ if (item?.type !== 'fileChange')
632
+ return [];
633
+ return item.changes.map((change) => {
634
+ if (change.kind?.type === 'add')
635
+ return wholeFile(change.path, '+', change.diff);
636
+ if (change.kind?.type === 'delete')
637
+ return wholeFile(change.path, '-', change.diff);
638
+ return { path: change.kind?.move_path ?? change.path, ...changeCounts(change.diff) };
639
+ });
640
+ }
641
+ produced(held) {
642
+ if (held.imaged || held.kind === 'read' || held.parent !== null)
643
+ return [];
644
+ const image = (held.content ?? []).find((entry) => entry.type === 'content' && entry.content?.type === 'image');
645
+ if (image === undefined)
646
+ return [];
647
+ held.imaged = true;
648
+ return [{ kind: 'image', data: image.content.data, mediaType: image.content.mimeType }];
649
+ }
650
+ }
651
+ class GrokReader extends Reader {
652
+ watchedOptions = {};
653
+ children = new Map();
654
+ settled = new Map();
655
+ schedules = new Set();
656
+ models = [];
657
+ model = null;
658
+ answered(result) {
659
+ if (result?.models !== undefined)
660
+ this.offered(result.models);
661
+ return super.answered(result);
662
+ }
663
+ read(message) {
664
+ const session = message.params?.sessionId;
665
+ if (this.session !== null && session !== undefined && session !== this.session && !this.children.has(session))
666
+ return [];
667
+ if (message.method === '_x.ai/queue/changed') {
668
+ return (message.params.runningPromptId ?? null) !== null && session === this.session ? [{ kind: 'started' }] : [];
669
+ }
670
+ if (message.params?.update?.sessionUpdate === 'turn_completed') {
671
+ if (session !== this.session)
672
+ return [];
673
+ return [...this.spent(message.params.update.usage), { kind: 'ended', stop: null }];
674
+ }
675
+ if (message.method === '_x.ai/models/update') {
676
+ this.offered(message.params);
677
+ return [];
678
+ }
679
+ return super.read(message);
680
+ }
681
+ elsewhere(session, message) {
682
+ const parent = this.children.get(session);
683
+ const update = message.params?.update;
684
+ if (typeof parent !== 'string' || message.method !== 'session/update' || !CHILD_UPDATES.has(update?.sessionUpdate))
685
+ return [];
686
+ return this.update(update, parent);
687
+ }
688
+ spent(usage) {
689
+ if (usage === null || usage === undefined)
690
+ return [];
691
+ const { inputTokens, outputTokens, cachedReadTokens, cacheCreationTokens } = usage;
692
+ const input = inputTokens - cachedReadTokens - cacheCreationTokens;
693
+ return counted([{ input, output: outputTokens, cache_read: cachedReadTokens, cache_write: cacheCreationTokens }]);
694
+ }
695
+ offered(models) {
696
+ this.models = models.availableModels ?? this.models;
697
+ this.model = models.currentModelId ?? this.model;
698
+ }
699
+ window() {
700
+ return this.models.find((model) => model.modelId === this.model)?._meta?.totalContextTokens ?? null;
701
+ }
702
+ extension(message) {
703
+ const update = message.params?.update;
704
+ switch (message.method) {
705
+ case '_x.ai/task_backgrounded':
706
+ this.handedOff(update.tool_call_id);
707
+ return this.background(update.task_id, 'shell', 'running');
708
+ case '_x.ai/task_completed': {
709
+ const snapshot = update.task_snapshot;
710
+ return this.background(snapshot.task_id, 'shell', snapshot.exit_code === 0 ? 'done' : 'failed');
711
+ }
712
+ case '_x.ai/scheduled_task_created': {
713
+ this.schedules.add(update.task_id);
714
+ return this.background(update.task_id, 'schedule', 'running');
715
+ }
716
+ case '_x.ai/scheduled_task_deleted':
717
+ return this.schedules.delete(update.task_id) ? this.background(update.task_id, 'schedule', 'stopped') : [];
718
+ case '_x.ai/session_notification':
719
+ return this.notification(update);
720
+ default:
721
+ return [];
722
+ }
723
+ }
724
+ notification(update) {
725
+ switch (update.sessionUpdate) {
726
+ case 'response_completed': {
727
+ const usage = update.usage;
728
+ const window = this.window();
729
+ if (window === null)
730
+ return [];
731
+ const used = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + usage.output_tokens;
732
+ return [{ kind: 'state', state: { context: { used, window, breakdown: [] } } }];
733
+ }
734
+ case 'subagent_spawned': {
735
+ const linked = [...this.children.values()];
736
+ const unlinked = [...this.calls.values()].filter((candidate) => candidate.counted === 'subagent' && !linked.includes(candidate.id));
737
+ const held = unlinked.find((candidate) => candidate.rawInput?.description === update.description);
738
+ this.children.set(update.child_session_id, held?.id ?? null);
739
+ return [];
740
+ }
741
+ case 'subagent_finished': {
742
+ const key = this.children.get(update.child_session_id);
743
+ if (typeof key !== 'string')
744
+ return [];
745
+ this.settled.set(key, ENDED[update.status] ?? 'failed');
746
+ const held = this.calls.get(key);
747
+ return held === undefined ? [] : this.shown(held);
748
+ }
749
+ case 'auto_compact_completed':
750
+ return [{ kind: 'notice', notice: 'compaction', text: '' }];
751
+ case 'model_auto_switched':
752
+ this.model = update.new_model_id;
753
+ return [{ kind: 'notice', notice: 'model', text: update.new_model_id }];
754
+ case 'retry_state':
755
+ return [{ kind: 'notice', notice: 'retry', text: update.message ?? update.reason ?? update.error_type ?? '' }];
756
+ default:
757
+ return [];
758
+ }
759
+ }
760
+ xai(held) {
761
+ return (held.meta['x.ai/tool'] ?? {});
762
+ }
763
+ kindOf(held) {
764
+ const tool = this.xai(held);
765
+ if (tool.name === 'spawn_subagent' || tool.kind === 'task')
766
+ return 'subagent';
767
+ if (tool.kind === 'plan')
768
+ return 'plan';
769
+ if (tool.name === 'run_terminal_command')
770
+ return 'command';
771
+ const kind = tool.kind ?? held.kind;
772
+ if (kind === 'execute')
773
+ return 'command';
774
+ return kind === 'write' || kind === 'edit' ? 'edit' : 'other';
775
+ }
776
+ subagentStatus(held) {
777
+ return this.settled.get(held.id) ?? (held.status === 'failed' ? 'failed' : 'running');
778
+ }
779
+ filesOf(held) {
780
+ return (held.content ?? []).filter((entry) => entry.type === 'diff').map(replaced);
781
+ }
782
+ }
783
+ export function answeredFailure(answer) {
784
+ const failure = answer._meta?.jetbrains?.air?.sessionFailure;
785
+ return typeof failure?.title === 'string' ? { title: failure.title, limit: failure.category === 'limit' } : null;
786
+ }
787
+ export function readerFor(kind) {
788
+ if (kind === 'claude-agent-acp')
789
+ return new ClaudeReader();
790
+ if (kind === 'grok-build')
791
+ return new GrokReader();
792
+ return new CodexReader();
793
+ }