@agentshouse/kit 0.2.1-ccf188e02985d → 0.2.1-ccffb3f637815

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 (164) hide show
  1. package/README.md +37 -41
  2. package/dist/acp.js +66 -12
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +122 -53
  5. package/dist/api.js +15 -10
  6. package/dist/binaries.js +89 -0
  7. package/dist/bridge.js +29 -28
  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 +62 -50
  12. package/dist/connect.js +108 -0
  13. package/dist/connection.js +120 -0
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +594 -219
  16. package/dist/copies.js +772 -279
  17. package/dist/earlier.js +263 -0
  18. package/dist/end.js +12 -5
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +206 -38
  21. package/dist/git-main.js +24 -29
  22. package/dist/git.js +90 -15
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +80 -29
  25. package/dist/house-cli.js +155 -164
  26. package/dist/house-main.js +3 -3
  27. package/dist/instructions.js +29 -11
  28. package/dist/keys.js +238 -0
  29. package/dist/kit-cli.js +18 -8
  30. package/dist/kit-main.js +3 -3
  31. package/dist/login.js +36 -22
  32. package/dist/logout.js +2 -2
  33. package/dist/mcp.js +42 -3
  34. package/dist/old-references.js +27 -0
  35. package/dist/owner.js +46 -0
  36. package/dist/placement.js +15 -20
  37. package/dist/refusals.js +37 -21
  38. package/dist/relay.js +21 -0
  39. package/dist/resident.js +128 -82
  40. package/dist/scope.js +15 -4
  41. package/dist/scripts.js +303 -0
  42. package/dist/secret-input.js +1 -1
  43. package/dist/settings.js +188 -0
  44. package/dist/sign-in.js +67 -21
  45. package/dist/silence.js +28 -0
  46. package/dist/skills.js +42 -97
  47. package/dist/supervisor.js +163 -0
  48. package/dist/transcription.js +88 -45
  49. package/dist/translate.js +19 -18
  50. package/dist/update.js +118 -120
  51. package/dist/wire.js +30 -4
  52. package/dist/work.js +27 -2
  53. package/dist/workspace.js +103 -0
  54. package/package.json +26 -22
  55. package/dist/authority-main.js +0 -22
  56. package/dist/bootstrap.json +0 -24
  57. package/dist/chatgpt.js +0 -32
  58. package/dist/clis-main.js +0 -23
  59. package/dist/configure-main.js +0 -6
  60. package/dist/enrol-main.js +0 -10
  61. package/dist/inputs.js +0 -37
  62. package/dist/parts.js +0 -82
  63. package/dist/service-main.js +0 -9
  64. package/dist/service.js +0 -55
  65. package/dist/stream.js +0 -123
  66. package/how-we-work.md +0 -33
  67. package/skills/ask-matt/LICENSE +0 -21
  68. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  69. package/skills/ask-matt/SKILL.md +0 -97
  70. package/skills/ask-matt/agents/openai.yaml +0 -5
  71. package/skills/code-review/LICENSE +0 -21
  72. package/skills/code-review/SKILL.md +0 -89
  73. package/skills/code-review/agents/openai.yaml +0 -3
  74. package/skills/codebase-design/DEEPENING.md +0 -37
  75. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  76. package/skills/codebase-design/LICENSE +0 -21
  77. package/skills/codebase-design/SKILL.md +0 -114
  78. package/skills/codebase-design/agents/openai.yaml +0 -3
  79. package/skills/diagnosing-bugs/LICENSE +0 -21
  80. package/skills/diagnosing-bugs/SKILL.md +0 -138
  81. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  82. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  83. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  84. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  85. package/skills/domain-modeling/LICENSE +0 -21
  86. package/skills/domain-modeling/SKILL.md +0 -74
  87. package/skills/domain-modeling/agents/openai.yaml +0 -3
  88. package/skills/grill-me/LICENSE +0 -21
  89. package/skills/grill-me/SKILL.md +0 -7
  90. package/skills/grill-me/agents/openai.yaml +0 -5
  91. package/skills/grill-with-docs/LICENSE +0 -21
  92. package/skills/grill-with-docs/SKILL.md +0 -7
  93. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  94. package/skills/grilling/LICENSE +0 -21
  95. package/skills/grilling/SKILL.md +0 -30
  96. package/skills/grilling/agents/openai.yaml +0 -3
  97. package/skills/handoff/LICENSE +0 -21
  98. package/skills/handoff/SKILL.md +0 -16
  99. package/skills/handoff/agents/openai.yaml +0 -5
  100. package/skills/implement/LICENSE +0 -21
  101. package/skills/implement/SKILL.md +0 -17
  102. package/skills/implement/agents/openai.yaml +0 -5
  103. package/skills/implement-spec/LICENSE +0 -21
  104. package/skills/implement-spec/SKILL.md +0 -40
  105. package/skills/implement-spec/agents/openai.yaml +0 -5
  106. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  107. package/skills/improve-codebase-architecture/LICENSE +0 -21
  108. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  109. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  110. package/skills/pr/CREDITS.md +0 -3
  111. package/skills/pr/LICENSE +0 -21
  112. package/skills/pr/SKILL.md +0 -170
  113. package/skills/pr/agents/openai.yaml +0 -3
  114. package/skills/prototype/LICENSE +0 -21
  115. package/skills/prototype/LOGIC.md +0 -67
  116. package/skills/prototype/SKILL.md +0 -26
  117. package/skills/prototype/UI.md +0 -112
  118. package/skills/prototype/agents/openai.yaml +0 -3
  119. package/skills/research/LICENSE +0 -21
  120. package/skills/research/SKILL.md +0 -12
  121. package/skills/research/agents/openai.yaml +0 -3
  122. package/skills/retro/LICENSE +0 -21
  123. package/skills/retro/SKILL.md +0 -44
  124. package/skills/retro/agents/openai.yaml +0 -5
  125. package/skills/tdd/LICENSE +0 -21
  126. package/skills/tdd/SKILL.md +0 -38
  127. package/skills/tdd/agents/openai.yaml +0 -3
  128. package/skills/tdd/mocking.md +0 -59
  129. package/skills/tdd/tests.md +0 -77
  130. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  131. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  132. package/skills/teach/LICENSE +0 -21
  133. package/skills/teach/MISSION-FORMAT.md +0 -31
  134. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  135. package/skills/teach/SKILL.md +0 -140
  136. package/skills/teach/agents/openai.yaml +0 -5
  137. package/skills/to-questionnaire/LICENSE +0 -21
  138. package/skills/to-questionnaire/SKILL.md +0 -54
  139. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  140. package/skills/to-spec/LICENSE +0 -21
  141. package/skills/to-spec/SKILL.md +0 -75
  142. package/skills/to-spec/agents/openai.yaml +0 -5
  143. package/skills/to-tickets/LICENSE +0 -21
  144. package/skills/to-tickets/SKILL.md +0 -105
  145. package/skills/to-tickets/agents/openai.yaml +0 -5
  146. package/skills/triage/AGENT-BRIEF.md +0 -207
  147. package/skills/triage/LICENSE +0 -21
  148. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  149. package/skills/triage/SKILL.md +0 -112
  150. package/skills/triage/agents/openai.yaml +0 -5
  151. package/skills/wait-what/LICENSE +0 -21
  152. package/skills/wait-what/SKILL.md +0 -7
  153. package/skills/wait-what/agents/openai.yaml +0 -5
  154. package/skills/wayfinder/LICENSE +0 -21
  155. package/skills/wayfinder/SKILL.md +0 -128
  156. package/skills/wayfinder/agents/openai.yaml +0 -5
  157. package/skills/wizard/LICENSE +0 -21
  158. package/skills/wizard/SKILL.md +0 -44
  159. package/skills/wizard/agents/openai.yaml +0 -3
  160. package/skills/wizard/template.sh +0 -223
  161. package/skills/writing-for-agents/LICENSE +0 -21
  162. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  163. package/skills/writing-for-agents/SKILL.md +0 -81
  164. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/events.js CHANGED
@@ -1,74 +1,93 @@
1
- const COMMAND = { shown: 'command' };
2
- const HIDDEN = { shown: 'hidden' };
3
- const FINISHED = new Set(['completed', 'failed']);
1
+ const AUTONOMOUS_ORIGINS = new Set(['task-notification', 'peer', 'coordinator', 'observer', 'observer-activity']);
2
+ const FINISHED = new Set(['completed', 'failed', 'stopped']);
4
3
  export const RUNNING_JOB = new Set(['running', 'paused']);
5
- const ROUTINE_TARGETS = { send_routine_request: 'access', cancel_routine_request: 'request' };
6
- function words(line) {
7
- const found = [];
8
- let word = null;
9
- let quote = null;
10
- for (let index = 0; index < line.length; index++) {
11
- const character = line[index];
12
- if (quote !== null) {
13
- if (character === quote)
14
- quote = null;
15
- else if (character === '\\' && quote === '"')
16
- word += line[++index] ?? '';
17
- else
18
- word += character;
19
- }
20
- else if (character === "'" || character === '"') {
21
- quote = character;
22
- word ??= '';
23
- }
24
- else if (character === '\\') {
25
- word = (word ?? '') + (line[++index] ?? '');
26
- }
27
- else if (/\s/.test(character)) {
28
- if (word !== null)
29
- found.push(word);
30
- word = null;
31
- }
32
- else {
33
- word = (word ?? '') + character;
34
- }
35
- }
36
- if (word !== null)
37
- found.push(word);
38
- return found;
39
- }
40
- export function houseMessage(line) {
41
- const [program, verb, json] = words(line.trim());
42
- if (program !== 'house' || verb !== 'run_command' || json === undefined)
43
- return null;
44
- let call;
45
- try {
46
- call = JSON.parse(json);
47
- }
48
- catch {
49
- return null;
50
- }
51
- const argument = ROUTINE_TARGETS[call.command];
52
- if (argument === undefined)
53
- return null;
54
- const target = call.arguments?.[argument];
55
- return { shown: 'message', command: call.command, target: typeof target === 'string' ? target : null };
56
- }
57
- function decidedByLine(command, final) {
58
- 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;
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 })) : [];
62
13
  }
63
14
  function contentText(content) {
64
- const text = (content ?? [])
15
+ return (content ?? [])
65
16
  .map((entry) => (entry.type === 'content' && entry.content?.type === 'text' ? entry.content.text : ''))
66
17
  .filter((part) => part !== '')
67
18
  .join('\n');
68
- return text === '' ? null : text;
69
19
  }
70
- function plan(entries) {
71
- return entries.map((entry) => ({ content: entry.content, status: entry.status }));
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);
72
91
  }
73
92
  function merged(into, from) {
74
93
  if (from === null || from === undefined)
@@ -82,22 +101,25 @@ function merged(into, from) {
82
101
  }
83
102
  return result;
84
103
  }
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;
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}`;
91
111
  }
92
112
  class Reader {
93
113
  session = null;
94
114
  calls = new Map();
95
- subagents = new Set();
96
- done = new Set();
115
+ owners = new Map();
116
+ backgrounds = new Map();
117
+ work = new Map();
97
118
  seenOptions = new Map();
98
119
  requestedOptions = new Map();
99
120
  compactions = new Set();
100
- jobs = new Map();
121
+ turns = new Set();
122
+ edits = new Map();
101
123
  read(message) {
102
124
  if (message.method === undefined)
103
125
  return this.answered(message.result);
@@ -107,22 +129,23 @@ class Reader {
107
129
  }
108
130
  return this.own(message);
109
131
  }
132
+ tap(_message) {
133
+ return [];
134
+ }
110
135
  requested(option, value) {
111
136
  this.requestedOptions.set(option, value);
112
137
  }
113
138
  refused(option) {
114
139
  this.requestedOptions.delete(option);
115
140
  }
141
+ began() {
142
+ this.edits.clear();
143
+ return this.editedFiles();
144
+ }
116
145
  closeTurn() {
117
- const events = [];
118
- for (const [id, call] of this.calls) {
119
- if (call.decided?.shown === 'subagent')
120
- continue;
121
- if (call.decided === null)
122
- events.push(...this.shown(call, this.decide(call, true)));
123
- this.calls.delete(id);
124
- }
125
- return events;
146
+ for (const [id, held] of this.calls)
147
+ if (held.counted !== 'subagent')
148
+ this.calls.delete(id);
126
149
  }
127
150
  answered(result) {
128
151
  if (typeof result?.sessionId === 'string' && this.session === null)
@@ -139,28 +162,26 @@ class Reader {
139
162
  own(message) {
140
163
  if (message.method !== 'session/update')
141
164
  return this.extension(message);
142
- return this.update(message.params.update);
165
+ return this.update(message.params.update, null);
143
166
  }
144
167
  extension(_message) {
145
168
  return [];
146
169
  }
147
- update(update) {
170
+ update(update, parent) {
148
171
  switch (update.sessionUpdate) {
149
172
  case 'agent_message_chunk':
173
+ if (parent !== null)
174
+ return [];
150
175
  if (update.content.type === 'image')
151
176
  return [{ kind: 'image', data: update.content.data, mediaType: update.content.mimeType }];
152
177
  return update.content.type === 'text' ? [{ kind: 'text', id: update.messageId ?? null, text: update.content.text }] : [];
153
- case 'agent_thought_chunk':
154
- return update.content.type === 'text' ? [{ kind: 'reasoning', id: update.messageId ?? null, text: update.content.text }] : [];
155
178
  case 'tool_call':
156
179
  case 'tool_call_update':
157
- return this.tool(update);
158
- case 'plan':
159
- return [{ kind: 'plan', entries: plan(update.entries) }];
180
+ return this.tool(update, parent);
160
181
  case 'usage_update':
161
- return [{ kind: 'context', used: update.used, window: update.size }];
182
+ return [{ kind: 'state', state: this.used(update) }];
162
183
  case 'current_mode_update':
163
- return [{ kind: 'marker', marker: 'mode', text: update.currentModeId }];
184
+ return [{ kind: 'notice', notice: 'mode', text: update.currentModeId }];
164
185
  case 'available_commands_update':
165
186
  return [{ kind: 'commands', commands: update.availableCommands }];
166
187
  case 'config_option_update':
@@ -169,251 +190,469 @@ class Reader {
169
190
  if (update.status !== 'completed' || this.compactions.has(update.compactionId))
170
191
  return [];
171
192
  this.compactions.add(update.compactionId);
172
- return [{ kind: 'marker', marker: 'compaction', text: '' }];
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
+ }
173
200
  case 'async_task_spawned':
174
- return this.job(update.asyncTaskId, update.name ?? update.description ?? '', 'running');
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');
175
207
  case 'async_task_state_update':
176
- return RUNNING_JOB.has(update.state) ? [] : this.job(update.asyncTaskId, null, update.state);
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');
177
216
  default:
178
217
  return [];
179
218
  }
180
219
  }
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}` }];
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 })) } }];
188
259
  }
189
260
  optionsChanged(options) {
190
261
  const events = [];
191
262
  for (const option of options) {
192
- const marker = this.watchedOptions[option.id];
263
+ const notice = this.watchedOptions[option.id];
193
264
  const before = this.seenOptions.get(option.id);
194
265
  this.seenOptions.set(option.id, option.currentValue);
195
- if (marker === undefined || before === undefined || before === option.currentValue)
266
+ if (notice === undefined || before === undefined || before === option.currentValue)
196
267
  continue;
197
268
  if (this.requestedOptions.get(option.id) === option.currentValue) {
198
269
  this.requestedOptions.delete(option.id);
199
270
  continue;
200
271
  }
201
- events.push({ kind: 'marker', marker, text: String(option.currentValue) });
272
+ events.push({ kind: 'notice', notice, text: String(option.currentValue) });
202
273
  }
203
274
  return events;
204
275
  }
205
- tool(update) {
206
- let call = this.calls.get(update.toolCallId);
207
- if (call === undefined) {
276
+ tool(update, parent) {
277
+ let held = this.calls.get(update.toolCallId);
278
+ if (held === undefined) {
208
279
  if (update.sessionUpdate !== 'tool_call')
209
280
  return [];
210
- call = { id: update.toolCallId, decided: null, meta: {}, imaged: false, status: 'in_progress' };
211
- this.calls.set(call.id, call);
281
+ held = { id: update.toolCallId, parent, counted: null, meta: {}, imaged: false, status: 'in_progress' };
282
+ this.calls.set(held.id, held);
212
283
  }
213
284
  if (update.kind !== undefined)
214
- call.kind = update.kind;
285
+ held.kind = update.kind;
215
286
  if (update.title !== undefined)
216
- call.title = update.title;
217
- if (update.status !== undefined)
218
- call.status = update.status;
287
+ held.title = update.title;
288
+ if (update.status !== undefined && !FINISHED.has(held.status))
289
+ held.status = update.status;
219
290
  if (update.rawInput !== undefined)
220
- call.rawInput = merged(call.rawInput ?? {}, update.rawInput);
291
+ held.rawInput = merged(held.rawInput ?? {}, update.rawInput);
292
+ if (update.rawOutput !== undefined)
293
+ held.rawOutput = update.rawOutput;
221
294
  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;
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;
237
327
  }
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 }];
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 });
252
342
  }
343
+ return [{ kind: 'state', state: { files: changedFiles(files) } }];
253
344
  }
254
345
  produced(_call) {
255
346
  return [];
256
347
  }
257
- subagentFinished(call) {
258
- this.calls.delete(call.id);
259
- return this.finish(call.id, contentText(call.content));
260
- }
261
- finish(id, result) {
262
- if (!this.subagents.has(id) || this.done.has(id))
263
- return [];
264
- this.done.add(id);
265
- this.calls.delete(id);
266
- return [{ kind: 'subagent-done', id, result }];
267
- }
268
348
  }
269
349
  class ClaudeReader extends Reader {
270
350
  watchedOptions = { model: 'model' };
271
- tasks = new Map();
272
- own(message) {
273
- if (message.params?.update?._meta?.claudeCode?.parentToolUseId !== undefined)
274
- return [];
275
- return super.own(message);
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))];
276
373
  }
277
- update(update) {
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) {
278
389
  if (update.sessionUpdate === 'usage_update' && update._meta?.['_claude/origin'] !== undefined) {
279
- return [...super.update(update), { kind: 'ended' }];
390
+ const stop = this.stop;
391
+ this.stop = null;
392
+ return [...super.update(update, parent), { kind: 'ended', stop }];
280
393
  }
281
394
  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 }];
395
+ return [{ kind: 'notice', notice: 'retry', text: update._meta.jetbrains.air.sessionFailure.title }];
283
396
  }
284
- return super.update(update);
397
+ return super.update(update, parent);
285
398
  }
286
399
  extension(message) {
287
400
  if (message.method !== '_claude/sdkMessage')
288
401
  return [];
289
402
  const sdk = message.params.message;
290
- switch (sdk.subtype) {
291
- case 'task_started':
292
- if (sdk.tool_use_id !== undefined)
293
- this.tasks.set(sdk.task_id, sdk.tool_use_id);
294
- return [];
295
- case 'task_notification':
296
- return sdk.tool_use_id === undefined ? [] : this.finish(sdk.tool_use_id, sdk.summary ?? null);
297
- default:
298
- return [];
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);
299
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');
300
420
  }
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 ?? '' };
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));
308
447
  }
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;
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
+ });
315
461
  }
316
- if (call.kind === 'switch_mode')
317
- return { shown: 'marker', marker: 'mode', text: call.title ?? '' };
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';
318
473
  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;
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');
324
506
  }
325
- return COMMAND;
326
- }
327
- produced(call) {
328
- const tool = call.meta.claudeCode?.toolName;
329
- if (call.status !== 'completed')
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))
330
513
  return [];
331
- if (tool === 'CronCreate' || (tool === 'ScheduleWakeup' && call.rawInput?.stop !== true)) {
332
- return [{ kind: 'marker', marker: 'job', text: `${call.rawInput?.prompt ?? call.title ?? ''}: scheduled` }];
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'));
333
518
  }
334
- return [];
335
- }
336
- subagentFinished(call) {
337
- if (call.meta.claudeCode?.toolResponse?.isAsync === true)
519
+ const seconds = WAKEUP.exec(contentText(held.content))?.[1];
520
+ if (seconds === undefined)
338
521
  return [];
339
- return super.subagentFinished(call);
522
+ const next = Date.now() + Number(seconds) * 1000;
523
+ this.wakeups.set(held.id, next);
524
+ return this.background(held.id, 'schedule', 'running');
340
525
  }
341
526
  }
342
- const COLLABORATION = new Set(['spawnAgent', 'sendInput', 'resumeAgent', 'wait', 'closeAgent', 'followupTask']);
343
527
  class CodexReader extends Reader {
344
528
  watchedOptions = { mode: 'mode', collaboration_mode: 'mode' };
345
- children = new Map();
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
+ }
346
583
  own(message) {
347
584
  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 ?? '' }];
585
+ return [{ kind: 'started' }, { kind: 'notice', notice: 'mode', text: message.params.toolCall.title ?? '' }];
349
586
  }
350
587
  return super.own(message);
351
588
  }
352
- update(update) {
589
+ update(update, parent) {
353
590
  switch (update.sessionUpdate) {
354
591
  case 'session_info_update': {
355
592
  const codex = update._meta?.codex;
356
593
  if (codex?.threadStatus?.type === 'active')
357
594
  return [{ kind: 'started' }];
358
595
  if (codex?.threadStatus?.type === 'idle')
359
- return [{ kind: 'ended' }];
596
+ return [{ kind: 'ended', stop: null }];
360
597
  if (codex?.error !== undefined)
361
- return [{ kind: 'marker', marker: 'retry', text: codex.error.message ?? '' }];
362
- return [];
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);
363
605
  }
364
- case 'notice':
365
- return update.severity === 'info' ? [{ kind: 'marker', marker: 'model', text: update.description ?? update.title }] : [];
366
- case 'subagent_spawned':
367
- 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
606
  case 'subagent_state_update':
371
- return this.finish(update.subagentSessionId, this.children.get(update.subagentSessionId)?.text || null);
607
+ if (!this.children.has(update.subagentSessionId))
608
+ return [];
609
+ return this.subagent(update.subagentSessionId, parent, ENDED[update.state] ?? 'failed', false);
372
610
  default:
373
- return super.update(update);
611
+ return super.update(update, parent);
374
612
  }
375
613
  }
376
614
  elsewhere(session, message) {
377
- const child = this.children.get(session);
378
615
  const update = message.params?.update;
379
- if (child === undefined || update === undefined)
616
+ if (!this.children.has(session) || update === undefined)
380
617
  return [];
381
- if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
382
- const id = update.messageId ?? null;
383
- if (child.id !== id)
384
- child.text = '';
385
- child.id = id;
386
- child.text += update.content.text;
387
- }
388
- return [];
389
- }
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')
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')
406
632
  return [];
407
- const image = (call.content ?? []).find((entry) => entry.type === 'content' && entry.content?.type === 'image');
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');
408
645
  if (image === undefined)
409
646
  return [];
410
- call.imaged = true;
647
+ held.imaged = true;
411
648
  return [{ kind: 'image', data: image.content.data, mediaType: image.content.mimeType }];
412
649
  }
413
650
  }
414
651
  class GrokReader extends Reader {
415
652
  watchedOptions = {};
416
653
  children = new Map();
654
+ settled = new Map();
655
+ schedules = new Set();
417
656
  models = [];
418
657
  model = null;
419
658
  answered(result) {
@@ -429,7 +668,9 @@ class GrokReader extends Reader {
429
668
  return (message.params.runningPromptId ?? null) !== null && session === this.session ? [{ kind: 'started' }] : [];
430
669
  }
431
670
  if (message.params?.update?.sessionUpdate === 'turn_completed') {
432
- return session === this.session ? [{ kind: 'ended' }] : [];
671
+ if (session !== this.session)
672
+ return [];
673
+ return [...this.spent(message.params.update.usage), { kind: 'ended', stop: null }];
433
674
  }
434
675
  if (message.method === '_x.ai/models/update') {
435
676
  this.offered(message.params);
@@ -437,6 +678,20 @@ class GrokReader extends Reader {
437
678
  }
438
679
  return super.read(message);
439
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
+ }
440
695
  offered(models) {
441
696
  this.models = models.availableModels ?? this.models;
442
697
  this.model = models.currentModelId ?? this.model;
@@ -448,11 +703,18 @@ class GrokReader extends Reader {
448
703
  const update = message.params?.update;
449
704
  switch (message.method) {
450
705
  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}` }];
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') : [];
456
718
  case '_x.ai/session_notification':
457
719
  return this.notification(update);
458
720
  default:
@@ -467,49 +729,55 @@ class GrokReader extends Reader {
467
729
  if (window === null)
468
730
  return [];
469
731
  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 }];
732
+ return [{ kind: 'state', state: { context: { used, window, breakdown: [] } } }];
471
733
  }
472
734
  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);
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);
478
739
  return [];
479
740
  }
480
741
  case 'subagent_finished': {
481
- const call = this.children.get(update.child_session_id);
482
- return typeof call === 'string' ? this.finish(call, update.output ?? null) : [];
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);
483
748
  }
484
749
  case 'auto_compact_completed':
485
- return [{ kind: 'marker', marker: 'compaction', text: '' }];
750
+ return [{ kind: 'notice', notice: 'compaction', text: '' }];
486
751
  case 'model_auto_switched':
487
752
  this.model = update.new_model_id;
488
- return [{ kind: 'marker', marker: 'model', text: update.new_model_id }];
753
+ return [{ kind: 'notice', notice: 'model', text: update.new_model_id }];
489
754
  case 'retry_state':
490
- return [{ kind: 'marker', marker: 'retry', text: update.message ?? update.reason ?? update.error_type ?? '' }];
755
+ return [{ kind: 'notice', notice: 'retry', text: update.message ?? update.reason ?? update.error_type ?? '' }];
491
756
  default:
492
757
  return [];
493
758
  }
494
759
  }
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;
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';
507
769
  if (tool.name === 'run_terminal_command')
508
- return decidedByLine(call.rawInput?.command, true);
509
- return 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';
510
775
  }
511
- subagentFinished(_call) {
512
- return [];
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);
513
781
  }
514
782
  }
515
783
  export function answeredFailure(answer) {