Skip to content
Open
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
2 changes: 2 additions & 0 deletions docs/configuration.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,8 @@
| `compress.streamSummary` | boolean | false (unset) | — | 事前チェックの要約を、最初の試行からストリーミング(SSE)コールとして実行することを強制する。エラー駆動の自己学習は、ストリーミングを強制するアップストリームを独自に処理する(非ストリーミング要約での 400 はワンショット SSE プローブをトリガーする、#2494)が、ゲートウェイタイムアウト(例: Cloudflare HTTP 524)では決してアームしない:bili とオリジンの間にそのようなゲートウェイがある場合にこれを設定するか、単に 1 回のプローブ往復をスキップするために設定する。 |
| `compress.preserveRecentMessages` | number | 3 | — | 最新のメッセージは、折りたたみからソフト保護される。 |
| `compress.preserveRecentTokens` | number | kernel ≈5000 | — | 最新のトークンはフォールドからソフト保護される。 |
| `compress.preserveRecentTurns` | number | off | — | 直近 N ターン(ターン = user メッセージ→次の user メッセージ)の全メッセージがソフト保護される(#4593)。 |
| `compress.protectUserMessages` | boolean | off | — | 全 user テキストメッセージをハード保護し、圧縮不能とする(#4593)。 |
| `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | フォールド可能な最小範囲(文字数)。これより短い範囲はフォールドされない。 |
| `compress.maxSummaryLength` | number | kernel 20000 | — | 1つの生成サマリーに対する文字数のハード上限。これを超える返信は全体として拒否される(切り詰めもリトライもされない)。外部サマライザーにはこの正確な上限が事前に通知される(#3635)。0 = 無制限。 |
| `compress.minSummaryLength` | number | kernel 50 | — | 生成サマリーの文字数下限:単一範囲はこれに単独で達する必要がある。複数範囲のバッチは、その結合サマリーがこれに達した場合に合格する(#5894)。0 = 無効。外部サマライザーはサマリーごとの下限に引き続き従う(#3635)。 |
Expand Down
22 changes: 22 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,8 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed
| `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. |
| `compress.preserveRecentTokens` | number | kernel ≈5000 | — | The most recent tokens stay soft-protected from folds. |
| `compress.preserveRecentTurns` | number | off | — | All messages of the last N turns (turn = user message → next user message) join the soft-protected zone (#4593). |
| `compress.protectUserMessages` | boolean | off | — | Every user text message is hard-protected, never compressible (#4593). |
| `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | Smallest foldable range, in characters; shorter ranges never fold. |
| `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: a single range must meet it alone; a multi-range batch passes when its combined summaries reach it (#5894). 0 = disabled. External summarizers remain held to the per-summary floor (#3635). |
Expand Down Expand Up @@ -1516,6 +1518,26 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t
- **Status:** ACTIVE
- **Description:** Token budget reserved for recent-message protection. Maps to the kernel field `preserveRecentTokens`.

#### `preserveRecentTurns`

- **Type:** `number`
- **Default:** off (`0` or unset)
- **Status:** ACTIVE (#4593, requires `acp-kernel` ≥ 0.0.197)
- **Description:** Per-turn retention. A "turn" is one user message plus everything up to the next user message. All messages of the last N turns join the soft-protected zone alongside `preserveRecentMessages`/`preserveRecentTokens`/the latest-user pin — one union set, no internal priority. Message counts don't bound a turn (a single turn spans dozens of tool calls/results), which is why count-based retention alone either cuts mid-turn or over-retains. Deterministic behavior for a submitted compress range:
- **Range entirely inside the protected zone** → no-op success (#4521, landed on master after this PR branched): nothing folds, the receipt warns `folded nothing — it lies entirely inside the protected zone … do not resend this range` (a rejection would send retry loops back into the same zone).
- **Range partially overlapping** → the protected part is filtered out (truncated at the first interior protected message so no summary lands above the question it answers, #3953); the rest compresses normally, and the receipt carries an auditable warning listing exactly which refs were skipped and their cause (`…of which N in last-turns retention`). If the remainder falls below `minCompressRange`, the existing too-small rejection applies.
- Recommended ranges (`acp_status`) never cross the boundary — only hand-picked ranges hit the carve.
- Overflow relaxation (#330) zeroes `preserveRecentMessages`/`preserveRecentTokens` but deliberately NOT this knob: folding user instructions under pressure defeats the feature, so an unresolvable overflow fails loudly instead.
- **Example:** `{ "compress": { "preserveRecentTurns": 3 } }`

#### `protectUserMessages`

- **Type:** `boolean`
- **Default:** off (unset = `false`)
- **Status:** ACTIVE (#4593, requires `acp-kernel` ≥ 0.0.197)
- **Description:** Hard-protect every user text message — the only non-regenerable input in a session: tool results can be re-run, summaries rewritten, but once a user instruction is folded into a model-written summary it can no longer be checked verbatim. Protection is a HARD exclusion like `protectedTools`: matching refs render as `BLOCKED`, are never advertised as compressible, and a submitted range containing them has them carved out with an auditable receipt warning (`Excluded N user message(s) … (protectUserMessages)`); a range consisting solely of such messages is a no-op success (#4521, landed on master after this PR branched) — nothing folds, the receipt warns `folded nothing … do not resend this range`. Conservative by design: host-injected runtime-context user messages are covered too (over-protection costs compression ratio; under-protection loses instructions). Summary carriers — user-role messages whose text starts with the kernel's SUMMARY_HEADER — and tool results (role `tool`) do NOT match. Deepest level wins across global → provider → model like the other compress fields.
- **Example:** `{ "compress": { "protectUserMessages": true } }`

#### `minCompressRangeChars`

- **Type:** `number`
Expand Down
22 changes: 22 additions & 0 deletions docs/configuration.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,8 @@
| `compress.streamSummary` | boolean | false (unset) | — | 强制 preflight 摘要从首次尝试起就走流式(SSE)请求。要求流式的上游现在由错误驱动自学习自动处理(非流式摘要的任何 400 都会触发一次性 SSE 探测,#2494),但网关超时(如 Cloudflare HTTP 524)永远无法触发自学习:在此类网关位于 bili 与源站之间时设置此项,或用于省去一次探测往返。 |
| `compress.preserveRecentMessages` | number | 3 | — | 最近的消息软保护、免于折叠。 |
| `compress.preserveRecentTokens` | number | kernel ≈5000 | — | 最近的 token 软保护、免于折叠。 |
| `compress.preserveRecentTurns` | number | off | — | 最近 N 轮(轮 = 一条 user 消息到下一条 user 消息)的全部消息加入软保护区(#4593)。 |
| `compress.protectUserMessages` | boolean | off | — | 所有 user 文本消息硬保护、永不压缩(#4593)。 |
| `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | 可折叠片段的最小字符数;更短的永不折叠。 |
| `compress.maxSummaryLength` | number | kernel 20000 | — | 单条生成摘要的硬字符上限;超长的回复被整段拒绝(不截断、不重试)。外部摘要模型会被提前告知这个确切上限(#3635)。0 = 不限制。 |
| `compress.minSummaryLength` | number | kernel 50 | — | 生成摘要的字符下限:单段压缩按自身判定;批量压缩按合计判定——一段偷懒不再拖垮整批(#5894)。0 = 禁用。外部摘要模型仍受逐段下限约束(#3635)。 |
Expand Down Expand Up @@ -1513,6 +1515,26 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报
- **状态:** ACTIVE
- **说明:** 为最近消息保护预留的 token 预算。映射到内核字段 `preserveRecentTokens`。

#### `preserveRecentTurns`

- **类型:** `number`
- **默认值:** 关闭(`0` 或未设置)
- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.197)
- **说明:** 按轮保留。一轮 = 一条 user 消息 + 到下一条 user 消息为止的全部内容。最近 N 轮的全部消息与 `preserveRecentMessages`/`preserveRecentTokens`/最新 user 钉住一起并入软保护区——同一个并集,无内部优先级。一条轮往往横跨几十条工具调用/结果,按条数保留要么截在轮中间、要么过度保留,这正是本键存在的理由。提交压缩区间时的确定行为:
- **区间完全落在保护区内** → 空操作成功(#4521,在本 PR 分支后合入 master):不折叠任何消息,回执警告 `folded nothing — it lies entirely inside the protected zone … do not resend this range`(若拒绝会把重试循环送回同一保护区)。
- **区间部分重叠** → 受保护部分被过滤掉(在第一条内部受保护消息处截断,保证摘要不会落在它所回答的问题之上,#3953),其余部分正常压缩;回执里带一条可审计警告,逐条列出被跳过的 ref 及原因(`…of which N in last-turns retention`)。若剩余不足 `minCompressRange`,走既有的 too-small 拒绝。
- 推荐区间(`acp_status`)永不跨边界——只有手工挑选的区间才会触发过滤。
- 溢出松弛(#330)会把 `preserveRecentMessages`/`preserveRecentTokens` 清零,但**有意不**清本键:压力下折叠用户指令等于让本功能失效,因此无法解决的溢出会响亮地失败而不是悄悄折掉指令。
- **示例:** `{ "compress": { "preserveRecentTurns": 3 } }`

#### `protectUserMessages`

- **类型:** `boolean`
- **默认值:** 关闭(未设置 = `false`)
- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.197)
- **说明:** 硬保护所有 user 文本消息——会话中唯一不可再生的输入:工具结果可以重跑、摘要可以重写,但用户指令一旦被折进模型自写的摘要,就无法再逐字核对。保护是 HARD 排除,语义同 `protectedTools`:匹配的 ref 显示为 `BLOCKED`、永不出现在可压缩推荐里;提交的区间包含它们时会被过滤并留下可审计的回执警告(`Excluded N user message(s) … (protectUserMessages)`);整段全是这类消息的区间是空操作成功(#4521,在本 PR 分支后合入 master)——不折叠任何消息,回执警告 `folded nothing … do not resend this range`。刻意保守:宿主注入的 runtime-context user 消息也在保护范围内(误保护只损失压缩比,误折叠会丢指令)。摘要载体——文本以内核 SUMMARY_HEADER 开头的 user 消息——与工具结果(role `tool`)不匹配。与其他 compress 字段一样,global → provider → model 最深层生效。
- **示例:** `{ "compress": { "protectUserMessages": true } }`

#### `minCompressRangeChars`

- **类型:** `number`
Expand Down
4 changes: 2 additions & 2 deletions kernel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion kernel/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "acp-kernel",
"version": "0.0.198",
"version": "0.0.199",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
Expand Down
6 changes: 5 additions & 1 deletion kernel/src/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1266,7 +1266,11 @@ const assignRefsNode: PipelineNode = {
ctx.config.protectedTools.length > 0 ||
!!ctx.config.isToolProtected ||
!!ctx.config.isMessageProtected ||
(ctx.config.protectedLatestTools?.length ?? 0) > 0;
(ctx.config.protectedLatestTools?.length ?? 0) > 0 ||
// #4593: protectUserMessages alone must also run protectedFn — without
// this gate addition its isMessageProtected branch never executes and
// user messages get plain foldable refs.
ctx.config.protectUserMessages === true;
const latest = hasProtection
? collectLatestProtected(io.messages, ctx.config)
: undefined;
Expand Down
13 changes: 13 additions & 0 deletions kernel/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,19 @@ export function validateConfig(config: Config): string[] {
) {
errors.push("preserveRecentTools must be a string array");
}
if (
config.preserveRecentTurns !== undefined &&
(!Number.isFinite(config.preserveRecentTurns) ||
config.preserveRecentTurns < 0)
) {
errors.push("preserveRecentTurns must be a finite number >= 0");
}
if (
config.protectUserMessages !== undefined &&
typeof config.protectUserMessages !== "boolean"
) {
errors.push("protectUserMessages must be a boolean");
}
if (config.absorb) {
if (config.absorb.enabled && !config.absorb.toolName) {
errors.push("absorb.toolName must be a non-empty string when enabled");
Expand Down
25 changes: 24 additions & 1 deletion kernel/src/protected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,22 @@ export function virtualToolPathOf(
return config.messagePathOf?.(msg);
}

/** True for a genuine user text message — role "user", plain text content,
* not a pasted summary carrier. #4593 protectUserMessages hard-protection
* rides on this: user instructions are the only non-regenerable input in a
* session (tool results can be re-run, summaries rewritten), so once one
* leaves the wire it can no longer be checked verbatim. Summary carriers
* are excluded so tier-merge of blocks that contain user messages stays
* possible; host-injected runtime-context user messages ARE protected on
* purpose (conservative default: over-protecting costs compression ratio,
* under-protecting loses an instruction). */
export function isUserTextMessage(msg: CoreMessage): boolean {
if (msg.role !== "user") return false;
if (msg.contentType !== "text") return false;
if (msg.text?.startsWith(SUMMARY_HEADER)) return false;
return true;
}

/** #5109: the newest HUMAN user request — the Rule-3 protection anchor.
* Backward scan skipping (a) bili's own summary carriers and covered ids
* (same predicate as recommend's isSyntheticOrPruned, restated here to keep
Expand Down Expand Up @@ -345,13 +361,20 @@ export function lastUserAnchor(

export function isMessageProtected(
msg: CoreMessage,
config: Pick<Config, "protectedTools" | "isToolProtected" | "isMessageProtected" | "messagePathOf" | "isCompressTool">,
config: Pick<Config, "protectedTools" | "isToolProtected" | "isMessageProtected" | "messagePathOf" | "isCompressTool" | "protectUserMessages">,
failedToolCallIds?: ReadonlySet<string>,
): boolean {
// Host-declared message-level protection (#2419): applies to ANY content
// type and outranks everything below — the host owns the decision.
if (config.isMessageProtected?.(msg)) return true;

// #4593: user-text hard protection (protectUserMessages). Checked before
// the tool-path branches because its domain (role "user" text) never
// overlaps them.
if (config.protectUserMessages === true && isUserTextMessage(msg)) {
return true;
}

// #4289: a compress exchange that applied ZERO ranges is refuse, not
// metadata — no block carries its arguments and decompress never consults
// it. Exempt both halves from EVERY built-in source below (ALWAYS table,
Expand Down
23 changes: 22 additions & 1 deletion kernel/src/recommend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
isNeverPreserveRecent,
lastUserAnchor,
} from "./protected.js";
import { computeTurnRetention } from "./turn-retention.js";
import { countMessageTokens } from "./tokenize.js";
import { computeIntegrityWithdrawals } from "./turn-integrity.js";
import { evaluateRefold } from "./refold.js";
Expand Down Expand Up @@ -70,10 +71,15 @@ function isSyntheticOrPruned(
* Compute the set of protected message refs (mNNNNN) that form the
* "soft-protected zone" at the tail of the conversation.
*
* Combines three rules:
* Combines four rules:
* 1. Last N messages (`config.preserveRecentMessages`)
* 2. Last N tokens expanding backward (`config.preserveRecentTokens`)
* 3. Last visible user message (couples to Rule 1)
* 4. Per-turn retention (#4593): the last N user-initiated turns form a
* positional protected suffix (`config.preserveRecentTurns`; recomputed
* every turn — see turn-retention.ts). A submitted range overlapping it
* is carved there with an auditable receipt (like Rules 1-3); a range
* entirely inside it is rejected by projectUnit.
*
* Then closes the tool-pair gap (#2886): if either half of a (tool-call,
* tool-result) pair is protected, both are. Without this, `neverPreserveRecentTools`
Expand Down Expand Up @@ -155,6 +161,21 @@ export function computeProtectedRefs(
}
}

// Rule 4 (#4593): per-turn retention — the last N user-initiated turns form
// a positional protected suffix. Recomputed every turn (the window slides
// with each new user message), which is why it lives here rather than in
// the permanent BLOCKED-ref decision. Fewer than N+1 visible user messages
// ⇒ the whole conversation is retained (boundaryIndex 0).
{
const retention = computeTurnRetention(messages, state, config);
if (retention) {
for (let i = retention.boundaryIndex; i < messages.length; i++) {
const ref = state.messageRefs.byRaw[messages[i]!.id];
if (ref && ref !== "BLOCKED") result.add(ref);
}
}
}

// #2886: close the tool-pair gap. neverPreserveRecentTools drops big-result
// tools (read/bash/...) from `visible`, so a matching tool-result can never
// enter the recent zone while its paired tool-call (unmatched name) can.
Expand Down
Loading
Loading