agy-cli 0.1.15: an array tool schema whose items live only on a sibling gets an items schema Gemini accepts (klarkxy #963)

Gemini refuses an array schema with no `items`. array-items.mjs infers
the items from the schema around it, or adds a permissive items schema 8
levels deep, without narrowing what the client allowed; tuple `items`
lists are left as they are, with a hint. Closes #962.

Reviewed head c7d3e7b8 (on c27ba5f7), landed onto main 738fd501 with the
version moved to 0.1.15 and package.json `files` keeping both
re2-pattern.mjs (#946) and array-items.mjs.
Run at the reviewed head: WSL2 bun test packages/agy-cli 9 of 9,
check.mjs ok; Windows 8 pass, 1 fail, the same smoke red as main (#973).
Broken by hand: without the ensureGeminiArrayItems call in normalizeTools
smoke.mjs reports 2 failures; PERMISSIVE_ARRAY_DEPTH = 1 and removing
`if (openArray) return null` each turn a test red.
Run at this commit (WSL2 Ubuntu 24.04, Bun 1.4.2, temp HOME): bun test
packages/agy-cli 10 of 10 pass; bun scripts/check.mjs agy-cli ok;
npm pack --dry-run lists 14 files, both new modules among them.
Not tried: macOS (mote refused ssh), a real agy.

Closes #963

Co-authored-by: klarkxy <klarkxy@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-11 13:35:07 +08:00
co-authored by klarkxy
parent 738fd501d7
commit dbd082f6d1
7 changed files with 539 additions and 3 deletions
+6
View File
@@ -42,3 +42,9 @@ test("test/smoke.mjs against a fake agy", () => {
expect(output).toMatch(/ALL OK \(\d+ checks\)/)
expect(code).toBe(0)
}, 250_000)
test("test/array-items-unit.mjs", () => {
const { code, output } = run([path.join(dir, "array-items-unit.mjs")], 60_000)
expect(output).toMatch(/ALL OK/)
expect(code).toBe(0)
}, 70_000)
+207
View File
@@ -0,0 +1,207 @@
// Fill a sibling `items` on array JSON Schemas so Gemini function_declarations
// are not rejected with `items: missing field`. Called as a tree walk after
// sanitizeInputSchema, so this module does not have to live inside that
// function (the RE2 PR also edits the end of sanitizeInputSchema).
function appendSchemaHint(node, hint) {
if (!hint) return
if (typeof node.description === "string" && node.description.trim()) {
if (!node.description.includes(hint)) node.description = `${node.description} (${hint})`
} else {
node.description = hint
}
}
function nodeDeclaresArray(node) {
if (!node || typeof node !== "object" || Array.isArray(node)) return false
if (typeof node.type === "string") return node.type === "array"
if (Array.isArray(node.type)) return node.type.includes("array")
return false
}
function typelessItems(items) {
if (items == null || items === true) return true
if (items === false) return false
if (Array.isArray(items)) return false
if (typeof items !== "object") return true
if (typeof items.$ref === "string" && items.$ref) return false
if (typeof items.type === "string" && items.type) return false
if (Array.isArray(items.type) && items.type.length) return false
return !items.anyOf && !items.oneOf && !items.allOf
}
function cloneSchemaNode(node) {
if (Array.isArray(node)) return node.map((item) => cloneSchemaNode(item))
if (node && typeof node !== "object") return node
if (node && typeof node === "object") return { ...node }
return node
}
function branchCanAcceptArray(branch) {
if (branch == null || branch === false) return false
if (branch === true) return true
if (typeof branch !== "object" || Array.isArray(branch)) return false
if (typeof branch.type === "string") return branch.type === "array"
if (Array.isArray(branch.type)) return branch.type.includes("array")
// Typeless schemas, including {}, accept arrays. Object-only keywords still
// accept non-objects in JSON Schema unless type is set, but a missing type
// must not be treated as "not an array" or an anyOf [{}] would be ignored.
return true
}
function itemsFromCombinators(node) {
const collected = []
for (const key of ["anyOf", "oneOf", "allOf"]) {
if (!Array.isArray(node[key])) continue
let openArray = false
const definite = []
for (const branch of node[key]) {
if (!branchCanAcceptArray(branch)) continue
if (Array.isArray(branch.items)) continue
// An anyOf/oneOf alternative that accepts any array must not let a
// sibling's items become a global constraint (e.g. string items next to
// {} would reject [1]). allOf alternatives all apply, so typeless ones
// do not loosen the others.
if (typelessItems(branch.items)) {
if (key !== "allOf") openArray = true
continue
}
definite.push(cloneSchemaNode(branch.items))
}
if (openArray) return null
collected.push(...definite)
}
if (!collected.length) return null
const unique = []
const seen = new Set()
for (const item of collected) {
const sig = JSON.stringify(item)
if (seen.has(sig)) continue
seen.add(sig)
unique.push(item)
}
if (unique.length === 1) return unique[0]
return { anyOf: unique }
}
function inferItemsFromExisting(existing) {
// Do not stamp type:"object" onto a properties-only items schema: JSON Schema
// would then reject non-object values that were previously allowed.
if (existing.properties || existing.additionalProperties !== undefined) {
return { ...existing }
}
if (Array.isArray(existing.enum) && existing.enum.length && !existing.type) {
const samples = existing.enum.filter((item) => item !== null && item !== undefined)
if (!samples.length) return null
const types = new Set(samples.map((sample) => (
typeof sample === "boolean" ? "boolean"
: typeof sample === "number" ? (Number.isInteger(sample) ? "integer" : "number")
: "string"
)))
if (types.has("number") && types.has("integer")) types.delete("integer")
if (types.size !== 1) return null
return { ...existing, type: [...types][0] }
}
return null
}
export const PERMISSIVE_LEAF_TYPES = ["string", "number", "integer", "boolean", "object", "null"]
// Gemini Schema cannot express an unbounded nested array without $ref, which
// the translator may not honor. Eight levels is enough for tool arguments and
// is idempotent because the innermost array already has typed items.
export const PERMISSIVE_ARRAY_DEPTH = 8
const TUPLE_ITEMS_HINT = "tuple items were left as a list; positional tuples may not be honored"
const UNTYPED_ITEMS_HINT = "array items were untyped; a permissive items schema was added"
function leafSchemas() {
return PERMISSIVE_LEAF_TYPES.map((type) => ({ type }))
}
function permissiveValueSchema(depth) {
const leaves = leafSchemas()
if (depth <= 1) {
return { anyOf: [...leaves, { type: "array", items: { anyOf: leaves.map((item) => ({ ...item })) } }] }
}
return { anyOf: [...leaves, { type: "array", items: permissiveValueSchema(depth - 1) }] }
}
function permissiveItemSchema(existing = {}) {
return { ...existing, ...permissiveValueSchema(PERMISSIVE_ARRAY_DEPTH) }
}
function mergeItems(fromCombo, existing) {
if (!existing || Object.keys(existing).length === 0) return fromCombo
// Keep constraints already on the typeless items node (e.g. maxLength).
return { ...fromCombo, ...existing }
}
function fillGeminiArrayItems(node) {
if (!nodeDeclaresArray(node)) return
if (Array.isArray(node.items)) {
appendSchemaHint(node, TUPLE_ITEMS_HINT)
return
}
const existing = (node.items && typeof node.items === "object" && !Array.isArray(node.items))
? { ...node.items }
: {}
if (Array.isArray(node.prefixItems)) {
appendSchemaHint(node, TUPLE_ITEMS_HINT)
if (!typelessItems(node.items)) return
// prefixItems alone still leaves sibling items missing; fill a rest schema.
const fromCombo = itemsFromCombinators(node)
if (fromCombo) node.items = mergeItems(fromCombo, existing)
else {
const inferred = inferItemsFromExisting(existing)
node.items = inferred || permissiveItemSchema(existing)
if (!inferred) appendSchemaHint(node, UNTYPED_ITEMS_HINT)
}
return
}
if (!typelessItems(node.items)) return
const fromCombo = itemsFromCombinators(node)
if (fromCombo) {
node.items = mergeItems(fromCombo, existing)
return
}
const inferred = inferItemsFromExisting(existing)
if (inferred) {
node.items = inferred
return
}
node.items = permissiveItemSchema(existing)
appendSchemaHint(node, UNTYPED_ITEMS_HINT)
}
const SCHEMA_CHILD_KEYS = [
"additionalProperties", "propertyNames", "contains", "if", "then", "else",
"not", "unevaluatedProperties", "unevaluatedItems", "items",
]
const SCHEMA_ARRAY_KEYS = ["anyOf", "oneOf", "allOf", "prefixItems"]
const SCHEMA_MAP_KEYS = ["properties", "patternProperties", "dependentSchemas", "$defs", "definitions"]
function walk(node) {
if (!node || typeof node !== "object") return
if (Array.isArray(node)) {
for (const item of node) walk(item)
return
}
// Children first so combinator branches are filled before we copy items up.
for (const key of SCHEMA_CHILD_KEYS) walk(node[key])
for (const key of SCHEMA_ARRAY_KEYS) {
if (Array.isArray(node[key])) for (const item of node[key]) walk(item)
}
for (const key of SCHEMA_MAP_KEYS) {
const map = node[key]
if (map && typeof map === "object" && !Array.isArray(map)) {
for (const child of Object.values(map)) walk(child)
}
}
fillGeminiArrayItems(node)
}
// Mutates and returns the schema tree so callers can write
// `ensureGeminiArrayItems(sanitizeInputSchema(raw))`.
export function ensureGeminiArrayItems(node) {
walk(node)
return node
}
+4 -1
View File
@@ -10,6 +10,7 @@ import { fileURLToPath } from "node:url"
import { createUsageReader } from "./usage.mjs"
import { sanitizePatternFields } from "./re2-pattern.mjs"
import { startLogin } from "./login.mjs"
import { ensureGeminiArrayItems } from "./array-items.mjs"
const PROVIDER_ID = "agy-cli"
// Client tools reach the session through a private `nc` placed first on agy's
@@ -2764,6 +2765,7 @@ function appendSchemaHint(node, hint) {
}
}
// Sanitize JSON Schema constructs that agy's ACP -> Google Code Assist translator
// converts into invalid Schema protos (e.g. union types leaving stale array/object
// keywords, or non-string/empty enum entries producing `enum[0]: cannot be empty`).
@@ -2902,7 +2904,7 @@ function normalizeTools(body) {
if (!rawSchema || typeof rawSchema !== "object" || Array.isArray(rawSchema)) {
throw new UnsupportedContent(`an invalid schema for tool ${tool.name}`)
}
const inputSchema = sanitizeInputSchema(rawSchema)
const inputSchema = ensureGeminiArrayItems(sanitizeInputSchema(rawSchema))
tools.push({
name: tool.name,
description: typeof tool.description === "string" ? tool.description : "",
@@ -4583,3 +4585,4 @@ process.once("exit", () => {
export { sanitizeInputSchema }
export default { id: PROVIDER_ID, server: AntigravityBridgePlugin }
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-agy-cli-auth",
"version": "0.1.14",
"version": "0.1.15",
"description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI",
"type": "module",
"main": "./opencode.mjs",
@@ -19,7 +19,8 @@
"README.en.md",
"LICENSE",
"NOTICE.md",
"re2-pattern.mjs"
"re2-pattern.mjs",
"array-items.mjs"
],
"keywords": [
"magpie",
+284
View File
@@ -0,0 +1,284 @@
// Standalone checks for Gemini array `items` filling. Run with:
// node test/array-items-unit.mjs
import { ensureGeminiArrayItems, PERMISSIVE_LEAF_TYPES, PERMISSIVE_ARRAY_DEPTH } from "../array-items.mjs"
let failed = 0
function check(name, ok, detail) {
if (ok) {
console.log(`ok ${name}`)
return
}
failed++
console.error(`FAIL ${name}${detail ? " :: " + detail : ""}`)
}
function sanitize(schema) {
return ensureGeminiArrayItems(schema)
}
function permissiveTypes(items) {
return (items?.anyOf || []).map((branch) => branch.type)
}
function isPermissiveItems(items, depth = PERMISSIVE_ARRAY_DEPTH) {
const types = permissiveTypes(items)
if (JSON.stringify(types) !== JSON.stringify([...PERMISSIVE_LEAF_TYPES, "array"])) return false
const arrayBranch = items.anyOf[types.indexOf("array")]
if (depth <= 1) {
return JSON.stringify((arrayBranch.items?.anyOf || []).map((branch) => branch.type)) === JSON.stringify(PERMISSIVE_LEAF_TYPES)
}
return isPermissiveItems(arrayBranch.items, depth - 1)
}
function countArrayDepth(items) {
let depth = 0
let node = items
while (node?.anyOf) {
const arrayBranch = node.anyOf.find((branch) => branch && branch.type === "array")
if (!arrayBranch) break
depth++
node = arrayBranch.items
}
return depth
}
// Production shape: Pydantic Optional[list[str]] as seen on minimax-code input_images.
{
const production = sanitize({
type: "object",
properties: {
input_images: {
anyOf: [
{ items: { type: "string" }, type: "array" },
{ type: "null" },
],
default: null,
title: "Input Images",
type: "array",
},
},
})
const images = production.properties.input_images
check("Pydantic optional array (production input_images) gets typed items from anyOf",
images.type === "array"
&& images.items && images.items.type === "string"
&& Array.isArray(images.anyOf)
&& images.anyOf.some((branch) => branch && branch.type === "null"),
JSON.stringify(images))
check("production input_images sanitizer is idempotent",
JSON.stringify(sanitize(production)) === JSON.stringify(production))
}
// Do not narrow a string|list union by stamping type: array on the parent.
{
const schema = sanitize({
type: "object",
properties: {
path: {
anyOf: [
{ type: "string" },
{ type: "array", items: { type: "string" } },
],
},
list_or_string: {
anyOf: [
{ type: "array", items: { type: "string" } },
{ type: "string" },
],
},
},
})
const path = schema.properties.path
const flipped = schema.properties.list_or_string
check("string|list union keeps both branches and does not get type:array",
path.type === undefined
&& Array.isArray(path.anyOf)
&& path.anyOf[0].type === "string"
&& path.anyOf[1].type === "array"
&& path.anyOf[1].items.type === "string",
JSON.stringify(path))
check("list|string union (array first) is also left un-narrowed",
flipped.type === undefined
&& flipped.anyOf[0].type === "array"
&& flipped.anyOf[1].type === "string",
JSON.stringify(flipped))
}
// Do not drop null from an array|null anyOf that has no top-level type.
{
const schema = sanitize({
type: "object",
properties: {
maybe: {
anyOf: [
{ type: "array", items: { type: "string" } },
{ type: "null" },
],
default: null,
},
},
})
const maybe = schema.properties.maybe
check("array|null anyOf without a top-level type keeps null and is not forced to type:array",
maybe.type === undefined
&& maybe.anyOf.some((branch) => branch && branch.type === "null")
&& maybe.anyOf.some((branch) => branch && branch.type === "array"),
JSON.stringify(maybe))
}
// Bare array / items:true get a least-narrowing typed items + a hint, not string.
{
const schema = sanitize({
type: "object",
properties: {
bare: { type: "array" },
items_true: { type: "array", items: true },
empty_items: { type: "array", items: {} },
desc_only: { type: "array", items: { description: "paths" } },
from_enum: { type: "array", items: { enum: ["a", "b"] } },
from_props: { type: "array", items: { properties: { url: { type: "string" } } } },
tuple: { type: "array", items: [{ type: "string" }, { type: "number" }] },
prefix: { type: "array", prefixItems: [{ type: "string" }, { type: "number" }] },
nullable: { type: ["array", "null"] },
nested: {
type: "array",
items: {
type: "object",
properties: {
tags: { type: "array" },
},
},
},
contains_arr: { type: "object", contains: { type: "array" } },
},
})
const p = schema.properties
check("bare array gets permissive typed items and a hint, not string",
isPermissiveItems(p.bare.items)
&& (p.bare.description || "").includes("array items were untyped"),
JSON.stringify(p.bare))
check("permissive items allow several levels of nested arrays, not just one",
// Literal 8: reading PERMISSIVE_ARRAY_DEPTH here would stay green if it were 1.
countArrayDepth(p.bare.items) === 8,
String(countArrayDepth(p.bare.items)))
check("items:true gets permissive typed items and a hint",
isPermissiveItems(p.items_true.items)
&& (p.items_true.description || "").includes("array items were untyped"),
JSON.stringify(p.items_true))
check("empty items object gets permissive types",
isPermissiveItems(p.empty_items.items),
JSON.stringify(p.empty_items))
check("description-only items keep the hint and gain permissive types",
isPermissiveItems(p.desc_only.items)
&& p.desc_only.items.description === "paths",
JSON.stringify(p.desc_only))
check("items type is inferred from enum without inventing string on a typeless parent",
p.from_enum.items.type === "string" && JSON.stringify(p.from_enum.items.enum) === JSON.stringify(["a", "b"]),
JSON.stringify(p.from_enum))
check("items with properties keep those properties and do not gain a forced type:object",
p.from_props.items.type === undefined && p.from_props.items.properties.url.type === "string",
JSON.stringify(p.from_props))
check("tuple items are left as a list, with a hint, not collapsed to the first item",
Array.isArray(p.tuple.items)
&& p.tuple.items.length === 2
&& p.tuple.items[0].type === "string"
&& p.tuple.items[1].type === "number"
&& (p.tuple.description || "").includes("tuple items were left as a list"),
JSON.stringify(p.tuple))
check("prefixItems tuples are left in place with a hint and gain a sibling items field",
Array.isArray(p.prefix.prefixItems)
&& p.prefix.prefixItems.length === 2
&& p.prefix.items
&& (p.prefix.description || "").includes("tuple items were left as a list"),
JSON.stringify(p.prefix))
check("nullable array type is kept, and items are filled without dropping null",
JSON.stringify(p.nullable.type) === JSON.stringify(["array", "null"])
&& p.nullable.items,
JSON.stringify(p.nullable))
check("nested typeless array items are filled recursively without forcing string when untyped",
isPermissiveItems(p.nested.items.properties.tags.items),
JSON.stringify(p.nested))
check("contains also receives filled array items",
isPermissiveItems(p.contains_arr.contains.items),
JSON.stringify(p.contains_arr))
check("array-items sanitizer is idempotent",
JSON.stringify(sanitize(schema)) === JSON.stringify(schema))
}
{
const schema = sanitize({
type: "array",
anyOf: [
{ type: "array", items: { type: "string" } },
{ type: "array", items: { type: "number" } },
],
})
check("multiple array combinator branches become an anyOf of their items, not just the first",
schema.items && Array.isArray(schema.items.anyOf)
&& schema.items.anyOf.some((branch) => branch && branch.type === "string")
&& schema.items.anyOf.some((branch) => branch && branch.type === "number"),
JSON.stringify(schema))
}
{
const schema = sanitize({
type: "array",
items: { maxLength: 3 },
anyOf: [
{ type: "array", items: { type: "string" } },
],
})
check("existing typeless items constraints are merged, not overwritten, when copying combinator items",
schema.items.type === "string" && schema.items.maxLength === 3,
JSON.stringify(schema))
}
{
const schema = sanitize({
type: "array",
anyOf: [
{ type: "array", items: { type: "string" } },
{},
],
})
check("anyOf with a typeless {} branch does not gain global items:string",
isPermissiveItems(schema.items)
&& Array.isArray(schema.anyOf)
&& schema.anyOf.some((branch) => branch && Object.keys(branch).length === 0)
&& (schema.description || "").includes("array items were untyped"),
JSON.stringify(schema))
}
{
const schema = sanitize({
type: "array",
anyOf: [
{ type: "array", items: { type: "string" } },
{ type: "array" },
],
})
const onlyString = schema.items?.type === "string" && !schema.items.anyOf
const allowsNumber = isPermissiveItems(schema.items)
|| (Array.isArray(schema.items?.anyOf) && schema.items.anyOf.some((branch) => (
branch?.type === "number" || isPermissiveItems(branch) || Array.isArray(branch?.anyOf)
)))
check("anyOf with an items-less array branch does not narrow to items:string",
!onlyString && allowsNumber,
JSON.stringify(schema))
}
{
const schema = sanitize({
type: "array",
items: { enum: [1, 1.5, null] },
})
check("mixed numeric enum does not get type:integer from the first sample",
schema.items.type === "number" && JSON.stringify(schema.items.enum) === JSON.stringify([1, 1.5, null]),
JSON.stringify(schema))
}
if (failed) {
console.error(`\n${failed} check(s) failed`)
process.exit(1)
}
console.log("\nALL OK")
+32
View File
@@ -1853,6 +1853,14 @@ for (const location of ["inline", "system", "developer", "user"]) {
union_arr: { type: ["object", "array"], items: { type: "string" } },
stale_items: { type: ["string", "number"], items: { type: "string" }, properties: { bad: { type: "string" } } },
num_enum: { type: "integer", enum: [0, 1, 2] },
input_images: {
type: "array",
anyOf: [
{ type: "array", items: { type: "string" } },
{ type: "null" },
],
},
bare_list: { type: "array" },
},
required: ["union_arr", "missing_field"],
},
@@ -1885,6 +1893,30 @@ for (const location of ["inline", "system", "developer", "user"]) {
JSON.stringify(initTool?.inputSchema?.required) === JSON.stringify(["union_arr"]),
JSON.stringify(initTool?.inputSchema))
const filledImages = initTool?.inputSchema?.properties?.input_images
const filledBare = initTool?.inputSchema?.properties?.bare_list
const bareDepth = (() => {
let depth = 0
let node = filledBare?.items
while (node?.anyOf) {
const arrayBranch = node.anyOf.find(branch => branch && branch.type === "array")
if (!arrayBranch) break
depth++
node = arrayBranch.items
}
return depth
})()
check("request-path array items fills production input_images and a bare array",
filledImages?.items?.type === "string" &&
Array.isArray(filledImages?.anyOf) &&
filledImages.anyOf.some(branch => branch && branch.type === "null") &&
(filledBare?.description || "").includes("array items were untyped") &&
!/gemini/i.test(JSON.stringify(initTool?.inputSchema || {})),
JSON.stringify({ input_images: filledImages, bare_list: filledBare }))
check("request-path permissive items have a fixed depth of 8",
bareDepth === 8,
String(bareDepth))
const pdfRes = await callFetch({
model,
messages: [{
+3
View File
@@ -31,6 +31,7 @@ export const REPO_DIR = path.dirname(path.dirname(fileURLToPath(import.meta.url)
export const INDEX_FILE = process.env.AGY_BRIDGE_TEST_INDEX || path.join(REPO_DIR, "index.mjs")
export const USAGE_FILE = path.join(REPO_DIR, "usage.mjs")
export const PLATFORM_FILE = path.join(REPO_DIR, "platform.mjs")
export const ARRAY_ITEMS_FILE = path.join(REPO_DIR, "array-items.mjs")
export const LOGIN_FILE = path.join(REPO_DIR, "login.mjs")
export const RE2_PATTERN_FILE = path.join(REPO_DIR, "re2-pattern.mjs")
export const MESSAGES_URL = "agy://local/v1/messages"
@@ -487,6 +488,7 @@ export async function createBridgeKit(options = {}) {
const indexUrl = pathToFileURL(path.join(REPO_DIR, "index.mjs")).href
const usageUrl = pathToFileURL(USAGE_FILE).href
const platformUrl = pathToFileURL(PLATFORM_FILE).href
const arrayItemsUrl = pathToFileURL(ARRAY_ITEMS_FILE).href
const loginUrl = pathToFileURL(LOGIN_FILE).href
const re2Url = pathToFileURL(RE2_PATTERN_FILE).href
const linker = (specifier) => {
@@ -497,6 +499,7 @@ export async function createBridgeKit(options = {}) {
let module
if (key === "./usage.mjs") module = sourceModule(USAGE_FILE, "", usageUrl)
else if (key === "./platform.mjs") module = sourceModule(PLATFORM_FILE, "", platformUrl)
else if (key === "./array-items.mjs") module = sourceModule(ARRAY_ITEMS_FILE, "", arrayItemsUrl)
else if (key === "./login.mjs") module = sourceModule(LOGIN_FILE, "", loginUrl)
else if (key === "./re2-pattern.mjs") module = sourceModule(RE2_PATTERN_FILE, "", re2Url)
else if (key.startsWith("node:")) module = builtinModule(key, overrides[key])