@phren/cli 0.3.18 → 0.3.20

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 +16 -1
  2. package/dist/bridge/agent-hooks.js +56 -4
  3. package/dist/bridge/changes.d.ts +4 -0
  4. package/dist/bridge/changes.js +25 -2
  5. package/dist/bridge/command.js +24 -6
  6. package/dist/bridge/dispatch-returns.d.ts +11 -0
  7. package/dist/bridge/dispatch-returns.js +47 -7
  8. package/dist/bridge/dispatch.d.ts +19 -0
  9. package/dist/bridge/dispatch.js +164 -5
  10. package/dist/bridge/harnesses.d.ts +1 -1
  11. package/dist/bridge/harnesses.js +9 -2
  12. package/dist/bridge/health.d.ts +3 -2
  13. package/dist/bridge/health.js +4 -3
  14. package/dist/bridge/hook-fast.d.ts +13 -1
  15. package/dist/bridge/hook-fast.js +17 -2
  16. package/dist/bridge/models.d.ts +11 -1
  17. package/dist/bridge/models.js +47 -2
  18. package/dist/bridge/server-launch.d.ts +20 -0
  19. package/dist/bridge/server-launch.js +77 -3
  20. package/dist/bridge/server-routes.d.ts +4 -0
  21. package/dist/bridge/server-routes.js +2 -2
  22. package/dist/bridge/server.js +6 -1
  23. package/dist/bridge/speech-live.d.ts +45 -0
  24. package/dist/bridge/speech-live.js +413 -0
  25. package/dist/bridge/speech-transcribe.d.ts +5 -2
  26. package/dist/bridge/speech-transcribe.js +8 -5
  27. package/dist/bridge/speech-voice.d.ts +22 -1
  28. package/dist/bridge/speech-voice.js +20 -2
  29. package/dist/bridge/speech.d.ts +24 -4
  30. package/dist/bridge/speech.js +115 -14
  31. package/dist/bridge/stalls.d.ts +9 -2
  32. package/dist/bridge/stalls.js +20 -4
  33. package/dist/bridge/terminal-herdr.d.ts +7 -0
  34. package/dist/bridge/terminal-herdr.js +81 -7
  35. package/dist/bridge/terminal-tmux.js +2 -2
  36. package/dist/bridge/terminal.d.ts +3 -0
  37. package/dist/bridge/terminal.js +1 -0
  38. package/dist/bridge/transcript-preview.d.ts +11 -1
  39. package/dist/bridge/transcript-preview.js +37 -11
  40. package/dist/bridge/transcripts.d.ts +2 -1
  41. package/dist/bridge/transcripts.js +7 -3
  42. package/dist/bridge/transport.js +4 -3
  43. package/dist/bridge/turn-records.d.ts +6 -3
  44. package/dist/bridge/turn-records.js +9 -4
  45. package/dist/bridge/usage.d.ts +1 -1
  46. package/dist/bridge/usage.js +4 -3
  47. package/dist/bridge/worker-close.js +2 -1
  48. package/dist/bridge/worker-unfinished.d.ts +37 -0
  49. package/dist/bridge/worker-unfinished.js +145 -0
  50. package/dist/bridge-hook.mjs +2171 -1230
  51. package/dist/cli-registry.js +2 -1
  52. package/dist/modules/registry.js +2 -2
  53. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { type ModuleSnapshot } from "../modules/runtime.js";
2
+ import { type ServerResponse } from "node:http";
2
3
  import { type Json, type Provider, type Target } from "./protocol.js";
3
4
  import { ToolChanges } from "./changes.js";
4
5
  import { ApprovalPushService } from "./push.js";
@@ -15,6 +16,10 @@ export { ApprovalWatchLeases, PushBindingStore, recordedSession } from "./agent-
15
16
  /** Where a held request's answer goes: the callback's HTTP response, or the
16
17
  * reply to a Codex app-server request (codex-servers.ts). Either takes the
17
18
  * PermissionRequest-shaped JSON; "{}" gives the request back to the terminal. */
19
+ /** Whether the caller hung up on `res` before it was answered. Not
20
+ * `req.destroyed`: a request body read to its end is destroyed on every
21
+ * Node this supports, so that read as a hang-up on each normal callback. */
22
+ export declare function watchHangUp(res: ServerResponse): () => boolean;
18
23
  interface HeldReply {
19
24
  end(body: string): unknown;
20
25
  readonly destroyed: boolean;
@@ -392,4 +397,14 @@ export declare function stopFacts(value: Json): {
392
397
  background?: number;
393
398
  reply?: string;
394
399
  };
395
- export declare function agentHook(source: Provider): Promise<void>;
400
+ /** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
401
+ * tool call's callback ran out of its budget: the caller then exits at once,
402
+ * since a socket or a process read still pending would hold the agent. */
403
+ export declare function agentHook(source: Provider, elapsed?: () => number): Promise<void | "abandoned">;
404
+ /**
405
+ * Runs a callback's work. A PreToolUse or PostToolUse callback gets what is
406
+ * left of TOOL_HOOK_BUDGET_MS since its process started (hook-fast.ts says
407
+ * why): "abandoned" once that runs out, and the caller exits without an
408
+ * answer so the tool runs. Every other event runs to its own timeouts.
409
+ */
410
+ export declare function withinToolBudget<T>(event: string, work: (left: () => number) => Promise<T>, elapsed?: () => number, budgetMs?: number): Promise<T | "abandoned">;
@@ -10,6 +10,7 @@ import { createHash, randomUUID } from "node:crypto";
10
10
  import { hostname } from "node:os";
11
11
  import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
12
12
  import { findPane, knownPanes, paneForCodexSession, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
13
+ import { TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
13
14
  import { underCodexDaemon } from "./codex-daemon.js";
14
15
  import { codexAutoReview } from "./codex-review-mode.js";
15
16
  import { terminalPaneFromEnv, terminalProvider } from "./terminal.js";
@@ -58,6 +59,19 @@ const FANOUT_SWEEP_MS = 5_000;
58
59
  * forward, and the card goes only when the ask is gone or the pane is dead. */
59
60
  const SERVED_ASK_MS = 60 * 60_000;
60
61
  const FANOUT_ARCHIVE_MS = 60 * 60 * 1000;
62
+ /** Where a held request's answer goes: the callback's HTTP response, or the
63
+ * reply to a Codex app-server request (codex-servers.ts). Either takes the
64
+ * PermissionRequest-shaped JSON; "{}" gives the request back to the terminal. */
65
+ /** Whether the caller hung up on `res` before it was answered. Not
66
+ * `req.destroyed`: a request body read to its end is destroyed on every
67
+ * Node this supports, so that read as a hang-up on each normal callback. */
68
+ export function watchHangUp(res) {
69
+ let closed = res.destroyed || res.socket?.destroyed === true;
70
+ const onClose = () => { if (!res.writableEnded)
71
+ closed = true; };
72
+ res.once("close", onClose);
73
+ return () => { res.off("close", onClose); return closed || res.destroyed; };
74
+ }
61
75
  /** The approval card's tool and input for an app-server request, in the
62
76
  * shapes `approvalSummary` and the phone already read for Codex's hook.
63
77
  * Undefined for questions (`item/tool/requestUserInput`) and MCP
@@ -734,7 +748,8 @@ export class AgentHooks {
734
748
  await recordTurn(target.server, target.pane, { event: String(body.event), terminal: pane.terminal_id, source: target.source, session: target.session,
735
749
  ...(dispatch ? { dispatch } : {}),
736
750
  ...(typeof body.background === "number" ? { background: body.background } : {}),
737
- ...(typeof body.reply === "string" ? { reply: body.reply } : {}) }).catch(() => undefined);
751
+ ...(typeof body.reply === "string" ? { reply: body.reply } : {}),
752
+ ...(body.event === "Stop" && typeof body.cwd === "string" ? { cwd: body.cwd } : {}) }).catch(() => undefined);
738
753
  }
739
754
  rememberTerminalPrompt(target, body) {
740
755
  const tool = String(body.tool || "action").slice(0, 200);
@@ -1686,6 +1701,11 @@ export class AgentHooks {
1686
1701
  const status = autoReview ? undefined : eventStatus(body.event);
1687
1702
  if (status && typeof pane.terminal_id === "string")
1688
1703
  notePaneStatus(target.server, target.pane, pane.terminal_id, status);
1704
+ // Herdr does not watch phren-agent: a pane the Hook reported as running
1705
+ // it (a phone launch) takes its status from these events.
1706
+ if (status && target.source === "phren" && pane.agent === "phren" && pane.agent_status !== status) {
1707
+ await terminalProvider().reportAgent?.(target.server, target.pane, "phren", status).catch(() => undefined);
1708
+ }
1689
1709
  // What a shell call changed on disk: snapshot before, diff after.
1690
1710
  const input = typeof body.input === "string" ? { patch: body.input } : object(body.input), command = [input.command, input.cmd].find(v => typeof v === "string");
1691
1711
  // A shell call by name, or any tool whose input is a command line —
@@ -1723,8 +1743,13 @@ export class AgentHooks {
1723
1743
  await this.recordTurn(target, pane, body, dispatch);
1724
1744
  if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body.event)) && capturesChanges(String(body.tool), input)) {
1725
1745
  const conversation = `${target.source}:${target.session}`, id = String(body.toolUseId || "").slice(0, 200);
1726
- if (body.event === "PreToolUse")
1746
+ if (body.event === "PreToolUse") {
1747
+ const hungUp = watchHangUp(res);
1727
1748
  await this.changes.before(conversation, id, typeof body.cwd === "string" && path.isAbsolute(body.cwd) ? body.cwd : await trustedDirectory(pane), command ?? "", input);
1749
+ // The callback gave up (TOOL_HOOK_BUDGET_MS) and the tool ran while this was read.
1750
+ if (hungUp())
1751
+ this.changes.drop(conversation, id);
1752
+ }
1728
1753
  else
1729
1754
  await this.changes.after(conversation, id);
1730
1755
  res.end("{}");
@@ -1895,7 +1920,10 @@ export function stopFacts(value) {
1895
1920
  return { ...(tasks ? { background: tasks.length } : {}),
1896
1921
  ...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
1897
1922
  }
1898
- export async function agentHook(source) {
1923
+ /** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
1924
+ * tool call's callback ran out of its budget: the caller then exits at once,
1925
+ * since a socket or a process read still pending would hold the agent. */
1926
+ export async function agentHook(source, elapsed = () => performance.now()) {
1899
1927
  provider.parse(source);
1900
1928
  // A missing helper must never prevent the coding agent from running.
1901
1929
  // Inside Herdr only Herdr's pane counts; elsewhere a tmux pane does.
@@ -1914,6 +1942,30 @@ export async function agentHook(source) {
1914
1942
  const target = targetSchema.parse({ server: place.server, workspace: place.workspace, tab: place.tab,
1915
1943
  pane: place.pane, source, session: value.session_id || value.sessionId });
1916
1944
  const event = String(value.hook_event_name || "SessionStart");
1945
+ return withinToolBudget(event, left => forwardHook(source, target, event, value, left), elapsed);
1946
+ }
1947
+ /**
1948
+ * Runs a callback's work. A PreToolUse or PostToolUse callback gets what is
1949
+ * left of TOOL_HOOK_BUDGET_MS since its process started (hook-fast.ts says
1950
+ * why): "abandoned" once that runs out, and the caller exits without an
1951
+ * answer so the tool runs. Every other event runs to its own timeouts.
1952
+ */
1953
+ export async function withinToolBudget(event, work, elapsed = () => performance.now(), budgetMs = TOOL_HOOK_BUDGET_MS) {
1954
+ if (!event.endsWith("ToolUse"))
1955
+ return work(() => Infinity);
1956
+ const left = () => Math.floor(budgetMs - elapsed());
1957
+ if (left() <= 0)
1958
+ return "abandoned";
1959
+ let timer;
1960
+ const expired = new Promise(resolve => { timer = setTimeout(() => resolve("abandoned"), left()); });
1961
+ try {
1962
+ return await Promise.race([work(left), expired]);
1963
+ }
1964
+ finally {
1965
+ clearTimeout(timer);
1966
+ }
1967
+ }
1968
+ async function forwardHook(source, target, event, value, left) {
1917
1969
  const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
1918
1970
  if (!modules.has("hook") || (event.endsWith("ToolUse") && !modules.has("git")))
1919
1971
  return;
@@ -1936,7 +1988,7 @@ export async function agentHook(source) {
1936
1988
  ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
1937
1989
  ...(event === "Stop" ? stopFacts(value) : {}) });
1938
1990
  await new Promise(resolve => {
1939
- const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 : 12_000,
1991
+ const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? Math.max(1, left()) : 12_000,
1940
1992
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
1941
1993
  let result = "";
1942
1994
  res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384)
@@ -45,6 +45,10 @@ export declare class ToolChanges {
45
45
  private discard;
46
46
  close(): Promise<void>;
47
47
  before(conversation: string, toolUseId: string, cwd: string, command: string, input?: Json): Promise<void>;
48
+ /** Forget the snapshot of a tool call whose PreToolUse callback gave up
49
+ * before the snapshot was taken: the tool may have run while it was read,
50
+ * so no diff is shown for that call rather than a wrong one. */
51
+ drop(conversation: string, toolUseId: string): void;
48
52
  private claim;
49
53
  /** Whether another conversation's call named this file while `snapshot` ran. */
50
54
  private claimedElsewhere;
@@ -232,7 +232,7 @@ export class ToolChanges {
232
232
  this.claim(conversation, toolUseId, claimed);
233
233
  if (this.snapshots.size >= 64 || this.snapshots.has(key))
234
234
  return;
235
- const snapshot = { at: Date.now(), conversation, own: new Set(claimed), trees: new Map() };
235
+ const snapshot = { at: Date.now(), conversation, own: new Set(claimed), trees: new Map(), taking: true };
236
236
  this.snapshots.set(key, snapshot);
237
237
  try {
238
238
  await this.budget(async (signal) => {
@@ -255,6 +255,11 @@ export class ToolChanges {
255
255
  }
256
256
  signal.throwIfAborted();
257
257
  });
258
+ snapshot.taking = false;
259
+ if (snapshot.dropped) {
260
+ await this.discard(snapshot);
261
+ return;
262
+ }
258
263
  if (!snapshot.trees.size) {
259
264
  this.snapshots.delete(key);
260
265
  return;
@@ -269,10 +274,24 @@ export class ToolChanges {
269
274
  snapshot.expiry.unref();
270
275
  }
271
276
  catch {
272
- this.snapshots.delete(key);
277
+ if (this.snapshots.get(key) === snapshot)
278
+ this.snapshots.delete(key);
273
279
  await this.discard(snapshot);
274
280
  }
275
281
  }
282
+ /** Forget the snapshot of a tool call whose PreToolUse callback gave up
283
+ * before the snapshot was taken: the tool may have run while it was read,
284
+ * so no diff is shown for that call rather than a wrong one. */
285
+ drop(conversation, toolUseId) {
286
+ const key = `${conversation}\0${toolUseId}`, snapshot = this.snapshots.get(key);
287
+ if (!snapshot || snapshot.result)
288
+ return;
289
+ this.snapshots.delete(key);
290
+ if (snapshot.taking)
291
+ snapshot.dropped = true;
292
+ else
293
+ void this.discard(snapshot).catch(() => { });
294
+ }
276
295
  claim(conversation, toolUseId, paths) {
277
296
  const now = Date.now();
278
297
  this.claims = this.claims.filter(claim => claim.end === undefined ? now - claim.start < 30 * 60_000 : now - claim.end < CLAIM_RETENTION);
@@ -291,6 +310,10 @@ export class ToolChanges {
291
310
  claim.end ??= Date.now();
292
311
  if (!snapshot)
293
312
  return;
313
+ if (snapshot.taking) {
314
+ this.drop(conversation, toolUseId);
315
+ return;
316
+ }
294
317
  snapshot.result ??= this.compute(snapshot);
295
318
  const files = await snapshot.result;
296
319
  if (this.snapshots.get(key) === snapshot) {
@@ -9,7 +9,7 @@ import { askpass } from "./sudo.js";
9
9
  import { object, provider } from "./protocol.js";
10
10
  import { apnsSetupSteps } from "./push.js";
11
11
  import { speechKeyFile, speechKeyStatus, writeSpeechKey } from "./speech-key.js";
12
- import { clearSpeechModel, clearSpeechVoice, DEFAULT_SPEECH_MODEL, FALLBACK_SPEECH_MODEL, resolveSpeechModel, resolveSpeechVoice, speechModelId, speechVoiceFile, voiceId, writeSpeechModel, writeSpeechVoice } from "./speech-voice.js";
12
+ import { clearSpeechModel, clearSpeechVoice, DEFAULT_SPEECH_MODEL, FALLBACK_SPEECH_MODEL, resolveSpeechModel, resolveSpeechRegion, resolveSpeechVoice, SPEECH_REGIONS, speechModelId, speechRegion, speechVoiceFile, voiceId, writeSpeechModel, writeSpeechRegion, writeSpeechVoice } from "./speech-voice.js";
13
13
  import { AccountUsageReader, captureClaudeUsage } from "./usage.js";
14
14
  import { acceptComputer, enrollComputer } from "./computers.js";
15
15
  import { addPeerFromLink, discoverComputers, linkComputer } from "./link.js";
@@ -158,6 +158,22 @@ export async function runBridge(args, version) {
158
158
  throw new Error(SPEECH_MODEL_USAGE);
159
159
  break;
160
160
  }
161
+ case "speech-region": {
162
+ const [, region = "show"] = args;
163
+ if (args.length > 2)
164
+ throw new Error(SPEECH_REGION_USAGE);
165
+ if (region === "show") {
166
+ const current = await resolveSpeechRegion();
167
+ console.log(`${current.region}: ${current.origin} (${current.source === "setting" ? `stored in ${speechVoiceFile()}` : current.source})`);
168
+ }
169
+ else if (speechRegion.safeParse(region).success) {
170
+ const stored = await writeSpeechRegion(region);
171
+ console.log(`Talk mode now reaches ElevenLabs at ${SPEECH_REGIONS[stored]} (${stored}). Install and update keep it.`);
172
+ }
173
+ else
174
+ throw new Error(SPEECH_REGION_USAGE);
175
+ break;
176
+ }
161
177
  case "usage-statusline":
162
178
  await captureClaudeUsage(args[1] || "");
163
179
  break;
@@ -165,7 +181,8 @@ export async function runBridge(args, version) {
165
181
  console.log(JSON.stringify(await new AccountUsageReader().read(), null, 2));
166
182
  break;
167
183
  case "hook":
168
- await agentHook(provider.parse(args[1])).catch(() => { });
184
+ if (await agentHook(provider.parse(args[1])).catch(() => undefined) === "abandoned")
185
+ process.exit(0);
169
186
  break;
170
187
  // sudo -A runs <bridge>/askpass, which runs this: the password on stdout, or exit 1.
171
188
  case "askpass": return askpass(args[1]);
@@ -182,7 +199,7 @@ export async function runBridge(args, version) {
182
199
  return Array.isArray(rows[source]) ? rows[source] : [];
183
200
  };
184
201
  const emptyUsage = (source) => ({ source, windows: [] });
185
- const modelCatalog = new ModelCatalog(() => readModels("codex"), () => readModels("claude"), () => readModels("opencode"), 0);
202
+ const modelCatalog = new ModelCatalog(() => readModels("codex"), () => readModels("claude"), () => readModels("opencode"), 0, () => readModels("phren"));
186
203
  const accountUsage = new AccountUsageReader(async () => emptyUsage("codex"), Date.now, async () => ({ source: "claude", windows: [{ id: "fixture", name: "Fixture", usedPercent: 0 }] }), async () => emptyUsage("opencode"), async () => undefined, async () => emptyUsage("opencode-go"), async () => emptyUsage("copilot"));
187
204
  await serve(version, { modelCatalog, accountUsage });
188
205
  break;
@@ -205,7 +222,7 @@ export async function runBridge(args, version) {
205
222
  break;
206
223
  case "doctor": {
207
224
  const helper = await health(), muxes = await servers(), terminal = await terminalHealth();
208
- const push = approvalPushCheck(helper), speech = await speechKeyStatus(), voice = await resolveSpeechVoice().catch(() => undefined), model = await resolveSpeechModel();
225
+ const push = approvalPushCheck(helper), speech = await speechKeyStatus(), voice = await resolveSpeechVoice().catch(() => undefined), model = await resolveSpeechModel(), region = await resolveSpeechRegion();
209
226
  // Chat needs Herdr or tmux; a plain project shell or agent over SSH does not.
210
227
  console.log(JSON.stringify({ ok: true, helper, herdr: muxes, terminal, checks: {
211
228
  privateSocket: true, protocol: true, independentHelper: true,
@@ -214,13 +231,13 @@ export async function runBridge(args, version) {
214
231
  shell: muxes.length > 0 ? "available" : "Neither Herdr nor tmux is available: chat is unavailable, project shells and agents still open over SSH",
215
232
  approvalPush: push.configured ? "configured" : "not configured",
216
233
  speechKey: speech.configured ? "configured" : "not configured", speechKeyDetail: speech.detail,
217
- ...(voice ? { speechVoice: `${voice.voice} (${voice.source})` } : {}), speechModel: `${model.model} (${model.source})`,
234
+ ...(voice ? { speechVoice: `${voice.voice} (${voice.source})` } : {}), speechModel: `${model.model} (${model.source})`, speechRegion: `${region.region} (${region.source})`,
218
235
  }, ...(push.warning ? { warnings: [push.warning] } : {}) }, null, 2));
219
236
  if (push.warning)
220
237
  console.error(`warning: ${push.warning}`);
221
238
  break;
222
239
  }
223
- default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|speech-key set|speech-voice|speech-model>");
240
+ default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|speech-key set|speech-voice|speech-model|speech-region>");
224
241
  }
225
242
  return 0;
226
243
  }
@@ -234,6 +251,7 @@ export function approvalPushCheck(helper) {
234
251
  }
235
252
  const SPEECH_VOICE_USAGE = "Usage: phren bridge speech-voice [show | set <elevenlabs-voice-id> | clear]";
236
253
  const SPEECH_MODEL_USAGE = "Usage: phren bridge speech-model [show | set <elevenlabs-model-id> | clear]";
254
+ const SPEECH_REGION_USAGE = "Usage: phren bridge speech-region [show | us | global]";
237
255
  const SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
238
256
  /** One line from stdin: piped as is, or typed at a prompt without echo. */
239
257
  async function readSecret(prompt) {
@@ -9,6 +9,7 @@ import { peerRequest, type HookPeer } from "./peers.js";
9
9
  import { type ApprovalDecision, type Json, type Provider, type Target } from "./protocol.js";
10
10
  import { type FinalTurn } from "./schedule-watch.js";
11
11
  import { type TurnRecord } from "./turn-records.js";
12
+ import { type Uncommitted } from "./worker-unfinished.js";
12
13
  export { truncateUtf8 } from "./turn-records.js";
13
14
  /**
14
15
  * The conductor's returns loop. The worker's computer answers what its
@@ -95,6 +96,12 @@ export interface WorkerObservation {
95
96
  stalled?: boolean;
96
97
  stalledSince?: string;
97
98
  stallFor?: number;
99
+ /** Why a turn that ended is not done (worker-unfinished.ts): it announced a
100
+ * next step, or left uncommitted work and no PR. Returned as needs-you. */
101
+ unfinished?: string;
102
+ /** The worker's checkout could not be read in time: the turn may be done,
103
+ * but it is not closed on that (worker-close.ts). */
104
+ unchecked?: true;
98
105
  }
99
106
  export interface WorkerReaders {
100
107
  snapshot: (server: string) => Promise<Json>;
@@ -112,6 +119,10 @@ export interface WorkerReaders {
112
119
  stall?: typeof sessionStalls.observe;
113
120
  /** The turn a Codex pane lost with its app-server, which no Stop will end. */
114
121
  lost?: (server: string, pane: string, session?: string) => LostTurn | undefined;
122
+ /** Tracked files with uncommitted changes in the worker's checkout. */
123
+ uncommitted?: (directory: string) => Promise<Uncommitted>;
124
+ /** Whether other panes' folders share the worker's checkout, whose changes then are not only its own. */
125
+ shared?: (directory: string, folders: readonly unknown[]) => Promise<boolean>;
115
126
  }
116
127
  export declare function paneTurn(server: string, pane: Json, source: Provider): Promise<TurnRecord | undefined>;
117
128
  /** The default readers with the approval reader of the Hook that runs the workers. */
@@ -19,6 +19,7 @@ import { liveWork } from "./session-activity.js";
19
19
  import { terminalProvider } from "./terminal.js";
20
20
  import { childAgentTree, runningChildAgents } from "./transcripts.js";
21
21
  import { opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
22
+ import { recentUncommitted, sharedCheckout, unfinishedTurn } from "./worker-unfinished.js";
22
23
  export { truncateUtf8 } from "./turn-records.js";
23
24
  /**
24
25
  * The conductor's returns loop. The worker's computer answers what its
@@ -67,8 +68,10 @@ const defaultReaders = {
67
68
  finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
68
69
  turn: paneTurn,
69
70
  children: (source, session) => childAgentTree(source, session).then(runningChildAgents).then(children => children.length),
70
- stall: (target, pane) => sessionStalls.observe(target, pane),
71
+ stall: (target, pane, live) => sessionStalls.observe(target, pane, live),
71
72
  lost: (server, pane, session) => codexServers.lostTurn(server, pane, session),
73
+ uncommitted: directory => recentUncommitted(directory),
74
+ shared: sharedCheckout,
72
75
  };
73
76
  /** The default readers with the approval reader of the Hook that runs the workers. */
74
77
  export const workerReaders = (approval) => ({ ...defaultReaders, approval });
@@ -125,6 +128,35 @@ async function fromTurn(record, session, status, source, readers) {
125
128
  ...(final?.completed && final.error ? { error: final.error } : {}),
126
129
  ...(phase.reply ? replyFields(phase.reply, phase.truncated) : replyFields(final?.lastAssistant)) };
127
130
  }
131
+ /** The live work a working pane's turn still waits on (`liveWork`), for the
132
+ * stall clock, which reads it only once it runs out: a worker whose only
133
+ * activity is an awaited background shell is waiting, not stalled. */
134
+ function liveReader(record, source, session, readers) {
135
+ return async () => {
136
+ const [final, children] = await Promise.all([
137
+ readers.finalTurn(source, session).catch(() => undefined),
138
+ readers.children ? readers.children(source, session).catch(() => 0) : Promise.resolve(0),
139
+ ]);
140
+ return liveWork(record, final, children, (readers.now ?? Date.now)());
141
+ };
142
+ }
143
+ /** A finished turn that announced a next step, or left uncommitted work in
144
+ * its checkout and no PR, is not done (worker-unfinished.ts). The checkout is
145
+ * where the agent was when it stopped, else the pane's folder, and it is asked
146
+ * only when it is the worker's own: a checkout another pane works in (the
147
+ * owner's, a sibling worker's) holds changes that are not the worker's. A
148
+ * truncated reply has lost its closing sentence, so only the checkout is asked
149
+ * then. */
150
+ async function unfinished(seen, directory, readers, s, pane, prs) {
151
+ if ((seen.state !== "done" && seen.state !== "idle") || !seen.completed || seen.error || seen.interrupted)
152
+ return {};
153
+ let folder = typeof directory === "string" && directory ? directory : undefined;
154
+ const others = objects(s.panes).filter(other => other.pane_id !== pane.pane_id).flatMap(other => [other.foreground_cwd, other.cwd]);
155
+ if (folder && readers.shared && await readers.shared(folder, others).catch(() => true))
156
+ folder = undefined;
157
+ return unfinishedTurn({ reply: seen.truncated ? undefined : seen.reply, prs, directory: folder }, readers.uncommitted);
158
+ }
159
+ const paneDirectory = (pane) => pane.foreground_cwd || pane.cwd;
128
160
  /** Receiving side: the state of each dispatched pane, from its agent's turn
129
161
  * record when its hooks wrote one, else from the shared snapshot and, once
130
162
  * the agent has stopped, the final reply in its transcript. */
@@ -176,13 +208,13 @@ export async function workerStates(input, readers = defaultReaders) {
176
208
  const seen = await fromTurn(own, own.session, status, target.source, readers);
177
209
  const full = targetSchema.safeParse({ ...target, session: seen.session });
178
210
  const prs = full.success && seen.state === "done" ? await workerPrs(full.data, own) : undefined;
179
- return { ...seen, ...(prs ? { prs } : {}), ...(full.success && seen.state === "working" ? await readers.stall?.(full.data, { ...pane, agent_status: "working" }) : {}) };
211
+ return { ...seen, ...(prs ? { prs } : {}), ...await unfinished(seen, own.stop?.cwd ?? paneDirectory(pane), readers, s, pane, prs), ...(full.success && seen.state === "working" ? await readers.stall?.(full.data, { ...pane, agent_status: "working" }, liveReader(own, target.source, own.session, readers)) : {}) };
180
212
  }
181
213
  const session = expected ?? current;
182
214
  const state = ["working", "idle", "done", "blocked"].find(value => value === status) ?? "unknown";
183
215
  if ((state !== "idle" && state !== "done") || !session) {
184
216
  const full = targetSchema.safeParse({ ...target, session });
185
- return { state, ...(session ? { session } : {}), ...(full.success && state === "working" ? await readers.stall?.(full.data, pane) : {}) };
217
+ return { state, ...(session ? { session } : {}), ...(full.success && state === "working" ? await readers.stall?.(full.data, pane, liveReader(undefined, target.source, full.data.session, readers)) : {}) };
186
218
  }
187
219
  const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
188
220
  const children = readers.children ? await readers.children(target.source, session).catch(() => 0) : 0;
@@ -193,8 +225,9 @@ export async function workerStates(input, readers = defaultReaders) {
193
225
  if (live) {
194
226
  return { state: "working", session, completed: true, background: live, ...(turn?.error ? { error: turn.error } : {}), ...replyFields(turn?.lastAssistant) };
195
227
  }
196
- return { state, session, completed: turn?.completed === true, ...(turn?.error ? { error: turn.error } : {}),
228
+ const seen = { state, session, completed: turn?.completed === true, ...(turn?.error ? { error: turn.error } : {}),
197
229
  ...(turn?.interrupted ? { interrupted: true } : {}), ...replyFields(turn?.lastAssistant) };
230
+ return { ...seen, ...await unfinished(seen, paneDirectory(pane), readers, s, pane) };
198
231
  }));
199
232
  // Only a conversation this dispatch named can be answered; a starting target has no session yet.
200
233
  return { workers: workers.map((seen, index) => {
@@ -212,7 +245,7 @@ const observationSchema = z.object({
212
245
  hook: z.boolean().optional(), endedAt: z.string().max(40).optional(), background: z.number().int().min(0).max(999).optional(),
213
246
  prs: prsSchema.optional(),
214
247
  stalled: z.boolean().optional(), stalledSince: z.string().datetime().optional(), stallFor: z.number().nonnegative().optional(),
215
- interrupted: z.boolean().optional(), approval: z.unknown().optional(),
248
+ interrupted: z.boolean().optional(), approval: z.unknown().optional(), unfinished: z.string().max(200).optional(), unchecked: z.boolean().optional(),
216
249
  }).passthrough();
217
250
  /** A worker's forwarded permission request as its Hook sent it; an invalid one is ignored, not a reason to drop the state. */
218
251
  const approvalObservation = z.object({
@@ -301,7 +334,9 @@ function observeState(receipt, parsed, now) {
301
334
  // A turn the harness ended on an error (a usage limit) failed, reply or not,
302
335
  // and so did one the owner interrupted in the worker's terminal.
303
336
  const failed = stopped && seen.completed && seen.error ? seen.error : stopped && seen.interrupted ? INTERRUPTED : undefined;
304
- const question = seen.completed && seen.reply && !failed ? ownerQuestion(seen.reply) : undefined;
337
+ // A turn that stopped mid-task needs a nudge, not a close: it returns as
338
+ // needs-you with the reason, never as done.
339
+ const question = failed || !seen.completed ? undefined : (seen.reply ? ownerQuestion(seen.reply) : undefined) ?? seen.unfinished;
305
340
  let next;
306
341
  if (seen.state === "gone")
307
342
  next = "gone";
@@ -323,7 +358,12 @@ function observeState(receipt, parsed, now) {
323
358
  const previous = receipt.worker?.state;
324
359
  // The same finished state with a different final reply is a new turn: the
325
360
  // worker took more work (a hand_off) and finished again between two polls.
326
- const repeated = previous === next && !(turn && receipt.returned?.turn && turn !== receipt.returned.turn);
361
+ // A finished turn is returned once: the same turn reading done on one poll
362
+ // and needs-you on the next (its checkout read late, or the owner committed
363
+ // its edits) is not a second return.
364
+ const finished = (state) => state === "done" || state === "needs-you";
365
+ const reread = finished(previous) && finished(next) && !!turn && receipt.returned?.turn === turn;
366
+ const repeated = reread || (previous === next && !(turn && receipt.returned?.turn && turn !== receipt.returned.turn));
327
367
  if (repeated) {
328
368
  if (receipt.worker && receipt.worker.sawWorking !== sawWorking) {
329
369
  receipt.worker.sawWorking = sawWorking;
@@ -389,13 +389,32 @@ export declare class DispatchService {
389
389
  private readonly identity?;
390
390
  private readonly local;
391
391
  private readonly settleIntervalMs;
392
+ /** One placement at a time: choosing a computer, saving the receipt and the
393
+ * launch request. Confirming the brief afterwards (up to a minute and a half
394
+ * for a slow starting pane) runs outside it, so other dispatches are not
395
+ * refused meanwhile; `placing` counts those launches toward their
396
+ * computer's load for the next `anywhere` choice. */
392
397
  private active;
398
+ private readonly placing;
393
399
  /** `local` is this computer as a dispatch destination (its own Hook's
394
400
  * socket); tests replace it so they never reach a real Hook. */
395
401
  constructor(identity?: DispatchIdentity | undefined, local?: () => DispatchHost, settleIntervalMs?: number);
396
402
  /** `originValue` is the local pane the request came from, as its agent's
397
403
  * Herdr variables name it; a pane without a running agent is left out. */
398
404
  dispatch(input: unknown, originValue?: unknown): Promise<Json>;
405
+ /** Launches placed on `computer` whose brief is still being confirmed. */
406
+ private inFlight;
407
+ /**
408
+ * A brief typed into a pane that has no conversation yet: typed once the
409
+ * pane reads ready, then confirmed by the conversation it starts. A brief
410
+ * the pane swallowed (still idle on its starting binding) is typed again,
411
+ * under its own delivery id, but only after `readyForRetry` finds the pane
412
+ * still idle there: a first brief that landed late is never typed twice.
413
+ * After BRIEF_TRIES the receipt carries a failed return yet stays watched
414
+ * (uncertain), so a brief that lands later still brings the worker's return.
415
+ * A Claude prompt left typed but unsubmitted is not typed again.
416
+ */
417
+ private typeIntoStarting;
399
418
  /**
400
419
  * A brief that went with the launch: wait for the worker's hook to confirm
401
420
  * it by dispatch id. A startup screen (folder trust, sign-in) holds the