@phren/cli 0.3.67 → 0.3.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/bridge/agent-hook-callback.js +11 -2
  2. package/dist/bridge/agent-hooks.d.ts +11 -1
  3. package/dist/bridge/agent-hooks.js +259 -40
  4. package/dist/bridge/changes.d.ts +2 -2
  5. package/dist/bridge/changes.js +11 -9
  6. package/dist/bridge/checkpoints.d.ts +24 -0
  7. package/dist/bridge/checkpoints.js +423 -0
  8. package/dist/bridge/claude-input-state.d.ts +14 -0
  9. package/dist/bridge/claude-input-state.js +58 -0
  10. package/dist/bridge/claude-queue.js +5 -2
  11. package/dist/bridge/claude-suggestion.d.ts +3 -0
  12. package/dist/bridge/claude-suggestion.js +10 -0
  13. package/dist/bridge/codex-threads.d.ts +7 -1
  14. package/dist/bridge/codex-threads.js +185 -56
  15. package/dist/bridge/conversation-search.d.ts +20 -0
  16. package/dist/bridge/conversation-search.js +928 -0
  17. package/dist/bridge/git-watch.d.ts +46 -0
  18. package/dist/bridge/git-watch.js +351 -0
  19. package/dist/bridge/git-worktree-remove.d.ts +44 -0
  20. package/dist/bridge/git-worktree-remove.js +140 -0
  21. package/dist/bridge/git-worktrees.d.ts +14 -0
  22. package/dist/bridge/git-worktrees.js +7 -3
  23. package/dist/bridge/git-write-policy.js +1 -1
  24. package/dist/bridge/gitboy-webhooks.d.ts +3 -1
  25. package/dist/bridge/gitboy-webhooks.js +26 -2
  26. package/dist/bridge/herdr.d.ts +6 -1
  27. package/dist/bridge/herdr.js +56 -10
  28. package/dist/bridge/hook-fast.js +13 -1
  29. package/dist/bridge/input-classification.d.ts +33 -0
  30. package/dist/bridge/input-classification.js +84 -0
  31. package/dist/bridge/pane-status.d.ts +3 -3
  32. package/dist/bridge/pane-status.js +16 -8
  33. package/dist/bridge/prompt-deliveries.d.ts +30 -4
  34. package/dist/bridge/prompt-deliveries.js +365 -13
  35. package/dist/bridge/prompt-identity.d.ts +8 -0
  36. package/dist/bridge/prompt-identity.js +15 -0
  37. package/dist/bridge/request-origin.js +2 -1
  38. package/dist/bridge/schedule-events.d.ts +17 -0
  39. package/dist/bridge/schedule-events.js +53 -0
  40. package/dist/bridge/schedule-format.d.ts +22 -2
  41. package/dist/bridge/schedule-format.js +40 -5
  42. package/dist/bridge/schedule-update.js +2 -1
  43. package/dist/bridge/schedule-watch.js +15 -5
  44. package/dist/bridge/schedules.d.ts +9 -0
  45. package/dist/bridge/schedules.js +120 -7
  46. package/dist/bridge/server-pane-routes.d.ts +7 -8
  47. package/dist/bridge/server-pane-routes.js +186 -82
  48. package/dist/bridge/server-routes.d.ts +26 -2
  49. package/dist/bridge/server-routes.js +180 -56
  50. package/dist/bridge/server-stream.js +66 -15
  51. package/dist/bridge/server.js +25 -7
  52. package/dist/bridge/session-activity.d.ts +49 -4
  53. package/dist/bridge/session-activity.js +47 -0
  54. package/dist/bridge/session-evidence.d.ts +18 -0
  55. package/dist/bridge/session-evidence.js +72 -0
  56. package/dist/bridge/session-seen.d.ts +23 -0
  57. package/dist/bridge/session-seen.js +69 -0
  58. package/dist/bridge/tab-activity.d.ts +26 -1
  59. package/dist/bridge/tab-activity.js +64 -9
  60. package/dist/bridge/terminal-resolve.d.ts +20 -0
  61. package/dist/bridge/terminal-resolve.js +145 -0
  62. package/dist/bridge/terminal-tmux.d.ts +8 -3
  63. package/dist/bridge/terminal-tmux.js +59 -7
  64. package/dist/bridge/transcript-claude.d.ts +12 -2
  65. package/dist/bridge/transcript-claude.js +91 -13
  66. package/dist/bridge/transcript-index.d.ts +4 -2
  67. package/dist/bridge/transcript-index.js +6 -5
  68. package/dist/bridge/transcript-preview.d.ts +16 -1
  69. package/dist/bridge/transcript-preview.js +171 -27
  70. package/dist/bridge/transcripts.d.ts +41 -1
  71. package/dist/bridge/transcripts.js +181 -23
  72. package/dist/bridge/turn-queue-pane.d.ts +6 -0
  73. package/dist/bridge/turn-queue-pane.js +30 -0
  74. package/dist/bridge/turn-queue.d.ts +86 -0
  75. package/dist/bridge/turn-queue.js +280 -0
  76. package/dist/bridge/turn-records.d.ts +18 -0
  77. package/dist/bridge/turn-records.js +77 -5
  78. package/dist/bridge-hook.mjs +7074 -3173
  79. package/dist/cli/config-shared.js +2 -1
  80. package/dist/cli/schedules.js +6 -1
  81. package/dist/content/secrets.js +1 -1
  82. package/dist/modules/registry.js +12 -11
  83. package/package.json +1 -1
@@ -10,6 +10,8 @@ import { terminalPaneFromEnv } from "./terminal.js";
10
10
  import { briefId, DISPATCH_ID_ENV } from "./launch-brief.js";
11
11
  import { CODEX_SERVER_ENV, codexServerId } from "./codex-servers.js";
12
12
  import { localSocket } from "./agent-hook-stores.js";
13
+ import { claudePromptEntryId } from "./prompt-identity.js";
14
+ import { claudeCallbackFacts, classifyClaudeInput } from "./input-classification.js";
13
15
  /** The agent side of the Hook's callbacks: `hook <source>` reads the agent's
14
16
  * payload and posts it to the daemon's local socket (agent-hooks.ts). */
15
17
  /** A background task id as Claude Code writes them (an agent id, a shell id). */
@@ -83,7 +85,7 @@ export async function withinToolBudget(event, work, elapsed = () => performance.
83
85
  }
84
86
  async function forwardHook(source, target, event, value, left) {
85
87
  const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
86
- if (!modules.has("hook") || (event.endsWith("ToolUse") && !modules.has("git")))
88
+ if (!modules.has("hook"))
87
89
  return;
88
90
  // Codex 0.157 runs hooks inside its shared app-server daemon, whose pane
89
91
  // variables belong to whichever pane first started it.
@@ -98,10 +100,17 @@ async function forwardHook(source, target, event, value, left) {
98
100
  // daemon's variables belong to another pane, so it sends none.
99
101
  const dispatchId = !daemon && (event === "SessionStart" || event === "UserPromptSubmit") && briefId.safeParse(process.env[DISPATCH_ID_ENV]).success
100
102
  ? process.env[DISPATCH_ID_ENV] : undefined;
101
- const data = JSON.stringify({ target, event, ...(daemon ? { daemon: true } : {}), ...(autoReview ? { autoReview: true } : {}), ...(dispatchId ? { dispatchId } : {}),
103
+ const promptEntryId = source === "claude" && event === "UserPromptSubmit" ? claudePromptEntryId(value.prompt_id) : undefined;
104
+ // A background notification, a teammate message or a harness envelope is not
105
+ // the owner asking something new. Classify it here, from the bounded prompt
106
+ // alone: Claude does not put transcript provenance in the hook payload.
107
+ const promptInput = source === "claude" && event === "UserPromptSubmit" ? classifyClaudeInput({ text: value.prompt, ...claudeCallbackFacts(value) }) : undefined;
108
+ const data = JSON.stringify({ target, event, ...(source === "claude" ? claudeCallbackFacts(value) : {}), ...(daemon ? { daemon: true } : {}), ...(autoReview ? { autoReview: true } : {}), ...(dispatchId ? { dispatchId } : {}),
102
109
  ...(source === "claude" && typeof value.transcript_path === "string" ? { transcript: value.transcript_path.slice(0, 4096) } : {}),
103
110
  tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
111
+ ...(promptInput && promptInput.category !== "owner" ? { inputCategory: promptInput.category, inputReason: promptInput.reason } : {}),
104
112
  ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
113
+ ...(promptEntryId ? { promptEntryId } : {}),
105
114
  ...(event === "SessionStart" && typeof value.source === "string" ? { startSource: value.source.slice(0, 32) } : {}),
106
115
  ...(event === "Stop" ? stopFacts(value) : {}) });
107
116
  await new Promise(resolve => {
@@ -43,6 +43,14 @@ export interface ForwardedApproval {
43
43
  export declare class AgentHooks {
44
44
  readonly push: ApprovalPushService;
45
45
  private modules?;
46
+ private deferredSubmissions;
47
+ private deferSubmission;
48
+ private retrySubmission;
49
+ /** Streams can reconcile a newly landed row before consulting its old Stop. */
50
+ reconcileSubmissions(target: Target): Promise<void>;
51
+ private resolveSubmission;
52
+ /** Wake the Hook-held prompt queue after a recorded Stop. */
53
+ onTurnStopped?: () => void;
46
54
  readonly changes: ToolChanges;
47
55
  private pending;
48
56
  /** Phone messages Phren typed into a pane, until a conversation there
@@ -162,6 +170,8 @@ export declare class AgentHooks {
162
170
  /** The conversation's own turn events, for dispatch returns (turn-records.ts).
163
171
  * A failed write never fails the agent's callback. */
164
172
  private recordTurn;
173
+ /** Raw facts come only from the conversation the pane is verified to show. */
174
+ private inputState;
165
175
  private rememberTerminalPrompt;
166
176
  /** The request the agent is showing in its terminal, if one fell through
167
177
  * in the last fifteen minutes; the caller only asks while the pane waits. */
@@ -174,7 +184,7 @@ export declare class AgentHooks {
174
184
  * waits with nothing else to ask, read its last lines (at most once per
175
185
  * three seconds per pane) and publish the dialog as a terminal choice; drop
176
186
  * it when the pane leaves waiting or the dialog lines vanish. A remembered
177
- * permission request that is not a dialog keeps the slot untouched. The same
187
+ * Claude request is retired only after its dialog was seen and disappeared. The same
178
188
  * read notes whether the terminal is reading a password. */
179
189
  syncTerminalDialog(target: Target, active: boolean): Promise<void>;
180
190
  /** Resolve a phone option identifier. Real shortcuts retain their key path;
@@ -1,7 +1,7 @@
1
1
  import { approvalRuleContext, approvalRuleEffect } from "./approval-rules.js";
2
2
  import { recordedConductor } from "./conductor-role.js";
3
3
  import { conductorBrief, conductorContext } from "./conductor-context.js";
4
- import { disabledHint } from "../modules/registry.js";
4
+ import { isDeepStrictEqual } from "node:util";
5
5
  import { logger } from "../logger.js";
6
6
  import { createServer } from "node:http";
7
7
  import { mkdir, readFile, chmod, unlink, lstat } from "node:fs/promises";
@@ -28,7 +28,12 @@ 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
30
  import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js";
31
- import { noteTurn as recordTurn } from "./turn-records.js";
31
+ import { checkpointBoundary, checkpointActivityArrived } from "./checkpoints.js";
32
+ import { normalizedPromptEntryId } from "./prompt-identity.js";
33
+ import { claudeInputState } from "./claude-input-state.js";
34
+ import { targetTranscriptPath } from "./transcripts.js";
35
+ import { classifyClaudeInput, parseInputCategory } from "./input-classification.js";
36
+ import { noteTurn as recordTurn, readTurn, turnPhase } from "./turn-records.js";
32
37
  import { PromptDeliveries } from "./prompt-deliveries.js";
33
38
  import { countTick } from "./metrics.js";
34
39
  import { briefId, briefIdInPrompt, briefLabel, recordBriefArrival } from "./launch-brief.js";
@@ -89,6 +94,101 @@ function projectField(cwd) {
89
94
  export class AgentHooks {
90
95
  push;
91
96
  modules;
97
+ deferredSubmissions = new Map();
98
+ deferSubmission(target, pane, body, record, previous, pids) {
99
+ const key = `${target.server}:${target.pane}:${record.seq}`;
100
+ this.deferredSubmissions.set(key, { target, pane: { ...pane }, body: { ...body }, pids: [...pids], seq: record.seq, at: record.at, previous, until: Date.now() + 30_000, busy: false });
101
+ while (this.deferredSubmissions.size > 64) {
102
+ const oldest = this.deferredSubmissions.keys().next().value;
103
+ clearTimeout(this.deferredSubmissions.get(oldest)?.timer);
104
+ this.deferredSubmissions.delete(oldest);
105
+ }
106
+ this.retrySubmission(key);
107
+ }
108
+ retrySubmission(key) {
109
+ const pending = this.deferredSubmissions.get(key);
110
+ if (!pending)
111
+ return;
112
+ pending.timer = setTimeout(() => { void this.resolveSubmission(key); }, 250);
113
+ pending.timer.unref();
114
+ }
115
+ /** Streams can reconcile a newly landed row before consulting its old Stop. */
116
+ async reconcileSubmissions(target) {
117
+ for (const [key, pending] of this.deferredSubmissions) {
118
+ if (pending.target.server === target.server && pending.target.pane === target.pane && pending.target.session === target.session)
119
+ await this.resolveSubmission(key);
120
+ }
121
+ }
122
+ async resolveSubmission(key) {
123
+ const pending = this.deferredSubmissions.get(key);
124
+ if (!pending || pending.busy)
125
+ return;
126
+ if (Date.now() > pending.until) {
127
+ clearTimeout(pending.timer);
128
+ this.deferredSubmissions.delete(key);
129
+ return;
130
+ }
131
+ pending.busy = true;
132
+ clearTimeout(pending.timer);
133
+ try {
134
+ const { target, body } = pending;
135
+ const pane = await validateTarget(target, false, false);
136
+ const current = await readTurn(target.server, target.pane);
137
+ if (!pane || pane.terminal_id !== pending.pane.terminal_id || pane.agent !== target.source
138
+ || !current || current.terminal !== pane.terminal_id || current.session !== target.session
139
+ || current.source !== target.source || !current.prompt
140
+ || current.prompt.seq < pending.previous || current.prompt.seq >= pending.seq) {
141
+ this.deferredSubmissions.delete(key);
142
+ return;
143
+ }
144
+ const processes = await terminalProvider().processes(target.server, target.pane);
145
+ if (!processes.foregroundPids.some(pid => pending.pids.includes(pid))) {
146
+ this.deferredSubmissions.delete(key);
147
+ return;
148
+ }
149
+ const evidence = await this.inputState(target, typeof body.prompt === "string" ? body.prompt : undefined);
150
+ if (!evidence?.input)
151
+ return;
152
+ if (evidence.input.category !== "owner") {
153
+ this.deferredSubmissions.delete(key);
154
+ return;
155
+ }
156
+ const dispatch = briefId.safeParse(body.dispatchId).success ? String(body.dispatchId)
157
+ : typeof body.prompt === "string" ? briefIdInPrompt(body.prompt) : undefined;
158
+ if (this.deferredSubmissions.get(key) !== pending)
159
+ return;
160
+ const recorded = await this.recordTurn(target, pane, body, dispatch, evidence.input, false, { seq: pending.seq, at: pending.at, previous: pending.previous });
161
+ this.deferredSubmissions.delete(key);
162
+ if (!recorded)
163
+ return;
164
+ const latest = await readTurn(target.server, target.pane);
165
+ if (!latest || latest.terminal !== pane.terminal_id || latest.session !== target.session
166
+ || latest.source !== target.source || latest.prompt?.seq !== recorded.prompt?.seq)
167
+ return;
168
+ const status = turnPhase(latest).phase === "working" ? "working" : "idle";
169
+ const binding = object(JSON.parse(await readFile(bindingPath(target.server, target.pane), "utf8").catch(() => "{}")));
170
+ if (binding.terminal === pane.terminal_id && binding.session === target.session) {
171
+ await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ ...binding, status, event: status === "working" ? "UserPromptSubmit" : "Stop" }));
172
+ }
173
+ notePaneStatus(target.server, target.pane, String(pane.terminal_id), status);
174
+ if (typeof body.prompt === "string")
175
+ await this.deliveries.submitted(target, body.prompt.slice(0, 65_536));
176
+ if (status === "working") {
177
+ this.settleTerminalAnswered(target, body);
178
+ this.stopCompacting(target);
179
+ }
180
+ if (dispatch)
181
+ await recordBriefArrival(dispatch, "UserPromptSubmit", target).catch(() => undefined);
182
+ }
183
+ catch { /* Retry transient discovery and I/O failures within the bounded window. */ }
184
+ finally {
185
+ pending.busy = false;
186
+ if (this.deferredSubmissions.get(key) === pending)
187
+ this.retrySubmission(key);
188
+ }
189
+ }
190
+ /** Wake the Hook-held prompt queue after a recorded Stop. */
191
+ onTurnStopped;
92
192
  changes = new ToolChanges();
93
193
  pending = new Map();
94
194
  /** Phone messages Phren typed into a pane, until a conversation there
@@ -559,23 +659,49 @@ export class AgentHooks {
559
659
  }
560
660
  /** The conversation's own turn events, for dispatch returns (turn-records.ts).
561
661
  * A failed write never fails the agent's callback. */
562
- async recordTurn(target, pane, body, dispatch) {
662
+ async recordTurn(target, pane, body, dispatch, input, notificationStop = false, resolvePrompt) {
563
663
  if (typeof pane.terminal_id !== "string")
564
664
  return;
565
- await recordTurn(target.server, target.pane, { event: String(body.event), terminal: pane.terminal_id, source: target.source, session: target.session,
665
+ const recorded = await recordTurn(target.server, target.pane, { event: String(body.event), terminal: pane.terminal_id, source: target.source, session: target.session,
566
666
  ...(dispatch ? { dispatch } : {}),
667
+ ...(input ? { input: input.category } : {}),
668
+ ...(resolvePrompt ? { resolvePrompt } : {}),
669
+ ...(notificationStop ? { notificationStop: true } : {}),
567
670
  ...(body.event === "SessionStart" && typeof body.startSource === "string" ? { start: body.startSource } : {}),
568
671
  ...(typeof body.background === "number" ? { background: body.background } : {}),
569
672
  ...(body.event === "Stop" && Array.isArray(body.backgroundTasks) ? { backgroundTasks: body.backgroundTasks } : {}),
570
673
  ...(typeof body.reply === "string" ? { reply: body.reply } : {}),
571
674
  ...(body.event === "Stop" && typeof body.cwd === "string" ? { cwd: body.cwd } : {}) }).catch(() => undefined);
675
+ const cwd = typeof body.cwd === "string" ? body.cwd : pane.foreground_cwd || pane.cwd;
676
+ // A notification's callback is not a prompt checkpoint, and its Stop does
677
+ // not capture the foreground turn's boundary.
678
+ const automaticInput = input !== undefined && input.category !== "owner";
679
+ if (this.modules?.has("git") !== false && recorded && !notificationStop && !automaticInput && typeof cwd === "string") {
680
+ checkpointBoundary(cwd, target, String(body.event), recorded.prompt?.seq ?? recorded.seq, input?.category === "owner" || input === undefined ? (typeof body.prompt === "string" ? body.prompt : "") : "", target.source === "claude" && body.event === "UserPromptSubmit" ? normalizedPromptEntryId(body.promptEntryId) : undefined, body.event === "UserPromptSubmit" ? recorded.prompt?.at ?? recorded.at : recorded.at);
681
+ }
682
+ return recorded;
572
683
  }
573
- rememberTerminalPrompt(target, body) {
684
+ /** Raw facts come only from the conversation the pane is verified to show. */
685
+ async inputState(target, submitted, executionId) {
686
+ if (target.source !== "claude")
687
+ return undefined;
688
+ let file;
689
+ try {
690
+ file = await targetTranscriptPath(target);
691
+ }
692
+ catch {
693
+ return undefined;
694
+ }
695
+ // A verified transcript that cannot yet be read is still a correlation
696
+ // source: retain the old owner until a bounded deferred read succeeds.
697
+ return claudeInputState(file, submitted, executionId).catch(() => ({ recovery: [] }));
698
+ }
699
+ rememberTerminalPrompt(target, body, dialogSeenAt) {
574
700
  const tool = String(body.tool || "action").slice(0, 200);
575
701
  const questions = tool === "AskUserQuestion" ? terminalQuestions(body.input) : undefined;
576
702
  const choice = questions ? questionChoice(questions, 0) : terminalChoice(body.input);
577
703
  const summary = approvalSummary({ tool, input: body.input, question: tool === "AskUserQuestion" });
578
- this.terminalPrompts.set(JSON.stringify(target), { tool, input: body.input,
704
+ this.terminalPrompts.set(JSON.stringify(target), { tool, input: body.input, dialogSeenAt, toolUseId: typeof body.toolUseId === "string" ? body.toolUseId : undefined,
579
705
  message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}),
580
706
  ...summary,
581
707
  ...(questions ? { questions, questionIndex: 0 } : {}), at: Date.now() });
@@ -603,7 +729,7 @@ export class AgentHooks {
603
729
  * waits with nothing else to ask, read its last lines (at most once per
604
730
  * three seconds per pane) and publish the dialog as a terminal choice; drop
605
731
  * it when the pane leaves waiting or the dialog lines vanish. A remembered
606
- * permission request that is not a dialog keeps the slot untouched. The same
732
+ * Claude request is retired only after its dialog was seen and disappeared. The same
607
733
  * read notes whether the terminal is reading a password. */
608
734
  async syncTerminalDialog(target, active) {
609
735
  const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
@@ -647,7 +773,7 @@ export class AgentHooks {
647
773
  }
648
774
  // A released permission request that carried its own choices keeps them;
649
775
  // one without (a Bash or MCP call) reads the pane's rows below.
650
- if (!question && entry && !entry.dialog && entry.choice && !entry.released)
776
+ if (target.source !== "claude" && !question && entry && !entry.dialog && entry.choice && !entry.released)
651
777
  return;
652
778
  if (!active) {
653
779
  if (entry)
@@ -661,7 +787,10 @@ export class AgentHooks {
661
787
  this.dialogReads.set(key, now);
662
788
  while (this.dialogReads.size > 128)
663
789
  this.dialogReads.delete(this.dialogReads.keys().next().value);
664
- const text = await this.paneLines(target);
790
+ // Unlike optional display text, a failed read cannot prove a dialog is gone.
791
+ 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)
793
+ return;
665
794
  // A tall question has its tab bar above the 40 lines: look further up, for it only.
666
795
  const tall = target.source === "claude" && /Chat about this/.test(text) && !claudeQuestionDialog(text)
667
796
  ? await this.paneLines(target, true, QUESTION_READ_LINES).catch(() => "") : "";
@@ -683,6 +812,39 @@ export class AgentHooks {
683
812
  return;
684
813
  }
685
814
  const dialog = await this.screenDialog(target, text);
815
+ if (target.source === "claude") {
816
+ // A callback or a new ask may have replaced this request during the read.
817
+ if ((held && ![...this.pending.values()].includes(held)) || this.terminalPrompts.get(key) !== entry)
818
+ return;
819
+ const observed = held ?? entry;
820
+ if (dialog?.title && observed)
821
+ observed.dialogSeenAt ??= now;
822
+ if (!dialog?.title && observed?.dialogSeenAt !== undefined && now - observed.dialogSeenAt >= 3_000) {
823
+ for (const [action, pending] of this.pending) {
824
+ if (pending !== held)
825
+ continue;
826
+ clearTimeout(pending.timer);
827
+ this.pending.delete(action);
828
+ this.pushedHolds.delete(action);
829
+ this.dropPushBindings(action);
830
+ if (!pending.response.destroyed)
831
+ pending.response.end("{}");
832
+ }
833
+ const released = this.releasedHolds.get(key);
834
+ if (released) {
835
+ this.dropPushBindings(released.action);
836
+ this.releasedHolds.delete(key);
837
+ }
838
+ this.terminalPrompts.delete(key);
839
+ this.dropDialogPush(key);
840
+ this.dropForwardedDialog(key);
841
+ settleBlockedPane(target.server, target.pane);
842
+ return;
843
+ }
844
+ // Never settle a held or remembered ask before its dialog was observed.
845
+ if (held || (!dialog?.title && observed))
846
+ return;
847
+ }
686
848
  if (entry && !entry.dialog) {
687
849
  // The permission the pane still shows after its hook let go: keep the
688
850
  // request's own details and answer it with the dialog's rows, so the
@@ -711,7 +873,7 @@ export class AgentHooks {
711
873
  }
712
874
  this.terminalPrompts.set(key, { tool: "Question", message: dialog.title,
713
875
  ...approvalSummary({ tool: "Question", message: dialog.title }),
714
- choice: dialog, dialog: true, at: now });
876
+ choice: dialog, dialog: true, ...(target.source === "claude" ? { dialogSeenAt: now } : {}), at: now });
715
877
  while (this.terminalPrompts.size > 64)
716
878
  this.terminalPrompts.delete(this.terminalPrompts.keys().next().value);
717
879
  }
@@ -1192,23 +1354,29 @@ export class AgentHooks {
1192
1354
  async observeWaitingPanes(server, panes, resolve) {
1193
1355
  const waiting = new Set();
1194
1356
  for (const pane of panes) {
1195
- if (!pane.agent || !["waiting", "blocked"].includes(String(pane.agent_status)))
1357
+ const isWaiting = ["waiting", "blocked"].includes(String(pane.agent_status));
1358
+ if (!pane.agent || (!isWaiting && pane.agent !== "claude"))
1196
1359
  continue;
1197
1360
  const target = await resolve(pane).catch(() => undefined);
1198
1361
  if (!target)
1199
1362
  continue;
1200
1363
  const key = JSON.stringify(target);
1364
+ // tmux can already report working after its own dialog read. Keep
1365
+ // reconciling tracked Claude asks until our read confirms disappearance.
1366
+ if (!isWaiting && !this.terminalPrompts.has(key) && !this.releasedHolds.has(key)
1367
+ && ![...this.pending.values()].some(held => JSON.stringify(held.target) === key))
1368
+ continue;
1201
1369
  waiting.add(key);
1202
1370
  // A served OpenCode pane's asks were pushed as its server listed them.
1203
1371
  if (target.source === "opencode" && servedPane(target.server, target.pane))
1204
1372
  continue;
1205
- // A request its own hook already holds was pushed on arrival.
1206
- if ([...this.pending.values()].some(held => JSON.stringify(held.target) === key))
1373
+ // 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))
1207
1375
  continue;
1208
1376
  // Read the dialog even with no push device: the overview marks the
1209
1377
  // tab as needing permission from it, and the phone answers it there.
1210
1378
  await this.syncTerminalDialog(target, true).catch(() => { });
1211
- if (!this.push.available)
1379
+ if (!this.push.available || [...this.pending.values()].some(held => JSON.stringify(held.target) === key))
1212
1380
  continue;
1213
1381
  const entry = this.terminalPrompts.get(key);
1214
1382
  const title = entry?.dialog || entry?.released ? entry.choice?.title : undefined;
@@ -1436,10 +1604,11 @@ export class AgentHooks {
1436
1604
  * took a new prompt, or the agent asked something else. */
1437
1605
  settleTerminalAnswered(target, body) {
1438
1606
  const event = String(body.event), key = JSON.stringify(target);
1439
- const asked = event === "PermissionRequest" ? JSON.stringify([body.tool, body.input]) : undefined;
1607
+ const matches = (held) => held.toolUseId && typeof body.toolUseId === "string" && body.toolUseId
1608
+ ? held.toolUseId === body.toolUseId : held.tool === body.tool && isDeepStrictEqual(held.input, body.input);
1440
1609
  const settled = (held) => ["Stop", "UserPromptSubmit"].includes(event)
1441
- || (event === "PermissionRequest" && JSON.stringify([held.tool, held.input]) !== asked)
1442
- || (event === "PostToolUse" && held.tool === body.tool && JSON.stringify(held.input) === JSON.stringify(body.input));
1610
+ || (event === "PermissionRequest" && !matches(held))
1611
+ || (event === "PostToolUse" && matches(held));
1443
1612
  for (const [action, held] of this.pending) {
1444
1613
  if (held.appServer || JSON.stringify(held.target) !== key || !settled(held))
1445
1614
  continue;
@@ -1451,7 +1620,7 @@ export class AgentHooks {
1451
1620
  held.response.end("{}");
1452
1621
  }
1453
1622
  const hold = this.releasedHolds.get(key), remembered = this.terminalPrompts.get(key);
1454
- if (remembered && !remembered.questions?.length && settled({ tool: remembered.tool, input: remembered.input })) {
1623
+ if (remembered && !remembered.questions?.length && settled({ tool: remembered.tool, input: remembered.input, toolUseId: remembered.toolUseId })) {
1455
1624
  this.terminalPrompts.delete(key);
1456
1625
  if (hold) {
1457
1626
  this.dropPushBindings(hold.action);
@@ -1579,11 +1748,12 @@ export class AgentHooks {
1579
1748
  return;
1580
1749
  }
1581
1750
  let target = targetSchema.parse(body.target);
1582
- if (this.modules?.has("git") === false && ["PreToolUse", "PostToolUse"].includes(String(body.event))) {
1583
- res.statusCode = 404;
1584
- res.end(JSON.stringify({ error: disabledHint("git") }));
1585
- return;
1586
- }
1751
+ const activity = eventStatus(body.event);
1752
+ // Invalidate an in-flight restore immediately, before process or
1753
+ // transcript I/O. This is a safety fence, not a prompt checkpoint or
1754
+ // an owner-turn transition; classification still gates those below.
1755
+ if (activity === "working" || activity === "blocked")
1756
+ checkpointActivityArrived(target);
1587
1757
  // A callback Codex's app-server daemon ran names the pane that started
1588
1758
  // the daemon, not the conversation's. Place it by the conversation the
1589
1759
  // Hook proves each pane shows, and never record a binding from it.
@@ -1605,20 +1775,54 @@ export class AgentHooks {
1605
1775
  const pids = (await terminalProvider().processes(target.server, target.pane)).foregroundPids;
1606
1776
  if (!pids.length)
1607
1777
  throw new Error("No foreground process");
1608
- if (!daemon && target.source === "claude")
1609
- notePaneTranscript(paneAccountKey(target.server, target.pane), body.transcript, String(pane.terminal_id ?? ""));
1610
- if (!daemon)
1611
- await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ terminal: pane.terminal_id, source: target.source,
1612
- session: target.session, pids, workspace: target.workspace, tab: target.tab, event: String(body.event).slice(0, 64), at: new Date().toISOString() }));
1613
- // A terminal that does not watch its agents (tmux) takes the agent's
1614
- // status from these events.
1778
+ // Classify a submitted prompt before any prompt-boundary side effect. A
1779
+ // notification, teammate message or harness envelope belongs to the
1780
+ // turn already running; the fast forwarder forwards the same category.
1781
+ const promptInput = target.source === "claude" && body.event === "UserPromptSubmit"
1782
+ ? classifyClaudeInput({ text: body.prompt, origin: body.origin, commandMode: body.commandMode, isMeta: body.isMeta,
1783
+ isSidechain: body.isSidechain, isCompactSummary: body.isCompactSummary, toolResult: body.toolResult,
1784
+ notificationDelivery: body.notificationDelivery, hasImage: body.hasImage === true })
1785
+ : undefined;
1786
+ const declaredInput = parseInputCategory(body.inputCategory);
1787
+ // A callback may forward the category it already applied (the fast
1788
+ // forwarder does for automatic input). A validated non-owner category
1789
+ // wins; otherwise the Hook classifies the prompt itself.
1790
+ let unresolvedPrevious;
1791
+ let classifiedInput = declaredInput && declaredInput !== "owner"
1792
+ ? { category: declaredInput, reason: `callback:${declaredInput}` } : promptInput;
1793
+ if (target.source === "claude" && body.event === "UserPromptSubmit" && classifiedInput?.category === "owner") {
1794
+ const evidence = await this.inputState(target, typeof body.prompt === "string" ? body.prompt : undefined);
1795
+ if (evidence?.input)
1796
+ classifiedInput = evidence.input;
1797
+ else if (evidence || typeof body.transcript === "string") {
1798
+ const known = await readTurn(target.server, target.pane).catch(() => undefined);
1799
+ if (known?.prompt && known.terminal === pane.terminal_id && known.session === target.session && known.source === target.source) {
1800
+ classifiedInput = { category: "internal", reason: "callback:unresolved" };
1801
+ unresolvedPrevious = known.prompt.seq;
1802
+ }
1803
+ }
1804
+ }
1805
+ const automaticPrompt = classifiedInput !== undefined && classifiedInput.category !== "owner";
1806
+ // A Stop tied to background notification traffic must not close a
1807
+ // foreground execution that is still running.
1808
+ const stopInput = classifyClaudeInput({ text: "stop", origin: body.origin, commandMode: body.commandMode });
1809
+ const backgroundStop = target.source === "claude" && body.event === "Stop"
1810
+ && (stopInput.category !== "owner" || (await this.inputState(target, undefined, typeof body.executionId === "string" ? body.executionId : undefined))?.backgroundStop === true);
1615
1811
  // Codex's automatic reviewer decides this request on its own: it is
1616
1812
  // not a question for the owner, so nothing is held, pushed or
1617
1813
  // remembered and the pane is not marked blocked. If Codex hands the
1618
1814
  // request back to the owner it draws its approval dialog, which the
1619
1815
  // waiting-pane dialog read picks up and pushes like any other.
1620
1816
  const autoReview = body.event === "PermissionRequest" && target.source === "codex" && body.autoReview === true;
1621
- const status = autoReview ? undefined : eventStatus(body.event);
1817
+ const status = autoReview || automaticPrompt || backgroundStop ? undefined : eventStatus(body.event);
1818
+ if (!daemon && target.source === "claude")
1819
+ notePaneTranscript(paneAccountKey(target.server, target.pane), body.transcript, String(pane.terminal_id ?? ""));
1820
+ if (!daemon && !automaticPrompt && !backgroundStop)
1821
+ await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ terminal: pane.terminal_id, source: target.source,
1822
+ session: target.session, pids, workspace: target.workspace, tab: target.tab, event: String(body.event).slice(0, 64),
1823
+ ...(status ? { status } : {}), ...(classifiedInput ? { inputCategory: classifiedInput.category } : {}), at: new Date().toISOString() }));
1824
+ // A terminal that does not watch its agents (tmux) takes the agent's
1825
+ // status from these events.
1622
1826
  if (status && typeof pane.terminal_id === "string")
1623
1827
  notePaneStatus(target.server, target.pane, pane.terminal_id, status);
1624
1828
  // Herdr does not watch phren-agent: a pane the Hook reported as running
@@ -1634,7 +1838,7 @@ export class AgentHooks {
1634
1838
  // id (from its environment, or the brief path in its first prompt when
1635
1839
  // Codex's shared daemon ran the hook with another pane's variables).
1636
1840
  let dispatch;
1637
- if (body.event === "SessionStart" || body.event === "UserPromptSubmit") {
1841
+ if (body.event === "SessionStart" || (body.event === "UserPromptSubmit" && !automaticPrompt)) {
1638
1842
  const named = !daemon && briefId.safeParse(body.dispatchId).success ? String(body.dispatchId) : undefined;
1639
1843
  dispatch = named ?? (typeof body.prompt === "string" ? briefIdInPrompt(body.prompt) : undefined);
1640
1844
  if (dispatch)
@@ -1646,26 +1850,37 @@ export class AgentHooks {
1646
1850
  // had taken (before thread-origin.ts) back to the TUI's thread.
1647
1851
  if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)) && target.source === "codex" && !daemon)
1648
1852
  codexServers.follow(target.server, target.pane, target.session);
1649
- this.settleTerminalAnswered(target, body);
1853
+ // A notification is not a person answering a held interaction.
1854
+ if (!automaticPrompt && !backgroundStop)
1855
+ this.settleTerminalAnswered(target, body);
1650
1856
  if (body.event === "PreCompact") {
1651
1857
  this.startCompacting(target);
1652
1858
  res.end("{}");
1653
1859
  return;
1654
1860
  }
1655
- if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)))
1861
+ if (!automaticPrompt && !backgroundStop && ["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)))
1656
1862
  this.stopCompacting(target);
1657
1863
  if (body.event === "UserPromptSubmit") {
1658
- if (typeof body.prompt === "string")
1864
+ // A notification callback never settles an unrelated phone delivery.
1865
+ if (!automaticPrompt && typeof body.prompt === "string")
1659
1866
  await this.deliveries.submitted(target, body.prompt.slice(0, 65_536));
1660
- await this.recordTurn(target, pane, body, dispatch);
1867
+ const recorded = await this.recordTurn(target, pane, body, dispatch, classifiedInput);
1868
+ if (unresolvedPrevious !== undefined && recorded)
1869
+ this.deferSubmission(target, pane, body, recorded, unresolvedPrevious, pids);
1870
+ if (automaticPrompt) {
1871
+ res.end("{}");
1872
+ return;
1873
+ }
1661
1874
  const context = this.modules?.has("conductor") === false ? undefined : await conductorContext(target, s).catch(() => undefined);
1662
1875
  res.end(JSON.stringify(context ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context } } : {}));
1663
1876
  return;
1664
1877
  }
1665
- if (body.event === "Stop")
1878
+ if (body.event === "Stop" && !backgroundStop)
1666
1879
  this.deliveries.stopped(target);
1667
1880
  if (body.event === "SessionStart" || body.event === "Stop")
1668
- await this.recordTurn(target, pane, body, dispatch);
1881
+ await this.recordTurn(target, pane, body, dispatch, classifiedInput, backgroundStop);
1882
+ if (body.event === "Stop" && !backgroundStop)
1883
+ this.onTurnStopped?.();
1669
1884
  if (body.event === "SessionStart") {
1670
1885
  const context = this.modules?.has("conductor") === false ? undefined : await conductorContext(target, s).catch(() => undefined);
1671
1886
  res.end(JSON.stringify(context ? { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context } } : {}));
@@ -1749,9 +1964,10 @@ export class AgentHooks {
1749
1964
  // and then answers that, instead of going dead with the hold.
1750
1965
  let released = false;
1751
1966
  const timer = setTimeout(() => {
1967
+ const dialogSeenAt = this.pending.get(action)?.dialogSeenAt;
1752
1968
  released = true;
1753
1969
  this.pending.delete(action);
1754
- this.rememberTerminalPrompt(target, body);
1970
+ this.rememberTerminalPrompt(target, body, dialogSeenAt);
1755
1971
  // The id was already handed out (phone card, push, dispatcher): it keeps answering the dialog.
1756
1972
  const pushed = this.pushedHolds.get(action);
1757
1973
  this.releasedHolds.set(JSON.stringify(target), { action, expiresAt: pushed ?? Date.now() + DIALOG_PUSH_MS, pushed: pushed !== undefined });
@@ -1761,7 +1977,7 @@ export class AgentHooks {
1761
1977
  const expiresAt = new Date(Date.now() + APPROVAL_HOLD_MS).toISOString();
1762
1978
  const { choice, title } = permissionPrompt(String(body.tool || "action"), body.input);
1763
1979
  const summary = approvalSummary({ tool: String(body.tool || "action"), input: body.input, cwd, question: body.tool === "AskUserQuestion" });
1764
- this.pending.set(action, { target, response: res, tool: String(body.tool || "action").slice(0, 200), input: body.input, title,
1980
+ this.pending.set(action, { target, response: res, tool: String(body.tool || "action").slice(0, 200), input: body.input, toolUseId: typeof body.toolUseId === "string" ? body.toolUseId : undefined, title,
1765
1981
  message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...summary, ...(choice ? { choice } : {}), expiresAt, timer,
1766
1982
  ...(conductor ? { conductor } : {}) });
1767
1983
  res.on("close", () => { clearTimeout(timer); this.pending.delete(action); this.pushedHolds.delete(action); if (!released)
@@ -1828,6 +2044,9 @@ export class AgentHooks {
1828
2044
  this.paneServers.tick();
1829
2045
  }
1830
2046
  close() {
2047
+ for (const pending of this.deferredSubmissions.values())
2048
+ clearTimeout(pending.timer);
2049
+ this.deferredSubmissions.clear();
1831
2050
  this.closed = true;
1832
2051
  this.sudo.close();
1833
2052
  void this.changes.close().catch(() => { });
@@ -36,7 +36,7 @@ export declare class ToolChanges {
36
36
  private controllers;
37
37
  private claims;
38
38
  private failures;
39
- /** Conversation and repository root pairs already shown that Git could not capture changes. */
39
+ /** Repository roots already shown that Git could not capture changes. */
40
40
  private reported;
41
41
  private repositories;
42
42
  private scratches;
@@ -45,7 +45,7 @@ export declare class ToolChanges {
45
45
  * time shows no changes rather than an error: a busy machine is not
46
46
  * something to act on per call, and repository Changes still has the
47
47
  * status. A broken capture (Git missing, a corrupt repository) shows on the
48
- * first call it hits in a conversation, not on every later one. A per-call
48
+ * first call it hits, until capture succeeds in that repository again. A per-call
49
49
  * limit (too many files) shows on its own call. */
50
50
  private failed;
51
51
  /** A hook callback's wall-clock cap on Git work; past it the call records