@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
@@ -1,3 +1,4 @@
1
+ import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
1
2
  import path from "node:path";
2
3
  import { z } from "zod";
3
4
  import { saveCodeNote } from "./code-note.js";
@@ -5,30 +6,43 @@ import { handOff } from "./hand-off.js";
5
6
  import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
6
7
  import { homeDir } from "../home-paths.js";
7
8
  import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
8
- import { dispatchProjectDirectory, dispatchStatus } from "./dispatch.js";
9
- import { workerStates } from "./dispatch-returns.js";
9
+ import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
10
+ import { hookWorkers } from "./dispatch-returns.js";
10
11
  import { remoteChildren } from "./dispatch-tree.js";
11
- import { addGrant, listGrants, removeGrant } from "./grants.js";
12
+ import { briefArrival, briefId } from "./launch-brief.js";
13
+ import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
14
+ import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
15
+ import { readComputers } from "./computer-identity.js";
12
16
  import { optionalHookPeers, peerRequest } from "./peers.js";
13
17
  import { candidateRepos, enrollProject } from "./enroll.js";
14
18
  import { browseFiles } from "./files.js";
15
19
  import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
16
20
  import { storeRoute } from "./memory-store.js";
17
- import { paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
21
+ import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
22
+ import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
18
23
  import { locateProject } from "./locate.js";
19
24
  import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
20
25
  import { BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
21
26
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
22
- import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, transcriptPath } from "./transcripts.js";
27
+ import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, targetTranscriptPath } from "./transcripts.js";
23
28
  import { listUploads, saveUpload, uploadImage } from "./uploads.js";
24
29
  import { currentModel, currentStep } from "./steps.js";
30
+ import { usageForCaller } from "./usage.js";
31
+ import { readFinalTurn } from "./schedule-watch.js";
25
32
  import { healthDetails, listsCaller } from "./health.js";
26
33
  import { defaultPhrenPath } from "../shared.js";
27
34
  import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
28
35
  import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
29
- import { launchSession, localConductor, workspaceAction } from "./server-launch.js";
36
+ import { renameSession } from "./session-rename.js";
37
+ import { launchSession, makeConductor, stopConductor, workspaceAction } from "./server-launch.js";
38
+ import { conductorAnswer, nameSet, readSets } from "./conductor-sets.js";
39
+ import { conductorPane } from "./conductor-role.js";
30
40
  import { hookMetrics } from "./metrics.js";
31
- import { streamSpeech } from "./speech.js";
41
+ import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
42
+ import { readSpeechKey } from "./speech-key.js";
43
+ import { DEFAULT_SPEECH_VOICE, listSpeechVoices, resolveSpeechVoice } from "./speech-voice.js";
44
+ import { terminalKind, terminalMux } from "./terminal.js";
45
+ import { muxListForClient, muxReplyForClient, typedMuxRequest } from "./mux-wire.js";
32
46
  const CHILD_ACTIVITY_CACHE_MS = 5_000;
33
47
  /** How long the overview waits for per-tab git and transcript reads; the phone gives up at 20 s. */
34
48
  export const OVERVIEW_ENRICH_BUDGET_MS = 5_000;
@@ -49,9 +63,9 @@ async function childActivity(source, session) {
49
63
  return result;
50
64
  }
51
65
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
52
- terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
66
+ terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
53
67
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
54
- 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 };
68
+ 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 };
55
69
  export function capabilitiesForModules(snapshot) {
56
70
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
57
71
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -87,9 +101,19 @@ async function body(request) {
87
101
  }
88
102
  export function selectedServer(url) {
89
103
  const mux = url.searchParams.get("mux");
90
- if (mux && !mux.startsWith("herdr:"))
91
- throw new BridgeError(400, "Select a Herdr server.");
92
- return serverName.parse(url.searchParams.get("server") || mux?.slice(6) || "default");
104
+ const selected = mux ? /^(herdr|tmux):(.+)$/.exec(mux) : undefined;
105
+ if (mux && !selected)
106
+ throw new BridgeError(400, "Select a terminal source.");
107
+ const explicit = url.searchParams.get("server");
108
+ if (explicit && selected && explicit !== selected[2])
109
+ throw new BridgeError(400, "Conflicting terminal sources.");
110
+ const server = serverName.parse(explicit || selected?.[2] || "default");
111
+ // Old phones used herdr:tmux. Keep that alias, but a typed tmux id must
112
+ // never silently route to a Herdr session with the same server name.
113
+ if (selected?.[1] === "tmux" && terminalKind(server) !== "tmux") {
114
+ throw new BridgeError(409, "This terminal source changed. Refresh the computer.", { code: "mux-kind-mismatch" });
115
+ }
116
+ return server;
93
117
  }
94
118
  export function workspacesReader(ctx) {
95
119
  const { modules, info, agentHooks, journal, tabActivity, contextUsage } = ctx;
@@ -100,7 +124,9 @@ export function workspacesReader(ctx) {
100
124
  const context = await contextUsage.read(server, s);
101
125
  await journal.record(server, objects(s.panes));
102
126
  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(() => ({}))])));
103
- const workspaces = workspaceSnapshot(s, context, agentHooks.pendingPanes(server, s), lastChanged);
127
+ // The Hook's record says which pane is the conductor, whatever the agent is named.
128
+ const conductor = await conductorPane(server, s).catch(() => undefined);
129
+ const workspaces = workspaceSnapshot(s, context, agentHooks.pendingPanes(server, s), lastChanged, conductor ? String(conductor.pane_id) : null);
104
130
  // The branch each tab's agent is on, for the session cards.
105
131
  const agentsByTab = new Map();
106
132
  for (const pane of objects(s.panes)) {
@@ -121,6 +147,8 @@ export function workspacesReader(ctx) {
121
147
  const chat = chatStates.get(agents[0]);
122
148
  if (chat?.starting === true)
123
149
  tab.starting = true;
150
+ // After the identity probe above, which is what learns a pane's transcript.
151
+ Object.assign(tab, paneAccountField(server, agents[0]));
124
152
  if (typeof chat?.sessionId === "string" && provider.safeParse(agents[0].agent).success) {
125
153
  tab.target = { server, workspace: group.id, tab: tab.id, pane: agents[0].pane_id, source: agents[0].agent, session: chat.sessionId };
126
154
  }
@@ -130,8 +158,27 @@ export function workspacesReader(ctx) {
130
158
  // the phone waits, so the computer read as offline. The overview answers
131
159
  // within its budget with whatever decoration is ready; a later read fills in.
132
160
  let expired = false;
161
+ let timer;
162
+ const budget = new Promise(resolve => { timer = setTimeout(resolve, OVERVIEW_ENRICH_BUDGET_MS); });
163
+ // First, each pane's own turn record (one small file): whether its ended
164
+ // turn still has background work, and which dispatch it is. It runs ahead
165
+ // of the slower reads so the status does not flicker between answers, but
166
+ // inside the budget, so a stuck disk cannot hold the overview either.
167
+ const records = Promise.all(tabs.map(async ({ group, tab }) => {
168
+ const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
169
+ const session = agents.length === 1 && object(tab.target).session;
170
+ const record = typeof session === "string" ? await paneRecord(server, agents[0], session) : undefined;
171
+ const [title, background] = await Promise.all([
172
+ recordTitle(record, { paneLabel: tab.paneLabel, harnessTitle: tab.title, tabLabel: tab.label, workspaceLabel: group.label, fallbackLabel: tab.label }),
173
+ liveBackground(record, readFinalTurn),
174
+ ]);
175
+ if (expired)
176
+ return;
177
+ markBackground(tab, background);
178
+ tab.title = title;
179
+ }));
133
180
  let nextTab = 0;
134
- const enrich = Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
181
+ const enrich = records.then(() => Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
135
182
  while (!expired && nextTab < tabs.length) {
136
183
  const { group, tab } = tabs[nextTab++];
137
184
  const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
@@ -159,19 +206,37 @@ export function workspacesReader(ctx) {
159
206
  }
160
207
  }
161
208
  // A row finished after the answer left belongs to the next read.
162
- if (!expired)
209
+ if (!expired) {
163
210
  Object.assign(tab, Object.fromEntries(Object.entries(found).filter(([, value]) => value !== undefined)));
211
+ // Codex subagents and fanout jobs keep an idle-looking session working too.
212
+ markBackground(tab, typeof found.runningChildren === "number" ? found.runningChildren : undefined);
213
+ }
164
214
  }
165
- }));
166
- let timer;
167
- await Promise.race([enrich, new Promise(resolve => { timer = setTimeout(resolve, OVERVIEW_ENRICH_BUDGET_MS); })]);
215
+ })));
216
+ await Promise.race([enrich, budget]);
168
217
  expired = true;
169
218
  clearTimeout(timer);
170
- return { ...workspaces, phren: info };
219
+ const mux = terminalMux(server);
220
+ return { ...workspaces, kind: mux.kind, mux, phren: info };
171
221
  };
172
222
  }
223
+ /** One read-only GET to every linked peer, each answer or its error by computer name. */
224
+ async function fromPeers(route) {
225
+ const { peers, peerError } = await optionalHookPeers();
226
+ const answers = await Promise.all(peers.map(async (peer) => {
227
+ try {
228
+ return { name: peer.name, ...await peerRequest(peer, route, undefined, 15_000) };
229
+ }
230
+ catch (error) {
231
+ const code = error instanceof BridgeError && typeof error.details?.code === "string" ? error.details.code : undefined;
232
+ const older = error instanceof BridgeError && error.status === 404;
233
+ return { name: peer.name, error: older ? "This computer's Hook predates this report; update it with phren bridge update." : error instanceof Error ? error.message.slice(0, 300) : "Unavailable", ...(code ? { code } : {}) };
234
+ }
235
+ }));
236
+ return { peers: answers, ...(peerError ? { peerError } : {}) };
237
+ }
173
238
  export function createRouteHandler(ctx) {
174
- const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, launches, locatedDirectories, fanoutMessages, canary } = ctx;
239
+ const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, resources, launches, locatedDirectories, fanoutMessages, canary } = ctx;
175
240
  const { conversationReader, childConversationReader, emptyPage } = ctx.streams;
176
241
  const readWorkspaces = workspacesReader(ctx);
177
242
  return async (request, response) => {
@@ -208,22 +273,66 @@ export function createRouteHandler(ctx) {
208
273
  case "/v1/dispatch":
209
274
  result = { dispatches: await dispatchStatus() };
210
275
  break;
276
+ // Receiving side of a launched brief: what the worker's hooks reported for it.
277
+ case "/v1/dispatch/arrival":
278
+ result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
279
+ break;
211
280
  case "/v1/conductor/grants":
212
- result = { grants: await listGrants() };
281
+ result = { grants: await listNamedGrants() };
213
282
  break;
214
- // Asked by linked peers before they start a conductor: one per connected group.
283
+ // The owner's release authority policy, which conductors read and quote in briefs.
284
+ case "/v1/authority": {
285
+ const policy = await readAuthority();
286
+ const project = url.searchParams.get("project");
287
+ result = project !== null ? { authority: projectAuthority(policy, z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/).parse(project)) }
288
+ : { source: policy.source, ...(policy.updatedAt ? { updatedAt: policy.updatedAt } : {}), ...(policy.updatedBy ? { updatedBy: policy.updatedBy } : {}),
289
+ projects: Object.keys(policy.projects).sort().map(name => projectAuthority(policy, name)), confirmations: await listConfirmations() };
290
+ break;
291
+ }
292
+ // One row per real computer, however many names machines.yaml and the network give it.
293
+ case "/v1/computers": {
294
+ const { computers, peerError } = await readComputers({ probe: true, local: { id: info.computer.id } });
295
+ result = { computers, ...(peerError ? { peerError } : {}) };
296
+ break;
297
+ }
298
+ // Asked by linked peers to place this computer in a set, and before they start a conductor: one per set.
215
299
  case "/v1/conductor":
216
- result = { computer: info.computer, conductor: await localConductor() ?? null };
300
+ result = await conductorAnswer(info, url);
301
+ break;
302
+ case "/v1/sets":
303
+ result = await readSets(info);
304
+ break;
305
+ // Bounded like capacity: a cold `claude auth status` per home can take seconds. Without
306
+ // `harnesses` the phone treats the computer as unknown and offers everything; the probe keeps
307
+ // running, so the next request answers from cache.
308
+ case "/v1/harnesses":
309
+ result = await harnessInventoryWithin(2_500) ?? { pending: true };
217
310
  break;
218
311
  case "/v1/dispatch/capacity": {
219
312
  const live = await servers();
220
313
  const snapshots = await Promise.all(live.map(server => snapshot(String(server.session))));
221
- result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session),
222
- working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0) };
314
+ // Asked by a conductor with its name or host key: whether this computer links it back, so it dispatches only within its set.
315
+ const caller = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() })
316
+ .parse({ name: url.searchParams.get("name") ?? undefined, hostKey: url.searchParams.get("hostKey") ?? undefined });
317
+ const linksBack = caller.name || caller.hostKey ? { knowsCaller: (await listsCaller(caller)).knowsCaller } : {};
318
+ result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session), ...linksBack,
319
+ working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0),
320
+ // Bounded so a peer's capacity probe never waits on a cold `claude auth status`; missing means unknown.
321
+ // PHREN_LAUNCH_CHECK=off turns this Hook's availability checks off, including what it advertises to dispatch.
322
+ ...(launchCheckOff() ? {} : await harnessInventoryWithin(2_500).then(inventory => inventory ? { harnesses: inventory.harnesses } : {})) };
323
+ break;
324
+ }
325
+ case "/v1/speech/voices": {
326
+ // The phone's voice picker: this computer's setting and the voices its account has.
327
+ const key = await readSpeechKey();
328
+ if (!key)
329
+ throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
330
+ const current = await resolveSpeechVoice();
331
+ result = { voice: current.voice, source: current.source, defaultVoice: DEFAULT_SPEECH_VOICE, voices: await listSpeechVoices(key) };
223
332
  break;
224
333
  }
225
334
  case "/v1/muxes":
226
- result = { muxes: await servers() };
335
+ result = { muxes: muxListForClient(await servers(), url.searchParams.get("typed") === "1") };
227
336
  break;
228
337
  case "/v1/activity":
229
338
  result = { events: await journal.recent() };
@@ -268,7 +377,7 @@ export function createRouteHandler(ctx) {
268
377
  break;
269
378
  }
270
379
  case "/v1/models":
271
- result = { models: await modelCatalog.list(String(url.searchParams.get("source") ?? "")) };
380
+ result = { models: await modelCatalog.list(String(url.searchParams.get("source") ?? ""), url.searchParams.get("account") ?? undefined) };
272
381
  break;
273
382
  case "/v1/projects/files": {
274
383
  const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
@@ -294,8 +403,26 @@ export function createRouteHandler(ctx) {
294
403
  // meets a source it does not know, so a client names the sources it
295
404
  // understands and an older one gets the original four.
296
405
  const known = new Set((url.searchParams.get("sources") ?? "codex,claude,opencode,openrouter").split(",").map(s => s.trim()).filter(Boolean));
297
- const usage = await accountUsage.read();
298
- result = { ...usage, accounts: usage.accounts.filter(account => known.has(account.source)) };
406
+ // A phone built before Go's plan windows rejects a Go window with a
407
+ // percentage and no dollar limit (and the whole answer with it), so
408
+ // they go only to callers that ask with `goPlan=1`; others keep the
409
+ // Go account and its message without windows.
410
+ const goPlan = url.searchParams.get("goPlan") === "1";
411
+ // Likewise one `claude` row: a phone that shipped before accounts refuses
412
+ // two rows with one source, so extra Claude homes come only with `accounts=all`.
413
+ const allAccounts = url.searchParams.get("accounts") === "all";
414
+ const usage = await accountUsage.read(known, allAccounts);
415
+ result = { ...usage, accounts: usageForCaller(usage.accounts, known, goPlan) };
416
+ // `peers=1` (the memory-free `phren usage`): each linked computer's own answer too.
417
+ if (url.searchParams.get("peers") === "1")
418
+ result = { ...result, computer: info.computer,
419
+ ...await fromPeers(`/v1/usage?${new URLSearchParams({ sources: [...known].join(","), ...(goPlan ? { goPlan: "1" } : {}), ...(allAccounts ? { accounts: "all" } : {}) })}`) };
420
+ break;
421
+ }
422
+ case "/v1/resources": {
423
+ result = { computer: info.computer, resources: await resources.read() };
424
+ if (url.searchParams.get("peers") === "1")
425
+ result = { ...result, ...await fromPeers("/v1/resources") };
299
426
  break;
300
427
  }
301
428
  case "/v1/push/status":
@@ -317,17 +444,17 @@ export function createRouteHandler(ctx) {
317
444
  break;
318
445
  case "/v1/workspaces": {
319
446
  const server = selectedServer(url);
320
- result = await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1");
447
+ result = muxReplyForClient(await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1"), typedMuxRequest(url));
321
448
  break;
322
449
  }
323
450
  case "/v1/workspaces/panes":
324
- result = await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || "");
451
+ result = muxReplyForClient(await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || ""), typedMuxRequest(url));
325
452
  break;
326
453
  case "/v1/transcripts/blob": {
327
454
  const target = targetFromURL(url);
328
455
  await validateTarget(target);
329
456
  const inner = url.searchParams.get("inner");
330
- 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));
457
+ const bytes = await historicalImage(await targetTranscriptPath(target), Number(url.searchParams.get("line")), Number(url.searchParams.get("block")), target.source, inner === null ? undefined : Number(inner));
331
458
  response.setHeader("Content-Type", "application/octet-stream");
332
459
  response.end(bytes);
333
460
  return;
@@ -451,6 +578,9 @@ export function createRouteHandler(ctx) {
451
578
  harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
452
579
  } : undefined);
453
580
  }
581
+ else if (url.pathname === "/v1/sessions/rename") {
582
+ result = await renameSession(selectedServer(url), data);
583
+ }
454
584
  else if (url.pathname === "/v1/schedules") {
455
585
  result = await scheduler.statuses();
456
586
  }
@@ -477,14 +607,36 @@ export function createRouteHandler(ctx) {
477
607
  result = await dispatches.dispatch(brief, origin);
478
608
  }
479
609
  else if (url.pathname === "/v1/dispatch/workers") {
480
- result = await workerStates(data);
610
+ result = await hookWorkers(agentHooks)(data);
481
611
  }
482
612
  else if (url.pathname === "/v1/dispatch/returns") {
483
613
  result = { returns: await ctx.returns.take() };
484
614
  }
615
+ else if (url.pathname === "/v1/dispatch/approve") {
616
+ 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);
617
+ await ctx.returns.answerApproval(body.id, body.decision, body.actionId, body.origin);
618
+ result = { ok: true };
619
+ }
485
620
  else if (url.pathname === "/v1/conductor/grants") {
486
621
  result = { ok: true, grant: await addGrant(data) };
487
622
  }
623
+ else if (url.pathname === "/v1/authority" || url.pathname === "/v1/authority/confirm") {
624
+ // The owner writes the policy from the phone; an agent's call names its pane.
625
+ if (data.origin !== undefined)
626
+ throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
627
+ result = url.pathname === "/v1/authority" ? { ok: true, authority: await setProjectAuthority(data, "phone") }
628
+ : { ok: true, confirmation: await confirmAuthority(data, "phone") };
629
+ }
630
+ else if (url.pathname === "/v1/conductor/make") {
631
+ // Serialized with launches, so a conductor launch and a make cannot both pass the set check.
632
+ result = await launches.run(async () => makeConductor(selectedServer(url), data));
633
+ }
634
+ else if (url.pathname === "/v1/conductor/stop") {
635
+ result = await launches.run(async () => stopConductor(data));
636
+ }
637
+ else if (url.pathname === "/v1/sets/name") {
638
+ result = await nameSet(data);
639
+ }
488
640
  else if (url.pathname === "/v1/push/register") {
489
641
  // Registration is kept for when a key is added; the reply says whether push works now.
490
642
  await agentHooks.push.register(data);
@@ -527,7 +679,8 @@ export function createRouteHandler(ctx) {
527
679
  const cwd = storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
528
680
  : data.project !== undefined ? await dispatchProjectDirectory(data.project)
529
681
  : await launchDirectory(data.cwd, await journal.recent(), locatedDirectories);
530
- return launchSession(selectedServer(url), { ...data, cwd });
682
+ // A project the Hook resolved (a dispatch) is a folder it may trust; a folder the phone named is not.
683
+ return launchSession(selectedServer(url), { ...data, cwd }, { trustFolder: data.project !== undefined });
531
684
  });
532
685
  }
533
686
  else if (url.pathname.startsWith("/v1/workspaces/")) {
@@ -541,10 +694,16 @@ export function createRouteHandler(ctx) {
541
694
  }
542
695
  }
543
696
  else if (request.method === "DELETE") {
544
- if (url.pathname !== "/v1/conductor/grants")
697
+ if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority")
545
698
  throw new BridgeError(404, "Unknown Phren Hook route.");
546
699
  const data = await body(request);
547
- result = { ok: true, grant: await removeGrant(data) };
700
+ if (url.pathname === "/v1/authority") {
701
+ if (data.origin !== undefined)
702
+ throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
703
+ result = { ok: true, authority: await clearProjectAuthority(data, "phone") };
704
+ }
705
+ else
706
+ result = { ok: true, grant: await removeGrant(data) };
548
707
  }
549
708
  else
550
709
  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>;