From 23959f7e3b0418f8726bd82579453821ea19b03e Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 16:10:15 +0800 Subject: [PATCH 01/11] fix(guardrail): repetition guard refuses once at the abort threshold and only kills the turn on the repeat after it (#5225) --- CHANGELOG.md | 1 + CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- LIFECYCLE.md | 2 ++ src/agent/tool-guardrails.ts | 39 +++++++++++++++++----- tests/tool-guardrails-pi.test.ts | 47 +++++++++++++++++++++------ website/config-reference/process.yaml | 4 +-- 7 files changed, 74 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01669fa743..aab55ebbeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ## [Unreleased] ### Fixed +- **重复调用守卫不再一口咬死合法等待/轮询(#5225)**:此前同一工具、同样参数连发到第 5 次时,守卫在调用执行前就掐掉整个回合——调试器等待(`kd_wait` 10 秒一次)、omp 任务轮询这类「参数本来就不变、结果随外部状态变化」的合法调用被整段杀掉(Pi Codemode、omp 两起真实报告,等待还没到期)。现在升级为三段式:连续第 3、4 次照旧随结果附警告;第 5 次改为只拒绝这一次调用并发出明确的最后警告(回合保留——模型此时把多次短等待合并成一次更长等待、或换参数换工具,计数立即重置);被拒之后仍一字不差地重发同样调用,才终止整个回合。真死循环保护不受削弱(最多多烧一次调用)。同时修正提示文案里两处误导说法(「字节级相同」实为规范化后相同;「同样的调用不可能有新结果」对轮询类工具不成立)。tests/tool-guardrails-pi.test.ts 更新升级链断言并新增合法轮询逃生回归。 - **两份安装(全局树 + 宿主自带副本)差一个自动更新版本时不再互相卡死、流量裸奔(#4125)**:机器上 bili 本来就有两份合法安装——npm 全局树和宿主管理器自带的独立副本,各由各的更新节奏往前走。当全局树领先一个版本时:宿主插件想接上已占端口的旧进程 →「代码指纹不一致」拒绝采纳(#1225);旧进程置换只敢碰更老的邻居,而占位者是更新的那份,永远够不着(#3544);新拉起的子进程一绑定端口就撞口、向这个谁也不敢采纳的持有者让位退出——三条路全堵死,整条车道直接连模型(无压缩),直到有人整机重启对齐版本。修复三面一起落:①拉起子进程时把自己的代码摘要随环境传下去(`BILI_SPAWN_FINGERPRINT`,64 位 hex sha256;非法/缺失回落本地重算,沿用 #1225「陌生进程自称身份不采信」原则)——「同一构建」从此比字节不比口号;②宿主侧:候选者因指纹不一致被拒之前,先问一次**活着的**持有者真实版本号——严格更新、同车道、同形状、健康应答为证 → 采纳骑上而不是拒掉(跨车道和用户自己起的实例仍一律不碰,它们没有 bili 替身可退路);③子进程侧:确认端口被「严格更新的同车道同形状存活实例」占住时不再逐级换口(那只会造出第二个没人路由到的影子实例),改走既有的采纳信号退出(exit 3),由宿主骑上更新版。手动启动与升级替换流程语义完全不变。`tests/issue4125-two-install-deadlock.test.ts`(9 例)+ listen-policy/issue3654 判定表扩展钉住全部三面。 - **压缩「总是失败、要重试很多次才成功」的活锁(#4521)**:长会话里模型重报已被折叠覆盖的区间、或把 endId 猜到尚未发号的 ref 之上、或整段落在保护区,这些「其实无事可做」的请求一律被判 FAILED——原子批整体拒绝、断路器计数、模型照失败提示再猜再试,形成「失败→重试→再失败」循环(实测会话 01a18a4d 在 20:09 连续 4 次 FAILED 才成功)。现在五处修正:①endId 越界自动钳到最高已发 ref(警告提示,不整批拒);②区间全覆盖既有活动块=幂等 no-op 成功收据(`noop: true`,提示用 bN..bM 改写而非重发原文),不失败、不进断路器;③纯保护区区间同样 no-op(警告明说勿重发);④保护区 fatal 不再中止整批,只降级该区间;⑤新增 armed-but-silent 状态行:tier 级 nudge 已备好但本轮不投横幅时(退避/节拍/模型定时),以临时 user 消息刷新「最高已发 ref + 当前可压区间」,模型不再凭记忆猜号;全新会话的低于阈值计划保持完全静默(#196 域隔离、#3910 基线不破坏)。 - **自动升级换代旋转的「假存活」误判(#5167)**:旧实例接受 `/__bili/shutdown` 后毫秒级就关 listener(口已释放),但存量 keep-alive 连接照常应答——这是排水的本意(#3890 后最坏 (1+10)×10s 才退进程)。而两条旋转等待(launcher `rotateStalePredecessor` 每 200ms `fetchHealthInfo`、dsh `rotatePinnedStaleProxy` 每 500ms `fetchProxyVersion`)都用全局 fetch 的连接池轮询,轮询节拍远小于服务端 5s keepAliveTimeout,永远落在预热过的池化 socket 上 → 把「正在排水」误判为「没退出」,12s 预算耗尽得到假阴性:dsh 宿主 attach-anyway 骑上将被强退的旧实例、launcher 回退 spawn 阶梯,新旧两进程同写一份 machine-global 会话存储(index.db 双写横幅、#5046 SQLITE_BUSY、JSON 状态互踩)。修复:旋转等待的全部请求(含 shutdown POST)改带 `Connection: close` 每轮全新连接,「应答」重新等于「listener 还在收新连接」=真正的口释放信号;同步修正 12s 预算的过时注释(它只需覆盖 shutdown 请求被处理的延迟,不需覆盖进程退出)。`tests/issue5167-drain-aware-rotation.test.ts` 用真实排水 http 服务器(无 fetch mock、单连接 dispatcher 钉住池化拓扑)双向钉住:排水中的 resident 必须判为已释放,真占口不退的 holder 仍走超时回退。 diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 1d7d021264..1889614b79 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -181,7 +181,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `guardrails` | object | {} (all defaults) | — | Guardrails: tool-output guardrails for the pi/omp plugin bundles (#3066) plus the proxy-side text-run stream guard (#3406). | | `guardrails.bashTimeout` | number | 60 | BILI_GUARDRAIL_BASH_TIMEOUT | Seconds injected as the bash tool's timeout when the model omits it (#3066 owner intent, re-affirmed #3366: an unsupervised bash call could hang a pi session for a whole day — the host schema provides no default). Set N to tune, 0 to disable injection (pi-native no-default). | | `guardrails.maxOutputBytes` | number | 50000 | BILI_GUARDRAIL_MAX_OUTPUT_BYTES | Combined text-output byte cap per tool result in the pi/omp plugin (0 disables the cap). Over-cap output is truncated head-first with a notice pointing at the host-saved full output. | -| `guardrails.repetition` | boolean | true | BILI_GUARDRAIL_REPETITION | Identical-call loop-breaker for the pi/omp plugin (warn at 3, abort at 5 consecutive byte-identical calls). false / env 0 disables it. | +| `guardrails.repetition` | boolean | true | BILI_GUARDRAIL_REPETITION | Identical-call loop-breaker for the pi/omp plugin: warns from the 3rd consecutive identical call, issues ONE final refusal (that call is refused but the turn stays alive) at the 5th so a legitimate wait/poll can still switch to a longer wait, and aborts the turn only if the identical call is repeated again after that refusal (#5225). false / env 0 disables it. | | `guardrails.textRunThreshold` | number | 200 | BILI_GUARDRAIL_TEXT_RUN_THRESHOLD | Single-codepoint repetition breaker over decoded model text on the response stream (#3260; kill switch added by #3406 item 1 after the #3331 review). Trips at N consecutive identical codepoints - legit prose/code stays far below the 200 default, a symbol-loop model does not. Set N to tune, 0 (or negative) to disable: legit long same-char output (code comment separators, ASCII rules) is then never cut mid-stream. The thinking/reasoning channels sit inside this lane too. | | `persist` | object | {} (all defaults) | — | Session persistence to disk under the XDG state dir. | | `persist.enabled` | boolean | true | BILI_PERSIST | Master switch for writing session records to disk (0/false turns it off). | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 50a1435f14..470e1c5a23 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -181,7 +181,7 @@ | `guardrails` | object | {} (all defaults) | — | 守卫集合:pi/omp 插件的工具输出守卫(#3066)及代理侧流式 text-run 守卫(#3406)。 | | `guardrails.bashTimeout` | number | 60 | BILI_GUARDRAIL_BASH_TIMEOUT | 模型未写 timeout 时注入到 bash 工具的秒数(#3066 owner 有意为之,#3366 重申:无人看管的 bash 会把 pi 会话挂死一整天——宿主 schema 本身无默认值)。设 N 调整秒数,设 0 关闭注入(恢复 pi 原生行为)。 | | `guardrails.maxOutputBytes` | number | 50000 | BILI_GUARDRAIL_MAX_OUTPUT_BYTES | pi/omp 插件中每个工具结果的文本输出合计字节上限(0 禁用)。超限输出从头截断并附指向宿主已存完整输出的提示。 | -| `guardrails.repetition` | boolean | true | BILI_GUARDRAIL_REPETITION | pi/omp 插件的同一调用循环破除器(连续 3 次警告、5 次中止,按字节全同判定)。false 或 env 0 关闭。 | +| `guardrails.repetition` | boolean | true | BILI_GUARDRAIL_REPETITION | pi/omp 插件的同一调用循环破除器:连续第 3 次起随结果附警告;第 5 次只拒绝这一次调用并发出明确的最后警告(回合保留,合法的等待/轮询此时可改成一次更长的等待继续);被拒之后仍一字不差地重发同样调用才终止整个回合(#5225)。false 或 env 0 关闭。 | | `guardrails.textRunThreshold` | number | 200 | BILI_GUARDRAIL_TEXT_RUN_THRESHOLD | 响应流上解码后模型文本的单字符重复破除器(#3260;#3331 审查后由 #3406 第 1 项补上开关)。连续 N 个相同码点即触发——正常文本远低于默认 200,符号循环的模型会撞上。设 N 调整阈值,设 0(或负数)关闭:合法的长同字符输出(代码注释分隔线、ASCII 分隔线)不会再被中途掐断。thinking/reasoning 通道也在该守卫内。 | | `persist` | object | {} (all defaults) | — | 会话落盘持久化(XDG state 目录之下)。 | | `persist.enabled` | boolean | true | BILI_PERSIST | 会话记录落盘总开关(0/false 关闭)。 | diff --git a/LIFECYCLE.md b/LIFECYCLE.md index 3f09bd7716..a167ade58f 100644 --- a/LIFECYCLE.md +++ b/LIFECYCLE.md @@ -70,6 +70,7 @@ |------|-----------| | `BILI_LAUNCH_TOKEN` | launch 令牌(spawn 时注入;日志中脱敏) | | `BILI_PARENT_PID` | owner-pid 看门狗(会话生命周期归属) | +| `BILI_SPAWN_FINGERPRINT` | spawner 自身代码 sha256(hex64;子进程校验后信任,否则本地重算;#4125) | | `BILI_STRICT_PORT` | `=1` claude SessionStart hook 退出端口重试(#964) | | `BILI_OPENCODE_ACP_SPEC` | 剥离版 ACP spec 临时配置**文件路径**提示 | | `BILI_LAUNCHER_LANE` | lane 身份戳(attach 时比对归属) | @@ -125,6 +126,7 @@ | `BILI_SESSION_GC_INTERVAL_MS` / `BILI_SESSION_GC_MAX_AGE_DAYS` / `BILI_SESSION_GC_MAX_TOKENS` | 会话 GC 参数(默认 1h / 7d / 1M tokens) | | `BILI_SESSION_RESIDENT_MAX_BYTES` | sessions.residentMaxBytes,512 MiB 软上限(#2803) | | `BILI_SESSION_RESIDENT_HARD_MAX_BYTES` | sessions.hardMaxBytes,单会话驻留字节硬上限(#4788 D1-A);默认同 residentMaxBytes(512 MiB),设 0 关闭——补软上限对唯一活跃会话的盲区 | +| `BILI_SESSION_CONTENT_STORE_PIN` | `=1/true` 保持单会话 CCR 内容存储(byRef/byHash 原文)常驻内存不折叠(#4788 phase 2 / #3916-E;首次触摸时从 unified ccr 镜像或 .content-store.json 侧车重建);缺省/0/false = 落盘后折叠(默认) | | `BILI_SESSION_WARM_MAX_BYTES` | warm 解码字节上限,64 MiB(#2803) | | `BILI_PERSIST` | `=0` 关闭持久化(ephemeral/test) | | `BILI_PERSIST_DEBOUNCE_MS` | persist.debounceMs,500 | diff --git a/src/agent/tool-guardrails.ts b/src/agent/tool-guardrails.ts index e969c00e3e..708910b016 100644 --- a/src/agent/tool-guardrails.ts +++ b/src/agent/tool-guardrails.ts @@ -145,12 +145,18 @@ function formatBytes(n: number): string { return n >= 1024 ? `${(n / 1024).toFixed(1)}KB` : `${n}B`; } -// --- Generic tool-call repetition guard (ported from bcp #308) --- +// --- Generic tool-call repetition guard (ported from bcp #308; escalation +// retuned by #5225) --- // A greedy small model can re-emit the same (assistant -> toolResult) pair every -// turn; token penalties can't break that attractor, so we key on byte-for-byte -// identity of consecutive calls. At `warn` append a strong warning to the -// matching toolResult; at `abort` refuse the call (block) and abort the turn. -// Any arg/tool change resets the run. +// turn; token penalties can't break that attractor, so we key on canonical-form +// identity of consecutive calls (argument keys sorted). Escalation (#5225): +// warnings up to the `warn` threshold; at the `abort` threshold REFUSE that one +// call with an explicit final warning while keeping the turn alive (a model +// mid-legit-poll can still react — any argument/tool change resets the run); +// ONLY the next identical call refuses AND aborts the turn. The old single-step +// warn->kill aborted legitimate bounded polling (wait tools re-issue identical +// args by design; the result changes with external state, the arguments do not) +// before its deadline. Any arg/tool change resets the run. export function canonicalStringify(value: unknown): string { if (value === null || value === undefined || typeof value !== "object") { try { @@ -177,7 +183,7 @@ export function repetitionFingerprint(toolName: string, input: unknown): string } } -type RepetitionAction = "none" | "warn" | "abort"; +type RepetitionAction = "none" | "warn" | "final-refuse" | "abort"; interface RepetitionDecision { action: RepetitionAction; count: number; @@ -197,7 +203,8 @@ export class RepetitionTracker { this.count = 1; } let action: RepetitionAction = "none"; - if (this.count >= this.thresholds.abort) action = "abort"; + if (this.count > this.thresholds.abort) action = "abort"; + else if (this.count === this.thresholds.abort) action = "final-refuse"; else if (this.count >= this.thresholds.warn) action = "warn"; return { action, count: this.count, fingerprint: fp, toolName }; } @@ -208,11 +215,15 @@ export class RepetitionTracker { } function buildRepetitionWarnNotice(toolName: string, count: number): string { - return `\n\n[ACP guardrail: you have issued ${count} CONSECUTIVE identical \`${toolName}\` calls (name + arguments byte-for-byte identical). Re-running the exact same call will not produce a new result. STOP issuing this identical call — change your approach, change the arguments, or stop and report to the user.]`; + return `\n\n[ACP guardrail: WARNING — you have issued ${count} CONSECUTIVE identical \`${toolName}\` calls (same name, same arguments). Repeating an identical call usually produces nothing new; if you are deliberately waiting/polling external state, one LONGER wait beats repeated short polls. Continuing the identical call escalates to a hard refusal before the turn is aborted.]`; +} + +function buildRepetitionFinalRefuseNotice(toolName: string, count: number): string { + return `[ACP guardrail: REFUSED — you issued ${count} consecutive identical \`${toolName}\` calls (same name, same arguments). This call was refused and NOT executed. FINAL WARNING: if the very next call is identical again, the entire turn will be ABORTED. If you were waiting/polling external state, issue ONE longer wait instead (larger duration argument) or stop and report to the user. Changing the tool or ANY argument restarts the count.`; } function buildRepetitionAbortNotice(toolName: string, count: number): string { - return `[ACP guardrail: BLOCKED — you issued ${count} consecutive identical \`${toolName}\` calls (byte-for-byte identical arguments). This call was refused and NOT executed. You MUST change strategy: use different arguments, a different tool, or stop and report to the user. Do not re-issue the identical call. The turn has been aborted.`; + return `[ACP guardrail: BLOCKED — you issued ${count} consecutive identical \`${toolName}\` calls (same name, same arguments) despite the final refusal. This call was refused and NOT executed. You MUST change strategy: use different arguments, a different tool, or stop and report to the user. Do not re-issue the identical call. The turn has been aborted.`; } export interface GuardrailOptions { @@ -259,6 +270,16 @@ export function wireToolGuardrails(pi: ExtensionAPI, opts: GuardrailOptions = {} trackers.set(sid, tracker); } const decision = tracker.note(e.toolName, e.input); + if (decision.action === "final-refuse") { + const msg = buildRepetitionFinalRefuseNotice(decision.toolName, decision.count); + if (ctx?.ui?.notify) ctx?.ui?.notify(`[ACP] ${msg}`, "warning"); + // Deliberately NO ctx.abort() here: the refusal itself IS the final + // warning. The model sees this text and can still react (change + // args / pick another tool => the run resets). Only the NEXT + // identical call kills the turn (#5225: legitimate bounded polling + // must survive the warning stage). + return { block: true, reason: msg }; + } if (decision.action === "abort") { const msg = buildRepetitionAbortNotice(decision.toolName, decision.count); if (ctx?.ui?.notify) ctx?.ui?.notify(`[ACP] ${msg}`, "warning"); diff --git a/tests/tool-guardrails-pi.test.ts b/tests/tool-guardrails-pi.test.ts index 61cf4b6495..84b988752c 100644 --- a/tests/tool-guardrails-pi.test.ts +++ b/tests/tool-guardrails-pi.test.ts @@ -271,13 +271,14 @@ test("repetitionFingerprint distinguishes different tools with identical args", assert.notEqual(repetitionFingerprint("read", { path: "/x" }), repetitionFingerprint("bash", { path: "/x" })); }); -test("RepetitionTracker escalates none -> warn -> abort by consecutive count", () => { +test("RepetitionTracker escalates none -> warn -> final-refuse -> abort (#5225)", () => { const t = new RepetitionTracker({ warn: 3, abort: 5 }); assert.equal(t.note("x", {}).action, "none"); assert.equal(t.note("x", {}).action, "none"); assert.equal(t.note("x", {}).action, "warn"); assert.equal(t.note("x", {}).action, "warn"); - assert.equal(t.note("x", {}).action, "abort"); + assert.equal(t.note("x", {}).action, "final-refuse", "the 5th identical call is the single live refusal, not yet the kill"); + assert.equal(t.note("x", {}).action, "abort", "only a repeat AFTER the final refusal kills the turn"); assert.equal(t.note("x", {}).action, "abort"); }); @@ -346,17 +347,38 @@ test("repetition guard queues a warning at warn=3 (default) without blocking", ( assert.match(t, /acp_status/); }); -test("repetition guard blocks and aborts at abort=5 (default)", () => { +test("repetition guard refuses once at abort=5 and only aborts on the repeat after it (#5225)", () => { const w = wireRepetition(); for (const id of ["k1", "k2", "k3", "k4"]) { assert.equal(w.call(statusCall(id)), undefined, "below abort must not block"); } const fifth = w.call(statusCall("k5")) as { block?: boolean; reason?: string }; - assert.equal(fifth?.block, true, "5th identical call must be blocked"); - assert.match(fifth?.reason ?? "", /BLOCKED/); - assert.equal(w.ctx.abortCalls, 1, "turn must be aborted exactly once"); - const sixth = w.call(statusCall("k6")) as { block?: boolean }; - assert.equal(sixth?.block, true, "still blocked after abort"); + assert.equal(fifth?.block, true, "5th identical call must be refused (not executed)"); + assert.match(fifth?.reason ?? "", /FINAL WARNING/); + assert.match(fifth?.reason ?? "", /refused and NOT executed/i); + assert.equal(w.ctx.abortCalls, 0, "the refusal must NOT kill the turn — the model gets one live chance to change approach"); + const sixth = w.call(statusCall("k6")) as { block?: boolean; reason?: string }; + assert.equal(sixth?.block, true, "a repeat after the final refusal is blocked"); + assert.match(sixth?.reason ?? "", /BLOCKED/); + assert.equal(w.ctx.abortCalls, 1, "turn must be aborted exactly once, at the repeat after the final refusal"); + const seventh = w.call(statusCall("k7")) as { block?: boolean }; + assert.equal(seventh?.block, true, "still blocked after abort"); +}); + +test("#5225: legit bounded polling survives the final refusal and escapes via changed arguments", () => { + const w = wireRepetition(); + // kd_wait-shaped polling: same name+args every cycle while the target runs. + const poll = (id: string) => ({ type: "tool_call", toolName: "mcp__kernel_debug__kd_wait", toolCallId: id, input: { seconds: 10 } }); + for (let i = 1; i <= 4; i++) assert.equal(w.call(poll(`p${i}`)), undefined, `poll ${i} executes`); + const fifth = w.call(poll("p5")) as { block?: boolean }; + assert.equal(fifth?.block, true, "5th identical poll is refused"); + assert.equal(w.ctx.abortCalls, 0, "but the turn survives — this is the documented warning stage"); + // The model reacts: ONE longer wait (different args) resets the run... + const longer = { type: "tool_call", toolName: "mcp__kernel_debug__kd_wait", toolCallId: "p6", input: { seconds: 30 } }; + assert.equal(w.call(longer), undefined, "changed arguments reset the run and execute"); + // ...and going back to the old args starts a FRESH count. + assert.equal(w.call(poll("p7")), undefined, "back to the old args restarts the count at 1"); + assert.equal(w.ctx.abortCalls, 0, "legit polling never reaches the kill without ignoring the final refusal"); }); test("repetition guard resets the run when arguments change", () => { @@ -401,8 +423,13 @@ test("repetition guard honors custom warn/abort thresholds", () => { assert.equal(w.call(statusCall("t2")), undefined); const res2 = w.result(statusResult("t2")); assert.ok(hasContent(res2), "warn fires at custom warn=2"); - const third = w.call(statusCall("t3")) as { block?: boolean }; - assert.equal(third?.block, true, "abort fires at custom abort=3"); + const third = w.call(statusCall("t3")) as { block?: boolean; reason?: string }; + assert.equal(third?.block, true, "final refusal fires at custom abort=3"); + assert.match(third?.reason ?? "", /FINAL WARNING/); + assert.equal(w.ctx.abortCalls, 0, "custom-abort final refusal keeps the turn alive (#5225)"); + const fourth = w.call(statusCall("t4")) as { block?: boolean }; + assert.equal(fourth?.block, true, "a repeat after the final refusal kills the turn"); + assert.equal(w.ctx.abortCalls, 1); }); test("#3170: all three ctx handlers tolerate a missing ctx (no throw, block still enforced)", () => { diff --git a/website/config-reference/process.yaml b/website/config-reference/process.yaml index 61bea0bf2b..6e278f1c12 100644 --- a/website/config-reference/process.yaml +++ b/website/config-reference/process.yaml @@ -209,8 +209,8 @@ entries: default: "true" env: BILI_GUARDRAIL_REPETITION group: process - desc_en: "Identical-call loop-breaker for the pi/omp plugin (warn at 3, abort at 5 consecutive byte-identical calls). false / env 0 disables it." - desc_zh: "pi/omp 插件的同一调用循环破除器(连续 3 次警告、5 次中止,按字节全同判定)。false 或 env 0 关闭。" + desc_en: "Identical-call loop-breaker for the pi/omp plugin: warns from the 3rd consecutive identical call, issues ONE final refusal (that call is refused but the turn stays alive) at the 5th so a legitimate wait/poll can still switch to a longer wait, and aborts the turn only if the identical call is repeated again after that refusal (#5225). false / env 0 disables it." + desc_zh: "pi/omp 插件的同一调用循环破除器:连续第 3 次起随结果附警告;第 5 次只拒绝这一次调用并发出明确的最后警告(回合保留,合法的等待/轮询此时可改成一次更长的等待继续);被拒之后仍一字不差地重发同样调用才终止整个回合(#5225)。false 或 env 0 关闭。" - key: guardrails.textRunThreshold type: number default: "200" From 2b93ba50d8279b5ade9f1169f2c8e0abfe03094a Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 16:12:00 +0800 Subject: [PATCH 02/11] fix(tests): #4313 stubs accept ts-stamped message literals (inherited tsc red, c38777fd2) --- tests/storage-unified.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/storage-unified.test.ts b/tests/storage-unified.test.ts index d786d238de..3c5908f29a 100644 --- a/tests/storage-unified.test.ts +++ b/tests/storage-unified.test.ts @@ -875,7 +875,7 @@ test("#4313: ingest stamps ts from CoreMessage.ts; re-ingest never overwrites it const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-unified-v10b-")); const store = UnifiedStore.open(path.join(dir, "index.db")); try { - const stub = (id: string, msgs: CoreMessage[]): LegacySessionLike => ({ + const stub = (id: string, msgs: (CoreMessage & { ts?: number })[]): LegacySessionLike => ({ id, createdAt: 1700000000000, lastSeen: 1700000001000, @@ -912,7 +912,7 @@ test("#4313: fork clone copies ts verbatim (inherited ledger rows keep their sta const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-unified-v10c-")); const store = UnifiedStore.open(path.join(dir, "index.db")); try { - const stub = (id: string, msgs: CoreMessage[]): LegacySessionLike => ({ + const stub = (id: string, msgs: (CoreMessage & { ts?: number })[]): LegacySessionLike => ({ id, createdAt: 1700000000000, lastSeen: 1700000001000, From 73e6d2bae37e06ea56f2e9bd38cd80c41e1b2f2d Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 16:51:02 +0800 Subject: [PATCH 03/11] fix(gate): make CodexWindowSource module-local (#5243 export never consumed; master self-red on unused-exports) --- src/codex-models.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/codex-models.ts b/src/codex-models.ts index 45ee8b588e..ff8fd5bbf1 100644 --- a/src/codex-models.ts +++ b/src/codex-models.ts @@ -88,8 +88,9 @@ function positiveWindow(value: unknown): number | undefined { /** #5243: which surface produced a codex-aligned window — named in the clamp * log so "window clamped" stops claiming client metadata when no client - * metadata existed. */ -export type CodexWindowSource = + * metadata existed. Module-local: never imported elsewhere (unused-exports + * gate would flag a bare export). */ +type CodexWindowSource = | "client-metadata" | "codex-catalog" | "codex-models-cache" From a4bbf470f6813a78161ae12b47efe4295d35551e Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 16:51:02 +0800 Subject: [PATCH 04/11] docs: regenerate config artifacts after rebase onto master (#5319 builtin chat pack) --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 1889614b79..95f22352c3 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -275,7 +275,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.maxSummaryLength` | number | kernel 20000 | — | Hard character cap on ONE generated summary; longer replies are rejected whole (no truncation, no retry). External summarizers are told this exact cap up front (#3635). 0 = unbounded. | | `compress.minSummaryLength` | number | kernel 50 | — | Character floor for generated summaries; shorter replies are rejected whole. 0 = disabled. External summarizers are held to the same floor (#3635). | | `compress.reconcile` | "off" \| "warn" \| "repair" | "repair" | BILI_FOLD_RECONCILE | Reconcile folded state when the client rewinds or rewrites history between turns. | -| `compress.promptPack` | string (builtin: "default", "lean", "chat") | builtin "default" | — | Compression prompt pack, resolved project pack → user pack → shipped pack → builtin; not gated by acknowledgePromptsRisk. | +| `compress.promptPack` | string (builtin: "default", "lean") | builtin "default" | — | Compression prompt pack, resolved project pack → user pack → builtin; not gated by acknowledgePromptsRisk. | | `compress.tiers` | boolean | true | — | Tiered T1→T3 distillation spreads folding cost across generations. | | `compress.protectedTools` | string[] | none | — | Hard exclusion across all history: results of listed tools never fold. Path patterns (skill/) select skills by name (#1947). | | `compress.protectedLatestTools` | string[] | none | — | Protects only the LATEST instance of cumulative-snapshot tools whose newest result supersedes older ones (e.g. todo lists). Path patterns keep the latest instance per skill (skill/*, #1947). | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 470e1c5a23..5fe979e7f3 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -275,7 +275,7 @@ | `compress.maxSummaryLength` | number | kernel 20000 | — | 单条生成摘要的硬字符上限;超长的回复被整段拒绝(不截断、不重试)。外部摘要模型会被提前告知这个确切上限(#3635)。0 = 不限制。 | | `compress.minSummaryLength` | number | kernel 50 | — | 生成摘要的字符下限;过短的回复被整段拒绝。0 = 禁用。外部摘要模型受同一下限约束(#3635)。 | | `compress.reconcile` | "off" \| "warn" \| "repair" | "repair" | BILI_FOLD_RECONCILE | 客户端在轮次之间回退或改写历史时校准已折叠状态。 | -| `compress.promptPack` | string (builtin: "default", "lean", "chat") | builtin "default" | — | 压缩提示词包,按 项目包 → 用户包 → 随包附带(chat)→ 内置 解析;不受 acknowledgePromptsRisk 门控。 | +| `compress.promptPack` | string (builtin: "default", "lean") | builtin "default" | — | 压缩提示词包,按 项目包 → 用户包 → 内置 解析;不受 acknowledgePromptsRisk 门控。 | | `compress.tiers` | boolean | true | — | T1→T3 分级蒸馏把折叠成本摊到多代。 | | `compress.protectedTools` | string[] | none | — | 全历史硬排除:列出工具的结果永不折叠。路径模式(skill/)可按名指定 skill(#1947)。 | | `compress.protectedLatestTools` | string[] | none | — | 只保护累积快照类工具「最新一次」实例(新结果覆盖旧结果的工具,如 todo 列表)。路径模式按 skill 分组各保最新(skill/*,#1947)。 | From 892a378ab6e2835641a36fa8a57092e464f15b30 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 17:11:14 +0800 Subject: [PATCH 05/11] test(#5103): pin the updated refusal remedy (#4125 newer-target auto-adopt wording) --- tests/issue5103-startup-recovery-visibility.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/issue5103-startup-recovery-visibility.test.ts b/tests/issue5103-startup-recovery-visibility.test.ts index 2f59fc183b..3fce3ce791 100644 --- a/tests/issue5103-startup-recovery-visibility.test.ts +++ b/tests/issue5103-startup-recovery-visibility.test.ts @@ -102,7 +102,12 @@ test("#5103: explicit attachUrl target found but build-incompatible — refusal const notice = stderrLines.find((l) => l.includes(`explicit attach target ${ORIGIN}`)); assert.ok(notice, "the visible channel must name the refused explicit target"); assert.ok(notice!.includes("code-fingerprint-mismatch"), notice); - assert.ok(notice!.includes("restart the host once its copy converges to the same version"), notice); + // #4125 follow-up: newer same-lane targets attach automatically, so the + // remedy now spells out that reaching this message means the target + // reports the SAME or an OLDER build — aligning the installs (or stopping + // the target) is the way out. + assert.ok(notice!.includes("A target that reports a STRICTLY NEWER build attaches automatically"), notice); + assert.ok(notice!.includes("align the two installs"), notice); assert.ok(diags.some((d) => d.includes(`explicit attach target ${ORIGIN}`)), "the durable log gets the same line"); }); From 1f209ff8955325a364fc9c3ce0298fbb81655eee Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 17:41:07 +0800 Subject: [PATCH 06/11] fix(store): adopt survives an unrecoverable lazy content-store prev (#4788 phase-2 side effect) --- CHANGELOG.md | 1 + src/store.ts | 21 ++++++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aab55ebbeb..39221e0d53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ## [Unreleased] ### Fixed +- **磁盘写入临时失败后,会话不再陷入「之后每次触碰都硬报错」(#4788 phase-2 副作用)**:phase 2 的闲时内存折叠会在一次成功保存之后,把内存里的原始内容降成「用时从磁盘重新加载」的惰性代理。若此时盘上信封恰好写不进/已损坏(瞬时写入失败或损坏),下一回合采纳内核新内容时要先读旧内容做差集——按 #2674 纪律它会抛「无法重新物化、拒绝瘦身视图」——整个采纳直接炸掉:新引用记不进去,会话从此每次访问都报 `[persist] resident content store … could not be re-materialized`,直到人工修好文件。现在旧内容重加载失败(镜像与 sidecar 双双已不可读)时按「无存活旧引用」处理——旧字节那时本已不可恢复——新库照样完整采纳、标脏并在下次保存落盘,会话随瞬时故障消除而恢复而不是持续报错。tests/store.test.ts 的 flushAll 瞬时失败重试回归恢复绿。 - **重复调用守卫不再一口咬死合法等待/轮询(#5225)**:此前同一工具、同样参数连发到第 5 次时,守卫在调用执行前就掐掉整个回合——调试器等待(`kd_wait` 10 秒一次)、omp 任务轮询这类「参数本来就不变、结果随外部状态变化」的合法调用被整段杀掉(Pi Codemode、omp 两起真实报告,等待还没到期)。现在升级为三段式:连续第 3、4 次照旧随结果附警告;第 5 次改为只拒绝这一次调用并发出明确的最后警告(回合保留——模型此时把多次短等待合并成一次更长等待、或换参数换工具,计数立即重置);被拒之后仍一字不差地重发同样调用,才终止整个回合。真死循环保护不受削弱(最多多烧一次调用)。同时修正提示文案里两处误导说法(「字节级相同」实为规范化后相同;「同样的调用不可能有新结果」对轮询类工具不成立)。tests/tool-guardrails-pi.test.ts 更新升级链断言并新增合法轮询逃生回归。 - **两份安装(全局树 + 宿主自带副本)差一个自动更新版本时不再互相卡死、流量裸奔(#4125)**:机器上 bili 本来就有两份合法安装——npm 全局树和宿主管理器自带的独立副本,各由各的更新节奏往前走。当全局树领先一个版本时:宿主插件想接上已占端口的旧进程 →「代码指纹不一致」拒绝采纳(#1225);旧进程置换只敢碰更老的邻居,而占位者是更新的那份,永远够不着(#3544);新拉起的子进程一绑定端口就撞口、向这个谁也不敢采纳的持有者让位退出——三条路全堵死,整条车道直接连模型(无压缩),直到有人整机重启对齐版本。修复三面一起落:①拉起子进程时把自己的代码摘要随环境传下去(`BILI_SPAWN_FINGERPRINT`,64 位 hex sha256;非法/缺失回落本地重算,沿用 #1225「陌生进程自称身份不采信」原则)——「同一构建」从此比字节不比口号;②宿主侧:候选者因指纹不一致被拒之前,先问一次**活着的**持有者真实版本号——严格更新、同车道、同形状、健康应答为证 → 采纳骑上而不是拒掉(跨车道和用户自己起的实例仍一律不碰,它们没有 bili 替身可退路);③子进程侧:确认端口被「严格更新的同车道同形状存活实例」占住时不再逐级换口(那只会造出第二个没人路由到的影子实例),改走既有的采纳信号退出(exit 3),由宿主骑上更新版。手动启动与升级替换流程语义完全不变。`tests/issue4125-two-install-deadlock.test.ts`(9 例)+ listen-policy/issue3654 判定表扩展钉住全部三面。 - **压缩「总是失败、要重试很多次才成功」的活锁(#4521)**:长会话里模型重报已被折叠覆盖的区间、或把 endId 猜到尚未发号的 ref 之上、或整段落在保护区,这些「其实无事可做」的请求一律被判 FAILED——原子批整体拒绝、断路器计数、模型照失败提示再猜再试,形成「失败→重试→再失败」循环(实测会话 01a18a4d 在 20:09 连续 4 次 FAILED 才成功)。现在五处修正:①endId 越界自动钳到最高已发 ref(警告提示,不整批拒);②区间全覆盖既有活动块=幂等 no-op 成功收据(`noop: true`,提示用 bN..bM 改写而非重发原文),不失败、不进断路器;③纯保护区区间同样 no-op(警告明说勿重发);④保护区 fatal 不再中止整批,只降级该区间;⑤新增 armed-but-silent 状态行:tier 级 nudge 已备好但本轮不投横幅时(退避/节拍/模型定时),以临时 user 消息刷新「最高已发 ref + 当前可压区间」,模型不再凭记忆猜号;全新会话的低于阈值计划保持完全静默(#196 域隔离、#3910 基线不破坏)。 diff --git a/src/store.ts b/src/store.ts index 9e24628e6b..fe180fe99c 100644 --- a/src/store.ts +++ b/src/store.ts @@ -134,9 +134,24 @@ export function contentStoreOf(session: Session): MessageContentStore { * only when new entries appeared, so a no-growth turn costs nothing. */ export function adoptContentStore(session: Session, store: MessageContentStore): void { const prev = session.contentStore; - const added = prev - ? Object.entries(store.byRef).filter(([ref]) => !(ref in prev.byRef)) - : Object.entries(store.byRef); + // #4788 phase-2 dropped prev can be a lazy re-materialize proxy whose disk + // proof vanished after the drop (envelope lost/corrupted). Touching it + // throws by design (#2674 payload-first discipline) — but nothing READABLE + // lived in that proxy (its loader already failed), so an unrecoverable + // prev degrades to "no prior refs" instead of aborting the turn: the + // incoming store stays authoritative and the session survives to its next + // save instead of hard-erroring on every subsequent touch. + let prevRefs: Set | null = null; + if (prev) { + try { + prevRefs = new Set(Object.keys(prev.byRef)); + } catch (err) { + loggerLog("warn", `[ccr] lazy content store for ${session.id} could not be re-materialized during adopt (${String(err instanceof Error ? err.message : err)}) — proceeding with the incoming store as the full set`); + } + } + const added = !prev || prevRefs === null + ? Object.entries(store.byRef) + : Object.entries(store.byRef).filter(([ref]) => !prevRefs!.has(ref)); session.contentStore = store; if (added.length === 0) return; let saved = 0; From 3491e2d32fa83171976a68de9d472405d7a1e44b Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 17:46:49 +0800 Subject: [PATCH 07/11] fix(packs): drop dead export from PackInstallOptions (#5340 follow-up, unused-export gate) --- src/pack-install.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pack-install.ts b/src/pack-install.ts index a70844c1a8..dad6facaf3 100644 --- a/src/pack-install.ts +++ b/src/pack-install.ts @@ -31,7 +31,7 @@ export const PACK_ENTRY_FILE = "bili-pack.json"; const NPM_TIMEOUT_MS = 120_000; -export interface PackInstallOptions { +interface PackInstallOptions { /** Target `./.billion-context/packs/` instead of the user-dir default. */ project?: boolean; /** Replace an existing pack file (refused otherwise). */ From e030d3b11ed6379a5a3356ec6dbb5b53babdafa8 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 18:03:35 +0800 Subject: [PATCH 08/11] fix(packs): resolve npm.cmd on Windows + drop raw negative slice (#5340 follow-ups, gate green) --- src/pack-install.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/pack-install.ts b/src/pack-install.ts index dad6facaf3..84369daf67 100644 --- a/src/pack-install.ts +++ b/src/pack-install.ts @@ -18,6 +18,7 @@ // pattern shared with every other writer here. import { execFileSync } from "node:child_process"; +import { safePrefix } from "./text-safe.js"; import { closeSync, existsSync, fsyncSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -107,14 +108,20 @@ export function installPackFromNpm(spec: string, options: PackInstallOptions = { try { let stderr = ""; try { - execFileSync("npm", [ + // #5340 follow-up: on Windows the npm shim is npm.cmd (no shell here), + // so ENOENT meant "not found" even when node/npm were installed. + const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm"; + execFileSync(npmCmd, [ "install", "--prefix", tmp, "--no-save", "--no-audit", "--no-fund", trimmed, ], { timeout: NPM_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] }); } catch (error) { const err = error as { stderr?: unknown; message?: string }; stderr = typeof err.stderr === "string" ? err.stderr : ""; if (/ENOENT/.test(String(err.message))) throw new Error("npm was not found on PATH"); - const tail = stderr.trim().split("\n").slice(-3).join(" ").slice(0, 300); + const tailLines = stderr.trim().split("\n"); + // text-safe family gate: no raw negative slice literals; head-keep, + // surrogate-safe via safePrefix (#816/#1615 discipline). + const tail = safePrefix((tailLines.length > 3 ? tailLines.slice(tailLines.length - 3) : tailLines).join(" "), 300); throw new Error(`npm install ${trimmed} failed${tail ? `: ${tail}` : ""}`); } From 3260255e35e3c7c19cc8af6bf23f54cb9a91aed3 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 18:38:21 +0800 Subject: [PATCH 09/11] ci: fresh matrix after stuck runner (no code change) From 4a12c1a4ad3e571dd15d21a325083dbbfeb9b48f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 18:55:33 +0800 Subject: [PATCH 10/11] fix(packs): bypass the npm shim on windows via sibling npm-cli.js (#5340 windows shard) --- src/pack-install.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/pack-install.ts b/src/pack-install.ts index 84369daf67..9b3e184f5e 100644 --- a/src/pack-install.ts +++ b/src/pack-install.ts @@ -99,6 +99,21 @@ function findInstalledPkg(prefix: string): { dir: string; manifest: Record Date: Sat, 31 Oct 2026 19:30:23 +0800 Subject: [PATCH 11/11] docs(lifecycle): keep one registry row per env after rebase onto master (ci-fixes owns both registrations) Rebased onto master (485c5eaf). master's ci-fixes commit 0371089db already registers BILI_SESSION_CONTENT_STORE_PIN and BILI_SPAWN_FINGERPRINT in LIFECYCLE.md; this PR's own registrations would have landed as duplicate rows in two different tables. Drop this branch's copies, keep the ci-fixes-owned rows. lifecycle-ledger-guard green (171 readers / 174 entries). --- LIFECYCLE.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/LIFECYCLE.md b/LIFECYCLE.md index a167ade58f..0bc9786c07 100644 --- a/LIFECYCLE.md +++ b/LIFECYCLE.md @@ -53,7 +53,6 @@ | `BILI_OPENCODE_INLINE` | #3278 opencode 移植(#4687) | opencode inline 模式(需手动开启,默认保持旧行为 spawn,owner 决定不改默认):与 pi 同构——不起 proxy 进程,模型 URL 被 V2 route/intercept 改写成伪 origin 后由进程内引擎接住(bun 宿主已验:引擎 boot/dispatch 全绿);`=1/on/yes/TRUE` 或 file 家 `"opencode": {"inline": true}` 显式开启(显式开启压过 attach 目标);`bili opencode-inline` 一键车道 | 同 pi inline 车道节奏 | opt-in(不设置时 attach/spawn 行为与旧版完全一致) | | `BILI_INLINE_DEBUG` | #4669 | 仅 inline 车道:引擎 stderr 日志腿默认静默(stderr 是 pi 的交互终端,日志会挤掉输入框;默认只写 bili.log),设 1 恢复 stderr 输出用于排查 | 随 inline 车道(#3278)走 | 排查逃生口 | | 测试钩子:`BILI_DSH_RECOVERY_INTERVAL_MS` / `BILI_DSH_RETRY_INTERVAL_MS` / `BILI_MODEL_INFO_RETRY_MS` | #2082 等 | 缩短测试/运维节奏(dsh-native.ts;NODE_TEST_CONTEXT 感知,避免生产误缩) | 永久测试设施,随宿主代码走 | 测试钩子 | -| `BILI_SESSION_CONTENT_STORE_PIN` | #4788 phase 2(c8d7a802) | idle-fold 逃生口:`=1/true` 让每会话 CCR content store({byRef}/{byHash} 原文)常驻内存、save 落盘后不折叠(默认折叠;读点 src/knobs.ts:451,store 可从 unified ccr mirror 或 .content-store.json sidecar 重新物化) | #4788 phase 2 idle-fold 生产站稳后评估退役(owner 拍板) | 在用(默认 fold) | ## 2. 常设面全量登记表(src/ 实际读取的其余 BILI_* 环境变量) @@ -70,7 +69,6 @@ |------|-----------| | `BILI_LAUNCH_TOKEN` | launch 令牌(spawn 时注入;日志中脱敏) | | `BILI_PARENT_PID` | owner-pid 看门狗(会话生命周期归属) | -| `BILI_SPAWN_FINGERPRINT` | spawner 自身代码 sha256(hex64;子进程校验后信任,否则本地重算;#4125) | | `BILI_STRICT_PORT` | `=1` claude SessionStart hook 退出端口重试(#964) | | `BILI_OPENCODE_ACP_SPEC` | 剥离版 ACP spec 临时配置**文件路径**提示 | | `BILI_LAUNCHER_LANE` | lane 身份戳(attach 时比对归属) |