@phren/cli 0.3.12 → 0.3.14

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 (58) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hooks.d.ts +3 -0
  4. package/dist/bridge/agent-hooks.js +20 -1
  5. package/dist/bridge/codex-app-server.d.ts +6 -0
  6. package/dist/bridge/codex-app-server.js +3 -1
  7. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  8. package/dist/bridge/codex-hook-trust.js +237 -0
  9. package/dist/bridge/codex-servers.d.ts +25 -1
  10. package/dist/bridge/codex-servers.js +78 -14
  11. package/dist/bridge/command.js +4 -1
  12. package/dist/bridge/dispatch-command.js +9 -3
  13. package/dist/bridge/dispatch-returns.d.ts +8 -0
  14. package/dist/bridge/dispatch-returns.js +21 -6
  15. package/dist/bridge/dispatch.d.ts +25 -1
  16. package/dist/bridge/dispatch.js +35 -6
  17. package/dist/bridge/hand-off-queue.d.ts +74 -0
  18. package/dist/bridge/hand-off-queue.js +235 -0
  19. package/dist/bridge/hand-off.d.ts +12 -4
  20. package/dist/bridge/hand-off.js +27 -7
  21. package/dist/bridge/install.d.ts +8 -1
  22. package/dist/bridge/install.js +60 -7
  23. package/dist/bridge/pane-status.d.ts +12 -0
  24. package/dist/bridge/pane-status.js +50 -1
  25. package/dist/bridge/push.d.ts +6 -0
  26. package/dist/bridge/push.js +21 -0
  27. package/dist/bridge/schedule-launch.d.ts +1 -1
  28. package/dist/bridge/schedule-launch.js +5 -1
  29. package/dist/bridge/schedule-watch.d.ts +15 -1
  30. package/dist/bridge/schedule-watch.js +45 -10
  31. package/dist/bridge/server-launch.js +14 -4
  32. package/dist/bridge/server-overview.d.ts +8 -1
  33. package/dist/bridge/server-overview.js +12 -3
  34. package/dist/bridge/server-pane-routes.d.ts +1 -0
  35. package/dist/bridge/server-pane-routes.js +9 -7
  36. package/dist/bridge/server-routes.d.ts +4 -0
  37. package/dist/bridge/server-routes.js +57 -7
  38. package/dist/bridge/server.js +15 -2
  39. package/dist/bridge/session-activity.d.ts +24 -12
  40. package/dist/bridge/session-activity.js +36 -14
  41. package/dist/bridge/stalls.d.ts +22 -0
  42. package/dist/bridge/stalls.js +57 -0
  43. package/dist/bridge/sudo.d.ts +209 -0
  44. package/dist/bridge/sudo.js +501 -0
  45. package/dist/bridge/terminal-tmux.d.ts +12 -0
  46. package/dist/bridge/terminal-tmux.js +79 -4
  47. package/dist/bridge/transcript-claude.d.ts +4 -0
  48. package/dist/bridge/transcript-claude.js +131 -6
  49. package/dist/bridge/usage.d.ts +17 -0
  50. package/dist/bridge/usage.js +37 -3
  51. package/dist/bridge-hook.mjs +24911 -23487
  52. package/dist/cli-registry.js +7 -1
  53. package/dist/modules/registry.js +8 -8
  54. package/dist/test-global-setup.js +7 -0
  55. package/dist/tools/dispatch.js +17 -2
  56. package/package.json +1 -1
  57. package/starter/global/AGENTS.md +4 -0
  58. package/starter/global/skills/conductor/SKILL.md +34 -2
@@ -0,0 +1,237 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, readFile, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { codexHome } from "../home-paths.js";
5
+ import { logger } from "../logger.js";
6
+ import { pretrustEnabled } from "./folder-trust.js";
7
+ import { atomic, object, objects } from "./protocol.js";
8
+ /**
9
+ * Keeping the owner's trust in Phren's own Codex hooks when an install
10
+ * rewrites them.
11
+ *
12
+ * Codex 0.158+ runs a `hooks.json` handler only when `config.toml` holds a
13
+ * matching `trusted_hash` for it, under
14
+ * `[hooks.state."<hooks.json path>:<event_snake>:<group>:<handler>"]`. The
15
+ * hash covers the handler's command, timeout and matcher, so an install that
16
+ * changes Phren's timeout (3 s to 15 s) or moves its group turns a handler the
17
+ * owner trusted into a "modified" one: Codex skips it and every new TUI opens
18
+ * on "Hooks need review".
19
+ *
20
+ * The rule never grants trust the owner did not give. A Phren handler whose
21
+ * key has no matching hash is trusted only when a hash stored for the same
22
+ * event in the same hooks.json is one of:
23
+ *
24
+ * - the same command with a timeout Phren has shipped (3, 10, 15, 60 or none);
25
+ * - a Phren handler for that event in hooks.json as it was before this
26
+ * install rewrote it (a changed node path, a moved group).
27
+ *
28
+ * A hash cannot come from anything but that event and that command, so a
29
+ * match means the owner trusted Phren's handler there. Other handlers are
30
+ * never touched. `PHREN_PRETRUST=off` turns this off with folder trust.
31
+ */
32
+ /** Timeouts Phren's Codex callbacks have carried in any release; undefined is "no timeout key". */
33
+ const SHIPPED_TIMEOUTS = [3, 10, 15, 60, undefined];
34
+ const quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
35
+ /** `SessionStart` to `session_start`, the event name in Codex's trust keys. */
36
+ export function codexEventName(event) {
37
+ return event.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
38
+ }
39
+ /** JSON with every object's keys sorted and no whitespace: serde_json's output for Codex's identity value. */
40
+ function canonicalJson(value) {
41
+ if (Array.isArray(value))
42
+ return `[${value.map(canonicalJson).join(",")}]`;
43
+ if (value && typeof value === "object") {
44
+ const record = value;
45
+ return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
46
+ }
47
+ // JSON.stringify escapes strings as serde_json does: `"`, `\` and control
48
+ // characters only, lowercase \u00xx, non-ASCII left as UTF-8.
49
+ return JSON.stringify(value);
50
+ }
51
+ /**
52
+ * Codex's `hook_hash` for one handler in one group (codex-rs hooks
53
+ * discovery + config fingerprint): sha256 of the canonical JSON of
54
+ * `{ event_name, matcher?, hooks: [handler] }`, where the handler always
55
+ * carries `timeout` (default 600, at least 1) and `async` (default false).
56
+ */
57
+ export function codexHookHash(event, group, handler) {
58
+ const name = codexEventName(event);
59
+ const shortLived = name === "session_end" || name === "interrupt";
60
+ const given = typeof handler.timeout === "number" ? handler.timeout : undefined;
61
+ const timeout = shortLived ? Math.min(3, Math.max(1, given ?? 1)) : Math.max(1, given ?? 600);
62
+ const hook = { type: handler.type ?? "command", command: handler.command, timeout, async: handler.async ?? false };
63
+ for (const key of ["statusMessage", "commandWindows", "additionalContextLimit"]) {
64
+ if (handler[key] !== undefined && handler[key] !== null)
65
+ hook[key] = handler[key];
66
+ }
67
+ const identity = { event_name: name, hooks: [hook] };
68
+ if (typeof group.matcher === "string")
69
+ identity.matcher = group.matcher;
70
+ return `sha256:${createHash("sha256").update(canonicalJson(identity), "utf8").digest("hex")}`;
71
+ }
72
+ /** Phren's own handlers in a Codex hooks.json text; none when it does not parse. */
73
+ function ownHandlers(text, program) {
74
+ if (text === undefined)
75
+ return [];
76
+ let parsed;
77
+ try {
78
+ parsed = JSON.parse(text);
79
+ }
80
+ catch {
81
+ return [];
82
+ }
83
+ const suffix = ` ${quote(program)} hook codex`;
84
+ const found = [];
85
+ for (const [event, groups] of Object.entries(object(object(parsed).hooks))) {
86
+ objects(groups).forEach((group, groupIndex) => objects(group.hooks).forEach((handler, handlerIndex) => {
87
+ if (typeof handler.command === "string" && handler.command.endsWith(suffix))
88
+ found.push({ event, group, handler, groupIndex, handlerIndex });
89
+ }));
90
+ }
91
+ return found;
92
+ }
93
+ const TABLE = /^[ \t]*\[[ \t]*hooks[ \t]*\.[ \t]*state[ \t]*\.[ \t]*("(?:[^"\\\r\n]|\\.)*"|'[^'\r\n]*')[ \t]*\][ \t]*(?:#.*)?$/;
94
+ const HASH_LINE = /^[ \t]*trusted_hash[ \t]*=[ \t]*"([^"\r\n]*)"/;
95
+ /** The `[hooks.state."<key>"]` tables of a config.toml, by line. */
96
+ function stateTables(lines) {
97
+ const tables = [];
98
+ let current;
99
+ lines.forEach((line, index) => {
100
+ if (/^[ \t]*\[/.test(line)) {
101
+ if (current)
102
+ current.end = index;
103
+ current = undefined;
104
+ const match = TABLE.exec(line);
105
+ if (!match)
106
+ return;
107
+ let key;
108
+ try {
109
+ key = match[1].startsWith("'") ? match[1].slice(1, -1) : JSON.parse(match[1]);
110
+ }
111
+ catch {
112
+ return;
113
+ }
114
+ current = { key, header: index, end: lines.length };
115
+ tables.push(current);
116
+ return;
117
+ }
118
+ const hash = current && current.hash === undefined ? HASH_LINE.exec(line) : null;
119
+ if (current && hash) {
120
+ current.hash = hash[1];
121
+ current.hashLine = index;
122
+ }
123
+ });
124
+ return tables;
125
+ }
126
+ function tomlKey(value) {
127
+ return `"${value.replace(/[\\"\u0000-\u001f\u007f]/g, c => c === "\\" ? "\\\\" : c === "\"" ? "\\\"" : `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)}"`;
128
+ }
129
+ /**
130
+ * The config text with trust carried forward to Phren's handlers in
131
+ * `hooks` (the hooks.json text as it is now), or undefined when nothing
132
+ * changes. `before` is hooks.json as it stood before this install rewrote
133
+ * it, when there was a rewrite. `hooksPaths` are the names Codex may key
134
+ * this hooks.json by; the first is used for a new key.
135
+ */
136
+ export function codexHookTrustText(config, hooks, program, hooksPaths, before) {
137
+ const own = ownHandlers(hooks, program);
138
+ if (!own.length)
139
+ return undefined;
140
+ const newline = config.includes("\r\n") ? "\r\n" : "\n";
141
+ const lines = config.split(/\r?\n/);
142
+ const tables = stateTables(lines);
143
+ const split = (key) => {
144
+ const match = /^(.*):([a-z_]+):(\d+):(\d+)$/.exec(key);
145
+ return match && hooksPaths.includes(match[1]) ? { file: match[1], event: match[2] } : undefined;
146
+ };
147
+ const stored = tables.flatMap(table => { const parts = split(table.key); return parts && table.hash ? [{ ...parts, hash: table.hash }] : []; });
148
+ if (!stored.length)
149
+ return undefined;
150
+ const keyPath = stored[0].file;
151
+ const previous = ownHandlers(before, program);
152
+ const edits = new Map(), appended = [], carried = [];
153
+ for (const entry of own) {
154
+ const name = codexEventName(entry.event);
155
+ const key = `${keyPath}:${name}:${entry.groupIndex}:${entry.handlerIndex}`;
156
+ const want = codexHookHash(entry.event, entry.group, entry.handler);
157
+ const table = tables.find(t => t.key === key);
158
+ if (table?.hash === want)
159
+ continue;
160
+ const accepted = new Set([
161
+ ...SHIPPED_TIMEOUTS.map(timeout => codexHookHash(entry.event, entry.group, { ...entry.handler, timeout })),
162
+ ...previous.filter(p => p.event === entry.event).map(p => codexHookHash(p.event, p.group, p.handler)),
163
+ ]);
164
+ if (!stored.some(s => s.event === name && accepted.has(s.hash)))
165
+ continue;
166
+ const line = `trusted_hash = "${want}"`;
167
+ if (table?.hashLine !== undefined)
168
+ edits.set(table.hashLine, lines[table.hashLine].replace(/"[^"]*"/, `"${want}"`));
169
+ else if (table)
170
+ edits.set(table.header, `${lines[table.header]}${newline}${line}`);
171
+ else
172
+ appended.push(`[hooks.state.${tomlKey(key)}]${newline}${line}${newline}`);
173
+ carried.push(key);
174
+ }
175
+ if (!carried.length)
176
+ return undefined;
177
+ const next = lines.map((line, index) => edits.get(index) ?? line);
178
+ if (appended.length) {
179
+ // New tables go right after the last hooks.state table, next to their siblings.
180
+ const last = tables[tables.length - 1];
181
+ const insertAt = last.end;
182
+ const block = appended.join(newline);
183
+ if (insertAt < next.length)
184
+ next.splice(insertAt, 0, ...block.split(newline).slice(0, -1), "");
185
+ else {
186
+ const text = next.join(newline);
187
+ const separator = text.endsWith(newline + newline) || text === "" ? "" : text.endsWith(newline) ? newline : newline + newline;
188
+ return { text: text + separator + block, carried };
189
+ }
190
+ }
191
+ return { text: next.join(newline), carried };
192
+ }
193
+ /**
194
+ * Carries the owner's Codex trust forward to Phren's handlers in
195
+ * `$CODEX_HOME/hooks.json`. Runs after every install, update, rollback and
196
+ * module reconcile, whether or not hooks.json changed, so a computer an
197
+ * earlier install left untrusted is repaired too. Never throws.
198
+ */
199
+ export async function carryCodexHookTrust(program, before, env = process.env) {
200
+ if (!pretrustEnabled(env))
201
+ return [];
202
+ try {
203
+ const directory = codexHome(env);
204
+ const hooksFile = path.join(directory, "hooks.json");
205
+ const hooks = await readFile(hooksFile, "utf8").catch(() => undefined);
206
+ if (hooks === undefined)
207
+ return [];
208
+ const hooksPaths = [...new Set([hooksFile, await realpath(hooksFile).catch(() => hooksFile)])];
209
+ const configured = path.join(directory, "config.toml");
210
+ const file = await realpath(configured).catch(() => configured);
211
+ for (let attempt = 0; attempt < 3; attempt++) {
212
+ const text = await readFile(file, "utf8").catch(error => {
213
+ if (error.code === "ENOENT")
214
+ return undefined;
215
+ throw error;
216
+ });
217
+ // No config means the owner never trusted anything.
218
+ if (text === undefined)
219
+ return [];
220
+ const result = codexHookTrustText(text, hooks, program, hooksPaths, before);
221
+ if (!result)
222
+ return [];
223
+ const metadata = await lstat(file);
224
+ // Codex may have rewritten the file meanwhile; start over from its text.
225
+ if (await readFile(file, "utf8").catch(() => "") !== text)
226
+ continue;
227
+ await atomic(file, result.text, metadata.mode & 0o777);
228
+ logger.info("install", `Kept Codex trust for Phren's rewritten hooks: ${result.carried.join(", ")}.`);
229
+ return result.carried;
230
+ }
231
+ throw new Error("config.toml kept changing while it was being updated");
232
+ }
233
+ catch (error) {
234
+ logger.warn("install", `Could not carry Codex hook trust forward: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`);
235
+ return [];
236
+ }
237
+ }
@@ -61,7 +61,12 @@ export interface CodexServerDeps {
61
61
  /** True while `pid` is a running process. */
62
62
  alive(pid: number): boolean;
63
63
  kill(pid: number): void;
64
+ /** The systemd scope a new server runs in, or undefined to run it in the Hook's own process tree. */
65
+ scope?(serverId: string): string | undefined;
64
66
  }
67
+ /** The systemd service cgroup a process runs in (`/proc/<pid>/cgroup`, cgroup
68
+ * v2), or undefined outside a service: a terminal, a scope, macOS. */
69
+ export declare function serviceCgroup(pid?: number | "self"): string | undefined;
65
70
  /** `PHREN_CODEX_APP_SERVER=off` keeps every Codex launch on the typed path. */
66
71
  export declare function codexAppServerEnabled(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): boolean;
67
72
  /** A question on a Hook-run pane reaches the phone as a card either way, but
@@ -83,6 +88,15 @@ export declare const codexServerId: z.ZodString;
83
88
  * server report this pane) and the caller's. */
84
89
  export declare function serverEnvironment(base: NodeJS.ProcessEnv, extra: Record<string, string>): NodeJS.ProcessEnv;
85
90
  export declare function codexServersRoot(): string;
91
+ /** A turn whose server ended before it did: the Hook restarted with the
92
+ * server inside its service, or the server crashed. Nothing will finish it. */
93
+ export interface LostTurn {
94
+ threadId: string;
95
+ turn: string;
96
+ dispatchId?: string;
97
+ at: string;
98
+ }
99
+ export declare const LOST_TURN = "The worker's Codex server stopped before its turn finished (the Phren Hook restarted with it, or it crashed), so the turn will not finish. Resume the thread or dispatch the work again.";
86
100
  /** Nothing was sent: the server could not be reached. */
87
101
  export declare class CodexServerUnavailable extends Error {
88
102
  constructor(message: string);
@@ -106,6 +120,8 @@ export interface LaunchOptions {
106
120
  export declare class CodexServers {
107
121
  private deps;
108
122
  private live;
123
+ /** Turns lost with their server, by `<server>\n<pane>`. */
124
+ private lost;
109
125
  private sink?;
110
126
  private closed;
111
127
  constructor(deps?: CodexServerDeps);
@@ -170,6 +186,9 @@ export declare class CodexServers {
170
186
  /** Interrupt the running turn, declining the thread's parked server
171
187
  * requests first. False when no turn is known to be running. */
172
188
  interrupt(entry: CodexServerEntry): Promise<boolean>;
189
+ /** The turn the pane's worker lost with its server, while that pane still
190
+ * shows `threadId` (any thread when not given). */
191
+ lostTurn(server: string, pane: string, threadId?: string, now?: number): LostTurn | undefined;
173
192
  /** The last finished turn of a registered thread and the running one, for
174
193
  * the returns loop. */
175
194
  turnState(threadId: string): {
@@ -204,13 +223,18 @@ export declare class CodexServers {
204
223
  private client;
205
224
  private connect;
206
225
  private listen;
226
+ /** A server that ended on its own mid-turn: the returns loop reports the turn failed. */
227
+ private markLost;
207
228
  private drop;
208
229
  private forget;
209
- private read;
210
230
  /** One server's registry writes run in order, each with the entry as it is
211
231
  * then, so an earlier write that finishes late never lands over a newer one. */
212
232
  private save;
213
233
  }
234
+ /** Registered servers still running inside the systemd service `unit`
235
+ * (`phren-hook.service`): stopping it ends them and cuts off their turns.
236
+ * Servers a Hook with scopes started run outside it. */
237
+ export declare function serversInService(unit: string, cgroup?: (pid: number) => string | undefined): Promise<CodexServerEntry[]>;
214
238
  /** The Hook's servers: launch, prompt and keys routes, identity and the
215
239
  * approval store all see the same registry. */
216
240
  export declare const codexServers: CodexServers;
@@ -1,4 +1,5 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
2
3
  import { mkdir, mkdtemp, readdir, readFile, rm } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import path from "node:path";
@@ -16,7 +17,9 @@ import { atomic, bridgeRoot, id, object, objects, serverName } from "./protocol.
16
17
  * approvals (server requests, no hold timeout); whatever the owner does in the
17
18
  * pane reaches the same thread. The registry under
18
19
  * `<bridge>/codex-servers/<id>/server.json` lets a restarted Hook find each
19
- * running server again and reconnect to its thread.
20
+ * running server again and reconnect to its thread. Under systemd each server
21
+ * runs in its own scope (`phren-codex-<id>.scope`), outside the Hook's
22
+ * service, so stopping or restarting the Hook does not end it.
20
23
  */
21
24
  const REGISTRY = "codex-servers";
22
25
  /** A Unix socket path is limited to about 104 bytes (macOS) / 108 (Linux). */
@@ -24,6 +27,8 @@ const MAX_SOCKET_PATH = 100;
24
27
  /** A pane that shows no Codex for this long no longer runs the worker. */
25
28
  const AGENT_GONE_MS = 120_000;
26
29
  const CLIENT_NAME = "phren_hook";
30
+ /** How long a turn lost with its server is reported to the returns loop. */
31
+ const LOST_MS = 24 * 60 * 60 * 1000;
27
32
  const QUESTION_METHODS = new Set(["item/tool/requestUserInput", "mcpServer/elicitation/request"]);
28
33
  const entrySchema = z.object({
29
34
  id: z.string().regex(/^[a-f0-9]{12}$/),
@@ -74,7 +79,20 @@ const defaultDeps = {
74
79
  catch { /* already gone */ }
75
80
  }
76
81
  },
82
+ scope: serverId => process.platform === "linux" && serviceCgroup() ? `phren-codex-${serverId}.scope` : undefined,
77
83
  };
84
+ /** The systemd service cgroup a process runs in (`/proc/<pid>/cgroup`, cgroup
85
+ * v2), or undefined outside a service: a terminal, a scope, macOS. */
86
+ export function serviceCgroup(pid = "self") {
87
+ try {
88
+ const line = readFileSync(`/proc/${pid}/cgroup`, "utf8").split("\n").find(candidate => candidate.startsWith("0::"));
89
+ const group = line?.slice(3).trim();
90
+ return group?.endsWith(".service") ? group : undefined;
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ }
78
96
  /** `PHREN_CODEX_APP_SERVER=off` keeps every Codex launch on the typed path. */
79
97
  export function codexAppServerEnabled(env = process.env, platform = process.platform) {
80
98
  // The server listens on a unix socket and the pane joins it with
@@ -117,6 +135,7 @@ export function serverEnvironment(base, extra) {
117
135
  return { ...env, ...extra };
118
136
  }
119
137
  export function codexServersRoot() { return path.join(bridgeRoot(), REGISTRY); }
138
+ export const LOST_TURN = "The worker's Codex server stopped before its turn finished (the Phren Hook restarted with it, or it crashed), so the turn will not finish. Resume the thread or dispatch the work again.";
120
139
  /** Nothing was sent: the server could not be reached. */
121
140
  export class CodexServerUnavailable extends Error {
122
141
  constructor(message) { super(message); this.name = "CodexServerUnavailable"; }
@@ -124,6 +143,8 @@ export class CodexServerUnavailable extends Error {
124
143
  export class CodexServers {
125
144
  deps;
126
145
  live = new Map();
146
+ /** Turns lost with their server, by `<server>\n<pane>`. */
147
+ lost = new Map();
127
148
  sink;
128
149
  closed = false;
129
150
  constructor(deps = defaultDeps) {
@@ -166,8 +187,17 @@ export class CodexServers {
166
187
  throw new Error(`The Codex server socket path is too long: ${socket}`);
167
188
  await mkdir(codexServersRoot(), { recursive: true, mode: 0o700 });
168
189
  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) => {
190
+ const spawnOptions = { socketPath: socket, cwd: options.cwd, detached: true, logFile: path.join(directory, "server.log"),
191
+ config: serverConfig(), replaceEnv: true, env: serverEnvironment(process.env, { ...(options.env ?? {}), [CODEX_SERVER_ENV]: serverId }) };
192
+ const scope = this.deps.scope?.(serverId);
193
+ const handle = await (scope
194
+ // No systemd-run, or no user manager to ask: the server runs in the
195
+ // Hook's service as before, and a Hook restart ends it.
196
+ ? this.deps.spawn({ ...spawnOptions, scope }).catch(error => {
197
+ logger.warn("codex-servers", `Could not start the Codex server in its own scope ${scope}; it will stop with the Hook: ${error instanceof Error ? error.message : String(error)}`);
198
+ return this.deps.spawn(spawnOptions);
199
+ })
200
+ : this.deps.spawn(spawnOptions)).catch(async (error) => {
171
201
  await rm(directory, { recursive: true, force: true }).catch(() => undefined);
172
202
  throw error;
173
203
  });
@@ -195,6 +225,7 @@ export class CodexServers {
195
225
  }
196
226
  await this.save(entry);
197
227
  this.live.set(serverId, live);
228
+ this.lost.delete(paneKey(place.server, place.pane));
198
229
  const args = entry.threadId ? ["resume", entry.threadId, "--remote", `unix://${socket}`]
199
230
  : ["--remote", `unix://${socket}`, ...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", `model_reasoning_effort=${options.effort}`] : []), ...(options.remoteArgs ?? [])];
200
231
  return { entry, args };
@@ -222,8 +253,10 @@ export class CodexServers {
222
253
  for (const name of names.slice(0, 256)) {
223
254
  if (!codexServerId.safeParse(name).success || [...this.live.values()].some(live => live.entry.id === name))
224
255
  continue;
225
- const entry = await this.read(name);
256
+ const entry = await readEntry(name);
226
257
  if (!entry || !this.deps.alive(entry.pid)) {
258
+ if (entry)
259
+ this.markLost(entry);
227
260
  await this.forget(name);
228
261
  continue;
229
262
  }
@@ -374,6 +407,18 @@ export class CodexServers {
374
407
  this.sink?.resolved(this.target(live.entry), request.requestId);
375
408
  return true;
376
409
  }
410
+ /** The turn the pane's worker lost with its server, while that pane still
411
+ * shows `threadId` (any thread when not given). */
412
+ lostTurn(server, pane, threadId, now = Date.now()) {
413
+ const key = paneKey(server, pane), lost = this.lost.get(key);
414
+ if (!lost)
415
+ return undefined;
416
+ if (now - Date.parse(lost.at) >= LOST_MS) {
417
+ this.lost.delete(key);
418
+ return undefined;
419
+ }
420
+ return threadId === undefined || threadId === lost.threadId ? lost : undefined;
421
+ }
377
422
  /** The last finished turn of a registered thread and the running one, for
378
423
  * the returns loop. */
379
424
  turnState(threadId) {
@@ -390,6 +435,7 @@ export class CodexServers {
390
435
  if (entry.server !== server)
391
436
  continue;
392
437
  if (!this.deps.alive(entry.pid)) {
438
+ this.markLost(entry);
393
439
  await this.drop(live);
394
440
  continue;
395
441
  }
@@ -421,6 +467,7 @@ export class CodexServers {
421
467
  if (running.includes(live.entry.server))
422
468
  continue;
423
469
  if (!this.deps.alive(live.entry.pid)) {
470
+ this.markLost(live.entry);
424
471
  await this.drop(live);
425
472
  continue;
426
473
  }
@@ -481,7 +528,7 @@ export class CodexServers {
481
528
  this.live.clear();
482
529
  }
483
530
  /** For tests: forget everything without touching processes. */
484
- reset() { this.close(); this.closed = false; }
531
+ reset() { this.close(); this.lost.clear(); this.closed = false; }
485
532
  /** Resolves once every registry write started so far has finished. */
486
533
  async saved() {
487
534
  await Promise.all([...this.saving.values()].map(write => write.catch(() => undefined)));
@@ -600,6 +647,14 @@ export class CodexServers {
600
647
  const offClose = client.onClose?.(socketClosed);
601
648
  live.off = () => { off(); offClose?.(); };
602
649
  }
650
+ /** A server that ended on its own mid-turn: the returns loop reports the turn failed. */
651
+ markLost(entry) {
652
+ if (!entry.activeTurn || !entry.threadId)
653
+ return;
654
+ logger.warn("codex-servers", `The Codex server for ${entry.server} ${entry.pane} ended during turn ${entry.activeTurn}`);
655
+ this.lost.set(paneKey(entry.server, entry.pane), { threadId: entry.threadId, turn: entry.activeTurn,
656
+ ...(entry.dispatchId ? { dispatchId: entry.dispatchId } : {}), at: new Date().toISOString() });
657
+ }
603
658
  async drop(live) {
604
659
  live.off?.();
605
660
  live.client?.close();
@@ -610,15 +665,6 @@ export class CodexServers {
610
665
  async forget(serverId) {
611
666
  await rm(path.join(codexServersRoot(), codexServerId.parse(serverId)), { recursive: true, force: true }).catch(() => undefined);
612
667
  }
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
668
  /** One server's registry writes run in order, each with the entry as it is
623
669
  * then, so an earlier write that finishes late never lands over a newer one. */
624
670
  save(entry) {
@@ -631,6 +677,24 @@ export class CodexServers {
631
677
  return next;
632
678
  }
633
679
  }
680
+ const paneKey = (server, pane) => `${server}\n${pane}`;
681
+ async function readEntry(serverId) {
682
+ try {
683
+ const parsed = entrySchema.safeParse(JSON.parse(await readFile(path.join(codexServersRoot(), serverId, "server.json"), "utf8")));
684
+ return parsed.success && parsed.data.id === serverId ? parsed.data : undefined;
685
+ }
686
+ catch {
687
+ return undefined;
688
+ }
689
+ }
690
+ /** Registered servers still running inside the systemd service `unit`
691
+ * (`phren-hook.service`): stopping it ends them and cuts off their turns.
692
+ * Servers a Hook with scopes started run outside it. */
693
+ export async function serversInService(unit, cgroup = serviceCgroup) {
694
+ const names = await readdir(codexServersRoot()).catch(() => []);
695
+ const entries = await Promise.all(names.filter(name => codexServerId.safeParse(name).success).slice(0, 256).map(readEntry));
696
+ return entries.filter((entry) => !!entry && cgroup(entry.pid)?.endsWith(`/${unit}`) === true);
697
+ }
634
698
  /** The Hook's servers: launch, prompt and keys routes, identity and the
635
699
  * approval store all see the same registry. */
636
700
  export const codexServers = new CodexServers();
@@ -5,6 +5,7 @@ import { install, rollback, uninstall } from "./install.js";
5
5
  import { servers } from "./herdr.js";
6
6
  import { describeTerminal, terminalHealth } from "./health.js";
7
7
  import { agentHook } from "./agent-hooks.js";
8
+ import { askpass } from "./sudo.js";
8
9
  import { object, provider } from "./protocol.js";
9
10
  import { apnsSetupSteps } from "./push.js";
10
11
  import { speechKeyFile, speechKeyStatus, writeSpeechKey } from "./speech-key.js";
@@ -166,6 +167,8 @@ export async function runBridge(args, version) {
166
167
  case "hook":
167
168
  await agentHook(provider.parse(args[1])).catch(() => { });
168
169
  break;
170
+ // sudo -A runs <bridge>/askpass, which runs this: the password on stdout, or exit 1.
171
+ case "askpass": return askpass(args[1]);
169
172
  case "serve": {
170
173
  // The subprocess bridge suite supplies this fixture; no agent binaries or
171
174
  // machine-specific catalogue caches should affect its HTTP assertions.
@@ -189,7 +192,7 @@ export async function runBridge(args, version) {
189
192
  break;
190
193
  case "install":
191
194
  case "update":
192
- await install(version, args.includes("--no-service"));
195
+ await install(version, args.includes("--no-service"), args.includes("--force"));
193
196
  break;
194
197
  case "uninstall":
195
198
  await uninstall();
@@ -14,6 +14,12 @@ export async function runDispatch(args) {
14
14
  console.log(JSON.stringify(await hookRequest("/v1/dispatch/returns", {}), null, 2));
15
15
  return 0;
16
16
  }
17
+ if (args[0] === "usage" && args.slice(1).every(arg => arg === "--json")) {
18
+ const { readAccountUsage, formatAccountUsage } = await import("./account-usage.js");
19
+ const view = await readAccountUsage();
20
+ console.log(args.includes("--json") ? JSON.stringify(view, null, 2) : formatAccountUsage(view));
21
+ return 0;
22
+ }
17
23
  if (args.length === 1 && args[0] === "sessions") {
18
24
  const { listLiveSessions } = await import("./hand-off.js");
19
25
  console.log(JSON.stringify(await listLiveSessions(), null, 2));
@@ -47,12 +53,12 @@ export async function runDispatch(args) {
47
53
  }
48
54
  export async function runHandOff(args) {
49
55
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
50
- session: { type: "string" }, text: { type: "string" }, project: { type: "string" }, account: { type: "string" },
56
+ "delivery-id": { type: "string" }, status: { type: "boolean" }, session: { type: "string" }, text: { type: "string" }, project: { type: "string" }, account: { type: "string" },
51
57
  } });
52
- if (positionals.length !== 1 || !values.session || !values.text)
58
+ if (positionals.length !== 1 || !values.session || (!values.status && !values.text) || (values.status && !values["delivery-id"]))
53
59
  throw new Error("Usage: phren hand-off <computer|local> --session <id> --text <prompt> [--project <slug>] [--account <id>]");
54
60
  const computer = positionals[0] === "local" ? undefined : positionals[0];
55
- const result = await handOff({ ...(computer ? { computer } : {}), project: values.project, ...(values.account ? { account: values.account } : {}), session: sessionId.parse(values.session), text: values.text });
61
+ const result = await handOff({ ...(computer ? { computer } : {}), project: values.project, ...(values.account ? { account: values.account } : {}), session: sessionId.parse(values.session), ...(values.status ? { status: true } : { text: values.text }), ...(values["delivery-id"] ? { deliveryId: values["delivery-id"] } : {}) });
56
62
  console.log(JSON.stringify(result, null, 2));
57
63
  return result.ok ? 0 : 1;
58
64
  }
@@ -1,6 +1,8 @@
1
+ import { sessionStalls } from "./stalls.js";
1
2
  import { z } from "zod";
2
3
  import { type OriginPane, type Receipt } from "./dispatch.js";
3
4
  import { type BriefArrival } from "./launch-brief.js";
5
+ import { type LostTurn } from "./codex-servers.js";
4
6
  import { findGrant } from "./grants.js";
5
7
  import { peerRequest, type HookPeer } from "./peers.js";
6
8
  import { type Json, type Provider, type Target } from "./protocol.js";
@@ -84,6 +86,9 @@ export interface WorkerObservation {
84
86
  interrupted?: true;
85
87
  /** A permission request the pane's worker is waiting on, forwarded by its Hook (`AgentHooks.workerApproval`). */
86
88
  approval?: Json;
89
+ stalled?: boolean;
90
+ stalledSince?: string;
91
+ stallFor?: number;
87
92
  }
88
93
  export interface WorkerReaders {
89
94
  snapshot: (server: string) => Promise<Json>;
@@ -94,6 +99,9 @@ export interface WorkerReaders {
94
99
  /** What the worker in this conversation is waiting on, from the Hook that runs it. */
95
100
  approval?: (target: Target) => Json | undefined;
96
101
  now?: () => number;
102
+ stall?: typeof sessionStalls.observe;
103
+ /** The turn a Codex pane lost with its app-server, which no Stop will end. */
104
+ lost?: (server: string, pane: string, session?: string) => LostTurn | undefined;
97
105
  }
98
106
  /** The default readers with the approval reader of the Hook that runs the workers. */
99
107
  export declare const workerReaders: (approval: NonNullable<WorkerReaders["approval"]>) => WorkerReaders;