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
12 changes: 12 additions & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,18 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t
- **Status:** ACTIVE
- **Description:** The **positive-facing** counterpart of `neverPreserveRecentTools`: tool-name patterns **removed** from the effective recent-zone exclusion list. The #1198/#1277 batch-read fold→re-read remedy becomes a one-entry config — `{ "compress": { "preserveRecentTools": ["read"] } }` — that protects fresh read results without restating (or freezing a stale hand-copy of) the built-in list, and keeps following built-in evolution. Effective exclusion = `(neverPreserveRecentTools ?? built-in) minus preserveRecentTools`; composable with an explicit `neverPreserveRecentTools` (subtraction applies to the explicit list too); glob-suffix patterns subtract matching entries (`"bash*"` removes `bash`). Prefer this knob over editing the never-list unless you genuinely need verbatim-replace semantics. **⚠ Empty array `[]` is rejected** — it is a pure no-op here, so a bare `[]` is almost certainly a typo for `neverPreserveRecentTools: []` (the max-protection escape hatch). Whole-array replace at the deepest defined level, like the sibling knobs.

#### `burstHold`

- **Type:** `object` (`{ enabled?, minToolResults?, lookbackMessages?, minToolShare? }`)
- **Default:** `{ enabled: true, minToolResults: 5, lookbackMessages: 12, minToolShare: 0.55 }` — **on by default** (#1487)
- **Status:** ACTIVE
- **Description:** **Tool-burst nudge hold.** While the tail of the resent history is dominated by fresh tool results — the agent mid-batch of reads/greps/globs/bash calls — AND context usage is still below the hold ceiling, GROWTH-based compression nudges are held so the agent can finish its batch before its working content gets folded. This is the automated counterpart of the #1198/#1277 fold→re-read death loop (reported in dsh discussion #5795): instead of manually keeping fresh results out of the fold via recent-zone knobs, the nudge simply waits for the batch to end. The hold is stateless per request, applies on every wire in both compression modes, and touches only PROACTIVE growth nudges — the kernel's pressure-band force-nudge (usage ≥ `maxContextLimit`) and the host emergency nudge (usage ≥ 70%) always fire, so a context that runs out mid-burst still compresses immediately. Hold ceiling = `min(0.7, effective maxContextLimit)`. Sub-fields (merged deepest-wins per sub-field like `absorb`):
- `enabled: boolean` — default `true`; set `false` to restore the legacy always-nudge behavior.
- `minToolResults: number` — minimum tool-result count inside the window to count as a burst (default `5`). Positive integer.
- `lookbackMessages: number` — trailing-history window size inspected, in messages (default `12`). Positive integer.
- `minToolShare: number` — minimum share of the window that must be tool results, 0..1 (default `0.55`) — calibrated so steady assistant/tool alternation (~0.5) never trips while parallel batches (~0.8+) always trip.
- **Example:** `{ "compress": { "burstHold": { "enabled": false } } }` disables the hold entirely; `{ "compress": { "burstHold": { "minToolShare": 0.7 } } }` makes it stricter.

#### `prompts`
- **Default:** *(kernel defaults — see `acp-kernel` `defaultPrompts`)*
- **Status:** ACTIVE
Expand Down
12 changes: 12 additions & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,18 @@
- **状态:** ACTIVE
- **说明:** `neverPreserveRecentTools` 的**正向配对旋钮**:从生效的最近区排除列表中**移除**的工具名模式。#1198/#1277 批量读文件「折叠→重读」死循环的解法由此变成一条配置 —— `{ "compress": { "preserveRecentTools": ["read"] } }` —— 既不用重述(也不用冻结一份很快过时的手抄)内置列表,还自动跟随内置列表演化。生效排除表 = `(neverPreserveRecentTools ?? 内置) 减 preserveRecentTools`;可与显式 `neverPreserveRecentTools` 组合(减法同样作用于显式列表);通配后缀模式移除匹配项(`"bash*"` 移除 `bash`)。除非确实需要逐字替换语义,优先用本旋钮而不是改 never-list。**⚠ 空数组 `[]` 会被拒绝** —— 在这里是纯无操作,裸 `[]` 几乎必然是 `neverPreserveRecentTools: []`(最大保护逃生门)的笔误。与同族旋钮一样跨层级整体替换(最深层胜出)。

#### `burstHold`

- **类型:** `object`(`{ enabled?, minToolResults?, lookbackMessages?, minToolShare? }`)
- **默认值:** `{ enabled: true, minToolResults: 5, lookbackMessages: 12, minToolShare: 0.55 }` —— **默认开启**(#1487)
- **状态:** ACTIVE
- **说明:** **工具批量调用期间的压缩提示暂缓(tool-burst nudge hold)。** 当客户端重发的历史尾部以大量新鲜工具结果为主 —— agent 正在批量执行 read/grep/glob/bash —— 且上下文用量仍低于暂缓上限时,**增长型**压缩提示被暂缓,让 agent 先把这一票干完再压,避免它正在使用的工作内容刚出现就被折掉。这是 #1198/#1277「折叠→重读」死循环(dsh discussion #5795 报告)的自动化对策:不必手动用最近区旋钮把新结果挡在折叠之外,提示自己等批量结束。暂缓每请求无状态、双压缩模式与所有 wire 路径一致生效;只暂缓**主动的增长型提示** —— 内核压力带强制提示(用量 ≥ `maxContextLimit`)与宿主紧急提示(用量 ≥ 70%)永远放行,因此批量中途上下文吃紧时立刻照常压缩。暂缓上限 = `min(0.7, 生效的 maxContextLimit)`。子字段(像 `absorb` 一样按子字段跨层级最深层胜出合并):
- `enabled: boolean` —— 默认 `true`;设 `false` 恢复旧版「到点必提示」行为。
- `minToolResults: number` —— 窗口内工具结果达到该数量才算批量(默认 `5`),正整数。
- `lookbackMessages: number` —— 检查的历史尾部窗口大小(消息数,默认 `12`),正整数。
- `minToolShare: number` —— 窗口内工具结果占比下限(0..1](默认 `0.55`)。校准目标:稳定的 assistant/工具交替节奏(~0.5)不触发,并行批量(~0.8+)必触发。
- **示例:** `{ "compress": { "burstHold": { "enabled": false } } }` 完全关闭暂缓;`{ "compress": { "burstHold": { "minToolShare": 0.7 } } }` 收紧触发条件。

#### `prompts`

- **类型:** `object`(`{ compressPhilosophy?, howToCompressRules?, tier2DistillRules?, tier3CondenseRules? }`,均为字符串)
Expand Down
79 changes: 79 additions & 0 deletions src/burst-hold.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import type { CoreMessage } from "acp-kernel";
import { EMERGENCY_NUDGE_ESCALATION_PCT } from "./server/budget.js";

// #1487: tool-burst nudge hold. Batch tool work (e.g. reading a directory of
// files in one turn) fills the trailing history with fresh, high-value results;
// the flat-50K growth nudge firing mid-burst makes the model compress exactly
// the content it is working on, which then gets re-read after the fold — the
// fold→re-read loop reported in #1198/#1277 and the dsh discussion #5795.
// While a burst is active AND context still has headroom, hold GROWTH-based
// nudge injections so the agent can finish its batch; pressure-band nudges
// (kernel force-inject at maxContextLimitPct) and the host emergency nudge
// (>= EMERGENCY_NUDGE_ESCALATION_PCT) are never held, so a context that runs
// out mid-burst still compresses immediately. Stateless per request; applies in
// both compression modes (the proxy-side nudge is the proactive trigger in both).

export interface BurstHoldSettings {
/** Default true (#1487 owner decision: allow the agent to finish its batch
* first while context has headroom). Set false to restore the legacy
* always-nudge behavior. */
enabled?: boolean;
/** Minimum tool-result count in the lookback window to count as a burst. */
minToolResults?: number;
/** Size of the trailing-history window inspected (messages). */
lookbackMessages?: number;
/** Minimum share of the window that must be tool results (0..1]. Steady
* assistant/tool alternation sits near 0.5 and must NOT trip; parallel
* batches sit at 0.8+ and MUST trip. */
minToolShare?: number;
}

export const DEFAULT_BURST_HOLD = {
enabled: true,
minToolResults: 5,
lookbackMessages: 12,
minToolShare: 0.55,
};

export interface BurstDetection {
active: boolean;
toolResults: number;
windowSize: number;
share: number;
}

/** Count tool-result entries in the trailing window of the inbound (normalized)
* history. CoreMessages are flat — one core per tool result on every wire —
* so counting cores counts results. Detection runs on the INCOMING messages
* (what the client just resent), i.e. before processTurn touches state. */
export function detectToolBurst(msgs: CoreMessage[], s?: BurstHoldSettings): BurstDetection {
const enabled = s?.enabled ?? DEFAULT_BURST_HOLD.enabled;
const minToolResults = s?.minToolResults ?? DEFAULT_BURST_HOLD.minToolResults;
const lookback = Math.max(1, Math.floor(s?.lookbackMessages ?? DEFAULT_BURST_HOLD.lookbackMessages));
const minShare = s?.minToolShare ?? DEFAULT_BURST_HOLD.minToolShare;
if (!enabled) return { active: false, toolResults: 0, windowSize: 0, share: 0 };
const win = msgs.slice(-lookback);
let toolResults = 0;
for (const m of win) if (m.contentType === "tool-result") toolResults++;
const share = win.length > 0 ? toolResults / win.length : 0;
return { active: toolResults >= minToolResults && share >= minShare, toolResults, windowSize: win.length, share };
}

/** Usage line below which growth nudges may be held during a burst: the lower
* of the host emergency-escalation line (0.7 — above it the #453 mitigation
* already treats every turn as urgent) and the effective kernel pressure line
* (nudge.maxContextLimitPct, user-configurable and possibly < 0.7). At or
* above this line nothing is ever held. Kernel default when unset/invalid:
* 0.75 (acp-kernel built-in). */
export function burstHoldCeiling(maxContextLimitPct?: number): number {
const maxPct = typeof maxContextLimitPct === "number" && Number.isFinite(maxContextLimitPct) && maxContextLimitPct > 0 ? maxContextLimitPct : 0.75;
return Math.min(EMERGENCY_NUDGE_ESCALATION_PCT, maxPct);
}

/** True = suppress this turn's growth-based nudge injection. Only armed when a
* burst is active AND measured usage is strictly below the ceiling; pressure
* and emergency injections bypass this by construction (their usage lines are
* >= the ceiling). */
export function holdGrowthNudge(det: BurstDetection, contextUsage: number, maxContextLimitPct?: number): boolean {
return det.active && Number.isFinite(contextUsage) && contextUsage >= 0 && contextUsage < burstHoldCeiling(maxContextLimitPct);
}
2 changes: 2 additions & 0 deletions src/compress-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export function mergeCompress(
const absorbLevels = [global?.absorb, provider?.absorb, model?.absorb].filter(Boolean) as NonNullable<CompressSettings["absorb"]>[];
const ccrLevels = [global?.ccr, provider?.ccr, model?.ccr].filter(Boolean) as NonNullable<CompressSettings["ccr"]>[];
const searchLevels = [global?.search, provider?.search, model?.search].filter(Boolean) as NonNullable<CompressSettings["search"]>[];
const burstHoldLevels = [global?.burstHold, provider?.burstHold, model?.burstHold].filter(Boolean) as NonNullable<CompressSettings["burstHold"]>[];
const imageCompressionLevels = [global?.imageCompression, provider?.imageCompression, model?.imageCompression].filter(Boolean) as NonNullable<CompressSettings["imageCompression"]>[];
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"]>[];
Expand All @@ -85,6 +86,7 @@ export function mergeCompress(
absorb: absorbLevels.length > 0 ? Object.assign({}, ...absorbLevels) : undefined,
ccr: ccrLevels.length > 0 ? Object.assign({}, ...ccrLevels) : undefined,
search: searchLevels.length > 0 ? Object.assign({}, ...searchLevels) : undefined,
burstHold: burstHoldLevels.length > 0 ? Object.assign({}, ...burstHoldLevels) : undefined,
imageCompression: imageCompressionLevels.length > 0 ? Object.assign({}, ...imageCompressionLevels) : undefined,
rules: pick("rules"),

Expand Down
47 changes: 47 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,29 @@ export type CompressSettings = {
* Patterns match like kernel tool patterns (exact name or `*` glob).
* Deepest level wins (global → provider → model), whole-array replace. */
preserveRecentTools?: string[];
/** [#1487] Tool-burst nudge hold: while the trailing history is dominated
* by fresh tool results (a batch of reads/greps/globs in flight) AND
* context usage is below the hold ceiling, GROWTH-based compression nudges
* are held so the agent can finish its batch before its working content
* gets folded (the fold→re-read loop, #1198/#1277). Pressure-band nudges
* and the emergency nudge are never held — a context that runs out
* mid-burst still compresses immediately. Default ON (#1487 owner
* decision); `enabled: false` restores the legacy always-nudge behavior.
* Merged sub-field-wise across the three levels like `absorb`. */
burstHold?: {
/** Default true. */
enabled?: boolean;
/** Minimum tool-result count in the window to count as a burst
* (default 5). Positive integer. */
minToolResults?: number;
/** Trailing-history window size in messages (default 12). Positive
* integer. */
lookbackMessages?: number;
/** Minimum share of the window that must be tool results, 0..1
* (default 0.55 — steady assistant/tool alternation near 0.5 must not
* trip, parallel batches at 0.8+ must trip). */
minToolShare?: number;
};
/** Emit 📦/❌ ACP visibility markers after proxy tool executions
* (compress / decompress / search_context / acp_status) — both the marker
* line streamed to the client and the marker message re-injected into
Expand Down Expand Up @@ -1396,6 +1419,30 @@ export function parseCompressSettings(v: unknown): (CompressSettings & { injectT
if (ok) out.search = cleaned;
}
}
if ("burstHold" in obj && obj.burstHold !== undefined) {
const b = obj.burstHold;
if (!b || typeof b !== "object" || Array.isArray(b)) {
ok = false;
} else {
const bo = b as Record<string, unknown>;
const cleaned: NonNullable<CompressSettings["burstHold"]> = {};
for (const key of ["enabled", "minToolResults", "lookbackMessages", "minToolShare"] as const) {
if (!(key in bo)) continue;
const v = bo[key];
if (key === "enabled") {
if (typeof v !== "boolean") { ok = false; continue; }
cleaned.enabled = v;
} else if (key === "minToolShare") {
if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > 1) { ok = false; continue; }
cleaned.minToolShare = v;
} else {
if (typeof v !== "number" || !Number.isInteger(v) || v <= 0) { ok = false; continue; }
cleaned[key] = v;
}
}
if (ok) out.burstHold = cleaned;
}
}
if ("imageCompression" in obj && obj.imageCompression !== undefined) {
const c = obj.imageCompression;
if (!c || typeof c !== "object" || Array.isArray(c)) {
Expand Down
Loading
Loading