From 863b6a12d1404b405d291c07b086c7c3be3f4adc Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 16 Nov 2026 00:24:57 +0000 Subject: [PATCH 1/7] fix(agent-tools): add cluster message approval policy --- CHANGELOG.md | 1 + app/api/web-settings/route.ts | 7 + .../SettingsConfig.agent-messages.test.mjs | 100 ++++++++++++ components/SettingsConfig.tsx | 59 ++++++- lib/agent-tools.test.mjs | 150 +++++++++++++++--- lib/agent-tools.ts | 30 ++-- lib/i18n/locales/en.json | 6 + lib/i18n/locales/ja.json | 6 + lib/i18n/locales/zh-CN.json | 6 + lib/i18n/locales/zh-TW.json | 6 + lib/message-outbox-review.test.mjs | 4 +- lib/rpc-manager.ts | 6 +- lib/web-settings.test.mjs | 40 ++++- lib/web-settings.ts | 6 + 14 files changed, 387 insertions(+), 40 deletions(-) create mode 100644 components/SettingsConfig.agent-messages.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 28cc2d4c7..9bbd74b2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Restore HTTP LAN and VPN access.** Browser UUID generation now works without secure-context-only `crypto.randomUUID()`, preventing the "Something went wrong" crash when opening the app or creating a session. - **Open live subagent transcripts without waiting forever.** Transcript pages now read the subagent's on-disk artifact directly instead of waiting for its busy agent process to answer first. +- **Make cross-session message approval coherent across a cluster.** Choose whether every `send_to_session` call asks first, or sessions may message any session within the cluster without asking. ### Added diff --git a/app/api/web-settings/route.ts b/app/api/web-settings/route.ts index daec00729..3f05b8139 100644 --- a/app/api/web-settings/route.ts +++ b/app/api/web-settings/route.ts @@ -53,6 +53,13 @@ export async function PUT(req: Request) { patch.agentToolsEnabled = payload.agentToolsEnabled; } + if (payload.agentMessagePermission !== undefined) { + if (payload.agentMessagePermission !== "alwaysAsk" && payload.agentMessagePermission !== "trustCluster") { + return Response.json({ error: 'agentMessagePermission must be "alwaysAsk" or "trustCluster"', code: "invalid_settings" }, { status: 400 }); + } + patch.agentMessagePermission = payload.agentMessagePermission; + } + if (payload.githubWritesUnasked !== undefined) { if (typeof payload.githubWritesUnasked !== "boolean") { return Response.json({ error: "githubWritesUnasked must be a boolean", code: "invalid_settings" }, { status: 400 }); diff --git a/components/SettingsConfig.agent-messages.test.mjs b/components/SettingsConfig.agent-messages.test.mjs new file mode 100644 index 000000000..0d73f7a51 --- /dev/null +++ b/components/SettingsConfig.agent-messages.test.mjs @@ -0,0 +1,100 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test from "node:test"; +import { act, createElement } from "react"; +const { cleanup, fireEvent, render, waitFor, within } = await import("@testing-library/react/pure.js"); +const { SettingsConfig } = await import("./SettingsConfig"); + +const noop = () => {}; +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 20))); +const settingsProps = { + activeTab: "system", + toolCallsDefaultCollapsed: false, onToolCallsDefaultCollapsedChange: noop, + hideToolActivity: false, onHideToolActivityChange: noop, + expandThinkingByDefault: false, onExpandThinkingByDefaultChange: noop, onHideThinkingBlockChange: noop, + providerUsageVisible: false, onProviderUsageVisibleChange: noop, + scopeNativeSelectAll: false, onScopeNativeSelectAllChange: noop, + openUrlAutomatically: false, onOpenUrlAutomaticallyChange: noop, + cwd: null, remoteHost: false, sessionId: null, + onModelsSaved: noop, onPluginsReloaded: noop, + appUpdate: null, onRefreshAppUpdate: async () => null, + onRequestAppUpdate: noop, onSelectTab: noop, onClose: noop, +}; + +async function choose(select, name) { + fireEvent.click(select); + const list = await waitFor(() => within(document.body).getByRole("listbox")); + const option = within(list).getByRole("option", { name, exact: true }); + fireEvent.pointerDown(option, { pointerType: "mouse" }); + fireEvent.click(option); + await settle(); +} + +test("agent message approval loads and saves the trust-cluster policy", async (t) => { + const puts = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (url, init) => { + if (String(url) === "/api/web-settings") { + if (init?.method === "PUT") { + puts.push(init.body); + return Response.json({ agentMessagePermission: "trustCluster" }); + } + return Response.json({ agentMessagePermission: "alwaysAsk" }); + } + return Response.json({}); + }; + t.after(() => { + cleanup(); + globalThis.fetch = originalFetch; + }); + + const { container } = render(createElement(SettingsConfig, settingsProps)); + await settle(); + const select = within(container).getByRole("combobox", { name: "Agent message approval" }); + assert.equal(select.textContent, "Always ask"); + await choose(select, "Trust cluster"); + assert.deepEqual(puts, ['{"agentMessagePermission":"trustCluster"}']); + assert.equal(select.textContent, "Trust cluster"); +}); + +test("agent message approval shows unavailable instead of inventing a policy while loading fails", async (t) => { + const pending = Promise.withResolvers(); + const originalFetch = globalThis.fetch; + globalThis.fetch = async (url) => String(url) === "/api/web-settings" ? pending.promise : Response.json({}); + t.after(() => { + cleanup(); + globalThis.fetch = originalFetch; + }); + + const { container } = render(createElement(SettingsConfig, settingsProps)); + const select = await waitFor(() => within(container).getByRole("combobox", { name: "Agent message approval" })); + assert.equal(select.disabled, true); + assert.equal(select.textContent, "Unavailable"); + pending.resolve(new Response(null, { status: 503 })); + await settle(); + assert.equal(select.disabled, true); + assert.equal(select.textContent, "Unavailable"); +}); + +test("an uncertain agent message approval save reloads the committed policy", async (t) => { + let loads = 0; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (url, init) => { + if (String(url) !== "/api/web-settings") return Response.json({}); + if (init?.method === "PUT") throw new TypeError("Failed to fetch"); + loads++; + return Response.json({ agentMessagePermission: loads === 1 ? "alwaysAsk" : "trustCluster" }); + }; + t.after(() => { + cleanup(); + globalThis.fetch = originalFetch; + }); + + const { container } = render(createElement(SettingsConfig, settingsProps)); + await settle(); + const select = within(container).getByRole("combobox", { name: "Agent message approval" }); + await choose(select, "Trust cluster"); + assert.ok(loads > 1); + assert.equal(select.disabled, false); + assert.equal(select.textContent, "Trust cluster"); +}); diff --git a/components/SettingsConfig.tsx b/components/SettingsConfig.tsx index 04af234fa..9f23fb5f2 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -35,7 +35,7 @@ import { } from "@/lib/notification-client"; import { BROWSER_TRANSPORTS, type BrowserTransport } from "@/lib/event-stream-protocol"; import { setConnectionDiagnosticsEnabled, useConnectionDiagnosticsEnabled } from "@/lib/connection-diagnostics-prefs"; -import type { GithubActionsOperation, GithubActionsPermission, GithubActionsPermissions } from "@/lib/web-settings"; +import type { AgentMessagePermission, GithubActionsOperation, GithubActionsPermission, GithubActionsPermissions } from "@/lib/web-settings"; const SettingsTabLoading = () => { const { t } = useI18n(); return
{t("settingsConfig.loadingSettings")}
; @@ -205,6 +205,7 @@ const SETTING_INDEX: SettingIndexEntry[] = [ // Windows Background Service & System Tray { id: "auto-resume-sessions", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.autoResumeSessions", descKey: "settingsConfig.autoResumeSessionsDesc", fallbackSection: "System", fallbackLabel: "Resume running sessions after a restart", fallbackDesc: "When omp-web restarts while agents are working, restart those sessions and tell each agent: \"Session interrupted and resumed. Continue as you would have done without the interruption.\" Work in progress at the moment of the restart, such as a running command, is lost." }, { id: "agent-tools-cross-session", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.agentTools", descKey: "settingsConfig.agentToolsDesc", fallbackSection: "System", fallbackLabel: "Agent tools (cross-session)", fallbackDesc: "Allow cross-session tools and GitHub tools for watching and reading issues and pull requests, writing comments and threads, and managing Actions workflow runs. Requires the GitHub CLI (gh) installed and logged in on this server." }, + { id: "agent-message-permission", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.agentMessagePermission", descKey: "settingsConfig.agentMessagePermissionDesc", fallbackSection: "System", fallbackLabel: "Agent message approval", fallbackDesc: "Always ask before send_to_session, or trust sends between cluster members." }, { id: "github-writes-unasked", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.githubWritesUnasked", descKey: "settingsConfig.githubWritesUnaskedDesc", fallbackSection: "System", fallbackLabel: "Allow agent GitHub writes without asking", fallbackDesc: "Let agents post comments, reply in review threads and resolve threads through this server's gh login without a confirmation each time. Off: each of those comment and thread writes asks in the session first." }, { id: "github-actions-dispatch", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.githubActionsDispatch", descKey: "settingsConfig.githubActionsDispatchDesc", fallbackSection: "System", fallbackLabel: "Dispatch workflows", fallbackDesc: "Choose whether agents may start GitHub Actions workflows." }, { id: "github-actions-cancel", tab: "system", sectionKey: "settingsConfig.systemUpdates", labelKey: "settingsConfig.githubActionsCancel", descKey: "settingsConfig.githubActionsCancelDesc", fallbackSection: "System", fallbackLabel: "Cancel workflow runs", fallbackDesc: "Choose whether agents may cancel running GitHub Actions workflows." }, @@ -345,6 +346,61 @@ function AgentToolsSetting() { ); } +function AgentMessagePermissionSetting() { + const { t } = useI18n(); + const [permission, setPermission] = useState(null); + const [saving, setSaving] = useState(false); + const load = useCallback(async (response?: Response): Promise => { + try { + const res = response ?? await fetch("/api/web-settings"); + if (!res.ok) return null; + const value = (await res.json() as { agentMessagePermission?: unknown }).agentMessagePermission; + return value === "alwaysAsk" || value === "trustCluster" ? value : null; + } catch { + return null; + } + }, []); + useEffect(() => { + let alive = true; + void load().then((value) => { if (alive) setPermission(value); }); + return () => { alive = false; }; + }, [load]); + const change = async (next: AgentMessagePermission) => { + setSaving(true); + try { + const res = await fetch("/api/web-settings", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ agentMessagePermission: next }), + }); + const saved = await load(res); + if (!saved) throw new Error(`HTTP ${res.status}`); + setPermission(saved); + } catch (error) { + setPermission(null); + toast.error(t("settingsConfig.agentMessagePermissionSaveFailed"), error instanceof Error ? error.message : String(error)); + setPermission(await load()); + } finally { + setSaving(false); + } + }; + return ( + + void change(next as AgentMessagePermission)} + /> + + ); +} + function GithubWritesSetting() { const { t } = useI18n(); // null until loaded, and after a failed load: showing "off" there could hide writes the server allows. @@ -1957,6 +2013,7 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal + diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs index 51437a6cf..a3142c82d 100644 --- a/lib/agent-tools.test.mjs +++ b/lib/agent-tools.test.mjs @@ -57,7 +57,7 @@ function fakeOps(overrides = {}) { }, async sessionHostId(sessionId) { calls.hostLookups.push(sessionId); - return { "target-1": "local", "ci-target": "h-ci", "build-target": "h-build" }[sessionId] ?? null; + return { "target-1": "local", t: "local", "ci-target": "h-ci", "build-target": "h-build" }[sessionId] ?? null; }, ...overrides, }; @@ -68,6 +68,8 @@ const ctx = (overrides = {}) => ({ sourceRequestId: "native-request-1", sourceCwd: "/tmp/source", sourceHostId: "local", + messagePermission: "trustCluster", + clusterHostIds: new Set(), enabled: true, guard: new AgentToolGuard(), confirm: async () => { throw new Error("no confirm expected"); }, @@ -360,37 +362,94 @@ test("a remote caller reaching another host is asked unless that host allows age assert.deepEqual(ops.calls.create.map((input) => input.hostId), ["h-build", "h-ci"]); }); -test("a remote caller's send_to_session to a session on this machine asks first", async () => { +test("always ask requires confirmation for every send_to_session target", async () => { const ops = fakeOps(); const titles = []; - await assert.rejects( - () => executeAgentTool("send_to_session", { sessionId: "target-1", message: "rm -rf ~" }, ops, ctx({ sourceHostId: "h-ci", confirm: asking(titles, false) })), - /declined/, + await executeAgentTool( + "send_to_session", + { sessionId: "build-target", message: "hi" }, + ops, + ctx({ messagePermission: "alwaysAsk", confirm: asking(titles) }), ); - assert.deepEqual(titles, ["Send a message from a session on ci-box to session target-1 on This machine?"]); - assert.equal(ops.calls.deliver.length, 0); - await executeAgentTool("send_to_session", { sessionId: "target-1", message: "hi" }, ops, ctx({ sourceHostId: "h-ci", confirm: asking([]) })); - assert.equal(ops.calls.deliver.length, 1); + await executeAgentTool( + "send_to_session", + { sessionId: "build-target", message: "again" }, + ops, + ctx({ sourceHostId: "h-build", messagePermission: "alwaysAsk", confirm: asking(titles) }), + ); + assert.deepEqual(titles, [ + "Send a message from a session on This machine to session build-target on build-box?", + "Send a message from a session on build-box to session build-target on build-box?", + ]); + assert.equal(ops.calls.deliver.length, 2); }); -test("a remote caller's send_to_session on its own host, or to a host that allows agent starts, asks nothing", async () => { +test("an absent runtime message policy fails safe by asking", async () => { const ops = fakeOps(); - await executeAgentTool("send_to_session", { sessionId: "build-target", message: "hi" }, ops, ctx({ sourceHostId: "h-build" })); - await executeAgentTool("send_to_session", { sessionId: "ci-target", message: "hi" }, ops, ctx({ sourceHostId: "h-build" })); - assert.equal(ops.calls.deliver.length, 2); - await assert.rejects( - () => executeAgentTool("send_to_session", { sessionId: "nowhere", message: "hi" }, ops, ctx({ sourceHostId: "h-build" })), - /Session not found/, + const titles = []; + await executeAgentTool( + "send_to_session", + { sessionId: "build-target", message: "hi" }, + ops, + ctx({ messagePermission: undefined, confirm: asking(titles) }), ); + assert.deepEqual(titles, ["Send a message from a session on This machine to session build-target on build-box?"]); }); -test("a local caller's send_to_session neither looks up the target's host nor asks", async () => { +test("trust cluster sends between cluster members without asking", async () => { const ops = fakeOps(); - await executeAgentTool("send_to_session", { sessionId: "build-target", message: "hi" }, ops, ctx()); - assert.deepEqual(ops.calls.hostLookups, []); + await executeAgentTool( + "send_to_session", + { sessionId: "target-1", message: "hi" }, + ops, + ctx({ + sourceHostId: "h-ci", + messagePermission: "trustCluster", + clusterHostIds: new Set(["local", "h-ci"]), + }), + ); assert.equal(ops.calls.deliver.length, 1); }); +test("trust cluster still asks across either side of the cluster boundary", async () => { + const titles = []; + for (const clusterHostIds of [new Set(["h-ci"]), new Set(["h-build"])]) { + await executeAgentTool( + "send_to_session", + { sessionId: "build-target", message: "hi" }, + fakeOps(), + ctx({ sourceHostId: "h-ci", messagePermission: "trustCluster", clusterHostIds, confirm: asking(titles) }), + ); + } + assert.deepEqual(titles, [ + "Send a message from a session on ci-box to session build-target on build-box?", + "Send a message from a session on ci-box to session build-target on build-box?", + ]); +}); + +test("trust cluster preserves standalone host approval rules", async () => { + const ops = fakeOps(); + const titles = []; + await executeAgentTool( + "send_to_session", + { sessionId: "build-target", message: "hi" }, + ops, + ctx({ sourceHostId: "h-ci", messagePermission: "trustCluster", confirm: asking(titles) }), + ); + await executeAgentTool( + "send_to_session", + { sessionId: "ci-target", message: "hi" }, + ops, + ctx({ sourceHostId: "h-build", messagePermission: "trustCluster" }), + ); + assert.deepEqual(titles, ["Send a message from a session on ci-box to session build-target on build-box?"]); + assert.equal(ops.calls.deliver.length, 2); + await assert.rejects( + () => executeAgentTool("send_to_session", { sessionId: "nowhere", message: "hi" }, ops, ctx({ messagePermission: "trustCluster" })), + /Session not found/, + ); +}); + test("unknown agent tools are rejected (#275)", async () => { await assert.rejects(() => executeAgentTool("delete_everything", {}, fakeOps(), ctx()), /Unknown agent tool/); }); @@ -502,6 +561,59 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold return { rpc, hub, until, sourceId, sourceRow, sourceCwd, sourceChannel, source, worker, standalone, pool, spawns, preparations, commands, results, dialogs, session, call, reachedInitialization: reachedInitialization.promise }; } +test("send_to_session re-reads cluster membership and refuses corrupt pool state", async (t) => { + const f = await placementFixture(t, { workerAllows: false }); + const { savePools } = await import("./hosts/pools.ts"); + const targetId = randomUUID(); + const targetCwd = "/selected/project"; + const { session: target } = await f.rpc.startRpcSession( + targetId, + `/remote/sessions/${targetId}.jsonl`, + targetCwd, + undefined, + false, + targetCwd, + undefined, + f.hub.getHost(f.worker.id), + ); + writeFileSync(join(agentScratch, "omp-web-settings.json"), JSON.stringify({ + agentToolsEnabled: true, + agentMessagePermission: "trustCluster", + agentEnv: {}, + })); + globalThis.__ompWebSettingsCache = undefined; + const member = (hostId, projectsRoot) => ({ hostId, projectsRoot, provisioned: true, draining: false }); + const cluster = { + id: `cluster-${randomUUID()}`, + label: "Cluster", + enabled: true, + members: [member(f.source.id, "/owner"), member(f.worker.id, "/selected")], + projects: [], + }; + savePools([cluster, f.pool]); + + const trusted = await f.call({ sessionId: target.sessionId, message: "inside" }, "inside-cluster", "send_to_session"); + assert.equal(trusted.isError, false, trusted.result.content[0].text); + assert.equal(f.dialogs.length, 0); + + savePools([{ ...cluster, members: [cluster.members[0]] }, f.pool]); + const pending = f.call({ sessionId: target.sessionId, message: "outside", delivery: "followUp" }, "outside-cluster", "send_to_session"); + await Promise.race([ + f.until(() => f.dialogs.length === 1, "cross-boundary confirmation"), + pending.then((result) => assert.fail(`cross-boundary send finished without approval: ${result.result.content[0].text}`)), + ]); + await f.session.send({ type: "ui_response", id: f.dialogs[0].id, value: true }); + const approved = await pending; + assert.equal(approved.isError, false, approved.result.content[0].text); + + const messagesBefore = f.commands.filter((command) => command.hostId === f.worker.id && ["prompt", "follow_up", "steer"].includes(command.type)).length; + writeFileSync(join(agentScratch, "omp-web", "pools.json"), "{ invalid", "utf8"); + const corrupt = await f.call({ sessionId: target.sessionId, message: "blocked", delivery: "followUp" }, "corrupt-cluster", "send_to_session"); + assert.equal(corrupt.isError, true); + assert.match(corrupt.result.content[0].text, /Invalid pool registry JSON/); + assert.equal(f.commands.filter((command) => command.hostId === f.worker.id && ["prompt", "follow_up", "steer"].includes(command.type)).length, messagesBefore); +}); + test("independent pooled agent creation reserves a real owner and initializes one child for a native request", async (t) => { const f = await placementFixture(t); const requestId = `native/request:Ω/${"x".repeat(300)}`; diff --git a/lib/agent-tools.ts b/lib/agent-tools.ts index 789937017..65ae5337e 100644 --- a/lib/agent-tools.ts +++ b/lib/agent-tools.ts @@ -2,6 +2,7 @@ import type { HostToolDefinition } from "./pi-types"; import { isRecord } from "./type-guards"; import { startsUnasked, type AgentToolHost } from "./agent-tool-hosts"; import { GITHUB_TOOL_DEFINITIONS, GITHUB_TOOL_NAMES, executeGithubTool, type GithubToolOps } from "./github/tools"; +import type { AgentMessagePermission } from "./web-settings"; /** * Server-side agent tools for issue #275: tools an agent running inside @@ -151,6 +152,10 @@ export interface AgentToolContext { sourceCwd: string; /** The host the calling session runs on; "local" is this machine. */ sourceHostId: string; + /** Whether every send asks, or messages within the cluster are trusted. */ + messagePermission: AgentMessagePermission; + /** Physical hosts in the first pool. */ + clusterHostIds: ReadonlySet; /** The off-by-default Settings gate (lib/web-settings agentToolsEnabled). */ enabled: boolean; guard: AgentToolGuard; @@ -390,17 +395,20 @@ export async function executeAgentTool( const delivery = parseDelivery(record); const { wait, waitTimeoutMs } = parseWait(record); const depth = ctx.guard.checkChainDepth(ctx.sourceSessionId); - // A remote agent reaching a session on another machine asks first, as new_session does. - if (ctx.sourceHostId !== "local") { - const targetHostId = await ops.sessionHostId(sessionId); - if (!targetHostId) throw new Error(`Session not found: ${sessionId}`); - const hosts = ops.listHosts(); - const target = hosts.find((h) => h.id === targetHostId); - if (targetHostId !== ctx.sourceHostId && !(target && startsUnasked(target, ctx.sourceHostId))) { - const sourceLabel = hosts.find((h) => h.id === ctx.sourceHostId)?.label ?? ctx.sourceHostId; - if (!(await ctx.confirm(`Send a message from a session on ${sourceLabel} to session ${sessionId} on ${target?.label ?? targetHostId}?`))) { - throw new Error(`The user declined to send a message to session ${sessionId}.`); - } + const targetHostId = await ops.sessionHostId(sessionId); + if (!targetHostId) throw new Error(`Session not found: ${sessionId}`); + const hosts = ops.listHosts(); + const target = hosts.find((host) => host.id === targetHostId); + const sameCluster = ctx.messagePermission === "trustCluster" + && ctx.clusterHostIds.has(ctx.sourceHostId) + && ctx.clusterHostIds.has(targetHostId); + const followsExistingRule = targetHostId === ctx.sourceHostId + || ctx.sourceHostId === "local" + || (target ? startsUnasked(target, ctx.sourceHostId) : false); + if (ctx.messagePermission !== "trustCluster" || (!sameCluster && !followsExistingRule)) { + const sourceLabel = hosts.find((host) => host.id === ctx.sourceHostId)?.label ?? ctx.sourceHostId; + if (!(await ctx.confirm(`Send a message from a session on ${sourceLabel} to session ${sessionId} on ${target?.label ?? targetHostId}?`))) { + throw new Error(`The user declined to send a message to session ${sessionId}.`); } } const result = await ops.deliver({ diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index dcc7bda5c..714fed259 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -90,6 +90,12 @@ "settingsConfig.agentTools": "Agent tools (cross-session)", "settingsConfig.agentToolsDesc": "Allow agents to call list_sessions, new_session and send_to_session to reach other omp-web sessions, even with no browser tab open. Messages delivered this way are prefixed with the sending session's ID. A per-session rate limit and a chain-depth limit stop sessions looping messages to each other. GitHub tools for watching and reading issues and pull requests, writing comments and threads, and managing Actions workflow runs are under this setting too and need the GitHub CLI (gh) installed and logged in on this server. Applies to sessions started or reconnected after saving.", "settingsConfig.agentToolsSaveFailed": "Could not save the agent tools setting", + "settingsConfig.agentMessagePermission": "Agent message approval", + "settingsConfig.agentMessagePermissionDesc": "Choose whether every send_to_session call asks first, or sessions may message other sessions within the cluster without asking. Standalone hosts still follow their per-host permission.", + "settingsConfig.agentMessagePermissionAlwaysAsk": "Always ask", + "settingsConfig.agentMessagePermissionTrustCluster": "Trust cluster", + "settingsConfig.agentMessagePermissionSaveFailed": "Could not save the agent message approval", + "settingsConfig.agentMessagePermissionUnavailable": "Unavailable", "settingsConfig.githubWritesUnasked": "Allow agent GitHub writes without asking", "settingsConfig.githubWritesUnaskedDesc": "Let agents post comments, reply in review threads and resolve threads through this server's gh login without a confirmation each time. Off: each of those comment and thread writes asks in the session first.", "settingsConfig.githubWritesUnaskedSaveFailed": "Could not save the GitHub writes setting", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index ec51a427c..16b5a1051 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -88,6 +88,12 @@ "settingsConfig.autoResumeSessionsDesc": "エージェントの作業中に omp-web が再起動した場合、それらのセッションを再開し、各エージェントに「Session interrupted and resumed. Continue as you would have done without the interruption.」と伝えます。再起動の時点で進行中だった作業(実行中のコマンドなど)は失われます。", "settingsConfig.autoResumeSessions": "再起動後に実行中のセッションを再開", "settingsConfig.agentToolsDesc": "ブラウザーのタブを開いていなくても、エージェントが list_sessions、new_session、send_to_session を使って他の omp-web セッションとやり取りできるようにします。この方法で届くメッセージには送信元セッションの ID が先頭に付きます。セッションごとの送信回数と連鎖の深さを制限し、相互送信のループを防ぎます。Issue とプルリクエストの監視・読み取り、コメントとスレッドへの書き込み、Actions ワークフロー実行の管理を行う GitHub ツールもこの設定で制御され、このサーバーに GitHub CLI(gh)をインストールしてログインしておく必要があります。保存後に開始または再接続したセッションに適用されます。", + "settingsConfig.agentMessagePermission": "エージェントメッセージの承認", + "settingsConfig.agentMessagePermissionDesc": "send_to_session の呼び出しごとに確認するか、クラスター内のセッション間メッセージを確認なしで許可するかを選択します。スタンドアロンホストには、ホストごとの権限が引き続き適用されます。", + "settingsConfig.agentMessagePermissionAlwaysAsk": "常に確認", + "settingsConfig.agentMessagePermissionTrustCluster": "クラスターを信頼", + "settingsConfig.agentMessagePermissionSaveFailed": "エージェントメッセージの承認設定を保存できませんでした", + "settingsConfig.agentMessagePermissionUnavailable": "利用できません", "settingsConfig.uploadRetention": "送信済みのアップロードを削除するまで", "settingsConfig.uploadRetentionDesc": "「ファイルとして」添付したファイルは、この期間が過ぎると、すべてのホストの各セッションの local://uploads フォルダー(アーカイブ済みセッションを含む)から削除されます。「しない」を選ぶと削除されません。", "settingsConfig.uploadRetentionNever": "しない", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 240b0493d..3b3365119 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -88,6 +88,12 @@ "settingsConfig.autoResumeSessionsDesc": "如果 omp-web 在智能体工作时重启,将重新启动这些会话并告知每个智能体:“Session interrupted and resumed. Continue as you would have done without the interruption.”重启时正在进行的工作(例如正在运行的命令)会丢失。", "settingsConfig.autoResumeSessions": "重启后恢复正在运行的会话", "settingsConfig.agentToolsDesc": "允许智能体通过 list_sessions、new_session 和 send_to_session 与其他 omp-web 会话通信,即使未打开浏览器标签页也可使用。通过此方式传递的消息会带有发送会话 ID 前缀。每个会话的速率限制和调用链深度限制可防止会话之间循环发送消息。用于监视和读取议题与拉取请求、写入评论与审查线程以及管理 Actions 工作流运行的 GitHub 工具也受此设置控制,并要求本服务器已安装 GitHub CLI(gh)且已登录。保存后启动或重新连接的会话才会应用此设置。", + "settingsConfig.agentMessagePermission": "智能体消息审批", + "settingsConfig.agentMessagePermissionDesc": "选择每次调用 send_to_session 时都先确认,或允许集群内的会话无需确认即可互发消息。独立主机仍遵循各自主机权限。", + "settingsConfig.agentMessagePermissionAlwaysAsk": "每次询问", + "settingsConfig.agentMessagePermissionTrustCluster": "信任集群", + "settingsConfig.agentMessagePermissionSaveFailed": "无法保存智能体消息审批设置", + "settingsConfig.agentMessagePermissionUnavailable": "不可用", "settingsConfig.uploadRetention": "已发送的上传文件保留时间", "settingsConfig.uploadRetentionDesc": "以“作为文件”方式附加的文件,超过此时间后会从所有主机上每个会话的 local://uploads 文件夹(包括已归档的会话)中删除。选择“从不”则一直保留。", "settingsConfig.uploadRetentionNever": "从不", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 4fd46760d..9c3d47a29 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -90,6 +90,12 @@ "settingsConfig.agentTools": "代理工具(跨對話)", "settingsConfig.agentToolsDesc": "允許代理呼叫 list_sessions、new_session 與 send_to_session 與其他 omp-web 對話溝通,即使瀏覽器分頁未開啟也適用。透過此方式傳遞的訊息會加上來源對話的 ID 前綴。每個對話設有速率限制與呼叫鏈深度限制,以防止對話間陷入訊息迴圈。用於監看和讀取議題與提取要求、寫入留言與審查討論串,以及管理 Actions 工作流程執行的 GitHub 工具同樣受此設定控制,且需要本伺服器已安裝並登入 GitHub CLI(gh)。設定會在儲存後啟動或重新連線的對話中生效。", "settingsConfig.agentToolsSaveFailed": "無法儲存代理工具設定", + "settingsConfig.agentMessagePermission": "代理訊息核准", + "settingsConfig.agentMessagePermissionDesc": "選擇每次呼叫 send_to_session 時都先詢問,或允許叢集內的工作階段無需詢問即可互傳訊息。獨立主機仍遵循各主機的權限設定。", + "settingsConfig.agentMessagePermissionAlwaysAsk": "每次詢問", + "settingsConfig.agentMessagePermissionTrustCluster": "信任叢集", + "settingsConfig.agentMessagePermissionSaveFailed": "無法儲存代理訊息核准設定", + "settingsConfig.agentMessagePermissionUnavailable": "無法使用", "settingsConfig.githubWritesUnasked": "允許代理無需詢問即可寫入 GitHub", "settingsConfig.githubWritesUnaskedDesc": "允許代理透過本伺服器的 gh 登入發表留言、在審查討論串中回覆並解決討論串,每次無需再確認。關閉時,這些留言與討論串寫入每次都會先在對話中詢問。", "settingsConfig.githubWritesUnaskedSaveFailed": "無法儲存 GitHub 寫入設定", diff --git a/lib/message-outbox-review.test.mjs b/lib/message-outbox-review.test.mjs index 6ccf0aece..fb913de5d 100644 --- a/lib/message-outbox-review.test.mjs +++ b/lib/message-outbox-review.test.mjs @@ -789,7 +789,7 @@ test("a hidden native custom message with the exact ID never settles its row, ev }); test("a real server agent-tool steer also invalidates an overlapping identical text-matched outbox echo", async () => { - saveWebServerSettings({ agentToolsEnabled: true }); + saveWebServerSettings({ agentToolsEnabled: true, agentMessagePermission: "trustCluster" }); const sid = "overlap-agent-target"; const sourceId = "overlap-agent-source"; const message = `[From session ${sourceId} via omp-web agent tools]: same`; @@ -810,7 +810,7 @@ test("a real server agent-tool steer also invalidates an overlapping identical t test("an open ask holds a steer until it is answered and turns an agent-tool steer into a follow-up", async () => { outbox.startOutbox(); - saveWebServerSettings({ agentToolsEnabled: true }); + saveWebServerSettings({ agentToolsEnabled: true, agentMessagePermission: "trustCluster" }); const sid = "open-ask-target"; const target = await liveSession(sid); const source = await liveSession("open-ask-source"); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 1c82df2b5..90774b8a3 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -1990,12 +1990,16 @@ export class AgentSessionWrapper { try { const args = event.arguments && typeof event.arguments === "object" ? event.arguments as Record : {}; const getSessionId = () => this.sessionId; + const settings = loadWebServerSettings(); + const clusterHostIds = new Set(loadPools()[0]?.members.map((member) => member.hostId) ?? []); const context: AgentToolContext = { get sourceSessionId() { return getSessionId(); }, sourceRequestId: id, sourceCwd: this.cwd, sourceHostId: this.host.id, - enabled: loadWebServerSettings().agentToolsEnabled, + enabled: settings.agentToolsEnabled, + messagePermission: settings.agentMessagePermission, + clusterHostIds, guard: getAgentToolGuard(), confirm: (title) => this.confirmFromServer(title, cancel.signal), signal: cancel.signal, diff --git a/lib/web-settings.test.mjs b/lib/web-settings.test.mjs index 9826a2529..fc620c7f6 100644 --- a/lib/web-settings.test.mjs +++ b/lib/web-settings.test.mjs @@ -23,7 +23,7 @@ function withAgentDir(run) { test("defaults apply when no settings file exists yet", () => { withAgentDir(() => { - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }); }); }); @@ -39,7 +39,7 @@ test("agentEnv round-trips through the settings file", () => { delete globalThis.__ompWebSettingsCache; process.env.PI_CODING_AGENT_DIR = fresh; try { - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { OBSIDIAN_API_KEY: "secret" }, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { OBSIDIAN_API_KEY: "secret" }, browserTransport: "ws", uploadRetentionDays: 30 }); } finally { rmSync(fresh, { recursive: true, force: true }); } @@ -60,7 +60,7 @@ test("a patch leaves the other keys untouched", () => { withAgentDir(() => { saveWebServerSettings({ autoResumeSessions: true, agentEnv: { A: "1" } }); saveWebServerSettings({ agentEnv: { B: "2" } }); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: true, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { B: "2" }, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: true, agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { B: "2" }, browserTransport: "ws", uploadRetentionDays: 30 }); }); }); @@ -107,7 +107,7 @@ test("settings GET reports peer permission changes and refuses unreadable values test("corrupt files fall back to defaults instead of throwing", () => { withAgentDir((dir) => { writeFileSync(join(dir, "omp-web-settings.json"), "{ not json", "utf8"); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }); }); }); @@ -122,6 +122,18 @@ test("agentToolsEnabled round-trips, and a non-boolean value falls back to false }); }); +test("agent message permission defaults to always ask, round-trips trust cluster, and rejects unknown stored values", () => { + withAgentDir(() => { + assert.equal(loadWebServerSettings().agentMessagePermission, "alwaysAsk"); + saveWebServerSettings({ agentMessagePermission: "trustCluster" }); + assert.equal(loadWebServerSettings().agentMessagePermission, "trustCluster"); + }); + withAgentDir((dir) => { + writeFileSync(join(dir, "omp-web-settings.json"), JSON.stringify({ agentMessagePermission: "sometimes" }), "utf8"); + assert.equal(loadWebServerSettings().agentMessagePermission, "alwaysAsk"); + }); +}); + test("watcher and write gates read peer permissions without changing cached settings", () => { withAgentDir((dir) => { const file = join(dir, "omp-web-settings.json"); @@ -188,6 +200,22 @@ test("web settings PUT validates GitHub Actions permission maps and GET returns rmSync(dir, { recursive: true, force: true }); }); const { GET, PUT } = await import("../app/api/web-settings/route.ts"); + const invalidMessagePermission = await PUT(new Request("http://localhost/api/web-settings", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ agentMessagePermission: "sometimes" }), + })); + assert.equal(invalidMessagePermission.status, 400); + assert.equal((await invalidMessagePermission.json()).code, "invalid_settings"); + + const savedMessagePermission = await PUT(new Request("http://localhost/api/web-settings", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ agentMessagePermission: "trustCluster" }), + })); + assert.equal(savedMessagePermission.status, 200); + assert.equal((await savedMessagePermission.json()).agentMessagePermission, "trustCluster"); + for (const githubActionsPermissions of [ "allow", { dispatch: "sometimes" }, @@ -227,7 +255,7 @@ test("a missing browserTransport reads as ws, sse and ws round-trip, and unknown for (const value of ["ws-client", "ws-client-split", "ws-session", "ws-pool", "websocket", true]) { withAgentDir((dir) => { writeFileSync(join(dir, "omp-web-settings.json"), JSON.stringify({ browserTransport: value, browserTransportPerSocket: 8, browserTransportMaxSockets: 3 }), "utf8"); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }, `${JSON.stringify(value)} reads as ws`); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }, `${JSON.stringify(value)} reads as ws`); }); } }); @@ -239,7 +267,7 @@ test("only string-valued agentEnv entries are kept", () => { JSON.stringify({ autoResumeSessions: "yes", agentEnv: { GOOD: "1", BAD: 2, WORSE: null, NESTED: { a: 1 } } }), "utf8", ); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { GOOD: "1" }, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { GOOD: "1" }, browserTransport: "ws", uploadRetentionDays: 30 }); }); }); diff --git a/lib/web-settings.ts b/lib/web-settings.ts index 59080a5f9..b666c2856 100644 --- a/lib/web-settings.ts +++ b/lib/web-settings.ts @@ -10,6 +10,8 @@ export type GithubActionsOperation = "dispatch" | "cancel" | "rerun"; export type GithubActionsPermission = "deny" | "ask" | "allow"; export type GithubActionsPermissions = Record; +export type AgentMessagePermission = "alwaysAsk" | "trustCluster"; + /** omp-web's own server-side settings (omp's config.yml stays omp's). */ export interface WebServerSettings { /** Resume sessions that were mid-run when omp-web stopped. */ @@ -22,6 +24,8 @@ export interface WebServerSettings { * or SSE reconnect). */ agentToolsEnabled: boolean; + /** Approval policy for send_to_session calls. */ + agentMessagePermission: AgentMessagePermission; /** The GitHub agent tools may post and resolve threads as the server's `gh` account without asking the user each time. */ githubWritesUnasked: boolean; /** Per-operation approval policy for GitHub Actions mutations. */ @@ -41,6 +45,7 @@ export interface WebServerSettings { const DEFAULTS: WebServerSettings = { autoResumeSessions: false, agentToolsEnabled: false, + agentMessagePermission: "alwaysAsk", githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, @@ -94,6 +99,7 @@ function normalizeSettings(raw: Record): WebServerSettings { return { autoResumeSessions: raw.autoResumeSessions === true, agentToolsEnabled: raw.agentToolsEnabled === true, + agentMessagePermission: raw.agentMessagePermission === "trustCluster" ? "trustCluster" : "alwaysAsk", githubWritesUnasked: raw.githubWritesUnasked === true, githubActionsPermissions: readGithubActionsPermissions(raw.githubActionsPermissions), agentEnv: readAgentEnvRecord(raw.agentEnv), From cf2313342d312412b4215f720d6d0eb20f824339 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 16 Nov 2026 01:30:50 +0000 Subject: [PATCH 2/7] fix(agent-tools): harden message approval handling --- .../SettingsConfig.agent-messages.test.mjs | 15 ++++++++---- lib/agent-tools.test.mjs | 21 +++++++++++++++++ lib/agent-tools.ts | 1 + lib/rpc-manager.test.mjs | 23 ++++++++++++++++++- lib/rpc-manager.ts | 2 +- 5 files changed, 55 insertions(+), 7 deletions(-) diff --git a/components/SettingsConfig.agent-messages.test.mjs b/components/SettingsConfig.agent-messages.test.mjs index 0d73f7a51..7b340b019 100644 --- a/components/SettingsConfig.agent-messages.test.mjs +++ b/components/SettingsConfig.agent-messages.test.mjs @@ -77,13 +77,17 @@ test("agent message approval shows unavailable instead of inventing a policy whi }); test("an uncertain agent message approval save reloads the committed policy", async (t) => { - let loads = 0; + let saveAttempted = false; + let loadsAfterSave = 0; const originalFetch = globalThis.fetch; globalThis.fetch = async (url, init) => { if (String(url) !== "/api/web-settings") return Response.json({}); - if (init?.method === "PUT") throw new TypeError("Failed to fetch"); - loads++; - return Response.json({ agentMessagePermission: loads === 1 ? "alwaysAsk" : "trustCluster" }); + if (init?.method === "PUT") { + saveAttempted = true; + throw new TypeError("Failed to fetch"); + } + if (saveAttempted) loadsAfterSave++; + return Response.json({ agentMessagePermission: saveAttempted ? "trustCluster" : "alwaysAsk" }); }; t.after(() => { cleanup(); @@ -94,7 +98,8 @@ test("an uncertain agent message approval save reloads the committed policy", as await settle(); const select = within(container).getByRole("combobox", { name: "Agent message approval" }); await choose(select, "Trust cluster"); - assert.ok(loads > 1); + assert.equal(saveAttempted, true); + assert.ok(loadsAfterSave > 0); assert.equal(select.disabled, false); assert.equal(select.textContent, "Trust cluster"); }); diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs index a3142c82d..658014c94 100644 --- a/lib/agent-tools.test.mjs +++ b/lib/agent-tools.test.mjs @@ -411,6 +411,27 @@ test("trust cluster sends between cluster members without asking", async () => { assert.equal(ops.calls.deliver.length, 1); }); +test("a cancelled trusted-cluster send stops before delivery", async () => { + const ops = fakeOps(); + const controller = new AbortController(); + controller.abort(); + await assert.rejects( + () => executeAgentTool( + "send_to_session", + { sessionId: "target-1", message: "hi" }, + ops, + ctx({ + sourceHostId: "h-ci", + messagePermission: "trustCluster", + clusterHostIds: new Set(["local", "h-ci"]), + signal: controller.signal, + }), + ), + /cancelled/, + ); + assert.equal(ops.calls.deliver.length, 0); +}); + test("trust cluster still asks across either side of the cluster boundary", async () => { const titles = []; for (const clusterHostIds of [new Set(["h-ci"]), new Set(["h-build"])]) { diff --git a/lib/agent-tools.ts b/lib/agent-tools.ts index 65ae5337e..6c71af82b 100644 --- a/lib/agent-tools.ts +++ b/lib/agent-tools.ts @@ -411,6 +411,7 @@ export async function executeAgentTool( throw new Error(`The user declined to send a message to session ${sessionId}.`); } } + if (ctx.signal?.aborted) throw new Error("The agent tool call was cancelled before the message was sent."); const result = await ops.deliver({ sessionId, message: formatAttributedMessage(ctx.sourceSessionId, message), diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index b1c704a1e..6fb38d76b 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; -import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; @@ -2573,6 +2573,27 @@ test("server agent tools are answered by the server, not the browser (#275)", as detach(); }); +test("corrupt pool state does not block GitHub agent tools", async (t) => { + globalThis.__ompWebSettingsCache = undefined; + const settingsPath = join(isolatedAgentDir, "omp-web-settings.json"); + const poolsPath = join(isolatedAgentDir, "omp-web", "pools.json"); + writeFileSync(settingsPath, JSON.stringify({ agentToolsEnabled: true, agentEnv: {} })); + mkdirSync(join(isolatedAgentDir, "omp-web"), { recursive: true }); + writeFileSync(poolsPath, "{ invalid", "utf8"); + t.after(() => { + globalThis.__ompWebSettingsCache = undefined; + try { rmSync(settingsPath); } catch { /* already gone */ } + try { rmSync(poolsPath); } catch { /* already gone */ } + }); + + const { transports } = await serverToolSession(t, "github-invalid-pools", "local"); + transports[0].emitFrame({ type: "host_tool_call", id: "invalid-target", toolName: "github_read", arguments: { target: "not a target" } }); + await waitUntil(() => hostToolResults(transports[0]).some((frame) => frame.id === "invalid-target")); + const result = hostToolResults(transports[0]).find((frame) => frame.id === "invalid-target"); + assert.equal(result.isError, true); + assert.doesNotMatch(result.result.content[0].text, /pool registry/i); +}); + test("cancelling GitHub read and write confirmations closes dialogs without granting or posting", async (t) => { globalThis.__ompWebSettingsCache = undefined; const settingsPath = join(isolatedAgentDir, "omp-web-settings.json"); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 90774b8a3..e99b0b231 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -1991,7 +1991,7 @@ export class AgentSessionWrapper { const args = event.arguments && typeof event.arguments === "object" ? event.arguments as Record : {}; const getSessionId = () => this.sessionId; const settings = loadWebServerSettings(); - const clusterHostIds = new Set(loadPools()[0]?.members.map((member) => member.hostId) ?? []); + const clusterHostIds = new Set(toolName === "send_to_session" ? loadPools()[0]?.members.map((member) => member.hostId) ?? [] : []); const context: AgentToolContext = { get sourceSessionId() { return getSessionId(); }, sourceRequestId: id, From 2b292ab5b6d6994639124d88677218501bcfcf68 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 16 Nov 2026 01:52:17 +0000 Subject: [PATCH 3/7] fix(agent-tools): read message policy from disk --- lib/agent-tools.test.mjs | 26 +++++++++++++++++++++++--- lib/rpc-manager.ts | 4 ++-- lib/web-settings.test.mjs | 12 +++++++++--- lib/web-settings.ts | 4 ++++ 4 files changed, 38 insertions(+), 8 deletions(-) diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs index 658014c94..20c6d5da3 100644 --- a/lib/agent-tools.test.mjs +++ b/lib/agent-tools.test.mjs @@ -582,7 +582,7 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold return { rpc, hub, until, sourceId, sourceRow, sourceCwd, sourceChannel, source, worker, standalone, pool, spawns, preparations, commands, results, dialogs, session, call, reachedInitialization: reachedInitialization.promise }; } -test("send_to_session re-reads cluster membership and refuses corrupt pool state", async (t) => { +test("send_to_session re-reads message policy and cluster membership, and refuses corrupt pool state", async (t) => { const f = await placementFixture(t, { workerAllows: false }); const { savePools } = await import("./hosts/pools.ts"); const targetId = randomUUID(); @@ -617,13 +617,33 @@ test("send_to_session re-reads cluster membership and refuses corrupt pool state assert.equal(trusted.isError, false, trusted.result.content[0].text); assert.equal(f.dialogs.length, 0); + const settingsFile = join(agentScratch, "omp-web-settings.json"); + writeFileSync(settingsFile, JSON.stringify({ + agentToolsEnabled: true, + agentMessagePermission: "alwaysAsk", + agentEnv: {}, + })); + const policyPending = f.call({ sessionId: target.sessionId, message: "ask now", delivery: "followUp" }, "fresh-policy", "send_to_session"); + await Promise.race([ + f.until(() => f.dialogs.length === 1, "fresh policy confirmation"), + policyPending.then((result) => assert.fail(`stale trust-cluster policy bypassed approval: ${result.result.content[0].text}`)), + ]); + await f.session.send({ type: "ui_response", id: f.dialogs[0].id, value: true }); + const policyApproved = await policyPending; + assert.equal(policyApproved.isError, false, policyApproved.result.content[0].text); + writeFileSync(settingsFile, JSON.stringify({ + agentToolsEnabled: true, + agentMessagePermission: "trustCluster", + agentEnv: {}, + })); + savePools([{ ...cluster, members: [cluster.members[0]] }, f.pool]); const pending = f.call({ sessionId: target.sessionId, message: "outside", delivery: "followUp" }, "outside-cluster", "send_to_session"); await Promise.race([ - f.until(() => f.dialogs.length === 1, "cross-boundary confirmation"), + f.until(() => f.dialogs.length === 2, "cross-boundary confirmation"), pending.then((result) => assert.fail(`cross-boundary send finished without approval: ${result.result.content[0].text}`)), ]); - await f.session.send({ type: "ui_response", id: f.dialogs[0].id, value: true }); + await f.session.send({ type: "ui_response", id: f.dialogs[1].id, value: true }); const approved = await pending; assert.equal(approved.isError, false, approved.result.content[0].text); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index e99b0b231..77f01cb28 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -9,7 +9,7 @@ import { RpcCommandError, RpcCommandTimeoutError, RpcProcess, type RpcFrame } fr import type { RpcTransport } from "./omp/rpc-transport"; import { cacheSessionPath } from "./session-reader"; import { allowFileRoot } from "./file-access"; -import { loadWebServerSettings } from "./web-settings"; +import { loadWebServerSettings, readAgentMessagePermissionFromDisk } from "./web-settings"; import { AGENT_TOOL_DEFINITIONS, AGENT_TOOL_NAMES, @@ -1998,7 +1998,7 @@ export class AgentSessionWrapper { sourceCwd: this.cwd, sourceHostId: this.host.id, enabled: settings.agentToolsEnabled, - messagePermission: settings.agentMessagePermission, + messagePermission: readAgentMessagePermissionFromDisk(), clusterHostIds, guard: getAgentToolGuard(), confirm: (title) => this.confirmFromServer(title, cancel.signal), diff --git a/lib/web-settings.test.mjs b/lib/web-settings.test.mjs index fc620c7f6..284588465 100644 --- a/lib/web-settings.test.mjs +++ b/lib/web-settings.test.mjs @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -const { loadWebServerSettings, readAgentToolsEnabledFromDisk, readGithubActionsPermissionFromDisk, readGithubWritesUnaskedFromDisk, saveWebServerSettings } = await import("./web-settings.ts"); +const { loadWebServerSettings, readAgentMessagePermissionFromDisk, readAgentToolsEnabledFromDisk, readGithubActionsPermissionFromDisk, readGithubWritesUnaskedFromDisk, saveWebServerSettings } = await import("./web-settings.ts"); function withAgentDir(run) { const dir = mkdtempSync(join(tmpdir(), "omp-web-web-settings-")); @@ -137,24 +137,30 @@ test("agent message permission defaults to always ask, round-trips trust cluster test("watcher and write gates read peer permissions without changing cached settings", () => { withAgentDir((dir) => { const file = join(dir, "omp-web-settings.json"); - saveWebServerSettings({ agentToolsEnabled: true, githubWritesUnasked: true }); + saveWebServerSettings({ agentToolsEnabled: true, agentMessagePermission: "trustCluster", githubWritesUnasked: true }); assert.equal(loadWebServerSettings().agentToolsEnabled, true); + assert.equal(loadWebServerSettings().agentMessagePermission, "trustCluster"); assert.equal(loadWebServerSettings().githubWritesUnasked, true); - writeFileSync(file, JSON.stringify({ agentToolsEnabled: false, githubWritesUnasked: false }), "utf8"); + writeFileSync(file, JSON.stringify({ agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false }), "utf8"); assert.equal(readAgentToolsEnabledFromDisk(), false); + assert.equal(readAgentMessagePermissionFromDisk(), "alwaysAsk"); assert.equal(readGithubWritesUnaskedFromDisk(), false); assert.equal(loadWebServerSettings().agentToolsEnabled, true); + assert.equal(loadWebServerSettings().agentMessagePermission, "trustCluster"); assert.equal(loadWebServerSettings().githubWritesUnasked, true); writeFileSync(file, "{ not json", "utf8"); assert.equal(readAgentToolsEnabledFromDisk(), false); assert.equal(readGithubWritesUnaskedFromDisk(), false); + assert.equal(readAgentMessagePermissionFromDisk(), "alwaysAsk"); rmSync(file); assert.equal(readAgentToolsEnabledFromDisk(), false); assert.equal(readGithubWritesUnaskedFromDisk(), false); + assert.equal(readAgentMessagePermissionFromDisk(), "alwaysAsk"); assert.equal(loadWebServerSettings().agentToolsEnabled, true); assert.equal(loadWebServerSettings().githubWritesUnasked, true); + assert.equal(loadWebServerSettings().agentMessagePermission, "trustCluster"); }); }); diff --git a/lib/web-settings.ts b/lib/web-settings.ts index b666c2856..e545038e4 100644 --- a/lib/web-settings.ts +++ b/lib/web-settings.ts @@ -156,6 +156,10 @@ export function readAgentToolsEnabledFromDisk(): boolean { return freshSettingsRecord()?.agentToolsEnabled === true; } +export function readAgentMessagePermissionFromDisk(): AgentMessagePermission { + return freshSettingsRecord()?.agentMessagePermission === "trustCluster" ? "trustCluster" : "alwaysAsk"; +} + export function readGithubWritesUnaskedFromDisk(): boolean { return freshSettingsRecord()?.githubWritesUnasked === true; } From 147d4a46dc5a4ee6683f5460bd250b36233c7882 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 16 Nov 2026 01:59:38 +0000 Subject: [PATCH 4/7] perf(agent-tools): read message policy asynchronously --- lib/rpc-manager.ts | 2 +- lib/web-settings.test.mjs | 26 +++++++++++++++++++++----- lib/web-settings.ts | 9 +++++++-- 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 77f01cb28..618530312 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -1998,7 +1998,7 @@ export class AgentSessionWrapper { sourceCwd: this.cwd, sourceHostId: this.host.id, enabled: settings.agentToolsEnabled, - messagePermission: readAgentMessagePermissionFromDisk(), + messagePermission: await readAgentMessagePermissionFromDisk(), clusterHostIds, guard: getAgentToolGuard(), confirm: (title) => this.confirmFromServer(title, cancel.signal), diff --git a/lib/web-settings.test.mjs b/lib/web-settings.test.mjs index 284588465..28e1e20d3 100644 --- a/lib/web-settings.test.mjs +++ b/lib/web-settings.test.mjs @@ -21,6 +21,20 @@ function withAgentDir(run) { } } +async function withAgentDirAsync(run) { + const dir = mkdtempSync(join(tmpdir(), "omp-web-web-settings-")); + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = dir; + try { + return await run(dir); + } finally { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + delete globalThis.__ompWebSettingsCache; + rmSync(dir, { recursive: true, force: true }); + } +} + test("defaults apply when no settings file exists yet", () => { withAgentDir(() => { assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }); @@ -134,8 +148,8 @@ test("agent message permission defaults to always ask, round-trips trust cluster }); }); -test("watcher and write gates read peer permissions without changing cached settings", () => { - withAgentDir((dir) => { +test("watcher and write gates read peer permissions without changing cached settings", async () => { + await withAgentDirAsync(async (dir) => { const file = join(dir, "omp-web-settings.json"); saveWebServerSettings({ agentToolsEnabled: true, agentMessagePermission: "trustCluster", githubWritesUnasked: true }); assert.equal(loadWebServerSettings().agentToolsEnabled, true); @@ -144,7 +158,9 @@ test("watcher and write gates read peer permissions without changing cached sett writeFileSync(file, JSON.stringify({ agentToolsEnabled: false, agentMessagePermission: "alwaysAsk", githubWritesUnasked: false }), "utf8"); assert.equal(readAgentToolsEnabledFromDisk(), false); - assert.equal(readAgentMessagePermissionFromDisk(), "alwaysAsk"); + const permission = readAgentMessagePermissionFromDisk(); + assert.ok(permission instanceof Promise); + assert.equal(await permission, "alwaysAsk"); assert.equal(readGithubWritesUnaskedFromDisk(), false); assert.equal(loadWebServerSettings().agentToolsEnabled, true); assert.equal(loadWebServerSettings().agentMessagePermission, "trustCluster"); @@ -153,11 +169,11 @@ test("watcher and write gates read peer permissions without changing cached sett writeFileSync(file, "{ not json", "utf8"); assert.equal(readAgentToolsEnabledFromDisk(), false); assert.equal(readGithubWritesUnaskedFromDisk(), false); - assert.equal(readAgentMessagePermissionFromDisk(), "alwaysAsk"); + assert.equal(await readAgentMessagePermissionFromDisk(), "alwaysAsk"); rmSync(file); assert.equal(readAgentToolsEnabledFromDisk(), false); assert.equal(readGithubWritesUnaskedFromDisk(), false); - assert.equal(readAgentMessagePermissionFromDisk(), "alwaysAsk"); + assert.equal(await readAgentMessagePermissionFromDisk(), "alwaysAsk"); assert.equal(loadWebServerSettings().agentToolsEnabled, true); assert.equal(loadWebServerSettings().githubWritesUnasked, true); assert.equal(loadWebServerSettings().agentMessagePermission, "trustCluster"); diff --git a/lib/web-settings.ts b/lib/web-settings.ts index e545038e4..b1c526c69 100644 --- a/lib/web-settings.ts +++ b/lib/web-settings.ts @@ -1,5 +1,6 @@ import { DatabaseSync } from "node:sqlite"; import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs"; +import { readFile } from "node:fs/promises"; import { resolve } from "path"; import { getAgentDir } from "./omp/paths"; import { BROWSER_TRANSPORTS, type BrowserTransport, type BrowserTransportState } from "./event-stream-protocol"; @@ -156,8 +157,12 @@ export function readAgentToolsEnabledFromDisk(): boolean { return freshSettingsRecord()?.agentToolsEnabled === true; } -export function readAgentMessagePermissionFromDisk(): AgentMessagePermission { - return freshSettingsRecord()?.agentMessagePermission === "trustCluster" ? "trustCluster" : "alwaysAsk"; +export async function readAgentMessagePermissionFromDisk(): Promise { + try { + return parseSettingsRecord(await readFile(settingsPath(), "utf8")).agentMessagePermission === "trustCluster" ? "trustCluster" : "alwaysAsk"; + } catch { + return "alwaysAsk"; + } } export function readGithubWritesUnaskedFromDisk(): boolean { From 5a8ce91bea1e123aa4f45c89974f3ab74dedcf53 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 16 Nov 2026 02:10:23 +0000 Subject: [PATCH 5/7] fix(agent-tools): preserve replay and membership ordering --- lib/rpc-manager.test.mjs | 13 ++++++++----- lib/rpc-manager.ts | 8 +++++--- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 6fb38d76b..9535b4128 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -3761,11 +3761,14 @@ test("replayed standalone new_session and other mutating agent tools stay unknow }); await until(() => hostToolResults(transport).length === 3, "every replayed agent tool answered"); const unknown = "omp-web restarted while this ran; the outcome is unknown, check with list_sessions before retrying"; - assert.deepEqual(hostToolResults(transport).map((frame) => [frame.id, frame.isError, frame.result.content[0].text === unknown]), [ - ["n1", true, true], - ["s1", true, true], - ["l1", false, false], - ]); + assert.deepEqual(Object.fromEntries(hostToolResults(transport).map((frame) => [ + frame.id, + [frame.isError, frame.result.content[0].text === unknown], + ])), { + n1: [true, true], + s1: [true, true], + l1: [false, false], + }); }); test("replayed github_comment and github_resolve_thread stay unknown and post nothing; github_read runs again", async (t) => { diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 618530312..e3e9cefea 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -1991,6 +1991,8 @@ export class AgentSessionWrapper { const args = event.arguments && typeof event.arguments === "object" ? event.arguments as Record : {}; const getSessionId = () => this.sessionId; const settings = loadWebServerSettings(); + const replaying = this.replaying; + const messagePermission = await readAgentMessagePermissionFromDisk(); const clusterHostIds = new Set(toolName === "send_to_session" ? loadPools()[0]?.members.map((member) => member.hostId) ?? [] : []); const context: AgentToolContext = { get sourceSessionId() { return getSessionId(); }, @@ -1998,16 +2000,16 @@ export class AgentSessionWrapper { sourceCwd: this.cwd, sourceHostId: this.host.id, enabled: settings.agentToolsEnabled, - messagePermission: await readAgentMessagePermissionFromDisk(), + messagePermission, clusterHostIds, guard: getAgentToolGuard(), confirm: (title) => this.confirmFromServer(title, cancel.signal), signal: cancel.signal, }; - if (this.replaying && toolName === "new_session" && ( + if (replaying && toolName === "new_session" && ( args.shareWorkspace === true || args.host != null || !poolProjectBindings(loadPools()).get(this.host.id)?.size )) throw new Error(AGENT_TOOL_UNKNOWN_OUTCOME); - const result = await executeAgentTool(toolName, args, createAgentToolOps(context, this.replaying), context); + const result = await executeAgentTool(toolName, args, createAgentToolOps(context, replaying), context); sendToolResult(typeof result === "string" ? result : JSON.stringify(result)); } catch (error) { if (error instanceof PoolStartError) { From ff9000c6a3de74f8554828ec95dc7e65f15ecb00 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 16 Nov 2026 02:25:12 +0000 Subject: [PATCH 6/7] fix(agent-tools): fence approved session operations --- lib/agent-tools.test.mjs | 54 ++++++++++++++++++++++++++++++++++++++-- lib/agent-tools.ts | 4 +++ lib/rpc-manager.ts | 19 ++++++++++++-- 3 files changed, 73 insertions(+), 4 deletions(-) diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs index 20c6d5da3..a5fdda768 100644 --- a/lib/agent-tools.test.mjs +++ b/lib/agent-tools.test.mjs @@ -172,6 +172,7 @@ test("send_to_session attributes, defaults to prompt, and passes wait through (# ); assert.equal(ops.calls.deliver.length, 1); const input = ops.calls.deliver[0]; + assert.equal(input.hostId, "local"); assert.equal(input.message, "[From session source-1 via omp-web agent tools]: The build passed"); assert.equal(input.delivery, "prompt"); assert.equal(input.wait, true); @@ -339,8 +340,24 @@ test("a remote caller's new_session defaults to its own host and follows that ho const titles = []; await executeAgentTool("new_session", {}, ops, ctx({ sourceHostId: "h-build", sourceCwd: "/srv/app", confirm: asking(titles) })); assert.deepEqual(titles, ["Start a session on build-box in /srv/app?"]); + assert.equal(ops.calls.create[1].hostId, "h-build"); }); +test("a cancelled unasked new_session stops before creation", async () => { + const ops = fakeOps(); + const controller = new AbortController(); + controller.abort(); + await assert.rejects( + () => executeAgentTool( + "new_session", + { host: "ci-box", cwd: "/srv/app" }, + ops, + ctx({ signal: controller.signal }), + ), + /cancelled/, + ); + assert.equal(ops.calls.create.length, 0); +}); test("a remote caller starting a session on this machine is always asked", async () => { const ops = fakeOps(); @@ -514,6 +531,7 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold const identities = new Map(); const sourceCwd = "/owner/.project_worktrees/session/unpublished-parent"; const sourceRow = { id: sourceId, path: `/remote/sessions/${sourceId}.jsonl`, cwd: sourceCwd, projectRoot: "/owner/project", created: "c", modified: "m", messageCount: 1, firstMessage: "parent" }; + const sessionRows = new Map(links.map((link) => [link.id, link === source ? [sourceRow] : []])); const pool = { id: poolId, label: "Agent pool", enabled: true, members: [{ hostId: worker.id, projectsRoot: "/selected", provisioned: true, draining: false }, @@ -526,7 +544,7 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold writeFileSync(join(agentScratch, "omp-web-settings.json"), JSON.stringify({ agentToolsEnabled: true, agentEnv: {} })); for (const link of links) { link.serve({ - listSessions: () => link === source ? [sourceRow] : [], + listSessions: () => sessionRows.get(link.id), validateCwd: ({ path }) => ({ ok: true, value: { cwd: path, projectRoot: link === source ? "/owner/project" : path } }), sessionFileExists: () => false, invalidateSessionLists: () => null, @@ -579,7 +597,7 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold await until(() => results.slice(before).some((result) => result.id === requestId), `${toolName} result`); return results.slice(before).find((result) => result.id === requestId); } - return { rpc, hub, until, sourceId, sourceRow, sourceCwd, sourceChannel, source, worker, standalone, pool, spawns, preparations, commands, results, dialogs, session, call, reachedInitialization: reachedInitialization.promise }; + return { rpc, hub, until, sourceId, sourceRow, sourceCwd, sourceChannel, source, worker, standalone, pool, sessionRows, spawns, preparations, commands, results, dialogs, session, call, reachedInitialization: reachedInitialization.promise }; } test("send_to_session re-reads message policy and cluster membership, and refuses corrupt pool state", async (t) => { @@ -655,6 +673,38 @@ test("send_to_session re-reads message policy and cluster membership, and refuse assert.equal(f.commands.filter((command) => command.hostId === f.worker.id && ["prompt", "follow_up", "steer"].includes(command.type)).length, messagesBefore); }); +test("send_to_session refuses a cold target that moves after approval", async (t) => { + const f = await placementFixture(t, { workerAllows: false }); + const { invalidateHostSessionList } = await import("./hosts/session-index.ts"); + const targetId = randomUUID(); + const target = { + id: targetId, + path: `/remote/sessions/${targetId}.jsonl`, + cwd: "/selected/project", + created: "c", + modified: "m", + messageCount: 1, + firstMessage: "target", + }; + f.sessionRows.get(f.worker.id).push(target); + invalidateHostSessionList(f.worker.id); + const pending = f.call({ sessionId: targetId, message: "checked owner" }, "moved-target", "send_to_session"); + await Promise.race([ + f.until(() => f.dialogs.length === 1, "target-host confirmation"), + pending.then((result) => assert.fail(`message finished before approval: ${result.result.content[0].text}`)), + ]); + + f.sessionRows.set(f.worker.id, []); + f.sessionRows.get(f.standalone.id).push({ ...target, cwd: "/standalone/project" }); + invalidateHostSessionList(f.worker.id); + invalidateHostSessionList(f.standalone.id); + await f.session.send({ type: "ui_response", id: f.dialogs[0].id, value: true }); + const result = await pending; + assert.equal(result.isError, true); + assert.match(result.result.content[0].text, /moved to another host/); + assert.equal(f.spawns.length, 1, "the moved target must not start on its unchecked host"); +}); + test("independent pooled agent creation reserves a real owner and initializes one child for a native request", async (t) => { const f = await placementFixture(t); const requestId = `native/request:Ω/${"x".repeat(300)}`; diff --git a/lib/agent-tools.ts b/lib/agent-tools.ts index 6c71af82b..3cea88de4 100644 --- a/lib/agent-tools.ts +++ b/lib/agent-tools.ts @@ -115,6 +115,8 @@ export interface AgentToolCreateSessionInput { export interface AgentToolDeliverInput { sessionId: string; + /** Host whose approval policy was checked before delivery. */ + hostId: string; /** Already sender-attributed by executeAgentTool. */ message: string; delivery: "prompt" | "steer" | "followUp"; @@ -370,6 +372,7 @@ export async function executeAgentTool( const requestedHost = optionalString(record, "host"); const host = resolveHost(ops.listHosts(), requestedHost ?? ctx.sourceHostId); if (shareWorkspace && host.id !== ctx.sourceHostId) throw new Error("shareWorkspace requires the calling session's host."); + if (ctx.signal?.aborted) throw new Error("The agent tool call was cancelled before a session was started."); const created = await ops.createSession({ cwd, hostId: host.id, @@ -414,6 +417,7 @@ export async function executeAgentTool( if (ctx.signal?.aborted) throw new Error("The agent tool call was cancelled before the message was sent."); const result = await ops.deliver({ sessionId, + hostId: targetHostId, message: formatAttributedMessage(ctx.sourceSessionId, message), delivery, wait, diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index e3e9cefea..42d947ea8 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -3432,10 +3432,16 @@ function createAgentToolOps(source: AgentToolContext, replaying: boolean): Agent listHosts: hosts, async createSession(input, authorize) { - const authorizeHost = (host: Host) => { + const throwIfCancelled = () => { + if (source.signal?.aborted) throw new Error("The agent tool call was cancelled before a session was started."); + }; + const authorizeHost = async (host: Host) => { + throwIfCancelled(); const configured = this.listHosts().find((candidate) => candidate.id === host.id); if (!configured) throw new Error(`Unknown host: ${host.id}`); - return authorize(configured); + const allowed = await authorize(configured); + throwIfCancelled(); + return allowed; }; const initialize = async (session: AgentSessionWrapper, preserveUnknownDelivery: boolean) => { if (input.provider && input.modelId) { @@ -3446,6 +3452,7 @@ function createAgentToolOps(source: AgentToolContext, replaying: boolean): Agent }; if (!input.shareWorkspace && !input.explicitHost && input.hostId === source.sourceHostId) { const sessions = await listSessionsAllHosts(); + throwIfCancelled(); const origin = sessions.find((session) => session.id === source.sourceSessionId && (session.hostId ?? LOCAL_HOST_ID) === source.sourceHostId); const bindings = poolProjectBindings(loadPools()).get(source.sourceHostId); const binding = bindings?.get(comparableProjectPath(input.cwd === source.sourceCwd @@ -3454,6 +3461,7 @@ function createAgentToolOps(source: AgentToolContext, replaying: boolean): Agent const creationId = createHash("sha256").update("ompweb:agent-creation:v1:") .update(JSON.stringify([source.sourceSessionId, source.sourceRequestId])).digest("hex"); const result = await startPooledSession({ creationId, poolId: binding.pool.id, projectId: binding.project.id, intent: { ...input } }, async (host, prepared, id, onStarted) => { + throwIfCancelled(); const started = await startNewRpcSession(host, prepared.cwd, undefined, false, true, id); if (!started.ok) throw new HostOpError(started.status, started.code, started.error); const { session, realSessionId } = started.value; @@ -3470,6 +3478,7 @@ function createAgentToolOps(source: AgentToolContext, replaying: boolean): Agent if (!host) throw new Error(`Unknown host: ${input.hostId}`); if (!(await authorizeHost(host))) throw new Error(`The user declined to start a session on ${host.label}.`); const preparing = !!(input.prompt || input.name || (input.provider && input.modelId)); + throwIfCancelled(); const started = await startNewRpcSession(host, input.cwd, undefined, undefined, preparing); if (!started.ok) throw new Error(started.error); const { session, realSessionId } = started.value; @@ -3487,10 +3496,16 @@ function createAgentToolOps(source: AgentToolContext, replaying: boolean): Agent async deliver(input): Promise { const live = getRpcSession(input.sessionId); + if (live?.isAlive() && live.host.id !== input.hostId) { + throw new Error(`Session ${input.sessionId} moved to another host; the message was not sent.`); + } let wrapper = live?.isAlive() ? live : undefined; let cold = false; if (!wrapper) { const host = await hostForSessionId(input.sessionId); + if (host && host.id !== input.hostId) { + throw new Error(`Session ${input.sessionId} moved to another host; the message was not sent.`); + } const target = host && await sessionSpawnTarget(input.sessionId, host); if (!host || !target) throw new Error(`Session not found: ${input.sessionId}`); // The open's preparation lease keeps an idle shared child (and its advisor mode) until the message is sent. From c6d22106f4e70bbcf57a8096dc3c12c2d75c2f11 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 16 Nov 2026 03:02:30 +0000 Subject: [PATCH 7/7] fix(agent-tools): release cancelled pool starts --- lib/agent-tools.test.mjs | 36 ++++++++++++++++++++++++++++++++---- lib/rpc-manager.ts | 2 +- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs index a5fdda768..444b54e55 100644 --- a/lib/agent-tools.test.mjs +++ b/lib/agent-tools.test.mjs @@ -515,7 +515,7 @@ test("new_session preserves the enable, rate and chain-depth guards", async () = const startsInJournal = () => existsSync(journalPath) ? JSON.parse(readFileSync(journalPath, "utf8")).starts : []; /** Keep registry, admission, RpcProcess and link routing real; replace only daemon/OMP boundaries. */ -async function placementFixture(t, { workerAllows = true, fallback = false, holdInitialization } = {}) { +async function placementFixture(t, { workerAllows = true, fallback = false, holdInitialization, holdPreparation = false } = {}) { const rpc = await import("./rpc-manager.ts"); const hub = await import("./hosts/hub.ts"); const { linkHost, until } = await import("./hosts/link-driver.test-helper.mjs"); @@ -528,6 +528,8 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold for (const link of links) updateHost(link.id, { allowAgentStart: link !== worker || workerAllows }); const spawns = [], preparations = [], commands = [], results = [], dialogs = []; const reachedInitialization = Promise.withResolvers(); + const reachedPreparation = Promise.withResolvers(); + const releasePreparation = Promise.withResolvers(); const identities = new Map(); const sourceCwd = "/owner/.project_worktrees/session/unpublished-parent"; const sourceRow = { id: sourceId, path: `/remote/sessions/${sourceId}.jsonl`, cwd: sourceCwd, projectRoot: "/owner/project", created: "c", modified: "m", messageCount: 1, firstMessage: "parent" }; @@ -547,9 +549,12 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold listSessions: () => sessionRows.get(link.id), validateCwd: ({ path }) => ({ ok: true, value: { cwd: path, projectRoot: link === source ? "/owner/project" : path } }), sessionFileExists: () => false, - invalidateSessionLists: () => null, - preparePoolProject: ({ input }) => { + preparePoolProject: async ({ input }) => { preparations.push({ hostId: link.id, ...input }); + if (holdPreparation) { + reachedPreparation.resolve(); + await releasePreparation.promise; + } // A simulated POSIX worker: its paths follow POSIX rules whatever OS runs this test. return { ok: true, value: { cwd: posix.join(posix.dirname(input.cloneRoot), `.${posix.basename(input.cloneRoot)}_worktrees`, "session", input.creationId), projectRoot: input.cloneRoot, baseCommit: "a".repeat(40) } }; }, @@ -597,7 +602,7 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold await until(() => results.slice(before).some((result) => result.id === requestId), `${toolName} result`); return results.slice(before).find((result) => result.id === requestId); } - return { rpc, hub, until, sourceId, sourceRow, sourceCwd, sourceChannel, source, worker, standalone, pool, sessionRows, spawns, preparations, commands, results, dialogs, session, call, reachedInitialization: reachedInitialization.promise }; + return { rpc, hub, until, sourceId, sourceRow, sourceCwd, sourceChannel, source, worker, standalone, pool, sessionRows, spawns, preparations, commands, results, dialogs, session, call, reachedInitialization: reachedInitialization.promise, reachedPreparation: reachedPreparation.promise, releasePreparation: releasePreparation.resolve }; } test("send_to_session re-reads message policy and cluster membership, and refuses corrupt pool state", async (t) => { @@ -778,6 +783,29 @@ test("independent pooled agent creation reserves a real owner and initializes on assert.equal(f.commands.filter((command) => command.type === "prompt").length, 1); }); +test("cancelling pooled creation during preparation releases its reservation without spawning", async (t) => { + const f = await placementFixture(t, { holdPreparation: true }); + const requestId = "cancel-during-pool-preparation"; + const pending = f.call({}, requestId); + await f.reachedPreparation; + const reserved = startsInJournal().find((start) => start.poolId === f.pool.id && start.reserved); + assert.ok(reserved); + + await f.source.post({ + type: "stdout", + ch: f.sourceChannel, + line: JSON.stringify({ t: "host_tool_cancel", targetId: requestId }), + }); + f.releasePreparation(); + const cancelled = await pending; + assert.equal(cancelled.isError, true); + assert.match(cancelled.result.content[0].text, /cancelled/); + const released = startsInJournal().find((start) => start.creationId === reserved.creationId); + assert.equal(released.reserved, false); + assert.equal(released.creation, "refused"); + assert.equal(f.spawns.length, 1, "only the source session exists"); +}); + for (const [label, args, target] of [ ["shared workspace", { shareWorkspace: true }, "source"], ["explicit standalone host", { host: "Standalone target", cwd: "/standalone/project" }, "standalone"], diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 42d947ea8..98abf53f5 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -3433,7 +3433,7 @@ function createAgentToolOps(source: AgentToolContext, replaying: boolean): Agent async createSession(input, authorize) { const throwIfCancelled = () => { - if (source.signal?.aborted) throw new Error("The agent tool call was cancelled before a session was started."); + if (source.signal?.aborted) throw new HostOpError(499, "agent_tool_cancelled", "The agent tool call was cancelled before a session was started."); }; const authorizeHost = async (host: Host) => { throwIfCancelled();