From d67780d50a08449d0d1fda079219b149cd5cfc4f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 04:02:56 +0800 Subject: [PATCH] fix: plugin-lane absorb tool follows base config so manifest and gate agree (#1359) The plugin manifest advertised absorb under its static constants while per-session adjudication resolved the merged route/model name, so a renamed absorb.toolName made the advertised tool 400 (same silent-loss class as #1345, wider trigger surface: one base-level rename suffices). - resolveAbsorbSettings(): single source of truth for raw->resolved absorb, shared by applyCompressSettings and the plugin-lane base stamp. - server.ts: in plugin mode the whole absorb block follows the BASE config (advertise + adjudicate the same name); provider/model absorb.* overrides stay proxy-lane-only. Proxy mode unchanged (still honors the merged name). - plugin.ts: manifest advertises the resolved name via absorbToolsFor(), which builds byte-identical wire shapes at the default name. - config.ts: load-time per-field divergence warning (findAbsorbPluginDivergences), mirroring the #1360 ccr diagnostic. - docs (en+zh): document lane governance for absorb.toolName. - tests/absorb-plugin.test.ts: regression coverage (plugin manifest follows the resolved name and the gate agrees; proxy still honors the merged override; default shapes byte-identical; divergence diagnostic fires/stays silent). Fixes #1359 --- CONFIGURATION.md | 4 +- CONFIGURATION.zh-CN.md | 4 +- src/compress-settings.ts | 26 ++-- src/compress-tool.ts | 15 +++ src/config.ts | 41 ++++++ src/plugin.ts | 14 +- src/server.ts | 59 ++++++--- tests/absorb-plugin.test.ts | 250 ++++++++++++++++++++++++++++++++++++ 8 files changed, 372 insertions(+), 41 deletions(-) create mode 100644 tests/absorb-plugin.test.ts diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 401aa858fc..5cc294d41e 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -371,8 +371,8 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - `minToolTokens: number` — only results at or above this many tokens are prompted (kernel default 1000). - `contextThresholdPct: number|percent-string` — only prompt once usage reaches this fraction of `modelContextLimit` (`0` = size gate alone; `"75%"` is accepted). - `excludeTools: string[]` — tool-name patterns never absorbed. **Known limitation:** a no-op on tool *results* until [ranxianglei/acp-kernel#213](https://github.com/ranxianglei/acp-kernel/issues/213) ships (wire projections don't carry `toolName` on results, so the kernel's name guard can't fire). - - `toolName: string` — rename the injected tool (default `"absorb"`); the schema, system-prompt section and per-session adjudication all follow the name. - Injection follows the wire's native-tool surface: proxy mode injects the tool + a static system-prompt section on the anthropic/openai/responses native-tools wires, plugin mode advertises it in the plugin manifest **only while enabled** (hosts register the manifest's tools verbatim — advertising a disabled tool breaks them, #1192; the MCP shell picks it up for free). Responses **marker/text-protocol** routes are not supported (no native tool surface — the REQUIRED absorb instruction would be unsatisfiable), and title-generation requests (`max_tokens ≤ 200`) skip injection like the compress prompt does. Absorbed pairs stay hidden across restarts (persisted in the session state). + - `toolName: string` — rename the injected tool (default `"absorb"`); the advertised/injected schema, the system-prompt section and per-session adjudication all follow the name in both lanes. **Lane governance (#1359):** plugin mode governs the *entire* `absorb` block by the **base** config, so a renamed tool is advertised under that name and executed under it (they can never diverge); provider/model-level `absorb.*` overrides are **proxy-lane-only** (the proxy injects and adjudicates the merged name). A load-time warning lists any provider/model `absorb.*` field whose value diverges from base. + Injection follows the wire's native-tool surface: proxy mode injects the tool (under the per-request resolved name) + a system-prompt section on the anthropic/openai/responses native-tools wires, plugin mode advertises it in the plugin manifest **only while enabled** (hosts register the manifest's tools verbatim — advertising a disabled tool breaks them, #1192; the MCP shell picks it up for free). Responses **marker/text-protocol** routes are not supported (no native tool surface — the REQUIRED absorb instruction would be unsatisfiable), and title-generation requests (`max_tokens ≤ 200`) skip injection like the compress prompt does. Absorbed pairs stay hidden across restarts (persisted in the session state). #### `ccr` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 90d49a2a6e..ec52287496 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -371,8 +371,8 @@ - `minToolTokens: number` — 仅达到此 token 数的结果被附带提示(内核默认 1000)。 - `contextThresholdPct: number|percent-string` — 仅当用量达到 `modelContextLimit` 的此比例时附带提示(`0` = 仅尺寸门槛;`"75%"` 接受)。 - `excludeTools: string[]` — 永不吸收的工具名模式。**已知限制:对工具*结果*目前无效,直到 [ranxianglei/acp-kernel#213](https://github.com/ranxianglei/acp-kernel/issues/213) 修复发布**(wire 投影不把 `toolName` 携带在结果上,内核名称守卫无法命中)。 - - `toolName: string` — 重命名注入工具(默认 `"absorb"`);模式、系统提示段与按会话裁决都跟随名称。 - 注入跟随线上原生工具面:代理模式在 anthropic/openai/responses 原生工具线上注入工具 + 静态系统提示段,插件模式在插件清单中广告它(MCP shell 自动拾取)。Responses **marker/文本协议**路由不支持(无原生工具面 — 强制的 absorb 指令不可满足),标题生成请求(`max_tokens ≤ 200`)跳过注入如压缩提示一样。吸收配对在重启后保持隐藏(在会话状态持久化)。 + - `toolName: string` — 重命名注入工具(默认 `"absorb"`);声明/注入的模式、系统提示段与按会话裁决在两条车道中都跟随该名称。**车道治理(#1359):** 插件模式用**基础**配置治理整个 `absorb` 块,因此重命名后的工具既以该名声明、也以该名执行(二者永不背离);provider/model 层的 `absorb.*` 覆盖**仅限代理车道**(代理注入并裁决合并后的名称)。加载时会输出一条警告,列出任何取值与基础值不同的 provider/model `absorb.*` 字段。 + 注入跟随线上原生工具面:代理模式在 anthropic/openai/responses 原生工具线上注入工具(按每请求解析的名称)+ 系统提示段,插件模式在插件清单中广告它(MCP shell 自动拾取)。Responses **marker/文本协议**路由不支持(无原生工具面 — 强制的 absorb 指令不可满足),标题生成请求(`max_tokens ≤ 200`)跳过注入如压缩提示一样。吸收配对在重启后保持隐藏(在会话状态持久化)。 #### `ccr` diff --git a/src/compress-settings.ts b/src/compress-settings.ts index a0f0af5c49..f51bd1e350 100644 --- a/src/compress-settings.ts +++ b/src/compress-settings.ts @@ -252,6 +252,20 @@ export function hasCompressSettings(s: CompressSettings): boolean { // (validateConfig does not flag unknown keys). export type ResolvedKernelConfig = Config & { preserveRecentTools?: string[] }; +// Single source of truth for raw->resolved absorb: applyCompressSettings and the +// plugin-lane base stamp (#1359) both go through this or they drift apart. +export function resolveAbsorbSettings(s: CompressSettings["absorb"]): AbsorbConfig | undefined { + if (s === undefined) return undefined; + const d = DEFAULT_ABSORB_CONFIG; + return { + enabled: s.enabled === true, + toolName: s.toolName ?? d.toolName, + minToolTokens: s.minToolTokens ?? d.minToolTokens, + contextThresholdPct: s.contextThresholdPct !== undefined ? parsePercent(s.contextThresholdPct) : d.contextThresholdPct, + excludeTools: s.excludeTools ?? [...d.excludeTools], + }; +} + export function applyCompressSettings(base: Config, limit: number, s: CompressSettings): ResolvedKernelConfig { const nudge = { ...base.nudge }; const truncate = { ...base.truncate }; @@ -267,17 +281,7 @@ export function applyCompressSettings(base: Config, limit: number, s: CompressSe } const tiers = { ...base.tiers }; if (s.tiers !== undefined) tiers.enabled = s.tiers; - let absorb: AbsorbConfig | undefined; - if (s.absorb !== undefined) { - const d = DEFAULT_ABSORB_CONFIG; - absorb = { - enabled: s.absorb.enabled === true, - toolName: s.absorb.toolName ?? d.toolName, - minToolTokens: s.absorb.minToolTokens ?? d.minToolTokens, - contextThresholdPct: s.absorb.contextThresholdPct !== undefined ? parsePercent(s.absorb.contextThresholdPct) : d.contextThresholdPct, - excludeTools: s.absorb.excludeTools ?? [...d.excludeTools], - }; - } + const absorb = resolveAbsorbSettings(s.absorb); // #1207 owner decision: CCR is opt-in on every lane — no default-on // else-branch; an unset `s.ccr` leaves `base.ccr` untouched (off). let ccr: CcrConfig | undefined; diff --git a/src/compress-tool.ts b/src/compress-tool.ts index 6d90548026..f76c76df89 100644 --- a/src/compress-tool.ts +++ b/src/compress-tool.ts @@ -12,6 +12,8 @@ */ import { parseCompressArgs, + ABSORB_TOOL, + ABSORB_TOOL_GOOGLE, ABSORB_TOOL_OPENAI, DECOMPRESS_TOOL, DECOMPRESS_TOOL_GOOGLE, @@ -168,6 +170,19 @@ export const ABSORB_TOOL_RESPONSES = { parameters: ABSORB_TOOL_OPENAI.function.parameters, }; +// #1359: absorb wire shapes parameterized by name so registration (manifest + +// per-request injection) follows the resolved `absorb.toolName` in BOTH lanes — +// a renamed tool must be advertised, injected, and adjudicated under one name. +// At the default name this is byte-identical to the static consts above. +export function absorbToolsFor(name: string) { + return { + anthropic: { name, description: ABSORB_TOOL.description, input_schema: ABSORB_TOOL.input_schema }, + openai: { type: "function" as const, function: { name, description: ABSORB_TOOL_OPENAI.function.description, parameters: ABSORB_TOOL_OPENAI.function.parameters } }, + responses: { type: "function" as const, name, description: ABSORB_TOOL_OPENAI.function.description, parameters: ABSORB_TOOL_OPENAI.function.parameters }, + google: { name, description: ABSORB_TOOL_GOOGLE.description, parameters: ABSORB_TOOL_GOOGLE.parameters }, + }; +} + // The reconciled kernel (acp-kernel#332) ships RULE_TOOL_NAME + the rule state // helpers but no wire tool objects. Synthesize all four wire shapes here so // every injection point (wire helpers, plugin manifest) serves one definition. diff --git a/src/config.ts b/src/config.ts index 7c2eeac0e6..0a76e6f00e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -646,6 +646,46 @@ export function passthroughState(env: NodeJS.ProcessEnv): { enabled: boolean; so return { enabled: filePassthrough, source: filePassthrough ? "file" : null }; } +// #1359: provider/model absorb.* overrides apply only to the proxy lane (plugin +// lane follows the base block). Warn once per load so the divergence isn't silent. +const ABSORB_DIVERGENCE_FIELDS = ["enabled", "toolName", "minToolTokens", "contextThresholdPct", "excludeTools"] as const; +const seenAbsorbDivergenceWarnings = new Set(); + +function normAbsorbValue(field: string, v: unknown): unknown { + if (field === "contextThresholdPct" && typeof v === "string") { + const m = v.match(/^(-?\d+(?:\.\d+)?)\s*%$/); + if (m) return Number(m[1]) / 100; + } + return v; +} + +export function findAbsorbPluginDivergences(routes: ProviderRoutes, baseAbsorb?: CompressSettings["absorb"]): string[] { + const out: string[] = []; + const check = (scope: string, level?: CompressSettings["absorb"]) => { + if (!level) return; + for (const field of ABSORB_DIVERGENCE_FIELDS) { + if (level[field] === undefined) continue; + if (JSON.stringify(normAbsorbValue(field, level[field])) !== JSON.stringify(normAbsorbValue(field, baseAbsorb?.[field]))) { + out.push(`${scope}.absorb.${field}=${JSON.stringify(level[field])} (base=${JSON.stringify(baseAbsorb?.[field])})`); + } + } + }; + for (const [url, route] of Object.entries(routes)) { + check(url, route.compress?.absorb); + for (const [model, entry] of Object.entries(route.models ?? {})) check(`${url}/${model}`, entry.compress?.absorb); + } + return out; +} + +function warnAbsorbPluginDivergences(routes: ProviderRoutes, baseAbsorb?: CompressSettings["absorb"]): void { + const divs = findAbsorbPluginDivergences(routes, baseAbsorb); + if (divs.length === 0) return; + const sig = divs.join("\u0000"); + if (seenAbsorbDivergenceWarnings.has(sig)) return; + seenAbsorbDivergenceWarnings.add(sig); + loggerLog("warn", `[acp-config] provider/model absorb override diverges from base [${divs.join("; ")}] — plugin-mode sessions follow the base value, proxy-mode sessions honor the override (#1359)`); +} + export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions { // --- Source 1: JSON config file (~/.config/billion-context/billion-context.json) --- // The canonical, user-editable config. Loaded first so env vars below can @@ -661,6 +701,7 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions const host = rawHost === "localhost" ? "127.0.0.1" : rawHost; const upstream = (env.ACP_UPSTREAM ?? fileConfig.upstream ?? "https://api.anthropic.com").replace(/\/$/, ""); const routes = loadRoutes(env); + warnAbsorbPluginDivergences(routes, fileConfig.compress?.absorb); const passthrough = passthroughState(env); const modelContextLimit = parseInt(env.ACP_MODEL_CONTEXT_LIMIT ?? `${fileConfig.modelContextLimit ?? 200000}`, 10); const biliProxy = nonEmpty(env.BILI_UPSTREAM_PROXY); diff --git a/src/plugin.ts b/src/plugin.ts index 70ad9f3545..08cf9908d1 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -5,7 +5,7 @@ import type { ServerResponse } from "node:http"; import fs from "node:fs"; import path from "node:path"; import { acquireInFlight, effectiveConfig, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, withSessionLock, type Session } from "./session.js"; -import { ABSORB_TOOL, ABSORB_TOOL_NAME, ABSORB_TOOL_OPENAI, ABSORB_TOOL_RESPONSES, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_RESPONSES, PROXY_TOOL_NAMES, RETRIEVE_TOOL_NAME, RULE_TOOL, RULE_TOOL_NAME, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, SEARCH_CONTEXT_CONVERSATION_ID_PARAM, SEARCH_CONTEXT_TOOL_NAME, retrieveToolsFor } from "./compress-tool.js"; +import { ABSORB_TOOL_NAME, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_RESPONSES, PROXY_TOOL_NAMES, RETRIEVE_TOOL_NAME, RULE_TOOL, RULE_TOOL_NAME, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, SEARCH_CONTEXT_CONVERSATION_ID_PARAM, SEARCH_CONTEXT_TOOL_NAME, absorbToolsFor, retrieveToolsFor } from "./compress-tool.js"; import { absorbEnabled, effectiveAbsorbConfig, isProxyToolFor } from "./absorb.js"; import { effectiveRulesConfig, rulesEnabled } from "./rules-feature.js"; import { executeProxyTool } from "./loop/core.js"; @@ -560,7 +560,11 @@ export function handlePluginManifest(res: import("node:http").ServerResponse, co // per-request provider/model overrides may still differ (conservative: the // manifest never advertises what the base config disables) and per-session // enablement stays enforced at execution (isProxyToolFor / executeProxyTool). + // #1359: the advertised name is the base-config toolName, matching the + // plugin-lane gate (which adjudicates the same base block). const absorbOn = absorbEnabled(config); + const absorbName = config.absorb?.toolName ?? ABSORB_TOOL_NAME; + const absorbTools = absorbOn ? absorbToolsFor(absorbName) : undefined; const rulesOn = rulesEnabled(config); // [#1271] acp_retrieve is advertised only while the base config enables CCR (same // #1192 conservative rule as absorb/acp_rule). The proxy wires it on the anthropic/ @@ -575,11 +579,11 @@ export function handlePluginManifest(res: import("node:http").ServerResponse, co protocolVersion: PLUGIN_PROTOCOL_VERSION, proxy: "billion-context", version: VERSION, - toolNames: [...PROXY_TOOL_NAMES, ...(absorbOn ? [ABSORB_TOOL_NAME] : []), ...(rulesOn ? [RULE_TOOL_NAME] : []), ...(ccrOn ? [ccrName] : [])], + toolNames: [...PROXY_TOOL_NAMES, ...(absorbTools ? [absorbName] : []), ...(rulesOn ? [RULE_TOOL_NAME] : []), ...(ccrOn ? [ccrName] : [])], tools: { - anthropic: withSearchContextConversationDescription([...BILI_ACP_TOOLS_ANTHROPIC, ...(absorbOn ? [ABSORB_TOOL] : []), ...(rulesOn ? [RULE_TOOL] : []), ...(ccrTools ? [ccrTools.anthropic] : [])].map(withConversationIdParam)), - openai: withSearchContextConversationDescription([...BILI_ACP_TOOLS_OPENAI, ...(absorbOn ? [ABSORB_TOOL_OPENAI] : []), ...(rulesOn ? [RULE_TOOL_OPENAI] : []), ...(ccrTools ? [ccrTools.openai] : [])].map(withConversationIdParam)), - responses: withSearchContextConversationDescription([...BILI_ACP_TOOLS_RESPONSES, ...(absorbOn ? [ABSORB_TOOL_RESPONSES] : []), ...(rulesOn ? [RULE_TOOL_RESPONSES] : [])].map(withConversationIdParam)), + anthropic: withSearchContextConversationDescription([...BILI_ACP_TOOLS_ANTHROPIC, ...(absorbTools ? [absorbTools.anthropic] : []), ...(rulesOn ? [RULE_TOOL] : []), ...(ccrTools ? [ccrTools.anthropic] : [])].map(withConversationIdParam)), + openai: withSearchContextConversationDescription([...BILI_ACP_TOOLS_OPENAI, ...(absorbTools ? [absorbTools.openai] : []), ...(rulesOn ? [RULE_TOOL_OPENAI] : []), ...(ccrTools ? [ccrTools.openai] : [])].map(withConversationIdParam)), + responses: withSearchContextConversationDescription([...BILI_ACP_TOOLS_RESPONSES, ...(absorbTools ? [absorbTools.responses] : []), ...(rulesOn ? [RULE_TOOL_RESPONSES] : [])].map(withConversationIdParam)), }, headers: { agent: PLUGIN_AGENT_HEADER, conversation: PLUGIN_CONVERSATION_HEADER, contextWindow: PLUGIN_CONTEXT_WINDOW_HEADER, maxOutput: PLUGIN_MAX_OUTPUT_HEADER, model: PLUGIN_MODEL_HEADER, instructionsMutable: PLUGIN_INSTRUCTIONS_MUTABLE_HEADER }, toolEndpoint: "/__bili/plugin/tool", diff --git a/src/server.ts b/src/server.ts index 39d3befd74..4d828f200f 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3,10 +3,10 @@ import fs from "node:fs"; import path from "node:path"; import { createHash, randomUUID } from "node:crypto"; import { performance } from "node:perf_hooks"; -import { createCore, type CompressionCore, type CompressionState, type Config, type CoreMessage, type NudgeDecision, type Prompts, type PackSurface, type ToolPrompts, applyAcpToolOverrides, defaultPrompts, defaultCountTokens, estimateTokensFast, renderNudgeText, deactivateBlock, viableRanges, resolveOutputSteeringConfig } from "acp-kernel"; -import { DEFAULT_STRIP_IMAGES_KEEP_RECENT, applyCompressSettings, resolveCompress, resolveCompressPrompts, resolveCompressSurfaceDetailed, resolveRequestConfig } from "./compress-settings.js"; +import { createCore, type CompressionCore, type CompressionState, type Config, type AbsorbConfig, type CoreMessage, type NudgeDecision, type Prompts, type PackSurface, type ToolPrompts, applyAcpToolOverrides, defaultPrompts, defaultCountTokens, estimateTokensFast, renderNudgeText, deactivateBlock, viableRanges, resolveOutputSteeringConfig } from "acp-kernel"; +import { DEFAULT_STRIP_IMAGES_KEEP_RECENT, applyCompressSettings, resolveAbsorbSettings, resolveCompress, resolveCompressPrompts, resolveCompressSurfaceDetailed, resolveRequestConfig } from "./compress-settings.js"; import { dropCompressReasoning, type CompressReasoningConfig } from "./reasoning-drop.js"; -import type { ProxyOptions } from "./config.js"; +import type { CompressSettings, ProxyOptions } from "./config.js"; import { loadOptions, loadRoutes } from "./config.js"; import { resetProxyCache } from "./upstream-proxy.js"; import { FALLBACK_EFFECTIVE_WINDOW_FLOOR, findRoute, lookupContextLimit, resolveConfiguredContextLimit, resolveConfiguredOutputLimit, resolveCompressProtocol } from "./config.js"; @@ -60,7 +60,7 @@ import { type GoogleSystemInstruction, type GoogleTool, } from "acp-kernel/wire"; -import { ABSORB_TOOL, ABSORB_TOOL_GOOGLE, ABSORB_TOOL_OPENAI, ABSORB_TOOL_RESPONSES, COMPRESS_TOOL, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES, COMPRESS_TOOL_NAME, IMAGE_FULL_TOOL, IMAGE_FULL_TOOL_GOOGLE, IMAGE_FULL_TOOL_OPENAI, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL, RULE_TOOL_GOOGLE, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, retrieveToolsFor, buildAbsorbSystemPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withConversationIdNote, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "./compress-tool.js"; +import { ABSORB_TOOL_NAME, COMPRESS_TOOL, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_GOOGLE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES, COMPRESS_TOOL_NAME, IMAGE_FULL_TOOL, IMAGE_FULL_TOOL_GOOGLE, IMAGE_FULL_TOOL_OPENAI, IMAGE_FULL_TOOL_RESPONSES, RULE_TOOL, RULE_TOOL_GOOGLE, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, absorbToolsFor, retrieveToolsFor, buildAbsorbSystemPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withConversationIdNote, withMarkerIntegrityNote, withStagedCompressGuidance, withSummaryBudgetNote } from "./compress-tool.js"; import { applyAbsorbView, absorbEnabled, absorbToolName, storeEffectiveAbsorb } from "./absorb.js"; import { adoptContentStore, ccrEnabled, ccrPluginWireOk, contentStoreOf, drainPendingRetrievals, executeRetrieve, retrieveToolName, storeEffectiveCcr, type CcrSettings } from "./store.js"; import { applyImageCompressionPass, imageCompressionEnabled, imageFullTrailingNote, storeEffectiveImageCompression, type ImageCompressionSettings } from "./image-compress.js"; @@ -2617,7 +2617,9 @@ async function prepareAnthropic( // strip absorb from the loop config so the REQUIRED instruction never // reaches the wire. Hiding recorded absorptions is unaffected // (applyAbsorbView hides regardless of enablement). - const absorbActive = absorbEnabled(config) && opts.compress.injectTool; + const absorbBlock = effectiveAbsorbBlock(pluginMode, config, opts.compress.absorb); + const absorbTools = absorbToolsFor(absorbBlock?.toolName ?? ABSORB_TOOL_NAME); + const absorbActive = absorbBlock?.enabled === true && opts.compress.injectTool; // acp_rule has no processTurn side effect (no markers/instructions are // ever injected into messages), so unlike absorb it needs no loop- // config stripping — only tool availability matters. @@ -2626,7 +2628,7 @@ async function prepareAnthropic( // BEFORE absorb (ID-reference wins over distill); armed policy is // stamped per-request — strip `ccr` from the loop config when disarmed // (plugin mode / no tool channel) so placeholders never hit the wire. - const loopConfig = { ...(absorbActive ? config : { ...config, absorb: undefined }), ...(ccrEnabled(session) ? {} : { ccr: undefined }) }; + const loopConfig = { ...config, absorb: absorbActive ? absorbBlock : undefined, ...(ccrEnabled(session) ? {} : { ccr: undefined }) }; const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags: process.env.ACP_RENDER_NONE ? "none" : "text-only", contentStore: contentStoreOf(session) }); session.state = turn.state; adoptContentStore(session, turn.contentStore); @@ -2679,7 +2681,7 @@ async function prepareAnthropic( systemOut = injectSystem(parsed, opts, prompts, loopConfig, ensureCanonicalId(session), surface, visibilityMarkers); if (injectTools) { - toolsOut = injectTool(parsed.tools, [...(absorbActive ? [ABSORB_TOOL] : []), ...(rulesActive ? [RULE_TOOL] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).anthropic] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL] : [])], surface?.toolPrompts); + toolsOut = injectTool(parsed.tools, [...(absorbActive ? [absorbTools.anthropic] : []), ...(rulesActive ? [RULE_TOOL] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).anthropic] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL] : [])], surface?.toolPrompts); } // Nudge as a separate trailing user message (cache-friendly): the // system block stays byte-stable so the prefix cache survives. @@ -2808,9 +2810,11 @@ async function prepareOpenai( // Absorb markers ride in the kernel's processTurn output (gated by // config.absorb). Title-gen requests skip ALL injection for // prefix-cache stability, so strip absorb from the loop config there. - const absorbActive = absorbEnabled(config) && shouldInject; + const absorbBlock = effectiveAbsorbBlock(pluginMode, config, opts.compress.absorb); + const absorbTools = absorbToolsFor(absorbBlock?.toolName ?? ABSORB_TOOL_NAME); + const absorbActive = absorbBlock?.enabled === true && shouldInject; const rulesActive = rulesEnabled(config) && shouldInject; - const loopConfig = { ...(absorbActive ? config : { ...config, absorb: undefined }), ...(ccrEnabled(session) ? {} : { ccr: undefined }) }; + const loopConfig = { ...config, absorb: absorbActive ? absorbBlock : undefined, ...(ccrEnabled(session) ? {} : { ccr: undefined }) }; const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags: process.env.ACP_RENDER_NONE ? "none" : "text-only", contentStore: contentStoreOf(session) }); session.state = turn.state; adoptContentStore(session, turn.contentStore); @@ -2866,7 +2870,7 @@ async function prepareOpenai( const sysParts: string[] = []; if (openaiSystemText) sysParts.push(openaiSystemText); if (shouldInject) sysParts.push(withConversationIdNote(withMarkerIntegrityNote(withSummaryBudgetNote(buildCompressSystemPrompt(prompts, surface?.promptSections)), visibilityMarkers), ensureCanonicalId(session))); - if (absorbActive) sysParts.push(buildAbsorbSystemPrompt(absorbToolName(config))); + if (absorbActive) sysParts.push(buildAbsorbSystemPrompt(absorbToolName(loopConfig))); rebuiltMessages = injectOpenaiSystem(rebuiltMessages, sysParts); if (sysNotes.length > 0) { rebuiltMessages = [...rebuiltMessages, ...sysNotes.map((text) => ({ role: "user" as const, content: text }))]; @@ -2877,7 +2881,7 @@ async function prepareOpenai( // avoids double-counting it. openaiOutboundSystem = sysParts.join("\n\n"); if (injectTools) { - toolsOut = injectOpenaiTool(parsed.tools, [...(absorbActive ? [ABSORB_TOOL_OPENAI] : []), ...(rulesActive ? [RULE_TOOL_OPENAI] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).openai] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL_OPENAI] : [])], surface?.toolPrompts); + toolsOut = injectOpenaiTool(parsed.tools, [...(absorbActive ? [absorbTools.openai] : []), ...(rulesActive ? [RULE_TOOL_OPENAI] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).openai] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL_OPENAI] : [])], surface?.toolPrompts); } // Nudge as a separate trailing user message (cache-friendly). Injected // in BOTH modes (#451): plugin agents supply the ACP tools but have no @@ -3022,12 +3026,14 @@ async function prepareGoogle( originalMessages = msgs; const tokenCount = effectiveTokenCount(session, msgs, imageTokensInParsedBody("google", parsed, imageBillingFor(opts, upstreamOrigin))); const activeBefore = new Set(session.state.blocks.filter((b) => b.active).map((b) => b.blockId)); - const absorbActive = absorbEnabled(config) && shouldInject; + const absorbBlock = effectiveAbsorbBlock(pluginMode, config, opts.compress.absorb); + const absorbTools = absorbToolsFor(absorbBlock?.toolName ?? ABSORB_TOOL_NAME); + const absorbActive = absorbBlock?.enabled === true && shouldInject; // acp_rule has no processTurn side effect (no markers/instructions are // ever injected into messages), so unlike absorb it needs no loop- // config stripping — only tool availability matters. const rulesActive = rulesEnabled(config) && shouldInject; - const loopConfig = { ...(absorbActive ? config : { ...config, absorb: undefined }), ...(ccrEnabled(session) ? {} : { ccr: undefined }) }; + const loopConfig = { ...config, absorb: absorbActive ? absorbBlock : undefined, ...(ccrEnabled(session) ? {} : { ccr: undefined }) }; const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags: "text-only", contentStore: contentStoreOf(session) }); session.state = turn.state; adoptContentStore(session, turn.contentStore); @@ -3063,7 +3069,7 @@ async function prepareGoogle( const sysParts: string[] = []; if (googleClientSystem) sysParts.push(googleClientSystem); if (shouldInject) sysParts.push(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections), visibilityMarkers)); - if (absorbActive) sysParts.push(buildAbsorbSystemPrompt(absorbToolName(config))); + if (absorbActive) sysParts.push(buildAbsorbSystemPrompt(absorbToolName(loopConfig))); googleOutboundSystem = sysParts.join("\n\n"); // Untouched when nothing was added beyond the client's own text: the // original `systemInstruction` object then rides through byte-identical @@ -3071,7 +3077,7 @@ async function prepareGoogle( const extraSystemParts = sysParts.slice(googleClientSystem ? 1 : 0); systemInstruction = extraSystemParts.length > 0 ? { parts: sysParts.map((text) => ({ text })) } : parsed.systemInstruction; if (injectTools) { - toolsOut = injectGoogleTool(parsed.tools, [...(absorbActive ? [ABSORB_TOOL_GOOGLE] : []), ...(rulesActive ? [RULE_TOOL_GOOGLE] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).google] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL_GOOGLE] : [])], surface?.toolPrompts); + toolsOut = injectGoogleTool(parsed.tools, [...(absorbActive ? [absorbTools.google] : []), ...(rulesActive ? [RULE_TOOL_GOOGLE] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).google] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL_GOOGLE] : [])], surface?.toolPrompts); } if (sysNotes.length > 0) { rebuiltContents = appendGoogleNudge(rebuiltContents, sysNotes.join("\n\n---\n\n")); @@ -3260,9 +3266,11 @@ async function prepareResponses( // Absorb markers ride in the kernel's processTurn output (gated by // config.absorb). The marker/text protocol has no native tool channel, // so strip absorb from the loop config there (both modes). - const absorbActive = absorbEnabled(config) && shouldInject && !isCompactionTrigger && !responsesTextProtocol; + const absorbBlock = effectiveAbsorbBlock(pluginMode, config, opts.compress.absorb); + const absorbTools = absorbToolsFor(absorbBlock?.toolName ?? ABSORB_TOOL_NAME); + const absorbActive = absorbBlock?.enabled === true && shouldInject && !isCompactionTrigger && !responsesTextProtocol; const rulesActive = rulesEnabled(config) && shouldInject && !isCompactionTrigger && !responsesTextProtocol; - const loopConfig = { ...(absorbActive ? config : { ...config, absorb: undefined }), ...(ccrEnabled(session) ? {} : { ccr: undefined }) }; + const loopConfig = { ...config, absorb: absorbActive ? absorbBlock : undefined, ...(ccrEnabled(session) ? {} : { ccr: undefined }) }; const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags, contentStore: contentStoreOf(session) }); session.state = turn.state; adoptContentStore(session, turn.contentStore); @@ -3303,12 +3311,12 @@ async function prepareResponses( if (shouldInject && !isCompactionTrigger && !process.env.ACP_NO_COMPRESS_PROMPT) { const prompt = withConversationIdNote(withMarkerIntegrityNote(withSummaryBudgetNote(responsesTextProtocol ? buildCompressHybridSystemPrompt(prompts, surface?.promptSections) : buildCompressSystemPrompt(prompts, surface?.promptSections)), visibilityMarkers), ensureCanonicalId(session)); const devParts = [...projection.systemParts, ...forgedSummaries, prompt]; - if (absorbActive) devParts.push(buildAbsorbSystemPrompt(absorbToolName(config))); + if (absorbActive) devParts.push(buildAbsorbSystemPrompt(absorbToolName(loopConfig))); const devContent = devParts.join("\n\n---\n\n"); responsesDevContent = devContent; rebuiltInput = injectResponsesDeveloperMessage(rebuiltInput, devContent); if (!process.env.ACP_NO_INJECT_TOOL && injectTools) { - const respExtra = [...(absorbActive ? [ABSORB_TOOL_RESPONSES] : []), ...(rulesActive ? [RULE_TOOL_RESPONSES] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).responses] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL_RESPONSES] : [])]; + const respExtra = [...(absorbActive ? [absorbTools.responses] : []), ...(rulesActive ? [RULE_TOOL_RESPONSES] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).responses] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL_RESPONSES] : [])]; toolsOut = responsesTextProtocol ? injectResponsesTool(parsed.tools, BILI_ACP_READONLY_TOOLS_RESPONSES, surface?.toolPrompts) : injectResponsesTool(parsed.tools, respExtra.length > 0 ? [...BILI_ACP_TOOLS_RESPONSES, ...respExtra] : BILI_ACP_TOOLS_RESPONSES, surface?.toolPrompts); @@ -3667,6 +3675,14 @@ function isAutoModeClassifier(parsed: AnthropicRequestBody): boolean { return stops.some((s) => typeof s === "string" && AUTO_MODE_CLASSIFIER_STOPS.has(s)); } +// #1359: which absorb block governs a session, by lane. Proxy lane keeps the +// per-request merged block (provider/model overrides apply); plugin lane uses +// the base block so the manifest's advertised name and the gate's adjudicated +// name always agree — provider/model absorb.* overrides are proxy-lane-only. +function effectiveAbsorbBlock(pluginMode: boolean, config: Config, baseAbsorb?: CompressSettings["absorb"]): AbsorbConfig | undefined { + return pluginMode ? resolveAbsorbSettings(baseAbsorb) : config.absorb; +} + function injectSystem( parsed: AnthropicRequestBody, opts: ProxyOptions, @@ -5102,8 +5118,9 @@ async function forward( // Same absorb gate as prepare*: the section only exists where the // tool is callable, keeping loop re-requests byte-consistent with // the first request (prefix-cache anchor). - const absorbActive = absorbEnabled(config) && opts.compress.injectTool && !textProtocol; - const loopConfig = { ...(absorbActive ? config : { ...config, absorb: undefined }), ...(ccrEnabled(prepared.session) ? {} : { ccr: undefined }) }; + const absorbBlock = effectiveAbsorbBlock(prepared.pluginMode === true, config, opts.compress.absorb); + const absorbActive = absorbBlock?.enabled === true && opts.compress.injectTool && !textProtocol; + const loopConfig = { ...config, absorb: absorbActive ? absorbBlock : undefined, ...(ccrEnabled(prepared.session) ? {} : { ccr: undefined }) }; const absorbSection = absorbActive ? `\n\n---\n\n${buildAbsorbSystemPrompt(absorbToolName(loopConfig))}` : ""; diff --git a/tests/absorb-plugin.test.ts b/tests/absorb-plugin.test.ts new file mode 100644 index 0000000000..de14862264 --- /dev/null +++ b/tests/absorb-plugin.test.ts @@ -0,0 +1,250 @@ +// #1359: absorb plugin-lane tool-name divergence (same class as #1345/#1360 CCR). +// The manifest must advertise the SAME name the per-session gate adjudicates. +// Plugin lane governs the whole absorb block by the BASE config (provider/model +// overrides are proxy-lane-only); proxy lane follows the per-request merged block. +// Regression pinned here: a base-level rename advertised the static name while the +// gate expected the renamed one, so the host-registered tool 400'd on the plugin lane. + +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; + +process.env.NODE_ENV = "test"; +process.env.BILI_PERSIST = "0"; + +import { defaultConfig, type Config } from "acp-kernel"; +import { startServer, type ProxyOptions } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { listSessions, getSession } from "../src/session.ts"; +import { handlePluginManifest } from "../src/plugin.ts"; +import { effectiveAbsorbConfig, storeEffectiveAbsorb, isProxyToolFor } from "../src/absorb.ts"; +import { applyCompressSettings } from "../src/compress-settings.ts"; +import { findAbsorbPluginDivergences } from "../src/config.ts"; + +const MODEL = "test-model"; + +function readManifest(config: Parameters[1]): { toolNames: string[]; tools: Record } { + let body = ""; + const res = { writeHead: () => {}, end: (b: string) => { body = b; } } as unknown as Parameters[0]; + handlePluginManifest(res, config); + return JSON.parse(body) as { toolNames: string[]; tools: Record }; +} + +function namesOnWire(wire: unknown[]): string[] { + return wire.map((t) => { + const o = t as Record; + return typeof o.name === "string" ? o.name : String((o.function as { name?: unknown } | undefined)?.name ?? ""); + }); +} + +// — manifest advertising follows base absorb.toolName (the #1359 core) — + +test("handlePluginManifest: absorb NOT advertised when disabled", () => { + const m = readManifest(defaultConfig(200_000)); + assert.ok(!m.toolNames.includes("absorb"), "disabled by default → not advertised"); +}); + +test("handlePluginManifest: enabled absorb with default name advertises 'absorb'", () => { + const m = readManifest({ ...defaultConfig(200_000), absorb: { enabled: true } }); + assert.ok(m.toolNames.includes("absorb"), "default name advertised"); + for (const wire of ["anthropic", "openai", "responses"]) { + assert.ok(namesOnWire(m.tools[wire] ?? []).includes("absorb"), `${wire} carries 'absorb'`); + } +}); + +test("handlePluginManifest: base absorb.toolName rename is advertised, not the static name", () => { + const m = readManifest({ ...defaultConfig(200_000), absorb: { enabled: true, toolName: "my_absorb" } }); + assert.ok(m.toolNames.includes("my_absorb"), "renamed tool advertised"); + assert.ok(!m.toolNames.includes("absorb"), "static name no longer advertised after rename"); + for (const wire of ["anthropic", "openai", "responses"]) { + const names = namesOnWire(m.tools[wire] ?? []); + assert.ok(names.includes("my_absorb"), `${wire} carries the renamed tool`); + assert.ok(!names.includes("absorb"), `${wire} must not carry the static name`); + } +}); + +// — per-session gate: the advertised (renamed) name is the only accepted one — + +test("gate: plugin-lane stamp makes the renamed name the sole accepted absorb tool", () => { + const base = defaultConfig(200_000); + const renamed: Config = { ...base, absorb: { enabled: true, toolName: "my_absorb", minToolTokens: 1 } }; + const s = getSession(`t-absorb-plugin-${Math.random().toString(36).slice(2)}`); + storeEffectiveAbsorb(s, renamed); + assert.equal(isProxyToolFor("my_absorb", s, base), true, "renamed (advertised) name accepted"); + assert.equal(isProxyToolFor("absorb", s, base), false, "static name rejected after rename"); +}); + +// — load-time per-field divergence diagnostic — + +test("findAbsorbPluginDivergences: aligned / unset levels report nothing", () => { + const u = "http://u"; + assert.deepEqual(findAbsorbPluginDivergences({ [u]: {} }, { enabled: true, minToolTokens: 100 }), []); + assert.deepEqual(findAbsorbPluginDivergences({ [u]: { compress: { absorb: undefined } } }, { enabled: true }), []); + assert.deepEqual(findAbsorbPluginDivergences({ [u]: { compress: { absorb: { enabled: true } } } }, { enabled: true }), []); +}); + +test("findAbsorbPluginDivergences: route-level rename diverges from base", () => { + const u = "http://u"; + const divs = findAbsorbPluginDivergences( + { [u]: { compress: { absorb: { enabled: true, toolName: "route_absorb" } } } }, + { enabled: true }, + ); + assert.equal(divs.length, 1, `expected exactly the toolName field, got ${JSON.stringify(divs)}`); + assert.match(divs[0]!, /toolName=\s*"route_absorb"/); +}); + +test("findAbsorbPluginDivergences: model-level field diverges; only fields the level SETS are reported", () => { + const u = "http://u"; + const divs = findAbsorbPluginDivergences( + { [u]: { models: { m1: { compress: { absorb: { minToolTokens: 999 } } } } } }, + { minToolTokens: 100, contextThresholdPct: 0.5, excludeTools: ["bash"] }, + ); + assert.equal(divs.length, 1, `only the set field (minToolTokens) diverges, got ${JSON.stringify(divs)}`); + assert.match(divs[0]!, /m1\.absorb\.minToolTokens=\s*999/); + assert.ok(!divs.join("").includes("contextThresholdPct"), "unset-at-level field not reported"); + assert.ok(!divs.join("").includes("excludeTools"), "unset-at-level field not reported"); +}); + +test("findAbsorbPluginDivergences: percent form normalizes to the fraction form", () => { + const u = "http://u"; + assert.deepEqual( + findAbsorbPluginDivergences({ [u]: { compress: { absorb: { contextThresholdPct: "80%" } } } }, { contextThresholdPct: 0.8 }), + [], + "'80%' == 0.8 → no divergence", + ); + const divs = findAbsorbPluginDivergences({ [u]: { compress: { absorb: { contextThresholdPct: "90%" } } } }, { contextThresholdPct: 0.8 }); + assert.equal(divs.length, 1, "'90%' != 0.8 → divergence"); +}); + +// — e2e lane governance (real server through the proxy) — + +type Rig = { proxyPort: number; upstreamPort: number; forwards: string[]; proxy: http.Server; upstream: http.Server }; + +function okJson(): string { + return JSON.stringify({ + id: "chatcmpl-1", + object: "chat.completion", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 }, + }); +} + +async function startRig(baseCompress: Record, routeCompress?: Record): Promise { + const forwards: string[] = []; + const upstream = http.createServer((req, res) => { + let b = ""; + req.on("data", (c) => (b += c)); + req.on("end", () => { + forwards.push(b); + res.writeHead(200, { "content-type": "application/json" }); + res.end(okJson()); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = upstream.address().port as number; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const url = `http://127.0.0.1:${upstreamPort}`; + const routes = routeCompress ? { [url]: { compress: routeCompress } } : { [url]: {} }; + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000), + compress: baseCompress, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + return { proxyPort: proxy.address().port as number, upstreamPort, forwards, proxy, upstream }; +} + +async function closeRig(rig: Rig): Promise { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); +} + +async function post(rig: Rig, convId: string, pluginMode: boolean, messages: unknown[]): Promise { + const headers: Record = { "content-type": "application/json", "x-acp-session": convId }; + if (pluginMode) headers["x-bili-plugin"] = "test-agent"; + const res = await fetch(`http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`, { + method: "POST", + headers, + body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages }), + }); + const txt = await res.text(); + if (res.status !== 200) throw new Error(`proxy returned ${res.status}: ${txt}`); +} + +const SIMPLE_MSGS = (): unknown[] => [ + { role: "user", content: "hello" }, + { role: "assistant", content: "hi there" }, +]; + +test("e2e: base rename → plugin lane advertises, stamps, and executes the renamed tool", async () => { + const baseCompress = { injectTool: true, injectNudge: false, absorb: { enabled: true, toolName: "my_absorb", minToolTokens: 1 } }; + const rig = await startRig(baseCompress); + try { + // Manifest (built from the base config, as server.ts does) advertises the rename. + const m = readManifest(applyCompressSettings(defaultConfig(200_000), 200_000, baseCompress as Parameters[2])); + assert.ok(m.toolNames.includes("my_absorb"), "manifest advertises the base-renamed tool"); + + // A plugin-mode turn stamps the session with the base (renamed) name. + await post(rig, "abs-e2e-a", true, SIMPLE_MSGS()); + const sess = listSessions().find((s) => effectiveAbsorbConfig(s, defaultConfig(200_000))?.enabled === true); + assert.ok(sess, "a session armed absorb"); + assert.equal(effectiveAbsorbConfig(sess!, defaultConfig(200_000))?.toolName, "my_absorb", "plugin lane stamps the base (renamed) name"); + + // THE core repro: the advertised tool runs through the REAL plugin endpoint + // (pre-fix it 400'd because the gate expected the renamed name while the + // manifest advertised the static one). + const tr = await fetch(`http://127.0.0.1:${rig.proxyPort}/__bili/plugin/tool`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: "abs-e2e-a", tool: "my_absorb", args: { ref: "m00001", summary: "x" } }), + }); + const tj = JSON.parse(await tr.text()) as { ok: boolean; error?: string }; + assert.equal(tr.status, 200, `advertised tool must not 400; got ${tr.status}: ${JSON.stringify(tj)}`); + assert.equal(tj.ok, true, "gate accepts the advertised (renamed) absorb tool"); + } finally { + await closeRig(rig); + } +}); + +test("e2e: route rename → plugin lane stays on base, proxy lane honors the override", async () => { + const baseCompress = { injectTool: true, injectNudge: false, absorb: { enabled: true, minToolTokens: 1 } }; + const routeCompress = { absorb: { enabled: true, toolName: "route_absorb", minToolTokens: 1 } }; + const rig = await startRig(baseCompress, routeCompress); + try { + // Plugin lane: the route override must NOT leak into the base-governed stamp. + const beforeP = new Set(listSessions().map((s) => s.id)); + await post(rig, "abs-e2e-b1", true, SIMPLE_MSGS()); + const pSess = listSessions().find((s) => !beforeP.has(s.id)); + assert.ok(pSess, "plugin turn created a session"); + assert.equal(effectiveAbsorbConfig(pSess!, defaultConfig(200_000))?.toolName, "absorb", "plugin lane follows the BASE name, ignoring the route override"); + + // Proxy lane: the merged (route) name governs, and the injected schema carries it. + const beforeX = new Set(listSessions().map((s) => s.id)); + await post(rig, "abs-e2e-b2", false, SIMPLE_MSGS()); + const xSess = listSessions().find((s) => !beforeX.has(s.id)); + assert.ok(xSess, "proxy turn created a session"); + assert.equal(effectiveAbsorbConfig(xSess!, defaultConfig(200_000))?.toolName, "route_absorb", "proxy lane honors the route override"); + const lastFwd = rig.forwards[rig.forwards.length - 1]!; + assert.ok(lastFwd.includes('"route_absorb"'), "proxy wire injects the renamed absorb tool"); + } finally { + await closeRig(rig); + } +});