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(agent-runtime): restore deferred ToolSearch activations
yg22244d9f2921a31b
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex e1be5daf1..064f7a4fc 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1332,16 +1332,18 @@ one-line descriptions appear in an `# On-demand tools` catalog; parameterschemas do not. The catalog is bounded so a plugin with many tools cannotrecreate the original prompt bloat.The model calls `ToolSearch` with an exact name or a short capability query.-The sidecar activates up to four matches, returns their names through-pi-agent-core's `addedToolNames`, and rebuilds the next-turn context with those+The sidecar activates up to four matches, records their names in the canonical+`details.addedToolNames` field, and rebuilds the next-turn context with thoseschemas. 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 deferredactivation set and rebuilds it from the effective context. Successful-`ToolSearch` results contribute their `addedToolNames`; 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+`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 ormissing-result placeholders, and assistant/user prose never activate a tool.The tool registry, host permission path, tool timeout, and workspace containmentrules remain unchanged. `ToolSearch` is local to the sidecar and does not crossdiff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 91c7c7b33..924aa21cf 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -63,10 +63,12 @@ descriptions. The model calls the local `ToolSearch` tool with an exact name orcapability query; the matching schemas become available on the next model turn.At the beginning of every new user prompt, the sidecar clears the in-memorydeferred set and restores only successful activation evidence from the effective-session context: `addedToolNames` on successful `ToolSearch` results and the-names of successful deferred-tool results. Failed rows, interrupted or missing-result placeholders, and assistant/user prose are ignored. Restored names must-still be in the current mode's deferred catalog. The host permission,+session context: canonical `details.addedToolNames` on successful `ToolSearch`+results and the names of successful deferred-tool results. For compatibility,+historical `details.activated` and top-level `addedToolNames` markers are+accepted as well. Failed rows, interrupted or missing-result placeholders, and+assistant/user prose are ignored. Restored names must still be in the current+mode's deferred catalog. The host permission,workspace/scratch containment, timeout, and audit rules do not change when atool is loaded. `ToolSearch` itself never executes a workspace operation andnever bypasses host-core policy.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 3b35677a6..6a5c57cdb 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1075,8 +1075,11 @@ identify the platform validation still needed.through live reload while the page is refined. Generated, test-only, andnon-visual HTML files do not trigger a preview call. At the second prompt,successful activation markers still in the effective context may restore the- matching deferred schemas in the first request; failed, interrupted, and- missing-result rows do not. Catalog and mode changes also prevent restoration.+ matching deferred schemas in the first request, including tools that were+ activated but not yet called. New results use `details.addedToolNames`; the+ legacy `details.activated` and top-level `addedToolNames` markers remain+ readable. Failed, interrupted, and missing-result rows do not restore tools.+ Catalog and mode changes also prevent restoration.No host permission or workspace escape is granted by restoration.- **Specs linked**: `03-runtime/02-agent-runtime.md` §7.1,`03-runtime/03-tools-and-permissions.md` §2.1, ADR 0048, ADR 0225,diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 47c8c740e..a9b1ccc20 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -960,18 +960,20 @@ sidecar 构建了一个完整的工具注册表,但它不会序列化每个工模式则不然。目录是有限的,因此具有许多工具的插件无法重新创建原来的提示膨胀。该模型使用确切的名称或简短的功能查询调用 `ToolSearch`。-sidecar 激活最多四场比赛,通过返回他们的名字-pi-agent-core 的 `addedToolNames`,并用这些重建下一轮上下文-模式。具有本机延迟工具搜索的提供商可在以下位置接收定义:-该负载点;其他提供商通常会收到活动定义。--延迟激活会在每个新用户提示之前重置,因此之前的任务-无法使不相关的第一个请求携带不断增长的工具集。工具-注册表、主机权限路径、工具超时和工作区包含规则-保持不变。 `ToolSearch` 是 sidecar 的本地变量,不跨越-主机 RPC 边界。其激活标记保留在持久化工具中-结果,尽管重新启动,恢复的转录仍然是提供商有效的-在重用延迟功能之前,运行时仍然需要重新搜索。+sidecar 最多激活四个匹配项,并将名称写入 canonical+`details.addedToolNames` 字段,再用这些名称重建下一轮上下文+模式。具有本机延迟工具搜索的提供商可在该负载点接收定义;其他+提供商通常会收到活动定义。++每个新用户提示前都会清除延迟激活集,再从有效上下文重建。成功的+`ToolSearch` 结果读取 canonical `details.addedToolNames`;为兼容历史+数据,也接受 `details.activated` 和顶层 `addedToolNames`。成功的延迟+工具结果会贡献其工具名。仅恢复当前模式延迟目录中仍存在的名称;失败、+中断、缺少结果的占位行以及助手/用户文本不会激活工具。工具注册表、主机+权限路径、工具超时和工作区包含规则保持不变。`ToolSearch` 是 sidecar 的+本地工具,不跨越主机 RPC 边界。激活标记保留在持久化工具结果中,因此+只要证据仍在有效上下文,运行时重启或新提示都可以复用能力;证据被压缩+或消失后仍需重新搜索。对于用户可见的 HTML 可交付成果,默认系统提示要求代理创建页面或创建第一个页面后激活 `BrowserPreview` 一次diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.mdindex b141878b3..b0a36d87a 100644--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md@@ -63,10 +63,14 @@ Plan 和 Goal 保留其 read/inspection 核心。`Skill` 有意不作延迟:`/这些工具出现在有界的 `# On-demand tools` 目录中,具有紧凑的结构描述。该模型使用确切的名称调用本地 `ToolSearch` 工具或能力查询;匹配的模式在下一个模型回合中可用。-sidecar 在每个新用户提示开始时重置此延迟集。-主机权限、workspace/scratch 遏制、超时和审核规则-加载工具时不会改变。 `ToolSearch` 本身从不执行工作区-操作并且永远不会绕过 host-core 策略。+sidecar 在每个新用户提示开始时重置此延迟集,并从有效会话上下文中的+成功证据重建:成功 `ToolSearch` 结果使用 canonical+`details.addedToolNames`,成功的延迟工具结果使用其工具名。为兼容历史+数据,也接受 `details.activated` 和顶层 `addedToolNames`。失败、中断或+缺少结果的占位行以及助手/用户文本都会被忽略;恢复的名称必须仍在当前+模式的延迟目录中。主机权限、workspace/scratch 遏制、超时和审核规则+加载工具时不会改变。`ToolSearch` 本身从不执行工作区操作并且永远不会+绕过 host-core 策略。## 3. 常用工具约束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 ac4a34adc..897470d5d 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@@ -435,12 +435,14 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备下一个模型回合。对于用户可见的 HTML 可交付成果,`BrowserPreview` 是创建或第一次有意义的视觉编辑后调用一次,然后重复使用在页面优化时通过实时重新加载。已生成,仅供测试,并且- 非可视 HTML 文件不会触发预览调用。加载的集合不- 泄漏到下一个提示的第一个请求中。工具激活标记幸存- 在不授予主机权限或工作区逃逸的情况下重新加载脚本。+ 非可视 HTML 文件不会触发预览调用。第二个提示的第一个请求可以恢复+ 有效上下文中仍存在的成功激活标记,包括已激活但尚未调用的工具。新结果+ 使用 `details.addedToolNames`,历史 `details.activated` 和顶层+ `addedToolNames` 也可读取;失败、中断或缺少结果的行不会恢复工具。目录+ 或模式变化会阻止恢复,且恢复不会授予主机权限或工作区逃逸。- **链接规格**:`03-runtime/02-agent-runtime.md` §7.1,- `03-runtime/03-tools-and-permissions.md` §2.1、ADR 0048、- `08-meta/decisions-log.md` (D185)+ `03-runtime/03-tools-and-permissions.md` §2.1、ADR 0048、ADR 0225、+ `08-meta/decisions-log.md` (D185、D400)- **验收**:C(第一轮和流)+ E(工具执行)- **里程碑**:M5- **状态**:单位覆盖(`agent-runtime` 延迟工具测试);真人模特diff --git a/packages/agent-runtime/src/delegation-history.test.ts b/packages/agent-runtime/src/delegation-history.test.tsindex feaf544c9..edffe38d2 100644--- a/packages/agent-runtime/src/delegation-history.test.ts+++ b/packages/agent-runtime/src/delegation-history.test.ts@@ -321,6 +321,37 @@ describe("seedDelegateMessages", () => {});});+ it("keeps legacy ToolSearch activation markers in resumed history", () => {+ const rows: UiMessage[] = [+ delegateTool(+ "search-1",+ "ToolSearch",+ { query: "BrowserPreview" },+ {+ content: [{ type: "text", text: "Activated on-demand tools: BrowserPreview." }],+ addedToolNames: ["BrowserPreview", "BrowserPreview"],+ details: { query: "BrowserPreview", activated: ["BrowserPreview"] },+ },+ "call-1",+ ),+ ];+ const messages = seedDelegateMessages({+ originalTask: "explore",+ rows,+ provider: provider(),+ model: buildProviderModel(provider()),+ budget: generousBudget(),+ });+ expect(messages.at(-1)).toMatchObject({+ role: "toolResult",+ details: {+ query: "BrowserPreview",+ activated: ["BrowserPreview"],+ addedToolNames: ["BrowserPreview"],+ },+ });+ });+it("skips a failed assistant row but still replays its tool pair", () => {const rows: UiMessage[] = [{diff --git a/packages/agent-runtime/src/delegation-history.ts b/packages/agent-runtime/src/delegation-history.tsindex 06251d875..7ad607a99 100644--- a/packages/agent-runtime/src/delegation-history.ts+++ b/packages/agent-runtime/src/delegation-history.ts@@ -456,7 +456,22 @@ function toolResultFromUi(m: UiMessage, timestamp: number): ToolResultMessage {: MISSING_TOOL_RESULT_PLACEHOLDER,});}- const details = toJsonValue(isRecord(raw) ? raw.details : undefined);+ const rawRecord = isRecord(raw) ? raw : undefined;+ const rawDetails = toJsonValue(rawRecord?.details);+ const legacyAddedToolNames =+ m.toolName === "ToolSearch" && Array.isArray(rawRecord?.addedToolNames)+ ? rawRecord.addedToolNames.filter(+ (name: unknown): name is string =>+ typeof name === "string" && name.length > 0,+ )+ : [];+ const details =+ legacyAddedToolNames.length > 0+ ? {+ ...(isRecord(rawDetails) ? rawDetails : {}),+ addedToolNames: [...new Set(legacyAddedToolNames)],+ }+ : rawDetails;return {role: "toolResult",toolCallId: m.toolCallId ?? "",diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex cfa256975..8600cfc45 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2083,6 +2083,7 @@ describe("DesktopAgentRuntime deferred tool catalog", () => {const result = await search.execute("search-1", { query: "BrowserPreview" });expect(result.details.activated).toEqual(["BrowserPreview"]);+ expect(result.details.addedToolNames).toEqual(["BrowserPreview"]);expect(agent.state.tools.some((tool: any) => tool.name === "BrowserPreview")).toBe(false,);@@ -2098,7 +2099,6 @@ describe("DesktopAgentRuntime deferred tool catalog", () => {toolName: "ToolSearch",content: result.content,details: result.details,- addedToolNames: result.details.activated,isError: false,timestamp: Date.now(),},@@ -8400,8 +8400,9 @@ describe("DesktopAgentRuntime deferred tool restore (#225)", () => {toolArgs: { query: "BrowserPreview" },toolResult: {content: [{ type: "text", text: "Activated on-demand tools: BrowserPreview." }],- details: { activated: ["BrowserPreview"] },- addedToolNames: ["BrowserPreview"],+ details: {+ addedToolNames: ["BrowserPreview"],+ },},...overrides,});@@ -8424,6 +8425,69 @@ describe("DesktopAgentRuntime deferred tool restore (#225)", () => {await runtime.dispose();});+ it("restores legacy activation markers for an unused tool", async () => {+ const fixtures: Array<{ details: Record<string, unknown>; addedToolNames?: string[] }> = [+ { details: { activated: ["BrowserPreview"] } },+ { details: { activated: [] }, addedToolNames: ["BrowserPreview"] },+ ];++ for (const [index, fixture] of fixtures.entries()) {+ const runtime = createRuntime({+ history: [+ assistantRow,+ searchRow({+ id: `tool-search-legacy-${index}`,+ toolCallId: `call-search-legacy-${index}`,+ toolResult: {+ content: [{ type: "text", text: "Activated on-demand tools: BrowserPreview." }],+ details: fixture.details,+ ...(fixture.addedToolNames+ ? { addedToolNames: fixture.addedToolNames }+ : {}),+ },+ }),+ ],+ });++ (runtime as any).resetDeferredToolsForPrompt();+ expect(hasTool(runtime, "BrowserPreview")).toBe(true);+ await runtime.dispose();+ }+ });++ it("restores all activated tools when only some have been called", async () => {+ const runtime = createRuntime({+ history: [+ assistantRow,+ searchRow({+ toolResult: {+ content: [{ type: "text", text: "Activated on-demand tools: BrowserPreview, Glob." }],+ details: {+ addedToolNames: ["BrowserPreview", "Glob"],+ },+ },+ }),+ {+ id: "tool-preview-ok",+ role: "tool",+ content: "",+ createdAt: now(),+ status: "complete",+ toolName: "BrowserPreview",+ toolCallId: "call-preview-ok",+ toolStatus: "success",+ toolArgs: {},+ toolResult: { content: [{ type: "text", text: "opened" }] },+ },+ ],+ });++ (runtime as any).resetDeferredToolsForPrompt();+ expect(hasTool(runtime, "BrowserPreview")).toBe(true);+ expect(hasTool(runtime, "Glob")).toBe(true);+ await runtime.dispose();+ });+it("restores a tool from its own successful result, not from failed or empty rows", async () => {const runtime = createRuntime({history: [diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 475d18b61..b49f68cde 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -363,6 +363,36 @@ export const TOOL_SEARCH_NAME = "ToolSearch";/** Stands in for a persisted tool row that never recorded a result. */const MISSING_TOOL_RESULT_PLACEHOLDER = "[no tool result recorded]";+function toolNameList(value: unknown): string[] {+ if (!Array.isArray(value)) return [];+ return [+ ...new Set(+ value.filter(+ (name: unknown): name is string =>+ typeof name === "string" && name.length > 0,+ ),+ ),+ ];+}++/** Read canonical and historical activation markers from a ToolSearch row. */+function toolSearchActivatedNames(+ details: unknown,+ legacyAddedToolNames?: unknown,+): string[] {+ const record = isRecord(details) ? details : undefined;+ const candidates = [+ record?.addedToolNames,+ record?.activated,+ legacyAddedToolNames,+ ];+ for (const candidate of candidates) {+ const names = toolNameList(candidate);+ if (names.length > 0) return names;+ }+ return [];+}+function isMissingToolResultPlaceholder(content: ToolResultMessage["content"],): boolean {@@ -1436,12 +1466,9 @@ function toolResultFromUi(: undefined;const rawAddedToolNames = rawRecord?.addedToolNames;const addedToolNames =- Array.isArray(rawAddedToolNames)- ? rawAddedToolNames.filter(- (name: unknown): name is string =>- typeof name === "string" && name.length > 0,- )- : [];+ m.toolName === TOOL_SEARCH_NAME+ ? toolSearchActivatedNames(rawRecord?.details, rawAddedToolNames)+ : toolNameList(rawAddedToolNames);if (blocks.length === 0) {blocks.push({type: "text",@@ -3654,7 +3681,12 @@ Delegation rules:: `No matching on-demand tool. Available names: ${availablePreview.join(", ")}${remaining > 0 ? `, and ${remaining} more` : ""}.`;return {content: [{ type: "text", text }],- details: { query, matches, activated },+ details: {+ query,+ matches,+ activated,+ ...(activated.length > 0 ? { addedToolNames: activated } : {}),+ },};},};@@ -5109,9 +5141,10 @@ Delegation rules:if (isMissingToolResultPlaceholder(message.content)) continue;const names =message.toolName === TOOL_SEARCH_NAME- ? (isRecord(message.details) && Array.isArray(message.details.addedToolNames)- ? message.details.addedToolNames.filter((name): name is string => typeof name === "string")- : [])+ ? toolSearchActivatedNames(+ message.details,+ (message as unknown as { addedToolNames?: unknown }).addedToolNames,+ ): [message.toolName];for (const name of names) {if (this.deferredToolNames.has(name)) {