@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
@@ -0,0 +1,295 @@
1
+ import { execFile } from "node:child_process";
2
+ import path from "node:path";
3
+ import { promisify } from "node:util";
4
+ import { intervalFromEnv } from "./limits.js";
5
+ import { freePort, listPaneServers, newPassword, openPaneClient, PromptNotSent, readPaneServer, registerPaneServer, removePaneServer, } from "./opencode-pane-server.js";
6
+ import { bridgeRoot } from "./protocol.js";
7
+ import { terminalProvider } from "./terminal.js";
8
+ /**
9
+ * OpenCode panes the Hook starts serve their own HTTP API: the TUI runs as
10
+ * `OPENCODE_SERVER_PASSWORD=<pw> opencode --port <port>`, and the Hook drives
11
+ * the session the TUI shows over that API instead of typing into it. The pane
12
+ * stays the owner's live view. A registry entry per pane
13
+ * (`<bridge>/opencode-panes/`, 0600 files in a 0700 folder) holds the port,
14
+ * password, process id and directory; a pane with no entry (one the owner
15
+ * started by hand) keeps the typed path.
16
+ */
17
+ const exec = promisify(execFile);
18
+ /** Set in a served pane's environment: the port its TUI listens on. The
19
+ * OpenCode plugin leaves permission asks to the Hook's HTTP client when its
20
+ * own process was started with this port. */
21
+ export const PANE_PORT_ENV = "PHREN_OPENCODE_PORT";
22
+ const PASSWORD_ENV = "OPENCODE_SERVER_PASSWORD";
23
+ /** How long a served TUI may take to answer its first request after Herdr
24
+ * reports the agent ready. */
25
+ const READY_MS = 20_000;
26
+ /** The terminal reports the agent started once its process runs, so a
27
+ * process carrying the port shows up at once; with none (a wrapper that
28
+ * dropped the flag), the pane keeps the typed path without a long wait. */
29
+ const PID_MS = intervalFromEnv("PHREN_OPENCODE_PID_MS", 2_000);
30
+ const BRIEF_CONFIRM_MS = 10_000;
31
+ export function paneServersDir() { return path.join(bridgeRoot(), "opencode-panes"); }
32
+ /** The live server entry for a pane, if the Hook started its OpenCode. */
33
+ export function servedPane(server, pane) {
34
+ return readPaneServer(paneServersDir(), server, pane);
35
+ }
36
+ export function servedPanes() { return listPaneServers(paneServersDir()); }
37
+ export function forgetServedPane(server, pane) { removePaneServer(paneServersDir(), server, pane); }
38
+ let clientFactory = entry => openPaneClient(entry);
39
+ export function paneClient(entry) { return clientFactory(entry); }
40
+ /** For tests: build clients against a fake server; returns the restore. */
41
+ export function setPaneClientFactory(factory) {
42
+ const previous = clientFactory;
43
+ clientFactory = factory;
44
+ return () => { clientFactory = previous; };
45
+ }
46
+ /** The port, password, extra arguments and pane variables for one launch. */
47
+ export async function prepareServedLaunch() {
48
+ const port = await freePort(), password = newPassword();
49
+ return { port, password, args: ["--port", String(port)], env: { [PASSWORD_ENV]: password, [PANE_PORT_ENV]: String(port) } };
50
+ }
51
+ /** `--port N` or `--port=N` in a command line. */
52
+ export function listensOn(command, port) {
53
+ return new RegExp(`(?:^|\\s)--port(?:\\s+|=)${port}(?:\\s|$)`).test(command) && /opencode/.test(command);
54
+ }
55
+ async function processTable() {
56
+ const { stdout } = await exec("ps", ["-Aww", "-o", "pid=,command="], { timeout: 3_000, maxBuffer: 8_388_608 });
57
+ return String(stdout).split("\n").flatMap(line => {
58
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
59
+ return match ? [{ pid: Number(match[1]), command: match[2] }] : [];
60
+ });
61
+ }
62
+ /** The OpenCode process serving `port` in the pane: a foreground process of
63
+ * the pane whose command line carries that port, else any process that does
64
+ * (a launcher shim can hold the pane's foreground). The newest wins, which is
65
+ * the real binary under a shim. */
66
+ export async function servingPid(server, pane, port, table = processTable) {
67
+ const foreground = await terminalProvider().processes(server, pane).then(value => value.foregroundPids, () => []);
68
+ const rows = (await table().catch(() => [])).filter(row => row.pid > 0 && listensOn(row.command, port));
69
+ const own = rows.filter(row => foreground.includes(row.pid));
70
+ const pool = own.length ? own : rows;
71
+ return pool.length ? Math.max(...pool.map(row => row.pid)) : undefined;
72
+ }
73
+ /**
74
+ * Registers a pane whose OpenCode the Hook just started with `launch`, once
75
+ * its server answers. Undefined when it never did: the pane then keeps the
76
+ * typed path, exactly like one started by hand.
77
+ */
78
+ export async function registerServedPane(server, pane, directory, launch, options = {}) {
79
+ const started = Date.now(), deadline = started + (options.readyMs ?? READY_MS);
80
+ let pid;
81
+ for (;;) {
82
+ pid ??= await servingPid(server, pane, launch.port, options.table).catch(() => undefined);
83
+ if (!pid && Date.now() - started >= Math.min(PID_MS, options.readyMs ?? PID_MS))
84
+ return undefined;
85
+ const entry = pid ? { server, pane, port: launch.port, password: launch.password, pid, directory,
86
+ createdAt: new Date().toISOString(), ...(options.defaults && Object.keys(options.defaults).length ? { defaults: options.defaults } : {}) } : undefined;
87
+ if (entry && await paneClient(entry).ready()) {
88
+ registerPaneServer(paneServersDir(), entry);
89
+ return entry;
90
+ }
91
+ if (Date.now() >= deadline)
92
+ return undefined;
93
+ await new Promise(resolve => setTimeout(resolve, 250));
94
+ }
95
+ }
96
+ /** The session the Hook last created and showed in each served pane, by
97
+ * pane and process. */
98
+ const shownSessions = new Map();
99
+ /** Whether the pane draws the start of `text`: a sent prompt's user turn. */
100
+ async function paneShows(server, pane, text) {
101
+ const needle = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, 24);
102
+ if (!needle)
103
+ return true;
104
+ const screen = await terminalProvider().readScreen(server, pane, { scope: "pane", source: "visible", lines: 200, stripAnsi: true }).catch(() => "");
105
+ return screen.replace(/\s+/g, " ").includes(needle);
106
+ }
107
+ /** How long to keep moving a just-started TUI onto a new session. */
108
+ const SHOW_MS = 10_000;
109
+ /**
110
+ * Moves the TUI onto `session`, whose first turn is `text`. A TUI that has
111
+ * only just started answers HTTP before it listens for its own navigation
112
+ * events and drops the first request (seen live on 1.18.31), so the request
113
+ * is repeated until the pane draws that turn. False when it never did: the
114
+ * conversation is still real, only not on screen.
115
+ */
116
+ export async function showSession(entry, client, session, text, options = {}) {
117
+ const shows = options.shows ?? (value => paneShows(entry.server, entry.pane, value));
118
+ const deadline = Date.now() + (options.timeoutMs ?? SHOW_MS);
119
+ for (;;) {
120
+ await client.selectSession(session).catch(() => { });
121
+ await new Promise(resolve => setTimeout(resolve, options.intervalMs ?? 500));
122
+ if (await shows(text))
123
+ return true;
124
+ if (Date.now() >= deadline)
125
+ return false;
126
+ }
127
+ }
128
+ /**
129
+ * Sends `text` into the session a served TUI shows. `session` is the
130
+ * conversation the phone means and must be a root session of this server; with
131
+ * none (a TUI still on its home screen) a new session is created, and once the
132
+ * prompt is in, the TUI is moved onto it so the owner sees it there.
133
+ * `sent: false` means nothing reached OpenCode, so the caller may type it.
134
+ */
135
+ export async function sendServedPrompt(entry, session, text, options = {}) {
136
+ const client = paneClient(entry);
137
+ const shownKey = `${paneKey(entry)}\u0000${entry.pid}`;
138
+ // A pane whose conversation the terminal cannot name yet (no Herdr
139
+ // integration, no plugin record) keeps the session the Hook last showed
140
+ // there, rather than starting a new one for every message.
141
+ const shown = session ? undefined : shownSessions.get(shownKey);
142
+ let id = session ?? shown;
143
+ try {
144
+ if (id) {
145
+ const known = await client.session(id);
146
+ if (!known || known.parentID) {
147
+ if (!shown)
148
+ return { sent: false, reason: "This conversation is not a root session of the pane's OpenCode." };
149
+ shownSessions.delete(shownKey);
150
+ id = (await client.createSession()).id;
151
+ }
152
+ }
153
+ else
154
+ id = (await client.createSession()).id;
155
+ }
156
+ catch (error) {
157
+ return { sent: false, reason: error.message };
158
+ }
159
+ const fresh = !session && id !== shown;
160
+ if (!session) {
161
+ shownSessions.set(shownKey, id);
162
+ while (shownSessions.size > 64)
163
+ shownSessions.delete(shownSessions.keys().next().value);
164
+ }
165
+ // A continuing conversation keeps the agent and model of its last turn;
166
+ // a new one takes what the TUI was started with.
167
+ const defaults = entry.defaults ?? {};
168
+ const settings = !fresh ? { inherit: true, ...options }
169
+ : { ...(defaults.agent ? { agent: defaults.agent } : {}), ...(defaults.model ? { model: defaults.model } : {}),
170
+ ...(defaults.variant ? { variant: defaults.variant } : {}), ...options };
171
+ let delivered;
172
+ try {
173
+ delivered = (await client.prompt(id, text, settings)).delivered;
174
+ }
175
+ catch (error) {
176
+ if (error instanceof PromptNotSent)
177
+ return { sent: false, reason: error.message };
178
+ delivered = false;
179
+ }
180
+ if (fresh)
181
+ await showSession(entry, client, id, text).catch(() => false);
182
+ return { sent: true, delivered, session: id };
183
+ }
184
+ /** A launch brief sent over HTTP: into a new session the TUI shows. */
185
+ export async function sendServedBrief(entry, text, options = {}) {
186
+ return sendServedPrompt(entry, undefined, text, { timeoutMs: BRIEF_CONFIRM_MS, ...options });
187
+ }
188
+ /** The root of a (possibly subagent) session: the conversation the pane shows. */
189
+ export async function rootSession(client, session) {
190
+ let current = session;
191
+ for (let depth = 0; depth < 8; depth++) {
192
+ const info = await client.session(current).catch(() => undefined);
193
+ if (!info?.parentID)
194
+ return current;
195
+ current = info.parentID;
196
+ }
197
+ return current;
198
+ }
199
+ const ASK_EVENTS = new Set(["permission.asked", "permission.replied", "permission.updated", "question.asked", "question.replied", "question.rejected"]);
200
+ const MAX_BACKOFF_MS = 30_000;
201
+ export const paneKey = (entry) => `${entry.server}\u0000${entry.pane}`;
202
+ /**
203
+ * One event subscription per served pane. On every (re)connect and on each
204
+ * permission or question event it lists the pane's pending asks and hands the
205
+ * whole set to the sink, so an ask answered in the TUI disappears too. A
206
+ * dropped stream reconnects with backoff; `tick` stops panes whose entry is
207
+ * gone (the process exited) and starts new ones.
208
+ */
209
+ export class PaneServerWatcher {
210
+ sink;
211
+ list;
212
+ minBackoffMs;
213
+ live = new Map();
214
+ closed = false;
215
+ constructor(sink, list = servedPanes, minBackoffMs = 1_000) {
216
+ this.sink = sink;
217
+ this.list = list;
218
+ this.minBackoffMs = minBackoffMs;
219
+ }
220
+ tick() {
221
+ if (this.closed)
222
+ return;
223
+ const current = new Map(this.list().map(entry => [paneKey(entry), entry]));
224
+ for (const [key, running] of this.live) {
225
+ const entry = current.get(key);
226
+ // A live pane is listed again each tick, so an ask it still has keeps
227
+ // its card however long it waits with no event.
228
+ if (entry && entry.pid === running.entry.pid && entry.port === running.entry.port) {
229
+ void running.refresh?.().catch(() => { });
230
+ continue;
231
+ }
232
+ running.abort.abort();
233
+ this.live.delete(key);
234
+ this.sink.gone(key);
235
+ }
236
+ for (const [key, entry] of current) {
237
+ if (this.live.has(key))
238
+ continue;
239
+ const abort = new AbortController();
240
+ this.live.set(key, { entry, abort });
241
+ void this.follow(entry, abort.signal);
242
+ }
243
+ }
244
+ watching() { return [...this.live.keys()]; }
245
+ close() {
246
+ this.closed = true;
247
+ for (const running of this.live.values())
248
+ running.abort.abort();
249
+ this.live.clear();
250
+ }
251
+ async follow(entry, signal) {
252
+ const client = paneClient(entry);
253
+ let backoff = this.minBackoffMs;
254
+ let refreshing, again = false;
255
+ const refresh = () => {
256
+ if (refreshing) {
257
+ again = true;
258
+ return refreshing;
259
+ }
260
+ refreshing = (async () => {
261
+ do {
262
+ again = false;
263
+ const [permissions, questions] = await Promise.all([client.permissions(), client.questions()]);
264
+ if (!signal.aborted)
265
+ await this.sink.asks(entry, client, { permissions, questions });
266
+ } while (again && !signal.aborted);
267
+ })().finally(() => { refreshing = undefined; });
268
+ return refreshing;
269
+ };
270
+ const running = this.live.get(paneKey(entry));
271
+ if (running?.entry === entry)
272
+ running.refresh = refresh;
273
+ while (!signal.aborted) {
274
+ try {
275
+ // The list is read once the stream is open (its first event), so an
276
+ // ask raised in between is never missed.
277
+ let first = true;
278
+ for await (const event of client.events(signal)) {
279
+ if (signal.aborted)
280
+ break;
281
+ if (first)
282
+ backoff = this.minBackoffMs;
283
+ if (first || ASK_EVENTS.has(event.type))
284
+ await refresh().catch(() => { });
285
+ first = false;
286
+ }
287
+ }
288
+ catch { /* the stream dropped or the server is not answering yet */ }
289
+ if (signal.aborted)
290
+ break;
291
+ await new Promise(resolve => { const timer = setTimeout(resolve, backoff); timer.unref?.(); signal.addEventListener("abort", () => { clearTimeout(timer); resolve(undefined); }, { once: true }); });
292
+ backoff = Math.min(MAX_BACKOFF_MS, backoff * 2);
293
+ }
294
+ }
295
+ }
@@ -0,0 +1,8 @@
1
+ import { type AccountRef } from "./claude-accounts.js";
2
+ export declare const paneAccountKey: (server: string, pane: unknown) => string;
3
+ /** The account a pane was launched with (`default` or a slug). */
4
+ export declare function recordPaneAccount(paneKey: string, accountId: string, terminal?: string): void;
5
+ /** A Claude transcript path the pane's session is known to use. */
6
+ export declare function notePaneTranscript(paneKey: string, file: unknown, terminal?: string): void;
7
+ /** The pane's account: from its transcript when known, else the recorded launch. */
8
+ export declare function paneAccount(paneKey: string, terminal?: string): AccountRef | undefined;
@@ -0,0 +1,46 @@
1
+ // Which Claude account a pane runs under. Known from the launch (recorded by
2
+ // recordPaneAccount), from the hook payload's transcript_path, or from the
3
+ // transcript file the pane's process holds open; the file's home decides.
4
+ // In memory only: a restarted Hook relearns it from the next poll or hook.
5
+ import path from "node:path";
6
+ import { claudeAccountRef, claudeHome, claudeHomeOfPath } from "./claude-accounts.js";
7
+ const known = new Map();
8
+ const MAX_PANES = 512;
9
+ export const paneAccountKey = (server, pane) => `${server}\0${String(pane)}`;
10
+ function entry(paneKey, terminal) {
11
+ let current = known.get(paneKey);
12
+ if (current && terminal && current.terminal && current.terminal !== terminal) {
13
+ known.delete(paneKey);
14
+ current = undefined;
15
+ }
16
+ if (!current) {
17
+ while (known.size >= MAX_PANES)
18
+ known.delete(known.keys().next().value);
19
+ current = {};
20
+ known.set(paneKey, current);
21
+ }
22
+ if (terminal)
23
+ current.terminal = terminal;
24
+ return current;
25
+ }
26
+ /** The account a pane was launched with (`default` or a slug). */
27
+ export function recordPaneAccount(paneKey, accountId, terminal) {
28
+ entry(paneKey, terminal).launched = accountId;
29
+ }
30
+ /** A Claude transcript path the pane's session is known to use. */
31
+ export function notePaneTranscript(paneKey, file, terminal) {
32
+ if (typeof file !== "string" || !path.isAbsolute(file) || file.length > 4096)
33
+ return;
34
+ const home = claudeHomeOfPath(file);
35
+ if (home)
36
+ entry(paneKey, terminal).fromFile = home.id;
37
+ }
38
+ /** The pane's account: from its transcript when known, else the recorded launch. */
39
+ export function paneAccount(paneKey, terminal) {
40
+ const current = known.get(paneKey);
41
+ if (!current || (terminal && current.terminal && current.terminal !== terminal))
42
+ return undefined;
43
+ const id = current.fromFile ?? current.launched;
44
+ const home = id ? claudeHome(id) : undefined;
45
+ return home ? claudeAccountRef(home) : undefined;
46
+ }
@@ -0,0 +1,5 @@
1
+ /** Only agent_not_ready guarantees that no text reached the terminal. A
2
+ * freshly dispatched agent can report its session before Herdr registers it
3
+ * as active. Revalidate that exact target before every retry, and never
4
+ * retry a timeout, lost reply, or other potentially delivered write. */
5
+ export declare function promptWithStartupRetry<T>(send: () => Promise<T>, revalidate: () => Promise<void>, waitMs?: number): Promise<T>;
@@ -0,0 +1,24 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import { agentNotReady } from "./terminal.js";
3
+ /** Only agent_not_ready guarantees that no text reached the terminal. A
4
+ * freshly dispatched agent can report its session before Herdr registers it
5
+ * as active. Revalidate that exact target before every retry, and never
6
+ * retry a timeout, lost reply, or other potentially delivered write. */
7
+ export async function promptWithStartupRetry(send, revalidate, waitMs = 20_000) {
8
+ const deadline = Date.now() + waitMs;
9
+ for (;;) {
10
+ try {
11
+ return await send();
12
+ }
13
+ catch (error) {
14
+ if (!agentNotReady(error) || Date.now() >= deadline)
15
+ throw error;
16
+ await sleep(Math.min(500, deadline - Date.now()));
17
+ if (Date.now() >= deadline)
18
+ throw error;
19
+ await revalidate();
20
+ if (Date.now() >= deadline)
21
+ throw error;
22
+ }
23
+ }
24
+ }
@@ -76,3 +76,8 @@ export declare function atomic(file: string, value: unknown, mode?: number): Pro
76
76
  /** {@link atomic}, first creating the file's directory (0700 where it is new). */
77
77
  export declare function atomicInPrivateDir(file: string, value: unknown, mode?: number): Promise<void>;
78
78
  export declare function targetFromURL(url: URL): Target;
79
+ /** The reasoning efforts a launch or a dispatch may ask a harness for. */
80
+ export declare const launchEfforts: readonly ["minimal", "low", "medium", "high", "xhigh", "max"];
81
+ /** The permission modes a worker may start in, in the phone's words (T3's). */
82
+ export declare const PERMISSION_MODES: readonly ["supervised", "auto-edits", "auto", "full-access"];
83
+ export type PermissionMode = (typeof PERMISSION_MODES)[number];
@@ -96,3 +96,7 @@ export async function atomicInPrivateDir(file, value, mode) {
96
96
  export function targetFromURL(url) {
97
97
  return targetSchema.parse(Object.fromEntries(["server", "workspace", "tab", "pane", "source", "session"].map(k => [k, url.searchParams.get(k)])));
98
98
  }
99
+ /** The reasoning efforts a launch or a dispatch may ask a harness for. */
100
+ export const launchEfforts = ["minimal", "low", "medium", "high", "xhigh", "max"];
101
+ /** The permission modes a worker may start in, in the phone's words (T3's). */
102
+ export const PERMISSION_MODES = ["supervised", "auto-edits", "auto", "full-access"];
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { type RequestKind } from "./approval-summary.js";
2
3
  /** A phone registered through the phren push relay: the relay knows where to
3
4
  * deliver, and `key` (32 bytes, base64url) encrypts what the notification says
4
5
  * so only the phone reads it. The phone made the key and sent it over SSH. */
@@ -36,10 +37,10 @@ export interface ApprovalPush {
36
37
  provider: string;
37
38
  question: boolean;
38
39
  expiresAt: string;
39
- /** What the request is, when the provider names it (an opencode permission
40
- * ask): shown in the alert so the phone can answer without opening Phren. */
41
- title?: string;
42
- message?: string;
40
+ project?: string;
41
+ computer?: string;
42
+ request?: string;
43
+ requestKind?: RequestKind;
43
44
  }
44
45
  export interface FanoutBlockedPush {
45
46
  job: string;
@@ -4,6 +4,7 @@ import { connect } from "node:http2";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
6
6
  import { atomic, bridgeRoot } from "./protocol.js";
7
+ import { approvalTitle, shortApproval } from "./approval-summary.js";
7
8
  /** A phone registered through the phren push relay: the relay knows where to
8
9
  * deliver, and `key` (32 bytes, base64url) encrypts what the notification says
9
10
  * so only the phone reads it. The phone made the key and sent it over SSH. */
@@ -32,15 +33,16 @@ export function scheduleCollapseId(kind, runId) {
32
33
  return `${runId.slice(0, 63 - kind.length)}-${kind}`;
33
34
  }
34
35
  export function approvalPushPayload(value, host) {
35
- const label = value.provider === "claude" ? "Claude" : value.provider === "codex" ? "Codex" : value.provider === "opencode" ? "opencode" : "Your agent";
36
+ const request = shortApproval(value.request ?? "Open Phren to review the request.") || "Open Phren to review the request.";
36
37
  return {
37
38
  aps: {
38
- alert: { title: value.title ?? (value.question ? `${label} has a question` : `${label} needs approval`),
39
- body: value.message ?? "Open Phren to review the request." },
39
+ alert: { title: approvalTitle(value.provider, value.project, value.computer), body: request },
40
40
  sound: "default", category: value.question ? "PHREN_AGENT_QUESTION" : "PHREN_AGENT_APPROVAL",
41
41
  "interruption-level": "time-sensitive",
42
42
  },
43
- phren: { version: 1, binding: value.binding, expiresAt: value.expiresAt, ...(host ? { host } : {}) },
43
+ phren: { version: 1, binding: value.binding, expiresAt: value.expiresAt, ...(host ? { host } : {}),
44
+ agent: value.provider, ...(value.project ? { project: value.project } : {}), ...(value.computer ? { computer: value.computer } : {}),
45
+ request, requestKind: value.requestKind ?? (value.question ? "question" : "other") },
44
46
  };
45
47
  }
46
48
  export function fanoutBlockedPushPayload(value) {
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { type Json, type Target } from "./protocol.js";
3
+ import type { AppServerRequestId, PendingServerRequest } from "./codex-app-server.js";
4
+ import type { CodexServerEntry } from "./codex-servers.js";
3
5
  declare const question: z.ZodObject<{
4
6
  title: z.ZodString;
5
7
  options: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
@@ -16,25 +18,58 @@ export declare function deliveredQuestion(raw: Json): {
16
18
  questions: Question[];
17
19
  } | undefined;
18
20
  export declare function questionReply(questions: Question[], answers: unknown): string;
21
+ /** The same answers as Codex's own TUI sends them into the running turn. */
22
+ export declare function asyncQuestionReply(id: string, questions: Question[], answers: unknown): string;
19
23
  interface PendingQuestion {
20
24
  id: string;
21
25
  questions: Question[];
22
26
  }
23
27
  export declare function pendingAsyncQuestions(file: string, targetID?: string): Promise<PendingQuestion[]>;
24
28
  export declare function pendingAsyncQuestion(file: string, id: string): Promise<Question[]>;
29
+ /** The Hook's own Codex app-servers (codex-servers.ts), as far as questions go. */
30
+ export interface ServedCodex {
31
+ forTarget(target: Target): CodexServerEntry | undefined;
32
+ steer(entry: CodexServerEntry, text: string, extra?: Json[]): Promise<{
33
+ turnId: string;
34
+ }>;
35
+ questions(entry: CodexServerEntry): PendingServerRequest[];
36
+ answerQuestion(entry: CodexServerEntry, requestId: AppServerRequestId, result: Json): boolean;
37
+ }
38
+ /** A question parked on the app-server as the phone shows it, and the
39
+ * server's answer for the phone's choices. */
40
+ interface ServerQuestion {
41
+ questions: Question[];
42
+ result(values: string[]): Json;
43
+ attachments: boolean;
44
+ }
45
+ /** Files the phone attached to an answer, named the way the phone names them
46
+ * under a chat message it sends with attachments. */
47
+ export declare const attachedFiles: (paths: string[]) => string;
48
+ /** The phone's attachments for an answer: at most eight of this conversation's uploads. */
49
+ export declare function answerAttachments(session: string, data: Json): Promise<string[]>;
50
+ /** `item/tool/requestUserInput` (the synchronous tool) and a form MCP
51
+ * elicitation whose fields are all single values. Secret inputs, URL
52
+ * elicitations and multi-select fields stay in the pane. */
53
+ export declare function serverQuestion(request: PendingServerRequest): ServerQuestion | undefined;
25
54
  export declare class CodexQuestions {
26
55
  private readonly configured?;
56
+ private readonly served?;
27
57
  private snapshots;
28
58
  private failedSnapshots;
29
59
  private inboxAvailable;
30
60
  /** Feature discovery must never delay permission/status frames. */
31
61
  get available(): boolean;
32
62
  private probe?;
33
- /** No executable: the real `codex` on PATH, past phren's session wrapper. */
34
- constructor(configured?: string | undefined);
63
+ /** No executable: the real `codex` on PATH, past phren's session wrapper.
64
+ * `served` answers panes on the Hook's own app-server over that server. */
65
+ constructor(configured?: string | undefined, served?: ServedCodex | undefined);
66
+ /** Whether the phone can answer this pane's questions: a pane on the Hook's
67
+ * own app-server always can; any other needs `codex queue`. */
68
+ availableFor(target: Target): boolean;
35
69
  private get executable();
36
70
  supported(): Promise<boolean>;
37
71
  pending(target: Target): Promise<Json[]>;
72
+ private transcriptPending;
38
73
  answer(target: Target, data: Json): Promise<void>;
39
74
  }
40
75
  export {};