@phren/cli 0.3.19 → 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 (43) hide show
  1. package/dist/bridge/agent-hooks.d.ts +16 -1
  2. package/dist/bridge/agent-hooks.js +51 -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/hook-fast.d.ts +13 -1
  11. package/dist/bridge/hook-fast.js +17 -2
  12. package/dist/bridge/models.d.ts +11 -1
  13. package/dist/bridge/models.js +47 -2
  14. package/dist/bridge/server-launch.d.ts +20 -0
  15. package/dist/bridge/server-launch.js +63 -1
  16. package/dist/bridge/server-routes.d.ts +4 -0
  17. package/dist/bridge/server-routes.js +2 -2
  18. package/dist/bridge/server.js +6 -1
  19. package/dist/bridge/speech-live.d.ts +45 -0
  20. package/dist/bridge/speech-live.js +413 -0
  21. package/dist/bridge/speech-transcribe.d.ts +5 -2
  22. package/dist/bridge/speech-transcribe.js +8 -5
  23. package/dist/bridge/speech-voice.d.ts +22 -1
  24. package/dist/bridge/speech-voice.js +20 -2
  25. package/dist/bridge/speech.d.ts +24 -4
  26. package/dist/bridge/speech.js +115 -14
  27. package/dist/bridge/stalls.d.ts +9 -2
  28. package/dist/bridge/stalls.js +20 -4
  29. package/dist/bridge/transcript-preview.d.ts +11 -1
  30. package/dist/bridge/transcript-preview.js +37 -11
  31. package/dist/bridge/transcripts.d.ts +2 -1
  32. package/dist/bridge/transcripts.js +7 -3
  33. package/dist/bridge/turn-records.d.ts +6 -3
  34. package/dist/bridge/turn-records.js +9 -4
  35. package/dist/bridge/usage.d.ts +1 -1
  36. package/dist/bridge/usage.js +4 -3
  37. package/dist/bridge/worker-close.js +2 -1
  38. package/dist/bridge/worker-unfinished.d.ts +37 -0
  39. package/dist/bridge/worker-unfinished.js +145 -0
  40. package/dist/bridge-hook.mjs +2001 -1130
  41. package/dist/cli-registry.js +2 -1
  42. package/dist/modules/registry.js +2 -2
  43. package/package.json +1 -1
@@ -291,6 +291,83 @@ async function sendBrief(peer, target, text, deliveryId) {
291
291
  }
292
292
  }
293
293
  }
294
+ /** The pane as the remote Hook lists it now, or undefined when it does not list it. */
295
+ async function listedPane(peer, place) {
296
+ const panes = await peer.request(`/v1/workspaces/panes?server=${encodeURIComponent(peer.server)}&groupId=${encodeURIComponent(String(place.workspace))}&childId=${encodeURIComponent(String(place.tab))}`).catch(() => undefined);
297
+ return (Array.isArray(panes?.panes) ? panes.panes : []).find((p) => p && typeof p === "object" && p.id === place.pane);
298
+ }
299
+ /** Tries of a brief typed into a starting pane before the dispatch fails. */
300
+ const BRIEF_TRIES = 2;
301
+ /** Looks, one settle interval apart, for a starting pane to read ready, and for a typed brief to show. */
302
+ const READY_LOOKS = 15;
303
+ const LANDED_LOOKS = 20;
304
+ /**
305
+ * A starting agent's terminal takes typed text only once its prompt is drawn,
306
+ * which Herdr reads as idle: text typed while it is still `unknown` can be
307
+ * swallowed with nothing to show for it (Mini w4E, 2026-09-30). Waits for that,
308
+ * at most READY_LOOKS. A startup screen is the owner's to answer; a pane the
309
+ * Hook does not list is not waited on.
310
+ */
311
+ async function readyForBrief(peer, target, intervalMs) {
312
+ for (let look = 0; look < READY_LOOKS; look++) {
313
+ const pane = await listedPane(peer, target);
314
+ const status = pane?.agentStatus;
315
+ if (!pane || ["idle", "done", "working"].includes(String(status)))
316
+ return;
317
+ if (status === "blocked" || status === "waiting")
318
+ throw new StartupScreen(String(status));
319
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
320
+ }
321
+ }
322
+ /**
323
+ * Before a brief is typed again. The first try can reach the agent after its
324
+ * landed window (a loaded machine starts the turn late), and a second copy
325
+ * would hand the worker its task twice, so the pane is read first. It is typed
326
+ * again only into a pane that still sits idle on the same starting binding with
327
+ * no conversation. A conversation, or the agent working, blocked, waiting or
328
+ * done, means it took the first brief; a pane the Hook does not list, on
329
+ * another binding or never classified, cannot be told, and nothing is typed.
330
+ */
331
+ async function readyForRetry(peer, target, intervalMs) {
332
+ for (let look = 0; look < READY_LOOKS; look++) {
333
+ if (look)
334
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
335
+ const pane = await listedPane(peer, target);
336
+ if (!pane)
337
+ return { state: "unknown" };
338
+ if (typeof pane.sessionId === "string" && pane.sessionId)
339
+ return { state: "arrived", session: pane.sessionId };
340
+ if (pane.starting === true && pane.startingToken !== target.startingToken)
341
+ return { state: "unknown" };
342
+ const status = String(pane.agentStatus);
343
+ if (status === "idle")
344
+ return { state: "ready" };
345
+ if (["working", "blocked", "waiting", "done"].includes(status))
346
+ return { state: "arrived" };
347
+ }
348
+ return { state: "unknown" };
349
+ }
350
+ /**
351
+ * Whether a brief typed into a starting pane reached its agent: a conversation
352
+ * appeared, or the agent went to work. Lost when the pane still sits idle on
353
+ * the same starting binding after LANDED_LOOKS; unknown when the Hook does not
354
+ * list the pane, or it no longer holds that binding.
355
+ */
356
+ async function briefLanded(peer, target, intervalMs) {
357
+ for (let look = 0; look < LANDED_LOOKS; look++) {
358
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
359
+ const pane = await listedPane(peer, target);
360
+ if (!pane)
361
+ return { state: "unknown" };
362
+ if (typeof pane.sessionId === "string" && pane.sessionId)
363
+ return { state: "arrived", session: pane.sessionId };
364
+ if (pane.starting === true && pane.startingToken !== target.startingToken)
365
+ return { state: "unknown" };
366
+ if (["working", "blocked", "waiting"].includes(String(pane.agentStatus)))
367
+ return { state: "arrived" };
368
+ }
369
+ return { state: "lost" };
370
+ }
294
371
  /** What the worker's own hooks reported for a brief that went with its
295
372
  * launch, or undefined when the receiving Hook has no such brief. */
296
373
  export async function arrivalOf(peer, id) {
@@ -325,7 +402,13 @@ export class DispatchService {
325
402
  identity;
326
403
  local;
327
404
  settleIntervalMs;
405
+ /** One placement at a time: choosing a computer, saving the receipt and the
406
+ * launch request. Confirming the brief afterwards (up to a minute and a half
407
+ * for a slow starting pane) runs outside it, so other dispatches are not
408
+ * refused meanwhile; `placing` counts those launches toward their
409
+ * computer's load for the next `anywhere` choice. */
328
410
  active = false;
411
+ placing = new Map();
329
412
  /** `local` is this computer as a dispatch destination (its own Hook's
330
413
  * socket); tests replace it so they never reach a real Hook. */
331
414
  constructor(identity, local = () => localHost(), settleIntervalMs = 1_000) {
@@ -342,6 +425,11 @@ export class DispatchService {
342
425
  if (this.active)
343
426
  throw new BridgeError(429, "A dispatch is already being placed. Try again after its receipt arrives.");
344
427
  this.active = true;
428
+ let holding = true, placed;
429
+ const release = () => { if (holding) {
430
+ holding = false;
431
+ this.active = false;
432
+ } };
345
433
  try {
346
434
  if (data.parent !== undefined || data.parentTarget !== undefined) {
347
435
  if (!this.identity)
@@ -400,7 +488,7 @@ export class DispatchService {
400
488
  });
401
489
  skipped.sort((a, b) => a.computer.localeCompare(b.computer));
402
490
  const selected = capable
403
- .sort((a, b) => a.working - b.working || a.peer.name.localeCompare(b.peer.name))[0];
491
+ .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
492
  peer = selected?.peer;
405
493
  remoteComputerID = selected?.computerId;
406
494
  if (!peer && spentSeen)
@@ -448,6 +536,10 @@ export class DispatchService {
448
536
  // The brief goes with the launch: a Hook that can start the harness
449
537
  // with it says so, and any other types it below.
450
538
  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 } });
539
+ // Placed: the brief is confirmed outside the lock.
540
+ placed = peer.name;
541
+ this.placing.set(placed, this.inFlight(placed) + 1);
542
+ release();
451
543
  // An older Hook ignores the field and starts the worker in its own default mode.
452
544
  const ignored = data.permissionMode && launched.permissionMode !== data.permissionMode ? IGNORED_MODE : undefined;
453
545
  if (launched.briefLaunched === true) {
@@ -473,10 +565,14 @@ export class DispatchService {
473
565
  receipt.state = "sending";
474
566
  receipt.updatedAt = new Date().toISOString();
475
567
  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";
568
+ if (!("starting" in target)) {
569
+ const result = await sendBrief(peer, target, prompt, `dispatch-${receipt.id}`);
570
+ receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
571
+ }
572
+ else
573
+ await this.typeIntoStarting(peer, receipt, target, prompt);
478
574
  if (ignored)
479
- receipt.error = ignored;
575
+ receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
480
576
  }
481
577
  catch (error) {
482
578
  if (error instanceof StartupScreen) {
@@ -497,7 +593,70 @@ export class DispatchService {
497
593
  return { ok: receipt.state === "accepted", ...receipt };
498
594
  }
499
595
  finally {
500
- this.active = false;
596
+ release();
597
+ if (placed) {
598
+ const left = this.inFlight(placed) - 1;
599
+ if (left > 0)
600
+ this.placing.set(placed, left);
601
+ else
602
+ this.placing.delete(placed);
603
+ }
604
+ }
605
+ }
606
+ /** Launches placed on `computer` whose brief is still being confirmed. */
607
+ inFlight(computer) { return this.placing.get(computer) ?? 0; }
608
+ /**
609
+ * A brief typed into a pane that has no conversation yet: typed once the
610
+ * pane reads ready, then confirmed by the conversation it starts. A brief
611
+ * the pane swallowed (still idle on its starting binding) is typed again,
612
+ * under its own delivery id, but only after `readyForRetry` finds the pane
613
+ * still idle there: a first brief that landed late is never typed twice.
614
+ * After BRIEF_TRIES the receipt carries a failed return yet stays watched
615
+ * (uncertain), so a brief that lands later still brings the worker's return.
616
+ * A Claude prompt left typed but unsubmitted is not typed again.
617
+ */
618
+ async typeIntoStarting(peer, receipt, target, prompt) {
619
+ const arrived = (session) => {
620
+ const full = session ? targetSchema.safeParse({ server: target.server, workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source, session }) : undefined;
621
+ if (full?.success)
622
+ receipt.target = full.data;
623
+ receipt.state = "accepted";
624
+ };
625
+ for (let attempt = 1;; attempt++) {
626
+ if (attempt === 1)
627
+ await readyForBrief(peer, target, this.settleIntervalMs);
628
+ else {
629
+ const before = await readyForRetry(peer, target, this.settleIntervalMs);
630
+ if (before.state === "arrived") {
631
+ arrived(before.session);
632
+ return;
633
+ }
634
+ if (before.state === "unknown") {
635
+ receipt.state = "uncertain";
636
+ 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);
637
+ return;
638
+ }
639
+ }
640
+ const result = await sendBrief(peer, target, prompt, attempt === 1 ? `dispatch-${receipt.id}` : `dispatch-${receipt.id}-${attempt}`);
641
+ const sent = result.ok === true && result.deliveryUncertain !== true;
642
+ const landed = await briefLanded(peer, target, this.settleIntervalMs);
643
+ if (landed.state === "arrived") {
644
+ arrived(landed.session);
645
+ return;
646
+ }
647
+ if (landed.state === "unknown" || result.unsubmitted === true) {
648
+ receipt.state = sent ? "accepted" : "uncertain";
649
+ return;
650
+ }
651
+ logger.info("dispatch", `The brief for ${receipt.computer} ${receipt.label} did not reach the starting pane (try ${attempt} of ${BRIEF_TRIES}).`);
652
+ if (attempt < BRIEF_TRIES)
653
+ continue;
654
+ 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);
655
+ // Watched still: a brief that lands after all brings the worker's own return.
656
+ receipt.state = "uncertain";
657
+ receipt.error = error;
658
+ receipt.returned = { state: "failed", at: new Date().toISOString(), error, read: false };
659
+ return;
501
660
  }
502
661
  }
503
662
  /**
@@ -1,4 +1,16 @@
1
1
  /** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
2
2
  export declare const FAST_HOOK_FILE = "claude-hook.mjs";
3
3
  export declare const fastHookPath: (versionDir: string) => string;
4
- export declare const FAST_HOOK_SOURCE = "// Installed by Phren Hook: Claude Code's hook events, forwarded to the running Hook.\nimport { request } from \"node:http\";\nimport { homedir } from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nconst env = process.env, source = process.argv[2];\nasync function full() {\n const bundle = path.join(path.dirname(fileURLToPath(import.meta.url)), \"bridge-hook.mjs\");\n process.argv = [process.argv[0], bundle, \"hook\", source];\n await import(pathToFileURL(bundle).href);\n}\nfunction herdrPane() {\n if (!env.HERDR_SOCKET_PATH) return undefined;\n const socket = path.resolve(env.HERDR_SOCKET_PATH), root = path.resolve(env.PHREN_HERDR_HOME || path.join(homedir(), \".config/herdr\"));\n const server = socket === path.join(root, \"herdr.sock\") ? \"default\"\n : socket.startsWith(path.join(root, \"sessions\") + path.sep) ? path.basename(path.dirname(socket)) : undefined;\n const { HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane } = env;\n return server && workspace && tab && pane ? { server, workspace, tab, pane } : undefined;\n}\nconst plain = value => value && typeof value === \"object\" && !Array.isArray(value) ? value : {};\nasync function forward(place) {\n let input = \"\";\n for await (const chunk of process.stdin) { input += chunk.toString(); if (input.length > 1_048_576) return; }\n const value = plain(JSON.parse(input));\n if (value.agent_id || value.agentId || value.isSidechain || value.is_sidechain) return;\n const target = { ...place, source, session: value.session_id || value.sessionId };\n const event = String(value.hook_event_name || \"SessionStart\");\n const dispatchId = (event === \"SessionStart\" || event === \"UserPromptSubmit\") && /^[A-Za-z0-9_-]{8,64}$/.test(env.PHREN_DISPATCH_ID ?? \"\") ? env.PHREN_DISPATCH_ID : undefined;\n const tasks = Array.isArray(value.background_tasks)\n ? value.background_tasks.filter(task => ![\"completed\", \"failed\", \"killed\", \"stopped\"].includes(String(plain(task).status))) : undefined;\n const stop = event !== \"Stop\" ? {} : { ...(tasks ? { background: tasks.length } : {}),\n ...(typeof value.last_assistant_message === \"string\" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };\n const data = JSON.stringify({ target, event, ...(dispatchId ? { dispatchId } : {}),\n tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,\n ...(event === \"UserPromptSubmit\" && typeof value.prompt === \"string\" ? { prompt: value.prompt.slice(0, 65_536) } : {}), ...stop });\n const socketPath = path.join(env.PHREN_BRIDGE_HOME || path.join(homedir(), \".local/share/phren/bridge\"), \"agent.sock\");\n await new Promise(resolve => {\n const req = request({ socketPath, path: \"/hook\", method: \"POST\", timeout: event === \"PermissionRequest\" ? 58_000 : event.endsWith(\"ToolUse\") ? 8_000 : 12_000,\n headers: { \"Content-Type\": \"application/json\", \"Content-Length\": Buffer.byteLength(data) } }, res => {\n let result = \"\";\n res.on(\"data\", chunk => { result += chunk.toString(); if (result.length > 16_384) req.destroy(); });\n res.on(\"end\", () => { if (res.statusCode === 200 && (event === \"PermissionRequest\" || (event === \"UserPromptSubmit\" && result.includes(\"\\\"decision\\\"\")))) process.stdout.write(result); resolve(); });\n res.on(\"error\", () => resolve());\n });\n req.on(\"error\", () => resolve()); req.on(\"timeout\", () => { req.destroy(); resolve(); }); req.end(data);\n });\n}\n// Outside Herdr a tmux pane is placed by asking tmux, which the bundle does.\nif (source !== \"claude\" || (env.HERDR_ENV !== \"1\" && env.TMUX)) await full().catch(() => {});\nelse if (env.HERDR_ENV === \"1\") { const place = herdrPane(); if (place) await forward(place).catch(() => {}); }\n";
4
+ /**
5
+ * How long a PreToolUse or PostToolUse callback may run, from its process's
6
+ * start. Install registers them for every tool call (Codex takes no matcher),
7
+ * and Codex kills a hook at 10 s: on the Mini under a load average near 130
8
+ * (2026-10-01) the old 8 s socket wait, after a slow start, ran past it and
9
+ * Codex showed "Hook failed: hook timed out after 10s" on every call. These
10
+ * callbacks only snapshot changed files for the phone and nothing waits on
11
+ * them, so once the budget is spent they give up and the tool runs.
12
+ */
13
+ export declare const TOOL_HOOK_BUDGET_MS = 5000;
14
+ /** The forwarder's source, with the ToolUse budget written in. */
15
+ export declare const fastHookSource: (toolBudgetMs?: number) => string;
16
+ export declare const FAST_HOOK_SOURCE: string;
@@ -15,7 +15,18 @@ import path from "node:path";
15
15
  /** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
16
16
  export const FAST_HOOK_FILE = "claude-hook.mjs";
17
17
  export const fastHookPath = (versionDir) => path.join(versionDir, FAST_HOOK_FILE);
18
- export const FAST_HOOK_SOURCE = `// Installed by Phren Hook: Claude Code's hook events, forwarded to the running Hook.
18
+ /**
19
+ * How long a PreToolUse or PostToolUse callback may run, from its process's
20
+ * start. Install registers them for every tool call (Codex takes no matcher),
21
+ * and Codex kills a hook at 10 s: on the Mini under a load average near 130
22
+ * (2026-10-01) the old 8 s socket wait, after a slow start, ran past it and
23
+ * Codex showed "Hook failed: hook timed out after 10s" on every call. These
24
+ * callbacks only snapshot changed files for the phone and nothing waits on
25
+ * them, so once the budget is spent they give up and the tool runs.
26
+ */
27
+ export const TOOL_HOOK_BUDGET_MS = 5_000;
28
+ /** The forwarder's source, with the ToolUse budget written in. */
29
+ export const fastHookSource = (toolBudgetMs = TOOL_HOOK_BUDGET_MS) => `// Installed by Phren Hook: Claude Code's hook events, forwarded to the running Hook.
19
30
  import { request } from "node:http";
20
31
  import { homedir } from "node:os";
21
32
  import path from "node:path";
@@ -51,8 +62,11 @@ async function forward(place) {
51
62
  tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
52
63
  ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}), ...stop });
53
64
  const socketPath = path.join(env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"), "agent.sock");
65
+ // A tool call's callback fits its budget from process start, or is skipped.
66
+ const left = Math.floor(${toolBudgetMs} - performance.now());
67
+ if (event.endsWith("ToolUse") && left <= 0) return;
54
68
  await new Promise(resolve => {
55
- const req = request({ socketPath, path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 : 12_000,
69
+ const req = request({ socketPath, path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? left : 12_000,
56
70
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
57
71
  let result = "";
58
72
  res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384) req.destroy(); });
@@ -66,3 +80,4 @@ async function forward(place) {
66
80
  if (source !== "claude" || (env.HERDR_ENV !== "1" && env.TMUX)) await full().catch(() => {});
67
81
  else if (env.HERDR_ENV === "1") { const place = herdrPane(); if (place) await forward(place).catch(() => {}); }
68
82
  `;
83
+ export const FAST_HOOK_SOURCE = fastHookSource();
@@ -33,6 +33,15 @@ export declare function readClaudeModels(configDir?: string, installed?: string
33
33
  * models sit under `opencode-go/`, Zen's under `opencode/`, and everything
34
34
  * else under the gateway it came from; the configured default is marked. */
35
35
  export declare function readOpenCodeModels(executable?: string, configDir?: string): Promise<AgentModel[]>;
36
+ /** phren agent's catalog (`phren-agent models --json`): only providers with
37
+ * credentials on this computer, ids as `<provider>/<model>`, the
38
+ * auto-detected default marked. The agent package next to this CLI (or this
39
+ * checkout's) runs under this Node; otherwise `phren-agent` on PATH. Never the
40
+ * npm global lookup, which blocks. */
41
+ export declare function readPhrenModels(command?: {
42
+ file: string;
43
+ args: string[];
44
+ }): Promise<AgentModel[]>;
36
45
  /** "claude-fable-5-1" reads as "Fable 5.1"; a date suffix is dropped. */
37
46
  export declare function claudeName(id: string): string;
38
47
  /** The account a request names is not one on this computer (or has no catalogue for that source). */
@@ -44,7 +53,8 @@ export declare class ModelCatalog {
44
53
  private readonly claude;
45
54
  private readonly opencode;
46
55
  private readonly cacheMs;
56
+ private readonly phren;
47
57
  private cache;
48
- constructor(codex?: () => Promise<AgentModel[]>, claude?: (configDir?: string) => Promise<AgentModel[]>, opencode?: () => Promise<AgentModel[]>, cacheMs?: number);
58
+ constructor(codex?: () => Promise<AgentModel[]>, claude?: (configDir?: string) => Promise<AgentModel[]>, opencode?: () => Promise<AgentModel[]>, cacheMs?: number, phren?: () => Promise<AgentModel[]>);
49
59
  list(source: string, account?: string): Promise<AgentModel[]>;
50
60
  }
@@ -230,6 +230,49 @@ export async function readOpenCodeModels(executable = "opencode", configDir = pa
230
230
  return { id, name, description, ...(id === configured ? { isDefault: true } : {}) };
231
231
  });
232
232
  }
233
+ /** phren agent's catalog (`phren-agent models --json`): only providers with
234
+ * credentials on this computer, ids as `<provider>/<model>`, the
235
+ * auto-detected default marked. The agent package next to this CLI (or this
236
+ * checkout's) runs under this Node; otherwise `phren-agent` on PATH. Never the
237
+ * npm global lookup, which blocks. */
238
+ export async function readPhrenModels(command) {
239
+ const found = command ? undefined : (await import("../modules/agent-package.js")).findAgentPackage({ global: false });
240
+ const run = command ?? (found ? { file: process.execPath, args: [found.bin, "models", "--json"] } : { file: "phren-agent", args: ["models", "--json"] });
241
+ const listed = await new Promise(resolve => {
242
+ const child = spawn(run.file, run.args, { cwd: homedir(), stdio: ["ignore", "pipe", "ignore"] });
243
+ let out = "", done = false;
244
+ const finish = () => { if (!done) {
245
+ done = true;
246
+ clearTimeout(timer);
247
+ resolve(out);
248
+ } };
249
+ const timer = setTimeout(() => { child.kill("SIGTERM"); finish(); }, 12_000);
250
+ child.stdout.setEncoding("utf8");
251
+ child.stdout.on("data", (chunk) => { if (out.length < 262_144)
252
+ out += chunk; });
253
+ child.on("error", finish);
254
+ child.on("close", finish);
255
+ });
256
+ let rows;
257
+ try {
258
+ rows = objects(object(JSON.parse(listed)).models);
259
+ }
260
+ catch {
261
+ return [];
262
+ }
263
+ const text = (value, max) => typeof value === "string" && value.trim() && !/[\x00-\x1f\x7f]/.test(value) ? value.trim().slice(0, max) : undefined;
264
+ const models = [];
265
+ for (const row of rows.slice(0, 200)) {
266
+ const id = text(row.id, 200), name = text(row.name, 120);
267
+ if (!id || !name || !/^[a-z0-9-]+\/\S+$/.test(id))
268
+ continue;
269
+ const description = text(row.description, 120), effort = text(row.defaultReasoningEffort, 20);
270
+ const efforts = Array.isArray(row.supportedReasoningEfforts) ? row.supportedReasoningEfforts.map(value => text(value, 20)).filter((value) => !!value) : [];
271
+ models.push({ id, name, ...(description ? { description } : {}), ...(row.isDefault === true ? { isDefault: true } : {}),
272
+ ...(effort ? { defaultReasoningEffort: effort } : {}), ...(efforts.length ? { supportedReasoningEfforts: efforts } : {}) });
273
+ }
274
+ return models;
275
+ }
233
276
  /** "claude-fable-5-1" reads as "Fable 5.1"; a date suffix is dropped. */
234
277
  export function claudeName(id) {
235
278
  const parts = id.replace(/^claude-/, "").replace(/-\d{8}$/, "").replace(/\[1m\]$/, "").split("-");
@@ -247,12 +290,14 @@ export class ModelCatalog {
247
290
  claude;
248
291
  opencode;
249
292
  cacheMs;
293
+ phren;
250
294
  cache = new Map();
251
- constructor(codex = () => readCodexModels(), claude = dir => readClaudeModels(dir), opencode = () => readOpenCodeModels(), cacheMs = 600_000) {
295
+ constructor(codex = () => readCodexModels(), claude = dir => readClaudeModels(dir), opencode = () => readOpenCodeModels(), cacheMs = 600_000, phren = () => readPhrenModels()) {
252
296
  this.codex = codex;
253
297
  this.claude = claude;
254
298
  this.opencode = opencode;
255
299
  this.cacheMs = cacheMs;
300
+ this.phren = phren;
256
301
  }
257
302
  list(source, account) {
258
303
  const id = account?.trim() || DEFAULT_ACCOUNT;
@@ -268,7 +313,7 @@ export class ModelCatalog {
268
313
  const key = `${source}:${id}`, cached = this.cache.get(key);
269
314
  if (cached && Date.now() - cached.at < this.cacheMs)
270
315
  return cached.value;
271
- const value = (source === "codex" ? this.codex() : source === "claude" ? this.claude(dir) : source === "opencode" ? this.opencode() : Promise.resolve([])).catch(() => []);
316
+ const value = (source === "codex" ? this.codex() : source === "claude" ? this.claude(dir) : source === "opencode" ? this.opencode() : source === "phren" ? this.phren() : Promise.resolve([])).catch(() => []);
272
317
  this.cache.set(key, { at: Date.now(), value });
273
318
  return value;
274
319
  }
@@ -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
@@ -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";
@@ -68,6 +69,66 @@ function effortArgs(kind, effort) {
68
69
  }
69
70
  /** phren's own agent runs as `phren agent`: the subcommand and its interactive TUI lead its arguments. */
70
71
  const PHREN_AGENT_ARGS = ["agent", "-i"];
72
+ /**
73
+ * phren agent's quick chat and resume: `mode: "chat"` starts it with no tools
74
+ * and its memory read up front (`--mode chat`); `resumeSession` continues a
75
+ * session's history (`--session <id>`). Resuming a chat in `mode: "agent"`
76
+ * promotes it: the same conversation with tools. An agent session that used
77
+ * tools cannot go back to a chat: its history holds tool calls and results,
78
+ * which a request with no tools may not carry (Anthropic refuses it with a
79
+ * 400), so it is refused here before any pane exists.
80
+ */
81
+ export async function phrenLaunchArgs(kind, data, store = phrenStoreRoot()) {
82
+ const mode = z.enum(["agent", "chat"]).optional().parse(data.mode ?? undefined);
83
+ const resume = data.resumeSession === undefined || data.resumeSession === null ? undefined
84
+ : z.string().uuid("resumeSession must be a phren agent session id.").parse(data.resumeSession);
85
+ if ((mode || resume) && kind !== "phren")
86
+ throw new BridgeError(400, "mode and resumeSession are for phren agent launches (kind phren).");
87
+ if (mode === "chat" && resume && await sessionUsedTools(resume, store)) {
88
+ 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" });
89
+ }
90
+ return [...(mode === "chat" ? ["--mode", "chat"] : []), ...(resume ? ["--session", resume] : [])];
91
+ }
92
+ /** Whether a phren agent session's history, as its model sees it, holds a
93
+ * tool call or result: its event log (`<store>/.sessions`) folded as the
94
+ * agent folds it, so a span a compaction summary replaced counts as that
95
+ * summary. False when there is no readable log; phren agent says so itself. */
96
+ export async function sessionUsedTools(session, store = phrenStoreRoot()) {
97
+ const raw = await readFile(path.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
98
+ const withTools = (message) => {
99
+ const content = message?.content;
100
+ return Array.isArray(content) && content.some(block => ["tool_use", "tool_result"].includes(String(block?.type)));
101
+ };
102
+ const surface = new Map();
103
+ for (const line of raw.split("\n")) {
104
+ let event;
105
+ try {
106
+ event = JSON.parse(line);
107
+ }
108
+ catch {
109
+ continue;
110
+ }
111
+ if (typeof event.seq !== "number" || !event.data)
112
+ continue;
113
+ if (["user/message", "assistant/message", "tool/results"].includes(String(event.type)))
114
+ surface.set(event.seq, withTools(event.data.message));
115
+ else if (event.type === "log/replace" && typeof event.data.start === "number" && typeof event.data.end === "number") {
116
+ for (const seq of [...surface.keys()])
117
+ if (seq >= event.data.start && seq <= event.data.end)
118
+ surface.delete(seq);
119
+ surface.set(event.data.start, withTools(event.data.message));
120
+ }
121
+ }
122
+ return [...surface.values()].some(Boolean);
123
+ }
124
+ /** A model from phren agent's catalog (`/v1/models?source=phren`) is
125
+ * `<provider>/<model>`. phren agent reads an openai or openai-codex prefix off
126
+ * `--model` itself; the rest name their provider with `--provider`. Any other
127
+ * model (an OpenRouter id typed by hand) passes through as it is. */
128
+ export function phrenModelArgs(model) {
129
+ const match = /^(anthropic|deepseek|ollama|openrouter)\/(.+)$/.exec(model);
130
+ return match ? ["--provider", match[1], "--model", match[2]] : ["--model", model];
131
+ }
71
132
  async function prepareConductor(kind, effort, model) {
72
133
  const brief = await conductorBrief();
73
134
  const briefDirectory = path.join(bridgeRoot(), "conductor");
@@ -253,6 +314,7 @@ export async function launchSession(server, data, options = {}) {
253
314
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
254
315
  if (role === "conductor" && kind === "phren")
255
316
  throw new BridgeError(400, PHREN_NO_CONDUCTOR);
317
+ const phrenArgs = await phrenLaunchArgs(kind, data);
256
318
  // A dispatched worker's or scheduled run's first prompt. It rides on the
257
319
  // launch where the harness takes one; elsewhere the caller types it.
258
320
  const brief = data.brief === undefined || data.brief === null ? undefined : launchBriefSchema.parse(data.brief);
@@ -293,7 +355,7 @@ export async function launchSession(server, data, options = {}) {
293
355
  if (conductorHere && conductorHere.workspace_id === workspace)
294
356
  workspace = undefined;
295
357
  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)),
358
+ : [...(kind === "phren" ? [...PHREN_AGENT_ARGS, ...phrenArgs] : []), ...(model && kind === "phren" ? phrenModelArgs(model) : model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
297
359
  ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : [])];
298
360
  // A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
299
361
  // pane joins the thread the Hook started, and the brief is that thread's
@@ -108,6 +108,8 @@ 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;
@@ -117,6 +119,8 @@ export declare const capabilities: {
117
119
  resources: boolean;
118
120
  sudo: boolean;
119
121
  sudoOutcome: boolean;
122
+ previewDeltas: boolean;
123
+ quickChat: boolean;
120
124
  };
121
125
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
122
126
  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, 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;
@@ -16,6 +16,7 @@ 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 { relayLiveSpeech } from "./speech-live.js";
19
20
  import { relayTranscription } from "./speech-transcribe.js";
20
21
  import { ActivityJournal } from "./activity.js";
21
22
  import { countTick } from "./metrics.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
  }
@@ -239,6 +240,10 @@ export async function serve(version, options = {}) {
239
240
  void relayTranscription(client, url.searchParams).catch(() => client.close(1011, "Transcription unavailable"));
240
241
  return;
241
242
  }
243
+ if (url.pathname === "/v1/speech/live") {
244
+ void relayLiveSpeech(client, url.searchParams).catch(() => client.close(1011, "Spoken replies unavailable"));
245
+ return;
246
+ }
242
247
  void stream(client, url).catch(() => client.close(1011, "Conversation unavailable; refresh"));
243
248
  });
244
249
  }
@@ -0,0 +1,45 @@
1
+ import { type SpeechState } from "./speech.js";
2
+ export interface LiveSocket {
3
+ readonly readyState: number;
4
+ /** Bytes queued to send; the phone's socket has it, ElevenLabs' need not. */
5
+ readonly bufferedAmount?: number;
6
+ send(data: string): void;
7
+ close(code?: number, reason?: string): void;
8
+ on(event: "message", listener: (data: Buffer, isBinary: boolean) => void): unknown;
9
+ on(event: "open", listener: () => void): unknown;
10
+ on(event: "close", listener: (code?: number, reason?: Buffer) => void): unknown;
11
+ on(event: "error", listener: (error: Error) => void): unknown;
12
+ }
13
+ /** ElevenLabs' side: a socket that also reports a refused handshake with its
14
+ * HTTP status and ElevenLabs' `detail.status`. */
15
+ export interface LiveUpstream extends LiveSocket {
16
+ on(event: "message", listener: (data: Buffer, isBinary: boolean) => void): unknown;
17
+ on(event: "open", listener: () => void): unknown;
18
+ on(event: "close", listener: (code?: number, reason?: Buffer) => void): unknown;
19
+ on(event: "error", listener: (error: Error) => void): unknown;
20
+ on(event: "refused", listener: (status: number, code: string) => void): unknown;
21
+ }
22
+ export interface LiveSpeechOptions {
23
+ key?: () => Promise<string | undefined>;
24
+ connect?: (url: string, key: string) => LiveUpstream;
25
+ /** Defaults to this computer's model and region settings. */
26
+ model?: string;
27
+ origin?: string;
28
+ state?: SpeechState;
29
+ maxSessionMs?: number;
30
+ handshakeMs?: number;
31
+ firstAudioMs?: number;
32
+ }
33
+ /** Text-to-dialogue serves v3 and v4; text-to-speech stream-input the rest. */
34
+ export declare function liveEndpoint(model: string): "dialogue" | "speech";
35
+ /** Markdown arriving a piece at a time, released a sentence or line at a time
36
+ * as the words speakableText leaves of it. A code block is skipped until it
37
+ * closes; the unfinished sentence waits for more text or `end`. */
38
+ export declare class SpeakableStream {
39
+ private pending;
40
+ private inFence;
41
+ push(text: string): string;
42
+ end(): string;
43
+ private speak;
44
+ }
45
+ export declare function relayLiveSpeech(client: LiveSocket, query: URLSearchParams, options?: LiveSpeechOptions): Promise<void>;