@phren/cli 0.3.30 → 0.3.31

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.
@@ -7,6 +7,7 @@ import { type RequestKind } from "./approval-summary.js";
7
7
  import { type DialogAnswer, type DialogQuestion } from "./claude-question-dialog.js";
8
8
  import { type TerminalChoice } from "./terminal-choice.js";
9
9
  import { ApprovalWatchLeases } from "./agent-hook-stores.js";
10
+ import { PromptDeliveries } from "./prompt-deliveries.js";
10
11
  import { SudoBroker } from "./sudo.js";
11
12
  import type { AppServerRequestId, PendingServerRequest } from "./codex-app-server.js";
12
13
  import { PaneServerWatcher, type PaneAsks } from "./opencode-panes.js";
@@ -87,30 +88,14 @@ export declare const OPENCODE_APPROVAL_OPTIONS: Json[];
87
88
  * are `always`, a plain approve is `once`, a deny is `reject`. Undefined for
88
89
  * anything else. */
89
90
  export declare function opencodePermissionReply(decision: unknown): "once" | "always" | "reject" | undefined;
90
- export type DeliveryOutcome = "delivered" | "blocked" | "pending";
91
- /** A phone message typed under its delivery id, so the phone can ask what
92
- * became of it by that id. `typed` until the Hook answers it queued; the
93
- * typed record's own settlement moves it on by id, never by its words. */
94
- interface TrackedDelivery {
95
- source: Provider;
96
- session: string;
97
- state: "typed" | "queued" | "delivered" | "blocked";
98
- at: number;
99
- }
100
- export type TrackedState = Exclude<TrackedDelivery["state"], "typed"> | "unknown";
101
91
  export declare class AgentHooks {
102
92
  readonly push: ApprovalPushService;
103
93
  private modules?;
104
94
  readonly changes: ToolChanges;
105
95
  private pending;
106
- /** Prompts Phren has typed into a pane, by a hash of their words, until the agent that
107
- * actually receives one reports in through UserPromptSubmit. Herdr writes
108
- * to a pane, not a conversation; the receiving agent's hook is the only
109
- * party that knows which conversation consumed the text, so it is the one
110
- * that can refuse it when that is not the conversation the phone meant. */
111
- private deliveries;
112
- /** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
113
- private tracked;
96
+ /** Phone messages Phren typed into a pane, until a conversation there
97
+ * submits them through UserPromptSubmit: see prompt-deliveries.ts. */
98
+ readonly deliveries: PromptDeliveries;
114
99
  /** The permission request a conversation is drawing in its own terminal
115
100
  * because nobody was there to hold it: what the phone shows above its
116
101
  * answer keys until the pane stops waiting. `dialog` marks a choice parsed
@@ -173,7 +158,7 @@ export declare class AgentHooks {
173
158
  private computerName;
174
159
  /** sudo -A requests from askpass, answered from the phone (sudo.ts). */
175
160
  readonly sudo: SudoBroker;
176
- constructor(push?: ApprovalPushService, modules?: ModuleSnapshot | undefined);
161
+ constructor(push?: ApprovalPushService, modules?: ModuleSnapshot | undefined, deliveriesFile?: string);
177
162
  private approvalsDirectory;
178
163
  private scheduleOpencodeSweep;
179
164
  /** Read every live opencode request file, map it to a target through the
@@ -216,41 +201,6 @@ export declare class AgentHooks {
216
201
  * fails never takes the Hook down. */
217
202
  private sweepFanoutArchive;
218
203
  watch(target: Target): () => void;
219
- /** Register a prompt about to be typed into `target`'s pane. The returned
220
- * promise settles "delivered" once that conversation's own hook submits the
221
- * text, "blocked" if another conversation in the pane tried to, or "pending"
222
- * after `waitMs`: a busy agent queues typed input and submits it only when
223
- * its turn ends, so the record outlives the wait (up to ten minutes) and a
224
- * late submission to the wrong conversation is still refused. A phone
225
- * message's `id` follows the record, so its outcome lands on that id. */
226
- expectDelivery(target: Target, text: string, waitMs?: number, signal?: AbortSignal, id?: string): Promise<DeliveryOutcome>;
227
- /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
228
- deliveryPending(target: Target, text: string): boolean;
229
- /** Wait again for a delivery `expectDelivery` already reported pending,
230
- * after the Hook pressed Enter a second time. */
231
- awaitLateDelivery(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
232
- private track;
233
- /** The Hook answered the phone message `id` as queued: its typed record
234
- * still waits for the agent's hook, which settles it by this id. */
235
- queueDelivery(id: string, target: Target): void;
236
- /** What became of the phone message `id` sent to `target`'s conversation:
237
- * queued until the agent submits it, then delivered, or blocked when
238
- * another conversation in the pane took it. Unknown while the Hook has not
239
- * answered it, for another conversation, or older than TRACK_MS. A
240
- * message answered uncertain still turns delivered once its hook takes it. */
241
- deliveryState(id: string, target: Target): TrackedState;
242
- /** Every known phone message to `target`'s conversation, for its stream. */
243
- deliveriesFor(target: Target): {
244
- deliveryId: string;
245
- state: TrackedState;
246
- }[];
247
- private settleTracked;
248
- /** The conversation `target` just submitted `prompt`. Nothing Phren typed
249
- * matches: a locally typed prompt, always allowed. Otherwise the oldest
250
- * matching delivery decides: its own conversation consumes it; any other
251
- * conversation is told to drop it, so the text is never spoken to the
252
- * wrong agent and the phone can safely send it again. */
253
- private submitted;
254
204
  /** The conversation's own turn events, for dispatch returns (turn-records.ts).
255
205
  * A failed write never fails the agent's callback. */
256
206
  private recordTurn;
@@ -8,17 +8,18 @@ import { request, createServer } from "node:http";
8
8
  import { mkdir, readFile, chmod, unlink, lstat } from "node:fs/promises";
9
9
  import { watch } from "node:fs";
10
10
  import path from "node:path";
11
- import { createHash, randomUUID } from "node:crypto";
11
+ import { randomUUID } from "node:crypto";
12
12
  import { hostname } from "node:os";
13
13
  import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
14
14
  import { findPane, knownPanes, paneIdentity, paneForCodexSession, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
15
15
  import { hookOutput, TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
16
16
  import { underCodexDaemon } from "./codex-daemon.js";
17
17
  import { codexAutoReview } from "./codex-review-mode.js";
18
+ import { codexForeignThread } from "./codex-thread-origin.js";
18
19
  import { terminalPaneFromEnv, terminalProvider } from "./terminal.js";
19
20
  import { readPaneText } from "./pane-text.js";
20
21
  import { capturesChanges, ToolChanges } from "./changes.js";
21
- import { phrenStoreRoot, unwrapPastedContent } from "./transcripts.js";
22
+ import { phrenStoreRoot } from "./transcripts.js";
22
23
  import { archiveFinishedFanouts, blockedFanouts, fanoutAsking } from "./fanouts.js";
23
24
  import { ensureGrant, findGrant } from "./grants.js";
24
25
  import { ApprovalPushService } from "./push.js";
@@ -33,6 +34,7 @@ import { ApprovalWatchLeases, bindingPath, localSocket, PushBindingStore } from
33
34
  import { notePaneTranscript, paneAccountKey } from "./pane-accounts.js";
34
35
  import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js";
35
36
  import { noteTurn as recordTurn } from "./turn-records.js";
37
+ import { PromptDeliveries } from "./prompt-deliveries.js";
36
38
  import { countTick } from "./metrics.js";
37
39
  import { briefId, briefIdInPrompt, briefLabel, DISPATCH_ID_ENV, recordBriefArrival } from "./launch-brief.js";
38
40
  import { SudoBroker } from "./sudo.js";
@@ -147,19 +149,6 @@ export function opencodePermissionReply(decision) {
147
149
  return "always";
148
150
  return undefined;
149
151
  }
150
- /** As long as a typed prompt's own record guards it (`expectDelivery`). */
151
- const TRACK_MS = 600_000;
152
- /** What the agent hands its UserPromptSubmit hook is the terminal's pasted
153
- * form of what Phren typed; compare the words, not the wrapping. Claude Code
154
- * also takes each attached picture's path line out of the text and puts an
155
- * "[Image #N]" label at the front, so neither side keeps picture paths or
156
- * labels. */
157
- function promptKey(text) {
158
- return unwrapPastedContent(text).split("\n").filter(line => !PICTURE_PATH_LINE.test(line)).join("\n")
159
- .replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
160
- }
161
- const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
162
- const promptHash = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
163
152
  /** This socket is deliberately separate from the phone's HTTP pipe. Only local
164
153
  * agent callbacks can register identities or create an approval request. */
165
154
  /** The project a notification names for a pane's folder: none for the
@@ -173,14 +162,9 @@ export class AgentHooks {
173
162
  modules;
174
163
  changes = new ToolChanges();
175
164
  pending = new Map();
176
- /** Prompts Phren has typed into a pane, by a hash of their words, until the agent that
177
- * actually receives one reports in through UserPromptSubmit. Herdr writes
178
- * to a pane, not a conversation; the receiving agent's hook is the only
179
- * party that knows which conversation consumed the text, so it is the one
180
- * that can refuse it when that is not the conversation the phone meant. */
181
- deliveries = new Map();
182
- /** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
183
- tracked = new Map();
165
+ /** Phone messages Phren typed into a pane, until a conversation there
166
+ * submits them through UserPromptSubmit: see prompt-deliveries.ts. */
167
+ deliveries;
184
168
  /** The permission request a conversation is drawing in its own terminal
185
169
  * because nobody was there to hold it: what the phone shows above its
186
170
  * answer keys until the pane stops waiting. `dialog` marks a choice parsed
@@ -243,9 +227,10 @@ export class AgentHooks {
243
227
  computerName = hostname().replace(/\.local$/i, "").split(".")[0] || "Computer";
244
228
  /** sudo -A requests from askpass, answered from the phone (sudo.ts). */
245
229
  sudo;
246
- constructor(push = new ApprovalPushService(), modules) {
230
+ constructor(push = new ApprovalPushService(), modules, deliveriesFile) {
247
231
  this.push = push;
248
232
  this.modules = modules;
233
+ this.deliveries = new PromptDeliveries(deliveriesFile);
249
234
  void computerDisplayName().then(name => { this.computerName = name; }, () => { });
250
235
  this.sudo = new SudoBroker({ computer: () => this.computerName, push, label: briefLabel,
251
236
  describe: async (place) => {
@@ -634,130 +619,6 @@ export class AgentHooks {
634
619
  else
635
620
  this.watching.delete(key); };
636
621
  }
637
- /** Register a prompt about to be typed into `target`'s pane. The returned
638
- * promise settles "delivered" once that conversation's own hook submits the
639
- * text, "blocked" if another conversation in the pane tried to, or "pending"
640
- * after `waitMs`: a busy agent queues typed input and submits it only when
641
- * its turn ends, so the record outlives the wait (up to ten minutes) and a
642
- * late submission to the wrong conversation is still refused. A phone
643
- * message's `id` follows the record, so its outcome lands on that id. */
644
- expectDelivery(target, text, waitMs = 1_500, signal, id) {
645
- if (!promptKey(text) || signal?.aborted)
646
- return Promise.resolve("pending");
647
- const key = promptHash(text);
648
- if (id)
649
- this.track(id, target, "typed");
650
- return new Promise(resolve => {
651
- let settled = false;
652
- const list = this.deliveries.get(key) ?? [];
653
- const remove = () => {
654
- signal?.removeEventListener("abort", cancel);
655
- const current = this.deliveries.get(key) ?? [];
656
- const index = current.indexOf(delivery);
657
- if (index >= 0)
658
- current.splice(index, 1);
659
- if (!current.length)
660
- this.deliveries.delete(key);
661
- };
662
- const settle = (outcome) => {
663
- if (!settled) {
664
- settled = true;
665
- resolve(outcome);
666
- }
667
- else if (outcome !== "pending")
668
- delivery.late?.(outcome);
669
- if (outcome !== "pending") {
670
- clearTimeout(delivery.timer);
671
- remove();
672
- this.settleTracked(delivery, outcome);
673
- }
674
- };
675
- const delivery = { source: target.source, session: target.session, ...(id ? { id } : {}), settle, timer: setTimeout(() => settle("pending"), waitMs) };
676
- // Only cancel after a provider explicitly refused before writing. A
677
- // possibly delivered paste keeps its guard against the wrong session.
678
- const cancel = () => { clearTimeout(delivery.timer); settle("pending"); remove(); };
679
- signal?.addEventListener("abort", cancel, { once: true });
680
- delivery.timer.unref?.();
681
- const expiry = setTimeout(remove, 600_000);
682
- expiry.unref?.();
683
- list.push(delivery);
684
- this.deliveries.set(key, list);
685
- while (this.deliveries.size > 256)
686
- this.deliveries.delete(this.deliveries.keys().next().value);
687
- });
688
- }
689
- /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
690
- deliveryPending(target, text) {
691
- return !!this.deliveries.get(promptHash(text))?.some(entry => entry.source === target.source && entry.session === target.session);
692
- }
693
- /** Wait again for a delivery `expectDelivery` already reported pending,
694
- * after the Hook pressed Enter a second time. */
695
- awaitLateDelivery(target, text, waitMs = 2_500) {
696
- const delivery = this.deliveries.get(promptHash(text))?.find(entry => entry.source === target.source && entry.session === target.session);
697
- if (!delivery)
698
- return Promise.resolve("pending");
699
- return new Promise(resolve => {
700
- const timer = setTimeout(() => { delivery.late = undefined; resolve("pending"); }, waitMs);
701
- timer.unref?.();
702
- delivery.late = outcome => { clearTimeout(timer); delivery.late = undefined; resolve(outcome); };
703
- });
704
- }
705
- track(id, target, state) {
706
- const now = Date.now();
707
- for (const [key, entry] of this.tracked)
708
- if (now - entry.at > TRACK_MS)
709
- this.tracked.delete(key);
710
- while (this.tracked.size >= 512)
711
- this.tracked.delete(this.tracked.keys().next().value);
712
- this.tracked.set(id, { source: target.source, session: target.session, state, at: now });
713
- }
714
- /** The Hook answered the phone message `id` as queued: its typed record
715
- * still waits for the agent's hook, which settles it by this id. */
716
- queueDelivery(id, target) {
717
- const entry = this.tracked.get(id);
718
- if (entry?.state === "typed" && entry.source === target.source && entry.session === target.session)
719
- entry.state = "queued";
720
- }
721
- /** What became of the phone message `id` sent to `target`'s conversation:
722
- * queued until the agent submits it, then delivered, or blocked when
723
- * another conversation in the pane took it. Unknown while the Hook has not
724
- * answered it, for another conversation, or older than TRACK_MS. A
725
- * message answered uncertain still turns delivered once its hook takes it. */
726
- deliveryState(id, target) {
727
- const entry = this.tracked.get(id);
728
- return entry && entry.state !== "typed" && entry.source === target.source && entry.session === target.session && Date.now() - entry.at <= TRACK_MS ? entry.state : "unknown";
729
- }
730
- /** Every known phone message to `target`'s conversation, for its stream. */
731
- deliveriesFor(target) {
732
- return [...this.tracked.keys()].map(deliveryId => ({ deliveryId, state: this.deliveryState(deliveryId, target) })).filter(item => item.state !== "unknown");
733
- }
734
- settleTracked(delivery, outcome) {
735
- const entry = delivery.id ? this.tracked.get(delivery.id) : undefined;
736
- if (entry && entry.source === delivery.source && entry.session === delivery.session) {
737
- entry.state = outcome;
738
- entry.at = Date.now();
739
- }
740
- }
741
- /** The conversation `target` just submitted `prompt`. Nothing Phren typed
742
- * matches: a locally typed prompt, always allowed. Otherwise the oldest
743
- * matching delivery decides: its own conversation consumes it; any other
744
- * conversation is told to drop it, so the text is never spoken to the
745
- * wrong agent and the phone can safely send it again. */
746
- submitted(target, prompt) {
747
- const list = this.deliveries.get(promptHash(prompt));
748
- // The same words sent to two conversations at once: each one's own
749
- // submission settles its own record, not whichever was typed first.
750
- const delivery = list?.find(entry => entry.source === target.source && entry.session === target.session) ?? list?.[0];
751
- if (!delivery)
752
- return {};
753
- const own = delivery.source === target.source && delivery.session === target.session;
754
- if (own) {
755
- delivery.settle("delivered");
756
- return {};
757
- }
758
- delivery.settle("blocked");
759
- return { decision: "block", reason: "Phren sent this message to a different conversation in this pane; it was not delivered here. Send it again from the phone." };
760
- }
761
622
  /** The conversation's own turn events, for dispatch returns (turn-records.ts).
762
623
  * A failed write never fails the agent's callback. */
763
624
  async recordTurn(target, pane, body, dispatch) {
@@ -1772,7 +1633,9 @@ export class AgentHooks {
1772
1633
  }
1773
1634
  // `/new` or `/resume` in a pane on the Hook's own Codex server: follow
1774
1635
  // the TUI to its new thread. Only a callback trusted to name its pane.
1775
- if (body.event === "SessionStart" && target.source === "codex" && !daemon)
1636
+ // A prompt or a turn's end also moves a server a nested `codex exec`
1637
+ // had taken (before codex-thread-origin.ts) back to the TUI's thread.
1638
+ if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)) && target.source === "codex" && !daemon)
1776
1639
  codexServers.follow(target.server, target.pane, target.session);
1777
1640
  if (body.event === "PreCompact") {
1778
1641
  this.startCompacting(target);
@@ -1782,14 +1645,15 @@ export class AgentHooks {
1782
1645
  if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)))
1783
1646
  this.stopCompacting(target);
1784
1647
  if (body.event === "UserPromptSubmit") {
1785
- const answer = typeof body.prompt === "string" ? this.submitted(target, body.prompt.slice(0, 65_536)) : {};
1786
- // A prompt refused here never starts a turn in this conversation.
1787
- if (answer.decision !== "block")
1788
- await this.recordTurn(target, pane, body, dispatch);
1789
- const context = answer.decision === "block" || this.modules?.has("conductor") === false ? undefined : await conductorContext(target, s).catch(() => undefined);
1790
- res.end(JSON.stringify({ ...answer, ...(context ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context } } : {}) }));
1648
+ if (typeof body.prompt === "string")
1649
+ this.deliveries.submitted(target, body.prompt.slice(0, 65_536));
1650
+ await this.recordTurn(target, pane, body, dispatch);
1651
+ const context = this.modules?.has("conductor") === false ? undefined : await conductorContext(target, s).catch(() => undefined);
1652
+ res.end(JSON.stringify(context ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context } } : {}));
1791
1653
  return;
1792
1654
  }
1655
+ if (body.event === "Stop")
1656
+ this.deliveries.stopped(target);
1793
1657
  if (body.event === "SessionStart" || body.event === "Stop")
1794
1658
  await this.recordTurn(target, pane, body, dispatch);
1795
1659
  if (body.event === "SessionStart") {
@@ -1995,6 +1859,9 @@ export async function agentHook(source, elapsed = () => performance.now()) {
1995
1859
  const value = object(JSON.parse(input));
1996
1860
  if (value.agent_id || value.agentId || value.isSidechain || value.is_sidechain)
1997
1861
  return;
1862
+ // A `codex exec` or a subagent inside a Codex pane is not the pane's conversation.
1863
+ if (source === "codex" && await codexForeignThread(value.transcript_path).catch(() => false))
1864
+ return;
1998
1865
  const target = targetSchema.parse({ server: place.server, workspace: place.workspace, tab: place.tab,
1999
1866
  pane: place.pane, source, session: value.session_id || value.sessionId });
2000
1867
  const event = String(value.hook_event_name || "SessionStart");
@@ -54,6 +54,8 @@ export type CodexNextTurn = NonNullable<CodexServerEntry["nextTurn"]>;
54
54
  export interface CodexApprovalSink {
55
55
  request(target: Target, request: PendingServerRequest, answer: (result: Json) => void): void;
56
56
  resolved(target: Target, requestId: AppServerRequestId): void;
57
+ /** The pane moved to another thread; input still pending on `previous` will not show there. */
58
+ threadChanged?(previous: Target): void;
57
59
  }
58
60
  export interface CodexServerDeps {
59
61
  spawn: typeof spawnAppServer;
@@ -158,6 +160,16 @@ export declare class CodexServers {
158
160
  prompt(entry: CodexServerEntry, text: string): Promise<{
159
161
  turnId: string;
160
162
  }>;
163
+ /** A phone message, sent as the pane's TUI sends Enter: steered into the
164
+ * running turn, else a new turn. Either way Codex holds it as input until
165
+ * the model's next step takes it (after the tool call that is running, which
166
+ * can be long), and only then runs UserPromptSubmit; on Codex 0.160 a
167
+ * `turn/start` during a turn is merged into it the same way. So the turn id
168
+ * acknowledges the hand-over, not the delivery. A held model change starts
169
+ * a turn, which carries it. */
170
+ send(entry: CodexServerEntry, text: string): Promise<{
171
+ turnId: string;
172
+ }>;
161
173
  /** `thread/name/set` on the pane's thread: Codex's own rename, which its TUI
162
174
  * shows and `session_index.jsonl` keeps. Allowed while a turn runs. */
163
175
  renameThread(entry: CodexServerEntry, name: string): Promise<void>;
@@ -226,8 +226,11 @@ export class CodexServers {
226
226
  await this.save(entry);
227
227
  this.live.set(serverId, live);
228
228
  this.lost.delete(paneKey(place.server, place.pane));
229
- const args = entry.threadId ? ["resume", entry.threadId, "--remote", `unix://${socket}`]
230
- : ["--remote", `unix://${socket}`, ...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", `model_reasoning_effort=${options.effort}`] : []), ...(options.remoteArgs ?? [])];
229
+ // The resumed TUI carries the model too: without it a /new in the pane
230
+ // fell back to config.toml's default, not the model this pane was given.
231
+ const model = [...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", `model_reasoning_effort=${options.effort}`] : [])];
232
+ const args = entry.threadId ? ["resume", entry.threadId, "--remote", `unix://${socket}`, ...model]
233
+ : ["--remote", `unix://${socket}`, ...model, ...(options.remoteArgs ?? [])];
231
234
  return { entry, args };
232
235
  }
233
236
  catch (error) {
@@ -287,6 +290,29 @@ export class CodexServers {
287
290
  }
288
291
  return started;
289
292
  }
293
+ /** A phone message, sent as the pane's TUI sends Enter: steered into the
294
+ * running turn, else a new turn. Either way Codex holds it as input until
295
+ * the model's next step takes it (after the tool call that is running, which
296
+ * can be long), and only then runs UserPromptSubmit; on Codex 0.160 a
297
+ * `turn/start` during a turn is merged into it the same way. So the turn id
298
+ * acknowledges the hand-over, not the delivery. A held model change starts
299
+ * a turn, which carries it. */
300
+ async send(entry, text) {
301
+ if (!entry.threadId)
302
+ throw new CodexServerUnavailable("The Codex pane has not started its thread yet.");
303
+ const live = this.live.get(entry.id)?.entry ?? entry, running = live.activeTurn;
304
+ if (running && !live.nextTurn) {
305
+ const client = await this.client(entry);
306
+ try {
307
+ return await client.turnSteer({ threadId: entry.threadId, expectedTurnId: running, input: [{ type: "text", text, text_elements: [] }] });
308
+ }
309
+ catch (error) {
310
+ if (!(error instanceof AppServerRpcError))
311
+ throw error;
312
+ }
313
+ }
314
+ return await this.prompt(entry, text);
315
+ }
290
316
  /** `thread/name/set` on the pane's thread: Codex's own rename, which its TUI
291
317
  * shows and `session_index.jsonl` keeps. Allowed while a turn runs. */
292
318
  async renameThread(entry, name) {
@@ -491,6 +517,8 @@ export class CodexServers {
491
517
  if (entry.threadId === threadId)
492
518
  return;
493
519
  const previous = entry.threadId;
520
+ if (previous)
521
+ this.sink?.threadChanged?.(this.target(entry));
494
522
  // The old thread's cards cannot be answered from this pane any more.
495
523
  if (previous && live.client) {
496
524
  const target = this.target(entry);
@@ -599,9 +627,13 @@ export class CodexServers {
599
627
  // thread only at launch, so a top-level thread in the pane's folder
600
628
  // is the one the pane now shows (helper threads, such as the one
601
629
  // naming the thread, have no environment; subagents have a parent).
630
+ // Codex's auto-review guardian runs as a subagent thread in the
631
+ // pane's folder with no parent id, and a `codex exec` is not the TUI's:
632
+ // following either moved the pane off its conversation (w63, 2026-10-04).
602
633
  const thread = object(event.params.thread);
603
634
  const here = objects(thread.environments).some(environment => typeof environment.cwd === "string" && path.resolve(environment.cwd) === path.resolve(entry.cwd));
604
- if (typeof thread.id === "string" && thread.id && !thread.parentThreadId && here)
635
+ const foreign = thread.source === "exec" || (typeof thread.source === "object" && thread.source !== null && "subAgent" in thread.source) || thread.ephemeral === true;
636
+ if (typeof thread.id === "string" && thread.id && !thread.parentThreadId && here && !foreign)
605
637
  this.rebind(live, thread.id);
606
638
  return;
607
639
  }
@@ -0,0 +1,12 @@
1
+ /** Whether a Codex hook callback comes from a thread that is not the pane's
2
+ * own conversation: a `codex exec` started inside the pane (a fanout worker,
3
+ * a review run) or a subagent (the guardian reviewer, a spawned thread). They
4
+ * inherit the pane's variables, so their callbacks name the pane, and each
5
+ * one used to rebind it: the pane's conversation then looked replaced, phone
6
+ * sends were refused as "conversation changed" and queued hand-offs failed.
7
+ * Read from the rollout's first row (`originator`, `source`); a rollout that
8
+ * cannot be read counts as the pane's own. */
9
+ export declare function codexForeignThread(transcriptPath: unknown): Promise<boolean>;
10
+ /** The session_meta fields come before its long instructions, so the head of
11
+ * the line is enough; no full parse. */
12
+ export declare function foreignMeta(head: string): boolean;
@@ -0,0 +1,31 @@
1
+ import { open } from "node:fs/promises";
2
+ import path from "node:path";
3
+ /** Whether a Codex hook callback comes from a thread that is not the pane's
4
+ * own conversation: a `codex exec` started inside the pane (a fanout worker,
5
+ * a review run) or a subagent (the guardian reviewer, a spawned thread). They
6
+ * inherit the pane's variables, so their callbacks name the pane, and each
7
+ * one used to rebind it: the pane's conversation then looked replaced, phone
8
+ * sends were refused as "conversation changed" and queued hand-offs failed.
9
+ * Read from the rollout's first row (`originator`, `source`); a rollout that
10
+ * cannot be read counts as the pane's own. */
11
+ export async function codexForeignThread(transcriptPath) {
12
+ if (typeof transcriptPath !== "string" || !path.isAbsolute(transcriptPath) || !/^rollout-.*\.jsonl$/.test(path.basename(transcriptPath)))
13
+ return false;
14
+ const file = await open(transcriptPath, "r").catch(() => undefined);
15
+ if (!file)
16
+ return false;
17
+ try {
18
+ const buffer = Buffer.alloc(4096), { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
19
+ return foreignMeta(buffer.subarray(0, bytesRead).toString("utf8"));
20
+ }
21
+ finally {
22
+ await file.close();
23
+ }
24
+ }
25
+ /** The session_meta fields come before its long instructions, so the head of
26
+ * the line is enough; no full parse. */
27
+ export function foreignMeta(head) {
28
+ if (!head.includes('"session_meta"'))
29
+ return false;
30
+ return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
31
+ }
@@ -37,6 +37,11 @@ export interface QueueOptions {
37
37
  validate: (target: Target) => Promise<Json>;
38
38
  send: (target: Target, text: string, deliveryId: string, typing: () => Promise<void>) => Promise<Json>;
39
39
  notify?: (target: Target, text: string, deliveryId: string, computer: string) => Promise<Json>;
40
+ /** The conversation the target's pane shows now, and its terminal. */
41
+ current?: (target: Target) => Promise<{
42
+ session: string;
43
+ terminal: unknown;
44
+ } | undefined>;
40
45
  now?: () => number;
41
46
  root?: string;
42
47
  }
@@ -69,6 +74,11 @@ export declare class HandOffQueue {
69
74
  private reply;
70
75
  enqueue(input: unknown): Promise<Json>;
71
76
  status(id: string, target: Target): Promise<Json>;
77
+ /** Validates the row's target. When the pane's conversation was replaced
78
+ * in the same terminal (a Codex thread change, a Claude /clear), the row
79
+ * follows it: a queued message is for the pane, not for a conversation
80
+ * that is no longer there. Saved by the caller's next state change. */
81
+ private validate;
72
82
  private attempt;
73
83
  /** Coalesced: the Hook calls this every 5 s whether or not the last tick
74
84
  * finished, and queuing each behind the lock would hold every enqueue and
@@ -22,7 +22,8 @@ export const HAND_OFF_RETENTION_MS = 7 * DAY;
22
22
  /** At most this many rows stay on disk; the oldest settled rows go first. */
23
23
  export const HAND_OFF_MAX_ROWS = 512;
24
24
  const settled = (row) => row.state !== "queued" && row.state !== "attempting";
25
- const sameTarget = (a, b) => ["server", "workspace", "tab", "pane", "source", "session"].every(key => a[key] === b[key]);
25
+ /** A row follows its pane's conversation, so it is found by pane. */
26
+ const samePane = (a, b) => ["server", "workspace", "tab", "pane", "source"].every(key => a[key] === b[key]);
26
27
  /** A durable outbox on the receiving Hook. Persist 'attempting' before input,
27
28
  * so a crash in the input/ack gap recovers as uncertain, never as a retry.
28
29
  * Tombstones are retained for HAND_OFF_RETENTION_MS, so a retried delivery id
@@ -127,30 +128,52 @@ export class HandOffQueue {
127
128
  const data = queuedHandOffSchema.parse(input), id = data.deliveryId ?? randomUUID().replaceAll("-", "");
128
129
  const prior = await this.read(id);
129
130
  if (prior) {
130
- if (!sameTarget(prior.target, data.target) || prior.text !== data.text)
131
+ if (!samePane(prior.target, data.target) || prior.text !== data.text)
131
132
  throw new BridgeError(409, "This message id was already used for a different message.");
132
133
  return { ...this.reply(prior), replayed: true };
133
134
  }
134
- const pane = await this.options.validate(data.target);
135
+ const row = { ...data, deliveryId: id };
136
+ const pane = await this.validate(row);
135
137
  if (typeof pane.terminal_id !== "string")
136
138
  throw new BridgeError(409, "This agent has no terminal binding.");
137
139
  const at = new Date(this.now()).toISOString();
138
- const row = { ...data, deliveryId: id, terminal: pane.terminal_id, state: "queued", createdAt: at, updatedAt: at };
140
+ Object.assign(row, { terminal: pane.terminal_id, state: "queued", createdAt: at, updatedAt: at });
139
141
  await this.save(row);
140
142
  // Older queued messages take precedence even if this one arrives at idle.
141
- const ahead = (await this.prune(await this.rows())).some(other => other.deliveryId !== id && sameTarget(other.target, row.target) && other.state === "queued");
143
+ const ahead = (await this.prune(await this.rows())).some(other => other.deliveryId !== id && samePane(other.target, row.target) && other.state === "queued");
142
144
  if (!ahead)
143
145
  await this.attempt(row, pane);
144
146
  return this.reply(row);
145
147
  });
146
148
  }
147
149
  status(id, target) {
148
- return this.serial(async () => { const row = await this.read(id); if (!row || !sameTarget(row.target, target))
150
+ return this.serial(async () => { const row = await this.read(id); if (!row || !samePane(row.target, target))
149
151
  throw new BridgeError(404, "No hand-off with this id and target."); return this.reply(row); });
150
152
  }
153
+ /** Validates the row's target. When the pane's conversation was replaced
154
+ * in the same terminal (a Codex thread change, a Claude /clear), the row
155
+ * follows it: a queued message is for the pane, not for a conversation
156
+ * that is no longer there. Saved by the caller's next state change. */
157
+ async validate(row) {
158
+ try {
159
+ return await this.options.validate(row.target);
160
+ }
161
+ catch (error) {
162
+ if (!(error instanceof BridgeError) || error.status !== 409 || !this.options.current)
163
+ throw error;
164
+ const now = await this.options.current(row.target).catch(() => undefined);
165
+ if (!now || now.session === row.target.session || (row.terminal && now.terminal !== row.terminal))
166
+ throw error;
167
+ row.target = { ...row.target, session: now.session };
168
+ return await this.options.validate(row.target);
169
+ }
170
+ }
151
171
  async attempt(row, pane) {
172
+ const session = row.target.session;
152
173
  try {
153
- pane ??= await this.options.validate(row.target);
174
+ pane ??= await this.validate(row);
175
+ if (row.target.session !== session)
176
+ await this.save(row);
154
177
  }
155
178
  catch (error) {
156
179
  if (error instanceof BridgeError && [404, 409].includes(error.status)) {
@@ -207,7 +230,7 @@ export class HandOffQueue {
207
230
  const attempted = new Set(), remote = [];
208
231
  for (const row of rows)
209
232
  if (row.state === "queued") {
210
- const key = JSON.stringify(row.target);
233
+ const key = JSON.stringify({ ...row.target, session: undefined });
211
234
  if (attempted.has(key))
212
235
  continue;
213
236
  attempted.add(key);
@@ -255,10 +278,10 @@ export class HandOffQueue {
255
278
  * A new hand-off cannot be accepted between the pending check and closure. */
256
279
  whenNoPending(target, close) {
257
280
  return this.serial(async () => {
258
- if ((await this.rows()).some(row => sameTarget(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state)))
281
+ if ((await this.rows()).some(row => samePane(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state)))
259
282
  return { ok: true, closed: false };
260
283
  return close();
261
284
  });
262
285
  }
263
- hasPending(target) { return this.serial(async () => (await this.rows()).some(row => sameTarget(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state))); }
286
+ hasPending(target) { return this.serial(async () => (await this.rows()).some(row => samePane(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state))); }
264
287
  }
@@ -1,7 +1,17 @@
1
- import { runBridge } from "./command.js";
2
1
  import { nonInteractiveGitEnv } from "../utils-helpers.js";
3
2
  Object.assign(process.env, nonInteractiveGitEnv());
4
- runBridge(process.argv.slice(2), PHREN_HOOK_VERSION).then(code => {
3
+ async function main() {
4
+ const args = process.argv.slice(2);
5
+ // sudo starts a fresh process for every password attempt. It needs only
6
+ // the askpass client, rather than initializing the Hook server and tools.
7
+ if (args[0] === "askpass") {
8
+ const { askpass } = await import("./sudo.js");
9
+ return askpass(args[1]);
10
+ }
11
+ const { runBridge } = await import("./command.js");
12
+ return runBridge(args, PHREN_HOOK_VERSION);
13
+ }
14
+ main().then(code => {
5
15
  process.exitCode = code;
6
16
  }).catch(error => {
7
17
  console.error(error instanceof Error ? error.message : "Phren Hook failed.");