@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,636 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdir, mkdtemp, readdir, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { z } from "zod";
6
+ import { AppServerRpcError, connectAppServer, spawnAppServer } from "./codex-app-server.js";
7
+ import { logger } from "../logger.js";
8
+ import { atomic, bridgeRoot, id, object, objects, serverName } from "./protocol.js";
9
+ /**
10
+ * Codex panes the Hook launches run on a Phren-owned `codex app-server`, one
11
+ * per pane: the Hook spawns `codex app-server --listen unix://<sock>`, starts
12
+ * the thread itself (`thread/start`), and the pane runs `codex resume
13
+ * <threadId> --remote unix://<sock>` as a second client of that thread. The
14
+ * Hook's own client sends prompts (`turn/start`, acknowledged with a turn id),
15
+ * interrupts (`turn/interrupt`, after declining parked requests) and answers
16
+ * approvals (server requests, no hold timeout); whatever the owner does in the
17
+ * pane reaches the same thread. The registry under
18
+ * `<bridge>/codex-servers/<id>/server.json` lets a restarted Hook find each
19
+ * running server again and reconnect to its thread.
20
+ */
21
+ const REGISTRY = "codex-servers";
22
+ /** A Unix socket path is limited to about 104 bytes (macOS) / 108 (Linux). */
23
+ const MAX_SOCKET_PATH = 100;
24
+ /** A pane that shows no Codex for this long no longer runs the worker. */
25
+ const AGENT_GONE_MS = 120_000;
26
+ const CLIENT_NAME = "phren_hook";
27
+ const QUESTION_METHODS = new Set(["item/tool/requestUserInput", "mcpServer/elicitation/request"]);
28
+ const entrySchema = z.object({
29
+ id: z.string().regex(/^[a-f0-9]{12}$/),
30
+ server: serverName,
31
+ workspace: id,
32
+ tab: id,
33
+ pane: id,
34
+ socket: z.string().min(1).max(4096),
35
+ pid: z.number().int().positive(),
36
+ /** Unknown for a moment after a launch without a brief: the pane's TUI
37
+ * starts the thread itself and the Hook learns it from `thread/started`. */
38
+ threadId: z.string().min(1).max(200).optional(),
39
+ cwd: z.string().min(1).max(4096),
40
+ startedAt: z.string(),
41
+ dispatchId: z.string().optional(),
42
+ activeTurn: z.string().optional(),
43
+ lastTurn: z.object({ id: z.string(), status: z.string(), at: z.string() }).optional(),
44
+ /** What the phone chose, sent with the Hook's next `turn/start` (Codex keeps
45
+ * it for the thread's later turns too): model and effort, and the permission
46
+ * and plan settings as T3 maps them. */
47
+ nextTurn: z.object({
48
+ model: z.string().min(1).max(200).optional(), effort: z.string().min(1).max(20).optional(),
49
+ approvalPolicy: z.enum(["untrusted", "on-request", "never"]).optional(),
50
+ approvalsReviewer: z.enum(["user", "auto_review"]).optional(),
51
+ sandboxPolicy: z.object({ type: z.enum(["readOnly", "workspaceWrite", "dangerFullAccess"]) }).strict().optional(),
52
+ collaborationMode: z.object({ mode: z.enum(["plan", "default"]) }).strict().optional(),
53
+ }).strict().optional(),
54
+ }).strict();
55
+ const defaultDeps = {
56
+ spawn: spawnAppServer,
57
+ connect: connectAppServer,
58
+ alive: pid => { try {
59
+ process.kill(pid, 0);
60
+ return true;
61
+ }
62
+ catch (error) {
63
+ return error.code === "EPERM";
64
+ } },
65
+ kill: pid => {
66
+ // The detached server leads its own process group: end the group.
67
+ try {
68
+ process.kill(-pid, "SIGTERM");
69
+ }
70
+ catch {
71
+ try {
72
+ process.kill(pid, "SIGTERM");
73
+ }
74
+ catch { /* already gone */ }
75
+ }
76
+ },
77
+ };
78
+ /** `PHREN_CODEX_APP_SERVER=off` keeps every Codex launch on the typed path. */
79
+ export function codexAppServerEnabled(env = process.env, platform = process.platform) {
80
+ // The server listens on a unix socket and the pane joins it with
81
+ // `--remote unix://…`; Windows keeps the typed path.
82
+ if (platform === "win32")
83
+ return false;
84
+ return !/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_APP_SERVER ?? "");
85
+ }
86
+ /** A question on a Hook-run pane reaches the phone as a card either way, but
87
+ * only the blocking `request_user_input` holds the turn until someone answers:
88
+ * an async question (`request_user_input_async`) lets the worker carry on
89
+ * without the answer, and a plain-text question never becomes a card at all.
90
+ * Codex 0.157 offers the blocking tool outside plan mode only behind
91
+ * `features.default_mode_request_user_input`, and a short developer
92
+ * instruction steers the model to it (as T3 Code's CodexDeveloperInstructions
93
+ * does). `PHREN_CODEX_BLOCKING_QUESTIONS=off` leaves both out. */
94
+ export const BLOCKING_QUESTION_INSTRUCTIONS = "When you need the user to decide or supply something you cannot find out yourself, "
95
+ + "ask with the `request_user_input` tool, which waits for the answer; the user answers it from their phone or this terminal. "
96
+ + "Do not use `request_user_input_async` for that, and never write a multiple-choice question as a plain message. "
97
+ + "Ask only when a reasonable assumption would be risky.";
98
+ export function serverConfig(env = process.env) {
99
+ if (/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_BLOCKING_QUESTIONS ?? ""))
100
+ return [];
101
+ return ["features.default_mode_request_user_input=true", `developer_instructions=${JSON.stringify(BLOCKING_QUESTION_INSTRUCTIONS)}`];
102
+ }
103
+ /** The variable that tells a hook it runs inside the Hook's own app-server
104
+ * for one pane, so the pane variables it carries are that pane's. */
105
+ export const CODEX_SERVER_ENV = "PHREN_CODEX_SERVER";
106
+ export const codexServerId = z.string().regex(/^[a-f0-9]{12}$/);
107
+ /** The server's environment: the Hook's own, minus the variables that name
108
+ * the Hook's terminal, plus the pane's (so the hooks Codex runs inside the
109
+ * server report this pane) and the caller's. */
110
+ export function serverEnvironment(base, extra) {
111
+ const env = {};
112
+ for (const [key, value] of Object.entries(base)) {
113
+ if (/^(?:HERDR_|TMUX$|TMUX_PANE$|PHREN_DISPATCH_ID$)/.test(key))
114
+ continue;
115
+ env[key] = value;
116
+ }
117
+ return { ...env, ...extra };
118
+ }
119
+ export function codexServersRoot() { return path.join(bridgeRoot(), REGISTRY); }
120
+ /** Nothing was sent: the server could not be reached. */
121
+ export class CodexServerUnavailable extends Error {
122
+ constructor(message) { super(message); this.name = "CodexServerUnavailable"; }
123
+ }
124
+ export class CodexServers {
125
+ deps;
126
+ live = new Map();
127
+ sink;
128
+ closed = false;
129
+ constructor(deps = defaultDeps) {
130
+ this.deps = deps;
131
+ }
132
+ setDeps(deps) {
133
+ const previous = this.deps;
134
+ this.deps = { ...this.deps, ...deps };
135
+ return () => { this.deps = previous; };
136
+ }
137
+ saving = new Map();
138
+ setSink(sink) { this.sink = sink; }
139
+ entries() { return [...this.live.values()].map(live => live.entry); }
140
+ forPane(server, pane) {
141
+ return [...this.live.values()].find(live => live.entry.server === server && live.entry.pane === pane)?.entry;
142
+ }
143
+ forThread(threadId) {
144
+ return [...this.live.values()].find(live => live.entry.threadId !== undefined && live.entry.threadId === threadId)?.entry;
145
+ }
146
+ /** The server behind a Codex target, when the target is exactly its pane and thread. */
147
+ forTarget(target) {
148
+ if (target.source !== "codex")
149
+ return undefined;
150
+ const entry = this.forPane(target.server, target.pane);
151
+ return entry && entry.threadId !== undefined && entry.threadId === target.session && entry.workspace === target.workspace && entry.tab === target.tab ? entry : undefined;
152
+ }
153
+ /** A new server for a pane the Hook just created, and the arguments the
154
+ * pane's `codex` joins it with. With `startThread` (a launch that carries a
155
+ * brief) the Hook starts the thread and the pane resumes it:
156
+ * `codex resume <threadId> --remote unix://<socket>`. Codex cannot resume a
157
+ * thread with no turn yet, so without one the pane's TUI starts the thread
158
+ * (`codex --remote unix://<socket>`, with the model and effort as its own
159
+ * flags) and the Hook learns it from `thread/started` (`awaitThread`). The
160
+ * caller `stop`s the server if the pane cannot start. */
161
+ async launch(place, options) {
162
+ const serverId = randomBytes(6).toString("hex");
163
+ const directory = path.join(codexServersRoot(), serverId);
164
+ const socket = path.join(directory, "app.sock");
165
+ if (Buffer.byteLength(socket) > MAX_SOCKET_PATH)
166
+ throw new Error(`The Codex server socket path is too long: ${socket}`);
167
+ await mkdir(codexServersRoot(), { recursive: true, mode: 0o700 });
168
+ await mkdir(directory, { recursive: true, mode: 0o700 });
169
+ const handle = await this.deps.spawn({ socketPath: socket, cwd: options.cwd, detached: true, logFile: path.join(directory, "server.log"),
170
+ config: serverConfig(), replaceEnv: true, env: serverEnvironment(process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) }).catch(async (error) => {
171
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
172
+ throw error;
173
+ });
174
+ const pid = handle.child.pid;
175
+ let client;
176
+ try {
177
+ if (!pid)
178
+ throw new Error("codex app-server started without a process id");
179
+ client = await this.deps.connect(socket, { clientName: CLIENT_NAME, clientTitle: "Phren Hook" });
180
+ const entry = entrySchema.parse({ id: serverId, ...place, socket, pid, cwd: options.cwd, startedAt: new Date().toISOString(),
181
+ ...(options.dispatchId ? { dispatchId: options.dispatchId } : {}) });
182
+ const live = { entry, client };
183
+ // Listening before the thread exists, so its `thread/started` is not missed.
184
+ this.listen(live, client);
185
+ if (options.startThread) {
186
+ const started = await client.threadStart({ cwd: options.cwd, ...(options.model ? { model: options.model } : {}),
187
+ ...(options.effort ? { config: { model_reasoning_effort: options.effort } } : {}) });
188
+ const threadId = object(started.thread).id;
189
+ if (typeof threadId !== "string" || !threadId)
190
+ throw new Error("codex app-server thread/start returned no thread id");
191
+ entry.threadId = threadId;
192
+ live.subscribed = true;
193
+ if (typeof started.model === "string")
194
+ live.model = started.model;
195
+ }
196
+ await this.save(entry);
197
+ this.live.set(serverId, live);
198
+ const args = entry.threadId ? ["resume", entry.threadId, "--remote", `unix://${socket}`]
199
+ : ["--remote", `unix://${socket}`, ...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", `model_reasoning_effort=${options.effort}`] : []), ...(options.remoteArgs ?? [])];
200
+ return { entry, args };
201
+ }
202
+ catch (error) {
203
+ client?.close();
204
+ await handle.stop().catch(() => undefined);
205
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
206
+ throw error;
207
+ }
208
+ }
209
+ /** The pane's thread once its TUI has started it; undefined after `timeoutMs`. */
210
+ async awaitThread(entry, timeoutMs = 10_000) {
211
+ const deadline = Date.now() + timeoutMs;
212
+ while (!entry.threadId && Date.now() < deadline && this.live.has(entry.id))
213
+ await new Promise(resolve => setTimeout(resolve, 100));
214
+ return entry.threadId;
215
+ }
216
+ /** On Hook start: every registered server still running is reconnected
217
+ * and its thread followed again (its pending approvals are replayed to
218
+ * the new client); the rest are forgotten. */
219
+ async adopt() {
220
+ this.closed = false;
221
+ const names = await readdir(codexServersRoot()).catch(() => []);
222
+ for (const name of names.slice(0, 256)) {
223
+ if (!codexServerId.safeParse(name).success || [...this.live.values()].some(live => live.entry.id === name))
224
+ continue;
225
+ const entry = await this.read(name);
226
+ if (!entry || !this.deps.alive(entry.pid)) {
227
+ await this.forget(name);
228
+ continue;
229
+ }
230
+ const live = { entry };
231
+ this.live.set(name, live);
232
+ await this.connect(live).catch(error => logger.warn("codex-servers", `Could not reconnect to Codex server ${name}: ${error instanceof Error ? error.message : String(error)}`));
233
+ }
234
+ }
235
+ /** `turn/start` on the pane's thread; resolves with the turn id the server
236
+ * acknowledged. Nothing is typed into the pane. */
237
+ async prompt(entry, text) {
238
+ if (!entry.threadId)
239
+ throw new CodexServerUnavailable("The Codex pane has not started its thread yet.");
240
+ const client = await this.client(entry);
241
+ const live = this.live.get(entry.id)?.entry ?? entry, next = live.nextTurn;
242
+ const modeModel = next?.model ?? this.live.get(entry.id)?.model;
243
+ const collaborationMode = next?.collaborationMode && modeModel
244
+ // The mode carries its own model and effort, which win over the turn's.
245
+ ? { mode: next.collaborationMode.mode, settings: { model: modeModel, reasoning_effort: next.effort ?? null, developer_instructions: null } } : undefined;
246
+ const started = await client.turnStart({ threadId: entry.threadId, input: [{ type: "text", text, text_elements: [] }],
247
+ ...(next ? { ...(next.model ? { model: next.model } : {}), ...(next.effort ? { effort: next.effort } : {}),
248
+ ...(next.approvalPolicy ? { approvalPolicy: next.approvalPolicy } : {}), ...(next.approvalsReviewer ? { approvalsReviewer: next.approvalsReviewer } : {}),
249
+ ...(next.sandboxPolicy ? { sandboxPolicy: next.sandboxPolicy } : {}), ...(collaborationMode ? { collaborationMode } : {}) } : {}) });
250
+ // Codex took the override with the turn; the turn's own record shows it.
251
+ if (next && live.nextTurn === next) {
252
+ delete live.nextTurn;
253
+ void this.save(live).catch(() => undefined);
254
+ }
255
+ return started;
256
+ }
257
+ /** `thread/name/set` on the pane's thread: Codex's own rename, which its TUI
258
+ * shows and `session_index.jsonl` keeps. Allowed while a turn runs. */
259
+ async renameThread(entry, name) {
260
+ if (!entry.threadId)
261
+ throw new CodexServerUnavailable("The Codex pane has not started its thread yet.");
262
+ await (await this.client(entry)).request("thread/name/set", { threadId: entry.threadId, name });
263
+ }
264
+ /** Holds a model and effort for the pane's next Hook-sent turn. Nothing is
265
+ * typed into the TUI and a running turn is not disturbed. */
266
+ setNextTurn(entry, model, effort) {
267
+ this.hold(entry, { model, effort });
268
+ // A model chosen without an effort takes its own default, not the last one's.
269
+ if (!effort) {
270
+ const live = this.live.get(entry.id)?.entry;
271
+ if (live?.nextTurn)
272
+ delete live.nextTurn.effort;
273
+ }
274
+ }
275
+ /** Holds permission and plan settings the same way, next to a pending model. */
276
+ holdSettings(entry, settings) {
277
+ const live = this.live.get(entry.id);
278
+ if (settings.collaborationMode && !(live?.entry.nextTurn?.model ?? live?.model)) {
279
+ throw new CodexServerUnavailable("Codex has not reported this thread's model yet. Send a message first, then change plan mode.");
280
+ }
281
+ this.hold(entry, settings);
282
+ }
283
+ /** Merges into what is pending: a later choice replaces its own fields only. */
284
+ hold(entry, patch) {
285
+ const live = this.live.get(entry.id)?.entry;
286
+ if (!live)
287
+ throw new CodexServerUnavailable("This Codex server is no longer registered.");
288
+ live.nextTurn = { ...live.nextTurn, ...Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined)) };
289
+ void this.save(live).catch(() => undefined);
290
+ }
291
+ /** Input for the thread's running turn (`turn/steer`, as the TUI sends an
292
+ * async question's answer), or a new turn when none is running or the one
293
+ * it knew has ended. A refused steer sent nothing, so starting is safe. */
294
+ async steer(entry, text, extra = []) {
295
+ if (!entry.threadId)
296
+ throw new CodexServerUnavailable("The Codex pane has not started its thread yet.");
297
+ const client = await this.client(entry);
298
+ const input = [{ type: "text", text, text_elements: [] }, ...extra];
299
+ const running = this.live.get(entry.id)?.entry.activeTurn;
300
+ if (running) {
301
+ try {
302
+ return await client.turnSteer({ threadId: entry.threadId, expectedTurnId: running, input });
303
+ }
304
+ catch (error) {
305
+ if (!(error instanceof AppServerRpcError))
306
+ throw error;
307
+ }
308
+ }
309
+ return client.turnStart({ threadId: entry.threadId, input });
310
+ }
311
+ /** The thread's parked questions: `item/tool/requestUserInput` and MCP
312
+ * elicitations, which wait for an answer from any client. */
313
+ questions(entry) {
314
+ const client = this.live.get(entry.id)?.client;
315
+ if (!client || !entry.threadId)
316
+ return [];
317
+ return [...client.pending.values()].filter(request => QUESTION_METHODS.has(request.method)
318
+ && (request.threadId === undefined || request.threadId === entry.threadId));
319
+ }
320
+ /** Answers one parked question; false when no client still waits on it. */
321
+ answerQuestion(entry, requestId, result) {
322
+ const client = this.live.get(entry.id)?.client;
323
+ if (!client?.pending.has(requestId))
324
+ return false;
325
+ client.respond(requestId, result);
326
+ return true;
327
+ }
328
+ /** One proactive refresh of the shared Codex sign-in (codex-auth-refresh.ts)
329
+ * through Codex's own flow: on a running server's connection, or on a
330
+ * short-lived server when none runs. */
331
+ async refreshAuth() {
332
+ for (const live of this.live.values()) {
333
+ if (!this.deps.alive(live.entry.pid))
334
+ continue;
335
+ const client = await this.client(live.entry).catch(() => undefined);
336
+ if (!client)
337
+ continue;
338
+ await client.request("account/read", { refreshToken: true });
339
+ return;
340
+ }
341
+ const directory = await mkdtemp(path.join(tmpdir(), "phren-codex-auth-"));
342
+ const socket = path.join(directory, "app.sock");
343
+ try {
344
+ const handle = await this.deps.spawn({ socketPath: socket, cwd: directory, replaceEnv: true, env: serverEnvironment(process.env, {}) });
345
+ try {
346
+ const client = await this.deps.connect(socket, { clientName: CLIENT_NAME, clientTitle: "Phren Hook" });
347
+ try {
348
+ await client.request("account/read", { refreshToken: true });
349
+ }
350
+ finally {
351
+ client.close();
352
+ }
353
+ }
354
+ finally {
355
+ await handle.stop().catch(() => undefined);
356
+ }
357
+ }
358
+ finally {
359
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined);
360
+ }
361
+ }
362
+ /** Interrupt the running turn, declining the thread's parked server
363
+ * requests first. False when no turn is known to be running. */
364
+ async interrupt(entry) {
365
+ const live = this.live.get(entry.id);
366
+ const turn = live?.entry.activeTurn, threadId = live?.entry.threadId;
367
+ if (!live || !turn || !threadId)
368
+ return false;
369
+ const client = await this.client(entry);
370
+ const parked = [...client.pending.values()].filter(request => request.threadId === undefined || request.threadId === threadId);
371
+ await client.interruptTurn(threadId, turn);
372
+ // Declined by this client, so no `serverRequest/resolved` comes back for them.
373
+ for (const request of parked)
374
+ this.sink?.resolved(this.target(live.entry), request.requestId);
375
+ return true;
376
+ }
377
+ /** The last finished turn of a registered thread and the running one, for
378
+ * the returns loop. */
379
+ turnState(threadId) {
380
+ const entry = this.forThread(threadId);
381
+ return entry ? { ...(entry.activeTurn ? { activeTurn: entry.activeTurn } : {}), ...(entry.lastTurn ? { lastTurn: entry.lastTurn } : {}) } : undefined;
382
+ }
383
+ /** One Hook tick for `server`: forget servers whose process ended, stop
384
+ * servers whose pane closed (or has shown no Codex for two minutes), and
385
+ * reconnect a client that dropped. */
386
+ async reap(server, snapshot, now = Date.now()) {
387
+ const panes = objects(snapshot.panes);
388
+ for (const live of [...this.live.values()]) {
389
+ const entry = live.entry;
390
+ if (entry.server !== server)
391
+ continue;
392
+ if (!this.deps.alive(entry.pid)) {
393
+ await this.drop(live);
394
+ continue;
395
+ }
396
+ const pane = panes.find(candidate => candidate.pane_id === entry.pane);
397
+ if (!pane) {
398
+ await this.stop(entry);
399
+ continue;
400
+ }
401
+ if (pane.agent === "codex")
402
+ live.agentGoneSince = undefined;
403
+ else {
404
+ live.agentGoneSince ??= now;
405
+ if (now - live.agentGoneSince >= AGENT_GONE_MS) {
406
+ await this.stop(entry);
407
+ continue;
408
+ }
409
+ }
410
+ if (!live.client && !live.connecting)
411
+ await this.connect(live).catch(() => undefined);
412
+ else if (live.client && !live.subscribed && entry.threadId)
413
+ await this.subscribe(live, live.client).catch(() => undefined);
414
+ }
415
+ }
416
+ /** Servers whose terminal server is no longer running at all (a stopped
417
+ * Herdr session takes its panes with it): forgotten once dead, stopped
418
+ * after the same two minutes a pane without Codex gets. */
419
+ async sweep(running, now = Date.now()) {
420
+ for (const live of [...this.live.values()]) {
421
+ if (running.includes(live.entry.server))
422
+ continue;
423
+ if (!this.deps.alive(live.entry.pid)) {
424
+ await this.drop(live);
425
+ continue;
426
+ }
427
+ live.agentGoneSince ??= now;
428
+ if (now - live.agentGoneSince >= AGENT_GONE_MS)
429
+ await this.stop(live.entry);
430
+ }
431
+ }
432
+ /** The pane's TUI moved to `threadId` (`/new`, `/resume`), as its
433
+ * SessionStart hook reports: follow it, so prompts, approvals and Escape
434
+ * go where the TUI is. False when the pane has no registered server. */
435
+ follow(server, pane, threadId) {
436
+ const live = [...this.live.values()].find(candidate => candidate.entry.server === server && candidate.entry.pane === pane);
437
+ if (!live)
438
+ return false;
439
+ this.rebind(live, threadId);
440
+ return true;
441
+ }
442
+ rebind(live, threadId) {
443
+ const entry = live.entry;
444
+ if (entry.threadId === threadId)
445
+ return;
446
+ const previous = entry.threadId;
447
+ // The old thread's cards cannot be answered from this pane any more.
448
+ if (previous && live.client) {
449
+ const target = this.target(entry);
450
+ for (const request of live.client.pending.values())
451
+ if (request.threadId === undefined || request.threadId === previous)
452
+ this.sink?.resolved(target, request.requestId);
453
+ }
454
+ entry.threadId = threadId;
455
+ delete entry.activeTurn;
456
+ delete entry.lastTurn;
457
+ live.subscribed = false;
458
+ void this.save(entry).catch(() => undefined);
459
+ // A thread with no turn yet cannot be resumed; the tick tries again.
460
+ if (live.client)
461
+ void this.subscribe(live, live.client).catch(() => undefined);
462
+ }
463
+ /** Ends the server and forgets it. */
464
+ async stop(entry) {
465
+ const live = this.live.get(entry.id);
466
+ if (this.deps.alive(entry.pid))
467
+ this.deps.kill(entry.pid);
468
+ if (live)
469
+ await this.drop(live);
470
+ else
471
+ await this.forget(entry.id);
472
+ }
473
+ /** Close every client; the servers keep running for the next Hook. */
474
+ close() {
475
+ this.closed = true;
476
+ for (const live of this.live.values()) {
477
+ live.off?.();
478
+ live.client?.close();
479
+ live.client = undefined;
480
+ }
481
+ this.live.clear();
482
+ }
483
+ /** For tests: forget everything without touching processes. */
484
+ reset() { this.close(); this.closed = false; }
485
+ /** Resolves once every registry write started so far has finished. */
486
+ async saved() {
487
+ await Promise.all([...this.saving.values()].map(write => write.catch(() => undefined)));
488
+ }
489
+ target(entry) {
490
+ return { server: entry.server, workspace: entry.workspace, tab: entry.tab, pane: entry.pane, source: "codex", session: entry.threadId ?? "" };
491
+ }
492
+ /** Rejoin the thread: its history is skipped, its pending server requests
493
+ * come again as requests. */
494
+ async subscribe(live, client) {
495
+ const threadId = live.entry.threadId;
496
+ if (!threadId)
497
+ return;
498
+ const resumed = await client.threadResume({ threadId });
499
+ // The pane moved on while this was in flight: that thread's join decides.
500
+ if (live.entry.threadId !== threadId)
501
+ return;
502
+ live.subscribed = true;
503
+ if (typeof resumed.model === "string")
504
+ live.model = resumed.model;
505
+ // A turn that ended while no client listened: the recorded one is stale.
506
+ if (object(object(resumed.thread).status).type === "idle")
507
+ delete live.entry.activeTurn;
508
+ }
509
+ async client(entry) {
510
+ const live = this.live.get(entry.id);
511
+ if (!live)
512
+ throw new CodexServerUnavailable("This Codex server is no longer registered.");
513
+ if (!live.client)
514
+ await this.connect(live).catch(error => { throw new CodexServerUnavailable(`The Codex server is not reachable: ${error instanceof Error ? error.message : String(error)}`); });
515
+ if (!live.client)
516
+ throw new CodexServerUnavailable("The Codex server is not reachable.");
517
+ return live.client;
518
+ }
519
+ connect(live) {
520
+ if (live.connecting)
521
+ return live.connecting;
522
+ live.connecting = (async () => {
523
+ const client = await this.deps.connect(live.entry.socket, { clientName: CLIENT_NAME, clientTitle: "Phren Hook" });
524
+ live.subscribed = false;
525
+ try {
526
+ this.listen(live, client);
527
+ // A thread without a turn cannot be resumed yet; the tick retries.
528
+ await this.subscribe(live, client).catch(error => { if (!/no rollout/i.test(error instanceof Error ? error.message : ""))
529
+ throw error; });
530
+ }
531
+ catch (error) {
532
+ live.off?.();
533
+ live.off = undefined;
534
+ client.close();
535
+ throw error;
536
+ }
537
+ if (this.closed || !this.live.has(live.entry.id)) {
538
+ client.close();
539
+ return;
540
+ }
541
+ live.client = client;
542
+ })().finally(() => { live.connecting = undefined; });
543
+ return live.connecting;
544
+ }
545
+ listen(live, client) {
546
+ live.off?.();
547
+ const off = client.on(event => {
548
+ const entry = live.entry;
549
+ if (event.kind === "notification" && event.method === "thread/started") {
550
+ // The pane's TUI started a thread: its first one, or a later /new.
551
+ // Only the TUI and this Hook use the server, and the Hook starts a
552
+ // thread only at launch, so a top-level thread in the pane's folder
553
+ // is the one the pane now shows (helper threads, such as the one
554
+ // naming the thread, have no environment; subagents have a parent).
555
+ const thread = object(event.params.thread);
556
+ const here = objects(thread.environments).some(environment => typeof environment.cwd === "string" && path.resolve(environment.cwd) === path.resolve(entry.cwd));
557
+ if (typeof thread.id === "string" && thread.id && !thread.parentThreadId && here)
558
+ this.rebind(live, thread.id);
559
+ return;
560
+ }
561
+ if (!entry.threadId)
562
+ return;
563
+ if (event.kind === "request") {
564
+ if (event.threadId !== undefined && event.threadId !== entry.threadId)
565
+ return;
566
+ const changes = event.method === "item/fileChange/requestApproval" ? live.fileChanges?.get(String(event.params.itemId)) : undefined;
567
+ const request = changes ? { ...event, params: { ...event.params, changes } } : event;
568
+ this.sink?.request(this.target(entry), request, result => client.respond(event.requestId, result));
569
+ return;
570
+ }
571
+ if (event.kind === "resolved") {
572
+ if (event.threadId === undefined || event.threadId === entry.threadId)
573
+ this.sink?.resolved(this.target(entry), event.requestId);
574
+ return;
575
+ }
576
+ if (event.params.threadId !== entry.threadId)
577
+ return;
578
+ const item = object(event.params.item);
579
+ if (event.method === "item/started" && item.type === "fileChange" && typeof item.id === "string") {
580
+ live.fileChanges ??= new Map();
581
+ live.fileChanges.set(item.id, objects(item.changes).slice(0, 64));
582
+ while (live.fileChanges.size > 32)
583
+ live.fileChanges.delete(live.fileChanges.keys().next().value);
584
+ }
585
+ const turn = object(event.params.turn);
586
+ if (event.method === "turn/started" && typeof turn.id === "string") {
587
+ entry.activeTurn = turn.id;
588
+ void this.save(entry).catch(() => undefined);
589
+ }
590
+ else if (event.method === "turn/completed" && typeof turn.id === "string") {
591
+ if (entry.activeTurn === turn.id)
592
+ delete entry.activeTurn;
593
+ entry.lastTurn = { id: turn.id, status: typeof turn.status === "string" ? turn.status : "completed", at: new Date().toISOString() };
594
+ void this.save(entry).catch(() => undefined);
595
+ }
596
+ });
597
+ // A dropped connection is reconnected on the next tick.
598
+ const socketClosed = () => { if (live.client === client)
599
+ live.client = undefined; };
600
+ const offClose = client.onClose?.(socketClosed);
601
+ live.off = () => { off(); offClose?.(); };
602
+ }
603
+ async drop(live) {
604
+ live.off?.();
605
+ live.client?.close();
606
+ live.client = undefined;
607
+ this.live.delete(live.entry.id);
608
+ await this.forget(live.entry.id);
609
+ }
610
+ async forget(serverId) {
611
+ await rm(path.join(codexServersRoot(), codexServerId.parse(serverId)), { recursive: true, force: true }).catch(() => undefined);
612
+ }
613
+ async read(serverId) {
614
+ try {
615
+ const parsed = entrySchema.safeParse(JSON.parse(await readFile(path.join(codexServersRoot(), serverId, "server.json"), "utf8")));
616
+ return parsed.success && parsed.data.id === serverId ? parsed.data : undefined;
617
+ }
618
+ catch {
619
+ return undefined;
620
+ }
621
+ }
622
+ /** One server's registry writes run in order, each with the entry as it is
623
+ * then, so an earlier write that finishes late never lands over a newer one. */
624
+ save(entry) {
625
+ const file = path.join(codexServersRoot(), entry.id, "server.json");
626
+ const next = (this.saving.get(entry.id) ?? Promise.resolve()).catch(() => undefined)
627
+ .then(() => atomic(file, entrySchema.parse(entry)));
628
+ this.saving.set(entry.id, next);
629
+ void next.catch(() => undefined).finally(() => { if (this.saving.get(entry.id) === next)
630
+ this.saving.delete(entry.id); });
631
+ return next;
632
+ }
633
+ }
634
+ /** The Hook's servers: launch, prompt and keys routes, identity and the
635
+ * approval store all see the same registry. */
636
+ export const codexServers = new CodexServers();