@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
@@ -61,32 +61,50 @@ export function publicAssistant(raw, source) {
61
61
  .filter(block => block.type === "text").map(block => String(block.text ?? "")).join("\n");
62
62
  return text.trim() || undefined;
63
63
  }
64
+ if (source === "copilot") {
65
+ // A sub-agent's messages carry its agentId; only the session's own reply counts.
66
+ const data = object(raw.data);
67
+ if (raw.type !== "assistant.message" || raw.agentId || typeof data.content !== "string")
68
+ return;
69
+ return data.content.trim() || undefined;
70
+ }
64
71
  return;
65
72
  }
66
73
  const FINAL_TURN_TAIL_BYTES = 512 * 1024;
67
74
  /** A turn's end as the harness writes it: Claude's end_turn reply or its
68
- * turn_duration record, Codex's task_complete, opencode's end_turn step. */
69
- function turnEnded(raw, source) {
75
+ * turn_duration record, Codex's task_complete, opencode's end_turn step.
76
+ * Copilot writes a turn_start/turn_end pair per model call, so its turn ends
77
+ * at the turn_end after the reply marked `final_answer` (`copilotFinal`). */
78
+ function turnEnded(raw, source, copilotFinal = false) {
70
79
  const payload = object(raw.payload), message = object(raw.message), data = object(raw.data);
71
80
  if (source === "claude")
72
81
  return (raw.type === "assistant" && message.stop_reason === "end_turn")
73
82
  || (raw.type === "system" && raw.subtype === "turn_duration");
74
83
  if (source === "codex")
75
84
  return raw.type === "event_msg" && ["task_complete", "task_completed"].includes(String(payload.type));
85
+ if (source === "copilot")
86
+ return raw.type === "session.error" || (raw.type === "assistant.turn_end" && !raw.agentId && copilotFinal);
76
87
  return data.stop_reason === "end_turn";
77
88
  }
78
89
  /** The error a turn ended on, when the harness records one: Codex's
79
- * task_complete carries `error.message` (a usage limit, a failed compaction). */
90
+ * task_complete carries `error.message` (a usage limit, a failed compaction),
91
+ * Copilot's session.error its `message`. */
80
92
  function turnError(raw, source) {
93
+ if (source === "copilot") {
94
+ const data = object(raw.data), message = raw.type === "session.error" && typeof data.message === "string" ? data.message.replace(/\s+/g, " ").trim() : "";
95
+ return message ? message.slice(0, 500) : raw.type === "session.error" ? "Copilot stopped on an error." : undefined;
96
+ }
81
97
  if (source !== "codex")
82
98
  return;
83
99
  const error = object(object(raw.payload).error), message = typeof error.message === "string" ? error.message.replace(/\s+/g, " ").trim() : "";
84
100
  return message ? message.slice(0, 500) : undefined;
85
101
  }
86
- /** The owner stopping a turn: Claude's interruption marker, Codex's aborted turn. */
102
+ /** The owner stopping a turn: Claude's interruption marker, Codex's aborted turn, Copilot's abort. */
87
103
  function turnInterrupted(raw, source) {
88
104
  if (source === "codex")
89
105
  return raw.type === "event_msg" && object(raw.payload).type === "turn_aborted";
106
+ if (source === "copilot")
107
+ return raw.type === "abort";
90
108
  if (source !== "claude" || raw.type !== "user")
91
109
  return false;
92
110
  const content = object(raw.message).content;
@@ -102,14 +120,25 @@ function turnInterrupted(raw, source) {
102
120
  * row, and may stay there with no new turn to deliver it. */
103
121
  /** A backgrounded command that runs until killed rather than finishing:
104
122
  * following a log, watching files, serving a dev build. Nobody waits on it. */
105
- export const ENDLESS_COMMAND = /\btail\s+(?:-[a-zA-Z]*[fF][a-zA-Z]*\b|--follow\b)|\bjournalctl\b[^|;&]*\s(?:-[a-zA-Z]*f[a-zA-Z]*\b|--follow\b)|\blog\s+stream\b|\blogcat\b|\bwatch\s|--watch\b|\binotifywait\b[^|;&]*\s-m\b|\bfswatch\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|serve|preview)\b|\bhttp\.server\b|\bsleep\s+infinity\b/;
123
+ export const ENDLESS_COMMAND = /\btail\s+(?:-[a-zA-Z]*[fF][a-zA-Z]*\b|--follow\b)|\bjournalctl\b[^|;&]*\s(?:-[a-zA-Z]*f[a-zA-Z]*\b|--follow\b)|\blog\s+stream\b|\blogcat\b|(?:^|[;&|(]|\b(?:sudo|nohup|exec)\s)\s*watch\s|--watch\b|\binotifywait\b[^|;&]*\s-m\b|\bfswatch\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|serve|preview)\b|\bhttp\.server\b|\bsleep\s+infinity\b/;
106
124
  function backgroundTasks(raw, running, finished, tail) {
107
125
  const result = object(raw.toolUseResult), blocks = objects(object(raw.message).content);
108
126
  if (raw.type === "assistant") {
109
127
  for (const block of blocks) {
110
128
  const input = object(block.input);
111
- if (block.type === "tool_use" && typeof block.id === "string" && input.run_in_background === true && typeof input.command === "string")
129
+ // A command can reach the background by outrunning its timeout too.
130
+ if (block.type === "tool_use" && typeof block.id === "string" && typeof input.command === "string")
112
131
  tail.commands.set(block.id, input.command.slice(0, 2_000));
132
+ // Reading a task's output, or naming it, is still waiting on it
133
+ // (ios-fast-voice2, 2026-10-01: the dispatcher's prompt came mid-run).
134
+ if (block.type === "tool_use" && tail.earlier.size) {
135
+ const named = JSON.stringify(block.input ?? {});
136
+ for (const id of tail.earlier)
137
+ if (named.includes(id)) {
138
+ tail.earlier.delete(id);
139
+ tail.awaited.add(id);
140
+ }
141
+ }
113
142
  }
114
143
  }
115
144
  const shell = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId : undefined;
@@ -120,15 +149,16 @@ function backgroundTasks(raw, running, finished, tail) {
120
149
  if (shell) {
121
150
  const call = blocks.find(block => block.type === "tool_result")?.tool_use_id;
122
151
  const command = typeof call === "string" ? tail.commands.get(call) : undefined;
123
- if (!command || !ENDLESS_COMMAND.test(command))
152
+ if (command && ENDLESS_COMMAND.test(command))
153
+ tail.endless.add(shell);
154
+ else
124
155
  tail.awaited.add(shell);
125
156
  }
126
157
  else if (monitor)
127
158
  tail.awaited.add(monitor);
128
- if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message)) {
129
- running.delete(result.task_id);
130
- tail.awaited.delete(result.task_id);
131
- }
159
+ const ended = (id) => { running.delete(id); tail.awaited.delete(id); tail.earlier.delete(id); tail.endless.delete(id); };
160
+ if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message))
161
+ ended(result.task_id);
132
162
  const content = object(raw.message).content, attachment = object(raw.attachment);
133
163
  const notices = [typeof content === "string" ? content : "", typeof attachment.prompt === "string" ? attachment.prompt : "",
134
164
  raw.type === "queue-operation" && typeof raw.content === "string" ? raw.content : ""];
@@ -137,8 +167,7 @@ function backgroundTasks(raw, running, finished, tail) {
137
167
  const id = /<task-id>([^<\s]{1,100})<\/task-id>/.exec(block)?.[1];
138
168
  if (!id || !/<status>(?:completed|failed|killed|stopped)<\/status>/.test(block))
139
169
  continue;
140
- running.delete(id);
141
- tail.awaited.delete(id);
170
+ ended(id);
142
171
  if (!finished.has(id) && typeof raw.timestamp === "string" && !Number.isNaN(Date.parse(raw.timestamp)))
143
172
  finished.set(id, raw.timestamp);
144
173
  }
@@ -146,8 +175,8 @@ function backgroundTasks(raw, running, finished, tail) {
146
175
  /** The last assistant reply in a transcript and whether its turn finished.
147
176
  * A person's message after the reply opens a new turn, so it clears both. */
148
177
  export function finalTurnFromLines(lines, source) {
149
- let completed = false, lastAssistant, error, interrupted = false;
150
- const running = new Set(), finished = new Map(), tail = { commands: new Map(), awaited: new Set() };
178
+ let completed = false, lastAssistant, error, interrupted = false, copilotFinal = false;
179
+ const running = new Set(), finished = new Map(), tail = { commands: new Map(), awaited: new Set(), earlier: new Set(), endless: new Set() };
151
180
  for (const line of lines) {
152
181
  if (!line.trim())
153
182
  continue;
@@ -162,9 +191,13 @@ export function finalTurnFromLines(lines, source) {
162
191
  if (source === "claude") {
163
192
  backgroundTasks(raw, running, finished, tail);
164
193
  // The owner moving on leaves what earlier turns started behind: a
165
- // shell still running from then is a leftover, not work in flight.
166
- if (ownerPrompt(raw))
194
+ // shell still running from then is a leftover, not work in flight,
195
+ // unless the agent looks at it again.
196
+ if (ownerPrompt(raw)) {
197
+ for (const id of tail.awaited)
198
+ tail.earlier.add(id);
167
199
  tail.awaited.clear();
200
+ }
168
201
  }
169
202
  if (turnInterrupted(raw, source)) {
170
203
  interrupted = true;
@@ -173,12 +206,14 @@ export function finalTurnFromLines(lines, source) {
173
206
  }
174
207
  const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta && typeof object(raw.message).content === "string"
175
208
  : source === "codex" ? raw.type === "response_item" && payload.type === "message" && payload.role === "user"
176
- : raw.type === "user/message";
209
+ : source === "copilot" ? raw.type === "user.message"
210
+ : raw.type === "user/message";
177
211
  if (userTurn) {
178
212
  completed = false;
179
213
  lastAssistant = undefined;
180
214
  error = undefined;
181
215
  interrupted = false;
216
+ copilotFinal = false;
182
217
  continue;
183
218
  }
184
219
  const text = publicAssistant(raw, source);
@@ -187,15 +222,19 @@ export function finalTurnFromLines(lines, source) {
187
222
  completed = false;
188
223
  interrupted = false;
189
224
  }
190
- if (turnEnded(raw, source)) {
225
+ if (source === "copilot" && raw.type === "assistant.message" && !raw.agentId)
226
+ copilotFinal = object(raw.data).phase === "final_answer";
227
+ if (turnEnded(raw, source, copilotFinal)) {
191
228
  completed = true;
192
229
  interrupted = false;
193
230
  error = turnError(raw, source);
231
+ copilotFinal = false;
194
232
  }
195
233
  }
196
234
  return { completed, ...(lastAssistant ? { lastAssistant } : {}), ...(completed && error ? { error } : {}),
197
235
  ...(interrupted ? { interrupted: true } : {}), ...(completed && running.size ? { background: running.size } : {}),
198
- ...(finished.size ? { finishedTasks: [...finished.values()] } : {}), ...(tail.awaited.size ? { awaited: tail.awaited.size } : {}) };
236
+ ...(finished.size ? { finishedTasks: [...finished.values()] } : {}), ...(tail.awaited.size ? { awaited: tail.awaited.size } : {}),
237
+ ...(completed && tail.endless.size ? { endless: tail.endless.size } : {}) };
199
238
  }
200
239
  /** A prompt the owner (or a dispatcher) typed, not a task's notification or
201
240
  * a teammate's message waking the session. */
@@ -1,5 +1,25 @@
1
1
  import { type HarnessInventory } from "./harnesses.js";
2
2
  import { type Json } from "./protocol.js";
3
+ /**
4
+ * phren agent's quick chat and resume: `mode: "chat"` starts it with no tools
5
+ * and its memory read up front (`--mode chat`); `resumeSession` continues a
6
+ * session's history (`--session <id>`). Resuming a chat in `mode: "agent"`
7
+ * promotes it: the same conversation with tools. An agent session that used
8
+ * tools cannot go back to a chat: its history holds tool calls and results,
9
+ * which a request with no tools may not carry (Anthropic refuses it with a
10
+ * 400), so it is refused here before any pane exists.
11
+ */
12
+ export declare function phrenLaunchArgs(kind: string, data: Json, store?: string): Promise<string[]>;
13
+ /** Whether a phren agent session's history, as its model sees it, holds a
14
+ * tool call or result: its event log (`<store>/.sessions`) folded as the
15
+ * agent folds it, so a span a compaction summary replaced counts as that
16
+ * summary. False when there is no readable log; phren agent says so itself. */
17
+ export declare function sessionUsedTools(session: string, store?: string): Promise<boolean>;
18
+ /** A model from phren agent's catalog (`/v1/models?source=phren`) is
19
+ * `<provider>/<model>`. phren agent reads an openai or openai-codex prefix off
20
+ * `--model` itself; the rest name their provider with `--provider`. Any other
21
+ * model (an OpenRouter id typed by hand) passes through as it is. */
22
+ export declare function phrenModelArgs(model: string): string[];
3
23
  /** The live conductor on this computer, as a target: the pane the Hook
4
24
  * recorded (docs/conductor-sets.md), or before any record, a pane named as a
5
25
  * conductor on any server, which is then recorded. `known` reuses a snapshot
@@ -34,7 +54,13 @@ export interface LaunchOptions {
34
54
  * Herdr's create calls do not return identifiers, so the new tab is found
35
55
  * by diffing snapshots; `agent.start` returns once Herdr has detected the
36
56
  * agent and it is ready for input, which can take most of `timeoutMs`.
57
+ * A `launchId` (a UUID the caller keeps for one intended launch) makes it
58
+ * idempotent: the same id again returns the first launch's pane while it is
59
+ * listed, with `reused: true`, instead of starting a second agent.
37
60
  */
38
61
  export declare function launchSession(server: string, data: Json, options?: LaunchOptions): Promise<Json>;
62
+ export declare const LAUNCH_ID_TTL_MS: number;
63
+ /** For tests: forget every remembered launch. */
64
+ export declare function resetLaunchIds(): void;
39
65
  export declare function workspaceAction(server: string, operation: string, data: Json): Promise<Json>;
40
66
  export {};
@@ -1,5 +1,6 @@
1
1
  import { markPaneClosed } from "./worker-close.js";
2
2
  import { mkdir, readFile } from "node:fs/promises";
3
+ import { phrenStoreRoot } from "./transcripts.js";
3
4
  import path from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { z } from "zod";
@@ -25,7 +26,7 @@ import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
25
26
  import { logger } from "../logger.js";
26
27
  import { JobRegistry } from "./job-registry.js";
27
28
  import { atomic, BridgeError, bridgeRoot, id, launchEfforts, objects, PERMISSION_MODES, provider } from "./protocol.js";
28
- import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags } from "./settings-switch.js";
29
+ import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags, copilotModeFlags } from "./settings-switch.js";
29
30
  /** Starting agents in Herdr from the phone: the launch route's harness
30
31
  * arguments, the conductor brief, and workspace, tab and pane actions. */
31
32
  const launchKinds = ["codex", "claude", "copilot", "opencode", "phren"];
@@ -61,6 +62,8 @@ function effortArgs(kind, effort) {
61
62
  return ["-c", `model_reasoning_effort=${effort}`];
62
63
  if (kind === "opencode")
63
64
  return ["--variant", effort];
65
+ if (kind === "copilot")
66
+ return ["--reasoning-effort", effort];
64
67
  // phren-agent takes low to xhigh, and max as xhigh.
65
68
  if (kind === "phren")
66
69
  return ["--reasoning", effort === "minimal" ? "low" : effort];
@@ -68,6 +71,66 @@ function effortArgs(kind, effort) {
68
71
  }
69
72
  /** phren's own agent runs as `phren agent`: the subcommand and its interactive TUI lead its arguments. */
70
73
  const PHREN_AGENT_ARGS = ["agent", "-i"];
74
+ /**
75
+ * phren agent's quick chat and resume: `mode: "chat"` starts it with no tools
76
+ * and its memory read up front (`--mode chat`); `resumeSession` continues a
77
+ * session's history (`--session <id>`). Resuming a chat in `mode: "agent"`
78
+ * promotes it: the same conversation with tools. An agent session that used
79
+ * tools cannot go back to a chat: its history holds tool calls and results,
80
+ * which a request with no tools may not carry (Anthropic refuses it with a
81
+ * 400), so it is refused here before any pane exists.
82
+ */
83
+ export async function phrenLaunchArgs(kind, data, store = phrenStoreRoot()) {
84
+ const mode = z.enum(["agent", "chat"]).optional().parse(data.mode ?? undefined);
85
+ const resume = data.resumeSession === undefined || data.resumeSession === null ? undefined
86
+ : z.string().uuid("resumeSession must be a phren agent session id.").parse(data.resumeSession);
87
+ if ((mode || resume) && kind !== "phren")
88
+ throw new BridgeError(400, "mode and resumeSession are for phren agent launches (kind phren).");
89
+ if (mode === "chat" && resume && await sessionUsedTools(resume, store)) {
90
+ throw new BridgeError(400, "This session used tools, so it can't continue as a quick chat. Resume it as an agent (mode agent).", { code: "chat-has-tools" });
91
+ }
92
+ return [...(mode === "chat" ? ["--mode", "chat"] : []), ...(resume ? ["--session", resume] : [])];
93
+ }
94
+ /** Whether a phren agent session's history, as its model sees it, holds a
95
+ * tool call or result: its event log (`<store>/.sessions`) folded as the
96
+ * agent folds it, so a span a compaction summary replaced counts as that
97
+ * summary. False when there is no readable log; phren agent says so itself. */
98
+ export async function sessionUsedTools(session, store = phrenStoreRoot()) {
99
+ const raw = await readFile(path.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
100
+ const withTools = (message) => {
101
+ const content = message?.content;
102
+ return Array.isArray(content) && content.some(block => ["tool_use", "tool_result"].includes(String(block?.type)));
103
+ };
104
+ const surface = new Map();
105
+ for (const line of raw.split("\n")) {
106
+ let event;
107
+ try {
108
+ event = JSON.parse(line);
109
+ }
110
+ catch {
111
+ continue;
112
+ }
113
+ if (typeof event.seq !== "number" || !event.data)
114
+ continue;
115
+ if (["user/message", "assistant/message", "tool/results"].includes(String(event.type)))
116
+ surface.set(event.seq, withTools(event.data.message));
117
+ else if (event.type === "log/replace" && typeof event.data.start === "number" && typeof event.data.end === "number") {
118
+ for (const seq of [...surface.keys()])
119
+ if (seq >= event.data.start && seq <= event.data.end)
120
+ surface.delete(seq);
121
+ surface.set(event.data.start, withTools(event.data.message));
122
+ }
123
+ }
124
+ return [...surface.values()].some(Boolean);
125
+ }
126
+ /** A model from phren agent's catalog (`/v1/models?source=phren`) is
127
+ * `<provider>/<model>`. phren agent reads an openai or openai-codex prefix off
128
+ * `--model` itself; the rest name their provider with `--provider`. Any other
129
+ * model (an OpenRouter id typed by hand) passes through as it is. */
130
+ export function phrenModelArgs(model) {
131
+ const match = /^(anthropic|deepseek|ollama|openrouter)\/(.+)$/.exec(model);
132
+ return match ? ["--provider", match[1], "--model", match[2]] : ["--model", model];
133
+ }
71
134
  async function prepareConductor(kind, effort, model) {
72
135
  const brief = await conductorBrief();
73
136
  const briefDirectory = path.join(bridgeRoot(), "conductor");
@@ -96,10 +159,9 @@ async function targetForPane(server, pane) {
96
159
  if (!provider.safeParse(pane.agent).success || !id.safeParse(pane.workspace_id).success || !id.safeParse(pane.tab_id).success || !id.safeParse(pane.pane_id).success)
97
160
  return undefined;
98
161
  const binding = { server, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent };
99
- const session = await paneIdentity(server, pane);
100
- if (session)
101
- return { ...binding, session };
102
- const chat = await paneChatState(server, pane).catch(() => ({}));
162
+ const chat = await paneChatState(server, pane, { tokenWhenIdentified: false }).catch(() => ({}));
163
+ if (typeof chat.sessionId === "string")
164
+ return { ...binding, session: chat.sessionId };
103
165
  return chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
104
166
  }
105
167
  /** The live conductor on this computer, as a target: the pane the Hook
@@ -229,8 +291,57 @@ async function requireAvailable(kind, account) {
229
291
  * Herdr's create calls do not return identifiers, so the new tab is found
230
292
  * by diffing snapshots; `agent.start` returns once Herdr has detected the
231
293
  * agent and it is ready for input, which can take most of `timeoutMs`.
294
+ * A `launchId` (a UUID the caller keeps for one intended launch) makes it
295
+ * idempotent: the same id again returns the first launch's pane while it is
296
+ * listed, with `reused: true`, instead of starting a second agent.
232
297
  */
233
298
  export async function launchSession(server, data, options = {}) {
299
+ const launchId = data.launchId === undefined || data.launchId === null ? undefined
300
+ : z.string().uuid("launchId must be a UUID.").parse(data.launchId);
301
+ if (!launchId)
302
+ return startSession(server, data, options);
303
+ const now = Date.now();
304
+ for (const [key, entry] of launchesById)
305
+ if (now - entry.at > LAUNCH_ID_TTL_MS)
306
+ launchesById.delete(key);
307
+ const key = `${server}\u0000${launchId}`;
308
+ const earlier = launchesById.get(key);
309
+ // Reserve the id before checking the old pane. Two retries after a closed
310
+ // chat must share its replacement, just as they share the initial launch.
311
+ const result = Promise.resolve().then(async () => {
312
+ if (earlier) {
313
+ const previous = await earlier.result;
314
+ if (await stillListed(server, previous))
315
+ return { ...previous, reused: true };
316
+ }
317
+ return startSession(server, data, options);
318
+ });
319
+ // An in-flight launch must not expire while another caller is waiting.
320
+ const entry = { at: Infinity, result };
321
+ launchesById.set(key, entry);
322
+ void result.then(() => { entry.at = Date.now(); }, () => {
323
+ if (launchesById.get(key) !== entry)
324
+ return;
325
+ // A temporary snapshot failure is not evidence that the old pane died.
326
+ if (earlier && Number.isFinite(earlier.at))
327
+ launchesById.set(key, earlier);
328
+ else
329
+ launchesById.delete(key);
330
+ });
331
+ return result;
332
+ }
333
+ /** Launches by the caller's `launchId`, for `LAUNCH_ID_TTL_MS`: a repeat
334
+ * joins the launch in flight or gets its pane back. In memory only. */
335
+ const launchesById = new Map();
336
+ export const LAUNCH_ID_TTL_MS = 10 * 60_000;
337
+ /** For tests: forget every remembered launch. */
338
+ export function resetLaunchIds() { launchesById.clear(); }
339
+ async function stillListed(server, result) {
340
+ const s = await snapshot(server);
341
+ return objects(s.tabs).some(t => t.tab_id === result.tabId && t.workspace_id === result.workspaceId)
342
+ && objects(s.panes).some(p => p.pane_id === result.paneId && p.tab_id === result.tabId && p.workspace_id === result.workspaceId);
343
+ }
344
+ async function startSession(server, data, options) {
234
345
  const role = z.enum(["agent", "conductor"]).default("agent").parse(data.role);
235
346
  const projectDirectory = z.string().min(1).max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
236
347
  const worktreeRequest = data.worktree === undefined || data.worktree === null ? undefined : launchWorktreeSchema.parse(data.worktree);
@@ -244,15 +355,14 @@ export async function launchSession(server, data, options = {}) {
244
355
  if (permissionMode && role === "conductor")
245
356
  throw new BridgeError(400, "A conductor starts with its own permissions; permissionMode is for workers.");
246
357
  if (permissionMode && kind === "opencode")
247
- throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and Codex workers.");
248
- if (permissionMode && kind === "copilot")
249
- throw new BridgeError(400, "Copilot takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
358
+ throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
250
359
  if (permissionMode && kind === "phren")
251
- throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
360
+ throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude, Codex and Copilot workers.");
252
361
  if (role === "conductor" && kind === "copilot")
253
362
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
254
363
  if (role === "conductor" && kind === "phren")
255
364
  throw new BridgeError(400, PHREN_NO_CONDUCTOR);
365
+ const phrenArgs = await phrenLaunchArgs(kind, data);
256
366
  // A dispatched worker's or scheduled run's first prompt. It rides on the
257
367
  // launch where the harness takes one; elsewhere the caller types it.
258
368
  const brief = data.brief === undefined || data.brief === null ? undefined : launchBriefSchema.parse(data.brief);
@@ -269,7 +379,7 @@ export async function launchSession(server, data, options = {}) {
269
379
  const wanted = options.canary ? "phren-canary" : role === "conductor" ? (isConductorName(baseName) ? baseName : herdrAgentName(`conductor-${baseName}`))
270
380
  : isConductorName(baseName) ? herdrAgentName(`worker-${baseName}`) : baseName;
271
381
  const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : undefined;
272
- const modelFlag = { codex: "--model", claude: "--model", opencode: "--model", phren: "--model" };
382
+ const modelFlag = { codex: "--model", claude: "--model", opencode: "--model", copilot: "--model", phren: "--model" };
273
383
  let workspace = data.workspaceId === undefined ? undefined : id.parse(data.workspaceId);
274
384
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
275
385
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
@@ -293,8 +403,8 @@ export async function launchSession(server, data, options = {}) {
293
403
  if (conductorHere && conductorHere.workspace_id === workspace)
294
404
  workspace = undefined;
295
405
  const args = role === "conductor" ? await prepareConductor(kind, effort, model)
296
- : [...(kind === "phren" ? PHREN_AGENT_ARGS : []), ...(model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
297
- ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : [])];
406
+ : [...(kind === "phren" ? [...PHREN_AGENT_ARGS, ...phrenArgs] : []), ...(model && kind === "phren" ? phrenModelArgs(model) : model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
407
+ ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : []), ...(permissionMode && kind === "copilot" ? copilotModeFlags(permissionMode) : [])];
298
408
  // A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
299
409
  // pane joins the thread the Hook started, and the brief is that thread's
300
410
  // first turn. The typed arguments below stay the fallback.
@@ -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") {
@@ -108,15 +108,20 @@ export declare const capabilities: {
108
108
  overviewStream: boolean;
109
109
  speech: boolean;
110
110
  speechTimestamps: boolean;
111
+ speechTimestampStream: boolean;
112
+ speechLive: boolean;
111
113
  speechVoices: boolean;
112
114
  speechFormats: ("mp3_44100_128" | "mp3_44100_192" | "pcm_24000" | "pcm_44100")[];
113
115
  transcribe: boolean;
114
116
  memoryStore: boolean;
115
117
  promptOnce: boolean;
116
118
  promptStatus: boolean;
119
+ deliveryFrames: boolean;
117
120
  resources: boolean;
118
121
  sudo: boolean;
119
122
  sudoOutcome: boolean;
123
+ previewDeltas: boolean;
124
+ quickChat: boolean;
120
125
  };
121
126
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
122
127
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -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, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, resources: true, sudo: true, sudoOutcome: 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)));
@@ -183,7 +183,7 @@ export function workspacesReader(ctx) {
183
183
  markBackground(tab, background);
184
184
  const target = targetSchema.safeParse(tab.target);
185
185
  if (target.success && agents.length === 1)
186
- Object.assign(tab, await sessionStalls.observe(target.data, { ...agents[0], agent_status: tab.agentStatus }));
186
+ Object.assign(tab, await sessionStalls.observe(target.data, { ...agents[0], agent_status: tab.agentStatus }, async () => background));
187
187
  tab.title = title;
188
188
  }));
189
189
  let nextTab = 0;
@@ -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) {
@@ -16,7 +16,8 @@ import { createServer } from "node:http";
16
16
  import { cpus, hostname, loadavg } from "node:os";
17
17
  import path from "node:path";
18
18
  import { WebSocketServer } from "ws";
19
- import { relayTranscription } from "./speech-transcribe.js";
19
+ import { relayLiveSpeech } from "./speech-live.js";
20
+ import { failRelay, relayTranscription } from "./speech-transcribe.js";
20
21
  import { ActivityJournal } from "./activity.js";
21
22
  import { countTick } from "./metrics.js";
22
23
  import { AgentHooks } from "./agent-hooks.js";
@@ -217,7 +218,7 @@ export async function serve(version, options = {}) {
217
218
  http.on("upgrade", (request, socket, head) => {
218
219
  try {
219
220
  const url = new URL(request.url || "/", "http://phren.local");
220
- if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe"].includes(url.pathname) || url.origin !== "http://phren.local") {
221
+ if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live"].includes(url.pathname) || url.origin !== "http://phren.local") {
221
222
  socket.destroy();
222
223
  return;
223
224
  }
@@ -236,7 +237,11 @@ export async function serve(version, options = {}) {
236
237
  return;
237
238
  }
238
239
  if (url.pathname === "/v1/speech/transcribe") {
239
- void relayTranscription(client, url.searchParams).catch(() => client.close(1011, "Transcription unavailable"));
240
+ void relayTranscription(client, url.searchParams).catch(() => failRelay(client));
241
+ return;
242
+ }
243
+ if (url.pathname === "/v1/speech/live") {
244
+ void relayLiveSpeech(client, url.searchParams).catch(() => client.close(1011, "Spoken replies unavailable"));
240
245
  return;
241
246
  }
242
247
  void stream(client, url).catch(() => client.close(1011, "Conversation unavailable; refresh"));
@@ -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