@phren/cli 0.3.11 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanouts.d.ts +7 -1
  42. package/dist/bridge/fanouts.js +39 -4
  43. package/dist/bridge/folder-trust.d.ts +56 -0
  44. package/dist/bridge/folder-trust.js +195 -0
  45. package/dist/bridge/grants.d.ts +22 -1
  46. package/dist/bridge/grants.js +57 -9
  47. package/dist/bridge/hand-off.d.ts +21 -9
  48. package/dist/bridge/hand-off.js +58 -45
  49. package/dist/bridge/harness-status.d.ts +11 -0
  50. package/dist/bridge/harness-status.js +32 -0
  51. package/dist/bridge/harnesses.d.ts +39 -0
  52. package/dist/bridge/harnesses.js +65 -0
  53. package/dist/bridge/health.d.ts +2 -0
  54. package/dist/bridge/health.js +1 -1
  55. package/dist/bridge/herdr.d.ts +11 -2
  56. package/dist/bridge/herdr.js +98 -23
  57. package/dist/bridge/hook-fast.d.ts +4 -0
  58. package/dist/bridge/hook-fast.js +68 -0
  59. package/dist/bridge/install.d.ts +16 -1
  60. package/dist/bridge/install.js +88 -21
  61. package/dist/bridge/launch-brief.d.ts +96 -0
  62. package/dist/bridge/launch-brief.js +164 -0
  63. package/dist/bridge/model-switch.d.ts +3 -0
  64. package/dist/bridge/model-switch.js +17 -1
  65. package/dist/bridge/models.d.ts +8 -4
  66. package/dist/bridge/models.js +24 -8
  67. package/dist/bridge/mux-wire.d.ts +9 -0
  68. package/dist/bridge/mux-wire.js +19 -0
  69. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  70. package/dist/bridge/opencode-pane-server.js +332 -0
  71. package/dist/bridge/opencode-panes.d.ts +111 -0
  72. package/dist/bridge/opencode-panes.js +295 -0
  73. package/dist/bridge/pane-accounts.d.ts +8 -0
  74. package/dist/bridge/pane-accounts.js +46 -0
  75. package/dist/bridge/prompt-startup.d.ts +5 -0
  76. package/dist/bridge/prompt-startup.js +24 -0
  77. package/dist/bridge/protocol.d.ts +5 -0
  78. package/dist/bridge/protocol.js +4 -0
  79. package/dist/bridge/push.d.ts +5 -4
  80. package/dist/bridge/push.js +6 -4
  81. package/dist/bridge/questions.d.ts +37 -2
  82. package/dist/bridge/questions.js +158 -15
  83. package/dist/bridge/resources.d.ts +9 -3
  84. package/dist/bridge/resources.js +24 -8
  85. package/dist/bridge/schedule-format.d.ts +2 -0
  86. package/dist/bridge/schedule-format.js +3 -0
  87. package/dist/bridge/schedule-launch.d.ts +2 -1
  88. package/dist/bridge/schedule-launch.js +23 -53
  89. package/dist/bridge/schedule-watch.d.ts +10 -1
  90. package/dist/bridge/schedule-watch.js +54 -2
  91. package/dist/bridge/server-launch.d.ts +22 -5
  92. package/dist/bridge/server-launch.js +225 -29
  93. package/dist/bridge/server-overview.d.ts +3 -3
  94. package/dist/bridge/server-overview.js +22 -14
  95. package/dist/bridge/server-pane-routes.d.ts +2 -0
  96. package/dist/bridge/server-pane-routes.js +145 -15
  97. package/dist/bridge/server-routes.d.ts +7 -0
  98. package/dist/bridge/server-routes.js +163 -35
  99. package/dist/bridge/server-stream.d.ts +2 -0
  100. package/dist/bridge/server-stream.js +22 -8
  101. package/dist/bridge/server.d.ts +6 -1
  102. package/dist/bridge/server.js +44 -12
  103. package/dist/bridge/session-activity.d.ts +81 -0
  104. package/dist/bridge/session-activity.js +117 -0
  105. package/dist/bridge/session-rename.d.ts +48 -0
  106. package/dist/bridge/session-rename.js +190 -0
  107. package/dist/bridge/session-servers.js +2 -2
  108. package/dist/bridge/settings-switch.d.ts +60 -0
  109. package/dist/bridge/settings-switch.js +287 -0
  110. package/dist/bridge/speech-voice.d.ts +55 -0
  111. package/dist/bridge/speech-voice.js +132 -0
  112. package/dist/bridge/speech.d.ts +70 -11
  113. package/dist/bridge/speech.js +169 -41
  114. package/dist/bridge/terminal-herdr.js +9 -3
  115. package/dist/bridge/terminal-tmux.d.ts +3 -3
  116. package/dist/bridge/terminal-tmux.js +24 -9
  117. package/dist/bridge/terminal.d.ts +27 -4
  118. package/dist/bridge/terminal.js +8 -1
  119. package/dist/bridge/transcript-claude.js +57 -12
  120. package/dist/bridge/transcript-codex.d.ts +0 -2
  121. package/dist/bridge/transcript-codex.js +29 -4
  122. package/dist/bridge/transcript-preview.d.ts +1 -0
  123. package/dist/bridge/transcript-preview.js +24 -4
  124. package/dist/bridge/transcripts.d.ts +15 -2
  125. package/dist/bridge/transcripts.js +47 -16
  126. package/dist/bridge/turn-records.d.ts +85 -0
  127. package/dist/bridge/turn-records.js +143 -0
  128. package/dist/bridge/uploads.d.ts +3 -0
  129. package/dist/bridge/uploads.js +14 -0
  130. package/dist/bridge/usage.d.ts +39 -10
  131. package/dist/bridge/usage.js +155 -44
  132. package/dist/bridge-hook.mjs +19169 -13176
  133. package/dist/cli/claude-unmanaged.d.ts +12 -0
  134. package/dist/cli/claude-unmanaged.js +105 -0
  135. package/dist/cli/schedules.js +2 -1
  136. package/dist/cli/session-start.js +10 -1
  137. package/dist/cli/session-stop.js +9 -1
  138. package/dist/cli-registry.js +24 -5
  139. package/dist/data/task-receipts.d.ts +19 -0
  140. package/dist/data/task-receipts.js +68 -0
  141. package/dist/data/tasks.js +4 -1
  142. package/dist/generated/memory-ui-graph.browser.js +63 -63
  143. package/dist/graph-core/model.js +24 -3
  144. package/dist/graph-core/types.d.ts +4 -1
  145. package/dist/graph-core/types.js +1 -0
  146. package/dist/init/init-preset.js +7 -3
  147. package/dist/init/init-uninstall.js +2 -11
  148. package/dist/init/teardown.d.ts +3 -0
  149. package/dist/init/teardown.js +47 -0
  150. package/dist/link/context.js +21 -9
  151. package/dist/mcp/plugin-mode.js +1 -1
  152. package/dist/memory-ui-graph.runtime.js +63 -63
  153. package/dist/modules/code-package.d.ts +1 -0
  154. package/dist/modules/code-package.js +36 -7
  155. package/dist/modules/registry.js +14 -13
  156. package/dist/profile-store.d.ts +6 -0
  157. package/dist/profile-store.js +25 -1
  158. package/dist/shell/graph/glyphs.js +4 -0
  159. package/dist/shell/graph/graph-view.js +2 -0
  160. package/dist/status.js +7 -1
  161. package/dist/sync/task-claim.js +3 -2
  162. package/dist/task/lifecycle.js +25 -4
  163. package/dist/test-global-setup.js +5 -0
  164. package/dist/tools/dispatch.js +35 -2
  165. package/dist/tools/tasks.js +10 -1
  166. package/package.json +1 -1
  167. package/plugins/opencode/phren-transcript.js +87 -4
  168. package/starter/global/skills/conductor/SKILL.md +17 -2
@@ -0,0 +1,287 @@
1
+ import { open, stat } from "node:fs/promises";
2
+ import { z } from "zod";
3
+ import { visibleTerminalChoice } from "./agent-hooks.js";
4
+ import { codexServers } from "./codex-servers.js";
5
+ import { validateTarget } from "./herdr.js";
6
+ import { intervalFromEnv } from "./limits.js";
7
+ import { emptyComposer } from "./model-switch.js";
8
+ import { BridgeError, object, PERMISSION_MODES } from "./protocol.js";
9
+ import { terminalProvider } from "./terminal.js";
10
+ import { transcriptPath } from "./transcripts.js";
11
+ import { stripTerminal } from "../terminal-text.js";
12
+ /** T3's CodexSessionRuntime mapping. The reviewer is always sent: leaving it
13
+ * out would keep `auto_review` from an earlier turn. */
14
+ export const CODEX_MODES = {
15
+ supervised: { approvalPolicy: "untrusted", approvalsReviewer: "user", sandboxPolicy: { type: "readOnly" } },
16
+ "auto-edits": { approvalPolicy: "on-request", approvalsReviewer: "user", sandboxPolicy: { type: "workspaceWrite" } },
17
+ auto: { approvalPolicy: "on-request", approvalsReviewer: "auto_review", sandboxPolicy: { type: "workspaceWrite" } },
18
+ "full-access": { approvalPolicy: "never", approvalsReviewer: "user", sandboxPolicy: { type: "dangerFullAccess" } },
19
+ };
20
+ /** Claude Code's `permissionMode` values, as the phone names them. */
21
+ const CLAUDE_MODES = { default: "supervised", acceptEdits: "auto-edits", auto: "auto", bypassPermissions: "full-access", plan: "plan" };
22
+ export const CLAUDE_NAMES = Object.fromEntries(Object.entries(CLAUDE_MODES).map(([raw, phone]) => [phone, raw]));
23
+ /** The same Codex mode as command-line flags, for a Codex started with no thread yet. */
24
+ export function codexModeFlags(mode) {
25
+ const { approvalPolicy, approvalsReviewer, sandboxPolicy } = CODEX_MODES[mode];
26
+ const sandbox = { readOnly: "read-only", workspaceWrite: "workspace-write", dangerFullAccess: "danger-full-access" }[String(sandboxPolicy?.type)];
27
+ return ["-a", String(approvalPolicy), "-s", String(sandbox), ...(approvalsReviewer === "auto_review" ? ["-c", 'approvals_reviewer="auto_review"'] : [])];
28
+ }
29
+ const MAX_PRESSES = 6, STEP_WAIT_MS = 2_000;
30
+ /** What this pane can change from the phone; undefined for harnesses that
31
+ * offer nothing. A hand-started Codex TUI is empty: its state is still read
32
+ * from its transcript, but switching is not offered. Claude's cycle holds
33
+ * `full-access` only when it was launched allowing bypass. */
34
+ export function settingsCapabilities(source, codexServed, claudeBypass = false) {
35
+ if (source === "codex")
36
+ return codexServed ? { permissionModes: [...PERMISSION_MODES], plan: true, fast: false } : { permissionModes: [], plan: false, fast: false };
37
+ if (source === "claude")
38
+ return { permissionModes: PERMISSION_MODES.filter(mode => mode !== "full-access" || claudeBypass), plan: true, fast: true };
39
+ return undefined;
40
+ }
41
+ const request = z.object({ permissionMode: z.enum(PERMISSION_MODES).optional(), plan: z.boolean().optional(), fast: z.boolean().optional() })
42
+ .strict().refine(value => value.permissionMode !== undefined || value.plan !== undefined || value.fast !== undefined, "Choose a setting to change.");
43
+ /** Claude's permission mode from the footer line its TUI draws under the
44
+ * composer. The transcript lags it: a `permission-mode` row is written only
45
+ * when a prompt is submitted, and a fresh session has no file yet. The line may
46
+ * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. */
47
+ export function claudeFooterMode(screen) {
48
+ for (const line of stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(-8).reverse()) {
49
+ const text = line.replace(/^[⏵⏸]+\s*/, "");
50
+ if (text === line)
51
+ continue;
52
+ if (/bypass permissions on/i.test(text))
53
+ return "bypassPermissions";
54
+ if (/^manual mode on\b/i.test(text))
55
+ return "default";
56
+ if (/^accept edits on\b/i.test(text))
57
+ return "acceptEdits";
58
+ if (/^plan mode on\b/i.test(text))
59
+ return "plan";
60
+ if (/^auto mode on\b/i.test(text))
61
+ return "auto";
62
+ }
63
+ return undefined;
64
+ }
65
+ /** A Claude pane's settings as its footer shows them, read at most once per
66
+ * `PHREN_DIALOG_THROTTLE_MS` like the dialog check, and whether bypass was
67
+ * ever seen in it (which is when full access is offered). */
68
+ export class ClaudeSettingsReader {
69
+ hooks;
70
+ every;
71
+ cache = new Map();
72
+ constructor(hooks, every = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000)) {
73
+ this.hooks = hooks;
74
+ this.every = every;
75
+ }
76
+ async read(target, terminal) {
77
+ const key = `${target.server}:${target.pane}`;
78
+ let entry = this.cache.get(key);
79
+ if (!entry || entry.terminal !== terminal)
80
+ entry = { terminal, at: 0, bypass: false };
81
+ // Re-set on every use so the Map's order is recency.
82
+ this.cache.delete(key);
83
+ this.cache.set(key, entry);
84
+ if (Date.now() - entry.at >= this.every) {
85
+ entry.at = Date.now();
86
+ entry.mode = await this.hooks.paneLines(target).then(claudeFooterMode, () => entry.mode);
87
+ if (entry.mode === "bypassPermissions")
88
+ entry.bypass = true;
89
+ while (this.cache.size > 64)
90
+ this.cache.delete(this.cache.keys().next().value);
91
+ }
92
+ const phone = entry.mode ? CLAUDE_MODES[entry.mode] : undefined;
93
+ return { bypass: entry.bypass, ...(phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {}) };
94
+ }
95
+ }
96
+ /** Claude's answer to a slash command: the first `<local-command-stdout>` user
97
+ * row appended after `from`. */
98
+ async function commandOutput(file, from) {
99
+ const handle = await open(file, "r");
100
+ try {
101
+ const { size } = await handle.stat(), length = Math.min(Math.max(size - from, 0), 1_048_576), buffer = Buffer.alloc(length);
102
+ await handle.read(buffer, 0, length, from);
103
+ for (const line of buffer.subarray(0, buffer.lastIndexOf(10) + 1).toString("utf8").split("\n")) {
104
+ if (!line.includes("local-command-stdout"))
105
+ continue;
106
+ try {
107
+ const content = object(object(JSON.parse(line)).message).content;
108
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.map(block => String(object(block).text ?? "")).join("") : "";
109
+ const match = /<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/.exec(text);
110
+ if (match)
111
+ return stripTerminal(match[1]).trim().slice(0, 300);
112
+ }
113
+ catch { /* Unrelated row. */ }
114
+ }
115
+ return undefined;
116
+ }
117
+ finally {
118
+ await handle.close();
119
+ }
120
+ }
121
+ const fileSize = async (file) => file ? (await stat(file).catch(() => undefined))?.size ?? 0 : 0;
122
+ /** One settings transaction per pane owns its terminal input until it ends. */
123
+ export class SettingsSwitcher {
124
+ hooks;
125
+ wait;
126
+ active = new Set();
127
+ reader;
128
+ constructor(hooks, wait = STEP_WAIT_MS) {
129
+ this.hooks = hooks;
130
+ this.wait = wait;
131
+ this.reader = new ClaudeSettingsReader(hooks);
132
+ }
133
+ /** A Claude pane's footer-read settings and capabilities for the stream. */
134
+ async streamSettings(target, terminal, codexServed) {
135
+ if (target.source !== "claude") {
136
+ const settings = settingsCapabilities(target.source, codexServed);
137
+ return settings ? { settings } : {};
138
+ }
139
+ const { state, bypass } = await this.reader.read(target, terminal);
140
+ return { settings: settingsCapabilities("claude", false, bypass), ...(state ? { settingsState: state } : {}) };
141
+ }
142
+ key(target) { return `${target.server}:${target.pane}`; }
143
+ assertAvailable(target) {
144
+ if (this.active.has(this.key(target)))
145
+ throw new BridgeError(409, "A settings change is already in progress. Wait for it to finish.");
146
+ }
147
+ async switch(target, data) {
148
+ this.assertAvailable(target);
149
+ // The route's own envelope is not a setting; anything else unknown is refused.
150
+ const { target: _target, deliveryId: _delivery, ...settings } = data;
151
+ const change = request.parse(settings);
152
+ // A Codex pane on the Hook's own app-server takes the settings with its
153
+ // next turn/start, whatever it is doing now, as with the model.
154
+ const served = target.source === "codex" ? codexServers.forTarget(target) : undefined;
155
+ if (served)
156
+ return this.hold(served, change);
157
+ if (target.source !== "claude")
158
+ throw new BridgeError(422, "Changing these settings is not supported for this harness. Open terminal to change them.");
159
+ this.active.add(this.key(target));
160
+ try {
161
+ return await this.claude(target, change);
162
+ }
163
+ finally {
164
+ this.active.delete(this.key(target));
165
+ }
166
+ }
167
+ hold(entry, change) {
168
+ if (change.fast !== undefined)
169
+ throw new BridgeError(422, "Fast mode is Claude's. Codex has no fast setting here.");
170
+ try {
171
+ codexServers.holdSettings(entry, { ...(change.permissionMode ? CODEX_MODES[change.permissionMode] : {}),
172
+ ...(change.plan !== undefined ? { collaborationMode: { mode: change.plan ? "plan" : "default" } } : {}) });
173
+ }
174
+ catch (error) {
175
+ throw new BridgeError(409, error instanceof Error ? error.message : "Codex could not take the setting.");
176
+ }
177
+ return { ok: true, ...(change.permissionMode ? { permissionMode: change.permissionMode } : {}), ...(change.plan !== undefined ? { plan: change.plan } : {}), applies: "next-turn" };
178
+ }
179
+ async claude(target, change) {
180
+ if (change.permissionMode && change.plan === true)
181
+ throw new BridgeError(422, "Claude's plan mode replaces the permission mode. Change one at a time.");
182
+ if (change.permissionMode === "full-access")
183
+ throw new BridgeError(422, "Claude only offers full access when it was launched allowing it. Open terminal to check.");
184
+ const first = await validateTarget(target, false, true);
185
+ if (!["idle", "done"].includes(String(first.agent_status))) {
186
+ throw new BridgeError(409, "This agent is working. Settings change between turns; choose it again when the turn ends.");
187
+ }
188
+ const terminal = first.terminal_id;
189
+ const validate = async () => {
190
+ const pane = await validateTarget(target, false, true);
191
+ if (pane.terminal_id !== terminal)
192
+ throw new BridgeError(409, "The terminal changed during the settings change.");
193
+ if (pane.agent_status === "working")
194
+ throw new BridgeError(409, "The agent started working during the settings change. The result is unconfirmed; check the terminal.");
195
+ };
196
+ const screenMode = async () => claudeFooterMode(await this.hooks.paneLines(target));
197
+ // The mode after a change: polled from the screen until it differs from `from`.
198
+ const changed = async (from, wait) => {
199
+ const deadline = Date.now() + wait;
200
+ do {
201
+ await new Promise(resolve => setTimeout(resolve, 150));
202
+ await validate();
203
+ const now = await screenMode();
204
+ if (now && now !== from)
205
+ return now;
206
+ } while (Date.now() < deadline);
207
+ throw new BridgeError(409, "Could not verify Claude's permission mode. Open terminal to check it.");
208
+ };
209
+ const slash = async (command) => {
210
+ // Typing into a draft would corrupt both it and the command.
211
+ const before = await this.hooks.paneLines(target, false);
212
+ const composer = before.split(/\r?\n/).reverse().find(line => /^\s*[›❯>]/.test(stripTerminal(line)));
213
+ if (!composer || !emptyComposer(composer) || visibleTerminalChoice(stripTerminal(before))) {
214
+ throw new BridgeError(409, "The terminal has a draft or an unreadable prompt. Open terminal before changing settings.");
215
+ }
216
+ await validate();
217
+ await terminalProvider().prompt(target.server, target.pane, command);
218
+ };
219
+ let verified;
220
+ if (change.fast !== undefined) {
221
+ const said = async () => [...stripTerminal(await this.hooks.paneLines(target, true)).matchAll(/fast mode (on|off)\b/gi)].map(match => match[1].toLowerCase());
222
+ // Older answers, in the transcript or the scrollback, must not count.
223
+ let file = await transcriptPath("claude", target.session).catch(() => undefined);
224
+ const from = await fileSize(file), earlier = (await said()).length;
225
+ await slash(`/fast ${change.fast ? "on" : "off"}`);
226
+ verified = false;
227
+ // Claude answers in the transcript, as a user row right after the command.
228
+ const deadline = Date.now() + Math.round(this.wait * 1.5);
229
+ let answer;
230
+ do {
231
+ await new Promise(resolve => setTimeout(resolve, 150));
232
+ await validate();
233
+ file ??= await transcriptPath("claude", target.session).catch(() => undefined);
234
+ answer = file ? await commandOutput(file, from).catch(() => undefined) : undefined;
235
+ } while (answer === undefined && Date.now() < deadline);
236
+ if (answer !== undefined) {
237
+ const state = /fast mode (?:is )?(on|off)\b/i.exec(answer)?.[1].toLowerCase();
238
+ if (/unavailable|not available/i.test(answer))
239
+ throw new BridgeError(422, `Claude: ${answer}`);
240
+ if (state) {
241
+ if ((state === "on") !== change.fast)
242
+ throw new BridgeError(409, `Claude answered Fast mode ${state}. Open terminal to check.`);
243
+ verified = true;
244
+ }
245
+ }
246
+ else {
247
+ // No row in time: the screen is the fallback.
248
+ const answers = await said(), last = answers.length > earlier ? answers.at(-1) : undefined;
249
+ if (last) {
250
+ if ((last === "on") !== change.fast)
251
+ throw new BridgeError(409, `Claude answered Fast mode ${last}. Open terminal to check.`);
252
+ verified = true;
253
+ }
254
+ }
255
+ }
256
+ let mode = await screenMode();
257
+ if ((change.plan !== undefined || change.permissionMode) && !mode)
258
+ throw new BridgeError(409, "Could not read Claude's permission mode from its screen. Open terminal to check.");
259
+ const started = mode ?? "default"; // Only used once a change needs the mode, and then the footer was read.
260
+ if (change.plan === true) {
261
+ if (started !== "plan") {
262
+ await slash("/plan");
263
+ mode = await changed(started, this.wait);
264
+ if (mode !== "plan")
265
+ throw new BridgeError(409, "Claude did not enter plan mode. Open terminal to check.");
266
+ }
267
+ }
268
+ else if (change.permissionMode || change.plan === false) {
269
+ const wanted = change.permissionMode ? CLAUDE_NAMES[change.permissionMode] : undefined;
270
+ const reached = (raw) => wanted ? raw === wanted : raw !== "plan";
271
+ // Shift+Tab steps through the modes Claude offers in this session; a
272
+ // lap back to the start means it does not offer the one asked for.
273
+ for (let presses = 0; !reached(mode); presses++) {
274
+ if (presses >= MAX_PRESSES || (presses > 0 && mode === started))
275
+ throw new BridgeError(422, "Claude doesn't offer that mode in this session.");
276
+ await validate();
277
+ // Herdr's name for the key (it sends ESC [ Z); shift-tab, backtab and btab are rejected.
278
+ await terminalProvider().sendKeys(target.server, target.pane, ["shift+tab"]);
279
+ mode = await changed(mode, this.wait);
280
+ }
281
+ }
282
+ const phone = mode ? CLAUDE_MODES[mode] : undefined;
283
+ // Only what the footer showed is reported; a fast-only change with an unreadable one says nothing of the mode.
284
+ return { ok: true, ...(phone && phone !== "plan" ? { permissionMode: phone } : {}), ...(phone ? { plan: phone === "plan" } : {}),
285
+ ...(change.fast !== undefined ? { fast: change.fast, verified: verified === true } : {}) };
286
+ }
287
+ }
@@ -0,0 +1,55 @@
1
+ import { z } from "zod";
2
+ /** The ElevenLabs voice talk mode speaks with. A new computer uses the
3
+ * built-in default; `phren bridge speech-voice set <id>` stores another in
4
+ * the Hook's own directory, next to the speech key, where install and update
5
+ * leave it alone. The phone may name a voice per request, which wins. */
6
+ /** River: relaxed, neutral and informative, ElevenLabs' premade voice. */
7
+ export declare const DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
8
+ /** The environment override from before the setting existed. It is read only
9
+ * when nothing is stored, and copied into the setting then. */
10
+ export declare const SPEECH_VOICE_ENV = "PHREN_SPEECH_VOICE";
11
+ /** An ElevenLabs voice id: letters and digits (20 today). */
12
+ export declare const voiceId: z.ZodString;
13
+ export declare function speechVoiceFile(): string;
14
+ export declare function readStoredVoice(file?: string): Promise<string | undefined>;
15
+ export declare function writeSpeechVoice(voice: string, file?: string): Promise<string>;
16
+ export declare function clearSpeechVoice(file?: string): Promise<void>;
17
+ /** The ElevenLabs model talk mode speaks with. It sits in the same
18
+ * `speech.json` as the voice (`phren bridge speech-model set <id>`), so
19
+ * install and update leave it alone too. Unset, it is v4 Turbo; speech.ts
20
+ * drops to Flash v2.5 on its own while the chosen model fails or is slow. */
21
+ export declare const DEFAULT_SPEECH_MODEL = "eleven_v4_turbo";
22
+ /** ElevenLabs' lowest-latency model: the fallback. */
23
+ export declare const FALLBACK_SPEECH_MODEL = "eleven_flash_v2_5";
24
+ /** An ElevenLabs model id, e.g. eleven_v4_turbo or eleven_flash_v2_5. */
25
+ export declare const speechModelId: z.ZodString;
26
+ export declare function readStoredModel(file?: string): Promise<string | undefined>;
27
+ export declare function writeSpeechModel(model: string, file?: string): Promise<string>;
28
+ export declare function clearSpeechModel(file?: string): Promise<void>;
29
+ /** The stored model, else v4 Turbo. Read on every reply, so a change needs
30
+ * no Hook restart. */
31
+ export declare function resolveSpeechModel(file?: string): Promise<{
32
+ model: string;
33
+ source: "setting" | "default";
34
+ }>;
35
+ export type SpeechVoiceSource = "request" | "setting" | "environment" | "default";
36
+ /** The voice to speak with: the request's own, the stored setting, the old
37
+ * environment override (copied into the setting on first use), else the
38
+ * default. */
39
+ export declare function resolveSpeechVoice(requested?: string, paths?: {
40
+ env?: NodeJS.ProcessEnv;
41
+ file?: string;
42
+ }): Promise<{
43
+ voice: string;
44
+ source: SpeechVoiceSource;
45
+ }>;
46
+ export interface SpeechVoiceChoice {
47
+ id: string;
48
+ name: string;
49
+ category?: string;
50
+ description?: string;
51
+ }
52
+ /** The voices this computer's ElevenLabs account can speak with, for the
53
+ * phone's picker: id, name and a short description, never the account's
54
+ * other details. */
55
+ export declare function listSpeechVoices(key: string, fetcher?: typeof fetch, signal?: AbortSignal): Promise<SpeechVoiceChoice[]>;
@@ -0,0 +1,132 @@
1
+ import { mkdir, readFile, rm } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { z } from "zod";
4
+ import { atomic, BridgeError, bridgeRoot } from "./protocol.js";
5
+ /** The ElevenLabs voice talk mode speaks with. A new computer uses the
6
+ * built-in default; `phren bridge speech-voice set <id>` stores another in
7
+ * the Hook's own directory, next to the speech key, where install and update
8
+ * leave it alone. The phone may name a voice per request, which wins. */
9
+ /** River: relaxed, neutral and informative, ElevenLabs' premade voice. */
10
+ export const DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
11
+ /** The environment override from before the setting existed. It is read only
12
+ * when nothing is stored, and copied into the setting then. */
13
+ export const SPEECH_VOICE_ENV = "PHREN_SPEECH_VOICE";
14
+ /** An ElevenLabs voice id: letters and digits (20 today). */
15
+ export const voiceId = z.string().trim().regex(/^[A-Za-z0-9]{10,40}$/, "An ElevenLabs voice id is 10 to 40 letters and digits.");
16
+ export function speechVoiceFile() {
17
+ return path.join(bridgeRoot(), "speech.json");
18
+ }
19
+ /** Everything `speech.json` holds; a write keeps the keys it doesn't touch. */
20
+ async function readSettings(file) {
21
+ try {
22
+ const parsed = JSON.parse(await readFile(file, "utf8"));
23
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
24
+ }
25
+ catch {
26
+ return {};
27
+ }
28
+ }
29
+ /** Sets or removes one key of `speech.json`; the file goes when it is empty. */
30
+ async function updateSettings(file, key, value) {
31
+ const settings = await readSettings(file);
32
+ if (value === undefined)
33
+ delete settings[key];
34
+ else
35
+ settings[key] = value;
36
+ if (!Object.keys(settings).length) {
37
+ await rm(file, { force: true });
38
+ return;
39
+ }
40
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
41
+ await atomic(file, JSON.stringify(settings) + "\n", 0o600);
42
+ }
43
+ export async function readStoredVoice(file = speechVoiceFile()) {
44
+ const parsed = voiceId.safeParse((await readSettings(file)).voice);
45
+ return parsed.success ? parsed.data : undefined;
46
+ }
47
+ export async function writeSpeechVoice(voice, file = speechVoiceFile()) {
48
+ const value = voiceId.parse(voice);
49
+ await updateSettings(file, "voice", value);
50
+ return value;
51
+ }
52
+ export async function clearSpeechVoice(file = speechVoiceFile()) {
53
+ await updateSettings(file, "voice", undefined);
54
+ }
55
+ /** The ElevenLabs model talk mode speaks with. It sits in the same
56
+ * `speech.json` as the voice (`phren bridge speech-model set <id>`), so
57
+ * install and update leave it alone too. Unset, it is v4 Turbo; speech.ts
58
+ * drops to Flash v2.5 on its own while the chosen model fails or is slow. */
59
+ export const DEFAULT_SPEECH_MODEL = "eleven_v4_turbo";
60
+ /** ElevenLabs' lowest-latency model: the fallback. */
61
+ export const FALLBACK_SPEECH_MODEL = "eleven_flash_v2_5";
62
+ /** An ElevenLabs model id, e.g. eleven_v4_turbo or eleven_flash_v2_5. */
63
+ export const speechModelId = z.string().trim().regex(/^[a-z0-9][a-z0-9_]{2,63}$/, "An ElevenLabs model id is 3 to 64 lowercase letters, digits and underscores, e.g. eleven_v4_turbo.");
64
+ export async function readStoredModel(file = speechVoiceFile()) {
65
+ const parsed = speechModelId.safeParse((await readSettings(file)).model);
66
+ return parsed.success ? parsed.data : undefined;
67
+ }
68
+ export async function writeSpeechModel(model, file = speechVoiceFile()) {
69
+ const value = speechModelId.parse(model);
70
+ await updateSettings(file, "model", value);
71
+ return value;
72
+ }
73
+ export async function clearSpeechModel(file = speechVoiceFile()) {
74
+ await updateSettings(file, "model", undefined);
75
+ }
76
+ /** The stored model, else v4 Turbo. Read on every reply, so a change needs
77
+ * no Hook restart. */
78
+ export async function resolveSpeechModel(file = speechVoiceFile()) {
79
+ const stored = await readStoredModel(file);
80
+ return stored ? { model: stored, source: "setting" } : { model: DEFAULT_SPEECH_MODEL, source: "default" };
81
+ }
82
+ /** The voice to speak with: the request's own, the stored setting, the old
83
+ * environment override (copied into the setting on first use), else the
84
+ * default. */
85
+ export async function resolveSpeechVoice(requested, paths = {}) {
86
+ if (requested)
87
+ return { voice: voiceId.parse(requested), source: "request" };
88
+ const file = paths.file ?? speechVoiceFile();
89
+ const stored = await readStoredVoice(file);
90
+ if (stored)
91
+ return { voice: stored, source: "setting" };
92
+ const legacy = voiceId.safeParse((paths.env ?? process.env)[SPEECH_VOICE_ENV]);
93
+ if (legacy.success) {
94
+ await writeSpeechVoice(legacy.data, file).catch(() => { });
95
+ return { voice: legacy.data, source: "environment" };
96
+ }
97
+ return { voice: DEFAULT_SPEECH_VOICE, source: "default" };
98
+ }
99
+ /** The voices this computer's ElevenLabs account can speak with, for the
100
+ * phone's picker: id, name and a short description, never the account's
101
+ * other details. */
102
+ export async function listSpeechVoices(key, fetcher = fetch, signal) {
103
+ let upstream;
104
+ try {
105
+ upstream = await fetcher("https://api.elevenlabs.io/v1/voices", { headers: { "xi-api-key": key }, signal });
106
+ }
107
+ catch {
108
+ throw new BridgeError(502, "Couldn't reach ElevenLabs from this computer.", { code: "speech-unreachable" });
109
+ }
110
+ if (upstream.status === 401 || upstream.status === 403)
111
+ throw new BridgeError(502, "ElevenLabs refused this computer's key.", { code: "speech-rejected" });
112
+ if (!upstream.ok)
113
+ throw new BridgeError(502, `ElevenLabs failed (HTTP ${upstream.status}).`, { code: "speech-failed" });
114
+ let body;
115
+ try {
116
+ body = (await upstream.json());
117
+ }
118
+ catch {
119
+ throw new BridgeError(502, "ElevenLabs sent an unreadable reply.", { code: "speech-failed" });
120
+ }
121
+ const text = (value, max) => typeof value === "string" && value.trim() ? value.replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, max) : undefined;
122
+ const voices = [];
123
+ for (const raw of Array.isArray(body.voices) ? body.voices.slice(0, 500) : []) {
124
+ const item = raw;
125
+ const id = voiceId.safeParse(item.voice_id), name = text(item.name, 120);
126
+ if (!id.success || !name)
127
+ continue;
128
+ const category = text(item.category, 40), description = text(item.description, 240);
129
+ voices.push({ id: id.data, name, ...(category ? { category } : {}), ...(description ? { description } : {}) });
130
+ }
131
+ return voices.sort((a, b) => a.name.localeCompare(b.name));
132
+ }
@@ -1,21 +1,64 @@
1
1
  import type { ServerResponse } from "node:http";
2
2
  import { z } from "zod";
3
3
  import { BridgeError, type Json } from "./protocol.js";
4
+ export { DEFAULT_SPEECH_MODEL, DEFAULT_SPEECH_VOICE, FALLBACK_SPEECH_MODEL } from "./speech-voice.js";
4
5
  /** Spoken replies for the phone's talk mode. The phone sends a sentence; the
5
6
  * Hook voices it with ElevenLabs and streams the audio back. The API key is
6
7
  * read on this computer, used only in the request to ElevenLabs, and never
7
8
  * appears in a response, including errors. */
8
- /** Raw signed 16-bit little-endian mono PCM, so the phone can queue it
9
- * straight into its audio engine without decoding. */
9
+ /** What a phone that names no `formats` gets, as every phone did before
10
+ * `speechFormats`: raw signed 16-bit little-endian mono PCM at 24 kHz, which
11
+ * it queues straight into its audio engine without decoding. */
10
12
  export declare const SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
11
- /** ElevenLabs' lowest-latency model. */
12
- export declare const SPEECH_MODEL = "eleven_flash_v2_5";
13
- /** River: relaxed, neutral and informative. PHREN_SPEECH_VOICE overrides it. */
14
- export declare const DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
13
+ /** ElevenLabs output formats the Hook can serve, best first. Each account
14
+ * plan allows some of them (Creator refuses pcm_44100, which is Pro and
15
+ * above); the Hook learns which from ElevenLabs' refusal rather than a
16
+ * hard-coded plan table. pcm_24000 works on every plan and every phone. */
17
+ export declare const SPEECH_FORMATS: readonly ["pcm_44100", "mp3_44100_192", "pcm_24000"];
18
+ export type SpeechFormat = typeof SPEECH_FORMATS[number];
19
+ /** How each format is described to the phone: `audioFormat` in the JSON reply
20
+ * and `X-Phren-Audio` on the streamed one, plus the sample rate on its own. */
21
+ export declare const SPEECH_FORMAT_INFO: Record<SpeechFormat, {
22
+ audio: string;
23
+ sampleRate: number;
24
+ contentType: string;
25
+ }>;
26
+ /** Talk mode waits for the whole sentence on the timestamped path, so a model
27
+ * whose recent replies took longer than this to start playing is set aside
28
+ * for FALLBACK_HOLD_MS. Measured 2026-09-28 on a 95-character reply with the
29
+ * owner's voice: v4 Turbo ~200-400 ms to first streamed byte and ~1.1 s for
30
+ * the timestamped reply; Flash v2.5 ~180-460 ms and ~0.4 s. 1.5 s leaves v4
31
+ * Turbo headroom on a normal day and catches a slow one. */
32
+ export declare const SPEECH_SLOW_MS = 1500;
33
+ /** How long a failing or slow model, or a refused format, is set aside. */
34
+ export declare const FALLBACK_HOLD_MS: number;
15
35
  export declare const speechRequest: z.ZodObject<{
16
36
  text: z.ZodString;
17
37
  timestamps: z.ZodOptional<z.ZodBoolean>;
38
+ voice: z.ZodOptional<z.ZodString>;
39
+ formats: z.ZodPreprocess<z.ZodOptional<z.ZodArray<z.ZodEnum<{
40
+ mp3_44100_192: "mp3_44100_192";
41
+ pcm_24000: "pcm_24000";
42
+ pcm_44100: "pcm_44100";
43
+ }>>>, unknown>;
18
44
  }, z.core.$strip>;
45
+ /** What the Hook learned about this account: formats its plan refused and
46
+ * models set aside for failing or being slow, each until a time, and the
47
+ * recent start-of-audio times per model. One per Hook process. */
48
+ export declare class SpeechState {
49
+ private readonly now;
50
+ private readonly refused;
51
+ private readonly benched;
52
+ private readonly latency;
53
+ constructor(now?: () => number);
54
+ formatAllowed(format: SpeechFormat): boolean;
55
+ refuseFormat(format: SpeechFormat): void;
56
+ benchedReason(model: string): "failed" | "slow" | undefined;
57
+ bench(model: string, reason: "failed" | "slow"): void;
58
+ /** Records how long a reply took to start; benches the model when the median
59
+ * of its last three is over SPEECH_SLOW_MS. */
60
+ recordLatency(model: string, ms: number): void;
61
+ }
19
62
  /** When each character of the voiced text starts and ends, in seconds from
20
63
  * the start of the audio. */
21
64
  export interface SpeechAlignment {
@@ -28,6 +71,18 @@ export interface SpeechOptions {
28
71
  /** Resolves the ElevenLabs key; defaults to ELEVENLABS_API_KEY, then the stored key (speech-key.ts). */
29
72
  key?: () => Promise<string | undefined>;
30
73
  voice?: string;
74
+ /** Formats the phone plays, from the request; pcm_24000 always. */
75
+ formats?: readonly string[];
76
+ /** Defaults to this computer's setting (speech-voice.ts). */
77
+ model?: string;
78
+ /** Defaults to the Hook's own. */
79
+ state?: SpeechState;
80
+ now?: () => number;
81
+ }
82
+ /** What was voiced: the model and format actually used. */
83
+ export interface SpeechResult {
84
+ model: string;
85
+ format: SpeechFormat;
31
86
  }
32
87
  /** A fixed message per ElevenLabs failure: its own response text is never
33
88
  * passed on. */
@@ -39,9 +94,11 @@ export declare function speechError(upstream: Response): Promise<BridgeError>;
39
94
  * nothing speakable is left. */
40
95
  export declare function speakableText(text: string): string;
41
96
  /** Starts ElevenLabs' streaming synthesis and returns its audio body. */
42
- export declare function synthesizeSpeech(text: string, signal: AbortSignal, options?: SpeechOptions): Promise<ReadableStream<Uint8Array>>;
97
+ export declare function synthesizeSpeech(text: string, signal: AbortSignal, options?: SpeechOptions): Promise<SpeechResult & {
98
+ body: ReadableStream<Uint8Array>;
99
+ }>;
43
100
  /** Voices the text in one piece with ElevenLabs' character alignment. */
44
- export declare function synthesizeTimedSpeech(text: string, signal: AbortSignal, options?: SpeechOptions): Promise<{
101
+ export declare function synthesizeTimedSpeech(text: string, signal: AbortSignal, options?: SpeechOptions): Promise<SpeechResult & {
45
102
  audio: string;
46
103
  alignment: SpeechAlignment | null;
47
104
  }>;
@@ -52,9 +109,11 @@ export declare function alignmentOf(raw: {
52
109
  character_end_times_seconds?: unknown;
53
110
  } | null | undefined): SpeechAlignment | null;
54
111
  /** POST /v1/speech: writes the audio to the phone as ElevenLabs produces it.
55
- * With `timestamps`, answers JSON instead: `{ audio, audioFormat, alignment }`,
56
- * the audio base64 in the same PCM format and the alignment null when
57
- * ElevenLabs sent none.
112
+ * With `timestamps`, answers JSON instead: `{ audio, audioFormat, sampleRate,
113
+ * format, model, alignment }`, the audio base64 in the format served and the
114
+ * alignment null when ElevenLabs sent none. The streamed reply names its
115
+ * format in `X-Phren-Audio` and `X-Phren-Audio-Rate`. A phone that sends no
116
+ * `formats` always gets pcm_24000.
58
117
  * Failures before the first byte are thrown for the route's JSON error; a
59
118
  * failure mid-stream cuts the response off, which the phone treats as an
60
119
  * error. The phone hanging up cancels the ElevenLabs request. */