@phren/cli 0.3.19 → 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 (76) hide show
  1. package/dist/bridge/agent-hooks.d.ts +38 -20
  2. package/dist/bridge/agent-hooks.js +100 -37
  3. package/dist/bridge/approval-summary.d.ts +4 -0
  4. package/dist/bridge/approval-summary.js +12 -1
  5. package/dist/bridge/changes.d.ts +4 -0
  6. package/dist/bridge/changes.js +25 -2
  7. package/dist/bridge/code-note.d.ts +1 -0
  8. package/dist/bridge/code-note.js +2 -2
  9. package/dist/bridge/codex-binary.d.ts +5 -0
  10. package/dist/bridge/codex-binary.js +7 -0
  11. package/dist/bridge/command.js +24 -6
  12. package/dist/bridge/dispatch-command.js +1 -1
  13. package/dist/bridge/dispatch-returns.d.ts +14 -2
  14. package/dist/bridge/dispatch-returns.js +72 -16
  15. package/dist/bridge/dispatch.d.ts +23 -0
  16. package/dist/bridge/dispatch.js +169 -8
  17. package/dist/bridge/folder-trust.d.ts +13 -3
  18. package/dist/bridge/folder-trust.js +42 -4
  19. package/dist/bridge/hand-off.js +2 -1
  20. package/dist/bridge/herdr.js +6 -5
  21. package/dist/bridge/hook-fast.d.ts +13 -1
  22. package/dist/bridge/hook-fast.js +17 -2
  23. package/dist/bridge/launch-brief.d.ts +3 -1
  24. package/dist/bridge/launch-brief.js +3 -1
  25. package/dist/bridge/memory-store.d.ts +7 -0
  26. package/dist/bridge/memory-store.js +37 -1
  27. package/dist/bridge/models.d.ts +11 -1
  28. package/dist/bridge/models.js +47 -2
  29. package/dist/bridge/schedule-format.d.ts +1 -1
  30. package/dist/bridge/schedule-format.js +1 -1
  31. package/dist/bridge/schedule-launch.js +5 -0
  32. package/dist/bridge/schedule-watch.d.ts +5 -2
  33. package/dist/bridge/schedule-watch.js +59 -20
  34. package/dist/bridge/server-launch.d.ts +26 -0
  35. package/dist/bridge/server-launch.js +122 -12
  36. package/dist/bridge/server-pane-routes.js +20 -13
  37. package/dist/bridge/server-routes.d.ts +5 -0
  38. package/dist/bridge/server-routes.js +2 -2
  39. package/dist/bridge/server-stream.js +12 -0
  40. package/dist/bridge/server.js +8 -3
  41. package/dist/bridge/session-activity.d.ts +6 -0
  42. package/dist/bridge/session-activity.js +16 -0
  43. package/dist/bridge/settings-switch.d.ts +7 -0
  44. package/dist/bridge/settings-switch.js +15 -0
  45. package/dist/bridge/speech-live.d.ts +45 -0
  46. package/dist/bridge/speech-live.js +413 -0
  47. package/dist/bridge/speech-transcribe.d.ts +13 -3
  48. package/dist/bridge/speech-transcribe.js +26 -8
  49. package/dist/bridge/speech-voice.d.ts +22 -1
  50. package/dist/bridge/speech-voice.js +20 -2
  51. package/dist/bridge/speech.d.ts +24 -4
  52. package/dist/bridge/speech.js +115 -14
  53. package/dist/bridge/stalls.d.ts +9 -2
  54. package/dist/bridge/stalls.js +20 -4
  55. package/dist/bridge/transcript-claude.js +39 -10
  56. package/dist/bridge/transcript-preview.d.ts +11 -1
  57. package/dist/bridge/transcript-preview.js +37 -11
  58. package/dist/bridge/transcripts.d.ts +2 -1
  59. package/dist/bridge/transcripts.js +7 -3
  60. package/dist/bridge/turn-records.d.ts +6 -3
  61. package/dist/bridge/turn-records.js +9 -4
  62. package/dist/bridge/usage.d.ts +1 -1
  63. package/dist/bridge/usage.js +4 -3
  64. package/dist/bridge/worker-close.js +3 -1
  65. package/dist/bridge/worker-unfinished.d.ts +43 -0
  66. package/dist/bridge/worker-unfinished.js +178 -0
  67. package/dist/bridge-hook.mjs +2458 -1351
  68. package/dist/cli-registry.js +3 -2
  69. package/dist/home-paths.d.ts +2 -0
  70. package/dist/home-paths.js +4 -0
  71. package/dist/modules/registry.js +2 -2
  72. package/dist/test-global-setup.js +2 -1
  73. package/dist/test-sandbox.d.ts +15 -0
  74. package/dist/test-sandbox.js +36 -0
  75. package/package.json +1 -1
  76. package/starter/global/skills/conductor/SKILL.md +2 -1
@@ -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) {
@@ -42,7 +42,7 @@ export async function runDispatch(args) {
42
42
  "parent-server": { type: "string" }, "parent-workspace": { type: "string" }, "parent-tab": { type: "string" }, "parent-pane": { type: "string" },
43
43
  } });
44
44
  if (positionals.length !== 2)
45
- throw new Error("Usage: phren dispatch <computer|anywhere> <project> --label <label> --prompt <brief> [--harness codex|claude|opencode] [--model <model>] [--effort minimal|low|medium|high|xhigh|max] [--account <id>] [--permission-mode supervised|auto-edits|auto|full-access] [explicit parent flags]");
45
+ throw new Error("Usage: phren dispatch <computer|anywhere> <project> --label <label> --prompt <brief> [--harness codex|claude|opencode|copilot] [--model <model>] [--effort minimal|low|medium|high|xhigh|max] [--account <id>] [--permission-mode supervised|auto-edits|auto|full-access] [explicit parent flags]");
46
46
  const parentValues = ["parent-provider", "parent-session", "parent-computer", "parent-server", "parent-workspace", "parent-tab", "parent-pane"];
47
47
  const hasParent = parentValues.some(key => values[key] !== undefined);
48
48
  const parent = hasParent ? {
@@ -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
@@ -84,8 +85,9 @@ export interface WorkerObservation {
84
85
  /** When the turn's Stop arrived, on the worker's clock; names the turn. */
85
86
  endedAt?: string;
86
87
  stopSeq?: number;
87
- /** Background tasks the harness still runs: waited on while `working`,
88
- * left running when `done` after BACKGROUND_WAIT_MS. */
88
+ /** Background tasks the harness still runs: waited on while `working`;
89
+ * when `done`, left running (after BACKGROUND_WAIT_MS, or not awaited), so
90
+ * the pane is not closed on them. */
89
91
  background?: number;
90
92
  /** The owner stopped the turn in the worker's terminal. */
91
93
  interrupted?: true;
@@ -95,6 +97,12 @@ export interface WorkerObservation {
95
97
  stalled?: boolean;
96
98
  stalledSince?: string;
97
99
  stallFor?: number;
100
+ /** Why a turn that ended is not done (worker-unfinished.ts): it announced a
101
+ * next step, or left uncommitted work and no PR. Returned as needs-you. */
102
+ unfinished?: string;
103
+ /** The worker's checkout could not be read in time: the turn may be done,
104
+ * but it is not closed on that (worker-close.ts). */
105
+ unchecked?: true;
98
106
  }
99
107
  export interface WorkerReaders {
100
108
  snapshot: (server: string) => Promise<Json>;
@@ -112,6 +120,10 @@ export interface WorkerReaders {
112
120
  stall?: typeof sessionStalls.observe;
113
121
  /** The turn a Codex pane lost with its app-server, which no Stop will end. */
114
122
  lost?: (server: string, pane: string, session?: string) => LostTurn | undefined;
123
+ /** Tracked files with uncommitted changes in the worker's checkout. */
124
+ uncommitted?: (directory: string) => Promise<Uncommitted>;
125
+ /** Whether other panes' folders share the worker's checkout, whose changes then are not only its own. */
126
+ shared?: (directory: string, folders: readonly unknown[]) => Promise<boolean>;
115
127
  }
116
128
  export declare function paneTurn(server: string, pane: Json, source: Provider): Promise<TurnRecord | undefined>;
117
129
  /** The default readers with the approval reader of the Hook that runs the workers. */
@@ -15,10 +15,11 @@ import { hookPeers, peerRequest } from "./peers.js";
15
15
  import { isLocalComputer } from "./dispatch-hosts.js";
16
16
  import { BridgeError, objects, startingTargetSchema, targetSchema } from "./protocol.js";
17
17
  import { ownerQuestion, readFinalTurn } from "./schedule-watch.js";
18
- import { liveWork } from "./session-activity.js";
18
+ import { liveWork, runningTasks } 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 { awaitedInReply, 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
@@ -64,11 +65,13 @@ const defaultReaders = {
64
65
  snapshot: server => sharedSnapshot(server, SNAPSHOT_AGE_MS),
65
66
  freshSnapshot: snapshot,
66
67
  identity: (server, pane) => paneIdentity(server, pane),
67
- finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
68
+ finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" || source === "copilot" ? 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 });
@@ -87,12 +90,20 @@ function replyFields(text, truncated) {
87
90
  const reply = truncateUtf8(text);
88
91
  return { reply: reply.text, ...(reply.truncated || truncated ? { truncated: true } : {}) };
89
92
  }
93
+ /** A finished turn's state with nothing awaited left (`liveWork`): working
94
+ * when its reply says it waits on a task that still runs (`awaitedInReply`),
95
+ * else done, carrying what still runs so its pane is not closed on it. */
96
+ function settled(reply, running) {
97
+ if (running && awaitedInReply(reply))
98
+ return { state: "working", background: running };
99
+ return { state: "done", ...(running ? { background: running } : {}) };
100
+ }
90
101
  /** A worker's state from its own turn events. Done means a Stop arrived after
91
102
  * the last submitted prompt with no live work left (see `liveWork`: awaited
92
- * shells plus running children, never a leftover idle shell); a prompt with no
93
- * Stop is still working, unless the pane is idle and the transcript shows the
94
- * owner interrupted it (no Stop comes then) or a finished turn whose Stop the
95
- * Hook never received. */
103
+ * shells plus running children, never a leftover idle shell, and `settled`); a
104
+ * prompt with no Stop is still working, unless the pane is idle and the
105
+ * transcript shows the owner interrupted it (no Stop comes then) or a
106
+ * finished turn whose Stop the Hook never received. */
96
107
  async function fromTurn(record, session, status, source, readers) {
97
108
  const base = { session, hook: true };
98
109
  if (status === "blocked")
@@ -116,15 +127,50 @@ async function fromTurn(record, session, status, source, readers) {
116
127
  const live = liveWork(record, final, children, now);
117
128
  if (live)
118
129
  return { state: "working", ...base, background: live };
119
- return { state: "done", ...base, completed: true, ...(final.error ? { error: final.error } : {}), ...replyFields(final.lastAssistant) };
130
+ const end = settled(final.lastAssistant, runningTasks(record, final, now));
131
+ if (end.state === "working")
132
+ return { ...end, ...base };
133
+ return { ...end, ...base, completed: true, ...(final.error ? { error: final.error } : {}), ...replyFields(final.lastAssistant) };
120
134
  }
121
135
  const live = liveWork(record, final, children, now);
122
136
  if (live)
123
137
  return { state: "working", ...base, background: live };
124
- return { state: "done", ...base, completed: true, endedAt: phase.at, stopSeq: record.stop?.seq,
138
+ const end = settled(phase.reply ?? final?.lastAssistant, runningTasks(record, final, now));
139
+ if (end.state === "working")
140
+ return { ...end, ...base };
141
+ return { ...end, ...base, completed: true, endedAt: phase.at, stopSeq: record.stop?.seq,
125
142
  ...(final?.completed && final.error ? { error: final.error } : {}),
126
143
  ...(phase.reply ? replyFields(phase.reply, phase.truncated) : replyFields(final?.lastAssistant)) };
127
144
  }
145
+ /** The live work a working pane's turn still waits on (`liveWork`), for the
146
+ * stall clock, which reads it only once it runs out: a worker whose only
147
+ * activity is an awaited background shell is waiting, not stalled. */
148
+ function liveReader(record, source, session, readers) {
149
+ return async () => {
150
+ const [final, children] = await Promise.all([
151
+ readers.finalTurn(source, session).catch(() => undefined),
152
+ readers.children ? readers.children(source, session).catch(() => 0) : Promise.resolve(0),
153
+ ]);
154
+ return liveWork(record, final, children, (readers.now ?? Date.now)());
155
+ };
156
+ }
157
+ /** A finished turn that announced a next step, or left uncommitted work in
158
+ * its checkout and no PR, is not done (worker-unfinished.ts). The checkout is
159
+ * where the agent was when it stopped, else the pane's folder, and it is asked
160
+ * only when it is the worker's own: a checkout another pane works in (the
161
+ * owner's, a sibling worker's) holds changes that are not the worker's. A
162
+ * truncated reply has lost its closing sentence, so only the checkout is asked
163
+ * then. */
164
+ async function unfinished(seen, directory, readers, s, pane, prs) {
165
+ if ((seen.state !== "done" && seen.state !== "idle") || !seen.completed || seen.error || seen.interrupted)
166
+ return {};
167
+ let folder = typeof directory === "string" && directory ? directory : undefined;
168
+ const others = objects(s.panes).filter(other => other.pane_id !== pane.pane_id).flatMap(other => [other.foreground_cwd, other.cwd]);
169
+ if (folder && readers.shared && await readers.shared(folder, others).catch(() => true))
170
+ folder = undefined;
171
+ return unfinishedTurn({ reply: seen.truncated ? undefined : seen.reply, prs, directory: folder }, readers.uncommitted);
172
+ }
173
+ const paneDirectory = (pane) => pane.foreground_cwd || pane.cwd;
128
174
  /** Receiving side: the state of each dispatched pane, from its agent's turn
129
175
  * record when its hooks wrote one, else from the shared snapshot and, once
130
176
  * the agent has stopped, the final reply in its transcript. */
@@ -176,25 +222,28 @@ export async function workerStates(input, readers = defaultReaders) {
176
222
  const seen = await fromTurn(own, own.session, status, target.source, readers);
177
223
  const full = targetSchema.safeParse({ ...target, session: seen.session });
178
224
  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" }) : {}) };
225
+ 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
226
  }
181
227
  const session = expected ?? current;
182
228
  const state = ["working", "idle", "done", "blocked"].find(value => value === status) ?? "unknown";
183
229
  if ((state !== "idle" && state !== "done") || !session) {
184
230
  const full = targetSchema.safeParse({ ...target, session });
185
- return { state, ...(session ? { session } : {}), ...(full.success && state === "working" ? await readers.stall?.(full.data, pane) : {}) };
231
+ return { state, ...(session ? { session } : {}), ...(full.success && state === "working" ? await readers.stall?.(full.data, pane, liveReader(undefined, target.source, full.data.session, readers)) : {}) };
186
232
  }
187
233
  const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
188
234
  const children = readers.children ? await readers.children(target.source, session).catch(() => 0) : 0;
189
235
  // A finished turn that left live work is still the worker's turn. With no
190
236
  // Stop record, the transcript's awaited shells and the running children are
191
237
  // all there is: a leftover shell alone does not hold it.
192
- const live = turn?.completed ? liveWork(undefined, turn, children, (readers.now ?? Date.now)()) : undefined;
238
+ const now = (readers.now ?? Date.now)();
239
+ const end = turn?.completed ? settled(turn.lastAssistant, runningTasks(undefined, turn, now)) : undefined;
240
+ const live = turn?.completed ? liveWork(undefined, turn, children, now) ?? (end?.state === "working" ? end.background : undefined) : undefined;
193
241
  if (live) {
194
242
  return { state: "working", session, completed: true, background: live, ...(turn?.error ? { error: turn.error } : {}), ...replyFields(turn?.lastAssistant) };
195
243
  }
196
- return { state, session, completed: turn?.completed === true, ...(turn?.error ? { error: turn.error } : {}),
244
+ const seen = { state, session, completed: turn?.completed === true, ...(end?.background ? { background: end.background } : {}), ...(turn?.error ? { error: turn.error } : {}),
197
245
  ...(turn?.interrupted ? { interrupted: true } : {}), ...replyFields(turn?.lastAssistant) };
246
+ return { ...seen, ...await unfinished(seen, paneDirectory(pane), readers, s, pane) };
198
247
  }));
199
248
  // Only a conversation this dispatch named can be answered; a starting target has no session yet.
200
249
  return { workers: workers.map((seen, index) => {
@@ -212,7 +261,7 @@ const observationSchema = z.object({
212
261
  hook: z.boolean().optional(), endedAt: z.string().max(40).optional(), background: z.number().int().min(0).max(999).optional(),
213
262
  prs: prsSchema.optional(),
214
263
  stalled: z.boolean().optional(), stalledSince: z.string().datetime().optional(), stallFor: z.number().nonnegative().optional(),
215
- interrupted: z.boolean().optional(), approval: z.unknown().optional(),
264
+ interrupted: z.boolean().optional(), approval: z.unknown().optional(), unfinished: z.string().max(200).optional(), unchecked: z.boolean().optional(),
216
265
  }).passthrough();
217
266
  /** A worker's forwarded permission request as its Hook sent it; an invalid one is ignored, not a reason to drop the state. */
218
267
  const approvalObservation = z.object({
@@ -301,7 +350,9 @@ function observeState(receipt, parsed, now) {
301
350
  // A turn the harness ended on an error (a usage limit) failed, reply or not,
302
351
  // and so did one the owner interrupted in the worker's terminal.
303
352
  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;
353
+ // A turn that stopped mid-task needs a nudge, not a close: it returns as
354
+ // needs-you with the reason, never as done.
355
+ const question = failed || !seen.completed ? undefined : (seen.reply ? ownerQuestion(seen.reply) : undefined) ?? seen.unfinished;
305
356
  let next;
306
357
  if (seen.state === "gone")
307
358
  next = "gone";
@@ -323,7 +374,12 @@ function observeState(receipt, parsed, now) {
323
374
  const previous = receipt.worker?.state;
324
375
  // The same finished state with a different final reply is a new turn: the
325
376
  // 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);
377
+ // A finished turn is returned once: the same turn reading done on one poll
378
+ // and needs-you on the next (its checkout read late, or the owner committed
379
+ // its edits) is not a second return.
380
+ const finished = (state) => state === "done" || state === "needs-you";
381
+ const reread = finished(previous) && finished(next) && !!turn && receipt.returned?.turn === turn;
382
+ const repeated = reread || (previous === next && !(turn && receipt.returned?.turn && turn !== receipt.returned.turn));
327
383
  if (repeated) {
328
384
  if (receipt.worker && receipt.worker.sawWorking !== sawWorking) {
329
385
  receipt.worker.sawWorking = sawWorking;
@@ -3,12 +3,15 @@ import { type DispatchHost } from "./dispatch-hosts.js";
3
3
  import { type Json, type Provider, type Target } from "./protocol.js";
4
4
  import { type BriefArrival } from "./launch-brief.js";
5
5
  export declare const projectName: z.ZodString;
6
+ /** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
7
+ export declare const DISPATCH_HARNESSES: readonly ["codex", "claude", "opencode", "copilot"];
6
8
  export declare const dispatchSchema: z.ZodObject<{
7
9
  computer: z.ZodUnion<readonly [z.ZodLiteral<"anywhere">, z.ZodString]>;
8
10
  project: z.ZodString;
9
11
  harness: z.ZodEnum<{
10
12
  claude: "claude";
11
13
  codex: "codex";
14
+ copilot: "copilot";
12
15
  opencode: "opencode";
13
16
  }>;
14
17
  model: z.ZodOptional<z.ZodString>;
@@ -97,6 +100,7 @@ declare const receiptSchema: z.ZodObject<{
97
100
  harness: z.ZodEnum<{
98
101
  claude: "claude";
99
102
  codex: "codex";
103
+ copilot: "copilot";
100
104
  opencode: "opencode";
101
105
  }>;
102
106
  model: z.ZodOptional<z.ZodString>;
@@ -389,13 +393,32 @@ export declare class DispatchService {
389
393
  private readonly identity?;
390
394
  private readonly local;
391
395
  private readonly settleIntervalMs;
396
+ /** One placement at a time: choosing a computer, saving the receipt and the
397
+ * launch request. Confirming the brief afterwards (up to a minute and a half
398
+ * for a slow starting pane) runs outside it, so other dispatches are not
399
+ * refused meanwhile; `placing` counts those launches toward their
400
+ * computer's load for the next `anywhere` choice. */
392
401
  private active;
402
+ private readonly placing;
393
403
  /** `local` is this computer as a dispatch destination (its own Hook's
394
404
  * socket); tests replace it so they never reach a real Hook. */
395
405
  constructor(identity?: DispatchIdentity | undefined, local?: () => DispatchHost, settleIntervalMs?: number);
396
406
  /** `originValue` is the local pane the request came from, as its agent's
397
407
  * Herdr variables name it; a pane without a running agent is left out. */
398
408
  dispatch(input: unknown, originValue?: unknown): Promise<Json>;
409
+ /** Launches placed on `computer` whose brief is still being confirmed. */
410
+ private inFlight;
411
+ /**
412
+ * A brief typed into a pane that has no conversation yet: typed once the
413
+ * pane reads ready, then confirmed by the conversation it starts. A brief
414
+ * the pane swallowed (still idle on its starting binding) is typed again,
415
+ * under its own delivery id, but only after `readyForRetry` finds the pane
416
+ * still idle there: a first brief that landed late is never typed twice.
417
+ * After BRIEF_TRIES the receipt carries a failed return yet stays watched
418
+ * (uncertain), so a brief that lands later still brings the worker's return.
419
+ * A Claude prompt left typed but unsubmitted is not typed again.
420
+ */
421
+ private typeIntoStarting;
399
422
  /**
400
423
  * A brief that went with the launch: wait for the worker's hook to confirm
401
424
  * it by dispatch id. A startup screen (folder trust, sign-in) holds the
@@ -23,15 +23,17 @@ import { hasUsable } from "./harnesses.js";
23
23
  import { arrivalSchema } from "./launch-brief.js";
24
24
  const text = (max) => z.string().min(1).max(max).refine(value => !!value.trim() && !/[\x00-\x1f\x7f]/.test(value));
25
25
  export const projectName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/);
26
+ /** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
27
+ export const DISPATCH_HARNESSES = ["codex", "claude", "opencode", "copilot"];
26
28
  export const dispatchSchema = z.object({
27
29
  computer: z.union([z.literal("anywhere"), computerName]).describe("Enrolled computer name, or anywhere for the least busy connected computer."),
28
30
  project: projectName.describe("Project slug registered on the receiving computer."),
29
- harness: z.enum(["codex", "claude", "opencode"]).describe("Agent harness on the receiving computer."),
31
+ harness: z.enum(DISPATCH_HARNESSES).describe("Agent harness on the receiving computer."),
30
32
  model: text(200).optional().describe("Explicit model, otherwise the remote harness default."),
31
33
  effort: z.enum(launchEfforts).optional().describe("Reasoning effort for the worker (minimal, low, medium, high, xhigh, max), otherwise the harness default."),
32
34
  account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
33
35
  .describe("Claude account id to run the worker under (default, or a slug from `phren bridge accounts`). anywhere only picks computers where that account is signed in; a named computer without it fails."),
34
- permissionMode: z.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude and Codex only); otherwise the receiving computer's own default."),
36
+ permissionMode: z.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude, Codex and Copilot; not OpenCode); otherwise the receiving computer's own default."),
35
37
  releaseActions: z.array(releaseAction).min(1).max(RELEASE_ACTIONS.length).optional()
36
38
  .describe("Release-type actions the brief asks the worker to do (merge, publish, deploy, app-store, github-admin). Ask-first projects refuse them from an agent unless the owner confirmed."),
37
39
  prompt: z.string().min(1).max(32768).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value)).describe("Worker brief, at most 32768 characters."),
@@ -291,6 +293,83 @@ async function sendBrief(peer, target, text, deliveryId) {
291
293
  }
292
294
  }
293
295
  }
296
+ /** The pane as the remote Hook lists it now, or undefined when it does not list it. */
297
+ async function listedPane(peer, place) {
298
+ const panes = await peer.request(`/v1/workspaces/panes?server=${encodeURIComponent(peer.server)}&groupId=${encodeURIComponent(String(place.workspace))}&childId=${encodeURIComponent(String(place.tab))}`).catch(() => undefined);
299
+ return (Array.isArray(panes?.panes) ? panes.panes : []).find((p) => p && typeof p === "object" && p.id === place.pane);
300
+ }
301
+ /** Tries of a brief typed into a starting pane before the dispatch fails. */
302
+ const BRIEF_TRIES = 2;
303
+ /** Looks, one settle interval apart, for a starting pane to read ready, and for a typed brief to show. */
304
+ const READY_LOOKS = 15;
305
+ const LANDED_LOOKS = 20;
306
+ /**
307
+ * A starting agent's terminal takes typed text only once its prompt is drawn,
308
+ * which Herdr reads as idle: text typed while it is still `unknown` can be
309
+ * swallowed with nothing to show for it (Mini w4E, 2026-09-30). Waits for that,
310
+ * at most READY_LOOKS. A startup screen is the owner's to answer; a pane the
311
+ * Hook does not list is not waited on.
312
+ */
313
+ async function readyForBrief(peer, target, intervalMs) {
314
+ for (let look = 0; look < READY_LOOKS; look++) {
315
+ const pane = await listedPane(peer, target);
316
+ const status = pane?.agentStatus;
317
+ if (!pane || ["idle", "done", "working"].includes(String(status)))
318
+ return;
319
+ if (status === "blocked" || status === "waiting")
320
+ throw new StartupScreen(String(status));
321
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
322
+ }
323
+ }
324
+ /**
325
+ * Before a brief is typed again. The first try can reach the agent after its
326
+ * landed window (a loaded machine starts the turn late), and a second copy
327
+ * would hand the worker its task twice, so the pane is read first. It is typed
328
+ * again only into a pane that still sits idle on the same starting binding with
329
+ * no conversation. A conversation, or the agent working, blocked, waiting or
330
+ * done, means it took the first brief; a pane the Hook does not list, on
331
+ * another binding or never classified, cannot be told, and nothing is typed.
332
+ */
333
+ async function readyForRetry(peer, target, intervalMs) {
334
+ for (let look = 0; look < READY_LOOKS; look++) {
335
+ if (look)
336
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
337
+ const pane = await listedPane(peer, target);
338
+ if (!pane)
339
+ return { state: "unknown" };
340
+ if (typeof pane.sessionId === "string" && pane.sessionId)
341
+ return { state: "arrived", session: pane.sessionId };
342
+ if (pane.starting === true && pane.startingToken !== target.startingToken)
343
+ return { state: "unknown" };
344
+ const status = String(pane.agentStatus);
345
+ if (status === "idle")
346
+ return { state: "ready" };
347
+ if (["working", "blocked", "waiting", "done"].includes(status))
348
+ return { state: "arrived" };
349
+ }
350
+ return { state: "unknown" };
351
+ }
352
+ /**
353
+ * Whether a brief typed into a starting pane reached its agent: a conversation
354
+ * appeared, or the agent went to work. Lost when the pane still sits idle on
355
+ * the same starting binding after LANDED_LOOKS; unknown when the Hook does not
356
+ * list the pane, or it no longer holds that binding.
357
+ */
358
+ async function briefLanded(peer, target, intervalMs) {
359
+ for (let look = 0; look < LANDED_LOOKS; look++) {
360
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
361
+ const pane = await listedPane(peer, target);
362
+ if (!pane)
363
+ return { state: "unknown" };
364
+ if (typeof pane.sessionId === "string" && pane.sessionId)
365
+ return { state: "arrived", session: pane.sessionId };
366
+ if (pane.starting === true && pane.startingToken !== target.startingToken)
367
+ return { state: "unknown" };
368
+ if (["working", "blocked", "waiting"].includes(String(pane.agentStatus)))
369
+ return { state: "arrived" };
370
+ }
371
+ return { state: "lost" };
372
+ }
294
373
  /** What the worker's own hooks reported for a brief that went with its
295
374
  * launch, or undefined when the receiving Hook has no such brief. */
296
375
  export async function arrivalOf(peer, id) {
@@ -325,7 +404,13 @@ export class DispatchService {
325
404
  identity;
326
405
  local;
327
406
  settleIntervalMs;
407
+ /** One placement at a time: choosing a computer, saving the receipt and the
408
+ * launch request. Confirming the brief afterwards (up to a minute and a half
409
+ * for a slow starting pane) runs outside it, so other dispatches are not
410
+ * refused meanwhile; `placing` counts those launches toward their
411
+ * computer's load for the next `anywhere` choice. */
328
412
  active = false;
413
+ placing = new Map();
329
414
  /** `local` is this computer as a dispatch destination (its own Hook's
330
415
  * socket); tests replace it so they never reach a real Hook. */
331
416
  constructor(identity, local = () => localHost(), settleIntervalMs = 1_000) {
@@ -338,10 +423,15 @@ export class DispatchService {
338
423
  async dispatch(input, originValue) {
339
424
  const data = dispatchSchema.parse(input);
340
425
  if (data.permissionMode && data.harness === "opencode")
341
- throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and Codex workers.");
426
+ throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
342
427
  if (this.active)
343
428
  throw new BridgeError(429, "A dispatch is already being placed. Try again after its receipt arrives.");
344
429
  this.active = true;
430
+ let holding = true, placed;
431
+ const release = () => { if (holding) {
432
+ holding = false;
433
+ this.active = false;
434
+ } };
345
435
  try {
346
436
  if (data.parent !== undefined || data.parentTarget !== undefined) {
347
437
  if (!this.identity)
@@ -400,7 +490,7 @@ export class DispatchService {
400
490
  });
401
491
  skipped.sort((a, b) => a.computer.localeCompare(b.computer));
402
492
  const selected = capable
403
- .sort((a, b) => a.working - b.working || a.peer.name.localeCompare(b.peer.name))[0];
493
+ .sort((a, b) => a.working + this.inFlight(a.peer.name) - b.working - this.inFlight(b.peer.name) || a.peer.name.localeCompare(b.peer.name))[0];
404
494
  peer = selected?.peer;
405
495
  remoteComputerID = selected?.computerId;
406
496
  if (!peer && spentSeen)
@@ -448,6 +538,10 @@ export class DispatchService {
448
538
  // The brief goes with the launch: a Hook that can start the harness
449
539
  // with it says so, and any other types it below.
450
540
  const launched = await peer.request(`/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`, { project: data.project, kind: data.harness, model: data.model, ...(data.effort ? { effort: data.effort } : {}), ...(data.account ? { account: data.account } : {}), ...(data.permissionMode ? { permissionMode: data.permissionMode } : {}), label: data.label, brief: { id: receipt.id, text: prompt } });
541
+ // Placed: the brief is confirmed outside the lock.
542
+ placed = peer.name;
543
+ this.placing.set(placed, this.inFlight(placed) + 1);
544
+ release();
451
545
  // An older Hook ignores the field and starts the worker in its own default mode.
452
546
  const ignored = data.permissionMode && launched.permissionMode !== data.permissionMode ? IGNORED_MODE : undefined;
453
547
  if (launched.briefLaunched === true) {
@@ -473,10 +567,14 @@ export class DispatchService {
473
567
  receipt.state = "sending";
474
568
  receipt.updatedAt = new Date().toISOString();
475
569
  await save(receipt);
476
- const result = await sendBrief(peer, receipt.target, prompt, `dispatch-${receipt.id}`);
477
- receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
570
+ if (!("starting" in target)) {
571
+ const result = await sendBrief(peer, target, prompt, `dispatch-${receipt.id}`);
572
+ receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
573
+ }
574
+ else
575
+ await this.typeIntoStarting(peer, receipt, target, prompt);
478
576
  if (ignored)
479
- receipt.error = ignored;
577
+ receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
480
578
  }
481
579
  catch (error) {
482
580
  if (error instanceof StartupScreen) {
@@ -497,7 +595,70 @@ export class DispatchService {
497
595
  return { ok: receipt.state === "accepted", ...receipt };
498
596
  }
499
597
  finally {
500
- this.active = false;
598
+ release();
599
+ if (placed) {
600
+ const left = this.inFlight(placed) - 1;
601
+ if (left > 0)
602
+ this.placing.set(placed, left);
603
+ else
604
+ this.placing.delete(placed);
605
+ }
606
+ }
607
+ }
608
+ /** Launches placed on `computer` whose brief is still being confirmed. */
609
+ inFlight(computer) { return this.placing.get(computer) ?? 0; }
610
+ /**
611
+ * A brief typed into a pane that has no conversation yet: typed once the
612
+ * pane reads ready, then confirmed by the conversation it starts. A brief
613
+ * the pane swallowed (still idle on its starting binding) is typed again,
614
+ * under its own delivery id, but only after `readyForRetry` finds the pane
615
+ * still idle there: a first brief that landed late is never typed twice.
616
+ * After BRIEF_TRIES the receipt carries a failed return yet stays watched
617
+ * (uncertain), so a brief that lands later still brings the worker's return.
618
+ * A Claude prompt left typed but unsubmitted is not typed again.
619
+ */
620
+ async typeIntoStarting(peer, receipt, target, prompt) {
621
+ const arrived = (session) => {
622
+ const full = session ? targetSchema.safeParse({ server: target.server, workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source, session }) : undefined;
623
+ if (full?.success)
624
+ receipt.target = full.data;
625
+ receipt.state = "accepted";
626
+ };
627
+ for (let attempt = 1;; attempt++) {
628
+ if (attempt === 1)
629
+ await readyForBrief(peer, target, this.settleIntervalMs);
630
+ else {
631
+ const before = await readyForRetry(peer, target, this.settleIntervalMs);
632
+ if (before.state === "arrived") {
633
+ arrived(before.session);
634
+ return;
635
+ }
636
+ if (before.state === "unknown") {
637
+ receipt.state = "uncertain";
638
+ receipt.error = `The brief typed into the new "${receipt.label}" pane on ${receipt.computer} did not show in time, and the pane can no longer be read as waiting for it, so it was not typed again. The Hook keeps watching the pane.`.slice(0, 500);
639
+ return;
640
+ }
641
+ }
642
+ const result = await sendBrief(peer, target, prompt, attempt === 1 ? `dispatch-${receipt.id}` : `dispatch-${receipt.id}-${attempt}`);
643
+ const sent = result.ok === true && result.deliveryUncertain !== true;
644
+ const landed = await briefLanded(peer, target, this.settleIntervalMs);
645
+ if (landed.state === "arrived") {
646
+ arrived(landed.session);
647
+ return;
648
+ }
649
+ if (landed.state === "unknown" || result.unsubmitted === true) {
650
+ receipt.state = sent ? "accepted" : "uncertain";
651
+ return;
652
+ }
653
+ logger.info("dispatch", `The brief for ${receipt.computer} ${receipt.label} did not reach the starting pane (try ${attempt} of ${BRIEF_TRIES}).`);
654
+ if (attempt < BRIEF_TRIES)
655
+ continue;
656
+ const error = `The brief typed into the new "${receipt.label}" pane on ${receipt.computer} never reached ${receipt.harness}: after ${BRIEF_TRIES} tries the pane still sits idle with no conversation. The pane is still open; hand the brief off to it or close it.`.slice(0, 500);
657
+ // Watched still: a brief that lands after all brings the worker's own return.
658
+ receipt.state = "uncertain";
659
+ receipt.error = error;
660
+ receipt.returned = { state: "failed", at: new Date().toISOString(), error, read: false };
661
+ return;
501
662
  }
502
663
  }
503
664
  /**