@phren/cli 0.3.69 → 0.3.70

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.
@@ -167,8 +167,6 @@ async function loginKind(home, last) {
167
167
  * account fits. Logged with the reason.
168
168
  */
169
169
  export async function pickClaudeAccount(what, scope = {}, computer = "this computer", now = Date.now()) {
170
- if (!usageReader)
171
- return undefined;
172
170
  const project = scopeRule(scope);
173
171
  const last = await readLastKnown();
174
172
  // This computer's accounts.yaml roles and pools, read here rather than only through the inventory: a slow or
@@ -232,7 +230,7 @@ export async function pickClaudeAccount(what, scope = {}, computer = "this compu
232
230
  if (!policyApplies(policyRooms([]), rules)) {
233
231
  if (policyRooms([]).filter(room => room.usable !== false).length < 2)
234
232
  return fallback();
235
- const usage = await within(2_500, usageReader());
233
+ const usage = usageReader ? await within(2_500, usageReader()) : undefined;
236
234
  if (!usage)
237
235
  return fallback();
238
236
  const { choice, skipped } = chooseAccount(claudeRooms(inventory, usage, now), limitedBy(await readAccountLimits(now), computer));
@@ -245,8 +243,8 @@ export async function pickClaudeAccount(what, scope = {}, computer = "this compu
245
243
  logger.info("accounts", `${what}: no Claude account has room (${skipped.join("; ")}); launching under default.`);
246
244
  return undefined;
247
245
  }
248
- // Unknown room ranks last, so a slow usage read still leaves the policy to choose.
249
- const usage = await within(2_500, usageReader()) ?? [];
246
+ // Unknown room ranks last: an absent or slow usage reader must not bypass pools or roles.
247
+ const usage = (usageReader ? await within(2_500, usageReader()) : undefined) ?? [];
250
248
  const { choice, skipped } = choosePolicyAccount(policyRooms(usage), rules, limitedBy(await readAccountLimits(now), computer));
251
249
  if (!choice) {
252
250
  throw new BridgeError(409, `No Claude account on ${computer} may do this work${skipped.length ? `: ${skipped.join("; ")}` : ""}.`.slice(0, 500), { code: "account_pool", skipped });
@@ -63,8 +63,13 @@ export declare class AgentHooks {
63
63
  * `questions` carries a released AskUserQuestion's normalized question set
64
64
  * with the index currently being answered. */
65
65
  private terminalPrompts;
66
- /** The last time each pane's terminal lines were read for a dialog, so a
67
- * status tick reads them at most once per three seconds per pane. */
66
+ /** Shared confirmed observations for the card and status readers. */
67
+ private dialogObservations;
68
+ private dialogFlights;
69
+ private dialogEpochs;
70
+ private questionBoundaries;
71
+ questionResolution(target: Target): number | undefined;
72
+ confirmedTerminalDialog(target: Target): boolean;
68
73
  private dialogReads;
69
74
  /** Panes whose last read terminal line is a password prompt, so the status
70
75
  * frame can offer the phone's secret sheet only when one is really asking. */
@@ -182,11 +187,12 @@ export declare class AgentHooks {
182
187
  /** Claude Code's auto-mode fallback, opencode and Codex draw a numbered
183
188
  * dialog in the pane with no PermissionRequest hook behind it. While the pane
184
189
  * waits with nothing else to ask, read its last lines (at most once per
185
- * three seconds per pane) and publish the dialog as a terminal choice; drop
190
+ * discovery window per pane) and publish the dialog as a terminal choice; drop
186
191
  * it when the pane leaves waiting or the dialog lines vanish. A remembered
187
- * Claude request is retired only after its dialog was seen and disappeared. The same
192
+ * Claude request keeps its initial draw grace, then follows the current screen. The same
188
193
  * read notes whether the terminal is reading a password. */
189
194
  syncTerminalDialog(target: Target, active: boolean): Promise<void>;
195
+ private readTerminalDialog;
190
196
  /** Resolve a phone option identifier. Real shortcuts retain their key path;
191
197
  * keyless rows are reached and verified before returning Enter to the route. */
192
198
  dialogAnswerKeys<K extends string>(target: Target, keys: readonly K[]): Promise<(K | "Enter")[]>;
@@ -20,14 +20,14 @@ import { ensureGrant, findGrant } from "./grants.js";
20
20
  import { ApprovalPushService } from "./push.js";
21
21
  import { approvalSummary, paneProject } from "./approval-summary.js";
22
22
  import { computerDisplayName } from "./pair.js";
23
- import { intervalFromEnv } from "./limits.js";
23
+ import { confirmDialogRead, DIALOG_READ_MS } from "./dialog-observation.js";
24
24
  import { answerClaudeQuestionDialog, claudeQuestionDialog } from "./claude-question-dialog.js";
25
- import { answeredQuestionInput, numberedDialog, opencodePermissionDialog, passwordLine, permissionPrompt, questionChoice, terminalChoice, terminalQuestions, visibleTerminalChoice } from "./terminal-choice.js";
25
+ import { answeredQuestionInput, claudePermissionDialog, opencodePermissionDialog, passwordLine, permissionPrompt, questionChoice, terminalChoice, terminalQuestions, visibleTerminalChoice } from "./terminal-choice.js";
26
26
  import { directoryNames, opencodeApprovalFile, opencodeRequest, readOpencodeRequest } from "./opencode-approvals.js";
27
27
  import { allowOpencodeToolEverywhere } from "./opencode-permissions.js";
28
28
  import { ApprovalWatchLeases, bindingPath, localSocket, PushBindingStore } from "./agent-hook-stores.js";
29
29
  import { notePaneTranscript, paneAccountKey } from "./pane-accounts.js";
30
- import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js";
30
+ import { eventStatus, notePaneStatus, screenDialogState, settleBlockedPane } from "./pane-status.js";
31
31
  import { checkpointBoundary, checkpointActivityArrived } from "./checkpoints.js";
32
32
  import { normalizedPromptEntryId } from "./prompt-identity.js";
33
33
  import { claudeInputState } from "./claude-input-state.js";
@@ -45,6 +45,9 @@ export { permissionPrompt, terminalChoice, visibleTerminalChoice } from "./termi
45
45
  export { appServerApproval, appServerDecision, conductorCall, OPENCODE_APPROVAL_OPTIONS, opencodePermissionReply } from "./agent-hook-asks.js";
46
46
  export { agentHook, stopFacts, withinToolBudget } from "./agent-hook-callback.js";
47
47
  export { ApprovalWatchLeases, PushBindingStore, recordedSession } from "./agent-hook-stores.js";
48
+ // Target objects arrive through several readers with different property order.
49
+ const targetKey = (target) => target ? JSON.stringify({ server: target.server,
50
+ workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source, session: target.session }) : "";
48
51
  const APPROVAL_SWEEP_MS = 2_000;
49
52
  /** How recent the Herdr snapshots must be for the poll to trust "no opencode pane". */
50
53
  const OPENCODE_PANES_FRESH_MS = 15_000;
@@ -55,10 +58,8 @@ const APPROVAL_HOLD_MS = (() => {
55
58
  const value = Number(process.env.PHREN_APPROVAL_HOLD_MS);
56
59
  return Number.isFinite(value) && value >= 50 && value <= 60_000 ? Math.floor(value) : 55_000;
57
60
  })();
58
- /** A pane's terminal dialog is read at most once per this window. */
59
61
  /** Lines read to find Claude's question dialog: its tab bar sits above the whole question. */
60
62
  const QUESTION_READ_LINES = 120;
61
- const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000);
62
63
  /** How long a pushed terminal dialog can be answered from its notification. */
63
64
  const DIALOG_PUSH_MS = 10 * 60_000;
64
65
  const FANOUT_SWEEP_MS = 5_000;
@@ -201,8 +202,16 @@ export class AgentHooks {
201
202
  * `questions` carries a released AskUserQuestion's normalized question set
202
203
  * with the index currently being answered. */
203
204
  terminalPrompts = new Map();
204
- /** The last time each pane's terminal lines were read for a dialog, so a
205
- * status tick reads them at most once per three seconds per pane. */
205
+ /** Shared confirmed observations for the card and status readers. */
206
+ dialogObservations = new Map();
207
+ dialogFlights = new Map();
208
+ dialogEpochs = new Map();
209
+ questionBoundaries = new Map();
210
+ questionResolution(target) { return this.questionBoundaries.get(targetKey(target)); }
211
+ confirmedTerminalDialog(target) {
212
+ const key = targetKey(target), entry = this.terminalPrompts.get(key);
213
+ return !!entry && (entry.dialog ? this.dialogObservations.get(key)?.confirmed === true : entry.dialogSeenAt !== undefined);
214
+ }
206
215
  dialogReads = new Map();
207
216
  /** Panes whose last read terminal line is a password prompt, so the status
208
217
  * frame can offer the phone's secret sheet only when one is really asking. */
@@ -466,8 +475,8 @@ export class AgentHooks {
466
475
  servedQuestion(target) {
467
476
  if (target.source !== "opencode")
468
477
  return undefined;
469
- const key = JSON.stringify(target);
470
- const held = [...this.servedQuestions.values()].find(value => value.target && JSON.stringify(value.target) === key);
478
+ const key = targetKey(target);
479
+ const held = [...this.servedQuestions.values()].find(value => value.target && targetKey(value.target) === key);
471
480
  if (!held)
472
481
  return undefined;
473
482
  const title = held.questions[0].question;
@@ -504,8 +513,8 @@ export class AgentHooks {
504
513
  /** The phone's answers to a served pane's question: the labels it chose
505
514
  * (and a typed answer) per question, for exactly the questions it shows. */
506
515
  async answerServedQuestion(target, questions, answers) {
507
- const key = JSON.stringify(target);
508
- const found = [...this.servedQuestions.entries()].find(([, value]) => value.target && JSON.stringify(value.target) === key);
516
+ const key = targetKey(target);
517
+ const found = [...this.servedQuestions.entries()].find(([, value]) => value.target && targetKey(value.target) === key);
509
518
  if (!found)
510
519
  throw new BridgeError(409, "This question is no longer pending.");
511
520
  const [id, held] = found;
@@ -536,8 +545,8 @@ export class AgentHooks {
536
545
  const entry = servedPane(target.server, target.pane);
537
546
  if (!entry)
538
547
  return false;
539
- const client = paneClient(entry), key = JSON.stringify(target);
540
- const question = [...this.servedQuestions.entries()].find(([, value]) => value.target && JSON.stringify(value.target) === key);
548
+ const client = paneClient(entry), key = targetKey(target);
549
+ const question = [...this.servedQuestions.entries()].find(([, value]) => value.target && targetKey(value.target) === key);
541
550
  const escape = keys.length > 0 && keys.every(value => value === "Escape");
542
551
  if (question && escape) {
543
552
  await client.rejectQuestion(question[0]).catch(() => { throw new BridgeError(409, "This question is no longer pending."); });
@@ -650,7 +659,7 @@ export class AgentHooks {
650
659
  catch { /* The archive sweep must never break the Hook. */ }
651
660
  }
652
661
  watch(target) {
653
- const key = JSON.stringify(target);
662
+ const key = targetKey(target);
654
663
  this.watching.set(key, (this.watching.get(key) || 0) + 1);
655
664
  return () => { const n = (this.watching.get(key) || 1) - 1; if (n)
656
665
  this.watching.set(key, n);
@@ -701,7 +710,7 @@ export class AgentHooks {
701
710
  const questions = tool === "AskUserQuestion" ? terminalQuestions(body.input) : undefined;
702
711
  const choice = questions ? questionChoice(questions, 0) : terminalChoice(body.input);
703
712
  const summary = approvalSummary({ tool, input: body.input, question: tool === "AskUserQuestion" });
704
- this.terminalPrompts.set(JSON.stringify(target), { tool, input: body.input, dialogSeenAt, toolUseId: typeof body.toolUseId === "string" ? body.toolUseId : undefined,
713
+ this.terminalPrompts.set(targetKey(target), { tool, input: body.input, dialogSeenAt, toolUseId: typeof body.toolUseId === "string" ? body.toolUseId : undefined,
705
714
  message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}),
706
715
  ...summary,
707
716
  ...(questions ? { questions, questionIndex: 0 } : {}), at: Date.now() });
@@ -711,7 +720,7 @@ export class AgentHooks {
711
720
  /** The request the agent is showing in its terminal, if one fell through
712
721
  * in the last fifteen minutes; the caller only asks while the pane waits. */
713
722
  terminalPrompt(target) {
714
- const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
723
+ const key = targetKey(target), entry = this.terminalPrompts.get(key);
715
724
  if (!entry)
716
725
  return undefined;
717
726
  if (Date.now() - entry.at > 900_000) {
@@ -721,25 +730,50 @@ export class AgentHooks {
721
730
  return { toolName: entry.tool, message: entry.message, ...(entry.request ? { request: entry.request } : {}), ...(entry.choice ? { choice: entry.choice } : {}),
722
731
  ...(entry.questions?.length ? { questions: entry.questions, questionIndex: entry.questionIndex ?? 0 } : {}), at: new Date(entry.at).toISOString() };
723
732
  }
724
- clearTerminalPrompt(target) { this.terminalPrompts.delete(JSON.stringify(target)); }
733
+ clearTerminalPrompt(target) {
734
+ const key = targetKey(target);
735
+ this.terminalPrompts.delete(key);
736
+ this.dialogObservations.delete(key);
737
+ this.dialogEpochs.delete(key);
738
+ }
725
739
  /** True while the pane's own terminal is reading a password. */
726
- passwordPrompt(target) { return this.passwords.get(JSON.stringify(target)) === true; }
740
+ passwordPrompt(target) { return this.passwords.get(targetKey(target)) === true; }
727
741
  /** Claude Code's auto-mode fallback, opencode and Codex draw a numbered
728
742
  * dialog in the pane with no PermissionRequest hook behind it. While the pane
729
743
  * waits with nothing else to ask, read its last lines (at most once per
730
- * three seconds per pane) and publish the dialog as a terminal choice; drop
744
+ * discovery window per pane) and publish the dialog as a terminal choice; drop
731
745
  * it when the pane leaves waiting or the dialog lines vanish. A remembered
732
- * Claude request is retired only after its dialog was seen and disappeared. The same
746
+ * Claude request keeps its initial draw grace, then follows the current screen. The same
733
747
  * read notes whether the terminal is reading a password. */
734
748
  async syncTerminalDialog(target, active) {
735
- const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
749
+ const key = targetKey(target);
750
+ if (!active)
751
+ this.clearTerminalPrompt(target);
752
+ const running = this.dialogFlights.get(key);
753
+ if (running)
754
+ return running;
755
+ const work = this.readTerminalDialog(target, active);
756
+ this.dialogFlights.set(key, work);
757
+ try {
758
+ await work;
759
+ }
760
+ finally {
761
+ if (this.dialogFlights.get(key) === work)
762
+ this.dialogFlights.delete(key);
763
+ }
764
+ }
765
+ async readTerminalDialog(target, active) {
766
+ const key = targetKey(target), entry = this.terminalPrompts.get(key), epoch = {};
767
+ this.dialogEpochs.set(key, epoch);
768
+ while (this.dialogEpochs.size > 128)
769
+ this.dialogEpochs.delete(this.dialogEpochs.keys().next().value);
736
770
  // A served OpenCode pane lists its asks over its API; its screen is not read.
737
771
  if (target.source === "opencode" && servedPane(target.server, target.pane)) {
738
772
  if (entry)
739
773
  this.terminalPrompts.delete(key);
740
774
  return;
741
775
  }
742
- const held = [...this.pending.values()].find(p => JSON.stringify(p.target) === key);
776
+ const held = [...this.pending.values()].find(p => targetKey(p.target) === key);
743
777
  // A held Codex permission can already have real choices in its pane.
744
778
  // Refresh those before publishing the approval, even while it is held.
745
779
  // One the Hook's own app-server asked is answered over RPC, not in the pane.
@@ -789,11 +823,18 @@ export class AgentHooks {
789
823
  this.dialogReads.delete(this.dialogReads.keys().next().value);
790
824
  // Unlike optional display text, a failed read cannot prove a dialog is gone.
791
825
  const text = await terminalProvider().readScreen(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi: true, timeoutMs: 2_000 }).catch(() => undefined);
792
- if (text === undefined)
826
+ if (text === undefined) {
827
+ if (!this.dialogObservations.get(key)?.confirmed)
828
+ this.dialogObservations.delete(key);
829
+ return;
830
+ }
831
+ if (this.dialogEpochs.get(key) !== epoch)
793
832
  return;
794
833
  // A tall question has its tab bar above the 40 lines: look further up, for it only.
795
834
  const tall = target.source === "claude" && /Chat about this/.test(text) && !claudeQuestionDialog(text)
796
835
  ? await this.paneLines(target, true, QUESTION_READ_LINES).catch(() => "") : "";
836
+ if (this.dialogEpochs.get(key) !== epoch)
837
+ return;
797
838
  const asking = target.source === "claude" && !!(claudeQuestionDialog(text) || (tall && claudeQuestionDialog(tall)));
798
839
  this.passwords.set(key, passwordLine(text));
799
840
  while (this.passwords.size > 128)
@@ -803,15 +844,39 @@ export class AgentHooks {
803
844
  // a numbered dialog: its digits advance on their own and a trailing
804
845
  // Enter would land on the next tab.
805
846
  if (asking) {
847
+ this.dialogObservations.delete(key);
806
848
  if (entry && !question)
807
849
  this.terminalPrompts.delete(key);
808
850
  return;
809
851
  }
810
852
  if (question) {
811
- this.terminalPrompts.delete(key);
853
+ if (screenDialogState(target.source, text) === "gone")
854
+ this.terminalPrompts.delete(key);
812
855
  return;
813
856
  }
814
- const dialog = await this.screenDialog(target, text);
857
+ let dialog = await this.screenDialog(target, text);
858
+ if (dialog && !held && (!entry || entry.dialog) && this.dialogObservations.get(key)?.signature !== JSON.stringify(dialog)) {
859
+ const confirmation = await confirmDialogRead(async () => {
860
+ const screen = await terminalProvider().readScreen(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi: true, timeoutMs: 400 });
861
+ return { screen, dialog: await this.screenDialog(target, screen) };
862
+ }, () => this.dialogEpochs.get(key) === epoch);
863
+ if (confirmation === undefined)
864
+ return;
865
+ dialog = confirmation.dialog;
866
+ if (!dialog && screenDialogState(target.source, confirmation.screen) !== "gone")
867
+ return;
868
+ }
869
+ else if (!dialog && screenDialogState(target.source, text) !== "gone")
870
+ return;
871
+ if (this.dialogEpochs.get(key) !== epoch)
872
+ return;
873
+ const signature = JSON.stringify(dialog);
874
+ if (dialog)
875
+ this.dialogObservations.set(key, { signature, confirmed: true });
876
+ else
877
+ this.dialogObservations.delete(key);
878
+ while (this.dialogObservations.size > 128)
879
+ this.dialogObservations.delete(this.dialogObservations.keys().next().value);
815
880
  if (target.source === "claude") {
816
881
  // A callback or a new ask may have replaced this request during the read.
817
882
  if ((held && ![...this.pending.values()].includes(held)) || this.terminalPrompts.get(key) !== entry)
@@ -819,7 +884,7 @@ export class AgentHooks {
819
884
  const observed = held ?? entry;
820
885
  if (dialog?.title && observed)
821
886
  observed.dialogSeenAt ??= now;
822
- if (!dialog?.title && observed?.dialogSeenAt !== undefined && now - observed.dialogSeenAt >= 3_000) {
887
+ if (!dialog?.title && observed && (observed.dialogSeenAt !== undefined || (!held && now - entry.at >= 3_000))) {
823
888
  for (const [action, pending] of this.pending) {
824
889
  if (pending !== held)
825
890
  continue;
@@ -838,10 +903,10 @@ export class AgentHooks {
838
903
  this.terminalPrompts.delete(key);
839
904
  this.dropDialogPush(key);
840
905
  this.dropForwardedDialog(key);
841
- settleBlockedPane(target.server, target.pane);
906
+ settleBlockedPane(target.server, target.pane, 0);
842
907
  return;
843
908
  }
844
- // Never settle a held or remembered ask before its dialog was observed.
909
+ // A live hook hold is authoritative until resolved; released asks get a draw grace.
845
910
  if (held || (!dialog?.title && observed))
846
911
  return;
847
912
  }
@@ -880,7 +945,7 @@ export class AgentHooks {
880
945
  /** Resolve a phone option identifier. Real shortcuts retain their key path;
881
946
  * keyless rows are reached and verified before returning Enter to the route. */
882
947
  async dialogAnswerKeys(target, keys) {
883
- const entry = this.terminalPrompts.get(JSON.stringify(target));
948
+ const entry = this.terminalPrompts.get(targetKey(target));
884
949
  const choice = entry?.choice;
885
950
  const option = choice?.options.find(option => keys.includes(option.key));
886
951
  if (choice && option?.hasKey === false) {
@@ -956,7 +1021,7 @@ export class AgentHooks {
956
1021
  * tab, a changed question or a missed key stops it with nothing stray
957
1022
  * typed. A finished set clears the remembered question. */
958
1023
  async answerClaudeQuestions(target, questions, answers, options = {}) {
959
- const key = JSON.stringify(target);
1024
+ const key = targetKey(target);
960
1025
  await answerClaudeQuestionDialog({
961
1026
  // A tall question (long text, many options) pushes its tab bar out of 40 lines.
962
1027
  read: () => this.paneLines(target, true, QUESTION_READ_LINES),
@@ -976,7 +1041,7 @@ export class AgentHooks {
976
1041
  * the same verified steps and submit after the last. False when the
977
1042
  * prompt is not a remembered question, so the keys take the usual path. */
978
1043
  async answerReleasedQuestion(target, keys) {
979
- const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
1044
+ const key = targetKey(target), entry = this.terminalPrompts.get(key);
980
1045
  if (target.source !== "claude" || !entry?.questions?.length)
981
1046
  return false;
982
1047
  const digits = keys.filter(value => /^[1-9]$/.test(value));
@@ -991,15 +1056,15 @@ export class AgentHooks {
991
1056
  return true;
992
1057
  }
993
1058
  startCompacting(target) {
994
- this.compactingSince.set(JSON.stringify(target), Date.now());
1059
+ this.compactingSince.set(targetKey(target), Date.now());
995
1060
  while (this.compactingSince.size > 64)
996
1061
  this.compactingSince.delete(this.compactingSince.keys().next().value);
997
1062
  }
998
- stopCompacting(target) { this.compactingSince.delete(JSON.stringify(target)); }
1063
+ stopCompacting(target) { this.compactingSince.delete(targetKey(target)); }
999
1064
  /** True while Claude Code is compacting `target`; a boundary older than ten
1000
1065
  * minutes is stale, so a missed SessionStart cannot pin the state forever. */
1001
1066
  compacting(target) {
1002
- const key = JSON.stringify(target), at = this.compactingSince.get(key);
1067
+ const key = targetKey(target), at = this.compactingSince.get(key);
1003
1068
  if (at === undefined)
1004
1069
  return false;
1005
1070
  if (Date.now() - at > 600_000) {
@@ -1009,20 +1074,20 @@ export class AgentHooks {
1009
1074
  return true;
1010
1075
  }
1011
1076
  menuOpened(target, command) {
1012
- this.menus.set(JSON.stringify(target), { at: Date.now(), ...(command ? { command } : {}) });
1077
+ this.menus.set(targetKey(target), { at: Date.now(), ...(command ? { command } : {}) });
1013
1078
  while (this.menus.size > 64)
1014
1079
  this.menus.delete(this.menus.keys().next().value);
1015
1080
  }
1016
1081
  menuOpen(target) {
1017
- const entry = this.menus.get(JSON.stringify(target));
1082
+ const entry = this.menus.get(targetKey(target));
1018
1083
  return entry !== undefined && Date.now() - entry.at < 30_000;
1019
1084
  }
1020
1085
  /** The bare slash command that opened this pane's current menu window. */
1021
1086
  menuCommand(target) {
1022
- const entry = this.menus.get(JSON.stringify(target));
1087
+ const entry = this.menus.get(targetKey(target));
1023
1088
  return entry && Date.now() - entry.at < 30_000 ? entry.command : undefined;
1024
1089
  }
1025
- menuClosed(target) { this.menus.delete(JSON.stringify(target)); }
1090
+ menuClosed(target) { this.menus.delete(targetKey(target)); }
1026
1091
  /** The pane with its colors, for dialogs whose cursor is only a color. */
1027
1092
  paneAnsi(target) {
1028
1093
  return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi: false, format: "ansi", timeoutMs: 2_000 });
@@ -1038,7 +1103,7 @@ export class AgentHooks {
1038
1103
  * seconds is left open as the visible prompt, published as the terminal
1039
1104
  * choice the phone draws as a question card. Runs at most once per window. */
1040
1105
  async walkMenuConfirmation(target) {
1041
- const key = JSON.stringify(target), entry = this.menus.get(key);
1106
+ const key = targetKey(target), entry = this.menus.get(key);
1042
1107
  if (!entry || entry.confirmationAttempted)
1043
1108
  return entry ? { menuClosed: false } : { menuClosed: true };
1044
1109
  entry.confirmationAttempted = true;
@@ -1067,7 +1132,7 @@ export class AgentHooks {
1067
1132
  }
1068
1133
  }
1069
1134
  approval(target) {
1070
- const pending = [...this.pending.entries()].find(([, p]) => JSON.stringify(p.target) === JSON.stringify(target));
1135
+ const pending = [...this.pending.entries()].find(([, p]) => targetKey(p.target) === targetKey(target));
1071
1136
  if (pending)
1072
1137
  return { actionId: pending[0], toolName: pending[1].tool, title: pending[1].choice?.title ?? pending[1].title, message: pending[1].message,
1073
1138
  request: pending[1].request,
@@ -1085,7 +1150,7 @@ export class AgentHooks {
1085
1150
  message: worker.request.message, request: worker.requestLine, expiresAt: worker.request.expiresAt, options: OPENCODE_APPROVAL_OPTIONS } : undefined;
1086
1151
  }
1087
1152
  opencodeApproval(target) {
1088
- const held = [...this.opencode.values()].find(value => !value.fanout && JSON.stringify(value.target) === JSON.stringify(target));
1153
+ const held = [...this.opencode.values()].find(value => !value.fanout && targetKey(value.target) === targetKey(target));
1089
1154
  if (held)
1090
1155
  return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, request: held.requestLine, expiresAt: held.request.expiresAt, options: OPENCODE_APPROVAL_OPTIONS };
1091
1156
  const request = opencodeRequest(target.session);
@@ -1095,8 +1160,8 @@ export class AgentHooks {
1095
1160
  }
1096
1161
  /** Live fan-out worker asks shown on this parent conversation, oldest first. */
1097
1162
  fanoutHeld(target) {
1098
- const key = JSON.stringify(target);
1099
- return [...this.opencode.values()].filter(value => value.fanout && value.target && JSON.stringify(value.target) === key
1163
+ const key = targetKey(target);
1164
+ return [...this.opencode.values()].filter(value => value.fanout && value.target && targetKey(value.target) === key
1100
1165
  && value.expiresAt > Date.now() && opencodeRequest(value.fanout.session)?.id === value.request.id);
1101
1166
  }
1102
1167
  pendingPanes(server, state) {
@@ -1165,15 +1230,15 @@ export class AgentHooks {
1165
1230
  // answered with the pane's own keys.
1166
1231
  if (id.startsWith("dialog-") || (!this.pending.has(id) && await this.releasedHoldDialog(id))) {
1167
1232
  const dialog = this.dialogActions.get(id);
1168
- if (!dialog || JSON.stringify(dialog.target) !== JSON.stringify(target))
1233
+ if (!dialog || targetKey(dialog.target) !== targetKey(target))
1169
1234
  throw new BridgeError(409, "This approval is no longer pending.");
1170
1235
  if (updatedInput !== undefined || !["approve", "deny"].includes(String(decision)))
1171
1236
  throw new BridgeError(400, "The approval answer is not valid.");
1172
1237
  await this.answerDialog(id, decision);
1173
- this.dropForwardedDialog(JSON.stringify(target));
1238
+ this.dropForwardedDialog(targetKey(target));
1174
1239
  return;
1175
1240
  }
1176
- const worker = [...this.opencode.entries()].find(([, held]) => held.fanout?.actionId === id && JSON.stringify(held.target) === JSON.stringify(target));
1241
+ const worker = [...this.opencode.entries()].find(([, held]) => held.fanout?.actionId === id && targetKey(held.target) === targetKey(target));
1177
1242
  if (worker) {
1178
1243
  if (updatedInput !== undefined)
1179
1244
  throw new BridgeError(400, "Answers go with an approval.");
@@ -1185,7 +1250,7 @@ export class AgentHooks {
1185
1250
  if (served?.served) {
1186
1251
  if (updatedInput !== undefined)
1187
1252
  throw new BridgeError(400, "Answers go with an approval.");
1188
- if (!served.target || JSON.stringify(served.target) !== JSON.stringify(target))
1253
+ if (!served.target || targetKey(served.target) !== targetKey(target))
1189
1254
  throw new BridgeError(409, "This approval is no longer pending.");
1190
1255
  await validateTarget(target);
1191
1256
  await this.answerServed(id, served, decision);
@@ -1212,7 +1277,7 @@ export class AgentHooks {
1212
1277
  return;
1213
1278
  }
1214
1279
  const entry = this.pending.get(id);
1215
- if (!entry || JSON.stringify(entry.target) !== JSON.stringify(target))
1280
+ if (!entry || targetKey(entry.target) !== targetKey(target))
1216
1281
  throw new BridgeError(409, "This approval is no longer pending.");
1217
1282
  const grantAnswer = entry.conductor && (decision === "allow-project" || decision === "allow-everywhere") ? decision : undefined;
1218
1283
  if (grantAnswer && !entry.conductor)
@@ -1252,7 +1317,7 @@ export class AgentHooks {
1252
1317
  * once instead of leaving the card up until the 55-second timer. */
1253
1318
  releaseChoice(target) {
1254
1319
  for (const [id, entry] of this.pending) {
1255
- if (!entry.choice || JSON.stringify(entry.target) !== JSON.stringify(target))
1320
+ if (!entry.choice || targetKey(entry.target) !== targetKey(target))
1256
1321
  continue;
1257
1322
  this.pending.delete(id);
1258
1323
  this.dropPushBindings(id);
@@ -1268,7 +1333,7 @@ export class AgentHooks {
1268
1333
  cancelHeldQuestion(target) {
1269
1334
  let cancelled = false;
1270
1335
  for (const [id, entry] of this.pending) {
1271
- if (entry.tool !== "AskUserQuestion" || JSON.stringify(entry.target) !== JSON.stringify(target))
1336
+ if (entry.tool !== "AskUserQuestion" || targetKey(entry.target) !== targetKey(target))
1272
1337
  continue;
1273
1338
  this.pending.delete(id);
1274
1339
  this.dropPushBindings(id);
@@ -1360,23 +1425,23 @@ export class AgentHooks {
1360
1425
  const target = await resolve(pane).catch(() => undefined);
1361
1426
  if (!target)
1362
1427
  continue;
1363
- const key = JSON.stringify(target);
1428
+ const key = targetKey(target);
1364
1429
  // tmux can already report working after its own dialog read. Keep
1365
1430
  // reconciling tracked Claude asks until our read confirms disappearance.
1366
1431
  if (!isWaiting && !this.terminalPrompts.has(key) && !this.releasedHolds.has(key)
1367
- && ![...this.pending.values()].some(held => JSON.stringify(held.target) === key))
1432
+ && ![...this.pending.values()].some(held => targetKey(held.target) === key))
1368
1433
  continue;
1369
1434
  waiting.add(key);
1370
1435
  // A served OpenCode pane's asks were pushed as its server listed them.
1371
1436
  if (target.source === "opencode" && servedPane(target.server, target.pane))
1372
1437
  continue;
1373
1438
  // Held asks were pushed on arrival; Claude still needs its dialog reconciled.
1374
- if (target.source !== "claude" && [...this.pending.values()].some(held => JSON.stringify(held.target) === key))
1439
+ if (target.source !== "claude" && [...this.pending.values()].some(held => targetKey(held.target) === key))
1375
1440
  continue;
1376
1441
  // Read the dialog even with no push device: the overview marks the
1377
1442
  // tab as needing permission from it, and the phone answers it there.
1378
1443
  await this.syncTerminalDialog(target, true).catch(() => { });
1379
- if (!this.push.available || [...this.pending.values()].some(held => JSON.stringify(held.target) === key))
1444
+ if (!this.push.available || [...this.pending.values()].some(held => targetKey(held.target) === key))
1380
1445
  continue;
1381
1446
  const entry = this.terminalPrompts.get(key);
1382
1447
  const title = entry?.dialog || entry?.released ? entry.choice?.title : undefined;
@@ -1475,7 +1540,7 @@ export class AgentHooks {
1475
1540
  return { actionId, tool: clip(held.toolName, 200) ?? "action", ...(title ? { title } : {}), ...(request ? { request } : {}),
1476
1541
  ...(pending ? { requestKind: pending.requestKind } : {}), ...(expiresAt ? { expiresAt } : {}), ...(conductor ? { conductor } : {}), ...(pushed ? { pushed: true } : {}) };
1477
1542
  }
1478
- const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
1543
+ const key = targetKey(target), entry = this.terminalPrompts.get(key);
1479
1544
  const title = entry && (entry.dialog || entry.released) ? entry.choice?.title : undefined;
1480
1545
  if (!entry?.choice || !title)
1481
1546
  return undefined;
@@ -1561,8 +1626,8 @@ export class AgentHooks {
1561
1626
  * color; the other fallbacks number rows without a key in the label. */
1562
1627
  async screenDialog(target, text) {
1563
1628
  return ["codex", "copilot"].includes(target.source) ? visibleTerminalChoice(text)
1564
- : target.source === "opencode" ? opencodePermissionDialog(await this.paneAnsi(target))?.choice ?? numberedDialog(text)
1565
- : numberedDialog(text);
1629
+ : target.source === "opencode" ? opencodePermissionDialog(await this.paneAnsi(target))?.choice
1630
+ : claudePermissionDialog(text);
1566
1631
  }
1567
1632
  /** Approve picks the dialog's yes/allow row (else its first), Deny its
1568
1633
  * no/deny row (else Escape), typed as the pane's own keys. */
@@ -1572,7 +1637,7 @@ export class AgentHooks {
1572
1637
  throw new BridgeError(409, "This approval is no longer pending.");
1573
1638
  // Claimed before any await: a second answer for the same dialog gets a 409 instead of typing the keys twice.
1574
1639
  this.dialogActions.delete(action);
1575
- const key = JSON.stringify(dialog.target);
1640
+ const key = targetKey(dialog.target);
1576
1641
  try {
1577
1642
  await validateTarget(dialog.target, false, true);
1578
1643
  }
@@ -1603,14 +1668,21 @@ export class AgentHooks {
1603
1668
  * dialog is gone: the call it held ran (its PostToolUse), the turn ended or
1604
1669
  * took a new prompt, or the agent asked something else. */
1605
1670
  settleTerminalAnswered(target, body) {
1606
- const event = String(body.event), key = JSON.stringify(target);
1671
+ const event = String(body.event), key = targetKey(target);
1672
+ this.dialogEpochs.delete(key);
1673
+ this.dialogObservations.delete(key);
1674
+ if (["Stop", "UserPromptSubmit"].includes(event)) {
1675
+ this.questionBoundaries.set(key, Date.now());
1676
+ while (this.questionBoundaries.size > 128)
1677
+ this.questionBoundaries.delete(this.questionBoundaries.keys().next().value);
1678
+ }
1607
1679
  const matches = (held) => held.toolUseId && typeof body.toolUseId === "string" && body.toolUseId
1608
1680
  ? held.toolUseId === body.toolUseId : held.tool === body.tool && isDeepStrictEqual(held.input, body.input);
1609
1681
  const settled = (held) => ["Stop", "UserPromptSubmit"].includes(event)
1610
1682
  || (event === "PermissionRequest" && !matches(held))
1611
1683
  || (event === "PostToolUse" && matches(held));
1612
1684
  for (const [action, held] of this.pending) {
1613
- if (held.appServer || JSON.stringify(held.target) !== key || !settled(held))
1685
+ if (held.appServer || targetKey(held.target) !== key || !settled(held))
1614
1686
  continue;
1615
1687
  clearTimeout(held.timer);
1616
1688
  this.pending.delete(action);
@@ -1620,7 +1692,7 @@ export class AgentHooks {
1620
1692
  held.response.end("{}");
1621
1693
  }
1622
1694
  const hold = this.releasedHolds.get(key), remembered = this.terminalPrompts.get(key);
1623
- if (remembered && !remembered.questions?.length && settled({ tool: remembered.tool, input: remembered.input, toolUseId: remembered.toolUseId })) {
1695
+ if (remembered && settled({ tool: remembered.tool, input: remembered.input, toolUseId: remembered.toolUseId })) {
1624
1696
  this.terminalPrompts.delete(key);
1625
1697
  if (hold) {
1626
1698
  this.dropPushBindings(hold.action);
@@ -1640,7 +1712,7 @@ export class AgentHooks {
1640
1712
  if (!shown || this.closed)
1641
1713
  return;
1642
1714
  // Replayed after a reconnect: the card stays, answered through the new connection.
1643
- const known = [...this.pending.values()].find(entry => entry.appServer?.requestId === request.requestId && JSON.stringify(entry.target) === JSON.stringify(target));
1715
+ const known = [...this.pending.values()].find(entry => entry.appServer?.requestId === request.requestId && targetKey(entry.target) === targetKey(target));
1644
1716
  if (known?.appServer) {
1645
1717
  known.appServer.answer = answer;
1646
1718
  return;
@@ -1680,7 +1752,7 @@ export class AgentHooks {
1680
1752
  /** Another client (the pane's TUI) answered the request, or this one declined it. */
1681
1753
  codexResolved(target, requestId) {
1682
1754
  for (const [action, entry] of this.pending) {
1683
- if (entry.appServer?.requestId !== requestId || JSON.stringify(entry.target) !== JSON.stringify(target))
1755
+ if (entry.appServer?.requestId !== requestId || targetKey(entry.target) !== targetKey(target))
1684
1756
  continue;
1685
1757
  this.pending.delete(action);
1686
1758
  this.dropPushBindings(action);
@@ -1916,7 +1988,7 @@ export class AgentHooks {
1916
1988
  return;
1917
1989
  }
1918
1990
  if (body.event === "PermissionRequest")
1919
- this.terminalPrompts.delete(JSON.stringify(target));
1991
+ this.terminalPrompts.delete(targetKey(target));
1920
1992
  if (body.event === "PermissionRequest" && ruleEffect !== "always-ask") {
1921
1993
  const conductor = conductorCall(String(body.tool || "action"), body.input);
1922
1994
  if (conductor) {
@@ -1942,7 +2014,7 @@ export class AgentHooks {
1942
2014
  return;
1943
2015
  }
1944
2016
  if (body.event !== "PermissionRequest" || target.source === "copilot"
1945
- || (!this.watching.has(JSON.stringify(target)) && !this.overview.has(target.server) && !this.push.available && !this.dispatchLeased(target))) {
2017
+ || (!this.watching.has(targetKey(target)) && !this.overview.has(target.server) && !this.push.available && !this.dispatchLeased(target))) {
1946
2018
  if (body.event === "PermissionRequest")
1947
2019
  this.rememberTerminalPrompt(target, body);
1948
2020
  res.end("{}");
@@ -1955,9 +2027,9 @@ export class AgentHooks {
1955
2027
  return;
1956
2028
  }
1957
2029
  const action = randomUUID();
1958
- this.dialogReads.delete(JSON.stringify(target));
2030
+ this.dialogReads.delete(targetKey(target));
1959
2031
  const conductor = body.event === "PermissionRequest" ? conductorCall(String(body.tool || "action"), body.input) : undefined;
1960
- const locallyWatched = this.watching.has(JSON.stringify(target)) || this.overview.has(target.server) || this.dispatchLeased(target);
2032
+ const locallyWatched = this.watching.has(targetKey(target)) || this.overview.has(target.server) || this.dispatchLeased(target);
1961
2033
  const cwd = typeof body.cwd === "string" && path.isAbsolute(body.cwd) ? body.cwd : await trustedDirectory(pane).catch(() => undefined);
1962
2034
  // When the hold ends the request stays in the terminal. A pushed
1963
2035
  // notification keeps working: its binding waits for the pane's dialog
@@ -1970,7 +2042,7 @@ export class AgentHooks {
1970
2042
  this.rememberTerminalPrompt(target, body, dialogSeenAt);
1971
2043
  // The id was already handed out (phone card, push, dispatcher): it keeps answering the dialog.
1972
2044
  const pushed = this.pushedHolds.get(action);
1973
- this.releasedHolds.set(JSON.stringify(target), { action, expiresAt: pushed ?? Date.now() + DIALOG_PUSH_MS, pushed: pushed !== undefined });
2045
+ this.releasedHolds.set(targetKey(target), { action, expiresAt: pushed ?? Date.now() + DIALOG_PUSH_MS, pushed: pushed !== undefined });
1974
2046
  this.pushedHolds.delete(action);
1975
2047
  res.end("{}");
1976
2048
  }, APPROVAL_HOLD_MS);
@@ -0,0 +1,7 @@
1
+ import type { PermissionModeName } from "./permission-mode.js";
2
+ /** Claude's permission mode from the footer line its TUI draws under the
3
+ * composer. The transcript lags it: a `permission-mode` row is written only
4
+ * when a prompt is submitted, and a fresh session has no file yet. The line may
5
+ * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. A
6
+ * mode the footer does not mark is `undefined`: "manual mode on" is default. */
7
+ export declare function claudeFooterMode(screen: string): PermissionModeName | undefined;