diff --git a/AGENTS.md b/AGENTS.md index aa12e24042..c937b563d1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,7 +44,7 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite - **pluginMode** (the `x-bili-plugin` header / registered agent, e.g. `bili pi`): the ACP-native agent OWNS compression — it executes `compress` locally, the call+result live in its own re-sent history, and the wire summary carrier is the **tool call** (the proxy suppresses tool + nudge injection; the agent's view never renders the kernel's `acp_summary`). - **proxy mode** (plain client, no header): the proxy executes `compress` server-side; the tool call is ephemeral (never enters the client's history) and preflight blocks have none, so the carrier is the **`acp_summary` message** — the kernel renders it role `system`, but `systemToUser` (`src/util.ts`) re-voices it as a **`user` message** (leaving it at its anchor) so strict backends (SGLang: exactly one system at index 0, #377) accept it and the head system message stays byte-stable for the prefix cache. - The mode is decided per request and bound per session (`session.metadata.pluginAgent`, sticky, upgrade-only). See TECHNICAL-NOTES.md "Two compression modes". -8. **Nudge cadence is flat 50K by design (kernel contract)** — acp-kernel pins the growth interval at 50000 for every window size (`nudge.growthFloor == nudge.growthCap == 50000`; window-percentage scaling was deliberately removed — #379/#380 settled "growth-driven, no usage/count proxy gates"). Do NOT re-scale the interval with the context window or reintroduce percentage gates; a 1M-window session folding every 50K of growth is intended lean-context behavior. User escape hatch: `compress.nudgeGrowthTokens` (flattens `growthFloor`+`growthCap` to a fixed step) — big-window users who want a lazier cadence set it explicitly. Prompt wording is kernel-owned (`src/nudge-text.ts`). + 8. **Nudge cadence is growth-driven, window-scaled within [20k, 50k] (kernel contract)** — acp-kernel resolves the growth step as `clamp(growthRatio × modelContextLimit, growthFloor, growthCap)` with defaults `growthFloor: 20000`, `growthCap: 50000`, `growthRatio: 0.05` — i.e. `clamp(5% × window, 20k, 50k)`: ≥1M windows keep the legacy flat 50k step byte-identical, sub-400k windows floor at 20k (#2110 RC2 / #2278 — the #379/#380 flat-50k-at-every-window calibration made a 50k gate ~24% of a 204k budget line and starved small-window cadence, so it was explicitly reversed for sub-1M windows). What survives from #379/#380: cadence is GROWTH-driven — no usage-percentage or message-count proxy gates on the day-to-day path (the pressure layer's maxContextLimit/emergency thresholds remain the percentage backstop), and a 1M-window session folding every 50K of growth stays intended lean-context behavior. Do NOT add usage/count proxy gates or widen the [20k, 50k] band without a dedicated decision issue. User escape hatch: `compress.nudgeGrowthTokens` (flattens `growthFloor`+`growthCap` to a fixed step) — set it explicitly to pin a flat step at any window. Prompt wording is kernel-owned (`src/nudge-text.ts`). 9. **Hosts that reuse ONE session id across personas get id + system-hash session keys ("hash 不一样自动分裂")** — when a plugin host stamps the SAME conversation id on every model request of a session INCLUDING auxiliary personas (dsh auto-review `classifyRisk()`: fixed REVIEW_POLICY system + a fresh flattened blob before every tool call — #1916/#1307/#1314), those auxiliary requests must be keyed by `subagentNamespace(id, systemText)` so the persona forks onto its own `|sub:` session instead of overwriting the main session's baseline/snapshots. The FIRST system seen under the id keeps the raw key (kernel anchor), so main turns never fork; an empty system is non-anchoring (verbatim); SIDE REQUESTS never claim the anchor either — dsh's title-gen sidecar fires at session start before/concurrent with the first main turn, and claiming it would fork the whole main conversation onto `|sub:` while every host-stamped ACP management call (compress/decompress/acp_status) routes into the ghost's empty session and fails forever (#2156/#2160; the `sideRequestLike` gate in `src/server.ts` mirrors the #388 passthrough predicate). This is an EVIDENCE-PERMITLIST (`dshPersonaFingerprintApplies` in `src/session-id.ts`), the same discipline as the instructions fingerprint (#1104/#1107): do NOT enable it wholesale — for everyone else system drift mid-id means "same conversation, evolved", and forking resets compression for no defending bug (#1106). A future host found reusing session ids across personas gets added to that predicate WITH traffic evidence (shape + stability proof: the host's main system must be session-stable, e.g. dsh composes it once per session and puts volatile time-context in a USER message). The fork must record itself under its suffixed id (`personaForked` → `recordPluginSession`) so the single-valued conversations map keeps the raw key owned by the main session (#970 discipline). Tests: `tests/dsh-persona-fingerprint.test.ts`. 10. **Thinking-family blocks are signature-verified — NEVER rewrite them (#1960)** — Anthropic `thinking`/`redacted_thinking` blocks and Gemini `thoughtSignature` parts are verified byte-for-byte when the latest assistant message is replayed ("thinking blocks ... cannot be modified"). The bytes the proxy forwards become the client's persisted history, and the bytes the loop accumulates become the re-request rebuild — BOTH must stay verbatim. Any transformation (tag/marker stripping, dedup, trimming, re-laying-out block order, dropping empty segments) desynchronizes text from signature and bricks the session: first on the in-turn re-request, then on every subsequent request via the client's echo. #1882 put a prose filter on the thinking channel and it was exactly this bug. Treat ANY future change touching thinking-family payloads as high-risk: it needs loop-level byte-equality tests (re-request body AND client-visible stream) on both signed wires, not just adapter-level ones. The prose filters (#206/#1881) are for the TEXT channel only. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index de77563496..7fd248e281 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -200,7 +200,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.maxContextLimit` | number \| "N%" | "75%" | — | Forced-compression nudge threshold: once history passes this share of the window the nudge fires immediately, bypassing growth gates. Not a hard cap. | | `compress.emergencyThresholdPercent` | number \| % | "95%" | — | Emergency truncation of oversized tool outputs when history passes this share of the window (must be >= maxContextLimit). | | `compress.outputHeadroomMaxPct` | number \| % | 0.25 | — | Cap on the share of the window reserved for output via max_tokens. | -| `compress.nudgeGrowthTokens` | number | 50000 (kernel flat cadence) | — | Growth gate: nudges fire only when a foldable range exceeds baseline growth by this many tokens (flat by design, independent of window size). | +| `compress.nudgeGrowthTokens` | number | unset — window-scaled: clamp(5% × window, 20k, 50k) | — | Growth gate: nudges fire only when a foldable range exceeds baseline growth by this many tokens. Default scales with the window (50k at ≥1M, 20k below 400k — #2110); set a number to pin a flat window-independent step. | | `compress.streamSummary` | boolean | false (unset) | — | Force preflight summarization to run as a streaming (SSE) call from the first attempt. Needed when the upstream sits behind a gateway that times out long non-streaming completions (e.g. Cloudflare HTTP 524): the error-driven self-learn only sees 400 "stream required" rejections and never arms on gateway timeouts. | | `compress.preserveRecentMessages` | number | kernel ≈5 | — | The most recent messages stay soft-protected from folds. | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | The most recent tokens stay soft-protected from folds. | @@ -1094,9 +1094,9 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t #### `nudgeGrowthTokens` - **Type:** `number` -- **Default:** `50000` +- **Default:** *(unset — window-scaled step `clamp(5% × window, 20000, 50000)`: 50k at ≥1M windows, 20k below 400k; #2110)* - **Status:** ACTIVE -- **Description:** Token-growth step for soft compression nudges. A nudge fires roughly every time this many tokens become compressible. Lower values produce more frequent nudges. Maps to the kernel fields `nudge.growthFloor` and `nudge.growthCap` (it flattens the engine's adaptive band to this fixed step). +- **Description:** Token-growth step for soft compression nudges. A nudge fires roughly every time this many tokens become compressible. Lower values produce more frequent nudges. Maps to the kernel fields `nudge.growthFloor` and `nudge.growthCap` (it flattens the engine's adaptive band to this fixed step; when unset the band defaults to [20k, 50k] and the step scales with the window). #### `preserveRecentMessages` @@ -1356,14 +1356,16 @@ These two toggles are honoured only at the **global** level. Setting them inside Compaction does **not** trigger on absolute window position — it triggers on **growth intervals**: by default the first soft compaction fires after the -session grows **50k tokens past its boot content** -([`nudgeGrowthTokens`](#nudgegrowthtokens), a flat step independent of window -size). The absolute position of the first compaction is therefore ≈ **boot + -50k**: +session grows **one growth step past its boot content** +([`nudgeGrowthTokens`](#nudgegrowthtokens), default window-scaled +`clamp(5% × window, 20k, 50k)` — 50k at ≥1M windows, 20k below 400k, #2110). +The absolute position of the first compaction is therefore ≈ **boot + step** +(boot + 50k on a ≥1M window, boot + 20k on a ≤400k window): -- boot 30k–50k (the dsh default) → first compaction at ~80k–100k; -- a boot around 100k, or a growth step set to ~100k → the first compaction may - wait until **~200k**. +- boot 30k–50k (the dsh default) on a ≥1M window → first compaction at + ~80k–100k; +- a boot around 100k on a ≥1M window, or a growth step set to ~100k → the + first compaction may wait until **~200k**. The forced threshold ([`maxContextLimit`](#maxcontextlimit), default 75%) is only a backstop, and it applies to the *effective* window — the output reserve @@ -1374,16 +1376,16 @@ carries a very large `max_tokens`: a 262,144-token window with `max_tokens = 131072` → effective window 196,608 → forced line ≈147k; the same window with an 8k reserve → forced line ≈190k. -After that the cadence stays growth-based: one incremental compaction per +50k -of compressible growth. On local models each compaction is a full re-prefill — -a heavy boot plus a large window puts several of them into one long task, which -is how wall-clock ends up 2–3× longer. +After that the cadence stays growth-based: one incremental compaction per +growth step of compressible growth. On local models each compaction is a full +re-prefill — a heavy boot plus a large window puts several of them into one +long task, which is how wall-clock ends up 2–3× longer. To make the first compaction fire earlier (and save tokens), in this order: 1. **trim the system prompt, disable unneeded tools, prune skills** — boot size directly determines the absolute position of the first compaction; -2. **lower `nudgeGrowthTokens` to ~50k** (especially if it was raised to 100k); +2. **lower `nudgeGrowthTokens`** (especially if it was raised to 100k); 3. **enable lean mode** (`promptPack: "lean"`). Measure actual boot/context usage with `/acp` or the web UI before tuning. @@ -1406,7 +1408,7 @@ Express it with the existing soft bands instead: keep the limit at the native wi How compression actually decides (acp-kernel, verified): -1. **Growth layer (day-to-day driver, absolute tokens):** a proactive nudge fires once cumulative growth since the last anchor (session start / last nudge / post-compression reset) reaches the growth gate **and** enough compressible mass has accumulated. Both numbers are absolute and window-independent by design: the growth step is flat 50k at every window size (kernel `nudge.growthFloor == nudge.growthCap == 50000`, golden-pinned; window-percentage scaling was deliberately removed — #379/#380; override with `nudgeGrowthTokens`); the growth gate is `max(20k, 0.45 × step)` ≈ 22.5k, and the T1 path additionally needs ≥ one step (50k) of compressible mass. This layer keeps compressing long sessions even far below any percentage band. +1. **Growth layer (day-to-day driver):** a proactive nudge fires once cumulative growth since the last anchor (session start / last nudge / post-compression reset) reaches the growth gate **and** enough compressible mass has accumulated. The growth step scales with the window by default — `clamp(5% × window, 20k, 50k)`: flat 50k at every window ≥1M (byte-identical to the old #379/#380 calibration), 20k below 400k; the flat-at-every-window behavior of #379/#380 was reverted for sub-1M windows because a 50k step on a 204k budget line (~24% of the window) starved the nudge cadence — #2110 (override with a flat step via `nudgeGrowthTokens`). The growth gate is `max(20k, 0.45 × step)` — 22.5k at the 50k step, exactly 20k at smaller steps — and the T1 path additionally needs ≥ one step of compressible mass. This layer keeps compressing long sessions even far below any percentage band. 2. **Pressure layer (percent of the window):** `usage ≥ maxContextLimit` (default 75%) → a nudge is injected every turn until context drops back under; `usage ≥ emergencyThresholdPercent` (default 95%) → forced nudge + emergency truncation. 3. **Qualification layer (kernel default 45%, not exposed):** gates only the turn-1 cold-start ticket and the block-count floor for T2/T3 tier escalation — not part of the day-to-day path. diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index f439171f5e..d0022f6b9c 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -200,7 +200,7 @@ | `compress.maxContextLimit` | number \| "N%" | "75%" | — | 强制压缩提醒阈值:历史超过窗口该占比时提醒立即触发,绕过增长门槛。不是硬上限。 | | `compress.emergencyThresholdPercent` | number \| % | "95%" | — | 历史超过窗口该占比时对超大工具输出做紧急截断(必须 >= maxContextLimit)。 | | `compress.outputHeadroomMaxPct` | number \| % | 0.25 | — | max_tokens 输出预留占窗口的最大比例。 | -| `compress.nudgeGrowthTokens` | number | 50000 (kernel flat cadence) | — | 增长门槛:可折叠片段超出基线增长达到该 token 数才发提醒(按设计恒定,与窗口大小无关)。 | +| `compress.nudgeGrowthTokens` | number | unset — window-scaled: clamp(5% × window, 20k, 50k) | — | 增长门槛:可折叠片段超出基线增长达到该 token 数才发提醒。默认随窗口缩放(≥1M 窗 50k,<400k 窗 20k,#2110);设为具体数字可钉住固定步长(与窗口无关)。 | | `compress.streamSummary` | boolean | false (unset) | — | 强制 preflight 摘要从首次尝试起就走流式(SSE)请求。适用于上游位于会掐断长非流式补全的网关之后(如 Cloudflare HTTP 524):错误驱动的自学习只认 400 "stream required",网关超时永远无法触发。 | | `compress.preserveRecentMessages` | number | kernel ≈5 | — | 最近的消息软保护、免于折叠。 | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | 最近的 token 软保护、免于折叠。 | @@ -1097,9 +1097,9 @@ #### `nudgeGrowthTokens` - **类型:** `number` -- **默认值:** `50000` +- **默认值:** *(未设置——随窗口缩放的步长 `clamp(5% × 窗口, 20000, 50000)`:≥1M 窗口 50k,<400k 窗口 20k;#2110)* - **状态:** ACTIVE -- **说明:** 软压缩 nudge 的 token 增长步长。每当有这么多 token 变为可压缩时,大约就会触发一次 nudge。值越小,nudge 越频繁。映射到内核字段 `nudge.growthFloor` 和 `nudge.growthCap`(它将引擎的自适应区间扁平化为这个固定步长)。 +- **说明:** 软压缩 nudge 的 token 增长步长。每当有这么多 token 变为可压缩时,大约就会触发一次 nudge。值越小,nudge 越频繁。映射到内核字段 `nudge.growthFloor` 和 `nudge.growthCap`(它将引擎的自适应区间扁平化为这个固定步长;未设置时区间默认为 [20k, 50k],步长随窗口缩放)。 #### `preserveRecentMessages` @@ -1359,12 +1359,14 @@ ### 为什么第一次压缩要到 200k 才触发? -压缩触发时机**不是按绝对窗口位置,而是按增长区间**:默认在开机内容之上**增长 -50k token** 才触发第一次软压缩([`nudgeGrowthTokens`](#nudgegrowthtokens) -恒定步长,与窗口大小无关)。因此第一次压缩的绝对位置 ≈ **开机占用 + 50k**: +压缩触发时机**不是按绝对窗口位置,而是按增长区间**:默认在会话**超过开机内容 +一个增长步长**后触发第一次软压缩([`nudgeGrowthTokens`](#nudgegrowthtokens), +默认随窗口缩放 `clamp(5% × 窗口, 20k, 50k)`——≥1M 窗口 50k、<400k 窗口 20k, +#2110)。因此第一次压缩的绝对位置 ≈ **开机占用 + 步长**(≥1M 窗口上为开机 + +50k,≤400k 窗口上为开机 + 20k): -- 开机 30k–50k(dsh 默认)→ 第一次压缩在 ~80k–100k; -- 开机 100k 左右,或把 `nudgeGrowthTokens` 设到 100k 左右 → 可能要到 +- 开机 30k–50k(dsh 默认),≥1M 窗口 → 第一次压缩在 ~80k–100k; +- ≥1M 窗口上开机 100k 左右,或把增长步长设到 100k 左右 → 可能要到 **~200k** 才发生第一次压缩。 强制压缩线([`maxContextLimit`](#maxcontextlimit) 默认 75%)只是兑底,且作用在 @@ -1374,7 +1376,7 @@ 262,144 窗口 + `max_tokens = 131072` → 有效窗口 196,608 → 强制线 ≈147k; 262,144 窗口 + 预留 8k → 强制线 ≈190k。 -之后仍是增长制节奏:每 +50k 可压缩增长一次增量压缩。本地模型每次压缩都是 +之后仍是增长制节奏:每增长一个步长的可压缩量做一次增量压缩。本地模型每次压缩都是 整窗重新 prefill —— 重型启动 + 大窗口的长任务会经历多次,任务时长可能被拖长 2–3 倍。 @@ -1382,7 +1384,7 @@ 1. **删减系统提示词、关闭不需要的工具、精简 skill** —— 开机占用直接决定 第一次压缩的绝对位置; -2. **把 `nudgeGrowthTokens` 调小到 50k 左右**(尤其当它曾被调大到 100k); +2. **调小 `nudgeGrowthTokens`**(尤其当它曾被调大到 100k); 3. **开启 lean 功能**(`promptPack: "lean"`)。 调参前先用 `/acp` 或网页界面实测开机/上下文占用。 @@ -1405,7 +1407,7 @@ 压缩实际如何决策(acp-kernel,已实证): -1. **增长层(日常主力,绝对 token)**:自上次锚点(会话起点 / 上次 nudge / 压缩后重置)以来的累计增长达到增长门、且可压缩质量足够时,发出主动 nudge。这两个数都是绝对值、按设计不随窗口放大:增长步长在任意窗口大小下固定 50k(内核 `nudge.growthFloor == nudge.growthCap == 50000`,golden 钉死;窗口百分比缩放被有意移除——#379/#380;可用 `nudgeGrowthTokens` 覆盖);增长门 = `max(20k, 0.45 × 步长)` ≈ 22.5k,且 T1 路径另需 ≥ 一个步长(50k)的可压缩质量。这一层保证长会话在任何百分比档位之下也持续得到压缩。 +1. **增长层(日常主力)**:自上次锚点(会话起点 / 上次 nudge / 压缩后重置)以来的累计增长达到增长门、且可压缩质量足够时,发出主动 nudge。增长步长默认随窗口缩放——`clamp(5% × 窗口, 20k, 50k)`:≥1M 窗口恒为 50k(与旧 #379/#380 标定逐字节一致),<400k 窗口取 20k;#379/#380 的「任意窗口恒定 50k」行为对亚 1M 窗口被撤销,因为 204k 预算线上 50k 步长(约占窗口 24%)会让 nudge 节奏饿死——#2110(可用 `nudgeGrowthTokens` 覆盖为固定步长)。增长门 = `max(20k, 0.45 × 步长)`——50k 步长时为 22.5k,更小的步长下恰为 20k——且 T1 路径另需 ≥ 一个步长的可压缩质量。这一层保证长会话在任何百分比档位之下也持续得到压缩。 2. **压力层(窗口的百分比)**:`usage ≥ maxContextLimit`(默认 75%)→ 每轮注入 nudge,直到上下文回落到线以下;`usage ≥ emergencyThresholdPercent`(默认 95%)→ 强制 nudge + 紧急截断。 3. **资格层(内核默认 45%,未暴露)**:只管第 1 轮冷启动门票和 T2/T3 块数升级地板——不参与日常路径。 diff --git a/README.md b/README.md index 2687c51605..1d364e4c14 100644 --- a/README.md +++ b/README.md @@ -333,19 +333,21 @@ connectivity test. Everything is also plain JSON for scripting (`/__bili/stats`, `/__bili/sessions`, `/__bili/config`, …). **When does compression happen?** It is model-driven: the injected context -tools are called by the model as context grows, gentle growth nudges -(~50K-token steps by design, adjustable via `compress.nudgeGrowthTokens`) +tools are called by the model as context grows, gentle growth nudges (a +window-scaled step — 5% of the window clamped to [20k, 50k], so 50k at ≥1M +windows and 20k below 400k; pin a flat step with `compress.nudgeGrowthTokens`) prompt it along the way, and preflight fires as a hard backstop when the input alone exceeds the window (#470). Watch it live with `/acp` or the web UI. **Why does the first compaction wait until ~200k?** Compaction does not trigger on absolute window position but on growth intervals: by default the -first soft compaction fires 50k tokens past the boot content -(`compress.nudgeGrowthTokens`, flat and window-independent). With a boot around -100k — or with the growth step set to ~100k — the first compaction may wait -until ~200k. To make it fire earlier: 1) trim the system prompt, disable -unneeded tools, prune skills; 2) lower `compress.nudgeGrowthTokens` to ~50k; -3) enable lean mode. Worked example in +first soft compaction fires one growth step past the boot content +(clamp(5% × window, 20k, 50k) — 50k on ≥1M windows, 20k below 400k; +[`nudgeGrowthTokens`](CONFIGURATION.md#nudgegrowthtokens) pins a flat step). +With a boot around 100k on a ≥1M window — or with the growth step set to +~100k — the first compaction may wait until ~200k. To make it fire earlier: +1) trim the system prompt, disable unneeded tools, prune skills; 2) lower +`compress.nudgeGrowthTokens`; 3) enable lean mode. Worked example in [CONFIGURATION.md](CONFIGURATION.md#why-the-first-compaction-waits-until-200k). **Is bili transparent? How do I turn it off?** Unrecognized endpoints forward diff --git a/README.zh-CN.md b/README.zh-CN.md index f17502cf66..b7c35cefaa 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -258,9 +258,9 @@ curl -s http://localhost:8787/__bili/stats **能用网页查会话和配置吗?** 能 —— 打开 [http://localhost:8787](http://localhost:8787):总览仪表盘、会话列表(含逐会话详情)、实时日志、配置编辑器、上游连通性测试。全部功能同样以纯 JSON 提供(`/__bili/stats`、`/__bili/sessions`、`/__bili/config`、…),方便脚本化。 -**压缩什么时候发生?** 由模型驱动:注入的上下文工具由模型在上下文增长时自行调用,温和的增长 nudge(按设计固定约 50K token 步长,可用 `compress.nudgeGrowthTokens` 调整)沿途提醒它,仅输入就超窗时预检作为硬兜底触发(#470)。用 `/acp` 或网页界面实时观察。 +**压缩什么时候发生?** 由模型驱动:注入的上下文工具由模型在上下文增长时自行调用,温和的增长 nudge(随窗口缩放的步长——窗口的 5%、夹在 [20k, 50k],即 ≥1M 窗口 50k、<400k 窗口 20k;用 `compress.nudgeGrowthTokens` 可钉住固定步长)沿途提醒它,仅输入就超窗时预检作为硬兜底触发(#470)。用 `/acp` 或网页界面实时观察。 -**为什么第一次压缩要到 ~200k 才触发?** 压缩触发不是按绝对窗口位置、而是按增长区间:默认在开机内容之上增长 50k token 才触发第一次软压缩(`compress.nudgeGrowthTokens` 恒定步长、与窗口无关)。开机 100k 左右、或把 `compress.nudgeGrowthTokens` 设到 100k 左右时,可能都要到 ~200k 才发生第一次压缩。想更早压缩省 token:1.删减系统提示词、关闭不需要的工具、精简 skill;2.把 nudge 调小到 50k 左右;3.开启 lean 功能。完整算例见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md#为什么第一次压缩要到-200k-才触发)。 +**为什么第一次压缩要到 ~200k 才触发?** 压缩触发不是按绝对窗口位置、而是按增长区间:默认在开机内容之上再增长一个步长才触发第一次软压缩(步长随窗口缩放:clamp(5% × 窗口, 20k, 50k)——≥1M 窗口 50k、<400k 窗口 20k;`compress.nudgeGrowthTokens` 可钉住固定步长)。在 ≥1M 窗口上开机 100k 左右、或把步长显式设到 100k 左右时,可能都要到 ~200k 才发生第一次压缩。想更早压缩省 token:1.删减系统提示词、关闭不需要的工具、精简 skill;2.调小 `compress.nudgeGrowthTokens`;3.开启 lean 功能。完整算例见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md#为什么第一次压缩要到-200k-才触发)。 **bili 是透明的吗?怎么关掉?** 未识别端点原样转发([CLIENTS.zh-CN.md](CLIENTS.zh-CN.md)),且每种模式都能干净退出:原生安装用 `bili plugin remove `,另两种模式停掉启动器命令 / 环境变量 / `/bili/` 前缀即可 —— 流量立刻恢复直连。 diff --git a/kernel/package.json b/kernel/package.json index b86a0ffe82..3dc5533b9f 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.104", + "version": "0.0.105", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/config.ts b/kernel/src/config.ts index 5306539bb7..900ad057f0 100644 --- a/kernel/src/config.ts +++ b/kernel/src/config.ts @@ -13,7 +13,16 @@ export function defaultConfig( iterationThreshold: 15, force: "soft", growthRatio: 0.05, - growthFloor: 50000, + // #2110: the default band is window-relative again — resolveAdaptiveGrowth + // clamps growthRatio × modelContextLimit into [growthFloor, growthCap], + // so ≥1M windows keep the flat 50k step byte-identical while smaller + // windows scale down (floored at 20k below 400k). The old floor=cap=50k + // (#379/#380) pinned EVERY window to a 50k step: ~24% of a 204k budget + // line, so quiet-turn growth never re-armed the nudge cadence and + // compressible mass sat idle turn after turn (issue #2110: pending + // 43–52k against a 50k gate for 66 straight requests). Explicit + // `compress.nudgeGrowthTokens` still flattens the band to a fixed step. + growthFloor: 20000, growthCap: 50000, minGrowthFloor: 20000, minGrowthRatio: 0.45, diff --git a/kernel/src/types.ts b/kernel/src/types.ts index 17e8d0fcc3..634f607751 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -316,9 +316,9 @@ export interface NudgeConfig { iterationThreshold: number; force: "soft" | "strong"; growthRatio: number; - /** Adaptive growth threshold = modelContextLimit × this ratio, clamped to [growthFloor, growthCap]. Default 0.05 (5%). */ + /** Lower clamp for the adaptive growth step = modelContextLimit × growthRatio. Default 20000 (#2110: sub-400k windows get a 20k step instead of #379/#380's flat 50k, which starved small-window nudge cadence). */ growthFloor: number; - /** Upper clamp for adaptive growth threshold. Default 50000. */ + /** Upper clamp for the adaptive growth step. Default 50000 — reached at ≥1M windows (0.05 × 1M); smaller windows scale below it. */ growthCap: number; /** Anti-thrashing: suppress nudge unless growth ≥ max(minGrowthFloor, minGrowthRatio × growthTokens). Default 5000. */ minGrowthFloor: number; diff --git a/kernel/tests/nudge-growth-window-scale.test.ts b/kernel/tests/nudge-growth-window-scale.test.ts new file mode 100644 index 0000000000..7de9cb11d8 --- /dev/null +++ b/kernel/tests/nudge-growth-window-scale.test.ts @@ -0,0 +1,59 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createCore } from "../src/compress.js"; +import { createInitialState } from "../src/state.js"; +import { defaultConfig } from "../src/config.js"; + +// #2110: the default growth step must be window-relative — +// clamp(growthRatio × modelContextLimit, growthFloor=20000, growthCap=50000). +// The old flat floor=cap=50000 (#379/#380) pinned EVERY window to a 50k step: +// ~24% of a 204k budget line, so quiet-turn growth never re-armed the nudge +// cadence and compressible mass sat idle turn after turn (the issue's session +// held pending 43–52k against the 50k gate for 66 straight requests). ≥1M +// windows must stay byte-identical (0.05 × 1M = 50000 = cap). +function growthBreakdown(modelContextLimit: number, nudgeOverrides: Record = {}): Record { + const config = defaultConfig(modelContextLimit, { nudge: nudgeOverrides } as never); + const core = createCore(); + const turn = core.processTurn({ + messages: [], + state: createInitialState(), + config, + tokenCount: 1, + }); + assert.ok(turn.nudge?.breakdown, "decideNudge always emits a breakdown"); + return turn.nudge.breakdown as unknown as Record; +} + +test("#2110: default growth step scales with the window", () => { + // Legacy calibration is preserved at the top: 1M windows are byte-identical. + assert.equal(growthBreakdown(1_000_000).nudgeGrowthTokens, 50000, "1M window keeps the flat 50k step"); + assert.equal(growthBreakdown(2_000_000).nudgeGrowthTokens, 50000, "cap binds above 1M"); + + // In-band scaling: 5% of the window between 400k and 1M. + assert.equal(growthBreakdown(600_000).nudgeGrowthTokens, 30000, "600k window scales to 5% = 30k"); + + // The #2110 window: 272k native (204k effective budget line) previously + // waited a flat 50k; now the floor binds at 20k. + assert.equal(growthBreakdown(272_000).nudgeGrowthTokens, 20000, "272k window (the issue) gets the 20k floor"); + assert.equal(growthBreakdown(204_000).nudgeGrowthTokens, 20000, "204k window gets the 20k floor"); + assert.equal(growthBreakdown(400_000).nudgeGrowthTokens, 20000, "400k window is exactly at the floor crossover"); +}); + +test("#2110: the anti-thrash gate follows the scaled step", () => { + // gate2 = max(minGrowthFloor=20000, minGrowthRatio 0.45 × step): the small-window + // floor is exactly minGrowthFloor; the 1M step keeps the legacy 22500. + assert.equal(growthBreakdown(272_000).growthFloor, 20000, "272k: max(20000, 0.45 × 20000) = 20000"); + assert.equal(growthBreakdown(1_000_000).growthFloor, 22500, "1M: max(20000, 0.45 × 50000) = 22500 (unchanged)"); +}); + +test("#2110: nudgeGrowthTokens-style flatten still pins a flat step", () => { + // compress.nudgeGrowthTokens sets growthFloor = growthCap (the documented + // escape hatch, verified live in issue #2110 with 25000). At every window. + for (const limit of [204_000, 272_000, 600_000, 1_000_000]) { + assert.equal( + growthBreakdown(limit, { growthFloor: 25000, growthCap: 25000 }).nudgeGrowthTokens, + 25000, + `limit=${limit}: flattened band pins the step`, + ); + } +}); diff --git a/tests/golden/wire-contract/kernel.json b/tests/golden/wire-contract/kernel.json index 42cce6ba3a..aa674f31cc 100644 --- a/tests/golden/wire-contract/kernel.json +++ b/tests/golden/wire-contract/kernel.json @@ -1628,7 +1628,7 @@ "iterationThreshold": 15, "force": "soft", "growthRatio": 0.05, - "growthFloor": 50000, + "growthFloor": 20000, "growthCap": 50000, "minGrowthFloor": 20000, "minGrowthRatio": 0.45, diff --git a/tests/issue1595-nudge-reanchor.test.ts b/tests/issue1595-nudge-reanchor.test.ts index 81e615e2a2..5e1ffd346a 100644 --- a/tests/issue1595-nudge-reanchor.test.ts +++ b/tests/issue1595-nudge-reanchor.test.ts @@ -78,12 +78,12 @@ test("#1595 unit A: usage-grade drop beyond one interval retires a stale-high sh assert.equal(s.state.nudge.lastPerMessageNudgeTokens, 100_000, "baseline re-anchored to the real value"); assert.deepEqual(s.state.nudge.lastShownByTier, {}, "per-tier stamps cleared"); assert.ok(lines.some((l) => l.includes("nudge reference re-anchored 600000 -> 100000")), `re-anchor log missing: ${JSON.stringify(lines)}`); - assert.ok(lines.some((l) => l.includes("(margin 50000)")), "default flat 50k margin"); + assert.ok(lines.some((l) => l.includes("(margin 20000)")), "#2110: unstamped-config margin is the kernel growthFloor default (20k, window-scaled band bottom)"); }); test("#1595 unit B: a drop within one growth interval leaves the reference alone", () => { const s = makeSession(); - s.stats.lastInputTokens = 570_000; // 30k below the reference — inside the 50k margin + s.stats.lastInputTokens = 585_000; // 15k below the reference — inside the 20k margin (#2110 band bottom) s.state.nudge.lastNudgeShownTokens = PHANTOM; s.state.nudge.lastPerMessageNudgeTokens = 135_000; const { lines } = captureLogs(() => reanchorNudgeOnUsageDrop(s)); @@ -103,13 +103,15 @@ test("#1595 unit C: no live reference is a no-op", () => { test("#1595 unit D: margin follows the owner-flattened stamped config", () => { const s = makeSession(); const cfg = defaultConfig(272_000); - cfg.nudge.growthFloor = cfg.nudge.growthCap = 20_000; // compress.nudgeGrowthTokens-style flatten + // #2110: the 272k window now scales the default band to a 20k floor, so + // flatten BELOW the scaled default to keep this a tightening test. + cfg.nudge.growthFloor = cfg.nudge.growthCap = 10_000; // compress.nudgeGrowthTokens-style flatten storeEffectiveConfig(s, cfg); - s.stats.lastInputTokens = 575_000; // 25k below — beyond the 20k margin, inside the default 50k + s.stats.lastInputTokens = 575_000; // 25k below — beyond the 10k flattened margin, inside the 20k scaled default s.state.nudge.lastNudgeShownTokens = PHANTOM; const { lines } = captureLogs(() => reanchorNudgeOnUsageDrop(s)); assert.equal(s.state.nudge.lastNudgeShownTokens, 0, "flattened margin must tighten the trigger"); - assert.ok(lines.some((l) => l.includes("(margin 20000)")), `expected 20k margin in log: ${JSON.stringify(lines)}`); + assert.ok(lines.some((l) => l.includes("(margin 10000)")), `expected 10k margin in log: ${JSON.stringify(lines)}`); }); test("#1595 unit E: success-without-usage diagnostic warns once per session", () => { diff --git a/tests/issue2110-nudge-growth-window-scale.test.ts b/tests/issue2110-nudge-growth-window-scale.test.ts new file mode 100644 index 0000000000..53ea2ee20a --- /dev/null +++ b/tests/issue2110-nudge-growth-window-scale.test.ts @@ -0,0 +1,66 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +process.env.NODE_ENV = "test"; + +import { createCore, createInitialState, defaultConfig } from "acp-kernel"; +import type { Config } from "acp-kernel"; +import { resolveRequestConfig } from "../src/compress-settings.ts"; + +// #2110 root cause RC2: the kernel default growth step was flat 50k at every +// window (floor=cap=50000, #379/#380), so sub-1M windows waited a 1M-calibrated +// step — on the issue's 272k-native window the effective 204k budget line made +// the 50k gate ~24% of the window, and quiet-turn growth never re-armed the +// nudge cadence (66 straight requests, pending 43–52k, zero folds). +// +// The fix restores a window-relative default band +// clamp(0.05 × window, 20000, 50000): ≥1M byte-identical, ≤400k floored at 20k. +// This suite pins the bili-side plumbing: per-route modelContextLimit flows into +// the effective kernel config (the step scales with the ROUTE's window, not the +// global base), and compress.nudgeGrowthTokens still flattens the band to a +// fixed step (the live-verified escape hatch from issue #2110). + +function stepFor(config: Config): number { + const turn = createCore().processTurn({ + messages: [], + state: createInitialState(), + config, + tokenCount: 1, + }); + const breakdown = turn.nudge?.breakdown as Record | undefined; + assert.ok(breakdown?.nudgeGrowthTokens !== undefined, "decideNudge breakdown carries nudgeGrowthTokens"); + return breakdown.nudgeGrowthTokens; +} + +test("#2110: per-route windows scale the default growth step through resolveRequestConfig", () => { + const routes = { + "http://upstream.local": { + models: { + "small-window-model": { context: 272_000 }, + "big-window-model": { context: 1_000_000 }, + }, + }, + }; + const base = defaultConfig(1_000_000); + + const small = resolveRequestConfig(base, routes, "http://upstream.local", "small-window-model", 272_000); + assert.equal(small.modelContextLimit, 272_000, "route window wins"); + assert.equal(stepFor(small), 20000, "272k route window gets the 20k floor (was flat 50k)"); + + const big = resolveRequestConfig(base, routes, "http://upstream.local", "big-window-model", undefined); + assert.equal(big.modelContextLimit, 1_000_000); + assert.equal(stepFor(big), 50000, "1M window keeps the legacy 50k step byte-identical"); +}); + +test("#2110: compress.nudgeGrowthTokens still pins a flat step over the scaled default", () => { + const routes = { + "http://upstream.local": { + models: { "small-window-model": { context: 204_000, compress: { nudgeGrowthTokens: 25000 } } }, + }, + }; + const base = defaultConfig(1_000_000); + const cfg = resolveRequestConfig(base, routes, "http://upstream.local", "small-window-model", undefined); + assert.equal(cfg.nudge.growthFloor, 25000, "escape hatch flattens the band floor"); + assert.equal(cfg.nudge.growthCap, 25000, "escape hatch flattens the band cap"); + assert.equal(stepFor(cfg), 25000, "the flattened step wins over window scaling at any window"); +}); diff --git a/website/config-reference/compress.yaml b/website/config-reference/compress.yaml index fffad92188..307921b64f 100644 --- a/website/config-reference/compress.yaml +++ b/website/config-reference/compress.yaml @@ -44,14 +44,14 @@ entries: site_zh: "max_tokens 输出预留占窗口的最大比例(0–1,默认 0.25)。" - key: compress.nudgeGrowthTokens type: number - default: "50000 (kernel flat cadence)" + default: "unset — window-scaled: clamp(5% × window, 20k, 50k)" group: compress id: cw.ngt render: compress-row - desc_en: "Growth gate: nudges fire only when a foldable range exceeds baseline growth by this many tokens (flat by design, independent of window size)." - desc_zh: "增长门槛:可折叠片段超出基线增长达到该 token 数才发提醒(按设计恒定,与窗口大小无关)。" - site_en: "Growth gate (default 50000): nudges fire only when a foldable range exceeds baseline growth by this many tokens." - site_zh: "增长门槛(默认 50000):可折叠片段超出基线增长达到该 token 数才发提醒。" + desc_en: "Growth gate: nudges fire only when a foldable range exceeds baseline growth by this many tokens. Default scales with the window (50k at ≥1M, 20k below 400k — #2110); set a number to pin a flat window-independent step." + desc_zh: "增长门槛:可折叠片段超出基线增长达到该 token 数才发提醒。默认随窗口缩放(≥1M 窗 50k,<400k 窗 20k,#2110);设为具体数字可钉住固定步长(与窗口无关)。" + site_en: "Growth gate (default window-scaled: 20k–50k): nudges fire only when a foldable range exceeds baseline growth by this many tokens." + site_zh: "增长门槛(默认随窗口缩放:20k–50k):可折叠片段超出基线增长达到该 token 数才发提醒。" - key: compress.streamSummary type: boolean default: "false (unset)" diff --git a/website/docs/index.html b/website/docs/index.html index 185e8fbd24..eb332302b1 100644 --- a/website/docs/index.html +++ b/website/docs/index.html @@ -182,7 +182,7 @@

compress — every knob

maxContextLimitnumber | "N%"Forced-compression nudge threshold (default "75%"): once history passes this share of the window the nudge fires immediately, bypassing the growth gates. Not a hard cap. emergencyThresholdPercentnumber | %Default "95%": emergency truncation of oversized tool outputs when history passes this share of the window (must be ≥ maxContextLimit). outputHeadroomMaxPctnumber | %Cap (0–1, default 0.25) on the share of the window reserved for output via max_tokens. - nudgeGrowthTokensnumberGrowth gate (default 50000): nudges fire only when a foldable range exceeds baseline growth by this many tokens. + nudgeGrowthTokensnumberGrowth gate (default window-scaled: 20k–50k): nudges fire only when a foldable range exceeds baseline growth by this many tokens. streamSummarybooleanForce streaming (SSE) summarization from the first attempt — an escape hatch for upstreams behind gateways that time out long non-streaming calls (e.g. Cloudflare 524), which the error-driven self-learn cannot detect. preserveRecentMessagesnumberKernel default ≈5: the most recent messages stay soft-protected from folds. preserveRecentTokensnumberKernel default ≈5000: the most recent tokens stay soft-protected from folds. diff --git a/website/main.js b/website/main.js index 886834707a..efb4757ca3 100644 --- a/website/main.js +++ b/website/main.js @@ -65,7 +65,7 @@ "cw.mxcl": "Forced-compression nudge threshold (default \"75%\"): once history passes this share of the window the nudge fires immediately, bypassing the growth gates. Not a hard cap.", "cw.etc": "Default \"95%\": emergency truncation of oversized tool outputs when history passes this share of the window (must be ≥ maxContextLimit).", "cw.ohmp": "Cap (0–1, default 0.25) on the share of the window reserved for output via max_tokens.", - "cw.ngt": "Growth gate (default 50000): nudges fire only when a foldable range exceeds baseline growth by this many tokens.", + "cw.ngt": "Growth gate (default window-scaled: 20k–50k): nudges fire only when a foldable range exceeds baseline growth by this many tokens.", "cw.ssm": "Force streaming (SSE) summarization from the first attempt — an escape hatch for upstreams behind gateways that time out long non-streaming calls (e.g. Cloudflare 524), which the error-driven self-learn cannot detect.", "cw.prm": "Kernel default ≈5: the most recent messages stay soft-protected from folds.", "cw.prt": "Kernel default ≈5000: the most recent tokens stay soft-protected from folds.", @@ -169,9 +169,9 @@ "fa.webq.q": "Can I query sessions and config over the web?", "fa.webq.a": "Yes — open http://localhost:8787: overview dashboard, session list with per-session detail, live logs, a config editor, and an upstream connectivity test. Everything is also plain JSON for scripting (/__bili/stats, /__bili/sessions, /__bili/config, …).", "fa.when.q": "When does compression happen?", - "fa.when.a": "It is model-driven: the injected context tools are called by the model as context grows, growth nudges (~50K-token steps by design, adjustable via compress.nudgeGrowthTokens) prompt it along the way, and preflight fires as a hard backstop when the input alone exceeds the window. Watch it live with /acp or the web UI.", + "fa.when.a": "It is model-driven: the injected context tools are called by the model as context grows, growth nudges (window-scaled ~20K–50K token steps, adjustable via compress.nudgeGrowthTokens) prompt it along the way, and preflight fires as a hard backstop when the input alone exceeds the window. Watch it live with /acp or the web UI.", "fa.fc.q": "Why does the first compaction wait until ~200k?", - "fa.fc.a": "Compaction triggers on growth intervals, not absolute window position: by default the first soft compaction fires 50k tokens past the boot content (compress.nudgeGrowthTokens, flat and window-independent) — with a ~100k boot it may wait until ~200k. To make it fire earlier: trim the system prompt / disable unneeded tools / prune skills, lower compress.nudgeGrowthTokens to ~50k, or enable lean mode.", + "fa.fc.a": "Compaction triggers on growth intervals, not absolute window position: by default the first soft compaction fires one growth step past the boot content (compress.nudgeGrowthTokens, window-scaled: 20k below 400k windows, up to 50k at ≥1M) — with a ~100k boot on a small-window model it may wait until ~120k. To make it fire earlier: trim the system prompt / disable unneeded tools / prune skills, pin compress.nudgeGrowthTokens lower (e.g. 10000), or enable lean mode.", "fa.transp.q": "Is bili transparent? How do I turn it off?", "fa.transp.a": "Unrecognized endpoints forward unchanged, and every mode reverses cleanly: bili plugin remove <client> for native installs; stop using the launcher command / env vars / /bili/ prefix for the other two — traffic goes direct again immediately. Per-client mechanics: CLIENTS.md.", "fa.paths.q": "Where are logs and session data stored?", @@ -296,7 +296,7 @@ "cw.mxcl": "强制压缩提醒阈值(默认 \"75%\"):历史超过窗口的该占比时提醒立即触发,绕过增长门槛。不是硬上限。", "cw.etc": "默认 \"95%\":历史超过窗口该占比时,对超大工具输出做紧急截断(必须 ≥ maxContextLimit)。", "cw.ohmp": "max_tokens 输出预留占窗口的最大比例(0–1,默认 0.25)。", - "cw.ngt": "增长门槛(默认 50000):可折叠片段超出基线增长达到该 token 数才发提醒。", + "cw.ngt": "增长门槛(默认随窗口缩放:20k–50k):可折叠片段超出基线增长达到该 token 数才发提醒。", "cw.ssm": "强制摘要从首次起走流式(SSE)——用于上游在会掐断长非流式调用的网关之后(如 Cloudflare 524),错误自学习无法感知该场景。", "cw.prm": "内核默认约 5:最近消息软保护、免于折叠。", "cw.prt": "内核默认约 5000:最近的 token 软保护、免于折叠。", @@ -400,9 +400,9 @@ "fa.webq.q": "能在网页上查会话和配置吗?", "fa.webq.a": "可以——打开 http://localhost:8787:总览面板、会话列表与单会话详情、实时日志、配置编辑器、上游连通性测试。一切同时也是纯 JSON 接口(/__bili/stats、/__bili/sessions、/__bili/config …),方便脚本使用。", "fa.when.q": "压缩什么时候发生?", - "fa.when.a": "由模型驱动:注入的上下文工具由模型在上下文增长时调用,沿途有增长提醒(设计上约每 50K token 一步,可用 compress.nudgeGrowthTokens 调整),单条输入就超窗口时 preflight 兜底硬触发。用 /acp 或 Web 面板实时观察。", + "fa.when.a": "由模型驱动:注入的上下文工具由模型在上下文增长时调用,沿途有增长提醒(随窗口缩放的 20K–50K token 步长,可用 compress.nudgeGrowthTokens 调整),单条输入就超窗口时 preflight 兜底硬触发。用 /acp 或 Web 面板实时观察。", "fa.fc.q": "为什么第一次压缩要等到 ~200k?", - "fa.fc.a": "压缩按增长间隔触发,不按窗口绝对位置:默认首次软压缩发生在启动内容之外再长 50k token 时(compress.nudgeGrowthTokens,固定值、与窗口大小无关)——启动内容若已有 ~100k,可能要等到 ~200k。想提前:精简系统提示词 / 关掉不用的工具 / 清理 skills,把 compress.nudgeGrowthTokens 降到 ~50k,或开 lean 模式。", + "fa.fc.a": "压缩按增长间隔触发,不按窗口绝对位置:默认首次软压缩发生在启动内容之外再长一个增长步长时(compress.nudgeGrowthTokens,随窗口缩放:<400k 窗 20k,≥1M 窗最高 50k)——小窗口模型上启动内容若已有 ~100k,可能要等到 ~120k。想提前:精简系统提示词 / 关掉不用的工具 / 清理 skills,把 compress.nudgeGrowthTokens 钉得更低(如 10000),或开 lean 模式。", "fa.transp.q": "bili 是透明的吗?怎么关?", "fa.transp.a": "无法识别的端点原样转发,每种接法都能干净退出:原生插件用 bili plugin remove <client>;其余两种停掉启动器命令 / 环境变量 / /bili/ 前缀即可——流量立刻恢复直连。各客户端细节见 CLIENTS.md。", "fa.paths.q": "日志和会话数据存在哪?",