Skip to content
Open
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
4 changes: 2 additions & 2 deletions kernel/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 kernel/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "acp-kernel",
"version": "0.0.217",
"version": "0.0.218",
"description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
"license": "MIT",
"author": "ranxianglei",
Expand Down
80 changes: 68 additions & 12 deletions kernel/src/wire/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export type AnthropicThinking = {
type: "thinking";
thinking: string;
signature?: string;
cache_control?: unknown;
[key: string]: unknown;
};
export type AnthropicRedactedThinking = {
type: "redacted_thinking";
Expand Down Expand Up @@ -95,11 +97,16 @@ export function buildSystem(
return text;
}

type Flat = { msgs: BiliMessage[]; cacheControls: Map<string, unknown> };
type Flat = {
msgs: BiliMessage[];
cacheControls: Map<string, unknown>;
clientMessageControls: Map<string, unknown>;
};

export function anthropicToCore(body: AnthropicRequestBody): Flat {
const msgs: BiliMessage[] = [];
const cacheControls = new Map<string, unknown>();
const clientMessageControls = new Map<string, unknown>();
const clusters = new ClusterCounter();
// Backfill toolName onto tool-results from their paired tool_use: the wire
// format only carries the call id on results, but kernel guards
Expand All @@ -122,6 +129,7 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat {
if (mark) cacheControls.set(core.id, mark);
continue;
}
const msgLevelCtrl = (m as { cache_control?: unknown }).cache_control;
const blocks =
typeof m.content === "string"
? [{ type: "text" as const, text: m.content }]
Expand Down Expand Up @@ -203,14 +211,26 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat {
"reasoning",
b.thinking,
);
const id = clusters.next(base);
const hasExtra = Object.keys(b).some(
(k) =>
k !== "type" &&
k !== "thinking" &&
k !== "signature" &&
k !== "cache_control",
);
msgs.push({
id: clusters.next(base),
id,
role: "assistant",
contentType: "reasoning",
text: b.thinking,
anthropicThinking: true,
...(b.signature ? { thinkingSignature: b.signature } : {}),
...(typeof b.signature === "string"
? { thinkingSignature: b.signature }
: {}),
...(hasExtra ? { rawAnthropicBlock: b } : {}),
});
if (b.cache_control) cacheControls.set(id, b.cache_control);
break;
}
case "image": {
Expand Down Expand Up @@ -240,15 +260,19 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat {
? imageMediaFingerprint(source.url)
: undefined,
});
const id = clusters.next(base);
msgs.push({
id: clusters.next(base),
id,
role: m.role,
contentType: "text",
text: CANONICAL_IMAGE_TEXT,
imagePart: true,
rawAnthropicBlock: b,
...mediaSidecar,
});
if ((b as { cache_control?: unknown }).cache_control) {
cacheControls.set(id, (b as { cache_control?: unknown }).cache_control);
}
break;
}
case "redacted_thinking": {
Expand All @@ -263,13 +287,17 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat {
"text",
CANONICAL_REDACTED_THINKING_TEXT,
);
const id = clusters.next(base);
msgs.push({
id: clusters.next(base),
id,
role: m.role,
contentType: "text",
text: "[redacted_thinking]",
rawAnthropicBlock: b,
});
if ((b as { cache_control?: unknown }).cache_control) {
cacheControls.set(id, (b as { cache_control?: unknown }).cache_control);
}
break;
}
default: {
Expand All @@ -283,22 +311,35 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat {
const label =
typeof unknownType === "string" ? `[${unknownType}]` : "[unknown]";
const base = deriveCanonicalMessageId(m.role, "text", label);
const id = clusters.next(base);
msgs.push({
id: clusters.next(base),
id,
role: m.role,
contentType: "text",
text: label,
rawAnthropicBlock: b,
});
if ((b as { cache_control?: unknown }).cache_control) {
cacheControls.set(id, (b as { cache_control?: unknown }).cache_control);
}
break;
}
}
}
for (let k = before; k < msgs.length; k++) {
(msgs[k] as BiliMessage).wireIndex = wireIndex;
}
if (msgLevelCtrl !== undefined) {
for (let k = msgs.length - 1; k >= before; k--) {
const cand = msgs[k]!;
if (cand.contentType !== "reasoning") {
clientMessageControls.set(cand.id, msgLevelCtrl);
break;
}
}
}
}
return { msgs, cacheControls };
return { msgs, cacheControls, clientMessageControls };
}

// Mid-conversation system messages (Pi's tool_addition / tool_removal
Expand Down Expand Up @@ -639,7 +680,7 @@ export function coreToAnthropic(
switch (m.contentType) {
case "text": {
if (m.rawAnthropicBlock) {
current.blocks.push(m.rawAnthropicBlock as AnthropicBlock);
current.blocks.push({ ...(m.rawAnthropicBlock as AnthropicBlock), ...cc(m.id) });
break;
}
// Cross-lane image: no foreign raw block to reuse — rebuild the
Expand Down Expand Up @@ -670,7 +711,7 @@ export function coreToAnthropic(
break;
case "tool-result":
if (m.rawAnthropicBlock) {
current.blocks.push(m.rawAnthropicBlock as AnthropicBlock);
current.blocks.push({ ...(m.rawAnthropicBlock as AnthropicBlock), ...cc(m.id) });
break;
}
current.blocks.push({
Expand All @@ -682,26 +723,41 @@ export function coreToAnthropic(
});
break;
case "reasoning":
if (m.rawAnthropicBlock) {
current.blocks.push({
...(m.rawAnthropicBlock as AnthropicThinking),
type: "thinking",
thinking: m.text ?? "",
...(typeof m.thinkingSignature === "string"
? { signature: m.thinkingSignature }
: {}),
...cc(m.id),
});
break;
}
if (m.thinkingSignature) {
current.blocks.push({
type: "thinking",
thinking: m.text ?? "",
signature: m.thinkingSignature,
...(typeof m.thinkingSignature === "string"
? { signature: m.thinkingSignature }
: {}),
...cc(m.id),
});
} else if (m.anthropicThinking && (m.text ?? "").length > 0) {
// Same-lane round-trip (#5495): this core came from an Anthropic
// wire thinking block — an unsigned upstream (DeepSeek /anthropic)
// accepted it without a signature and REQUIRES it passed back
// verbatim ("content[].thinking ... must be passed back"). Re-emit
// as a thinking block, never as text.
current.blocks.push({ type: "thinking", thinking: m.text ?? "" });
current.blocks.push({ type: "thinking", thinking: m.text ?? "", ...cc(m.id) });
} else if ((m.text ?? "").length > 0) {
// Unsigned reasoning of FOREIGN origin (cross-lane re-render,
// e.g. openai reasoning_content after a model switch): the
// Anthropic API rejects unsigned thinking blocks it did not issue,
// so degrade to a visible text block — pi's requiresThinkingAsText
// parity. Same-lane signed behavior is unchanged.
current.blocks.push({ type: "text", text: m.text ?? "" });
current.blocks.push({ type: "text", text: m.text ?? "", ...cc(m.id) });
}
break;
}
Expand Down
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.

9 changes: 5 additions & 4 deletions src/loop/adapter-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { CoreMessage } from "acp-kernel";
import { coreToAnthropic, healAnthropicSystemPositions, insertBeforeTrailingSystemRun, type AnthropicRequestBody } from "acp-kernel/wire";
import { dedupeAdjacentOutputConfig } from "../dedupe-adjacent-output-config.js";
import { appendSystemText, declaredInclusiveFromUsage, lastIterationContext } from "../util.js";
import { stampAnthropicSystemCacheControl } from "./cache-control.js";
import { stampSystemWithinAnthropicBudget } from "./cache-control.js";
import { buildVisibilityMarker } from "./core.js";
import { composeStreamFilters, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js";
import { degenerateTurnWarning } from "../degenerate-turn.js";
Expand Down Expand Up @@ -131,7 +131,7 @@ function buildTextDeltaEvent(index: number, text: string): Buffer {
);
}

export function createAnthropicAdapter(requestBody: Record<string, unknown>, originalSystem?: AnthropicRequestBody["system"], notes?: string[], errorShape: "protocol" | "completion" = "protocol", cacheMarks?: Map<string, { type: "ephemeral" }>, clientCacheControls?: Map<string, unknown>, absorbArmed?: boolean): CompressLoopAdapter {
export function createAnthropicAdapter(requestBody: Record<string, unknown>, originalSystem?: AnthropicRequestBody["system"], notes?: string[], errorShape: "protocol" | "completion" = "protocol", cacheMarks?: Map<string, unknown>, clientCacheControls?: Map<string, unknown>, absorbArmed?: boolean): CompressLoopAdapter {
const model = (requestBody.model as string) ?? undefined;
let messageId: string | undefined;
let stopSequence: string | null = null;
Expand Down Expand Up @@ -274,11 +274,12 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
// [#5688] round-2 re-renders from the core view fold reconstruction
// can leave adjacent effort directives in — collapse like the
// steady egress or the rebuild 400s where the main request passed.
const messages = dedupeAdjacentOutputConfig(coreToAnthropic(coreMessages, cacheMarks ?? clientCacheControls));
const effectiveMarks = cacheMarks ?? clientCacheControls;
const messages = dedupeAdjacentOutputConfig(coreToAnthropic(coreMessages, effectiveMarks));
// #1876: same append-not-merge rebuild as the steady path's
// injectSystem — both must emit byte-identical system (F2 seam).
const system = originalSystem !== undefined ? appendSystemText(systemPrompt, originalSystem) : systemPrompt;
const stamped = cacheMarks ? stampAnthropicSystemCacheControl(system) : system;
const stamped = stampSystemWithinAnthropicBudget(system, body.tools, originalSystem, effectiveMarks, cacheMarks !== undefined);
// #5432: notes go BEFORE a trailing client system run; the #4570
// backstop heals whatever still arrives illegal (fold orphans).
const withNotes = notes && notes.length > 0
Expand Down
Loading
Loading