@phren/cli 0.3.10 → 0.3.12

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 (184) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanout-messages.js +2 -2
  42. package/dist/bridge/fanouts.d.ts +7 -1
  43. package/dist/bridge/fanouts.js +40 -5
  44. package/dist/bridge/folder-trust.d.ts +56 -0
  45. package/dist/bridge/folder-trust.js +195 -0
  46. package/dist/bridge/grants.d.ts +22 -1
  47. package/dist/bridge/grants.js +57 -9
  48. package/dist/bridge/hand-off.d.ts +21 -9
  49. package/dist/bridge/hand-off.js +58 -45
  50. package/dist/bridge/harness-status.d.ts +11 -0
  51. package/dist/bridge/harness-status.js +32 -0
  52. package/dist/bridge/harnesses.d.ts +39 -0
  53. package/dist/bridge/harnesses.js +65 -0
  54. package/dist/bridge/health.d.ts +2 -0
  55. package/dist/bridge/health.js +1 -1
  56. package/dist/bridge/herdr.d.ts +11 -2
  57. package/dist/bridge/herdr.js +98 -23
  58. package/dist/bridge/hook-fast.d.ts +4 -0
  59. package/dist/bridge/hook-fast.js +68 -0
  60. package/dist/bridge/install.d.ts +16 -1
  61. package/dist/bridge/install.js +88 -21
  62. package/dist/bridge/launch-brief.d.ts +96 -0
  63. package/dist/bridge/launch-brief.js +164 -0
  64. package/dist/bridge/model-switch.d.ts +3 -0
  65. package/dist/bridge/model-switch.js +17 -1
  66. package/dist/bridge/models.d.ts +8 -4
  67. package/dist/bridge/models.js +24 -8
  68. package/dist/bridge/mux-wire.d.ts +9 -0
  69. package/dist/bridge/mux-wire.js +19 -0
  70. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  71. package/dist/bridge/opencode-pane-server.js +332 -0
  72. package/dist/bridge/opencode-panes.d.ts +111 -0
  73. package/dist/bridge/opencode-panes.js +295 -0
  74. package/dist/bridge/pane-accounts.d.ts +8 -0
  75. package/dist/bridge/pane-accounts.js +46 -0
  76. package/dist/bridge/prompt-startup.d.ts +5 -0
  77. package/dist/bridge/prompt-startup.js +24 -0
  78. package/dist/bridge/protocol.d.ts +5 -0
  79. package/dist/bridge/protocol.js +4 -0
  80. package/dist/bridge/push.d.ts +5 -4
  81. package/dist/bridge/push.js +6 -4
  82. package/dist/bridge/questions.d.ts +37 -2
  83. package/dist/bridge/questions.js +158 -15
  84. package/dist/bridge/resources.d.ts +125 -0
  85. package/dist/bridge/resources.js +314 -0
  86. package/dist/bridge/schedule-format.d.ts +2 -0
  87. package/dist/bridge/schedule-format.js +3 -0
  88. package/dist/bridge/schedule-launch.d.ts +2 -1
  89. package/dist/bridge/schedule-launch.js +23 -53
  90. package/dist/bridge/schedule-watch.d.ts +10 -1
  91. package/dist/bridge/schedule-watch.js +54 -2
  92. package/dist/bridge/server-launch.d.ts +22 -5
  93. package/dist/bridge/server-launch.js +225 -29
  94. package/dist/bridge/server-overview.d.ts +8 -2
  95. package/dist/bridge/server-overview.js +26 -5
  96. package/dist/bridge/server-pane-routes.d.ts +2 -0
  97. package/dist/bridge/server-pane-routes.js +145 -15
  98. package/dist/bridge/server-routes.d.ts +11 -1
  99. package/dist/bridge/server-routes.js +195 -36
  100. package/dist/bridge/server-stream.d.ts +2 -0
  101. package/dist/bridge/server-stream.js +22 -8
  102. package/dist/bridge/server.d.ts +6 -1
  103. package/dist/bridge/server.js +47 -12
  104. package/dist/bridge/session-activity.d.ts +81 -0
  105. package/dist/bridge/session-activity.js +117 -0
  106. package/dist/bridge/session-rename.d.ts +48 -0
  107. package/dist/bridge/session-rename.js +190 -0
  108. package/dist/bridge/session-servers.js +2 -2
  109. package/dist/bridge/settings-switch.d.ts +60 -0
  110. package/dist/bridge/settings-switch.js +287 -0
  111. package/dist/bridge/speech-voice.d.ts +55 -0
  112. package/dist/bridge/speech-voice.js +132 -0
  113. package/dist/bridge/speech.d.ts +70 -11
  114. package/dist/bridge/speech.js +169 -41
  115. package/dist/bridge/terminal-herdr.js +9 -3
  116. package/dist/bridge/terminal-tmux.d.ts +3 -3
  117. package/dist/bridge/terminal-tmux.js +24 -9
  118. package/dist/bridge/terminal.d.ts +27 -4
  119. package/dist/bridge/terminal.js +8 -1
  120. package/dist/bridge/transcript-claude.js +62 -12
  121. package/dist/bridge/transcript-codex.d.ts +0 -2
  122. package/dist/bridge/transcript-codex.js +29 -4
  123. package/dist/bridge/transcript-preview.d.ts +1 -0
  124. package/dist/bridge/transcript-preview.js +24 -4
  125. package/dist/bridge/transcripts.d.ts +15 -2
  126. package/dist/bridge/transcripts.js +47 -16
  127. package/dist/bridge/turn-records.d.ts +85 -0
  128. package/dist/bridge/turn-records.js +143 -0
  129. package/dist/bridge/uploads.d.ts +3 -0
  130. package/dist/bridge/uploads.js +14 -0
  131. package/dist/bridge/usage.d.ts +73 -28
  132. package/dist/bridge/usage.js +313 -340
  133. package/dist/bridge-hook.mjs +24624 -18450
  134. package/dist/cli/claude-unmanaged.d.ts +12 -0
  135. package/dist/cli/claude-unmanaged.js +105 -0
  136. package/dist/cli/schedules.js +2 -1
  137. package/dist/cli/session-start.js +10 -1
  138. package/dist/cli/session-stop.js +9 -1
  139. package/dist/cli-registry.d.ts +2 -0
  140. package/dist/cli-registry.js +37 -5
  141. package/dist/computers/command.d.ts +6 -0
  142. package/dist/computers/command.js +152 -0
  143. package/dist/computers/mcp.d.ts +1 -0
  144. package/dist/computers/mcp.js +97 -0
  145. package/dist/computers/read.d.ts +85 -0
  146. package/dist/computers/read.js +177 -0
  147. package/dist/data/task-receipts.d.ts +19 -0
  148. package/dist/data/task-receipts.js +68 -0
  149. package/dist/data/tasks.js +4 -1
  150. package/dist/entrypoint.js +10 -0
  151. package/dist/fanout/adapters/claude.js +15 -2
  152. package/dist/fanout/adapters/types.d.ts +6 -0
  153. package/dist/fanout/launcher.d.ts +5 -1
  154. package/dist/fanout/launcher.js +34 -3
  155. package/dist/fanout/picker.js +3 -2
  156. package/dist/fanout/usage.js +1 -1
  157. package/dist/generated/memory-ui-graph.browser.js +63 -63
  158. package/dist/graph-core/model.js +24 -3
  159. package/dist/graph-core/types.d.ts +4 -1
  160. package/dist/graph-core/types.js +1 -0
  161. package/dist/init/init-preset.js +7 -3
  162. package/dist/init/init-uninstall.js +2 -11
  163. package/dist/init/teardown.d.ts +3 -0
  164. package/dist/init/teardown.js +47 -0
  165. package/dist/link/context.js +21 -9
  166. package/dist/mcp/plugin-mode.js +1 -1
  167. package/dist/memory-ui-graph.runtime.js +63 -63
  168. package/dist/modules/code-package.d.ts +1 -0
  169. package/dist/modules/code-package.js +36 -7
  170. package/dist/modules/registry.js +14 -13
  171. package/dist/profile-store.d.ts +6 -0
  172. package/dist/profile-store.js +25 -1
  173. package/dist/shell/graph/glyphs.js +4 -0
  174. package/dist/shell/graph/graph-view.js +2 -0
  175. package/dist/status.js +7 -1
  176. package/dist/sync/task-claim.js +3 -2
  177. package/dist/task/lifecycle.js +25 -4
  178. package/dist/test-global-setup.js +5 -0
  179. package/dist/tools/dispatch.js +35 -2
  180. package/dist/tools/tasks.js +10 -1
  181. package/package.json +1 -1
  182. package/plugins/opencode/phren-transcript.js +87 -4
  183. package/starter/global/skills/conductor/SKILL.md +17 -2
  184. package/starter/global/skills/fanout/SKILL.md +3 -0
@@ -6,24 +6,33 @@ import { request, createServer } from "node:http";
6
6
  import { mkdir, readFile, chmod, unlink, lstat } from "node:fs/promises";
7
7
  import { watch } from "node:fs";
8
8
  import path from "node:path";
9
- import { randomUUID } from "node:crypto";
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ import { hostname } from "node:os";
10
11
  import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
11
12
  import { findPane, knownPanes, paneForCodexSession, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
12
13
  import { underCodexDaemon } from "./codex-daemon.js";
14
+ import { codexAutoReview } from "./codex-review-mode.js";
13
15
  import { terminalPaneFromEnv, terminalProvider } from "./terminal.js";
14
16
  import { readPaneText } from "./pane-text.js";
15
17
  import { capturesChanges, ToolChanges } from "./changes.js";
16
18
  import { phrenStoreRoot, unwrapPastedContent } from "./transcripts.js";
17
19
  import { archiveFinishedFanouts, blockedFanouts, fanoutAsking } from "./fanouts.js";
18
- import { ensureGrant, listGrants, matchGrant } from "./grants.js";
20
+ import { ensureGrant, findGrant } from "./grants.js";
19
21
  import { ApprovalPushService } from "./push.js";
22
+ import { approvalSummary } from "./approval-summary.js";
23
+ import { computerDisplayName } from "./pair.js";
20
24
  import { intervalFromEnv } from "./limits.js";
21
25
  import { answerClaudeQuestionDialog, claudeQuestionDialog } from "./claude-question-dialog.js";
22
26
  import { answeredQuestionInput, numberedDialog, opencodePermissionDialog, passwordLine, permissionPrompt, questionChoice, terminalChoice, terminalQuestions, visibleTerminalChoice } from "./terminal-choice.js";
23
27
  import { directoryNames, opencodeApprovalFile, opencodeRequest, readOpencodeRequest } from "./opencode-approvals.js";
24
28
  import { ApprovalWatchLeases, bindingPath, localSocket, PushBindingStore } from "./agent-hook-stores.js";
29
+ import { notePaneTranscript, paneAccountKey } from "./pane-accounts.js";
25
30
  import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js";
31
+ import { noteTurn as recordTurn } from "./turn-records.js";
26
32
  import { countTick } from "./metrics.js";
33
+ import { briefId, briefIdInPrompt, DISPATCH_ID_ENV, recordBriefArrival } from "./launch-brief.js";
34
+ import { CODEX_SERVER_ENV, codexServerId, codexServers } from "./codex-servers.js";
35
+ import { paneClient, paneKey, PaneServerWatcher, rootSession, servedPane } from "./opencode-panes.js";
27
36
  export { permissionPrompt, terminalChoice, visibleTerminalChoice } from "./terminal-choice.js";
28
37
  export { ApprovalWatchLeases, PushBindingStore, recordedSession } from "./agent-hook-stores.js";
29
38
  const APPROVAL_SWEEP_MS = 2_000;
@@ -38,11 +47,45 @@ const APPROVAL_HOLD_MS = (() => {
38
47
  })();
39
48
  /** A pane's terminal dialog is read at most once per this window. */
40
49
  const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000);
41
- const AGENT_NAMES = { claude: "Claude", codex: "Codex", opencode: "OpenCode", copilot: "Copilot", phren: "phren" };
42
50
  /** How long a pushed terminal dialog can be answered from its notification. */
43
51
  const DIALOG_PUSH_MS = 10 * 60_000;
44
52
  const FANOUT_SWEEP_MS = 5_000;
53
+ /** How far ahead a served OpenCode pane's ask expires. OpenCode waits for as
54
+ * long as it takes, so this is only a horizon: every listing that still
55
+ * returns the ask (each ask event, reconnect and the Hook's 5 s tick) moves it
56
+ * forward, and the card goes only when the ask is gone or the pane is dead. */
57
+ const SERVED_ASK_MS = 60 * 60_000;
45
58
  const FANOUT_ARCHIVE_MS = 60 * 60 * 1000;
59
+ /** The approval card's tool and input for an app-server request, in the
60
+ * shapes `approvalSummary` and the phone already read for Codex's hook.
61
+ * Undefined for questions (`item/tool/requestUserInput`) and MCP
62
+ * elicitations, which stay in the pane. */
63
+ export function appServerApproval(request) {
64
+ const params = request.params;
65
+ const reason = typeof params.reason === "string" && params.reason ? { reason: params.reason } : {};
66
+ if (request.method === "item/commandExecution/requestApproval") {
67
+ return { tool: "Bash", input: { ...(typeof params.command === "string" ? { command: params.command } : {}),
68
+ ...(typeof params.cwd === "string" ? { cwd: params.cwd } : {}), ...reason } };
69
+ }
70
+ if (request.method === "item/fileChange/requestApproval") {
71
+ const changes = objects(params.changes);
72
+ const verb = (change) => object(change.kind).type === "add" ? "Add" : object(change.kind).type === "delete" ? "Delete" : "Update";
73
+ const patch = changes.filter(change => typeof change.path === "string").map(change => `*** ${verb(change)} File: ${change.path}`).join("\n");
74
+ return { tool: "apply_patch", input: { ...(patch ? { patch } : {}), ...(typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}), ...reason } };
75
+ }
76
+ if (request.method === "item/permissions/requestApproval")
77
+ return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...reason } };
78
+ return undefined;
79
+ }
80
+ /** The app-server's answer for the phone's allow or deny (T3's
81
+ * CodexSessionRuntime shapes: accept / decline, a permission grant or none). */
82
+ export function appServerDecision(request, allow) {
83
+ if (request.method === "item/permissions/requestApproval")
84
+ return { permissions: allow ? object(request.params.permissions) : {}, scope: "turn" };
85
+ return { decision: allow ? "accept" : "decline" };
86
+ }
87
+ /** How long a dispatching Hook's poll keeps a worker pane's permission asks held. */
88
+ const DISPATCH_LEASE_MS = 45_000;
46
89
  /** A conductor `dispatch` or `hand_off` permission ask the Hook can answer
47
90
  * itself under a standing grant, or offer the phone two grant-writing answers. */
48
91
  export function conductorCall(tool, input) {
@@ -63,11 +106,19 @@ export function conductorCall(tool, input) {
63
106
  const computer = typeof fields.computer === "string" ? fields.computer : undefined;
64
107
  return { action, ...(project ? { project } : {}), ...(computer ? { computer } : {}) };
65
108
  }
109
+ /** As long as a typed prompt's own record guards it (`expectDelivery`). */
110
+ const TRACK_MS = 600_000;
66
111
  /** What the agent hands its UserPromptSubmit hook is the terminal's pasted
67
- * form of what Phren typed; compare the words, not the wrapping. */
112
+ * form of what Phren typed; compare the words, not the wrapping. Claude Code
113
+ * also takes each attached picture's path line out of the text and puts an
114
+ * "[Image #N]" label at the front, so neither side keeps picture paths or
115
+ * labels. */
68
116
  function promptKey(text) {
69
- return unwrapPastedContent(text).replace(/\s+/g, " ").trim();
117
+ return unwrapPastedContent(text).split("\n").filter(line => !PICTURE_PATH_LINE.test(line)).join("\n")
118
+ .replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
70
119
  }
120
+ const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
121
+ const trackKey = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
71
122
  /** This socket is deliberately separate from the phone's HTTP pipe. Only local
72
123
  * agent callbacks can register identities or create an approval request. */
73
124
  export class AgentHooks {
@@ -81,6 +132,8 @@ export class AgentHooks {
81
132
  * party that knows which conversation consumed the text, so it is the one
82
133
  * that can refuse it when that is not the conversation the phone meant. */
83
134
  deliveries = new Map();
135
+ /** Phone messages by delivery id, until TRACK_MS: see `trackDelivery`. */
136
+ tracked = new Map();
84
137
  /** The permission request a conversation is drawing in its own terminal
85
138
  * because nobody was there to hold it: what the phone shows above its
86
139
  * answer keys until the pane stops waiting. `dialog` marks a choice parsed
@@ -114,8 +167,18 @@ export class AgentHooks {
114
167
  * action, what an answer from the notification types. */
115
168
  dialogPushes = new Map();
116
169
  dialogActions = new Map();
117
- /** opencode permission asks seen on disk, by request id. */
170
+ /** Terminal dialogs offered to a dispatching Hook, by pane: the `dialog-` action minted for the dialog's current title. */
171
+ forwardedDialogs = new Map();
172
+ /** Requests this Hook pushed to its own phone on behalf of a dispatched worker on another computer: action -> the answer to send back. */
173
+ forwardedPushes = new Map();
174
+ /** Panes a dispatching Hook polled lately (`server\npane\nsource` -> expiry). */
175
+ dispatchLeases = new Map();
176
+ /** opencode permission asks seen on disk or listed by a served pane, by request id. */
118
177
  opencode = new Map();
178
+ /** Questions served OpenCode panes are asking, by question id. */
179
+ servedQuestions = new Map();
180
+ /** One event subscription per served OpenCode pane; ticked with the Hook. */
181
+ paneServers = new PaneServerWatcher({ asks: (entry, client, asks) => this.servedAsks(entry, client, asks), gone: key => this.servedGone(key) });
119
182
  closed = false;
120
183
  opencodeSweep;
121
184
  opencodeLive = new Set();
@@ -128,9 +191,13 @@ export class AgentHooks {
128
191
  fanoutSeen = new Map();
129
192
  fanoutTimer;
130
193
  fanoutArchiveTimer;
194
+ /** The name the phone paired with (macOS Computer Name), for approval alerts;
195
+ * the short host name until that lookup answers. */
196
+ computerName = hostname().replace(/\.local$/i, "").split(".")[0] || "Computer";
131
197
  constructor(push = new ApprovalPushService(), modules) {
132
198
  this.push = push;
133
199
  this.modules = modules;
200
+ void computerDisplayName().then(name => { this.computerName = name; }, () => { });
134
201
  }
135
202
  approvalsDirectory() { return path.join(phrenStoreRoot(), ".runtime", "approvals"); }
136
203
  scheduleOpencodeSweep() {
@@ -188,30 +255,224 @@ export class AgentHooks {
188
255
  const expiresAt = typeof request.expiresAt === "string" ? Date.parse(request.expiresAt) : NaN;
189
256
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now())
190
257
  continue;
258
+ const pane = target && !asking?.worktree ? findPane(await snapshot(target.server).catch(() => ({})), { workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source }) : undefined;
259
+ const cwd = asking?.worktree ?? (pane ? await trustedDirectory(pane).catch(() => undefined) : undefined);
260
+ const summary = approvalSummary({ tool: String(request.type ?? ""), input: request, message: typeof request.message === "string" ? request.message : undefined, cwd });
191
261
  // The answer route checks an action id by the parent's source: a UUID
192
262
  // for Claude and Codex, a plain token for opencode.
193
263
  const fanout = asking ? { session: match[1], actionId: asking.parent.provider === "opencode" ? randomUUID().replaceAll("-", "") : randomUUID() } : undefined;
194
- this.opencode.set(id, { ...(target ? { target } : {}), request, expiresAt, ...(fanout ? { fanout } : {}) });
264
+ this.opencode.set(id, { ...(target ? { target } : {}), request, requestLine: summary.request, expiresAt, ...(fanout ? { fanout } : {}) });
195
265
  if (!this.push.available)
196
266
  continue;
197
267
  const binding = randomUUID();
198
268
  this.pushBindings.add(binding, { action: id, expiresAt });
199
- const title = typeof request.title === "string" ? request.title : `Allow ${String(request.type ?? "action")}?`;
200
- const message = typeof request.message === "string" ? request.message : "";
201
269
  // The held request is what stops a later sweep from pushing again; a
202
270
  // failed delivery only drops the binding and leaves the card in place.
203
- void this.push.notify({ binding, provider: "opencode", question: false, expiresAt: String(request.expiresAt), title, message })
271
+ void this.push.notify({ binding, provider: "opencode", question: false, expiresAt: String(request.expiresAt),
272
+ ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
204
273
  .then(delivered => { if (!delivered)
205
274
  this.pushBindings.dropAction(id); })
206
275
  .catch(() => { });
207
276
  }
208
277
  for (const [id, held] of this.opencode) {
278
+ if (held.served)
279
+ continue;
209
280
  if (!live.has(id) || held.expiresAt <= Date.now()) {
210
281
  this.opencode.delete(id);
211
282
  this.pushBindings.dropAction(id);
212
283
  }
213
284
  }
214
285
  }
286
+ /** The pane a served OpenCode ask belongs to, as the phone names it: the
287
+ * pane's place from its terminal, and the root of the asking session (a
288
+ * subagent's ask shows on the conversation the pane shows). */
289
+ async servedTarget(entry, client, session) {
290
+ if (typeof session !== "string")
291
+ return undefined;
292
+ const root = await rootSession(client, session);
293
+ const state = await snapshot(entry.server).catch(() => undefined);
294
+ const pane = objects(state?.panes).find(value => value.pane_id === entry.pane);
295
+ if (!pane)
296
+ return undefined;
297
+ const parsed = targetSchema.safeParse({ server: entry.server, workspace: pane.workspace_id, tab: pane.tab_id, pane: entry.pane, source: "opencode", session: root });
298
+ return parsed.success ? parsed.data : undefined;
299
+ }
300
+ /** Everything a served pane is asking right now. New asks become the same
301
+ * cards (and pushes) as the plugin's file asks; asks no longer listed were
302
+ * answered in the TUI or went away, and their cards go with them. */
303
+ async servedAsks(entry, client, asks) {
304
+ if (this.closed)
305
+ return;
306
+ const key = paneKey(entry), where = { key, server: entry.server, pane: entry.pane };
307
+ const expiresAt = Date.now() + SERVED_ASK_MS;
308
+ const permissions = new Set();
309
+ for (const ask of asks.permissions) {
310
+ if (typeof ask.id !== "string" || !/^[A-Za-z0-9_]{1,200}$/.test(ask.id))
311
+ continue;
312
+ permissions.add(ask.id);
313
+ const known = this.opencode.get(ask.id);
314
+ if (known) {
315
+ if (known.served?.key === key) {
316
+ known.expiresAt = expiresAt;
317
+ known.request.expiresAt = new Date(expiresAt).toISOString();
318
+ this.pushBindings.extendAction(ask.id, expiresAt);
319
+ }
320
+ continue;
321
+ }
322
+ const target = await this.servedTarget(entry, client, ask.sessionID).catch(() => undefined);
323
+ if (this.closed)
324
+ return;
325
+ const type = typeof ask.permission === "string" && ask.permission ? ask.permission.slice(0, 200) : "action";
326
+ const patterns = (Array.isArray(ask.patterns) ? ask.patterns : []).filter((value) => typeof value === "string").slice(0, 32);
327
+ const metadata = object(ask.metadata);
328
+ const detail = [patterns.join(", "), metadata.command, metadata.description, metadata.filepath, metadata.path, metadata.url]
329
+ .find((value) => typeof value === "string" && !!value);
330
+ const message = (detail ? `${type}: ${detail}` : `opencode asks to use ${type}.`).slice(0, 2000);
331
+ const request = { id: ask.id, sessionID: ask.sessionID, type, title: `Allow ${type}?`, message, pattern: patterns,
332
+ ...(typeof metadata.command === "string" ? { metadata: { command: metadata.command } } : {}), expiresAt: new Date(expiresAt).toISOString() };
333
+ const summary = approvalSummary({ tool: type, input: request, message, cwd: entry.directory });
334
+ this.opencode.set(ask.id, { ...(target ? { target } : {}), request, requestLine: summary.request, expiresAt, served: where });
335
+ if (!this.push.available)
336
+ continue;
337
+ const binding = randomUUID();
338
+ this.pushBindings.add(binding, { action: ask.id, expiresAt });
339
+ void this.push.notify({ binding, provider: "opencode", question: false, expiresAt: String(request.expiresAt),
340
+ project: path.basename(entry.directory), computer: this.computerName, ...summary })
341
+ .then(delivered => { if (!delivered)
342
+ this.pushBindings.dropAction(ask.id); })
343
+ .catch(() => { });
344
+ }
345
+ for (const [id, held] of this.opencode) {
346
+ if (held.served?.key === key && !permissions.has(id)) {
347
+ this.opencode.delete(id);
348
+ this.pushBindings.dropAction(id);
349
+ }
350
+ }
351
+ const questions = new Set();
352
+ for (const ask of asks.questions) {
353
+ if (typeof ask.id !== "string" || !/^[A-Za-z0-9_]{1,200}$/.test(ask.id))
354
+ continue;
355
+ questions.add(ask.id);
356
+ if (this.servedQuestions.has(ask.id))
357
+ continue;
358
+ const raw = Array.isArray(ask.questions) ? ask.questions : [];
359
+ // OpenCode's `multiple` is the phone's multiSelect. A set the phone
360
+ // cannot show whole stays in the TUI.
361
+ const mapped = terminalQuestions({ questions: raw.map(value => ({ ...object(value), multiSelect: object(value).multiple === true })) });
362
+ if (!mapped || mapped.length !== raw.length)
363
+ continue;
364
+ const target = await this.servedTarget(entry, client, ask.sessionID).catch(() => undefined);
365
+ if (this.closed)
366
+ return;
367
+ this.servedQuestions.set(ask.id, { ...where, ...(target ? { target } : {}), question: ask, questions: mapped, at: Date.now() });
368
+ while (this.servedQuestions.size > 64)
369
+ this.servedQuestions.delete(this.servedQuestions.keys().next().value);
370
+ }
371
+ for (const [id, held] of this.servedQuestions)
372
+ if (held.key === key && !questions.has(id))
373
+ this.servedQuestions.delete(id);
374
+ }
375
+ /** A served pane's process is gone: nothing it asked can be answered. */
376
+ servedGone(key) {
377
+ for (const [id, held] of this.opencode)
378
+ if (held.served?.key === key) {
379
+ this.opencode.delete(id);
380
+ this.pushBindings.dropAction(id);
381
+ }
382
+ for (const [id, held] of this.servedQuestions)
383
+ if (held.key === key)
384
+ this.servedQuestions.delete(id);
385
+ }
386
+ /** The question a served OpenCode pane is asking, in the shape the phone
387
+ * answers Claude's AskUserQuestion with (`/v1/questions/answer`). */
388
+ servedQuestion(target) {
389
+ if (target.source !== "opencode")
390
+ return undefined;
391
+ const key = JSON.stringify(target);
392
+ const held = [...this.servedQuestions.values()].find(value => value.target && JSON.stringify(value.target) === key);
393
+ if (!held)
394
+ return undefined;
395
+ const title = held.questions[0].question;
396
+ return { toolName: "AskUserQuestion", actionId: held.question.id, message: title,
397
+ request: approvalSummary({ tool: "Question", message: title, question: true }).request,
398
+ choice: questionChoice(held.questions, 0), questions: held.questions, questionIndex: 0, at: new Date(held.at).toISOString() };
399
+ }
400
+ servedClient(server, pane) {
401
+ const entry = servedPane(server, pane);
402
+ if (!entry)
403
+ throw new BridgeError(409, "This approval is no longer pending.");
404
+ return paneClient(entry);
405
+ }
406
+ /** Answers a served pane's permission ask over its own API. */
407
+ async answerServed(id, held, decision) {
408
+ if (!["approve", "deny"].includes(String(decision)))
409
+ throw new BridgeError(400, "The approval answer is not valid.");
410
+ const served = held.served;
411
+ const client = this.servedClient(served.server, served.pane);
412
+ try {
413
+ await client.replyPermission(id, decision === "approve" ? "once" : "reject");
414
+ }
415
+ catch {
416
+ throw new BridgeError(409, "This approval is no longer pending.");
417
+ }
418
+ this.opencode.delete(id);
419
+ this.pushBindings.dropAction(id);
420
+ }
421
+ /** The phone's answers to a served pane's question: the labels it chose
422
+ * (and a typed answer) per question, for exactly the questions it shows. */
423
+ async answerServedQuestion(target, questions, answers) {
424
+ const key = JSON.stringify(target);
425
+ const found = [...this.servedQuestions.entries()].find(([, value]) => value.target && JSON.stringify(value.target) === key);
426
+ if (!found)
427
+ throw new BridgeError(409, "This question is no longer pending.");
428
+ const [id, held] = found;
429
+ const same = held.questions.length === questions.length && held.questions.every((question, index) => question.question === questions[index].question.trim()
430
+ && question.options.length === questions[index].options.length
431
+ && question.options.every((option, position) => option.label === questions[index].options[position].label.trim()));
432
+ if (!same)
433
+ throw new BridgeError(409, "That question has changed. Open phren to answer it.");
434
+ await validateTarget(target);
435
+ const labels = answers.map((answer, index) => [...answer.options.map(option => held.questions[index].options[option].label), ...(answer.text ? [answer.text] : [])]);
436
+ try {
437
+ await this.servedClient(held.server, held.pane).replyQuestion(id, labels);
438
+ }
439
+ catch {
440
+ throw new BridgeError(409, "This question is no longer pending.");
441
+ }
442
+ this.servedQuestions.delete(id);
443
+ }
444
+ /** Keys the phone sends to a served OpenCode pane that its API answers
445
+ * better than the terminal: Esc declines a pending question or stops a
446
+ * working turn (`session.abort`), and a digit answers a pending
447
+ * single-question, single-choice set. False leaves the keys to the pane. */
448
+ async servedKeys(target, keys, status) {
449
+ if (target.source !== "opencode")
450
+ return false;
451
+ const entry = servedPane(target.server, target.pane);
452
+ if (!entry)
453
+ return false;
454
+ const client = paneClient(entry), key = JSON.stringify(target);
455
+ const question = [...this.servedQuestions.entries()].find(([, value]) => value.target && JSON.stringify(value.target) === key);
456
+ const escape = keys.length > 0 && keys.every(value => value === "Escape");
457
+ if (question && escape) {
458
+ await client.rejectQuestion(question[0]).catch(() => { throw new BridgeError(409, "This question is no longer pending."); });
459
+ this.servedQuestions.delete(question[0]);
460
+ return true;
461
+ }
462
+ if (question && keys.length === 1 && /^[1-9]$/.test(keys[0]) && question[1].questions.length === 1 && !question[1].questions[0].multiSelect) {
463
+ const option = question[1].questions[0].options[Number(keys[0]) - 1];
464
+ if (!option)
465
+ throw new BridgeError(400, "Choose an available answer.");
466
+ await client.replyQuestion(question[0], [[option.label]]).catch(() => { throw new BridgeError(409, "This question is no longer pending."); });
467
+ this.servedQuestions.delete(question[0]);
468
+ return true;
469
+ }
470
+ if (escape && status === "working") {
471
+ // A failed abort leaves Esc to the terminal, as before.
472
+ return client.abort(target.session).then(done => done === true, () => false);
473
+ }
474
+ return false;
475
+ }
215
476
  /** A session's exact pane. A recorded binding carries the full target; when
216
477
  * there is none, Herdr's explicit session identity names the pane. */
217
478
  async resolveTarget(source, session) {
@@ -314,16 +575,22 @@ export class AgentHooks {
314
575
  * after `waitMs`: a busy agent queues typed input and submits it only when
315
576
  * its turn ends, so the record outlives the wait (up to ten minutes) and a
316
577
  * late submission to the wrong conversation is still refused. */
317
- expectDelivery(target, text, waitMs = 1_500) {
578
+ expectDelivery(target, text, waitMs = 1_500, signal) {
318
579
  const key = promptKey(text);
319
- if (!key)
580
+ if (!key || signal?.aborted)
320
581
  return Promise.resolve("pending");
321
582
  return new Promise(resolve => {
322
583
  let settled = false;
323
584
  const list = this.deliveries.get(key) ?? [];
324
- const remove = () => { const current = this.deliveries.get(key) ?? []; const index = current.indexOf(delivery); if (index >= 0)
325
- current.splice(index, 1); if (!current.length)
326
- this.deliveries.delete(key); };
585
+ const remove = () => {
586
+ signal?.removeEventListener("abort", cancel);
587
+ const current = this.deliveries.get(key) ?? [];
588
+ const index = current.indexOf(delivery);
589
+ if (index >= 0)
590
+ current.splice(index, 1);
591
+ if (!current.length)
592
+ this.deliveries.delete(key);
593
+ };
327
594
  const settle = (outcome) => {
328
595
  if (!settled) {
329
596
  settled = true;
@@ -337,6 +604,10 @@ export class AgentHooks {
337
604
  }
338
605
  };
339
606
  const delivery = { source: target.source, session: target.session, settle, timer: setTimeout(() => settle("pending"), waitMs) };
607
+ // Only cancel after a provider explicitly refused before writing. A
608
+ // possibly delivered paste keeps its guard against the wrong session.
609
+ const cancel = () => { clearTimeout(delivery.timer); settle("pending"); remove(); };
610
+ signal?.addEventListener("abort", cancel, { once: true });
340
611
  delivery.timer.unref?.();
341
612
  const expiry = setTimeout(remove, 600_000);
342
613
  expiry.unref?.();
@@ -362,6 +633,35 @@ export class AgentHooks {
362
633
  delivery.late = outcome => { clearTimeout(timer); delivery.late = undefined; resolve(outcome); };
363
634
  });
364
635
  }
636
+ /** Remember a phone message's outcome under its delivery id. A queued one
637
+ * is tracked only while its typed record still waits for the agent's hook,
638
+ * so the hook's later answer always reaches it (`settleTracked`). */
639
+ trackDelivery(id, target, text, state) {
640
+ if (state === "queued" && !this.deliveryPending(target, text))
641
+ return;
642
+ const now = Date.now();
643
+ for (const [key, entry] of this.tracked)
644
+ if (now - entry.at > TRACK_MS)
645
+ this.tracked.delete(key);
646
+ while (this.tracked.size >= 512)
647
+ this.tracked.delete(this.tracked.keys().next().value);
648
+ this.tracked.set(id, { source: target.source, session: target.session, key: trackKey(text), state, at: now });
649
+ }
650
+ /** What became of the phone message `id` sent to `target`'s conversation:
651
+ * queued until the agent submits it, then delivered, or blocked when
652
+ * another conversation in the pane took it. Unknown when the Hook did not
653
+ * track it, it was for another conversation, or it is older than TRACK_MS. */
654
+ deliveryState(id, target) {
655
+ const entry = this.tracked.get(id);
656
+ return entry && entry.source === target.source && entry.session === target.session && Date.now() - entry.at <= TRACK_MS ? entry.state : "unknown";
657
+ }
658
+ /** The oldest queued message tracked for `delivery`'s conversation with these words. */
659
+ settleTracked(delivery, prompt, state) {
660
+ const key = trackKey(prompt);
661
+ const entry = [...this.tracked.values()].find(item => item.state === "queued" && item.key === key && item.source === delivery.source && item.session === delivery.session);
662
+ if (entry)
663
+ entry.state = state;
664
+ }
365
665
  /** The conversation `target` just submitted `prompt`. Nothing Phren typed
366
666
  * matches: a locally typed prompt, always allowed. Otherwise the oldest
367
667
  * matching delivery decides: its own conversation consumes it; any other
@@ -369,22 +669,38 @@ export class AgentHooks {
369
669
  * wrong agent and the phone can safely send it again. */
370
670
  submitted(target, prompt) {
371
671
  const list = this.deliveries.get(promptKey(prompt));
372
- const delivery = list?.[0];
672
+ // The same words sent to two conversations at once: each one's own
673
+ // submission settles its own record, not whichever was typed first.
674
+ const delivery = list?.find(entry => entry.source === target.source && entry.session === target.session) ?? list?.[0];
373
675
  if (!delivery)
374
676
  return {};
375
- if (delivery.source === target.source && delivery.session === target.session) {
677
+ const own = delivery.source === target.source && delivery.session === target.session;
678
+ this.settleTracked(delivery, prompt, own ? "delivered" : "blocked");
679
+ if (own) {
376
680
  delivery.settle("delivered");
377
681
  return {};
378
682
  }
379
683
  delivery.settle("blocked");
380
684
  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." };
381
685
  }
686
+ /** The conversation's own turn events, for dispatch returns (turn-records.ts).
687
+ * A failed write never fails the agent's callback. */
688
+ async recordTurn(target, pane, body, dispatch) {
689
+ if (typeof pane.terminal_id !== "string")
690
+ return;
691
+ await recordTurn(target.server, target.pane, { event: String(body.event), terminal: pane.terminal_id, source: target.source, session: target.session,
692
+ ...(dispatch ? { dispatch } : {}),
693
+ ...(typeof body.background === "number" ? { background: body.background } : {}),
694
+ ...(typeof body.reply === "string" ? { reply: body.reply } : {}) }).catch(() => undefined);
695
+ }
382
696
  rememberTerminalPrompt(target, body) {
383
697
  const tool = String(body.tool || "action").slice(0, 200);
384
698
  const questions = tool === "AskUserQuestion" ? terminalQuestions(body.input) : undefined;
385
699
  const choice = questions ? questionChoice(questions, 0) : terminalChoice(body.input);
700
+ const summary = approvalSummary({ tool, input: body.input, question: tool === "AskUserQuestion" });
386
701
  this.terminalPrompts.set(JSON.stringify(target), { tool,
387
702
  message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}),
703
+ ...summary,
388
704
  ...(questions ? { questions, questionIndex: 0 } : {}), at: Date.now() });
389
705
  while (this.terminalPrompts.size > 64)
390
706
  this.terminalPrompts.delete(this.terminalPrompts.keys().next().value);
@@ -399,7 +715,7 @@ export class AgentHooks {
399
715
  this.terminalPrompts.delete(key);
400
716
  return undefined;
401
717
  }
402
- return { toolName: entry.tool, message: entry.message, ...(entry.choice ? { choice: entry.choice } : {}),
718
+ return { toolName: entry.tool, message: entry.message, ...(entry.request ? { request: entry.request } : {}), ...(entry.choice ? { choice: entry.choice } : {}),
403
719
  ...(entry.questions?.length ? { questions: entry.questions, questionIndex: entry.questionIndex ?? 0 } : {}), at: new Date(entry.at).toISOString() };
404
720
  }
405
721
  clearTerminalPrompt(target) { this.terminalPrompts.delete(JSON.stringify(target)); }
@@ -414,9 +730,18 @@ export class AgentHooks {
414
730
  * read notes whether the terminal is reading a password. */
415
731
  async syncTerminalDialog(target, active) {
416
732
  const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
733
+ // A served OpenCode pane lists its asks over its API; its screen is not read.
734
+ if (target.source === "opencode" && servedPane(target.server, target.pane)) {
735
+ if (entry)
736
+ this.terminalPrompts.delete(key);
737
+ return;
738
+ }
417
739
  const held = [...this.pending.values()].find(p => JSON.stringify(p.target) === key);
418
740
  // A held Codex permission can already have real choices in its pane.
419
741
  // Refresh those before publishing the approval, even while it is held.
742
+ // One the Hook's own app-server asked is answered over RPC, not in the pane.
743
+ if (held?.appServer)
744
+ return;
420
745
  if (held && target.source === "codex") {
421
746
  const now = Date.now();
422
747
  if (now - (this.dialogReads.get(key) ?? 0) < DIALOG_READ_MS)
@@ -427,7 +752,8 @@ export class AgentHooks {
427
752
  held.choice = prompt.choice;
428
753
  held.title = prompt.title;
429
754
  if (held.choice)
430
- this.terminalPrompts.set(key, { tool: held.tool, message: held.message, choice: held.choice, dialog: true, at: now });
755
+ this.terminalPrompts.set(key, { tool: held.tool, message: held.message,
756
+ request: held.request, requestKind: held.requestKind, choice: held.choice, dialog: true, at: now });
431
757
  else
432
758
  this.terminalPrompts.delete(key);
433
759
  }
@@ -475,13 +801,7 @@ export class AgentHooks {
475
801
  this.terminalPrompts.delete(key);
476
802
  return;
477
803
  }
478
- // Codex draws "> 1. Yes, proceed (y)" rows and Copilot a boxed select
479
- // with a cursor row, both answered by moving to a row; the other
480
- // fallbacks number rows without a key in the label.
481
- const dialog = ["codex", "copilot"].includes(target.source) ? visibleTerminalChoice(text)
482
- // OpenCode's prompt is one row of options; its cursor is only a color.
483
- : target.source === "opencode" ? opencodePermissionDialog(await this.paneAnsi(target))?.choice ?? numberedDialog(text)
484
- : numberedDialog(text);
804
+ const dialog = await this.screenDialog(target, text);
485
805
  if (entry && !entry.dialog) {
486
806
  // The permission the pane still shows after its hook let go: keep the
487
807
  // request's own details and answer it with the dialog's rows, so the
@@ -508,7 +828,9 @@ export class AgentHooks {
508
828
  settleBlockedPane(target.server, target.pane);
509
829
  return;
510
830
  }
511
- this.terminalPrompts.set(key, { tool: "Question", message: dialog.title, choice: dialog, dialog: true, at: now });
831
+ this.terminalPrompts.set(key, { tool: "Question", message: dialog.title,
832
+ ...approvalSummary({ tool: "Question", message: dialog.title }),
833
+ choice: dialog, dialog: true, at: now });
512
834
  while (this.terminalPrompts.size > 64)
513
835
  this.terminalPrompts.delete(this.terminalPrompts.keys().next().value);
514
836
  }
@@ -704,8 +1026,11 @@ export class AgentHooks {
704
1026
  const pending = [...this.pending.entries()].find(([, p]) => JSON.stringify(p.target) === JSON.stringify(target));
705
1027
  if (pending)
706
1028
  return { actionId: pending[0], toolName: pending[1].tool, title: pending[1].choice?.title ?? pending[1].title, message: pending[1].message,
707
- details: pending[1].message, terminalOnly: target.source === "codex" && !pending[1].choice,
708
- ...(pending[1].choice ? { choice: pending[1].choice } : {}), expiresAt: pending[1].expiresAt,
1029
+ request: pending[1].request,
1030
+ details: pending[1].message, terminalOnly: target.source === "codex" && !pending[1].choice && !pending[1].appServer,
1031
+ ...(pending[1].choice ? { choice: pending[1].choice } : {}),
1032
+ // An app-server request waits for as long as it takes: its card never runs out.
1033
+ expiresAt: pending[1].appServer ? new Date(Math.max(Date.parse(pending[1].expiresAt), Date.now() + DIALOG_PUSH_MS)).toISOString() : pending[1].expiresAt,
709
1034
  ...(pending[1].conductor ? { conductor: pending[1].conductor } : {}) };
710
1035
  const own = target.source === "opencode" ? this.opencodeApproval(target) : undefined;
711
1036
  if (own)
@@ -713,14 +1038,16 @@ export class AgentHooks {
713
1038
  // A fan-out worker this conversation started is waiting on the owner.
714
1039
  const worker = this.fanoutHeld(target)[0];
715
1040
  return worker?.fanout ? { actionId: worker.fanout.actionId, toolName: worker.request.type, title: worker.request.title,
716
- message: worker.request.message, expiresAt: worker.request.expiresAt } : undefined;
1041
+ message: worker.request.message, request: worker.requestLine, expiresAt: worker.request.expiresAt } : undefined;
717
1042
  }
718
1043
  opencodeApproval(target) {
719
1044
  const held = [...this.opencode.values()].find(value => !value.fanout && JSON.stringify(value.target) === JSON.stringify(target));
720
1045
  if (held)
721
- return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, expiresAt: held.request.expiresAt };
1046
+ return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, request: held.requestLine, expiresAt: held.request.expiresAt };
722
1047
  const request = opencodeRequest(target.session);
723
- return request ? { actionId: request.id, toolName: request.type, title: request.title, message: request.message, expiresAt: request.expiresAt } : undefined;
1048
+ return request ? { actionId: request.id, toolName: request.type, title: request.title, message: request.message,
1049
+ request: approvalSummary({ tool: String(request.type ?? ""), input: request, message: typeof request.message === "string" ? request.message : undefined }).request,
1050
+ expiresAt: request.expiresAt } : undefined;
724
1051
  }
725
1052
  /** Live fan-out worker asks shown on this parent conversation, oldest first. */
726
1053
  fanoutHeld(target) {
@@ -755,6 +1082,14 @@ export class AgentHooks {
755
1082
  pending.add(String(pane.pane_id));
756
1083
  }
757
1084
  }
1085
+ // A served OpenCode pane's permission or question, listed by its server.
1086
+ const served = [...[...this.opencode.values()].filter(held => held.served).map(held => held.target), ...[...this.servedQuestions.values()].map(held => held.target)];
1087
+ for (const at of served) {
1088
+ if (!at || at.server !== server)
1089
+ continue;
1090
+ if (panes.some(pane => pane.pane_id === at.pane && pane.workspace_id === at.workspace && pane.tab_id === at.tab && pane.agent === "opencode"))
1091
+ pending.add(at.pane);
1092
+ }
758
1093
  for (const held of this.opencode.values()) {
759
1094
  const parent = held.target;
760
1095
  if (!held.fanout || !parent || parent.server !== server)
@@ -777,6 +1112,17 @@ export class AgentHooks {
777
1112
  this.pushBindings.dropAction(id);
778
1113
  }
779
1114
  async answer(target, id, decision, updatedInput) {
1115
+ // A terminal dialog offered to a dispatching Hook (`workerApproval`) or pushed: answered with the pane's own keys.
1116
+ if (id.startsWith("dialog-")) {
1117
+ const dialog = this.dialogActions.get(id);
1118
+ if (!dialog || JSON.stringify(dialog.target) !== JSON.stringify(target))
1119
+ throw new BridgeError(409, "This approval is no longer pending.");
1120
+ if (updatedInput !== undefined || !["approve", "deny"].includes(String(decision)))
1121
+ throw new BridgeError(400, "The approval answer is not valid.");
1122
+ await this.answerDialog(id, decision);
1123
+ this.dropForwardedDialog(JSON.stringify(target));
1124
+ return;
1125
+ }
780
1126
  const worker = [...this.opencode.entries()].find(([, held]) => held.fanout?.actionId === id && JSON.stringify(held.target) === JSON.stringify(target));
781
1127
  if (worker) {
782
1128
  if (updatedInput !== undefined)
@@ -785,6 +1131,16 @@ export class AgentHooks {
785
1131
  await this.answerFanout(worker[0], worker[1], decision);
786
1132
  return;
787
1133
  }
1134
+ const served = target.source === "opencode" ? this.opencode.get(id) : undefined;
1135
+ if (served?.served) {
1136
+ if (updatedInput !== undefined)
1137
+ throw new BridgeError(400, "Answers go with an approval.");
1138
+ if (!served.target || JSON.stringify(served.target) !== JSON.stringify(target))
1139
+ throw new BridgeError(409, "This approval is no longer pending.");
1140
+ await validateTarget(target);
1141
+ await this.answerServed(id, served, decision);
1142
+ return;
1143
+ }
788
1144
  if (target.source === "opencode") {
789
1145
  if (!["approve", "deny"].includes(String(decision)))
790
1146
  throw new BridgeError(400, "The approval answer is not valid.");
@@ -874,6 +1230,13 @@ export class AgentHooks {
874
1230
  const linked = this.pushBindings.consume(binding);
875
1231
  if (!linked)
876
1232
  throw new BridgeError(409, "This approval is no longer pending.");
1233
+ // A worker's request on another computer: the callback answers it there.
1234
+ const forwarded = this.forwardedPushes.get(linked.action);
1235
+ if (forwarded) {
1236
+ this.forwardedPushes.delete(linked.action);
1237
+ await forwarded(decision);
1238
+ return;
1239
+ }
877
1240
  const pending = this.pending.get(linked.action);
878
1241
  if (pending) {
879
1242
  await this.answer(pending.target, linked.action, decision);
@@ -899,6 +1262,11 @@ export class AgentHooks {
899
1262
  await this.answerFanout(linked.action, held, decision);
900
1263
  return;
901
1264
  }
1265
+ // A served pane's ask is answered over its own API, target or not.
1266
+ if (held?.served) {
1267
+ await this.answerServed(linked.action, held, decision);
1268
+ return;
1269
+ }
902
1270
  if (held?.target) {
903
1271
  await this.answer(held.target, linked.action, decision);
904
1272
  return;
@@ -932,6 +1300,9 @@ export class AgentHooks {
932
1300
  continue;
933
1301
  const key = JSON.stringify(target);
934
1302
  waiting.add(key);
1303
+ // A served OpenCode pane's asks were pushed as its server listed them.
1304
+ if (target.source === "opencode" && servedPane(target.server, target.pane))
1305
+ continue;
935
1306
  // A request its own hook already holds was pushed on arrival.
936
1307
  if ([...this.pending.values()].some(held => JSON.stringify(held.target) === key))
937
1308
  continue;
@@ -956,8 +1327,11 @@ export class AgentHooks {
956
1327
  this.dialogPushes.set(key, { action, title });
957
1328
  this.dialogActions.set(action, { target, choice: entry.choice, expiresAt });
958
1329
  this.pushBindings.add(binding, { action, expiresAt });
959
- void this.push.notify({ binding, provider: target.source, question: false, expiresAt: new Date(expiresAt).toISOString(),
960
- title: `${AGENT_NAMES[target.source] ?? "An agent"} needs your approval`, message: title.slice(0, 1_000) })
1330
+ const cwd = await trustedDirectory(pane).catch(() => undefined);
1331
+ const summary = entry.request ? { request: entry.request, requestKind: entry.requestKind ?? "other" }
1332
+ : approvalSummary({ tool: entry.tool, message: title });
1333
+ void this.push.notify({ binding, provider: target.source, question: entry.tool === "AskUserQuestion", expiresAt: new Date(expiresAt).toISOString(),
1334
+ ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
961
1335
  .then(delivered => { if (!delivered)
962
1336
  this.dropDialogPush(key); }).catch(() => this.dropDialogPush(key));
963
1337
  }
@@ -975,6 +1349,100 @@ export class AgentHooks {
975
1349
  this.dialogPushes.delete(key);
976
1350
  }
977
1351
  }
1352
+ for (const key of this.forwardedDialogs.keys())
1353
+ if (!waiting.has(key) && JSON.parse(key).server === server)
1354
+ this.dropForwardedDialog(key);
1355
+ }
1356
+ /** Keeps the held asks of these dispatched panes for the dispatching Hook's
1357
+ * next polls: without a phone, a watcher or push here, a worker's request
1358
+ * would go straight to its terminal and only its `blocked` state would
1359
+ * reach the conductor. Keyed by pane, since a worker that has not yet
1360
+ * reported a conversation has no session. */
1361
+ leaseDispatch(targets) {
1362
+ const now = Date.now();
1363
+ for (const [key, expiry] of this.dispatchLeases)
1364
+ if (expiry <= now)
1365
+ this.dispatchLeases.delete(key);
1366
+ for (const target of targets) {
1367
+ const key = `${target.server}\n${target.pane}\n${target.source}`;
1368
+ this.dispatchLeases.delete(key);
1369
+ while (this.dispatchLeases.size >= 256)
1370
+ this.dispatchLeases.delete(this.dispatchLeases.keys().next().value);
1371
+ this.dispatchLeases.set(key, now + DISPATCH_LEASE_MS);
1372
+ }
1373
+ }
1374
+ dispatchLeased(target) {
1375
+ return (this.dispatchLeases.get(`${target.server}\n${target.pane}\n${target.source}`) ?? 0) > Date.now();
1376
+ }
1377
+ dropForwardedDialog(key) {
1378
+ const forwarded = this.forwardedDialogs.get(key);
1379
+ if (!forwarded)
1380
+ return;
1381
+ this.forwardedDialogs.delete(key);
1382
+ if (this.dialogPushes.get(key)?.action !== forwarded.action)
1383
+ this.dialogActions.delete(forwarded.action);
1384
+ }
1385
+ /** What this pane's worker is waiting on, for the dispatching Hook: the held
1386
+ * or app-server request, else the terminal dialog the pane draws (offered
1387
+ * under a `dialog-` action the answer route accepts). */
1388
+ workerApproval(target) {
1389
+ const clip = (value, max) => typeof value === "string" && value ? value.slice(0, max) : undefined;
1390
+ const held = this.approval(target);
1391
+ if (held) {
1392
+ const actionId = String(held.actionId), pending = this.pending.get(actionId);
1393
+ const pushed = pending ? this.pushedHolds.has(actionId) || (!!pending.appServer && this.push.available) : this.push.available;
1394
+ const title = clip(held.title, 200), request = clip(held.request, 500), expiresAt = clip(held.expiresAt, 40);
1395
+ const conductor = held.conductor;
1396
+ return { actionId, tool: clip(held.toolName, 200) ?? "action", ...(title ? { title } : {}), ...(request ? { request } : {}),
1397
+ ...(pending ? { requestKind: pending.requestKind } : {}), ...(expiresAt ? { expiresAt } : {}), ...(conductor ? { conductor } : {}), ...(pushed ? { pushed: true } : {}) };
1398
+ }
1399
+ const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
1400
+ const title = entry && (entry.dialog || entry.released) ? entry.choice?.title : undefined;
1401
+ if (!entry?.choice || !title)
1402
+ return undefined;
1403
+ const pushedDialog = this.dialogPushes.get(key);
1404
+ // A dialog is the same one only with the same title and command: Claude and Codex share generic titles.
1405
+ const pushedAction = pushedDialog && this.dialogActions.get(pushedDialog.action);
1406
+ let action = pushedDialog?.title === title && pushedAction && pushedAction.choice.body === entry.choice.body ? pushedDialog.action : undefined;
1407
+ if (!action) {
1408
+ const known = this.forwardedDialogs.get(key);
1409
+ if (known?.title === title && known.body === entry.choice.body && (this.dialogActions.get(known.action)?.expiresAt ?? 0) > Date.now())
1410
+ action = known.action;
1411
+ else {
1412
+ this.dropForwardedDialog(key);
1413
+ while (this.forwardedDialogs.size >= 64)
1414
+ this.dropForwardedDialog(this.forwardedDialogs.keys().next().value);
1415
+ action = `dialog-${randomUUID()}`;
1416
+ this.forwardedDialogs.set(key, { action, title, body: entry.choice.body });
1417
+ this.dialogActions.set(action, { target, choice: entry.choice, expiresAt: Date.now() + DIALOG_PUSH_MS });
1418
+ }
1419
+ }
1420
+ const request = clip(entry.request ?? approvalSummary({ tool: entry.tool, message: title }).request, 500);
1421
+ return { actionId: action, tool: entry.tool.slice(0, 200), title: title.slice(0, 200), ...(request ? { request } : {}),
1422
+ ...(entry.requestKind ? { requestKind: entry.requestKind } : {}),
1423
+ expiresAt: new Date(this.dialogActions.get(action).expiresAt).toISOString(), terminal: true,
1424
+ ...(pushedDialog?.action === action ? { pushed: true } : {}) };
1425
+ }
1426
+ /** A worker's request on another computer, sent to this Hook's own phone:
1427
+ * the notification's answer calls `answer`, which sends it back over the
1428
+ * dispatch path. */
1429
+ pushForwarded(summary, answer) {
1430
+ if (!this.push.available || this.closed)
1431
+ return;
1432
+ const action = `forward-${randomUUID()}`, binding = randomUUID(), expiresAt = Date.now() + DIALOG_PUSH_MS;
1433
+ while (this.forwardedPushes.size >= 64) {
1434
+ const oldest = this.forwardedPushes.keys().next().value;
1435
+ this.forwardedPushes.delete(oldest);
1436
+ this.dropPushBindings(oldest);
1437
+ }
1438
+ this.forwardedPushes.set(action, answer);
1439
+ this.pushBindings.add(binding, { action, expiresAt });
1440
+ const drop = () => { this.forwardedPushes.delete(action); this.dropPushBindings(action); };
1441
+ void this.push.notify({ binding, provider: summary.provider, question: false, expiresAt: new Date(expiresAt).toISOString(),
1442
+ ...(summary.project ? { project: summary.project } : {}), computer: summary.computer, request: summary.request,
1443
+ ...(summary.requestKind ? { requestKind: summary.requestKind } : {}) })
1444
+ .then(delivered => { if (!delivered)
1445
+ drop(); }).catch(drop);
978
1446
  }
979
1447
  adoptReleasedHold(key, target, choice, title) {
980
1448
  const hold = this.releasedHolds.get(key);
@@ -993,16 +1461,37 @@ export class AgentHooks {
993
1461
  this.dropPushBindings(pushed.action);
994
1462
  this.dialogPushes.delete(key);
995
1463
  }
1464
+ /** The dialog a pane's screen shows now. Codex draws "> 1. Yes, proceed (y)"
1465
+ * rows and Copilot a boxed select with a cursor row, both answered by moving
1466
+ * to a row; OpenCode's prompt is one row of options whose cursor is only a
1467
+ * color; the other fallbacks number rows without a key in the label. */
1468
+ async screenDialog(target, text) {
1469
+ return ["codex", "copilot"].includes(target.source) ? visibleTerminalChoice(text)
1470
+ : target.source === "opencode" ? opencodePermissionDialog(await this.paneAnsi(target))?.choice ?? numberedDialog(text)
1471
+ : numberedDialog(text);
1472
+ }
996
1473
  /** Approve picks the dialog's yes/allow row (else its first), Deny its
997
1474
  * no/deny row (else Escape), typed as the pane's own keys. */
998
1475
  async answerDialog(action, decision) {
999
1476
  const dialog = this.dialogActions.get(action);
1000
1477
  if (!dialog || dialog.expiresAt <= Date.now())
1001
1478
  throw new BridgeError(409, "This approval is no longer pending.");
1479
+ // Claimed before any await: a second answer for the same dialog gets a 409 instead of typing the keys twice.
1480
+ this.dialogActions.delete(action);
1002
1481
  const key = JSON.stringify(dialog.target);
1003
- await validateTarget(dialog.target, false, true);
1004
- const live = this.terminalPrompts.get(key)?.choice;
1005
- if (!live || live.title !== dialog.choice.title) {
1482
+ try {
1483
+ await validateTarget(dialog.target, false, true);
1484
+ }
1485
+ catch (error) {
1486
+ if (!this.dialogActions.has(action))
1487
+ this.dialogActions.set(action, dialog);
1488
+ throw error;
1489
+ }
1490
+ // Read the screen now, not the activity tick's cached prompt: in the seconds
1491
+ // since that tick the dialog may have been answered and replaced by another
1492
+ // with the same title, and the keys must only ever answer the one forwarded.
1493
+ const live = await this.screenDialog(dialog.target, await this.paneLines(dialog.target));
1494
+ if (!live || live.title !== dialog.choice.title || live.body !== dialog.choice.body) {
1006
1495
  this.dropDialogPush(key);
1007
1496
  throw new BridgeError(409, "That question in the terminal has changed. Open phren to answer it.");
1008
1497
  }
@@ -1017,6 +1506,63 @@ export class AgentHooks {
1017
1506
  dropPushBindings(action) {
1018
1507
  this.pushBindings.dropAction(action);
1019
1508
  }
1509
+ /** A server request from one of the Hook's own Codex app-servers: an
1510
+ * approval card like a held PermissionRequest, pushed the same way, but
1511
+ * with no hold timer. The request stays parked in Codex until someone
1512
+ * answers it, here or in the pane's TUI (`codexResolved`). */
1513
+ codexRequest(target, request, answer) {
1514
+ const shown = appServerApproval(request);
1515
+ if (!shown || this.closed)
1516
+ return;
1517
+ // Replayed after a reconnect: the card stays, answered through the new connection.
1518
+ const known = [...this.pending.values()].find(entry => entry.appServer?.requestId === request.requestId && JSON.stringify(entry.target) === JSON.stringify(target));
1519
+ if (known?.appServer) {
1520
+ known.appServer.answer = answer;
1521
+ return;
1522
+ }
1523
+ const action = randomUUID();
1524
+ const held = { requestId: request.requestId, answer };
1525
+ const reply = { destroyed: false, end(body) {
1526
+ if (reply.destroyed)
1527
+ return;
1528
+ reply.destroyed = true;
1529
+ // "{}" gives the request back to the pane: it stays parked in Codex.
1530
+ const behavior = object(object(object((() => { try {
1531
+ return JSON.parse(body);
1532
+ }
1533
+ catch {
1534
+ return {};
1535
+ } })()).hookSpecificOutput).decision).behavior;
1536
+ if (behavior === "allow" || behavior === "deny")
1537
+ held.answer(appServerDecision(request, behavior === "allow"));
1538
+ } };
1539
+ const cwd = typeof request.params.cwd === "string" && path.isAbsolute(request.params.cwd) ? request.params.cwd : undefined;
1540
+ const summary = approvalSummary({ tool: shown.tool, input: shown.input, cwd });
1541
+ const expiresAt = Date.now() + DIALOG_PUSH_MS;
1542
+ this.pending.set(action, { target, response: reply, tool: shown.tool, input: shown.input, message: JSON.stringify(shown.input, null, 2).slice(0, 32_768),
1543
+ ...summary, expiresAt: new Date(expiresAt).toISOString(), appServer: held });
1544
+ while (this.pending.size > 64)
1545
+ this.pending.delete(this.pending.keys().next().value);
1546
+ if (!this.push.available)
1547
+ return;
1548
+ const binding = randomUUID();
1549
+ this.pushBindings.add(binding, { action, expiresAt });
1550
+ void this.push.notify({ binding, provider: "codex", question: false, expiresAt: new Date(expiresAt).toISOString(),
1551
+ ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
1552
+ .then(delivered => { if (!delivered)
1553
+ this.pushBindings.consume(binding); }).catch(() => { });
1554
+ }
1555
+ /** Another client (the pane's TUI) answered the request, or this one declined it. */
1556
+ codexResolved(target, requestId) {
1557
+ for (const [action, entry] of this.pending) {
1558
+ if (entry.appServer?.requestId !== requestId || JSON.stringify(entry.target) !== JSON.stringify(target))
1559
+ continue;
1560
+ this.pending.delete(action);
1561
+ this.dropPushBindings(action);
1562
+ entry.response.destroyed = true;
1563
+ settleBlockedPane(target.server, target.pane, 0);
1564
+ }
1565
+ }
1020
1566
  async start() {
1021
1567
  await this.push.start();
1022
1568
  // The public helper singleton was already checked before this is called.
@@ -1067,18 +1613,40 @@ export class AgentHooks {
1067
1613
  const pids = (await terminalProvider().processes(target.server, target.pane)).foregroundPids;
1068
1614
  if (!pids.length)
1069
1615
  throw new Error("No foreground process");
1616
+ if (!daemon && target.source === "claude")
1617
+ notePaneTranscript(paneAccountKey(target.server, target.pane), body.transcript, String(pane.terminal_id ?? ""));
1070
1618
  if (!daemon)
1071
1619
  await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ terminal: pane.terminal_id, source: target.source,
1072
1620
  session: target.session, pids, workspace: target.workspace, tab: target.tab, event: String(body.event).slice(0, 64), at: new Date().toISOString() }));
1073
1621
  // A terminal that does not watch its agents (tmux) takes the agent's
1074
1622
  // status from these events.
1075
- const status = eventStatus(body.event);
1623
+ // Codex's automatic reviewer decides this request on its own: it is
1624
+ // not a question for the owner, so nothing is held, pushed or
1625
+ // remembered and the pane is not marked blocked. If Codex hands the
1626
+ // request back to the owner it draws its approval dialog, which the
1627
+ // waiting-pane dialog read picks up and pushes like any other.
1628
+ const autoReview = body.event === "PermissionRequest" && target.source === "codex" && body.autoReview === true;
1629
+ const status = autoReview ? undefined : eventStatus(body.event);
1076
1630
  if (status && typeof pane.terminal_id === "string")
1077
1631
  notePaneStatus(target.server, target.pane, pane.terminal_id, status);
1078
1632
  // What a shell call changed on disk: snapshot before, diff after.
1079
1633
  const input = typeof body.input === "string" ? { patch: body.input } : object(body.input), command = [input.command, input.cmd].find(v => typeof v === "string");
1080
1634
  // A shell call by name, or any tool whose input is a command line —
1081
1635
  // Codex has renamed its shell tool more than once.
1636
+ // A launched brief's receipt: the worker's own hook names its dispatch
1637
+ // id (from its environment, or the brief path in its first prompt when
1638
+ // Codex's shared daemon ran the hook with another pane's variables).
1639
+ let dispatch;
1640
+ if (body.event === "SessionStart" || body.event === "UserPromptSubmit") {
1641
+ const named = !daemon && briefId.safeParse(body.dispatchId).success ? String(body.dispatchId) : undefined;
1642
+ dispatch = named ?? (typeof body.prompt === "string" ? briefIdInPrompt(body.prompt) : undefined);
1643
+ if (dispatch)
1644
+ await recordBriefArrival(dispatch, String(body.event), target).catch(() => undefined);
1645
+ }
1646
+ // `/new` or `/resume` in a pane on the Hook's own Codex server: follow
1647
+ // the TUI to its new thread. Only a callback trusted to name its pane.
1648
+ if (body.event === "SessionStart" && target.source === "codex" && !daemon)
1649
+ codexServers.follow(target.server, target.pane, target.session);
1082
1650
  if (body.event === "PreCompact") {
1083
1651
  this.startCompacting(target);
1084
1652
  res.end("{}");
@@ -1087,9 +1655,15 @@ export class AgentHooks {
1087
1655
  if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)))
1088
1656
  this.stopCompacting(target);
1089
1657
  if (body.event === "UserPromptSubmit") {
1090
- res.end(JSON.stringify(typeof body.prompt === "string" ? this.submitted(target, body.prompt.slice(0, 65_536)) : {}));
1658
+ const answer = typeof body.prompt === "string" ? this.submitted(target, body.prompt.slice(0, 65_536)) : {};
1659
+ // A prompt refused here never starts a turn in this conversation.
1660
+ if (answer.decision !== "block")
1661
+ await this.recordTurn(target, pane, body, dispatch);
1662
+ res.end(JSON.stringify(answer));
1091
1663
  return;
1092
1664
  }
1665
+ if (body.event === "SessionStart" || body.event === "Stop")
1666
+ await this.recordTurn(target, pane, body, dispatch);
1093
1667
  if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body.event)) && capturesChanges(String(body.tool), input)) {
1094
1668
  const conversation = `${target.source}:${target.session}`, id = String(body.toolUseId || "").slice(0, 200);
1095
1669
  if (body.event === "PreToolUse")
@@ -1105,17 +1679,28 @@ export class AgentHooks {
1105
1679
  const conductor = conductorCall(String(body.tool || "action"), body.input);
1106
1680
  if (conductor) {
1107
1681
  // A standing grant answers the call before it becomes an approval card.
1108
- const grant = matchGrant(await listGrants().catch(() => []), {
1682
+ const grant = await findGrant({
1109
1683
  action: conductor.action, project: conductor.project, computer: conductor.computer,
1110
- });
1684
+ }).catch(() => undefined);
1111
1685
  if (grant) {
1112
1686
  res.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "allow" } } }));
1113
1687
  return;
1114
1688
  }
1115
1689
  }
1116
1690
  }
1691
+ if (autoReview) {
1692
+ res.end("{}");
1693
+ return;
1694
+ }
1695
+ // A thread on the Hook's own Codex app-server: the request reaches
1696
+ // this Hook as a server request with no time limit, so the callback
1697
+ // lets Codex ask for it at once instead of holding a second card.
1698
+ if (body.event === "PermissionRequest" && target.source === "codex" && codexServers.forThread(target.session)) {
1699
+ res.end("{}");
1700
+ return;
1701
+ }
1117
1702
  if (body.event !== "PermissionRequest" || target.source === "copilot"
1118
- || (!this.watching.has(JSON.stringify(target)) && !this.overview.has(target.server) && !this.push.available)) {
1703
+ || (!this.watching.has(JSON.stringify(target)) && !this.overview.has(target.server) && !this.push.available && !this.dispatchLeased(target))) {
1119
1704
  if (body.event === "PermissionRequest")
1120
1705
  this.rememberTerminalPrompt(target, body);
1121
1706
  res.end("{}");
@@ -1130,7 +1715,8 @@ export class AgentHooks {
1130
1715
  const action = randomUUID();
1131
1716
  this.dialogReads.delete(JSON.stringify(target));
1132
1717
  const conductor = body.event === "PermissionRequest" ? conductorCall(String(body.tool || "action"), body.input) : undefined;
1133
- const locallyWatched = this.watching.has(JSON.stringify(target)) || this.overview.has(target.server);
1718
+ const locallyWatched = this.watching.has(JSON.stringify(target)) || this.overview.has(target.server) || this.dispatchLeased(target);
1719
+ const cwd = typeof body.cwd === "string" && path.isAbsolute(body.cwd) ? body.cwd : await trustedDirectory(pane).catch(() => undefined);
1134
1720
  // When the hold ends the request stays in the terminal. A pushed
1135
1721
  // notification keeps working: its binding waits for the pane's dialog
1136
1722
  // and then answers that, instead of going dead with the hold.
@@ -1146,8 +1732,9 @@ export class AgentHooks {
1146
1732
  }, APPROVAL_HOLD_MS);
1147
1733
  const expiresAt = new Date(Date.now() + APPROVAL_HOLD_MS).toISOString();
1148
1734
  const { choice, title } = permissionPrompt(String(body.tool || "action"), body.input);
1735
+ const summary = approvalSummary({ tool: String(body.tool || "action"), input: body.input, cwd, question: body.tool === "AskUserQuestion" });
1149
1736
  this.pending.set(action, { target, response: res, tool: String(body.tool || "action").slice(0, 200), input: body.input, title,
1150
- message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}), expiresAt, timer,
1737
+ message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...summary, ...(choice ? { choice } : {}), expiresAt, timer,
1151
1738
  ...(conductor ? { conductor } : {}) });
1152
1739
  res.on("close", () => { clearTimeout(timer); this.pending.delete(action); this.pushedHolds.delete(action); if (!released)
1153
1740
  this.dropPushBindings(action); });
@@ -1156,7 +1743,7 @@ export class AgentHooks {
1156
1743
  this.pushBindings.add(binding, { action, expiresAt: pushExpiresAt });
1157
1744
  this.pushedHolds.set(action, pushExpiresAt);
1158
1745
  void this.push.notify({ binding, provider: target.source, question: body.tool === "AskUserQuestion",
1159
- expiresAt: new Date(pushExpiresAt).toISOString() }).catch(() => false).then(delivered => {
1746
+ expiresAt: new Date(pushExpiresAt).toISOString(), ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary }).catch(() => false).then(delivered => {
1160
1747
  if (!delivered) {
1161
1748
  this.pushBindings.consume(binding);
1162
1749
  this.pushedHolds.delete(action);
@@ -1210,6 +1797,7 @@ export class AgentHooks {
1210
1797
  this.fanoutArchiveTimer.unref?.();
1211
1798
  this.scheduleOpencodeSweep();
1212
1799
  void this.sweepBlockedFanouts();
1800
+ this.paneServers.tick();
1213
1801
  }
1214
1802
  close() {
1215
1803
  this.closed = true;
@@ -1223,6 +1811,9 @@ export class AgentHooks {
1223
1811
  this.server?.closeAllConnections();
1224
1812
  this.pushBindings.clear();
1225
1813
  this.opencode.clear();
1814
+ this.forwardedPushes.clear();
1815
+ this.paneServers.close();
1816
+ this.servedQuestions.clear();
1226
1817
  if (this.opencodeDebounce)
1227
1818
  clearTimeout(this.opencodeDebounce);
1228
1819
  if (this.opencodePoll)
@@ -1236,6 +1827,16 @@ export class AgentHooks {
1236
1827
  this.fanoutSeen.clear();
1237
1828
  }
1238
1829
  }
1830
+ /** What a Stop payload says about the turn it ends: the harness's last
1831
+ * assistant message (Claude, Codex) and, from Claude Code, the background
1832
+ * tasks still in flight, which will wake the conversation again when they
1833
+ * finish. Absent fields are left out, so the Hook falls back to the transcript. */
1834
+ export function stopFacts(value) {
1835
+ const tasks = Array.isArray(value.background_tasks)
1836
+ ? value.background_tasks.filter(task => !["completed", "failed", "killed", "stopped"].includes(String(object(task).status))) : undefined;
1837
+ return { ...(tasks ? { background: tasks.length } : {}),
1838
+ ...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
1839
+ }
1239
1840
  export async function agentHook(source) {
1240
1841
  provider.parse(source);
1241
1842
  // A missing helper must never prevent the coding agent from running.
@@ -1260,11 +1861,24 @@ export async function agentHook(source) {
1260
1861
  return;
1261
1862
  // Codex 0.157 runs hooks inside its shared app-server daemon, whose pane
1262
1863
  // variables belong to whichever pane first started it.
1263
- const daemon = source === "codex" && await underCodexDaemon().catch(() => false);
1264
- const data = JSON.stringify({ target, event, ...(daemon ? { daemon: true } : {}), tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
1265
- ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}) });
1864
+ // The Hook's own per-pane app-server (codex-servers.ts) runs its hooks
1865
+ // with that pane's variables, so they are trusted like a pane's own.
1866
+ const ownServer = source === "codex" && codexServerId.safeParse(process.env[CODEX_SERVER_ENV]).success;
1867
+ const daemon = source === "codex" && !ownServer && await underCodexDaemon().catch(() => false);
1868
+ // Codex asks this hook before its automatic reviewer: say when that
1869
+ // reviewer, not the owner, will decide.
1870
+ const autoReview = source === "codex" && event === "PermissionRequest" && await codexAutoReview(value.transcript_path);
1871
+ // A worker the Hook launched with its brief carries that dispatch's id. A
1872
+ // daemon's variables belong to another pane, so it sends none.
1873
+ const dispatchId = !daemon && (event === "SessionStart" || event === "UserPromptSubmit") && briefId.safeParse(process.env[DISPATCH_ID_ENV]).success
1874
+ ? process.env[DISPATCH_ID_ENV] : undefined;
1875
+ const data = JSON.stringify({ target, event, ...(daemon ? { daemon: true } : {}), ...(autoReview ? { autoReview: true } : {}), ...(dispatchId ? { dispatchId } : {}),
1876
+ ...(source === "claude" && typeof value.transcript_path === "string" ? { transcript: value.transcript_path.slice(0, 4096) } : {}),
1877
+ tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
1878
+ ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
1879
+ ...(event === "Stop" ? stopFacts(value) : {}) });
1266
1880
  await new Promise(resolve => {
1267
- const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 : 1500,
1881
+ const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 : 12_000,
1268
1882
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
1269
1883
  let result = "";
1270
1884
  res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384)