@phren/cli 0.3.10 → 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 (184) 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/fanout-messages.js +2 -2
  42. package/dist/bridge/fanouts.d.ts +7 -1
  43. package/dist/bridge/fanouts.js +40 -5
  44. package/dist/bridge/folder-trust.d.ts +56 -0
  45. package/dist/bridge/folder-trust.js +195 -0
  46. package/dist/bridge/grants.d.ts +22 -1
  47. package/dist/bridge/grants.js +57 -9
  48. package/dist/bridge/hand-off.d.ts +21 -9
  49. package/dist/bridge/hand-off.js +58 -45
  50. package/dist/bridge/harness-status.d.ts +11 -0
  51. package/dist/bridge/harness-status.js +32 -0
  52. package/dist/bridge/harnesses.d.ts +39 -0
  53. package/dist/bridge/harnesses.js +65 -0
  54. package/dist/bridge/health.d.ts +2 -0
  55. package/dist/bridge/health.js +1 -1
  56. package/dist/bridge/herdr.d.ts +11 -2
  57. package/dist/bridge/herdr.js +98 -23
  58. package/dist/bridge/hook-fast.d.ts +4 -0
  59. package/dist/bridge/hook-fast.js +68 -0
  60. package/dist/bridge/install.d.ts +16 -1
  61. package/dist/bridge/install.js +88 -21
  62. package/dist/bridge/launch-brief.d.ts +96 -0
  63. package/dist/bridge/launch-brief.js +164 -0
  64. package/dist/bridge/model-switch.d.ts +3 -0
  65. package/dist/bridge/model-switch.js +17 -1
  66. package/dist/bridge/models.d.ts +8 -4
  67. package/dist/bridge/models.js +24 -8
  68. package/dist/bridge/mux-wire.d.ts +9 -0
  69. package/dist/bridge/mux-wire.js +19 -0
  70. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  71. package/dist/bridge/opencode-pane-server.js +332 -0
  72. package/dist/bridge/opencode-panes.d.ts +111 -0
  73. package/dist/bridge/opencode-panes.js +295 -0
  74. package/dist/bridge/pane-accounts.d.ts +8 -0
  75. package/dist/bridge/pane-accounts.js +46 -0
  76. package/dist/bridge/prompt-startup.d.ts +5 -0
  77. package/dist/bridge/prompt-startup.js +24 -0
  78. package/dist/bridge/protocol.d.ts +5 -0
  79. package/dist/bridge/protocol.js +4 -0
  80. package/dist/bridge/push.d.ts +5 -4
  81. package/dist/bridge/push.js +6 -4
  82. package/dist/bridge/questions.d.ts +37 -2
  83. package/dist/bridge/questions.js +158 -15
  84. package/dist/bridge/resources.d.ts +125 -0
  85. package/dist/bridge/resources.js +314 -0
  86. package/dist/bridge/schedule-format.d.ts +2 -0
  87. package/dist/bridge/schedule-format.js +3 -0
  88. package/dist/bridge/schedule-launch.d.ts +2 -1
  89. package/dist/bridge/schedule-launch.js +23 -53
  90. package/dist/bridge/schedule-watch.d.ts +10 -1
  91. package/dist/bridge/schedule-watch.js +54 -2
  92. package/dist/bridge/server-launch.d.ts +22 -5
  93. package/dist/bridge/server-launch.js +225 -29
  94. package/dist/bridge/server-overview.d.ts +8 -2
  95. package/dist/bridge/server-overview.js +26 -5
  96. package/dist/bridge/server-pane-routes.d.ts +2 -0
  97. package/dist/bridge/server-pane-routes.js +145 -15
  98. package/dist/bridge/server-routes.d.ts +11 -1
  99. package/dist/bridge/server-routes.js +195 -36
  100. package/dist/bridge/server-stream.d.ts +2 -0
  101. package/dist/bridge/server-stream.js +22 -8
  102. package/dist/bridge/server.d.ts +6 -1
  103. package/dist/bridge/server.js +47 -12
  104. package/dist/bridge/session-activity.d.ts +81 -0
  105. package/dist/bridge/session-activity.js +117 -0
  106. package/dist/bridge/session-rename.d.ts +48 -0
  107. package/dist/bridge/session-rename.js +190 -0
  108. package/dist/bridge/session-servers.js +2 -2
  109. package/dist/bridge/settings-switch.d.ts +60 -0
  110. package/dist/bridge/settings-switch.js +287 -0
  111. package/dist/bridge/speech-voice.d.ts +55 -0
  112. package/dist/bridge/speech-voice.js +132 -0
  113. package/dist/bridge/speech.d.ts +70 -11
  114. package/dist/bridge/speech.js +169 -41
  115. package/dist/bridge/terminal-herdr.js +9 -3
  116. package/dist/bridge/terminal-tmux.d.ts +3 -3
  117. package/dist/bridge/terminal-tmux.js +24 -9
  118. package/dist/bridge/terminal.d.ts +27 -4
  119. package/dist/bridge/terminal.js +8 -1
  120. package/dist/bridge/transcript-claude.js +62 -12
  121. package/dist/bridge/transcript-codex.d.ts +0 -2
  122. package/dist/bridge/transcript-codex.js +29 -4
  123. package/dist/bridge/transcript-preview.d.ts +1 -0
  124. package/dist/bridge/transcript-preview.js +24 -4
  125. package/dist/bridge/transcripts.d.ts +15 -2
  126. package/dist/bridge/transcripts.js +47 -16
  127. package/dist/bridge/turn-records.d.ts +85 -0
  128. package/dist/bridge/turn-records.js +143 -0
  129. package/dist/bridge/uploads.d.ts +3 -0
  130. package/dist/bridge/uploads.js +14 -0
  131. package/dist/bridge/usage.d.ts +73 -28
  132. package/dist/bridge/usage.js +313 -340
  133. package/dist/bridge-hook.mjs +24624 -18450
  134. package/dist/cli/claude-unmanaged.d.ts +12 -0
  135. package/dist/cli/claude-unmanaged.js +105 -0
  136. package/dist/cli/schedules.js +2 -1
  137. package/dist/cli/session-start.js +10 -1
  138. package/dist/cli/session-stop.js +9 -1
  139. package/dist/cli-registry.d.ts +2 -0
  140. package/dist/cli-registry.js +37 -5
  141. package/dist/computers/command.d.ts +6 -0
  142. package/dist/computers/command.js +152 -0
  143. package/dist/computers/mcp.d.ts +1 -0
  144. package/dist/computers/mcp.js +97 -0
  145. package/dist/computers/read.d.ts +85 -0
  146. package/dist/computers/read.js +177 -0
  147. package/dist/data/task-receipts.d.ts +19 -0
  148. package/dist/data/task-receipts.js +68 -0
  149. package/dist/data/tasks.js +4 -1
  150. package/dist/entrypoint.js +10 -0
  151. package/dist/fanout/adapters/claude.js +15 -2
  152. package/dist/fanout/adapters/types.d.ts +6 -0
  153. package/dist/fanout/launcher.d.ts +5 -1
  154. package/dist/fanout/launcher.js +34 -3
  155. package/dist/fanout/picker.js +3 -2
  156. package/dist/fanout/usage.js +1 -1
  157. package/dist/generated/memory-ui-graph.browser.js +63 -63
  158. package/dist/graph-core/model.js +24 -3
  159. package/dist/graph-core/types.d.ts +4 -1
  160. package/dist/graph-core/types.js +1 -0
  161. package/dist/init/init-preset.js +7 -3
  162. package/dist/init/init-uninstall.js +2 -11
  163. package/dist/init/teardown.d.ts +3 -0
  164. package/dist/init/teardown.js +47 -0
  165. package/dist/link/context.js +21 -9
  166. package/dist/mcp/plugin-mode.js +1 -1
  167. package/dist/memory-ui-graph.runtime.js +63 -63
  168. package/dist/modules/code-package.d.ts +1 -0
  169. package/dist/modules/code-package.js +36 -7
  170. package/dist/modules/registry.js +14 -13
  171. package/dist/profile-store.d.ts +6 -0
  172. package/dist/profile-store.js +25 -1
  173. package/dist/shell/graph/glyphs.js +4 -0
  174. package/dist/shell/graph/graph-view.js +2 -0
  175. package/dist/status.js +7 -1
  176. package/dist/sync/task-claim.js +3 -2
  177. package/dist/task/lifecycle.js +25 -4
  178. package/dist/test-global-setup.js +5 -0
  179. package/dist/tools/dispatch.js +35 -2
  180. package/dist/tools/tasks.js +10 -1
  181. package/package.json +1 -1
  182. package/plugins/opencode/phren-transcript.js +87 -4
  183. package/starter/global/skills/conductor/SKILL.md +17 -2
  184. package/starter/global/skills/fanout/SKILL.md +3 -0
@@ -3,12 +3,25 @@ import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { z } from "zod";
5
5
  import { homeDir } from "../home-paths.js";
6
- import { agentNames, findPane, isConductorName, paneAgentName, paneChatState, paneIdentity, servers, snapshot } from "./herdr.js";
6
+ import { agentNames, findPane, isConductorName, paneChatState, paneIdentity, servers, snapshot } from "./herdr.js";
7
7
  import { agentNotReady, terminalName, terminalProvider } from "./terminal.js";
8
+ import { intervalFromEnv } from "./limits.js";
8
9
  import { createLaunchWorktree, launchWorktreeSchema } from "./launch-worktree.js";
10
+ import { briefArgs, DISPATCH_ID_ENV, launchBriefSchema, launchesWithBrief, recordBriefArrival, writeLaunchBrief } from "./launch-brief.js";
11
+ import { prepareServedLaunch, registerServedPane, sendServedBrief } from "./opencode-panes.js";
9
12
  import { groupConductor } from "./conductor-group.js";
13
+ import { clearConductor, conductorPane, noteConductorSession, readRoleState, recordConductor, runsAgent } from "./conductor-role.js";
14
+ import { localNames } from "./computer-names.js";
15
+ import { pretrustFolder } from "./folder-trust.js";
16
+ import { claudeHome, claudeLaunchEnv, isAccountSlug, DEFAULT_ACCOUNT } from "./claude-accounts.js";
17
+ import { harnessInventoryWithin, hasUsable, launchCheckOff } from "./harnesses.js";
18
+ import { paneAccountKey, recordPaneAccount } from "./pane-accounts.js";
10
19
  import { optionalHookPeers } from "./peers.js";
11
- import { atomic, BridgeError, bridgeRoot, id, objects, provider } from "./protocol.js";
20
+ import { AppServerRpcError } from "./codex-app-server.js";
21
+ import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
22
+ import { logger } from "../logger.js";
23
+ import { atomic, BridgeError, bridgeRoot, id, launchEfforts, objects, PERMISSION_MODES, provider } from "./protocol.js";
24
+ import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags } from "./settings-switch.js";
12
25
  /** Starting agents in Herdr from the phone: the launch route's harness
13
26
  * arguments, the conductor brief, and workspace, tab and pane actions. */
14
27
  const launchKinds = ["codex", "claude", "copilot", "opencode"];
@@ -36,7 +49,6 @@ async function conductorBrief() {
36
49
  throw new BridgeError(503, "The shipped conductor brief is empty. Reinstall Phren Hook.");
37
50
  return brief;
38
51
  }
39
- const launchEfforts = ["minimal", "low", "medium", "high", "xhigh", "max"];
40
52
  /** How each harness takes a reasoning effort at startup. */
41
53
  function effortArgs(kind, effort) {
42
54
  if (kind === "claude")
@@ -81,24 +93,124 @@ async function targetForPane(server, pane) {
81
93
  const chat = await paneChatState(server, pane).catch(() => ({}));
82
94
  return chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
83
95
  }
84
- /** The live conductor on this computer, on any Herdr server, as a target.
85
- * `known` reuses a snapshot the caller already took. */
96
+ /** The live conductor on this computer, as a target: the pane the Hook
97
+ * recorded (docs/conductor-sets.md), or before any record, a pane named as a
98
+ * conductor on any server, which is then recorded. `known` reuses a snapshot
99
+ * the caller already took. */
86
100
  export async function localConductor(known) {
87
- const names = [...new Set([...(known ? [known.server] : []), ...(await servers()).map(item => String(item.session))])];
101
+ const state = await readRoleState();
102
+ if (state?.conductor === null)
103
+ return undefined;
104
+ const live = new Set((await servers()).map(item => String(item.session)));
105
+ if (known)
106
+ live.add(known.server);
107
+ const names = state?.conductor ? [state.conductor.server].filter(name => live.has(name)) : [...live];
88
108
  for (const name of names) {
89
- const value = known && name === known.server ? known.snapshot : await snapshot(name);
90
- const existing = objects(value.panes).find(pane => isConductorName(paneAgentName(value, pane))
91
- && provider.safeParse(pane.agent).success && !["completed", "exited", "failed", "stopped"].includes(String(pane.agent_status)));
92
- if (existing)
93
- return { server: name, target: await targetForPane(name, existing) };
109
+ const value = known && name === known.server ? known.snapshot : await snapshot(name).catch(() => undefined);
110
+ if (!value)
111
+ continue;
112
+ const pane = await conductorPane(name, value);
113
+ if (!runsAgent(pane))
114
+ continue;
115
+ const target = await targetForPane(name, pane);
116
+ // A restart or a new login in the same pane: the role stays, the session is new.
117
+ if (typeof target?.session === "string")
118
+ await noteConductorSession(name, String(pane.pane_id), target.session);
119
+ return { server: name, target };
94
120
  }
95
121
  return undefined;
96
122
  }
123
+ /** Refuses a second conductor in this computer's set: a live one here on
124
+ * another pane, or on any member. Members that could not say come back as `unchecked`. */
125
+ async function requireNoConductor(server, before, except) {
126
+ const existing = await localConductor({ server, snapshot: before });
127
+ if (existing && !(except && existing.server === server && existing.target?.pane === except)) {
128
+ throw new BridgeError(409, "A conductor is already running on this computer. Stop it first.", { target: existing.target });
129
+ }
130
+ const group = await groupConductor((await optionalHookPeers()).peers, localNames());
131
+ if (group.found)
132
+ throw new BridgeError(409, `A conductor is already running on ${group.found.computer}, which is in this computer's set. A set of linked computers shares one conductor.`, { computer: group.found.computer, target: group.found.target });
133
+ return group.unchecked;
134
+ }
135
+ /** The phone names the pane's workspace and tab too; the CLI may know only the pane. */
136
+ const paneRequest = z.object({ workspaceId: id.optional(), tabId: id.optional(), paneId: id }).strict();
137
+ /** "Make conductor": the owner gives an agent already running in a pane on this computer the role. */
138
+ export async function makeConductor(server, data) {
139
+ const place = paneRequest.parse(data);
140
+ const before = await snapshot(server);
141
+ const pane = objects(before.panes).find(p => p.pane_id === place.paneId && (place.workspaceId === undefined || p.workspace_id === place.workspaceId)
142
+ && (place.tabId === undefined || p.tab_id === place.tabId));
143
+ if (!pane)
144
+ throw new BridgeError(409, "The pane changed.");
145
+ if (!runsAgent(pane))
146
+ throw new BridgeError(409, "No agent is running in this pane.");
147
+ if (pane.agent === "copilot")
148
+ throw new BridgeError(400, "Copilot cannot run as a conductor.");
149
+ const unchecked = await requireNoConductor(server, before, place.paneId);
150
+ const target = await targetForPane(server, pane);
151
+ await recordConductor(server, pane, "owner", typeof target?.session === "string" ? target.session : undefined);
152
+ return { ok: true, conductor: { server, ...(target ? { target } : {}) }, ...(unchecked.length ? { unchecked } : {}) };
153
+ }
154
+ /** "Stop being conductor": the pane keeps its agent and loses the role. With
155
+ * `paneId`, only that pane's role ends. */
156
+ export async function stopConductor(data) {
157
+ const pane = data.paneId === undefined ? undefined : id.parse(data.paneId);
158
+ const state = await readRoleState();
159
+ if (pane !== undefined && state?.conductor === undefined) {
160
+ // Before any record a named pane may still be the conductor; settle that first.
161
+ await localConductor();
162
+ }
163
+ const held = (await readRoleState())?.conductor;
164
+ if (pane !== undefined && held && held.pane !== pane)
165
+ throw new BridgeError(409, "That pane is not this computer's conductor.");
166
+ const stopped = await clearConductor(pane);
167
+ return { ok: true, stopped: !!stopped };
168
+ }
169
+ /** How long a pane the Hook just created may take to reach its shell prompt. */
170
+ const SHELL_READY_MS = intervalFromEnv("PHREN_SHELL_READY_MS", 15_000);
171
+ /** Herdr starts an agent only at an interactive shell prompt and refuses
172
+ * with `agent_pane_busy` ("is not an available shell") before that. A pane
173
+ * created a moment ago is busy only while its login shell starts, which a
174
+ * loaded computer can stretch to seconds (three Linuxbox dispatches failed
175
+ * this way on 2026-09-27; the same pane took the agent by hand a minute
176
+ * later). Nothing is typed on a refusal, so retry until the shell is up. */
177
+ async function startWhenShellReady(server, pane, agent) {
178
+ const deadline = Date.now() + SHELL_READY_MS;
179
+ for (;;) {
180
+ try {
181
+ await terminalProvider().startAgent(server, pane, agent);
182
+ return;
183
+ }
184
+ catch (error) {
185
+ const starting = error instanceof BridgeError && error.details?.herdrCode === "agent_pane_busy";
186
+ if (!starting || Date.now() >= deadline)
187
+ throw error;
188
+ await new Promise(resolve => setTimeout(resolve, 250));
189
+ }
190
+ }
191
+ }
97
192
  /** The Herdr agent-name slug for a human label: "Conductor smoke 4" becomes "conductor-smoke-4". */
98
193
  export function herdrAgentName(label) {
99
194
  const slug = label.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 32).replace(/-+$/, "");
100
195
  return slug || "agent";
101
196
  }
197
+ let inventoryReader;
198
+ /** Only for tests: what this computer can launch. Without one, `PHREN_LAUNCH_CHECK=off` skips the early availability check. */
199
+ export function setLaunchInventory(reader) { inventoryReader = reader; }
200
+ /** Refuses a launch the computer cannot run before any pane exists: the harness is not installed
201
+ * (`harness_unavailable`), or the account is unknown, signed out, or given for a harness without accounts
202
+ * (`account_unavailable`). Only a definite answer refuses; an inventory that cannot be read lets the launch go on. */
203
+ async function requireAvailable(kind, account) {
204
+ if (!inventoryReader && launchCheckOff())
205
+ return;
206
+ // Bounded: a cold sign-in check per home can take seconds, and an unready inventory lets the launch go on.
207
+ const inventory = await (inventoryReader ?? (() => harnessInventoryWithin(2_500)))().catch(() => undefined);
208
+ if (!inventory)
209
+ return;
210
+ const availability = hasUsable(inventory, kind, account);
211
+ if (!availability.ok)
212
+ throw new BridgeError(409, availability.reason, { code: availability.code });
213
+ }
102
214
  /**
103
215
  * "Open on a computer": a new Herdr workspace (or a tab in an existing one)
104
216
  * in the project's directory, with the chosen agent started in its pane.
@@ -115,8 +227,21 @@ export async function launchSession(server, data, options = {}) {
115
227
  const label = plainText(200).parse(data.label);
116
228
  const kind = z.enum(launchKinds).parse(data.kind);
117
229
  const effort = z.enum(launchEfforts).default("medium").parse(data.effort);
230
+ const account = data.account === undefined || data.account === null ? undefined : z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(data.account);
231
+ const permissionMode = z.enum(PERMISSION_MODES).optional().parse(data.permissionMode ?? undefined);
232
+ if (permissionMode && role === "conductor")
233
+ throw new BridgeError(400, "A conductor starts with its own permissions; permissionMode is for workers.");
234
+ if (permissionMode && kind === "opencode")
235
+ throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and Codex workers.");
236
+ if (permissionMode && kind === "copilot")
237
+ throw new BridgeError(400, "Copilot takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
118
238
  if (role === "conductor" && kind === "copilot")
119
239
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
240
+ // A dispatched worker's or scheduled run's first prompt. It rides on the
241
+ // launch where the harness takes one; elsewhere the caller types it.
242
+ const brief = data.brief === undefined || data.brief === null ? undefined : launchBriefSchema.parse(data.brief);
243
+ if (brief && role === "conductor")
244
+ throw new BridgeError(400, "A conductor starts with its own brief.");
120
245
  // Herdr's agent name is a slug (lowercase, digits, - or _, 1 to 32 chars);
121
246
  // the label a person typed is not, so derive one from it.
122
247
  const baseName = herdrAgentName(data.name === undefined ? label : plainText(200).parse(data.name));
@@ -132,6 +257,11 @@ export async function launchSession(server, data, options = {}) {
132
257
  let workspace = data.workspaceId === undefined ? undefined : id.parse(data.workspaceId);
133
258
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
134
259
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
260
+ // Checked before anything is created, so a refusal leaves no pane, worktree or brief file behind.
261
+ await requireAvailable(kind, account);
262
+ const home = kind === "claude" && account && account !== DEFAULT_ACCOUNT ? claudeHome(account) : undefined;
263
+ if (kind === "claude" && account && account !== DEFAULT_ACCOUNT && !home)
264
+ throw new BridgeError(409, `No claude account "${account}"`, { code: "account_unavailable" });
135
265
  const before = await snapshot(server);
136
266
  // Herdr agent names are unique per server; a scheduled run or a second
137
267
  // launch with the same label would otherwise collide with the first.
@@ -139,23 +269,31 @@ export async function launchSession(server, data, options = {}) {
139
269
  let name = wanted;
140
270
  for (let n = 2; taken.has(name) && n < 100; n++)
141
271
  name = `${wanted.slice(0, 32 - String(n).length - 1)}-${n}`;
142
- // One conductor per connected group: this computer and every linked peer.
143
- let unchecked = [];
144
- if (role === "conductor" && !options.canary) {
145
- const existing = await localConductor({ server, snapshot: before });
146
- if (existing)
147
- throw new BridgeError(409, "A conductor is already running on this computer.", { target: existing.target });
148
- const group = await groupConductor((await optionalHookPeers()).peers);
149
- if (group.found)
150
- throw new BridgeError(409, `A conductor is already running on ${group.found.computer}, which is linked with this computer. A connected group shares one conductor.`, { computer: group.found.computer, target: group.found.target });
151
- unchecked = group.unchecked;
152
- }
272
+ // One conductor per set of linked computers.
273
+ const unchecked = role === "conductor" && !options.canary ? await requireNoConductor(server, before) : [];
153
274
  // A worker opened in the conductor's workspace would be listed under the
154
275
  // conductor's name; it gets its own workspace instead.
155
- if (role === "agent" && workspace && objects(before.panes).some(pane => pane.workspace_id === workspace && isConductorName(paneAgentName(before, pane))))
276
+ const conductorHere = role === "agent" && workspace ? await conductorPane(server, before) : undefined;
277
+ if (conductorHere && conductorHere.workspace_id === workspace)
156
278
  workspace = undefined;
157
279
  const args = role === "conductor" ? await prepareConductor(kind, effort, model)
158
- : [...(model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort))];
280
+ : [...(model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
281
+ ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : [])];
282
+ // A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
283
+ // pane joins the thread the Hook started, and the brief is that thread's
284
+ // first turn. The typed arguments below stay the fallback.
285
+ const structured = kind === "codex" && role === "agent" && !options.canary && codexAppServerEnabled();
286
+ // OpenCode serves its own API on a port of its own (opencode-panes.ts): the
287
+ // Hook sends its prompts, answers its asks and interrupts it over HTTP, and
288
+ // the pane stays the owner's view. A brief goes the same way once it
289
+ // answers; its file still marks the dispatch so the arrival is recorded here.
290
+ const served = kind === "opencode" ? await prepareServedLaunch() : undefined;
291
+ if (served)
292
+ args.push(...served.args);
293
+ const briefFile = brief && (launchesWithBrief(kind) || structured || served) ? await writeLaunchBrief(brief, Date.now(), label) : undefined;
294
+ const briefLaunch = brief && briefFile && launchesWithBrief(kind) ? briefArgs(kind, briefFile) : undefined;
295
+ const variables = { ...(brief ? { [DISPATCH_ID_ENV]: brief.id } : {}), ...served?.env, ...(home ? claudeLaunchEnv(home) : {}) };
296
+ const env = Object.keys(variables).length ? variables : undefined;
159
297
  if (workspace && !objects(before.workspaces).some(w => w.workspace_id === workspace))
160
298
  throw new BridgeError(409, "The workspace changed.");
161
299
  const knownWorkspaces = new Set(objects(before.workspaces).map(w => w.workspace_id));
@@ -164,8 +302,12 @@ export async function launchSession(server, data, options = {}) {
164
302
  // never leaves a worktree or branch behind.
165
303
  const worktree = worktreeRequest ? await createLaunchWorktree(projectDirectory, worktreeRequest) : undefined;
166
304
  const cwd = worktree?.cwd ?? projectDirectory;
305
+ // Claude's folder-trust screen defaults to "No, exit" and Codex's holds the
306
+ // agent too; a folder the Hook picked or just created is trusted up front.
307
+ if (worktree || options.trustFolder)
308
+ await pretrustFolder(kind, cwd, worktree ? `new worktree for ${worktree.branch}` : "project folder", home ? { ...process.env, ...claudeLaunchEnv(home) } : process.env);
167
309
  try {
168
- await terminalProvider().create(server, { workspace, label, cwd });
310
+ await terminalProvider().create(server, { workspace, label, cwd, ...(env ? { env } : {}) });
169
311
  }
170
312
  catch (error) {
171
313
  await worktree?.discard();
@@ -188,10 +330,40 @@ export async function launchSession(server, data, options = {}) {
188
330
  }
189
331
  if (!created)
190
332
  throw new BridgeError(409, `${terminalName(server)} created "${label}" but its pane did not appear. Check ${terminalName(server)} on the computer.`);
333
+ const place = { workspace: created.workspaceId, tab: created.tabId, pane: created.paneId };
334
+ const structuredLaunch = structured ? await codexServers.launch({ server, ...place }, { cwd, ...(model ? { model } : {}),
335
+ ...(data.effort === undefined ? {} : { effort }), env: { ...(terminalProvider().paneEnv?.(server, place) ?? {}), ...(env ?? {}) },
336
+ ...(brief ? { dispatchId: brief.id } : {}), startThread: !!brief, ...(permissionMode ? { remoteArgs: codexModeFlags(permissionMode) } : {}) }).catch(error => {
337
+ logger.warn("launch", `Codex app-server unavailable, typing instead: ${error instanceof Error ? error.message : String(error)}`);
338
+ return undefined;
339
+ }) : undefined;
340
+ const appServer = structuredLaunch?.entry;
341
+ const binding = { server, workspace: created.workspaceId, tab: created.tabId, pane: created.paneId, source: kind };
342
+ // The brief is the thread's first turn, acknowledged with its id before
343
+ // the pane even starts; the pane's TUI shows it running when it joins.
344
+ // Refused outright, nothing was sent and the caller types it; a lost
345
+ // reply may have started it, so it is not offered for typing again.
346
+ let briefTurn;
347
+ if (appServer?.threadId && brief) {
348
+ try {
349
+ // The thread's first turn carries the mode; the TUI joining it has no flags to set.
350
+ if (permissionMode)
351
+ codexServers.holdSettings(appServer, { ...CODEX_MODES[permissionMode] });
352
+ await codexServers.prompt(appServer, brief.text);
353
+ briefTurn = "sent";
354
+ await recordBriefArrival(brief.id, "UserPromptSubmit", { ...binding, session: appServer.threadId }).catch(() => undefined);
355
+ }
356
+ catch (error) {
357
+ briefTurn = error instanceof AppServerRpcError ? undefined : "uncertain";
358
+ }
359
+ }
360
+ const agentArgs = structuredLaunch ? structuredLaunch.args : [...args, ...(briefLaunch ?? [])];
191
361
  try {
192
- await terminalProvider().startAgent(server, created.paneId, { name, kind, args, timeoutMs: timeout });
362
+ await startWhenShellReady(server, created.paneId, { name, kind, args: agentArgs, timeoutMs: timeout, ...(env ? { env } : {}) });
193
363
  }
194
364
  catch (error) {
365
+ if (appServer && !agentNotReady(error))
366
+ await codexServers.stop(appServer).catch(() => undefined);
195
367
  // A first-run screen (Claude's folder trust, a login notice) holds the
196
368
  // agent at startup. It did start: hand the pane back so the owner answers
197
369
  // that screen from the chat instead of stranding the workspace.
@@ -203,15 +375,39 @@ export async function launchSession(server, data, options = {}) {
203
375
  throw new BridgeError(409, `${host} couldn't start ${kind} in the new "${label}" pane (${reason}). The workspace was created and is still open on the computer — open it from ${host === "Herdr" ? "Herdr workspaces" : "its tmux session"}.`);
204
376
  }
205
377
  }
378
+ // Without a brief the pane's TUI started the thread; the Hook heard it.
379
+ if (appServer && !appServer.threadId)
380
+ await codexServers.awaitThread(appServer);
381
+ let servedBrief;
382
+ if (served) {
383
+ const variant = role === "conductor" || data.effort !== undefined ? effort : undefined;
384
+ const entry = await registerServedPane(server, created.paneId, cwd, served, { defaults: { ...(role === "conductor" ? { agent: "conductor" } : {}), ...(model ? { model } : {}), ...(variant ? { variant } : {}) } }).catch(() => undefined);
385
+ const sent = entry && brief ? await sendServedBrief(entry, brief.text) : undefined;
386
+ if (brief && sent?.sent) {
387
+ // Sent is enough to never type it again; the user turn appearing in
388
+ // the session is the acceptance the dispatch receipt waits for.
389
+ servedBrief = { session: sent.session, delivered: sent.delivered };
390
+ const at = { ...binding, session: sent.session };
391
+ await recordBriefArrival(brief.id, "SessionStart", at).catch(() => { });
392
+ if (sent.delivered)
393
+ await recordBriefArrival(brief.id, "UserPromptSubmit", at).catch(() => { });
394
+ }
395
+ }
206
396
  const after = await snapshot(server);
207
397
  const pane = findPane(after, { workspace: created.workspaceId, tab: created.tabId, pane: created.paneId });
208
398
  const agentStatus = typeof pane?.agent_status === "string" ? pane.agent_status : undefined;
209
- const sessionId = pane && pane.agent === kind ? await paneIdentity(server, pane) : undefined;
399
+ if (kind === "claude" && account)
400
+ recordPaneAccount(paneAccountKey(server, created.paneId), account, typeof pane?.terminal_id === "string" ? pane.terminal_id : undefined);
401
+ const sessionId = appServer?.threadId ?? (pane && pane.agent === kind ? await paneIdentity(server, pane) : undefined) ?? servedBrief?.session;
402
+ // The Hook, not the agent name, holds the role from here on.
403
+ if (role === "conductor" && !options.canary)
404
+ await recordConductor(server, pane ?? { pane_id: created.paneId, workspace_id: created.workspaceId, tab_id: created.tabId, agent: kind }, "launch", sessionId);
210
405
  const chat = !sessionId && pane && pane.agent === kind ? await paneChatState(server, pane).catch(() => ({})) : {};
211
- const binding = { server, workspace: created.workspaceId, tab: created.tabId, pane: created.paneId, source: kind };
212
406
  const target = sessionId ? { ...binding, session: sessionId }
213
407
  : chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
214
- return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target, ...(unchecked.length ? { unchecked } : {}),
408
+ return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
409
+ // The caller types the brief itself unless it went with the launch.
410
+ ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief } : {}),
215
411
  ...(worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}) };
216
412
  }
217
413
  export async function workspaceAction(server, operation, data) {
@@ -14,22 +14,28 @@ import type { WorkspacesReader } from "./server-routes.js";
14
14
  * overview it holds is still current.
15
15
  *
16
16
  * Frames: `{ type: "overview", ...workspaces, phren }` and
17
- * `{ type: "heartbeat", phren }`.
17
+ * `{ type: "heartbeat", phren }`. A phone that asks with `resources=1` also
18
+ * gets `{ type: "resources", resources }` after the first overview, then at
19
+ * `OVERVIEW_RESOURCES_MS` intervals (an older phone never asks, so never meets it).
18
20
  */
19
21
  export declare const OVERVIEW_TICK_MS: number;
20
22
  export declare const OVERVIEW_REFRESH_MS: number;
21
23
  export declare const OVERVIEW_HEARTBEAT_MS: number;
24
+ export declare const OVERVIEW_RESOURCES_MS: number;
22
25
  export interface OverviewStreamOptions {
23
26
  read: WorkspacesReader;
24
27
  /** The Hook's info, as `/v1/health` reports it. */
25
28
  info: () => Json;
26
29
  /** Renews the approval watch lease `watchApprovals=1` asks for. */
27
30
  renew: (server: string) => void;
31
+ /** This computer's resources (`GET /v1/resources`), for phones that ask. */
32
+ resources?: () => Promise<unknown>;
28
33
  snapshot?: (server: string, maxAgeMs: number) => Promise<Json>;
29
34
  now?: () => number;
30
35
  tickMs?: number;
31
36
  refreshMs?: number;
32
37
  heartbeatMs?: number;
38
+ resourcesMs?: number;
33
39
  }
34
40
  /** A socket-like peer: the `ws` client, or a test double. */
35
41
  export interface OverviewClient {
@@ -39,7 +45,7 @@ export interface OverviewClient {
39
45
  close(code?: number, reason?: string): void;
40
46
  once(event: "close" | "error", listener: () => void): unknown;
41
47
  }
42
- export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean) => {
48
+ export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean, withResources?: boolean, typedMux?: boolean) => {
43
49
  tick: () => Promise<void>;
44
50
  stop: () => void;
45
51
  };
@@ -3,6 +3,7 @@ import { logger } from "../logger.js";
3
3
  import { sharedSnapshot } from "./herdr.js";
4
4
  import { intervalFromEnv } from "./limits.js";
5
5
  import { countTick } from "./metrics.js";
6
+ import { muxReplyForClient } from "./mux-wire.js";
6
7
  import { MAX_FRAME } from "./protocol.js";
7
8
  import { streamCloseReason } from "./server-stream.js";
8
9
  /**
@@ -19,17 +20,21 @@ import { streamCloseReason } from "./server-stream.js";
19
20
  * overview it holds is still current.
20
21
  *
21
22
  * Frames: `{ type: "overview", ...workspaces, phren }` and
22
- * `{ type: "heartbeat", phren }`.
23
+ * `{ type: "heartbeat", phren }`. A phone that asks with `resources=1` also
24
+ * gets `{ type: "resources", resources }` after the first overview, then at
25
+ * `OVERVIEW_RESOURCES_MS` intervals (an older phone never asks, so never meets it).
23
26
  */
24
27
  export const OVERVIEW_TICK_MS = intervalFromEnv("PHREN_OVERVIEW_TICK_MS", 5_000, 250, 60_000);
25
28
  export const OVERVIEW_REFRESH_MS = intervalFromEnv("PHREN_OVERVIEW_REFRESH_MS", 10_000, 1_000, 120_000);
26
29
  export const OVERVIEW_HEARTBEAT_MS = intervalFromEnv("PHREN_OVERVIEW_HEARTBEAT_MS", 20_000, 1_000, 60_000);
30
+ export const OVERVIEW_RESOURCES_MS = intervalFromEnv("PHREN_OVERVIEW_RESOURCES_MS", 12_000, 1_000, 120_000);
27
31
  export function overviewStream(options) {
28
32
  const snapshot = options.snapshot ?? sharedSnapshot;
29
33
  const now = options.now ?? Date.now;
30
34
  const tickMs = options.tickMs ?? OVERVIEW_TICK_MS;
31
35
  const refreshMs = options.refreshMs ?? OVERVIEW_REFRESH_MS;
32
36
  const heartbeatMs = options.heartbeatMs ?? OVERVIEW_HEARTBEAT_MS;
37
+ const resourcesMs = options.resourcesMs ?? OVERVIEW_RESOURCES_MS;
33
38
  function send(client, frame) {
34
39
  if (client.readyState !== WebSocket.OPEN)
35
40
  return false;
@@ -43,9 +48,22 @@ export function overviewStream(options) {
43
48
  }
44
49
  /** Streams one server's overview until the client closes. Returns the
45
50
  * tick function, for tests that drive time themselves. */
46
- return function stream(client, server, watchApprovals) {
47
- let closed = false, busy = false, first = true;
48
- let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0;
51
+ return function stream(client, server, watchApprovals, withResources = false, typedMux = false) {
52
+ let closed = false, busy = false, resourcesPending = false, first = true;
53
+ let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0, resourcesAt = -Infinity;
54
+ const collectResources = () => {
55
+ const at = now();
56
+ if (!withResources || !options.resources || resourcesPending || at - resourcesAt < resourcesMs)
57
+ return;
58
+ resourcesPending = true;
59
+ resourcesAt = at;
60
+ void Promise.resolve().then(() => options.resources()).then(resources => {
61
+ if (!closed && resources)
62
+ send(client, { type: "resources", resources });
63
+ }).catch(error => {
64
+ logger.warn("stream", `/v1/overview resources read failed: ${streamCloseReason(error)}`);
65
+ }).finally(() => { resourcesPending = false; });
66
+ };
49
67
  const tick = async () => {
50
68
  if (busy || closed)
51
69
  return;
@@ -61,7 +79,7 @@ export function overviewStream(options) {
61
79
  if (first || key !== snapshotKey || at - builtAt >= refreshMs) {
62
80
  snapshotKey = key;
63
81
  builtAt = at;
64
- const overview = await options.read(server, held, watchApprovals);
82
+ const overview = muxReplyForClient(await options.read(server, held, watchApprovals), typedMux);
65
83
  if (closed)
66
84
  return;
67
85
  const { phren: _phren, ...rows } = overview;
@@ -90,6 +108,9 @@ export function overviewStream(options) {
90
108
  }
91
109
  finally {
92
110
  busy = false;
111
+ // Start this separately so ps and pane ownership cannot hold up the overview.
112
+ if (!closed)
113
+ collectResources();
93
114
  }
94
115
  };
95
116
  const timer = setInterval(() => { void tick(); }, tickMs);
@@ -2,6 +2,7 @@ import type { ServerResponse } from "node:http";
2
2
  import type { AgentHooks } from "./agent-hooks.js";
3
3
  import { type WorktreeWorker } from "./git-worktrees.js";
4
4
  import { type ModelSwitcher } from "./model-switch.js";
5
+ import type { SettingsSwitcher } from "./settings-switch.js";
5
6
  import { type Json, type Target } from "./protocol.js";
6
7
  import type { CodexQuestions } from "./questions.js";
7
8
  import { type SideQuestions } from "./side-questions.js";
@@ -11,6 +12,7 @@ import { type SideQuestions } from "./side-questions.js";
11
12
  export interface PaneRouteContext {
12
13
  agentHooks: AgentHooks;
13
14
  modelSwitcher: ModelSwitcher;
15
+ settingsSwitcher: SettingsSwitcher;
14
16
  codexQuestions: CodexQuestions;
15
17
  sideQuestions: SideQuestions;
16
18
  }