diff --git a/src/server/budget.ts b/src/server/budget.ts index db6def2588..5c5296fe91 100644 --- a/src/server/budget.ts +++ b/src/server/budget.ts @@ -21,13 +21,46 @@ const OUTPUT_CLAMP_FLOOR = 1024; // host-side: renderNudgeText does not depend on shouldInject. const EMERGENCY_NUDGE_ESCALATION_PCT = 0.7; +/** #2391: a budget view only; never forward this projection. OpenAI tool search + * defers individual function schemas, while namespace descriptions stay visible. + * https://developers.openai.com/api/docs/guides/tools-tool-search */ +export function modelVisibleTools(tools: unknown): unknown { + if (!Array.isArray(tools) || !tools.some((t) => t?.type === "tool_search")) return tools ?? []; + const project = (tool: unknown): unknown => { + if (!tool || typeof tool !== "object") return tool; + const item = tool as Record; + if (item.type === "namespace" && Array.isArray(item.tools)) { + return { ...item, tools: item.tools.map(project) }; + } + if (item.type === "function" && typeof item.name === "string" + && item.parameters && typeof item.parameters === "object" + && !Array.isArray(item.parameters) && item.defer_loading === true) { + return { type: item.type, name: item.name, defer_loading: true }; + } + return tool; + }; + return tools.map(project); +} + +/** Loaded definitions count in full even if they still carry defer_loading. */ +export function countLoadedToolTokens(body: Record): number { + if (!Array.isArray(body.input)) return 0; + let tokens = 0; + for (const item of body.input) { + if (["additional_tools", "tool_search_call", "tool_search_output", "mcp_list_tools"].includes(item?.type)) { + tokens += defaultCountTokens(JSON.stringify(item)); + } + } + return tokens; +} + /** chars/4 measure of the per-request overhead that lives OUTSIDE the kernel's * fold space: the outbound system prompt (client text plus bili-injected parts) * and the tool schemas. The kernel's contextBreakdown classifies messages only, * so this is what the status panel's SysPrompt row must add back (#532). Same * counting method as estimateInputTokens below. */ export function countSystemAndToolsTokens(systemText: string | undefined, tools: unknown): number { - return defaultCountTokens(systemText ?? "") + defaultCountTokens(JSON.stringify(tools ?? [])); + return defaultCountTokens(systemText ?? "") + defaultCountTokens(JSON.stringify(modelVisibleTools(tools))); } /** Conservative outbound-input estimate: the larger of the upstream-reported @@ -44,8 +77,8 @@ export function countSystemAndToolsTokens(systemText: string | undefined, tools: * raw chars/4 est ~137K vs provider-billed ~81K) used to win the max() raw * and starve the output clamp (32768 -> 3357 with ample actual headroom). * The usage-grade baseline is already provider-measured and is NEVER scaled. */ -export function estimateInputTokens(processedMessages: CoreMessage[], systemText: string | undefined, tools: unknown, lastInputTokens: number, lastInputTokensSource?: string, kFactor?: number, kOrigin?: string, origin?: string): number { - const est = applyEstimateCalibration(estimateCoreMessages(processedMessages) + countSystemAndToolsTokens(systemText, tools), kFactor, kOrigin, origin); +export function estimateInputTokens(processedMessages: CoreMessage[], systemText: string | undefined, tools: unknown, lastInputTokens: number, lastInputTokensSource?: string, kFactor?: number, kOrigin?: string, origin?: string, loadedToolTokens = 0): number { + const est = applyEstimateCalibration(estimateCoreMessages(processedMessages) + countSystemAndToolsTokens(systemText, tools) + loadedToolTokens, kFactor, kOrigin, origin); const baseline = lastInputTokens > 0 && lastInputTokensSource === "usage" ? lastInputTokens : 0; return Math.max(baseline, est); } @@ -184,7 +217,9 @@ export function estimateWireOverhead(protocol: "anthropic" | "openai" | "respons .join("\n"); if (hoisted) sysText = sysText ? `${sysText}\n${hoisted}` : hoisted; } - return defaultCountTokens(sysText) + defaultCountTokens(JSON.stringify(parsed.tools ?? [])); + return defaultCountTokens(sysText) + + defaultCountTokens(JSON.stringify(protocol === "responses" ? modelVisibleTools(parsed.tools) : parsed.tools ?? [])) + + (protocol === "responses" ? countLoadedToolTokens(parsed) : 0); } /** Output-budget cap so input+output <= window. Returns the clamped budget, or @@ -246,7 +281,8 @@ export function clampOutgoingOutput( if (typeof raw !== "number") return; // #488: images ride along in the rebuilt body but are invisible to the text model — // without them the cap is too generous and input+output can still overflow. - const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens, ctx.lastInputTokensSource, ctx.kFactor, ctx.kOrigin, ctx.origin) + ctx.imageTokens; + const loadedToolTokens = field === "max_output_tokens" ? countLoadedToolTokens(rebuilt) : 0; + const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens, ctx.lastInputTokensSource, ctx.kFactor, ctx.kOrigin, ctx.origin, loadedToolTokens) + ctx.imageTokens; const capped = clampOutputBudget(raw, inputEstimate, ctx.nativeWindow); if (capped !== undefined) { writeOutputBudget(rebuilt, field, capped); diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index e9d1d3dc44..31bb326d59 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -29,7 +29,7 @@ import { stripAcpPanelResponsesInput, stripAcpStatusMarkers } from "../acp-panel import type { ConversationIdentity } from "../session-id.js"; import { stripEmbeddedChainCarriers } from "../chain-checkpoint.js"; import { keepResponseId as knobKeepResponseId, noCompressPrompt as knobNoCompressPrompt, noInjectTool as knobNoInjectTool, renderNone as knobRenderNone } from "../knobs.js"; -import { clampOutgoingOutput, countSystemAndToolsTokens, emergencyNudge } from "./budget.js"; +import { clampOutgoingOutput, countLoadedToolTokens, countSystemAndToolsTokens, emergencyNudge, modelVisibleTools } from "./budget.js"; import { FORCE_TEXT_PROTOCOL, injectResponsesTool, injectTool } from "./inject.js"; export async function prepareResponses( @@ -456,8 +456,14 @@ export async function prepareResponses( // On this wire the system rides the injected developer message outside the // fold space, so counting devContent + tools does not double-count the // mid-history items the kernel already classifies. + const loadedToolTokens = countLoadedToolTokens(rebuilt); if (transformOk) { - session.metadata.systemPromptTokens = countSystemAndToolsTokens(responsesDevContent ?? "", toolsOut); + session.metadata.systemPromptTokens = countSystemAndToolsTokens(responsesDevContent ?? "", toolsOut) + loadedToolTokens; + const catalogTokens = defaultCountTokens(JSON.stringify(toolsOut ?? [])); + const visibleTokens = defaultCountTokens(JSON.stringify(modelVisibleTools(toolsOut))); + if (catalogTokens >= 50_000 || catalogTokens !== visibleTokens || loadedToolTokens > 0) { + log("info", `[${sessionId}] tool-budget catalog~${catalogTokens} visible~${visibleTokens} loaded~${loadedToolTokens} instruction~${defaultCountTokens(responsesDevContent ?? "")} tokens (estimates; definitions preserved)`); + } } // #728: record this turn's outbound payload upper bound as the fallback // token source for upstreams that never report usage (see effectiveTokenCount). @@ -466,11 +472,13 @@ export async function prepareResponses( if (!isCompactionTrigger) { session.stats.localInputEstimate = estimateCoreMessagesUpper(processedMessages.length > 0 ? processedMessages : originalMessages) + countSystemAndToolsTokens(responsesDevContent ?? "", toolsOut) + + loadedToolTokens + imageReserveFor(session, "responses", rebuilt, opts, billingUpstream ?? upstreamOrigin); // #1933 F1: billed-caliber twin (chars/4) for the kĖ‚ learning pair — // see the anthropic-lane counterpart above. session.stats.lastLocalTextEstimate = estimateCoreMessages(processedMessages.length > 0 ? processedMessages : originalMessages) + countSystemAndToolsTokens(responsesDevContent ?? "", toolsOut) + + loadedToolTokens + imageReserveFor(session, "responses", rebuilt, opts, billingUpstream ?? upstreamOrigin); const responsesPairOrigin = billingUpstream ?? upstreamOrigin; if (responsesPairOrigin) session.stats.lastLocalTextEstimateOrigin = responsesPairOrigin; diff --git a/tests/deferred-tool-budget.test.ts b/tests/deferred-tool-budget.test.ts new file mode 100644 index 0000000000..8cf60af4b7 --- /dev/null +++ b/tests/deferred-tool-budget.test.ts @@ -0,0 +1,160 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig, defaultCountTokens } from "acp-kernel"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { startServer } from "../src/server.ts"; +import { clampOutgoingOutput, countLoadedToolTokens, countSystemAndToolsTokens, estimateInputTokens, estimateWireOverhead, modelVisibleTools } from "../src/server/budget.ts"; + +const deferred = { + type: "function", name: "large_schema", description: "x".repeat(1_200_000), + parameters: { type: "object", properties: {} }, defer_loading: true, +}; +const search = { type: "tool_search" }; +const tools = [deferred, search]; + +test("#2391: deferred Responses schemas do not consume the visible tool budget", () => { + const body = { instructions: "SHORT", tools, input: [{ type: "message", role: "user", content: "hello" }] }; + const before = JSON.stringify(body); + assert.ok(defaultCountTokens(JSON.stringify(tools)) > 272_000); + assert.ok(countSystemAndToolsTokens(body.instructions, tools) < 100); + assert.ok(estimateWireOverhead("responses", before) < 100); + assert.equal(JSON.stringify(body), before, "budget projection must not mutate the forwarded catalog"); + assert.ok(countSystemAndToolsTokens(body.instructions, [deferred]) > 272_000, "without tool search, retain the full schema"); + assert.ok(countSystemAndToolsTokens(body.instructions, [{ ...deferred, defer_loading: false }, search]) > 272_000); +}); + +test("#2391: namespace descriptions and eager members remain visible; flags are not inherited", () => { + const inherited = { type: "function", name: "eager", description: "e".repeat(4000), parameters: { type: "object" } }; + const namespace = { type: "namespace", name: "workspace", description: "n".repeat(4000), defer_loading: true, tools: [deferred, inherited] }; + const original = [namespace, search]; + assert.deepEqual(modelVisibleTools(original), [{ ...namespace, tools: [ + { type: "function", name: deferred.name, defer_loading: true }, inherited, + ] }, search]); + assert.ok(countSystemAndToolsTokens("", original) >= 2000); + assert.equal(namespace.tools[0].description, deferred.description); +}); + +test("#2391: unknown flags, tool kinds, malformed schemas and Chat Completions stay conservative", () => { + const cases = [ + { ...deferred, defer_loading: "true" }, + { ...deferred, type: "custom" }, + { ...deferred, name: undefined }, + { ...deferred, parameters: [] }, + { ...deferred, parameters: null }, + { type: "function", function: { name: "chat", description: deferred.description, parameters: {} }, defer_loading: true }, + ]; + for (const candidate of cases) { + const catalog = [candidate, search]; + assert.deepEqual(modelVisibleTools(catalog), catalog); + assert.ok(countSystemAndToolsTokens("", catalog) > 272_000); + } + const chat = { messages: [], tools }; + assert.equal(estimateWireOverhead("openai", JSON.stringify(chat)), defaultCountTokens(JSON.stringify(tools))); +}); + +test("#2391: loaded records count in full even when the definitions still say deferred", () => { + for (const type of ["additional_tools", "tool_search_call", "tool_search_output", "mcp_list_tools"]) { + const loaded = { type, tools: [deferred], call_id: "loaded" }; + const body = { instructions: "SHORT", tools, input: [loaded] }; + const before = JSON.stringify(body); + const loadedTokens = defaultCountTokens(JSON.stringify(loaded)); + assert.equal(countLoadedToolTokens(body), loadedTokens); + assert.equal(estimateWireOverhead("responses", before), countSystemAndToolsTokens(body.instructions, tools) + loadedTokens); + assert.ok(estimateWireOverhead("responses", before) > 272_000); + assert.equal(JSON.stringify(body), before); + } + assert.equal(countLoadedToolTokens({ input: [] }), 0); + assert.equal(countLoadedToolTokens({ input: "hello" }), 0); +}); + +test("#2391: usage remains authoritative; loaded definitions enter calibration before the max", () => { + const visible = countSystemAndToolsTokens("", tools); + assert.equal(estimateInputTokens([], "", tools, 300_000, "usage"), 300_000); + assert.equal(estimateInputTokens([], "", tools, 300_000, "estimate"), visible); + assert.equal(estimateInputTokens([], "", tools, 250_000, "usage", undefined, undefined, undefined, 100_000), 250_000); + assert.equal(estimateInputTokens([], "", tools, 0, "estimate", 0.5, "fixture", "fixture", 100_000), (visible + 100_000) * 0.5); +}); + +test("#2391: output headroom includes loaded schemas without adding them again to usage", () => { + const loaded = { ...deferred, description: "l".repeat(780_000) }; + const body = { tools, input: [{ type: "additional_tools", tools: [loaded] }], max_output_tokens: 100_000 }; + const context = { processedMessages: [], systemText: "", tools, lastInputTokens: 0, imageTokens: 0, nativeWindow: 272_000 }; + clampOutgoingOutput(body, "max_output_tokens", context, "fixture", () => {}); + assert.ok(body.max_output_tokens < 100_000 && body.max_output_tokens > 60_000); + const usageBody = { ...body, max_output_tokens: 100_000 }; + clampOutgoingOutput(usageBody, "max_output_tokens", { ...context, lastInputTokens: 200_000, lastInputTokensSource: "usage" }, "fixture", () => {}); + assert.equal(usageBody.max_output_tokens, 62_000); +}); + +test("#2391: a 272k Responses proxy forwards the full deferred catalog and rejects eager/loaded overflow", async () => { + const received: Record[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + received.push(JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ id: "resp_fixture", object: "response", status: "completed", output: [], usage: { input_tokens: 10, output_tokens: 0, total_tokens: 10 } })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + const origin = `http://127.0.0.1:${upstreamPort}`; + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + let proxy: http.Server | undefined; + try { + proxy = await startServer({ + port: 0, host: "127.0.0.1", upstream: origin, + routes: { [origin]: { proxy: "", models: { "fixture-gpt": { context: 272_000, compress: { modelContextLimit: 272_000 } } } } }, + modelContextLimit: 272_000, kernelConfig: defaultConfig(272_000), + compress: { injectTool: false, injectNudge: false }, promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", log: false, debug: false, passthrough: false, + passthroughSource: null, autoUpdate: false, autoRestartOnUpdate: false, updateTag: "latest", + advisoryCheck: false, releaseNotesCheck: false, compat: { roles: {} }, + streamErrorShape: "protocol", mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + const body = { model: "fixture-gpt", stream: false, tools, max_output_tokens: 68_000, + input: [{ type: "message", role: "user", content: "hello" }] }; + const send = (payload: unknown, session: string) => fetch(`http://127.0.0.1:${proxyPort}/bili/${origin}/v1/responses`, { + method: "POST", headers: { "content-type": "application/json", "x-acp-session": session }, body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000), + }); + const accepted = await send(body, "2391-deferred"); + assert.equal(accepted.status, 200, await accepted.text()); + assert.equal(received.length, 1); + assert.deepEqual(received[0].tools, tools, "full upstream definitions must stay unchanged"); + const eager = await send({ ...body, tools: [{ ...deferred, defer_loading: false }, search] }, "2391-eager"); + assert.notEqual(eager.status, 200, await eager.text()); + assert.equal(received.length, 1, "eager overflow must be stopped before forwarding"); + const loaded = await send({ ...body, input: [{ type: "additional_tools", tools: [deferred] }, ...body.input] }, "2391-loaded"); + assert.notEqual(loaded.status, 200, await loaded.text()); + assert.equal(received.length, 1, "loaded overflow must be stopped before forwarding"); + const small = { ...deferred, description: "small loaded definition" }; + const loadedItems = [ + { type: "additional_tools", tools: [small] }, + { type: "tool_search_call", call_id: "search_1", arguments: { goal: "large_schema" }, execution: "client" }, + { type: "tool_search_output", call_id: "search_1", tools: [small], execution: "client" }, + ]; + const loadedSmall = await send({ ...body, input: [...loadedItems, ...body.input] }, "2391-loaded-small"); + assert.equal(loadedSmall.status, 200, await loadedSmall.text()); + const forwardedInput = received.at(-1)?.input as Record[]; + assert.deepEqual(forwardedInput.filter((item) => ["additional_tools", "tool_search_call", "tool_search_output"].includes(String(item.type))), loadedItems); + assert.equal(forwardedInput[0].type, "additional_tools", "leading loaded definitions must retain their position"); + } finally { + proxy?.closeAllConnections(); + const closingProxy = proxy; + if (closingProxy) await new Promise((resolve) => closingProxy.close(() => resolve())); + upstream.closeAllConnections(); + await new Promise((resolve) => upstream.close(() => resolve())); + } +});