@phren/cli 0.3.18 → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/bridge/agent-hooks.d.ts +16 -1
  2. package/dist/bridge/agent-hooks.js +56 -4
  3. package/dist/bridge/changes.d.ts +4 -0
  4. package/dist/bridge/changes.js +25 -2
  5. package/dist/bridge/command.js +24 -6
  6. package/dist/bridge/dispatch-returns.d.ts +11 -0
  7. package/dist/bridge/dispatch-returns.js +47 -7
  8. package/dist/bridge/dispatch.d.ts +19 -0
  9. package/dist/bridge/dispatch.js +164 -5
  10. package/dist/bridge/harnesses.d.ts +1 -1
  11. package/dist/bridge/harnesses.js +9 -2
  12. package/dist/bridge/health.d.ts +3 -2
  13. package/dist/bridge/health.js +4 -3
  14. package/dist/bridge/hook-fast.d.ts +13 -1
  15. package/dist/bridge/hook-fast.js +17 -2
  16. package/dist/bridge/models.d.ts +11 -1
  17. package/dist/bridge/models.js +47 -2
  18. package/dist/bridge/server-launch.d.ts +20 -0
  19. package/dist/bridge/server-launch.js +77 -3
  20. package/dist/bridge/server-routes.d.ts +4 -0
  21. package/dist/bridge/server-routes.js +2 -2
  22. package/dist/bridge/server.js +6 -1
  23. package/dist/bridge/speech-live.d.ts +45 -0
  24. package/dist/bridge/speech-live.js +413 -0
  25. package/dist/bridge/speech-transcribe.d.ts +5 -2
  26. package/dist/bridge/speech-transcribe.js +8 -5
  27. package/dist/bridge/speech-voice.d.ts +22 -1
  28. package/dist/bridge/speech-voice.js +20 -2
  29. package/dist/bridge/speech.d.ts +24 -4
  30. package/dist/bridge/speech.js +115 -14
  31. package/dist/bridge/stalls.d.ts +9 -2
  32. package/dist/bridge/stalls.js +20 -4
  33. package/dist/bridge/terminal-herdr.d.ts +7 -0
  34. package/dist/bridge/terminal-herdr.js +81 -7
  35. package/dist/bridge/terminal-tmux.js +2 -2
  36. package/dist/bridge/terminal.d.ts +3 -0
  37. package/dist/bridge/terminal.js +1 -0
  38. package/dist/bridge/transcript-preview.d.ts +11 -1
  39. package/dist/bridge/transcript-preview.js +37 -11
  40. package/dist/bridge/transcripts.d.ts +2 -1
  41. package/dist/bridge/transcripts.js +7 -3
  42. package/dist/bridge/transport.js +4 -3
  43. package/dist/bridge/turn-records.d.ts +6 -3
  44. package/dist/bridge/turn-records.js +9 -4
  45. package/dist/bridge/usage.d.ts +1 -1
  46. package/dist/bridge/usage.js +4 -3
  47. package/dist/bridge/worker-close.js +2 -1
  48. package/dist/bridge/worker-unfinished.d.ts +37 -0
  49. package/dist/bridge/worker-unfinished.js +145 -0
  50. package/dist/bridge-hook.mjs +2171 -1230
  51. package/dist/cli-registry.js +2 -1
  52. package/dist/modules/registry.js +2 -2
  53. package/package.json +1 -1
@@ -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,6 +1,6 @@
1
1
  import { type AccountRef, type AuthRunner } from "./claude-accounts.js";
2
2
  import { type ToolVersion } from "./health.js";
3
- export type HarnessSource = "claude" | "codex" | "opencode" | "copilot";
3
+ export type HarnessSource = "claude" | "codex" | "opencode" | "copilot" | "phren";
4
4
  export interface HarnessAccount extends AccountRef {
5
5
  signedIn: boolean;
6
6
  usable: boolean;
@@ -1,19 +1,26 @@
1
1
  // What this computer can launch: each harness's install state and, for Claude and Codex, its accounts.
2
+ // `phren` is phren's own agent, run as `phren agent`; it needs no account here.
2
3
  // Served as GET /v1/harnesses and as `harnesses` on /v1/dispatch/capacity. See docs/accounts.md.
3
4
  import { existsSync } from "node:fs";
4
5
  import path from "node:path";
5
6
  import { codexHome } from "../home-paths.js";
6
7
  import { claudeAccountRef, claudeAuthStatus, claudeHomes, CODEX_ACCOUNT } from "./claude-accounts.js";
7
8
  import { toolVersion } from "./health.js";
8
- const SOURCES = ["claude", "codex", "opencode", "copilot"];
9
+ const SOURCES = ["claude", "codex", "opencode", "copilot", "phren"];
10
+ /** The binary is `phren`; the agent answers `phren agent --version` from the separate @phren/agent package. */
11
+ const probeSource = (source) => source === "phren" ? toolVersion("phren agent", "phren", ["agent"]) : toolVersion(source);
9
12
  export async function harnessInventory(deps = {}) {
10
13
  const env = deps.env ?? process.env;
11
- const probe = deps.toolVersion ?? ((tool) => toolVersion(tool));
14
+ const probe = deps.toolVersion ?? probeSource;
12
15
  const harnesses = await Promise.all(SOURCES.map(async (source) => {
13
16
  const found = await probe(source);
14
17
  // Only a missing binary is definite; a slow or failing --version (a loaded computer) stays usable.
15
18
  if (found.status === "missing")
16
19
  return { source, installed: false, usable: false, reason: "Not installed" };
20
+ // `phren agent` without @phren/agent prints an install hint and no version.
21
+ if (source === "phren" && found.status === "error" && found.detail?.startsWith("--version exited")) {
22
+ return { source, installed: false, usable: false, reason: "Not installed: npm install -g @phren/agent" };
23
+ }
17
24
  const base = { source, installed: true, ...(found.version ? { version: found.version } : {}) };
18
25
  if (source === "claude") {
19
26
  const accounts = await Promise.all(claudeHomes(env).map(async (home) => {
@@ -114,8 +114,9 @@ export interface HealthOptions {
114
114
  devices: number;
115
115
  };
116
116
  }
117
- /** `<tool> --version`, bounded to 3 seconds and remembered for 5 minutes. */
118
- export declare function toolVersion(tool: string, executable?: string): Promise<ToolVersion>;
117
+ /** `<tool> --version`, bounded to 3 seconds and remembered for 5 minutes. `args` come
118
+ * before `--version` for a tool behind a subcommand (`phren agent --version`). */
119
+ export declare function toolVersion(tool: string, executable?: string, args?: string[]): Promise<ToolVersion>;
119
120
  /** Only for tests: forget cached versions. */
120
121
  export declare function clearVersionCache(): void;
121
122
  /** Branch and ahead/behind against the upstream as last fetched; nothing is fetched here. */
@@ -38,14 +38,15 @@ const VERSION_TIMEOUT_MS = 3_000;
38
38
  const VERSION_CACHE_MS = 5 * 60_000;
39
39
  const PEER_TIMEOUT_MS = 5_000;
40
40
  const versionCache = new Map();
41
- /** `<tool> --version`, bounded to 3 seconds and remembered for 5 minutes. */
42
- export function toolVersion(tool, executable = tool) {
41
+ /** `<tool> --version`, bounded to 3 seconds and remembered for 5 minutes. `args` come
42
+ * before `--version` for a tool behind a subcommand (`phren agent --version`). */
43
+ export function toolVersion(tool, executable = tool, args = []) {
43
44
  const cached = versionCache.get(tool);
44
45
  if (cached && Date.now() - cached.at < VERSION_CACHE_MS)
45
46
  return cached.value;
46
47
  const value = new Promise(resolve => {
47
48
  let out = "", done = false;
48
- const child = spawn(executable, ["--version"], { cwd: homedir(), stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
49
+ const child = spawn(executable, [...args, "--version"], { cwd: homedir(), stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
49
50
  const finish = (result) => { if (!done) {
50
51
  done = true;
51
52
  clearTimeout(timer);
@@ -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";
@@ -28,7 +29,7 @@ import { atomic, BridgeError, bridgeRoot, id, launchEfforts, objects, PERMISSION
28
29
  import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags } 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
- const launchKinds = ["codex", "claude", "copilot", "opencode"];
32
+ const launchKinds = ["codex", "claude", "copilot", "opencode", "phren"];
32
33
  const plainText = (max) => z.string().min(1).max(max).refine(t => !/[\x00-\x1f\x7f]/.test(t));
33
34
  async function conductorBrief() {
34
35
  let source;
@@ -61,8 +62,73 @@ function effortArgs(kind, effort) {
61
62
  return ["-c", `model_reasoning_effort=${effort}`];
62
63
  if (kind === "opencode")
63
64
  return ["--variant", effort];
65
+ // phren-agent takes low to xhigh, and max as xhigh.
66
+ if (kind === "phren")
67
+ return ["--reasoning", effort === "minimal" ? "low" : effort];
64
68
  return [];
65
69
  }
70
+ /** phren's own agent runs as `phren agent`: the subcommand and its interactive TUI lead its arguments. */
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
+ }
66
132
  async function prepareConductor(kind, effort, model) {
67
133
  const brief = await conductorBrief();
68
134
  const briefDirectory = path.join(bridgeRoot(), "conductor");
@@ -138,6 +204,7 @@ async function requireNoConductor(server, before, except) {
138
204
  }
139
205
  /** The phone names the pane's workspace and tab too; the CLI may know only the pane. */
140
206
  const paneRequest = z.object({ workspaceId: id.optional(), tabId: id.optional(), paneId: id }).strict();
207
+ const PHREN_NO_CONDUCTOR = "phren agent cannot run as a conductor: it takes no system brief at startup.";
141
208
  /** "Make conductor": the owner gives an agent already running in a pane on this computer the role. */
142
209
  export async function makeConductor(server, data) {
143
210
  const place = paneRequest.parse(data);
@@ -150,6 +217,8 @@ export async function makeConductor(server, data) {
150
217
  throw new BridgeError(409, "No agent is running in this pane.");
151
218
  if (pane.agent === "copilot")
152
219
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
220
+ if (pane.agent === "phren")
221
+ throw new BridgeError(400, PHREN_NO_CONDUCTOR);
153
222
  const unchecked = await requireNoConductor(server, before, place.paneId);
154
223
  const target = await targetForPane(server, pane);
155
224
  await recordConductor(server, pane, "owner", typeof target?.session === "string" ? target.session : undefined);
@@ -239,8 +308,13 @@ export async function launchSession(server, data, options = {}) {
239
308
  throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and Codex workers.");
240
309
  if (permissionMode && kind === "copilot")
241
310
  throw new BridgeError(400, "Copilot takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
311
+ if (permissionMode && kind === "phren")
312
+ throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
242
313
  if (role === "conductor" && kind === "copilot")
243
314
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
315
+ if (role === "conductor" && kind === "phren")
316
+ throw new BridgeError(400, PHREN_NO_CONDUCTOR);
317
+ const phrenArgs = await phrenLaunchArgs(kind, data);
244
318
  // A dispatched worker's or scheduled run's first prompt. It rides on the
245
319
  // launch where the harness takes one; elsewhere the caller types it.
246
320
  const brief = data.brief === undefined || data.brief === null ? undefined : launchBriefSchema.parse(data.brief);
@@ -257,7 +331,7 @@ export async function launchSession(server, data, options = {}) {
257
331
  const wanted = options.canary ? "phren-canary" : role === "conductor" ? (isConductorName(baseName) ? baseName : herdrAgentName(`conductor-${baseName}`))
258
332
  : isConductorName(baseName) ? herdrAgentName(`worker-${baseName}`) : baseName;
259
333
  const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : undefined;
260
- const modelFlag = { codex: "--model", claude: "--model", opencode: "--model" };
334
+ const modelFlag = { codex: "--model", claude: "--model", opencode: "--model", phren: "--model" };
261
335
  let workspace = data.workspaceId === undefined ? undefined : id.parse(data.workspaceId);
262
336
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
263
337
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
@@ -281,7 +355,7 @@ export async function launchSession(server, data, options = {}) {
281
355
  if (conductorHere && conductorHere.workspace_id === workspace)
282
356
  workspace = undefined;
283
357
  const args = role === "conductor" ? await prepareConductor(kind, effort, model)
284
- : [...(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)),
285
359
  ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : [])];
286
360
  // A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
287
361
  // pane joins the thread the Hook started, and the brief is that thread's