diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index 3d18490..b1a7c0b 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -13,6 +13,7 @@ import { sanitizePatternFields } from "./re2-pattern.mjs" import { startLogin } from "./login.mjs" import { ensureGeminiArrayItems } from "./array-items.mjs" import { expandToolSchema } from "./tool-schema.mjs" +import { fitTools } from "./tool-budget.mjs" import { hint, outgoing, turnsAway } from "./cloak.mjs" import { modelUsageCursor, modelUsageAfter, sessionDbPath } from "./step-usage.mjs" @@ -1798,7 +1799,16 @@ class Proc { // the server marks it always loaded; tools with larger schemas were left out // and the model could not reach them (#989). Every client-declared tool is // one the client means the model to see. - return this.tools.map((tool) => ({ ...tool, _meta: { ...tool._meta, [ALWAYS_LOAD]: true } })) + // + // agy holds them all in a 20,000-token budget and drops whole tools, + // the largest first, past it; fitTools shortens their descriptions + // instead, so every tool stays (plugins#1140). The trimmed list is kept + // per catalog: agy asks again on every tools/list_changed. + if (this.fittedFor !== this.toolsSignature) { + this.fitted = fitTools(this.tools.map((tool) => ({ ...tool, _meta: { ...tool._meta, [ALWAYS_LOAD]: true } }))) + this.fittedFor = this.toolsSignature + } + return this.fitted } addWatcher(socket) { diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index ad9c2c9..97538a9 100644 --- a/packages/agy-cli/package.json +++ b/packages/agy-cli/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.45", + "version": "0.1.46", "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,7 +15,7 @@ "login.mjs", "mcp-server.mjs", "step-usage.mjs", - "tool-schema.mjs", + "tool-schema.mjs", "tool-budget.mjs", "usage.mjs", "signin.mjs", "README.md", diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index ffe02ba..0902dd6 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -38,6 +38,7 @@ 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 SIGNIN_FILE = path.join(REPO_DIR, "signin.mjs") export const TOOL_SCHEMA_FILE = path.join(REPO_DIR, "tool-schema.mjs") +export const TOOL_BUDGET_FILE = path.join(REPO_DIR, "tool-budget.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 @@ -530,6 +531,7 @@ export async function createBridgeKit(options = {}) { const stepUsageUrl = pathToFileURL(STEP_USAGE_FILE).href const signinUrl = pathToFileURL(SIGNIN_FILE).href const toolSchemaUrl = pathToFileURL(TOOL_SCHEMA_FILE).href + const toolBudgetUrl = pathToFileURL(TOOL_BUDGET_FILE).href const linker = (specifier) => { const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER ? specifier @@ -545,6 +547,7 @@ export async function createBridgeKit(options = {}) { else if (key === "./step-usage.mjs") module = sourceModule(STEP_USAGE_FILE, "", stepUsageUrl) else if (key === "./signin.mjs") module = sourceModule(SIGNIN_FILE, "", signinUrl) else if (key === "./tool-schema.mjs") module = sourceModule(TOOL_SCHEMA_FILE, "", toolSchemaUrl) + else if (key === "./tool-budget.mjs") module = sourceModule(TOOL_BUDGET_FILE, "", toolBudgetUrl) else if (key.startsWith("node:")) module = builtinModule(key, overrides[key]) else throw new Error(`testkit: 未登记的依赖 ${specifier}`) cache.set(key, module) diff --git a/packages/agy-cli/test/tool-budget.mjs b/packages/agy-cli/test/tool-budget.mjs new file mode 100644 index 0000000..532d56e --- /dev/null +++ b/packages/agy-cli/test/tool-budget.mjs @@ -0,0 +1,105 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { TOOL_TOKEN_BUDGET, agyTokens, cut, fitTools } from "../tool-budget.mjs" + +const total = (tools) => tools.reduce((n, t) => n + agyTokens(JSON.stringify(t)), 0) + +// a schema with its prose taken out, so two shapes compare by what the model +// may send +function structure(node) { + if (Array.isArray(node)) return node.map(structure) + if (!node || typeof node !== "object") return node + const out = {} + for (const [k, v] of Object.entries(node)) { + if (k === "description") continue + out[k] = k === "properties" ? Object.fromEntries(Object.entries(v).map(([n, s]) => [n, structure(s)])) : structure(v) + } + return out +} +const undecorated = (node) => { + if (Array.isArray(node)) return node.map(undecorated) + if (!node || typeof node !== "object") return node + const out = {} + for (const [k, v] of Object.entries(node)) { + if (["$schema", "title", "examples"].includes(k)) continue + out[k] = k === "properties" ? Object.fromEntries(Object.entries(v).map(([n, s]) => [n, undecorated(s)])) : undecorated(v) + } + return out +} + +const long = (what, n) => `${what} does the thing it says. `.repeat(n) + "Examples: " + `${what}("a"), ${what}("b"). `.repeat(n) + +// a client's catalog about plugins#1140's size: 80 tools, each with a +// long description, long property texts, an enum, a property named "title" +// and one contract property whose text is all there is to it +function catalog(n = 80, size = 2) { + return Array.from({ length: n }, (_, i) => ({ + name: `tool_${i}`, + description: long(`tool_${i}`, size), + inputSchema: { + $schema: "https://json-schema.org/draft/2020-12/schema", + type: "object", + title: `Tool ${i}`, + properties: { + title: { type: "string", description: long("title", size), examples: ["x"] }, + mode: { type: "string", enum: ["a", "b"], description: "Short." }, + style: { type: "object", description: "Variants: " + long("style", size) }, + list: { type: "array", items: { type: "string", description: long("item", size) } }, + }, + required: ["title"], + }, + _meta: { "antigravity/alwaysLoad": true }, + })) +} + +test("a catalog within the budget goes as it is", () => { + const tools = catalog(10, 1) + assert.ok(total(tools) <= TOOL_TOKEN_BUDGET) + assert.equal(fitTools(tools), tools) +}) + +test("a catalog over the budget keeps every tool and its whole schema, and fits", () => { + const tools = catalog() + // about plugins#1140's 131 tools (~76 KB, ~25,000 agy tokens) + assert.ok(total(tools) > 20000 && total(tools) < 30000, `the fixture is over agy's budget (${total(tools)})`) + const fitted = fitTools(tools) + assert.ok(total(fitted) <= TOOL_TOKEN_BUDGET, `fits (${total(fitted)})`) + assert.deepEqual(fitted.map((t) => t.name), tools.map((t) => t.name)) + for (let i = 0; i < tools.length; i++) { + // nothing that decides a valid argument changes: names, types, enum, + // required, items; a property named "title" is the client's and stays + assert.deepEqual(structure(fitted[i].inputSchema), structure(undecorated(tools[i].inputSchema))) + assert.ok(fitted[i].inputSchema.properties.title, "the property named title stays") + assert.equal(fitted[i].inputSchema.$schema, undefined) + assert.equal(fitted[i].inputSchema.title, undefined) + assert.deepEqual(fitted[i]._meta, tools[i]._meta) + const p = fitted[i].inputSchema.properties + // a short description is left whole; long ones are cut, a contract's least + assert.equal(p.mode.description, "Short.") + assert.ok(p.title.description.length < tools[i].inputSchema.properties.title.description.length) + assert.ok(p.style.description.length > p.title.description.length, "a contract keeps more") + assert.ok(fitted[i].description.length >= p.title.description.length, "a tool's own keeps more") + } + // the client's catalog itself is untouched + assert.equal(tools[0].inputSchema.title, "Tool 0") +}) + +test("a catalog too large for any description keeps every tool", () => { + const tools = catalog(400, 6) + const fitted = fitTools(tools) + assert.deepEqual(fitted.map((t) => t.name), tools.map((t) => t.name)) + for (const t of fitted) assert.equal(t.inputSchema.properties.title.description, undefined) +}) + +test("cut stops on a whole character, within the bytes, and drops the examples first", () => { + const zh = "这是一个很长的中文说明,每个字是三个字节。".repeat(10) + for (const max of [10, 11, 12, 40, 100]) { + const out = cut(zh, max) + assert.ok(new TextEncoder().encode(out).length <= max, `${max}: ${out}`) + assert.ok(!out.includes("�")) + assert.ok(out.endsWith("…")) + } + assert.equal(cut("Reads a file. Examples: read('a'), read('b')", 20), "Reads a file.") + assert.equal(cut("short", 100), "short") + assert.equal(cut("anything longer", 3), null) +}) diff --git a/packages/agy-cli/test/tool-schema.mjs b/packages/agy-cli/test/tool-schema.mjs index 519f6ba..09c4939 100644 --- a/packages/agy-cli/test/tool-schema.mjs +++ b/packages/agy-cli/test/tool-schema.mjs @@ -687,3 +687,45 @@ test("bridge request path delivers expanded schemas to MCP tools/list without in await kit.dispose() } }) + +// plugins#1140: agy drops whole tools, the largest first, past its 20,000 +// customization tokens (ceil(UTF-8 bytes / 3)). Over the bridge, a catalog +// larger than that comes back to agy whole, with shorter descriptions. +test("bridge tools/list keeps every tool of a catalog over agy's budget, within it", async () => { + const kit = await createBridgeKit() + try { + let listed = null + kit.prompts.push(async (agent) => { + listed = await agent.listTools() + await agent.text("checked tools") + }) + const prose = (n) => "Runs the step it names and says what it did. ".repeat(n) + "Examples: step('a'), step('b')." + const tools = Array.from({ length: 100 }, (_, i) => ({ + name: `big_tool_${i}`, + description: prose(8), + input_schema: { + type: "object", + properties: { + path: { type: "string", description: prose(6) }, + mode: { type: "string", enum: ["fast", "safe"], description: "How." }, + }, + required: ["path"], + }, + })) + const tokens = (list) => list.reduce((n, t) => n + Math.ceil(Buffer.byteLength(JSON.stringify(t), "utf8") / 3), 0) + const res = await kit.request(baseBody({ tools })) + await readSse(res) + const mcpTools = listed?.result?.tools ?? [] + assert.deepEqual(mcpTools.map((t) => t.name), tools.map((t) => t.name)) + assert.ok(tokens(tools) > 20000, `the catalog is over agy's budget (${tokens(tools)})`) + assert.ok(tokens(mcpTools) <= 18000, `what agy is given fits (${tokens(mcpTools)})`) + for (const t of mcpTools) { + assert.deepEqual(t.inputSchema.required, ["path"]) + assert.deepEqual(t.inputSchema.properties.mode.enum, ["fast", "safe"]) + assert.equal(t.inputSchema.properties.mode.description, "How.") + assert.equal(t._meta?.["antigravity/alwaysLoad"], true) + } + } finally { + await kit.dispose() + } +}) diff --git a/packages/agy-cli/tool-budget.mjs b/packages/agy-cli/tool-budget.mjs new file mode 100644 index 0000000..0100a52 --- /dev/null +++ b/packages/agy-cli/tool-budget.mjs @@ -0,0 +1,139 @@ +// agy holds every MCP tool it loads into one customization budget of 20,000 +// tokens, counted as ceil(UTF-8 bytes / 3). Over it, agy drops whole tools, +// the largest first, so the best-documented ones (bash, a canvas's write +// tool) vanish from the model's function list, and with `tools: []` there is +// no other way to reach them (plugins#1140). fitTools trims the tools' prose +// instead, so every tool and every bit of its schema stays: names, property +// names, types, enums, required, items, anyOf and the bounds all go as the +// client wrote them. Only descriptions are shortened, and only as far as the +// budget needs. + +// What the listed tools may take of agy's 20,000: the rest is room for the +// server prefix agy adds to each name and its own serialization. +export const TOOL_TOKEN_BUDGET = 18000 + +const enc = new TextEncoder() +const bytes = (s) => enc.encode(s).length +export const agyTokens = (s) => Math.ceil(bytes(s) / 3) + +const tokensOf = (tools) => tools.reduce((n, tool) => n + agyTokens(JSON.stringify(tool)), 0) + +// Keywords that say nothing about which arguments are valid. They are taken +// out only where they are keywords: a property named "title" is the +// client's, and stays. +const DECOR = new Set(["$schema", "title", "examples"]) + +// A property whose description is its contract: an object with no +// properties of its own, or one whose description carries the branches +// tool-schema.mjs folded out of an anyOf/oneOf. Its text is the only place +// the model learns what goes in it, so it keeps more of it. +const CONTRACT_WEIGHT = 11 +const TOOL_WEIGHT = 2.5 + +function isContract(node) { + if (!node || typeof node !== "object") return false + const d = typeof node.description === "string" ? node.description : "" + if (/\b(Variants|Accepts anyOf):/.test(d)) return true + const types = Array.isArray(node.type) ? node.type : [node.type] + return types.includes("object") && !(node.properties && Object.keys(node.properties).length) +} + +// cut shortens text to at most max UTF-8 bytes. It drops a trailing +// Examples block first, then ends on a sentence boundary where one is near, +// else on a whole code point, and marks the cut with "…". null when nothing +// worth keeping fits. +export function cut(text, max) { + if (bytes(text) <= max) return text + const bare = text.replace(/\s*\bExamples?:[\s\S]*$/i, "").trimEnd() + if (bare && bytes(bare) <= max) return bare + const room = max - bytes("…") + if (room < 4) return null + let out = "" + let used = 0 + for (const ch of bare || text) { + const b = bytes(ch) + if (used + b > room) break + out += ch + used += b + } + const stop = Math.max(...[". ", "; ", "。", ";"].map((p) => out.lastIndexOf(p))) + if (stop > out.length / 2) out = out.slice(0, stop + 1) + return out.trimEnd() + "…" +} + +// walk copies one schema node with every description capped: cap(node) +// gives the byte cap for a node's description, and Infinity leaves it. +// strip takes the decorative keywords out too. +function walk(node, cap, strip) { + if (Array.isArray(node)) return node.map((item) => walk(item, cap, strip)) + if (!node || typeof node !== "object") return node + const out = {} + for (const [key, value] of Object.entries(node)) { + if (strip && DECOR.has(key)) continue + if (key === "description" && typeof value === "string") { + const max = cap(node) + const text = max === Infinity ? value : cut(value, max) + if (text) out.description = text + continue + } + if ((key === "properties" || key === "$defs" || key === "definitions" || key === "patternProperties") && value && typeof value === "object" && !Array.isArray(value)) { + // a map of names to schemas: the names are the client's, never keywords + out[key] = Object.fromEntries(Object.entries(value).map(([name, schema]) => [name, walk(schema, cap, strip)])) + continue + } + if (key === "enum" || key === "const" || key === "default" || key === "required") { + out[key] = value + continue + } + out[key] = walk(value, cap, strip) + } + return out +} + +function shaped(tools, { strip, L, top }) { + const prop = L === undefined ? () => Infinity : (node) => (isContract(node) ? CONTRACT_WEIGHT * L : L) + return tools.map((tool) => { + const out = { ...tool } + if (tool.inputSchema && typeof tool.inputSchema === "object") out.inputSchema = walk(tool.inputSchema, prop, strip) + if (typeof tool.description === "string") { + const max = top ?? (L === undefined ? Infinity : TOOL_WEIGHT * L) + const text = max === Infinity ? tool.description : cut(tool.description, max) + if (text) out.description = text + else delete out.description + } + return out + }) +} + +// highest finds the largest whole n in [lo, hi] for which fits(n) holds, +// given that it holds at lo; fits is monotone in n. +function highest(lo, hi, fits) { + while (lo < hi) { + const mid = Math.ceil((lo + hi) / 2) + if (fits(mid)) lo = mid + else hi = mid - 1 + } + return lo +} + +// fitTools gives the tools as agy should list them: unchanged when they fit +// the budget, else with the decorative keywords gone, then with every +// description capped at the highest level that fits (a tool's own +// description gets 2.5 times a property's, a contract property's 11 times), +// and when that level is nothing, with the properties' descriptions gone and +// the tools' own capped alone. A set too large even with no descriptions at +// all goes as small as it can, and agy drops what is left over. +export function fitTools(tools, budget = TOOL_TOKEN_BUDGET) { + if (tokensOf(tools) <= budget) return tools + const stripped = shaped(tools, { strip: true }) + if (tokensOf(stripped) <= budget) return stripped + const at = (L) => shaped(tools, { strip: true, L }) + const fits = (L) => tokensOf(at(L)) <= budget + if (!fits(0)) return at(0) + const L = highest(0, 4000, fits) + if (L > 0) return at(L) + // the properties' descriptions are gone; what room is left goes to the + // tools' own, which say what each tool is for + const bare = (top) => shaped(tools, { strip: true, L: 0, top }) + return bare(highest(0, 4000, (top) => tokensOf(bare(top)) <= budget)) +}