@phren/cli 0.3.11 → 0.3.13
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.
- package/dist/bridge/account-usage.d.ts +124 -0
- package/dist/bridge/account-usage.js +258 -0
- package/dist/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +5 -0
- package/dist/bridge/agent-hooks.d.ts +162 -5
- package/dist/bridge/agent-hooks.js +682 -49
- package/dist/bridge/approval-summary.d.ts +16 -0
- package/dist/bridge/approval-summary.js +133 -0
- package/dist/bridge/authority-command.d.ts +20 -0
- package/dist/bridge/authority-command.js +120 -0
- package/dist/bridge/authority.d.ts +223 -0
- package/dist/bridge/authority.js +231 -0
- package/dist/bridge/claude-account-setup.d.ts +14 -0
- package/dist/bridge/claude-account-setup.js +69 -0
- package/dist/bridge/claude-accounts.d.ts +49 -0
- package/dist/bridge/claude-accounts.js +195 -0
- package/dist/bridge/code-routes.js +2 -2
- package/dist/bridge/codex-app-server.d.ts +144 -0
- package/dist/bridge/codex-app-server.js +319 -0
- package/dist/bridge/codex-auth-refresh.d.ts +33 -0
- package/dist/bridge/codex-auth-refresh.js +71 -0
- package/dist/bridge/codex-hook-trust.d.ts +27 -0
- package/dist/bridge/codex-hook-trust.js +237 -0
- package/dist/bridge/codex-question-reply.d.ts +16 -0
- package/dist/bridge/codex-question-reply.js +57 -0
- package/dist/bridge/codex-review-mode.d.ts +10 -0
- package/dist/bridge/codex-review-mode.js +74 -0
- package/dist/bridge/codex-servers.d.ts +217 -0
- package/dist/bridge/codex-servers.js +636 -0
- package/dist/bridge/command.js +97 -4
- package/dist/bridge/computer-identity.d.ts +75 -0
- package/dist/bridge/computer-identity.js +166 -0
- package/dist/bridge/conductor-group.d.ts +91 -8
- package/dist/bridge/conductor-group.js +105 -9
- package/dist/bridge/conductor-role.d.ts +94 -0
- package/dist/bridge/conductor-role.js +176 -0
- package/dist/bridge/conductor-sets.d.ts +20 -0
- package/dist/bridge/conductor-sets.js +59 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +82 -12
- package/dist/bridge/dispatch-returns.d.ts +128 -19
- package/dist/bridge/dispatch-returns.js +371 -54
- package/dist/bridge/dispatch.d.ts +128 -3
- package/dist/bridge/dispatch.js +303 -42
- package/dist/bridge/fanouts.d.ts +7 -1
- package/dist/bridge/fanouts.js +39 -4
- package/dist/bridge/folder-trust.d.ts +56 -0
- package/dist/bridge/folder-trust.js +195 -0
- package/dist/bridge/grants.d.ts +22 -1
- package/dist/bridge/grants.js +57 -9
- package/dist/bridge/hand-off-queue.d.ts +74 -0
- package/dist/bridge/hand-off-queue.js +235 -0
- package/dist/bridge/hand-off.d.ts +30 -10
- package/dist/bridge/hand-off.js +79 -46
- package/dist/bridge/harness-status.d.ts +11 -0
- package/dist/bridge/harness-status.js +32 -0
- package/dist/bridge/harnesses.d.ts +39 -0
- package/dist/bridge/harnesses.js +65 -0
- package/dist/bridge/health.d.ts +2 -0
- package/dist/bridge/health.js +1 -1
- package/dist/bridge/herdr.d.ts +11 -2
- package/dist/bridge/herdr.js +98 -23
- package/dist/bridge/hook-fast.d.ts +4 -0
- package/dist/bridge/hook-fast.js +68 -0
- package/dist/bridge/install.d.ts +16 -1
- package/dist/bridge/install.js +102 -21
- package/dist/bridge/launch-brief.d.ts +96 -0
- package/dist/bridge/launch-brief.js +164 -0
- package/dist/bridge/model-switch.d.ts +3 -0
- package/dist/bridge/model-switch.js +17 -1
- package/dist/bridge/models.d.ts +8 -4
- package/dist/bridge/models.js +24 -8
- package/dist/bridge/mux-wire.d.ts +9 -0
- package/dist/bridge/mux-wire.js +19 -0
- package/dist/bridge/opencode-pane-server.d.ts +113 -0
- package/dist/bridge/opencode-pane-server.js +332 -0
- package/dist/bridge/opencode-panes.d.ts +111 -0
- package/dist/bridge/opencode-panes.js +295 -0
- package/dist/bridge/pane-accounts.d.ts +8 -0
- package/dist/bridge/pane-accounts.js +46 -0
- package/dist/bridge/pane-status.d.ts +12 -0
- package/dist/bridge/pane-status.js +50 -1
- package/dist/bridge/prompt-startup.d.ts +5 -0
- package/dist/bridge/prompt-startup.js +24 -0
- package/dist/bridge/protocol.d.ts +5 -0
- package/dist/bridge/protocol.js +4 -0
- package/dist/bridge/push.d.ts +11 -4
- package/dist/bridge/push.js +27 -4
- package/dist/bridge/questions.d.ts +37 -2
- package/dist/bridge/questions.js +158 -15
- package/dist/bridge/resources.d.ts +9 -3
- package/dist/bridge/resources.js +24 -8
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-format.js +3 -0
- package/dist/bridge/schedule-launch.d.ts +2 -1
- package/dist/bridge/schedule-launch.js +27 -53
- package/dist/bridge/schedule-watch.d.ts +24 -1
- package/dist/bridge/schedule-watch.js +89 -2
- package/dist/bridge/server-launch.d.ts +22 -5
- package/dist/bridge/server-launch.js +238 -32
- package/dist/bridge/server-overview.d.ts +10 -3
- package/dist/bridge/server-overview.js +32 -15
- package/dist/bridge/server-pane-routes.d.ts +3 -0
- package/dist/bridge/server-pane-routes.js +150 -18
- package/dist/bridge/server-routes.d.ts +11 -0
- package/dist/bridge/server-routes.js +214 -36
- package/dist/bridge/server-stream.d.ts +2 -0
- package/dist/bridge/server-stream.js +22 -8
- package/dist/bridge/server.d.ts +6 -1
- package/dist/bridge/server.js +58 -13
- package/dist/bridge/session-activity.d.ts +93 -0
- package/dist/bridge/session-activity.js +139 -0
- package/dist/bridge/session-rename.d.ts +48 -0
- package/dist/bridge/session-rename.js +190 -0
- package/dist/bridge/session-servers.js +2 -2
- package/dist/bridge/settings-switch.d.ts +60 -0
- package/dist/bridge/settings-switch.js +287 -0
- package/dist/bridge/speech-voice.d.ts +55 -0
- package/dist/bridge/speech-voice.js +132 -0
- package/dist/bridge/speech.d.ts +70 -11
- package/dist/bridge/speech.js +169 -41
- package/dist/bridge/stalls.d.ts +22 -0
- package/dist/bridge/stalls.js +57 -0
- package/dist/bridge/sudo.d.ts +209 -0
- package/dist/bridge/sudo.js +501 -0
- package/dist/bridge/terminal-herdr.js +9 -3
- package/dist/bridge/terminal-tmux.d.ts +15 -3
- package/dist/bridge/terminal-tmux.js +103 -13
- package/dist/bridge/terminal.d.ts +27 -4
- package/dist/bridge/terminal.js +8 -1
- package/dist/bridge/transcript-claude.d.ts +4 -0
- package/dist/bridge/transcript-claude.js +186 -16
- package/dist/bridge/transcript-codex.d.ts +0 -2
- package/dist/bridge/transcript-codex.js +29 -4
- package/dist/bridge/transcript-preview.d.ts +1 -0
- package/dist/bridge/transcript-preview.js +24 -4
- package/dist/bridge/transcripts.d.ts +15 -2
- package/dist/bridge/transcripts.js +47 -16
- package/dist/bridge/turn-records.d.ts +85 -0
- package/dist/bridge/turn-records.js +143 -0
- package/dist/bridge/uploads.d.ts +3 -0
- package/dist/bridge/uploads.js +14 -0
- package/dist/bridge/usage.d.ts +56 -10
- package/dist/bridge/usage.js +190 -45
- package/dist/bridge-hook.mjs +27975 -20636
- package/dist/cli/claude-unmanaged.d.ts +12 -0
- package/dist/cli/claude-unmanaged.js +105 -0
- package/dist/cli/schedules.js +2 -1
- package/dist/cli/session-start.js +10 -1
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.js +31 -6
- package/dist/data/task-receipts.d.ts +19 -0
- package/dist/data/task-receipts.js +68 -0
- package/dist/data/tasks.js +4 -1
- package/dist/generated/memory-ui-graph.browser.js +63 -63
- package/dist/graph-core/model.js +24 -3
- package/dist/graph-core/types.d.ts +4 -1
- package/dist/graph-core/types.js +1 -0
- package/dist/init/init-preset.js +7 -3
- package/dist/init/init-uninstall.js +2 -11
- package/dist/init/teardown.d.ts +3 -0
- package/dist/init/teardown.js +47 -0
- package/dist/link/context.js +21 -9
- package/dist/mcp/plugin-mode.js +1 -1
- package/dist/memory-ui-graph.runtime.js +63 -63
- package/dist/modules/code-package.d.ts +1 -0
- package/dist/modules/code-package.js +36 -7
- package/dist/modules/registry.js +17 -16
- package/dist/profile-store.d.ts +6 -0
- package/dist/profile-store.js +25 -1
- package/dist/shell/graph/glyphs.js +4 -0
- package/dist/shell/graph/graph-view.js +2 -0
- package/dist/status.js +7 -1
- package/dist/sync/task-claim.js +3 -2
- package/dist/task/lifecycle.js +25 -4
- package/dist/test-global-setup.js +5 -0
- package/dist/tools/dispatch.js +52 -4
- package/dist/tools/tasks.js +10 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +87 -4
- package/starter/global/AGENTS.md +4 -0
- package/starter/global/skills/conductor/SKILL.md +51 -4
|
@@ -6,24 +6,34 @@ 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,
|
|
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, briefLabel, DISPATCH_ID_ENV, recordBriefArrival } from "./launch-brief.js";
|
|
34
|
+
import { SudoBroker } from "./sudo.js";
|
|
35
|
+
import { CODEX_SERVER_ENV, codexServerId, codexServers } from "./codex-servers.js";
|
|
36
|
+
import { paneClient, paneKey, PaneServerWatcher, rootSession, servedPane } from "./opencode-panes.js";
|
|
27
37
|
export { permissionPrompt, terminalChoice, visibleTerminalChoice } from "./terminal-choice.js";
|
|
28
38
|
export { ApprovalWatchLeases, PushBindingStore, recordedSession } from "./agent-hook-stores.js";
|
|
29
39
|
const APPROVAL_SWEEP_MS = 2_000;
|
|
@@ -38,11 +48,45 @@ const APPROVAL_HOLD_MS = (() => {
|
|
|
38
48
|
})();
|
|
39
49
|
/** A pane's terminal dialog is read at most once per this window. */
|
|
40
50
|
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
51
|
/** How long a pushed terminal dialog can be answered from its notification. */
|
|
43
52
|
const DIALOG_PUSH_MS = 10 * 60_000;
|
|
44
53
|
const FANOUT_SWEEP_MS = 5_000;
|
|
54
|
+
/** How far ahead a served OpenCode pane's ask expires. OpenCode waits for as
|
|
55
|
+
* long as it takes, so this is only a horizon: every listing that still
|
|
56
|
+
* returns the ask (each ask event, reconnect and the Hook's 5 s tick) moves it
|
|
57
|
+
* forward, and the card goes only when the ask is gone or the pane is dead. */
|
|
58
|
+
const SERVED_ASK_MS = 60 * 60_000;
|
|
45
59
|
const FANOUT_ARCHIVE_MS = 60 * 60 * 1000;
|
|
60
|
+
/** The approval card's tool and input for an app-server request, in the
|
|
61
|
+
* shapes `approvalSummary` and the phone already read for Codex's hook.
|
|
62
|
+
* Undefined for questions (`item/tool/requestUserInput`) and MCP
|
|
63
|
+
* elicitations, which stay in the pane. */
|
|
64
|
+
export function appServerApproval(request) {
|
|
65
|
+
const params = request.params;
|
|
66
|
+
const reason = typeof params.reason === "string" && params.reason ? { reason: params.reason } : {};
|
|
67
|
+
if (request.method === "item/commandExecution/requestApproval") {
|
|
68
|
+
return { tool: "Bash", input: { ...(typeof params.command === "string" ? { command: params.command } : {}),
|
|
69
|
+
...(typeof params.cwd === "string" ? { cwd: params.cwd } : {}), ...reason } };
|
|
70
|
+
}
|
|
71
|
+
if (request.method === "item/fileChange/requestApproval") {
|
|
72
|
+
const changes = objects(params.changes);
|
|
73
|
+
const verb = (change) => object(change.kind).type === "add" ? "Add" : object(change.kind).type === "delete" ? "Delete" : "Update";
|
|
74
|
+
const patch = changes.filter(change => typeof change.path === "string").map(change => `*** ${verb(change)} File: ${change.path}`).join("\n");
|
|
75
|
+
return { tool: "apply_patch", input: { ...(patch ? { patch } : {}), ...(typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}), ...reason } };
|
|
76
|
+
}
|
|
77
|
+
if (request.method === "item/permissions/requestApproval")
|
|
78
|
+
return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...reason } };
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
/** The app-server's answer for the phone's allow or deny (T3's
|
|
82
|
+
* CodexSessionRuntime shapes: accept / decline, a permission grant or none). */
|
|
83
|
+
export function appServerDecision(request, allow) {
|
|
84
|
+
if (request.method === "item/permissions/requestApproval")
|
|
85
|
+
return { permissions: allow ? object(request.params.permissions) : {}, scope: "turn" };
|
|
86
|
+
return { decision: allow ? "accept" : "decline" };
|
|
87
|
+
}
|
|
88
|
+
/** How long a dispatching Hook's poll keeps a worker pane's permission asks held. */
|
|
89
|
+
const DISPATCH_LEASE_MS = 45_000;
|
|
46
90
|
/** A conductor `dispatch` or `hand_off` permission ask the Hook can answer
|
|
47
91
|
* itself under a standing grant, or offer the phone two grant-writing answers. */
|
|
48
92
|
export function conductorCall(tool, input) {
|
|
@@ -63,11 +107,19 @@ export function conductorCall(tool, input) {
|
|
|
63
107
|
const computer = typeof fields.computer === "string" ? fields.computer : undefined;
|
|
64
108
|
return { action, ...(project ? { project } : {}), ...(computer ? { computer } : {}) };
|
|
65
109
|
}
|
|
110
|
+
/** As long as a typed prompt's own record guards it (`expectDelivery`). */
|
|
111
|
+
const TRACK_MS = 600_000;
|
|
66
112
|
/** What the agent hands its UserPromptSubmit hook is the terminal's pasted
|
|
67
|
-
* form of what Phren typed; compare the words, not the wrapping.
|
|
113
|
+
* form of what Phren typed; compare the words, not the wrapping. Claude Code
|
|
114
|
+
* also takes each attached picture's path line out of the text and puts an
|
|
115
|
+
* "[Image #N]" label at the front, so neither side keeps picture paths or
|
|
116
|
+
* labels. */
|
|
68
117
|
function promptKey(text) {
|
|
69
|
-
return unwrapPastedContent(text).
|
|
118
|
+
return unwrapPastedContent(text).split("\n").filter(line => !PICTURE_PATH_LINE.test(line)).join("\n")
|
|
119
|
+
.replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
|
|
70
120
|
}
|
|
121
|
+
const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
|
|
122
|
+
const trackKey = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
|
|
71
123
|
/** This socket is deliberately separate from the phone's HTTP pipe. Only local
|
|
72
124
|
* agent callbacks can register identities or create an approval request. */
|
|
73
125
|
export class AgentHooks {
|
|
@@ -81,6 +133,8 @@ export class AgentHooks {
|
|
|
81
133
|
* party that knows which conversation consumed the text, so it is the one
|
|
82
134
|
* that can refuse it when that is not the conversation the phone meant. */
|
|
83
135
|
deliveries = new Map();
|
|
136
|
+
/** Phone messages by delivery id, until TRACK_MS: see `trackDelivery`. */
|
|
137
|
+
tracked = new Map();
|
|
84
138
|
/** The permission request a conversation is drawing in its own terminal
|
|
85
139
|
* because nobody was there to hold it: what the phone shows above its
|
|
86
140
|
* answer keys until the pane stops waiting. `dialog` marks a choice parsed
|
|
@@ -114,8 +168,18 @@ export class AgentHooks {
|
|
|
114
168
|
* action, what an answer from the notification types. */
|
|
115
169
|
dialogPushes = new Map();
|
|
116
170
|
dialogActions = new Map();
|
|
117
|
-
/**
|
|
171
|
+
/** Terminal dialogs offered to a dispatching Hook, by pane: the `dialog-` action minted for the dialog's current title. */
|
|
172
|
+
forwardedDialogs = new Map();
|
|
173
|
+
/** Requests this Hook pushed to its own phone on behalf of a dispatched worker on another computer: action -> the answer to send back. */
|
|
174
|
+
forwardedPushes = new Map();
|
|
175
|
+
/** Panes a dispatching Hook polled lately (`server\npane\nsource` -> expiry). */
|
|
176
|
+
dispatchLeases = new Map();
|
|
177
|
+
/** opencode permission asks seen on disk or listed by a served pane, by request id. */
|
|
118
178
|
opencode = new Map();
|
|
179
|
+
/** Questions served OpenCode panes are asking, by question id. */
|
|
180
|
+
servedQuestions = new Map();
|
|
181
|
+
/** One event subscription per served OpenCode pane; ticked with the Hook. */
|
|
182
|
+
paneServers = new PaneServerWatcher({ asks: (entry, client, asks) => this.servedAsks(entry, client, asks), gone: key => this.servedGone(key) });
|
|
119
183
|
closed = false;
|
|
120
184
|
opencodeSweep;
|
|
121
185
|
opencodeLive = new Set();
|
|
@@ -128,9 +192,26 @@ export class AgentHooks {
|
|
|
128
192
|
fanoutSeen = new Map();
|
|
129
193
|
fanoutTimer;
|
|
130
194
|
fanoutArchiveTimer;
|
|
195
|
+
/** The name the phone paired with (macOS Computer Name), for approval alerts;
|
|
196
|
+
* the short host name until that lookup answers. */
|
|
197
|
+
computerName = hostname().replace(/\.local$/i, "").split(".")[0] || "Computer";
|
|
198
|
+
/** sudo -A requests from askpass, answered from the phone (sudo.ts). */
|
|
199
|
+
sudo;
|
|
131
200
|
constructor(push = new ApprovalPushService(), modules) {
|
|
132
201
|
this.push = push;
|
|
133
202
|
this.modules = modules;
|
|
203
|
+
void computerDisplayName().then(name => { this.computerName = name; }, () => { });
|
|
204
|
+
this.sudo = new SudoBroker({ computer: () => this.computerName, push, label: briefLabel,
|
|
205
|
+
describe: async (place) => {
|
|
206
|
+
const s = await snapshot(place.server);
|
|
207
|
+
const pane = findPane(s, place);
|
|
208
|
+
if (!pane)
|
|
209
|
+
return undefined;
|
|
210
|
+
const tab = objects(s.tabs).find(item => item.tab_id === place.tab && item.workspace_id === place.workspace);
|
|
211
|
+
const workspace = objects(s.workspaces).find(item => item.workspace_id === place.workspace);
|
|
212
|
+
const label = [tab?.label, workspace?.label].find(value => typeof value === "string" && value.trim());
|
|
213
|
+
return { ...(typeof pane.agent === "string" ? { source: pane.agent } : {}), ...(label ? { label } : {}) };
|
|
214
|
+
} });
|
|
134
215
|
}
|
|
135
216
|
approvalsDirectory() { return path.join(phrenStoreRoot(), ".runtime", "approvals"); }
|
|
136
217
|
scheduleOpencodeSweep() {
|
|
@@ -188,30 +269,224 @@ export class AgentHooks {
|
|
|
188
269
|
const expiresAt = typeof request.expiresAt === "string" ? Date.parse(request.expiresAt) : NaN;
|
|
189
270
|
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now())
|
|
190
271
|
continue;
|
|
272
|
+
const pane = target && !asking?.worktree ? findPane(await snapshot(target.server).catch(() => ({})), { workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source }) : undefined;
|
|
273
|
+
const cwd = asking?.worktree ?? (pane ? await trustedDirectory(pane).catch(() => undefined) : undefined);
|
|
274
|
+
const summary = approvalSummary({ tool: String(request.type ?? ""), input: request, message: typeof request.message === "string" ? request.message : undefined, cwd });
|
|
191
275
|
// The answer route checks an action id by the parent's source: a UUID
|
|
192
276
|
// for Claude and Codex, a plain token for opencode.
|
|
193
277
|
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 } : {}) });
|
|
278
|
+
this.opencode.set(id, { ...(target ? { target } : {}), request, requestLine: summary.request, expiresAt, ...(fanout ? { fanout } : {}) });
|
|
195
279
|
if (!this.push.available)
|
|
196
280
|
continue;
|
|
197
281
|
const binding = randomUUID();
|
|
198
282
|
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
283
|
// The held request is what stops a later sweep from pushing again; a
|
|
202
284
|
// 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),
|
|
285
|
+
void this.push.notify({ binding, provider: "opencode", question: false, expiresAt: String(request.expiresAt),
|
|
286
|
+
...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
|
|
204
287
|
.then(delivered => { if (!delivered)
|
|
205
288
|
this.pushBindings.dropAction(id); })
|
|
206
289
|
.catch(() => { });
|
|
207
290
|
}
|
|
208
291
|
for (const [id, held] of this.opencode) {
|
|
292
|
+
if (held.served)
|
|
293
|
+
continue;
|
|
209
294
|
if (!live.has(id) || held.expiresAt <= Date.now()) {
|
|
210
295
|
this.opencode.delete(id);
|
|
211
296
|
this.pushBindings.dropAction(id);
|
|
212
297
|
}
|
|
213
298
|
}
|
|
214
299
|
}
|
|
300
|
+
/** The pane a served OpenCode ask belongs to, as the phone names it: the
|
|
301
|
+
* pane's place from its terminal, and the root of the asking session (a
|
|
302
|
+
* subagent's ask shows on the conversation the pane shows). */
|
|
303
|
+
async servedTarget(entry, client, session) {
|
|
304
|
+
if (typeof session !== "string")
|
|
305
|
+
return undefined;
|
|
306
|
+
const root = await rootSession(client, session);
|
|
307
|
+
const state = await snapshot(entry.server).catch(() => undefined);
|
|
308
|
+
const pane = objects(state?.panes).find(value => value.pane_id === entry.pane);
|
|
309
|
+
if (!pane)
|
|
310
|
+
return undefined;
|
|
311
|
+
const parsed = targetSchema.safeParse({ server: entry.server, workspace: pane.workspace_id, tab: pane.tab_id, pane: entry.pane, source: "opencode", session: root });
|
|
312
|
+
return parsed.success ? parsed.data : undefined;
|
|
313
|
+
}
|
|
314
|
+
/** Everything a served pane is asking right now. New asks become the same
|
|
315
|
+
* cards (and pushes) as the plugin's file asks; asks no longer listed were
|
|
316
|
+
* answered in the TUI or went away, and their cards go with them. */
|
|
317
|
+
async servedAsks(entry, client, asks) {
|
|
318
|
+
if (this.closed)
|
|
319
|
+
return;
|
|
320
|
+
const key = paneKey(entry), where = { key, server: entry.server, pane: entry.pane };
|
|
321
|
+
const expiresAt = Date.now() + SERVED_ASK_MS;
|
|
322
|
+
const permissions = new Set();
|
|
323
|
+
for (const ask of asks.permissions) {
|
|
324
|
+
if (typeof ask.id !== "string" || !/^[A-Za-z0-9_]{1,200}$/.test(ask.id))
|
|
325
|
+
continue;
|
|
326
|
+
permissions.add(ask.id);
|
|
327
|
+
const known = this.opencode.get(ask.id);
|
|
328
|
+
if (known) {
|
|
329
|
+
if (known.served?.key === key) {
|
|
330
|
+
known.expiresAt = expiresAt;
|
|
331
|
+
known.request.expiresAt = new Date(expiresAt).toISOString();
|
|
332
|
+
this.pushBindings.extendAction(ask.id, expiresAt);
|
|
333
|
+
}
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const target = await this.servedTarget(entry, client, ask.sessionID).catch(() => undefined);
|
|
337
|
+
if (this.closed)
|
|
338
|
+
return;
|
|
339
|
+
const type = typeof ask.permission === "string" && ask.permission ? ask.permission.slice(0, 200) : "action";
|
|
340
|
+
const patterns = (Array.isArray(ask.patterns) ? ask.patterns : []).filter((value) => typeof value === "string").slice(0, 32);
|
|
341
|
+
const metadata = object(ask.metadata);
|
|
342
|
+
const detail = [patterns.join(", "), metadata.command, metadata.description, metadata.filepath, metadata.path, metadata.url]
|
|
343
|
+
.find((value) => typeof value === "string" && !!value);
|
|
344
|
+
const message = (detail ? `${type}: ${detail}` : `opencode asks to use ${type}.`).slice(0, 2000);
|
|
345
|
+
const request = { id: ask.id, sessionID: ask.sessionID, type, title: `Allow ${type}?`, message, pattern: patterns,
|
|
346
|
+
...(typeof metadata.command === "string" ? { metadata: { command: metadata.command } } : {}), expiresAt: new Date(expiresAt).toISOString() };
|
|
347
|
+
const summary = approvalSummary({ tool: type, input: request, message, cwd: entry.directory });
|
|
348
|
+
this.opencode.set(ask.id, { ...(target ? { target } : {}), request, requestLine: summary.request, expiresAt, served: where });
|
|
349
|
+
if (!this.push.available)
|
|
350
|
+
continue;
|
|
351
|
+
const binding = randomUUID();
|
|
352
|
+
this.pushBindings.add(binding, { action: ask.id, expiresAt });
|
|
353
|
+
void this.push.notify({ binding, provider: "opencode", question: false, expiresAt: String(request.expiresAt),
|
|
354
|
+
project: path.basename(entry.directory), computer: this.computerName, ...summary })
|
|
355
|
+
.then(delivered => { if (!delivered)
|
|
356
|
+
this.pushBindings.dropAction(ask.id); })
|
|
357
|
+
.catch(() => { });
|
|
358
|
+
}
|
|
359
|
+
for (const [id, held] of this.opencode) {
|
|
360
|
+
if (held.served?.key === key && !permissions.has(id)) {
|
|
361
|
+
this.opencode.delete(id);
|
|
362
|
+
this.pushBindings.dropAction(id);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
const questions = new Set();
|
|
366
|
+
for (const ask of asks.questions) {
|
|
367
|
+
if (typeof ask.id !== "string" || !/^[A-Za-z0-9_]{1,200}$/.test(ask.id))
|
|
368
|
+
continue;
|
|
369
|
+
questions.add(ask.id);
|
|
370
|
+
if (this.servedQuestions.has(ask.id))
|
|
371
|
+
continue;
|
|
372
|
+
const raw = Array.isArray(ask.questions) ? ask.questions : [];
|
|
373
|
+
// OpenCode's `multiple` is the phone's multiSelect. A set the phone
|
|
374
|
+
// cannot show whole stays in the TUI.
|
|
375
|
+
const mapped = terminalQuestions({ questions: raw.map(value => ({ ...object(value), multiSelect: object(value).multiple === true })) });
|
|
376
|
+
if (!mapped || mapped.length !== raw.length)
|
|
377
|
+
continue;
|
|
378
|
+
const target = await this.servedTarget(entry, client, ask.sessionID).catch(() => undefined);
|
|
379
|
+
if (this.closed)
|
|
380
|
+
return;
|
|
381
|
+
this.servedQuestions.set(ask.id, { ...where, ...(target ? { target } : {}), question: ask, questions: mapped, at: Date.now() });
|
|
382
|
+
while (this.servedQuestions.size > 64)
|
|
383
|
+
this.servedQuestions.delete(this.servedQuestions.keys().next().value);
|
|
384
|
+
}
|
|
385
|
+
for (const [id, held] of this.servedQuestions)
|
|
386
|
+
if (held.key === key && !questions.has(id))
|
|
387
|
+
this.servedQuestions.delete(id);
|
|
388
|
+
}
|
|
389
|
+
/** A served pane's process is gone: nothing it asked can be answered. */
|
|
390
|
+
servedGone(key) {
|
|
391
|
+
for (const [id, held] of this.opencode)
|
|
392
|
+
if (held.served?.key === key) {
|
|
393
|
+
this.opencode.delete(id);
|
|
394
|
+
this.pushBindings.dropAction(id);
|
|
395
|
+
}
|
|
396
|
+
for (const [id, held] of this.servedQuestions)
|
|
397
|
+
if (held.key === key)
|
|
398
|
+
this.servedQuestions.delete(id);
|
|
399
|
+
}
|
|
400
|
+
/** The question a served OpenCode pane is asking, in the shape the phone
|
|
401
|
+
* answers Claude's AskUserQuestion with (`/v1/questions/answer`). */
|
|
402
|
+
servedQuestion(target) {
|
|
403
|
+
if (target.source !== "opencode")
|
|
404
|
+
return undefined;
|
|
405
|
+
const key = JSON.stringify(target);
|
|
406
|
+
const held = [...this.servedQuestions.values()].find(value => value.target && JSON.stringify(value.target) === key);
|
|
407
|
+
if (!held)
|
|
408
|
+
return undefined;
|
|
409
|
+
const title = held.questions[0].question;
|
|
410
|
+
return { toolName: "AskUserQuestion", actionId: held.question.id, message: title,
|
|
411
|
+
request: approvalSummary({ tool: "Question", message: title, question: true }).request,
|
|
412
|
+
choice: questionChoice(held.questions, 0), questions: held.questions, questionIndex: 0, at: new Date(held.at).toISOString() };
|
|
413
|
+
}
|
|
414
|
+
servedClient(server, pane) {
|
|
415
|
+
const entry = servedPane(server, pane);
|
|
416
|
+
if (!entry)
|
|
417
|
+
throw new BridgeError(409, "This approval is no longer pending.");
|
|
418
|
+
return paneClient(entry);
|
|
419
|
+
}
|
|
420
|
+
/** Answers a served pane's permission ask over its own API. */
|
|
421
|
+
async answerServed(id, held, decision) {
|
|
422
|
+
if (!["approve", "deny"].includes(String(decision)))
|
|
423
|
+
throw new BridgeError(400, "The approval answer is not valid.");
|
|
424
|
+
const served = held.served;
|
|
425
|
+
const client = this.servedClient(served.server, served.pane);
|
|
426
|
+
try {
|
|
427
|
+
await client.replyPermission(id, decision === "approve" ? "once" : "reject");
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
throw new BridgeError(409, "This approval is no longer pending.");
|
|
431
|
+
}
|
|
432
|
+
this.opencode.delete(id);
|
|
433
|
+
this.pushBindings.dropAction(id);
|
|
434
|
+
}
|
|
435
|
+
/** The phone's answers to a served pane's question: the labels it chose
|
|
436
|
+
* (and a typed answer) per question, for exactly the questions it shows. */
|
|
437
|
+
async answerServedQuestion(target, questions, answers) {
|
|
438
|
+
const key = JSON.stringify(target);
|
|
439
|
+
const found = [...this.servedQuestions.entries()].find(([, value]) => value.target && JSON.stringify(value.target) === key);
|
|
440
|
+
if (!found)
|
|
441
|
+
throw new BridgeError(409, "This question is no longer pending.");
|
|
442
|
+
const [id, held] = found;
|
|
443
|
+
const same = held.questions.length === questions.length && held.questions.every((question, index) => question.question === questions[index].question.trim()
|
|
444
|
+
&& question.options.length === questions[index].options.length
|
|
445
|
+
&& question.options.every((option, position) => option.label === questions[index].options[position].label.trim()));
|
|
446
|
+
if (!same)
|
|
447
|
+
throw new BridgeError(409, "That question has changed. Open phren to answer it.");
|
|
448
|
+
await validateTarget(target);
|
|
449
|
+
const labels = answers.map((answer, index) => [...answer.options.map(option => held.questions[index].options[option].label), ...(answer.text ? [answer.text] : [])]);
|
|
450
|
+
try {
|
|
451
|
+
await this.servedClient(held.server, held.pane).replyQuestion(id, labels);
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
throw new BridgeError(409, "This question is no longer pending.");
|
|
455
|
+
}
|
|
456
|
+
this.servedQuestions.delete(id);
|
|
457
|
+
}
|
|
458
|
+
/** Keys the phone sends to a served OpenCode pane that its API answers
|
|
459
|
+
* better than the terminal: Esc declines a pending question or stops a
|
|
460
|
+
* working turn (`session.abort`), and a digit answers a pending
|
|
461
|
+
* single-question, single-choice set. False leaves the keys to the pane. */
|
|
462
|
+
async servedKeys(target, keys, status) {
|
|
463
|
+
if (target.source !== "opencode")
|
|
464
|
+
return false;
|
|
465
|
+
const entry = servedPane(target.server, target.pane);
|
|
466
|
+
if (!entry)
|
|
467
|
+
return false;
|
|
468
|
+
const client = paneClient(entry), key = JSON.stringify(target);
|
|
469
|
+
const question = [...this.servedQuestions.entries()].find(([, value]) => value.target && JSON.stringify(value.target) === key);
|
|
470
|
+
const escape = keys.length > 0 && keys.every(value => value === "Escape");
|
|
471
|
+
if (question && escape) {
|
|
472
|
+
await client.rejectQuestion(question[0]).catch(() => { throw new BridgeError(409, "This question is no longer pending."); });
|
|
473
|
+
this.servedQuestions.delete(question[0]);
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
if (question && keys.length === 1 && /^[1-9]$/.test(keys[0]) && question[1].questions.length === 1 && !question[1].questions[0].multiSelect) {
|
|
477
|
+
const option = question[1].questions[0].options[Number(keys[0]) - 1];
|
|
478
|
+
if (!option)
|
|
479
|
+
throw new BridgeError(400, "Choose an available answer.");
|
|
480
|
+
await client.replyQuestion(question[0], [[option.label]]).catch(() => { throw new BridgeError(409, "This question is no longer pending."); });
|
|
481
|
+
this.servedQuestions.delete(question[0]);
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
if (escape && status === "working") {
|
|
485
|
+
// A failed abort leaves Esc to the terminal, as before.
|
|
486
|
+
return client.abort(target.session).then(done => done === true, () => false);
|
|
487
|
+
}
|
|
488
|
+
return false;
|
|
489
|
+
}
|
|
215
490
|
/** A session's exact pane. A recorded binding carries the full target; when
|
|
216
491
|
* there is none, Herdr's explicit session identity names the pane. */
|
|
217
492
|
async resolveTarget(source, session) {
|
|
@@ -314,16 +589,22 @@ export class AgentHooks {
|
|
|
314
589
|
* after `waitMs`: a busy agent queues typed input and submits it only when
|
|
315
590
|
* its turn ends, so the record outlives the wait (up to ten minutes) and a
|
|
316
591
|
* late submission to the wrong conversation is still refused. */
|
|
317
|
-
expectDelivery(target, text, waitMs = 1_500) {
|
|
592
|
+
expectDelivery(target, text, waitMs = 1_500, signal) {
|
|
318
593
|
const key = promptKey(text);
|
|
319
|
-
if (!key)
|
|
594
|
+
if (!key || signal?.aborted)
|
|
320
595
|
return Promise.resolve("pending");
|
|
321
596
|
return new Promise(resolve => {
|
|
322
597
|
let settled = false;
|
|
323
598
|
const list = this.deliveries.get(key) ?? [];
|
|
324
|
-
const remove = () => {
|
|
325
|
-
|
|
326
|
-
this.deliveries.
|
|
599
|
+
const remove = () => {
|
|
600
|
+
signal?.removeEventListener("abort", cancel);
|
|
601
|
+
const current = this.deliveries.get(key) ?? [];
|
|
602
|
+
const index = current.indexOf(delivery);
|
|
603
|
+
if (index >= 0)
|
|
604
|
+
current.splice(index, 1);
|
|
605
|
+
if (!current.length)
|
|
606
|
+
this.deliveries.delete(key);
|
|
607
|
+
};
|
|
327
608
|
const settle = (outcome) => {
|
|
328
609
|
if (!settled) {
|
|
329
610
|
settled = true;
|
|
@@ -337,6 +618,10 @@ export class AgentHooks {
|
|
|
337
618
|
}
|
|
338
619
|
};
|
|
339
620
|
const delivery = { source: target.source, session: target.session, settle, timer: setTimeout(() => settle("pending"), waitMs) };
|
|
621
|
+
// Only cancel after a provider explicitly refused before writing. A
|
|
622
|
+
// possibly delivered paste keeps its guard against the wrong session.
|
|
623
|
+
const cancel = () => { clearTimeout(delivery.timer); settle("pending"); remove(); };
|
|
624
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
340
625
|
delivery.timer.unref?.();
|
|
341
626
|
const expiry = setTimeout(remove, 600_000);
|
|
342
627
|
expiry.unref?.();
|
|
@@ -362,6 +647,35 @@ export class AgentHooks {
|
|
|
362
647
|
delivery.late = outcome => { clearTimeout(timer); delivery.late = undefined; resolve(outcome); };
|
|
363
648
|
});
|
|
364
649
|
}
|
|
650
|
+
/** Remember a phone message's outcome under its delivery id. A queued one
|
|
651
|
+
* is tracked only while its typed record still waits for the agent's hook,
|
|
652
|
+
* so the hook's later answer always reaches it (`settleTracked`). */
|
|
653
|
+
trackDelivery(id, target, text, state) {
|
|
654
|
+
if (state === "queued" && !this.deliveryPending(target, text))
|
|
655
|
+
return;
|
|
656
|
+
const now = Date.now();
|
|
657
|
+
for (const [key, entry] of this.tracked)
|
|
658
|
+
if (now - entry.at > TRACK_MS)
|
|
659
|
+
this.tracked.delete(key);
|
|
660
|
+
while (this.tracked.size >= 512)
|
|
661
|
+
this.tracked.delete(this.tracked.keys().next().value);
|
|
662
|
+
this.tracked.set(id, { source: target.source, session: target.session, key: trackKey(text), state, at: now });
|
|
663
|
+
}
|
|
664
|
+
/** What became of the phone message `id` sent to `target`'s conversation:
|
|
665
|
+
* queued until the agent submits it, then delivered, or blocked when
|
|
666
|
+
* another conversation in the pane took it. Unknown when the Hook did not
|
|
667
|
+
* track it, it was for another conversation, or it is older than TRACK_MS. */
|
|
668
|
+
deliveryState(id, target) {
|
|
669
|
+
const entry = this.tracked.get(id);
|
|
670
|
+
return entry && entry.source === target.source && entry.session === target.session && Date.now() - entry.at <= TRACK_MS ? entry.state : "unknown";
|
|
671
|
+
}
|
|
672
|
+
/** The oldest queued message tracked for `delivery`'s conversation with these words. */
|
|
673
|
+
settleTracked(delivery, prompt, state) {
|
|
674
|
+
const key = trackKey(prompt);
|
|
675
|
+
const entry = [...this.tracked.values()].find(item => item.state === "queued" && item.key === key && item.source === delivery.source && item.session === delivery.session);
|
|
676
|
+
if (entry)
|
|
677
|
+
entry.state = state;
|
|
678
|
+
}
|
|
365
679
|
/** The conversation `target` just submitted `prompt`. Nothing Phren typed
|
|
366
680
|
* matches: a locally typed prompt, always allowed. Otherwise the oldest
|
|
367
681
|
* matching delivery decides: its own conversation consumes it; any other
|
|
@@ -369,22 +683,38 @@ export class AgentHooks {
|
|
|
369
683
|
* wrong agent and the phone can safely send it again. */
|
|
370
684
|
submitted(target, prompt) {
|
|
371
685
|
const list = this.deliveries.get(promptKey(prompt));
|
|
372
|
-
|
|
686
|
+
// The same words sent to two conversations at once: each one's own
|
|
687
|
+
// submission settles its own record, not whichever was typed first.
|
|
688
|
+
const delivery = list?.find(entry => entry.source === target.source && entry.session === target.session) ?? list?.[0];
|
|
373
689
|
if (!delivery)
|
|
374
690
|
return {};
|
|
375
|
-
|
|
691
|
+
const own = delivery.source === target.source && delivery.session === target.session;
|
|
692
|
+
this.settleTracked(delivery, prompt, own ? "delivered" : "blocked");
|
|
693
|
+
if (own) {
|
|
376
694
|
delivery.settle("delivered");
|
|
377
695
|
return {};
|
|
378
696
|
}
|
|
379
697
|
delivery.settle("blocked");
|
|
380
698
|
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
699
|
}
|
|
700
|
+
/** The conversation's own turn events, for dispatch returns (turn-records.ts).
|
|
701
|
+
* A failed write never fails the agent's callback. */
|
|
702
|
+
async recordTurn(target, pane, body, dispatch) {
|
|
703
|
+
if (typeof pane.terminal_id !== "string")
|
|
704
|
+
return;
|
|
705
|
+
await recordTurn(target.server, target.pane, { event: String(body.event), terminal: pane.terminal_id, source: target.source, session: target.session,
|
|
706
|
+
...(dispatch ? { dispatch } : {}),
|
|
707
|
+
...(typeof body.background === "number" ? { background: body.background } : {}),
|
|
708
|
+
...(typeof body.reply === "string" ? { reply: body.reply } : {}) }).catch(() => undefined);
|
|
709
|
+
}
|
|
382
710
|
rememberTerminalPrompt(target, body) {
|
|
383
711
|
const tool = String(body.tool || "action").slice(0, 200);
|
|
384
712
|
const questions = tool === "AskUserQuestion" ? terminalQuestions(body.input) : undefined;
|
|
385
713
|
const choice = questions ? questionChoice(questions, 0) : terminalChoice(body.input);
|
|
714
|
+
const summary = approvalSummary({ tool, input: body.input, question: tool === "AskUserQuestion" });
|
|
386
715
|
this.terminalPrompts.set(JSON.stringify(target), { tool,
|
|
387
716
|
message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}),
|
|
717
|
+
...summary,
|
|
388
718
|
...(questions ? { questions, questionIndex: 0 } : {}), at: Date.now() });
|
|
389
719
|
while (this.terminalPrompts.size > 64)
|
|
390
720
|
this.terminalPrompts.delete(this.terminalPrompts.keys().next().value);
|
|
@@ -399,7 +729,7 @@ export class AgentHooks {
|
|
|
399
729
|
this.terminalPrompts.delete(key);
|
|
400
730
|
return undefined;
|
|
401
731
|
}
|
|
402
|
-
return { toolName: entry.tool, message: entry.message, ...(entry.choice ? { choice: entry.choice } : {}),
|
|
732
|
+
return { toolName: entry.tool, message: entry.message, ...(entry.request ? { request: entry.request } : {}), ...(entry.choice ? { choice: entry.choice } : {}),
|
|
403
733
|
...(entry.questions?.length ? { questions: entry.questions, questionIndex: entry.questionIndex ?? 0 } : {}), at: new Date(entry.at).toISOString() };
|
|
404
734
|
}
|
|
405
735
|
clearTerminalPrompt(target) { this.terminalPrompts.delete(JSON.stringify(target)); }
|
|
@@ -414,9 +744,18 @@ export class AgentHooks {
|
|
|
414
744
|
* read notes whether the terminal is reading a password. */
|
|
415
745
|
async syncTerminalDialog(target, active) {
|
|
416
746
|
const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
|
|
747
|
+
// A served OpenCode pane lists its asks over its API; its screen is not read.
|
|
748
|
+
if (target.source === "opencode" && servedPane(target.server, target.pane)) {
|
|
749
|
+
if (entry)
|
|
750
|
+
this.terminalPrompts.delete(key);
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
417
753
|
const held = [...this.pending.values()].find(p => JSON.stringify(p.target) === key);
|
|
418
754
|
// A held Codex permission can already have real choices in its pane.
|
|
419
755
|
// Refresh those before publishing the approval, even while it is held.
|
|
756
|
+
// One the Hook's own app-server asked is answered over RPC, not in the pane.
|
|
757
|
+
if (held?.appServer)
|
|
758
|
+
return;
|
|
420
759
|
if (held && target.source === "codex") {
|
|
421
760
|
const now = Date.now();
|
|
422
761
|
if (now - (this.dialogReads.get(key) ?? 0) < DIALOG_READ_MS)
|
|
@@ -427,7 +766,8 @@ export class AgentHooks {
|
|
|
427
766
|
held.choice = prompt.choice;
|
|
428
767
|
held.title = prompt.title;
|
|
429
768
|
if (held.choice)
|
|
430
|
-
this.terminalPrompts.set(key, { tool: held.tool, message: held.message,
|
|
769
|
+
this.terminalPrompts.set(key, { tool: held.tool, message: held.message,
|
|
770
|
+
request: held.request, requestKind: held.requestKind, choice: held.choice, dialog: true, at: now });
|
|
431
771
|
else
|
|
432
772
|
this.terminalPrompts.delete(key);
|
|
433
773
|
}
|
|
@@ -475,13 +815,7 @@ export class AgentHooks {
|
|
|
475
815
|
this.terminalPrompts.delete(key);
|
|
476
816
|
return;
|
|
477
817
|
}
|
|
478
|
-
|
|
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);
|
|
818
|
+
const dialog = await this.screenDialog(target, text);
|
|
485
819
|
if (entry && !entry.dialog) {
|
|
486
820
|
// The permission the pane still shows after its hook let go: keep the
|
|
487
821
|
// request's own details and answer it with the dialog's rows, so the
|
|
@@ -508,7 +842,9 @@ export class AgentHooks {
|
|
|
508
842
|
settleBlockedPane(target.server, target.pane);
|
|
509
843
|
return;
|
|
510
844
|
}
|
|
511
|
-
this.terminalPrompts.set(key, { tool: "Question", message: dialog.title,
|
|
845
|
+
this.terminalPrompts.set(key, { tool: "Question", message: dialog.title,
|
|
846
|
+
...approvalSummary({ tool: "Question", message: dialog.title }),
|
|
847
|
+
choice: dialog, dialog: true, at: now });
|
|
512
848
|
while (this.terminalPrompts.size > 64)
|
|
513
849
|
this.terminalPrompts.delete(this.terminalPrompts.keys().next().value);
|
|
514
850
|
}
|
|
@@ -704,8 +1040,11 @@ export class AgentHooks {
|
|
|
704
1040
|
const pending = [...this.pending.entries()].find(([, p]) => JSON.stringify(p.target) === JSON.stringify(target));
|
|
705
1041
|
if (pending)
|
|
706
1042
|
return { actionId: pending[0], toolName: pending[1].tool, title: pending[1].choice?.title ?? pending[1].title, message: pending[1].message,
|
|
707
|
-
|
|
708
|
-
|
|
1043
|
+
request: pending[1].request,
|
|
1044
|
+
details: pending[1].message, terminalOnly: target.source === "codex" && !pending[1].choice && !pending[1].appServer,
|
|
1045
|
+
...(pending[1].choice ? { choice: pending[1].choice } : {}),
|
|
1046
|
+
// An app-server request waits for as long as it takes: its card never runs out.
|
|
1047
|
+
expiresAt: pending[1].appServer ? new Date(Math.max(Date.parse(pending[1].expiresAt), Date.now() + DIALOG_PUSH_MS)).toISOString() : pending[1].expiresAt,
|
|
709
1048
|
...(pending[1].conductor ? { conductor: pending[1].conductor } : {}) };
|
|
710
1049
|
const own = target.source === "opencode" ? this.opencodeApproval(target) : undefined;
|
|
711
1050
|
if (own)
|
|
@@ -713,14 +1052,16 @@ export class AgentHooks {
|
|
|
713
1052
|
// A fan-out worker this conversation started is waiting on the owner.
|
|
714
1053
|
const worker = this.fanoutHeld(target)[0];
|
|
715
1054
|
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;
|
|
1055
|
+
message: worker.request.message, request: worker.requestLine, expiresAt: worker.request.expiresAt } : undefined;
|
|
717
1056
|
}
|
|
718
1057
|
opencodeApproval(target) {
|
|
719
1058
|
const held = [...this.opencode.values()].find(value => !value.fanout && JSON.stringify(value.target) === JSON.stringify(target));
|
|
720
1059
|
if (held)
|
|
721
|
-
return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, expiresAt: held.request.expiresAt };
|
|
1060
|
+
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
1061
|
const request = opencodeRequest(target.session);
|
|
723
|
-
return request ? { actionId: request.id, toolName: request.type, title: request.title, message: request.message,
|
|
1062
|
+
return request ? { actionId: request.id, toolName: request.type, title: request.title, message: request.message,
|
|
1063
|
+
request: approvalSummary({ tool: String(request.type ?? ""), input: request, message: typeof request.message === "string" ? request.message : undefined }).request,
|
|
1064
|
+
expiresAt: request.expiresAt } : undefined;
|
|
724
1065
|
}
|
|
725
1066
|
/** Live fan-out worker asks shown on this parent conversation, oldest first. */
|
|
726
1067
|
fanoutHeld(target) {
|
|
@@ -755,6 +1096,14 @@ export class AgentHooks {
|
|
|
755
1096
|
pending.add(String(pane.pane_id));
|
|
756
1097
|
}
|
|
757
1098
|
}
|
|
1099
|
+
// A served OpenCode pane's permission or question, listed by its server.
|
|
1100
|
+
const served = [...[...this.opencode.values()].filter(held => held.served).map(held => held.target), ...[...this.servedQuestions.values()].map(held => held.target)];
|
|
1101
|
+
for (const at of served) {
|
|
1102
|
+
if (!at || at.server !== server)
|
|
1103
|
+
continue;
|
|
1104
|
+
if (panes.some(pane => pane.pane_id === at.pane && pane.workspace_id === at.workspace && pane.tab_id === at.tab && pane.agent === "opencode"))
|
|
1105
|
+
pending.add(at.pane);
|
|
1106
|
+
}
|
|
758
1107
|
for (const held of this.opencode.values()) {
|
|
759
1108
|
const parent = held.target;
|
|
760
1109
|
if (!held.fanout || !parent || parent.server !== server)
|
|
@@ -777,6 +1126,17 @@ export class AgentHooks {
|
|
|
777
1126
|
this.pushBindings.dropAction(id);
|
|
778
1127
|
}
|
|
779
1128
|
async answer(target, id, decision, updatedInput) {
|
|
1129
|
+
// A terminal dialog offered to a dispatching Hook (`workerApproval`) or pushed: answered with the pane's own keys.
|
|
1130
|
+
if (id.startsWith("dialog-")) {
|
|
1131
|
+
const dialog = this.dialogActions.get(id);
|
|
1132
|
+
if (!dialog || JSON.stringify(dialog.target) !== JSON.stringify(target))
|
|
1133
|
+
throw new BridgeError(409, "This approval is no longer pending.");
|
|
1134
|
+
if (updatedInput !== undefined || !["approve", "deny"].includes(String(decision)))
|
|
1135
|
+
throw new BridgeError(400, "The approval answer is not valid.");
|
|
1136
|
+
await this.answerDialog(id, decision);
|
|
1137
|
+
this.dropForwardedDialog(JSON.stringify(target));
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
780
1140
|
const worker = [...this.opencode.entries()].find(([, held]) => held.fanout?.actionId === id && JSON.stringify(held.target) === JSON.stringify(target));
|
|
781
1141
|
if (worker) {
|
|
782
1142
|
if (updatedInput !== undefined)
|
|
@@ -785,6 +1145,16 @@ export class AgentHooks {
|
|
|
785
1145
|
await this.answerFanout(worker[0], worker[1], decision);
|
|
786
1146
|
return;
|
|
787
1147
|
}
|
|
1148
|
+
const served = target.source === "opencode" ? this.opencode.get(id) : undefined;
|
|
1149
|
+
if (served?.served) {
|
|
1150
|
+
if (updatedInput !== undefined)
|
|
1151
|
+
throw new BridgeError(400, "Answers go with an approval.");
|
|
1152
|
+
if (!served.target || JSON.stringify(served.target) !== JSON.stringify(target))
|
|
1153
|
+
throw new BridgeError(409, "This approval is no longer pending.");
|
|
1154
|
+
await validateTarget(target);
|
|
1155
|
+
await this.answerServed(id, served, decision);
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
788
1158
|
if (target.source === "opencode") {
|
|
789
1159
|
if (!["approve", "deny"].includes(String(decision)))
|
|
790
1160
|
throw new BridgeError(400, "The approval answer is not valid.");
|
|
@@ -874,6 +1244,13 @@ export class AgentHooks {
|
|
|
874
1244
|
const linked = this.pushBindings.consume(binding);
|
|
875
1245
|
if (!linked)
|
|
876
1246
|
throw new BridgeError(409, "This approval is no longer pending.");
|
|
1247
|
+
// A worker's request on another computer: the callback answers it there.
|
|
1248
|
+
const forwarded = this.forwardedPushes.get(linked.action);
|
|
1249
|
+
if (forwarded) {
|
|
1250
|
+
this.forwardedPushes.delete(linked.action);
|
|
1251
|
+
await forwarded(decision);
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
877
1254
|
const pending = this.pending.get(linked.action);
|
|
878
1255
|
if (pending) {
|
|
879
1256
|
await this.answer(pending.target, linked.action, decision);
|
|
@@ -899,6 +1276,11 @@ export class AgentHooks {
|
|
|
899
1276
|
await this.answerFanout(linked.action, held, decision);
|
|
900
1277
|
return;
|
|
901
1278
|
}
|
|
1279
|
+
// A served pane's ask is answered over its own API, target or not.
|
|
1280
|
+
if (held?.served) {
|
|
1281
|
+
await this.answerServed(linked.action, held, decision);
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
902
1284
|
if (held?.target) {
|
|
903
1285
|
await this.answer(held.target, linked.action, decision);
|
|
904
1286
|
return;
|
|
@@ -932,6 +1314,9 @@ export class AgentHooks {
|
|
|
932
1314
|
continue;
|
|
933
1315
|
const key = JSON.stringify(target);
|
|
934
1316
|
waiting.add(key);
|
|
1317
|
+
// A served OpenCode pane's asks were pushed as its server listed them.
|
|
1318
|
+
if (target.source === "opencode" && servedPane(target.server, target.pane))
|
|
1319
|
+
continue;
|
|
935
1320
|
// A request its own hook already holds was pushed on arrival.
|
|
936
1321
|
if ([...this.pending.values()].some(held => JSON.stringify(held.target) === key))
|
|
937
1322
|
continue;
|
|
@@ -956,8 +1341,11 @@ export class AgentHooks {
|
|
|
956
1341
|
this.dialogPushes.set(key, { action, title });
|
|
957
1342
|
this.dialogActions.set(action, { target, choice: entry.choice, expiresAt });
|
|
958
1343
|
this.pushBindings.add(binding, { action, expiresAt });
|
|
959
|
-
|
|
960
|
-
|
|
1344
|
+
const cwd = await trustedDirectory(pane).catch(() => undefined);
|
|
1345
|
+
const summary = entry.request ? { request: entry.request, requestKind: entry.requestKind ?? "other" }
|
|
1346
|
+
: approvalSummary({ tool: entry.tool, message: title });
|
|
1347
|
+
void this.push.notify({ binding, provider: target.source, question: entry.tool === "AskUserQuestion", expiresAt: new Date(expiresAt).toISOString(),
|
|
1348
|
+
...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
|
|
961
1349
|
.then(delivered => { if (!delivered)
|
|
962
1350
|
this.dropDialogPush(key); }).catch(() => this.dropDialogPush(key));
|
|
963
1351
|
}
|
|
@@ -975,6 +1363,100 @@ export class AgentHooks {
|
|
|
975
1363
|
this.dialogPushes.delete(key);
|
|
976
1364
|
}
|
|
977
1365
|
}
|
|
1366
|
+
for (const key of this.forwardedDialogs.keys())
|
|
1367
|
+
if (!waiting.has(key) && JSON.parse(key).server === server)
|
|
1368
|
+
this.dropForwardedDialog(key);
|
|
1369
|
+
}
|
|
1370
|
+
/** Keeps the held asks of these dispatched panes for the dispatching Hook's
|
|
1371
|
+
* next polls: without a phone, a watcher or push here, a worker's request
|
|
1372
|
+
* would go straight to its terminal and only its `blocked` state would
|
|
1373
|
+
* reach the conductor. Keyed by pane, since a worker that has not yet
|
|
1374
|
+
* reported a conversation has no session. */
|
|
1375
|
+
leaseDispatch(targets) {
|
|
1376
|
+
const now = Date.now();
|
|
1377
|
+
for (const [key, expiry] of this.dispatchLeases)
|
|
1378
|
+
if (expiry <= now)
|
|
1379
|
+
this.dispatchLeases.delete(key);
|
|
1380
|
+
for (const target of targets) {
|
|
1381
|
+
const key = `${target.server}\n${target.pane}\n${target.source}`;
|
|
1382
|
+
this.dispatchLeases.delete(key);
|
|
1383
|
+
while (this.dispatchLeases.size >= 256)
|
|
1384
|
+
this.dispatchLeases.delete(this.dispatchLeases.keys().next().value);
|
|
1385
|
+
this.dispatchLeases.set(key, now + DISPATCH_LEASE_MS);
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
dispatchLeased(target) {
|
|
1389
|
+
return (this.dispatchLeases.get(`${target.server}\n${target.pane}\n${target.source}`) ?? 0) > Date.now();
|
|
1390
|
+
}
|
|
1391
|
+
dropForwardedDialog(key) {
|
|
1392
|
+
const forwarded = this.forwardedDialogs.get(key);
|
|
1393
|
+
if (!forwarded)
|
|
1394
|
+
return;
|
|
1395
|
+
this.forwardedDialogs.delete(key);
|
|
1396
|
+
if (this.dialogPushes.get(key)?.action !== forwarded.action)
|
|
1397
|
+
this.dialogActions.delete(forwarded.action);
|
|
1398
|
+
}
|
|
1399
|
+
/** What this pane's worker is waiting on, for the dispatching Hook: the held
|
|
1400
|
+
* or app-server request, else the terminal dialog the pane draws (offered
|
|
1401
|
+
* under a `dialog-` action the answer route accepts). */
|
|
1402
|
+
workerApproval(target) {
|
|
1403
|
+
const clip = (value, max) => typeof value === "string" && value ? value.slice(0, max) : undefined;
|
|
1404
|
+
const held = this.approval(target);
|
|
1405
|
+
if (held) {
|
|
1406
|
+
const actionId = String(held.actionId), pending = this.pending.get(actionId);
|
|
1407
|
+
const pushed = pending ? this.pushedHolds.has(actionId) || (!!pending.appServer && this.push.available) : this.push.available;
|
|
1408
|
+
const title = clip(held.title, 200), request = clip(held.request, 500), expiresAt = clip(held.expiresAt, 40);
|
|
1409
|
+
const conductor = held.conductor;
|
|
1410
|
+
return { actionId, tool: clip(held.toolName, 200) ?? "action", ...(title ? { title } : {}), ...(request ? { request } : {}),
|
|
1411
|
+
...(pending ? { requestKind: pending.requestKind } : {}), ...(expiresAt ? { expiresAt } : {}), ...(conductor ? { conductor } : {}), ...(pushed ? { pushed: true } : {}) };
|
|
1412
|
+
}
|
|
1413
|
+
const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
|
|
1414
|
+
const title = entry && (entry.dialog || entry.released) ? entry.choice?.title : undefined;
|
|
1415
|
+
if (!entry?.choice || !title)
|
|
1416
|
+
return undefined;
|
|
1417
|
+
const pushedDialog = this.dialogPushes.get(key);
|
|
1418
|
+
// A dialog is the same one only with the same title and command: Claude and Codex share generic titles.
|
|
1419
|
+
const pushedAction = pushedDialog && this.dialogActions.get(pushedDialog.action);
|
|
1420
|
+
let action = pushedDialog?.title === title && pushedAction && pushedAction.choice.body === entry.choice.body ? pushedDialog.action : undefined;
|
|
1421
|
+
if (!action) {
|
|
1422
|
+
const known = this.forwardedDialogs.get(key);
|
|
1423
|
+
if (known?.title === title && known.body === entry.choice.body && (this.dialogActions.get(known.action)?.expiresAt ?? 0) > Date.now())
|
|
1424
|
+
action = known.action;
|
|
1425
|
+
else {
|
|
1426
|
+
this.dropForwardedDialog(key);
|
|
1427
|
+
while (this.forwardedDialogs.size >= 64)
|
|
1428
|
+
this.dropForwardedDialog(this.forwardedDialogs.keys().next().value);
|
|
1429
|
+
action = `dialog-${randomUUID()}`;
|
|
1430
|
+
this.forwardedDialogs.set(key, { action, title, body: entry.choice.body });
|
|
1431
|
+
this.dialogActions.set(action, { target, choice: entry.choice, expiresAt: Date.now() + DIALOG_PUSH_MS });
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
const request = clip(entry.request ?? approvalSummary({ tool: entry.tool, message: title }).request, 500);
|
|
1435
|
+
return { actionId: action, tool: entry.tool.slice(0, 200), title: title.slice(0, 200), ...(request ? { request } : {}),
|
|
1436
|
+
...(entry.requestKind ? { requestKind: entry.requestKind } : {}),
|
|
1437
|
+
expiresAt: new Date(this.dialogActions.get(action).expiresAt).toISOString(), terminal: true,
|
|
1438
|
+
...(pushedDialog?.action === action ? { pushed: true } : {}) };
|
|
1439
|
+
}
|
|
1440
|
+
/** A worker's request on another computer, sent to this Hook's own phone:
|
|
1441
|
+
* the notification's answer calls `answer`, which sends it back over the
|
|
1442
|
+
* dispatch path. */
|
|
1443
|
+
pushForwarded(summary, answer) {
|
|
1444
|
+
if (!this.push.available || this.closed)
|
|
1445
|
+
return;
|
|
1446
|
+
const action = `forward-${randomUUID()}`, binding = randomUUID(), expiresAt = Date.now() + DIALOG_PUSH_MS;
|
|
1447
|
+
while (this.forwardedPushes.size >= 64) {
|
|
1448
|
+
const oldest = this.forwardedPushes.keys().next().value;
|
|
1449
|
+
this.forwardedPushes.delete(oldest);
|
|
1450
|
+
this.dropPushBindings(oldest);
|
|
1451
|
+
}
|
|
1452
|
+
this.forwardedPushes.set(action, answer);
|
|
1453
|
+
this.pushBindings.add(binding, { action, expiresAt });
|
|
1454
|
+
const drop = () => { this.forwardedPushes.delete(action); this.dropPushBindings(action); };
|
|
1455
|
+
void this.push.notify({ binding, provider: summary.provider, question: false, expiresAt: new Date(expiresAt).toISOString(),
|
|
1456
|
+
...(summary.project ? { project: summary.project } : {}), computer: summary.computer, request: summary.request,
|
|
1457
|
+
...(summary.requestKind ? { requestKind: summary.requestKind } : {}) })
|
|
1458
|
+
.then(delivered => { if (!delivered)
|
|
1459
|
+
drop(); }).catch(drop);
|
|
978
1460
|
}
|
|
979
1461
|
adoptReleasedHold(key, target, choice, title) {
|
|
980
1462
|
const hold = this.releasedHolds.get(key);
|
|
@@ -993,16 +1475,37 @@ export class AgentHooks {
|
|
|
993
1475
|
this.dropPushBindings(pushed.action);
|
|
994
1476
|
this.dialogPushes.delete(key);
|
|
995
1477
|
}
|
|
1478
|
+
/** The dialog a pane's screen shows now. Codex draws "> 1. Yes, proceed (y)"
|
|
1479
|
+
* rows and Copilot a boxed select with a cursor row, both answered by moving
|
|
1480
|
+
* to a row; OpenCode's prompt is one row of options whose cursor is only a
|
|
1481
|
+
* color; the other fallbacks number rows without a key in the label. */
|
|
1482
|
+
async screenDialog(target, text) {
|
|
1483
|
+
return ["codex", "copilot"].includes(target.source) ? visibleTerminalChoice(text)
|
|
1484
|
+
: target.source === "opencode" ? opencodePermissionDialog(await this.paneAnsi(target))?.choice ?? numberedDialog(text)
|
|
1485
|
+
: numberedDialog(text);
|
|
1486
|
+
}
|
|
996
1487
|
/** Approve picks the dialog's yes/allow row (else its first), Deny its
|
|
997
1488
|
* no/deny row (else Escape), typed as the pane's own keys. */
|
|
998
1489
|
async answerDialog(action, decision) {
|
|
999
1490
|
const dialog = this.dialogActions.get(action);
|
|
1000
1491
|
if (!dialog || dialog.expiresAt <= Date.now())
|
|
1001
1492
|
throw new BridgeError(409, "This approval is no longer pending.");
|
|
1493
|
+
// Claimed before any await: a second answer for the same dialog gets a 409 instead of typing the keys twice.
|
|
1494
|
+
this.dialogActions.delete(action);
|
|
1002
1495
|
const key = JSON.stringify(dialog.target);
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1496
|
+
try {
|
|
1497
|
+
await validateTarget(dialog.target, false, true);
|
|
1498
|
+
}
|
|
1499
|
+
catch (error) {
|
|
1500
|
+
if (!this.dialogActions.has(action))
|
|
1501
|
+
this.dialogActions.set(action, dialog);
|
|
1502
|
+
throw error;
|
|
1503
|
+
}
|
|
1504
|
+
// Read the screen now, not the activity tick's cached prompt: in the seconds
|
|
1505
|
+
// since that tick the dialog may have been answered and replaced by another
|
|
1506
|
+
// with the same title, and the keys must only ever answer the one forwarded.
|
|
1507
|
+
const live = await this.screenDialog(dialog.target, await this.paneLines(dialog.target));
|
|
1508
|
+
if (!live || live.title !== dialog.choice.title || live.body !== dialog.choice.body) {
|
|
1006
1509
|
this.dropDialogPush(key);
|
|
1007
1510
|
throw new BridgeError(409, "That question in the terminal has changed. Open phren to answer it.");
|
|
1008
1511
|
}
|
|
@@ -1017,6 +1520,63 @@ export class AgentHooks {
|
|
|
1017
1520
|
dropPushBindings(action) {
|
|
1018
1521
|
this.pushBindings.dropAction(action);
|
|
1019
1522
|
}
|
|
1523
|
+
/** A server request from one of the Hook's own Codex app-servers: an
|
|
1524
|
+
* approval card like a held PermissionRequest, pushed the same way, but
|
|
1525
|
+
* with no hold timer. The request stays parked in Codex until someone
|
|
1526
|
+
* answers it, here or in the pane's TUI (`codexResolved`). */
|
|
1527
|
+
codexRequest(target, request, answer) {
|
|
1528
|
+
const shown = appServerApproval(request);
|
|
1529
|
+
if (!shown || this.closed)
|
|
1530
|
+
return;
|
|
1531
|
+
// Replayed after a reconnect: the card stays, answered through the new connection.
|
|
1532
|
+
const known = [...this.pending.values()].find(entry => entry.appServer?.requestId === request.requestId && JSON.stringify(entry.target) === JSON.stringify(target));
|
|
1533
|
+
if (known?.appServer) {
|
|
1534
|
+
known.appServer.answer = answer;
|
|
1535
|
+
return;
|
|
1536
|
+
}
|
|
1537
|
+
const action = randomUUID();
|
|
1538
|
+
const held = { requestId: request.requestId, answer };
|
|
1539
|
+
const reply = { destroyed: false, end(body) {
|
|
1540
|
+
if (reply.destroyed)
|
|
1541
|
+
return;
|
|
1542
|
+
reply.destroyed = true;
|
|
1543
|
+
// "{}" gives the request back to the pane: it stays parked in Codex.
|
|
1544
|
+
const behavior = object(object(object((() => { try {
|
|
1545
|
+
return JSON.parse(body);
|
|
1546
|
+
}
|
|
1547
|
+
catch {
|
|
1548
|
+
return {};
|
|
1549
|
+
} })()).hookSpecificOutput).decision).behavior;
|
|
1550
|
+
if (behavior === "allow" || behavior === "deny")
|
|
1551
|
+
held.answer(appServerDecision(request, behavior === "allow"));
|
|
1552
|
+
} };
|
|
1553
|
+
const cwd = typeof request.params.cwd === "string" && path.isAbsolute(request.params.cwd) ? request.params.cwd : undefined;
|
|
1554
|
+
const summary = approvalSummary({ tool: shown.tool, input: shown.input, cwd });
|
|
1555
|
+
const expiresAt = Date.now() + DIALOG_PUSH_MS;
|
|
1556
|
+
this.pending.set(action, { target, response: reply, tool: shown.tool, input: shown.input, message: JSON.stringify(shown.input, null, 2).slice(0, 32_768),
|
|
1557
|
+
...summary, expiresAt: new Date(expiresAt).toISOString(), appServer: held });
|
|
1558
|
+
while (this.pending.size > 64)
|
|
1559
|
+
this.pending.delete(this.pending.keys().next().value);
|
|
1560
|
+
if (!this.push.available)
|
|
1561
|
+
return;
|
|
1562
|
+
const binding = randomUUID();
|
|
1563
|
+
this.pushBindings.add(binding, { action, expiresAt });
|
|
1564
|
+
void this.push.notify({ binding, provider: "codex", question: false, expiresAt: new Date(expiresAt).toISOString(),
|
|
1565
|
+
...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
|
|
1566
|
+
.then(delivered => { if (!delivered)
|
|
1567
|
+
this.pushBindings.consume(binding); }).catch(() => { });
|
|
1568
|
+
}
|
|
1569
|
+
/** Another client (the pane's TUI) answered the request, or this one declined it. */
|
|
1570
|
+
codexResolved(target, requestId) {
|
|
1571
|
+
for (const [action, entry] of this.pending) {
|
|
1572
|
+
if (entry.appServer?.requestId !== requestId || JSON.stringify(entry.target) !== JSON.stringify(target))
|
|
1573
|
+
continue;
|
|
1574
|
+
this.pending.delete(action);
|
|
1575
|
+
this.dropPushBindings(action);
|
|
1576
|
+
entry.response.destroyed = true;
|
|
1577
|
+
settleBlockedPane(target.server, target.pane, 0);
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1020
1580
|
async start() {
|
|
1021
1581
|
await this.push.start();
|
|
1022
1582
|
// The public helper singleton was already checked before this is called.
|
|
@@ -1029,6 +1589,10 @@ export class AgentHooks {
|
|
|
1029
1589
|
this.server = createServer(async (req, res) => {
|
|
1030
1590
|
res.setHeader("Content-Type", "application/json");
|
|
1031
1591
|
try {
|
|
1592
|
+
if (req.method === "POST" && req.url === "/sudo") {
|
|
1593
|
+
await this.sudo.handle(req, res);
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1032
1596
|
if (req.method !== "POST" || req.url !== "/hook")
|
|
1033
1597
|
throw new Error("Invalid callback");
|
|
1034
1598
|
let size = 0;
|
|
@@ -1067,18 +1631,40 @@ export class AgentHooks {
|
|
|
1067
1631
|
const pids = (await terminalProvider().processes(target.server, target.pane)).foregroundPids;
|
|
1068
1632
|
if (!pids.length)
|
|
1069
1633
|
throw new Error("No foreground process");
|
|
1634
|
+
if (!daemon && target.source === "claude")
|
|
1635
|
+
notePaneTranscript(paneAccountKey(target.server, target.pane), body.transcript, String(pane.terminal_id ?? ""));
|
|
1070
1636
|
if (!daemon)
|
|
1071
1637
|
await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ terminal: pane.terminal_id, source: target.source,
|
|
1072
1638
|
session: target.session, pids, workspace: target.workspace, tab: target.tab, event: String(body.event).slice(0, 64), at: new Date().toISOString() }));
|
|
1073
1639
|
// A terminal that does not watch its agents (tmux) takes the agent's
|
|
1074
1640
|
// status from these events.
|
|
1075
|
-
|
|
1641
|
+
// Codex's automatic reviewer decides this request on its own: it is
|
|
1642
|
+
// not a question for the owner, so nothing is held, pushed or
|
|
1643
|
+
// remembered and the pane is not marked blocked. If Codex hands the
|
|
1644
|
+
// request back to the owner it draws its approval dialog, which the
|
|
1645
|
+
// waiting-pane dialog read picks up and pushes like any other.
|
|
1646
|
+
const autoReview = body.event === "PermissionRequest" && target.source === "codex" && body.autoReview === true;
|
|
1647
|
+
const status = autoReview ? undefined : eventStatus(body.event);
|
|
1076
1648
|
if (status && typeof pane.terminal_id === "string")
|
|
1077
1649
|
notePaneStatus(target.server, target.pane, pane.terminal_id, status);
|
|
1078
1650
|
// What a shell call changed on disk: snapshot before, diff after.
|
|
1079
1651
|
const input = typeof body.input === "string" ? { patch: body.input } : object(body.input), command = [input.command, input.cmd].find(v => typeof v === "string");
|
|
1080
1652
|
// A shell call by name, or any tool whose input is a command line —
|
|
1081
1653
|
// Codex has renamed its shell tool more than once.
|
|
1654
|
+
// A launched brief's receipt: the worker's own hook names its dispatch
|
|
1655
|
+
// id (from its environment, or the brief path in its first prompt when
|
|
1656
|
+
// Codex's shared daemon ran the hook with another pane's variables).
|
|
1657
|
+
let dispatch;
|
|
1658
|
+
if (body.event === "SessionStart" || body.event === "UserPromptSubmit") {
|
|
1659
|
+
const named = !daemon && briefId.safeParse(body.dispatchId).success ? String(body.dispatchId) : undefined;
|
|
1660
|
+
dispatch = named ?? (typeof body.prompt === "string" ? briefIdInPrompt(body.prompt) : undefined);
|
|
1661
|
+
if (dispatch)
|
|
1662
|
+
await recordBriefArrival(dispatch, String(body.event), target).catch(() => undefined);
|
|
1663
|
+
}
|
|
1664
|
+
// `/new` or `/resume` in a pane on the Hook's own Codex server: follow
|
|
1665
|
+
// the TUI to its new thread. Only a callback trusted to name its pane.
|
|
1666
|
+
if (body.event === "SessionStart" && target.source === "codex" && !daemon)
|
|
1667
|
+
codexServers.follow(target.server, target.pane, target.session);
|
|
1082
1668
|
if (body.event === "PreCompact") {
|
|
1083
1669
|
this.startCompacting(target);
|
|
1084
1670
|
res.end("{}");
|
|
@@ -1087,9 +1673,15 @@ export class AgentHooks {
|
|
|
1087
1673
|
if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)))
|
|
1088
1674
|
this.stopCompacting(target);
|
|
1089
1675
|
if (body.event === "UserPromptSubmit") {
|
|
1090
|
-
|
|
1676
|
+
const answer = typeof body.prompt === "string" ? this.submitted(target, body.prompt.slice(0, 65_536)) : {};
|
|
1677
|
+
// A prompt refused here never starts a turn in this conversation.
|
|
1678
|
+
if (answer.decision !== "block")
|
|
1679
|
+
await this.recordTurn(target, pane, body, dispatch);
|
|
1680
|
+
res.end(JSON.stringify(answer));
|
|
1091
1681
|
return;
|
|
1092
1682
|
}
|
|
1683
|
+
if (body.event === "SessionStart" || body.event === "Stop")
|
|
1684
|
+
await this.recordTurn(target, pane, body, dispatch);
|
|
1093
1685
|
if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body.event)) && capturesChanges(String(body.tool), input)) {
|
|
1094
1686
|
const conversation = `${target.source}:${target.session}`, id = String(body.toolUseId || "").slice(0, 200);
|
|
1095
1687
|
if (body.event === "PreToolUse")
|
|
@@ -1105,17 +1697,28 @@ export class AgentHooks {
|
|
|
1105
1697
|
const conductor = conductorCall(String(body.tool || "action"), body.input);
|
|
1106
1698
|
if (conductor) {
|
|
1107
1699
|
// A standing grant answers the call before it becomes an approval card.
|
|
1108
|
-
const grant =
|
|
1700
|
+
const grant = await findGrant({
|
|
1109
1701
|
action: conductor.action, project: conductor.project, computer: conductor.computer,
|
|
1110
|
-
});
|
|
1702
|
+
}).catch(() => undefined);
|
|
1111
1703
|
if (grant) {
|
|
1112
1704
|
res.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "allow" } } }));
|
|
1113
1705
|
return;
|
|
1114
1706
|
}
|
|
1115
1707
|
}
|
|
1116
1708
|
}
|
|
1709
|
+
if (autoReview) {
|
|
1710
|
+
res.end("{}");
|
|
1711
|
+
return;
|
|
1712
|
+
}
|
|
1713
|
+
// A thread on the Hook's own Codex app-server: the request reaches
|
|
1714
|
+
// this Hook as a server request with no time limit, so the callback
|
|
1715
|
+
// lets Codex ask for it at once instead of holding a second card.
|
|
1716
|
+
if (body.event === "PermissionRequest" && target.source === "codex" && codexServers.forThread(target.session)) {
|
|
1717
|
+
res.end("{}");
|
|
1718
|
+
return;
|
|
1719
|
+
}
|
|
1117
1720
|
if (body.event !== "PermissionRequest" || target.source === "copilot"
|
|
1118
|
-
|| (!this.watching.has(JSON.stringify(target)) && !this.overview.has(target.server) && !this.push.available)) {
|
|
1721
|
+
|| (!this.watching.has(JSON.stringify(target)) && !this.overview.has(target.server) && !this.push.available && !this.dispatchLeased(target))) {
|
|
1119
1722
|
if (body.event === "PermissionRequest")
|
|
1120
1723
|
this.rememberTerminalPrompt(target, body);
|
|
1121
1724
|
res.end("{}");
|
|
@@ -1130,7 +1733,8 @@ export class AgentHooks {
|
|
|
1130
1733
|
const action = randomUUID();
|
|
1131
1734
|
this.dialogReads.delete(JSON.stringify(target));
|
|
1132
1735
|
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);
|
|
1736
|
+
const locallyWatched = this.watching.has(JSON.stringify(target)) || this.overview.has(target.server) || this.dispatchLeased(target);
|
|
1737
|
+
const cwd = typeof body.cwd === "string" && path.isAbsolute(body.cwd) ? body.cwd : await trustedDirectory(pane).catch(() => undefined);
|
|
1134
1738
|
// When the hold ends the request stays in the terminal. A pushed
|
|
1135
1739
|
// notification keeps working: its binding waits for the pane's dialog
|
|
1136
1740
|
// and then answers that, instead of going dead with the hold.
|
|
@@ -1146,8 +1750,9 @@ export class AgentHooks {
|
|
|
1146
1750
|
}, APPROVAL_HOLD_MS);
|
|
1147
1751
|
const expiresAt = new Date(Date.now() + APPROVAL_HOLD_MS).toISOString();
|
|
1148
1752
|
const { choice, title } = permissionPrompt(String(body.tool || "action"), body.input);
|
|
1753
|
+
const summary = approvalSummary({ tool: String(body.tool || "action"), input: body.input, cwd, question: body.tool === "AskUserQuestion" });
|
|
1149
1754
|
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,
|
|
1755
|
+
message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...summary, ...(choice ? { choice } : {}), expiresAt, timer,
|
|
1151
1756
|
...(conductor ? { conductor } : {}) });
|
|
1152
1757
|
res.on("close", () => { clearTimeout(timer); this.pending.delete(action); this.pushedHolds.delete(action); if (!released)
|
|
1153
1758
|
this.dropPushBindings(action); });
|
|
@@ -1156,7 +1761,7 @@ export class AgentHooks {
|
|
|
1156
1761
|
this.pushBindings.add(binding, { action, expiresAt: pushExpiresAt });
|
|
1157
1762
|
this.pushedHolds.set(action, pushExpiresAt);
|
|
1158
1763
|
void this.push.notify({ binding, provider: target.source, question: body.tool === "AskUserQuestion",
|
|
1159
|
-
expiresAt: new Date(pushExpiresAt).toISOString() }).catch(() => false).then(delivered => {
|
|
1764
|
+
expiresAt: new Date(pushExpiresAt).toISOString(), ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary }).catch(() => false).then(delivered => {
|
|
1160
1765
|
if (!delivered) {
|
|
1161
1766
|
this.pushBindings.consume(binding);
|
|
1162
1767
|
this.pushedHolds.delete(action);
|
|
@@ -1210,9 +1815,11 @@ export class AgentHooks {
|
|
|
1210
1815
|
this.fanoutArchiveTimer.unref?.();
|
|
1211
1816
|
this.scheduleOpencodeSweep();
|
|
1212
1817
|
void this.sweepBlockedFanouts();
|
|
1818
|
+
this.paneServers.tick();
|
|
1213
1819
|
}
|
|
1214
1820
|
close() {
|
|
1215
1821
|
this.closed = true;
|
|
1822
|
+
this.sudo.close();
|
|
1216
1823
|
void this.changes.close().catch(() => { });
|
|
1217
1824
|
for (const pending of this.pending.values()) {
|
|
1218
1825
|
clearTimeout(pending.timer);
|
|
@@ -1223,6 +1830,9 @@ export class AgentHooks {
|
|
|
1223
1830
|
this.server?.closeAllConnections();
|
|
1224
1831
|
this.pushBindings.clear();
|
|
1225
1832
|
this.opencode.clear();
|
|
1833
|
+
this.forwardedPushes.clear();
|
|
1834
|
+
this.paneServers.close();
|
|
1835
|
+
this.servedQuestions.clear();
|
|
1226
1836
|
if (this.opencodeDebounce)
|
|
1227
1837
|
clearTimeout(this.opencodeDebounce);
|
|
1228
1838
|
if (this.opencodePoll)
|
|
@@ -1236,6 +1846,16 @@ export class AgentHooks {
|
|
|
1236
1846
|
this.fanoutSeen.clear();
|
|
1237
1847
|
}
|
|
1238
1848
|
}
|
|
1849
|
+
/** What a Stop payload says about the turn it ends: the harness's last
|
|
1850
|
+
* assistant message (Claude, Codex) and, from Claude Code, the background
|
|
1851
|
+
* tasks still in flight, which will wake the conversation again when they
|
|
1852
|
+
* finish. Absent fields are left out, so the Hook falls back to the transcript. */
|
|
1853
|
+
export function stopFacts(value) {
|
|
1854
|
+
const tasks = Array.isArray(value.background_tasks)
|
|
1855
|
+
? value.background_tasks.filter(task => !["completed", "failed", "killed", "stopped"].includes(String(object(task).status))) : undefined;
|
|
1856
|
+
return { ...(tasks ? { background: tasks.length } : {}),
|
|
1857
|
+
...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
|
|
1858
|
+
}
|
|
1239
1859
|
export async function agentHook(source) {
|
|
1240
1860
|
provider.parse(source);
|
|
1241
1861
|
// A missing helper must never prevent the coding agent from running.
|
|
@@ -1260,11 +1880,24 @@ export async function agentHook(source) {
|
|
|
1260
1880
|
return;
|
|
1261
1881
|
// Codex 0.157 runs hooks inside its shared app-server daemon, whose pane
|
|
1262
1882
|
// variables belong to whichever pane first started it.
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1883
|
+
// The Hook's own per-pane app-server (codex-servers.ts) runs its hooks
|
|
1884
|
+
// with that pane's variables, so they are trusted like a pane's own.
|
|
1885
|
+
const ownServer = source === "codex" && codexServerId.safeParse(process.env[CODEX_SERVER_ENV]).success;
|
|
1886
|
+
const daemon = source === "codex" && !ownServer && await underCodexDaemon().catch(() => false);
|
|
1887
|
+
// Codex asks this hook before its automatic reviewer: say when that
|
|
1888
|
+
// reviewer, not the owner, will decide.
|
|
1889
|
+
const autoReview = source === "codex" && event === "PermissionRequest" && await codexAutoReview(value.transcript_path);
|
|
1890
|
+
// A worker the Hook launched with its brief carries that dispatch's id. A
|
|
1891
|
+
// daemon's variables belong to another pane, so it sends none.
|
|
1892
|
+
const dispatchId = !daemon && (event === "SessionStart" || event === "UserPromptSubmit") && briefId.safeParse(process.env[DISPATCH_ID_ENV]).success
|
|
1893
|
+
? process.env[DISPATCH_ID_ENV] : undefined;
|
|
1894
|
+
const data = JSON.stringify({ target, event, ...(daemon ? { daemon: true } : {}), ...(autoReview ? { autoReview: true } : {}), ...(dispatchId ? { dispatchId } : {}),
|
|
1895
|
+
...(source === "claude" && typeof value.transcript_path === "string" ? { transcript: value.transcript_path.slice(0, 4096) } : {}),
|
|
1896
|
+
tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
|
|
1897
|
+
...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
|
|
1898
|
+
...(event === "Stop" ? stopFacts(value) : {}) });
|
|
1266
1899
|
await new Promise(resolve => {
|
|
1267
|
-
const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 :
|
|
1900
|
+
const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 : 12_000,
|
|
1268
1901
|
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
|
|
1269
1902
|
let result = "";
|
|
1270
1903
|
res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384)
|