Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep items on arrays when a Gemini tool schema is compacted
Ooi Pin Jun08fc34c51295
diff --git a/server/tool-list-budget.test.ts b/server/tool-list-budget.test.tsindex c0d5a43aa8..edb9d7f344 100644--- a/server/tool-list-budget.test.ts+++ b/server/tool-list-budget.test.ts@@ -152,4 +152,58 @@ describe("fitting a list into its share", () => {mode: { type: "string", enum: ["a", "b"] },} });});++ it("rebuilds an oversized array with its item type, and leaves a plain string array as it was", () => {+ const tool: ListedTool = {+ name: "sample", description: "A sample tool.",+ inputSchema: { type: "object", required: ["keys", "labels"], properties: {+ keys: { type: "array", items: { type: "integer" }, allOf: Array.from({ length: 200 }, () => ({ maxItems: 16 })) },+ labels: { type: "array", items: { type: "string" }, maxItems: 16 },+ } },+ };+ const fitted = fitToolListToShare([tool], 500);+ expect(fitted.from).toBeGreaterThan(500);+ expect(fitted.level.topLevelOnly).toBe(true);+ expect(fitted.fits).toBe(true);+ expect(fitted.bytes).toBeLessThanOrEqual(500);+ expect(fitted.tools[0]!.inputSchema).toEqual({ type: "object", required: ["keys", "labels"], properties: {+ keys: { type: "array", items: { type: "integer" } },+ labels: { type: "array", items: { type: "string" }, maxItems: 16 },+ } });+ });++ it("keeps a nullable, nested, missing, or recursive array's items when the field is rebuilt", () => {+ const tool: ListedTool = {+ name: "sample", description: "A sample tool.",+ inputSchema: {+ type: "object", required: ["keys", "nullable"],+ $defs: { node: { type: "array", items: { $ref: "#/$defs/node" } } },+ properties: {+ keys: { type: "array", items: { type: "integer" }, allOf: Array.from({ length: 200 }, () => ({ maxItems: 16 })) },+ nullable: { type: ["array", "null"], items: { type: "integer", minimum: 0 }, allOf: [{ maxItems: 4 }] },+ nested: { type: "array", items: { type: "array", items: { type: "boolean", description: "drop me" } }, allOf: [{ maxItems: 4 }] },+ bare: { type: "array" },+ tree: { type: "array", allOf: [{ maxItems: 4 }], $ref: "#/$defs/node" },+ labels: { type: "array", items: { type: "string" }, maxItems: 16 },+ },+ },+ };+ const fitted = fitToolListToShare([tool], 700);+ expect(fitted.from).toBeGreaterThan(700);+ expect(fitted.level.topLevelOnly).toBe(true);+ expect(fitted.fits).toBe(true);+ expect(fitted.bytes).toBeLessThanOrEqual(700);+ expect(fitted.tools[0]!.inputSchema).toEqual({+ type: "object", required: ["keys", "nullable"],+ $defs: { node: { type: "array", items: { $ref: "#/$defs/node" } } },+ properties: {+ keys: { type: "array", items: { type: "integer" } },+ nullable: { type: ["array", "null"], items: { type: "integer" } },+ nested: { type: "array", items: { type: "array", items: { type: "boolean" } } },+ bare: { type: "array", items: { type: "string" } },+ tree: { type: "array", items: { type: "array", items: { type: "string" } } },+ labels: { type: "array", items: { type: "string" }, maxItems: 16 },+ },+ });+ });});diff --git a/server/tool-list-budget.ts b/server/tool-list-budget.tsindex b480201da6..d162c462b9 100644--- a/server/tool-list-budget.ts+++ b/server/tool-list-budget.ts@@ -8,7 +8,7 @@// annotations, shorter parameter descriptions, shorter tool descriptions, and last nested fields. No tool is left out,// no name or required field changes, and every call is still checked against the tool's own full schema.import { compactAdvertisedSchema } from "./advertised-schema.ts";-import { schemaBytes } from "./tool-schema-profile.ts";+import { itemsOf, schemaBytes } from "./tool-schema-profile.ts";type Json = Record<string, unknown>;export type ListedTool = { name: string; description?: string; inputSchema?: unknown } & Json;@@ -91,24 +91,33 @@ function withSchemaLevel(node: unknown, parameters: number, annotations: booleanreturn result;}-/** A top-level field that holds an object, or a list of objects, as just its type and choices (a list keeps- * `items: {type: "object"}`, which a Gemini endpoint requires of every array); any other field, and one with no `type` of- * its own, as it was. */-function collapsedField(property: unknown): unknown {+function acceptsArray(type: unknown): boolean {+ return type === "array" || (Array.isArray(type) && type.includes("array"));+}++/** A top-level field that holds an object, or a nested value, as just its type and choices. Gemini requires `items` on+ * every array: a list of objects keeps `{type:"object"}`, and any other array keeps its item type (a string when that+ * type cannot be named). A field that is not nested stays as it was, except an array that would otherwise go out with+ * no `items`. A field with no `type` of its own stays as it was. */+function collapsedField(property: unknown, root: Json): unknown {if (!isObject(property) || !("type" in property)) return property;const listOfObjects = isObject(property.items) && (isObject(property.items.properties) || isObject(property.items.additionalProperties));const nested = isObject(property.properties) || isObject(property.additionalProperties) || listOfObjects|| Array.isArray(property.anyOf) || Array.isArray(property.oneOf) || Array.isArray(property.allOf);- if (!nested) return property;+ if (!nested) {+ if (acceptsArray(property.type) && !("items" in property)) return { ...property, items: itemsOf(property, root) };+ return property;+ }const kept: Json = Object.fromEntries(["type", "enum"].filter((key) => key in property).map((key) => [key, property[key]]));- return listOfObjects ? { ...kept, items: { type: "object" } } : kept;+ if (listOfObjects) return { ...kept, items: { type: "object" } };+ return acceptsArray(property.type) ? { ...kept, items: itemsOf(property, root) } : kept;}/** A schema with each top-level field collapsed as above; the field names and `required` as they were. The handler still* checks every nested field. */function withTopLevelFields(schema: unknown): unknown {if (!isObject(schema) || !isObject(schema.properties)) return schema;- return { ...schema, properties: Object.fromEntries(Object.entries(schema.properties).map(([name, property]) => [name, collapsedField(property)])) };+ return { ...schema, properties: Object.fromEntries(Object.entries(schema.properties).map(([name, property]) => [name, collapsedField(property, schema)])) };}/** How much of each tool a list keeps: description lengths in characters (Infinity keeps all), whether schemadiff --git a/server/tool-schema-profile.test.ts b/server/tool-schema-profile.test.tsindex 7a4e54958f..6e0eb5dfcb 100644--- a/server/tool-schema-profile.test.ts+++ b/server/tool-schema-profile.test.ts@@ -203,6 +203,80 @@ describe("fitting a tool list to Gemini's list budget", () => {});});+describe("fitting one tool schema to Gemini's per-tool limit", () => {+ const GEMINI = toolSchemaProfile("gemini")!;+ const keys = () => ({ type: "array", items: { type: "integer" }, allOf: Array.from({ length: 200 }, () => ({ maxItems: 16 })) });++ it("keeps an integer array's items when a nested field is collapsed", () => {+ const schema = { type: "object", properties: { group: { type: "object", properties: { keys: keys() } } } };+ expect(schemaBytes(schema)).toBeGreaterThan(GEMINI.maxSchemaBytes);+ const fit = fitToolSchema(schema, GEMINI);+ expect(fit.outcome).toBe("loosened");+ if (fit.outcome !== "loosened") return;+ expect(fit.bytes).toBeLessThanOrEqual(GEMINI.maxSchemaBytes);+ expect((fit.schema.properties as Json).group).toEqual({ type: "object", properties: { keys: { type: "array", items: { type: "integer" } } } });+ });++ it("keeps an integer array's items and its required name when only the top-level fields remain", () => {+ const schema = { type: "object", required: ["keys"], properties: { keys: keys() } };+ expect(schemaBytes(schema)).toBeGreaterThan(GEMINI.maxSchemaBytes);+ const fit = fitToolSchema(schema, GEMINI);+ expect(fit.outcome).toBe("minimal");+ if (fit.outcome !== "minimal") return;+ expect(fit.bytes).toBeLessThanOrEqual(GEMINI.maxSchemaBytes);+ expect(fit.schema).toEqual({+ type: "object", properties: { keys: { type: "array", items: { type: "integer" } } }, required: ["keys"], additionalProperties: true,+ });+ });++ it("keeps a known item type, and a string where an array has no single item schema", () => {+ const schema = {+ type: "object",+ $defs: { node: { type: "array", items: { $ref: "#/$defs/node" } } },+ properties: { group: { type: "object", properties: {+ keys: keys(),+ nullable: { type: ["array", "null"], items: { type: "integer", minimum: 0 } },+ nested: { type: "array", items: { type: "array", items: { type: "boolean", description: "drop me" } } },+ bare: { type: "array" },+ rows: { type: "array", items: { type: "object", description: "row", properties: { a: { type: "string" } } } },+ tuple: { type: "array", prefixItems: [{ type: "string" }, { type: "integer" }] },+ flag: { type: "array", items: true },+ tree: { $ref: "#/$defs/node" },+ } } },+ };+ expect(schemaBytes(schema)).toBeGreaterThan(GEMINI.maxSchemaBytes);+ const fit = fitToolSchema(schema, GEMINI);+ expect(fit.outcome).toBe("loosened");+ if (fit.outcome !== "loosened") return;+ expect(fit.bytes).toBeLessThanOrEqual(GEMINI.maxSchemaBytes);+ expect(fit.schema).toEqual({ type: "object", properties: { group: { type: "object", properties: {+ keys: { type: "array", items: { type: "integer" } },+ nullable: { type: ["array", "null"], items: { type: "integer" } },+ nested: { type: "array", items: { type: "array", items: { type: "boolean" } } },+ bare: { type: "array", items: { type: "string" } },+ rows: { type: "array", items: { type: "object" } },+ tuple: { type: "array", items: { type: "string" } },+ flag: { type: "array", items: { type: "string" } },+ tree: { type: "array", items: { type: "array", items: { type: "string" } } },+ } } } });+ });++ it("names items when a top-level value has no schema to copy", () => {+ const schema = { type: "object", properties: { keys: keys(), note: null } };+ expect(schemaBytes(schema)).toBeGreaterThan(GEMINI.maxSchemaBytes);+ const fit = fitToolSchema(schema, GEMINI);+ expect(fit.outcome).toBe("minimal");+ if (fit.outcome !== "minimal") return;+ expect(fit.bytes).toBeLessThanOrEqual(GEMINI.maxSchemaBytes);+ expect(fit.schema).toEqual({+ type: "object", additionalProperties: true, properties: {+ keys: { type: "array", items: { type: "integer" } },+ note: { type: ["string", "number", "integer", "boolean", "object", "array", "null"], items: { type: "string" } },+ },+ });+ });+});+describe("OpenMausBot's own tools", () => {const catalogs: Array<[string, ReadonlyArray<{ name: string; inputSchema: unknown }>]> = [["agents (full)", fullAgents.tools], ["agents (bridged)", bridgedAgents.tools], ["browser", BROWSER_TOOLS],diff --git a/server/tool-schema-profile.ts b/server/tool-schema-profile.tsindex b942aafbb3..48956d4bec 100644--- a/server/tool-schema-profile.ts+++ b/server/tool-schema-profile.ts@@ -222,18 +222,54 @@ function typesOf(node: Json, root: Json, hops = 0): string[] {return [];}+const ITEM_HOPS = 8;++function includesArray(type: string | readonly unknown[]): boolean {+ return type === "array" || (Array.isArray(type) && type.includes("array"));+}++/** The `items` Gemini's GenerateContentRequest requires on every array (Antigravity CLI 1.5.x). The item's type only,+ * and `items` again when that type is array. A tuple, a boolean, or a missing, cyclic, or unresolvable item schema is a string. */+export function itemsOf(node: Json, root: Json): Json {+ return projectedItems(node, root, new Set(), 0);+}++function projectedItems(node: Json, root: Json, seen: Set<string>, hops: number): Json {+ if (hops > ITEM_HOPS) return { type: "string" };+ const items = schemaItems(node, root, seen, hops);+ if (!isObject(items)) return { type: "string" };+ const types = [...new Set(typesOf(items, root).filter((type) => JSON_TYPES.includes(type)))];+ if (types.length !== 1) return { type: "string" };+ const type = types[0]!;+ return type === "array" ? { type, items: projectedItems(items, root, seen, hops + 1) } : { type };+}++function schemaItems(node: Json, root: Json, seen: Set<string>, hops: number): unknown {+ if ("items" in node) return node.items;+ const ref = node.$ref;+ if (typeof ref !== "string" || seen.has(ref) || hops > ITEM_HOPS) return undefined;+ const target = pointer(root, ref);+ if (!isObject(target)) return undefined;+ seen.add(ref);+ return schemaItems(target, root, seen, hops + 1);+}+/** A subschema's type and nothing inside it, valid where Moonshot wants every subschema typed; a free-form object names- * additionalProperties because a bare `{"type":"object"}` reads there as recursion without end. */+ * additionalProperties because a bare `{"type":"object"}` reads there as recursion without end. An array names `items`+ * because Gemini rejects an array without one. */function placeholder(node: Json, root: Json): Json {const types = typesOf(node, root).filter((type) => JSON_TYPES.includes(type));const unique = [...new Set(types.map((type) => (type === "integer" && types.includes("number") ? "number" : type)))];- if (unique.length !== 1) return { type: unique.length ? unique : JSON_TYPES };- const type = unique[0]!;- if (type === "object") return { type, additionalProperties: true };- const choices = Array.isArray(node.enum) ? node.enum : "const" in node ? [node.const] : undefined;- const sameType = (value: unknown) => valueType(value) === type || (type === "number" && valueType(value) === "integer");- const keep = type !== "array" && choices && choices.length <= 64 && choices.every(sameType) && schemaBytes(choices) <= 1_024;- return keep ? { type, enum: choices } : { type };+ const declared = unique.length === 1 ? unique[0]! : unique.length ? unique : JSON_TYPES;+ const withItems = (result: Json): Json => includesArray(declared) ? { ...result, items: itemsOf(node, root) } : result;+ if (declared === "object") return { type: declared, additionalProperties: true };+ if (typeof declared === "string") {+ const choices = Array.isArray(node.enum) ? node.enum : "const" in node ? [node.const] : undefined;+ const sameType = (value: unknown) => valueType(value) === declared || (declared === "number" && valueType(value) === "integer");+ const keep = declared !== "array" && choices && choices.length <= 64 && choices.every(sameType) && schemaBytes(choices) <= 1_024;+ return withItems(keep ? { type: declared, enum: choices } : { type: declared });+ }+ return withItems({ type: declared });}/** Each subschema at `depth` becomes its placeholder; its parent keeps every field name and `required`. */@@ -257,7 +293,7 @@ function topLevelOnly(schema: Json, descriptionChars: number): Json {const declared = isObject(schema.properties) ? schema.properties : {};const properties: Json = {};for (const [key, child] of Object.entries(declared)) {- const flat = isObject(child) ? placeholder(child, schema) : { type: JSON_TYPES };+ const flat = placeholder(isObject(child) ? child : {}, schema);const description = isObject(child) ? shortened(child.description, descriptionChars) : undefined;properties[key] = description ? { ...flat, description } : flat;}@@ -319,7 +355,8 @@ export function fitToolListForBudget<Tool extends { name: string; inputSchema?:Buffer.byteLength(JSON.stringify({ ...item, inputSchema: schemas.get(item as Tool) ?? item.inputSchema }) ?? "");// Each tool's size is measured again only when its own schema changes, so a long list is not re-measured per step.const sizes = new Map(list.map((tool) => [tool, bytesOf(tool)]));- let total = [...sizes.values()].reduce((sum, bytes) => sum + bytes, 0);+ const arrayFramingBytes = 2 + Math.max(0, list.length - 1);+ let total = arrayFramingBytes + [...sizes.values()].reduce((sum, bytes) => sum + bytes, 0);const from = total;if (from <= profile.maxListBytes) return list;const budget: number = profile.maxListBytes;