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): keep Flash tool declarations stable across searches
zszz3907594acb860
diff --git a/docs/adr/chronological-system-transcript.md b/docs/adr/chronological-system-transcript.mdindex c1a484003..659ec00a2 100644--- a/docs/adr/chronological-system-transcript.md+++ b/docs/adr/chronological-system-transcript.md@@ -45,7 +45,7 @@ transport support from a models.dev metadata match or an account endpointoverride. Both Pi and models.dev metadata projections can carry that binding;unverified routes and generic records retain the conservative fallback.-The existing Pi 0.99.1 dependency patch adds the missing mid-conversation system+The Pi 1.0.0 dependency patch adds the missing mid-conversation systemcapability to its `deepseek-flash` catalog entry. Authorized official-endpointexperiments confirmed both preserved cache reuse and effective updatedinstructions. Keep this correction in the single Pi catalog, not a parallel@@ -53,6 +53,43 @@ Desktop allowlist; remove the hunk when an upgraded Pi catalog carries it.The model/API/endpoint binding check still excludes aliases and relays. Nativetool-addition and tool-change flags are not enabled by this correction.+## Fixed declarations for the verified Flash route++For the exact official `deepseek-flash` / `openai-completions` binding with+verified chronological system support, declare the complete current tool catalog+in deterministic name order from the first request. ToolSearch changes execution+activation only. This is a Desktop declaration policy, not an additional Pi+transport capability or an endpoint switch. Other bindings keep on-demand+schema publication; native tool-state flags alone do not prove cache stability.++Keep activation separate from declarations in a versioned `tool_activation`+system section. The section records active deferred names and a SHA-256 identity+of the account, model, API, endpoint, declarations and deferred-name set. Updates+append after tool results and persist through the existing Host journal and+compaction checkpoint. Restoration never interprets the complete declaration+snapshot as permission to execute every tool. Successful ToolSearch results+newer than the saved activation section recover an interrupted activation.+Invalid, unknown-version or mismatched state grants no activation. Legacy+histories without this section retain their existing activation evidence rules.++Check activation before extension hooks or Host execution, then retain all+existing mode, approval and Host restrictions. A catalog/schema/mode/account or+route change starts a new declaration epoch and invalidates prior activation;+removed tools cannot be invoked. Temporary prompt replacement must preserve the+activation metadata. Current runtime activation remains authoritative between+prompts; declarations do not re-grant revoked activation.++DeepSeek limits a request to 128 functions. If the full catalog exceeds that+limit, or its estimated prompt/schema cost leaves less than the ordinary+retained-tail budget below the automatic compaction threshold, use the existing+on-demand path and log the fallback reason. Never truncate a catalog. Context+estimation charges the full declared catalog while fixed declarations are active.++The first request is larger. Short conversations may cost more overall even+when later cache-hit ratios improve. Acceptance compares cold and subsequent+uncached tokens and cumulative input cost across both short and longer synthetic+conversations; no universal savings or hit-rate guarantee is made.+## Alternatives and consequencesPrepending a reconstructed snapshot was rejected because it changes history ondiff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 08346ab68..15bcd08d4 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1393,10 +1393,10 @@ grammar and validated against another fails every call.### 7.1 Active tool context and on-demand loading (D185, ADR 0048)-The sidecar builds one complete tool registry, but it does not serialize every-registered schema into every provider request. Each new user prompt starts with-the mode's core set plus any deferred tools that can be restored from successful-activation evidence still present in the effective session context:+The sidecar builds one complete tool registry. By default, each provider request+declares the mode's core set plus activated deferred tools. The verified Flash+binding uses the fixed-declaration policy below, while preserving the same+execution activation rules:- Agent: `Read`, `Bash`, `Edit`, and `Write` (matching pi's coding-agent core)- Agent: `Skill` whenever the skill catalog is non-empty (D404, ADR 0230) — the@@ -1424,24 +1424,42 @@ The sidecar activates up to four matches, records their names in the canonicalschemas. Providers with native deferred-tool search receive the definitions atthat load point; other providers receive the active definitions normally.-At the start of each new user prompt, the sidecar clears the in-memory deferred-activation set and rebuilds it from the effective context. Recorded system-messages (including a compaction checkpoint) define the active baseline. Only-successful tool results after the latest declaration can add a new activation;-older results must not resurrect a removed tool. Histories without system records-continue to use successful results throughout their effective context.-`ToolSearch` results contribute their canonical `details.addedToolNames`.-For compatibility, historical `details.activated` and top-level-`addedToolNames` markers are also accepted. Successful results from deferred-tools contribute that tool's name. Only names still present in the current-mode's deferred catalog are restored. Failed rows, interrupted or-missing-result placeholders, and assistant/user prose never activate a tool.-The tool registry, host permission path, tool timeout, and workspace containment-rules remain unchanged. `ToolSearch` is local to the sidecar and does not cross-the host RPC boundary. Its activation marker is retained in the persisted tool-result, so a runtime restart or a new prompt can reuse an eligible capability-while that evidence remains in the effective context; a fresh search is still-required after the evidence is compacted away or otherwise absent.+Deferred activation is sticky for the live runtime. At restoration, recorded+system messages (including a compaction checkpoint) define the active baseline+for ordinary on-demand histories. Only successful results after the latest+system record can add activation; older results must not resurrect removed+tools. Legacy histories without system records use successful results throughout+their effective context. ToolSearch accepts canonical `details.addedToolNames`+and historical `details.activated` / top-level `addedToolNames`; successful+results from deferred tools also restore their names. Failed results,+missing-result placeholders and assistant/user prose never activate tools.+Only names in the current mode's deferred catalog are eligible.++For the exact official `deepseek-flash` Chat Completions binding with verified+mid-conversation system support, the runtime instead declares the complete+catalog in deterministic name order on the first request. ToolSearch changes+activation without changing the declared schemas. A visible schema does not+permit execution: inactive deferred calls are rejected before extension hooks+and the Host; activated calls still require the existing mode and Host checks.+ToolSearch remains local and never grants approval or bypasses permissions.++Fixed declarations persist separately from activation. A version-1+`tool_activation` section records active names and a fingerprint of the account,+model, API, endpoint, schema catalog and deferred set. Activation changes append+at the continuation boundary, and the existing system journal/checkpoint saves+both declarations and activation. Restore only validated activation for a+matching fingerprint, plus successful ToolSearch results newer than that state;+never activate tools merely because the full snapshot declared them. Malformed,+unknown-version and mismatched activation state fail closed. A catalog/schema,+mode, account, model or route change creates a new epoch and requires new+activation. Removal immediately removes the tool from executable registration.++If the full catalog exceeds 128 functions or its prompt/schema estimate cannot+leave the normal retained-tail budget below the compaction threshold, retain+on-demand declarations and emit a diagnostic explaining that ToolSearch cache+stability is not guaranteed. Do not truncate tools. Other models and unverified+routes retain the existing Pi projection. First-request schema overhead increases;+cache stability does not imply that short conversations become cheaper.For user-visible HTML deliverables, the default system prompt asks the agent toactivate `BrowserPreview` once after creating the page or making its firstdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 708281ee4..1407badc2 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -16318,3 +16318,30 @@ renderer's durable transcript reads. No real model or provider is contacted.same-model assistant reasoning remains separate from visible content. Adapterregressions also cover legacy identities and genuine account/model changes. Cachepercentages are observations, not deterministic pass thresholds.++### E2E-FIXED-TOOL-DECLARATIONS: Stable Flash schemas with independent activation++- Fixture: production AgentSidecar and isolated Host, official Pi Flash binding,+ and a child-process fetch boundary redirected to local HTTP/SSE. Credentials+ are dummy values and synthetic tools have no external side effects.+- Prompt, search Alpha, execute Alpha, search Beta and execute Beta. HTTP payload+ tests assert identical ordered `tools` and unchanged prior message prefixes.+ Directly calling a declared but inactive tool must fail before the Host.+- Restart both processes, then compact and restart again: Alpha stays activated,+ Beta remains inactive despite its declaration. Activate Beta, then remove it+ from the catalog and verify it cannot execute. New schema/route epochs must+ not restore old grants. Host rejection and Plan guards remain effective.+- Runtime contracts additionally cover legacy migration, interrupted activation,+ malformed metadata, temporary prompt replacement, deterministic catalog order,+ the 128-tool boundary and insufficient-context fallback.+- Automated: `node scripts/e2e-fixed-tool-declarations.mjs` with built+ shared/host-runtime/agent-runtime and `PI_DESKTOP_HOST_BIN` set to the candidate+ Host binary; `fixed-tool-runtime.test.ts` and `fixed-tool-declarations.test.ts`+ cover HTTP payload and policy contracts. Electron UI/outbox is outside this+ fixture's scope.+- Separately authorized official Flash experiments compare several independent+ on-demand/fixed sessions with the same synthetic catalog and call sequence.+ Record cold requests, both activations, follow-up cache hits/misses and+ cumulative input cost. Report the larger first request and possible short-chat+ cost increase, alongside any longer-conversation benefit. Offline test success+ alone is not evidence of provider cache behavior.diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 820a0d5b3..97ec5d4ab 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -978,15 +978,21 @@ sidecar 最多激活四个匹配项,并将名称写入 canonical模式。具有本机延迟工具搜索的提供商可在该负载点接收定义;其他提供商通常会收到活动定义。-每个新用户提示前都会清除延迟激活集,再从有效上下文重建。成功的-`ToolSearch` 结果读取 canonical `details.addedToolNames`;为兼容历史-数据,也接受 `details.activated` 和顶层 `addedToolNames`。成功的延迟-工具结果会贡献其工具名。仅恢复当前模式延迟目录中仍存在的名称;失败、-中断、缺少结果的占位行以及助手/用户文本不会激活工具。工具注册表、主机-权限路径、工具超时和工作区包含规则保持不变。`ToolSearch` 是 sidecar 的-本地工具,不跨越主机 RPC 边界。激活标记保留在持久化工具结果中,因此-只要证据仍在有效上下文,运行时重启或新提示都可以复用能力;证据被压缩-或消失后仍需重新搜索。+Deferred activation remains sticky within a live runtime. Restoration uses+successful activation evidence and the current catalog; old declarations do not+re-grant tools revoked from the live activation set. For official bound Flash,+full declarations and execution activation are independent: versioned+`tool_activation` sections carry the account/model/API/endpoint/catalog identity+and active names through restart and compaction. Only matching, valid state and+newer successful ToolSearch results restore activation; malformed or changed+epochs fail closed. Inactive declared tools are blocked before extension/Host+execution, and activation never bypasses mode or approval checks. The full+catalog is deterministic from the first request. More than 128 tools or an+insufficient context budget falls back to on-demand declarations with a+diagnostic, without truncation. Other bindings retain their existing projection.+Fixed declarations may increase total cost for short conversations. See the+English section 7.1 and the chronological-system-transcript ADR for the complete+contract.对于用户可见的 HTML 可交付成果,默认系统提示要求代理创建页面或创建第一个页面后激活 `BrowserPreview` 一次diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 4e8caff87..c48a69498 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -9219,3 +9219,30 @@ the latest destination. These assertions measure work counts, not device FPS.- **验收:** 缓存路径、迁移和清理单测通过;Windows task-candidate 验证应覆盖更新源传输、安装器交接和文件系统行为,且不连接真实发布源。- **里程碑:** M6+- **状态:** 单测和源码契约覆盖(`update-cache.test.mjs`、`auto-update.test.mjs`);仍需 Windows 安装器/E2E 验证。++### E2E-FIXED-TOOL-DECLARATIONS: Stable Flash schemas with independent activation++- Fixture: production AgentSidecar and isolated Host, official Pi Flash binding,+ and a child-process fetch boundary redirected to local HTTP/SSE. Credentials+ are dummy values and synthetic tools have no external side effects.+- Prompt, search Alpha, execute Alpha, search Beta and execute Beta. HTTP payload+ tests assert identical ordered `tools` and unchanged prior message prefixes.+ Directly calling a declared but inactive tool must fail before the Host.+- Restart both processes, then compact and restart again: Alpha stays activated,+ Beta remains inactive despite its declaration. Activate Beta, then remove it+ from the catalog and verify it cannot execute. New schema/route epochs must+ not restore old grants. Host rejection and Plan guards remain effective.+- Runtime contracts additionally cover legacy migration, interrupted activation,+ malformed metadata, temporary prompt replacement, deterministic catalog order,+ the 128-tool boundary and insufficient-context fallback.+- Automated: `node scripts/e2e-fixed-tool-declarations.mjs` with built+ shared/host-runtime/agent-runtime and `PI_DESKTOP_HOST_BIN` set to the candidate+ Host binary; `fixed-tool-runtime.test.ts` and `fixed-tool-declarations.test.ts`+ cover HTTP payload and policy contracts. Electron UI/outbox is outside this+ fixture's scope.+- Separately authorized official Flash experiments compare several independent+ on-demand/fixed sessions with the same synthetic catalog and call sequence.+ Record cold requests, both activations, follow-up cache hits/misses and+ cumulative input cost. Report the larger first request and possible short-chat+ cost increase, alongside any longer-conversation benefit. Offline test success+ alone is not evidence of provider cache behavior.diff --git a/packages/agent-runtime/src/fixed-tool-declarations.test.ts b/packages/agent-runtime/src/fixed-tool-declarations.test.tsnew file mode 100644index 000000000..8b54969b9--- /dev/null+++ b/packages/agent-runtime/src/fixed-tool-declarations.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import type { AgentTool } from "@earendil-works/pi-agent-core";+import { DEEPSEEK_MODELS } from "@earendil-works/pi-ai/providers/deepseek.models";+import { Type, type Api, type Model } from "@earendil-works/pi-ai";+import { toolDeclarationPolicy, toolActivationSection, restoredToolActivation, TOOL_ACTIVATION_SECTION } from "./fixed-tool-declarations.js";+import { replaceSystemPrompt, systemTranscriptCheckpoint } from "./system-transcript.js";++const model = Object.values(DEEPSEEK_MODELS).find((model) => model.id === "deepseek-flash")!;+const tool = (name: string): AgentTool => ({ name, label: name, description: "Fixture tool", parameters: Type.Object({}),+ execute: async () => ({ content: [{ type: "text", text: "Done" }], details: {} }) });+const deferred = new Set(["Alpha", "Beta"]);+const policy = (tools = [tool("Alpha"), tool("Beta")], overrides: Partial<Model<Api>> = {}, prompt = "") =>+ toolDeclarationPolicy({ ...model, ...overrides } as Model<Api>, tools, deferred, prompt, "fixture-account");++describe("fixed tool declaration policy", () => {+ it("has a deterministic declaration order and snapshot identity", () => {+ const first = policy();+ const second = policy([tool("Beta"), tool("Alpha")]);+ expect(second.key).toBe(first.key);+ expect(second.tools?.map((tool) => tool.name)).toEqual(["Alpha", "Beta"]);+ expect(policy([{ ...tool("Alpha"), parameters: Type.Object({ id: Type.String() }) }]).key).not.toBe(first.key);+ });+ it.each([+ { id: "deepseek-pro" }, { api: "openai-responses" }, { baseUrl: "https://relay.invalid" },+ { baseUrl: "https://api.deepseek.com/v1" }, { compat: { supportsMidConvoSystemMessages: false } },+ ] as Partial<Model<Api>>[])("does not enable unverified bindings: %j", (overrides) => {+ expect(policy(undefined, overrides).tools).toBeUndefined();+ expect(policy(undefined, overrides).fallback).toBeUndefined();+ });+ it("falls back without truncating catalogs beyond the provider's function limit", () => {+ expect(policy(Array.from({ length: 128 }, (_, index) => tool(`Tool${index}`))).tools).toHaveLength(128);+ expect(policy(Array.from({ length: 129 }, (_, index) => tool(`Tool${index}`)))).toMatchObject({ fallback: "tool-count" });+ });+ it("leaves room for retained conversation and output", () => {+ expect(policy([tool("Alpha")], { contextWindow: 32000, maxTokens: 4000 }, "x".repeat(80000)))+ .toMatchObject({ fallback: "context-budget" });+ });+ it("restores activation independently of full declarations, including compacted and transient prompts", () => {+ const current = policy();+ const messages = [{ role: "system" as const, content: "", timestamp: 1,+ toolsAdded: current.tools, sections: { runtime: "Rules", [TOOL_ACTIVATION_SECTION]: toolActivationSection(current.key, new Set(["Alpha"])) } }];+ const changed = replaceSystemPrompt(messages, "Temporary nudge");+ expect(restoredToolActivation(changed, current.key)?.active).toEqual(["Alpha"]);+ expect(restoredToolActivation([systemTranscriptCheckpoint(changed)!], current.key)?.active).toEqual(["Alpha"]);+ expect(restoredToolActivation(messages, "different-snapshot")?.active).toEqual([]);+ expect(restoredToolActivation([], current.key)).toBeUndefined();+ });+ it.each(["invalid JSON", '{"version":2}', null])("fails closed on invalid activation metadata: %s", (value) => {+ expect(restoredToolActivation([{ role: "system", content: "", timestamp: 1,+ sections: { [TOOL_ACTIVATION_SECTION]: value } }], policy().key)?.active).toEqual([]);+ });+});diff --git a/packages/agent-runtime/src/fixed-tool-declarations.ts b/packages/agent-runtime/src/fixed-tool-declarations.tsnew file mode 100644index 000000000..721f39663--- /dev/null+++ b/packages/agent-runtime/src/fixed-tool-declarations.ts@@ -0,0 +1,69 @@+import { createHash } from "node:crypto";+import type { AgentMessage, AgentTool } from "@earendil-works/pi-agent-core";+import { getCurrentSystemMessage, toToolDeclaration, Type, type Api, type Model } from "@earendil-works/pi-ai";+import * as Value from "typebox/value";+import { contextBudgetLimitsFor, automaticCompactionThresholdFor } from "./context-budget.js";+import { estimateOutputCapInputTokens } from "./output-cap.js";++export const TOOL_ACTIVATION_SECTION = "tool_activation";+const activationSchema = Type.Object({+ version: Type.Literal(1), snapshot: Type.String({ pattern: "^[a-f0-9]{64}$" }),+ active: Type.Array(Type.String({ minLength: 1 }), { uniqueItems: true }),+}, { additionalProperties: false });++export type ToolDeclarationPolicy = {+ key: string;+ tools?: AgentTool[];+ fallback?: "tool-count" | "context-budget";+};++/** The verified Flash route has chronological system updates, but no tool deltas. */+export function toolDeclarationPolicy(+ model: Model<Api>, tools: readonly AgentTool[], deferred: ReadonlySet<string>, prompt: string, accountId: string,+): ToolDeclarationPolicy {+ const ordered = [...tools].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);+ const key = createHash("sha256").update(JSON.stringify({+ account: accountId, model: model.id, api: model.api, endpoint: model.baseUrl.replace(/\/+$/, ""),+ tools: ordered.map(toToolDeclaration), deferred: [...deferred].sort(),+ })).digest("hex");+ if (model.id !== "deepseek-flash" || model.api !== "openai-completions"+ || model.baseUrl.replace(/\/+$/, "") !== "https://api.deepseek.com"+ || !model.compat || !("supportsMidConvoSystemMessages" in model.compat)+ || model.compat.supportsMidConvoSystemMessages !== true) return { key };+ // DeepSeek Chat Completions permits at most 128 functions. Never truncate.+ if (ordered.length > 128) return { key, fallback: "tool-count" };+ const budget = contextBudgetLimitsFor(model);+ const tokens = estimateOutputCapInputTokens({ messages: [], systemPrompt: prompt, tools: ordered }, model);+ // Leave the normal retained-tail budget available to the conversation. A+ // fixed catalog must not make every fresh/compacted request overflow again.+ if (tokens >= automaticCompactionThresholdFor(budget) - budget.keepRecentTokens) {+ return { key, fallback: "context-budget" };+ }+ return { key, tools: ordered };+}++export function toolActivationSection(key: string, active: ReadonlySet<string>): string {+ return JSON.stringify({ version: 1, snapshot: key, active: [...active].sort() });+}++/** A declaration is not activation. Malformed/new-version state fails closed. */+export function restoredToolActivation(messages: readonly AgentMessage[], key: string): { active: string[]; replayFrom: number } | undefined {+ const section = getCurrentSystemMessage(messages)?.sections?.[TOOL_ACTIVATION_SECTION];+ const closed = { active: [], replayFrom: messages.length };+ if (section == null) return messages.some((message) => message.role === "system"+ && TOOL_ACTIVATION_SECTION in (message.sections ?? {})) ? closed : undefined;+ try {+ const parsed: unknown = JSON.parse(section);+ if (!Value.Check(activationSchema, parsed) || parsed.snapshot !== key) return closed;+ const lastState = messages.map((message) => message.role === "system"+ && TOOL_ACTIVATION_SECTION in (message.sections ?? {})).lastIndexOf(true);+ return { active: parsed.active, replayFrom: lastState + 1 };+ } catch { return closed; }+}++/** Activation is appended after the result, never inserted into old instructions. */+export function syncToolActivation(messages: AgentMessage[], section: string): AgentMessage[] {+ if (getCurrentSystemMessage(messages)?.sections?.[TOOL_ACTIVATION_SECTION] === section) return messages;+ const timestamp = messages.reduce((latest, message) => Math.max(latest, message.timestamp + 1), Date.now());+ return [...messages, { role: "system", content: "", timestamp, sections: { [TOOL_ACTIVATION_SECTION]: section } }];+}diff --git a/packages/agent-runtime/src/fixed-tool-runtime.test.ts b/packages/agent-runtime/src/fixed-tool-runtime.test.tsnew file mode 100644index 000000000..2c86736ce--- /dev/null+++ b/packages/agent-runtime/src/fixed-tool-runtime.test.ts@@ -0,0 +1,216 @@+import { randomUUID } from "node:crypto";+import { createServer } from "node:http";+import { afterEach, describe, expect, it, vi } from "vitest";+import { DEEPSEEK_MODELS } from "@earendil-works/pi-ai/providers/deepseek.models";+import { systemTranscriptCheckpoint } from "./system-transcript.js";+import { readSystemMessage } from "./system-transcript-journal.js";+import type { UiMessage } from "@pi-desktop/shared";+import { modelConfigFromPi } from "./model-capabilities.js";+import { DesktopAgentRuntime, type PluginToolDef, type RuntimeProviderConfig } from "./runtime.js";++function flashProvider(): RuntimeProviderConfig {+ const model = Object.values(DEEPSEEK_MODELS).find((model) => model.id === "deepseek-flash")!;+ return { id: "flash-fixture", name: "Flash", modelId: model.id, baseUrl: model.baseUrl,+ apiKey: "fixture", authKind: "api_key", supportsReasoning: false, supportedThinkingLevels: ["off"],+ modelConfig: modelConfigFromPi(model) };+}+const pluginTools: PluginToolDef[] = ["plugin_alpha", "plugin_beta"].map((name) => ({+ name, description: `${name} synthetic probe`, parameters: { type: "object", properties: {}, required: [] }, risk: "low",+}));+type Payload = { tools: { function: { name: string } }[]; messages: { role: string; content?: unknown }[] };+type Call = { name: string; args?: Record<string, unknown> };+async function wireFixture(calls: Call[]) {+ const requests: Payload[] = [];+ const fetch = globalThis.fetch;+ const server = createServer(async (req, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ requests.push(JSON.parse(Buffer.concat(chunks).toString()));+ const call = calls.shift();+ const delta = call ? { role: "assistant", tool_calls: [{ index: 0, id: randomUUID(),+ type: "function", function: { name: call.name, arguments: JSON.stringify(call.args ?? {}) } }] }+ : { role: "assistant", content: "Done." };+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.end(`data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason: call ? "tool_calls" : "stop" }] })}\n\ndata: [DONE]\n\n`);+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("Missing HTTP address");+ vi.stubGlobal("fetch", ((_url, init) => fetch(`http://127.0.0.1:${address.port}`, init)) satisfies typeof fetch);+ return { requests, close: async () => {+ vi.unstubAllGlobals();+ await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));+ } };+}+function runtimeFixture(history: UiMessage[] = [], tools = pluginTools, provider = flashProvider(), denied = false) {+ const rows = structuredClone(history);+ const executed: string[] = [];+ const errors: unknown[] = [];+ const runtime = new DesktopAgentRuntime({+ sessionId: "fixed-tools", mode: "agent", provider, thinkingLevel: "off", history: rows, pluginTools: tools,+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ host: { call: async <T>(method: string, params?: unknown): Promise<T> => {+ if (method === "session.appendMessage") rows.push((params as { message: UiMessage }).message);+ else if (method === "tools.execute") {+ executed.push((params as { toolName: string }).toolName);+ return denied ? { ok: false, denied: true, content: "Permission denied" } as T+ : { ok: true, content: "Synthetic success" } as T;+ } else throw new Error(`Unexpected host method: ${method}`);+ return undefined as T;+ } },+ onEvent: ({ event }) => {+ if (event.type === "error") errors.push(event.error);+ if (event.type === "tool_start") rows.push({ id: event.toolCallId, role: "tool", content: "",+ toolCallId: event.toolCallId, toolName: event.toolName, toolArgs: event.args, createdAt: new Date().toISOString() });+ if (event.type === "tool_end") {+ const row = rows.find((row) => row.id === event.toolCallId)!;+ row.toolResult = event.result; row.isError = event.isError; row.toolStatus = event.isError ? "error" : "success";+ }+ if (event.type === "message_end") {+ const index = rows.findIndex((row) => row.id === event.message.id);+ if (index < 0) rows.push(event.message); else rows[index] = event.message;+ }+ },+ });+ return { runtime, rows, executed, errors, prompt: async (id = "user-1") => {+ rows.push({ id, role: "user", content: "Run the synthetic probes", createdAt: new Date().toISOString() });+ await runtime.prompt("Run the synthetic probes", id, `turn-${id}`);+ } };+}+afterEach(() => vi.unstubAllGlobals());+describe("fixed Flash declarations through runtime and HTTP/SSE", () => {+ it("rejects a declared but inactive tool without invoking Host", async () => {+ const wire = await wireFixture([{ name: "plugin_beta" }]);+ const f = runtimeFixture();+ try {+ await f.prompt();+ expect(f.errors).toEqual([]);+ expect(f.executed).toEqual([]);+ expect(f.rows.find((row) => row.toolName === "plugin_beta")).toMatchObject({ isError: true });+ expect(JSON.stringify(wire.requests[1].messages)).toContain("Call ToolSearch to activate plugin_beta");+ expect(wire.requests[1].tools).toEqual(wire.requests[0].tools);+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it.each([false, true])("restores only activated tools after restart (checkpoint=%s)", async (checkpoint) => {+ const wire = await wireFixture([{ name: "ToolSearch", args: { query: "plugin_alpha" } }]);+ const f = runtimeFixture();+ let history: UiMessage[];+ let declared: Payload["tools"];+ try {+ await f.prompt();+ expect(f.errors).toEqual([]);+ declared = wire.requests.at(-1)!.tools;+ history = structuredClone(f.rows);+ if (checkpoint) {+ const system = systemTranscriptCheckpoint(history.filter((row) => row.modelSystem)+ .map((row) => readSystemMessage(row.modelSystem!.messageJson)))!;+ history = [{ id: "checkpoint", role: "system", content: "", createdAt: new Date().toISOString(),+ modelSystem: { version: 1, messageJson: JSON.stringify(system) } }];+ }+ } finally { await f.runtime.dispose(); await wire.close(); }+ const resumed = await wireFixture([{ name: "plugin_alpha" }, { name: "plugin_beta" }]);+ const restored = runtimeFixture(history!);+ try {+ await restored.prompt("restored-user");+ expect(restored.errors).toEqual([]);+ expect(restored.executed).toEqual(["plugin_alpha"]);+ expect(resumed.requests[0].tools).toEqual(declared!);+ expect([...restored.rows].reverse().find((row) => row.toolName === "plugin_beta")).toMatchObject({ isError: true });+ } finally { await restored.runtime.dispose(); await resumed.close(); }+ });++ it.each(["schema", "removed", "route"])("does not revive activation after a %s change", async (change) => {+ const wire = await wireFixture([{ name: "ToolSearch", args: { query: "plugin_alpha" } }]);+ const f = runtimeFixture();+ let history: UiMessage[];+ try { await f.prompt(); history = structuredClone(f.rows); }+ finally { await f.runtime.dispose(); await wire.close(); }+ const tools = change === "removed" ? pluginTools.slice(1) : change === "schema"+ ? [{ ...pluginTools[0], description: "Changed schema epoch" }, pluginTools[1]] : pluginTools;+ const provider = change === "route" ? { ...flashProvider(), baseUrl: "https://relay.invalid/v1" } : flashProvider();+ const resumed = await wireFixture([{ name: "plugin_alpha" }]);+ const restored = runtimeFixture(history!, tools, provider);+ try {+ await restored.prompt("changed-user");+ expect(restored.errors).toEqual([]);+ expect(restored.executed).toEqual([]);+ if (change === "removed") expect(resumed.requests[0].tools.map((tool) => tool.function.name)).not.toContain("plugin_alpha");+ } finally { await restored.runtime.dispose(); await resumed.close(); }+ });++ it("still requires Host approval after ToolSearch activation", async () => {+ const wire = await wireFixture([{ name: "ToolSearch", args: { query: "plugin_alpha" } }, { name: "plugin_alpha" }]);+ const f = runtimeFixture([], pluginTools, flashProvider(), true);+ try {+ await f.prompt();+ expect(f.executed).toEqual(["plugin_alpha"]);+ expect(f.rows.find((row) => row.toolName === "plugin_alpha")).toMatchObject({ isError: true });+ expect(JSON.stringify(wire.requests.at(-1)?.messages)).toContain("Permission denied");+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it("replays a successful activation if stopped before its next declaration checkpoint", async () => {+ const wire = await wireFixture([{ name: "ToolSearch", args: { query: "plugin_alpha" } }]);+ const f = runtimeFixture();+ let history: UiMessage[];+ try {+ await f.prompt();+ const first = f.rows.find((row) => row.modelSystem)!;+ history = structuredClone(f.rows.filter((row) => !row.modelSystem || row === first));+ } finally { await f.runtime.dispose(); await wire.close(); }+ const resumed = await wireFixture([{ name: "plugin_alpha" }, { name: "plugin_beta" }]);+ const restored = runtimeFixture(history!);+ try {+ await restored.prompt("resumed-user");+ expect(restored.executed).toEqual(["plugin_alpha"]);+ } finally { await restored.runtime.dispose(); await resumed.close(); }+ });++ it("migrates legacy on-demand history without granting the rest of the catalog", async () => {+ const wire = await wireFixture([{ name: "ToolSearch", args: { query: "plugin_alpha" } }]);+ const f = runtimeFixture([], pluginTools, { ...flashProvider(), baseUrl: "https://relay.invalid" });+ let history: UiMessage[];+ try { await f.prompt(); history = structuredClone(f.rows); }+ finally { await f.runtime.dispose(); await wire.close(); }+ const resumed = await wireFixture([{ name: "plugin_alpha" }, { name: "plugin_beta" }]);+ const restored = runtimeFixture(history!);+ try {+ await restored.prompt("migrated-user");+ expect(restored.executed).toEqual(["plugin_alpha"]);+ expect(resumed.requests[0].tools.map((tool) => tool.function.name)).toEqual(expect.arrayContaining(["plugin_alpha", "plugin_beta"]));+ } finally { await restored.runtime.dispose(); await resumed.close(); }+ });++ it("retains the Plan execution guard for predeclared tools", async () => {+ const wire = await wireFixture([{ name: "Write", args: { path: "fixture", content: "denied" } }]);+ const f = runtimeFixture();+ try {+ f.runtime.setMode("plan");+ await f.prompt();+ expect(f.errors).toEqual([]);+ expect(f.executed).toEqual([]);+ expect(f.rows.find((row) => row.toolName === "Write")).toMatchObject({ isError: true });+ } finally { await f.runtime.dispose(); await wire.close(); }+ });++ it("keeps the complete request prefix while searching and executing two different tools", async () => {+ const wire = await wireFixture([+ { name: "ToolSearch", args: { query: "plugin_alpha" } }, { name: "plugin_alpha" },+ { name: "ToolSearch", args: { query: "plugin_beta" } }, { name: "plugin_beta" },+ ]);+ const f = runtimeFixture();+ try {+ await f.prompt();+ expect(f.errors).toEqual([]);+ expect(f.executed).toEqual(["plugin_alpha", "plugin_beta"]);+ expect(wire.requests).toHaveLength(5);+ expect(wire.requests[0].tools.map((tool) => tool.function.name)).toEqual(expect.arrayContaining(["plugin_alpha", "plugin_beta"]));+ for (let index = 1; index < wire.requests.length; index++) {+ expect(wire.requests[index].tools).toEqual(wire.requests[0].tools);+ const previous = wire.requests[index - 1].messages;+ expect(wire.requests[index].messages.slice(0, previous.length)).toEqual(previous);+ }+ } finally { await f.runtime.dispose(); await wire.close(); }+ });+});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex aa1379404..fbb689fd4 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1,3 +1,4 @@+import { TOOL_ACTIVATION_SECTION, toolDeclarationPolicy, toolActivationSection, restoredToolActivation, syncToolActivation, type ToolDeclarationPolicy } from "./fixed-tool-declarations.js";import { orderSystemRows, SystemTranscriptJournal } from "./system-transcript-journal.js";import { accountModelStream } from "./request-usage.js";import { modeToolDenial, retainModeToolDeclaration, withModeExecutionGuard } from "./mode-tool-access.js";@@ -1691,8 +1692,11 @@ export class DesktopAgentRuntime {private toolCatalog = new Map<string, AgentTool>();/** Tools intentionally omitted from the initial provider request. */private deferredToolNames = new Set<string>();- /** Deferred tools loaded for the current user prompt. */+ /** Deferred tools activated for this runtime and declaration epoch. */private activeDeferredToolNames = new Set<string>();+ private declarationPolicy?: ToolDeclarationPolicy;+ private trackToolActivation = false;+ private activationHydrated = false;private scratchDir?: string;private projectPath?: string;private commandShell: CommandShellOption;@@ -1880,7 +1884,6 @@ export class DesktopAgentRuntime {this.rebuildToolCatalog();const model = buildProviderModel(this.provider);this.model = model;- const tools = this.activeTools();const models = createProviderModels(this.provider, model);this.models = models;const runtimeApiKey = providerRequestKey(this.provider);@@ -1934,6 +1937,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the).trim(),...defaultSystemPromptParts.slice(1),].join("\n\n");+ this.refreshToolDeclarationPolicy();+ this.restoreDeferredToolsFromContext();+ const tools = this.declaredTools();this.agent = new Agent({streamFn: (m, context, options) => {this.setAgentActivity({ phase: "waiting-model", since: Date.now() });@@ -2204,7 +2210,13 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}private setAgentTools(tools: AgentTool[]): void {- this.agent.state.tools = tools;+ this.agent.state.tools = this.declarationPolicy?.tools ?? tools;+ if (this.trackToolActivation && this.declarationPolicy) {+ const section = toolActivationSection(this.declarationPolicy.key, this.activeDeferredToolNames);+ this.composedSections = { ...this.composedSections, [TOOL_ACTIVATION_SECTION]: section };+ this.composedSystemPrompt = Object.values(this.composedSections).filter(Boolean).join("\n\n");+ this.agent.state.messages = syncToolActivation(this.agent.state.messages, section);+ }}private agentSystemPromptContent(): string {@@ -2225,6 +2237,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the: "";this.composedSections = {runtime: this.baseSystemPrompt,+ ...(this.trackToolActivation && this.declarationPolicy ? {+ [TOOL_ACTIVATION_SECTION]: toolActivationSection(this.declarationPolicy.key, this.activeDeferredToolNames),+ } : {}),...pluginSkillsPromptSections(this.pluginSkills),context: composeModeSystemPrompt(this.mode, [...(this.customSystemPrompt?.append ? [this.customSystemPrompt.append] : []),@@ -2385,6 +2400,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when theprivate async beforeToolCall(context: BeforeToolCallContext,): Promise<BeforeToolCallResult | undefined> {+ if (this.deferredToolNames.has(context.toolCall.name) && !this.activeDeferredToolNames.has(context.toolCall.name)) {+ return { block: true, reason: `Call ${TOOL_SEARCH_NAME} to activate ${context.toolCall.name} before using it. A tool declaration does not grant execution permission.` };+ }const toolCalls = (context.assistantMessage.content as Array<{ type?: string }>).filter((block) => block.type === "toolCall",);@@ -3612,9 +3630,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}/**- * Build the complete registry once, then expose only the core subset to the- * first provider request. This mirrors pi's active-tool model while keeping- * the host tool implementation and permission path unchanged.+ * Build the complete registry before selecting fixed or on-demand+ * declarations. Execution activation and Host permissions remain separate+ * from the provider-visible schemas.*/private rebuildToolCatalog(): void {const catalog = new Map<string, AgentTool>();@@ -3659,6 +3677,25 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}),);}+ if (this.model) this.refreshToolDeclarationPolicy();+ }++ private refreshToolDeclarationPolicy(): void {+ const previous = this.declarationPolicy;+ const policy = toolDeclarationPolicy(this.model, [...this.toolCatalog.values()], this.deferredToolNames, this.composeSystemPrompt(), this.provider.id);+ if (previous && previous.key !== policy.key && this.trackToolActivation) {+ this.activeDeferredToolNames.clear();+ this.activationHydrated = true;+ }+ this.declarationPolicy = policy;+ this.trackToolActivation ||= Boolean(policy.tools || policy.fallback);+ if (policy.fallback && (previous?.key !== policy.key || previous.fallback !== policy.fallback)) {+ process.stderr.write(`[agent-runtime] fixed tool declarations unavailable (${policy.fallback}); using on-demand declarations; ToolSearch cache stability is not guaranteed.\n`);+ }+ }++ private declaredTools(): AgentTool[] {+ return this.declarationPolicy?.tools ?? this.activeTools();}private isPlanSafePluginTool(name: string): boolean {@@ -3747,7 +3784,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}return ["# On-demand tools",- `The following capabilities are available on demand. Call ${TOOL_SEARCH_NAME} with an exact tool name or a short capability description before using one that is not in the current tool list.`,+ `The following capabilities are available on demand. Call ${TOOL_SEARCH_NAME} with an exact tool name or a short capability description before using an on-demand tool that has not been activated. A visible schema is not activation; the tool_activation section, when present, records active names.`,...lines,].join("\n");}@@ -3777,7 +3814,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thename: TOOL_SEARCH_NAME,label: "Tool Search",description:- "Find and activate an on-demand tool by exact name or capability. Use this before calling any tool listed under On-demand tools that is not already in the current tool list.",+ "Find and activate an on-demand tool by exact name or capability. Use this before calling an inactive tool listed under On-demand tools, even when its schema is already visible. Activation does not bypass approval or mode restrictions.",parameters: Type.Object({query: Type.String({description:@@ -5340,9 +5377,18 @@ Do not invent objections or turn speculative risks into blockers. Stop when the*/private restoreDeferredToolsFromContext(): void {if (this.deferredToolNames.size === 0) return;+ if (this.trackToolActivation && this.activationHydrated) return;const { messages } = this.liveSessionContext();- const lastSystem = messages.map((message) => message.role).lastIndexOf("system");- if (lastSystem >= 0) {+ const restored = this.declarationPolicy && restoredToolActivation(messages, this.declarationPolicy.key);+ if (restored !== undefined) {+ this.trackToolActivation = true;+ for (const name of restored.active) {+ if (this.deferredToolNames.has(name)) this.activeDeferredToolNames.add(name);+ }+ }+ this.activationHydrated = true;+ const lastSystem = restored ? restored.replayFrom - 1 : messages.map((message) => message.role).lastIndexOf("system");+ if (!restored && lastSystem >= 0) {for (const tool of getCurrentTools(messages)) {if (this.deferredToolNames.has(tool.name)) this.activeDeferredToolNames.add(tool.name);}@@ -5350,6 +5396,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// Legacy histories lack declarations. For current histories, only results// after the last declaration can represent an activation not yet declared.for (const message of messages.slice(lastSystem + 1)) {+ if (restored && (message.role !== "toolResult" || message.toolName !== TOOL_SEARCH_NAME)) continue;if (message.role !== "toolResult" || message.isError) continue;if (isMissingToolResultPlaceholder(message.content)) continue;const names =@@ -6127,7 +6174,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the...(typeof this.agent.state.systemPrompt === "string"? { systemPrompt: this.agent.state.systemPrompt }: {}),- tools: this.activeTools(),+ tools: this.declaredTools(),},this.model,);@@ -6300,7 +6347,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theprivate rebuiltAgentContext(): AgentContext {const messages = this.liveSessionContext().messages;- const tools = this.activeTools();+ const tools = this.declaredTools();this.setAgentMessages(messages);this.setAgentTools(tools);return {diff --git a/packages/agent-runtime/src/system-transcript.ts b/packages/agent-runtime/src/system-transcript.tsindex f3e347033..9ba1167b2 100644--- a/packages/agent-runtime/src/system-transcript.ts+++ b/packages/agent-runtime/src/system-transcript.ts@@ -1,3 +1,4 @@+import { TOOL_ACTIVATION_SECTION } from "./fixed-tool-declarations.js";import type { AgentMessage } from "@earendil-works/pi-agent-core";import {contentText,@@ -35,7 +36,7 @@ function currentSystemMessage(messages: readonly AgentMessage[]): SystemMessageexport const CONTEXT_BUDGET_SECTION = "context_budget";function desktopSectionNames(sections: Record<string, unknown>): string[] {- return ["runtime", "skills", ...Object.keys(sections)+ return ["runtime", TOOL_ACTIVATION_SECTION, "skills", ...Object.keys(sections).filter((name) => name.startsWith(SKILL_SECTION_PREFIX)).sort((a, b) => a.localeCompare(b)), "context"];}@@ -83,7 +84,8 @@ export function initialSystemTranscript(export function replaceSystemPrompt(messages: AgentMessage[], prompt: string): AgentMessage[] {if (prompt === getCurrentSystemPrompt(messages) || prompt === systemPromptContent(messages)) return messages;- return syncSystemSections(messages, { runtime: prompt });+ const activation = getCurrentSystemMessage(messages)?.sections?.[TOOL_ACTIVATION_SECTION];+ return syncSystemSections(messages, { runtime: prompt, ...(activation ? { [TOOL_ACTIVATION_SECTION]: activation } : {}) });}export function rebuildSystemTranscript(diff --git a/scripts/e2e-fixed-tool-declarations.mjs b/scripts/e2e-fixed-tool-declarations.mjsnew file mode 100644index 000000000..c44d32ef5--- /dev/null+++ b/scripts/e2e-fixed-tool-declarations.mjs@@ -0,0 +1,170 @@+#!/usr/bin/env node+/** Production sidecar transport + isolated Host + local SSE provider.+ * Message persistence is harness-owned; Electron's UI/outbox is not exercised.+ */+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { createServer } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { AgentSidecar } from "../packages/host-runtime/dist/agent-sidecar.js";+import { DEEPSEEK_MODELS } from "../packages/agent-runtime/node_modules/@earendil-works/pi-ai/dist/providers/deepseek.models.js";+import { modelConfigFromPi } from "../packages/agent-runtime/dist/model-capabilities.js";+import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";+import { withScenario } from "./e2e/fixture.mjs";+import { resolveHostBinary } from "./e2e/host.mjs";+import { createSession } from "./e2e/session.mjs";++const root = await mkdtemp(join(tmpdir(), "pi-system-state-e2e-"));+const requests = [];+const responses = [];+const server = createServer(async (req, res) => {+ let body = "";+ for await (const chunk of req) body += chunk;+ requests.push(JSON.parse(body));+ const tool = responses.shift();+ const delta = tool ? { role: "assistant", tool_calls: [{ index: 0, id: randomUUID(), type: "function",+ function: { name: tool.name, arguments: JSON.stringify(tool.args) } }] }+ : { role: "assistant", content: "The fixture completed." };+ res.writeHead(200, { "content-type": "text/event-stream" });+ for (const [value, finish] of [[delta, null], [{}, tool ? "tool_calls" : "stop"]]) {+ res.write(`data: ${JSON.stringify({ id: "fixture", model: "fixture", choices: [{ index: 0, delta: value, finish_reason: finish }] })}\n\n`);+ }+ res.end("data: [DONE]\n\n");+});+await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;+const model = Object.values(DEEPSEEK_MODELS).find((model) => model.id === "deepseek-flash");+const provider = { id: "fixture", name: "Flash fixture", modelId: model.id, baseUrl: model.baseUrl,+ modelConfig: modelConfigFromPi(model), apiKey: "fixture", authKind: "api_key", supportsReasoning: false, supportedThinkingLevels: ["off"] };+const fetchHook = join(root, "fixture-fetch.mjs");+await writeFile(fetchHook, `const fetch = globalThis.fetch; globalThis.fetch = (url, init) => {+ if (String(url) !== "https://api.deepseek.com/chat/completions") throw new Error("Unexpected fixture endpoint");+ return fetch(${JSON.stringify(baseUrl)}, init);+};`);+let pluginTools = ["plugin_alpha", "plugin_beta"].map((name) => ({ name,+ description: "Synthetic read-only marker", parameters: { type: "object", properties: {}, required: [] }, risk: "low" }));+try {+ await withScenario("E2E-fixed-tool-declarations", async ({ host, workspace }) => {+ const session = await createSession(host, workspace, "System state fixture");+ let writes = Promise.resolve();+ let writeError;+ let stderr = "";+ const turns = new Map();+ const executedTools = [];+ const toolRows = new Map();+ const persist = (message, turnId) => {+ writes = writes.then(() => host.call("session.appendMessage", { sessionId: session.id, turnId, message }))+ .catch((error) => { writeError ??= error; });+ };+ const startSidecar = () => {+ const sidecar = new AgentSidecar({+ launch: { command: process.execPath,+ args: [fileURLToPath(new URL("../packages/agent-runtime/dist/sidecar.js", import.meta.url))],+ cwd: workspace,+ env: { ...process.env, NODE_OPTIONS: `--import=${fetchHook}`, PI_DESKTOP_PLAN_UI_PROBE: "1", PI_DESKTOP_COMPACTION_STRATEGY: "fresh_window" },+ },+ onStderr: (chunk) => { stderr += chunk; },+ });+ sidecar.setHost({ call: host.call.bind(host), onNotification: () => () => {}, onExit: () => () => {} });+ for (const name of ["plugin_alpha", "plugin_beta"]) sidecar.setLocalTool(name, async () => {+ executedTools.push(name);+ return { ok: true, content: `${name} synthetic result` };+ });+ sidecar.onNotification((method, envelope) => {+ if (method !== "agent.event") return;+ const { event, turnId } = envelope;+ const turn = turns.get(turnId);+ if (event.type === "error") turn?.errors.push(event.error);+ if (event.type === "message_end") persist(event.message, turnId);+ if (event.type === "tool_start") toolRows.set(event.toolCallId, {+ id: event.toolCallId, role: "tool", content: "", toolCallId: event.toolCallId,+ toolName: event.toolName, toolArgs: event.args, createdAt: new Date().toISOString(),+ });+ if (event.type === "tool_end") {+ turn?.toolResults.push(event);+ persist({ ...toolRows.get(event.toolCallId), toolResult: event.result, isError: event.isError,+ toolStatus: event.isError ? "error" : "success" }, turnId);+ }+ if (event.type === "agent_end") turn?.resolve();+ });+ return sidecar;+ };+ let sidecar = startSidecar();+ const params = () => ({ sessionId: session.id, mode: "agent", provider, thinkingLevel: "off", pluginTools,+ projectPath: workspace,+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ });+ const prompt = async (id, expectedErrors = 0) => {+ const { turnId } = await host.call("session.beginTurn", { sessionId: session.id });+ await host.call("session.appendMessage", { sessionId: session.id, turnId,+ message: { id, role: "user", content: "Continue", createdAt: new Date().toISOString() } });+ let timer;+ const turn = { errors: [], toolResults: [] };+ const ended = new Promise((resolve, reject) => {+ turn.resolve = resolve;+ timer = setTimeout(() => reject(new Error(`Turn timed out: ${JSON.stringify(turn.errors)}\n${stderr}`)), 20_000);+ });+ turns.set(turnId, turn);+ try {+ await sidecar.call("agent.prompt", { ...params(), turnId, userMessageId: id, content: "Continue" });+ await ended;+ await writes;+ if (writeError) throw writeError;+ assert.deepEqual(turn.errors, [], JSON.stringify(turn.errors));+ assert.equal(turn.toolResults.filter((event) => event.isError).length, expectedErrors, JSON.stringify(turn.toolResults));+ await host.call("session.endTurn", { turnId, status: "completed", createNotification: false });+ return turn;+ } finally { clearTimeout(timer); turns.delete(turnId); }+ };+ const detail = async () => (await host.call("session.get", { id: session.id })).session;+ try {+ responses.push({ name: "ToolSearch", args: { query: "plugin_alpha" } }, { name: "plugin_alpha", args: {} });+ await prompt("user-1");+ const declared = requests[0].tools;+ assert(declared.some((tool) => tool.function.name === "plugin_beta"));+ for (let index = 1; index < requests.length; index++) {+ assert.deepEqual(requests[index].tools, declared);+ assert.deepEqual(requests[index].messages.slice(0, requests[index - 1].messages.length), requests[index - 1].messages);+ }+ assert.deepEqual(executedTools, ["plugin_alpha"]);+ const states = (await detail()).messages.filter((row) => row.modelSystem);+ assert(states.length >= 2);+ console.log("PASS: fixed declarations survive ToolSearch through production sidecar and HTTP/SSE");+ await sidecar.dispose();+ await host.stop(); await host.start(PROTOCOL_VERSION);+ assert.deepEqual((await detail()).messages.filter((row) => row.modelSystem), states);+ sidecar = startSidecar();+ responses.push({ name: "plugin_alpha", args: {} }, { name: "plugin_beta", args: {} });+ await prompt("user-2", 1);+ assert.deepEqual(executedTools, ["plugin_alpha", "plugin_alpha"]);+ assert.deepEqual(requests.at(-1).tools, declared);+ console.log("PASS: Host and sidecar restart restore Alpha activation without activating declared Beta");+ await sidecar.call("agent.compact", params());+ const checkpoint = JSON.parse((await detail()).compaction.details.systemMessageJson);+ assert.deepEqual(JSON.parse(checkpoint.sections.tool_activation).active, ["plugin_alpha"]);+ await sidecar.dispose(); sidecar = startSidecar();+ responses.push({ name: "plugin_alpha", args: {} }, { name: "plugin_beta", args: {} });+ await prompt("user-3", 1);+ assert.deepEqual(executedTools, ["plugin_alpha", "plugin_alpha", "plugin_alpha"]);+ assert.deepEqual(requests.at(-1).tools, declared);+ console.log("PASS: compaction and process restart preserve declarations and activation separately");+ responses.push({ name: "ToolSearch", args: { query: "plugin_beta" } }, { name: "plugin_beta", args: {} });+ await prompt("user-4");+ assert.equal(executedTools.at(-1), "plugin_beta");+ assert.deepEqual(requests.at(-1).tools, declared);+ pluginTools = pluginTools.slice(0, 1);+ responses.push({ name: "plugin_beta", args: {} });+ await prompt("user-5", 1);+ assert.equal(executedTools.length, 4);+ assert(!requests.at(-1).tools.some((tool) => tool.function.name === "plugin_beta"));+ console.log("PASS: changed catalog revokes Beta execution and creates a new declaration epoch");+ } finally { await sidecar.dispose(); await writes; }+ }, resolveHostBinary(), root, PROTOCOL_VERSION);+} finally {+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ await rm(root, { recursive: true, force: true });+}