@phren/cli 0.3.20 → 0.3.21

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 (53) hide show
  1. package/dist/bridge/agent-hooks.d.ts +22 -19
  2. package/dist/bridge/agent-hooks.js +49 -33
  3. package/dist/bridge/approval-summary.d.ts +4 -0
  4. package/dist/bridge/approval-summary.js +12 -1
  5. package/dist/bridge/code-note.d.ts +1 -0
  6. package/dist/bridge/code-note.js +2 -2
  7. package/dist/bridge/codex-binary.d.ts +5 -0
  8. package/dist/bridge/codex-binary.js +7 -0
  9. package/dist/bridge/dispatch-command.js +1 -1
  10. package/dist/bridge/dispatch-returns.d.ts +3 -2
  11. package/dist/bridge/dispatch-returns.js +27 -11
  12. package/dist/bridge/dispatch.d.ts +4 -0
  13. package/dist/bridge/dispatch.js +5 -3
  14. package/dist/bridge/folder-trust.d.ts +13 -3
  15. package/dist/bridge/folder-trust.js +42 -4
  16. package/dist/bridge/hand-off.js +2 -1
  17. package/dist/bridge/herdr.js +6 -5
  18. package/dist/bridge/launch-brief.d.ts +3 -1
  19. package/dist/bridge/launch-brief.js +3 -1
  20. package/dist/bridge/memory-store.d.ts +7 -0
  21. package/dist/bridge/memory-store.js +37 -1
  22. package/dist/bridge/schedule-format.d.ts +1 -1
  23. package/dist/bridge/schedule-format.js +1 -1
  24. package/dist/bridge/schedule-launch.js +5 -0
  25. package/dist/bridge/schedule-watch.d.ts +5 -2
  26. package/dist/bridge/schedule-watch.js +59 -20
  27. package/dist/bridge/server-launch.d.ts +6 -0
  28. package/dist/bridge/server-launch.js +59 -11
  29. package/dist/bridge/server-pane-routes.js +20 -13
  30. package/dist/bridge/server-routes.d.ts +1 -0
  31. package/dist/bridge/server-routes.js +1 -1
  32. package/dist/bridge/server-stream.js +12 -0
  33. package/dist/bridge/server.js +2 -2
  34. package/dist/bridge/session-activity.d.ts +6 -0
  35. package/dist/bridge/session-activity.js +16 -0
  36. package/dist/bridge/settings-switch.d.ts +7 -0
  37. package/dist/bridge/settings-switch.js +15 -0
  38. package/dist/bridge/speech-transcribe.d.ts +8 -1
  39. package/dist/bridge/speech-transcribe.js +18 -3
  40. package/dist/bridge/transcript-claude.js +39 -10
  41. package/dist/bridge/worker-close.js +3 -2
  42. package/dist/bridge/worker-unfinished.d.ts +8 -2
  43. package/dist/bridge/worker-unfinished.js +57 -24
  44. package/dist/bridge-hook.mjs +513 -277
  45. package/dist/cli-registry.js +1 -1
  46. package/dist/home-paths.d.ts +2 -0
  47. package/dist/home-paths.js +4 -0
  48. package/dist/modules/registry.js +1 -1
  49. package/dist/test-global-setup.js +2 -1
  50. package/dist/test-sandbox.d.ts +15 -0
  51. package/dist/test-sandbox.js +36 -0
  52. package/package.json +1 -1
  53. package/starter/global/skills/conductor/SKILL.md +2 -1
@@ -400,10 +400,11 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
400
400
  return { ok: true, deliveryUncertain: true };
401
401
  }
402
402
  }
403
+ const deliveryId = deliveryIdSchema.parse(data.deliveryId);
403
404
  let busy = String(pane.agent_status) === "working";
404
405
  let outcome = await promptWithStartupRetry(async () => {
405
406
  const refused = new AbortController();
406
- const expected = agentHooks.expectDelivery(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal);
407
+ const expected = agentHooks.expectDelivery(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal, deliveryId);
407
408
  await typing();
408
409
  try {
409
410
  await terminalProvider().prompt(target.server, target.pane, text);
@@ -434,19 +435,16 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
434
435
  else
435
436
  followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
436
437
  }
438
+ const refusedHere = () => new BridgeError(409, "The conversation in this pane changed; the message was not delivered. Reopen the chat and send it again.");
437
439
  if (outcome === "blocked")
438
- throw new BridgeError(409, "The conversation in this pane changed; the message was not delivered. Reopen the chat and send it again.");
440
+ throw refusedHere();
439
441
  // A bare slash command opens the agent's own menu; the phone may
440
442
  // walk it with keys for the next half minute. The command rides
441
443
  // along so a Codex /permissions walk can find its confirmation.
442
444
  if (/^\/[a-z][a-z0-9_-]*$/i.test(text.trim()))
443
445
  agentHooks.menuOpened(target, text.trim());
444
- const deliveryId = deliveryIdSchema.parse(data.deliveryId);
445
- if (outcome === "delivered") {
446
+ if (outcome === "delivered")
446
447
  result = { ok: true, delivered: true };
447
- if (deliveryId)
448
- agentHooks.trackDelivery(deliveryId, target, text, "delivered");
449
- }
450
448
  else if (outcome === "unsubmitted") {
451
449
  result = { ok: true, deliveryUncertain: true, unsubmitted: true };
452
450
  }
@@ -462,12 +460,21 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
462
460
  confirmed = !!current && current.terminal_id === pane.terminal_id && await paneIdentity(target.server, current, true) === target.session;
463
461
  }
464
462
  catch { /* No reliable post-delivery identity. */ }
465
- // Still this conversation, in the same terminal: the agent holds the
466
- // message (a busy turn queues it) and its hook has not submitted it
467
- // yet. Queued, not delivered; `/v1/prompt/status` says when it lands.
468
- if (confirmed && deliveryId)
469
- agentHooks.trackDelivery(deliveryId, target, text, "queued");
470
- result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : { queued: true }) };
463
+ // The hook can take it while the identity probe runs; its answer,
464
+ // keyed by the delivery id, beats the probe.
465
+ const late = deliveryId ? agentHooks.deliveryState(deliveryId, target) : "unknown";
466
+ if (late === "blocked")
467
+ throw refusedHere();
468
+ if (late === "delivered")
469
+ result = { ok: true, delivered: true };
470
+ else {
471
+ // Still this conversation, in the same terminal: the agent holds the
472
+ // message (a busy turn queues it) and its hook has not submitted it
473
+ // yet. Queued, not delivered; `/v1/prompt/status` says when it lands.
474
+ if (confirmed && deliveryId)
475
+ agentHooks.queueDelivery(deliveryId, target);
476
+ result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : { queued: true }) };
477
+ }
471
478
  }
472
479
  }
473
480
  else if (url.pathname === "/v1/prompt/status") {
@@ -116,6 +116,7 @@ export declare const capabilities: {
116
116
  memoryStore: boolean;
117
117
  promptOnce: boolean;
118
118
  promptStatus: boolean;
119
+ deliveryFrames: boolean;
119
120
  resources: boolean;
120
121
  sudo: boolean;
121
122
  sudoOutcome: boolean;
@@ -68,7 +68,7 @@ async function childActivity(source, session) {
68
68
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
69
69
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
70
70
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
71
- files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
71
+ files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
72
72
  export function capabilitiesForModules(snapshot) {
73
73
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
74
74
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -91,6 +91,10 @@ export function transcriptStreams(ctx) {
91
91
  // for a phone that asked for them; an older phone rejects unknown frames.
92
92
  const sideAnswers = url.pathname === "/v1/transcripts" && child === null && url.searchParams.get("sideAnswers") === "1";
93
93
  const sentSide = new Map();
94
+ // A phone message's outcome by its delivery id (`/v1/prompt/status`),
95
+ // pushed as it changes to a stream opened with `deliveries=1`.
96
+ const deliveryFrames = url.pathname === "/v1/transcripts" && child === null && url.searchParams.get("deliveries") === "1";
97
+ const sentDelivery = new Map();
94
98
  // The first frame stays a backlog for protocol compatibility, but a
95
99
  // reconnect only reads rows beyond the phone's retained raw-line cursor.
96
100
  let resumeAfterLine = cursor === null ? undefined : z.coerce.number().int().nonnegative().max(4_294_967_295).parse(cursor);
@@ -214,6 +218,14 @@ export function transcriptStreams(ctx) {
214
218
  send(client, { type: "side-answer", ...conversation, ...side });
215
219
  }
216
220
  }
221
+ if (deliveryFrames) {
222
+ for (const { deliveryId, state } of agentHooks.deliveriesFor(target)) {
223
+ if (sentDelivery.get(deliveryId) === state)
224
+ continue;
225
+ sentDelivery.set(deliveryId, state);
226
+ send(client, { type: "delivery", ...conversation, deliveryId, state });
227
+ }
228
+ }
217
229
  first = false;
218
230
  }
219
231
  while (pending.length && reader && !abort.signal.aborted) {
@@ -17,7 +17,7 @@ import { cpus, hostname, loadavg } from "node:os";
17
17
  import path from "node:path";
18
18
  import { WebSocketServer } from "ws";
19
19
  import { relayLiveSpeech } from "./speech-live.js";
20
- import { relayTranscription } from "./speech-transcribe.js";
20
+ import { failRelay, relayTranscription } from "./speech-transcribe.js";
21
21
  import { ActivityJournal } from "./activity.js";
22
22
  import { countTick } from "./metrics.js";
23
23
  import { AgentHooks } from "./agent-hooks.js";
@@ -237,7 +237,7 @@ export async function serve(version, options = {}) {
237
237
  return;
238
238
  }
239
239
  if (url.pathname === "/v1/speech/transcribe") {
240
- void relayTranscription(client, url.searchParams).catch(() => client.close(1011, "Transcription unavailable"));
240
+ void relayTranscription(client, url.searchParams).catch(() => failRelay(client));
241
241
  return;
242
242
  }
243
243
  if (url.pathname === "/v1/speech/live") {
@@ -49,6 +49,12 @@ export declare function awaitedShells(record: TurnRecord | undefined, final: Fin
49
49
  * fan-out jobs) the caller counted. Leftover shells are awaited by neither, so
50
50
  * they do not hold a session or a dispatched worker open. */
51
51
  export declare function liveWork(record: TurnRecord | undefined, final: FinalTurn | undefined, runningChildren?: number, now?: number): number | undefined;
52
+ /** Every background task the finished turn left running, awaited or not, less
53
+ * the endless streams (a log tail, a dev server): the Stop's count less the
54
+ * tasks finished since, else the transcript's own count, and nothing once the
55
+ * Stop is BACKGROUND_STALE_MS old. A turn whose reply says it waits on such a
56
+ * task is still working, and a pane running one is not closed. */
57
+ export declare function runningTasks(record: TurnRecord | undefined, final: FinalTurn | undefined, now?: number): number;
52
58
  /** The background shells and monitors a pane's ended Claude turn is waiting
53
59
  * on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
54
60
  * (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
@@ -75,6 +75,22 @@ export function liveWork(record, final, runningChildren = 0, now = Date.now()) {
75
75
  const total = (awaitedShells(record, final, now) ?? 0) + runningChildren;
76
76
  return total || undefined;
77
77
  }
78
+ /** Every background task the finished turn left running, awaited or not, less
79
+ * the endless streams (a log tail, a dev server): the Stop's count less the
80
+ * tasks finished since, else the transcript's own count, and nothing once the
81
+ * Stop is BACKGROUND_STALE_MS old. A turn whose reply says it waits on such a
82
+ * task is still working, and a pane running one is not closed. */
83
+ export function runningTasks(record, final, now = Date.now()) {
84
+ const phase = record ? turnPhase(record) : undefined, endless = final?.endless ?? 0;
85
+ if (phase?.phase === "ended" && phase.background !== undefined) {
86
+ if (!(now - Date.parse(phase.at) < BACKGROUND_STALE_MS))
87
+ return 0;
88
+ return Math.max(0, backgroundLeft(phase.background, phase.at, final?.finishedTasks) - endless);
89
+ }
90
+ if (phase?.phase === "ended" && !(now - Date.parse(phase.at) < BACKGROUND_STALE_MS))
91
+ return 0;
92
+ return final?.completed ? Math.max(0, (final.background ?? 0) - endless) : 0;
93
+ }
78
94
  /** The background shells and monitors a pane's ended Claude turn is waiting
79
95
  * on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
80
96
  * (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
@@ -9,6 +9,13 @@ export declare const CODEX_MODES: Record<PermissionMode, Pick<CodexNextTurn, "ap
9
9
  export declare const CLAUDE_NAMES: Record<string, string>;
10
10
  /** The same Codex mode as command-line flags, for a Codex started with no thread yet. */
11
11
  export declare function codexModeFlags(mode: PermissionMode): string[];
12
+ /**
13
+ * Copilot CLI's launch flags for a mode. Copilot asks before every tool by
14
+ * default and has no automatic reviewer, so `auto` approves every tool call
15
+ * while file access stays inside the working folder, and `full-access` also
16
+ * lifts the path and URL checks (`--allow-all`).
17
+ */
18
+ export declare function copilotModeFlags(mode: PermissionMode): string[];
12
19
  export interface SettingsCapabilities {
13
20
  permissionModes: string[];
14
21
  plan: boolean;
@@ -29,6 +29,21 @@ export function codexModeFlags(mode) {
29
29
  const sandbox = { readOnly: "read-only", workspaceWrite: "workspace-write", dangerFullAccess: "danger-full-access" }[String(sandboxPolicy?.type)];
30
30
  return ["-a", String(approvalPolicy), "-s", String(sandbox), ...(approvalsReviewer === "auto_review" ? ["-c", 'approvals_reviewer="auto_review"'] : [])];
31
31
  }
32
+ /**
33
+ * Copilot CLI's launch flags for a mode. Copilot asks before every tool by
34
+ * default and has no automatic reviewer, so `auto` approves every tool call
35
+ * while file access stays inside the working folder, and `full-access` also
36
+ * lifts the path and URL checks (`--allow-all`).
37
+ */
38
+ export function copilotModeFlags(mode) {
39
+ if (mode === "auto-edits")
40
+ return ["--allow-tool=write"];
41
+ if (mode === "auto")
42
+ return ["--allow-all-tools"];
43
+ if (mode === "full-access")
44
+ return ["--allow-all"];
45
+ return [];
46
+ }
32
47
  const MAX_PRESSES = 6, STEP_WAIT_MS = 2_000;
33
48
  /** What this pane can change from the phone; undefined for harnesses that
34
49
  * offer nothing. A hand-started Codex TUI is empty: its state is still read
@@ -2,7 +2,11 @@
2
2
  * Scribe input. The phone streams 16 kHz mono PCM as binary frames; this
3
3
  * computer forwards it to ElevenLabs with its own key, which never leaves
4
4
  * here, and sends back `{type: "partial"|"committed", text}` frames. Errors
5
- * are fixed messages by code: ElevenLabs' own text is never passed on. */
5
+ * are fixed messages by code: ElevenLabs' own text is never passed on. No
6
+ * close is silent: `{type: "ready"}` says ElevenLabs answered, and every close
7
+ * the phone did not ask for follows an `error` frame or `{type: "end", reason}`
8
+ * (`session-limit` after ten minutes, `upstream-closed` when ElevenLabs hung
9
+ * up), so the phone reopens or reports without guessing from run length. */
6
10
  export declare const TRANSCRIBE_MODEL = "scribe_v2_realtime";
7
11
  export declare const TRANSCRIBE_RATE = 16000;
8
12
  /** The two sockets as the relay uses them, so tests can stand in for both. */
@@ -24,4 +28,7 @@ export interface TranscribeOptions {
24
28
  /** The upstream URL in the given region: VAD commits, the phone's language
25
29
  * and its vocabulary as keyterms. */
26
30
  export declare function transcribeURL(query: URLSearchParams, origin?: string): string;
31
+ /** Ends a socket whose relay threw before it could start (no key read, no
32
+ * region, no upstream socket), with the reason first. */
33
+ export declare function failRelay(client: RelaySocket): void;
27
34
  export declare function relayTranscription(client: RelaySocket, query: URLSearchParams, options?: TranscribeOptions): Promise<void>;
@@ -5,7 +5,11 @@ import { resolveSpeechRegion, SPEECH_REGIONS } from "./speech-voice.js";
5
5
  * Scribe input. The phone streams 16 kHz mono PCM as binary frames; this
6
6
  * computer forwards it to ElevenLabs with its own key, which never leaves
7
7
  * here, and sends back `{type: "partial"|"committed", text}` frames. Errors
8
- * are fixed messages by code: ElevenLabs' own text is never passed on. */
8
+ * are fixed messages by code: ElevenLabs' own text is never passed on. No
9
+ * close is silent: `{type: "ready"}` says ElevenLabs answered, and every close
10
+ * the phone did not ask for follows an `error` frame or `{type: "end", reason}`
11
+ * (`session-limit` after ten minutes, `upstream-closed` when ElevenLabs hung
12
+ * up), so the phone reopens or reports without guessing from run length. */
9
13
  export const TRANSCRIBE_MODEL = "scribe_v2_realtime";
10
14
  export const TRANSCRIBE_RATE = 16_000;
11
15
  const ENDPOINT = "/v1/speech-to-text/realtime";
@@ -38,6 +42,13 @@ const ERRORS = {
38
42
  queue_overflow: { code: "transcribe-busy", message: "ElevenLabs is busy. Try again shortly." },
39
43
  session_time_limit_exceeded: { code: "transcribe-limit", message: "This dictation reached ElevenLabs' time limit." },
40
44
  };
45
+ /** Ends a socket whose relay threw before it could start (no key read, no
46
+ * region, no upstream socket), with the reason first. */
47
+ export function failRelay(client) {
48
+ if (client.readyState === OPEN)
49
+ client.send(JSON.stringify({ type: "error", code: "transcribe-failed", error: "Couldn't reach ElevenLabs." }));
50
+ client.close(1011, "Transcription unavailable");
51
+ }
41
52
  export function relayTranscription(client, query, options = {}) {
42
53
  const connect = options.connect ?? ((url, key) => new WebSocket(url, { headers: { "xi-api-key": key } }));
43
54
  return (async () => {
@@ -64,7 +75,9 @@ export function relayTranscription(client, query, options = {}) {
64
75
  if (client.readyState === OPEN)
65
76
  client.close(code, reason);
66
77
  };
67
- const limit = setTimeout(() => finish(1000, "Session limit"), options.maxSessionMs ?? MAX_SESSION_MS);
78
+ const end = (reason) => { if (!closed)
79
+ tell({ type: "end", reason }); };
80
+ const limit = setTimeout(() => { end("session-limit"); finish(1000, "Session limit"); }, options.maxSessionMs ?? MAX_SESSION_MS);
68
81
  limit.unref?.();
69
82
  const chunk = (audio, commit = false) => JSON.stringify({
70
83
  message_type: "input_audio_chunk", audio_base_64: audio.toString("base64"), commit, sample_rate: TRANSCRIBE_RATE
@@ -97,6 +110,8 @@ export function relayTranscription(client, query, options = {}) {
97
110
  upstream.send(chunk(audio));
98
111
  pending = [];
99
112
  pendingBytes = 0;
113
+ if (!closed)
114
+ tell({ type: "ready" });
100
115
  });
101
116
  upstream.on("message", data => {
102
117
  let message;
@@ -122,6 +137,6 @@ export function relayTranscription(client, query, options = {}) {
122
137
  }
123
138
  });
124
139
  upstream.on("error", () => { tell({ type: "error", code: "transcribe-failed", error: "Couldn't reach ElevenLabs." }); finish(1011); });
125
- upstream.on("close", () => finish());
140
+ upstream.on("close", () => { end("upstream-closed"); finish(1000, "ElevenLabs closed"); });
126
141
  })();
127
142
  }
@@ -4,9 +4,10 @@ import { createInterface } from "node:readline";
4
4
  import { createHash } from "node:crypto";
5
5
  import path from "node:path";
6
6
  import { object, objects } from "./protocol.js";
7
- /** Claude Code's transcript reader: Task sidechains and named teammates as
8
- * child agents, and the public rows of a conversation. */
9
7
  const claudeRelationCache = new Map();
8
+ const copyRows = (rows) => ({ launches: new Map([...rows.launches].map(([id, launch]) => [id, { ...launch }])),
9
+ skills: new Set(rows.skills), workflows: new Map([...rows.workflows].map(([id, workflow]) => [id, { ...workflow }])),
10
+ teammates: new Map([...rows.teammates].map(([name, launch]) => [name, { ...launch }])) });
10
11
  const claudeChildModelCache = new Map();
11
12
  function cacheClaudeChildModel(file, entry) {
12
13
  claudeChildModelCache.set(file, entry);
@@ -91,6 +92,12 @@ export async function claudeChildAgents(file, session) {
91
92
  cached.relations = await withClaudeChildModels(cached.relations);
92
93
  return cached.relations;
93
94
  }
95
+ // A recheck of an unchanged parent (a launch whose transcript was not there
96
+ // yet, a background skill or workflow still running) reads only the children.
97
+ const rows = cached?.signature === signature && cached.rows ? cached.rows : await claudeParentRows(file);
98
+ return claudeChildRelations(file, session, signature, rows);
99
+ }
100
+ async function claudeParentRows(file) {
94
101
  const launches = new Map();
95
102
  const stops = new Map();
96
103
  // A background skill (`/code-review` run as `@code-review`) is announced in
@@ -177,15 +184,26 @@ export async function claudeChildAgents(file, session) {
177
184
  previous.state = "completed";
178
185
  }
179
186
  }
180
- if (content.includes("<teammate-message")) {
181
- const from = /<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"/.exec(content)?.[1];
182
- const teammate = from && teammates.get(from);
187
+ // One row can carry several messages (a shutdown approval and the
188
+ // system's termination notice together). Idle, an approved shutdown
189
+ // and termination end a teammate; anything else it says wakes it.
190
+ 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) : []) {
191
+ const [, from, body] = match;
192
+ const type = /"type":"([a-z_]+)"/.exec(body)?.[1];
193
+ 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;
194
+ const teammate = teammates.get(ended ?? from);
183
195
  if (teammate)
184
- teammate.state = content.includes("\"type\":\"idle_notification\"") ? "completed" : "running";
196
+ teammate.state = ended || type === "idle_notification" || type === "shutdown_approved" ? "completed" : "running";
185
197
  }
186
198
  }
187
199
  catch { /* Ignore unrelated/malformed rows. */ }
188
200
  }
201
+ return { launches, skills, workflows, teammates };
202
+ }
203
+ async function claudeChildRelations(file, session, signature, rows) {
204
+ // Kept as the parent wrote them: what follows marks finished children.
205
+ const kept = copyRows(rows);
206
+ const { launches, workflows, teammates } = copyRows(rows);
189
207
  const relations = [];
190
208
  // Claude Code records the launch in the parent before the child's own
191
209
  // file exists. A launch without a transcript yet is looked for again
@@ -201,7 +219,9 @@ export async function claudeChildAgents(file, session) {
201
219
  awaiting = true;
202
220
  continue;
203
221
  }
204
- if (skills.has(agentId) && launch.state === "running") {
222
+ // A skill never gets a notification, and any child loses its own when the
223
+ // session that ran it was restarted or continued: its transcript decides.
224
+ if (launch.state === "running") {
205
225
  if (await claudeSkillFinished(childFile).catch(() => false))
206
226
  launch.state = "completed";
207
227
  else
@@ -237,6 +257,14 @@ export async function claudeChildAgents(file, session) {
237
257
  }
238
258
  // The meta file names the model as the launcher chose it ("sonnet");
239
259
  // the transcript's first assistant turn carries the full id and wins.
260
+ // A teammate that never said it was idle or shut down (its session was
261
+ // restarted or continued) ends the same way: a finished reply, or quiet.
262
+ if (launch.state === "running") {
263
+ if (await claudeSkillFinished(childFile).catch(() => false))
264
+ launch.state = "completed";
265
+ else
266
+ live = true;
267
+ }
240
268
  const meta = await readFile(childFile.slice(0, -".jsonl".length) + ".meta.json", "utf8").then(v => object(JSON.parse(v))).catch(() => ({}));
241
269
  const model = await claudeChildModel(childFile).catch(() => undefined) ?? (typeof meta.model === "string" && meta.model ? meta.model.slice(0, 200) : undefined);
242
270
  const checkout = await claudeChildCheckout(childFile).catch(() => ({}));
@@ -258,7 +286,7 @@ export async function claudeChildAgents(file, session) {
258
286
  }
259
287
  }
260
288
  }
261
- claudeRelationCache.set(file, { signature, relations, ...(awaiting || live ? { recheckAt: Date.now() + (awaiting ? 2_000 : 5_000) } : {}) });
289
+ claudeRelationCache.set(file, { signature, relations, ...(awaiting || live ? { recheckAt: Date.now() + (awaiting ? 2_000 : 5_000), rows: kept } : {}) });
262
290
  while (claudeRelationCache.size > 64)
263
291
  claudeRelationCache.delete(claudeRelationCache.keys().next().value);
264
292
  return relations;
@@ -267,8 +295,9 @@ export async function claudeChildAgents(file, session) {
267
295
  * taken as finished: the parent records no end for it, and a session that
268
296
  * exited mid-skill leaves it without a final reply. */
269
297
  export const CLAUDE_SKILL_QUIET_MS = 30 * 60 * 1000;
270
- /** A background skill is done once its transcript ends on a finished reply,
271
- * or has not changed for CLAUDE_SKILL_QUIET_MS. */
298
+ /** A background child (a skill, or a sub-agent or teammate whose end the
299
+ * parent never recorded) is done once its transcript ends on a finished
300
+ * reply, or has not changed for CLAUDE_SKILL_QUIET_MS. */
272
301
  async function claudeSkillFinished(file, now = Date.now()) {
273
302
  const metadata = await stat(file);
274
303
  if (now - metadata.mtimeMs >= CLAUDE_SKILL_QUIET_MS)
@@ -51,8 +51,9 @@ export async function closeFinishedWorker(input, queue) {
51
51
  return { ok: true, closed: false };
52
52
  const seen = (await workerStates({ targets: [{ ...data.target, dispatch: data.dispatch }] })).workers[0];
53
53
  const turn = workerTurnKey(seen);
54
- // A turn that stopped mid-task, or whose checkout could not be read, keeps its pane.
55
- if (!seen.completed || seen.background || seen.error || seen.unfinished || seen.unchecked || turn !== data.turn)
54
+ // A turn still working, one that stopped mid-task or with background work
55
+ // running, or whose checkout could not be read, keeps its pane.
56
+ if ((seen.state !== "done" && seen.state !== "idle") || !seen.completed || seen.background || seen.error || seen.unfinished || seen.unchecked || turn !== data.turn)
56
57
  return { ok: true, closed: false };
57
58
  // One final fresh binding before the terminal mutation.
58
59
  const current = await validateTarget(data.target, false, true);
@@ -1,6 +1,12 @@
1
- /** The reply's closing sentence when it announces a next step ("Let me…",
2
- * "I'll…", "Now running…"), else undefined. */
1
+ /** The first sentence of the reply's closing paragraph that announces a next
2
+ * step ("Let me…", "I'll…", "Now running…"), else undefined. The closing line
3
+ * counts even as a list item; earlier lines only as prose, so a summary list
4
+ * that quotes an old step is not one. */
3
5
  export declare function announcedNextStep(reply: string | undefined): string | undefined;
6
+ /** The first sentence of the reply's closing paragraph that waits on work
7
+ * still to finish ("Now waiting on the rerun.", "I'll push once it passes."),
8
+ * else undefined. */
9
+ export declare function awaitedInReply(reply: string | undefined): string | undefined;
4
10
  /** A checkout git could not read in time (or at all): its work is unknown,
5
11
  * so a turn there is never closed on the strength of it. */
6
12
  export declare const UNKNOWN = "unknown";
@@ -13,44 +13,74 @@ import { countGit } from "./metrics.js";
13
13
  * is not closed and the dispatcher nudges it on.
14
14
  */
15
15
  const exec = promisify(execFile);
16
- /** A closing sentence that announces work the turn never did: "Let me…",
17
- * "I'll…", "I need to…", or "Now" with a working verb. Anything else, and
18
- * whatever follows the subject in HANDOVER or a sentence waiting on something
19
- * (CONDITIONAL), reads as finished: a done worker that says "I'll wait for
20
- * your review" must not read as needs-you. "Let me know…" is a sign-off. */
16
+ /** A sentence that announces work the turn never did: "Let me…", "I'll…",
17
+ * "I need to…", or "Now" with a working verb. Whatever follows the subject in
18
+ * HANDOVER, or a sentence waiting on something (CONDITIONAL, read by
19
+ * `awaitedInReply` instead), is not one: a done worker that says "I'll wait
20
+ * for your review" must not read as needs-you. "Let me know…" is a sign-off. */
21
21
  const NEXT_STEP = /^(?:(?:ok(?:ay)?|alright|now|next|then|first|great|good)\b[,.!:]?\s+)*(?:let me(?! know)|let's|let us|i'll|i will|i'm going to|i am going to|i need to|i'm now|i am now|now i)\s+(.*)$/i;
22
22
  const NOW_DOING = /^now,?\s+(?:adding|applying|building|checking|cleaning|committing|compiling|creating|debugging|editing|fixing|generating|implementing|installing|investigating|launching|looking|moving|opening|patching|pushing|reading|rebuilding|refactoring|removing|rerunning|re-running|running|searching|setting|starting|testing|trying|updating|verifying|wiring|working|writing)\b/i;
23
23
  /** What a finished worker says it does next: wait, leave it to the owner, stop, be around. */
24
24
  const HANDOVER = /^(?:just\s+)?(?:wait|await|leave|stop|hold|pause|be|hand|defer|stand|end|wrap|let you|keep an eye|check back|merge|ship|land|release|discuss|review|done|finished|ready)\b/i;
25
25
  const CONDITIONAL = /\b(?:once|when|whenever|after|as soon as|if|until|unless)\b/i;
26
- /** The last prose line of a reply: blank lines and fenced code are skipped, so
27
- * "Let me run:" before a closing code block is still the closing sentence. */
28
- function lastProseLine(reply) {
29
- let fenced = false, last;
26
+ /** A sentence that waits on something other than the owner: "Now waiting on
27
+ * the MacBook rerun.", "I'll push once it passes.", "Let's merge once CI is
28
+ * green." (ios-fast-voice2, 2026-10-01: returned done and closed with its test
29
+ * run going). Waiting for the owner's review or answer is a handover. */
30
+ const WAITS = /(?<!\bwhile\s)\b(?:wait(?:ing|s)?|await(?:ing|s)?)\s+(?:on|for|until)\b/i;
31
+ /** "Once it passes", "when the build finishes": waiting on a job, not an "if". */
32
+ const ONCE_DONE = /\b(?:once|when|after|as soon as|until)\s+(?:it|its|the|that|this|they|both|all|my|ci)\b/i;
33
+ const FUTURE = /\b(?:i'll|i will|we'll|we will|let's|let us|then i|will)\b/i;
34
+ const OWNER = /\b(?:you|your|yours|owner|reviewers?|approv\w*|let me know)\b/i;
35
+ const NEGATED = /\b(?:nothing|no longer|not|no need|without)\b|n't\b/i;
36
+ /** The closing paragraph's prose lines: blank lines end a paragraph and fenced
37
+ * code is skipped, so "Let me run:" before a closing code block is still in it. */
38
+ function closingLines(reply) {
39
+ let fenced = false, lines = [];
30
40
  for (const raw of reply.replace(/\r/g, "").split("\n")) {
31
41
  const line = raw.trim();
32
42
  if (/^(?:```|~~~)/.test(line)) {
33
43
  fenced = !fenced;
34
44
  continue;
35
45
  }
36
- if (!fenced && line)
37
- last = line;
46
+ if (fenced)
47
+ continue;
48
+ if (!line) {
49
+ if (lines.length)
50
+ lines = [...lines, ""];
51
+ continue;
52
+ }
53
+ if (lines.at(-1) === "")
54
+ lines = [];
55
+ lines.push(line);
38
56
  }
39
- return last;
57
+ return lines.filter(Boolean);
58
+ }
59
+ const LIST_ITEM = /^(?:[-*+>]|\d+[.)])\s+/;
60
+ const sentences = (line) => line.replace(LIST_ITEM, "").replace(/[*_`#]+/g, "").replace(/[\u2018\u2019]/g, "'").trim()
61
+ .split(/(?<=[.!?\u2026])\s+/).map(sentence => sentence.trim()).filter(Boolean);
62
+ function nextStep(sentence) {
63
+ if (CONDITIONAL.test(sentence))
64
+ return false;
65
+ const step = NEXT_STEP.exec(sentence);
66
+ return step ? !HANDOVER.test(step[1]) : NOW_DOING.test(sentence);
40
67
  }
41
- /** The reply's closing sentence when it announces a next step ("Let me…",
42
- * "I'll…", "Now running…"), else undefined. */
68
+ /** The first sentence of the reply's closing paragraph that announces a next
69
+ * step ("Let me…", "I'll…", "Now running…"), else undefined. The closing line
70
+ * counts even as a list item; earlier lines only as prose, so a summary list
71
+ * that quotes an old step is not one. */
43
72
  export function announcedNextStep(reply) {
44
- const line = reply ? lastProseLine(reply) : undefined;
45
- if (!line)
46
- return undefined;
47
- const plain = line.replace(/^(?:[-*+>]|\d+[.)])\s+/, "").replace(/[*_`#]+/g, "").replace(/[\u2018\u2019]/g, "'").trim();
48
- const last = plain.split(/(?<=[.!?\u2026])\s+/).filter(Boolean).at(-1)?.trim();
49
- if (!last || CONDITIONAL.test(last))
50
- return undefined;
51
- const step = NEXT_STEP.exec(last);
52
- const announced = step ? !HANDOVER.test(step[1]) : NOW_DOING.test(last);
53
- return announced ? last.slice(0, 160) : undefined;
73
+ const lines = reply ? closingLines(reply) : [];
74
+ const found = lines.flatMap((line, index) => index === lines.length - 1 || !LIST_ITEM.test(line) ? sentences(line) : []).find(nextStep);
75
+ return found?.slice(0, 160);
76
+ }
77
+ /** The first sentence of the reply's closing paragraph that waits on work
78
+ * still to finish ("Now waiting on the rerun.", "I'll push once it passes."),
79
+ * else undefined. */
80
+ export function awaitedInReply(reply) {
81
+ const found = (reply ? closingLines(reply) : []).flatMap(sentences).find(sentence => !OWNER.test(sentence) && !NEGATED.test(sentence)
82
+ && (WAITS.test(sentence) || (ONCE_DONE.test(sentence) && FUTURE.test(sentence))));
83
+ return found?.slice(0, 160);
54
84
  }
55
85
  /** A checkout git could not read in time (or at all): its work is unknown,
56
86
  * so a turn there is never closed on the strength of it. */
@@ -136,6 +166,9 @@ export async function unfinishedTurn(input, uncommitted) {
136
166
  const step = announcedNextStep(input.reply);
137
167
  if (step)
138
168
  return { unfinished: `Stopped mid-task: ${step}` };
169
+ const waiting = awaitedInReply(input.reply);
170
+ if (waiting)
171
+ return { unfinished: `Stopped waiting: ${waiting}` };
139
172
  if (input.prs?.length || PR_NAMED.test(input.reply ?? "") || !input.directory || !uncommitted)
140
173
  return {};
141
174
  const files = await uncommitted(input.directory).catch(() => UNKNOWN);