Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(runtime): preserve denied tool declarations in Plan and Goal
zszz37dfcd92e9122
diff --git a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md b/docs/adr/0062-bounded-subagents-behind-a-task-tool.mdindex 11c1dc4e0..a2ff87c2c 100644--- a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md+++ b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md@@ -89,9 +89,11 @@ The `Task` tool takes `agent`, `task` and an optional short `description`. Thecatalog of available delegates rides in the tool description rather than thesystem prompt, because the two change together.-`Task` is offered only in Agent mode. Plan and Goal are read-only contract+`Task` executes only in Agent mode. Plan and Goal are read-only contractnegotiations (D198), and a delegate with Bash or Edit would drive straight-through one.+through one. [Contract-mode declaration compatibility](plan-tool-declarations-and-execution-denials.md)+retains configured Task-family schemas but rejects their execution before any+delegate is created or controlled; a visible schema is not a permission grant.Concurrency is expressed through pi's execution modes: the session Agent runswith `toolExecution: "parallel"`, every catalog tool carriesdiff --git a/docs/adr/README.md b/docs/adr/README.mdindex 33651c3b3..0a69f87a9 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -20,6 +20,7 @@ Each ADR includes:| ID | Title | Status ||---|---|---|+| plan-tool-declarations-and-execution-denials | [Keep known tool declarations while denying contract-mode execution](plan-tool-declarations-and-execution-denials.md) | Accepted for implementation || trusted-extension-operation-ownership | [Trusted extension operation ownership](trusted-extension-operation-ownership.md) | Implemented candidate || scheduled-desktop-automations | [Desktop automation scheduling](scheduled-desktop-automations.md) | Accepted for implementation || subagent-model-fallback | [Ordered subagent model fallback](subagent-model-fallback.md) | Accepted for implementation |diff --git a/docs/adr/plan-tool-declarations-and-execution-denials.md b/docs/adr/plan-tool-declarations-and-execution-denials.mdnew file mode 100644index 000000000..da351fa5b--- /dev/null+++ b/docs/adr/plan-tool-declarations-and-execution-denials.md@@ -0,0 +1,57 @@+# ADR: Keep known tool declarations while denying contract-mode execution++- Status: Accepted for implementation+- Date: 2026-09-28+- Amends: ADR 0062 (declaration visibility only)+- Related: #1174++## Context++Plan/Goal removed editing and delegation tools from the provider request while+retaining earlier tool-call history. A model that repeats one of those names+can be rejected by a strict gateway before PI-Desktop receives the call. The+application then cannot produce a tool result with that call's identity.+Preserving a declaration and granting execution are separate responsibilities.++## Decision++Keep Write and Edit declarations in the main session's Plan/Goal requests.+When subagents are configured, retain the Task/TaskWait/TaskList/TaskStop+schemas too. These tools remain core declarations and are explicitly labelled+unavailable in the contract mode. Unknown tools, missing subagent definitions,+on-demand tools and non-plan-safe plugin tools do not gain new declarations.++Keep the current mode allowlist authoritative for execution. Block prohibited+calls before extension call hooks or tool handlers run. Additionally wrap the+registered handler with a fresh mode check, so an object retained before a+mode switch cannot execute using stale authority. pi's existing error path+returns the failure with the original call id and continues the model loop.+Task denial must occur before creating or controlling any delegate. Host-core+permission checks, including hard Plan/Goal Write/Edit denial, remain unchanged.++The transcript is retained. No synthetic tool call, replacement call id,+extra user correction prompt, provider-error classifier or retry path is added.+Returning to Agent restores normal execution through existing permission gates.+Subagent tool scopes and their isolated histories remain unchanged.++## Alternatives++- Delete or rewrite old tool history: changes useful context without proving+ that history caused the model's next invalid call.+- Add a user-message correction after a gateway failure: cannot produce a+ normal paired tool result and introduces a separate recovery policy.+- Declare every plugin/tool: expands context and capability disclosure beyond+ the known mode-restricted tools needed by this failure path.+- Permit editing in Plan/Goal: violates the existing execution boundary.++## Consequences++Declared tools no longer imply permission to execute them. Models see a small+number of denied schemas, so the mode prompt and each denied description must+remain explicit. The normal tool-error channel provides actionable feedback+without a request-level 502 when the gateway accepts the declared call.+A gateway rejecting a correctly declared tool or inventing an unknown tool+remains a separate interoperability failure; this decision does not promise+that every third-party model will obey the mode prompt.++No database, IPC, plugin permission or host ownership migration is required.diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 06aeb6d7f..0ee25ec6e 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -650,6 +650,16 @@ submitted Markdown bytes in a new immutablestructured title/question in `plan_approvals`, and moves the live state to`awaiting_approval`.+Plan/Goal requests retain Write/Edit declarations and, when subagents are+configured, the Task/TaskWait/TaskList/TaskStop declarations. They are marked+unavailable in the active mode. The execution allowlist remains unchanged:+prohibited calls are blocked before extension call hooks and handlers, and a+handler retained across a mode change rechecks that mode before executing.+The model receives an ordinary error tool result with the original call id;+no editing, delegation, fake user message or transcript deletion occurs.+Other deferred/plugin tools keep their existing visibility rules. See+[the declaration/permission decision](../../adr/plan-tool-declarations-and-execution-denials.md).+Approval has only `approve` and `reject`. Approval commits `mode = agent`, theexplicit permission mode, an execution ID, and `execution_state = queued` onthe same `plan_approvals` row in one host transaction. Thediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex d81b99fbb..44e903e39 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6145,6 +6145,23 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.`provider-retry.test.ts`, `runtime.test.ts`, `subagent.test.ts`.Other scenario variants remain Draft.+#### E2E-1174: Return a paired tool denial in Plan/Goal++- Seed earlier tool-call history, then switch an Agent session to Plan or Goal.+ A loopback Responses gateway emits Edit, Write or Task only if that tool is+ declared in the request; an undeclared name would cause a 502.+- Verify all six mode/tool combinations reach the normal tool-result path:+ the next request contains the original call id and a mode-denial error,+ preserves old call/result pairs, and adds no synthetic user correction.+- Assert that no host call occurs and no delegate starts. The tool event is an+ error while the model can continue with a read-only answer.+- A handler reference retained from Agent must refuse execution after Plan/Goal+ is entered; switching back to Agent restores the normal permission path.+- Automation: `mode-tool-access.test.ts` runs real runtime/SDK loops against a+ loopback HTTP/SSE fixture; `runtime.test.ts` covers catalog/mode transitions.+ Existing host permission tests keep Write/Edit denied regardless of grants or+ permission mode. No paid provider or user Desktop profile is used.+#### E2E-149: Recover provider rate limits (429) silently in place- **Preconditions**: A project-bound Agent session uses deterministic providerdiff --git a/docs/spec/07-plugins/16-trusted-extensions.md b/docs/spec/07-plugins/16-trusted-extensions.mdindex e924aacd2..cfb744f5a 100644--- a/docs/spec/07-plugins/16-trusted-extensions.md+++ b/docs/spec/07-plugins/16-trusted-extensions.md@@ -275,6 +275,11 @@ unsupported ones.| Deferred to v2 | `sendMessage`, `appendEntry`, `setLabel`, `sessionManager` read API, `switchSession`, `registerShortcut`, `registerMarkdownTransformer`, `ui.setEditorText`, `ui.getEditorText`, `ui.addAutocompleteProvider`, `registerFlag` value editing || Unsupported | `ui.setWidget`, `ui.setFooter`, `ui.setHeader`, `ui.setTitle`, `ui.custom`, `ui.overlay`, `ui.onTerminalInput`, `ui.setWorkingVisible`, `ui.setWorkingIndicator`, `ui.setHiddenThinkingLabel`, `ui.pasteToEditor`, `ui.editor`, `registerMessageRenderer`, `registerEntryRenderer`, `navigateTree`, `shutdown` |+`getActiveTools` describes the model-facing declarations, not execution grants.+Plan/Goal can retain denied Write/Edit and configured Task-family declarations;+the runtime mode gate runs before extension tool-call hooks or handlers. Plugins+must not infer permission from the presence of a name in this list.+`registerAgent({ id, name?, models, stream? | complete? })` registers asession-scoped plugin-owned LLM integration. Each model declares bounded publicmetadata (`id`, display name, API label, modalities, reasoning and limits). Thediff --git a/packages/agent-runtime/src/mode-prompts.ts b/packages/agent-runtime/src/mode-prompts.tsindex ecdfc07e1..332fb0680 100644--- a/packages/agent-runtime/src/mode-prompts.ts+++ b/packages/agent-runtime/src/mode-prompts.ts@@ -6,7 +6,7 @@ export const DEFAULT_RUNTIME_SYSTEM_PROMPT =export const PLAN_MODE_SYSTEM_PROMPT = ["You are operating in Plan mode as the same PI-Desktop agent, in a planning state.","Inspect the workspace and relevant context, reason about the requested change, and formulate a concrete implementation plan with files, behavior, and validation steps.",- "Do not use Write, Edit, or any unknown tool in Plan mode.",+ "Do not use Write, Edit, Task, TaskWait, TaskList, TaskStop, or any unknown tool in Plan mode. Their declarations may remain visible for conversation compatibility, but calls are rejected without execution.","Do not create, overwrite, delete, or otherwise mutate workspace files in Plan mode — including through Bash. Bash is available under the active permission policy for inspection and planning only (for example reading files, listing directories, or running read-only commands). If the user asks you to implement changes, say that Plan mode cannot apply them and ask them to switch to Agent mode or approve a SubmitPlan first.","Plugin tools that declare plan-safe actions are available for inspection (for example reading a URL through a browser plugin); only the listed plan-safe actions may run, anything else is denied.","Do not write or edit a plan file yourself. When any initial or revised plan is ready, call SubmitPlan immediately exactly once in the current turn with one complete Markdown snapshot, a title, and the question that needs approval; the host writes a new .pi/plan artifact and opens the review.",@@ -19,7 +19,7 @@ export const GOAL_MODE_SYSTEM_PROMPT = ["You are operating in Goal mode as the same PI-Desktop agent, negotiating a goal contract before any autonomous work.","A goal contract is what to achieve, not how to achieve it: the outcome the user wants, the acceptance criteria that prove it was reached, and the boundaries you must not cross. Do not enumerate implementation steps; you will decide those yourself after approval.","Inspect the workspace and ask the user about anything ambiguous first. Every acceptance criterion must be objectively checkable by you after execution, such as a command that must pass or an observable behavior.",- "Do not use Write, Edit, or any unknown tool in Goal mode.",+ "Do not use Write, Edit, Task, TaskWait, TaskList, TaskStop, or any unknown tool in Goal mode. Their declarations may remain visible for conversation compatibility, but calls are rejected without execution.","Do not create, overwrite, delete, or otherwise mutate workspace files in Goal mode — including through Bash. Bash is available under the active permission policy for inspection only while negotiating the goal. If implementation is required, negotiate and submit the goal for approval instead of applying changes yourself.","Plugin tools that declare plan-safe actions are available for inspection; only the listed plan-safe actions may run, anything else is denied.","Do not write or edit a goal file yourself. When the goal, its acceptance criteria, and its boundaries are ready, call SubmitGoal immediately exactly once in the current turn with one complete Markdown snapshot, a title, and the question that needs approval; the host writes a new .pi/goal artifact and opens the review.",diff --git a/packages/agent-runtime/src/mode-tool-access.test.ts b/packages/agent-runtime/src/mode-tool-access.test.tsnew file mode 100644index 000000000..64f96723e--- /dev/null+++ b/packages/agent-runtime/src/mode-tool-access.test.ts@@ -0,0 +1,122 @@+import { createServer, type ServerResponse } from "node:http";+import { afterEach, expect, it } from "vitest";+import { Type } from "typebox";+import type { AgentEventEnvelope, Mode, UiMessage } from "@pi-desktop/shared";+import { DesktopAgentRuntime } from "./runtime.js";+import type { RuntimeProviderConfig } from "./provider-binding.js";+import { modeToolDenial, withModeExecutionGuard } from "./mode-tool-access.js";++const cleanups: Array<() => Promise<void>> = [];+afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });++type Item = { type?: string; role?: string; name?: string; call_id?: string; content?: unknown; output?: unknown };+type Request = { tools: Array<{ name?: string }>; input: Item[] };++function respond(res: ServerResponse, name?: string) {+ res.writeHead(200, { "content-type": "text/event-stream" });+ const send = (data: { type: string; [key: string]: unknown }) => res.write(`event: ${data.type}\ndata: ${JSON.stringify(data)}\n\n`);+ send({ type: "response.created", response: { id: "resp_fixture" } });+ const args = name === "Task" ? { agent: "worker", task: "Inspect the fixture." }+ : name === "Write" ? { path: "fixture.txt", content: "must not be written" }+ : { path: "fixture.txt", tag: "ABCD", ops: "PUT >$:\n+must not be written" };+ const text = "This mode cannot perform that action. I will continue with a read-only plan.";+ const item = name+ ? { id: "fc_fixture", type: "function_call", call_id: "call_fixture", name, arguments: JSON.stringify(args), status: "completed" }+ : { id: "msg_fixture", type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text, annotations: [] }] };+ send({ type: "response.output_item.added", output_index: 0, item: name ? { ...item, arguments: "", status: "in_progress" } : { ...item, content: [], status: "in_progress" } });+ send(name+ ? { type: "response.function_call_arguments.delta", output_index: 0, delta: JSON.stringify(args) }+ : { type: "response.output_text.delta", output_index: 0, content_index: 0, delta: text });+ send({ type: "response.output_item.done", output_index: 0, item });+ send({ type: "response.completed", response: { id: "resp_fixture", status: "completed", output: [item],+ usage: { input_tokens: 10, output_tokens: 10, total_tokens: 20, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } } } });+ res.end();+}++it.each([+ ["plan", "Edit"], ["plan", "Write"], ["plan", "Task"],+ ["goal", "Edit"], ["goal", "Write"], ["goal", "Task"],+] as const)("%s declares %s but returns a paired denial before any host action", async (mode, name) => {+ const requests: Request[] = [];+ let firstReceived!: () => void;+ const received = new Promise<void>((resolve) => { firstReceived = resolve; });+ const server = createServer(async (req, res) => {+ let raw = "";+ for await (const part of req) raw += part;+ const request = JSON.parse(raw) as Request;+ requests.push(request);+ if (requests.length === 1) {+ firstReceived();+ // A strict gateway rejects undeclared calls before the application sees them.+ if (!request.tools.some((tool) => tool.name === name)) {+ res.writeHead(502, { "content-type": "application/json" });+ res.end(JSON.stringify({ error: { message: `undeclared client tool ${name}` } }));+ return;+ }+ respond(res, name);+ } else respond(res);+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ cleanups.push(async () => { server.closeAllConnections(); await new Promise<void>((resolve) => server.close(() => resolve())); });+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("fixture address missing");+ const baseUrl = `http://127.0.0.1:${address.port}/v1`;+ const provider: RuntimeProviderConfig = {+ id: "fixture", name: "Fixture", baseUrl, modelId: "fixture", apiKey: "fixture-not-real", apiStyle: "responses",+ supportsReasoning: false, supportedThinkingLevels: ["off"],+ modelConfig: { source: "generic", name: "Fixture", baseUrl, reasoning: false, input: ["text"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 200000, maxTokens: 2000 },+ };+ const history: UiMessage[] = [+ { id: "old-user", role: "user", content: "Earlier work", createdAt: "2026-09-28T00:00:00Z", status: "complete" },+ { id: "old-edit", role: "tool", toolName: "Edit", toolCallId: "old-edit", toolArgs: { path: "fixture.txt" },+ toolResult: "Earlier edit succeeded", content: "Earlier edit succeeded", toolStatus: "success", createdAt: "2026-09-28T00:00:00Z", status: "complete" },+ ];+ const originalHistory = structuredClone(history);+ const events: AgentEventEnvelope[] = [];+ const hostCalls: string[] = [];+ const runtime = new DesktopAgentRuntime({+ sessionId: "fixture", mode: "agent", provider, history, thinkingLevel: "off",+ compactionSettings: { enabled: false, reserveTokens: 0, keepRecentTokens: 0 },+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ subagents: [{ name: "worker", description: "Inspect", tools: ["Read"], prompt: "Inspect only.", source: "user" }],+ host: { call: async (method) => { hostCalls.push(method); throw new Error("blocked tools must never reach the host"); }, onNotification: () => () => {} },+ onEvent: (event) => { events.push(event); },+ });+ runtime.setMode(mode);+ const pending = runtime.prompt("Only discuss the plan.");+ void pending.catch(() => undefined);+ cleanups.push(async () => { await runtime.dispose(); await pending.catch(() => undefined); });+ await received;+ expect(requests[0].tools.some((tool) => tool.name === name)).toBe(true);+ await pending;+ expect(requests).toHaveLength(2);+ const result = requests[1].input.find((item) => item.type === "function_call_output" && item.call_id === "call_fixture");+ expect(JSON.stringify(result?.output)).toContain(`${name} is not allowed in ${mode} mode`);+ expect(requests[1].input.some((item) => item.type === "function_call" && item.call_id === "call_fixture" && item.name === name)).toBe(true);+ expect(requests[1].input.filter((item) => item.role === "user")).toEqual(requests[0].input.filter((item) => item.role === "user"));+ expect(requests[1].input.some((item) => item.type === "function_call_output" && item.call_id === "old-edit")).toBe(true);+ expect(history).toEqual(originalHistory);+ expect(hostCalls).toEqual([]);+ expect(events.some((event) => event.parentToolCallId)).toBe(false);+ expect(events.find((event) => event.event.type === "tool_end")?.event).toMatchObject({ type: "tool_end", isError: true });+ expect(events.some((event) => event.event.type === "error")).toBe(false);+ expect(events.some((event) => event.event.type === "agent_end")).toBe(true);+});++it("an old tool reference rechecks the current mode and resumes normal execution only in Agent", async () => {+ let mode: Mode = "agent";+ let calls = 0;+ const tool = withModeExecutionGuard({+ name: "Edit", label: "Edit", description: "Edit fixture", parameters: Type.Object({}),+ execute: async () => { calls++; return { content: [{ type: "text", text: "edited" }], details: {} }; },+ }, () => mode === "agent" ? undefined : modeToolDenial("Edit", mode));+ mode = "plan";+ await expect(tool.execute("blocked", {})).rejects.toThrow("not allowed in plan");+ mode = "goal";+ await expect(tool.execute("blocked-goal", {})).rejects.toThrow("not allowed in goal");+ expect(calls).toBe(0);+ mode = "agent";+ await tool.execute("allowed", {});+ expect(calls).toBe(1);+});diff --git a/packages/agent-runtime/src/mode-tool-access.ts b/packages/agent-runtime/src/mode-tool-access.tsnew file mode 100644index 000000000..1c8b9da2f--- /dev/null+++ b/packages/agent-runtime/src/mode-tool-access.ts@@ -0,0 +1,31 @@+import type { AgentTool } from "@earendil-works/pi-agent-core";+import type { Mode } from "@pi-desktop/shared";++/** Known editing/delegation names stay declared across contract-mode changes. */+const RETAINED_MODE_TOOLS = new Set(["Write", "Edit", "Task", "TaskWait", "TaskList", "TaskStop"]);++export function retainModeToolDeclaration(name: string): boolean {+ return RETAINED_MODE_TOOLS.has(name);+}++export function modeToolDenial(name: string, mode: Mode): string {+ return `${name} is not allowed in ${mode} mode. No action was performed. Continue read-only inspection and planning with the permitted tools; implementation requires Agent mode or approval of the submitted plan or goal.`;+}++/**+ * Declarations are not grants. Recheck immediately before execution, including+ * references retained from an earlier mode. Throwing here uses pi's existing+ * tool-error channel and the real call id, without inventing transcript items.+ */+export function withModeExecutionGuard(tool: AgentTool, denial: () => string | undefined): AgentTool {+ const currentDenial = denial();+ return {+ ...tool,+ description: currentDenial ? `${tool.description}\n\n${currentDenial}` : tool.description,+ execute: async (...args) => {+ const reason = denial();+ if (reason) throw new Error(reason);+ return tool.execute(...args);+ },+ };+}diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex f3c844e43..00c8e4624 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2050,8 +2050,7 @@ describe("DesktopAgentRuntime deferred tool catalog", () => {"SubmitPlan",]),);- expect(names).not.toContain("Write");- expect(names).not.toContain("Edit");+ expect(names).toEqual(expect.arrayContaining(["Write", "Edit"]));expect(names).not.toContain("Skill");expect(names).not.toContain("PluginCheck");expect(names).not.toContain("plugin_demo_run");@@ -2226,13 +2225,12 @@ describe("DesktopAgentRuntime mode and tool composition", () => {"SubmitPlan",]),);- expect(planTools).not.toEqual(- expect.arrayContaining(["Write", "Edit", "plugin_demo_run"]),- );+ expect(planTools).toEqual(expect.arrayContaining(["Write", "Edit"]));+ expect(planTools).not.toContain("plugin_demo_run");expect(planTools).not.toContain("EnterPlanMode");expect(planTools).not.toContain("SubmitGoal");expect(agent.state.systemPrompt).toContain("SubmitPlan");- expect(agent.state.systemPrompt).toContain("Do not use Write, Edit, or any unknown tool");+ expect(agent.state.systemPrompt).toContain("Do not use Write, Edit, Task");expect(agent.state.systemPrompt).toContain("plan-safe actions");expect(agent.state.systemPrompt).not.toContain("plugin_demo_run");expect(agent.state.systemPrompt).not.toContain("PluginCheck");@@ -2243,7 +2241,7 @@ describe("DesktopAgentRuntime mode and tool composition", () => {await runtime.dispose();});- it("gives Goal mode the read-only core plus only SubmitGoal", async () => {+ it("gives Goal mode the read-only core, guarded editing declarations, and SubmitGoal", async () => {const runtime = createRuntime({mode: "goal",pluginTools: [@@ -2267,8 +2265,7 @@ describe("DesktopAgentRuntime mode and tool composition", () => {"SubmitGoal",]),);- expect(goalTools).not.toContain("Write");- expect(goalTools).not.toContain("Edit");+ expect(goalTools).toEqual(expect.arrayContaining(["Write", "Edit"]));expect(goalTools).not.toContain("plugin_demo_run");expect(goalTools).not.toContain("SubmitPlan");expect(goalTools).not.toContain("EnterGoalMode");@@ -6922,7 +6919,7 @@ describe("DesktopAgentRuntime subagents", () => {await runtime.dispose();});- it("withholds Task without definitions and in contract modes", async () => {+ it("withholds undefined delegates but rejects declared Task execution in contract modes", async () => {const withoutDefinitions = createRuntime();expect(taskTool(withoutDefinitions)).toBeUndefined();await withoutDefinitions.dispose();@@ -6931,8 +6928,9 @@ describe("DesktopAgentRuntime subagents", () => {// with Bash or Edit would drive straight through them.for (const mode of ["plan", "goal"] as const) {const runtime = createRuntime({ mode, subagents: [explorer] });- expect(taskTool(runtime)).toBeUndefined();- expect((runtime as any).toolCatalog.has("Task")).toBe(false);+ expect(taskTool(runtime)).toBeDefined();+ await expect(taskTool(runtime).execute("blocked-task", { agent: "explorer", task: "Inspect." }))+ .rejects.toThrow(`not allowed in ${mode}`);await runtime.dispose();}});@@ -6940,8 +6938,11 @@ describe("DesktopAgentRuntime subagents", () => {it("rebuilds the Task catalog on a mode switch", async () => {const runtime = createRuntime({ subagents: [explorer] });+ const staleTask = taskTool(runtime);runtime.setMode("plan");- expect((runtime as any).toolCatalog.has("Task")).toBe(false);+ expect(taskTool(runtime)).toBeDefined();+ await expect(staleTask.execute("stale-task", { agent: "explorer", task: "Inspect." }))+ .rejects.toThrow("not allowed in plan");runtime.setMode("agent");expect(taskTool(runtime)).toBeDefined();diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 5ba8c7dbe..30cb878b7 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1,3 +1,4 @@+import { modeToolDenial, retainModeToolDeclaration, withModeExecutionGuard } from "./mode-tool-access.js";import { restoreHostedSearchReplay } from "./hosted-search-replay.js";import { requestExtensionUi } from "./extensions/ui-request.js";import { readLocalRequestErrorDetails } from "./local-request-errors.js";@@ -2324,7 +2325,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when thereason: `${[...MODE_TRANSITION_TOOL_NAMES].join(", ")} must be the only tool call in the assistant message.`,};}- if (!transition) return this.extensionToolCall(context);+ if (!transition) {+ if (!this.isToolAllowedInMode(context.toolCall.name)) {+ return { block: true, reason: modeToolDenial(context.toolCall.name, this.mode) };+ }+ return this.extensionToolCall(context);+ }const enterKind = enterToolKind(context.toolCall.name);if (enterKind && this.mode !== "agent") {return {@@ -3385,8 +3391,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// BrowserPreview is non-mutating (renders an existing workspace file in// the work panel browser), so it ships in every mode. PluginCheck only- // reads a directory; PluginScaffold and PluginPack write, so they follow- // Write/Edit/Bash into agent mode only.+ // reads a directory; PluginScaffold and PluginPack write and remain+ // Agent-only. Write/Edit keep guarded declarations in contract modes.const tools =this.mode === "agent"? [@@ -3399,7 +3405,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the"BrowserPreview","PluginCheck",]- : ["Read", "Glob", "Grep", "BrowserPreview", "Bash"];+ : ["Read", "Glob", "Grep", "BrowserPreview", "Bash", "Write", "Edit"];if (this.mode === "agent") {tools.push("PluginScaffold", "PluginPack", "GenerateImages", ...Object.keys(scheduledToolParameters));}@@ -3460,12 +3466,11 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.mode === "agent"? [this.buildEnterModeTool("plan"), this.buildEnterModeTool("goal")]: [this.buildSubmitTool(this.mode)];- // Delegation is an Agent-mode capability: Plan and Goal are read-only- // contract negotiations, and a delegate with Bash or Edit would drive- // straight through that (ADR 0062). The whole lifecycle rides together:- // `Task` starts, `TaskWait`/`TaskList`/`TaskStop` converge (ADR 0089).+ // Keep configured delegation declarations stable across mode changes.+ // Contract modes reject execution before handlers can spawn/control a+ // delegate; publishing a schema never grants delegation permission.const subagentTools =- this.mode === "agent" && this.subagents.length+ this.subagents.length? [this.buildSubagentTool(),this.buildSubagentWaitTool(),@@ -3499,7 +3504,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theprivate rebuildToolCatalog(): void {const catalog = new Map<string, AgentTool>();for (const tool of this.buildToolDefinitions()) {- if (!this.isToolAllowedInMode(tool.name)) continue;+ if (!this.isToolAllowedInMode(tool.name) && !retainModeToolDeclaration(tool.name)) continue;// The execution mode is decided here, in one place, so no tool can grow// an accidental parallel batch: everything is sequential except `Task`.// pi runs a whole batch sequentially when it holds one sequential tool,@@ -3509,11 +3514,14 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// same declaration (#864).catalog.set(tool.name,- withExplicitRequired({- ...tool,- executionMode:- tool.name === SUBAGENT_TOOL_NAME ? "parallel" : "sequential",- }),+ withModeExecutionGuard(+ withExplicitRequired({+ ...tool,+ executionMode:+ tool.name === SUBAGENT_TOOL_NAME ? "parallel" : "sequential",+ }),+ () => this.isToolAllowedInMode(tool.name) ? undefined : modeToolDenial(tool.name, this.mode),+ ),);}this.toolCatalog = catalog;@@ -3568,6 +3576,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theprivate isCoreTool(name: string): boolean {return (name === CONTEXT_COMPACTION_TOOL_NAME ||+ retainModeToolDeclaration(name) ||MODE_TRANSITION_TOOL_NAMES.has(name) ||// The whole delegation lifecycle stays in the core set rather than the// on-demand catalog: a capability the model has to go looking for is one