@phren/cli 0.3.11 → 0.3.12

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 (168) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanouts.d.ts +7 -1
  42. package/dist/bridge/fanouts.js +39 -4
  43. package/dist/bridge/folder-trust.d.ts +56 -0
  44. package/dist/bridge/folder-trust.js +195 -0
  45. package/dist/bridge/grants.d.ts +22 -1
  46. package/dist/bridge/grants.js +57 -9
  47. package/dist/bridge/hand-off.d.ts +21 -9
  48. package/dist/bridge/hand-off.js +58 -45
  49. package/dist/bridge/harness-status.d.ts +11 -0
  50. package/dist/bridge/harness-status.js +32 -0
  51. package/dist/bridge/harnesses.d.ts +39 -0
  52. package/dist/bridge/harnesses.js +65 -0
  53. package/dist/bridge/health.d.ts +2 -0
  54. package/dist/bridge/health.js +1 -1
  55. package/dist/bridge/herdr.d.ts +11 -2
  56. package/dist/bridge/herdr.js +98 -23
  57. package/dist/bridge/hook-fast.d.ts +4 -0
  58. package/dist/bridge/hook-fast.js +68 -0
  59. package/dist/bridge/install.d.ts +16 -1
  60. package/dist/bridge/install.js +88 -21
  61. package/dist/bridge/launch-brief.d.ts +96 -0
  62. package/dist/bridge/launch-brief.js +164 -0
  63. package/dist/bridge/model-switch.d.ts +3 -0
  64. package/dist/bridge/model-switch.js +17 -1
  65. package/dist/bridge/models.d.ts +8 -4
  66. package/dist/bridge/models.js +24 -8
  67. package/dist/bridge/mux-wire.d.ts +9 -0
  68. package/dist/bridge/mux-wire.js +19 -0
  69. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  70. package/dist/bridge/opencode-pane-server.js +332 -0
  71. package/dist/bridge/opencode-panes.d.ts +111 -0
  72. package/dist/bridge/opencode-panes.js +295 -0
  73. package/dist/bridge/pane-accounts.d.ts +8 -0
  74. package/dist/bridge/pane-accounts.js +46 -0
  75. package/dist/bridge/prompt-startup.d.ts +5 -0
  76. package/dist/bridge/prompt-startup.js +24 -0
  77. package/dist/bridge/protocol.d.ts +5 -0
  78. package/dist/bridge/protocol.js +4 -0
  79. package/dist/bridge/push.d.ts +5 -4
  80. package/dist/bridge/push.js +6 -4
  81. package/dist/bridge/questions.d.ts +37 -2
  82. package/dist/bridge/questions.js +158 -15
  83. package/dist/bridge/resources.d.ts +9 -3
  84. package/dist/bridge/resources.js +24 -8
  85. package/dist/bridge/schedule-format.d.ts +2 -0
  86. package/dist/bridge/schedule-format.js +3 -0
  87. package/dist/bridge/schedule-launch.d.ts +2 -1
  88. package/dist/bridge/schedule-launch.js +23 -53
  89. package/dist/bridge/schedule-watch.d.ts +10 -1
  90. package/dist/bridge/schedule-watch.js +54 -2
  91. package/dist/bridge/server-launch.d.ts +22 -5
  92. package/dist/bridge/server-launch.js +225 -29
  93. package/dist/bridge/server-overview.d.ts +3 -3
  94. package/dist/bridge/server-overview.js +22 -14
  95. package/dist/bridge/server-pane-routes.d.ts +2 -0
  96. package/dist/bridge/server-pane-routes.js +145 -15
  97. package/dist/bridge/server-routes.d.ts +7 -0
  98. package/dist/bridge/server-routes.js +163 -35
  99. package/dist/bridge/server-stream.d.ts +2 -0
  100. package/dist/bridge/server-stream.js +22 -8
  101. package/dist/bridge/server.d.ts +6 -1
  102. package/dist/bridge/server.js +44 -12
  103. package/dist/bridge/session-activity.d.ts +81 -0
  104. package/dist/bridge/session-activity.js +117 -0
  105. package/dist/bridge/session-rename.d.ts +48 -0
  106. package/dist/bridge/session-rename.js +190 -0
  107. package/dist/bridge/session-servers.js +2 -2
  108. package/dist/bridge/settings-switch.d.ts +60 -0
  109. package/dist/bridge/settings-switch.js +287 -0
  110. package/dist/bridge/speech-voice.d.ts +55 -0
  111. package/dist/bridge/speech-voice.js +132 -0
  112. package/dist/bridge/speech.d.ts +70 -11
  113. package/dist/bridge/speech.js +169 -41
  114. package/dist/bridge/terminal-herdr.js +9 -3
  115. package/dist/bridge/terminal-tmux.d.ts +3 -3
  116. package/dist/bridge/terminal-tmux.js +24 -9
  117. package/dist/bridge/terminal.d.ts +27 -4
  118. package/dist/bridge/terminal.js +8 -1
  119. package/dist/bridge/transcript-claude.js +57 -12
  120. package/dist/bridge/transcript-codex.d.ts +0 -2
  121. package/dist/bridge/transcript-codex.js +29 -4
  122. package/dist/bridge/transcript-preview.d.ts +1 -0
  123. package/dist/bridge/transcript-preview.js +24 -4
  124. package/dist/bridge/transcripts.d.ts +15 -2
  125. package/dist/bridge/transcripts.js +47 -16
  126. package/dist/bridge/turn-records.d.ts +85 -0
  127. package/dist/bridge/turn-records.js +143 -0
  128. package/dist/bridge/uploads.d.ts +3 -0
  129. package/dist/bridge/uploads.js +14 -0
  130. package/dist/bridge/usage.d.ts +39 -10
  131. package/dist/bridge/usage.js +155 -44
  132. package/dist/bridge-hook.mjs +19169 -13176
  133. package/dist/cli/claude-unmanaged.d.ts +12 -0
  134. package/dist/cli/claude-unmanaged.js +105 -0
  135. package/dist/cli/schedules.js +2 -1
  136. package/dist/cli/session-start.js +10 -1
  137. package/dist/cli/session-stop.js +9 -1
  138. package/dist/cli-registry.js +24 -5
  139. package/dist/data/task-receipts.d.ts +19 -0
  140. package/dist/data/task-receipts.js +68 -0
  141. package/dist/data/tasks.js +4 -1
  142. package/dist/generated/memory-ui-graph.browser.js +63 -63
  143. package/dist/graph-core/model.js +24 -3
  144. package/dist/graph-core/types.d.ts +4 -1
  145. package/dist/graph-core/types.js +1 -0
  146. package/dist/init/init-preset.js +7 -3
  147. package/dist/init/init-uninstall.js +2 -11
  148. package/dist/init/teardown.d.ts +3 -0
  149. package/dist/init/teardown.js +47 -0
  150. package/dist/link/context.js +21 -9
  151. package/dist/mcp/plugin-mode.js +1 -1
  152. package/dist/memory-ui-graph.runtime.js +63 -63
  153. package/dist/modules/code-package.d.ts +1 -0
  154. package/dist/modules/code-package.js +36 -7
  155. package/dist/modules/registry.js +14 -13
  156. package/dist/profile-store.d.ts +6 -0
  157. package/dist/profile-store.js +25 -1
  158. package/dist/shell/graph/glyphs.js +4 -0
  159. package/dist/shell/graph/graph-view.js +2 -0
  160. package/dist/status.js +7 -1
  161. package/dist/sync/task-claim.js +3 -2
  162. package/dist/task/lifecycle.js +25 -4
  163. package/dist/test-global-setup.js +5 -0
  164. package/dist/tools/dispatch.js +35 -2
  165. package/dist/tools/tasks.js +10 -1
  166. package/package.json +1 -1
  167. package/plugins/opencode/phren-transcript.js +87 -4
  168. package/starter/global/skills/conductor/SKILL.md +17 -2
@@ -1,4 +1,5 @@
1
1
  import { createHmac, randomBytes } from "node:crypto";
2
+ import { paneAccount, paneAccountKey, notePaneTranscript } from "./pane-accounts.js";
2
3
  import { execFile } from "node:child_process";
3
4
  import { connect } from "node:net";
4
5
  import { homedir } from "node:os";
@@ -8,11 +9,13 @@ import { promisify } from "node:util";
8
9
  import { BridgeError, id, object, objects, requestID, serverName, provider, sessionId } from "./protocol.js";
9
10
  import { logger } from "../logger.js";
10
11
  import { recordedSession } from "./agent-hook-stores.js";
12
+ import { paneRecord, recordTitle } from "./session-activity.js";
11
13
  import { tabActivityKey } from "./tab-activity.js";
12
14
  import { intervalFromEnv } from "./limits.js";
13
15
  import { countHerdr, countIdentity } from "./metrics.js";
14
16
  import { phrenStoreRoot } from "./transcripts.js";
15
17
  import { assignDaemonConversation, daemonRollouts, processTable, sameDirectory, startedAt } from "./codex-daemon.js";
18
+ import { codexServers } from "./codex-servers.js";
16
19
  // terminal.ts and terminal-tmux.ts import this module, so it reaches them at
17
20
  // call time; a static import back would be an import cycle.
18
21
  const terminal = () => import("./terminal.js");
@@ -149,8 +152,8 @@ export async function servers() {
149
152
  }));
150
153
  const running = results.filter((v) => v !== null);
151
154
  // The owner's own tmux servers always: agents started with `tmux` beside a
152
- // running Herdr show up too. The Hook's hidden server only without Herdr,
153
- // where phone launches go; with Herdr they go to Herdr.
155
+ // running Herdr show up too, including an already-running hidden server.
156
+ // Without Herdr, also offer the hidden server before its first launch.
154
157
  running.push(...await import("./terminal-tmux.js").then(tmux => tmux.tmuxServers({ hidden: !running.length })).catch(() => []));
155
158
  knownServers = running.map(server => String(server.session));
156
159
  return running;
@@ -232,11 +235,15 @@ export function findPane(s, address) {
232
235
  return objects(s.panes).find(p => p.pane_id === address.pane && p.tab_id === address.tab && p.workspace_id === address.workspace
233
236
  && (address.source === undefined || p.agent === address.source));
234
237
  }
235
- /** A conductor's Herdr name: "conductor", or "conductor-" plus its label. */
238
+ /** A conductor's Herdr name: "conductor", or "conductor-" plus its label. Only
239
+ * a label since the Hook records the role (conductor-role.ts): read to migrate
240
+ * a conductor from before that record, and kept off workers' names. */
236
241
  export function isConductorName(name) {
237
242
  return name === "conductor" || !!name?.startsWith("conductor-");
238
243
  }
239
- export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged) {
244
+ /** `conductorPane` is the pane the Hook records as the conductor (null for
245
+ * none); left out, the agent's name decides, as before the record. */
246
+ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, conductorPane) {
240
247
  const focusedPane = objects(s.panes).find(p => p.pane_id === s.focused_pane_id
241
248
  && p.tab_id === s.focused_tab_id && p.workspace_id === s.focused_workspace_id);
242
249
  const focus = focusedPane && id.safeParse(s.focused_workspace_id).success
@@ -253,9 +260,9 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
253
260
  // Herdr's per-pane state_change_seq climbs with every agent status
254
261
  // change; the phone orders "just finished" ahead of "finished an hour ago" by it.
255
262
  const changed = Math.max(0, ...panes.map(p => Number.isSafeInteger(p.state_change_seq) ? Number(p.state_change_seq) : 0));
256
- return { id: t.tab_id, label: t.label, title: agent?.title || agent?.terminal_title_stripped,
263
+ return { id: t.tab_id, label: t.label, paneLabel: agent?.label || undefined, title: agent?.title || agent?.terminal_title_stripped,
257
264
  agent: agent?.agent, agentStatus: t.agent_status, cwd: agent?.foreground_cwd || agent?.cwd,
258
- role: isConductorName(paneAgentName(s, agent)) ? "conductor" : undefined,
265
+ role: (conductorPane === undefined ? isConductorName(paneAgentName(s, agent)) : !!agent && agent.pane_id === conductorPane) ? "conductor" : undefined,
259
266
  changedSeq: changed || undefined,
260
267
  lastChangedAt: lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id)),
261
268
  approvalPending: panes.some(p => approvalPanes?.has(String(p.pane_id))) || undefined,
@@ -292,7 +299,10 @@ async function resolveIdentity(server, pane, fresh) {
292
299
  const reported = object(pane.agent_session);
293
300
  // Copilot's report lags a conversation switch (see copilotForegroundSession);
294
301
  // its own process log is read first and the report is the fallback.
295
- if (pane.agent !== "copilot" && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
302
+ // A Codex pane on the Hook's own app-server: the registry follows `/new`
303
+ // and `/resume` as they happen, while Herdr's report waits for a hook.
304
+ const owned = pane.agent === "codex" && !!codexServers.forPane(server, String(pane.pane_id))?.threadId;
305
+ if (pane.agent !== "copilot" && !owned && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
296
306
  countIdentity("reported");
297
307
  return { sessionId: reported.value };
298
308
  }
@@ -407,6 +417,16 @@ async function identityFromProcesses(server, pane, pids) {
407
417
  if (reported.kind === "id" && reported.agent === "copilot" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success)
408
418
  return { sessionId: reported.value, noTranscriptLogs: false };
409
419
  }
420
+ if (pane.agent === "codex") {
421
+ // A pane the Hook launched on its own app-server shows the thread the
422
+ // Hook started, while its TUI still runs against that server's socket.
423
+ const owned = codexServers.forPane(server, String(pane.pane_id));
424
+ if (owned?.threadId) {
425
+ const rows = await processTable();
426
+ if (rows.some(row => pids.includes(row.pid) && row.command.includes(`unix://${owned.socket}`)))
427
+ return { sessionId: owned.threadId, noTranscriptLogs: false };
428
+ }
429
+ }
410
430
  const files = await processLogs(pids);
411
431
  const candidates = files.flatMap(file => {
412
432
  const match = pane.agent === "codex" ? (/rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file) ?? /thread-writer-locks\/([a-f0-9-]{36})\.lock$/i.exec(file))
@@ -417,8 +437,14 @@ async function identityFromProcesses(server, pane, pids) {
417
437
  : /\/session-state\/([a-f0-9-]{36})\/events\.jsonl$/i.exec(file);
418
438
  return match ? [match[1]] : [];
419
439
  });
420
- if (new Set(candidates).size === 1)
440
+ if (new Set(candidates).size === 1) {
441
+ if (pane.agent === "claude") {
442
+ const open = files.find(file => file.endsWith(`/${candidates[0]}.jsonl`));
443
+ if (open)
444
+ notePaneTranscript(paneAccountKey(server, pane.pane_id), open, String(pane.terminal_id ?? ""));
445
+ }
421
446
  return { sessionId: candidates[0], noTranscriptLogs: false };
447
+ }
422
448
  if (pane.agent === "codex" && candidates.length === 0) {
423
449
  const daemon = await codexDaemonIdentity(server, pane, pids).catch(() => undefined);
424
450
  if (daemon?.sessionId)
@@ -459,7 +485,8 @@ async function codexDaemonIdentity(server, pane, pids) {
459
485
  // time. Their bindings are not trusted here: before this fix the daemon's
460
486
  // hooks wrote them for the pane that started the daemon.
461
487
  const s = await (await terminal()).terminalProvider().snapshot(server).catch(() => ({}));
462
- const claimed = new Set(), rivals = [];
488
+ // Threads the Hook's own app-servers run belong to their own panes.
489
+ const claimed = new Set(codexServers.entries().flatMap(entry => entry.threadId ? [entry.threadId] : [])), rivals = [];
463
490
  for (const peer of objects(s.panes).filter(p => p.agent === "codex" && p.pane_id !== pane.pane_id).slice(0, 16)) {
464
491
  if (!await sameDirectory(paneCwd(peer), cwd))
465
492
  continue;
@@ -497,6 +524,22 @@ export async function paneForCodexSession(server, session, cwd) {
497
524
  return same.length === 1 && !identities[same[0]] ? codex[same[0]] : undefined;
498
525
  }
499
526
  const startingKey = randomBytes(32);
527
+ const startingBindings = new Map();
528
+ const startingPaneKey = (server, pane) => JSON.stringify([server, pane.workspace_id, pane.tab_id, pane.pane_id, pane.terminal_id, pane.agent]);
529
+ const startingToken = (process) => createHmac("sha256", startingKey).update(process).update(randomBytes(32)).digest("hex");
530
+ /** Remember the first identified conversation even when an overview skips the
531
+ * PID probe. A later conversation in the same process retires its old token. */
532
+ function identifyStartingBinding(key, session) {
533
+ const binding = startingBindings.get(key);
534
+ if (!binding || binding.sessionId === session)
535
+ return;
536
+ if (binding.sessionId) {
537
+ binding.wasStarting = false;
538
+ binding.token = startingToken(binding.process);
539
+ }
540
+ binding.sessionId = session;
541
+ binding.identifiedAt = Date.now();
542
+ }
500
543
  /** Bind first-send permission to the actual terminal/process, never a cwd or
501
544
  * a guessed conversation. Tokens expire naturally when the Hook/process restarts. */
502
545
  export async function paneChatState(server, pane, options = {}) {
@@ -504,6 +547,9 @@ export async function paneChatState(server, pane, options = {}) {
504
547
  return {};
505
548
  const identity = await resolveIdentity(server, pane, false);
506
549
  const sessionId = identity.sessionId;
550
+ const key = startingPaneKey(server, pane);
551
+ if (sessionId)
552
+ identifyStartingBinding(key, sessionId);
507
553
  // A pane whose conversation is known is not starting, so a caller that
508
554
  // reads only `sessionId` and `starting` (the overview) needs no PIDs.
509
555
  if (sessionId && options.tokenWhenIdentified === false)
@@ -512,26 +558,50 @@ export async function paneChatState(server, pane, options = {}) {
512
558
  // The token binds to the agent's own process, the oldest in the pane's
513
559
  // foreground group. Helpers it spawns while starting up (Codex forks
514
560
  // several in its first seconds) must not turn the phone's first send away.
515
- const startingToken = typeof pane.terminal_id === "string" && pids.length
516
- ? createHmac("sha256", startingKey).update(JSON.stringify([server, pane.workspace_id, pane.tab_id, pane.pane_id, pane.terminal_id, pane.agent, pids[0]])).digest("hex") : undefined;
561
+ const process = typeof pane.terminal_id === "string" && pids.length ? JSON.stringify([key, pids[0]]) : undefined;
517
562
  // An ambiguous set of open logs is not a brand-new conversation.
518
563
  // Reuse the same two-second identity probe as context/overview polling;
519
564
  // discovering a new chat must not run lsof again for every list refresh.
520
565
  const evidence = identities.get(identityKey(server, pane, pids));
521
- const starting = !sessionId && !!startingToken && !!evidence && Date.now() - evidence.at < IDENTITY_CACHE_MS && (await evidence.result).noTranscriptLogs;
522
- return { sessionId, ...(startingToken ? { startingToken } : {}), ...(starting ? { starting: true } : {}) };
566
+ const starting = !sessionId && !!process && !!evidence && Date.now() - evidence.at < IDENTITY_CACHE_MS && (await evidence.result).noTranscriptLogs;
567
+ let binding = startingBindings.get(key);
568
+ if (process) {
569
+ // Lost identity, changed process, or newly ambiguous evidence requires a
570
+ // new token. Never revive a previous conversation's first-send permission.
571
+ if (!binding || binding.process !== process || (!sessionId && (!!binding.sessionId || binding.wasStarting !== starting))) {
572
+ binding = { process, token: startingToken(process), wasStarting: starting,
573
+ ...(sessionId ? { sessionId, identifiedAt: Date.now() } : {}) };
574
+ if (startingBindings.size >= 256)
575
+ startingBindings.delete(startingBindings.keys().next().value);
576
+ startingBindings.set(key, binding);
577
+ }
578
+ }
579
+ return { sessionId, ...(process && binding ? { startingToken: binding.token } : {}), ...(starting ? { starting: true } : {}) };
580
+ }
581
+ /** `{ account }` for a Claude pane whose account is known, else nothing. */
582
+ export function paneAccountField(server, pane) {
583
+ if (pane.agent !== "claude")
584
+ return {};
585
+ const account = paneAccount(paneAccountKey(server, pane.pane_id), String(pane.terminal_id ?? ""));
586
+ return account ? { account } : {};
523
587
  }
524
588
  export async function panes(server, workspace, tab) {
525
589
  id.parse(workspace);
526
590
  id.parse(tab);
527
591
  const s = await snapshot(server);
528
592
  if (!objects(s.tabs).some(t => t.tab_id === tab && t.workspace_id === workspace))
529
- throw new BridgeError(409, "This Herdr tab has changed. Refresh the computer.");
530
- return { kind: "herdr", groupId: workspace, childId: tab, panes: await Promise.all(objects(s.panes)
531
- .filter(p => p.workspace_id === workspace && p.tab_id === tab).map(async (p) => ({ id: p.pane_id,
532
- label: p.label || p.pane_id, agent: p.agent, agentStatus: p.agent_status,
533
- title: p.title || p.terminal_title_stripped, cwd: p.foreground_cwd || p.cwd,
534
- ...await paneChatState(server, p) }))) };
593
+ throw new BridgeError(409, "This terminal tab has changed. Refresh the computer.");
594
+ const mux = (await terminal()).terminalMux(server);
595
+ return { kind: mux.kind, mux, groupId: workspace, childId: tab, panes: await Promise.all(objects(s.panes)
596
+ .filter(p => p.workspace_id === workspace && p.tab_id === tab).map(async (p) => {
597
+ const chat = await paneChatState(server, p);
598
+ const record = await paneRecord(server, p, typeof chat.sessionId === "string" ? chat.sessionId : undefined);
599
+ const t = objects(s.tabs).find(candidate => candidate.tab_id === tab && candidate.workspace_id === workspace);
600
+ const w = objects(s.workspaces).find(candidate => candidate.workspace_id === workspace);
601
+ return { id: p.pane_id, label: p.label || p.pane_id, agent: p.agent, agentStatus: p.agent_status,
602
+ title: await recordTitle(record, { paneLabel: p.label, harnessTitle: p.title || p.terminal_title_stripped, tabLabel: t?.label, workspaceLabel: w?.label, fallbackLabel: p.label || p.pane_id }),
603
+ cwd: p.foreground_cwd || p.cwd, ...chat, ...paneAccountField(server, p) };
604
+ })) };
535
605
  }
536
606
  /** The pane a starting target names, if its terminal/process binding still
537
607
  * holds. Status is not checked here: a starting agent's first prompt (folder
@@ -552,14 +622,19 @@ export async function validateStartingTarget(target) {
552
622
  if (!pane)
553
623
  throw new BridgeError(409, "This agent pane changed. Reopen the chat.");
554
624
  // Force fresh process/log evidence before a mutation.
555
- if (await paneIdentity(target.server, pane, true))
556
- throw new BridgeError(409, "The conversation is ready. Wait for chat to attach before sending.");
625
+ await paneIdentity(target.server, pane, true);
557
626
  const state = await paneChatState(target.server, pane);
558
- if (!state.starting || state.startingToken !== target.startingToken)
627
+ const binding = startingBindings.get(startingPaneKey(target.server, pane));
628
+ // Only a token issued while proven new may follow its first identified
629
+ // conversation, for one minute. Tokens read from mature/ambiguous panes
630
+ // grant nothing; a process/terminal/conversation change retires the token.
631
+ const transitioned = !!state.sessionId && binding?.wasStarting && binding.sessionId === state.sessionId
632
+ && binding.identifiedAt !== undefined && Date.now() - binding.identifiedAt <= 60_000;
633
+ if ((!state.starting && !transitioned) || state.startingToken !== target.startingToken)
559
634
  throw new BridgeError(409, "This starting agent changed. Reopen the chat.");
560
635
  if (["blocked", "waiting", "unknown"].includes(String(pane.agent_status)))
561
636
  throw new BridgeError(409, "This agent needs input in the terminal first.");
562
- return pane;
637
+ return transitioned ? { ...pane, startingSession: state.sessionId } : pane;
563
638
  }
564
639
  /** Identities already resolved for a shared snapshot's pane objects, so every
565
640
  * stream reading the same snapshot resolves a pane once. */
@@ -0,0 +1,4 @@
1
+ /** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
2
+ export declare const FAST_HOOK_FILE = "claude-hook.mjs";
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";
@@ -0,0 +1,68 @@
1
+ // Claude Code runs its agent hooks as a fresh process per event. Loading the
2
+ // ~2 MB Hook bundle for each one cost a loaded machine past Claude's timeout
3
+ // ("UserPromptSubmit hook timed out", output discarded), losing delivery
4
+ // confirmation, dispatch returns and turn records. Install writes this small
5
+ // script into each version's folder next to its bundle, so `current/` always
6
+ // pairs the script with the daemon it talks to: in a Herdr pane it sends the same /hook
7
+ // body agentHook (agent-hooks.ts) builds over agent.sock and prints the same
8
+ // reply; anything it cannot place itself (a tmux pane, another agent) runs the
9
+ // bundle's full handler in the same process.
10
+ //
11
+ // It must stay dependency-free and in step with agentHook. The daemon gates
12
+ // the git module itself and the hook module's settings entries are removed
13
+ // when it is off, so the store's module config is not read here.
14
+ import path from "node:path";
15
+ /** The script's file name in a version's folder, beside `bridge-hook.mjs`. */
16
+ export const FAST_HOOK_FILE = "claude-hook.mjs";
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.
19
+ import { request } from "node:http";
20
+ import { homedir } from "node:os";
21
+ import path from "node:path";
22
+ import { fileURLToPath, pathToFileURL } from "node:url";
23
+ const env = process.env, source = process.argv[2];
24
+ async function full() {
25
+ const bundle = path.join(path.dirname(fileURLToPath(import.meta.url)), "bridge-hook.mjs");
26
+ process.argv = [process.argv[0], bundle, "hook", source];
27
+ await import(pathToFileURL(bundle).href);
28
+ }
29
+ function herdrPane() {
30
+ if (!env.HERDR_SOCKET_PATH) return undefined;
31
+ const socket = path.resolve(env.HERDR_SOCKET_PATH), root = path.resolve(env.PHREN_HERDR_HOME || path.join(homedir(), ".config/herdr"));
32
+ const server = socket === path.join(root, "herdr.sock") ? "default"
33
+ : socket.startsWith(path.join(root, "sessions") + path.sep) ? path.basename(path.dirname(socket)) : undefined;
34
+ const { HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane } = env;
35
+ return server && workspace && tab && pane ? { server, workspace, tab, pane } : undefined;
36
+ }
37
+ const plain = value => value && typeof value === "object" && !Array.isArray(value) ? value : {};
38
+ async function forward(place) {
39
+ let input = "";
40
+ for await (const chunk of process.stdin) { input += chunk.toString(); if (input.length > 1_048_576) return; }
41
+ const value = plain(JSON.parse(input));
42
+ if (value.agent_id || value.agentId || value.isSidechain || value.is_sidechain) return;
43
+ const target = { ...place, source, session: value.session_id || value.sessionId };
44
+ const event = String(value.hook_event_name || "SessionStart");
45
+ const dispatchId = (event === "SessionStart" || event === "UserPromptSubmit") && /^[A-Za-z0-9_-]{8,64}$/.test(env.PHREN_DISPATCH_ID ?? "") ? env.PHREN_DISPATCH_ID : undefined;
46
+ const tasks = Array.isArray(value.background_tasks)
47
+ ? value.background_tasks.filter(task => !["completed", "failed", "killed", "stopped"].includes(String(plain(task).status))) : undefined;
48
+ const stop = event !== "Stop" ? {} : { ...(tasks ? { background: tasks.length } : {}),
49
+ ...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
50
+ const data = JSON.stringify({ target, event, ...(dispatchId ? { dispatchId } : {}),
51
+ tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
52
+ ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}), ...stop });
53
+ const socketPath = path.join(env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"), "agent.sock");
54
+ 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,
56
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
57
+ let result = "";
58
+ res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384) req.destroy(); });
59
+ res.on("end", () => { if (res.statusCode === 200 && (event === "PermissionRequest" || (event === "UserPromptSubmit" && result.includes("\\"decision\\"")))) process.stdout.write(result); resolve(); });
60
+ res.on("error", () => resolve());
61
+ });
62
+ req.on("error", () => resolve()); req.on("timeout", () => { req.destroy(); resolve(); }); req.end(data);
63
+ });
64
+ }
65
+ // Outside Herdr a tmux pane is placed by asking tmux, which the bundle does.
66
+ if (source !== "claude" || (env.HERDR_ENV !== "1" && env.TMUX)) await full().catch(() => {});
67
+ else if (env.HERDR_ENV === "1") { const place = herdrPane(); if (place) await forward(place).catch(() => {}); }
68
+ `;
@@ -4,6 +4,21 @@ export declare function upgradeKeys(text: string): {
4
4
  text: string;
5
5
  changed: number;
6
6
  };
7
+ /** The existing LaunchAgent's own EnvironmentVariables beyond phren's, read
8
+ * with plutil. A missing or unreadable plist has none. */
9
+ export declare function extraLaunchAgentEnvironment(file: string, read?: (file: string) => Promise<string>): Promise<Record<string, string>>;
10
+ export interface LaunchAgentValues {
11
+ label: string;
12
+ node: string;
13
+ program: string;
14
+ path: string;
15
+ root: string;
16
+ herdr: string;
17
+ store: string;
18
+ profile: string;
19
+ }
20
+ /** The Hook's LaunchAgent: phren's own environment first, then every kept key. */
21
+ export declare function launchAgentXml(values: LaunchAgentValues, extra?: Record<string, string>): string;
7
22
  /** The forwarder the forced command uses for the phone's byte pipe. */
8
23
  export type GatewayKind = "socat" | "nc" | "node";
9
24
  export interface GatewayEnvironment {
@@ -32,7 +47,7 @@ interface SettingsEdit {
32
47
  before?: string;
33
48
  after: string;
34
49
  }
35
- export declare function planAgentHooks(program: string, remove?: boolean, modules?: ModuleSnapshot): Promise<SettingsEdit[]>;
50
+ export declare function planAgentHooks(program: string, remove?: boolean, modules?: ModuleSnapshot, fastClaude?: boolean): Promise<SettingsEdit[]>;
36
51
  /** The first line of every plugin copy phren wrote; a copy without it belongs to the user. */
37
52
  export declare const OPENCODE_PLUGIN_MARKER = "// Installed by Phren Hook";
38
53
  /** Whether to (re)write the installed plugin: a missing copy, or one phren wrote that is now out of date. */
@@ -3,15 +3,19 @@ import { defaultPhrenPath } from "../shared.js";
3
3
  import { disabledHint } from "../modules/registry.js";
4
4
  import { execFile } from "node:child_process";
5
5
  import { usageStatusLine } from "./usage.js";
6
- import { chmod, copyFile, mkdir, open, readFile, rename, symlink, unlink, lstat, writeFile } from "node:fs/promises";
6
+ import { access, chmod, copyFile, mkdir, open, readFile, rename, symlink, unlink, lstat, writeFile } from "node:fs/promises";
7
7
  import { homedir } from "node:os";
8
8
  import { codexHome, claudeConfigDir } from "../home-paths.js";
9
+ import { claudeHomes } from "./claude-accounts.js";
10
+ import { syncAccountMcpServers } from "./claude-account-setup.js";
9
11
  import path from "node:path";
10
12
  import { fileURLToPath } from "node:url";
11
13
  import { promisify } from "node:util";
12
14
  import { bridgeRoot, object, objects, atomic, socketPath } from "./protocol.js";
13
15
  import { herdrRoot } from "./herdr.js";
14
16
  import { health } from "./transport.js";
17
+ import { FAST_HOOK_SOURCE, fastHookPath } from "./hook-fast.js";
18
+ import { readStoredVoice, SPEECH_VOICE_ENV, writeSpeechVoice } from "./speech-voice.js";
15
19
  const exec = promisify(execFile);
16
20
  const label = "com.phren.hook";
17
21
  const unit = "phren-hook.service";
@@ -62,6 +66,34 @@ export function upgradeKeys(text) {
62
66
  }
63
67
  const quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
64
68
  const xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
69
+ /** The service environment install writes. Any other key in an existing
70
+ * LaunchAgent (a voice, a proxy, an API override someone added by hand) is
71
+ * kept: before, `phren bridge update` rewrote the plist and dropped it. */
72
+ const MANAGED_ENVIRONMENT = new Set(["PATH", "PHREN_BRIDGE_HOME", "PHREN_HERDR_HOME", "PHREN_PATH", "PHREN_PROFILE"]);
73
+ /** The existing LaunchAgent's own EnvironmentVariables beyond phren's, read
74
+ * with plutil. A missing or unreadable plist has none. */
75
+ export async function extraLaunchAgentEnvironment(file, read = async (f) => (await exec("plutil", ["-convert", "json", "-o", "-", f])).stdout) {
76
+ let parsed;
77
+ try {
78
+ parsed = JSON.parse(await read(file));
79
+ }
80
+ catch {
81
+ return {};
82
+ }
83
+ const extra = {};
84
+ for (const [key, value] of Object.entries(object(object(parsed).EnvironmentVariables))) {
85
+ if (!MANAGED_ENVIRONMENT.has(key) && /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(key) && typeof value === "string")
86
+ extra[key] = value;
87
+ }
88
+ return extra;
89
+ }
90
+ /** The Hook's LaunchAgent: phren's own environment first, then every kept key. */
91
+ export function launchAgentXml(values, extra = {}) {
92
+ const environment = [["PATH", values.path], ["PHREN_BRIDGE_HOME", values.root], ["PHREN_HERDR_HOME", values.herdr],
93
+ ["PHREN_PATH", values.store], ["PHREN_PROFILE", values.profile], ...Object.entries(extra).filter(([key]) => !MANAGED_ENVIRONMENT.has(key))];
94
+ const env = environment.map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`).join("");
95
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${xml(values.label)}</string><key>ProgramArguments</key><array><string>${xml(values.node)}</string><string>${xml(values.program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict>${env}</dict><key>StandardErrorPath</key><string>${xml(path.join(values.root, "service.log"))}</string></dict></plist>\n`;
96
+ }
65
97
  const systemdQuote = (s) => '"' + s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%") + '"';
66
98
  async function commandOutput(file, args, env) {
67
99
  try {
@@ -154,15 +186,29 @@ async function startService() {
154
186
  }
155
187
  }
156
188
  // RunAtLoad does not always fire for a job bootstrapped from an SSH login.
157
- await exec("launchctl", ["kickstart", `${domain}/${label}`]).catch(() => { });
189
+ // A failed kickstart is only fatal if the version check below also fails.
190
+ const kickstartError = await exec("launchctl", ["kickstart", `${domain}/${label}`]).then(() => undefined, error => String(error.stderr || error.message).trim());
158
191
  if (!gui)
159
192
  console.log(`No one is logged in at this Mac's screen, so the Phren Hook runs in ${domain}. After a screen login, run phren bridge install again to move it into gui/${uid}.`);
193
+ return kickstartError;
160
194
  }
161
195
  else {
162
196
  await exec("systemctl", ["--user", "daemon-reload"]);
163
197
  await exec("systemctl", ["--user", "enable", "--now", unit]);
164
198
  }
165
199
  }
200
+ async function serviceReady(version) {
201
+ for (let i = 0; i < 50; i++) {
202
+ try {
203
+ if ((await health()).version === version)
204
+ return true;
205
+ }
206
+ catch { /* Hook is still starting */ }
207
+ if (i < 49)
208
+ await new Promise(resolve => setTimeout(resolve, 200));
209
+ }
210
+ return false;
211
+ }
166
212
  export async function install(version, noService = false) {
167
213
  if (!["darwin", "linux"].includes(process.platform))
168
214
  throw new Error("Phren Hook supports macOS and Linux.");
@@ -192,6 +238,7 @@ export async function install(version, noService = false) {
192
238
  const stagedBundle = installedBundle + `.phren-${process.pid}`;
193
239
  await copyFile(bundle, stagedBundle);
194
240
  await rename(stagedBundle, installedBundle);
241
+ await atomic(fastHookPath(destination), FAST_HOOK_SOURCE);
195
242
  const previous = await readFile(path.join(root, "installed.json"), "utf8").then(v => JSON.parse(v)).catch(() => null);
196
243
  const gateway = await detectGateway();
197
244
  await atomic(path.join(root, "dispatch"), gatewayScript(gateway, {
@@ -204,7 +251,12 @@ export async function install(version, noService = false) {
204
251
  if (process.platform === "darwin") {
205
252
  const folder = path.join(homedir(), "Library/LaunchAgents");
206
253
  await mkdir(folder, { recursive: true });
207
- await atomic(path.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(path.join(root, "service.log"))}</string></dict></plist>\n`);
254
+ const plist = path.join(folder, `${label}.plist`);
255
+ const extra = await extraLaunchAgentEnvironment(plist);
256
+ // The talk-mode voice used to live only here; it moves to the Hook's own setting.
257
+ if (extra[SPEECH_VOICE_ENV] && !(await readStoredVoice()))
258
+ await writeSpeechVoice(extra[SPEECH_VOICE_ENV]).catch(() => { });
259
+ await atomic(plist, launchAgentXml({ label, node: process.execPath, program, path: environmentPath, root, herdr, store: modules.store, profile: modules.profile }, extra));
208
260
  }
209
261
  else {
210
262
  const folder = path.join(homedir(), ".config/systemd/user");
@@ -216,26 +268,26 @@ export async function install(version, noService = false) {
216
268
  await activate(version);
217
269
  try {
218
270
  if (!noService) {
219
- await startService();
220
- let ready = false;
221
- for (let i = 0; i < 30; i++) {
222
- try {
223
- const status = await health();
224
- ready = status.version === version;
225
- }
226
- catch { /* bounded readiness check */ }
227
- if (ready)
228
- break;
229
- await new Promise(resolve => setTimeout(resolve, 200));
271
+ let kickstartError = await startService();
272
+ let ready = await serviceReady(version);
273
+ if (!ready && process.platform === "darwin") {
274
+ // launchd may accept bootstrap but leave a throttled or old job behind.
275
+ // Reload the plist and give the new job a second bounded start window.
276
+ await stopService();
277
+ kickstartError = await startService();
278
+ ready = await serviceReady(version);
230
279
  }
231
280
  if (!ready) {
232
281
  const uid = process.getuid(), domain = process.platform === "darwin" ? launchDomain(uid, await guiSession(uid)) : undefined;
233
- throw new Error(`The new Phren Hook did not become ready. See ${serviceLog}. ` + (domain
282
+ throw new Error(`The new Phren Hook ${version} did not become ready after ${domain ? "two launchd starts" : "starting the service"}.${kickstartError ? ` Last launchctl kickstart error: ${kickstartError}.` : ""} See ${serviceLog}. ` + (domain
234
283
  ? `To start it by hand:\n ${launchCommands(domain, launchAgentPlist()).join("\n ")}`
235
284
  : `Check systemctl --user status ${unit}.`));
236
285
  }
237
286
  }
238
287
  await applyAgentHooks(hookEdits);
288
+ const synced = await syncAccountMcpServers().catch(() => []);
289
+ if (synced.length)
290
+ console.log(`Claude accounts: refreshed MCP servers in ${synced.join(", ")}.`);
239
291
  if (await applyOpencodePlugin()) {
240
292
  console.log("opencode chat: restart any opencode session started before now so it loads the transcript plugin.");
241
293
  }
@@ -300,14 +352,22 @@ async function missingFile(operation) {
300
352
  throw error;
301
353
  }
302
354
  }
303
- export async function planAgentHooks(program, remove = false, modules) {
355
+ /** Whether the version `current/` points at ships the Claude forwarder; one
356
+ * from before it does not, and its Claude callbacks run the bundle. */
357
+ const currentHasFastHook = (root) => access(fastHookPath(path.join(root, "current"))).then(() => true, () => false);
358
+ export async function planAgentHooks(program, remove = false, modules, fastClaude = true) {
304
359
  const edits = [];
360
+ // Extra Claude homes (one per account) get the same hooks; a symlinked settings.json shares another home's, so it is skipped.
361
+ const extraClaude = claudeHomes().slice(1).map(home => ["claude", path.join(home.dir, "settings.json")]);
305
362
  for (const [source, file] of [
306
363
  ["codex", path.join(codexHome(), "hooks.json")],
307
364
  ["claude", path.join(claudeConfigDir(), "settings.json")],
365
+ ...extraClaude,
308
366
  ["copilot", path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "hooks/phren.json")],
309
367
  ]) {
310
368
  const metadata = await missingFile(lstat(file));
369
+ if (metadata && extraClaude.some(([, extra]) => extra === file) && (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 2_097_152))
370
+ continue;
311
371
  if (metadata && (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 2_097_152)) {
312
372
  throw new Error(`Agent settings require a manual update: ${file}`);
313
373
  }
@@ -321,8 +381,11 @@ export async function planAgentHooks(program, remove = false, modules) {
321
381
  if (config.hooks !== undefined && (!config.hooks || typeof config.hooks !== "object" || Array.isArray(config.hooks)))
322
382
  throw new Error(`Invalid hook configuration: ${file}`);
323
383
  const hooks = object(config.hooks);
324
- const command = `${quote(process.execPath)} ${quote(program)} hook ${source}`;
325
- const ownHook = (entry) => typeof entry === "string" && entry.endsWith(` ${quote(program)} hook ${source}`);
384
+ // Claude's callbacks run the small forwarder beside the bundle (hook-fast.ts)
385
+ // instead of loading the whole bundle for every event.
386
+ const fast = fastHookPath(path.dirname(program));
387
+ const command = source === "claude" && fastClaude ? `${quote(process.execPath)} ${quote(fast)} claude` : `${quote(process.execPath)} ${quote(program)} hook ${source}`;
388
+ const ownHook = (entry) => typeof entry === "string" && (entry.endsWith(` ${quote(program)} hook ${source}`) || (source === "claude" && entry.endsWith(` ${quote(fast)} claude`)));
326
389
  if (remove || modules?.has("hook") === false) {
327
390
  const owned = Object.values(hooks).flatMap(objects).some(group => ownHook(group.command) || ownHook(group.bash) || objects(group.hooks).some(hook => ownHook(hook.command)));
328
391
  const statusChanged = source === "claude" && JSON.stringify(usageStatusLine(config.statusLine, program, true)) !== JSON.stringify(config.statusLine);
@@ -339,7 +402,7 @@ export async function planAgentHooks(program, remove = false, modules) {
339
402
  config.version = 1;
340
403
  for (const event of ["SessionStart", "UserPromptSubmit"]) {
341
404
  const entries = objects(hooks[event]).filter(h => !ownHook(h.bash) && !ownHook(h.command));
342
- hooks[event] = remove || modules?.has("hook") === false ? entries : [...entries, { type: "command", bash: command, timeoutSec: 3 }];
405
+ hooks[event] = remove || modules?.has("hook") === false ? entries : [...entries, { type: "command", bash: command, timeoutSec: 15 }];
343
406
  }
344
407
  }
345
408
  else {
@@ -350,7 +413,7 @@ export async function planAgentHooks(program, remove = false, modules) {
350
413
  // Codex names tools differently across versions; filter its callbacks
351
414
  // inside the Hook. Claude can narrow its registration here.
352
415
  const group = event.endsWith("ToolUse") ? { ...(source === "claude" ? { matcher: "Bash|Write|Edit|MultiEdit|NotebookEdit|apply_patch|str_replace_editor" } : {}), hooks: [{ type: "command", command, timeout: 10 }] }
353
- : { hooks: [{ type: "command", command, timeout: event === "PermissionRequest" ? 60 : 3 }] };
416
+ : { hooks: [{ type: "command", command, timeout: event === "PermissionRequest" ? 60 : 15 }] };
354
417
  const owner = event.endsWith("ToolUse") ? "git" : "hook";
355
418
  hooks[event] = remove || modules?.has("hook") === false || modules?.has(owner) === false ? groups : [...groups, group];
356
419
  }
@@ -440,6 +503,10 @@ export async function rollback() {
440
503
  await stopService();
441
504
  await activate(config.previous);
442
505
  await startService();
506
+ // The version now in `current/` decides whether Claude's callbacks run its
507
+ // forwarder or, from before the forwarder, its bundle.
508
+ const root = bridgeRoot();
509
+ await applyAgentHooks(await planAgentHooks(path.join(root, "current/bridge-hook.mjs"), false, moduleSnapshot(defaultPhrenPath(), undefined, true), await currentHasFastHook(root)));
443
510
  await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version }) + "\n");
444
511
  }
445
512
  export async function reconcileModuleHooks(store, profile) {
@@ -448,7 +515,7 @@ export async function reconcileModuleHooks(store, profile) {
448
515
  // Synced enablement alone never installs a host service or enrolls a key.
449
516
  if (!await missingFile(readFile(path.join(root, "installed.json"))))
450
517
  return;
451
- await applyAgentHooks(await planAgentHooks(path.join(root, "current/bridge-hook.mjs"), false, modules));
518
+ await applyAgentHooks(await planAgentHooks(path.join(root, "current/bridge-hook.mjs"), false, modules, await currentHasFastHook(root)));
452
519
  await applyOpencodePlugin(!modules.has("hook"));
453
520
  if (!modules.has("hook"))
454
521
  await stopService();