@phren/cli 0.3.6 → 0.3.8

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,
@@ -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. */
@@ -173,7 +173,14 @@ export function opencodePermissionDialog(ansi) {
173
173
  // Lines pushed far right are OpenCode's status column, not the question.
174
174
  const body = plain.slice(header + 1, row).map(content)
175
175
  .filter(line => line.trim() && !/^\s{24,}/.test(line)).map(line => line.trim());
176
- const title = ["Permission required", ...body].join("\n").slice(0, 4_000);
176
+ // "← Access external directory ~/apps" is what it asks; a "Patterns" list
177
+ // under it is what it applies to, one "- " line each.
178
+ const [asks, ...rest] = body;
179
+ const title = (asks?.replace(/^[←→]\s*/, "") || "Permission required").slice(0, 4_000);
180
+ const patterns = rest.indexOf("Patterns");
181
+ const details = patterns < 0 ? rest
182
+ : [...rest.slice(0, patterns), ...rest.slice(patterns + 1).map(line => line.replace(/^-\s+/, ""))];
183
+ const detail = details.join("\n").slice(0, 4_000);
177
184
  const backgrounds = OPENCODE_OPTIONS.map(label => {
178
185
  const at = raw[row].indexOf(label);
179
186
  if (at < 0)
@@ -183,7 +190,7 @@ export function opencodePermissionDialog(ansi) {
183
190
  });
184
191
  const unique = backgrounds.flatMap((background, index) => background !== undefined && backgrounds.filter(other => other === background).length === 1 ? [index] : []);
185
192
  const selected = unique.length === 1 && backgrounds.every(background => background !== undefined) ? unique[0] : undefined;
186
- return { choice: { title, options: [{ label: "Allow once", key: "1", hasKey: false }, { label: "Reject", key: "Escape", hasKey: true }],
193
+ return { choice: { title, ...(detail ? { body: detail } : {}), options: [{ label: "Allow once", key: "1", hasKey: false }, { label: "Reject", key: "Escape", hasKey: true }],
187
194
  ...(selected === 0 ? { highlightedIndex: 0 } : {}) }, ...(selected !== undefined ? { selected } : {}) };
188
195
  }
189
196
  /** The pane's last non-empty line is a password read: sudo's "[sudo] password
@@ -73,10 +73,12 @@ export declare function tmuxKey(key: string): string | undefined;
73
73
  export declare function sendKeysCalls(pane: string, keys: string[]): string[][];
74
74
  export declare const tmuxTerminal: TerminalProvider;
75
75
  /** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
76
- * servers that answer, and the hidden server whenever tmux is installed (a
77
- * launch starts it). `kind` stays "herdr", the phone's name for the Hook's
76
+ * servers that answer, and (unless `hidden: false`) the hidden server whenever
77
+ * tmux is installed (a launch starts it). `kind` stays "herdr", the phone's name for the Hook's
78
78
  * session protocol; `terminal` names the multiplexer. */
79
- export declare function tmuxServers(): Promise<Json[]>;
79
+ export declare function tmuxServers(options?: {
80
+ hidden?: boolean;
81
+ }): Promise<Json[]>;
80
82
  /** What `phren bridge doctor` and the health details say about tmux. */
81
83
  export interface TmuxHealth {
82
84
  /** "off" when PHREN_TMUX=off, "missing" without a tmux executable. */
@@ -494,13 +494,14 @@ async function ownerServers() {
494
494
  return names.filter((_, index) => running[index]);
495
495
  }
496
496
  /** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
497
- * servers that answer, and the hidden server whenever tmux is installed (a
498
- * launch starts it). `kind` stays "herdr", the phone's name for the Hook's
497
+ * servers that answer, and (unless `hidden: false`) the hidden server whenever
498
+ * tmux is installed (a launch starts it). `kind` stays "herdr", the phone's name for the Hook's
499
499
  * session protocol; `terminal` names the multiplexer. */
500
- export async function tmuxServers() {
500
+ export async function tmuxServers(options = {}) {
501
501
  if (!deps.binary())
502
502
  return [];
503
- return [...await ownerServers(), TMUX_HIDDEN].map(name => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
503
+ return [...await ownerServers(), ...(options.hidden ?? true ? [TMUX_HIDDEN] : [])]
504
+ .map(name => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
504
505
  }
505
506
  export async function tmuxHealth() {
506
507
  if (process.env.PHREN_TMUX === "off")
@@ -1,4 +1,5 @@
1
1
  import { type Json } from "./protocol.js";
2
- /** Copilot's transcript reader: public message, tool and usage events, with
3
- * optional reasoning fields dropped. */
2
+ /** Copilot's transcript reader: public message, tool and usage events, and
3
+ * the reasoning summary Copilot itself prints under "Thought for Ns". Its
4
+ * encrypted and opaque reasoning stays out. */
4
5
  export declare function visibleCopilotEvent(raw: Json): Json | undefined;
@@ -1,14 +1,33 @@
1
1
  import { object } from "./protocol.js";
2
- /** Copilot's transcript reader: public message, tool and usage events, with
3
- * optional reasoning fields dropped. */
2
+ /** Copilot's transcript reader: public message, tool and usage events, and
3
+ * the reasoning summary Copilot itself prints under "Thought for Ns". Its
4
+ * encrypted and opaque reasoning stays out. */
4
5
  export function visibleCopilotEvent(raw) {
5
- if (raw.agentId || raw.ephemeral || !["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "abort", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type)))
6
+ if (raw.agentId || raw.ephemeral)
7
+ return undefined;
8
+ // What a skill loaded: Copilot answers the `skill` call with only "Skill
9
+ // loaded", then writes the SKILL.md it put in context as `skill.invoked`.
10
+ if (raw.type === "skill.invoked") {
11
+ const data = object(raw.data);
12
+ if (typeof data.name !== "string" || typeof data.content !== "string")
13
+ return undefined;
14
+ return { type: raw.type, timestamp: raw.timestamp, data: { name: data.name.slice(0, 200), content: data.content.slice(0, 65_536),
15
+ ...(typeof data.description === "string" ? { description: data.description.slice(0, 1_000) } : {}) } };
16
+ }
17
+ if (!["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "abort", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type)))
6
18
  return undefined;
7
19
  const data = object(raw.data);
8
- // Copilot includes optional reasoning beside the public message in some
9
- // versions. Export only the fields used by public text/tool/usage readers.
20
+ // Copilot writes its reasoning beside the message three ways: the summary
21
+ // its terminal shows (`reasoningText`), and encrypted/opaque copies for the
22
+ // model (`encryptedContent`, `reasoningOpaque`, `reasoningBlocks`). Only the
23
+ // summary the person already sees in the terminal is exported.
10
24
  // `phase` marks Copilot 1.0.87's final answer (it writes no session.idle);
11
25
  // `success` is false on a failed tool run.
12
- const allowed = ["content", "source", "messageId", "deltaContent", "toolName", "toolCallId", "arguments", "result", "error", "success", "phase", "aborted", "inputTokens", "outputTokens", "cacheReadTokens"];
13
- return { type: raw.type, timestamp: raw.timestamp, data: Object.fromEntries(Object.entries(data).filter(([key]) => allowed.includes(key))) };
26
+ const allowed = ["content", "source", "messageId", "deltaContent", "toolName", "toolCallId", "arguments", "result", "error", "success", "phase", "aborted", "reasoningText", "mcpServerName", "mcpToolName", "inputTokens", "outputTokens", "cacheReadTokens"];
27
+ return { type: raw.type, timestamp: raw.timestamp, data: Object.fromEntries(Object.entries(data)
28
+ // The MCP server and tool a call went to (`phren` + `get_tasks` for the
29
+ // `phren-get_tasks` tool), so the phone draws the server's own card.
30
+ .filter(([key, value]) => allowed.includes(key) && (key !== "reasoningText" || (raw.type === "assistant.message" && typeof value === "string"))
31
+ && (!["mcpServerName", "mcpToolName"].includes(key) || (typeof value === "string" && value.length <= 200)))
32
+ .map(([key, value]) => [key, key === "reasoningText" ? String(value).slice(0, 8_000) : value])) };
14
33
  }