From 93e25138e4275768ffc230ebbcda8473a56203b7 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 12:34:33 +0800 Subject: [PATCH 1/4] feat: acp_rule on by default + /acp-rule remove/clear forwarding (#1399) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 诉求 1 — compress.rules defaults ON (owner decision: the model owns session rules): - rulesEnabled(): absent block now means enabled; only explicit false disables - new effectiveRulesEnabled() for the session-level plugin-tool paths (loop/core executeProxyTool, absorb isProxyToolFor, plugin tool allowlist) - kernel needs no change: acp_rule is unconditionally protected there 诉求 2 — human-side parity: pi/omp /acp-rule now forwards the full op set: - bare = list, text = record (unchanged) - 'remove ' -> { delete: id }; bare 'remove' warns with usage, no forward - bare 'clear' -> { clear: true }; 'clear ' records (typo guard) Docs en+zh: rules default line + migration note, /acp-rule usage incl. remove/clear, stale '#1178' claim removed. Tests: default-on expectations flipped at every gate site, new forwarding/regression cases, wire-contract ledger + manifest-default golden regenerated via scripts/update-wire-contract-goldens.ts. --- CONFIGURATION.md | 4 +- CONFIGURATION.zh-CN.md | 4 +- PLUGIN.md | 2 +- README.md | 20 +++-- README.zh-CN.md | 4 +- src/absorb.ts | 4 +- src/agent/pi.ts | 32 +++++-- src/config.ts | 5 +- src/loop/core.ts | 4 +- src/plugin.ts | 4 +- src/rules-feature.ts | 13 ++- tests/codex-official.test.ts | 5 +- .../wire-contract/manifest-default.json | 82 +++++++++++++++++- tests/issue1192-disabled-tools.test.ts | 16 +++- tests/issue1204-rules-google-plugin.test.ts | 4 +- tests/launcher-plugin-mode.test.ts | 4 +- tests/plugin-agent.test.ts | 83 +++++++++++++++++++ tests/plugin-protocol.test.ts | 21 ++--- tests/preflight-compress.test.ts | 20 +++-- tests/rules-wire.test.ts | 25 +++++- tests/rules.test.ts | 59 ++++++++----- tests/wire-contract.test.ts | 19 +++-- 22 files changed, 343 insertions(+), 91 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 21b0c7a9f4..1563b864bd 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -404,9 +404,9 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t #### `rules` - **Type:** `boolean` -- **Default:** `false` +- **Default:** `true` (since #1399; previously `false`) - **Status:** ACTIVE -- **Description:** Opt-in **persistent model reminders** (issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433), via the `acp-kernel` rules API). When enabled, an `acp_rule` tool is injected alongside the ACP tools: calling it with a short `rule` argument records a principle-level reminder that is **hard-protected** from compression (the call + result stay in context across every fold), and omitting the argument lists the recorded rules. Passing `delete` with a rule id (e.g. `"rule3"`) removes that one rule (`Removed ruleN: `); passing `clear: true` removes every rule. The two are mutually exclusive with each other and with `rule` — one operation per call — so a stale or accidentally-recorded rule can be deleted instead of hedged with a counter-rule. Guidance on *when* to record (user-emphasized lessons, behaviors the user asks to remember, major pitfalls hit) lives entirely in the tool description — nothing is added to the system prompt. Kernel limits apply (50 rules × 300 chars each); duplicate text is rejected pointing at the existing id. Injection follows the wire's native-tool surface exactly like `absorb`: proxy mode injects the tool 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; execution gated per session). Recorded rules persist across restarts in the session state; removals persist the same way. Requires `acp-kernel` >= 0.0.70 (>= 0.0.84 for delete/clear). Humans can inspect or record rules without going through the model: pi/omp expose a native `/acp-rule` command — bare `/acp-rule` lists every recorded rule, `/acp-rule ` records one directly (#1251). +- **Description:** **Persistent model reminders** (issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433), via the `acp-kernel` rules API), **on by default since #1399** — set `compress.rules: false` to restore the previous opt-in behavior. When enabled, an `acp_rule` tool is injected alongside the ACP tools: calling it with a short `rule` argument records a principle-level reminder that is **hard-protected** from compression (the call + result stay in context across every fold), and omitting the argument lists the recorded rules. Passing `delete` with a rule id (e.g. `"rule3"`) removes that one rule (`Removed ruleN: `); passing `clear: true` removes every rule. The two are mutually exclusive with each other and with `rule` — one operation per call — so a stale or accidentally-recorded rule can be deleted instead of hedged with a counter-rule. Guidance on *when* to record (user-emphasized lessons, behaviors the user asks to remember, major pitfalls hit) lives entirely in the tool description — nothing is added to the system prompt. Kernel limits apply (50 rules × 300 chars each); duplicate text is rejected pointing at the existing id. Injection follows the wire's native-tool surface exactly like `absorb`: proxy mode injects the tool 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; execution gated per session). Recorded rules persist across restarts in the session state; removals persist the same way. Requires `acp-kernel` >= 0.0.70 (>= 0.0.84 for delete/clear). Humans get the full operation set without going through the model: pi/omp expose a native `/acp-rule` command with the same semantics as the tool — bare `/acp-rule` lists every recorded rule, `/acp-rule ` records one directly, `/acp-rule remove ` deletes one, and bare `/acp-rule clear` wipes all recorded rules (`clear ` records instead of wiping) (#1251; remove/clear added in #1399). #### `reasoning` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 6eb0f05593..b30a6d31fd 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -404,9 +404,9 @@ #### `rules` - **类型:** `boolean` -- **默认值:** `false` +- **默认值:** `true`(#1399 起;此前为 `false`) - **状态:** ACTIVE -- **说明:** 可选开启的**持久化模型提醒**(issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433),经由 `acp-kernel` rules API)。启用后,一个 `acp_rule` 工具随 ACP 工具一同注入:传入简短的 `rule` 参数调用可记录一条**原则级提醒**,该提醒受**硬性保护**免于压缩(调用及结果在每次折叠中都保留在上下文中);省略参数则列出已记录的规则。传入 `delete`(规则 id,如 `"rule3"`)删除该条规则(返回 `Removed ruleN: `);传入 `clear: true` 清空全部规则。两者互斥,且均与 `rule` 互斥——一次调用只能执行一种操作——因此过时或误记的规则可以直接删除,而无需再写一条"作废声明"对冲。关于*何时*记录(用户强调的教训、用户要求记住的行为、遇到的重大陷阱)的指导完全写在工具描述里——不向系统提示词添加任何内容。受内核限制约束(50 条规则 × 每条 300 字符);重复文本会被拒绝并指向已有的 id。注入跟随线上原生工具面,与 `absorb` 完全一致:代理模式在 anthropic/openai/responses 原生工具线上注入该工具,插件模式在插件清单中声明(执行按会话门控)。已记录的规则在会话状态中持久化,跨重启保留;删除同样持久化。要求 `acp-kernel` >= 0.0.70(delete/clear 需要 >= 0.0.84)。人也可以不经过模型查看或记录指令:pi/omp 提供原生 `/acp-rule` 命令 —— 裸 `/acp-rule` 列出全部已记录规则,`/acp-rule <文本>` 直接记录一条(#1251)。 +- **说明:** **持久化模型提醒**(issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433),经由 `acp-kernel` rules API),**#1399 起默认开启**——设 `compress.rules: false` 可恢复旧的可选开启行为。启用后,一个 `acp_rule` 工具随 ACP 工具一同注入:传入简短的 `rule` 参数调用可记录一条**原则级提醒**,该提醒受**硬性保护**免于压缩(调用及结果在每次折叠中都保留在上下文中);省略参数则列出已记录的规则。传入 `delete`(规则 id,如 `"rule3"`)删除该条规则(返回 `Removed ruleN: `);传入 `clear: true` 清空全部规则。两者互斥,且均与 `rule` 互斥——一次调用只能执行一种操作——因此过时或误记的规则可以直接删除,而无需再写一条"作废声明"对冲。关于*何时*记录(用户强调的教训、用户要求记住的行为、遇到的重大陷阱)的指导完全写在工具描述里——不向系统提示词添加任何内容。受内核限制约束(50 条规则 × 每条 300 字符);重复文本会被拒绝并指向已有的 id。注入跟随线上原生工具面,与 `absorb` 完全一致:代理模式在 anthropic/openai/responses 原生工具线上注入该工具,插件模式在插件清单中声明(执行按会话门控)。已记录的规则在会话状态中持久化,跨重启保留;删除同样持久化。要求 `acp-kernel` >= 0.0.70(delete/clear 需要 >= 0.0.84)。人也可以不经过模型执行全部操作:pi/omp 提供原生 `/acp-rule` 命令,语义与工具一致 —— 裸 `/acp-rule` 列出全部已记录规则,`/acp-rule <文本>` 直接记录一条,`/acp-rule remove ` 删除一条,裸 `/acp-rule clear` 清空全部(`clear <文本>` 是记录而非清空)(#1251;remove/clear 由 #1399 补齐)。 #### `reasoning` diff --git a/PLUGIN.md b/PLUGIN.md index be6c94e5db..0484279642 100644 --- a/PLUGIN.md +++ b/PLUGIN.md @@ -50,7 +50,7 @@ Fetch once at plugin startup. } ``` -Register the tools natively with your agent, in whichever wire format your agent speaks — register exactly what `toolNames` lists. The opt-in tools (`absorb`, `acp_rule`) appear only when the proxy's config enables them; calling one that is known but disabled answers `200` with an explanatory `result` instead of an error (#1192). If `protocolVersion` is higher than you know, still register the tools — extra fields in schemas are ignored by agents. +Register the tools natively with your agent, in whichever wire format your agent speaks — register exactly what `toolNames` lists. `absorb` appears only when the proxy's config enables it; `acp_rule` is advertised by default since #1399 (an explicit `compress.rules: false` hides it again). Calling a tool that is known but disabled answers `200` with an explanatory `result` instead of an error (#1192). If `protocolVersion` is higher than you know, still register the tools — extra fields in schemas are ignored by agents. ### 2. Request headers diff --git a/README.md b/README.md index ef247109a0..efa2491d0b 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ The proxy injects four context-management tools (`compress`, `decompress`, `sear An opt-in fifth tool, `absorb` (`compress.absorb.enabled: true` — see [CONFIGURATION.md](CONFIGURATION.md)), compresses **individual tool results the moment they arrive**: large results (builds, logs, greps) get a forced absorb instruction, the model distills each into a compact summary, and the original pair is hidden from the wire from the next turn on — keeping mid-session pressure lower between fold rounds (#605). -An opt-in sixth tool, `acp_rule` (`compress.rules: true` — see [CONFIGURATION.md](CONFIGURATION.md)), records **persistent principle-level reminders**: a short rule recorded by the model (user-emphasized lessons, behaviors to remember, major pitfalls hit) is hard-protected from compression — the call and its result stay in context across every fold — and omitting the argument lists the recorded rules; passing `delete` with a rule id (e.g. `"rule3"`) removes one rule and `clear: true` removes all of them ([ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433)). +The sixth tool, `acp_rule` (on by default since #1399; set `compress.rules: false` to restore the previous opt-in behavior — see [CONFIGURATION.md](CONFIGURATION.md)), records **persistent principle-level reminders**: a short rule recorded by the model (user-emphasized lessons, behaviors to remember, major pitfalls hit) is hard-protected from compression — the call and its result stay in context across every fold — and omitting the argument lists the recorded rules; passing `delete` with a rule id (e.g. `"rule3"`) removes one rule and `clear: true` removes all of them ([ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433)). The seventh tool, `acp_retrieve` (opt-in on every lane — set `compress.ccr.enabled: true` at any level, after local verification; plugin lanes require the explicit global `true` so the manifest advertises the tool, #1271/#1273 — see [CONFIGURATION.md](CONFIGURATION.md)), backs the **content-addressed message store** (built-in CCR, #1097/#1179): oversized tool results are **ID-referenced at arrival instead of force-distilled** — the wire keeps a byte-stable placeholder and the original goes into a per-session content-store envelope (hash-deduped), retrievable on demand via one cheap tool call. V2 makes folds lossless too: covered originals are stored when a fold lands, `decompress` restores ranges (`startId`/`endId` refs) instead of whole blocks, and `search_context` hits carry the covered `mNNNNN` refs so you can fetch exactly what you need. Lossless by default: a retrieve not made costs nothing but the call; a detail distilled away by absorb is gone for good. Scope: proxy mode, plus plugin lanes on the anthropic + openai wires when explicitly enabled (`acp_retrieve` is advertised in the plugin manifest then, #1271); responses marker/text routes and google in plugin mode stay disarmed because no request-only round-trip channel exists there (silent loss, #1097). @@ -884,14 +884,16 @@ API: `bili plugin install claude` writes a model-mediated MCP tool and pastes the report back verbatim. codex/kimi/hermes expose no user-typable command seam — ask the model to call its `acp_cache` tool directly. -The same seam carries `/acp-rule` (#1251) — the human entry point to the -persistent-rules feature (identical output to the `acp_rule` tool): pi/omp -register it natively — bare `/acp-rule` lists every recorded rule, and -`/acp-rule ` records one directly (as if the model had called it). The -wrapped transcript message is stripped from model context by content signature -like the cache report — recorded rules reach the model every turn via the -system-prompt injection anyway. delete/clear subcommands land with #1178; -other lanes get it in follow-up work. +The same seam carries `/acp-rule` (#1251/#1399) — the human entry point to +the persistent-rules feature (identical output to the `acp_rule` tool): +pi/omp register it natively with the tool's full operation set — bare +`/acp-rule` lists every recorded rule, `/acp-rule ` records one directly +(as if the model had called it), `/acp-rule remove ` deletes one, and bare +`/acp-rule clear` wipes all recorded rules (`clear ` records instead of +wiping — a typo must not destroy every rule). The wrapped transcript message +is stripped from model context by content signature like the cache report — +recorded rules reach the model every turn via the system-prompt injection +anyway. ### Legacy opencode-acp sessions (#920) diff --git a/README.zh-CN.md b/README.zh-CN.md index 22612082f7..586367121b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -90,7 +90,7 @@ QQ群: 可选的第五个工具 `absorb`(`compress.absorb.enabled: true` —— 见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md))对**各个工具结果即时压缩**:大结果(构建、日志、grep)被附带强制吸收指令,模型将各自蒸馏为紧凑摘要,原配对从下一轮起从线上隐藏 —— 使折叠轮之间的中间会话压力更低(#605)。 -可选的第六个工具 `acp_rule`(`compress.rules: true` —— 见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md))记录**持久化的原则级提醒**:模型记录的简短规则(用户强调的教训、要求记住的行为、撞到的大坑)受硬性保护不被压缩——调用及结果在每次折叠中都保留在上下文中——省略参数则列出已记录规则;传入 `delete`(规则 id,如 `"rule3"`)删除单条规则,传入 `clear: true` 清空全部规则([ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433))。 +第六个工具 `acp_rule`(#1399 起默认开启;设 `compress.rules: false` 可恢复旧的可选开启行为 —— 见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md))记录**持久化的原则级提醒**:模型记录的简短规则(用户强调的教训、要求记住的行为、撞到的大坑)受硬性保护不被压缩——调用及结果在每次折叠中都保留在上下文中——省略参数则列出已记录规则;传入 `delete`(规则 id,如 `"rule3"`)删除单条规则,传入 `clear: true` 清空全部规则([ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433))。 第七个工具 `acp_retrieve`(全车道默认关闭、显式开启 —— 任意层级设 `compress.ccr.enabled: true` 方可启用,建议先本地验证;插件车道需全局显式 `true` 才会在 manifest 广播工具,#1271/#1273;见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md))支撑**内容寻址消息存储**(内置 CCR,#1097/#1179):超大工具结果**在到达时改为 ID 引用,而非强制蒸馏**——线上保留字节稳定的占位符,原文进入按会话的内容存储信封(按内容哈希去重),模型通过一次廉价工具调用按需取回。v2 让折叠同样无损:折叠落定时被覆盖的原文会存入存储,`decompress` 可按区间恢复(`startId`/`endId` ref)而无需整块展开,`search_context` 命中条目携带覆盖的 `mNNNNN` ref,让你精确取回所需内容。默认无损:未执行的 retrieve 只花一次调用;而被 absorb 蒸馏掉的细节则永久丢失。仅代理模式、仅原生工具线(marker/文本协议没有执行 retrieve 的通道,存储在这些场景下自动解除武装,而不是静默丢失内容)。 @@ -387,7 +387,7 @@ HTTPS 走证书 MITM,HTTP 走临时 `opencode.json` 副本(`/bili/` 改写;JSONC `/acp` 面板在所有模式下都绑定当前会话,`acp_status` 工具是其宿主内等价手段。在命令编辑器支持新增条目的宿主(2.0.x 稳定版,`editor.add`)上,V2 插件额外注册 `/acp` 斜杠命令 —— 以合成非模型消息渲染,面板优先(与 `acp_status` 工具一致);旧形状上该注册保持惰性。注意 `opencode run` 模式完全不派发斜杠命令(它们会透传给模型)—— 请用 TUI。 -同一接缝还承载 `/acp-rule`(#1251)—— 持久指令功能的人侧入口(输出与 `acp_rule` 工具一致):pi/omp 原生注册 —— 裸 `/acp-rule` 逐字列出全部已记录指令,`/acp-rule <文本>` 直接记录一条(等价于模型调用)。包裹后的 transcript 消息按内容签名从模型上下文剥离(与缓存报告同机制)—— 已记录的指令本来就每轮经 system prompt 注入。delete/clear 子命令随 #1178 落地;其他 lane 见后续工作。 +同一接缝还承载 `/acp-rule`(#1251/#1399)—— 持久指令功能的人侧入口(输出与 `acp_rule` 工具一致):pi/omp 原生注册,操作集与工具完全一致 —— 裸 `/acp-rule` 逐字列出全部已记录指令,`/acp-rule <文本>` 直接记录一条(等价于模型调用),`/acp-rule remove ` 删除一条,裸 `/acp-rule clear` 清空全部(`clear <文本>` 是记录而非清空——一个手误不该毁掉所有规则)。包裹后的 transcript 消息按内容签名从模型上下文剥离(与缓存报告同机制)—— 已记录的指令本来就每轮经 system prompt 注入。 ### 旧 opencode-acp 会话(#920) diff --git a/src/absorb.ts b/src/absorb.ts index aaf812b2b6..66b680cc02 100644 --- a/src/absorb.ts +++ b/src/absorb.ts @@ -12,7 +12,7 @@ import { type CoreMessage, } from "acp-kernel"; import { PROXY_TOOL_NAMES, RULE_TOOL_NAME } from "./compress-tool.js"; -import { effectiveRulesConfig } from "./rules-feature.js"; +import { effectiveRulesEnabled } from "./rules-feature.js"; import { IMAGE_FULL_TOOL_NAME, imageCompressionEnabled } from "./image-compress.js"; import { ccrEnabled, retrieveToolName } from "./store.js"; import { log as loggerLog } from "./logger.js"; @@ -52,7 +52,7 @@ export function isProxyToolFor(name: string, session: Session | undefined, confi if (absorb?.enabled === true && name === (absorb.toolName ?? ABSORB_TOOL_NAME)) return true; if (ccrEnabled(session) && name === retrieveToolName(session)) return true; if (imageCompressionEnabled(session) && name === IMAGE_FULL_TOOL_NAME) return true; - return effectiveRulesConfig(session, config)?.enabled === true && name === RULE_TOOL_NAME; + return effectiveRulesEnabled(session, config) && name === RULE_TOOL_NAME; } // Per-turn view transform: drop absorbed tool-call/result pairs, then append diff --git a/src/agent/pi.ts b/src/agent/pi.ts index 48d9bd7a33..572a8666e1 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -568,13 +568,15 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM notify(text, "info"); }, }); - // #1251: human entry point for the persistent-rules feature — the model side - // already has the acp_rule tool; this command shows humans the identical list - // (both paths hit executeRule on the proxy) and lets a human record a rule - // directly by passing text. Launcher mode and native mode both load this - // factory (see pi-native.ts), so one registration covers both. + // #1251/#1399: human entry point for the persistent-rules feature — the model + // side already has the acp_rule tool; this command shows humans the identical + // list (both paths hit executeRule on the proxy) and gives humans the full + // operation set: record by passing text, remove one via `remove `, wipe + // all via bare `clear` (extra words after clear are recorded, never wiped — + // a typo must not destroy every rule). Launcher mode and native mode both + // load this factory (see pi-native.ts), so one registration covers both. pi.registerCommand("acp-rule", { - description: "Persistent rules for this session (same list as the acp_rule tool). Usage: /acp-rule [text to record]", + description: "Persistent rules for this session (same ops as the acp_rule tool). Usage: /acp-rule [text to record] | /acp-rule remove | /acp-rule clear", handler: async (args, ctx) => { const notify = (message: string, type?: string): void => { try { @@ -589,8 +591,22 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM return; } const conversationId = sessionIdOf(ctx) ?? "unknown"; - const ruleText = (args ?? "").trim(); - const toolArgs = ruleText.length > 0 ? { rule: ruleText } : {}; + const raw = (args ?? "").trim(); + let toolArgs: Record; + if (raw === "") { + toolArgs = {}; + } else if (raw === "clear") { + toolArgs = { clear: true }; + } else if (raw === "remove" || raw.startsWith("remove ")) { + const id = raw.slice("remove".length).trim(); + if (id === "") { + notify("Usage: /acp-rule remove — bare /acp-rule lists the recorded ids", "warning"); + return; + } + toolArgs = { delete: id }; + } else { + toolArgs = { rule: raw }; + } let text: string; try { text = await forwardTool(proxyBase, conversationId, "acp_rule", toolArgs); diff --git a/src/config.ts b/src/config.ts index f0b6fe1e31..c56676dbae 100644 --- a/src/config.ts +++ b/src/config.ts @@ -317,8 +317,9 @@ export type CompressSettings = { * for the life of the session; omitting the argument lists recorded * rules for human review. The feature deliberately adds NO system-prompt * content (all guidance rides in the tool description). Maps to kernel - * `Config.rules = { enabled }`. Off unless explicitly enabled at some - * level. Deepest-wins like every other scalar field. */ + * `Config.rules = { enabled }`. On by default since #1399 — an explicit + * `false` at any level disables it. Deepest-wins like every other scalar + * field. */ rules?: boolean; /** Opt-in removal of historical image payloads, executed by the kernel's diff --git a/src/loop/core.ts b/src/loop/core.ts index daf6096895..a11bbb1b0b 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -14,7 +14,7 @@ import { RULE_TOOL_NAME, } from "../compress-tool.js"; import { effectiveAbsorbConfig, executeAbsorb, isProxyToolFor } from "../absorb.js"; -import { effectiveRulesConfig, executeRule } from "../rules-feature.js"; +import { effectiveRulesEnabled, executeRule } from "../rules-feature.js"; import { ccrEnabled, drainPendingRetrievals, executeRetrieve, retrieveToolName } from "../store.js"; import { IMAGE_FULL_TOOL_NAME, executeImageFull, imageCompressionEnabled, imageUsageSuffix } from "../image-compress.js"; import { applyRanges } from "../stream.js"; @@ -184,7 +184,7 @@ export function executeProxyTool( if (absorb?.enabled === true && toolName === (absorb.toolName ?? ABSORB_TOOL_NAME)) { return executeAbsorb(args, callId, absorb, ctx); } - if (effectiveRulesConfig(ctx.session, ctx.config)?.enabled === true && toolName === RULE_TOOL_NAME) { + if (effectiveRulesEnabled(ctx.session, ctx.config) && toolName === RULE_TOOL_NAME) { return executeRule(args, ctx); } if (ccrEnabled(ctx.session) && toolName === retrieveToolName(ctx.session)) { diff --git a/src/plugin.ts b/src/plugin.ts index 440af59ad7..197637947b 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -7,7 +7,7 @@ import path from "node:path"; import { acquireInFlight, effectiveConfig, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, withSessionLock, type Session } from "./session.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 { effectiveRulesEnabled, rulesEnabled } from "./rules-feature.js"; import { executeProxyTool } from "./loop/core.js"; import { normalizeSseLineEndings } from "./sse-util.js"; import { composeStreamFilters, containsMarkerLineText, containsRenderTagText, containsToolCallXmlFragment, createMarkerLineFilter, createTagEchoFilter, mayStartMarkerLine, mayStartRenderTag, stripAcpTags, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js"; @@ -894,7 +894,7 @@ export async function handlePluginTool( const allowed = [...PROXY_TOOL_NAMES]; const absorb = effectiveAbsorbConfig(session, deps.config); if (absorb?.enabled === true) allowed.push(absorb.toolName ?? ABSORB_TOOL_NAME); - if (effectiveRulesConfig(session, deps.config)?.enabled === true) allowed.push(RULE_TOOL_NAME); + if (effectiveRulesEnabled(session, deps.config)) allowed.push(RULE_TOOL_NAME); res.writeHead(400, { "content-type": "application/json" }); res.end(JSON.stringify({ ok: false, error: `unknown tool "${tool}" (expected one of: ${allowed.join(", ")})` })); return; diff --git a/src/rules-feature.ts b/src/rules-feature.ts index b284cd8d24..1c7a810247 100644 --- a/src/rules-feature.ts +++ b/src/rules-feature.ts @@ -12,8 +12,12 @@ import type { Session } from "./session.js"; const EFFECTIVE_RULES_KEY = "effectiveRules"; +// #1399: default-ON since the owner decision "the model has full rights over +// session rules" — an absent block means enabled, only an explicit +// `enabled: false` (user `compress.rules: false`) disables the feature. The +// pre-#1399 semantics were opt-in (`=== true`). export function rulesEnabled(config: Config): boolean { - return config.rules?.enabled === true; + return config.rules?.enabled ?? true; } // Two config sources exist (same split as absorb): wire paths carry the @@ -33,6 +37,13 @@ export function storeEffectiveRules(session: Session, config: Config): void { session.metadata[EFFECTIVE_RULES_KEY] = config.rules ?? null; } +// Session-level enablement for paths without a per-request resolved Config +// (plugin tool API): last resolved block wins, base config otherwise — same +// #1399 default-on semantics as rulesEnabled. +export function effectiveRulesEnabled(session: Session | undefined, fallback: Config): boolean { + return effectiveRulesConfig(session, fallback)?.enabled ?? true; +} + export type RuleExecCtx = { config: Config; session: Session; diff --git a/tests/codex-official.test.ts b/tests/codex-official.test.ts index d95028ac73..34bc0bfc3f 100644 --- a/tests/codex-official.test.ts +++ b/tests/codex-official.test.ts @@ -118,10 +118,11 @@ test("Codex official transport preserves OAuth headers, decodes bodies, and reba assert.equal(forwarded.instructions, undefined); assert.deepEqual(forwarded.additional_tools, requestBody.additional_tools); // CCR explicitly enabled in this test's compress config (#1207 - // opt-in), so acp_retrieve joins the injected tool set. + // opt-in), so acp_retrieve joins the injected tool set; acp_rule is + // in the default surface since #1399. assert.deepEqual( forwarded.tools.map((t: { name: string }) => t.name), - ["shell", "compress", "decompress", "search_context", "acp_status", "acp_cache", "acp_retrieve"], + ["shell", "compress", "decompress", "search_context", "acp_status", "acp_cache", "acp_rule", "acp_retrieve"], ); const session = listSessions().find((candidate) => candidate.meta.label === sessionId); diff --git a/tests/golden/wire-contract/manifest-default.json b/tests/golden/wire-contract/manifest-default.json index 7b8ab96833..278b859b7f 100644 --- a/tests/golden/wire-contract/manifest-default.json +++ b/tests/golden/wire-contract/manifest-default.json @@ -8,7 +8,8 @@ "decompress", "search_context", "acp_status", - "acp_cache" + "acp_cache", + "acp_rule" ], "tools": { "anthropic": [ @@ -201,6 +202,31 @@ } } } + }, + { + "name": "acp_rule", + "description": "Record a short, principle-level reminder so it survives context compression — the call and its result are protected and stay in context. Record when: the user calls out or repeatedly emphasizes a lesson; the user asks you to remember or follow a behavior; you personally hit a major pitfall worth remembering long-term. Keep each rule to one short line. Omit the rule argument to list recorded rules. To remove a recorded rule pass delete with its id (e.g. \"rule3\"); to remove every recorded rule pass clear: true. delete and clear are mutually exclusive with each other and with rule — use one operation per call.", + "input_schema": { + "type": "object", + "properties": { + "rule": { + "type": "string", + "description": "Short principle-level reminder to record. Omit to list recorded rules." + }, + "delete": { + "type": "string", + "description": "Id of a recorded rule to remove (e.g. \"rule3\"). Mutually exclusive with rule and clear." + }, + "clear": { + "type": "boolean", + "description": "Remove every recorded rule at once. Mutually exclusive with rule and delete." + }, + "conversation_id": { + "type": "string", + "description": "Your bili conversation id (the value from the 'your bili conversation id' line in the proxy notes). Pass it on every call when your host shares one MCP process across several concurrent conversations; omit it when the host bound the session itself." + } + } + } } ], "openai": [ @@ -408,6 +434,34 @@ } } } + }, + { + "type": "function", + "function": { + "name": "acp_rule", + "description": "Record a short, principle-level reminder so it survives context compression — the call and its result are protected and stay in context. Record when: the user calls out or repeatedly emphasizes a lesson; the user asks you to remember or follow a behavior; you personally hit a major pitfall worth remembering long-term. Keep each rule to one short line. Omit the rule argument to list recorded rules. To remove a recorded rule pass delete with its id (e.g. \"rule3\"); to remove every recorded rule pass clear: true. delete and clear are mutually exclusive with each other and with rule — use one operation per call.", + "parameters": { + "type": "object", + "properties": { + "rule": { + "type": "string", + "description": "Short principle-level reminder to record. Omit to list recorded rules." + }, + "delete": { + "type": "string", + "description": "Id of a recorded rule to remove (e.g. \"rule3\"). Mutually exclusive with rule and clear." + }, + "clear": { + "type": "boolean", + "description": "Remove every recorded rule at once. Mutually exclusive with rule and delete." + }, + "conversation_id": { + "type": "string", + "description": "Your bili conversation id (the value from the 'your bili conversation id' line in the proxy notes). Pass it on every call when your host shares one MCP process across several concurrent conversations; omit it when the host bound the session itself." + } + } + } + } } ], "responses": [ @@ -605,6 +659,32 @@ } } } + }, + { + "type": "function", + "name": "acp_rule", + "description": "Record a short, principle-level reminder so it survives context compression — the call and its result are protected and stay in context. Record when: the user calls out or repeatedly emphasizes a lesson; the user asks you to remember or follow a behavior; you personally hit a major pitfall worth remembering long-term. Keep each rule to one short line. Omit the rule argument to list recorded rules. To remove a recorded rule pass delete with its id (e.g. \"rule3\"); to remove every recorded rule pass clear: true. delete and clear are mutually exclusive with each other and with rule — use one operation per call.", + "parameters": { + "type": "object", + "properties": { + "rule": { + "type": "string", + "description": "Short principle-level reminder to record. Omit to list recorded rules." + }, + "delete": { + "type": "string", + "description": "Id of a recorded rule to remove (e.g. \"rule3\"). Mutually exclusive with rule and clear." + }, + "clear": { + "type": "boolean", + "description": "Remove every recorded rule at once. Mutually exclusive with rule and delete." + }, + "conversation_id": { + "type": "string", + "description": "Your bili conversation id (the value from the 'your bili conversation id' line in the proxy notes). Pass it on every call when your host shares one MCP process across several concurrent conversations; omit it when the host bound the session itself." + } + } + } } ] }, diff --git a/tests/issue1192-disabled-tools.test.ts b/tests/issue1192-disabled-tools.test.ts index 06f176ac6c..d464c911c1 100644 --- a/tests/issue1192-disabled-tools.test.ts +++ b/tests/issue1192-disabled-tools.test.ts @@ -1,9 +1,11 @@ // #1192: dsh registered the manifest's tools verbatim, so it called acp_rule -// even though compress.rules was never enabled — every call died with a hard +// even though compress.rules was disabled — every call died with a hard // 400 "unknown tool". The manifest side (only advertise enabled opt-in tools) // is covered by the plugin-protocol / rules / absorb suites; this pins the // execution side: a known-but-disabled opt-in tool answers with a model-facing -// explanation (ok:true), while a genuinely unknown tool still 400s. +// explanation (ok:true), while a genuinely unknown tool still 400s. Since +// #1399 the feature is on by default, so "disabled" here means an explicit +// `compress.rules: false`. import assert from "node:assert/strict"; import http from "node:http"; import { beforeEach, describe, it } from "node:test"; @@ -38,7 +40,8 @@ describe("#1192: known-but-disabled opt-in tools get an explanation, not a hard return { status: out.status(), json: JSON.parse(out.body()) as Record }; } - it("acp_rule with rules disabled → ok:true explanation instead of 400", async () => { + it("acp_rule with rules explicitly disabled → ok:true explanation instead of 400", async () => { + deps.config = { ...deps.config, rules: { enabled: false } }; const r = await call("acp_rule", { rule: "verify driver unload+reload" }); assert.equal(r.status, 200); assert.equal(r.json.ok, true); @@ -46,6 +49,13 @@ describe("#1192: known-but-disabled opt-in tools get an explanation, not a hard assert.match(String(r.json.result), /nothing was recorded/); }); + it("acp_rule with rules unset → executes by default (#1399)", async () => { + const r = await call("acp_rule", { rule: "default-on rule" }); + assert.equal(r.status, 200); + assert.equal(r.json.ok, true); + assert.match(String(r.json.result), /^Recorded rule\d+: default-on rule$/); + }); + it("absorb disabled → ok:true explanation", async () => { const r = await call("absorb", { ref: "m00001", summary: "x" }); assert.equal(r.status, 200); diff --git a/tests/issue1204-rules-google-plugin.test.ts b/tests/issue1204-rules-google-plugin.test.ts index 7e2ec23c2d..08adb1aa8a 100644 --- a/tests/issue1204-rules-google-plugin.test.ts +++ b/tests/issue1204-rules-google-plugin.test.ts @@ -113,8 +113,8 @@ test("#1204 google wire + provider-level rules: plugin tool acp_rule is accepted } }); -test("#1204 google wire + rules off: plugin tool acp_rule stays gated", async () => { - const h = await startHarness(); +test("#1204 google wire + rules explicitly disabled: plugin tool acp_rule stays gated", async () => { + const h = await startHarness({ rules: false }); try { const conv = "issue1204-rules-off"; await sendGoogleTurn(h, conv); diff --git a/tests/launcher-plugin-mode.test.ts b/tests/launcher-plugin-mode.test.ts index 141e6acf7f..02bdbf2ffa 100644 --- a/tests/launcher-plugin-mode.test.ts +++ b/tests/launcher-plugin-mode.test.ts @@ -340,7 +340,7 @@ test("mcp stdio shell: manifest → tools/list → tools/call forwards to the pl const init = byId(1) as { result?: { serverInfo?: { name?: string } } }; assert.equal(init.result?.serverInfo?.name, "bili"); const tools = byId(2) as { result?: { tools?: { name: string }[] } }; - assert.deepEqual(tools.result?.tools?.map((t) => t.name).sort(), ["acp_cache", "acp_status", "compress", "decompress", "search_context"]); + assert.deepEqual(tools.result?.tools?.map((t) => t.name).sort(), ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); const call = byId(3) as { result?: { content?: { text?: string }[]; isError?: boolean } }; assert.equal(call.result?.isError, false); assert.match(call.result?.content?.[0]?.text ?? "", /CONTEXT BREAKDOWN/, "acp_status result forwarded verbatim"); @@ -411,7 +411,7 @@ test("mcp stdio shell (codex style): BILI_CONVERSATION_ID self-register → head const byId = (n: number): Record => JSON.parse(lines.find((l) => (JSON.parse(l) as { id?: number }).id === n) ?? "{}"); const tools = byId(2) as { result?: { tools?: { name: string }[] } }; - assert.deepEqual(tools.result?.tools?.map((t) => t.name).sort(), ["acp_cache", "acp_status", "compress", "decompress", "search_context"], "tools listed"); + assert.deepEqual(tools.result?.tools?.map((t) => t.name).sort(), ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"], "tools listed"); const call = byId(3) as { result?: { content?: { text?: string }[]; isError?: boolean } }; assert.equal(call.result?.isError, false, `tools/call succeeded (self-registered conversation bound)${call.result?.isError ? ": " + (call.result?.content?.[0]?.text ?? "") : ""}`); assert.match(call.result?.content?.[0]?.text ?? "", /CONTEXT BREAKDOWN/); diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index 3b9c37989f..aeeeb056d4 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -1265,6 +1265,89 @@ test("/acp-rule warns with an enablement hint when the proxy reports the feature } }); +test("/acp-rule forwards `remove ` as { delete } to acp_rule (#1399)", async () => { + const proxy = await startRuleProxy("Removed rule1: always run tests first"); + try { + const sent: Array<{ customType: string; content: string }> = []; + const pi = { ...makeFakePi(), sendMessage: (m: { customType: string; content: string }) => sent.push(m) }; + createBiliPlugin()(pi as never); + const cmd = pi.commands.get("acp-rule")!; + const ctx = { + sessionManager: { getSessionId: () => "sess-rules-remove" }, + model: { baseUrl: `${proxy.origin}/bili/https://api.example.com/v1` }, + ui: { notify: (_msg: string) => {} }, + }; + await cmd.handler("remove rule1", ctx); + assert.deepEqual(proxy.calls, [{ conversationId: "sess-rules-remove", tool: "acp_rule", args: { delete: "rule1" } }], "`remove ` forwarded as { delete }"); + assert.equal(sent[0]!.customType, "bili-acp-rule"); + assert.equal(sent[0]!.content, wrapRuleReport("Removed rule1: always run tests first")); + } finally { + await proxy.close(); + } +}); + +test("/acp-rule forwards bare `clear` as { clear: true } to acp_rule (#1399)", async () => { + const proxy = await startRuleProxy("Cleared 2 rule(s)."); + try { + const sent: Array<{ customType: string; content: string }> = []; + const pi = { ...makeFakePi(), sendMessage: (m: { customType: string; content: string }) => sent.push(m) }; + createBiliPlugin()(pi as never); + const cmd = pi.commands.get("acp-rule")!; + const ctx = { + sessionManager: { getSessionId: () => "sess-rules-clear" }, + model: { baseUrl: `${proxy.origin}/bili/https://api.example.com/v1` }, + ui: { notify: (_msg: string) => {} }, + }; + await cmd.handler("clear", ctx); + assert.deepEqual(proxy.calls, [{ conversationId: "sess-rules-clear", tool: "acp_rule", args: { clear: true } }], "bare clear forwarded as { clear: true }"); + assert.equal(sent[0]!.content, wrapRuleReport("Cleared 2 rule(s).")); + } finally { + await proxy.close(); + } +}); + +test("/acp-rule bare `remove` warns with usage instead of forwarding (#1399)", async () => { + const proxy = await startRuleProxy("No rules recorded."); + try { + const notes: Array<{ msg: string; type?: string }> = []; + const pi = makeFakePi(); + createBiliPlugin()(pi as never); + const cmd = pi.commands.get("acp-rule")!; + const ctx = { + sessionManager: { getSessionId: () => "sess-rules-remove-usage" }, + model: { baseUrl: `${proxy.origin}/bili/https://api.example.com/v1` }, + ui: { notify: (msg: string, type?: string) => notes.push({ msg, type }) }, + }; + await cmd.handler("remove", ctx); + assert.equal(proxy.calls.length, 0, "nothing forwarded for a missing id"); + assert.equal(notes.length, 1); + assert.equal(notes[0]!.type, "warning"); + assert.match(notes[0]!.msg, /Usage: \/acp-rule remove /); + } finally { + await proxy.close(); + } +}); + +test("/acp-rule `clear ` records the text instead of wiping (#1399)", async () => { + const proxy = await startRuleProxy("Recorded rule3: clear all caches before deploys"); + try { + const sent: Array<{ customType: string }> = []; + const pi = { ...makeFakePi(), sendMessage: (m: { customType: string }) => sent.push(m) }; + createBiliPlugin()(pi as never); + const cmd = pi.commands.get("acp-rule")!; + const ctx = { + sessionManager: { getSessionId: () => "sess-rules-clear-words" }, + model: { baseUrl: `${proxy.origin}/bili/https://api.example.com/v1` }, + ui: { notify: (_msg: string) => {} }, + }; + await cmd.handler("clear all caches before deploys", ctx); + assert.deepEqual(proxy.calls, [{ conversationId: "sess-rules-clear-words", tool: "acp_rule", args: { rule: "clear all caches before deploys" } }], "extra words after clear are recorded, never wiped"); + assert.equal(sent.length, 1); + } finally { + await proxy.close(); + } +}); + test("omp entry reports x-bili-plugin: omp without env vars", async () => { const proxy = await startFakeProxy(); try { diff --git a/tests/plugin-protocol.test.ts b/tests/plugin-protocol.test.ts index c47bd4a7a0..714dcae90f 100644 --- a/tests/plugin-protocol.test.ts +++ b/tests/plugin-protocol.test.ts @@ -229,14 +229,15 @@ test("plugin manifest serves the exact wire tool schemas, headers and version", assert.equal(manifest.ok, true); assert.equal(manifest.protocolVersion, 1); assert.ok(/^\d+\.\d+\.\d+/.test(manifest.version), `version looks wrong: ${manifest.version}`); - // #1192: absorb/acp_rule are opt-in and only advertised when enabled — - // hosts register manifest tools verbatim, so a disabled tool must not be - // listed (the default config enables neither). acp_cache stays in the base toolset. - assert.deepEqual([...manifest.toolNames].sort(), ["acp_cache", "acp_status", "compress", "decompress", "search_context"]); + // #1192/#1399: absorb is opt-in and only advertised when enabled — hosts register + // manifest tools verbatim, so a disabled tool must not be listed (the default + // config disables it). acp_rule is on by default since #1399. acp_cache stays in + // the base toolset. + assert.deepEqual([...manifest.toolNames].sort(), ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); const names = manifest.tools.anthropic!.map((t) => String(t.name)).sort(); - assert.deepEqual(names, ["acp_cache", "acp_status", "compress", "decompress", "search_context"]); - assert.equal(manifest.tools.openai!.length, 5); - assert.equal(manifest.tools.responses!.length, 5); + assert.deepEqual(names, ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); + assert.equal(manifest.tools.openai!.length, 6); + assert.equal(manifest.tools.responses!.length, 6); // #841: search_context's conversation_id doubles as a cross-session // read-only search target — its param description must carry the // historical-search wording in every wire shape. @@ -294,14 +295,14 @@ test("plugin manifest: absorb advertised when enabled in the global compress blo const resp = await fetch(`http://127.0.0.1:${h.proxyPort}/__bili/plugin/manifest`); assert.equal(resp.status, 200); const manifest = (await resp.json()) as { toolNames: string[]; tools: Record>> }; - assert.deepEqual([...manifest.toolNames].sort(), ["absorb", "acp_cache", "acp_status", "compress", "decompress", "search_context"]); + assert.deepEqual([...manifest.toolNames].sort(), ["absorb", "acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); for (const shape of ["anthropic", "openai", "responses"] as const) { const listed = manifest.tools[shape]!.map((t) => { const fn = t.function as { name?: unknown } | undefined; return typeof t.name === "string" ? t.name : (typeof fn?.name === "string" ? fn.name : ""); }); assert.ok(listed.includes("absorb"), `${shape} has absorb`); - assert.equal(listed.length, 6); + assert.equal(listed.length, 7); } } finally { await h.close(); @@ -316,7 +317,7 @@ test("plugin manifest: absorb omitted when the global compress block disables it const resp = await fetch(`http://127.0.0.1:${h.proxyPort}/__bili/plugin/manifest`); assert.equal(resp.status, 200); const manifest = (await resp.json()) as { toolNames: string[] }; - assert.deepEqual([...manifest.toolNames].sort(), ["acp_cache", "acp_status", "compress", "decompress", "search_context"]); + assert.deepEqual([...manifest.toolNames].sort(), ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); } finally { await h.close(); } diff --git a/tests/preflight-compress.test.ts b/tests/preflight-compress.test.ts index b368073f6e..deaffae43e 100644 --- a/tests/preflight-compress.test.ts +++ b/tests/preflight-compress.test.ts @@ -106,10 +106,12 @@ test("e2e: model switch to a smaller window → preflight compresses before forw kernelConfig: defaultConfig(400_000), // CCR is opt-in on every lane (#1207 owner decision): off unless a // config level sets enabled=true, so the acp_retrieve tool schema does - // not load here. If this exact-budget boundary shifts again, someone - // re-enabled a default — treat that as a regression tripwire. CCR-on - // interplay with the cascade is covered by e2e-compress-cascade.test.ts. - compress: { injectTool: true, injectNudge: true }, + // not load here. acp_rule is pinned off too since #1399 made it + // default-on — its schema shifts this exact-budget fold boundary. If + // the boundary shifts again, someone re-enabled a default — treat that + // as a regression tripwire. CCR-on / rules-on interplay with the + // cascade is covered by e2e-compress-cascade.test.ts / the rules suites. + compress: { injectTool: true, injectNudge: true, rules: false }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false, @@ -301,10 +303,12 @@ test("e2e: fresh session (lastInputTokens=0) whose raw history overflows the win kernelConfig: defaultConfig(400_000), // CCR is opt-in on every lane (#1207 owner decision): off unless a // config level sets enabled=true, so the acp_retrieve tool schema does - // not load here. If this exact-budget boundary shifts again, someone - // re-enabled a default — treat that as a regression tripwire. CCR-on - // interplay with the cascade is covered by e2e-compress-cascade.test.ts. - compress: { injectTool: true, injectNudge: true }, + // not load here. acp_rule is pinned off too since #1399 made it + // default-on — its schema shifts this exact-budget fold boundary. If + // the boundary shifts again, someone re-enabled a default — treat that + // as a regression tripwire. CCR-on / rules-on interplay with the + // cascade is covered by e2e-compress-cascade.test.ts / the rules suites. + compress: { injectTool: true, injectNudge: true, rules: false }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false, diff --git a/tests/rules-wire.test.ts b/tests/rules-wire.test.ts index 8321963ca0..0b2739dda4 100644 --- a/tests/rules-wire.test.ts +++ b/tests/rules-wire.test.ts @@ -120,11 +120,32 @@ test("#749 anthropic wire: acp_rule injected alongside ACP tools when rules enab } }); -test("#749 anthropic wire: acp_rule NOT injected by default (rules off)", async () => { +test("#1399 anthropic wire: acp_rule injected by default (rules unset)", async () => { const up = await startUpstream(); const proxy = await startProxy(up.port); await once(proxy, "listening"); const pport = (proxy.address() as { port: number }).port; + try { + await post(`http://127.0.0.1:${pport}/bili/http://127.0.0.1:${up.port}/v1/messages`, + { "content-type": "application/json", "anthropic-version": "2023-06-01", "x-acp-session": "rw-ant-default" }, + JSON.stringify({ model: "m-test", max_tokens: 1024, stream: true, messages: [{ role: "user", content: "hi" }] })); + const tools = up.bodies()[0].tools as Array<{ name?: unknown }>; + const names = tools.map((t) => t.name); + assert.ok(names.includes("compress"), "ACP tools still injected"); + assert.ok(names.includes("acp_rule"), `acp_rule present by default since #1399 (got: ${names.join(", ")})`); + } finally { + proxy.close(); + await once(proxy, "close"); + up.server.close(); + await once(up.server, "close"); + } +}); + +test("#749 anthropic wire: acp_rule NOT injected when explicitly disabled", async () => { + const up = await startUpstream(); + const proxy = await startProxy(up.port, { rules: false }); + await once(proxy, "listening"); + const pport = (proxy.address() as { port: number }).port; try { await post(`http://127.0.0.1:${pport}/bili/http://127.0.0.1:${up.port}/v1/messages`, { "content-type": "application/json", "anthropic-version": "2023-06-01", "x-acp-session": "rw-ant-off" }, @@ -132,7 +153,7 @@ test("#749 anthropic wire: acp_rule NOT injected by default (rules off)", async const tools = up.bodies()[0].tools as Array<{ name?: unknown }>; const names = tools.map((t) => t.name); assert.ok(names.includes("compress"), "ACP tools still injected"); - assert.ok(!names.includes("acp_rule"), `acp_rule absent by default (got: ${names.join(", ")})`); + assert.ok(!names.includes("acp_rule"), `acp_rule absent when disabled (got: ${names.join(", ")})`); } finally { proxy.close(); await once(proxy, "close"); diff --git a/tests/rules.test.ts b/tests/rules.test.ts index 0c9cdca69c..f6e19a4cee 100644 --- a/tests/rules.test.ts +++ b/tests/rules.test.ts @@ -17,6 +17,7 @@ import { executeProxyTool, type LoopCtx } from "../src/loop/core.ts"; import { handlePluginManifest } from "../src/plugin.ts"; import { effectiveRulesConfig, + effectiveRulesEnabled, executeRule, rulesEnabled, storeEffectiveRules, @@ -35,25 +36,27 @@ function makeRuleCtx(config?: Partial): { session: Session; ctx: RuleExe return { session, ctx: { config: cfg, session, log: () => {} } }; } -test("rulesEnabled respects config", () => { - assert.equal(rulesEnabled(defaultConfig(200000)), false); +test("rulesEnabled defaults on (#1399); explicit false disables", () => { + assert.equal(rulesEnabled(defaultConfig(200000)), true); assert.equal(rulesEnabled({ ...defaultConfig(200000), rules: { enabled: false } }), false); assert.equal(rulesEnabled({ ...defaultConfig(200000), rules: { enabled: true } }), true); }); -test("isProxyToolFor: acp_rule only when effectively enabled", () => { +test("isProxyToolFor: acp_rule on by default, off when explicitly disabled (#1399)", () => { const base = defaultConfig(200000); assert.equal(isProxyToolFor("compress", undefined, base), true); - assert.equal(isProxyToolFor(RULE_TOOL_NAME, undefined, base), false); + assert.equal(isProxyToolFor(RULE_TOOL_NAME, undefined, base), true); - const on: Config = { ...base, rules: { enabled: true } }; - assert.equal(isProxyToolFor(RULE_TOOL_NAME, undefined, on), true); + const off: Config = { ...base, rules: { enabled: false } }; + assert.equal(isProxyToolFor(RULE_TOOL_NAME, undefined, off), false); const session = makeSession(); - storeEffectiveRules(session, on); + storeEffectiveRules(session, off); // Plugin tool API reads the per-session stored block even when the - // fallback (base kernel config) has the feature off. - assert.equal(isProxyToolFor(RULE_TOOL_NAME, session, base), true); + // fallback (base kernel config) has the feature on by default. + assert.equal(isProxyToolFor(RULE_TOOL_NAME, session, base), false); + storeEffectiveRules(session, { ...base, rules: { enabled: true } }); + assert.equal(isProxyToolFor(RULE_TOOL_NAME, session, off), true); }); test("effectiveRulesConfig: session metadata wins over fallback; absent stored block falls through", () => { @@ -68,6 +71,19 @@ test("effectiveRulesConfig: session metadata wins over fallback; absent stored b assert.equal(effectiveRulesConfig(undefined, defaultConfig(200000)), undefined); }); +test("effectiveRulesEnabled: unset → on (#1399); explicit false wins from either layer", () => { + const base = defaultConfig(200000); + assert.equal(effectiveRulesEnabled(undefined, base), true); + assert.equal(effectiveRulesEnabled(undefined, { ...base, rules: { enabled: false } }), false); + const session = makeSession(); + storeEffectiveRules(session, base); + assert.equal(effectiveRulesEnabled(session, { ...base, rules: { enabled: false } }), false, "stored-unset block falls through to the disabled fallback"); + storeEffectiveRules(session, { ...base, rules: { enabled: false } }); + assert.equal(effectiveRulesEnabled(session, { ...base, rules: { enabled: true } }), false, "stored false beats fallback true"); + storeEffectiveRules(session, { ...base, rules: { enabled: true } }); + assert.equal(effectiveRulesEnabled(session, base), true, "stored true beats absent fallback"); +}); + test("executeRule: add records with trim, omitting rule lists", () => { const { session, ctx } = makeRuleCtx(); assert.equal(executeRule({ rule: "always run tests before committing" }, ctx), "Recorded rule1: always run tests before committing"); @@ -153,7 +169,7 @@ test("executeProxyTool: routes acp_rule through executeRule when enabled, unknow assert.equal(executeProxyTool(RULE_TOOL_NAME, { delete: "rule1" }, loopCtx), "Removed rule1: via loop"); const offSession = makeSession(); - const offCtx: LoopCtx = { core: createCore(), config: defaultConfig(200000), messages: [], session: offSession, log: () => {} }; + const offCtx: LoopCtx = { core: createCore(), config: { ...defaultConfig(200000), rules: { enabled: false } }, messages: [], session: offSession, log: () => {} }; assert.equal(executeProxyTool(RULE_TOOL_NAME, {}, offCtx), `[Unknown proxy tool: ${RULE_TOOL_NAME}]`); }); @@ -179,9 +195,10 @@ test("applyCompressSettings: maps settings rules onto kernel RuleFeatureConfig", assert.equal(absent.rules, undefined, "absent settings leave the base rules block untouched"); }); -// #1192: hosts register manifest tools verbatim, so a disabled acp_rule must -// not be advertised at all — only a rules-enabled config may list it. -test("handlePluginManifest: acp_rule advertised on all three wires only when rules enabled", () => { +// #1192/#1399: hosts register manifest tools verbatim, so an explicitly +// disabled acp_rule must not be advertised at all — but since #1399 the +// default (unset) config advertises it on all three wires. +test("handlePluginManifest: acp_rule advertised by default, hidden when explicitly disabled", () => { let body = ""; const res = { writeHead: () => {}, end: (b: string) => { body = b; } } as unknown as Parameters[0]; const data = (): { @@ -191,17 +208,17 @@ test("handlePluginManifest: acp_rule advertised on all three wires only when rul handlePluginManifest(res, defaultConfig(200_000)); let d = data(); - assert.ok(!d.toolNames.includes(RULE_TOOL_NAME), "disabled by default → not advertised"); - assert.ok(!d.tools.anthropic.some((t) => t.name === RULE_TOOL_NAME)); - assert.ok(!d.tools.openai.some((t) => t.function?.name === RULE_TOOL_NAME)); - assert.ok(!d.tools.responses.some((t) => t.name === RULE_TOOL_NAME)); - - handlePluginManifest(res, { ...defaultConfig(200_000), rules: { enabled: true } }); - d = data(); - assert.ok(d.toolNames.includes(RULE_TOOL_NAME)); + assert.ok(d.toolNames.includes(RULE_TOOL_NAME), "on by default (#1399) → advertised"); assert.ok(d.tools.anthropic.some((t) => t.name === RULE_TOOL_NAME), "anthropic schema present"); assert.ok(d.tools.openai.some((t) => t.function?.name === RULE_TOOL_NAME)); assert.ok(d.tools.responses.some((t) => t.name === RULE_TOOL_NAME)); + + handlePluginManifest(res, { ...defaultConfig(200_000), rules: { enabled: false } }); + d = data(); + assert.ok(!d.toolNames.includes(RULE_TOOL_NAME), "explicitly disabled → not advertised"); + assert.ok(!d.tools.anthropic.some((t) => t.name === RULE_TOOL_NAME)); + assert.ok(!d.tools.openai.some((t) => t.function?.name === RULE_TOOL_NAME)); + assert.ok(!d.tools.responses.some((t) => t.name === RULE_TOOL_NAME)); }); test("persist round-trip: recorded rules survive save/load", () => { diff --git a/tests/wire-contract.test.ts b/tests/wire-contract.test.ts index 4ce2d36776..806d7bfff6 100644 --- a/tests/wire-contract.test.ts +++ b/tests/wire-contract.test.ts @@ -245,7 +245,10 @@ test("wire-contract C: default manifest serves only legal base tools", () => { assertManifestLegal(m, "default"); const anthNames = new Set(m.tools.anthropic.map((t) => t.name)); for (const n of BILI_ACP_TOOLS_ANTHROPIC.map((t) => t.name)) assert.ok(anthNames.has(n), `default manifest: base tool ${n} present`); - for (const optIn of ["absorb", "acp_rule", "acp_retrieve"]) assert.ok(!anthNames.has(optIn), `default manifest: ${optIn} absent when disabled (#1192)`); + for (const optIn of ["absorb", "acp_retrieve"]) assert.ok(!anthNames.has(optIn), `default manifest: ${optIn} absent when disabled (#1192)`); + assert.ok(anthNames.has("acp_rule"), "default manifest: acp_rule advertised — on by default since #1399"); + const offM = captureManifest({ ...defaultConfig(100_000), rules: { enabled: false } }); + assert.ok(!new Set(offM.tools.anthropic.map((t) => t.name)).has("acp_rule"), "disabled manifest: acp_rule absent (#1192)"); assertCompressFormsKept(m.tools.anthropic.find((t) => t.name === "compress") as ToolShape, "manifest-default"); }); @@ -319,11 +322,13 @@ const LANES: Lane[] = [ }, ]; +// #1399: acp_rule is part of the default injected surface on every wire, so +// it joins the base expectation here (opt-in lanes below no longer add it). const BASE_EXPECTED: Record = { - anthropic: BILI_ACP_TOOLS_ANTHROPIC.map((t) => t.name), - "openai-chat": BILI_ACP_TOOLS_OPENAI.map((t) => t.function.name), - responses: BILI_ACP_TOOLS_RESPONSES.map((t) => t.name), - google: BILI_ACP_TOOLS_GOOGLE.map((t) => t.name), + anthropic: [...BILI_ACP_TOOLS_ANTHROPIC.map((t) => t.name), "acp_rule"], + "openai-chat": [...BILI_ACP_TOOLS_OPENAI.map((t) => t.function.name), "acp_rule"], + responses: [...BILI_ACP_TOOLS_RESPONSES.map((t) => t.name), "acp_rule"], + google: [...BILI_ACP_TOOLS_GOOGLE.map((t) => t.name), "acp_rule"], }; function extractForwardedNames(wire: Wire, body: unknown): string[] { @@ -424,8 +429,8 @@ test("wire-contract D: opt-in lane (absorb+rules+ccr) forwards the extended surf await res.text(); assert.equal(fake.violations.length, 0, `opt-in fake violations:\n${fake.violations.join("\n")}`); const fwdNames = extractForwardedNames(lane.wire, fake.requests[0].body); - const expected = [...BASE_EXPECTED[lane.wire], ...lane.clientToolNames, "absorb", "acp_rule", "acp_retrieve"].sort(); - assert.deepEqual(fwdNames.sort(), expected, "opt-in lane forwards base + absorb/acp_rule/acp_retrieve + client tools"); + const expected = [...BASE_EXPECTED[lane.wire], ...lane.clientToolNames, "absorb", "acp_retrieve"].sort(); + assert.deepEqual(fwdNames.sort(), expected, "opt-in lane forwards base (incl. default-on acp_rule, #1399) + absorb/acp_retrieve + client tools"); const fwdTools = (fake.requests[0].body as ToolShape).tools; const compress = (Array.isArray(fwdTools) ? fwdTools : []).find((t) => (t as ToolShape).name === "compress") as ToolShape; assert.ok(compress, "opt-in forwarded body carries compress"); From ecc60ef2eac547d7639a2f7bd75f3c2fdf904353 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 20:47:35 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix:=20acp=5Frule=20back=20to=20opt-in=20?= =?UTF-8?q?=E2=80=94=20full-rights-when-enabled,=20not=20default=20injecti?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner decision on #1402: the #1399 'model has full rights over session rules' ruling covers the CAPABILITY (record/list/delete/clear, unprompted use allowed) within sessions where the feature is enabled — it does not inject the tool for everyone. Revert rulesEnabled/effectiveRulesEnabled to explicit-enable (=== true), flip every default-on assertion back (rules/manifest/mcp-shell/wire-contract/codex-official), regenerate the default golden manifest without acp_rule, and update README/CONFIGURATION (en+zh) + PLUGIN.md wording. --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- PLUGIN.md | 2 +- README.md | 2 +- README.zh-CN.md | 2 +- src/config.ts | 11 +-- src/rules-feature.ts | 15 ++-- tests/codex-official.test.ts | 8 +- .../wire-contract/manifest-default.json | 82 +------------------ tests/issue1192-disabled-tools.test.ts | 6 +- tests/launcher-plugin-mode.test.ts | 4 +- tests/plugin-protocol.test.ts | 21 +++-- tests/rules-wire.test.ts | 4 +- tests/rules.test.ts | 33 ++++---- tests/wire-contract.test.ts | 14 ++-- 15 files changed, 67 insertions(+), 141 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 1563b864bd..6691672833 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -406,7 +406,7 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - **Type:** `boolean` - **Default:** `true` (since #1399; previously `false`) - **Status:** ACTIVE -- **Description:** **Persistent model reminders** (issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433), via the `acp-kernel` rules API), **on by default since #1399** — set `compress.rules: false` to restore the previous opt-in behavior. When enabled, an `acp_rule` tool is injected alongside the ACP tools: calling it with a short `rule` argument records a principle-level reminder that is **hard-protected** from compression (the call + result stay in context across every fold), and omitting the argument lists the recorded rules. Passing `delete` with a rule id (e.g. `"rule3"`) removes that one rule (`Removed ruleN: `); passing `clear: true` removes every rule. The two are mutually exclusive with each other and with `rule` — one operation per call — so a stale or accidentally-recorded rule can be deleted instead of hedged with a counter-rule. Guidance on *when* to record (user-emphasized lessons, behaviors the user asks to remember, major pitfalls hit) lives entirely in the tool description — nothing is added to the system prompt. Kernel limits apply (50 rules × 300 chars each); duplicate text is rejected pointing at the existing id. Injection follows the wire's native-tool surface exactly like `absorb`: proxy mode injects the tool 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; execution gated per session). Recorded rules persist across restarts in the session state; removals persist the same way. Requires `acp-kernel` >= 0.0.70 (>= 0.0.84 for delete/clear). Humans get the full operation set without going through the model: pi/omp expose a native `/acp-rule` command with the same semantics as the tool — bare `/acp-rule` lists every recorded rule, `/acp-rule ` records one directly, `/acp-rule remove ` deletes one, and bare `/acp-rule clear` wipes all recorded rules (`clear ` records instead of wiping) (#1251; remove/clear added in #1399). +- **Description:** **Persistent model reminders** (issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433), via the `acp-kernel` rules API), **off by default** — set `compress.rules: true` to enable it (the #1399 decision: once enabled the model has full rights over session rules and may call it unprompted, including delete/clear). When enabled, an `acp_rule` tool is injected alongside the ACP tools: calling it with a short `rule` argument records a principle-level reminder that is **hard-protected** from compression (the call + result stay in context across every fold), and omitting the argument lists the recorded rules. Passing `delete` with a rule id (e.g. `"rule3"`) removes that one rule (`Removed ruleN: `); passing `clear: true` removes every rule. The two are mutually exclusive with each other and with `rule` — one operation per call — so a stale or accidentally-recorded rule can be deleted instead of hedged with a counter-rule. Guidance on *when* to record (user-emphasized lessons, behaviors the user asks to remember, major pitfalls hit) lives entirely in the tool description — nothing is added to the system prompt. Kernel limits apply (50 rules × 300 chars each); duplicate text is rejected pointing at the existing id. Injection follows the wire's native-tool surface exactly like `absorb`: proxy mode injects the tool 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; execution gated per session). Recorded rules persist across restarts in the session state; removals persist the same way. Requires `acp-kernel` >= 0.0.70 (>= 0.0.84 for delete/clear). Humans get the full operation set without going through the model: pi/omp expose a native `/acp-rule` command with the same semantics as the tool — bare `/acp-rule` lists every recorded rule, `/acp-rule ` records one directly, `/acp-rule remove ` deletes one, and bare `/acp-rule clear` wipes all recorded rules (`clear ` records instead of wiping) (#1251; remove/clear added in #1399). #### `reasoning` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index b30a6d31fd..027bc06bd7 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -406,7 +406,7 @@ - **类型:** `boolean` - **默认值:** `true`(#1399 起;此前为 `false`) - **状态:** ACTIVE -- **说明:** **持久化模型提醒**(issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433),经由 `acp-kernel` rules API),**#1399 起默认开启**——设 `compress.rules: false` 可恢复旧的可选开启行为。启用后,一个 `acp_rule` 工具随 ACP 工具一同注入:传入简短的 `rule` 参数调用可记录一条**原则级提醒**,该提醒受**硬性保护**免于压缩(调用及结果在每次折叠中都保留在上下文中);省略参数则列出已记录的规则。传入 `delete`(规则 id,如 `"rule3"`)删除该条规则(返回 `Removed ruleN: `);传入 `clear: true` 清空全部规则。两者互斥,且均与 `rule` 互斥——一次调用只能执行一种操作——因此过时或误记的规则可以直接删除,而无需再写一条"作废声明"对冲。关于*何时*记录(用户强调的教训、用户要求记住的行为、遇到的重大陷阱)的指导完全写在工具描述里——不向系统提示词添加任何内容。受内核限制约束(50 条规则 × 每条 300 字符);重复文本会被拒绝并指向已有的 id。注入跟随线上原生工具面,与 `absorb` 完全一致:代理模式在 anthropic/openai/responses 原生工具线上注入该工具,插件模式在插件清单中声明(执行按会话门控)。已记录的规则在会话状态中持久化,跨重启保留;删除同样持久化。要求 `acp-kernel` >= 0.0.70(delete/clear 需要 >= 0.0.84)。人也可以不经过模型执行全部操作:pi/omp 提供原生 `/acp-rule` 命令,语义与工具一致 —— 裸 `/acp-rule` 列出全部已记录规则,`/acp-rule <文本>` 直接记录一条,`/acp-rule remove ` 删除一条,裸 `/acp-rule clear` 清空全部(`clear <文本>` 是记录而非清空)(#1251;remove/clear 由 #1399 补齐)。 +- **说明:** **持久化模型提醒**(issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433),经由 `acp-kernel` rules API),**默认关闭**——设 `compress.rules: true` 显式开启(#1399 定案:开启后模型对会话规则有全权,可未经提示自主调用,含 delete/clear)。启用后,一个 `acp_rule` 工具随 ACP 工具一同注入:传入简短的 `rule` 参数调用可记录一条**原则级提醒**,该提醒受**硬性保护**免于压缩(调用及结果在每次折叠中都保留在上下文中);省略参数则列出已记录的规则。传入 `delete`(规则 id,如 `"rule3"`)删除该条规则(返回 `Removed ruleN: `);传入 `clear: true` 清空全部规则。两者互斥,且均与 `rule` 互斥——一次调用只能执行一种操作——因此过时或误记的规则可以直接删除,而无需再写一条"作废声明"对冲。关于*何时*记录(用户强调的教训、用户要求记住的行为、遇到的重大陷阱)的指导完全写在工具描述里——不向系统提示词添加任何内容。受内核限制约束(50 条规则 × 每条 300 字符);重复文本会被拒绝并指向已有的 id。注入跟随线上原生工具面,与 `absorb` 完全一致:代理模式在 anthropic/openai/responses 原生工具线上注入该工具,插件模式在插件清单中声明(执行按会话门控)。已记录的规则在会话状态中持久化,跨重启保留;删除同样持久化。要求 `acp-kernel` >= 0.0.70(delete/clear 需要 >= 0.0.84)。人也可以不经过模型执行全部操作:pi/omp 提供原生 `/acp-rule` 命令,语义与工具一致 —— 裸 `/acp-rule` 列出全部已记录规则,`/acp-rule <文本>` 直接记录一条,`/acp-rule remove ` 删除一条,裸 `/acp-rule clear` 清空全部(`clear <文本>` 是记录而非清空)(#1251;remove/clear 由 #1399 补齐)。 #### `reasoning` diff --git a/PLUGIN.md b/PLUGIN.md index 0484279642..e1f782e959 100644 --- a/PLUGIN.md +++ b/PLUGIN.md @@ -50,7 +50,7 @@ Fetch once at plugin startup. } ``` -Register the tools natively with your agent, in whichever wire format your agent speaks — register exactly what `toolNames` lists. `absorb` appears only when the proxy's config enables it; `acp_rule` is advertised by default since #1399 (an explicit `compress.rules: false` hides it again). Calling a tool that is known but disabled answers `200` with an explanatory `result` instead of an error (#1192). If `protocolVersion` is higher than you know, still register the tools — extra fields in schemas are ignored by agents. +Register the tools natively with your agent, in whichever wire format your agent speaks — register exactly what `toolNames` lists. `absorb` appears only when the proxy's config enables it; `acp_rule` is advertised only when the proxy's config enables it (`compress.rules: true`, opt-in). Calling a tool that is known but disabled answers `200` with an explanatory `result` instead of an error (#1192). If `protocolVersion` is higher than you know, still register the tools — extra fields in schemas are ignored by agents. ### 2. Request headers diff --git a/README.md b/README.md index efa2491d0b..a986e69c36 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ The proxy injects four context-management tools (`compress`, `decompress`, `sear An opt-in fifth tool, `absorb` (`compress.absorb.enabled: true` — see [CONFIGURATION.md](CONFIGURATION.md)), compresses **individual tool results the moment they arrive**: large results (builds, logs, greps) get a forced absorb instruction, the model distills each into a compact summary, and the original pair is hidden from the wire from the next turn on — keeping mid-session pressure lower between fold rounds (#605). -The sixth tool, `acp_rule` (on by default since #1399; set `compress.rules: false` to restore the previous opt-in behavior — see [CONFIGURATION.md](CONFIGURATION.md)), records **persistent principle-level reminders**: a short rule recorded by the model (user-emphasized lessons, behaviors to remember, major pitfalls hit) is hard-protected from compression — the call and its result stay in context across every fold — and omitting the argument lists the recorded rules; passing `delete` with a rule id (e.g. `"rule3"`) removes one rule and `clear: true` removes all of them ([ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433)). +The sixth tool, `acp_rule` (opt-in via `compress.rules: true` — see [CONFIGURATION.md](CONFIGURATION.md); once enabled the model has full rights over session rules and may call it unprompted, #1399), records **persistent principle-level reminders**: a short rule recorded by the model (user-emphasized lessons, behaviors to remember, major pitfalls hit) is hard-protected from compression — the call and its result stay in context across every fold — and omitting the argument lists the recorded rules; passing `delete` with a rule id (e.g. `"rule3"`) removes one rule and `clear: true` removes all of them ([ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433)). The seventh tool, `acp_retrieve` (opt-in on every lane — set `compress.ccr.enabled: true` at any level, after local verification; plugin lanes require the explicit global `true` so the manifest advertises the tool, #1271/#1273 — see [CONFIGURATION.md](CONFIGURATION.md)), backs the **content-addressed message store** (built-in CCR, #1097/#1179): oversized tool results are **ID-referenced at arrival instead of force-distilled** — the wire keeps a byte-stable placeholder and the original goes into a per-session content-store envelope (hash-deduped), retrievable on demand via one cheap tool call. V2 makes folds lossless too: covered originals are stored when a fold lands, `decompress` restores ranges (`startId`/`endId` refs) instead of whole blocks, and `search_context` hits carry the covered `mNNNNN` refs so you can fetch exactly what you need. Lossless by default: a retrieve not made costs nothing but the call; a detail distilled away by absorb is gone for good. Scope: proxy mode, plus plugin lanes on the anthropic + openai wires when explicitly enabled (`acp_retrieve` is advertised in the plugin manifest then, #1271); responses marker/text routes and google in plugin mode stay disarmed because no request-only round-trip channel exists there (silent loss, #1097). diff --git a/README.zh-CN.md b/README.zh-CN.md index 586367121b..0bc6ecf9c9 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -90,7 +90,7 @@ QQ群: 可选的第五个工具 `absorb`(`compress.absorb.enabled: true` —— 见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md))对**各个工具结果即时压缩**:大结果(构建、日志、grep)被附带强制吸收指令,模型将各自蒸馏为紧凑摘要,原配对从下一轮起从线上隐藏 —— 使折叠轮之间的中间会话压力更低(#605)。 -第六个工具 `acp_rule`(#1399 起默认开启;设 `compress.rules: false` 可恢复旧的可选开启行为 —— 见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md))记录**持久化的原则级提醒**:模型记录的简短规则(用户强调的教训、要求记住的行为、撞到的大坑)受硬性保护不被压缩——调用及结果在每次折叠中都保留在上下文中——省略参数则列出已记录规则;传入 `delete`(规则 id,如 `"rule3"`)删除单条规则,传入 `clear: true` 清空全部规则([ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433))。 +第六个工具 `acp_rule`(默认关闭;设 `compress.rules: true` 显式开启 —— 见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md)。开启后模型对会话规则有全权、可未经提示自主调用,#1399)记录**持久化的原则级提醒**:模型记录的简短规则(用户强调的教训、要求记住的行为、撞到的大坑)受硬性保护不被压缩——调用及结果在每次折叠中都保留在上下文中——省略参数则列出已记录规则;传入 `delete`(规则 id,如 `"rule3"`)删除单条规则,传入 `clear: true` 清空全部规则([ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433))。 第七个工具 `acp_retrieve`(全车道默认关闭、显式开启 —— 任意层级设 `compress.ccr.enabled: true` 方可启用,建议先本地验证;插件车道需全局显式 `true` 才会在 manifest 广播工具,#1271/#1273;见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md))支撑**内容寻址消息存储**(内置 CCR,#1097/#1179):超大工具结果**在到达时改为 ID 引用,而非强制蒸馏**——线上保留字节稳定的占位符,原文进入按会话的内容存储信封(按内容哈希去重),模型通过一次廉价工具调用按需取回。v2 让折叠同样无损:折叠落定时被覆盖的原文会存入存储,`decompress` 可按区间恢复(`startId`/`endId` ref)而无需整块展开,`search_context` 命中条目携带覆盖的 `mNNNNN` ref,让你精确取回所需内容。默认无损:未执行的 retrieve 只花一次调用;而被 absorb 蒸馏掉的细节则永久丢失。仅代理模式、仅原生工具线(marker/文本协议没有执行 retrieve 的通道,存储在这些场景下自动解除武装,而不是静默丢失内容)。 diff --git a/src/config.ts b/src/config.ts index c56676dbae..df2be4f4c1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -315,11 +315,12 @@ export type CompressSettings = { * plugin manifest): passing a short `rule` records a principle-level * reminder that is hard-protected from compression and stays in context * for the life of the session; omitting the argument lists recorded - * rules for human review. The feature deliberately adds NO system-prompt - * content (all guidance rides in the tool description). Maps to kernel - * `Config.rules = { enabled }`. On by default since #1399 — an explicit - * `false` at any level disables it. Deepest-wins like every other scalar - * field. */ + * rules for human review. `delete` removes one rule by id, `clear: true` + * removes all (#1399: the model has full rights over session rules and + * may call any of these unprompted). The feature deliberately adds NO + * system-prompt content (all guidance rides in the tool description). + * Maps to kernel `Config.rules = { enabled }`. Off unless explicitly + * enabled at some level. Deepest-wins like every other scalar field. */ rules?: boolean; /** Opt-in removal of historical image payloads, executed by the kernel's diff --git a/src/rules-feature.ts b/src/rules-feature.ts index 1c7a810247..6cee31cae6 100644 --- a/src/rules-feature.ts +++ b/src/rules-feature.ts @@ -12,12 +12,13 @@ import type { Session } from "./session.js"; const EFFECTIVE_RULES_KEY = "effectiveRules"; -// #1399: default-ON since the owner decision "the model has full rights over -// session rules" — an absent block means enabled, only an explicit -// `enabled: false` (user `compress.rules: false`) disables the feature. The -// pre-#1399 semantics were opt-in (`=== true`). +// #1399: opt-in — the owner decision "the model has full rights over session +// rules" covers the CAPABILITY (record/list/delete/clear, and the model may +// call it unprompted) within sessions where the feature is enabled; it does +// not inject the tool for everyone. Off unless `compress.rules: true` +// (deepest-wins). An explicit `enabled: false` stays a loud off. export function rulesEnabled(config: Config): boolean { - return config.rules?.enabled ?? true; + return config.rules?.enabled === true; } // Two config sources exist (same split as absorb): wire paths carry the @@ -39,9 +40,9 @@ export function storeEffectiveRules(session: Session, config: Config): void { // Session-level enablement for paths without a per-request resolved Config // (plugin tool API): last resolved block wins, base config otherwise — same -// #1399 default-on semantics as rulesEnabled. +// opt-in semantics as rulesEnabled. export function effectiveRulesEnabled(session: Session | undefined, fallback: Config): boolean { - return effectiveRulesConfig(session, fallback)?.enabled ?? true; + return effectiveRulesConfig(session, fallback)?.enabled === true; } export type RuleExecCtx = { diff --git a/tests/codex-official.test.ts b/tests/codex-official.test.ts index 34bc0bfc3f..adcd615483 100644 --- a/tests/codex-official.test.ts +++ b/tests/codex-official.test.ts @@ -51,7 +51,7 @@ test("Codex official transport preserves OAuth headers, decodes bodies, and reba }, modelContextLimit: 400_000, kernelConfig: defaultConfig(400_000), - compress: { injectTool: true, injectNudge: true, ccr: { enabled: true } }, + compress: { injectTool: true, injectNudge: true, ccr: { enabled: true }, rules: true }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false, @@ -117,9 +117,9 @@ test("Codex official transport preserves OAuth headers, decodes bodies, and reba assert.equal(forwarded.prompt_cache_key, undefined); assert.equal(forwarded.instructions, undefined); assert.deepEqual(forwarded.additional_tools, requestBody.additional_tools); - // CCR explicitly enabled in this test's compress config (#1207 - // opt-in), so acp_retrieve joins the injected tool set; acp_rule is - // in the default surface since #1399. + // CCR and rules explicitly enabled in this test's compress config + // (#1207 / #1399 are both opt-in), so acp_retrieve and acp_rule join + // the injected tool set. assert.deepEqual( forwarded.tools.map((t: { name: string }) => t.name), ["shell", "compress", "decompress", "search_context", "acp_status", "acp_cache", "acp_rule", "acp_retrieve"], diff --git a/tests/golden/wire-contract/manifest-default.json b/tests/golden/wire-contract/manifest-default.json index 278b859b7f..7b8ab96833 100644 --- a/tests/golden/wire-contract/manifest-default.json +++ b/tests/golden/wire-contract/manifest-default.json @@ -8,8 +8,7 @@ "decompress", "search_context", "acp_status", - "acp_cache", - "acp_rule" + "acp_cache" ], "tools": { "anthropic": [ @@ -202,31 +201,6 @@ } } } - }, - { - "name": "acp_rule", - "description": "Record a short, principle-level reminder so it survives context compression — the call and its result are protected and stay in context. Record when: the user calls out or repeatedly emphasizes a lesson; the user asks you to remember or follow a behavior; you personally hit a major pitfall worth remembering long-term. Keep each rule to one short line. Omit the rule argument to list recorded rules. To remove a recorded rule pass delete with its id (e.g. \"rule3\"); to remove every recorded rule pass clear: true. delete and clear are mutually exclusive with each other and with rule — use one operation per call.", - "input_schema": { - "type": "object", - "properties": { - "rule": { - "type": "string", - "description": "Short principle-level reminder to record. Omit to list recorded rules." - }, - "delete": { - "type": "string", - "description": "Id of a recorded rule to remove (e.g. \"rule3\"). Mutually exclusive with rule and clear." - }, - "clear": { - "type": "boolean", - "description": "Remove every recorded rule at once. Mutually exclusive with rule and delete." - }, - "conversation_id": { - "type": "string", - "description": "Your bili conversation id (the value from the 'your bili conversation id' line in the proxy notes). Pass it on every call when your host shares one MCP process across several concurrent conversations; omit it when the host bound the session itself." - } - } - } } ], "openai": [ @@ -434,34 +408,6 @@ } } } - }, - { - "type": "function", - "function": { - "name": "acp_rule", - "description": "Record a short, principle-level reminder so it survives context compression — the call and its result are protected and stay in context. Record when: the user calls out or repeatedly emphasizes a lesson; the user asks you to remember or follow a behavior; you personally hit a major pitfall worth remembering long-term. Keep each rule to one short line. Omit the rule argument to list recorded rules. To remove a recorded rule pass delete with its id (e.g. \"rule3\"); to remove every recorded rule pass clear: true. delete and clear are mutually exclusive with each other and with rule — use one operation per call.", - "parameters": { - "type": "object", - "properties": { - "rule": { - "type": "string", - "description": "Short principle-level reminder to record. Omit to list recorded rules." - }, - "delete": { - "type": "string", - "description": "Id of a recorded rule to remove (e.g. \"rule3\"). Mutually exclusive with rule and clear." - }, - "clear": { - "type": "boolean", - "description": "Remove every recorded rule at once. Mutually exclusive with rule and delete." - }, - "conversation_id": { - "type": "string", - "description": "Your bili conversation id (the value from the 'your bili conversation id' line in the proxy notes). Pass it on every call when your host shares one MCP process across several concurrent conversations; omit it when the host bound the session itself." - } - } - } - } } ], "responses": [ @@ -659,32 +605,6 @@ } } } - }, - { - "type": "function", - "name": "acp_rule", - "description": "Record a short, principle-level reminder so it survives context compression — the call and its result are protected and stay in context. Record when: the user calls out or repeatedly emphasizes a lesson; the user asks you to remember or follow a behavior; you personally hit a major pitfall worth remembering long-term. Keep each rule to one short line. Omit the rule argument to list recorded rules. To remove a recorded rule pass delete with its id (e.g. \"rule3\"); to remove every recorded rule pass clear: true. delete and clear are mutually exclusive with each other and with rule — use one operation per call.", - "parameters": { - "type": "object", - "properties": { - "rule": { - "type": "string", - "description": "Short principle-level reminder to record. Omit to list recorded rules." - }, - "delete": { - "type": "string", - "description": "Id of a recorded rule to remove (e.g. \"rule3\"). Mutually exclusive with rule and clear." - }, - "clear": { - "type": "boolean", - "description": "Remove every recorded rule at once. Mutually exclusive with rule and delete." - }, - "conversation_id": { - "type": "string", - "description": "Your bili conversation id (the value from the 'your bili conversation id' line in the proxy notes). Pass it on every call when your host shares one MCP process across several concurrent conversations; omit it when the host bound the session itself." - } - } - } } ] }, diff --git a/tests/issue1192-disabled-tools.test.ts b/tests/issue1192-disabled-tools.test.ts index d464c911c1..d1c2057c01 100644 --- a/tests/issue1192-disabled-tools.test.ts +++ b/tests/issue1192-disabled-tools.test.ts @@ -49,11 +49,11 @@ describe("#1192: known-but-disabled opt-in tools get an explanation, not a hard assert.match(String(r.json.result), /nothing was recorded/); }); - it("acp_rule with rules unset → executes by default (#1399)", async () => { - const r = await call("acp_rule", { rule: "default-on rule" }); + it("acp_rule with rules unset → ok:true explanation (opt-in, same as explicit false)", async () => { + const r = await call("acp_rule", { rule: "should not record" }); assert.equal(r.status, 200); assert.equal(r.json.ok, true); - assert.match(String(r.json.result), /^Recorded rule\d+: default-on rule$/); + assert.match(String(r.json.result), /acp_rule is not enabled on this bili proxy \(compress\.rules\.enabled is not true\)/); }); it("absorb disabled → ok:true explanation", async () => { diff --git a/tests/launcher-plugin-mode.test.ts b/tests/launcher-plugin-mode.test.ts index 02bdbf2ffa..141e6acf7f 100644 --- a/tests/launcher-plugin-mode.test.ts +++ b/tests/launcher-plugin-mode.test.ts @@ -340,7 +340,7 @@ test("mcp stdio shell: manifest → tools/list → tools/call forwards to the pl const init = byId(1) as { result?: { serverInfo?: { name?: string } } }; assert.equal(init.result?.serverInfo?.name, "bili"); const tools = byId(2) as { result?: { tools?: { name: string }[] } }; - assert.deepEqual(tools.result?.tools?.map((t) => t.name).sort(), ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); + assert.deepEqual(tools.result?.tools?.map((t) => t.name).sort(), ["acp_cache", "acp_status", "compress", "decompress", "search_context"]); const call = byId(3) as { result?: { content?: { text?: string }[]; isError?: boolean } }; assert.equal(call.result?.isError, false); assert.match(call.result?.content?.[0]?.text ?? "", /CONTEXT BREAKDOWN/, "acp_status result forwarded verbatim"); @@ -411,7 +411,7 @@ test("mcp stdio shell (codex style): BILI_CONVERSATION_ID self-register → head const byId = (n: number): Record => JSON.parse(lines.find((l) => (JSON.parse(l) as { id?: number }).id === n) ?? "{}"); const tools = byId(2) as { result?: { tools?: { name: string }[] } }; - assert.deepEqual(tools.result?.tools?.map((t) => t.name).sort(), ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"], "tools listed"); + assert.deepEqual(tools.result?.tools?.map((t) => t.name).sort(), ["acp_cache", "acp_status", "compress", "decompress", "search_context"], "tools listed"); const call = byId(3) as { result?: { content?: { text?: string }[]; isError?: boolean } }; assert.equal(call.result?.isError, false, `tools/call succeeded (self-registered conversation bound)${call.result?.isError ? ": " + (call.result?.content?.[0]?.text ?? "") : ""}`); assert.match(call.result?.content?.[0]?.text ?? "", /CONTEXT BREAKDOWN/); diff --git a/tests/plugin-protocol.test.ts b/tests/plugin-protocol.test.ts index 714dcae90f..15abad9f2a 100644 --- a/tests/plugin-protocol.test.ts +++ b/tests/plugin-protocol.test.ts @@ -229,15 +229,14 @@ test("plugin manifest serves the exact wire tool schemas, headers and version", assert.equal(manifest.ok, true); assert.equal(manifest.protocolVersion, 1); assert.ok(/^\d+\.\d+\.\d+/.test(manifest.version), `version looks wrong: ${manifest.version}`); - // #1192/#1399: absorb is opt-in and only advertised when enabled — hosts register - // manifest tools verbatim, so a disabled tool must not be listed (the default - // config disables it). acp_rule is on by default since #1399. acp_cache stays in - // the base toolset. - assert.deepEqual([...manifest.toolNames].sort(), ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); + // #1192: every extra tool (absorb, acp_rule) is opt-in and only advertised + // when enabled — hosts register manifest tools verbatim, so a disabled + // tool must not be listed. acp_cache stays in the base toolset. + assert.deepEqual([...manifest.toolNames].sort(), ["acp_cache", "acp_status", "compress", "decompress", "search_context"]); const names = manifest.tools.anthropic!.map((t) => String(t.name)).sort(); - assert.deepEqual(names, ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); - assert.equal(manifest.tools.openai!.length, 6); - assert.equal(manifest.tools.responses!.length, 6); + assert.deepEqual(names, ["acp_cache", "acp_status", "compress", "decompress", "search_context"]); + assert.equal(manifest.tools.openai!.length, 5); + assert.equal(manifest.tools.responses!.length, 5); // #841: search_context's conversation_id doubles as a cross-session // read-only search target — its param description must carry the // historical-search wording in every wire shape. @@ -295,14 +294,14 @@ test("plugin manifest: absorb advertised when enabled in the global compress blo const resp = await fetch(`http://127.0.0.1:${h.proxyPort}/__bili/plugin/manifest`); assert.equal(resp.status, 200); const manifest = (await resp.json()) as { toolNames: string[]; tools: Record>> }; - assert.deepEqual([...manifest.toolNames].sort(), ["absorb", "acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); + assert.deepEqual([...manifest.toolNames].sort(), ["absorb", "acp_cache", "acp_status", "compress", "decompress", "search_context"]); for (const shape of ["anthropic", "openai", "responses"] as const) { const listed = manifest.tools[shape]!.map((t) => { const fn = t.function as { name?: unknown } | undefined; return typeof t.name === "string" ? t.name : (typeof fn?.name === "string" ? fn.name : ""); }); assert.ok(listed.includes("absorb"), `${shape} has absorb`); - assert.equal(listed.length, 7); + assert.equal(listed.length, 6); } } finally { await h.close(); @@ -317,7 +316,7 @@ test("plugin manifest: absorb omitted when the global compress block disables it const resp = await fetch(`http://127.0.0.1:${h.proxyPort}/__bili/plugin/manifest`); assert.equal(resp.status, 200); const manifest = (await resp.json()) as { toolNames: string[] }; - assert.deepEqual([...manifest.toolNames].sort(), ["acp_cache", "acp_rule", "acp_status", "compress", "decompress", "search_context"]); + assert.deepEqual([...manifest.toolNames].sort(), ["acp_cache", "acp_status", "compress", "decompress", "search_context"]); } finally { await h.close(); } diff --git a/tests/rules-wire.test.ts b/tests/rules-wire.test.ts index 0b2739dda4..63a1ae40a7 100644 --- a/tests/rules-wire.test.ts +++ b/tests/rules-wire.test.ts @@ -120,7 +120,7 @@ test("#749 anthropic wire: acp_rule injected alongside ACP tools when rules enab } }); -test("#1399 anthropic wire: acp_rule injected by default (rules unset)", async () => { +test("#1399 anthropic wire: acp_rule NOT injected when unset (opt-in)", async () => { const up = await startUpstream(); const proxy = await startProxy(up.port); await once(proxy, "listening"); @@ -132,7 +132,7 @@ test("#1399 anthropic wire: acp_rule injected by default (rules unset)", async ( const tools = up.bodies()[0].tools as Array<{ name?: unknown }>; const names = tools.map((t) => t.name); assert.ok(names.includes("compress"), "ACP tools still injected"); - assert.ok(names.includes("acp_rule"), `acp_rule present by default since #1399 (got: ${names.join(", ")})`); + assert.ok(!names.includes("acp_rule"), `acp_rule absent while unset — opt-in (got: ${names.join(", ")})`); } finally { proxy.close(); await once(proxy, "close"); diff --git a/tests/rules.test.ts b/tests/rules.test.ts index f6e19a4cee..44e6140cfe 100644 --- a/tests/rules.test.ts +++ b/tests/rules.test.ts @@ -36,16 +36,16 @@ function makeRuleCtx(config?: Partial): { session: Session; ctx: RuleExe return { session, ctx: { config: cfg, session, log: () => {} } }; } -test("rulesEnabled defaults on (#1399); explicit false disables", () => { - assert.equal(rulesEnabled(defaultConfig(200000)), true); +test("rulesEnabled is opt-in; explicit true enables, explicit false is a loud off", () => { + assert.equal(rulesEnabled(defaultConfig(200000)), false); assert.equal(rulesEnabled({ ...defaultConfig(200000), rules: { enabled: false } }), false); assert.equal(rulesEnabled({ ...defaultConfig(200000), rules: { enabled: true } }), true); }); -test("isProxyToolFor: acp_rule on by default, off when explicitly disabled (#1399)", () => { +test("isProxyToolFor: acp_rule opt-in — on only when enabled (#1399)", () => { const base = defaultConfig(200000); assert.equal(isProxyToolFor("compress", undefined, base), true); - assert.equal(isProxyToolFor(RULE_TOOL_NAME, undefined, base), true); + assert.equal(isProxyToolFor(RULE_TOOL_NAME, undefined, base), false, "unset → not a proxy tool"); const off: Config = { ...base, rules: { enabled: false } }; assert.equal(isProxyToolFor(RULE_TOOL_NAME, undefined, off), false); @@ -53,8 +53,8 @@ test("isProxyToolFor: acp_rule on by default, off when explicitly disabled (#139 const session = makeSession(); storeEffectiveRules(session, off); // Plugin tool API reads the per-session stored block even when the - // fallback (base kernel config) has the feature on by default. - assert.equal(isProxyToolFor(RULE_TOOL_NAME, session, base), false); + // fallback (base kernel config) has the feature enabled. + assert.equal(isProxyToolFor(RULE_TOOL_NAME, session, { ...base, rules: { enabled: true } }), false); storeEffectiveRules(session, { ...base, rules: { enabled: true } }); assert.equal(isProxyToolFor(RULE_TOOL_NAME, session, off), true); }); @@ -71,13 +71,14 @@ test("effectiveRulesConfig: session metadata wins over fallback; absent stored b assert.equal(effectiveRulesConfig(undefined, defaultConfig(200000)), undefined); }); -test("effectiveRulesEnabled: unset → on (#1399); explicit false wins from either layer", () => { +test("effectiveRulesEnabled: opt-in — unset → off; explicit true enables from either layer", () => { const base = defaultConfig(200000); - assert.equal(effectiveRulesEnabled(undefined, base), true); + assert.equal(effectiveRulesEnabled(undefined, base), false, "unset → off (opt-in)"); + assert.equal(effectiveRulesEnabled(undefined, { ...base, rules: { enabled: true } }), true); assert.equal(effectiveRulesEnabled(undefined, { ...base, rules: { enabled: false } }), false); const session = makeSession(); storeEffectiveRules(session, base); - assert.equal(effectiveRulesEnabled(session, { ...base, rules: { enabled: false } }), false, "stored-unset block falls through to the disabled fallback"); + assert.equal(effectiveRulesEnabled(session, { ...base, rules: { enabled: true } }), true, "stored-unset block falls through to the enabled fallback"); storeEffectiveRules(session, { ...base, rules: { enabled: false } }); assert.equal(effectiveRulesEnabled(session, { ...base, rules: { enabled: true } }), false, "stored false beats fallback true"); storeEffectiveRules(session, { ...base, rules: { enabled: true } }); @@ -195,10 +196,9 @@ test("applyCompressSettings: maps settings rules onto kernel RuleFeatureConfig", assert.equal(absent.rules, undefined, "absent settings leave the base rules block untouched"); }); -// #1192/#1399: hosts register manifest tools verbatim, so an explicitly -// disabled acp_rule must not be advertised at all — but since #1399 the -// default (unset) config advertises it on all three wires. -test("handlePluginManifest: acp_rule advertised by default, hidden when explicitly disabled", () => { +// #1192: hosts register manifest tools verbatim, so acp_rule must never be +// advertised while not enabled — including the unset (default-off) config. +test("handlePluginManifest: acp_rule advertised only when enabled", () => { let body = ""; const res = { writeHead: () => {}, end: (b: string) => { body = b; } } as unknown as Parameters[0]; const data = (): { @@ -208,7 +208,12 @@ test("handlePluginManifest: acp_rule advertised by default, hidden when explicit handlePluginManifest(res, defaultConfig(200_000)); let d = data(); - assert.ok(d.toolNames.includes(RULE_TOOL_NAME), "on by default (#1399) → advertised"); + assert.ok(!d.toolNames.includes(RULE_TOOL_NAME), "unset (default-off) → not advertised"); + assert.ok(!d.tools.anthropic.some((t) => t.name === RULE_TOOL_NAME)); + + handlePluginManifest(res, { ...defaultConfig(200_000), rules: { enabled: true } }); + d = data(); + assert.ok(d.toolNames.includes(RULE_TOOL_NAME), "enabled → advertised"); assert.ok(d.tools.anthropic.some((t) => t.name === RULE_TOOL_NAME), "anthropic schema present"); assert.ok(d.tools.openai.some((t) => t.function?.name === RULE_TOOL_NAME)); assert.ok(d.tools.responses.some((t) => t.name === RULE_TOOL_NAME)); diff --git a/tests/wire-contract.test.ts b/tests/wire-contract.test.ts index 806d7bfff6..396c3810c6 100644 --- a/tests/wire-contract.test.ts +++ b/tests/wire-contract.test.ts @@ -246,7 +246,7 @@ test("wire-contract C: default manifest serves only legal base tools", () => { const anthNames = new Set(m.tools.anthropic.map((t) => t.name)); for (const n of BILI_ACP_TOOLS_ANTHROPIC.map((t) => t.name)) assert.ok(anthNames.has(n), `default manifest: base tool ${n} present`); for (const optIn of ["absorb", "acp_retrieve"]) assert.ok(!anthNames.has(optIn), `default manifest: ${optIn} absent when disabled (#1192)`); - assert.ok(anthNames.has("acp_rule"), "default manifest: acp_rule advertised — on by default since #1399"); + assert.ok(!anthNames.has("acp_rule"), "default manifest: acp_rule absent — opt-in like absorb (#1192 discipline)"); const offM = captureManifest({ ...defaultConfig(100_000), rules: { enabled: false } }); assert.ok(!new Set(offM.tools.anthropic.map((t) => t.name)).has("acp_rule"), "disabled manifest: acp_rule absent (#1192)"); assertCompressFormsKept(m.tools.anthropic.find((t) => t.name === "compress") as ToolShape, "manifest-default"); @@ -325,10 +325,10 @@ const LANES: Lane[] = [ // #1399: acp_rule is part of the default injected surface on every wire, so // it joins the base expectation here (opt-in lanes below no longer add it). const BASE_EXPECTED: Record = { - anthropic: [...BILI_ACP_TOOLS_ANTHROPIC.map((t) => t.name), "acp_rule"], - "openai-chat": [...BILI_ACP_TOOLS_OPENAI.map((t) => t.function.name), "acp_rule"], - responses: [...BILI_ACP_TOOLS_RESPONSES.map((t) => t.name), "acp_rule"], - google: [...BILI_ACP_TOOLS_GOOGLE.map((t) => t.name), "acp_rule"], + anthropic: BILI_ACP_TOOLS_ANTHROPIC.map((t) => t.name), + "openai-chat": BILI_ACP_TOOLS_OPENAI.map((t) => t.function.name), + responses: BILI_ACP_TOOLS_RESPONSES.map((t) => t.name), + google: BILI_ACP_TOOLS_GOOGLE.map((t) => t.name), }; function extractForwardedNames(wire: Wire, body: unknown): string[] { @@ -429,8 +429,8 @@ test("wire-contract D: opt-in lane (absorb+rules+ccr) forwards the extended surf await res.text(); assert.equal(fake.violations.length, 0, `opt-in fake violations:\n${fake.violations.join("\n")}`); const fwdNames = extractForwardedNames(lane.wire, fake.requests[0].body); - const expected = [...BASE_EXPECTED[lane.wire], ...lane.clientToolNames, "absorb", "acp_retrieve"].sort(); - assert.deepEqual(fwdNames.sort(), expected, "opt-in lane forwards base (incl. default-on acp_rule, #1399) + absorb/acp_retrieve + client tools"); + const expected = [...BASE_EXPECTED[lane.wire], ...lane.clientToolNames, "acp_rule", "absorb", "acp_retrieve"].sort(); + assert.deepEqual(fwdNames.sort(), expected, "opt-in lane forwards base + acp_rule (rules:true) + absorb/acp_retrieve + client tools"); const fwdTools = (fake.requests[0].body as ToolShape).tools; const compress = (Array.isArray(fwdTools) ? fwdTools : []).find((t) => (t as ToolShape).name === "compress") as ToolShape; assert.ok(compress, "opt-in forwarded body carries compress"); From e04a9d52a396026fa3d51d62c8974de295fa0f23 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 20:55:21 +0800 Subject: [PATCH 3/4] docs: restore rules Default lines missed by the opt-in pivot (#1399) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pivot commit rewrote the Description lines of the compress.rules entry but left the Default line as 'true (since #1399; previously false)' in CONFIGURATION.md / CONFIGURATION.zh-CN.md — self-contradictory with the 'off by default' description directly below. Restored to the pre-PR value 'false'. --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 6691672833..391ec1fddc 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -404,7 +404,7 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t #### `rules` - **Type:** `boolean` -- **Default:** `true` (since #1399; previously `false`) +- **Default:** `false` - **Status:** ACTIVE - **Description:** **Persistent model reminders** (issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433), via the `acp-kernel` rules API), **off by default** — set `compress.rules: true` to enable it (the #1399 decision: once enabled the model has full rights over session rules and may call it unprompted, including delete/clear). When enabled, an `acp_rule` tool is injected alongside the ACP tools: calling it with a short `rule` argument records a principle-level reminder that is **hard-protected** from compression (the call + result stay in context across every fold), and omitting the argument lists the recorded rules. Passing `delete` with a rule id (e.g. `"rule3"`) removes that one rule (`Removed ruleN: `); passing `clear: true` removes every rule. The two are mutually exclusive with each other and with `rule` — one operation per call — so a stale or accidentally-recorded rule can be deleted instead of hedged with a counter-rule. Guidance on *when* to record (user-emphasized lessons, behaviors the user asks to remember, major pitfalls hit) lives entirely in the tool description — nothing is added to the system prompt. Kernel limits apply (50 rules × 300 chars each); duplicate text is rejected pointing at the existing id. Injection follows the wire's native-tool surface exactly like `absorb`: proxy mode injects the tool 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; execution gated per session). Recorded rules persist across restarts in the session state; removals persist the same way. Requires `acp-kernel` >= 0.0.70 (>= 0.0.84 for delete/clear). Humans get the full operation set without going through the model: pi/omp expose a native `/acp-rule` command with the same semantics as the tool — bare `/acp-rule` lists every recorded rule, `/acp-rule ` records one directly, `/acp-rule remove ` deletes one, and bare `/acp-rule clear` wipes all recorded rules (`clear ` records instead of wiping) (#1251; remove/clear added in #1399). diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 027bc06bd7..26c4f67caa 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -404,7 +404,7 @@ #### `rules` - **类型:** `boolean` -- **默认值:** `true`(#1399 起;此前为 `false`) +- **默认值:** `false` - **状态:** ACTIVE - **说明:** **持久化模型提醒**(issue [ranxianglei/billion-context-pi#433](https://github.com/ranxianglei/billion-context-pi/issues/433),经由 `acp-kernel` rules API),**默认关闭**——设 `compress.rules: true` 显式开启(#1399 定案:开启后模型对会话规则有全权,可未经提示自主调用,含 delete/clear)。启用后,一个 `acp_rule` 工具随 ACP 工具一同注入:传入简短的 `rule` 参数调用可记录一条**原则级提醒**,该提醒受**硬性保护**免于压缩(调用及结果在每次折叠中都保留在上下文中);省略参数则列出已记录的规则。传入 `delete`(规则 id,如 `"rule3"`)删除该条规则(返回 `Removed ruleN: `);传入 `clear: true` 清空全部规则。两者互斥,且均与 `rule` 互斥——一次调用只能执行一种操作——因此过时或误记的规则可以直接删除,而无需再写一条"作废声明"对冲。关于*何时*记录(用户强调的教训、用户要求记住的行为、遇到的重大陷阱)的指导完全写在工具描述里——不向系统提示词添加任何内容。受内核限制约束(50 条规则 × 每条 300 字符);重复文本会被拒绝并指向已有的 id。注入跟随线上原生工具面,与 `absorb` 完全一致:代理模式在 anthropic/openai/responses 原生工具线上注入该工具,插件模式在插件清单中声明(执行按会话门控)。已记录的规则在会话状态中持久化,跨重启保留;删除同样持久化。要求 `acp-kernel` >= 0.0.70(delete/clear 需要 >= 0.0.84)。人也可以不经过模型执行全部操作:pi/omp 提供原生 `/acp-rule` 命令,语义与工具一致 —— 裸 `/acp-rule` 列出全部已记录规则,`/acp-rule <文本>` 直接记录一条,`/acp-rule remove ` 删除一条,裸 `/acp-rule clear` 清空全部(`clear <文本>` 是记录而非清空)(#1251;remove/clear 由 #1399 补齐)。 From b3d211f4679c2da66e2420a92d5cefaec5212531 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 20:55:21 +0800 Subject: [PATCH 4/4] test: restore preflight-compress exact-budget harnesses to master state (#1399 pivot) v1 pinned 'rules: false' with a comment claiming '#1399 made it default-on'; after the pivot acp_rule is opt-in again, so the pin is redundant (absent == false, verified via compress-settings.ts mapping) and the rationale comment describes a world that no longer exists. Restored master's original comment block + config object; file is now byte-identical to master. Targeted rules suites: 134/134 pass. --- tests/preflight-compress.test.ts | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/tests/preflight-compress.test.ts b/tests/preflight-compress.test.ts index deaffae43e..b368073f6e 100644 --- a/tests/preflight-compress.test.ts +++ b/tests/preflight-compress.test.ts @@ -106,12 +106,10 @@ test("e2e: model switch to a smaller window → preflight compresses before forw kernelConfig: defaultConfig(400_000), // CCR is opt-in on every lane (#1207 owner decision): off unless a // config level sets enabled=true, so the acp_retrieve tool schema does - // not load here. acp_rule is pinned off too since #1399 made it - // default-on — its schema shifts this exact-budget fold boundary. If - // the boundary shifts again, someone re-enabled a default — treat that - // as a regression tripwire. CCR-on / rules-on interplay with the - // cascade is covered by e2e-compress-cascade.test.ts / the rules suites. - compress: { injectTool: true, injectNudge: true, rules: false }, + // not load here. If this exact-budget boundary shifts again, someone + // re-enabled a default — treat that as a regression tripwire. CCR-on + // interplay with the cascade is covered by e2e-compress-cascade.test.ts. + compress: { injectTool: true, injectNudge: true }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false, @@ -303,12 +301,10 @@ test("e2e: fresh session (lastInputTokens=0) whose raw history overflows the win kernelConfig: defaultConfig(400_000), // CCR is opt-in on every lane (#1207 owner decision): off unless a // config level sets enabled=true, so the acp_retrieve tool schema does - // not load here. acp_rule is pinned off too since #1399 made it - // default-on — its schema shifts this exact-budget fold boundary. If - // the boundary shifts again, someone re-enabled a default — treat that - // as a regression tripwire. CCR-on / rules-on interplay with the - // cascade is covered by e2e-compress-cascade.test.ts / the rules suites. - compress: { injectTool: true, injectNudge: true, rules: false }, + // not load here. If this exact-budget boundary shifts again, someone + // re-enabled a default — treat that as a regression tripwire. CCR-on + // interplay with the cascade is covered by e2e-compress-cascade.test.ts. + compress: { injectTool: true, injectNudge: true }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false,