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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag
- **系统架构文档体系落地(owner 指令 2026-11-08):`docs/architecture/` 成为实时维护的架构枢纽**:新增 `docs/architecture.md` / `docs/architecture.zh-CN.md` 总枢纽(整体架构图中英双版转正 + 8 模块总表),首个样板模块页 `docs/architecture/storage.{md,zh-CN.md}`(统一存储:职责/原理/工作机制/硬不变量,配模块图中英双版)。文件级地图 `reference/architecture.md` 补齐 125 个缺失条目(新存储层 / marker / fastpath / lanes 等全部新模块)并升级为 CI 强制全量覆盖。新增 CI 车道 `architecture-docs`(`tools/check-architecture-docs.mjs`):地图覆盖全 `src/` 文件、总表↔页面成对、图 svg 优先 + png 备选齐备、SVG 基础良构(未转义 `&` 曾让英文图线上破图)。AGENTS.md「Documentation Layout」新增实时维护规则:改结构 ⇒ 同 PR 更新页 + 图 + 总表。其余 7 个模块页(pipeline / lanes / kernel / identity / fastpaths / webui / update)同一 PR 全部补齐——总表 8 行全 ✅(每页 = 中英双版文档 + 中英双版图)。

### Fixed
- **compress.requireNudge 的单轮武装改为 nudge 信用窗口:模型隔轮回来压缩不再被误拒(#5943)**:开关开启时,模型按 nudge 指令干活(读范围、写摘要、被 requireRecommendation 拒后重试)通常要跨好几个模型轮次,而旧实现每轮 prepare 都把武装位重置为「本轮是否注入了 nudge」——模型干完活回来的那轮武装已失效,多轮清理式压缩的全部后续调用被白拒(0.1.212 现场:一次成功大折叠后收尾的 4 次压缩连拒,模型只能反复换范围碰运气)。现在:nudge 真正送达("injected",口径不变)后开启 20 轮信用窗口(常量 NUDGE_CREDIT_ROUNDS),窗口内未注入轮不再解武;完成一次折叠即消耗信用(同一轮内的 loop 重发仍放行,下一轮边界失效);更新的 nudge 刷新窗口。requireRecommendation 范围门与硬溢出兑底折叠不受影响;开关默认关、关闭时字节级不变。拒收回执文案同步改为信用窗口口径(web 面板 i18n 同)。tests:tests/issue5683-forbid-unprompted-compress.test.ts 新增 4 例(窗口内隔轮履约放行/窗口末轮边界/消耗后同轮放行+下轮拒/新 nudge 刷新),既有 17 例不变全绿。
- **dsh 闸门:必然被上游拒绝的超窗请求不再裸发直连(#5613 安全网 ①②③)**:`none`/`threw` 归属车道(如经网关的 ds-harness-remote)上的超窗历史请求,旧行为二选一——要么按乐观的 bytes/4 估算判「不超窗」而直接裸发上游(实测计费偏差≈×1.14,估算系统性偏低;真实现场把 max_tokens 挤到 1、乃至上游 400 后整会话报废),要么即便超窗也没有任何持续留痕(只记第一行之后全静默)。现在双档计价:原有 bytes/4 下限继续标记「必然超窗」,另加 ×1.14 校准估算档(会话 ledger 实测偏差,常数 `CALIBRATED_TEXT_TOKEN_RATIO`,src/util.ts),过线即本地 422 拒绝而不是骑 #1117 去赌上游——小体量的合法直通语义(sidecar 短调用等)逐字节保留,未知尺寸流式体保持 fail-open。每次裸发 DIRECT 现在都带体积(`this body N B`)或「尺寸未知、超窗熔断未跑」明示,按 首次/状态变化/每第10次 落 durable 日志(bili.log,[dsh-client] 通道)——连续泄漏环路从此必有痕。tests/dsh-native.test.ts:#2924/#4068 双臂升级为双档断言+校准边界钉(3,508,768 B 直通 / 3,508,772 B 拒)、新增留痕节拍回归、#4111/#4912 谓词改名对齐。
- **全量压缩与 persona 文本漂移同轮发生时,主会话不再分叉到 `|sub:` 副车道(#5719)**:dsh 全量压缩 checkpoint(#3733 authored checkpoint,把整段历史头替换成一条 user 消息)与系统提示漂移(如 dsh 重启后 GUI 端口重分配写进 system prompt)落在同一轮时,既有的全部位置型 re-anchor 逃生结构性不可达——被记录的尾部按定义已被抹掉、incoming 比记录更短、压缩后首个模型步零 assistant——于是活着的会话确定性地分叉到 `<id>|sub:<fp16(新tag)>`:父车道记录冻结、副车道从零起步(resume-inheritance miss)、事故当天又触发 3 次再压缩 + 1 次 REFUSED turn + 2 次 max-tokens 截断。根因=判定器要求一种全量压缩按定义抹掉的字节级续接证据,而唯一能存活压缩的自足证明——bili 自己铸造的 checkpoint 内嵌的 `conv="<rawId>"` 自声明——从未被读取。现在 tagChanged 分支最前新增 E5 级:**第一条** user 消息携带我方 `\x3cbili-snapshot v1 …\x3e` 身份头且其 conv 与当前 id 逐字相等 → 直接 re-anchor 回主车道(record() 同步更新 tagHash,后续请求即普通 continue)。外部 persona 引用 checkpoint 的情形照旧分叉:要么根本到不了判定层(sideRequestLike 门,#4438),要么标记 conv 不符 / 不在第一条 user 消息。**旧行为→新行为**:该形状从「必然分叉」变为「带自声明时 re-anchor 回主车道」;无标记的形状逐字节不变(回归测试钉住每一既有 rung 的 reason 文案)。tests/issue5719-self-checkpoint-reanchor.test.ts(验收标准 1/2/3 + 四种 wire 形状 + foreign-quote 边界)。

Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed
| `compress.maxEstimateHoldRounds` | number | 2 | — | Backstop for the phantom-pressure guard (#5865 ruling): how many CONSECUTIVE estimate-grade rounds the pressure band may wait before firing on the estimate anyway. Capped so an upstream that never reports usage (anonymous zero-baseline forks, silent backends — where the local estimate is the only pressure signal) still gets automatic compression. 0 = no waiting at all. Only consulted while requireUsageSampleForPressure is on. |
| `compress.nudgeModelDecided` | boolean | off (unset) | — | Model-decided nudge timing (#2228): an armed tier-1 nudge first asks the model — via a short side call over the session's cached prefix — whether compressing NOW helps the current task. A strict-JSON "yes" injects an explicit directive with a program-finalized span; "no", a malformed answer, or a timeout injects nothing this round. EMERGENCY arms and tier≥2 distillation always keep the legacy advisory. Off unless explicitly enabled. |
| `compress.nudgeDecisionMaxTokens` | number | 200 | — | Output budget (tokens) of the model-decision side call used by nudgeModelDecided. Must be > 0. |
| `compress.requireNudge` | boolean | off (unset) | — | Forbid UNPROMPTED model-initiated compression (#5683): a compress call is refused unless a compression nudge actually reached the model in the current turn (advisory, decide-directive and emergency injections all arm; loop rounds of the same turn keep the arm, the next un-nudged turn disarms). Refusal sends the model an error receipt instead of folding; bili's own overflow backstop folds are exempt. For models that fold on their own (e.g. qwen 27b); can be scoped per provider/model. Off unless explicitly enabled. |
| `compress.requireNudge` | boolean | off (unset) | — | Forbid UNPROMPTED model-initiated compression (#5683): a compress call is refused unless a compression nudge credit is live — a delivered nudge (advisory, decide-directive and emergency injections all arm; "gated"/"vetoed"/"skipped" never) opens a 20-prepare window during which the model may come back and fold; a committed fold consumes the credit (it holds for the rest of the turn and dies at the next round), and a newer nudge refreshes the window (#5943). Refusal sends the model an error receipt instead of folding; bili's own overflow backstop folds are exempt. For models that fold on their own (e.g. qwen 27b); can be scoped per provider/model. Off unless explicitly enabled. |
| `compress.requireRecommendation` | boolean | off (unset) | — | Forbid OUT-OF-BOUNDS model-initiated compression (#5683): every submitted range must stay within what bili currently recommends folding — the same live compressible set the nudge text and acp_status show (this request's prepare-time offer when present, else a live recompute). Judgment is by COVERAGE: subdividing a recommended span passes, and messages already folded into active blocks (refolds updating an existing summary) are exempt. A range carrying any other live message is refused whole with an error receipt naming the offending span(s). Off unless explicitly enabled. |
| `compress.streamSummary` | boolean | false (unset) | — | Force preflight summarization to run as a streaming (SSE) call from the first attempt. The error-driven self-learn handles stream-mandating upstreams on its own (any 400 on a non-streaming summary triggers a one-shot SSE probe, #2494) but NEVER arms on gateway timeouts (e.g. Cloudflare HTTP 524): set this where such a gateway sits between bili and the origin, or simply to skip the one probe round-trip. |
| `compress.preserveRecentMessages` | number | 3 | — | The most recent messages stay soft-protected from folds. |
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@
| `compress.maxEstimateHoldRounds` | number | 2 | — | 幻影压力守卫的兜底(#5865 裁定):压力带最多连等多少轮估算读数就必须照估算动手。兜底保证从不回传计费的会话(匿名零基线 fork、静默后端——本地估算是它们唯一的压力信号)也能拿到自动压缩。0=完全不等待。仅在 requireUsageSampleForPressure 开启时生效。 |
| `compress.nudgeModelDecided` | boolean | off (unset) | — | 模型自决的压缩时机(#2228):tier-1 提醒触发时,先通过一次走会话缓存前缀的短 side call 问模型——以当前任务为前提,现在压缩是否划算。严格 JSON 的 "yes" 会注入带程序最终确定范围的明确压缩指令;"no"、格式错误或超时则本轮不注入任何内容。EMERGENCY 档与 tier≥2 蒸馏始终保留原有 advisory。默认关闭,需显式开启。 |
| `compress.nudgeDecisionMaxTokens` | number | 200 | — | nudgeModelDecided 所用模型决策 side call 的输出预算(token)。必须 > 0。 |
| `compress.requireNudge` | boolean | off (unset) | — | 禁止未提示的模型主动压缩(#5683):只有当前轮次压缩提醒真正送达模型时(advisory、模型自决指令、紧急提醒都算;"gated"/"vetoed"/"skipped" 不算)才允许 compress,否则拒绝并回错误回执;同一轮内的多次 loop 请求保持武装,下一个未提示轮次自动解除。bili 自己的溢出兜底折叠不受影响。针对会自行乱压的模型(如 qwen 27b),可按 provider/model 单独开启。默认关闭。 |
| `compress.requireNudge` | boolean | off (unset) | — | 禁止未提示的模型主动压缩(#5683):只有压缩提醒信用(nudge credit)存活时才允许 compress —— 提醒真正送达模型(advisory、模型自决指令、紧急提醒都算;"gated"/"vetoed"/"skipped" 不算)后开启 20 轮窗口,模型可在窗口内回来压缩;完成一次折叠即消耗信用(本轮内剩余调用仍放行,下一轮边界失效),更新的提醒刷新窗口(#5943)。拒绝时回错误回执而非折叠;bili 自己的溢出兜底折叠不受影响。针对会自行乱压的模型(如 qwen 27b),可按 provider/model 单独开启。默认关闭。 |
| `compress.requireRecommendation` | boolean | off (unset) | — | 禁止越界的模型主动压缩(#5683):提交的每个范围必须落在 bili 当前推荐折叠的集合内——即 nudge 文案与 acp_status 展示的同一份实时可压缩列表(有本轮 prepare 快照用快照,否则实时重算)。按「覆盖」判定而非精确相等:把推荐跨度拆小段通过;已折进活跃块的消息豁免(重折已有块更新摘要合法)。范围里含任何其他仍存活的消息则整体拒绝,回执点名越界跨度并指向 acp_status。默认关闭。 |
| `compress.streamSummary` | boolean | false (unset) | — | 强制 preflight 摘要从首次尝试起就走流式(SSE)请求。要求流式的上游现在由错误驱动自学习自动处理(非流式摘要的任何 400 都会触发一次性 SSE 探测,#2494),但网关超时(如 Cloudflare HTTP 524)永远无法触发自学习:在此类网关位于 bili 与源站之间时设置此项,或用于省去一次探测往返。 |
| `compress.preserveRecentMessages` | number | 3 | — | 最近的消息软保护、免于折叠。 |
Expand Down
30 changes: 18 additions & 12 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { performance } from "node:perf_hooks";
import { defaultPrompts, type CompressionCore, type Config, type PackSurface, type Prompts } from "acp-kernel";
import { conversationSignalAnthropic, conversationSignalGoogle, conversationSignalOpenai, conversationIdentityResponses, conversationSignalResponses, googleSystemText, type AnthropicRequestBody, type GoogleRequestBody, type OpenAIRequestBody, type ResponsesRequestBody } from "acp-kernel/wire";
import { resolveCompress, resolveCompressPrompts, resolveCompressSurfaceDetailed, resolveRequestConfig, type CompressSettings } from "../compress-settings.js";
import { storeUnpromptedGate } from "../unprompted-gate.js";
import { stampUnpromptedGate } from "../unprompted-gate.js";
import { FALLBACK_EFFECTIVE_WINDOW_FLOOR, findRoute, findRouteKey, lookupContextLimit, resolveConfiguredOutputLimit, resolveCompressProtocol, resolveDeclaredProtocol, resolveModelEntry, type ProxyOptions } from "../config.js";
import { resolveProxyDecision } from "../upstream-proxy.js";
import { contextFromRegistry, peekRegistryContext, peekRegistryOutputLimit, peekRegistryPriceProfile } from "../registry.js";
Expand Down Expand Up @@ -2915,17 +2915,23 @@ async function handleRequest(
degradeAvailable: opts.compress.injectTool && !knobNoInjectTool(),
}, log);
}
// #5683: stamp this round's compression-prompt facts for the
// unprompted/out-of-bounds gates (applyRanges). armed tracks the
// SAME post-gate delivery fact as the self-heal credit above —
// only an actually delivered nudge ("injected") arms; "gated"
// rounds held by the emergency backoff never did reach the model.
// Stamped on EVERY round (not just nudge-carrying ones) so an
// un-nudged round disarms a stale arm; loop re-requests within
// the same turn do not re-run prepare, so the arm persists across
// rounds of one turn and dies with the next un-nudged turn.
storeUnpromptedGate(session, {
armed: prepared.nudgeOutcome === "injected",
// #5683/#5943: stamp this round's compression-prompt facts for
// the unprompted/out-of-bounds gates (applyRanges) via the
// NUDGE CREDIT. A delivered nudge ("injected" — the SAME
// post-gate delivery fact as the self-heal credit above; "gated"
// rounds held by the emergency backoff never did reach the model
// and never arm) opens a window of NUDGE_CREDIT_ROUNDS prepares
// during which the model may come back and fold: real cleanup
// work spans several rounds (read ranges, write the summary,
// retry after a requireRecommendation refusal), and the old
// one-round arm refused exactly that. Un-nudged rounds no longer
// disarm immediately — the credit carries forward until it
// expires, is consumed by a committed fold, or is refreshed by
// a newer nudge. Loop re-requests within the same turn do not
// re-run prepare, so the arm still persists across rounds of one
// turn.
stampUnpromptedGate(session, {
nudgeInjected: prepared.nudgeOutcome === "injected",
requireNudge: preparedCs?.requireNudge === true,
requireRecommendation: preparedCs?.requireRecommendation === true,
});
Expand Down
4 changes: 4 additions & 0 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,10 @@ export type Session = {
* all-off default until the first round re-stamps, which is safe: no
* tool call can reach applyRanges before its own round's prepare. */
unpromptedGate?: UnpromptedGate;
/** #5943: per-session prepare counter that paces the nudge credit
* (src/unprompted-gate.ts stampUnpromptedGate). In-memory only —
* restarts reset the credit along with the gate. */
nudgeCreditRound?: number;
};
id: string;
/** Identity / descriptive metadata. Populated on first request. */
Expand Down
11 changes: 8 additions & 3 deletions src/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { attachSubagentSessions, subagentSessionNote, subagentSessionsOf, syncSu
import { METADATA_DRIFT_ESCALATED } from "./fold-reconcile.js";
import { safePrefix, safeSuffix, scrubLoneSurrogates } from "./text-safe.js";
import { applyConfiguredCompression } from "./external-summary-compress.js";
import { unpromptedGateOf } from "./unprompted-gate.js";
import { consumeNudgeCredit, unpromptedGateOf } from "./unprompted-gate.js";
import { describeUncoveredRuns, shortTokenCount, uncoveredHistoryRuns } from "./uncovered.js";

export type RewriteCtx = {
Expand Down Expand Up @@ -1046,8 +1046,8 @@ export function applyRanges(parsed: ReturnType<typeof parseCompressInput>, ctx:
// nudge channel itself is suppressed.
const gate = trackLoop ? unpromptedGateOf(ctx.session) : undefined;
if (gate?.requireNudge && !gate.armed) {
ctx.log("[acp-proxy: refused unprompted compress — no nudge was injected this turn (compress.requireNudge)]");
return compressResult("[Compression REFUSED: unprompted compression is disabled on this route (compress.requireNudge) — you may only call compress in a round where a compression nudge was actually injected, and no nudge accompanied this round. Continue the task without folding; when a nudge appears, follow its ranges.]", "refused", 0, "unprompted");
ctx.log("[acp-proxy: refused unprompted compress — no live nudge credit (compress.requireNudge, #5943)]");
return compressResult("[Compression REFUSED: unprompted compression is disabled on this route (compress.requireNudge) — you may only call compress while a compression nudge credit is live: it opens when a nudge is actually injected, stays valid for the following rounds until you fold something under it (which consumes it), and a newer nudge refreshes it. No live credit covers this round. Continue the task without folding; when a nudge appears, follow its ranges.]", "refused", 0, "unprompted");
}
let { ranges, diagnostics } = parsed;
if (ranges.length === 0) {
Expand Down Expand Up @@ -1285,6 +1285,11 @@ export function applyRanges(parsed: ReturnType<typeof parseCompressInput>, ctx:
return compressResult(receipt, "refused", 0, "gate:no-net-shrink");
}
ctx.session.state = res.state;
// #5943: a committed model-initiated fold spends its nudge credit —
// the arm holds for the rest of this turn (loop re-requests do not
// re-stamp) and dies at the next prepare. No-op when the gate is off
// or the fold was not credit-backed.
if (trackLoop && r.blocksCreated > 0) consumeNudgeCredit(ctx.session);
// #2627 backstop: no committed state may carry outbound-only turn-
// separator ids in coverage (a polluted child would otherwise re-
// poison higher folds via effectiveMessageIds inheritance). Runs
Expand Down
Loading
Loading