From 8e6c75b1e35267e028c1b563c80dd1436c887594 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 19:31:15 +0800 Subject: [PATCH] agy-cli 0.1.19: tools with large schemas are shortened so agy keeps them in the model's function list (#989, klarkxy on X) agy lazy-loads MCP tools (McpToolConfig.EnableLazyLoad and a call_mcp_tool tool are in the 1.5.5 binary): a tool with a large declaration never reaches the model's function list and nothing says so. The reporter saw tools of about 691 tokens and up missing (bash, grep), 561 and below present. The exact cut-off is not in the binary. tool-budget.mjs fits each tool under 2000 characters (about 500 tokens; env AGY_BRIDGE_TOOL_BUDGET, 0 = off). Order of loss: default/examples/title, nested descriptions to 90 chars, the tool's description, nested descriptions, and last the largest optional parameters (never required ones). Each changed tool is logged on stderr as agy_bridge_tool_shrunk, with what was lost and stillOver when it cannot fit. Run (mica, HOME=$(mktemp -d)): bun test packages/agy-cli 14 pass, scripts/check.mjs ok. Broken by hand: without the fitTools call in the request path the smoke check goes red (5201 chars). Not tried: a real agy 1.5.x with Gemini 4 Carbon, so the 2000-character budget rests on the reporter's numbers. --- packages/agy-cli/agy-cli.test.mjs | 1 + packages/agy-cli/index.mjs | 16 ++++- packages/agy-cli/package.json | 1 + packages/agy-cli/test/smoke.mjs | 27 ++++++++ packages/agy-cli/test/testkit.mjs | 3 + packages/agy-cli/test/tool-budget.mjs | 77 +++++++++++++++++++++ packages/agy-cli/tool-budget.mjs | 98 +++++++++++++++++++++++++++ 7 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 packages/agy-cli/test/tool-budget.mjs create mode 100644 packages/agy-cli/tool-budget.mjs diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index 1a8f6e8..9c590f9 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -23,6 +23,7 @@ for (const [name, mocks] of [ ["usage-settlement.mjs", false], ["repeat-batch.mjs", false], ["conversation-key.mjs", false], + ["tool-budget.mjs", false], ]) { test(`test/${name}`, () => { // bun's 5s default per test is a fixed wait these process-spawning tests diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index a21ffdf..c6c3ba7 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -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 { fitTools } from "./tool-budget.mjs" import { cloak, hint, turnsAway } from "./cloak.mjs" const PROVIDER_ID = "agy-cli" @@ -3297,6 +3298,19 @@ function sanitizeInputSchema(schema) { return out } +// A tool shrunk (or still too big) to stay in agy's function list is said on +// stderr every time; agy itself drops an oversized tool without a word (#989). +function reportToolFit(row) { + try { + process.stderr.write("[agy-bridge] " + JSON.stringify({ + event: "agy_bridge_tool_shrunk", ts: Date.now(), ...row, + note: row.stillOver || row.dropped.length + ? "agy may not show this tool to the model, or some parameters were left out" + : "tool declaration shortened so agy keeps it in the model's function list", + }) + "\n") + } catch {} +} + function normalizeTools(body) { if (!Array.isArray(body.tools) || !body.tools.length) return [] const choice = body.tool_choice @@ -4809,7 +4823,7 @@ export const AntigravityBridgePlugin = async () => { const instructions = sessionInstructions(body, callerWorkDir) try { - const tools = normalizeTools(body) + const tools = fitTools(normalizeTools(body), { report: reportToolFit }) for (const message of body.messages) { if (message.role !== "assistant" || !Array.isArray(message.content)) continue for (const block of message.content) { diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 55cf644..db6c129 100644 --- a/packages/agy-cli/package.json +++ b/packages/agy-cli/package.json @@ -21,6 +21,7 @@ "NOTICE.md", "re2-pattern.mjs", "array-items.mjs", + "tool-budget.mjs", "cloak.mjs" ], "keywords": [ diff --git a/packages/agy-cli/test/smoke.mjs b/packages/agy-cli/test/smoke.mjs index 7362085..3551070 100644 --- a/packages/agy-cli/test/smoke.mjs +++ b/packages/agy-cli/test/smoke.mjs @@ -1938,6 +1938,33 @@ for (const location of ["inline", "system", "developer", "user"]) { JSON.stringify(countData)) } +{ + // plugins#989: agy leaves a tool with a large declaration out of the model's + // function list without a word, so the bridge shortens it and says so. + const bigTool = { + name: "big_bash", + description: "Run a command. " + "Long usage guidance. ".repeat(150), + input_schema: { + type: "object", + properties: { + command: { type: "string", description: "The command. " + "More detail. ".repeat(60), default: "ls" }, + timeout: { type: "number", description: "Timeout. " + "Seconds. ".repeat(60) }, + description: { type: "string", description: "What it does. " + "Words. ".repeat(60) }, + }, + required: ["command"], + }, + } + const bigRes = await callFetch({ model, stream: false, tools: [bigTool], messages: [{ role: "user", content: "big tool turn" }] }) + await bigRes.text() + const sent = inits().at(-1)?.tools?.[0] + const sentSize = JSON.stringify({ name: sent?.name, description: sent?.description, inputSchema: sent?.inputSchema }).length + check("a tool over the size budget is shortened but kept, with its required parameter", + bigRes.status === 200 && sent?.name === "big_bash" && sentSize <= 2000 && + JSON.stringify(sent.inputSchema.required) === JSON.stringify(["command"]) && + !!sent.inputSchema.properties.command && !!sent.inputSchema.properties.description, + String(sentSize)) +} + { // Tool schema sanitization, stream: false JSON response, promptCapabilities.image, text/PDF documents, and clean refusal. process.env.FAKE_AGY_PROMPT_IMAGE = "1" diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index db9bad0..9b33453 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -32,6 +32,7 @@ export const INDEX_FILE = process.env.AGY_BRIDGE_TEST_INDEX || path.join(REPO_DI 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 TOOL_BUDGET_FILE = path.join(REPO_DIR, "tool-budget.mjs") 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") @@ -490,6 +491,7 @@ export async function createBridgeKit(options = {}) { const usageUrl = pathToFileURL(USAGE_FILE).href const platformUrl = pathToFileURL(PLATFORM_FILE).href const arrayItemsUrl = pathToFileURL(ARRAY_ITEMS_FILE).href + const toolBudgetUrl = pathToFileURL(TOOL_BUDGET_FILE).href const cloakUrl = pathToFileURL(CLOAK_FILE).href const loginUrl = pathToFileURL(LOGIN_FILE).href const re2Url = pathToFileURL(RE2_PATTERN_FILE).href @@ -502,6 +504,7 @@ export async function createBridgeKit(options = {}) { 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 === "./tool-budget.mjs") module = sourceModule(TOOL_BUDGET_FILE, "", toolBudgetUrl) else if (key === "./cloak.mjs") module = sourceModule(CLOAK_FILE, "", cloakUrl) else if (key === "./login.mjs") module = sourceModule(LOGIN_FILE, "", loginUrl) else if (key === "./re2-pattern.mjs") module = sourceModule(RE2_PATTERN_FILE, "", re2Url) diff --git a/packages/agy-cli/test/tool-budget.mjs b/packages/agy-cli/test/tool-budget.mjs new file mode 100644 index 0000000..6f04ff7 --- /dev/null +++ b/packages/agy-cli/test/tool-budget.mjs @@ -0,0 +1,77 @@ +import { expect, test } from "bun:test" +import { fitTool, fitTools, toolBudget, DEFAULT_TOOL_BUDGET } from "../tool-budget.mjs" + +const size = (t) => JSON.stringify({ name: t.name, description: t.description, inputSchema: t.inputSchema }).length +const small = { name: "read", description: "Read a file", inputSchema: { type: "object", properties: { path: { type: "string" } }, required: ["path"] } } +const big = (n = 20, wordy = 400) => ({ + name: "big", + description: "Does a lot. ".repeat(wordy), + inputSchema: { + type: "object", + properties: Object.fromEntries(Array.from({ length: n }, (_, i) => [`p${i}`, { type: "string", description: "param ".repeat(80), default: "x", title: "T" }])), + required: ["p0"], + }, +}) + +test("a small tool is returned as is", () => { + const { tool, lost } = fitTool(small) + expect(tool).toBe(small) + expect(lost.steps).toEqual([]) +}) + +test("a large tool is shortened under the budget and keeps required parameters", () => { + const { tool, lost } = fitTool(big()) + expect(size(tool)).toBeLessThanOrEqual(DEFAULT_TOOL_BUDGET) + expect(tool.inputSchema.properties.p0).toBeDefined() + expect(tool.inputSchema.required).toEqual(["p0"]) + expect(lost.steps.length).toBeGreaterThan(0) +}) + +test("shortening comes before dropping: descriptions go, parameters stay", () => { + const t = { name: "t", description: "d".repeat(3000), inputSchema: { type: "object", properties: { a: { type: "string", description: "x".repeat(500), default: "q" }, b: { type: "string" } } } } + const { tool, lost } = fitTool(t) + expect(lost.dropped).toEqual([]) + expect(Object.keys(tool.inputSchema.properties)).toEqual(["a", "b"]) + expect(tool.inputSchema.properties.a.default).toBeUndefined() +}) + +test("a parameter named like a keyword is not mistaken for the keyword", () => { + const t = { name: "t", description: "d".repeat(3000), inputSchema: { type: "object", properties: { description: { type: "string" }, default: { type: "string" }, title: { type: "string" } }, required: ["description", "default", "title"] } } + const { tool } = fitTool(t) + expect(Object.keys(tool.inputSchema.properties)).toEqual(["description", "default", "title"]) +}) + +test("optional parameters go last, largest first, and are named", () => { + const { tool, lost } = fitTool(big(60, 1), 1200) + expect(size(tool)).toBeLessThanOrEqual(1200) + expect(lost.dropped.length).toBeGreaterThan(0) + expect(tool.inputSchema.properties.p0).toBeDefined() +}) + +test("fitTools reports each changed tool once and leaves the rest", () => { + const rows = [] + const out = fitTools([small, big()], { report: (r) => rows.push(r) }) + expect(out[0]).toBe(small) + expect(rows.length).toBe(1) + expect(rows[0].tool).toBe("big") + expect(rows[0].stillOver).toBe(false) +}) + +test("a tool that cannot fit is reported as still over", () => { + const rows = [] + const t = { name: "n", description: "", inputSchema: { type: "object", properties: { a: { type: "string", enum: Array.from({ length: 500 }, (_, i) => "value" + i) } }, required: ["a"] } } + fitTools([t], { report: (r) => rows.push(r) }) + expect(rows[0].stillOver).toBe(true) +}) + +test("72 realistic tools all end under the budget", () => { + const tools = Array.from({ length: 72 }, (_, i) => (i % 5 === 0 ? { ...big(15, 200), name: `t${i}` } : { ...small, name: `t${i}` })) + for (const t of fitTools(tools)) expect(size(t)).toBeLessThanOrEqual(DEFAULT_TOOL_BUDGET) +}) + +test("AGY_BRIDGE_TOOL_BUDGET changes the budget, 0 turns it off", () => { + expect(toolBudget({ AGY_BRIDGE_TOOL_BUDGET: "900" })).toBe(900) + expect(toolBudget({})).toBe(DEFAULT_TOOL_BUDGET) + const b = big() + expect(fitTool(b, toolBudget({ AGY_BRIDGE_TOOL_BUDGET: "0" })).tool).toBe(b) +}) diff --git a/packages/agy-cli/tool-budget.mjs b/packages/agy-cli/tool-budget.mjs new file mode 100644 index 0000000..7591484 --- /dev/null +++ b/packages/agy-cli/tool-budget.mjs @@ -0,0 +1,98 @@ +// agy lazy-loads MCP tools (McpToolConfig.EnableLazyLoad and a call_mcp_tool +// tool in the agy binary): a tool whose advertised declaration is large is not +// put in the model's function list, and nothing tells the model it exists. +// Observed on agy 1.5.4 / Gemini 4 Carbon (plugins#989): tools of about 691 +// tokens and up were missing, ones of about 561 and below were present. The +// cut-off is not in the binary, so the budget below stays under the lowest +// kept size and can be changed with AGY_BRIDGE_TOOL_BUDGET (characters). +export const DEFAULT_TOOL_BUDGET = 2000 // ~500 tokens at 4 characters a token +const MIN_DESCRIPTION = 240 +const NESTED_DESCRIPTION = 90 + +export function toolBudget(env = process.env) { + const n = Number(env.AGY_BRIDGE_TOOL_BUDGET) + return Number.isFinite(n) && n >= 0 ? Math.floor(n) : DEFAULT_TOOL_BUDGET +} + +const size = (tool) => JSON.stringify({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema }).length +const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v) + +// Schema keywords that carry a nested schema map (names are data, not keywords). +const MAPS = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"] +const SINGLE = ["items", "additionalProperties", "not", "if", "then", "else", "contains", "propertyNames", "unevaluatedProperties"] +const LISTS = ["anyOf", "oneOf", "allOf", "prefixItems"] + +function walk(node, fn, top = true) { + if (!isObject(node)) return node + const out = { ...node } + fn(out, top) + for (const key of MAPS) { + if (isObject(out[key])) out[key] = Object.fromEntries(Object.entries(out[key]).map(([k, v]) => [k, walk(v, fn, false)])) + } + for (const key of SINGLE) if (isObject(out[key])) out[key] = walk(out[key], fn, false) + for (const key of LISTS) if (Array.isArray(out[key])) out[key] = out[key].map((v) => walk(v, fn, false)) + return out +} + +function cut(text, max) { + if (text.length <= max) return text + return text.slice(0, Math.max(0, max - 1)).trimEnd() + "…" +} + +// Largest optional property of the top-level object, by serialized size. +function dropLargestOptional(schema) { + const props = schema.properties + if (!isObject(props)) return null + const required = new Set(Array.isArray(schema.required) ? schema.required : []) + let pick = null + let pickSize = -1 + for (const [name, value] of Object.entries(props)) { + if (required.has(name)) continue + const s = JSON.stringify(value).length + if (s > pickSize) { pick = name; pickSize = s } + } + if (pick === null) return null + const { [pick]: _gone, ...rest } = props + return { name: pick, schema: { ...schema, properties: rest } } +} + +// Fits one tool under the budget, losing the least meaning first. Returns the +// tool and what was lost: { steps: [...], dropped: [property names] }. +export function fitTool(tool, budget = toolBudget()) { + const lost = { steps: [], dropped: [] } + if (!budget || size(tool) <= budget) return { tool, lost } + let cur = { ...tool } + const step = (name, next) => { + if (size(next) < size(cur)) { cur = next; lost.steps.push(name) } + return size(cur) <= budget + } + const noise = new Set(["default", "examples", "example", "title", "$comment", "deprecated", "readOnly", "writeOnly"]) + if (step("noise", { ...cur, inputSchema: walk(cur.inputSchema, (n) => { for (const k of noise) delete n[k] }) })) return { tool: cur, lost } + if (step("nested-descriptions", { ...cur, inputSchema: walk(cur.inputSchema, (n, top) => { + if (!top && typeof n.description === "string") n.description = cut(n.description, NESTED_DESCRIPTION) + }) })) return { tool: cur, lost } + if (step("tool-description", { ...cur, description: cut(cur.description, Math.max(MIN_DESCRIPTION, budget - (size({ ...cur, description: "" })))) })) return { tool: cur, lost } + if (step("nested-descriptions-removed", { ...cur, inputSchema: walk(cur.inputSchema, (n, top) => { if (!top) delete n.description }) })) return { tool: cur, lost } + if (step("tool-description-short", { ...cur, description: cut(cur.description, MIN_DESCRIPTION) })) return { tool: cur, lost } + while (size(cur) > budget) { + const next = dropLargestOptional(cur.inputSchema) + if (!next) break + cur = { ...cur, inputSchema: next.schema } + lost.dropped.push(next.name) + } + return { tool: cur, lost } +} + +// Fits every tool. report(row) is called once per tool that changed or still +// does not fit, so the loss is never silent. +export function fitTools(tools, { budget = toolBudget(), report = () => {} } = {}) { + return tools.map((tool) => { + const before = size(tool) + const { tool: fitted, lost } = fitTool(tool, budget) + const after = size(fitted) + if (fitted !== tool) { + report({ tool: tool.name, before, after, budget, ...lost, stillOver: budget > 0 && after > budget }) + } + return fitted + }) +}