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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag

## [Unreleased]

- **Deterministic pre-crush, kernel-native (#1094)**: `compress.crush` (`{ enabled, minReduction, strategies }`, top-level sibling of `absorb`) opts a route into the kernel's tier-1 absorb gate (acp-kernel >= 0.0.84). The kernel crush node runs inside `processTurn` between absorb-hide and absorb-prompt: eligible oversized tool results are mechanically reduced before the absorb decision — JSON field-variance folding (lossless), code comment/docstring elision, log level-classified line selection (both lossy) — and a result crushed below `minToolTokens` skips the model absorb round-trip entirely. Strategy toggles per kernel plugin id (`json-fold` / `code-trim` / `log-select`) support `{ enabled, excludeTools }`. Requires `absorb.enabled` at the resolved level; off by default. Replaces the bili-local pre-crush of PR #1098 with the kernel implementation (no duplicate strategy library, identical behavior in both compression modes).

- **Session-file zstd compression, opt-in; decoupled from encryption (#1080)**: set `BILI_PERSIST_ZSTD=1` to compress session files — each file that actually shrinks is written as `BILIZSTD1`, a magic + format-version + mode-byte header over a JSON body that is zstd-compressed on Node ≥ 22.15 and stored raw on older runtimes; readers accept both bodies (native zstd, else the bundled fzstd WASM fallback), so files stay readable across versions and runtimes. **The default stays plain JSON** (owner decision: recoverability — jq/grep-debuggable, no downgrade tail risk — beats silent disk savings; the format change then only ever happens for deployments that opted in). `BILI_ENCRYPTION_KEY` (#708) is now an orthogonal knob: `BILIENC1` bytes are unchanged, its mode byte records whether the body is compressed (the opt-in applies inside it too), existing plain-JSON files are never rewritten at boot (downgrade safety) and convert organically on their next save. `createSessionCodec(key)` is replaced by `createStorageCodec({ key?, compress? })` (no codec when neither is active; both default off). Tests cover round-trip, mixed trees, opt-in/opt-out, raw fallback, cross-runtime decode, never-rewrite-at-boot, and organic conversion on next save.

- **Marker-integrity silence clause now follows `visibilityMarkers` (#913)**: `MARKER_INTEGRITY_NOTE` was one unconditional constant carrying two rules — the #717 anti-forgery segment (never write a marker-style line as your own text) and the #862 silence clause (execute compress-class calls silently, no preamble before / no summary after). With `compress.visibilityMarkers: false` the proxy stops emitting markers entirely, yet the silence clause kept riding every nudge and the injected compress prompt — an instruction about artifacts that deployment never shows. The constant is split (`MARKER_INTEGRITY_NOTE` base + `MARKER_SILENCE_CLAUSE`), and `withMarkerIntegrityNote(text, visibilityMarkers = true)` appends the clause only while markers are visible. The flag is resolved once per request at the prepare dispatch (`resolveCompress(...).visibilityMarkers ?? true`) and threaded through `prepareAnthropic` / `prepareOpenai` / `prepareGoogle` / `prepareResponses` / `injectSystem` plus the compress-loop systemPrompt build, so first request and loop re-requests agree (per-config byte-stable anchor preserved; default output byte-identical to before). The #717 anti-forgery segment stays unconditional in every configuration. Tests pin: clause dropped at `false`, base intact, pure-suffix byte-stability, default-arg legacy equality.
Expand Down
11 changes: 11 additions & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,17 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t
- `toolName: string` — rename the injected tool (default `"absorb"`); the schema, system-prompt section and per-session adjudication all follow the name.
Injection follows the wire's native-tool surface: proxy mode injects the tool + a static system-prompt section on the anthropic/openai/responses native-tools wires, plugin mode advertises it in the plugin manifest (the MCP shell picks it up for free). Responses **marker/text-protocol** routes are not supported (no native tool surface — the REQUIRED absorb instruction would be unsatisfiable), and title-generation requests (`max_tokens ≤ 200`) skip injection like the compress prompt does. Absorbed pairs stay hidden across restarts (persisted in the session state).

#### `crush`

- **Type:** `object` (`{ enabled?, minReduction?, strategies? }`)
- **Default:** *(disabled — the feature is off unless you set `enabled: true`)*
- **Status:** ACTIVE (requires `absorb.enabled: true` at the resolved level; kernel >= 0.0.84)
- **Description:** Opt-in **deterministic pre-crush** — tier 1 of the absorb gate (issue #1094). The kernel runs it inside `processTurn` between absorb-hide and absorb-prompt: before the `[ACP absorb]` decision, each eligible oversized result is mechanically reduced by a pure, stateless selector (no model call) — **JSON** gets constant fields hoisted + identical rows/runs folded into annotated envelopes (lossless, decodable back to the original); **code** (Python, JS/TS) gets comment/docstring/blank-line elision (lossy); **logs** get level-classified line selection keeping ERROR/FAIL lines with priority, deduped warnings, summary lines and collapsed stack frames (lossy, honest `[N lines omitted: …]` footer). A result crushed below `absorb.minToolTokens` skips the model absorb round-trip entirely; a result still over it is forwarded crushed with the normal absorb prompt. Unparseable or below-reduction-floor content passes through byte-identical (fail-open). Sub-fields:
- `enabled: boolean` — master switch for the pre-crush channel.
- `minReduction: number|percent-string` — minimum fraction of the payload that must be removed for the crush to be used (default `0.1`; marginal savings are not worth altered bytes on the wire).
- `strategies: object` — per-strategy overrides keyed by kernel plugin id: `"json-fold"`, `"code-trim"`, `"log-select"`. Each entry `{ enabled?: boolean, excludeTools?: string[] }` can disable a strategy outright or skip it for matching tool names; ids merge deepest-wins (a deeper entry replaces that id whole, shallower ids survive).
Merged deepest-wins like the parent block; executed by the kernel (its `crush` pipeline node), so both compression modes get it identically.

#### `rules`

- **Type:** `boolean`
Expand Down
11 changes: 11 additions & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,17 @@
- `toolName: string` — 重命名注入工具(默认 `"absorb"`);模式、系统提示段与按会话裁决都跟随名称。
注入跟随线上原生工具面:代理模式在 anthropic/openai/responses 原生工具线上注入工具 + 静态系统提示段,插件模式在插件清单中广告它(MCP shell 自动拾取)。Responses **marker/文本协议**路由不支持(无原生工具面 — 强制的 absorb 指令不可满足),标题生成请求(`max_tokens ≤ 200`)跳过注入如压缩提示一样。吸收配对在重启后保持隐藏(在会话状态持久化)。

#### `crush`

- **类型:** `object`(`{ enabled?, minReduction?, strategies? }`)
- **默认值:** *(禁用 — 除非显式设置 `enabled: true`,该特性完全关闭)*
- **状态:** ACTIVE(要求解析层级上 `absorb.enabled: true`;内核 >= 0.0.84)
- **说明:** 可选开启的**确定性预压碎** — absorb 门槛的第 1 层(issue #1094)。内核在 `processTurn` 内部执行它(位于 absorb-hide 与 absorb-prompt 之间):在 `[ACP absorb]` 决策之前,每个符合条件的超大结果被纯函数选择器机械缩减(无模型调用)— **JSON** 常量字段提升 + 相同行/连续段折叠为带注释的信封(无损,可解码回原文);**代码**(Python、JS/TS)注释/文档串/空行省略(有损);**日志**按级别分类选行,优先保留 ERROR/FAIL 行、去重 warning、摘要行与折叠栈帧(有损,诚实 `[N lines omitted: …]` 尾注)。被压到 `absorb.minToolTokens` 以下的结果完全跳过模型 absorb 往返;仍超限的结果以压碎后的载荷附带正常 absorb 提示转发。不可解析或低于缩减底线的内容字节原样通过(fail-open)。子字段:
- `enabled: boolean` — 预压碎通道主开关。
- `minReduction: number|percent-string` — 压碎必须移除的载荷最小比例(默认 `0.1`;边际节省不值得改变线上字节)。
- `strategies: object` — 按内核插件 id 的逐策略覆盖:`"json-fold"`、`"code-trim"`、`"log-select"`。每项 `{ enabled?: boolean, excludeTools?: string[] }` 可整体禁用策略或对匹配工具名跳过;id 级最深层级胜出(更深的条目整体替换该 id,浅层其他 id 保留)。
按字段最深层级胜出合并,如父块一样;由内核执行(其 `crush` 管线节点),两种压缩模式行为完全一致。

#### `rules`

- **类型:** `boolean`
Expand Down
30 changes: 28 additions & 2 deletions src/compress-settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DEFAULT_ABSORB_CONFIG, defaultPrompts, resolvePrompts, createPackResolver, defaultPackSources, isValidPackName, type AbsorbConfig, type Config, type PackSurface, type Prompts } from "acp-kernel";
import { DEFAULT_ABSORB_CONFIG, DEFAULT_CRUSH_CONFIG, defaultPrompts, resolvePrompts, createPackResolver, defaultPackSources, isValidPackName, type AbsorbConfig, type Config, type CrushConfig, type PackSurface, type Prompts } from "acp-kernel";
import * as path from "node:path";
import { findRoute, type CompressSettings, type ProviderRoutes } from "./config.js";
import { configDir } from "./paths.js";
Expand Down Expand Up @@ -59,6 +59,16 @@ export function mergeCompress(
// like `prompts`: a model-level minToolTokens must not discard a
// provider-level excludeTools.
const absorbLevels = [global?.absorb, provider?.absorb, model?.absorb].filter(Boolean) as NonNullable<CompressSettings["absorb"]>[];
// `crush` merges like `absorb` one level down: scalar fields sub-field-wise,
// and its nested `strategies` map id-wise (deepest entry per id wins whole).
const crushLevels = [global?.crush, provider?.crush, model?.crush].filter(Boolean) as NonNullable<CompressSettings["crush"]>[];
let crushMerged: CompressSettings["crush"];
if (crushLevels.length > 0) {
const merged = Object.assign({}, ...crushLevels);
const stratMaps = crushLevels.map((l) => l.strategies).filter(Boolean) as NonNullable<NonNullable<CompressSettings["crush"]>["strategies"]>[];
if (stratMaps.length > 0) merged.strategies = Object.assign({}, ...stratMaps);
crushMerged = merged;
}
const reasoningLevels = [global?.reasoning, provider?.reasoning, model?.reasoning].filter(Boolean) as NonNullable<CompressSettings["reasoning"]>[];
const reasoningGuardLevels = [global?.reasoningGuard, provider?.reasoningGuard, model?.reasoningGuard].filter(Boolean) as NonNullable<CompressSettings["reasoningGuard"]>[];
return {
Expand All @@ -76,6 +86,7 @@ export function mergeCompress(
prompts: promptLevels.length > 0 ? Object.assign({}, ...promptLevels) : undefined,
acknowledgePromptsRisk: pick("acknowledgePromptsRisk"),
absorb: absorbLevels.length > 0 ? Object.assign({}, ...absorbLevels) : undefined,
crush: crushMerged,
rules: pick("rules"),

stripImages: pick("stripImages"),
Expand Down Expand Up @@ -210,7 +221,12 @@ export function hasCompressSettings(s: CompressSettings): boolean {
* fully). Absent `s.absorb` leaves `base.absorb` untouched — the feature
* stays off unless some level enables it.
* - `rules` → `rules = { enabled }` (kernel RuleFeatureConfig; limits stay
* at kernel defaults). Absent `s.rules` leaves `base.rules` untouched. */
* at kernel defaults). Absent `s.rules` leaves `base.rules` untouched.
* - `crush` → `crush` (kernel CrushConfig, acp-kernel >= 0.0.84; the kernel
* runs the crush node inside processTurn between absorb-hide and
* absorb-prompt). Unset fields inherit DEFAULT_CRUSH_CONFIG. Absent
* `s.crush` leaves `base.crush` untouched — the feature stays off unless
* some level enables it (and absorb.enabled resolves true). */
export function applyCompressSettings(base: Config, limit: number, s: CompressSettings): Config {
const nudge = { ...base.nudge };
const truncate = { ...base.truncate };
Expand All @@ -237,6 +253,15 @@ export function applyCompressSettings(base: Config, limit: number, s: CompressSe
excludeTools: s.absorb.excludeTools ?? [...d.excludeTools],
};
}
let crush: CrushConfig | undefined;
if (s.crush !== undefined) {
const d = DEFAULT_CRUSH_CONFIG;
crush = {
enabled: s.crush.enabled === true,
minReduction: s.crush.minReduction !== undefined ? parsePercent(s.crush.minReduction) : d.minReduction,
};
if (s.crush.strategies !== undefined) crush.strategies = s.crush.strategies;
}
return {
...base,
modelContextLimit: limit,
Expand All @@ -252,6 +277,7 @@ export function applyCompressSettings(base: Config, limit: number, s: CompressSe
protectedLatestTools: s.protectedLatestTools ?? base.protectedLatestTools,
protectedTools: s.protectedTools ?? base.protectedTools,
...(absorb !== undefined ? { absorb } : {}),
...(crush !== undefined ? { crush } : {}),
...(s.rules !== undefined ? { rules: { enabled: s.rules === true } } : {}),
};
}
Expand Down
75 changes: 75 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,33 @@ export type CompressSettings = {
* the client's own tool names or the agent will call its own tool. */
toolName?: string;
};
/** Deterministic pre-crush of eligible oversized tool results — tier 1 of
* the absorb gate (#1094, kernel `Config.crush`, acp-kernel >= 0.0.84:
* the kernel runs it inside processTurn between absorb-hide and
* absorb-prompt). Requires `absorb.enabled` at the resolved level.
* JSON payloads get lossless field-variance folding (constant fields
* hoisted, identical runs collapsed); code gets comment/docstring
* elision; logs get level-classified line selection (both lossy). A
* result crushed below `absorb.minToolTokens` never triggers a model
* absorb round-trip. Unparseable or uncrushable content passes through
* byte-identical. Off unless explicitly enabled. */
crush?: {
/** Enable pre-crush for this scope (`absorb.enabled` must also be
* true at the resolved level). */
enabled?: boolean;
/** Minimum fraction of tokens the crush must save for the
* replacement to be accepted. Accepts a ratio in (0,1] or a percent
* string; kernel default 0.1. */
minReduction?: number | string;
/** Per-strategy toggles keyed by kernel plugin id (`json-fold`,
* `code-trim`, `log-select`). Id-level deepest-wins merge. */
strategies?: Record<string, {
/** Set false to disable this strategy even when crush is enabled. */
enabled?: boolean;
/** Tool-name patterns this strategy skips. */
excludeTools?: string[];
}>;
};
/** Persistent rule reminders (kernel `Config.rules`, acp-kernel >= 0.0.70).
* When `enabled`, an `acp_rule` tool is injected (or advertised in the
* plugin manifest): passing a short `rule` records a principle-level
Expand Down Expand Up @@ -1010,6 +1037,54 @@ export function parseCompressSettings(v: unknown): (CompressSettings & { injectT
if (ok) out.absorb = cleaned;
}
}
if ("crush" in obj && obj.crush !== undefined) {
const c = obj.crush;
if (!c || typeof c !== "object" || Array.isArray(c)) {
ok = false;
} else {
const co = c as Record<string, unknown>;
const cleaned: NonNullable<CompressSettings["crush"]> = {};
if ("enabled" in co) {
if (typeof co.enabled !== "boolean") ok = false;
else cleaned.enabled = co.enabled;
}
if ("minReduction" in co) {
const v = co.minReduction;
if (typeof v === "number" || (typeof v === "string" && v.trim().endsWith("%"))) {
const ratio = typeof v === "number" ? v : Number(v.trim().slice(0, -1)) / 100;
if (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1) ok = false;
else cleaned.minReduction = typeof v === "string" ? v.trim() : v;
} else {
ok = false;
}
}
if ("strategies" in co && co.strategies !== undefined) {
const sv = co.strategies;
if (!sv || typeof sv !== "object" || Array.isArray(sv)) {
ok = false;
} else {
const strategies: NonNullable<NonNullable<CompressSettings["crush"]>["strategies"]> = {};
for (const [id, ent] of Object.entries(sv as Record<string, unknown>)) {
if (typeof id !== "string" || id.trim().length === 0 || !ent || typeof ent !== "object" || Array.isArray(ent)) { ok = false; continue; }
const eo = ent as Record<string, unknown>;
const entry: NonNullable<NonNullable<NonNullable<CompressSettings["crush"]>["strategies"]>[string]> = {};
if ("enabled" in eo) {
if (typeof eo.enabled !== "boolean") { ok = false; continue; }
entry.enabled = eo.enabled;
}
if ("excludeTools" in eo) {
const ev = eo.excludeTools;
if (!Array.isArray(ev) || ev.some((x) => typeof x !== "string" || x.trim().length === 0)) { ok = false; continue; }
entry.excludeTools = (ev as string[]).map((x) => x.trim());
}
strategies[id.trim()] = entry;
}
if (ok) cleaned.strategies = strategies;
}
}
if (ok) out.crush = cleaned;
}
}
if ("prompts" in obj && obj.prompts !== undefined) {
const prompts = obj.prompts;
if (!prompts || typeof prompts !== "object" || Array.isArray(prompts)) {
Expand Down
Loading
Loading