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 kernel/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "acp-kernel",
"version": "0.0.109",
"version": "0.0.110",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
Expand Down
1 change: 1 addition & 0 deletions kernel/src/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,7 @@ const assignRefsNode: PipelineNode = {
const hasProtection =
ctx.config.protectedTools.length > 0 ||
!!ctx.config.isToolProtected ||
!!ctx.config.isMessageProtected ||
(ctx.config.protectedLatestTools?.length ?? 0) > 0;
const latest = hasProtection
? collectLatestProtected(io.messages, ctx.config)
Expand Down
6 changes: 5 additions & 1 deletion kernel/src/protected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,12 @@ export function matchToolMessagePattern(

export function isMessageProtected(
msg: CoreMessage,
config: Pick<Config, "protectedTools" | "isToolProtected">,
config: Pick<Config, "protectedTools" | "isToolProtected" | "isMessageProtected">,
): boolean {
// Host-declared message-level protection (#2419): applies to ANY content
// type and outranks everything below — the host owns the decision.
if (config.isMessageProtected?.(msg)) return true;

// tool-result carries the same toolName as its tool-call (the host projects
// it), so checking toolName covers both sides of a tool exchange.
if (
Expand Down
15 changes: 15 additions & 0 deletions kernel/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,21 @@ export interface Config {
compress: CompressValidationConfig;
protectedTools: string[];
isToolProtected?: (toolName: string, toolInputText?: string) => boolean;
/** Host-declared message-level hard protection (billion-context#2419):
* when set, ANY message for which the predicate returns true is excluded
* from compression exactly like a protectedTools hit — BLOCKED ref in
* assignRefs (never advertised, never foldable-by-ref) AND dropped from
* effectiveMessageIds in applyCompression (stays fully visible; the
* summary reflects only what was actually folded). Applies to every
* content type; the tool-exchange checks below run additionally, not
* instead. Use for host-injected DURABLE STATE carried as ordinary
* conversation messages — e.g. dsh's skill catalog, which DSH
* fingerprint-gates (sha256 over name+description) and never resends
* while unchanged, so folding it loses skill visibility permanently.
* Unset = byte-identical behavior to before (only tool exchanges and
* media payloads are protectable). Must be pure and cheap: it runs once
* per message per turn. */
isMessageProtected?: (msg: CoreMessage) => boolean;
/** Tool-name patterns (glob suffix allowed) protected in their LATEST
* instance only: the newest matching tool-call and its paired tool-result
* are protected from compression; older instances remain compressible. For
Expand Down
224 changes: 224 additions & 0 deletions kernel/tests/message-protection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
// #2419: host-declared message-level hard protection (Config.isMessageProtected).
// The dsh skill catalog rides as an ordinary user-role text message and DSH
// never resends it while its fingerprint is unchanged — folding it loses skill
// visibility permanently. These tests pin the generic mechanism: any message
// matching the host predicate is excluded from compression exactly like a
// protectedTools hit, for every content type, in both the assignRefs path
// (BLOCKED ref — never advertised) and the applyCompression path (excluded
// from effectiveMessageIds — stays visible).
import { test } from "node:test";
import assert from "node:assert/strict";
import { createCore } from "../src/compress.js";
import { createInitialState } from "../src/state.js";
import { assignRefs, BLOCKED_REF } from "../src/refs.js";
import { defaultConfig } from "../src/config.js";
import type { Config, CoreMessage } from "../src/types.js";

const CATALOG_MARKER = "\x3cavailable_skills\x3e";

function msg(
id: string,
text: string,
role: CoreMessage["role"] = "user",
): CoreMessage {
return { id, role, contentType: "text", text };
}

function setupRefs(messages: CoreMessage[]) {
const state = createInitialState();
state.messageRefs = assignRefs(messages, {
existing: state.messageRefs,
nextIndex: 1,
}).map;
return state;
}

const longText = "x".repeat(6000);
const catalogText = `\x3csystem-reminder\x3e ${CATALOG_MARKER} skill-a: does A; skill-b: does B \x3c/system-reminder\x3e`;
const validSummary =
"A meaningful summary that captures the key information of the compressed range including file paths and decisions.";

function cfg(overrides: Partial<Config> = {}): Config {
return defaultConfig(200000, {
compress: { minCompressRange: 0, maxSummaryLength: 0, minSummaryLength: 0 },
preserveRecentMessages: 0,
preserveRecentTokens: 0,
...overrides,
});
}

const catalogGuard = (m: CoreMessage) =>
m.contentType === "text" && m.text?.includes(CATALOG_MARKER) === true;

test("isMessageProtected: predicate-protected user text message is excluded from the range", () => {
const core = createCore();
const messages = [
msg("a", longText),
msg("catalog", catalogText),
msg("d", longText),
];
const state = setupRefs(messages);
const config = cfg({ isMessageProtected: catalogGuard });

const result = core.applyCompression({
ranges: [{ startRef: "m00001", endRef: "m00003", summary: validSummary }],
messages,
state,
config,
});

assert.equal(result.result.blocksCreated, 1);
assert.equal(result.result.errors.length, 0);

const block = result.state.blocks[0]!;
assert.ok(
!block.directMessageIds.includes("catalog"),
"catalog must be excluded from the compressed set",
);
assert.ok(
!block.effectiveMessageIds.includes("catalog"),
"catalog must be excluded from effective coverage (stays visible)",
);
assert.ok(block.directMessageIds.includes("a"), "regular msg 'a' folded");
assert.ok(block.directMessageIds.includes("d"), "regular msg 'd' folded");
assert.equal(
block.summary,
validSummary,
"summary is exactly what the author wrote — no protected content appended",
);
});

test("isMessageProtected: applies to every content type, not just user text", () => {
const core = createCore();
const messages = [
msg("a", longText),
msg("assistant-catalog", catalogText, "assistant"),
msg("d", longText),
];
const state = setupRefs(messages);
const config = cfg({ isMessageProtected: catalogGuard });

const result = core.applyCompression({
ranges: [{ startRef: "m00001", endRef: "m00003", summary: validSummary }],
messages,
state,
config,
});

const block = result.state.blocks[0]!;
assert.ok(
!block.effectiveMessageIds.includes("assistant-catalog"),
"assistant-role message matching the predicate is protected too",
);
assert.ok(block.effectiveMessageIds.includes("a"), "msg 'a' folded");
assert.ok(block.effectiveMessageIds.includes("d"), "msg 'd' folded");
});

test("isMessageProtected: without the predicate the same message folds normally", () => {
const core = createCore();
const messages = [
msg("a", longText),
msg("catalog", catalogText),
msg("d", longText),
];
const state = setupRefs(messages);
const config = cfg(); // no isMessageProtected

const result = core.applyCompression({
ranges: [{ startRef: "m00001", endRef: "m00003", summary: validSummary }],
messages,
state,
config,
});

const block = result.state.blocks[0]!;
assert.ok(
block.effectiveMessageIds.includes("catalog"),
"unset predicate = byte-identical behavior: catalog folds like any other message",
);
});

test("isMessageProtected: predicate-protected message gets a BLOCKED ref via processTurn (never advertised)", () => {
const core = createCore();
const messages = [
msg("a", longText),
msg("catalog", catalogText),
msg("d", longText),
];
const state = createInitialState();
const config = cfg({ isMessageProtected: catalogGuard });

const turn = core.processTurn({
messages,
state,
config,
tokenCount: 1000,
});

assert.equal(
turn.state.messageRefs.byRaw["catalog"],
BLOCKED_REF,
"protected message must carry the BLOCKED ref (no mNNNNN allocated)",
);
assert.notEqual(
turn.state.messageRefs.byRaw["a"],
BLOCKED_REF,
"unprotected message keeps a normal ref",
);
assert.notEqual(
turn.state.messageRefs.byRaw["d"],
BLOCKED_REF,
"unprotected message keeps a normal ref",
);
});

test("isMessageProtected: legacy refs assigned before protection still cannot be folded (upgrade path)", () => {
const core = createCore();
const messages = [
msg("a", longText),
msg("catalog", catalogText),
msg("d", longText),
];
// Simulates a session whose state predates the guard: refs were assigned
// with NO protection, so the catalog holds a live m-ref.
const state = setupRefs(messages);
assert.notEqual(state.messageRefs.byRaw["catalog"], BLOCKED_REF);
const config = cfg({ isMessageProtected: catalogGuard });

const result = core.applyCompression({
ranges: [{ startRef: "m00001", endRef: "m00003", summary: validSummary }],
messages,
state,
config,
});

const block = result.state.blocks[0]!;
assert.ok(
!block.effectiveMessageIds.includes("catalog"),
"pre-existing ref does not make the message foldable once protected",
);
assert.ok(block.effectiveMessageIds.includes("a"), "msg 'a' folded");
assert.ok(block.effectiveMessageIds.includes("d"), "msg 'd' folded");
});

test("isMessageProtected: range consisting solely of protected messages fails with a clear error", () => {
const core = createCore();
const messages = [msg("catalog", catalogText)];
const state = setupRefs(messages);
const config = cfg({ isMessageProtected: catalogGuard });

const result = core.applyCompression({
ranges: [{ startRef: "m00001", endRef: "m00001", summary: validSummary }],
messages,
state,
config,
});

assert.equal(result.result.blocksCreated, 0, "nothing may be created");
assert.equal(result.result.errors.length, 1);
assert.match(
result.result.errors[0]!,
/no compressible messages/,
"an entirely-protected range must fail loudly, not fake-compress",
);
});
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.

92 changes: 92 additions & 0 deletions src/durable-message-guards.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// #2419/#2447/#2481: durable-state message guards, declared per plugin lane.
//
// Some hosts inject DURABLE STATE as ordinary conversation messages and gate
// re-injection on a content fingerprint: dsh ships three such carriers as
// user-role messages — dsh-tool-skill's skill catalog (\x3cavailable_skills\x3e,
// #2419; never resent while the sha256(name+description) digest is unchanged),
// @deepseek-ai/dsh-agent-instructions' workspace-instructions baseline
// (#2447: global + project AGENTS.md merged into ONE message, re-emitted only
// when baselineIdentity — projectRoot + discovery/budget config, NOT file
// contents — changes), and the agent-loop runtime-context snapshot (#2481:
// sandbox/approval policy state, self-declared "supersedes earlier
// runtime-context snapshots" — resent only when the runtime context CHANGES,
// not every turn). ACP compression treats every history message as consumable,
// so one fold of any carrier silently kills its guidance forever (the host
// will not resend what it believes is already present). The structured
// source.kind these hosts stamp internally never reaches the proxy wire
// (CoreMessage carries no metadata field), so the guards match stable text
// markers instead — the same criterion discipline as #2447. The kernel's
// protection surface was tool-exchange-only (protectedTools /
// isToolProtected), structurally unable to cover a plain text message — hence
// the generic Config.isMessageProtected hook (kernel 0.0.108) and this
// lane-scoped policy map. The mechanism lives in the kernel; the POLICY
// (which shapes, for which host) lives here, one entry per lane with traffic
// evidence.
//
// KDD #9 evidence-permitlist discipline applies: entries are added PER HOST
// with traffic evidence (shape + stability proof), never enabled wholesale —
// a message-shape guard applied to every lane would hard-pin arbitrary user
// prose into context for hosts whose state carriers have no such contract.

import type { CoreMessage } from "acp-kernel";

type DurableMessageGuard = (msg: CoreMessage) => boolean;

/** dsh skill-catalog guard (#2419): matches the durable catalog message
* injected by dsh-tool-skill (a \x3csystem-reminder\x3e carrying the
* \x3cavailable_skills\x3e block; source: asar dsh-tool-skill/lib/index.js,
* createUserMessage({ source: { kind: "skill-catalog" } })). The marker is
* matched on its own rather than on the wrapper so a future wrapper change
* cannot silently disarm the guard; a false positive is benign (a matching
* message simply stays visible) and the marker is DSH-specific XML. */
export function dshSkillCatalogGuard(msg: CoreMessage): boolean {
return msg.contentType === "text" && typeof msg.text === "string" && msg.text.includes("\x3cavailable_skills\x3e");
}

/** dsh workspace-instructions guard (#2447): matches the durable AGENTS.md
* baseline message injected by @deepseek-ai/dsh-agent-instructions — global
* (~/.dsh/AGENTS.md) and project instructions merged into ONE user-role
* \x3csystem-reminder\x3e message whose sections are labelled
* `Instructions from: <path>` (source: lib/index.js sectionText +
* createUserMessage). The host re-emits the baseline only when
* baselineIdentity (projectRoot + discovery/budget config, NOT file contents)
* changes, so one fold of it silently kills hard constraints like "read X
* before any web access" forever. Same marker-over-wrapper rationale as
* dshSkillCatalogGuard: the per-file label is matched on its own so wrapper/
* intro rewording cannot silently disarm the guard; a false positive is
* benign (a matching message simply stays visible). The match is
* case-sensitive on purpose — reconciliation change messages use lowercase
* variants ("Updated instructions from:") that remain ordinary consumable
* history. At most ~one such baseline lives per session (replacements are
* rare identity changes), so pinning every match is bounded. */
export function dshWorkspaceInstructionsGuard(msg: CoreMessage): boolean {
return msg.contentType === "text" && typeof msg.text === "string" && msg.text.includes("Instructions from:");
}

/** dsh runtime-context guard (#2481): matches the durable runtime-context
* snapshot injected by the dsh agent loop — sandbox/approval policy state
* carried as a user-role message containing "Current runtime context"
* (source: deepseek-ai/deepseek-harness MIT packages/core/agent-loop/src/
* runtime-context.ts; the same text family bili already recognizes as an
* auto-injected notification in #2286's AUTO_INJECTED_NOTIFICATION_PREFIXES).
* Both variants match on purpose: the populated snapshot ("Current runtime
* context. This snapshot supersedes earlier runtime-context snapshots. …")
* AND the cleared form ("Current runtime context: none. Earlier
* runtime-context snapshots no longer apply.") — the cleared notice must
* stay visible too, because it is what invalidates the older snapshots this
* guard pins. The host re-emits only when the runtime context CHANGES (the
* per-turn time-context carrier deliberately stays foldable), so one fold of
* the latest snapshot silently drops the session's sandbox/approval semantics
* forever. Each snapshot is tiny (~100–400 chars); superseded ones keep
* pinning harmlessly because the newest carries the supersedes clause. */
export function dshRuntimeContextGuard(msg: CoreMessage): boolean {
return msg.contentType === "text" && typeof msg.text === "string" && msg.text.includes("Current runtime context");
}

/** Lane → guard registry. Only lanes with traffic evidence of the
* durable-user-message carrier belong here (KDD #9). Keyed by the value of
* the x-bili-plugin header / session.metadata.pluginAgent binding. */
export const durableMessageGuards: Record<string, DurableMessageGuard> = {
dsh: (msg) =>
dshSkillCatalogGuard(msg) || dshWorkspaceInstructionsGuard(msg) || dshRuntimeContextGuard(msg),
};
Loading
Loading