Skip to content
Merged
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
6 changes: 3 additions & 3 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed
| `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | Smallest foldable range, in characters; shorter ranges never fold. |
| `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") | builtin "default" | — | Compression prompt pack, resolved project pack → user pack → builtin; not gated by acknowledgePromptsRisk. |
| `compress.stripImagesKeepRecent` | number | 5 | — | With stripImages on, images inside the N newest messages are kept. |
| `compress.stripImagesKeepRecent` | number | 5 | — | With stripImages on, images inside the N newest messages are kept (fallback window when no fold anchors the boundary). |
| `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. |
| `compress.protectedLatestTools` | string[] | none | — | Protects only the LATEST instance of cumulative-snapshot tools whose newest result supersedes older ones (e.g. todo lists). |
Expand Down Expand Up @@ -1318,14 +1318,14 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t
- **Type:** `boolean`
- **Default:** `false`
- **Status:** ACTIVE
- **Description:** Opt-in removal of historical image payloads. When `true`, every message **except** the most recent `stripImagesKeepRecent` has its image parts dropped before the wire rebuild; an image-only message collapses to a single `[image]` text placeholder (mixed text+image messages keep their text). Recent-N images are forwarded verbatim, and a freshly-sent image always falls inside that window on the turn it arrives. Off by default — while off, the #488 image-token floor and its overflow `502` stay the opt-in signal for image-heavy payloads. Applies to both compression modes (in plugin mode the agent's own history is untouched; only the upstream-bound wire is slimmed). See issue #617.
- **Description:** Opt-in removal of historical image payloads. When `true`, aged-out messages have their image parts dropped before the wire rebuild; an image-only message collapses to a single `[image]` text placeholder (mixed text+image messages keep their text). **Strip boundary (#1995):** on anthropic sessions with an active compression fold, the boundary is FOLD-ANCHORED — only wire messages covered by active folds are stripped, and the boundary moves only on compression events, so the stripped prefix stays byte-stable between folds (the prompt cache stops re-billing it every turn) and un-folded images stay live. Without an active fold, or on the other wires (whose strip placeholders would flip kernel message ids), the classic sliding window applies: every message except the most recent `stripImagesKeepRecent` is stripped. A freshly-sent image always sits in the un-stripped tail on the turn it arrives. **Recovery:** stripped pixels are recoverable via `decompress({ imageRef })` — each stripped image is indexed by its `mNNNNN` ref and spilled under `<state>/retrieve/img/<session>/` (best-effort 7-day TTL); preflight fold summaries carry the ref in their notes (`[image: png 1024x768 · m00042]`). Off by default — while off, the #488 image-token floor and its overflow `502` stay the opt-in signal for image-heavy payloads. Applies to both compression modes (in plugin mode the agent's own history is untouched; only the upstream-bound wire is slimmed). See issue #617.

#### `stripImagesKeepRecent`

- **Type:** `number`
- **Default:** `5`
- **Status:** ACTIVE
- **Description:** With `stripImages: true`, how many trailing messages keep their images verbatim. Ignored unless `stripImages` is enabled.
- **Description:** With `stripImages: true`, how many trailing messages keep their images verbatim. Ignored unless `stripImages` is enabled. **Fallback role (#1995):** on anthropic sessions an active fold anchors the strip boundary instead; this window applies when no fold anchors it (and on all other wires).

#### `visibilityMarkers`

Expand Down
6 changes: 3 additions & 3 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@
| `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | 可折叠片段的最小字符数;更短的永不折叠。 |
| `compress.reconcile` | "off" \| "warn" \| "repair" | "repair" | BILI_FOLD_RECONCILE | 客户端在轮次之间回退或改写历史时校准已折叠状态。 |
| `compress.promptPack` | string (builtin: "default", "lean") | builtin "default" | — | 压缩提示词包,按 项目包 → 用户包 → 内置 解析;不受 acknowledgePromptsRisk 门控。 |
| `compress.stripImagesKeepRecent` | number | 5 | — | 开启剥离图片时,最新 N 条消息内的图片保留。 |
| `compress.stripImagesKeepRecent` | number | 5 | — | 开启剥离图片时,最新 N 条消息内的图片保留(无折叠锚定时的回退窗口)。 |
| `compress.tiers` | boolean | true | — | T1→T3 分级蒸馏把折叠成本摊到多代。 |
| `compress.protectedTools` | string[] | none | — | 全历史硬排除:列出工具的结果永不折叠。 |
| `compress.protectedLatestTools` | string[] | none | — | 只保护累积快照类工具「最新一次」实例(新结果覆盖旧结果的工具,如 todo 列表)。 |
Expand Down Expand Up @@ -1323,14 +1323,14 @@
- **类型:** `boolean`
- **默认值:** `false`
- **状态:** ACTIVE
- **说明:** 可选的历史图像载荷移除。设为 `true` 时,除最近 `stripImagesKeepRecent` 条消息外,所有消息在重建 wire 前都会丢弃其图像部分;纯图像消息折叠为单个 `[image]` 文本占位符(图文混合消息保留其文本)。最近 N 条的图像逐字转发,且新发送的图像在其到达的那一轮必然落在该窗口内。默认关闭 —— 关闭期间,#488 图像 token 下限及其溢出 `502` 仍是图像密集型载荷的显式信号。对两种压缩模式均生效(plugin 模式下 agent 自身历史不受影响,仅精简发往上游的 wire)。见 issue #617。
- **说明:** 可选的历史图像载荷移除。设为 `true` 时,老化消息在重建 wire 前会丢弃其图像部分;纯图像消息折叠为单个 `[image]` 文本占位符(图文混合消息保留其文本)。**剥离边界(#1995):** anthropic 会话存在活跃压缩折叠时,边界为折叠锚定——只剥离被活跃折叠覆盖的 wire 消息,边界仅在压缩事件时移动,被剥离的前缀在两次折叠之间保持字节稳定(prompt cache 不再每轮重复计费),未折叠的图像保持可见。无活跃折叠时(以及其他 wire——其剥离占位符会翻转 kernel 消息 id)沿用经典滑动窗口:除最近 `stripImagesKeepRecent` 条外全部剥离。新发送的图像在其到达的那一轮必然落在未剥离尾部。**恢复:** 被剥离的像素可通过 `decompress({ imageRef })` 恢复——每个被剥离图像按 `mNNNNN` 引用建索引并 spill 到 `<state>/retrieve/img/<session>/`(尽力而为的 7 天 TTL);preflight 折叠摘要的注释携带引用(`[image: png 1024x768 · m00042]`)。默认关闭 —— 关闭期间,#488 图像 token 下限及其溢出 `502` 仍是图像密集型载荷的显式信号。对两种压缩模式均生效(plugin 模式下 agent 自身历史不受影响,仅精简发往上游的 wire)。见 issue #617。

#### `stripImagesKeepRecent`

- **类型:** `number`
- **默认值:** `5`
- **状态:** ACTIVE
- **说明:** 在 `stripImages: true` 时,末尾多少条消息保留其图像逐字转发。仅在启用 `stripImages` 时生效。
- **说明:** 在 `stripImages: true` 时,末尾多少条消息保留其图像逐字转发。仅在启用 `stripImages` 时生效。**回退角色(#1995):** anthropic 会话存在活跃折叠时剥离边界改为折叠锚定;此窗口在无折叠锚定时(以及所有其他 wire 上)生效。

#### `visibilityMarkers`

Expand Down
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.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",
Expand Down
9 changes: 8 additions & 1 deletion kernel/src/wire/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat {
// (excludeTools / protectedTools / isNeverPreserveRecent) are name-based.
// Not part of the result identity seed — ids must stay stable across versions.
const toolNames = new Map<string, string>();
for (const m of body.messages) {
for (const [wireIndex, m] of body.messages.entries()) {
// #1995: record the source wire ordinal so host-side strip anchoring can
// map fold coverage (core-message space) back to wire positions without
// re-deriving the converter's block-split behavior.
const before = msgs.length;
const blocks =
typeof m.content === "string"
? [{ type: "text" as const, text: m.content }]
Expand Down Expand Up @@ -198,6 +202,9 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat {
}
}
}
for (let k = before; k < msgs.length; k++) {
(msgs[k] as BiliMessage).wireIndex = wireIndex;
}
}
return { msgs, cacheControls };
}
Expand Down
7 changes: 7 additions & 0 deletions kernel/src/wire/bili-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ export interface BiliMessage extends CoreMessage {
* the content from these when present, so parts the core does not model
* survive a round-trip. */
rawGoogleParts?: unknown[];
/** Source wire-message ordinal for this core message, tagged by the
* converters (`wireIndex` of the protocol message it was flattened from).
* Host-side consumers use it to translate core-space fold coverage back
* into wire positions (e.g. #1995's fold-anchored stripImages cutoff)
* without re-deriving each codec's block-split behavior. Optional:
* converters adopt it incrementally; absence means "unknown". */
wireIndex?: number;
/** Anthropic thinking signature. Anthropic verifies thinking+signature
* pairs; without it the request is rejected. Stored alongside the
* reasoning text so coreToAnthropic can reattach it. */
Expand Down
29 changes: 24 additions & 5 deletions kernel/src/wire/strip-images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,14 @@ function stripNestedImages(
return {
part: {
...part,
content: kept.length > 0 ? kept : placeholderContent(protocol),
// #1995: an image-only tool_result collapses to the EMPTY STRING, not
// a "[image]" text part. anthropicToCore seeds the tool_result id from
// its concatenated TEXT parts (images contribute ""), so "" keeps the
// derived id byte-identical pre/post strip — a "[image]" part would
// flip the id and churn the ref projection / fold anchoring state
// (stripImages anchoring, src/image-restore.ts). String content is
// valid Anthropic tool_result shape.
content: kept.length > 0 ? kept : "",
},
removed,
};
Expand Down Expand Up @@ -140,19 +147,31 @@ function stripParts(
/** Drop image parts from every message older than the most recent `keepRecent`.
* `protocol` selects the wire dialect; `null` (unparseable) is a no-op. Returns
* `{ body, removed }` where `body` is the input reference untouched (and
* `removed` is 0) when there was nothing to strip. */
* `removed` is 0) when there was nothing to strip.
*
* `opts.cutoffIndex` (protocol-neutral, #1995): when present, replaces the
* sliding `len - keepRecent` cutoff with an explicit wire-message index —
* strip messages at index < cutoffIndex. Hosts use this to anchor the strip
* boundary to fold coverage so the stripped prefix only moves on compression
* events (prompt-cache stability) instead of every turn. When absent the
* historical sliding-window behavior applies. */
export function stripHistoricalImages(
body: unknown,
protocol: StripProtocol,
keepRecent: number,
opts?: { cutoffIndex?: number },
): StripResult {
if (!protocol || !isObj(body)) return { body, removed: 0 };
const recentCount = Math.max(0, Math.floor(keepRecent));
const explicitCutoff =
opts?.cutoffIndex !== undefined && Number.isFinite(opts.cutoffIndex)
? Math.max(0, Math.floor(opts.cutoffIndex))
: undefined;

if (protocol === "responses") {
const input = body.input;
if (!Array.isArray(input)) return { body, removed: 0 };
const cutoff = input.length - recentCount;
const cutoff = explicitCutoff ?? input.length - recentCount;
let removed = 0;
let touched = false;
const nextInput = input.map((item, i) => {
Expand All @@ -178,7 +197,7 @@ export function stripHistoricalImages(
if (protocol === "google") {
const contents = body.contents;
if (!Array.isArray(contents)) return { body, removed: 0 };
const cutoff = contents.length - recentCount;
const cutoff = explicitCutoff ?? contents.length - recentCount;
let removed = 0;
let touched = false;
const nextContents = contents.map((c, i) => {
Expand All @@ -198,7 +217,7 @@ export function stripHistoricalImages(

const messages = body.messages;
if (!Array.isArray(messages)) return { body, removed: 0 };
const cutoff = messages.length - recentCount;
const cutoff = explicitCutoff ?? messages.length - recentCount;
let removed = 0;
let touched = false;
const nextMessages = messages.map((m, i) => {
Expand Down
Loading
Loading