@phren/cli 0.3.7 → 0.3.9

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.
@@ -8,7 +8,8 @@ import { watch } from "node:fs";
8
8
  import path from "node:path";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
11
- import { findPane, knownPanes, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
11
+ import { findPane, knownPanes, paneForCodexSession, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
12
+ import { underCodexDaemon } from "./codex-daemon.js";
12
13
  import { terminalPaneFromEnv, terminalProvider } from "./terminal.js";
13
14
  import { readPaneText } from "./pane-text.js";
14
15
  import { capturesChanges, ToolChanges } from "./changes.js";
@@ -1038,12 +1039,27 @@ export class AgentHooks {
1038
1039
  throw new Error("Oversized hook");
1039
1040
  chunks.push(bytes);
1040
1041
  }
1041
- const body = object(JSON.parse(Buffer.concat(chunks).toString())), target = targetSchema.parse(body.target);
1042
+ const body = object(JSON.parse(Buffer.concat(chunks).toString()));
1043
+ let target = targetSchema.parse(body.target);
1042
1044
  if (this.modules?.has("git") === false && ["PreToolUse", "PostToolUse"].includes(String(body.event))) {
1043
1045
  res.statusCode = 404;
1044
1046
  res.end(JSON.stringify({ error: disabledHint("git") }));
1045
1047
  return;
1046
1048
  }
1049
+ // A callback Codex's app-server daemon ran names the pane that started
1050
+ // the daemon, not the conversation's. Place it by the conversation the
1051
+ // Hook proves each pane shows, and never record a binding from it.
1052
+ const daemon = body.daemon === true;
1053
+ if (daemon) {
1054
+ if (target.source !== "codex")
1055
+ throw new Error("Invalid callback");
1056
+ const placed = await paneForCodexSession(target.server, target.session, typeof body.cwd === "string" && path.isAbsolute(body.cwd) ? body.cwd : undefined);
1057
+ if (!placed) {
1058
+ res.end("{}");
1059
+ return;
1060
+ }
1061
+ target = targetSchema.parse({ ...target, workspace: placed.workspace_id, tab: placed.tab_id, pane: placed.pane_id });
1062
+ }
1047
1063
  const s = await snapshot(target.server);
1048
1064
  const pane = findPane(s, { workspace: target.workspace, tab: target.tab, pane: target.pane });
1049
1065
  if (!pane || (pane.agent && pane.agent !== target.source))
@@ -1051,8 +1067,9 @@ export class AgentHooks {
1051
1067
  const pids = (await terminalProvider().processes(target.server, target.pane)).foregroundPids;
1052
1068
  if (!pids.length)
1053
1069
  throw new Error("No foreground process");
1054
- await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ terminal: pane.terminal_id, source: target.source,
1055
- session: target.session, pids, workspace: target.workspace, tab: target.tab, event: String(body.event).slice(0, 64), at: new Date().toISOString() }));
1070
+ if (!daemon)
1071
+ await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ terminal: pane.terminal_id, source: target.source,
1072
+ session: target.session, pids, workspace: target.workspace, tab: target.tab, event: String(body.event).slice(0, 64), at: new Date().toISOString() }));
1056
1073
  // A terminal that does not watch its agents (tmux) takes the agent's
1057
1074
  // status from these events.
1058
1075
  const status = eventStatus(body.event);
@@ -1241,7 +1258,10 @@ export async function agentHook(source) {
1241
1258
  const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
1242
1259
  if (!modules.has("hook") || (event.endsWith("ToolUse") && !modules.has("git")))
1243
1260
  return;
1244
- const data = JSON.stringify({ target, event, tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
1261
+ // Codex 0.157 runs hooks inside its shared app-server daemon, whose pane
1262
+ // variables belong to whichever pane first started it.
1263
+ const daemon = source === "codex" && await underCodexDaemon().catch(() => false);
1264
+ const data = JSON.stringify({ target, event, ...(daemon ? { daemon: true } : {}), tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
1245
1265
  ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}) });
1246
1266
  await new Promise(resolve => {
1247
1267
  const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 : 1500,
@@ -95,6 +95,10 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
95
95
  await sleep(120);
96
96
  }
97
97
  };
98
+ // After a key that answers, Claude may take seconds to redraw on a busy
99
+ // computer; the answer was taken, so wait for the redraw instead of
100
+ // calling it refused (the phone would say it was not confirmed).
101
+ const ANSWERED_MS = 8_000;
98
102
  const initial = await settle(screen => screen);
99
103
  if (!initial)
100
104
  throw changed("The terminal is not showing Claude's question.");
@@ -146,7 +150,7 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
146
150
  else {
147
151
  await io.keys([String(screen.options[answer.options[0]].number)]);
148
152
  }
149
- if (!await settle(leaves(index)))
153
+ if (!await settle(leaves(index), ANSWERED_MS))
150
154
  throw changed("The terminal did not take the answer.");
151
155
  continue;
152
156
  }
@@ -189,12 +193,12 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
189
193
  // Tab from the typed row would stop on Next instead of leaving.
190
194
  await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
191
195
  }
192
- if (!await settle(leaves(index)))
196
+ if (!await settle(leaves(index), ANSWERED_MS))
193
197
  throw changed("The terminal did not move past the question.");
194
198
  }
195
199
  if (!submit)
196
200
  return;
197
- const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined);
201
+ const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined, ANSWERED_MS);
198
202
  // A lone single-select question submits on its digit.
199
203
  if (review === "gone")
200
204
  return;
@@ -205,6 +209,6 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
205
209
  throw changed("Not every question has an answer in the terminal.");
206
210
  }
207
211
  await io.keys(["1"]);
208
- if (await settle(value => value === undefined ? "gone" : undefined) !== "gone")
212
+ if (await settle(value => value === undefined ? "gone" : undefined, ANSWERED_MS) !== "gone")
209
213
  throw changed("The terminal did not submit the answers.");
210
214
  }
@@ -0,0 +1,11 @@
1
+ /** The `codex` the Hook runs for its own helper calls (`codex queue`, `codex
2
+ * app-server`). `phren init` can put a session wrapper at ~/.local/bin/codex
3
+ * that runs phren's session-start hook before the real binary for every
4
+ * subcommand except a bare --help. That takes seconds (about 8 s on the Linux
5
+ * box), longer than the Hook's 5 s `codex queue --help` probe, so Codex async
6
+ * questions were reported as terminal-only, and each call opened a phren
7
+ * session. The Hook skips its own wrapper and runs the binary it names. */
8
+ export declare function codexExecutable(env?: NodeJS.ProcessEnv): string;
9
+ /** The real binary a phren session wrapper names, "" for a phren wrapper
10
+ * whose target cannot be read, undefined for anything else. */
11
+ export declare function phrenWrapperTarget(file: string): string | undefined;
@@ -0,0 +1,58 @@
1
+ import { accessSync, closeSync, constants, openSync, readSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ /** The `codex` the Hook runs for its own helper calls (`codex queue`, `codex
4
+ * app-server`). `phren init` can put a session wrapper at ~/.local/bin/codex
5
+ * that runs phren's session-start hook before the real binary for every
6
+ * subcommand except a bare --help. That takes seconds (about 8 s on the Linux
7
+ * box), longer than the Hook's 5 s `codex queue --help` probe, so Codex async
8
+ * questions were reported as terminal-only, and each call opened a phren
9
+ * session. The Hook skips its own wrapper and runs the binary it names. */
10
+ export function codexExecutable(env = process.env) {
11
+ if (process.platform === "win32")
12
+ return "codex";
13
+ for (const directory of (env.PATH ?? "").split(path.delimiter)) {
14
+ if (!path.isAbsolute(directory))
15
+ continue;
16
+ const candidate = path.join(directory, "codex");
17
+ if (!executable(candidate))
18
+ continue;
19
+ const wrapped = phrenWrapperTarget(candidate);
20
+ if (wrapped === undefined)
21
+ return candidate;
22
+ if (wrapped && executable(wrapped))
23
+ return wrapped;
24
+ }
25
+ return "codex";
26
+ }
27
+ function executable(file) {
28
+ try {
29
+ return statSync(file).isFile() && (accessSync(file, constants.X_OK), true);
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ /** The real binary a phren session wrapper names, "" for a phren wrapper
36
+ * whose target cannot be read, undefined for anything else. */
37
+ export function phrenWrapperTarget(file) {
38
+ let head = "";
39
+ try {
40
+ const fd = openSync(file, "r");
41
+ try {
42
+ const buffer = Buffer.alloc(4096);
43
+ head = buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, 0)).toString("utf8");
44
+ }
45
+ finally {
46
+ closeSync(fd);
47
+ }
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ if (!head.startsWith("#!/bin/sh") || !head.includes("phren wrapper error:"))
53
+ return undefined;
54
+ // shellEscape in hooks.ts: single quotes, an embedded quote written '\''.
55
+ const match = /^REAL_BIN='((?:[^']|'\\'')*)'$/m.exec(head);
56
+ const target = match?.[1].replace(/'\\''/g, "'");
57
+ return target && path.isAbsolute(target) ? target : "";
58
+ }
@@ -0,0 +1,59 @@
1
+ /** A conversation begins as its TUI starts; allow for clock rounding. */
2
+ export declare const START_SLACK_MS = 5000;
3
+ export interface ProcessRow {
4
+ pid: number;
5
+ ppid: number;
6
+ startedAt: number;
7
+ command: string;
8
+ }
9
+ export interface DaemonRollout {
10
+ id: string;
11
+ cwd: string;
12
+ startedAt: number;
13
+ activeAt: number;
14
+ held: boolean;
15
+ }
16
+ /** `ps` etime: `[[dd-]hh:]mm:ss`, in milliseconds. */
17
+ export declare function parseElapsed(text: string): number | undefined;
18
+ /** Every process with its parent, start time and command line, from one `ps`. */
19
+ export declare function processTable(now?: number): Promise<ProcessRow[]>;
20
+ export declare function isCodexDaemon(command: string): boolean;
21
+ /** When a pane's agent started: its oldest foreground process. */
22
+ export declare function startedAt(rows: ProcessRow[], pids: number[]): number | undefined;
23
+ /** True when this process runs under a Codex app-server daemon: a hook the
24
+ * daemon ran carries the environment of the pane that started the daemon,
25
+ * which is not the pane of the conversation it reports. */
26
+ export declare function underCodexDaemon(env?: NodeJS.ProcessEnv, pid?: number): Promise<boolean>;
27
+ /** The session_meta fields identity needs, from a rollout's first line read
28
+ * at most META_BYTES deep. Codex 0.157 writes its whole base instructions into
29
+ * that line, so a cut line is read field by field instead of parsed. */
30
+ export declare function rolloutMeta(file: string): Promise<{
31
+ id: string;
32
+ cwd: string;
33
+ startedAt: number;
34
+ subagent: boolean;
35
+ } | undefined>;
36
+ /**
37
+ * The conversations a running Codex daemon holds open (by `openFiles`, the
38
+ * caller's lsof or /proc read), else, when it holds none, the recent rollouts
39
+ * in Codex's sessions folder. Empty when no daemon runs: a TUI that runs its
40
+ * own conversation holds its rollout itself.
41
+ */
42
+ export declare function daemonRollouts(openFiles: (pids: number[]) => Promise<string[]>, now?: number): Promise<DaemonRollout[]>;
43
+ export declare function resetCodexDaemonCache(): void;
44
+ export declare function sameDirectory(a: unknown, b: unknown): Promise<boolean>;
45
+ /**
46
+ * Which daemon conversation a Codex pane shows, given the conversations in
47
+ * its folder, when its TUI started, which ones other panes' processes hold,
48
+ * and when every other Codex pane in that folder started.
49
+ *
50
+ * With no other Codex pane in the folder, the pane shows the most recently
51
+ * active conversation begun since its TUI started, so a later /new or
52
+ * /resume follows. With several, the latest-started pane chooses first (ties
53
+ * by pane key), each taking the earliest conversation begun after it started.
54
+ */
55
+ export interface CodexPaneStart {
56
+ key: string;
57
+ start: number;
58
+ }
59
+ export declare function assignDaemonConversation(here: DaemonRollout[], self: CodexPaneStart, claimed: Set<string>, rivals: CodexPaneStart[], now?: number): string | undefined;
@@ -0,0 +1,194 @@
1
+ import { execFile } from "node:child_process";
2
+ import { open, readdir, realpath, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { codexHome } from "../home-paths.js";
6
+ import { countIdentity } from "./metrics.js";
7
+ import { object, sessionId } from "./protocol.js";
8
+ /** Codex 0.157 runs its conversations in a shared background daemon
9
+ * (`codex app-server --listen … --managed-daemon`, reparented to launchd or
10
+ * init), not in the pane's own `codex` process. The pane's TUI holds no
11
+ * rollout, and Codex's lifecycle hooks run inside the daemon with the
12
+ * environment of whichever pane first started it. This module is what the
13
+ * Hook can still prove about such a conversation: which rollouts the daemon
14
+ * holds, the folder and time each began, and when each pane's TUI started. */
15
+ const exec = promisify(execFile);
16
+ const DAEMON_COMMAND = /(?:^|\/)codex\s+app-server(?:\s|$)/;
17
+ const ROLLOUT = /rollout-[^/]*-([a-f0-9-]{36})\.jsonl$/i;
18
+ const CACHE_MS = 2_000, META_BYTES = 65_536, MAX_ROLLOUTS = 32, MAX_DAEMONS = 4;
19
+ /** A conversation begins as its TUI starts; allow for clock rounding. */
20
+ export const START_SLACK_MS = 5_000;
21
+ /** `ps` etime: `[[dd-]hh:]mm:ss`, in milliseconds. */
22
+ export function parseElapsed(text) {
23
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(text.trim());
24
+ if (!match)
25
+ return undefined;
26
+ const [, days = "0", hours = "0", minutes, seconds] = match;
27
+ return (((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1000;
28
+ }
29
+ let table;
30
+ /** Every process with its parent, start time and command line, from one `ps`. */
31
+ export function processTable(now = Date.now()) {
32
+ if (table && now - table.at < CACHE_MS)
33
+ return table.rows;
34
+ countIdentity("ps");
35
+ const rows = exec("ps", ["-Aww", "-o", "pid=,ppid=,etime=,command="], { timeout: 3000, maxBuffer: 8_388_608 }).then(({ stdout }) => {
36
+ const out = [];
37
+ for (const line of String(stdout).split("\n")) {
38
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
39
+ const elapsed = match ? parseElapsed(match[3]) : undefined;
40
+ if (match && elapsed !== undefined)
41
+ out.push({ pid: Number(match[1]), ppid: Number(match[2]), startedAt: now - elapsed, command: match[4].slice(0, 4096) });
42
+ }
43
+ return out;
44
+ }, () => []);
45
+ table = { at: now, rows };
46
+ return rows;
47
+ }
48
+ export function isCodexDaemon(command) { return DAEMON_COMMAND.test(command); }
49
+ /** When a pane's agent started: its oldest foreground process. */
50
+ export function startedAt(rows, pids) {
51
+ const times = rows.filter(row => pids.includes(row.pid)).map(row => row.startedAt);
52
+ return times.length ? Math.min(...times) : undefined;
53
+ }
54
+ /** True when this process runs under a Codex app-server daemon: a hook the
55
+ * daemon ran carries the environment of the pane that started the daemon,
56
+ * which is not the pane of the conversation it reports. */
57
+ export async function underCodexDaemon(env = process.env, pid = process.pid) {
58
+ // Set only in the daemon's environment by Codex 0.157; a hint, not a contract.
59
+ if (env.CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED !== undefined)
60
+ return true;
61
+ if (process.platform === "win32")
62
+ return false;
63
+ const rows = await processTable(), byPid = new Map(rows.map(row => [row.pid, row]));
64
+ let current = byPid.get(pid)?.ppid ?? process.ppid;
65
+ for (let depth = 0; depth < 8 && current > 1; depth++) {
66
+ const row = byPid.get(current);
67
+ if (!row)
68
+ return false;
69
+ if (isCodexDaemon(row.command))
70
+ return true;
71
+ current = row.ppid;
72
+ }
73
+ return false;
74
+ }
75
+ /** The session_meta fields identity needs, from a rollout's first line read
76
+ * at most META_BYTES deep. Codex 0.157 writes its whole base instructions into
77
+ * that line, so a cut line is read field by field instead of parsed. */
78
+ export async function rolloutMeta(file) {
79
+ const handle = await open(file, "r").catch(() => undefined);
80
+ if (!handle)
81
+ return undefined;
82
+ let text;
83
+ try {
84
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(META_BYTES), 0, META_BYTES, 0);
85
+ text = buffer.subarray(0, bytesRead).toString("utf8");
86
+ }
87
+ catch {
88
+ return undefined;
89
+ }
90
+ finally {
91
+ await handle.close();
92
+ }
93
+ const newline = text.indexOf("\n");
94
+ let payload;
95
+ if (newline >= 0) {
96
+ try {
97
+ const raw = object(JSON.parse(text.slice(0, newline)));
98
+ if (raw.type !== "session_meta")
99
+ return undefined;
100
+ payload = object(raw.payload);
101
+ }
102
+ catch { /* fall through to field reads */ }
103
+ }
104
+ if (!payload) {
105
+ // The row's own type comes before its payload.
106
+ if (!text.slice(0, 256).includes('"type":"session_meta"'))
107
+ return undefined;
108
+ payload = {};
109
+ for (const key of ["id", "session_id", "timestamp", "cwd", "thread_source"]) {
110
+ // An unescaped `"key":"` is a JSON key: inside a string its quotes are escaped.
111
+ const match = new RegExp(`"${key}":("(?:[^"\\\\]|\\\\.)*")`).exec(text);
112
+ if (match)
113
+ try {
114
+ payload[key] = JSON.parse(match[1]);
115
+ }
116
+ catch { /* ignore */ }
117
+ }
118
+ if (/"source":\{"subagent"/.test(text))
119
+ payload.source = { subagent: true };
120
+ }
121
+ const id = String(payload.id ?? payload.session_id ?? ""), fromName = ROLLOUT.exec(file)?.[1];
122
+ const at = Date.parse(String(payload.timestamp ?? ""));
123
+ if (!sessionId.safeParse(id).success || (fromName && fromName.toLowerCase() !== id.toLowerCase()) || typeof payload.cwd !== "string" || !path.isAbsolute(payload.cwd) || !Number.isFinite(at))
124
+ return undefined;
125
+ const subagent = !!object(payload.source).subagent || (typeof payload.thread_source === "string" && /sub.?agent/i.test(payload.thread_source));
126
+ return { id, cwd: payload.cwd, startedAt: at, subagent };
127
+ }
128
+ /** Today's and yesterday's rollouts, newest first by name, capped. */
129
+ async function recentRollouts(now) {
130
+ const files = [];
131
+ for (const offset of [0, 1]) {
132
+ const day = new Date(now - offset * 86_400_000);
133
+ const folder = path.join(codexHome(), "sessions", String(day.getFullYear()), String(day.getMonth() + 1).padStart(2, "0"), String(day.getDate()).padStart(2, "0"));
134
+ const names = (await readdir(folder).catch(() => [])).filter(name => ROLLOUT.test(name)).sort().reverse();
135
+ files.push(...names.slice(0, MAX_ROLLOUTS).map(name => path.join(folder, name)));
136
+ }
137
+ return files.slice(0, MAX_ROLLOUTS);
138
+ }
139
+ let rollouts;
140
+ /**
141
+ * The conversations a running Codex daemon holds open (by `openFiles`, the
142
+ * caller's lsof or /proc read), else, when it holds none, the recent rollouts
143
+ * in Codex's sessions folder. Empty when no daemon runs: a TUI that runs its
144
+ * own conversation holds its rollout itself.
145
+ */
146
+ export function daemonRollouts(openFiles, now = Date.now()) {
147
+ if (rollouts && now - rollouts.at < CACHE_MS)
148
+ return rollouts.value;
149
+ const value = (async () => {
150
+ const daemons = (await processTable(now)).filter(row => isCodexDaemon(row.command)).map(row => row.pid).slice(0, MAX_DAEMONS);
151
+ if (!daemons.length)
152
+ return [];
153
+ countIdentity("codex-daemon");
154
+ const held = (await openFiles(daemons).catch(() => [])).filter(file => ROLLOUT.test(file)).slice(0, MAX_ROLLOUTS);
155
+ const files = held.length ? held : await recentRollouts(now);
156
+ const out = [];
157
+ for (const file of files) {
158
+ const meta = await rolloutMeta(file);
159
+ if (!meta || meta.subagent)
160
+ continue;
161
+ const info = await stat(file).catch(() => undefined);
162
+ out.push({ id: meta.id, cwd: meta.cwd, startedAt: meta.startedAt, activeAt: info?.mtimeMs ?? meta.startedAt, held: held.length > 0 });
163
+ }
164
+ return out;
165
+ })().catch(() => []);
166
+ rollouts = { at: now, value };
167
+ return value;
168
+ }
169
+ export function resetCodexDaemonCache() { table = undefined; rollouts = undefined; }
170
+ const real = async (dir) => realpath(dir).catch(() => path.resolve(dir));
171
+ export async function sameDirectory(a, b) {
172
+ if (typeof a !== "string" || typeof b !== "string" || !path.isAbsolute(a) || !path.isAbsolute(b))
173
+ return false;
174
+ return path.resolve(a) === path.resolve(b) || await real(a) === await real(b);
175
+ }
176
+ export function assignDaemonConversation(here, self, claimed, rivals, now = Date.now()) {
177
+ const open = here.filter(r => !claimed.has(r.id) && r.startedAt <= now + 60_000);
178
+ const after = (from) => open.filter(r => r.startedAt >= from - START_SLACK_MS);
179
+ if (!rivals.length) {
180
+ const pool = after(self.start);
181
+ const held = pool.filter(r => r.held);
182
+ return (held.length ? held : pool).sort((a, b) => b.activeAt - a.activeAt)[0]?.id;
183
+ }
184
+ const order = [...rivals, self].sort((a, b) => b.start - a.start || (a.key < b.key ? 1 : a.key > b.key ? -1 : 0));
185
+ const taken = new Set();
186
+ for (const pane of order) {
187
+ const pick = after(pane.start).filter(r => !taken.has(r.id)).sort((a, b) => a.startedAt - b.startedAt)[0];
188
+ if (pane === self)
189
+ return pick?.id;
190
+ if (pick)
191
+ taken.add(pick.id);
192
+ }
193
+ return undefined;
194
+ }
@@ -78,6 +78,10 @@ export declare function copilotForegroundSession(pids: number[], home?: string):
78
78
  * records it by PID on each prompt), when its transcript exists. Herdr's own
79
79
  * OpenCode integration may be missing; this does not depend on it. */
80
80
  export declare function opencodePidSession(pids: number[], root?: string): Promise<string | undefined>;
81
+ /** The Codex pane that shows `session`, for a lifecycle callback that ran
82
+ * inside a Codex daemon and so cannot name its pane. Falls back to the only
83
+ * Codex pane in the callback's folder while that pane shows no conversation. */
84
+ export declare function paneForCodexSession(server: string, session: string, cwd?: string): Promise<Json | undefined>;
81
85
  /** Bind first-send permission to the actual terminal/process, never a cwd or
82
86
  * a guessed conversation. Tokens expire naturally when the Hook/process restarts. */
83
87
  export declare function paneChatState(server: string, pane: Json, options?: {
@@ -12,6 +12,7 @@ import { tabActivityKey } from "./tab-activity.js";
12
12
  import { intervalFromEnv } from "./limits.js";
13
13
  import { countHerdr, countIdentity } from "./metrics.js";
14
14
  import { phrenStoreRoot } from "./transcripts.js";
15
+ import { assignDaemonConversation, daemonRollouts, processTable, sameDirectory, startedAt } from "./codex-daemon.js";
15
16
  // terminal.ts and terminal-tmux.ts import this module, so it reaches them at
16
17
  // call time; a static import back would be an import cycle.
17
18
  const terminal = () => import("./terminal.js");
@@ -147,9 +148,10 @@ export async function servers() {
147
148
  }
148
149
  }));
149
150
  const running = results.filter((v) => v !== null);
150
- // Without a running Herdr, tmux: the owner's server and the Hook's hidden one.
151
- if (!running.length)
152
- running.push(...await import("./terminal-tmux.js").then(tmux => tmux.tmuxServers()).catch(() => []));
151
+ // The owner's own tmux servers always: agents started with `tmux` beside a
152
+ // running Herdr show up too. The Hook's hidden server only without Herdr,
153
+ // where phone launches go; with Herdr they go to Herdr.
154
+ running.push(...await import("./terminal-tmux.js").then(tmux => tmux.tmuxServers({ hidden: !running.length })).catch(() => []));
153
155
  knownServers = running.map(server => String(server.session));
154
156
  return running;
155
157
  }
@@ -417,6 +419,15 @@ async function identityFromProcesses(server, pane, pids) {
417
419
  });
418
420
  if (new Set(candidates).size === 1)
419
421
  return { sessionId: candidates[0], noTranscriptLogs: false };
422
+ if (pane.agent === "codex" && candidates.length === 0) {
423
+ const daemon = await codexDaemonIdentity(server, pane, pids).catch(() => undefined);
424
+ if (daemon?.sessionId)
425
+ return { sessionId: daemon.sessionId, noTranscriptLogs: false };
426
+ const recorded = await recordedSession(server, pane, pids);
427
+ // A binding naming a conversation the daemon runs came from a hook inside
428
+ // the daemon, which carries the pane that started the daemon, not this one.
429
+ return { sessionId: recorded && !daemon?.known.has(recorded) ? recorded : undefined, noTranscriptLogs: true };
430
+ }
420
431
  // A lifecycle callback is bound to the process and terminal, never just cwd.
421
432
  // Codex can hold its parent and subagent transcripts in the same process.
422
433
  // Use the verified binding to disambiguate only if its log is still open;
@@ -424,6 +435,67 @@ async function identityFromProcesses(server, pane, pids) {
424
435
  const recorded = await recordedSession(server, pane, pids);
425
436
  return { sessionId: candidates.length === 0 || (recorded && candidates.includes(recorded)) ? recorded : undefined, noTranscriptLogs: candidates.length === 0 };
426
437
  }
438
+ const rolloutIds = (files) => files.flatMap(file => /rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file)?.[1] ?? []);
439
+ const paneCwd = (pane) => pane.foreground_cwd || pane.cwd;
440
+ /** A Codex 0.157 pane whose TUI holds no rollout: the conversation a Codex
441
+ * app-server daemon runs for it, matched by the pane's folder and its TUI's
442
+ * start time (codex-daemon.ts). `known` names every conversation the daemon
443
+ * holds, so a binding written from inside the daemon can be refused. */
444
+ async function codexDaemonIdentity(server, pane, pids) {
445
+ const all = await daemonRollouts(processLogs);
446
+ const known = new Set(all.map(r => r.id));
447
+ const cwd = paneCwd(pane);
448
+ const here = [];
449
+ for (const r of all)
450
+ if (await sameDirectory(r.cwd, cwd))
451
+ here.push(r);
452
+ if (!here.length)
453
+ return { known };
454
+ const rows = await processTable(), start = startedAt(rows, pids);
455
+ if (start === undefined)
456
+ return { known };
457
+ // Other Codex panes in the same folder: a conversation their own processes
458
+ // hold is theirs; otherwise they compete for daemon conversations by start
459
+ // time. Their bindings are not trusted here: before this fix the daemon's
460
+ // hooks wrote them for the pane that started the daemon.
461
+ const s = await (await terminal()).terminalProvider().snapshot(server).catch(() => ({}));
462
+ const claimed = new Set(), rivals = [];
463
+ for (const peer of objects(s.panes).filter(p => p.agent === "codex" && p.pane_id !== pane.pane_id).slice(0, 16)) {
464
+ if (!await sameDirectory(paneCwd(peer), cwd))
465
+ continue;
466
+ const peerPids = await foregroundPids(server, peer).catch(() => []);
467
+ if (!peerPids.length)
468
+ continue;
469
+ const own = rolloutIds(await processLogs(peerPids));
470
+ if (own.length) {
471
+ for (const id of own)
472
+ claimed.add(id);
473
+ continue;
474
+ }
475
+ const peerStart = startedAt(rows, peerPids);
476
+ if (peerStart !== undefined)
477
+ rivals.push({ key: String(peer.pane_id), start: peerStart });
478
+ }
479
+ return { sessionId: assignDaemonConversation(here, { key: String(pane.pane_id), start }, claimed, rivals), known };
480
+ }
481
+ /** The Codex pane that shows `session`, for a lifecycle callback that ran
482
+ * inside a Codex daemon and so cannot name its pane. Falls back to the only
483
+ * Codex pane in the callback's folder while that pane shows no conversation. */
484
+ export async function paneForCodexSession(server, session, cwd) {
485
+ const s = await snapshot(server);
486
+ const codex = objects(s.panes).filter(p => p.agent === "codex").slice(0, 32);
487
+ const identities = await Promise.all(codex.map(p => paneIdentity(server, p).catch(() => undefined)));
488
+ const index = identities.indexOf(session);
489
+ if (index >= 0)
490
+ return codex[index];
491
+ if (!cwd)
492
+ return undefined;
493
+ const same = [];
494
+ for (const [i, p] of codex.entries())
495
+ if (await sameDirectory(paneCwd(p), cwd))
496
+ same.push(i);
497
+ return same.length === 1 && !identities[same[0]] ? codex[same[0]] : undefined;
498
+ }
427
499
  const startingKey = randomBytes(32);
428
500
  /** Bind first-send permission to the actual terminal/process, never a cwd or
429
501
  * a guessed conversation. Tokens expire naturally when the Hook/process restarts. */
@@ -4,8 +4,9 @@ import { homedir } from "node:os";
4
4
  import { claudeConfigDir } from "../home-paths.js";
5
5
  import path from "node:path";
6
6
  import { object, objects } from "./protocol.js";
7
+ import { codexExecutable } from "./codex-binary.js";
7
8
  /** Only initialize and list. Never a thread, a prompt, or a login. */
8
- export function readCodexModels(executable = "codex") {
9
+ export function readCodexModels(executable = codexExecutable()) {
9
10
  return new Promise(resolve => {
10
11
  const child = spawn(executable, ["app-server"], { cwd: homedir(), stdio: ["pipe", "pipe", "ignore"] });
11
12
  let pending = "", bytes = 0, initialized = false, done = false;
@@ -23,14 +23,16 @@ interface PendingQuestion {
23
23
  export declare function pendingAsyncQuestions(file: string, targetID?: string): Promise<PendingQuestion[]>;
24
24
  export declare function pendingAsyncQuestion(file: string, id: string): Promise<Question[]>;
25
25
  export declare class CodexQuestions {
26
- private executable;
26
+ private readonly configured?;
27
27
  private snapshots;
28
28
  private failedSnapshots;
29
29
  private inboxAvailable;
30
30
  /** Feature discovery must never delay permission/status frames. */
31
31
  get available(): boolean;
32
32
  private probe?;
33
- constructor(executable?: string);
33
+ /** No executable: the real `codex` on PATH, past phren's session wrapper. */
34
+ constructor(configured?: string | undefined);
35
+ private get executable();
34
36
  supported(): Promise<boolean>;
35
37
  pending(target: Target): Promise<Json[]>;
36
38
  answer(target: Target, data: Json): Promise<void>;
@@ -7,6 +7,7 @@ import { z } from "zod";
7
7
  import { BridgeError, bridgeRoot, object, objects } from "./protocol.js";
8
8
  import { paneIdentity, validateTarget } from "./herdr.js";
9
9
  import { transcriptPath } from "./transcripts.js";
10
+ import { codexExecutable } from "./codex-binary.js";
10
11
  import { withTranscriptIndex } from "./transcript-index.js";
11
12
  const exec = promisify(execFile);
12
13
  const text = z.string().trim().min(1).max(4000).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
@@ -68,7 +69,7 @@ const answersQuestions = (reply, questions) => questions.every(q => {
68
69
  });
69
70
  export async function pendingAsyncQuestions(file, targetID) {
70
71
  return withTranscriptIndex(file, async (handle, index) => {
71
- const replies = [], acknowledged = new Set(), resolved = new Set(), pending = [];
72
+ const replies = [], acknowledged = new Set(), resolved = new Set(), seen = new Set(), pending = [];
72
73
  let bytes = 0;
73
74
  for await (const row of index.rows(handle, index.lines, Math.max(0, index.lines - 10_000))) {
74
75
  // An incomplete scan is not evidence that no questions remain. Status
@@ -106,11 +107,15 @@ export async function pendingAsyncQuestions(file, targetID) {
106
107
  if (!id || !acknowledged.has(id))
107
108
  continue;
108
109
  const questions = asyncQuestion(raw, id);
109
- if (questions && !replies.some(reply => answersQuestions(reply, questions))) {
110
+ // Codex 0.155 records one question twice under the same id: the
111
+ // request_user_input_async call and the AgentMessage delivered async.
112
+ if (questions && !seen.has(id) && !replies.some(reply => answersQuestions(reply, questions))) {
110
113
  pending.push({ id, questions });
111
114
  if (pending.length >= 64)
112
115
  throw new BridgeError(413, "Too many pending questions to verify.");
113
116
  }
117
+ if (questions)
118
+ seen.add(id);
114
119
  if (targetID && questions && id === targetID)
115
120
  return pending.filter(p => p.id === targetID);
116
121
  }
@@ -126,16 +131,18 @@ export async function pendingAsyncQuestion(file, id) {
126
131
  return pending.questions;
127
132
  }
128
133
  export class CodexQuestions {
129
- executable;
134
+ configured;
130
135
  snapshots = new Map();
131
136
  failedSnapshots = new Map();
132
137
  inboxAvailable = false;
133
138
  /** Feature discovery must never delay permission/status frames. */
134
139
  get available() { void this.supported(); return this.inboxAvailable; }
135
140
  probe;
136
- constructor(executable = "codex") {
137
- this.executable = executable;
141
+ /** No executable: the real `codex` on PATH, past phren's session wrapper. */
142
+ constructor(configured) {
143
+ this.configured = configured;
138
144
  }
145
+ get executable() { return this.configured ?? codexExecutable(); }
139
146
  supported() {
140
147
  if (!this.probe || Date.now() - this.probe.at > 300_000)
141
148
  this.probe = { at: Date.now(), result: exec(this.executable, ["queue", "--help"], { timeout: 5000, maxBuffer: 65_536 })