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): spell out required on nested tool-schema objects
xpeng5278-web7b56da1365fc
diff --git a/packages/agent-runtime/src/tool-schema.test.ts b/packages/agent-runtime/src/tool-schema.test.tsindex 9be1940a3..e95c5a393 100644--- a/packages/agent-runtime/src/tool-schema.test.ts+++ b/packages/agent-runtime/src/tool-schema.test.ts@@ -11,6 +11,33 @@ function toolWith(parameters: unknown): AgentTool {return { name: "fx", description: "fx", parameters } as unknown as AgentTool;}+// Raw JSON fixtures have no `required` key until normalisation adds one.+// Reading them back through this shape keeps that key visible to tsc.+type ReadableSchema = {+ type?: string;+ required?: string[];+ properties?: Record<string, ReadableSchema>;+ items?: ReadableSchema | ReadableSchema[];+ additionalProperties?: ReadableSchema | boolean;+ anyOf?: ReadableSchema[];+ oneOf?: ReadableSchema[];+ allOf?: ReadableSchema[];+ prefixItems?: ReadableSchema[];+};++function readable(schema: unknown): ReadableSchema {+ return schema as ReadableSchema;+}++function readableList(+ schema: ReadableSchema | ReadableSchema[] | undefined,+): ReadableSchema[] {+ if (!Array.isArray(schema)) {+ throw new Error("expected a schema array");+ }+ return schema;+}+describe("withExplicitRequired", () => {it("omits required for an all-optional TypeBox object schema", () => {// The premise: Read, Glob, Grep, and BrowserPreview declare every argument@@ -49,4 +76,196 @@ describe("withExplicitRequired", () => {const union = toolWith({ anyOf: [{ type: "object" }] });expect(withExplicitRequired(union)).toBe(union);});++ it("spells out required on a nested all-optional TypeBox object", () => {+ // TypeBox 1.x also omits `required` on a nested object whose properties+ // are all optional. Optional here is "not listed in required", not an+ // anyOf wrapper, so `properties.options` itself is that object.+ const parameters = Type.Object({+ path: Type.String(),+ options: Type.Optional(+ Type.Object({+ path: Type.Optional(Type.String()),+ file_path: Type.Optional(Type.String()),+ }),+ ),+ });+ expect(parameters.properties.options).not.toHaveProperty("required");+ expect(parameters.required).toEqual(["path"]);++ const normalized = withExplicitRequired(toolWith(parameters))+ .parameters as typeof parameters;+ expect(normalized.required).toEqual(["path"]);+ expect(normalized.required).toBe(parameters.required);+ expect(normalized.properties.options).toMatchObject({+ type: "object",+ required: [],+ });+ expect(normalized.properties.options.properties.path).toBe(+ parameters.properties.options.properties.path,+ );+ expect(normalized.properties.options.properties.path).not.toHaveProperty(+ "required",+ );+ expect(parameters.properties.options).not.toHaveProperty("required");+ });++ it("spells out required on a nested JSON object without replacing the parent list", () => {+ // MCP and plugin tools hand over raw JSON Schema, not TypeBox.+ const parameters = {+ type: "object",+ required: ["config"],+ properties: {+ config: {+ type: "object",+ properties: {+ path: { type: "string" },+ },+ },+ },+ };+ const normalized = readable(+ withExplicitRequired(toolWith(parameters)).parameters,+ );+ expect(normalized.required).toEqual(["config"]);+ expect(normalized.required).toBe(parameters.required);+ expect(normalized.properties?.config?.required).toEqual([]);+ expect(parameters.properties.config).not.toHaveProperty("required");+ });++ it("spells out required on object items, including a tuple items array", () => {+ const item = {+ type: "object",+ properties: { name: { type: "string" } },+ };+ const tupleObject = {+ type: "object",+ properties: { a: { type: "string" } },+ };+ const tupleString = { type: "string" };+ const parameters = {+ type: "object",+ required: ["rows", "pair"],+ properties: {+ rows: { type: "array", items: item },+ pair: { type: "array", items: [tupleObject, tupleString] },+ },+ };+ const normalized = readable(+ withExplicitRequired(toolWith(parameters)).parameters,+ );+ const rowsItems = normalized.properties?.rows?.items;+ const pairItems = readableList(normalized.properties?.pair?.items);+ expect(normalized.required).toEqual(["rows", "pair"]);+ expect(readable(rowsItems).required).toEqual([]);+ expect(pairItems[0]?.required).toEqual([]);+ expect(pairItems[1]).toBe(tupleString);+ expect(pairItems[1]).not.toHaveProperty("required");+ expect(item).not.toHaveProperty("required");+ expect(tupleObject).not.toHaveProperty("required");+ });++ it("keeps an already-required nested object and non-object nodes unchanged", () => {+ const nested = {+ type: "object",+ required: ["id"],+ properties: { id: { type: "string" } },+ };+ const emptyRequired = {+ type: "object",+ required: [] as string[],+ properties: { note: { type: "string" } },+ };+ const label = { type: "string" };+ const normalizedTool = toolWith({+ type: "object",+ required: ["nested", "emptyRequired", "label"],+ properties: { nested, emptyRequired, label },+ });+ expect(withExplicitRequired(normalizedTool)).toBe(normalizedTool);++ // A sibling that still needs `required` forces a new parameters object.+ // The nodes that were already explicit keep their identity, and a deeper+ // copy does not replace an existing required list.+ const bag = { type: "object", properties: { note: { type: "string" } } };+ const childRequired = ["child"];+ const inner = { type: "object", properties: { note: { type: "string" } } };+ const parent = {+ type: "object",+ required: childRequired,+ properties: { child: inner },+ };+ const mixed = {+ type: "object",+ required: ["nested", "label", "bag", "parent"],+ properties: { nested, label, bag, parent },+ };+ const normalized = readable(withExplicitRequired(toolWith(mixed)).parameters);+ expect(normalized.required).toBe(mixed.required);+ expect(normalized.properties?.nested).toBe(nested);+ expect(normalized.properties?.label).toBe(label);+ expect(normalized.properties?.bag).not.toBe(bag);+ expect(normalized.properties?.bag?.required).toEqual([]);+ expect(normalized.properties?.parent?.required).toBe(childRequired);+ expect(normalized.properties?.parent?.properties?.child?.required).toEqual(+ [],+ );+ expect(bag).not.toHaveProperty("required");+ expect(inner).not.toHaveProperty("required");+ expect(parent.required).toBe(childRequired);+ });++ it("does not write required onto non-object nodes", () => {+ const branch = { type: "object", properties: { a: { type: "string" } } };+ const stringBranch = { type: "string" };+ const prefixObject = {+ type: "object",+ properties: { b: { type: "string" } },+ };+ const valueSchema = {+ type: "object",+ properties: { v: { type: "string" } },+ };+ const parameters = {+ type: "object",+ required: ["choice", "extra"],+ additionalProperties: false,+ properties: {+ choice: {+ anyOf: [branch, stringBranch],+ oneOf: [stringBranch],+ allOf: [branch],+ },+ extra: {+ type: "object",+ additionalProperties: valueSchema,+ prefixItems: [prefixObject, stringBranch],+ },+ rows: { type: "array", items: stringBranch },+ },+ };+ const normalized = readable(+ withExplicitRequired(toolWith(parameters)).parameters,+ );+ const choice = normalized.properties?.choice;+ const extra = normalized.properties?.extra;+ const prefixItems = readableList(extra?.prefixItems);+ expect(normalized.additionalProperties).toBe(false);+ expect(choice).not.toHaveProperty("required");+ expect(choice?.anyOf?.[0]?.required).toEqual([]);+ expect(choice?.anyOf?.[1]).toBe(stringBranch);+ expect(choice?.oneOf?.[0]).toBe(stringBranch);+ expect(choice?.allOf?.[0]?.required).toEqual([]);+ // `extra` is itself an object schema, so it gains an empty required list+ // while its non-object siblings do not.+ expect(extra?.required).toEqual([]);+ expect(readable(extra?.additionalProperties).required).toEqual([]);+ expect(prefixItems[0]?.required).toEqual([]);+ expect(prefixItems[1]).toBe(stringBranch);+ expect(normalized.properties?.rows).not.toHaveProperty("required");+ expect(normalized.properties?.rows?.items).toBe(stringBranch);+ expect(branch).not.toHaveProperty("required");+ expect(valueSchema).not.toHaveProperty("required");+ expect(prefixObject).not.toHaveProperty("required");+ });});diff --git a/packages/agent-runtime/src/tool-schema.ts b/packages/agent-runtime/src/tool-schema.tsindex 4767f2913..90f9def00 100644--- a/packages/agent-runtime/src/tool-schema.ts+++ b/packages/agent-runtime/src/tool-schema.ts@@ -5,36 +5,124 @@* 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+ * is required — on the root and on nested objects and array `items`. 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).+ * MCP, plugin, and custom-tool JSON Schema has the same hole.*/import type { AgentTool } from "@earendil-works/pi-agent-core";+const SCHEMA_ARRAY_KEYS = ["anyOf", "oneOf", "allOf", "prefixItems"] as const;++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/**+ * Spell out `required: []` on one schema node and the object schemas nested in+ * it. An existing `required` (including `[]`) is kept. Unchanged nodes keep+ * their identity, and the input is never mutated.+ */+function schemaWithExplicitRequired(schema: unknown): unknown {+ if (!isRecord(schema)) return schema;++ let next: Record<string, unknown> | undefined;+ const update = (key: string, value: unknown) => {+ if (Object.is(value, schema[key])) return;+ next ??= { ...schema };+ next[key] = value;+ };++ if (isRecord(schema.properties)) {+ update("properties", recordWithExplicitRequired(schema.properties));+ }+ if ("items" in schema) {+ update("items", itemsWithExplicitRequired(schema.items));+ }+ // `additionalProperties` is often the boolean `false`. Only a schema object+ // can itself omit `required`.+ if (isRecord(schema.additionalProperties)) {+ update(+ "additionalProperties",+ schemaWithExplicitRequired(schema.additionalProperties),+ );+ }+ for (const key of SCHEMA_ARRAY_KEYS) {+ const entries = schema[key];+ if (Array.isArray(entries)) {+ update(key, schemasWithExplicitRequired(entries));+ }+ }++ if (schema.type !== "object" || schema.required !== undefined) {+ return next ?? schema;+ }+ if (next) {+ next.required = [];+ return next;+ }+ return Object.assign({}, schema, { required: [] });+}++function recordWithExplicitRequired(+ record: Record<string, unknown>,+): Record<string, unknown> {+ let next: Record<string, unknown> | undefined;+ for (const [key, value] of Object.entries(record)) {+ const normalized = schemaWithExplicitRequired(value);+ if (normalized === value) continue;+ next ??= { ...record };+ next[key] = normalized;+ }+ return next ?? record;+}++function schemasWithExplicitRequired(+ schemas: readonly unknown[],+): readonly unknown[] {+ let next: unknown[] | undefined;+ for (let index = 0; index < schemas.length; index += 1) {+ const value = schemas[index];+ const normalized = schemaWithExplicitRequired(value);+ if (normalized === value) continue;+ next ??= schemas.slice();+ next[index] = normalized;+ }+ return next ?? schemas;+}++function itemsWithExplicitRequired(items: unknown): unknown {+ if (Array.isArray(items)) return schemasWithExplicitRequired(items);+ return schemaWithExplicitRequired(items);+}+/**- * Spell out `required` on an object tool schema before it reaches the provider.+ * Spell out `required` on object tool schemas before they reach 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.+ * same pass. The pass walks `properties`, `items` (schema or tuple), object+ * `additionalProperties`, and `anyOf` / `oneOf` / `allOf` / `prefixItems`, and+ * writes `required: []` only on a `type: "object"` node that omitted it.+ * TypeBox's `Optional` is absent from `required`; a `Type.Union` wrapper is an+ * `anyOf`, and the object inside that wrapper is what gets the key. Parameters+ * that are not themselves `type: "object"`, and a schema that already spells+ * `required` out on every object node, are returned untouched.*/export function withExplicitRequired(tool: AgentTool): AgentTool {- const parameters = tool.parameters as {- type?: unknown;- required?: unknown;- };- if (parameters.type !== "object" || parameters.required !== undefined) {+ if (!isRecord(tool.parameters) || tool.parameters.type !== "object") {return tool;}+ const normalized = schemaWithExplicitRequired(tool.parameters);+ if (normalized === tool.parameters) return tool;return {...tool,- parameters: Object.assign({}, tool.parameters, {- required: [],- }) as AgentTool["parameters"],+ parameters: normalized as AgentTool["parameters"],};}