Skip to content
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.105",
"version": "0.0.106",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
Expand Down
6 changes: 3 additions & 3 deletions kernel/src/compress-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const COMPRESS_PARAMETERS = {
},
content: {
description:
"One or more ranges to compress into separate summary blocks. Array form: one entry per range — line form (one STRING per range: first line 'm00150–m00220 optional topic', remaining lines the markdown summary verbatim) or object form {startId,endId,summary,topic?}. Single-string form (PREFERRED for multi-range batches — plain text survives lossy gateways best): ONE plain string holding ALL ranges, each block starting with its 'm00150–m00220 optional topic' header line followed by that block's summary. A JSON-encoded array of ranges as that string is also accepted (some gateways stringify arrays). Batch multiple ranges into ONE call — do not split into one call per range. REQUIRED unless the flat single-range form is used.",
"One or more ranges to compress into separate summary blocks. PREFERRED (multi-range batch): ONE plain string holding ALL ranges — each block starts with its 'm00150–m00220 optional topic' header line followed by that block's summary (plain text survives lossy gateways best; a JSON-encoded array as that string is also accepted). Array form: one entry per range — a line-form string or an object {startId,endId,summary,topic?}. Batch multiple ranges into ONE call — do not split into one call per range. REQUIRED unless the flat single-range form is used.",
anyOf: [
{
type: "array",
Expand Down Expand Up @@ -150,7 +150,7 @@ export const COMPRESS_PARAMETERS = {
export const COMPRESS_TOOL = {
name: COMPRESS_TOOL_NAME,
description:
"Replace consumed conversation ranges with self-contained summaries you write, identified by their refs. Line form (preferred): content = one STRING per range — first line 'm00150–m00220 optional topic', remaining lines the markdown summary written verbatim (no JSON structure, no escaping). Also accepted: object entries {startId,endId,summary,topic?} in the content array, content as a single string (bare line form — one string may hold ALL ranges, each block starting with its refs header line — or JSON-encoded array), and a flat single-range call {startId,endId,summary,topic?} without content. Batch multiple ranges into ONE call. Use when content is genuinely consumed. REQUIRED — compress without content or flat range fields is invalid.",
"Replace consumed conversation ranges with self-contained summaries you write, identified by their refs. PREFERRED form: content = ONE plain string holding ALL ranges — each block starts with its 'm00150–m00220 optional topic' header line followed by that block's summary (no JSON structure, no escaping; a JSON-encoded array as that string is also accepted for gateways that stringify arrays). Also accepted: object entries {startId,endId,summary,topic?} in the content array, and a flat single-range call {startId,endId,summary,topic?} without content. Batch multiple ranges into ONE call — do not split into one call per range. Use when content is genuinely consumed. REQUIRED — compress without content or flat range fields is invalid.",
input_schema: COMPRESS_PARAMETERS,
};

Expand Down Expand Up @@ -252,7 +252,7 @@ Each message in the conversation is annotated with a <acp tokens="2.1K" type="to

You have five context-management tools:

- compress — Replace a contiguous range of older conversation with a single detailed summary you write. Use when content is genuinely consumed (no longer needed for the current task step). Single range: compress({ topic: "...", content: [{ startId: "m00150", endId: "m00220", summary: "..." }] }). Batch (multiple unrelated ranges, each with its own topic): compress({ content: [{ topic: "Auth", startId: "m00150", endId: "m00220", summary: "..." }, { topic: "Deploy", startId: "m00300", endId: "m00350", summary: "..." }] }), or the same batch as ONE plain string — most robust through lossy gateways: compress({ content: "m00150–m00220 Auth\\nsummary…\\nm00300–m00350 Deploy\\nsummary…" }) — one block per range, each starting with its 'mNNNNN–mNNNNN optional topic' header line.
- compress — Replace consumed conversation ranges with self-contained summaries you write. ONE call carries EVERY range: compress({ content: "m00150–m00220 Auth\\nsummary…\\nm00300–m00350 Deploy\\nsummary…" }) — one plain string, one block per range, each block starting with its 'mNNNNN–mNNNNN optional topic' header line followed by that block's summary (plain text survives lossy gateways best). A single range is the same shape with one block. Object entries {startId,endId,summary,topic?} in the content array are also accepted. Never split a batch into one call per range.
- decompress — Restore a previously compressed block's content. By default restores one tier up (T2→T1 summaries, not raw messages). Use full: true to restore all the way to original messages. Use toFile to write to file instead of inflating context. Example: decompress({ blockId: "b5" }) or decompress({ blockId: "b5", toFile: "path" }) or decompress({ blockId: "b5", full: true }).
- search_context — Search compressed block summaries (and optionally visible messages) by keyword. Use BEFORE decompressing to find the right block. Example: search_context({ query: "auth token refresh" }).
- acp_status — Context status with compressible ranges. No args = overview + ranges. Use to find what to compress next.`,
Expand Down
2 changes: 1 addition & 1 deletion kernel/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export {
countMessageTokens,
} from "./tokenize.js";
export type { TokenCountFn } from "./tokenize.js";
export { renderNudgeText, formatRanges } from "./nudge-text.js";
export { renderNudgeText, formatRanges, oneCallPayload, oneCallTail } from "./nudge-text.js";
export type {
NudgeVoice,
RenderedNudge,
Expand Down
49 changes: 48 additions & 1 deletion kernel/src/nudge-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,52 @@ function compact(parts: string[]): string[] {
return parts;
}

/** #2302: serialize ranges as a ready-to-fill line-form skeleton — the
* compress tool's preferred content shape. ONE string carries the whole
* batch: one block per range, first line the refs (en dash, optional
* topic slot), remaining lines the model's summary. No JSON shells, no
* escaping. Ranges beyond maxEntries collapse into a trailing same-string
* note. Refs are ours; the wording is the model's. */
export function oneCallPayload(
ranges: readonly CompressibleRange[],
maxEntries = 16,
): string {
const shown = ranges.slice(0, maxEntries);
const blocks = shown.map(
(r) =>
`${r.startRef}–${r.endRef} <topic>\n<write your summary of this range>`,
);
const more = ranges.length - shown.length;
const tailMore =
more > 0
? `\n\n(+${more} more range(s) — continue the SAME string with further blocks, one per range: ${ranges
.slice(maxEntries)
.map((r) => `${r.startRef}–${r.endRef}`)
.join(", ")})`
: "";
return blocks.join("\n\n") + tailMore;
}

/** #2302 root-cause fix, as a nudge tail. The nudge used to hand the model
* a LIST of recommended ranges plus a batching hint — and the model
* digests the list in groups, one compress call per group. Each separate
* call resets the provider prefix cache from its fold point and re-bills
* the whole remaining history; one call carrying every range pays once
* (live incident: five single-range calls over 44s on a 555K-token
* session re-billed 1.38M tokens; one 9-range call on the same log paid
* once). Instructions about batching do not survive contact with the
* model — the arguments themselves now do. Empty when fewer than two
* ranges (nothing to batch). Keeps #1198 licensing: the gentle tip above
* stays conditional, and delete-don't-split semantics mean a model that
* still needs a range drops the block, never folds the call in halves. */
export function oneCallTail(
ranges: readonly CompressibleRange[],
): string {
if (ranges.length < 2) return "";
return `\n\nONE CALL, ONE STRING — copy, fill each summary, DELETE the blocks you still need (they reappear in later nudges); never split into several calls:\n${oneCallPayload(ranges)}`;
}


export function renderNudgeText(
decision: NudgeDecision,
prompts: Prompts = defaultPrompts,
Expand Down Expand Up @@ -285,11 +331,11 @@ export function renderNudgeText(
"",
prompts.howToCompressRules,
"",
`{ "topic": "...", "content": [{ "startId": "<ID>", "endId": "<ID>", "summary": "..." }] }`,
"Only use IDs from visible messages above. Compress older work first.",
"",
rangesStr,
...(blockMapStr ? ["", blockMapStr] : []),
oneCallTail(decision.compressibleRanges),
]).join("\n"),
};
}
Expand All @@ -308,6 +354,7 @@ export function renderNudgeText(
...(blockMapStr ? ["", blockMapStr] : []),
"",
`💡 If you compress, fold the ranges you keep in ONE call — pass multiple content entries (\`content: [{...}, {...}]\`) or ONE plain string holding every range, each block starting with its 'mNNNNN–mNNNNN topic' header line (most robust through lossy gateways). Ranges the task still needs can wait — they reappear in later nudges.`,
oneCallTail(decision.compressibleRanges),
]).join("\n"),
};
}
2 changes: 1 addition & 1 deletion kernel/src/packs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ const LEAN_TOOL_PROMPTS: ToolPrompts = {
"Replace consumed conversation ranges with self-contained summaries using mNNNNN or bN refs; batch multiple ranges into ONE call (a single string may hold every range).",
paramDescriptions: {
content:
"One string per range: first line 'm00150–m00220 optional topic', remaining lines the summary markdown; ONE string may hold several ranges (new header line per range). Object form also accepted.",
"ONE plain string holding ALL ranges — one block per range, first line 'm00150–m00220 optional topic', remaining lines the summary markdown; object entries in the content array also accepted.",
startId: "Inclusive first mNNNNN or bN ref.",
endId: "Inclusive last mNNNNN or bN ref.",
summary: "Self-contained replacement preserving exact technical details.",
Expand Down
2 changes: 1 addition & 1 deletion kernel/tests/fixtures/prompt-function-default.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ TOOLS

You have five context-management tools:

- compress — Replace a contiguous range of older conversation with a single detailed summary you write. Use when content is genuinely consumed (no longer needed for the current task step). Single range: compress({ topic: "...", content: [{ startId: "m00150", endId: "m00220", summary: "..." }] }). Batch (multiple unrelated ranges, each with its own topic): compress({ content: [{ topic: "Auth", startId: "m00150", endId: "m00220", summary: "..." }, { topic: "Deploy", startId: "m00300", endId: "m00350", summary: "..." }] }), or the same batch as ONE plain string — most robust through lossy gateways: compress({ content: "m00150–m00220 Auth\nsummary…\nm00300–m00350 Deploy\nsummary…" }) — one block per range, each starting with its 'mNNNNN–mNNNNN optional topic' header line.
- compress — Replace consumed conversation ranges with self-contained summaries you write. ONE call carries EVERY range: compress({ content: "m00150–m00220 Auth\nsummary…\nm00300–m00350 Deploy\nsummary…" }) — one plain string, one block per range, each block starting with its 'mNNNNN–mNNNNN optional topic' header line followed by that block's summary (plain text survives lossy gateways best). A single range is the same shape with one block. Object entries {startId,endId,summary,topic?} in the content array are also accepted. Never split a batch into one call per range.
- decompress — Restore a previously compressed block's content. By default restores one tier up (T2→T1 summaries, not raw messages). Use full: true to restore all the way to original messages. Use toFile to write to file instead of inflating context. Example: decompress({ blockId: "b5" }) or decompress({ blockId: "b5", toFile: "path" }) or decompress({ blockId: "b5", full: true }).
- search_context — Search compressed block summaries (and optionally visible messages) by keyword. Use BEFORE decompressing to find the right block. Example: search_context({ query: "auth token refresh" }).
- acp_status — Context status with compressible ranges. No args = overview + ranges. Use to find what to compress next.
Expand Down
48 changes: 48 additions & 0 deletions kernel/tests/nudge-text.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,3 +380,51 @@ test("no user-msg annotation when count is zero or absent", () => {
"makeRanges fixtures carry no userMsgs",
);
});

// #2302: the one-call skeleton (line form) rides both gentle and emergency
// nudges — the model gets ready-to-fill compress arguments, not a batch
// hint it will ignore. T2/T3 nudges fold block refs and never see it.
test("#2302: gentle nudge carries the one-call line-form skeleton", () => {
const result = renderNudgeText(makeDecision({ contextUsage: 0.5 }));
assert.ok(result.text.includes("ONE CALL, ONE STRING"), "skeleton framing");
assert.ok(
result.text.includes("m00001–m00003 <topic>"),
"refs header from the recommended ranges",
);
assert.ok(
result.text.includes("<write your summary of this range>"),
"summary slot left to the model",
);
// the old batch hint stays — the skeleton extends it, not replaces it
assert.ok(result.text.includes("fold the ranges you keep in ONE call"));
});

test("#2302: emergency nudge keeps the skeleton but stays unconditional (#1198)", () => {
const emergency = renderNudgeText(
makeDecision({ contextUsage: 0.99, breakdown: { emergencyOverride: 1 } }),
);
assert.ok(emergency.text.includes("ONE CALL, ONE STRING"), "skeleton rides");
assert.ok(
!emergency.text.includes("If you compress"),
"emergency stays unconditional",
);
assert.ok(
emergency.text.includes("ONE CALL, ONE STRING"),
"skeleton framing has no conditional of its own (the emergency header carries the directive)",
);
});

test("#2302: tier-2/tier-3 nudges carry no message-ref skeleton (block refs)", () => {
const t2 = renderNudgeText(
makeDecision({ contextUsage: 0.5, tier: 2, tierTargetBlocks: [] }),
);
assert.ok(!t2.text.includes("ONE CALL, ONE STRING"), "T2 folds blocks");
assert.ok(!t2.text.includes("<write your summary of this range>"));
});

test("#2302: fewer than two ranges → no skeleton (nothing to batch)", () => {
const single = renderNudgeText(
makeDecision({ contextUsage: 0.5, compressibleRanges: makeRanges(1) }),
);
assert.ok(!single.text.includes("ONE CALL, ONE STRING"));
});
2 changes: 1 addition & 1 deletion package-lock.json

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

3 changes: 2 additions & 1 deletion src/acp-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { conflictEventsOf, formatConflictSection } from "./conflict-watch.js";
import { getBlindTunnelStats } from "./mitm.js";
import { getUnrecognizedPathStats } from "./server/observability.js";
import { ccrEnabled, ccrLoopConfig, contentStoreOf } from "./store.js";
import { oneCallTail } from "acp-kernel";
import { coveredRefSpan } from "./decompress-shared.js";
import { preCompactionArchiveOf, statusInputBaseline, type Session } from "./session.js";
import { describeAdvisory, getAdvisoryState } from "./advisory.js";
Expand Down Expand Up @@ -77,7 +78,7 @@ export function handleAcpStatus(args: Record<string, unknown>, ctx: AcpStatusCtx
const protectedRanges = nudge.protectedRanges ?? [];
if (ranges.length > 0 || protectedRanges.length > 0) {
extra.push("");
extra.push(formatRanges(ranges, protectedRanges));
extra.push(formatRanges(ranges, protectedRanges) + oneCallTail(ranges));
}
}
} catch {
Expand Down
12 changes: 8 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3964,8 +3964,9 @@ async function prepareAnthropic(
if (willInjectNudge && turn.nudge) {
try {
const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections);
const renderedWithPayload = rendered.text;
if (rendered.text) {
rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(rendered.text), externalSummaryEnabled(config)), visibilityMarkers) }];
rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) }];
}
} catch {
}
Expand Down Expand Up @@ -4213,8 +4214,9 @@ async function prepareOpenai(
if (willInjectNudge && turn.nudge) {
try {
const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections);
const renderedWithPayload = rendered.text;
if (rendered.text) {
rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(rendered.text), externalSummaryEnabled(config)), visibilityMarkers) }];
rebuiltMessages = [...rebuiltMessages, { role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) }];
}
} catch {
}
Expand Down Expand Up @@ -4464,8 +4466,9 @@ async function prepareGoogle(
if (willInjectNudge && turn.nudge) {
try {
const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections);
const renderedWithPayload = rendered.text;
if (rendered.text) {
rebuiltContents = appendGoogleNudge(rebuiltContents, withMarkerIntegrityNote(withStagedCompressGuidance(rendered.text), visibilityMarkers));
rebuiltContents = appendGoogleNudge(rebuiltContents, withMarkerIntegrityNote(withStagedCompressGuidance(renderedWithPayload), visibilityMarkers));
}
} catch {
}
Expand Down Expand Up @@ -4792,11 +4795,12 @@ async function prepareResponses(
if (willInjectNudge && turn.nudge) {
try {
const rendered = renderNudgeText(turn.nudge, prompts, surface?.nudgeSections);
const renderedWithPayload = rendered.text;
if (rendered.text) {
const inputItems: ResponseInputItem[] = typeof rebuiltInput === "string"
? [{ type: "message", role: "user", content: rebuiltInput }]
: rebuiltInput;
inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(rendered.text), externalSummaryEnabled(config)), visibilityMarkers) });
inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(renderedWithPayload), externalSummaryEnabled(config)), visibilityMarkers) });
rebuiltInput = inputItems;
log("debug", `[${sessionId}] [inject] ephemeral nudge appended as trailing user turn (${rendered.text.length} chars)`);
}
Expand Down
Loading
Loading