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): declare required on every object tool schema
vastsa92029e88efe9
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 916cc7e1c..02791e5ec 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2233,6 +2233,111 @@ describe("DesktopAgentRuntime mode and tool composition", () => {});});+describe("DesktopAgentRuntime tool schema completeness (#864)", () => {+ it("declares required for every object schema handed to the provider", async () => {+ // Plan mode keeps the read-only core (Read, Glob, Grep, BrowserPreview)+ // active instead of deferring it behind ToolSearch, and a plan-safe plugin+ // tool joins that same core set.+ const runtime = createRuntime({+ mode: "plan",+ pluginTools: [+ {+ name: "plugin_demo_read",+ description: "demo",+ planSafeActions: ["read"],+ // A manifest that spells out no `required` at all, like the built-ins+ // whose canonical argument is declared optional.+ parameters: { type: "object", properties: {} },+ },+ ],+ });+ type WireTool = {+ name: string;+ parameters?: { type?: unknown; required?: unknown };+ };+ const declarations = (+ (runtime as any).agent.state.tools as Array<unknown>+ ).map(+ (tool) => toToolDeclaration(tool as never) as unknown as WireTool,+ );+ const byName = new Map<string, WireTool>();+ for (const declaration of declarations) {+ byName.set(declaration.name, declaration);+ }++ // The alias tools require no argument, but the key still has to be an+ // array: a relay that decodes a missing key into a nil slice answers+ // `Invalid schema for function 'Read': null is not of type "array"`.+ for (const name of [+ "Read",+ "Glob",+ "Grep",+ "BrowserPreview",+ "plugin_demo_read",+ ]) {+ const declaration = byName.get(name);+ expect(+ declaration,+ `${name} missing from the active catalogue`,+ ).toBeDefined();+ expect(declaration!.parameters, name).toMatchObject({+ type: "object",+ required: [],+ });+ }+ for (const declaration of declarations) {+ const parameters = declaration.parameters;+ if (parameters?.type !== "object") continue;+ expect(+ Array.isArray(parameters.required),+ `${declaration.name}.required`,+ ).toBe(true);+ }+ // A tool that does have a required argument keeps exactly that list.+ expect(byName.get("Bash")!.parameters?.required).toEqual(["command"]);++ await runtime.dispose();+ });++ it("hands the same schema to a delegated Task run", async () => {+ // A delegate reads its tools straight from the tool catalogue, so a+ // normalisation applied only where the session agent is wired up would miss+ // it — and the default delegate toolset is exactly these read tools.+ const runtime = createRuntime({+ subagents: [+ {+ name: "worker",+ description: "Reads files.",+ tools: ["Read", "Glob", "Grep"],+ prompt: "Do the job.",+ source: "user",+ },+ ],+ });+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;+ const task = (runtime as any).agent.state.tools.find(+ (tool: { name: string }) => tool.name === "Task",+ );+ await task.execute("delegate-1", { agent: "worker", task: "Read a file." });++ expect(subagentRuns.calls).toHaveLength(1);+ const delegateTools: Array<Record<string, any>> =+ subagentRuns.calls[0].tools;+ expect(delegateTools.map((tool) => tool.name)).toEqual(+ expect.arrayContaining(["Read", "Glob", "Grep"]),+ );+ for (const delegateTool of delegateTools) {+ expect(Array.isArray(delegateTool.parameters?.required)).toBe(true);+ }+ expect(+ delegateTools.find((tool) => tool.name === "Read")!.parameters.required,+ ).toEqual([]);++ await runtime.dispose();+ });+});+describe("DesktopAgentRuntime plan transitions", () => {it("guards transition batches and terminates after durable plan submission", async () => {const host = { call: vi.fn() };diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 31382897d..3fe4029ab 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -127,6 +127,7 @@ import {usageFromPi,usageToPi,} from "./agent-messages.js";+import { withExplicitRequired } from "./tool-schema.js";import { buildSessionContext } from "./session-context.js";import {initialSystemTranscript,@@ -3474,11 +3475,17 @@ Delegation rules:// an accidental parallel batch: everything is sequential except `Task`.// pi runs a whole batch sequentially when it holds one sequential tool,// so only an all-`Task` batch fans out.- catalog.set(tool.name, {- ...tool,- executionMode:- tool.name === SUBAGENT_TOOL_NAME ? "parallel" : "sequential",- });+ // The provider-facing schema is settled here too, at the single origin of+ // every tool, so the session agent and a delegated `Task` run send the+ // same declaration (#864).+ catalog.set(+ tool.name,+ withExplicitRequired({+ ...tool,+ executionMode:+ tool.name === SUBAGENT_TOOL_NAME ? "parallel" : "sequential",+ }),+ );}this.toolCatalog = catalog;this.deferredToolNames = new Set(@@ -3492,10 +3499,13 @@ Delegation rules:}}if (this.deferredToolNames.size > 0) {- this.toolCatalog.set(TOOL_SEARCH_NAME, {- ...this.buildToolSearchTool(),- executionMode: "sequential",- });+ this.toolCatalog.set(+ TOOL_SEARCH_NAME,+ withExplicitRequired({+ ...this.buildToolSearchTool(),+ executionMode: "sequential",+ }),+ );}}diff --git a/packages/agent-runtime/src/tool-schema.test.ts b/packages/agent-runtime/src/tool-schema.test.tsnew file mode 100644index 000000000..9be1940a3--- /dev/null+++ b/packages/agent-runtime/src/tool-schema.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import { Type } from "typebox";+import type { AgentTool } from "@earendil-works/pi-agent-core";+import { withExplicitRequired } from "./tool-schema.js";++// Guards the provider-facing shape of a tool schema (#864). Tool types go+// through a JSON round trip before the provider sees them, so a key that is+// absent here is absent on the wire.++function toolWith(parameters: unknown): AgentTool {+ return { name: "fx", description: "fx", parameters } as unknown as AgentTool;+}++describe("withExplicitRequired", () => {+ it("omits required for an all-optional TypeBox object schema", () => {+ // The premise: Read, Glob, Grep, and BrowserPreview declare every argument+ // optional so the alias spelling validates too, and TypeBox 1.x then emits+ // no `required` key at all.+ expect(+ Type.Object({ path: Type.Optional(Type.String()) }),+ ).not.toHaveProperty("required");+ });++ it("spells out an empty required list", () => {+ const aliasTool = toolWith({+ type: "object",+ properties: {+ path: { type: "string" },+ file_path: { type: "string" },+ },+ });+ expect(withExplicitRequired(aliasTool).parameters).toMatchObject({+ type: "object",+ required: [],+ });+ });++ it("leaves an existing required list untouched", () => {+ const writeTool = toolWith(+ Type.Object({+ path: Type.Optional(Type.String()),+ content: Type.String(),+ }),+ );+ expect(withExplicitRequired(writeTool)).toBe(writeTool);+ });++ it("ignores schemas that are not object-shaped", () => {+ const union = toolWith({ anyOf: [{ type: "object" }] });+ expect(withExplicitRequired(union)).toBe(union);+ });+});diff --git a/packages/agent-runtime/src/tool-schema.ts b/packages/agent-runtime/src/tool-schema.tsnew file mode 100644index 000000000..4767f2913--- /dev/null+++ b/packages/agent-runtime/src/tool-schema.ts@@ -0,0 +1,40 @@+/**+ * Provider-facing normalisation of tool parameter schemas.+ *+ * `Read`, `Glob`, `Grep`, and `BrowserPreview` declare their canonical argument+ * as `Type.Optional` so the `file_path` / `query` alias spelling validates too;+ * "exactly one spelling" is enforced by `requireAliasedParams` at execute time+ * instead (D273). TypeBox 1.x then omits `required` altogether when no property+ * is required, and the OpenAI chat/completions adapter forwards `parameters`+ * verbatim while only the Anthropic adapter fills `required ?? []`. A relay that+ * decodes the missing key into a nil slice rejects the whole request with+ * `Invalid schema for function 'Read': null is not of type "array"` (#864).+ */++import type { AgentTool } from "@earendil-works/pi-agent-core";++/**+ * Spell out `required` on an object tool schema before it reaches the provider.+ *+ * For an object schema an absent `required` already means "nothing is+ * required", so writing `[]` states the same contract explicitly and changes no+ * tool's accepted arguments. Applied when the tool catalogue is built, so the+ * session agent and a delegated `Task` run send one declaration, and plugin,+ * skill, mode, delegation, extension, and ToolSearch schemas are covered by the+ * same pass. A non-object or already-normalised schema is returned untouched.+ */+export function withExplicitRequired(tool: AgentTool): AgentTool {+ const parameters = tool.parameters as {+ type?: unknown;+ required?: unknown;+ };+ if (parameters.type !== "object" || parameters.required !== undefined) {+ return tool;+ }+ return {+ ...tool,+ parameters: Object.assign({}, tool.parameters, {+ required: [],+ }) as AgentTool["parameters"],+ };+}