@phren/cli 0.3.72 → 0.3.74

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 (81) hide show
  1. package/dist/bridge/agent-hooks.js +11 -1
  2. package/dist/bridge/browser-env.d.ts +1 -1
  3. package/dist/bridge/browser-env.js +34 -10
  4. package/dist/bridge/browser-watch.d.ts +12 -0
  5. package/dist/bridge/browser-watch.js +83 -0
  6. package/dist/bridge/claude-account-setup.js +3 -1
  7. package/dist/bridge/claude-accounts.d.ts +5 -1
  8. package/dist/bridge/claude-accounts.js +36 -6
  9. package/dist/bridge/claude-question-dialog.d.ts +2 -3
  10. package/dist/bridge/claude-question-dialog.js +129 -46
  11. package/dist/bridge/codex-servers.d.ts +2 -0
  12. package/dist/bridge/codex-servers.js +1 -1
  13. package/dist/bridge/command.js +24 -5
  14. package/dist/bridge/conductor-sets.d.ts +2 -1
  15. package/dist/bridge/conductor-sets.js +3 -2
  16. package/dist/bridge/dialog-observation.d.ts +4 -0
  17. package/dist/bridge/dialog-observation.js +24 -0
  18. package/dist/bridge/dispatch-clone.d.ts +33 -0
  19. package/dist/bridge/dispatch-clone.js +176 -0
  20. package/dist/bridge/dispatch-command.d.ts +14 -0
  21. package/dist/bridge/dispatch-command.js +98 -13
  22. package/dist/bridge/dispatch-idempotency.d.ts +85 -0
  23. package/dist/bridge/dispatch-idempotency.js +235 -0
  24. package/dist/bridge/dispatch-returns.d.ts +6 -0
  25. package/dist/bridge/dispatch-returns.js +131 -1
  26. package/dist/bridge/dispatch-wait.d.ts +32 -0
  27. package/dist/bridge/dispatch-wait.js +177 -0
  28. package/dist/bridge/dispatch.d.ts +68 -2
  29. package/dist/bridge/dispatch.js +839 -25
  30. package/dist/bridge/fanouts.js +20 -3
  31. package/dist/bridge/files.d.ts +1 -1
  32. package/dist/bridge/git-credential.d.ts +44 -0
  33. package/dist/bridge/git-credential.js +113 -0
  34. package/dist/bridge/git-host-auth.d.ts +9 -1
  35. package/dist/bridge/git-host-auth.js +18 -5
  36. package/dist/bridge/git-host-gitboy.js +8 -1
  37. package/dist/bridge/git-hosts.d.ts +12 -1
  38. package/dist/bridge/git-publish.js +3 -2
  39. package/dist/bridge/herdr.d.ts +4 -0
  40. package/dist/bridge/herdr.js +29 -3
  41. package/dist/bridge/install.d.ts +1 -1
  42. package/dist/bridge/install.js +8 -4
  43. package/dist/bridge/launch-worktree.d.ts +2 -0
  44. package/dist/bridge/launch-worktree.js +5 -1
  45. package/dist/bridge/pane-status.js +2 -19
  46. package/dist/bridge/protocol.d.ts +7 -0
  47. package/dist/bridge/schedule-watch.js +13 -2
  48. package/dist/bridge/server-launch.d.ts +2 -0
  49. package/dist/bridge/server-launch.js +251 -145
  50. package/dist/bridge/server-pane-routes.d.ts +1 -1
  51. package/dist/bridge/server-pane-routes.js +12 -9
  52. package/dist/bridge/server-routes.js +26 -8
  53. package/dist/bridge/server.js +12 -1
  54. package/dist/bridge/status-line-fast.d.ts +9 -0
  55. package/dist/bridge/status-line-fast.js +56 -0
  56. package/dist/bridge/terminal-herdr.d.ts +5 -1
  57. package/dist/bridge/terminal-herdr.js +65 -1
  58. package/dist/bridge/terminal-tmux.d.ts +6 -0
  59. package/dist/bridge/terminal-tmux.js +38 -11
  60. package/dist/bridge/terminal.d.ts +5 -1
  61. package/dist/bridge/transcript-claude.d.ts +7 -0
  62. package/dist/bridge/transcript-claude.js +227 -112
  63. package/dist/bridge/transcript-preview.d.ts +2 -1
  64. package/dist/bridge/transcript-preview.js +85 -3
  65. package/dist/bridge/transcripts.js +17 -11
  66. package/dist/bridge/turn-records.js +16 -4
  67. package/dist/bridge/usage.d.ts +7 -1
  68. package/dist/bridge/usage.js +47 -31
  69. package/dist/bridge/worker-close.d.ts +15 -0
  70. package/dist/bridge/worker-close.js +304 -3
  71. package/dist/bridge/worker-identity.d.ts +51 -0
  72. package/dist/bridge/worker-identity.js +289 -0
  73. package/dist/bridge-hook.mjs +22097 -19129
  74. package/dist/cli/browser-hint.d.ts +2 -0
  75. package/dist/cli/browser-hint.js +21 -0
  76. package/dist/cli/hooks-context.d.ts +2 -2
  77. package/dist/cli/hooks-context.js +3 -3
  78. package/dist/cli/hooks.js +20 -11
  79. package/dist/cli-registry.js +5 -3
  80. package/dist/modules/registry.js +1 -1
  81. package/package.json +3 -3
@@ -55,6 +55,23 @@ async function claudeChildModel(file) {
55
55
  * too: Git routes must fail explicitly when a checkout disappears, never
56
56
  * substitute the parent repository. */
57
57
  export async function claudeChildCheckout(file) {
58
+ // A child's first rows never change and its meta file rarely does; the tree asks for every child each time.
59
+ const [child, metaInfo] = await Promise.all([stat(file), stat(file.slice(0, -".jsonl".length) + ".meta.json").catch(() => undefined)]);
60
+ const stamp = `${child.dev}:${child.ino}:${metaInfo ? `${metaInfo.ino}:${metaInfo.size}:${metaInfo.mtimeMs}` : "-"}`;
61
+ const cached = claudeCheckoutCache.get(file);
62
+ if (cached?.stamp === stamp)
63
+ return cached.checkout;
64
+ const checkout = await readClaudeChildCheckout(file);
65
+ if (checkout.cwd) {
66
+ claudeCheckoutCache.delete(file);
67
+ claudeCheckoutCache.set(file, { stamp, checkout });
68
+ while (claudeCheckoutCache.size > 1024)
69
+ claudeCheckoutCache.delete(claudeCheckoutCache.keys().next().value);
70
+ }
71
+ return checkout;
72
+ }
73
+ const claudeCheckoutCache = new Map();
74
+ async function readClaudeChildCheckout(file) {
58
75
  const meta = await readFile(file.slice(0, -".jsonl".length) + ".meta.json", "utf8").then(v => object(JSON.parse(v))).catch(() => ({}));
59
76
  let cwd = typeof meta.worktreePath === "string" && path.isAbsolute(meta.worktreePath) ? meta.worktreePath : undefined;
60
77
  let branch = typeof meta.worktreeBranch === "string" && meta.worktreeBranch ? meta.worktreeBranch.slice(0, 200) : undefined;
@@ -108,7 +125,8 @@ export async function claudeChildAgents(file, session) {
108
125
  const rows = cached?.signature.startsWith(`${parent}:`) && cached.rows ? cached.rows : await claudeParentRows(file);
109
126
  return claudeChildRelations(file, session, signature, rows, stop);
110
127
  }
111
- async function claudeParentRows(file) {
128
+ const claudeParentParses = new Map();
129
+ function newParentParse(identity) {
112
130
  const launches = new Map();
113
131
  const stops = new Map();
114
132
  // A background skill (`/code-review` run as `@code-review`) is announced in
@@ -125,122 +143,170 @@ async function claudeParentRows(file) {
125
143
  // Agent calls by tool_use id: the parent waits on a foreground one until its tool_result; a background one
126
144
  // waits here for its launch result, which names its agent (or, when it names none, stays here).
127
145
  const foreground = new Map(), background = new Map(), unidentified = new Map();
128
- const lines = createInterface({ input: createReadStream(file, { encoding: "utf8" }), crlfDelay: Infinity });
129
- for await (const line of lines) {
130
- try {
131
- const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
132
- const blocks = objects(object(raw.message).content);
133
- const status = String(result.status ?? "");
134
- // The agent id under the key Claude Code uses, or the one an older or newer version does.
135
- const agentId = String([result.agentId, result.agent_id, result.taskType === "local_workflow" ? undefined : result.taskId, result.task_id]
136
- .find(value => typeof value === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value)) ?? "");
137
- // A launch that runs on: async by its own word, or by any status that is not an end.
138
- const launched = result.taskType !== "local_workflow" && !/^(completed|failed|error|killed|cancell?ed|stopped|done)$/.test(status)
139
- && (result.isAsync === true || /^(async_)?(launched|running|started|queued|pending|spawned)$/.test(status));
140
- const resultCall = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
141
- if (launched && agentId && resultCall) {
142
- launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId: resultCall, state: "running" });
143
- }
144
- else if (launched && resultCall && !agentId && background.has(resultCall)) {
145
- const call = background.get(resultCall);
146
- // Timed from the call itself: its agent can start before the launch result is stamped.
147
- unidentified.set(resultCall, { path: String(result.description || call?.path || "Agent").slice(0, 200), callId: resultCall, prompt: call?.prompt ?? "",
148
- ...(call?.at ? { at: call.at } : typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) });
149
- }
150
- // SendMessage to a finished agent resumes it until its next final notification.
151
- const resumed = typeof result.resumedAgentId === "string" ? launches.get(result.resumedAgentId) : undefined;
152
- if (resumed && typeof result.message === "string" && /^Resuming agent\b/i.test(result.message)) {
153
- resumed.state = "running";
154
- if (typeof raw.timestamp === "string")
155
- resumed.resumedAt = raw.timestamp;
156
- }
157
- if (result.taskType === "local_workflow" && status === "async_launched" && typeof result.taskId === "string"
158
- && typeof result.runId === "string" && /^wf_[A-Za-z0-9-]{1,64}$/.test(result.runId)) {
159
- const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
160
- workflows.set(result.taskId, { runId: result.runId, name: String(result.workflowName || "Workflow").slice(0, 200), callId, state: "running" });
146
+ return { identity, offset: 0, stops, background, rows: { launches, skills, workflows, teammates, foreground, unidentified } };
147
+ }
148
+ async function claudeParentRows(file) {
149
+ // Reads of one file take turns, so no row is applied twice.
150
+ while (claudeParentParses.get(file)?.reading)
151
+ await claudeParentParses.get(file).reading;
152
+ const metadata = await stat(file), identity = `${metadata.dev}:${metadata.ino}`;
153
+ let parse = claudeParentParses.get(file);
154
+ if (parse?.reading)
155
+ return claudeParentRows(file);
156
+ // Replaced or rewritten (shorter than what was read): read from the start.
157
+ if (!parse || parse.identity !== identity || metadata.size < parse.offset)
158
+ parse = newParentParse(identity);
159
+ claudeParentParses.delete(file);
160
+ claudeParentParses.set(file, parse);
161
+ while (claudeParentParses.size > 64)
162
+ claudeParentParses.delete(claudeParentParses.keys().next().value);
163
+ if (metadata.size > parse.offset) {
164
+ const reading = readParentRows(file, parse, metadata.size);
165
+ parse.reading = reading.catch(() => undefined).finally(() => { parse.reading = undefined; });
166
+ await reading;
167
+ }
168
+ return copyRows(parse.rows);
169
+ }
170
+ /** Applies every whole row in [offset, size). A last row with no newline yet counts once it parses; a
171
+ * part-written one is left for the next read. */
172
+ async function readParentRows(file, parse, size) {
173
+ let carry = Buffer.alloc(0);
174
+ for await (const chunk of createReadStream(file, { start: parse.offset, end: size - 1 })) {
175
+ let data = carry.length ? Buffer.concat([carry, chunk]) : chunk, from = 0;
176
+ for (let at = data.indexOf(10); at !== -1; at = data.indexOf(10, from)) {
177
+ const end = at > from && data[at - 1] === 13 ? at - 1 : at;
178
+ applyParentRow(parse, data.toString("utf8", from, end));
179
+ parse.offset += at + 1 - from;
180
+ from = at + 1;
181
+ }
182
+ carry = data.subarray(from);
183
+ }
184
+ if (!carry.length)
185
+ return;
186
+ const line = carry.toString("utf8");
187
+ try {
188
+ JSON.parse(line);
189
+ }
190
+ catch {
191
+ return;
192
+ }
193
+ applyParentRow(parse, line);
194
+ parse.offset += carry.length;
195
+ }
196
+ function applyParentRow(parse, line) {
197
+ const { stops, background } = parse, { launches, skills, workflows, teammates, foreground, unidentified } = parse.rows;
198
+ try {
199
+ const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
200
+ const blocks = objects(object(raw.message).content);
201
+ const status = String(result.status ?? "");
202
+ // The agent id under the key Claude Code uses, or the one an older or newer version does.
203
+ const agentId = String([result.agentId, result.agent_id, result.taskType === "local_workflow" ? undefined : result.taskId, result.task_id]
204
+ .find(value => typeof value === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value)) ?? "");
205
+ // A launch that runs on: async by its own word, or by any status that is not an end.
206
+ const launched = result.taskType !== "local_workflow" && !/^(completed|failed|error|killed|cancell?ed|stopped|done)$/.test(status)
207
+ && (result.isAsync === true || /^(async_)?(launched|running|started|queued|pending|spawned)$/.test(status));
208
+ const resultCall = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
209
+ if (launched && agentId && resultCall) {
210
+ launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId: resultCall, state: "running" });
211
+ }
212
+ else if (launched && resultCall && !agentId && background.has(resultCall)) {
213
+ const call = background.get(resultCall);
214
+ // Timed from the call itself: its agent can start before the launch result is stamped.
215
+ unidentified.set(resultCall, { path: String(result.description || call?.path || "Agent").slice(0, 200), callId: resultCall, prompt: call?.prompt ?? "",
216
+ ...(call?.at ? { at: call.at } : typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) });
217
+ }
218
+ // SendMessage to a finished agent resumes it until its next final notification.
219
+ const resumed = typeof result.resumedAgentId === "string" ? launches.get(result.resumedAgentId) : undefined;
220
+ if (resumed && typeof result.message === "string" && /^Resuming agent\b/i.test(result.message)) {
221
+ resumed.state = "running";
222
+ if (typeof raw.timestamp === "string")
223
+ resumed.resumedAt = raw.timestamp;
224
+ }
225
+ if (result.taskType === "local_workflow" && status === "async_launched" && typeof result.taskId === "string"
226
+ && typeof result.runId === "string" && /^wf_[A-Za-z0-9-]{1,64}$/.test(result.runId)) {
227
+ const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
228
+ workflows.set(result.taskId, { runId: result.runId, name: String(result.workflowName || "Workflow").slice(0, 200), callId, state: "running" });
229
+ }
230
+ if (raw.type === "system" && typeof raw.content === "string" && raw.content.includes("<forked-skill-launch>")) {
231
+ const launch = object(JSON.parse(/<forked-skill-launch>([\s\S]*?)<\/forked-skill-launch>/.exec(raw.content)?.[1] ?? "{}"));
232
+ const id = String(launch.agentId ?? "");
233
+ if (/^[A-Za-z0-9._-]{1,128}$/.test(id)) {
234
+ launches.set(id, { path: String(launch.description || (launch.skillName ? `/${launch.skillName}` : "Skill")).slice(0, 200), callId: `skill:${id}`, state: "running" });
235
+ skills.add(id);
161
236
  }
162
- if (raw.type === "system" && typeof raw.content === "string" && raw.content.includes("<forked-skill-launch>")) {
163
- const launch = object(JSON.parse(/<forked-skill-launch>([\s\S]*?)<\/forked-skill-launch>/.exec(raw.content)?.[1] ?? "{}"));
164
- const id = String(launch.agentId ?? "");
165
- if (/^[A-Za-z0-9._-]{1,128}$/.test(id)) {
166
- launches.set(id, { path: String(launch.description || (launch.skillName ? `/${launch.skillName}` : "Skill")).slice(0, 200), callId: `skill:${id}`, state: "running" });
167
- skills.add(id);
237
+ }
238
+ if (raw.type === "assistant") {
239
+ for (const block of blocks) {
240
+ if (block.type !== "tool_use")
241
+ continue;
242
+ if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
243
+ stops.set(block.id, String(object(block.input).task_id));
168
244
  }
169
- }
170
- if (raw.type === "assistant") {
171
- for (const block of blocks) {
172
- if (block.type !== "tool_use")
173
- continue;
174
- if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
175
- stops.set(block.id, String(object(block.input).task_id));
176
- }
177
- if (block.name !== "Agent" && block.name !== "Task")
178
- continue;
179
- const input = object(block.input), name = String(input.name ?? "");
180
- if (typeof block.id !== "string")
181
- continue;
182
- if (block.name === "Agent" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
183
- teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
184
- continue;
185
- }
186
- const call = { path: String(input.description || input.subagent_type || "Agent").slice(0, 200), callId: block.id.slice(0, 200),
187
- prompt: typeof input.prompt === "string" ? input.prompt : "", ...(typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) };
188
- (input.run_in_background === true ? background : foreground).set(call.callId, call);
245
+ if (block.name !== "Agent" && block.name !== "Task")
246
+ continue;
247
+ const input = object(block.input), name = String(input.name ?? "");
248
+ if (typeof block.id !== "string")
249
+ continue;
250
+ if (block.name === "Agent" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
251
+ teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
252
+ continue;
189
253
  }
254
+ const call = { path: String(input.description || input.subagent_type || "Agent").slice(0, 200), callId: block.id.slice(0, 200),
255
+ prompt: typeof input.prompt === "string" ? input.prompt : "", ...(typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) };
256
+ (input.run_in_background === true ? background : foreground).set(call.callId, call);
190
257
  }
191
- // A call's result ends the parent's wait on it: the foreground agent finished, failed or was interrupted.
192
- if (raw.type === "user")
193
- for (const block of blocks) {
194
- if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
195
- continue;
196
- foreground.delete(block.tool_use_id);
197
- background.delete(block.tool_use_id);
198
- }
199
- // A stop request alone proves nothing. Its successful, matching result
200
- // ends the child even when no later task notification is recorded.
201
- if (raw.type === "user") {
202
- for (const block of blocks) {
203
- if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
204
- continue;
205
- const task = stops.get(block.tool_use_id);
206
- if (!task)
207
- continue;
208
- stops.delete(block.tool_use_id);
209
- const previous = launches.get(task) ?? workflows.get(task);
210
- if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
211
- && /^Successfully stopped task\b/i.test(result.message))
212
- previous.state = "completed";
213
- }
258
+ }
259
+ // A call's result ends the parent's wait on it: the foreground agent finished, failed or was interrupted.
260
+ if (raw.type === "user")
261
+ for (const block of blocks) {
262
+ if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
263
+ continue;
264
+ foreground.delete(block.tool_use_id);
265
+ background.delete(block.tool_use_id);
214
266
  }
215
- const content = typeof raw.content === "string" ? raw.content : typeof object(raw.message).content === "string" ? String(object(raw.message).content) : "";
216
- const attachment = object(raw.attachment);
217
- const notices = [raw.type === "queue-operation" || raw.type === "user" ? content : "",
218
- ...(raw.type === "user" ? blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)) : []),
219
- raw.type === "attachment" && attachment.type === "queued_command" && attachment.commandMode === "task-notification" && typeof attachment.prompt === "string" ? attachment.prompt : ""];
220
- for (const notice of notices) {
221
- for (const match of notice.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
222
- const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(match[1])?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(match[1])?.[1].trim();
223
- // Terminal notifications end only the child named in that envelope.
224
- const previous = child && (launches.get(child) ?? workflows.get(child));
225
- if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? ""))
226
- previous.state = "completed";
227
- }
267
+ // A stop request alone proves nothing. Its successful, matching result
268
+ // ends the child even when no later task notification is recorded.
269
+ if (raw.type === "user") {
270
+ for (const block of blocks) {
271
+ if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
272
+ continue;
273
+ const task = stops.get(block.tool_use_id);
274
+ if (!task)
275
+ continue;
276
+ stops.delete(block.tool_use_id);
277
+ const previous = launches.get(task) ?? workflows.get(task);
278
+ if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
279
+ && /^Successfully stopped task\b/i.test(result.message))
280
+ previous.state = "completed";
228
281
  }
229
- // One row can carry several messages (a shutdown approval and the
230
- // system's termination notice together). Idle, an approved shutdown
231
- // and termination end a teammate; anything else it says wakes it.
232
- for (const match of content.includes("<teammate-message") ? content.matchAll(/<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"[^>]*>([\s\S]*?)<\/teammate-message>/g) : []) {
233
- const [, from, body] = match;
234
- const type = /"type":"([a-z_]+)"/.exec(body)?.[1];
235
- const ended = from === "system" && type === "teammate_terminated" ? /"message":"([A-Za-z0-9][A-Za-z0-9_-]{0,63}) has shut down/.exec(body)?.[1] : undefined;
236
- const teammate = teammates.get(ended ?? from);
237
- if (teammate)
238
- teammate.state = ended || type === "idle_notification" || type === "shutdown_approved" ? "completed" : "running";
282
+ }
283
+ const content = typeof raw.content === "string" ? raw.content : typeof object(raw.message).content === "string" ? String(object(raw.message).content) : "";
284
+ const attachment = object(raw.attachment);
285
+ const notices = [raw.type === "queue-operation" || raw.type === "user" ? content : "",
286
+ ...(raw.type === "user" ? blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)) : []),
287
+ raw.type === "attachment" && attachment.type === "queued_command" && attachment.commandMode === "task-notification" && typeof attachment.prompt === "string" ? attachment.prompt : ""];
288
+ for (const notice of notices) {
289
+ for (const match of notice.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
290
+ const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(match[1])?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(match[1])?.[1].trim();
291
+ // Terminal notifications end only the child named in that envelope.
292
+ const previous = child && (launches.get(child) ?? workflows.get(child));
293
+ if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? ""))
294
+ previous.state = "completed";
239
295
  }
240
296
  }
241
- catch { /* Ignore unrelated/malformed rows. */ }
297
+ // One row can carry several messages (a shutdown approval and the
298
+ // system's termination notice together). Idle, an approved shutdown
299
+ // and termination end a teammate; anything else it says wakes it.
300
+ for (const match of content.includes("<teammate-message") ? content.matchAll(/<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"[^>]*>([\s\S]*?)<\/teammate-message>/g) : []) {
301
+ const [, from, body] = match;
302
+ const type = /"type":"([a-z_]+)"/.exec(body)?.[1];
303
+ const ended = from === "system" && type === "teammate_terminated" ? /"message":"([A-Za-z0-9][A-Za-z0-9_-]{0,63}) has shut down/.exec(body)?.[1] : undefined;
304
+ const teammate = teammates.get(ended ?? from);
305
+ if (teammate)
306
+ teammate.state = ended || type === "idle_notification" || type === "shutdown_approved" ? "completed" : "running";
307
+ }
242
308
  }
243
- return { launches, skills, workflows, teammates, foreground, unidentified };
309
+ catch { /* Ignore unrelated/malformed rows. */ }
244
310
  }
245
311
  async function claudeChildRelations(file, session, signature, rows, stop) {
246
312
  // Kept as the parent wrote them: what follows marks finished children.
@@ -510,24 +576,38 @@ async function claudeWorkflowAgents(root, session, workflow, quietEnds = true, n
510
576
  }
511
577
  return relations;
512
578
  }
579
+ /** Answers from a child's first row, which Claude Code never rewrites: kept per file while it is the same file. */
580
+ const claudeBelongsCache = new Map();
513
581
  async function claudeChildBelongsTo(file, parent, agentId) {
514
- let bytes = Buffer.alloc(0);
582
+ const info = await stat(file), identity = `${info.dev}:${info.ino}`, key = `${file}\0${parent}\0${agentId}`;
583
+ const cached = claudeBelongsCache.get(key);
584
+ if (cached?.identity === identity)
585
+ return cached.belongs;
586
+ let bytes = Buffer.alloc(0), whole = false;
515
587
  for await (const chunk of createReadStream(file, { start: 0, end: 1_048_575 })) {
516
588
  bytes = Buffer.concat([bytes, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
517
589
  const newline = bytes.indexOf(0x0a);
518
590
  if (newline >= 0) {
519
591
  bytes = bytes.subarray(0, newline);
592
+ whole = true;
520
593
  break;
521
594
  }
522
595
  }
596
+ let belongs = false;
523
597
  try {
524
598
  const raw = object(JSON.parse(bytes.toString("utf8")));
525
- return (raw.isSidechain === true && raw.sessionId === parent && raw.agentId === agentId)
599
+ belongs = (raw.isSidechain === true && raw.sessionId === parent && raw.agentId === agentId)
526
600
  || (raw.type === "fork-context-ref" && raw.parentSessionId === parent && raw.agentId === agentId);
527
601
  }
528
- catch {
529
- return false;
602
+ catch { /* Not a row yet, or not one of this parent's. */ }
603
+ // A first row still being written is read again next time.
604
+ if (whole) {
605
+ claudeBelongsCache.delete(key);
606
+ claudeBelongsCache.set(key, { identity, belongs });
607
+ while (claudeBelongsCache.size > 1024)
608
+ claudeBelongsCache.delete(claudeBelongsCache.keys().next().value);
530
609
  }
610
+ return belongs;
531
611
  }
532
612
  // `effort` rides on each assistant row (Claude Code 2.1): with `message.model`
533
613
  // it is what the phone's model chip shows as in effect. `permissionMode` on a
@@ -631,6 +711,36 @@ export function skillBody(raw) {
631
711
  const QUEUED_IMAGE_LABEL = /\[Image #\d+\]/;
632
712
  const QUEUED_IMAGE_LABELS = /\[Image #\d+\]/g;
633
713
  const ATTACHED_FILES_FOOTER = /Attached files on this computer:\s*$/;
714
+ /** How much of one agent's message crosses: the terminal folds it too. */
715
+ const PEER_MESSAGE_LIMIT = 32_768;
716
+ const HANDBACK_FRAME = /^\[Subagent hand-back\][\s\S]*?The report follows:\n/;
717
+ /** A message another agent sent this session (a teammate, a subagent's
718
+ * hand-back or another Claude session), which Claude Code delivers as a hidden
719
+ * user row when the agent is idle, or a queued_command attachment mid-turn,
720
+ * both naming it with `origin.kind: "peer"`. The terminal shows it as
721
+ * "Message from @name"; only the sender's name and the words cross, never the
722
+ * envelope, socket path or ids. */
723
+ export function peerMessage(raw, includeSidechain = false) {
724
+ if (raw.isSidechain && !includeSidechain)
725
+ return undefined;
726
+ const attachment = object(raw.attachment);
727
+ const origin = raw.type === "user" ? object(raw.origin)
728
+ : raw.type === "attachment" && attachment.type === "queued_command" ? object(attachment.origin) : {};
729
+ if (origin.kind !== "peer" || typeof origin.body !== "string")
730
+ return undefined;
731
+ const handback = origin.handback === true;
732
+ // A hand-back's body opens with the harness's framing and indents the
733
+ // report two spaces; the report itself is carried alongside when it fits.
734
+ const text = handback && typeof origin.handbackReportText === "string" ? origin.handbackReportText
735
+ : handback && HANDBACK_FRAME.test(origin.body) ? origin.body.replace(HANDBACK_FRAME, "").replace(/^ {2}/gm, "")
736
+ : origin.body;
737
+ if (!text.trim())
738
+ return undefined;
739
+ const name = typeof origin.name === "string" ? origin.name.replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim().slice(0, 80) : "";
740
+ return { type: "phren_peer_message", timestamp: raw.timestamp, ...(typeof raw.uuid === "string" ? { uuid: raw.uuid } : {}),
741
+ name: name || "agent", ...(handback ? { handback: true } : {}),
742
+ text: text.length > PEER_MESSAGE_LIMIT ? text.slice(0, PEER_MESSAGE_LIMIT) + "\n…" : text };
743
+ }
634
744
  /** A phren UserPromptSubmit injection, as `{ type: "phren_hook_context",
635
745
  * parentUuid, content }`, or undefined for any other row. */
636
746
  export function phrenHookContext(raw, includeSidechain = false) {
@@ -641,6 +751,9 @@ export function phrenHookContext(raw, includeSidechain = false) {
641
751
  // its hook output. Only whether it was a background notification crosses,
642
752
  // so the phone can leave a notification's injection out.
643
753
  if (attachment.type === "queued_command") {
754
+ const peer = peerMessage(raw, includeSidechain);
755
+ if (peer)
756
+ return peer;
644
757
  return { type: "phren_turn_input", timestamp: raw.timestamp, notification: attachment.commandMode === "task-notification" };
645
758
  }
646
759
  if (attachment.type !== "hook_success" || attachment.hookEvent !== "UserPromptSubmit")
@@ -797,6 +910,8 @@ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
797
910
  // origin says "task-notification" (sometimes wrapped in a system reminder).
798
911
  // It is a notice, not a prompt: normalize only its public envelope and never
799
912
  // let established notification provenance fall through as ordinary user text.
913
+ if (raw.type === "user" && object(raw.origin).kind === "peer")
914
+ return peerMessage(raw, includeSidechain);
800
915
  if (raw.type === "user") {
801
916
  const content = object(raw.message).content;
802
917
  const text = typeof content === "string" ? content
@@ -116,7 +116,8 @@ export declare class TranscriptPreviewStream {
116
116
  constructor(target: Target, pane?: () => Promise<string>, delta?: (file?: string) => Promise<TranscriptPreview | null>);
117
117
  observe(entries: Entry[], reset?: boolean): void;
118
118
  /** Whether pane text is a reply block that already landed: its words agree with the block's as far as
119
- * both go (drawsLanded), so a block still drawing the same opening as a landed one waits until the two part. */
119
+ * both go (drawsLanded), or a long paragraph is still on screen after the block's opening scrolled away.
120
+ * A block still drawing the same opening as a landed one waits until the two part. */
120
121
  private hasLanded;
121
122
  /** Seed a reconnect from a classified owner row in the verified transcript. */
122
123
  seedTurn(turnStartedAt: string, prompt: string): void;
@@ -17,7 +17,9 @@ const MAX_PREVIEW_BYTES = MAX_TEXT * 6 + 1_024;
17
17
  * unless `inTurn` (the turn already landed an entry, so the screen is its own
18
18
  * output and the prompt scrolled off above it). */
19
19
  export function claudePanePreview(rendered, prompt, previous = "", inTurn = false) {
20
- const screen = rendered.split("\n");
20
+ const screen = claudeReplyRegion(rendered.split("\n"));
21
+ if (!screen)
22
+ return "";
21
23
  const raw = screen.map(stripTerminal);
22
24
  // What the phone shows: the line with Claude's bold as Markdown. Detection
23
25
  // below reads the plain line.
@@ -323,6 +325,84 @@ export function readPreviewPane(target) {
323
325
  }
324
326
  // An SGR sequence (captured) or any other control sequence stripTerminal removes.
325
327
  const PANE_CONTROL = /\x1b\[([0-?]*)[ -/]*([@-~])|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\r/g;
328
+ /** Separate a styled sidebar before classifying rows or measuring wraps. Claude's diff
329
+ * panel has no enclosing box: bold paths and dim/italic instructions start at a fixed
330
+ * column, with padding between them and the reply. Two rows establish that column;
331
+ * crop every row there, including unstyled wraps and rows with no intervening space.
332
+ * An isolated region cannot establish a safe boundary, so that read stays silent. */
333
+ function claudeReplyRegion(screen) {
334
+ const columns = new Map();
335
+ const rows = screen.map(line => {
336
+ const styles = new Map();
337
+ const runs = [];
338
+ let plain = "", last = 0, inkStyle = "";
339
+ const take = (end) => {
340
+ const text = line.slice(last, end);
341
+ if (!text)
342
+ return;
343
+ runs.push({ raw: last, plain: plain.length, text });
344
+ if (text.trim()) {
345
+ const style = [...styles].sort(([a], [b]) => a - b).map(([key, value]) => `${key}:${value}`).join(";");
346
+ const before = plain + text.slice(0, text.length - text.trimStart().length);
347
+ if (before.length >= 20 && / {4,}$/.test(before) && style && style !== inkStyle) {
348
+ columns.set(before.length, (columns.get(before.length) ?? 0) + 1);
349
+ }
350
+ inkStyle = style;
351
+ }
352
+ plain += text;
353
+ };
354
+ for (const match of line.matchAll(PANE_CONTROL)) {
355
+ take(match.index);
356
+ last = match.index + match[0].length;
357
+ if (match[2] !== "m")
358
+ continue;
359
+ const params = (match[1] || "0").split(/[;:]/).map(value => Number(value || 0));
360
+ for (let i = 0; i < params.length; i++) {
361
+ const code = params[i];
362
+ if (code === 0)
363
+ styles.clear();
364
+ else if (code === 22) {
365
+ styles.delete(1);
366
+ styles.delete(2);
367
+ }
368
+ else if ([23, 24, 27, 29].includes(code))
369
+ styles.delete(code - 20);
370
+ else if (code === 39 || code === 49)
371
+ styles.delete(code - 1);
372
+ else if (code === 38 || code === 48 || code === 58) {
373
+ const size = params[i + 1] === 5 ? 2 : params[i + 1] === 2 ? 4 : 0;
374
+ styles.set(code, params.slice(i + 1, i + size + 1).join(":"));
375
+ i += size;
376
+ }
377
+ else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97))
378
+ styles.set(38, String(code));
379
+ else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))
380
+ styles.set(48, String(code));
381
+ else
382
+ styles.set(code, "");
383
+ }
384
+ }
385
+ take(line.length);
386
+ return { line, runs };
387
+ });
388
+ // Without usable styles/padding, a known diff-panel notice is still evidence
389
+ // that this read cannot safely be interpreted as a single text region.
390
+ const panelNotice = screen.some(line => /New file not yet staged\.|Run `?git add :\/.*to see line counts\./.test(stripTerminal(line)));
391
+ if (!columns.size)
392
+ return panelNotice ? undefined : screen;
393
+ const repeated = [...columns].filter(([, count]) => count >= 2).map(([column]) => column);
394
+ if (!repeated.length)
395
+ return undefined;
396
+ const column = Math.min(...repeated);
397
+ // Offsets above count UTF-16 units. Wide glyphs and combining marks make that
398
+ // an unsafe terminal column; do not guess a crop in those reads.
399
+ if (rows.some(({ line }) => /[\t\p{Mark}\u1100-\u11ff\u2e80-\ua4cf\uac00-\ud7a3\ud800-\udfff\uf900-\ufaff\ufe00-\ufe6f\uff00-\uffef]/u.test(stripTerminal(line).slice(0, column))))
400
+ return undefined;
401
+ return rows.map(({ line, runs }) => {
402
+ const run = runs.find(run => run.plain + run.text.length > column);
403
+ return run ? line.slice(0, run.raw + Math.max(0, column - run.plain)) + "\x1b[0m" : line;
404
+ });
405
+ }
326
406
  /**
327
407
  * One pane line as Markdown bold. Claude draws a reply's **bold** with SGR 1
328
408
  * and drops the asterisks, so a plain read loses it and the phone's preview
@@ -654,12 +734,14 @@ export class TranscriptPreviewStream {
654
734
  }
655
735
  }
656
736
  /** Whether pane text is a reply block that already landed: its words agree with the block's as far as
657
- * both go (drawsLanded), so a block still drawing the same opening as a landed one waits until the two part. */
737
+ * both go (drawsLanded), or a long paragraph is still on screen after the block's opening scrolled away.
738
+ * A block still drawing the same opening as a landed one waits until the two part. */
658
739
  hasLanded(text) {
659
740
  const words = previewWords(text);
660
741
  return !words || [...this.landedTexts].some(landed =>
661
742
  // A short block ("Let me check.") is not a longer one that starts with its words.
662
- !(landed.length < LANDED_MATCH_CHARS && words.length > landed.length) && drawsLanded(words, landed));
743
+ (words.length >= LANDED_MATCH_CHARS && landed.includes(words))
744
+ || !(landed.length < LANDED_MATCH_CHARS && words.length > landed.length) && drawsLanded(words, landed));
663
745
  }
664
746
  /** Seed a reconnect from a classified owner row in the verified transcript. */
665
747
  seedTurn(turnStartedAt, prompt) {
@@ -1,5 +1,6 @@
1
1
  import { claudeQuestionResolutions, projectClaudeQuestionResolutions } from "./claude-question-lifecycle.js";
2
- import { readdir, realpath, lstat } from "node:fs/promises";
2
+ import { readdir, realpath } from "node:fs/promises";
3
+ import { lstatSync } from "node:fs";
3
4
  import { createHash } from "node:crypto";
4
5
  import { homedir } from "node:os";
5
6
  import { codexHome } from "../home-paths.js";
@@ -159,19 +160,24 @@ async function findPatternMatches(root, pattern) {
159
160
  const last = index === segments.length - 1;
160
161
  if (!segment.includes("*") && !segment.includes("?")) {
161
162
  const next = path.join(dir, segment);
163
+ // A Claude session is looked for in every project folder, and nearly all
164
+ // miss: a throwing lstat built an error for each one, the Hook's top cost.
165
+ let info;
162
166
  try {
163
- const info = await lstat(next);
164
- if (last) {
165
- // glob returns a symlink to a file here too; the caller's realpath
166
- // check is what rejects one pointing outside the provider folder.
167
- if (info.isFile() || info.isSymbolicLink())
168
- matches.push(next);
169
- }
170
- else if (info.isDirectory()) {
171
- await walk(next, index + 1);
172
- }
167
+ info = lstatSync(next, { throwIfNoEntry: false });
173
168
  }
174
169
  catch { /* no match */ }
170
+ if (!info)
171
+ return;
172
+ if (last) {
173
+ // glob returns a symlink to a file here too; the caller's realpath
174
+ // check is what rejects one pointing outside the provider folder.
175
+ if (info.isFile() || info.isSymbolicLink())
176
+ matches.push(next);
177
+ }
178
+ else if (info.isDirectory()) {
179
+ await walk(next, index + 1);
180
+ }
175
181
  return;
176
182
  }
177
183
  let entries;