agy-cli 0.1.28: tool schemas with $ref/allOf/oneOf reach the model with their fields (#1042)
Tool schemas that use $ref, allOf or oneOf now reach the model with all their fields (expandToolSchema).
Nullable unions are lowered to type:[X,"null"]. Inlining is capped by depth (counted only along $ref and allOf), by 8192 nodes and by 256 KiB. A tool with no schema gets a plain object. The ToolSearch fallback was dropped.
Run at 80d19737 merged with main 16e753e8: `bun test packages/agy-cli` 16 pass, check ok.
Broken by hand: lowering a nullable union to a single type makes 1 test fail, and removing the byte cap makes 1 test fail.
Not tried: a real agy turn with these schemas.
Co-authored-by: tungloong <tungloong@users.noreply.github.com>
This commit is contained in:
@@ -21,6 +21,7 @@ for (const [name, mocks] of [
|
||||
["usage.mjs", true],
|
||||
["catalog.mjs", false],
|
||||
["step-usage.mjs", false],
|
||||
["tool-schema.mjs", false],
|
||||
["usage-settlement.mjs", false],
|
||||
["repeat-batch.mjs", false],
|
||||
["conversation-key.mjs", false],
|
||||
|
||||
@@ -11,6 +11,7 @@ import { createUsageReader } from "./usage.mjs"
|
||||
import { sanitizePatternFields } from "./re2-pattern.mjs"
|
||||
import { startLogin } from "./login.mjs"
|
||||
import { ensureGeminiArrayItems } from "./array-items.mjs"
|
||||
import { expandToolSchema } from "./tool-schema.mjs"
|
||||
import { cloak, hint, turnsAway } from "./cloak.mjs"
|
||||
import { modelUsageCursor, modelUsageAfter, sessionDbPath } from "./step-usage.mjs"
|
||||
|
||||
@@ -3436,7 +3437,7 @@ function normalizeTools(body) {
|
||||
if (!rawSchema || typeof rawSchema !== "object" || Array.isArray(rawSchema)) {
|
||||
throw new UnsupportedContent(`an invalid schema for tool ${tool.name}`)
|
||||
}
|
||||
const inputSchema = ensureGeminiArrayItems(sanitizeInputSchema(rawSchema))
|
||||
const inputSchema = ensureGeminiArrayItems(sanitizeInputSchema(expandToolSchema(rawSchema)))
|
||||
tools.push({
|
||||
name: tool.name,
|
||||
description: typeof tool.description === "string" ? tool.description : "",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-agy-cli-auth",
|
||||
"version": "0.1.27",
|
||||
"version": "0.1.28",
|
||||
"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",
|
||||
@@ -15,6 +15,7 @@
|
||||
"login.mjs",
|
||||
"mcp-server.mjs",
|
||||
"step-usage.mjs",
|
||||
"tool-schema.mjs",
|
||||
"usage.mjs",
|
||||
"README.md",
|
||||
"README.en.md",
|
||||
|
||||
@@ -1972,10 +1972,39 @@ for (const location of ["inline", "system", "developer", "user"]) {
|
||||
required: ["union_arr", "missing_field"],
|
||||
},
|
||||
}
|
||||
const refUnionTool = {
|
||||
name: "ref_union_schema",
|
||||
description: "Discriminated union + $ref check",
|
||||
input_schema: {
|
||||
type: "object",
|
||||
$defs: {
|
||||
Coords: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: { x: { type: "number" }, y: { type: "number" } },
|
||||
required: ["x", "y"],
|
||||
},
|
||||
},
|
||||
oneOf: [
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: { method: { const: "click" }, params: { $ref: "#/$defs/Coords" } },
|
||||
required: ["method", "params"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: { method: { const: "screenshot" } },
|
||||
required: ["method"],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
const syncRes = await callFetch({
|
||||
model,
|
||||
stream: false,
|
||||
tools: [trickyTool],
|
||||
tools: [trickyTool, refUnionTool, { name: "ToolSearch" }],
|
||||
messages: [{
|
||||
role: "user",
|
||||
content: [
|
||||
@@ -1986,7 +2015,10 @@ for (const location of ["inline", "system", "developer", "user"]) {
|
||||
}],
|
||||
})
|
||||
const syncMsg = await syncRes.json()
|
||||
const initTool = inits().at(-1)?.tools?.[0]
|
||||
const initTools = inits().at(-1)?.tools ?? []
|
||||
const initTool = initTools[0]
|
||||
const initRefUnion = initTools[1]
|
||||
const initToolSearch = initTools[2]
|
||||
const lastUser = lastOf("user")
|
||||
check("stream: false returns aggregated JSON message with image and text document",
|
||||
syncRes.status === 200 && syncMsg.type === "message" && lastUser.images === 1 && lastUser.text.includes("DOC_MARKER_42"),
|
||||
@@ -2023,6 +2055,15 @@ for (const location of ["inline", "system", "developer", "user"]) {
|
||||
check("request-path permissive items have a fixed depth of 8",
|
||||
bareDepth === 8,
|
||||
String(bareDepth))
|
||||
check("request-path expandToolSchema resolves $defs/$ref, lifts root oneOf object unions, preserves boolean additionalProperties, and leaves schema-less ToolSearch empty",
|
||||
initRefUnion?.inputSchema?.$defs === undefined &&
|
||||
initRefUnion?.inputSchema?.oneOf === undefined &&
|
||||
initRefUnion?.inputSchema?.additionalProperties === false &&
|
||||
JSON.stringify(initRefUnion?.inputSchema?.properties?.method?.enum) === JSON.stringify(["click", "screenshot"]) &&
|
||||
JSON.stringify(initRefUnion?.inputSchema?.properties?.params?.required) === JSON.stringify(["x", "y"]) &&
|
||||
JSON.stringify(initToolSearch?.inputSchema) === JSON.stringify({ type: "object", properties: {} }) &&
|
||||
!/gemini/i.test(JSON.stringify(initRefUnion?.inputSchema || {})),
|
||||
JSON.stringify({ refUnion: initRefUnion?.inputSchema, toolSearch: initToolSearch?.inputSchema }))
|
||||
|
||||
const pdfRes = await callFetch({
|
||||
model,
|
||||
|
||||
@@ -36,6 +36,7 @@ export const CLOAK_FILE = path.join(REPO_DIR, "cloak.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 STEP_USAGE_FILE = path.join(REPO_DIR, "step-usage.mjs")
|
||||
export const TOOL_SCHEMA_FILE = path.join(REPO_DIR, "tool-schema.mjs")
|
||||
export const MESSAGES_URL = "agy://local/v1/messages"
|
||||
export const COUNT_TOKENS_URL = "agy://local/v1/messages/count_tokens"
|
||||
export const CATALOG_TTL_MS = 5 * 60 * 1000
|
||||
@@ -329,6 +330,7 @@ class FakeAgy {
|
||||
return Promise.all(replies)
|
||||
},
|
||||
async tool(name, args) { return (await this.tools([[name, args]]))[0] },
|
||||
listTools() { return self.control({ kind: "list" }) },
|
||||
waitCancel() {
|
||||
if (self.cancelPending) return Promise.resolve()
|
||||
return new Promise((resolve) => self.cancelWaiters.push(resolve))
|
||||
@@ -507,6 +509,7 @@ export async function createBridgeKit(options = {}) {
|
||||
const loginUrl = pathToFileURL(LOGIN_FILE).href
|
||||
const re2Url = pathToFileURL(RE2_PATTERN_FILE).href
|
||||
const stepUsageUrl = pathToFileURL(STEP_USAGE_FILE).href
|
||||
const toolSchemaUrl = pathToFileURL(TOOL_SCHEMA_FILE).href
|
||||
const linker = (specifier) => {
|
||||
const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER
|
||||
? specifier
|
||||
@@ -520,6 +523,7 @@ export async function createBridgeKit(options = {}) {
|
||||
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 === "./step-usage.mjs") module = sourceModule(STEP_USAGE_FILE, "", stepUsageUrl)
|
||||
else if (key === "./tool-schema.mjs") module = sourceModule(TOOL_SCHEMA_FILE, "", toolSchemaUrl)
|
||||
else if (key.startsWith("node:")) module = builtinModule(key, overrides[key])
|
||||
else throw new Error(`testkit: 未登记的依赖 ${specifier}`)
|
||||
cache.set(key, module)
|
||||
|
||||
@@ -0,0 +1,689 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { expandToolSchema } from "../tool-schema.mjs"
|
||||
import { sanitizeInputSchema } from "../index.mjs"
|
||||
import { ensureGeminiArrayItems } from "../array-items.mjs"
|
||||
import { baseBody, createBridgeKit, readSse } from "./testkit.mjs"
|
||||
|
||||
const fullPipeline = (schema) => ensureGeminiArrayItems(sanitizeInputSchema(expandToolSchema(schema)))
|
||||
|
||||
test("local $ref resolves $defs and definitions with RFC 6901 escapes and preserves sibling overrides", () => {
|
||||
const input = {
|
||||
$schema: "https://json-schema.org/draft/2020-12/schema",
|
||||
type: "object",
|
||||
$defs: {
|
||||
"Options/a~b": {
|
||||
type: "object",
|
||||
description: "Base options",
|
||||
default: { path: "." },
|
||||
properties: {
|
||||
path: { type: "string", pattern: "^[^\\u0000]*$" },
|
||||
tags: { type: "array" },
|
||||
},
|
||||
required: ["path"],
|
||||
},
|
||||
},
|
||||
definitions: { Count: { type: "integer", minimum: 1, default: 2 } },
|
||||
properties: {
|
||||
options: { $ref: "#/$defs/Options~1a~0b", description: "Search options", default: { path: "/src" } },
|
||||
count: { $ref: "#/definitions/Count", maximum: 10, default: 5 },
|
||||
},
|
||||
}
|
||||
const original = structuredClone(input)
|
||||
const schema = fullPipeline(input)
|
||||
assert.equal(schema.$defs, undefined)
|
||||
assert.equal(schema.definitions, undefined)
|
||||
assert.equal(schema.$schema, undefined)
|
||||
assert.equal(schema.properties.options.type, "object")
|
||||
assert.equal(schema.properties.options.properties.path.type, "string")
|
||||
assert.equal(schema.properties.options.properties.path.pattern, "^[^\\x{0000}]*$")
|
||||
assert.ok(Array.isArray(schema.properties.options.properties.tags.items?.anyOf))
|
||||
assert.deepEqual(schema.properties.options.required, ["path"])
|
||||
assert.match(schema.properties.options.description, /^Search options \(Base options\)$/)
|
||||
assert.deepEqual(schema.properties.options.default, { path: "/src" })
|
||||
assert.equal(schema.properties.count.minimum, 1)
|
||||
assert.equal(schema.properties.count.maximum, 10)
|
||||
assert.equal(schema.properties.count.default, 5)
|
||||
assert.deepEqual(input, original)
|
||||
})
|
||||
|
||||
test("allOf combines required fields, intersects bounds and enums, and prunes dangling required keys", () => {
|
||||
const schema = fullPipeline({
|
||||
allOf: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
count: { type: "integer", minimum: 1, maximum: 20 },
|
||||
mode: { type: "string", enum: ["read", "write", "admin"] },
|
||||
},
|
||||
required: ["count"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
count: { type: "integer", minimum: 5, maximum: 10 },
|
||||
mode: { type: "string", enum: ["write", "admin", "audit"] },
|
||||
path: { type: "string" },
|
||||
},
|
||||
required: ["path", "missing"],
|
||||
},
|
||||
],
|
||||
})
|
||||
assert.equal(schema.allOf, undefined)
|
||||
assert.deepEqual(schema.required, ["count", "path"])
|
||||
assert.equal(schema.properties.count.minimum, 5)
|
||||
assert.equal(schema.properties.count.maximum, 10)
|
||||
assert.deepEqual(schema.properties.mode.enum, ["write", "admin"])
|
||||
})
|
||||
|
||||
test("recursive and unresolved $ref terminate with explicit hints", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
$defs: {
|
||||
Node: { type: "object", properties: { next: { $ref: "#/$defs/Node" } } },
|
||||
},
|
||||
properties: {
|
||||
head: { $ref: "#/$defs/Node" },
|
||||
remote: { $ref: "https://example.com/schema.json" },
|
||||
missing: { $ref: "#/$defs/Unknown" },
|
||||
},
|
||||
})
|
||||
assert.equal(schema.properties.head.type, "object")
|
||||
assert.equal(schema.properties.head.properties.next.type, "object")
|
||||
assert.equal(schema.properties.head.properties.next.properties, undefined)
|
||||
assert.match(schema.properties.head.properties.next.description, /Recursive schema/)
|
||||
assert.equal(schema.properties.remote.type, undefined)
|
||||
assert.equal(schema.properties.missing.type, undefined)
|
||||
assert.match(schema.properties.remote.description, /Unresolved schema reference/)
|
||||
assert.match(schema.properties.missing.description, /Unresolved schema reference/)
|
||||
})
|
||||
|
||||
test("reference expansion is bounded for deep and exponentially shared DAGs", () => {
|
||||
const $defs = { End: { type: "string" } }
|
||||
for (let i = 0; i < 40; i++) {
|
||||
$defs[`Node${i}`] = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: { $ref: i === 39 ? "#/$defs/End" : `#/$defs/Node${i + 1}` },
|
||||
b: { $ref: i === 39 ? "#/$defs/End" : `#/$defs/Node${i + 1}` },
|
||||
},
|
||||
}
|
||||
}
|
||||
const schema = fullPipeline({ type: "object", $defs, properties: { root: { $ref: "#/$defs/Node0" } } })
|
||||
const text = JSON.stringify(schema)
|
||||
assert.match(text, /Schema expansion limit/)
|
||||
assert.ok(text.length < 300_000, String(text.length))
|
||||
assert.equal(schema.properties.root.type, "object")
|
||||
// Cut-off subtrees keep their object type instead of becoming strings.
|
||||
assert.doesNotMatch(text, /"type":"string","description":"Schema expansion limit/)
|
||||
assert.match(text, /"type":"object","description":"Schema expansion limit/)
|
||||
|
||||
const tripleDefs = { End: { type: "string" } }
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const next = i === 39 ? "#/$defs/End" : `#/$defs/T${i + 1}`
|
||||
tripleDefs[`T${i}`] = { type: "object", properties: { a: { $ref: next }, b: { $ref: next }, c: { $ref: next } } }
|
||||
}
|
||||
const tripleText = JSON.stringify(fullPipeline({ type: "object", $defs: tripleDefs, properties: { root: { $ref: "#/$defs/T0" } } }))
|
||||
assert.match(tripleText, /Schema expansion limit/)
|
||||
assert.ok(tripleText.length < 300_000, String(tripleText.length))
|
||||
})
|
||||
|
||||
test("const discriminators, boolean schemas, and additionalProperties booleans vs dictionary schemas are handled cleanly", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
mode: { const: "read" },
|
||||
code: { const: 7 },
|
||||
forbidden: false,
|
||||
itemsTrue: { type: "array", items: true },
|
||||
strictNested: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: { ok: { type: "boolean" } },
|
||||
},
|
||||
openDict: {
|
||||
type: "object",
|
||||
description: "CSS style overrides",
|
||||
additionalProperties: true,
|
||||
},
|
||||
envMap: {
|
||||
type: "object",
|
||||
description: "Environment variables",
|
||||
additionalProperties: { type: "string" },
|
||||
},
|
||||
},
|
||||
})
|
||||
assert.equal(schema.additionalProperties, false)
|
||||
assert.equal(schema.description, undefined)
|
||||
assert.deepEqual(schema.properties.mode, { type: "string", enum: ["read"] })
|
||||
assert.equal(schema.properties.code.const, undefined)
|
||||
assert.equal(schema.properties.code.type, "integer")
|
||||
assert.match(schema.properties.code.description, /Must equal: 7/)
|
||||
assert.equal(schema.properties.forbidden.type, undefined)
|
||||
assert.match(schema.properties.forbidden.description, /No value is allowed/)
|
||||
assert.ok(Array.isArray(schema.properties.itemsTrue.items?.anyOf))
|
||||
assert.equal(schema.properties.strictNested.additionalProperties, false)
|
||||
assert.equal(schema.properties.openDict.additionalProperties, true)
|
||||
assert.match(schema.properties.openDict.description, /Accepts arbitrary additional key-value properties/)
|
||||
assert.deepEqual(schema.properties.envMap.additionalProperties, { type: "string" })
|
||||
assert.match(schema.properties.envMap.description, /Additional properties: string/)
|
||||
})
|
||||
|
||||
test("root and nested discriminated object unions lift properties, intersect required, and union method enums", () => {
|
||||
const cuaLike = fullPipeline({
|
||||
type: "object",
|
||||
oneOf: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
method: { type: "string", const: "screenshot" },
|
||||
params: {
|
||||
type: "object",
|
||||
properties: { displayId: { type: "number" } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
required: ["method"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
method: { type: "string", const: "click" },
|
||||
params: {
|
||||
anyOf: [
|
||||
{
|
||||
type: "object",
|
||||
properties: { x: { type: "number" }, y: { type: "number" } },
|
||||
required: ["x", "y"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: { target: { type: "string" } },
|
||||
required: ["target"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
required: ["method", "params"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
assert.equal(cuaLike.oneOf, undefined)
|
||||
assert.equal(cuaLike.anyOf, undefined)
|
||||
assert.equal(cuaLike.type, "object")
|
||||
assert.equal(cuaLike.additionalProperties, false)
|
||||
assert.deepEqual(cuaLike.required, ["method"])
|
||||
assert.deepEqual(cuaLike.properties.method, { type: "string", enum: ["screenshot", "click"] })
|
||||
assert.equal(cuaLike.properties.params.type, "object")
|
||||
assert.deepEqual(Object.keys(cuaLike.properties.params.properties).sort(), ["displayId", "target", "x", "y"])
|
||||
assert.equal(cuaLike.properties.params.required, undefined)
|
||||
assert.match(cuaLike.description, /Variants:/)
|
||||
})
|
||||
|
||||
test("nullable Pydantic Optional fields and heterogeneous array item unions stay lossless and idempotent", () => {
|
||||
const input = {
|
||||
type: "object",
|
||||
$defs: {
|
||||
Filter: {
|
||||
type: "object",
|
||||
properties: { tag: { type: "string" } },
|
||||
required: ["tag"],
|
||||
},
|
||||
},
|
||||
properties: {
|
||||
colorScheme: {
|
||||
description: "Preferred theme",
|
||||
anyOf: [{ type: "string", enum: ["light", "dark"] }, { type: "null" }],
|
||||
},
|
||||
plainNullable: {
|
||||
anyOf: [{ type: "string" }, { type: "null" }],
|
||||
},
|
||||
filter: {
|
||||
description: "Filter spec",
|
||||
anyOf: [{ $ref: "#/$defs/Filter" }, { type: "null" }],
|
||||
},
|
||||
mode: {
|
||||
anyOf: [{ type: "string", const: "auto" }, { type: "string" }],
|
||||
},
|
||||
order: {
|
||||
type: "array",
|
||||
items: {
|
||||
anyOf: [
|
||||
{ type: "string" },
|
||||
{
|
||||
type: "object",
|
||||
properties: { type: { const: "divider" } },
|
||||
required: ["type"],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
const once = fullPipeline(input)
|
||||
const twice = fullPipeline(once)
|
||||
|
||||
assert.deepEqual(once.properties.colorScheme.type, ["string", "null"])
|
||||
assert.equal(once.properties.colorScheme.enum, undefined)
|
||||
assert.equal(once.properties.colorScheme.description, 'Preferred theme (Allowed values: "light", "dark", null)')
|
||||
assert.deepEqual(
|
||||
once.properties.colorScheme,
|
||||
fullPipeline({ description: "Preferred theme", type: ["string", "null"], enum: ["light", "dark", null] }),
|
||||
)
|
||||
|
||||
assert.deepEqual(once.properties.plainNullable, { type: ["string", "null"] })
|
||||
assert.deepEqual(once.properties.plainNullable, fullPipeline({ type: ["string", "null"] }))
|
||||
|
||||
assert.deepEqual(once.properties.filter.type, ["object", "null"])
|
||||
assert.deepEqual(once.properties.filter.properties, { tag: { type: "string" } })
|
||||
assert.deepEqual(once.properties.filter.required, ["tag"])
|
||||
assert.deepEqual(
|
||||
once.properties.filter,
|
||||
fullPipeline({
|
||||
description: "Filter spec",
|
||||
type: ["object", "null"],
|
||||
properties: { tag: { type: "string" } },
|
||||
required: ["tag"],
|
||||
}),
|
||||
)
|
||||
|
||||
assert.equal(once.properties.mode.type, "string")
|
||||
assert.equal(once.properties.mode.enum, undefined)
|
||||
assert.match(once.properties.mode.description, /Known values include: "auto"/)
|
||||
|
||||
// Heterogeneous string | object items must NOT be forced to type:"string".
|
||||
assert.equal(once.properties.order.items.type, undefined)
|
||||
assert.ok(Array.isArray(once.properties.order.items.anyOf))
|
||||
assert.deepEqual(once.properties.order.items.anyOf[1].properties.type, { type: "string", enum: ["divider"] })
|
||||
assert.match(once.properties.order.items.description, /Accepts anyOf: string \| \{ type: "divider" \}/)
|
||||
assert.doesNotMatch(JSON.stringify(once), /gemini/i)
|
||||
assert.deepEqual(twice, once)
|
||||
})
|
||||
|
||||
test("a 40-variant union over 4 shared $defs expands fully and lifts to the root", () => {
|
||||
const $defs = {}
|
||||
for (let d = 0; d < 4; d++) {
|
||||
$defs[`D${d}`] = {
|
||||
type: "object",
|
||||
properties: Object.fromEntries(Array.from({ length: 15 }, (_, i) => [`f${d}_${i}`, { type: "string" }])),
|
||||
}
|
||||
}
|
||||
const oneOf = Array.from({ length: 40 }, (_, v) => ({
|
||||
type: "object",
|
||||
properties: {
|
||||
kind: { const: `k${v}` },
|
||||
a: { $ref: "#/$defs/D0" },
|
||||
b: { $ref: "#/$defs/D1" },
|
||||
c: { $ref: "#/$defs/D2" },
|
||||
d: { $ref: "#/$defs/D3" },
|
||||
},
|
||||
required: ["kind"],
|
||||
}))
|
||||
const schema = fullPipeline({ type: "object", $defs, oneOf })
|
||||
const text = JSON.stringify(schema)
|
||||
assert.equal(schema.anyOf, undefined)
|
||||
assert.equal(schema.oneOf, undefined)
|
||||
assert.equal(schema.type, "object")
|
||||
assert.deepEqual(schema.required, ["kind"])
|
||||
assert.equal(schema.properties.kind.enum.length, 40)
|
||||
for (const [key, d] of [["a", 0], ["b", 1], ["c", 2], ["d", 3]]) {
|
||||
assert.equal(schema.properties[key].type, "object")
|
||||
assert.equal(Object.keys(schema.properties[key].properties).length, 15)
|
||||
assert.equal(schema.properties[key].properties[`f${d}_14`].type, "string")
|
||||
}
|
||||
assert.doesNotMatch(text, /Schema expansion limit|Recursive schema/)
|
||||
assert.ok(text.length < 20_000, String(text.length))
|
||||
})
|
||||
|
||||
test("ordinary properties never use the expansion budget", () => {
|
||||
const properties = Object.fromEntries(Array.from({ length: 2100 }, (_, i) => [`p${i}`, { type: "integer" }]))
|
||||
const schema = fullPipeline({ type: "object", properties })
|
||||
assert.equal(Object.keys(schema.properties).length, 2100)
|
||||
for (const value of Object.values(schema.properties)) assert.deepEqual(value, { type: "integer" })
|
||||
})
|
||||
|
||||
test("shared $ref expansions are separate copies", () => {
|
||||
const schema = expandToolSchema({
|
||||
type: "object",
|
||||
$defs: { P: { type: "object", properties: { x: { type: "number" } } } },
|
||||
properties: { a: { $ref: "#/$defs/P" }, b: { $ref: "#/$defs/P" }, c: { $ref: "#/$defs/P" } },
|
||||
})
|
||||
assert.deepEqual(schema.properties.b, schema.properties.c)
|
||||
assert.notEqual(schema.properties.b, schema.properties.c)
|
||||
assert.notEqual(schema.properties.b.properties, schema.properties.c.properties)
|
||||
schema.properties.b.properties.x.type = "string"
|
||||
assert.equal(schema.properties.c.properties.x.type, "number")
|
||||
})
|
||||
|
||||
test("recursive z.lazy trees keep the object type at the cycle and add no string type", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
$defs: {
|
||||
Node: {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
children: { type: "array", items: { $ref: "#/$defs/Node" } },
|
||||
},
|
||||
required: ["name"],
|
||||
},
|
||||
},
|
||||
properties: { tree: { $ref: "#/$defs/Node" } },
|
||||
})
|
||||
const tree = schema.properties.tree
|
||||
assert.equal(tree.type, "object")
|
||||
assert.deepEqual(tree.required, ["name"])
|
||||
assert.equal(tree.properties.children.type, "array")
|
||||
assert.equal(tree.properties.children.items.type, "object")
|
||||
assert.match(tree.properties.children.items.description, /Recursive schema/)
|
||||
assert.doesNotMatch(JSON.stringify(schema), /"type":"string","description":"Recursive/)
|
||||
})
|
||||
|
||||
test("closed prefixItems tuples keep their length and element types", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
properties: {
|
||||
pair: { type: "array", prefixItems: [{ type: "string" }, { type: "number" }], items: false },
|
||||
point: { type: "array", prefixItems: [{ type: "number" }, { type: "number" }], items: false, maxItems: 5 },
|
||||
empty: { type: "array", items: false },
|
||||
},
|
||||
})
|
||||
const { pair, point, empty } = schema.properties
|
||||
assert.equal(pair.maxItems, 2)
|
||||
assert.deepEqual(pair.items.anyOf, [{ type: "string" }, { type: "number" }])
|
||||
assert.equal(point.maxItems, 2)
|
||||
assert.deepEqual(point.items, { type: "number" })
|
||||
assert.equal(empty.maxItems, 0)
|
||||
assert.deepEqual(empty.items, { type: "string", description: "No value is allowed by the original schema." })
|
||||
assert.equal(empty.description, undefined)
|
||||
})
|
||||
|
||||
test("const literals: numeric and boolean unions keep their values, empty string and null get hints", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
properties: {
|
||||
version: { anyOf: [{ type: "number", const: 1 }, { type: "number", const: 2 }] },
|
||||
flag: { anyOf: [{ const: true }, { const: false }] },
|
||||
empty: { const: "" },
|
||||
nothing: { const: null },
|
||||
seven: { const: 7 },
|
||||
ratio: { const: 0.5 },
|
||||
on: { const: true },
|
||||
shape: { const: { a: 1 } },
|
||||
list: { const: [1, 2] },
|
||||
nullableConst: { type: ["string", "null"], const: "x" },
|
||||
allNull: { anyOf: [{ type: "null" }, { const: null }] },
|
||||
maybe: { anyOf: [{ type: "string", enum: ["a", "b"] }, { const: null }] },
|
||||
},
|
||||
})
|
||||
const p = schema.properties
|
||||
assert.equal(p.version.type, "number")
|
||||
assert.match(p.version.description, /Allowed values: 1, 2/)
|
||||
assert.equal(p.flag.type, "boolean")
|
||||
assert.match(p.flag.description, /Allowed values: true, false/)
|
||||
assert.equal(p.empty.type, "string")
|
||||
assert.equal(p.empty.enum, undefined)
|
||||
assert.match(p.empty.description, /Must equal: ""/)
|
||||
assert.deepEqual(p.nothing, { description: "Must be null." })
|
||||
assert.equal(p.seven.type, "integer")
|
||||
assert.match(p.seven.description, /Must equal: 7/)
|
||||
assert.equal(p.ratio.type, "number")
|
||||
assert.equal(p.on.type, "boolean")
|
||||
assert.match(p.on.description, /Must equal: true/)
|
||||
assert.equal(p.shape.type, "object")
|
||||
assert.match(p.shape.description, /Must equal: \{"a":1\}/)
|
||||
assert.equal(p.list.type, "array")
|
||||
assert.match(p.list.description, /Must equal: \[1,2\]/)
|
||||
assert.deepEqual(p.nullableConst, { type: "string", enum: ["x"] })
|
||||
assert.deepEqual(p.allNull, { description: "Must be null." })
|
||||
assert.deepEqual(p.maybe, { type: ["string", "null"], description: 'Allowed values: "a", "b", null' })
|
||||
// Standalone null leaves have no `"type": "null"` or `["null"]`.
|
||||
assert.doesNotMatch(JSON.stringify({ nothing: p.nothing, allNull: p.allNull }), /"type"/)
|
||||
})
|
||||
|
||||
test("variant hints keep per-variant descriptions and stay under a length cap", () => {
|
||||
const $defs = {}
|
||||
for (let d = 0; d < 3; d++) {
|
||||
$defs[`S${d}`] = {
|
||||
type: "object",
|
||||
properties: Object.fromEntries(Array.from({ length: 10 }, (_, i) => [`long_field_${d}_${i}`, { type: "string" }])),
|
||||
}
|
||||
}
|
||||
const oneOf = Array.from({ length: 25 }, (_, v) => ({
|
||||
type: "object",
|
||||
description: `Perform action ${v}\n with a long description that keeps going well past the snippet limit for sure`,
|
||||
properties: {
|
||||
action: { const: `act_${v}` },
|
||||
x: { $ref: "#/$defs/S0" },
|
||||
y: { $ref: "#/$defs/S1" },
|
||||
z: { $ref: "#/$defs/S2" },
|
||||
},
|
||||
required: ["action"],
|
||||
}))
|
||||
const schema = fullPipeline({ type: "object", $defs, oneOf })
|
||||
assert.ok(schema.description.length < 2500, String(schema.description.length))
|
||||
assert.match(schema.description, /^Variants: \{ action: "act_0", x\?: object/)
|
||||
assert.match(schema.description, /\(Perform action 0 with a long description/)
|
||||
assert.match(schema.description, /\| \.\.\. \(\+\d+ more\)$/)
|
||||
assert.equal(schema.properties.action.enum.length, 25)
|
||||
|
||||
const two = fullPipeline({
|
||||
oneOf: [
|
||||
{ type: "object", description: "Click at coordinates", properties: { method: { const: "click" } } },
|
||||
{ type: "object", description: "Take a screenshot", properties: { method: { const: "screenshot" } } },
|
||||
],
|
||||
})
|
||||
assert.match(two.description, /^Variants: \{ method\?: "click" \} \(Click at coordinates\) \| \{ method\?: "screenshot" \} \(Take a screenshot\)$/)
|
||||
})
|
||||
|
||||
test("true and false property schemas carry hints without a fabricated type", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
properties: {
|
||||
data: true,
|
||||
never: false,
|
||||
either: { anyOf: [true, { type: "string" }] },
|
||||
},
|
||||
})
|
||||
assert.deepEqual(schema.properties.data, { description: "Accepts any JSON value." })
|
||||
assert.deepEqual(schema.properties.never, { description: "No value is allowed by the original schema." })
|
||||
assert.equal(schema.properties.either.type, undefined)
|
||||
assert.match(schema.properties.either.description, /Accepts anyOf: any \| string/)
|
||||
})
|
||||
|
||||
test("cross-variant property collisions stay an anyOf with a summary", () => {
|
||||
const schema = fullPipeline({
|
||||
oneOf: [
|
||||
{ type: "object", properties: { value: { type: "string" }, ver: { const: 1 } } },
|
||||
{ type: "object", properties: { value: { type: "number" }, ver: { const: 2 } } },
|
||||
],
|
||||
})
|
||||
assert.equal(schema.properties.value.type, undefined)
|
||||
assert.deepEqual(schema.properties.value.anyOf, [{ type: "string" }, { type: "number" }])
|
||||
assert.match(schema.properties.value.description, /Accepts anyOf: string \| number/)
|
||||
assert.equal(schema.properties.ver.type, "integer")
|
||||
assert.match(schema.properties.ver.description, /Allowed values: 1, 2/)
|
||||
})
|
||||
|
||||
test("$ref to a schema map or a non-schema value is unresolved", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
$defs: { E: { type: "string", enum: ["a"] } },
|
||||
properties: {
|
||||
map: { $ref: "#/properties" },
|
||||
defs: { $ref: "#/$defs" },
|
||||
enumList: { $ref: "#/$defs/E/enum" },
|
||||
named: { $ref: "#/properties/properties" },
|
||||
properties: { type: "boolean" },
|
||||
real: { $ref: "#/$defs/E" },
|
||||
},
|
||||
})
|
||||
const p = schema.properties
|
||||
for (const key of ["map", "defs", "enumList"]) {
|
||||
assert.equal(p[key].type, undefined, key)
|
||||
assert.equal(p[key].properties, undefined, key)
|
||||
assert.match(p[key].description, /Unresolved schema reference/, key)
|
||||
}
|
||||
assert.deepEqual(p.named, { type: "boolean" })
|
||||
assert.deepEqual(p.real, { type: "string", enum: ["a"] })
|
||||
})
|
||||
|
||||
test("allOf narrows number with integer and flags type and enum conflicts", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
properties: {
|
||||
count: { allOf: [{ type: "number", minimum: 0 }, { type: "integer" }] },
|
||||
mixed: { allOf: [{ type: "string" }, { type: "number" }] },
|
||||
mode: { allOf: [{ type: "string", enum: ["a"] }, { type: "string", enum: ["b"] }] },
|
||||
},
|
||||
})
|
||||
assert.deepEqual(schema.properties.count, { type: "integer", minimum: 0 })
|
||||
assert.equal(schema.properties.mixed.type, "string")
|
||||
assert.match(schema.properties.mixed.description, /Conflicting type constraints in allOf: string vs number/)
|
||||
assert.equal(schema.properties.mode.enum, undefined)
|
||||
assert.match(schema.properties.mode.description, /Conflicting enum constraints in allOf/)
|
||||
})
|
||||
|
||||
test("deep plain schemas without $ref or allOf pass through untouched past depth 64", () => {
|
||||
let inner = { type: "integer", minimum: 1 }
|
||||
for (let i = 70; i >= 0; i--) {
|
||||
inner = { type: "object", properties: { [`l${i}`]: inner } }
|
||||
}
|
||||
const schema = fullPipeline(inner)
|
||||
assert.doesNotMatch(JSON.stringify(schema), /Schema expansion limit/)
|
||||
let cur = schema
|
||||
for (let i = 0; i <= 70; i++) cur = cur.properties[`l${i}`]
|
||||
assert.deepEqual(cur, { type: "integer", minimum: 1 })
|
||||
})
|
||||
|
||||
test("linear $ref and allOf chains stop at depth 64 even when node and byte counts are small", () => {
|
||||
const $defs = { N70: { type: "string" } }
|
||||
for (let i = 0; i < 70; i++) {
|
||||
$defs[`N${i}`] = { type: "object", properties: { next: { $ref: `#/$defs/N${i + 1}` } } }
|
||||
}
|
||||
const refChain = fullPipeline({ type: "object", $defs, properties: { head: { $ref: "#/$defs/N0" } } })
|
||||
const refText = JSON.stringify(refChain)
|
||||
assert.match(refText, /Schema expansion limit/)
|
||||
assert.ok(refText.length < 20_000, String(refText.length))
|
||||
|
||||
let allOfChain = { type: "object", properties: { leaf: { type: "string" } } }
|
||||
for (let i = 0; i < 70; i++) allOfChain = { allOf: [allOfChain] }
|
||||
const lowered = fullPipeline(allOfChain)
|
||||
assert.match(JSON.stringify(lowered), /Schema expansion limit/)
|
||||
})
|
||||
|
||||
test("inlined byte and node budgets independently cap shared $ref amplification", () => {
|
||||
const heavyDefs = {
|
||||
Heavy: { type: "object", description: "x".repeat(4000), properties: { ok: { type: "boolean" } } },
|
||||
}
|
||||
const heavyProps = Object.fromEntries(Array.from({ length: 80 }, (_, i) => [`h${i}`, { $ref: "#/$defs/Heavy" }]))
|
||||
const heavySchema = fullPipeline({ type: "object", $defs: heavyDefs, properties: heavyProps })
|
||||
const heavyText = JSON.stringify(heavySchema)
|
||||
assert.match(heavyText, /Schema expansion limit/)
|
||||
assert.ok(heavyText.length < 280_000, String(heavyText.length))
|
||||
assert.equal(heavySchema.properties.h0.properties.ok.type, "boolean")
|
||||
assert.equal(heavySchema.properties.h79.properties, undefined)
|
||||
assert.equal(heavySchema.properties.h79.type, "object")
|
||||
|
||||
const tinyDefs = { Tiny: { type: "integer" } }
|
||||
const tinyProps = Object.fromEntries(Array.from({ length: 8300 }, (_, i) => [`t${i}`, { $ref: "#/$defs/Tiny" }]))
|
||||
const tinySchema = fullPipeline({ type: "object", $defs: tinyDefs, properties: tinyProps })
|
||||
assert.deepEqual(tinySchema.properties.t0, { type: "integer" })
|
||||
assert.equal(tinySchema.properties.t8299.type, "integer")
|
||||
assert.match(tinySchema.properties.t8299.description, /Schema expansion limit/)
|
||||
})
|
||||
|
||||
test("recursive nullable $ref preserves [object, null] at the cycle boundary", () => {
|
||||
const schema = fullPipeline({
|
||||
type: "object",
|
||||
$defs: {
|
||||
ListNode: {
|
||||
type: ["object", "null"],
|
||||
properties: { val: { type: "integer" }, next: { $ref: "#/$defs/ListNode" } },
|
||||
},
|
||||
},
|
||||
properties: { head: { $ref: "#/$defs/ListNode" } },
|
||||
})
|
||||
assert.deepEqual(schema.properties.head.type, ["object", "null"])
|
||||
assert.deepEqual(schema.properties.head.properties.next.type, ["object", "null"])
|
||||
assert.match(schema.properties.head.properties.next.description, /Recursive schema/)
|
||||
})
|
||||
|
||||
test("bridge request path delivers expanded schemas to MCP tools/list without inventing a ToolSearch schema", async () => {
|
||||
const kit = await createBridgeKit()
|
||||
try {
|
||||
let listed = null
|
||||
kit.prompts.push(async (agent) => {
|
||||
listed = await agent.listTools()
|
||||
await agent.text("checked tools")
|
||||
})
|
||||
|
||||
const res = await kit.request(baseBody({
|
||||
tools: [
|
||||
{ name: "ToolSearch", description: "Custom parameterless tool" },
|
||||
{
|
||||
name: "cua_action",
|
||||
description: "Desktop GUI action",
|
||||
input_schema: {
|
||||
type: "object",
|
||||
$defs: {
|
||||
Point: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: { x: { type: "number" }, y: { type: "number" } },
|
||||
required: ["x", "y"],
|
||||
},
|
||||
},
|
||||
oneOf: [
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
method: { const: "move" },
|
||||
params: { $ref: "#/$defs/Point" },
|
||||
},
|
||||
required: ["method", "params"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
method: { const: "capture" },
|
||||
env: { type: "object", additionalProperties: { type: "string" } },
|
||||
},
|
||||
required: ["method"],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
}))
|
||||
const parsed = await readSse(res)
|
||||
assert.equal(parsed.stopReason, "end_turn")
|
||||
|
||||
const mcpTools = listed?.result?.tools ?? []
|
||||
const searchTool = mcpTools.find((t) => t.name === "ToolSearch")
|
||||
const cuaTool = mcpTools.find((t) => t.name === "cua_action")
|
||||
|
||||
assert.ok(searchTool, "ToolSearch must be exposed over MCP tools/list")
|
||||
assert.deepEqual(searchTool.inputSchema, { type: "object", properties: {} })
|
||||
|
||||
assert.ok(cuaTool, "cua_action must be exposed over MCP tools/list")
|
||||
assert.equal(cuaTool.inputSchema.$defs, undefined)
|
||||
assert.equal(cuaTool.inputSchema.oneOf, undefined)
|
||||
assert.equal(cuaTool.inputSchema.additionalProperties, false)
|
||||
assert.deepEqual(cuaTool.inputSchema.required, ["method"])
|
||||
assert.deepEqual(cuaTool.inputSchema.properties?.method, { type: "string", enum: ["move", "capture"] })
|
||||
assert.deepEqual(cuaTool.inputSchema.properties?.params?.required, ["x", "y"])
|
||||
assert.equal(cuaTool.inputSchema.properties?.params?.additionalProperties, false)
|
||||
assert.match(cuaTool.inputSchema.properties?.env?.description ?? "", /Additional properties: string/)
|
||||
} finally {
|
||||
await kit.dispose()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,670 @@
|
||||
// Expand JSON Schema constructs that agy's ACP -> CloudCode Schema translator
|
||||
// either ignores or drops (`$ref` into `$defs`/`definitions`, `allOf`, `oneOf`,
|
||||
// object/primitive `anyOf` unions, `const` discriminators, `additionalProperties`
|
||||
// dictionaries, and boolean schemas), before `sanitizeInputSchema` and
|
||||
// `ensureGeminiArrayItems` normalize types, RE2 patterns, and untyped arrays.
|
||||
//
|
||||
// Nullable unions lower to `type: [X, "null"]` (matching `sanitizeInputSchema`),
|
||||
// which both agy's local JSON Schema validator and its CloudCode schema
|
||||
// translator accept for null and non-null values alike.
|
||||
// Local $ref/allOf/const expansion inspired by
|
||||
// DylanLIiii/opencode-antigravity-bridge (MIT).
|
||||
|
||||
const NUMBER_BOUNDS = [
|
||||
"minimum", "maximum", "minLength", "maxLength",
|
||||
"minItems", "maxItems", "minProperties", "maxProperties",
|
||||
]
|
||||
const CONTAINER_MAPS = ["properties", "patternProperties", "dependentSchemas"]
|
||||
const BOOLEAN_OR_SCHEMA_CHILDREN = ["additionalProperties", "unevaluatedProperties", "unevaluatedItems"]
|
||||
const SCHEMA_ONLY_CHILDREN = ["propertyNames", "contains", "if", "then", "else", "not"]
|
||||
const VISITED_OBJECT_KEYS = new Set([
|
||||
...CONTAINER_MAPS,
|
||||
...BOOLEAN_OR_SCHEMA_CHILDREN,
|
||||
...SCHEMA_ONLY_CHILDREN,
|
||||
"prefixItems", "items", "anyOf", "oneOf",
|
||||
])
|
||||
// Keywords whose value is a name -> schema map: a pointer may pass through
|
||||
// them but must not stop on them.
|
||||
const POINTER_MAP_KEYWORDS = new Set(["properties", "patternProperties", "dependentSchemas", "$defs", "definitions"])
|
||||
|
||||
// Only `$ref` and `allOf` inlining is charged; ordinary traversal is free.
|
||||
const MAX_INLINED_NODES = 8192
|
||||
const MAX_INLINED_BYTES = 256 * 1024
|
||||
const MAX_DEPTH = 64
|
||||
const MAX_VARIANT_HINT_CHARS = 1600
|
||||
const MAX_VARIANT_SUMMARY_CHARS = 240
|
||||
const MAX_VARIANT_DESCRIPTION_CHARS = 80
|
||||
|
||||
const ANY_VALUE_HINT = "Accepts any JSON value."
|
||||
const NO_VALUE_HINT = "No value is allowed by the original schema."
|
||||
const NULL_HINT = "Must be null."
|
||||
const RECURSIVE_HINT = "Recursive schema; follow the tool's original argument contract."
|
||||
const LIMIT_HINT = "Schema expansion limit reached; follow the tool's original argument contract."
|
||||
|
||||
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
|
||||
function appendHint(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 clip(text, max) {
|
||||
const flat = text.replace(/\s+/g, " ").trim()
|
||||
return flat.length > max ? `${flat.slice(0, max - 3).trimEnd()}...` : flat
|
||||
}
|
||||
|
||||
function scalarBytes(value) {
|
||||
if (typeof value === "string") return Buffer.byteLength(value) + 2
|
||||
if (typeof value === "number" || typeof value === "boolean") return String(value).length
|
||||
return 4
|
||||
}
|
||||
|
||||
function ownBytes(out) {
|
||||
let bytes = 2
|
||||
for (const [key, value] of Object.entries(out)) {
|
||||
if (value === undefined) continue
|
||||
bytes += Buffer.byteLength(key) + 4
|
||||
if (value === null || typeof value !== "object") {
|
||||
bytes += scalarBytes(value)
|
||||
} else if (key === "properties" || key === "patternProperties" || key === "dependentSchemas") {
|
||||
bytes += 2
|
||||
for (const mapKey of Object.keys(value)) bytes += Buffer.byteLength(mapKey) + 4
|
||||
} else if (VISITED_OBJECT_KEYS.has(key)) {
|
||||
bytes += 2
|
||||
} else if (Array.isArray(value) && value.every((item) => item === null || typeof item !== "object")) {
|
||||
bytes += 2
|
||||
for (const item of value) bytes += scalarBytes(item) + 1
|
||||
} else {
|
||||
bytes += Buffer.byteLength(JSON.stringify(value))
|
||||
}
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
function resolvePointer(root, ref) {
|
||||
if (ref === "#") return root
|
||||
if (!ref.startsWith("#/")) return undefined
|
||||
let parts
|
||||
try {
|
||||
parts = decodeURIComponent(ref.slice(2)).split("/")
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
let target = root
|
||||
let inMap = false
|
||||
for (const part of parts) {
|
||||
const key = part.replace(/~1/g, "/").replace(/~0/g, "~")
|
||||
if ((!isObject(target) && !Array.isArray(target)) || !Object.hasOwn(target, key)) return undefined
|
||||
// Inside a map the key is a name (`#/properties/properties` is a schema);
|
||||
// at a schema node it is a keyword.
|
||||
const entersMap = !inMap && isObject(target) && POINTER_MAP_KEYWORDS.has(key)
|
||||
target = target[key]
|
||||
inMap = entersMap
|
||||
}
|
||||
if (inMap) return undefined
|
||||
return isObject(target) || typeof target === "boolean" ? target : undefined
|
||||
}
|
||||
|
||||
function isNullType(type) {
|
||||
return type === "null" || (Array.isArray(type) && type.length === 1 && type[0] === "null")
|
||||
}
|
||||
|
||||
function isNullSchema(schema) {
|
||||
if (!isObject(schema)) return false
|
||||
if (isNullType(schema.type)) return true
|
||||
// A lowered `const: null` leaf (no type, only the null hint).
|
||||
return schema.type === undefined && typeof schema.description === "string" &&
|
||||
schema.description.includes(NULL_HINT) && schema.properties === undefined &&
|
||||
schema.items === undefined && schema.enum === undefined && schema.const === undefined &&
|
||||
schema.anyOf === undefined && schema.oneOf === undefined
|
||||
}
|
||||
|
||||
function declaresArray(schema) {
|
||||
if (!isObject(schema)) return false
|
||||
return schema.type === "array" || (Array.isArray(schema.type) && schema.type.includes("array"))
|
||||
}
|
||||
|
||||
function isObjectBranch(schema) {
|
||||
if (!isObject(schema)) return false
|
||||
if (schema.type === "object") return true
|
||||
if (Array.isArray(schema.type) && schema.type.includes("object") &&
|
||||
schema.type.every((t) => t === "object" || t === "null")) {
|
||||
return true
|
||||
}
|
||||
if (schema.type !== undefined) return false
|
||||
return isObject(schema.properties) || Array.isArray(schema.required) ||
|
||||
schema.additionalProperties !== undefined || isObject(schema.patternProperties)
|
||||
}
|
||||
|
||||
function primitiveTypeOf(schema) {
|
||||
if (!isObject(schema)) return null
|
||||
const raw = typeof schema.type === "string"
|
||||
? [schema.type]
|
||||
: Array.isArray(schema.type)
|
||||
? schema.type.filter((t) => t !== "null")
|
||||
: []
|
||||
if (raw.length !== 1) return null
|
||||
const t = raw[0]
|
||||
return (t === "string" || t === "number" || t === "integer" || t === "boolean") ? t : null
|
||||
}
|
||||
|
||||
// Stand-in for a subtree that is not expanded (recursion, depth or budget):
|
||||
// keep what kind of value it is, never invent a type it did not declare.
|
||||
function structuralFallback(schema, hint) {
|
||||
const nullable = isObject(schema) && Array.isArray(schema.type) && schema.type.includes("null")
|
||||
const withNull = (t) => nullable ? [t, "null"] : t
|
||||
if (isObjectBranch(schema)) return { type: withNull("object"), description: hint }
|
||||
if (declaresArray(schema)) return { type: withNull("array"), description: hint }
|
||||
const prim = primitiveTypeOf(schema)
|
||||
if (prim) return { type: withNull(prim), description: hint }
|
||||
return { description: hint }
|
||||
}
|
||||
|
||||
function summarizeSchema(schema, depth = 0) {
|
||||
if (!isObject(schema)) return schema === false ? "never" : "any"
|
||||
if (Array.isArray(schema.enum) && schema.enum.length) {
|
||||
const shown = schema.enum.slice(0, 12).map((v) => JSON.stringify(v)).join(" | ")
|
||||
return schema.enum.length > 12 ? `${shown} | ...` : shown
|
||||
}
|
||||
if (schema.const !== undefined) return JSON.stringify(schema.const)
|
||||
const types = Array.isArray(schema.type) ? schema.type : typeof schema.type === "string" ? [schema.type] : []
|
||||
const rawType = types.length ? types.join("|") : undefined
|
||||
const nullable = types.includes("null")
|
||||
const nonNullTypes = types.filter((t) => t !== "null")
|
||||
if ((!rawType || (nonNullTypes.length === 1 && nonNullTypes[0] === "object")) && isObject(schema.properties)) {
|
||||
if (depth >= 2) return rawType || "object"
|
||||
const req = new Set(Array.isArray(schema.required) ? schema.required : [])
|
||||
const entries = Object.entries(schema.properties)
|
||||
const shown = entries.slice(0, 8).map(([k, v]) => `${k}${req.has(k) ? "" : "?"}: ${summarizeSchema(v, depth + 1)}`)
|
||||
if (entries.length > 8) shown.push("...")
|
||||
const body = `{ ${shown.join(", ")} }`
|
||||
return nullable ? `${body} | null` : body
|
||||
}
|
||||
if ((!rawType || rawType === "object") && Array.isArray(schema.required) && schema.required.length) {
|
||||
return `{ required: [${schema.required.join(", ")}] }`
|
||||
}
|
||||
if ((nonNullTypes.length === 1 && nonNullTypes[0] === "array") || (!rawType && isObject(schema.items))) {
|
||||
if (depth >= 2 || !isObject(schema.items)) return rawType || "array"
|
||||
const body = `array<${summarizeSchema(schema.items, depth + 1)}>`
|
||||
return nullable ? `${body} | null` : body
|
||||
}
|
||||
const combo = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : null
|
||||
if (combo && combo.length) {
|
||||
if (depth >= 2) return "union"
|
||||
const shown = combo.slice(0, 6).map((b) => summarizeSchema(b, depth + 1)).join(" | ")
|
||||
return combo.length > 6 ? `${shown} | ...` : shown
|
||||
}
|
||||
return rawType || "any"
|
||||
}
|
||||
|
||||
function typeList(type) {
|
||||
if (typeof type === "string") return [type]
|
||||
if (Array.isArray(type)) return type.filter((t) => typeof t === "string")
|
||||
return null
|
||||
}
|
||||
|
||||
function intersectTypes(a, b) {
|
||||
const left = typeList(a)
|
||||
const right = typeList(b)
|
||||
if (!left || !left.length) return { type: b }
|
||||
if (!right || !right.length) return { type: a }
|
||||
const common = new Set()
|
||||
for (const t of left) {
|
||||
if (right.includes(t)) common.add(t)
|
||||
else if ((t === "number" && right.includes("integer")) || (t === "integer" && right.includes("number"))) {
|
||||
common.add("integer")
|
||||
}
|
||||
}
|
||||
if (!common.size) return { type: a, conflict: true }
|
||||
const nonNull = [...common].filter((t) => t !== "null")
|
||||
const list = common.has("null") ? [...nonNull, "null"] : nonNull
|
||||
return { type: list.length === 1 ? list[0] : list }
|
||||
}
|
||||
|
||||
function intersectSchemas(schemas) {
|
||||
const meaningful = schemas.filter((schema) => isObject(schema) && Object.keys(schema).length)
|
||||
if (!meaningful.length) return {}
|
||||
if (meaningful.length === 1) return { ...meaningful[0] }
|
||||
const out = { ...meaningful[0] }
|
||||
const conflicts = []
|
||||
for (const schema of meaningful.slice(1)) {
|
||||
appendHint(out, schema.description)
|
||||
for (const [key, value] of Object.entries(schema)) {
|
||||
if (key === "description" || key === "properties" || key === "required" || key === "items" ||
|
||||
key === "enum" || key === "type" || NUMBER_BOUNDS.includes(key)) continue
|
||||
if (out[key] === undefined) out[key] = value
|
||||
}
|
||||
if (schema.type !== undefined) {
|
||||
const merged = intersectTypes(out.type, schema.type)
|
||||
if (merged.conflict) conflicts.push(`${typeList(out.type).join("|")} vs ${typeList(schema.type).join("|")}`)
|
||||
out.type = merged.type
|
||||
}
|
||||
}
|
||||
for (const conflict of conflicts) appendHint(out, `Conflicting type constraints in allOf: ${conflict}.`)
|
||||
const objects = meaningful.filter((schema) => isObject(schema.properties))
|
||||
if (objects.length) {
|
||||
const keys = [...new Set(objects.flatMap((schema) => Object.keys(schema.properties)))]
|
||||
out.properties = Object.fromEntries(keys.map((key) => [
|
||||
key,
|
||||
intersectSchemas(objects.filter((schema) => Object.hasOwn(schema.properties, key)).map((schema) => schema.properties[key])),
|
||||
]))
|
||||
out.type ??= "object"
|
||||
}
|
||||
const reqKeys = [...new Set(meaningful.flatMap((schema) => Array.isArray(schema.required) ? schema.required : []))]
|
||||
if (reqKeys.length) {
|
||||
out.required = reqKeys
|
||||
out.type ??= "object"
|
||||
}
|
||||
const arrays = meaningful.filter((schema) => isObject(schema.items))
|
||||
if (arrays.length) {
|
||||
out.items = intersectSchemas(arrays.map((schema) => schema.items))
|
||||
out.type ??= "array"
|
||||
}
|
||||
for (const key of NUMBER_BOUNDS) {
|
||||
const values = meaningful.map((schema) => schema[key]).filter((v) => typeof v === "number" && Number.isFinite(v))
|
||||
if (!values.length) continue
|
||||
const lower = key === "minimum" || key.startsWith("min")
|
||||
out[key] = (lower ? Math.max : Math.min)(...values)
|
||||
}
|
||||
const enums = meaningful.filter((schema) => Array.isArray(schema.enum))
|
||||
if (enums.length) {
|
||||
const first = enums[0].enum
|
||||
const common = first.filter((value) => enums.every((schema) => schema.enum.includes(value)))
|
||||
if (common.length) {
|
||||
out.enum = [...new Set(common)]
|
||||
} else {
|
||||
delete out.enum
|
||||
appendHint(out, "Conflicting enum constraints in allOf.")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function primitiveFamily(nonNull) {
|
||||
const types = new Set()
|
||||
for (const branch of nonNull) {
|
||||
const t = primitiveTypeOf(branch)
|
||||
if (!t) return null
|
||||
types.add(t)
|
||||
}
|
||||
if (types.size === 1) return [...types][0]
|
||||
if (types.size === 2 && types.has("number") && types.has("integer")) return "number"
|
||||
return null
|
||||
}
|
||||
|
||||
function branchLiterals(branch) {
|
||||
if (Array.isArray(branch.enum) && branch.enum.length > 0) return branch.enum
|
||||
if (branch.const !== undefined && branch.const !== null) return [branch.const]
|
||||
return null
|
||||
}
|
||||
|
||||
function unionPrimitiveBranches(nonNull, family, hasNull) {
|
||||
const out = { type: hasNull ? [family, "null"] : family }
|
||||
const descriptions = [...new Set(
|
||||
nonNull.map((b) => typeof b.description === "string" ? b.description.trim() : "").filter(Boolean),
|
||||
)]
|
||||
if (descriptions.length) out.description = descriptions.slice(0, 3).join("; ")
|
||||
|
||||
// A `const` is a one-value enum. sanitizeInputSchema keeps non-empty string
|
||||
// enums and turns numeric, boolean, or null-bearing ones into an "Allowed values" hint.
|
||||
const literals = nonNull.map(branchLiterals)
|
||||
if (literals.every(Boolean)) {
|
||||
const values = [...new Set(literals.flat().filter((v) => v !== null))]
|
||||
out.enum = hasNull ? [...values, null] : values
|
||||
} else if (literals.some(Boolean)) {
|
||||
const known = [...new Set(literals.filter(Boolean).flat())].slice(0, 12).map((v) => JSON.stringify(v)).join(", ")
|
||||
appendHint(out, `Known values include: ${known}`)
|
||||
}
|
||||
|
||||
for (const key of NUMBER_BOUNDS) {
|
||||
if (!nonNull.every((b) => typeof b[key] === "number" && Number.isFinite(b[key]))) continue
|
||||
const values = nonNull.map((b) => b[key])
|
||||
const lower = key === "minimum" || key.startsWith("min")
|
||||
out[key] = (lower ? Math.min : Math.max)(...values)
|
||||
}
|
||||
const formats = [...new Set(nonNull.map((b) => b.format).filter((f) => typeof f === "string" && f))]
|
||||
if (formats.length === 1 && nonNull.every((b) => b.format === formats[0])) out.format = formats[0]
|
||||
const patterns = [...new Set(nonNull.map((b) => b.pattern).filter((p) => typeof p === "string" && p))]
|
||||
if (patterns.length === 1 && nonNull.every((b) => b.pattern === patterns[0])) out.pattern = patterns[0]
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
function unionPropertySchemas(schemas) {
|
||||
const meaningful = schemas.filter(isObject)
|
||||
if (!meaningful.length) return {}
|
||||
if (meaningful.length === 1) return { ...meaningful[0] }
|
||||
const nonNull = meaningful.filter((b) => !isNullSchema(b))
|
||||
const hasNull = nonNull.length < meaningful.length ||
|
||||
meaningful.some((b) => Array.isArray(b.type) && b.type.includes("null"))
|
||||
if (!nonNull.length) return { description: NULL_HINT }
|
||||
if (nonNull.every(isObjectBranch)) return unionObjectBranches(nonNull, hasNull)
|
||||
const family = primitiveFamily(nonNull)
|
||||
if (family) return unionPrimitiveBranches(nonNull, family, hasNull)
|
||||
return {
|
||||
anyOf: meaningful,
|
||||
description: `Accepts anyOf: ${meaningful.map((b) => summarizeSchema(b)).join(" | ")}`,
|
||||
}
|
||||
}
|
||||
|
||||
function variantsHint(branches) {
|
||||
const parts = []
|
||||
let length = 0
|
||||
for (let i = 0; i < branches.length; i++) {
|
||||
const branch = branches[i]
|
||||
let part = clip(summarizeSchema(branch, 1), MAX_VARIANT_SUMMARY_CHARS)
|
||||
if (typeof branch.description === "string" && branch.description.trim()) {
|
||||
part += ` (${clip(branch.description, MAX_VARIANT_DESCRIPTION_CHARS)})`
|
||||
}
|
||||
if (parts.length && length + part.length + 3 > MAX_VARIANT_HINT_CHARS) {
|
||||
parts.push(`... (+${branches.length - i} more)`)
|
||||
break
|
||||
}
|
||||
parts.push(part)
|
||||
length += part.length + 3
|
||||
}
|
||||
return `Variants: ${parts.join(" | ")}`
|
||||
}
|
||||
|
||||
function unionObjectBranches(nonNull, hasNull) {
|
||||
const out = { type: hasNull ? ["object", "null"] : "object" }
|
||||
if (nonNull.length === 1 && typeof nonNull[0].description === "string" && nonNull[0].description.trim()) {
|
||||
out.description = nonNull[0].description
|
||||
}
|
||||
const propKeys = [...new Set(nonNull.flatMap((b) => isObject(b.properties) ? Object.keys(b.properties) : []))]
|
||||
if (propKeys.length) {
|
||||
out.properties = Object.fromEntries(propKeys.map((key) => [
|
||||
key,
|
||||
unionPropertySchemas(
|
||||
nonNull.filter((b) => isObject(b.properties) && Object.hasOwn(b.properties, key)).map((b) => b.properties[key]),
|
||||
),
|
||||
]))
|
||||
}
|
||||
const reqSets = nonNull.map((b) => new Set(Array.isArray(b.required) ? b.required : []))
|
||||
const commonReq = [...reqSets[0]].filter((key) => reqSets.every((set) => set.has(key)))
|
||||
if (commonReq.length) out.required = commonReq
|
||||
|
||||
if (nonNull.some((b) => b.additionalProperties === true)) {
|
||||
out.additionalProperties = true
|
||||
} else if (nonNull.some((b) => isObject(b.additionalProperties))) {
|
||||
out.additionalProperties = unionPropertySchemas(
|
||||
nonNull.filter((b) => isObject(b.additionalProperties)).map((b) => b.additionalProperties),
|
||||
)
|
||||
} else if (nonNull.every((b) => b.additionalProperties === false)) {
|
||||
out.additionalProperties = false
|
||||
}
|
||||
|
||||
if (nonNull.length > 1) appendHint(out, variantsHint(nonNull))
|
||||
return out
|
||||
}
|
||||
|
||||
function lowerUnionKey(out, key) {
|
||||
const branches = out[key]
|
||||
if (!Array.isArray(branches)) return out
|
||||
if (!branches.length) {
|
||||
delete out[key]
|
||||
return out
|
||||
}
|
||||
const nonNull = branches.filter((b) => !isNullSchema(b))
|
||||
const hasNull = nonNull.length < branches.length ||
|
||||
branches.some((b) => Array.isArray(b?.type) && b.type.includes("null"))
|
||||
|
||||
if (!nonNull.length) {
|
||||
delete out[key]
|
||||
if (isNullType(out.type)) delete out.type
|
||||
appendHint(out, NULL_HINT)
|
||||
return out
|
||||
}
|
||||
|
||||
// Leave array-bearing combinators intact so `ensureGeminiArrayItems` can lift
|
||||
// item schemas without narrowing `string | string[]` or `array | null`.
|
||||
if (declaresArray(out) || nonNull.some(declaresArray)) {
|
||||
if (key === "oneOf") {
|
||||
out.anyOf = Array.isArray(out.anyOf) ? [...out.anyOf, ...branches] : branches
|
||||
delete out.oneOf
|
||||
}
|
||||
if (!declaresArray(out)) {
|
||||
appendHint(out, `Accepts anyOf: ${branches.map((b) => summarizeSchema(b)).join(" | ")}`)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
if (nonNull.every(isObjectBranch)) {
|
||||
const rest = { ...out }
|
||||
delete rest[key]
|
||||
return intersectSchemas([rest, unionObjectBranches(nonNull, hasNull)])
|
||||
}
|
||||
|
||||
const family = primitiveFamily(nonNull)
|
||||
if (family) {
|
||||
const rest = { ...out }
|
||||
delete rest[key]
|
||||
return intersectSchemas([rest, unionPrimitiveBranches(nonNull, family, hasNull)])
|
||||
}
|
||||
|
||||
if (key === "oneOf") {
|
||||
out.anyOf = Array.isArray(out.anyOf) ? [...out.anyOf, ...branches] : branches
|
||||
delete out.oneOf
|
||||
}
|
||||
appendHint(out, `Accepts anyOf: ${branches.map((b) => summarizeSchema(b)).join(" | ")}`)
|
||||
return out
|
||||
}
|
||||
|
||||
function constConflict(out) {
|
||||
if (!Array.isArray(out.enum)) return
|
||||
if (!out.enum.includes(out.const)) {
|
||||
appendHint(out, `Conflicting const and enum constraints; const is ${JSON.stringify(out.const)}.`)
|
||||
}
|
||||
delete out.enum
|
||||
}
|
||||
|
||||
// `const` on a leaf. Non-empty strings become a one-value enum; `""`, numbers,
|
||||
// booleans, objects and arrays keep `const` (sanitizeInputSchema turns it into
|
||||
// a "Must equal" hint) and get the matching type.
|
||||
function lowerConst(out) {
|
||||
const value = out.const
|
||||
if (value === null) {
|
||||
delete out.const
|
||||
if (isNullType(out.type)) delete out.type
|
||||
appendHint(out, NULL_HINT)
|
||||
return
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const types = typeList(out.type)
|
||||
if (types && !types.every((t) => t === "string" || t === "null")) return
|
||||
// `const` already excludes null, so a nullable string type narrows to string.
|
||||
out.type = "string"
|
||||
if (!value.length) {
|
||||
constConflict(out)
|
||||
return
|
||||
}
|
||||
if (Array.isArray(out.enum) && !out.enum.includes(value)) {
|
||||
appendHint(out, `Conflicting const and enum constraints; const is ${JSON.stringify(value)}.`)
|
||||
}
|
||||
out.enum = [value]
|
||||
delete out.const
|
||||
return
|
||||
}
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
out.type ??= Number.isInteger(value) ? "integer" : "number"
|
||||
constConflict(out)
|
||||
} else if (typeof value === "boolean") {
|
||||
out.type ??= "boolean"
|
||||
constConflict(out)
|
||||
} else if (Array.isArray(value)) {
|
||||
out.type ??= "array"
|
||||
} else if (isObject(value)) {
|
||||
out.type ??= "object"
|
||||
}
|
||||
}
|
||||
|
||||
export function expandToolSchema(root) {
|
||||
if (!isObject(root)) return root
|
||||
|
||||
// Cycle-free `$ref` targets are expanded once and deep-cloned on reuse.
|
||||
const cache = new Map()
|
||||
let produced = 0 // schema objects emitted, including cached copies
|
||||
let producedBytes = 0 // estimated JSON bytes emitted, including cached copies
|
||||
let inlined = 0 // of those, nodes emitted through $ref / allOf expansion
|
||||
let inlinedBytes = 0 // of those, bytes emitted through $ref / allOf expansion
|
||||
let limits = 0 // recursion / depth / budget fallbacks emitted
|
||||
let deepest = 0
|
||||
|
||||
function limit(schema, hint) {
|
||||
const out = structuralFallback(schema, hint)
|
||||
limits++
|
||||
produced++
|
||||
producedBytes += ownBytes(out)
|
||||
return out
|
||||
}
|
||||
|
||||
function measure(inlineDepth, fn) {
|
||||
const start = { produced, producedBytes, inlined, inlinedBytes, limits, deepest }
|
||||
deepest = inlineDepth
|
||||
const schema = fn()
|
||||
const result = {
|
||||
schema,
|
||||
weight: produced - start.produced,
|
||||
bytes: producedBytes - start.producedBytes,
|
||||
nested: inlined - start.inlined,
|
||||
nestedBytes: inlinedBytes - start.inlinedBytes,
|
||||
limited: limits !== start.limits,
|
||||
height: deepest - inlineDepth,
|
||||
}
|
||||
deepest = Math.max(start.deepest, deepest)
|
||||
// Charge only what nested expansions have not charged already.
|
||||
inlined += Math.max(0, result.weight - result.nested)
|
||||
inlinedBytes += Math.max(0, result.bytes - result.nestedBytes)
|
||||
return result
|
||||
}
|
||||
|
||||
function expandRef(target, inlineDepth, active) {
|
||||
if (typeof target === "boolean") return visit(target, inlineDepth, active)
|
||||
if (inlined >= MAX_INLINED_NODES || inlinedBytes >= MAX_INLINED_BYTES) return limit(target, LIMIT_HINT)
|
||||
const hit = cache.get(target)
|
||||
if (hit && inlineDepth + hit.height <= MAX_DEPTH) {
|
||||
if (inlined + hit.weight > MAX_INLINED_NODES || inlinedBytes + hit.bytes > MAX_INLINED_BYTES) {
|
||||
return limit(target, LIMIT_HINT)
|
||||
}
|
||||
produced += hit.weight
|
||||
inlined += hit.weight
|
||||
producedBytes += hit.bytes
|
||||
inlinedBytes += hit.bytes
|
||||
deepest = Math.max(deepest, inlineDepth + hit.height)
|
||||
return structuredClone(hit.schema)
|
||||
}
|
||||
const result = measure(inlineDepth, () => visit(target, inlineDepth, active))
|
||||
if (!result.limited) {
|
||||
cache.set(target, {
|
||||
schema: structuredClone(result.schema),
|
||||
weight: result.weight,
|
||||
bytes: result.bytes,
|
||||
height: result.height,
|
||||
})
|
||||
}
|
||||
return result.schema
|
||||
}
|
||||
|
||||
function visit(schema, inlineDepth, active) {
|
||||
deepest = Math.max(deepest, inlineDepth)
|
||||
if (!isObject(schema)) {
|
||||
const out = { description: schema === false ? NO_VALUE_HINT : ANY_VALUE_HINT }
|
||||
produced++
|
||||
producedBytes += ownBytes(out)
|
||||
return out
|
||||
}
|
||||
if (active.has(schema)) return limit(schema, RECURSIVE_HINT)
|
||||
if (inlineDepth > MAX_DEPTH) return limit(schema, LIMIT_HINT)
|
||||
produced++
|
||||
const nextActive = new Set(active).add(schema)
|
||||
const child = (value) => visit(value, inlineDepth, nextActive)
|
||||
|
||||
let out = {}
|
||||
for (const [key, value] of Object.entries(schema)) {
|
||||
if (key === "$defs" || key === "definitions" || key === "$schema" || key === "$id" ||
|
||||
key === "$ref" || key === "allOf") continue
|
||||
out[key] = value
|
||||
}
|
||||
|
||||
if (out.const !== undefined) lowerConst(out)
|
||||
|
||||
for (const mapKey of CONTAINER_MAPS) {
|
||||
if (isObject(out[mapKey])) {
|
||||
out[mapKey] = Object.fromEntries(Object.entries(out[mapKey]).map(([k, v]) => [k, child(v)]))
|
||||
}
|
||||
}
|
||||
for (const childKey of BOOLEAN_OR_SCHEMA_CHILDREN) {
|
||||
if (isObject(out[childKey])) {
|
||||
out[childKey] = child(out[childKey])
|
||||
}
|
||||
}
|
||||
for (const childKey of SCHEMA_ONLY_CHILDREN) {
|
||||
if (out[childKey] !== undefined && (isObject(out[childKey]) || typeof out[childKey] === "boolean")) {
|
||||
out[childKey] = child(out[childKey])
|
||||
}
|
||||
}
|
||||
if (Array.isArray(out.prefixItems)) {
|
||||
out.prefixItems = out.prefixItems.map((item) => child(item))
|
||||
}
|
||||
if (Array.isArray(out.items)) {
|
||||
out.items = out.items.map((item) => child(item))
|
||||
} else if (isObject(out.items)) {
|
||||
out.items = child(out.items)
|
||||
} else if (out.items === false) {
|
||||
if (Array.isArray(out.prefixItems) && out.prefixItems.length > 0) {
|
||||
// A closed tuple. agy ignores prefixItems, so give it the element
|
||||
// union and the tuple length instead of forbidding every element.
|
||||
const length = out.prefixItems.length
|
||||
out.maxItems = typeof out.maxItems === "number" ? Math.min(out.maxItems, length) : length
|
||||
out.items = structuredClone(unionPropertySchemas(out.prefixItems))
|
||||
} else {
|
||||
out.maxItems = 0
|
||||
out.items = { type: "string", description: NO_VALUE_HINT }
|
||||
}
|
||||
}
|
||||
for (const key of ["anyOf", "oneOf"]) {
|
||||
if (Array.isArray(out[key])) out[key] = out[key].map((branch) => child(branch))
|
||||
}
|
||||
|
||||
if (typeof schema.$ref === "string") {
|
||||
const target = resolvePointer(root, schema.$ref)
|
||||
if (target !== undefined) {
|
||||
out = intersectSchemas([out, expandRef(target, inlineDepth + 1, nextActive)])
|
||||
} else {
|
||||
appendHint(out, `Unresolved schema reference: ${schema.$ref}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(schema.allOf) && schema.allOf.length) {
|
||||
const branches = schema.allOf.map((branch) => {
|
||||
if (inlined >= MAX_INLINED_NODES || inlinedBytes >= MAX_INLINED_BYTES) {
|
||||
return limit(branch, LIMIT_HINT)
|
||||
}
|
||||
return measure(inlineDepth + 1, () => visit(branch, inlineDepth + 1, nextActive)).schema
|
||||
})
|
||||
out = intersectSchemas([out, ...branches])
|
||||
}
|
||||
|
||||
out = lowerUnionKey(out, "oneOf")
|
||||
out = lowerUnionKey(out, "anyOf")
|
||||
|
||||
if (out.additionalProperties === true) {
|
||||
appendHint(out, "Accepts arbitrary additional key-value properties.")
|
||||
} else if (isObject(out.additionalProperties)) {
|
||||
appendHint(out, `Additional properties: ${summarizeSchema(out.additionalProperties)}`)
|
||||
}
|
||||
if (isObject(out.patternProperties) && Object.keys(out.patternProperties).length > 0) {
|
||||
const shown = Object.entries(out.patternProperties).slice(0, 6).map(([pat, val]) => `${pat}: ${summarizeSchema(val)}`)
|
||||
appendHint(out, `Pattern properties: ${shown.join(", ")}`)
|
||||
}
|
||||
|
||||
producedBytes += ownBytes(out)
|
||||
return out
|
||||
}
|
||||
|
||||
return visit(root, 0, new Set())
|
||||
}
|
||||
Reference in New Issue
Block a user