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: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"name": "billion-context",
"source": "./",
"description": "Context-compression plugin for Claude Code · month-long single sessions (billions of tokens) · high compression quality even in small context windows (100K is enough) · 5× fewer tokens",
"version": "0.1.186",
"version": "0.1.188",
"author": {
"name": "ranxianglei"
},
Expand Down
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "billion-context",
"version": "0.1.186",
"version": "0.1.188",
"description": "Context-compression plugin for Claude Code · month-long single sessions (billions of tokens) · high compression quality even in small context windows (100K is enough) · 5× fewer tokens",
"author": {
"name": "ranxianglei"
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.106",
"version": "0.0.107",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
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, oneCallPayload, oneCallTail } from "./nudge-text.js";
export { renderNudgeText, formatRanges, ONE_CALL_HINT } from "./nudge-text.js";
export type {
NudgeVoice,
RenderedNudge,
Expand Down
64 changes: 17 additions & 47 deletions kernel/src/nudge-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,51 +229,21 @@ 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)}`;
}

/** #2302 root-cause fix, distilled to a STATIC reminder. 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 — but
* the expanded ready-to-fill skeleton had its own failure mode (#2377
* review): it grows linearly with the range count, reads like a mandatory
* to-do list (eroding the model's own judgment on WHAT to fold), and leaked
* onto query-only surfaces (acp_status). So the reminder is now ONE static
* line — never expanded, never range-aware, identical for every nudge. */
export const ONE_CALL_HINT =
"ONE call, ONE string — fold every range you keep into a single compress call: content entries ({startId, endId, summary, topic?}) or one plain string holding one block per range ('m00150–m00220 topic' header line, then the summary). Ranges you still need can wait — they reappear in later nudges; never split the batch across separate calls.";

export function renderNudgeText(
decision: NudgeDecision,
Expand Down Expand Up @@ -335,7 +305,8 @@ export function renderNudgeText(
"",
rangesStr,
...(blockMapStr ? ["", blockMapStr] : []),
oneCallTail(decision.compressibleRanges),
"",
ONE_CALL_HINT,
]).join("\n"),
};
}
Expand All @@ -354,7 +325,6 @@ 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"),
};
}
63 changes: 39 additions & 24 deletions kernel/tests/nudge-text.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,50 +381,65 @@ test("no user-msg annotation when count is zero or absent", () => {
);
});

// #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", () => {
// #2302 as shipped in v0.1.188+: the one-call reminder is a STATIC line —
// never expanded per range, never range-aware. The expanded skeleton grew
// linearly with the range count, read like a mandatory to-do list, and leaked
// onto query-only surfaces (acp_status). T2/T3 nudges fold block refs and
// never see it.
test("#2302: gentle nudge carries the static one-call hint, no expanded 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",
result.text.includes("fold the ranges you keep in ONE call"),
"static one-call batch hint",
);
assert.ok(
result.text.includes("<write your summary of this range>"),
"summary slot left to the model",
!result.text.includes("<write your summary of this range>"),
"no ready-to-fill skeleton",
);
assert.ok(
!result.text.includes("<topic>"),
"no per-range skeleton headers",
);
// 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)", () => {
test("#2302: emergency nudge carries the static hint, 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("ONE call, ONE string"),
"static hint rides emergency too",
);
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)",
!emergency.text.includes("<write your summary of this range>"),
"no skeleton even in emergency",
);
});

test("#2302: tier-2/tier-3 nudges carry no message-ref skeleton (block refs)", () => {
const t2 = renderNudgeText(
makeDecision({ contextUsage: 0.5, tier: 2, tierTargetBlocks: [] }),
test("#2302: hint never grows with the range count", () => {
const few = renderNudgeText(
makeDecision({ contextUsage: 0.5, compressibleRanges: makeRanges(2) }),
);
const many = renderNudgeText(
makeDecision({ contextUsage: 0.5, compressibleRanges: makeRanges(24) }),
);
const count = (s: string) => (s.match(/ONE call, ONE string/g) ?? []).length;
assert.equal(count(few.text), 0, "gentle hint phrased conditionally");
assert.equal(count(many.text), 0, "24 ranges — still no expanded skeleton");
assert.ok(
many.text.length < few.text.length + 200 * 22,
"growth stays bounded by the ranges table, not a skeleton",
);
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) }),
test("#2302: tier-2/tier-3 nudges carry no message-ref hint (block refs)", () => {
const t2 = renderNudgeText(
makeDecision({ contextUsage: 0.5, tier: 2, tierTargetBlocks: [] }),
);
assert.ok(!single.text.includes("ONE CALL, ONE STRING"));
assert.ok(!t2.text.includes("ONE call, ONE string"), "T2 folds blocks");
assert.ok(!t2.text.includes("<write your summary of this range>"));
});
4 changes: 2 additions & 2 deletions 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 package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "billion-context",
"version": "0.1.187",
"version": "0.1.188",
"description": "A context-compression plugin — small context windows (a 100K context is enough), 5x fewer tokens, month-long single sessions (billions of tokens), and compression quality — for all agents: pi, OpenCode, Codex, Claude Code, and more. billion-context is all you need.",
"type": "module",
"main": "dist/index.js",
Expand Down
3 changes: 1 addition & 2 deletions src/acp-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { conflictClientOf, conflictEventsOf, formatConflictSection } from "./con
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 @@ -78,7 +77,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) + oneCallTail(ranges));
extra.push(formatRanges(ranges, protectedRanges));
}
}
} catch {
Expand Down
2 changes: 2 additions & 0 deletions src/agent/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ function reportSessionName(ctx: Ctx | undefined, name: string): void {
headers: { "content-type": "application/json" },
body: JSON.stringify({ conversationId: sid, name }),
signal: AbortSignal.timeout(5000),
}).then((res) => {
if (!res.ok) lastReportedNames.delete(sid);
}).catch(() => {
lastReportedNames.delete(sid);
});
Expand Down
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ Usage:
global install, dsh bundles refresh through
dsh's channel, host-owned copies are pointed
at their host's updater — never overwritten
bili plugin list show install status + installed (on-disk) version for every host
bili plugin list show install status + installed (on-disk) version for every host
bili mcp run the bili MCP server standalone (stdio)
bili plugin-register <id> pre-bind a conversation to the plugin mode
(--origin URL, --agent name)
Expand Down
3 changes: 2 additions & 1 deletion src/lane-credentials.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { findRoute, type ProxyOptions } from "./config.js";
import { SummaryCredentialStore } from "./external-summary-credentials.js";
import { maskUrlForLog } from "./log-mask.js";

/**
* #2336 lane credential override (forward path). `providers[URL].apiKeyEnv`
Expand Down Expand Up @@ -47,7 +48,7 @@ export function laneCredential(
const fail = (reason: string): undefined => {
if (!warnedLaneCredentials.has(signature)) {
warnedLaneCredentials.add(signature);
warn(`[lane-credential] ${reference} for ${upstreamUrl ?? "the lane"} ${reason} — keeping the client's own headers (#2336)`);
warn(`[lane-credential] ${reference} for ${upstreamUrl ? maskUrlForLog(upstreamUrl) : "the lane"} ${reason} — keeping the client's own headers (#2336)`);
}
return undefined;
};
Expand Down
1 change: 1 addition & 0 deletions src/log-mask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ export function redactSecretsInText(text: string): string {
return text
.replace(/\b(bearer|basic)\s+([A-Za-z0-9._~+\/=-]{8,})/gi, (_m, scheme: string, tok: string) => `${scheme} <masked ${tok.length} chars>`)
.replace(/(?<![A-Za-z0-9])(?:sk|xai)-[A-Za-z0-9_-]{8,}/g, "<masked key>")
.replace(/(?<![A-Za-z0-9])AIza[A-Za-z0-9_-]{20,}/g, "<masked key>")
.replace(/eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g, "<masked jwt>")
.replace(/(\b(?:api[_-]?key|access[_-]?token|auth(?:orization)?|secret|passwd|password|token)\b\s*[:=]\s*)(["']?)([A-Za-z0-9._~+\/=-]{8,})\2/gi, (_m, pre: string, q: string, val: string) => `${pre}${q}<masked ${val.length} chars>${q}`);
}
4 changes: 2 additions & 2 deletions src/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { type Session, cacheBlockContent, markDirty, statusInputBaseline } from
import { COMPRESS_TOOL_NAME, parseCompressInput, ABSORB_TOOL_NAME, type ParsedRange } from "./compress-tool.js";
import { effectiveAbsorbConfig, executeAbsorb, isProxyToolFor } from "./absorb.js";
import { executeSearchContextTarget, resolveDecompress } from "./decompress-shared.js";
import { oneCallTail } from "acp-kernel";
import { ONE_CALL_HINT } from "acp-kernel";
import { adoptContentStore, contentStoreOf, ccrEnabled, drainPendingRetrievals, executeRetrieve, retrieveToolName } from "./store.js";
import { IMAGE_FULL_TOOL_NAME, executeImageFull, imageCompressionEnabled } from "./image-compress.js";
import { imagePlaceholdersForSummary } from "./image-note.js";
Expand Down Expand Up @@ -404,7 +404,7 @@ function postCompressTail(ctx: RewriteCtx, cleanSuccess: boolean): string {
const remaining = viableRanges(nudge.compressibleRanges)
.filter((r) => minChars <= 0 || (r.chars ?? r.tokens * 4) >= minChars);
if (remaining.length > 0) {
return `\n\nCurrent compressible ranges (use these refs exactly as listed):\n${formatRanges(remaining, [])}` + oneCallTail(remaining);
return `\n\nCurrent compressible ranges (use these refs exactly as listed):\n${formatRanges(remaining, [])}\n${ONE_CALL_HINT}`;
}
// A tier-distillation nudge means block-boundary compress calls (bN..bM)
// are still actionable — a stop signal there would contradict the tier
Expand Down
Loading
Loading