@phren/cli 0.3.11 → 0.3.13

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 (182) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  4. package/dist/bridge/agent-hook-stores.js +5 -0
  5. package/dist/bridge/agent-hooks.d.ts +162 -5
  6. package/dist/bridge/agent-hooks.js +682 -49
  7. package/dist/bridge/approval-summary.d.ts +16 -0
  8. package/dist/bridge/approval-summary.js +133 -0
  9. package/dist/bridge/authority-command.d.ts +20 -0
  10. package/dist/bridge/authority-command.js +120 -0
  11. package/dist/bridge/authority.d.ts +223 -0
  12. package/dist/bridge/authority.js +231 -0
  13. package/dist/bridge/claude-account-setup.d.ts +14 -0
  14. package/dist/bridge/claude-account-setup.js +69 -0
  15. package/dist/bridge/claude-accounts.d.ts +49 -0
  16. package/dist/bridge/claude-accounts.js +195 -0
  17. package/dist/bridge/code-routes.js +2 -2
  18. package/dist/bridge/codex-app-server.d.ts +144 -0
  19. package/dist/bridge/codex-app-server.js +319 -0
  20. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  21. package/dist/bridge/codex-auth-refresh.js +71 -0
  22. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  23. package/dist/bridge/codex-hook-trust.js +237 -0
  24. package/dist/bridge/codex-question-reply.d.ts +16 -0
  25. package/dist/bridge/codex-question-reply.js +57 -0
  26. package/dist/bridge/codex-review-mode.d.ts +10 -0
  27. package/dist/bridge/codex-review-mode.js +74 -0
  28. package/dist/bridge/codex-servers.d.ts +217 -0
  29. package/dist/bridge/codex-servers.js +636 -0
  30. package/dist/bridge/command.js +97 -4
  31. package/dist/bridge/computer-identity.d.ts +75 -0
  32. package/dist/bridge/computer-identity.js +166 -0
  33. package/dist/bridge/conductor-group.d.ts +91 -8
  34. package/dist/bridge/conductor-group.js +105 -9
  35. package/dist/bridge/conductor-role.d.ts +94 -0
  36. package/dist/bridge/conductor-role.js +176 -0
  37. package/dist/bridge/conductor-sets.d.ts +20 -0
  38. package/dist/bridge/conductor-sets.js +59 -0
  39. package/dist/bridge/dispatch-command.d.ts +3 -0
  40. package/dist/bridge/dispatch-command.js +82 -12
  41. package/dist/bridge/dispatch-returns.d.ts +128 -19
  42. package/dist/bridge/dispatch-returns.js +371 -54
  43. package/dist/bridge/dispatch.d.ts +128 -3
  44. package/dist/bridge/dispatch.js +303 -42
  45. package/dist/bridge/fanouts.d.ts +7 -1
  46. package/dist/bridge/fanouts.js +39 -4
  47. package/dist/bridge/folder-trust.d.ts +56 -0
  48. package/dist/bridge/folder-trust.js +195 -0
  49. package/dist/bridge/grants.d.ts +22 -1
  50. package/dist/bridge/grants.js +57 -9
  51. package/dist/bridge/hand-off-queue.d.ts +74 -0
  52. package/dist/bridge/hand-off-queue.js +235 -0
  53. package/dist/bridge/hand-off.d.ts +30 -10
  54. package/dist/bridge/hand-off.js +79 -46
  55. package/dist/bridge/harness-status.d.ts +11 -0
  56. package/dist/bridge/harness-status.js +32 -0
  57. package/dist/bridge/harnesses.d.ts +39 -0
  58. package/dist/bridge/harnesses.js +65 -0
  59. package/dist/bridge/health.d.ts +2 -0
  60. package/dist/bridge/health.js +1 -1
  61. package/dist/bridge/herdr.d.ts +11 -2
  62. package/dist/bridge/herdr.js +98 -23
  63. package/dist/bridge/hook-fast.d.ts +4 -0
  64. package/dist/bridge/hook-fast.js +68 -0
  65. package/dist/bridge/install.d.ts +16 -1
  66. package/dist/bridge/install.js +102 -21
  67. package/dist/bridge/launch-brief.d.ts +96 -0
  68. package/dist/bridge/launch-brief.js +164 -0
  69. package/dist/bridge/model-switch.d.ts +3 -0
  70. package/dist/bridge/model-switch.js +17 -1
  71. package/dist/bridge/models.d.ts +8 -4
  72. package/dist/bridge/models.js +24 -8
  73. package/dist/bridge/mux-wire.d.ts +9 -0
  74. package/dist/bridge/mux-wire.js +19 -0
  75. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  76. package/dist/bridge/opencode-pane-server.js +332 -0
  77. package/dist/bridge/opencode-panes.d.ts +111 -0
  78. package/dist/bridge/opencode-panes.js +295 -0
  79. package/dist/bridge/pane-accounts.d.ts +8 -0
  80. package/dist/bridge/pane-accounts.js +46 -0
  81. package/dist/bridge/pane-status.d.ts +12 -0
  82. package/dist/bridge/pane-status.js +50 -1
  83. package/dist/bridge/prompt-startup.d.ts +5 -0
  84. package/dist/bridge/prompt-startup.js +24 -0
  85. package/dist/bridge/protocol.d.ts +5 -0
  86. package/dist/bridge/protocol.js +4 -0
  87. package/dist/bridge/push.d.ts +11 -4
  88. package/dist/bridge/push.js +27 -4
  89. package/dist/bridge/questions.d.ts +37 -2
  90. package/dist/bridge/questions.js +158 -15
  91. package/dist/bridge/resources.d.ts +9 -3
  92. package/dist/bridge/resources.js +24 -8
  93. package/dist/bridge/schedule-format.d.ts +2 -0
  94. package/dist/bridge/schedule-format.js +3 -0
  95. package/dist/bridge/schedule-launch.d.ts +2 -1
  96. package/dist/bridge/schedule-launch.js +27 -53
  97. package/dist/bridge/schedule-watch.d.ts +24 -1
  98. package/dist/bridge/schedule-watch.js +89 -2
  99. package/dist/bridge/server-launch.d.ts +22 -5
  100. package/dist/bridge/server-launch.js +238 -32
  101. package/dist/bridge/server-overview.d.ts +10 -3
  102. package/dist/bridge/server-overview.js +32 -15
  103. package/dist/bridge/server-pane-routes.d.ts +3 -0
  104. package/dist/bridge/server-pane-routes.js +150 -18
  105. package/dist/bridge/server-routes.d.ts +11 -0
  106. package/dist/bridge/server-routes.js +214 -36
  107. package/dist/bridge/server-stream.d.ts +2 -0
  108. package/dist/bridge/server-stream.js +22 -8
  109. package/dist/bridge/server.d.ts +6 -1
  110. package/dist/bridge/server.js +58 -13
  111. package/dist/bridge/session-activity.d.ts +93 -0
  112. package/dist/bridge/session-activity.js +139 -0
  113. package/dist/bridge/session-rename.d.ts +48 -0
  114. package/dist/bridge/session-rename.js +190 -0
  115. package/dist/bridge/session-servers.js +2 -2
  116. package/dist/bridge/settings-switch.d.ts +60 -0
  117. package/dist/bridge/settings-switch.js +287 -0
  118. package/dist/bridge/speech-voice.d.ts +55 -0
  119. package/dist/bridge/speech-voice.js +132 -0
  120. package/dist/bridge/speech.d.ts +70 -11
  121. package/dist/bridge/speech.js +169 -41
  122. package/dist/bridge/stalls.d.ts +22 -0
  123. package/dist/bridge/stalls.js +57 -0
  124. package/dist/bridge/sudo.d.ts +209 -0
  125. package/dist/bridge/sudo.js +501 -0
  126. package/dist/bridge/terminal-herdr.js +9 -3
  127. package/dist/bridge/terminal-tmux.d.ts +15 -3
  128. package/dist/bridge/terminal-tmux.js +103 -13
  129. package/dist/bridge/terminal.d.ts +27 -4
  130. package/dist/bridge/terminal.js +8 -1
  131. package/dist/bridge/transcript-claude.d.ts +4 -0
  132. package/dist/bridge/transcript-claude.js +186 -16
  133. package/dist/bridge/transcript-codex.d.ts +0 -2
  134. package/dist/bridge/transcript-codex.js +29 -4
  135. package/dist/bridge/transcript-preview.d.ts +1 -0
  136. package/dist/bridge/transcript-preview.js +24 -4
  137. package/dist/bridge/transcripts.d.ts +15 -2
  138. package/dist/bridge/transcripts.js +47 -16
  139. package/dist/bridge/turn-records.d.ts +85 -0
  140. package/dist/bridge/turn-records.js +143 -0
  141. package/dist/bridge/uploads.d.ts +3 -0
  142. package/dist/bridge/uploads.js +14 -0
  143. package/dist/bridge/usage.d.ts +56 -10
  144. package/dist/bridge/usage.js +190 -45
  145. package/dist/bridge-hook.mjs +27975 -20636
  146. package/dist/cli/claude-unmanaged.d.ts +12 -0
  147. package/dist/cli/claude-unmanaged.js +105 -0
  148. package/dist/cli/schedules.js +2 -1
  149. package/dist/cli/session-start.js +10 -1
  150. package/dist/cli/session-stop.js +9 -1
  151. package/dist/cli-registry.js +31 -6
  152. package/dist/data/task-receipts.d.ts +19 -0
  153. package/dist/data/task-receipts.js +68 -0
  154. package/dist/data/tasks.js +4 -1
  155. package/dist/generated/memory-ui-graph.browser.js +63 -63
  156. package/dist/graph-core/model.js +24 -3
  157. package/dist/graph-core/types.d.ts +4 -1
  158. package/dist/graph-core/types.js +1 -0
  159. package/dist/init/init-preset.js +7 -3
  160. package/dist/init/init-uninstall.js +2 -11
  161. package/dist/init/teardown.d.ts +3 -0
  162. package/dist/init/teardown.js +47 -0
  163. package/dist/link/context.js +21 -9
  164. package/dist/mcp/plugin-mode.js +1 -1
  165. package/dist/memory-ui-graph.runtime.js +63 -63
  166. package/dist/modules/code-package.d.ts +1 -0
  167. package/dist/modules/code-package.js +36 -7
  168. package/dist/modules/registry.js +17 -16
  169. package/dist/profile-store.d.ts +6 -0
  170. package/dist/profile-store.js +25 -1
  171. package/dist/shell/graph/glyphs.js +4 -0
  172. package/dist/shell/graph/graph-view.js +2 -0
  173. package/dist/status.js +7 -1
  174. package/dist/sync/task-claim.js +3 -2
  175. package/dist/task/lifecycle.js +25 -4
  176. package/dist/test-global-setup.js +5 -0
  177. package/dist/tools/dispatch.js +52 -4
  178. package/dist/tools/tasks.js +10 -1
  179. package/package.json +1 -1
  180. package/plugins/opencode/phren-transcript.js +87 -4
  181. package/starter/global/AGENTS.md +4 -0
  182. package/starter/global/skills/conductor/SKILL.md +51 -4
@@ -0,0 +1,65 @@
1
+ // What this computer can launch: each harness's install state and, for Claude and Codex, its accounts.
2
+ // Served as GET /v1/harnesses and as `harnesses` on /v1/dispatch/capacity. See docs/accounts.md.
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { codexHome } from "../home-paths.js";
6
+ import { claudeAccountRef, claudeAuthStatus, claudeHomes, CODEX_ACCOUNT } from "./claude-accounts.js";
7
+ import { toolVersion } from "./health.js";
8
+ const SOURCES = ["claude", "codex", "opencode", "copilot"];
9
+ export async function harnessInventory(deps = {}) {
10
+ const env = deps.env ?? process.env;
11
+ const probe = deps.toolVersion ?? ((tool) => toolVersion(tool));
12
+ const harnesses = await Promise.all(SOURCES.map(async (source) => {
13
+ const found = await probe(source);
14
+ // Only a missing binary is definite; a slow or failing --version (a loaded computer) stays usable.
15
+ if (found.status === "missing")
16
+ return { source, installed: false, usable: false, reason: "Not installed" };
17
+ const base = { source, installed: true, ...(found.version ? { version: found.version } : {}) };
18
+ if (source === "claude") {
19
+ const accounts = await Promise.all(claudeHomes(env).map(async (home) => {
20
+ const auth = await claudeAuthStatus(home, deps.authRunner);
21
+ // An unanswered sign-in check stays usable: only Claude saying "logged out" hides an account.
22
+ const usable = auth.signedIn || auth.unknown === true;
23
+ return { ...claudeAccountRef(home), signedIn: auth.signedIn, usable,
24
+ ...(auth.plan ? { plan: auth.plan } : {}), ...(auth.signedIn ? {} : { reason: auth.reason ?? "Not signed in" }) };
25
+ }));
26
+ const usable = accounts.some(account => account.usable);
27
+ return { ...base, usable, ...(usable ? {} : { reason: "No signed-in Claude account" }), accounts };
28
+ }
29
+ if (source === "codex") {
30
+ const signedIn = existsSync(path.join(codexHome(env), "auth.json"));
31
+ return { ...base, usable: signedIn, ...(signedIn ? {} : { reason: "Not signed in" }),
32
+ accounts: [{ ...CODEX_ACCOUNT, signedIn, usable: signedIn, ...(signedIn ? {} : { reason: "Not signed in" }) }] };
33
+ }
34
+ return { ...base, usable: true };
35
+ }));
36
+ return { harnesses };
37
+ }
38
+ /** The inventory, or undefined when it is not ready within `ms` (a cold `claude auth status` can take seconds). */
39
+ export function harnessInventoryWithin(ms, deps = {}) {
40
+ let timer;
41
+ const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), ms); });
42
+ return Promise.race([harnessInventory(deps).catch(() => undefined), late]).finally(() => clearTimeout(timer));
43
+ }
44
+ /** `PHREN_LAUNCH_CHECK=off`: no early launch refusal and no `harnesses` advertised to dispatch (tests, or a misreporting computer). */
45
+ export function launchCheckOff(env = process.env) {
46
+ return /^(off|0|false|no)$/i.test(env.PHREN_LAUNCH_CHECK?.trim() ?? "");
47
+ }
48
+ /** Whether a launch of `source` (and `accountId`) should work on a computer with this inventory. */
49
+ export function hasUsable(inventory, source, accountId) {
50
+ const entry = inventory.harnesses.find(item => item.source === source);
51
+ if (!entry || !entry.installed)
52
+ return { ok: false, code: "harness_unavailable", reason: entry?.reason ?? "Not installed" };
53
+ if (!entry.accounts) {
54
+ return accountId && accountId !== "default"
55
+ ? { ok: false, code: "account_unavailable", reason: `${source} has no accounts` }
56
+ : entry.usable ? { ok: true } : { ok: false, code: "harness_unavailable", reason: entry.reason ?? "Unavailable" };
57
+ }
58
+ const id = accountId?.trim() || "default";
59
+ const account = entry.accounts.find(item => item.id === id);
60
+ if (!account)
61
+ return { ok: false, code: "account_unavailable", reason: `No ${source} account "${id}"` };
62
+ if (!account.usable)
63
+ return { ok: false, code: "account_unavailable", reason: account.reason ?? "Not signed in" };
64
+ return { ok: true };
65
+ }
@@ -122,6 +122,8 @@ export declare function clearVersionCache(): void;
122
122
  export declare function storeSync(store: string): Promise<StoreSync[]>;
123
123
  /** The newest run in schedule-runs.jsonl, with its schedule's name when the project still has it. */
124
124
  export declare function lastScheduledRun(store: string, runsFile?: string): Promise<LastScheduledRun | null>;
125
+ /** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
126
+ export declare function ownHostKey(): Promise<string | undefined>;
125
127
  /** Whether this computer's hooks.yaml lists the caller, by pinned host key or by name. */
126
128
  export declare function listsCaller(caller: {
127
129
  name?: string;
@@ -144,7 +144,7 @@ export async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
144
144
  startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}) };
145
145
  }
146
146
  /** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
147
- async function ownHostKey() {
147
+ export async function ownHostKey() {
148
148
  try {
149
149
  return publicComputerKey(await readFile("/etc/ssh/ssh_host_ed25519_key.pub", "utf8"));
150
150
  }
@@ -1,3 +1,4 @@
1
+ import type { AccountRef } from "./claude-accounts.js";
1
2
  import { BridgeError, type Json, type Target, type StartingTarget } from "./protocol.js";
2
3
  export declare function herdrRoot(): string;
3
4
  /** Where Herdr's socket for `server` lives. */
@@ -63,9 +64,13 @@ export interface PaneAddress {
63
64
  }
64
65
  /** The snapshot's pane at `address`; with a `source`, only while that agent runs there. */
65
66
  export declare function findPane(s: Json, address: PaneAddress): Json | undefined;
66
- /** A conductor's Herdr name: "conductor", or "conductor-" plus its label. */
67
+ /** A conductor's Herdr name: "conductor", or "conductor-" plus its label. Only
68
+ * a label since the Hook records the role (conductor-role.ts): read to migrate
69
+ * a conductor from before that record, and kept off workers' names. */
67
70
  export declare function isConductorName(name: string | undefined): boolean;
68
- export declare function workspaceSnapshot(s: Json, contextUsedPercent?: ReadonlyMap<Json, number>, approvalPanes?: ReadonlySet<string>, lastChanged?: ReadonlyMap<string, string>): Json;
71
+ /** `conductorPane` is the pane the Hook records as the conductor (null for
72
+ * none); left out, the agent's name decides, as before the record. */
73
+ export declare function workspaceSnapshot(s: Json, contextUsedPercent?: ReadonlyMap<Json, number>, approvalPanes?: ReadonlySet<string>, lastChanged?: ReadonlyMap<string, string>, conductorPane?: string | null): Json;
69
74
  export declare function paneIdentity(server: string, pane: Json, fresh?: boolean): Promise<string | undefined>;
70
75
  /** Copilot CLI changes conversation inside one process (/new, /clear,
71
76
  * /resume) and runs its sessionStart hook only once that conversation's first
@@ -87,6 +92,10 @@ export declare function paneForCodexSession(server: string, session: string, cwd
87
92
  export declare function paneChatState(server: string, pane: Json, options?: {
88
93
  tokenWhenIdentified?: boolean;
89
94
  }): Promise<Json>;
95
+ /** `{ account }` for a Claude pane whose account is known, else nothing. */
96
+ export declare function paneAccountField(server: string, pane: Json): {
97
+ account?: AccountRef;
98
+ };
90
99
  export declare function panes(server: string, workspace: string, tab: string): Promise<Json>;
91
100
  /** The pane a starting target names, if its terminal/process binding still
92
101
  * holds. Status is not checked here: a starting agent's first prompt (folder
@@ -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. */