@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
@@ -1,35 +1,50 @@
1
+ import { sessionStalls } from "./stalls.js";
2
+ import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
1
3
  import path from "node:path";
2
4
  import { z } from "zod";
5
+ import { sudoAnswer } from "./sudo.js";
3
6
  import { saveCodeNote } from "./code-note.js";
4
7
  import { handOff } from "./hand-off.js";
5
8
  import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
6
9
  import { homeDir } from "../home-paths.js";
7
10
  import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
8
- import { dispatchProjectDirectory, dispatchStatus } from "./dispatch.js";
9
- import { workerStates } from "./dispatch-returns.js";
11
+ import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
12
+ import { hookWorkers } from "./dispatch-returns.js";
10
13
  import { remoteChildren } from "./dispatch-tree.js";
11
- import { addGrant, listGrants, removeGrant } from "./grants.js";
14
+ import { briefArrival, briefId } from "./launch-brief.js";
15
+ import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
16
+ import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
17
+ import { readComputers } from "./computer-identity.js";
12
18
  import { optionalHookPeers, peerRequest } from "./peers.js";
13
19
  import { candidateRepos, enrollProject } from "./enroll.js";
14
20
  import { browseFiles } from "./files.js";
15
21
  import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
16
22
  import { storeRoute } from "./memory-store.js";
17
- import { paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
23
+ import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
24
+ import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
18
25
  import { locateProject } from "./locate.js";
19
26
  import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
20
27
  import { BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
21
28
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
22
- import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, transcriptPath } from "./transcripts.js";
29
+ import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, targetTranscriptPath } from "./transcripts.js";
23
30
  import { listUploads, saveUpload, uploadImage } from "./uploads.js";
24
31
  import { currentModel, currentStep } from "./steps.js";
25
- import { usageForCaller } from "./usage.js";
32
+ import { capacityRoom, usageForCaller } from "./usage.js";
33
+ import { readFinalTurn } from "./schedule-watch.js";
26
34
  import { healthDetails, listsCaller } from "./health.js";
27
35
  import { defaultPhrenPath } from "../shared.js";
28
36
  import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
29
37
  import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
30
- import { launchSession, localConductor, workspaceAction } from "./server-launch.js";
38
+ import { renameSession } from "./session-rename.js";
39
+ import { launchSession, makeConductor, stopConductor, workspaceAction } from "./server-launch.js";
40
+ import { conductorAnswer, nameSet, readSets } from "./conductor-sets.js";
41
+ import { conductorPane } from "./conductor-role.js";
31
42
  import { hookMetrics } from "./metrics.js";
32
- import { streamSpeech } from "./speech.js";
43
+ import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
44
+ import { readSpeechKey } from "./speech-key.js";
45
+ import { DEFAULT_SPEECH_VOICE, listSpeechVoices, resolveSpeechVoice } from "./speech-voice.js";
46
+ import { terminalKind, terminalMux } from "./terminal.js";
47
+ import { muxListForClient, muxReplyForClient, typedMuxRequest } from "./mux-wire.js";
33
48
  const CHILD_ACTIVITY_CACHE_MS = 5_000;
34
49
  /** How long the overview waits for per-tab git and transcript reads; the phone gives up at 20 s. */
35
50
  export const OVERVIEW_ENRICH_BUDGET_MS = 5_000;
@@ -50,9 +65,9 @@ async function childActivity(source, session) {
50
65
  return result;
51
66
  }
52
67
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
53
- terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
68
+ terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
54
69
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
55
- files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, transcribe: true, memoryStore: true, promptOnce: true, resources: true };
70
+ files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, resources: true, sudo: true, sudoOutcome: true };
56
71
  export function capabilitiesForModules(snapshot) {
57
72
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
58
73
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -88,9 +103,19 @@ async function body(request) {
88
103
  }
89
104
  export function selectedServer(url) {
90
105
  const mux = url.searchParams.get("mux");
91
- if (mux && !mux.startsWith("herdr:"))
92
- throw new BridgeError(400, "Select a Herdr server.");
93
- return serverName.parse(url.searchParams.get("server") || mux?.slice(6) || "default");
106
+ const selected = mux ? /^(herdr|tmux):(.+)$/.exec(mux) : undefined;
107
+ if (mux && !selected)
108
+ throw new BridgeError(400, "Select a terminal source.");
109
+ const explicit = url.searchParams.get("server");
110
+ if (explicit && selected && explicit !== selected[2])
111
+ throw new BridgeError(400, "Conflicting terminal sources.");
112
+ const server = serverName.parse(explicit || selected?.[2] || "default");
113
+ // Old phones used herdr:tmux. Keep that alias, but a typed tmux id must
114
+ // never silently route to a Herdr session with the same server name.
115
+ if (selected?.[1] === "tmux" && terminalKind(server) !== "tmux") {
116
+ throw new BridgeError(409, "This terminal source changed. Refresh the computer.", { code: "mux-kind-mismatch" });
117
+ }
118
+ return server;
94
119
  }
95
120
  export function workspacesReader(ctx) {
96
121
  const { modules, info, agentHooks, journal, tabActivity, contextUsage } = ctx;
@@ -101,7 +126,9 @@ export function workspacesReader(ctx) {
101
126
  const context = await contextUsage.read(server, s);
102
127
  await journal.record(server, objects(s.panes));
103
128
  const chatStates = new Map(await Promise.all(objects(s.panes).filter(p => p.agent).map(async (p) => [p, await paneChatState(server, p, { tokenWhenIdentified: false }).catch(() => ({}))])));
104
- const workspaces = workspaceSnapshot(s, context, agentHooks.pendingPanes(server, s), lastChanged);
129
+ // The Hook's record says which pane is the conductor, whatever the agent is named.
130
+ const conductor = await conductorPane(server, s).catch(() => undefined);
131
+ const workspaces = workspaceSnapshot(s, context, agentHooks.pendingPanes(server, s), lastChanged, conductor ? String(conductor.pane_id) : null);
105
132
  // The branch each tab's agent is on, for the session cards.
106
133
  const agentsByTab = new Map();
107
134
  for (const pane of objects(s.panes)) {
@@ -122,6 +149,8 @@ export function workspacesReader(ctx) {
122
149
  const chat = chatStates.get(agents[0]);
123
150
  if (chat?.starting === true)
124
151
  tab.starting = true;
152
+ // After the identity probe above, which is what learns a pane's transcript.
153
+ Object.assign(tab, paneAccountField(server, agents[0]));
125
154
  if (typeof chat?.sessionId === "string" && provider.safeParse(agents[0].agent).success) {
126
155
  tab.target = { server, workspace: group.id, tab: tab.id, pane: agents[0].pane_id, source: agents[0].agent, session: chat.sessionId };
127
156
  }
@@ -131,8 +160,33 @@ export function workspacesReader(ctx) {
131
160
  // the phone waits, so the computer read as offline. The overview answers
132
161
  // within its budget with whatever decoration is ready; a later read fills in.
133
162
  let expired = false;
163
+ let timer;
164
+ const budget = new Promise(resolve => { timer = setTimeout(resolve, OVERVIEW_ENRICH_BUDGET_MS); });
165
+ // First, each pane's own turn record (one small file): whether its ended
166
+ // turn still has background work, and which dispatch it is. It runs ahead
167
+ // of the slower reads so the status does not flicker between answers, but
168
+ // inside the budget, so a stuck disk cannot hold the overview either.
169
+ const awaited = new Map();
170
+ const records = Promise.all(tabs.map(async ({ group, tab }) => {
171
+ const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
172
+ const session = agents.length === 1 && object(tab.target).session;
173
+ const record = typeof session === "string" ? await paneRecord(server, agents[0], session) : undefined;
174
+ const [title, background] = await Promise.all([
175
+ recordTitle(record, { paneLabel: tab.paneLabel, harnessTitle: tab.title, tabLabel: tab.label, workspaceLabel: group.label, fallbackLabel: tab.label }),
176
+ liveBackground(record, readFinalTurn),
177
+ ]);
178
+ if (expired)
179
+ return;
180
+ if (background)
181
+ awaited.set(tab, background);
182
+ markBackground(tab, background);
183
+ const target = targetSchema.safeParse(tab.target);
184
+ if (target.success && agents.length === 1)
185
+ Object.assign(tab, await sessionStalls.observe(target.data, { ...agents[0], agent_status: tab.agentStatus }));
186
+ tab.title = title;
187
+ }));
134
188
  let nextTab = 0;
135
- const enrich = Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
189
+ const enrich = records.then(() => Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
136
190
  while (!expired && nextTab < tabs.length) {
137
191
  const { group, tab } = tabs[nextTab++];
138
192
  const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
@@ -160,18 +214,33 @@ export function workspacesReader(ctx) {
160
214
  }
161
215
  }
162
216
  // A row finished after the answer left belongs to the next read.
163
- if (!expired)
217
+ if (!expired) {
164
218
  Object.assign(tab, Object.fromEntries(Object.entries(found).filter(([, value]) => value !== undefined)));
219
+ // Running sub-agents and fan-out jobs keep an idle-looking session
220
+ // working too, on top of the shells its last turn is waiting on.
221
+ markBackground(tab, (awaited.get(tab) ?? 0) + (typeof found.runningChildren === "number" ? found.runningChildren : 0));
222
+ }
165
223
  }
166
- }));
167
- let timer;
168
- await Promise.race([enrich, new Promise(resolve => { timer = setTimeout(resolve, OVERVIEW_ENRICH_BUDGET_MS); })]);
224
+ })));
225
+ await Promise.race([enrich, budget]);
169
226
  expired = true;
170
227
  clearTimeout(timer);
171
- return { ...workspaces, phren: info };
228
+ const mux = terminalMux(server);
229
+ return { ...workspaces, kind: mux.kind, mux, phren: info };
172
230
  };
173
231
  }
174
232
  /** One read-only GET to every linked peer, each answer or its error by computer name. */
233
+ /** The value, or undefined once `ms` passes or it fails: a probe never waits on a slow reader. */
234
+ async function within(ms, value) {
235
+ let timer;
236
+ const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), ms); timer.unref(); });
237
+ try {
238
+ return await Promise.race([value.catch(() => undefined), late]);
239
+ }
240
+ finally {
241
+ clearTimeout(timer);
242
+ }
243
+ }
175
244
  async function fromPeers(route) {
176
245
  const { peers, peerError } = await optionalHookPeers();
177
246
  const answers = await Promise.all(peers.map(async (peer) => {
@@ -224,22 +293,68 @@ export function createRouteHandler(ctx) {
224
293
  case "/v1/dispatch":
225
294
  result = { dispatches: await dispatchStatus() };
226
295
  break;
296
+ // Receiving side of a launched brief: what the worker's hooks reported for it.
297
+ case "/v1/dispatch/arrival":
298
+ result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
299
+ break;
227
300
  case "/v1/conductor/grants":
228
- result = { grants: await listGrants() };
301
+ result = { grants: await listNamedGrants() };
229
302
  break;
230
- // Asked by linked peers before they start a conductor: one per connected group.
303
+ // The owner's release authority policy, which conductors read and quote in briefs.
304
+ case "/v1/authority": {
305
+ const policy = await readAuthority();
306
+ const project = url.searchParams.get("project");
307
+ result = project !== null ? { authority: projectAuthority(policy, z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/).parse(project)) }
308
+ : { source: policy.source, ...(policy.updatedAt ? { updatedAt: policy.updatedAt } : {}), ...(policy.updatedBy ? { updatedBy: policy.updatedBy } : {}),
309
+ projects: Object.keys(policy.projects).sort().map(name => projectAuthority(policy, name)), confirmations: await listConfirmations() };
310
+ break;
311
+ }
312
+ // One row per real computer, however many names machines.yaml and the network give it.
313
+ case "/v1/computers": {
314
+ const { computers, peerError } = await readComputers({ probe: true, local: { id: info.computer.id } });
315
+ result = { computers, ...(peerError ? { peerError } : {}) };
316
+ break;
317
+ }
318
+ // Asked by linked peers to place this computer in a set, and before they start a conductor: one per set.
231
319
  case "/v1/conductor":
232
- result = { computer: info.computer, conductor: await localConductor() ?? null };
320
+ result = await conductorAnswer(info, url);
321
+ break;
322
+ case "/v1/sets":
323
+ result = await readSets(info);
324
+ break;
325
+ // Bounded like capacity: a cold `claude auth status` per home can take seconds. Without
326
+ // `harnesses` the phone treats the computer as unknown and offers everything; the probe keeps
327
+ // running, so the next request answers from cache.
328
+ case "/v1/harnesses":
329
+ result = await harnessInventoryWithin(2_500) ?? { pending: true };
233
330
  break;
234
331
  case "/v1/dispatch/capacity": {
235
332
  const live = await servers();
236
333
  const snapshots = await Promise.all(live.map(server => snapshot(String(server.session))));
237
- result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session),
238
- working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0) };
334
+ // Asked by a conductor with its name or host key: whether this computer links it back, so it dispatches only within its set.
335
+ const caller = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() })
336
+ .parse({ name: url.searchParams.get("name") ?? undefined, hostKey: url.searchParams.get("hostKey") ?? undefined });
337
+ const linksBack = caller.name || caller.hostKey ? { knowsCaller: (await listsCaller(caller)).knowsCaller } : {};
338
+ // Both bounded so a peer's capacity probe never waits on a cold `claude auth status` or usage read; missing means unknown.
339
+ // PHREN_LAUNCH_CHECK=off turns this Hook's availability checks off, including what it advertises to dispatch.
340
+ // `usage` is the room left per Codex and Claude account, so `anywhere` can break a tie by it.
341
+ const [inventory, limits] = await Promise.all([launchCheckOff() ? undefined : harnessInventoryWithin(2_500), within(2_500, accountUsage.limits(true))]);
342
+ result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session), ...linksBack,
343
+ working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0),
344
+ ...(inventory ? { harnesses: inventory.harnesses } : {}), ...(limits ? { usage: capacityRoom(limits, Date.now()) } : {}) };
345
+ break;
346
+ }
347
+ case "/v1/speech/voices": {
348
+ // The phone's voice picker: this computer's setting and the voices its account has.
349
+ const key = await readSpeechKey();
350
+ if (!key)
351
+ throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
352
+ const current = await resolveSpeechVoice();
353
+ result = { voice: current.voice, source: current.source, defaultVoice: DEFAULT_SPEECH_VOICE, voices: await listSpeechVoices(key) };
239
354
  break;
240
355
  }
241
356
  case "/v1/muxes":
242
- result = { muxes: await servers() };
357
+ result = { muxes: muxListForClient(await servers(), url.searchParams.get("typed") === "1") };
243
358
  break;
244
359
  case "/v1/activity":
245
360
  result = { events: await journal.recent() };
@@ -284,7 +399,7 @@ export function createRouteHandler(ctx) {
284
399
  break;
285
400
  }
286
401
  case "/v1/models":
287
- result = { models: await modelCatalog.list(String(url.searchParams.get("source") ?? "")) };
402
+ result = { models: await modelCatalog.list(String(url.searchParams.get("source") ?? ""), url.searchParams.get("account") ?? undefined) };
288
403
  break;
289
404
  case "/v1/projects/files": {
290
405
  const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
@@ -315,12 +430,15 @@ export function createRouteHandler(ctx) {
315
430
  // they go only to callers that ask with `goPlan=1`; others keep the
316
431
  // Go account and its message without windows.
317
432
  const goPlan = url.searchParams.get("goPlan") === "1";
318
- const usage = await accountUsage.read();
433
+ // Likewise one `claude` row: a phone that shipped before accounts refuses
434
+ // two rows with one source, so extra Claude homes come only with `accounts=all`.
435
+ const allAccounts = url.searchParams.get("accounts") === "all";
436
+ const usage = await accountUsage.read(known, allAccounts);
319
437
  result = { ...usage, accounts: usageForCaller(usage.accounts, known, goPlan) };
320
438
  // `peers=1` (the memory-free `phren usage`): each linked computer's own answer too.
321
439
  if (url.searchParams.get("peers") === "1")
322
440
  result = { ...result, computer: info.computer,
323
- ...await fromPeers(`/v1/usage?${new URLSearchParams({ sources: [...known].join(","), ...(goPlan ? { goPlan: "1" } : {}) })}`) };
441
+ ...await fromPeers(`/v1/usage?${new URLSearchParams({ sources: [...known].join(","), ...(goPlan ? { goPlan: "1" } : {}), ...(allAccounts ? { accounts: "all" } : {}) })}`) };
324
442
  break;
325
443
  }
326
444
  case "/v1/resources": {
@@ -332,6 +450,9 @@ export function createRouteHandler(ctx) {
332
450
  case "/v1/push/status":
333
451
  result = agentHooks.push.status;
334
452
  break;
453
+ case "/v1/sudo":
454
+ result = { requests: agentHooks.sudo.list() };
455
+ break;
335
456
  case "/v1/projects/locate": {
336
457
  const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
337
458
  for (const candidate of candidates) {
@@ -348,17 +469,17 @@ export function createRouteHandler(ctx) {
348
469
  break;
349
470
  case "/v1/workspaces": {
350
471
  const server = selectedServer(url);
351
- result = await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1");
472
+ result = muxReplyForClient(await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1"), typedMuxRequest(url));
352
473
  break;
353
474
  }
354
475
  case "/v1/workspaces/panes":
355
- result = await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || "");
476
+ result = muxReplyForClient(await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || ""), typedMuxRequest(url));
356
477
  break;
357
478
  case "/v1/transcripts/blob": {
358
479
  const target = targetFromURL(url);
359
480
  await validateTarget(target);
360
481
  const inner = url.searchParams.get("inner");
361
- const bytes = await historicalImage(await transcriptPath(target.source, target.session), Number(url.searchParams.get("line")), Number(url.searchParams.get("block")), target.source, inner === null ? undefined : Number(inner));
482
+ const bytes = await historicalImage(await targetTranscriptPath(target), Number(url.searchParams.get("line")), Number(url.searchParams.get("block")), target.source, inner === null ? undefined : Number(inner));
362
483
  response.setHeader("Content-Type", "application/octet-stream");
363
484
  response.end(bytes);
364
485
  return;
@@ -482,6 +603,9 @@ export function createRouteHandler(ctx) {
482
603
  harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
483
604
  } : undefined);
484
605
  }
606
+ else if (url.pathname === "/v1/sessions/rename") {
607
+ result = await renameSession(selectedServer(url), data);
608
+ }
485
609
  else if (url.pathname === "/v1/schedules") {
486
610
  result = await scheduler.statuses();
487
611
  }
@@ -502,25 +626,72 @@ export function createRouteHandler(ctx) {
502
626
  await streamSpeech(data, response);
503
627
  return;
504
628
  }
629
+ else if (url.pathname === "/v1/hand-off") {
630
+ result = await ctx.handOffs.enqueue(data);
631
+ }
632
+ else if (url.pathname === "/v1/hand-off/status") {
633
+ const body = z.object({ deliveryId: z.string().min(8).max(64), target: targetSchema }).strict().parse(data);
634
+ result = await ctx.handOffs.status(body.deliveryId, body.target);
635
+ }
505
636
  else if (url.pathname === "/v1/dispatch") {
506
637
  // `origin` is the caller's own pane, added by the MCP tool or CLI from Herdr's variables.
507
638
  const { origin, ...brief } = data;
508
639
  result = await dispatches.dispatch(brief, origin);
509
640
  }
510
641
  else if (url.pathname === "/v1/dispatch/workers") {
511
- result = await workerStates(data);
642
+ result = await hookWorkers(agentHooks)(data);
512
643
  }
513
644
  else if (url.pathname === "/v1/dispatch/returns") {
514
645
  result = { returns: await ctx.returns.take() };
515
646
  }
647
+ else if (url.pathname === "/v1/dispatch/approve") {
648
+ const body = z.object({ id: z.string().uuid(), decision: z.enum(["approve", "deny"]), actionId: z.string().min(1).max(200), origin: originPaneSchema.optional() }).strict().parse(data);
649
+ await ctx.returns.answerApproval(body.id, body.decision, body.actionId, body.origin);
650
+ result = { ok: true };
651
+ }
516
652
  else if (url.pathname === "/v1/conductor/grants") {
517
653
  result = { ok: true, grant: await addGrant(data) };
518
654
  }
655
+ else if (url.pathname === "/v1/authority" || url.pathname === "/v1/authority/confirm") {
656
+ // The owner writes the policy from the phone; an agent's call names its pane.
657
+ if (data.origin !== undefined)
658
+ throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
659
+ result = url.pathname === "/v1/authority" ? { ok: true, authority: await setProjectAuthority(data, "phone") }
660
+ : { ok: true, confirmation: await confirmAuthority(data, "phone") };
661
+ }
662
+ else if (url.pathname === "/v1/conductor/make") {
663
+ // Serialized with launches, so a conductor launch and a make cannot both pass the set check.
664
+ result = await launches.run(async () => makeConductor(selectedServer(url), data));
665
+ }
666
+ else if (url.pathname === "/v1/conductor/stop") {
667
+ result = await launches.run(async () => stopConductor(data));
668
+ }
669
+ else if (url.pathname === "/v1/sets/name") {
670
+ result = await nameSet(data);
671
+ }
519
672
  else if (url.pathname === "/v1/push/register") {
520
673
  // Registration is kept for when a key is added; the reply says whether push works now.
521
674
  await agentHooks.push.register(data);
522
675
  result = { ok: true, configured: agentHooks.push.status.configured };
523
676
  }
677
+ else if (url.pathname === "/v1/sudo/answer") {
678
+ // The owner answers from the phone; an agent's call names its pane.
679
+ if (data && typeof data === "object" && "origin" in data)
680
+ throw new BridgeError(403, "Only the owner answers a sudo request, from the phone.");
681
+ let parsed;
682
+ try {
683
+ parsed = sudoAnswer(data);
684
+ }
685
+ catch {
686
+ throw new BridgeError(400, "Send an id and a password, or deny.");
687
+ }
688
+ const answered = agentHooks.sudo.answer(parsed.id, parsed.answer);
689
+ if (!answered)
690
+ throw new BridgeError(404, "This sudo request is no longer pending.");
691
+ // Asked for: whether sudo took the password, so the phone knows to save or forget it.
692
+ const outcome = parsed.outcome ? await answered.outcome : undefined;
693
+ result = { ok: true, ...(outcome ? { outcome } : {}) };
694
+ }
524
695
  else if (url.pathname === "/v1/push/answer") {
525
696
  await agentHooks.answerPush(z.string().uuid().parse(data.binding), data.decision);
526
697
  result = { ok: true };
@@ -558,7 +729,8 @@ export function createRouteHandler(ctx) {
558
729
  const cwd = storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
559
730
  : data.project !== undefined ? await dispatchProjectDirectory(data.project)
560
731
  : await launchDirectory(data.cwd, await journal.recent(), locatedDirectories);
561
- return launchSession(selectedServer(url), { ...data, cwd });
732
+ // A project the Hook resolved (a dispatch) is a folder it may trust; a folder the phone named is not.
733
+ return launchSession(selectedServer(url), { ...data, cwd }, { trustFolder: data.project !== undefined });
562
734
  });
563
735
  }
564
736
  else if (url.pathname.startsWith("/v1/workspaces/")) {
@@ -572,10 +744,16 @@ export function createRouteHandler(ctx) {
572
744
  }
573
745
  }
574
746
  else if (request.method === "DELETE") {
575
- if (url.pathname !== "/v1/conductor/grants")
747
+ if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority")
576
748
  throw new BridgeError(404, "Unknown Phren Hook route.");
577
749
  const data = await body(request);
578
- result = { ok: true, grant: await removeGrant(data) };
750
+ if (url.pathname === "/v1/authority") {
751
+ if (data.origin !== undefined)
752
+ throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
753
+ result = { ok: true, authority: await clearProjectAuthority(data, "phone") };
754
+ }
755
+ else
756
+ result = { ok: true, grant: await removeGrant(data) };
579
757
  }
580
758
  else
581
759
  throw new BridgeError(405, "Unsupported request method.");
@@ -6,6 +6,7 @@ import type { HookInfo } from "./server-routes.js";
6
6
  import type { SideQuestions } from "./side-questions.js";
7
7
  import { TranscriptReader } from "./transcripts.js";
8
8
  import type { ModuleSnapshot } from "../modules/runtime.js";
9
+ import { type SettingsSwitcher } from "./settings-switch.js";
9
10
  /** The WebSocket transcript and status streams: the backlog, appended rows and
10
11
  * previews on a tick loop, older pages on request, and the pane's status. */
11
12
  export interface StreamContext {
@@ -13,6 +14,7 @@ export interface StreamContext {
13
14
  agentHooks: AgentHooks;
14
15
  codexQuestions: CodexQuestions;
15
16
  sideQuestions?: SideQuestions;
17
+ settingsSwitcher?: SettingsSwitcher;
16
18
  info: HookInfo;
17
19
  activeCapabilities: Record<string, unknown>;
18
20
  }
@@ -6,8 +6,11 @@ import { SNAPSHOT_SHARE_MS, trustedDirectory, validateTarget } from "./herdr.js"
6
6
  import { repositoryBranch } from "./projects.js";
7
7
  import { BridgeError, MAX_FRAME, object, targetFromURL } from "./protocol.js";
8
8
  import { TranscriptPreviewStream } from "./transcript-preview.js";
9
- import { childAgent, childAgentTree, refreshTranscript, TranscriptReader, transcriptPath } from "./transcripts.js";
9
+ import { childAgent, childAgentTree, refreshTranscript, targetTranscriptPath, TranscriptReader } from "./transcripts.js";
10
10
  import { countTick } from "./metrics.js";
11
+ import { approvalSummary } from "./approval-summary.js";
12
+ import { codexServers } from "./codex-servers.js";
13
+ import { settingsCapabilities } from "./settings-switch.js";
11
14
  function send(socket, frame) {
12
15
  if (socket.readyState !== WebSocket.OPEN)
13
16
  return;
@@ -37,13 +40,13 @@ export function streamCloseReason(error) {
37
40
  return reason;
38
41
  }
39
42
  export function transcriptStreams(ctx) {
40
- const { modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities } = ctx;
43
+ const { modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities } = ctx;
41
44
  /** A conversation the agent has identified but not written yet (Claude
42
45
  * Code creates its file on the first turn) is an empty transcript, not a
43
46
  * missing one: `reader` stays undefined until the file appears. */
44
47
  async function conversationReader(target) {
45
48
  try {
46
- const reader = new TranscriptReader(await transcriptPath(target.source, target.session), target.source, undefined, modules.has("git") ? agentHooks.changes.view(`${target.source}:${target.session}`) : undefined);
49
+ const reader = new TranscriptReader(await targetTranscriptPath(target), target.source, undefined, modules.has("git") ? agentHooks.changes.view(`${target.source}:${target.session}`) : undefined);
47
50
  return { reader, source: target.source, session: target.session };
48
51
  }
49
52
  catch (error) {
@@ -155,7 +158,10 @@ export function transcriptStreams(ctx) {
155
158
  await agentHooks.syncTerminalDialog(target, waiting && !pendingQuestions?.length);
156
159
  pendingApproval = agentHooks.approval(target);
157
160
  }
158
- const hookPrompt = waiting ? agentHooks.terminalPrompt(target) : undefined;
161
+ // A served OpenCode pane's question comes from its own API, whatever
162
+ // status its terminal reports.
163
+ const servedQuestion = agentHooks.servedQuestion(target);
164
+ const hookPrompt = servedQuestion ?? (waiting ? agentHooks.terminalPrompt(target) : undefined);
159
165
  // Codex 0.155's queued follow-up question never becomes a held
160
166
  // PermissionRequest: it lives as a thread item the terminal shows
161
167
  // under "Queued follow-up inputs". With nothing else to ask, read
@@ -164,21 +170,29 @@ export function transcriptStreams(ctx) {
164
170
  const terminalPrompt = hookPrompt
165
171
  ?? (waiting && target.source === "codex" && !pendingQuestions?.length
166
172
  ? await queuedQuestion(target.session).then(queued => queued ? {
167
- toolName: "Question", message: queued.title, queued: true,
173
+ toolName: "Question", message: queued.title, request: approvalSummary({ tool: "Question", message: queued.title, question: true }).request, queued: true,
168
174
  choice: { title: queued.title, options: queued.options },
169
175
  } : undefined).catch(() => undefined)
170
176
  : undefined);
177
+ // Claude's own state comes from its footer, which leads the transcript.
178
+ const codexServed = target.source === "codex" && !!codexServers.forTarget(target);
179
+ const { settings, settingsState } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed)
180
+ : { settings: settingsCapabilities(target.source, codexServed), settingsState: undefined };
171
181
  const historyHealth = target.source === "codex" ? await threadHealth(target.session, pane.agent_status) : { stalled: false };
172
182
  send(client, { agentStatus: { source: target.source, session: target.session,
173
- status: pendingApproval ? "waiting" : pane.agent_status, pendingApproval, pendingQuestions, terminalPrompt,
183
+ status: pendingApproval || servedQuestion ? "waiting" : pane.agent_status, pendingApproval, pendingQuestions, terminalPrompt,
174
184
  ...(waiting && agentHooks.passwordPrompt(target) ? { passwordPrompt: true } : {}),
175
185
  compacting: agentHooks.compacting(target),
176
186
  ...(historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {}),
177
187
  modules: info.modules, store: info.store, profile: info.profile, generation: info.generation,
178
- capabilities: { ...activeCapabilities, asyncQuestions: target.source === "codex" && codexQuestions.available,
188
+ capabilities: { ...activeCapabilities, asyncQuestions: codexQuestions.availableFor(target),
189
+ // Answers to Codex questions may carry the phone's uploads.
190
+ ...(codexQuestions.availableFor(target) ? { questionAttachments: true } : {}),
179
191
  // Claude's AskUserQuestion is answered in its terminal dialog
180
192
  // through /v1/questions/answer, whether or not a hold caught it.
181
- ...(target.source === "claude" ? { questions: true } : {}) }, branch } });
193
+ ...(target.source === "claude" || servedQuestion ? { questions: true } : {}),
194
+ // What the composer's permission, plan and fast chips can change here.
195
+ ...(settings ? { settings } : {}) }, ...(settingsState ? { settingsState } : {}), branch } });
182
196
  }
183
197
  if (sideAnswers && sideQuestions) {
184
198
  for (const { revision, ...side } of sideQuestions.list(target)) {
@@ -1,4 +1,9 @@
1
+ import { ModelCatalog } from "./models.js";
2
+ import { AccountUsageReader } from "./usage.js";
1
3
  export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
2
4
  export { streamCloseReason } from "./server-stream.js";
3
5
  export { herdrAgentName, launchSession } from "./server-launch.js";
4
- export declare function serve(version: string): Promise<void>;
6
+ export declare function serve(version: string, options?: {
7
+ modelCatalog?: ModelCatalog;
8
+ accountUsage?: AccountUsageReader;
9
+ }): Promise<void>;