Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
4 changes: 2 additions & 2 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
26 changes: 15 additions & 11 deletions src/compress-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand All @@ -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;
Expand Down
15 changes: 15 additions & 0 deletions src/compress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
*/
import {
parseCompressArgs,
ABSORB_TOOL,
ABSORB_TOOL_GOOGLE,
ABSORB_TOOL_OPENAI,
DECOMPRESS_TOOL,
DECOMPRESS_TOOL_GOOGLE,
Expand Down Expand Up @@ -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.
Expand Down
41 changes: 41 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();

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
Expand All @@ -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);
Expand Down
14 changes: 9 additions & 5 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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/
Expand All @@ -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",
Expand Down
Loading
Loading