acp-kernel 0.0.40 → 0.0.41-pr.135.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compress-tools.d.ts +669 -0
- package/dist/compress-tools.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +361 -0
- package/dist/index.js.map +1 -1
- package/dist/persist/index.js +40 -8
- package/dist/persist/index.js.map +1 -1
- package/dist/persist/store.d.ts +28 -3
- package/dist/persist/store.d.ts.map +1 -1
- package/dist/wire/compress-detect.d.ts +142 -0
- package/dist/wire/compress-detect.d.ts.map +1 -0
- package/dist/wire/index.d.ts +1 -0
- package/dist/wire/index.d.ts.map +1 -1
- package/dist/wire/index.js +189 -1
- package/dist/wire/index.js.map +1 -1
- package/package.json +1 -1
package/dist/wire/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/wire/util.ts","../../src/wire/message-id.ts","../../src/wire/anthropic.ts","../../src/wire/demoted-thinking.ts","../../src/wire/bili-message.ts","../../src/wire/openai.ts","../../src/wire/responses.ts","../../src/wire/formats.ts","../../src/wire/mirror.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/** SHA-256-derived short id — kept verbatim from the proxy so message ids\n * stay byte-identical across the extraction (re-keying would orphan every\n * downstream map keyed on these ids). */\nexport function hashId(s: string): string {\n return createHash(\"sha256\").update(s, \"utf8\").digest(\"hex\").slice(0, 16);\n}\n\n/** How a conversation's identity was derived (kept verbatim from the proxy's\n * session-id.ts — only the TYPE moves; session-key derivation stays in the\n * proxy, which owns multi-tenant state). */\nexport type ConversationIdentity = {\n value: string;\n source: \"header\" | \"body-session\" | \"metadata-session\" | \"previous-response\" | \"content-fingerprint\" | \"generated\";\n clientProvided: boolean;\n};\n","import { hashId } from \"./util.js\";\n\n/**\n * Derive a stable, content-based message id.\n *\n * PROBLEM: none of the three wire protocols (Anthropic Messages, OpenAI Chat\n * Completions, OpenAI Responses) attach a stable id to request-side message\n * items. Historically each converter used `raw-${idx}` — a *position* index,\n * not an identity. As soon as a client deletes/reorders messages (other plugins\n * summarizing away old turns, multi-agent setups, etc.) the index drifts:\n * downstream ids shift, so\n * - assignRefs reuses stale `byRaw` entries, hiding new messages, and\n * - compression `effectiveMessageIds` start pointing at the *wrong* messages,\n * silently swallowing live content under an unrelated summary.\n *\n * FIX: derive the id from a SHA-256 of the message identity:\n * role + contentType + toolCallId + toolName + text\n * Two messages with identical identity collide. To keep duplicates distinct\n * (and avoid `covered` sets collapsing unrelated turns onto one id) we append a\n * within-conversation *cluster index* `_N`: the Nth occurrence of the same\n * identity, counting from 0 in arrival order.\n *\n * Trade-off vs a real client id:\n * - deleting a duplicated message only disturbs the cluster of that identity\n * (local damage), never the whole downstream (global damage like position).\n * - fully distinct messages are completely immune to reordering/deletion.\n *\n * `idx` is passed purely to break ties *within a single conversion pass*; it is\n * not part of the identity, so two passes over the same content produce the\n * same cluster numbering (deterministic).\n */\nexport function deriveMessageId(\n role: string,\n contentType: string,\n text: string,\n options: {\n toolCallId?: string;\n toolName?: string;\n } = {},\n): string {\n const seed = `${role}|${contentType}|${options.toolCallId ?? \"\"}|${options.toolName ?? \"\"}|${text}`;\n return \"h_\" + hashId(seed);\n}\n\n/**\n * Stateful cluster counter. Each converter instantiates one per conversion\n * pass; it tracks how many times each base identity has been seen so that the\n * Nth duplicate gets a `_${N}` suffix.\n */\nexport class ClusterCounter {\n private counts = new Map<string, number>();\n\n next(baseId: string): string {\n const n = this.counts.get(baseId) ?? 0;\n this.counts.set(baseId, n + 1);\n return n === 0 ? baseId : `${baseId}_${n}`;\n }\n}\n","import type { BiliMessage } from \"./bili-message.js\";\nimport { hashId } from \"./util.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\n\nexport type AnthropicTextBlock = { type: \"text\"; text: string; cache_control?: unknown };\nexport type AnthropicToolUse = {\n type: \"tool_use\";\n id: string;\n name: string;\n input: unknown;\n cache_control?: unknown;\n};\nexport type AnthropicToolResult = {\n type: \"tool_result\";\n tool_use_id: string;\n content: string | AnthropicTextBlock[];\n is_error?: boolean;\n cache_control?: unknown;\n};\nexport type AnthropicImage = { type: \"image\"; source: unknown };\nexport type AnthropicThinking = { type: \"thinking\"; thinking: string; signature?: string };\nexport type AnthropicBlock =\n | AnthropicTextBlock\n | AnthropicToolUse\n | AnthropicToolResult\n | AnthropicImage\n | AnthropicThinking;\n\nexport type AnthropicMessage = {\n role: \"user\" | \"assistant\";\n content: string | AnthropicBlock[];\n};\n\nexport type AnthropicRequestBody = {\n model?: string;\n max_tokens?: number;\n system?: string | AnthropicTextBlock[];\n messages: AnthropicMessage[];\n tools?: unknown[];\n stream?: boolean;\n temperature?: number;\n [key: string]: unknown;\n};\n\n\nexport function extractSystem(system: AnthropicRequestBody[\"system\"]): string {\n if (!system) return \"\";\n if (typeof system === \"string\") return system;\n return system.map((b) => b.text).join(\"\\n\\n\");\n}\n\nexport function buildSystem(text: string, original: AnthropicRequestBody[\"system\"]): string | AnthropicTextBlock[] {\n if (Array.isArray(original) && original.length > 0) {\n const ccBlock = original.find((b) => b.cache_control);\n return [{ type: \"text\", text, ...(ccBlock ? { cache_control: ccBlock.cache_control } : {}) }];\n }\n return text;\n}\n\ntype Flat = { msgs: BiliMessage[]; cacheControls: Map<string, unknown> };\n\nexport function anthropicToCore(body: AnthropicRequestBody): Flat {\n const msgs: BiliMessage[] = [];\n const cacheControls = new Map<string, unknown>();\n const clusters = new ClusterCounter();\n for (const m of body.messages) {\n const blocks = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n for (const b of blocks) {\n switch (b.type) {\n case \"text\": {\n const base = deriveMessageId(m.role, \"text\", b.text);\n const id = clusters.next(base);\n msgs.push({ id, role: m.role, contentType: \"text\", text: b.text });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"tool_use\": {\n const base = deriveMessageId(\"assistant\", \"tool-call\", safeStringify(b.input), {\n toolCallId: b.id,\n toolName: b.name,\n });\n const id = clusters.next(base);\n msgs.push({\n id,\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: b.name,\n toolCallId: b.id,\n text: safeStringify(b.input),\n });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"tool_result\": {\n const text = typeof b.content === \"string\" ? b.content : b.content.map((c) => c.text).join(\"\\n\");\n const base = deriveMessageId(\"tool\", \"tool-result\", text, { toolCallId: b.tool_use_id });\n const id = clusters.next(base);\n msgs.push({\n id,\n role: \"tool\",\n contentType: \"tool-result\",\n toolCallId: b.tool_use_id,\n text,\n ...(b.is_error === true ? { toolIsError: true } : {}),\n });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"thinking\": {\n const base = deriveMessageId(\"assistant\", \"reasoning\", b.thinking);\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: b.thinking,\n ...(b.signature ? { thinkingSignature: b.signature } : {}),\n });\n break;\n }\n case \"image\": {\n const base = deriveMessageId(m.role, \"text\", \"[image]\");\n msgs.push({\n id: clusters.next(base),\n role: m.role,\n contentType: \"text\",\n text: \"[image]\",\n rawAnthropicBlock: b,\n });\n break;\n }\n }\n }\n }\n return { msgs, cacheControls };\n}\n\nexport function coreToAnthropic(messages: BiliMessage[], cacheControls?: Map<string, unknown>): AnthropicMessage[] {\n const out: AnthropicMessage[] = [];\n let current: { role: \"user\" | \"assistant\"; blocks: AnthropicBlock[] } | null = null;\n const flush = () => {\n if (current && current.blocks.length > 0) {\n out.push({ role: current.role, content: current.blocks });\n }\n current = null;\n };\n const cc = (id: string): { cache_control?: unknown } => {\n const v = cacheControls?.get(id);\n return v ? { cache_control: v } : {};\n };\n for (const m of messages) {\n const target: \"user\" | \"assistant\" =\n m.role === \"assistant\" ? \"assistant\" : \"user\";\n if (!current || current.role !== target) {\n flush();\n current = { role: target, blocks: [] };\n }\n switch (m.contentType) {\n case \"text\": {\n if (m.rawAnthropicBlock) {\n current.blocks.push(m.rawAnthropicBlock as AnthropicBlock);\n break;\n }\n current.blocks.push({ type: \"text\", text: m.text ?? \"\", ...cc(m.id) });\n break;\n }\n case \"tool-call\":\n current.blocks.push({\n type: \"tool_use\",\n id: m.toolCallId ?? `call_${m.id}`,\n name: m.toolName ?? \"unknown\",\n input: safeParse(m.text),\n ...cc(m.id),\n });\n break;\n case \"tool-result\":\n current.blocks.push({\n type: \"tool_result\",\n tool_use_id: m.toolCallId ?? \"\",\n content: m.text ?? \"\",\n ...(m.toolIsError ? { is_error: true } : {}),\n ...cc(m.id),\n });\n break;\n case \"reasoning\":\n current.blocks.push({\n type: \"thinking\",\n thinking: m.text ?? \"\",\n ...(m.thinkingSignature ? { signature: m.thinkingSignature } : {}),\n });\n break;\n }\n }\n flush();\n return out;\n}\n\n/** Extract the conversation dimension for Anthropic: a client-provided\n * session header if present, else a content fingerprint of the first user\n * message. The protocol+upstream+key dimensions are mixed in by the caller\n * (server.ts) via deriveSessionId() — this function contributes only the\n * conversation axis. */\nexport function conversationSignalAnthropic(body: AnthropicRequestBody, headerValue?: string): string {\n if (headerValue && headerValue.trim()) return headerValue.trim();\n const firstUser = body.messages.find((m) => m.role === \"user\");\n const seed = firstUser ? JSON.stringify(firstUser.content) : \"default\";\n return hashId(seed);\n}\n\nfunction safeStringify(v: unknown): string {\n try {\n return JSON.stringify(v ?? {});\n } catch {\n return \"{}\";\n }\n}\n\nfunction safeParse(s: string | undefined): unknown {\n if (!s) return {};\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n}\n","/** Inline \"demoted thinking\" normalization.\n *\n * Hosts that cannot replay prior-turn reasoning as a structured block\n * (pi-ai transform-messages demotion on model switch, openai-completions\n * `requiresThinkingAsText` profiles, gateways that inline native\n * reasoning) fold it INTO the assistant content string wrapped in a\n * dialect tag:\n *\n * glm / deepseek / kimi / qwen3 / hermes : <think>\\n{text}\\n</think>\n * anthropic / minimax / xml : <thinking>\\n{text}\\n</thinking>\n * gemini : ```thinking\\n{text}\\n```\n *\n * followed by a single \"\\n\" glue before the next content block. The same\n * logical turn can therefore arrive as a `reasoning_content` field (or a\n * separate reasoning item on /v1/responses) OR as this inline form. If the\n * wire codecs kept both as one text blob, the two serializations of one\n * turn would land in DIFFERENT core-id/fingerprint spaces — exactly the\n * issue #64 \"restart loses blocks\" class, where the mirror produced one\n * form and the live wire the other.\n *\n * splitDemotedThinking() reverses the rendering byte-exactly so both\n * codecs can normalize before identity derivation (deriveMessageId). It\n * only fires when the tag opens at offset 0 of the content, which is the\n * only position the demotion renderer can produce it in.\n *\n * One form is intentionally NOT recoverable here: the pi-ai anthropic\n * dialect demotes to BARE text (no tag), which is indistinguishable from\n * ordinary assistant prose; that case must be aligned upstream (mirror\n * uses the same bare rendering), not parsed. */\n\nexport type DemotedSplit = {\n reasoning: string;\n text: string;\n};\n\ntype DelimitedForm = {\n open: string;\n close: string;\n};\n\n/** The three inline tag forms hosts actually emit (see file comment). */\nconst FORMS: readonly DelimitedForm[] = [\n { open: \"<think>\\n\", close: \"\\n</think>\" },\n { open: \"<thinking>\\n\", close: \"\\n</thinking>\" },\n { open: \"```thinking\\n\", close: \"\\n```\" },\n];\n\n/** If `content` starts with one or more inline demoted-thinking blocks,\n * split them out. Returns null when no tag opens the content (the common\n * case — including every user message and every assistant message whose\n * reasoning traveled as a field/item), in which case callers keep the\n * content as-is. Malformed (unterminated) or empty blocks do not match;\n * the content is then treated as plain text, never dropped. */\nexport function splitDemotedThinking(content: string): DemotedSplit | null {\n let rest = content;\n const parts: string[] = [];\n for (;;) {\n let matched = false;\n for (const form of FORMS) {\n if (!rest.startsWith(form.open)) continue;\n const end = rest.indexOf(form.close, form.open.length);\n if (end < 0) continue;\n const inner = rest.slice(form.open.length, end);\n if (inner.length === 0) continue;\n parts.push(inner);\n rest = rest.slice(end + form.close.length);\n // Glue the demotion renderer inserts between a demoted block\n // and the block that follows it.\n if (rest.startsWith(\"\\n\")) rest = rest.slice(1);\n matched = true;\n break;\n }\n if (!matched) break;\n }\n if (parts.length === 0) return null;\n return { reasoning: parts.join(\"\\n\"), text: rest };\n}\n","/**\n * Lossless message bridge between protocol-specific message formats and the\n * kernel's CoreMessage.\n *\n * Problem: `anthropicToCore` / `openaiToCore` / `responsesToCore` flatten\n * rich protocol blocks (images, thinking signatures, tool_result.is_error,\n * developer-role messages, image_url) into plain `{ text }` placeholders.\n * The reverse `coreToX` then can't reconstruct them — `is_error` is lost\n * (upstream can't tell a tool error from a result), `thinking.signature` is\n * lost (Anthropic rejects thinking blocks without a matching signature),\n * images become \"[image]\" (the model never sees the picture).\n *\n * Solution: `BiliMessage` extends CoreMessage with optional sidecar fields.\n * The kernel only reads `{ ...message }` (spread copy) and known fields, so\n * the extra fields survive the compression pipeline unchanged and arrive back\n * at `coreToX`, which prefers them over the flattened `text`. No `as any`\n * needed — TypeScript array covariance lets `BiliMessage[]` satisfy a\n * `CoreMessage[]` parameter.\n */\n\nimport type { CoreMessage } from \"acp-kernel\";\n\n/** A message that carries its original protocol block(s) verbatim, so the\n * reverse conversion can reconstruct losslessly. Every field is optional —\n * plain text messages (the common case) have none set. */\nexport interface BiliMessage extends CoreMessage {\n /** Anthropic: the original content block for an image or a structured\n * tool_result. Restored verbatim by coreToAnthropic. */\n rawAnthropicBlock?: unknown;\n /** OpenAI chat: the original content part for an image_url, or the\n * original message object for a developer-role message. */\n rawOpenaiContent?: unknown;\n /** Responses API: the original input item (for input_image, or a raw\n * function_call / function_call_output we pass through). */\n rawResponsesItem?: unknown;\n /** Anthropic thinking signature. Anthropic verifies thinking+signature\n * pairs; without it the request is rejected. Stored alongside the\n * reasoning text so coreToAnthropic can reattach it. */\n thinkingSignature?: string;\n /** OpenAI reasoning_content (chain-of-thought from DeepSeek-R1, GLM-4.6\n * thinking, Qwen-QwQ). These models require reasoning_content be echoed\n * back on subsequent requests or the API returns HTTP 400; stored so\n * coreToOpenai can reattach it. */\n reasoningContent?: string;\n /** Anthropic tool_result.is_error. Marks the tool result as an error so\n * the model knows the tool failed (not just returned an error string). */\n toolIsError?: boolean;\n /** OpenAI: original role was \"developer\" (reconstructed as \"system\" by\n * openaiToCore for the kernel; coreToOpenai restores \"developer\"). */\n originalRole?: \"system\" | \"developer\";\n /** The original media type for an image (image/png, image/jpeg, image/gif,\n * image/webp). Lets coreToOpenai/coreToResponses rebuild image_url /\n * input_image with the right data URL. */\n imageMediaType?: string;\n /** The base64 data of an image (without the data: prefix). Lets the\n * reverse conversion rebuild the full image payload. */\n imageBase64?: string;\n /** OpenAI chat: ALL original image_url content parts (each a data: URL\n * part) for a user message carrying more than one image, in wire order.\n * coreToOpenai re-emits these verbatim (after the text part). The\n * singular `rawOpenaiContent` still covers the single-image case and\n * legacy persisted state. Typed as unknown[] (not OpenAIContentPart) to\n * avoid a circular import with the openai codec. */\n rawOpenaiContentParts?: unknown[];\n}\n\n/** Narrow a BiliMessage[] to CoreMessage[] for the kernel. The sidecar fields\n * are transparently carried along — the kernel's `{ ...msg }` copies them. */\nexport function toCoreMessages(msgs: BiliMessage[]): CoreMessage[] {\n return msgs as CoreMessage[];\n}\n\n/** Re-decode a base64 data URL into media type + data. Returns undefined if\n * the input is not a recognized data URL. Used by openaiToCore/responsesToCore\n * to split image_url/input_image into the sidecar fields. */\nexport function parseDataUrl(url: string): { mediaType: string; base64: string } | undefined {\n const m = /^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);\n if (!m) return undefined;\n return { mediaType: m[1]!, base64: m[2]! };\n}\n","import { splitDemotedThinking } from \"./demoted-thinking.js\";\nimport { hashId } from \"./util.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\nimport { parseDataUrl, type BiliMessage } from \"./bili-message.js\";\n\nexport type OpenAIContentPart =\n | { type: \"text\"; text: string }\n | { type: \"image_url\"; image_url: { url: string } }\n | { type: string; [k: string]: unknown };\n\nexport type OpenAIToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\nexport type OpenAIMessage = {\n role: \"system\" | \"developer\" | \"user\" | \"assistant\" | \"tool\";\n content?: string | null | OpenAIContentPart[];\n reasoning_content?: string | null;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n name?: string;\n};\n\nexport type OpenAITool = {\n type: \"function\";\n function: { name: string; description?: string; parameters?: unknown };\n};\n\nexport type OpenAIRequestBody = {\n model?: string;\n messages: OpenAIMessage[];\n tools?: OpenAITool[];\n stream?: boolean;\n [key: string]: unknown;\n};\n\ntype Flat = { msgs: BiliMessage[]; systemText: string };\n\n/** Hoist the contiguous leading system/developer prefix out of the fold\n * space (openai-chat variant of the responses codec's systemParts and the\n * anthropic codec's top-level `system` field). The system prompt is host\n * runtime state: its content varies across restarts (injected reminders,\n * host-composed instructions), so keeping it inside the id space made every\n * downstream fingerprint spanning it unstable, and a compress range that\n * covered it removed the model's system prompt from the rebuilt wire\n * entirely. Mid-conversation system messages (rare, host-synthetic) stay in\n * the fold space unchanged. */\nexport function openaiToCore(body: OpenAIRequestBody): Flat {\n const msgs: BiliMessage[] = [];\n const systemParts: string[] = [];\n const clusters = new ClusterCounter();\n for (const m of body.messages) {\n switch (m.role) {\n case \"system\":\n case \"developer\": {\n if (msgs.length === 0) {\n systemParts.push(stringContent(m.content));\n break;\n }\n const base = deriveMessageId(m.role, \"text\", stringContent(m.content));\n msgs.push({ id: clusters.next(base), role: \"system\", contentType: \"text\", text: stringContent(m.content), originalRole: m.role });\n break;\n }\n case \"user\": {\n const text = stringContent(m.content);\n const imgs = allImageParts(m.content);\n const firstImg = imgs[0];\n const firstUrl = firstImg ? firstImg.image_url.url : undefined;\n const firstParsed = firstUrl ? parseDataUrl(firstUrl) : undefined;\n const base = deriveMessageId(\"user\", \"text\", text);\n msgs.push({\n id: clusters.next(base),\n role: \"user\",\n contentType: \"text\",\n text,\n ...(imgs.length === 1 && firstParsed\n ? { rawOpenaiContent: imgs[0], imageMediaType: firstParsed.mediaType, imageBase64: firstParsed.base64 }\n : imgs.length > 1\n ? { rawOpenaiContentParts: imgs }\n : {}),\n });\n break;\n }\n case \"assistant\": {\n const fieldReasoning = typeof m.reasoning_content === \"string\" ? m.reasoning_content : \"\";\n let reasoning = fieldReasoning;\n let text = stringContent(m.content);\n if (!reasoning) {\n // Hosts that cannot replay prior-turn reasoning as a\n // structured field inline it into content wrapped in a\n // dialect tag (<think>, <thinking>, ```thinking). Split\n // it back out BEFORE identity derivation so the inline\n // form and the reasoning_content field form of one turn\n // land in a single core-id/fingerprint space (issue #64\n // demoted variant).\n const split = splitDemotedThinking(text);\n if (split) {\n reasoning = split.reasoning;\n text = split.text;\n }\n }\n if (reasoning) {\n const base = deriveMessageId(\"assistant\", \"reasoning\", reasoning);\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: reasoning,\n reasoningContent: reasoning,\n });\n }\n if (text) {\n const base = deriveMessageId(\"assistant\", \"text\", text);\n msgs.push({ id: clusters.next(base), role: \"assistant\", contentType: \"text\", text });\n }\n if (Array.isArray(m.tool_calls)) {\n for (const tc of m.tool_calls) {\n const base = deriveMessageId(\"assistant\", \"tool-call\", tc.function.arguments ?? \"\", {\n toolCallId: tc.id,\n toolName: tc.function.name,\n });\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: tc.function.name,\n toolCallId: tc.id,\n text: tc.function.arguments ?? \"\",\n });\n }\n }\n break;\n }\n case \"tool\": {\n const base = deriveMessageId(\"tool\", \"tool-result\", stringContent(m.content), {\n toolCallId: m.tool_call_id ?? \"\",\n });\n msgs.push({\n id: clusters.next(base),\n role: \"tool\",\n contentType: \"tool-result\",\n toolCallId: m.tool_call_id ?? \"\",\n text: stringContent(m.content),\n });\n break;\n }\n }\n }\n return { msgs, systemText: systemParts.join(\"\\n\\n\") };\n}\n\nexport function coreToOpenai(messages: BiliMessage[]): OpenAIMessage[] {\n const out: OpenAIMessage[] = [];\n let pending: { text: string | null; toolCalls: OpenAIToolCall[]; reasoning: string | null } | null = null;\n const flush = () => {\n if (!pending) return;\n const reasoning = pending.reasoning !== null && pending.reasoning.length > 0 ? pending.reasoning : undefined;\n if (pending.toolCalls.length > 0) {\n out.push({\n role: \"assistant\",\n content: pending.text ?? null,\n tool_calls: pending.toolCalls,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n });\n } else if (pending.text !== null) {\n out.push({ role: \"assistant\", content: pending.text, ...(reasoning ? { reasoning_content: reasoning } : {}) });\n } else if (reasoning) {\n out.push({ role: \"assistant\", content: null, reasoning_content: reasoning });\n }\n pending = null;\n };\n for (const m of messages) {\n if (m.role === \"assistant\") {\n if (!pending) pending = { text: null, toolCalls: [], reasoning: null };\n if (m.contentType === \"reasoning\") {\n pending.reasoning = (pending.reasoning ?? \"\") + (m.reasoningContent ?? m.text ?? \"\");\n } else if (m.contentType === \"text\") {\n pending.text = (pending.text ?? \"\") + (m.text ?? \"\");\n } else if (m.contentType === \"tool-call\") {\n pending.toolCalls.push({\n id: m.toolCallId ?? `call_${m.id}`,\n type: \"function\",\n function: { name: m.toolName ?? \"unknown\", arguments: m.text ?? \"\" },\n });\n }\n } else {\n flush();\n if (m.role === \"system\") {\n out.push({ role: m.originalRole === \"developer\" ? \"developer\" : \"system\", content: m.text ?? \"\" });\n } else if (m.role === \"user\") {\n if (m.rawOpenaiContent || m.imageBase64 || m.rawOpenaiContentParts) {\n const parts: OpenAIContentPart[] = [];\n if (m.text) parts.push({ type: \"text\", text: m.text });\n if (m.rawOpenaiContentParts && m.rawOpenaiContentParts.length > 0) {\n for (const part of m.rawOpenaiContentParts) parts.push(part as OpenAIContentPart);\n } else if (m.rawOpenaiContent) {\n parts.push(m.rawOpenaiContent as OpenAIContentPart);\n } else if (m.imageBase64 && m.imageMediaType) {\n parts.push({ type: \"image_url\", image_url: { url: `data:${m.imageMediaType};base64,${m.imageBase64}` } });\n }\n out.push({ role: \"user\", content: parts });\n } else {\n out.push({ role: \"user\", content: m.text ?? \"\" });\n }\n } else if (m.role === \"tool\") {\n out.push({ role: \"tool\", tool_call_id: m.toolCallId ?? \"\", content: m.text ?? \"\" });\n }\n }\n }\n flush();\n return out;\n}\n\nexport function injectOpenaiSystem(messages: OpenAIMessage[], parts: string[]): OpenAIMessage[] {\n if (parts.length === 0) return messages;\n const extra = parts.join(\"\\n\\n\");\n if (messages.length > 0 && (messages[0]?.role === \"system\" || messages[0]?.role === \"developer\")) {\n const head = messages[0] as OpenAIMessage;\n const base = stringContent(head.content);\n const merged = base ? `${base}\\n\\n---\\n\\n${extra}` : extra;\n return [{ ...head, content: merged }, ...messages.slice(1)];\n }\n return [{ role: \"system\", content: extra }, ...messages];\n}\n\n/** Extract the conversation dimension for OpenAI Chat: a client-provided\n * session header if present, else a content fingerprint of the first user\n * message. See conversationSignalAnthropic for the full rationale. */\nexport function conversationSignalOpenai(body: OpenAIRequestBody, headerValue?: string): string {\n if (headerValue && headerValue.trim()) return headerValue.trim();\n const firstUser = body.messages.find((m) => m.role === \"user\");\n const seed = firstUser ? stringContent(firstUser.content) : \"default\";\n return hashId(seed);\n}\n\nfunction stringContent(content: OpenAIMessage[\"content\"]): string {\n if (content == null) return \"\";\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((p) => (typeof p === \"string\" ? p : p.type === \"text\" ? (p as { text?: string }).text ?? \"\" : \"\"))\n .join(\"\\n\");\n }\n return \"\";\n}\n\ntype OpenAIImagePart = { type: \"image_url\"; image_url: { url: string } };\n\n/** Collect ALL data-URL image parts in a user content array, in wire order.\n * (firstImagePart only kept the first, which silently dropped images 2..N\n * on the coreToOpenai rebuild.) */\nfunction allImageParts(content: OpenAIMessage[\"content\"]): OpenAIImagePart[] {\n if (!Array.isArray(content)) return [];\n const out: OpenAIImagePart[] = [];\n for (const p of content) {\n if (typeof p !== \"object\" || p === null) continue;\n if (!(\"type\" in p) || p.type !== \"image_url\" || !(\"image_url\" in p)) continue;\n // The union's index-signature member leaves image_url as `unknown`, so\n // narrow via a named const before reading the url.\n const imagePart = p as { image_url: { url?: unknown } };\n const url = imagePart.image_url.url;\n if (typeof url === \"string\" && parseDataUrl(url)) out.push(p as OpenAIImagePart);\n }\n return out;\n}\n","import type { CoreMessage } from \"../types.js\";\nimport { splitDemotedThinking } from \"./demoted-thinking.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\nimport type { ConversationIdentity } from \"./util.js\";\nimport { hashId } from \"./util.js\";\nimport { parseDataUrl, type BiliMessage } from \"./bili-message.js\";\n\nexport type ResponseContentPart =\n | { type: \"input_text\"; text: string; [key: string]: unknown }\n | { type: \"output_text\"; text: string; [key: string]: unknown }\n | { type: \"input_image\"; image_url: string; [key: string]: unknown }\n | { type: string; [key: string]: unknown };\n\nexport type ResponseInputMessage = {\n type: \"message\";\n role: \"system\" | \"developer\" | \"user\" | \"assistant\";\n content: string | ResponseContentPart[];\n [key: string]: unknown;\n};\n\nexport type ResponseFunctionCall = {\n type: \"function_call\";\n id?: string;\n call_id: string;\n name: string;\n arguments: string;\n [key: string]: unknown;\n};\n\nexport type ResponseFunctionCallOutput = {\n type: \"function_call_output\";\n call_id: string;\n output: string;\n [key: string]: unknown;\n};\n\nexport type ResponseInputItem =\n | ResponseInputMessage\n | ResponseFunctionCall\n | ResponseFunctionCallOutput\n | { type: string; [key: string]: unknown };\n\nexport type ResponsesRequestBody = {\n model?: string;\n input: string | ResponseInputItem[];\n instructions?: string;\n tools?: unknown[];\n stream?: boolean;\n session_id?: string;\n previous_response_id?: string;\n prompt_cache_key?: string;\n metadata?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\ntype ResponseLayoutSlot = {\n original: ResponseInputItem;\n coreId?: string;\n};\n\nexport type ResponsesProjection = {\n msgs: BiliMessage[];\n systemParts: string[];\n preamble: ResponseInputItem[];\n customToolCallIds: Set<string>;\n layout: ResponseLayoutSlot[];\n stringInput?: { original: string; coreId: string };\n /** Reasoning items dropped because ACP_REASONING_KEEP=none. 0 by default —\n * reasoning is normally routed through the compression pipeline so it is\n * hidden automatically once its turn is summarized. */\n droppedReasoning: number;\n};\n\n/** Item types that are host DIRECTIVES (tool/definition listings), not\n * conversation history: preserved verbatim and re-prepended at input[0..].\n * `additional_tools` carries the Codex code_mode exec/wait tool definitions\n * and MUST stay at input[0]. `mcp_list_tools` is a stable per-session listing.\n *\n * Only definitions belong here. Output/action items from a prior response\n * (reasoning, computer_call, function_call, mcp_call, ...) ARE conversation\n * history and are routed as tracked BiliMessages, so the compression pipeline\n * hides them once their turn is summarized — preserving them verbatim in the\n * preamble instead made them accumulate unbounded every turn and broke Codex's\n * prompt-cache prefix. */\nconst OPAQUE_ITEM_TYPES = new Set([\n \"additional_tools\",\n \"mcp_list_tools\",\n]);\n\nfunction isOpaqueItem(item: ResponseInputItem): boolean {\n return OPAQUE_ITEM_TYPES.has(item.type);\n}\n\nfunction shouldDropAllReasoning(): boolean {\n return (process.env.ACP_REASONING_KEEP ?? \"\").trim().toLowerCase() === \"none\";\n}\n\nfunction partText(part: ResponseContentPart): string {\n if (part.type === \"input_text\" || part.type === \"output_text\") {\n return typeof part.text === \"string\" ? part.text : \"\";\n }\n return \"\";\n}\n\nfunction messageContent(content: string | ResponseContentPart[]): string {\n return typeof content === \"string\" ? content : content.map(partText).join(\"\\n\");\n}\n\n/** Extract the reasoning text from a responses reasoning item. The host\n * carries it in `content` (reasoning_text parts); the primeFold mirror\n * carries it in `summary` (summary_text parts). Both must yield the same\n * text so the kernel derives the same core id (issue #64, responses). */\nfunction reasoningText(item: ResponseInputItem): string {\n const fromParts = (parts: unknown, type: string): string => {\n if (!Array.isArray(parts)) return \"\";\n const texts: string[] = [];\n for (const part of parts) {\n if (part && typeof part === \"object\" && \"type\" in part && \"text\" in part) {\n const rec = part as { type: unknown; text: unknown };\n if (rec.type === type && typeof rec.text === \"string\") texts.push(rec.text);\n }\n }\n return texts.join(\"\\n\");\n };\n const content = \"content\" in item ? item.content : undefined;\n const summary = \"summary\" in item ? item.summary : undefined;\n return fromParts(content, \"reasoning_text\") || fromParts(summary, \"summary_text\");\n}\n\nexport function responsesToCore(body: ResponsesRequestBody): ResponsesProjection {\n const msgs: BiliMessage[] = [];\n const systemParts: string[] = [];\n const preamble: ResponseInputItem[] = [];\n const customToolCallIds = new Set<string>();\n const layout: ResponseLayoutSlot[] = [];\n let droppedReasoning = 0;\n const clusters = new ClusterCounter();\n let idx = 0;\n if (typeof body.instructions === \"string\" && body.instructions.trim()) systemParts.push(body.instructions);\n if (typeof body.input === \"string\") {\n const id = clusters.next(deriveMessageId(\"user\", \"text\", body.input));\n msgs.push({ id, role: \"user\", contentType: \"text\", text: body.input });\n return { msgs, systemParts, preamble, customToolCallIds, layout, droppedReasoning, stringInput: { original: body.input, coreId: id } };\n }\n for (const item of body.input) {\n let coreId: string | undefined;\n if (isOpaqueItem(item)) preamble.push(item);\n switch (item.type) {\n case \"reasoning\": {\n if (shouldDropAllReasoning()) {\n droppedReasoning++;\n continue;\n }\n // Key the reasoning piece on its TEXT (deterministic), consistent\n // with the anthropic/openai codecs. The host mints a per-request\n // item id that the primeFold mirror cannot reproduce; keying on it\n // put the mirror in a different ref/fingerprint space, so restart\n // replay rejected every in-stream compress call (issue #64,\n // responses variant).\n const text = reasoningText(item);\n const rid =\n text.length > 0\n ? text\n : \"id\" in item && typeof item.id === \"string\"\n ? item.id\n : hashId(JSON.stringify(item));\n coreId = clusters.next(deriveMessageId(\"assistant\", \"reasoning\", rid));\n msgs.push({\n id: coreId,\n role: \"assistant\",\n contentType: \"reasoning\",\n text: rid,\n rawResponsesItem: item,\n });\n break;\n }\n case \"message\": {\n const message = item as ResponseInputMessage;\n const text = messageContent(message.content);\n if (message.role === \"system\" || message.role === \"developer\") {\n systemParts.push(text);\n idx++;\n continue;\n } else if (message.role === \"user\" || (message.role === \"assistant\" && text)) {\n const role = message.role;\n let effText = text;\n if (role === \"assistant\") {\n // Same normalization as openaiToCore: hosts that demote\n // prior-turn reasoning inline it as a dialect tag at the\n // head of the message text. Split it out before identity\n // derivation so the inline form and the separate\n // reasoning-item form of one turn share a single\n // core-id/fingerprint space.\n const split = splitDemotedThinking(text);\n if (split) {\n msgs.push({\n id: clusters.next(deriveMessageId(\"assistant\", \"reasoning\", split.reasoning)),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: split.reasoning,\n rawResponsesItem: item,\n });\n effText = split.text;\n }\n }\n if (effText) {\n coreId = clusters.next(deriveMessageId(role, \"text\", effText));\n const imageUrl = Array.isArray(message.content)\n ? message.content.find((part) => part.type === \"input_image\" && typeof part.image_url === \"string\")?.image_url\n : undefined;\n const image = typeof imageUrl === \"string\" ? parseDataUrl(imageUrl) : undefined;\n msgs.push({\n id: coreId,\n role,\n contentType: \"text\",\n text: effText,\n rawResponsesItem: item,\n ...(image ? { imageMediaType: image.mediaType, imageBase64: image.base64 } : {}),\n });\n }\n }\n break;\n }\n case \"function_call\": {\n const call = item as ResponseFunctionCall;\n coreId = clusters.next(deriveMessageId(\"assistant\", \"tool-call\", call.arguments ?? \"\", {\n toolCallId: call.call_id,\n toolName: call.name,\n }));\n msgs.push({\n id: coreId,\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: call.name,\n toolCallId: call.call_id,\n text: call.arguments ?? \"\",\n rawResponsesItem: item,\n });\n break;\n }\n case \"function_call_output\": {\n const output = item as ResponseFunctionCallOutput;\n const text = typeof output.output === \"string\" ? output.output : JSON.stringify(output.output);\n coreId = clusters.next(deriveMessageId(\"tool\", \"tool-result\", text, { toolCallId: output.call_id }));\n msgs.push({ id: coreId, role: \"tool\", contentType: \"tool-result\", toolCallId: output.call_id, text, rawResponsesItem: item });\n break;\n }\n case \"computer_call\":\n case \"computer_call_output\":\n case \"file_search_call\":\n case \"web_search_call\":\n case \"image_generation_call\":\n case \"code_interpreter_call\":\n case \"mcp_call\": {\n const rid =\n typeof (item as { id?: unknown }).id === \"string\"\n ? String((item as { id?: string }).id)\n : hashId(JSON.stringify(item));\n coreId = clusters.next(deriveMessageId(\"assistant\", \"responses-call\", rid));\n msgs.push({ id: coreId, role: \"assistant\", contentType: \"reasoning\", text: rid, rawResponsesItem: item });\n break;\n }\n case \"custom_tool_call\": {\n const ctc = item as { call_id?: string; name?: string; input?: string; arguments?: string };\n const callId = ctc.call_id ?? `call_${idx}`;\n customToolCallIds.add(callId);\n const argText = ctc.input ?? ctc.arguments ?? \"\";\n coreId = clusters.next(deriveMessageId(\"assistant\", \"tool-call\", argText, { toolCallId: callId, toolName: ctc.name ?? \"custom\" }));\n msgs.push({ id: coreId, role: \"assistant\", contentType: \"tool-call\", toolName: ctc.name ?? \"custom\", toolCallId: callId, text: argText, rawResponsesItem: item });\n break;\n }\n case \"custom_tool_call_output\": {\n const ctco = item as { call_id?: string; output?: string };\n const callId = ctco.call_id ?? `call_${idx}`;\n customToolCallIds.add(callId);\n const outText = typeof ctco.output === \"string\" ? ctco.output : JSON.stringify(ctco.output ?? \"\");\n coreId = clusters.next(deriveMessageId(\"tool\", \"tool-result\", outText, { toolCallId: callId }));\n msgs.push({ id: coreId, role: \"tool\", contentType: \"tool-result\", toolCallId: callId, text: outText, rawResponsesItem: item });\n break;\n }\n default:\n if (!isOpaqueItem(item)) preamble.push(item);\n break;\n }\n layout.push({ original: item, coreId });\n idx++;\n }\n return { msgs, systemParts, preamble, customToolCallIds, layout, droppedReasoning };\n}\n\nfunction patchTextParts(parts: ResponseContentPart[], text: string): ResponseContentPart[] {\n const textIndexes = parts.flatMap((part, index) =>\n part.type === \"input_text\" || part.type === \"output_text\" ? [index] : [],\n );\n if (textIndexes.length === 0) return [{ type: \"input_text\", text }, ...parts];\n const first = textIndexes[0];\n const remaining = new Set(textIndexes.slice(1));\n return parts.map((part, index) => {\n if (index === first) return { ...part, text };\n if (remaining.has(index)) return { ...part, text: \"\" };\n return part;\n });\n}\n\nfunction patchOriginalItem(original: ResponseInputItem, source: CoreMessage, next: CoreMessage): ResponseInputItem {\n if (\n source.text === next.text &&\n source.toolName === next.toolName &&\n source.toolCallId === next.toolCallId &&\n source.role === next.role &&\n source.contentType === next.contentType\n ) return original;\n if (original.type === \"message\") {\n const message = original as ResponseInputMessage;\n const content = typeof message.content === \"string\" ? next.text ?? \"\" : patchTextParts(message.content, next.text ?? \"\");\n return { ...message, content };\n }\n if (original.type === \"function_call\") {\n return {\n ...original,\n name: next.toolName ?? String(original.name ?? \"unknown\"),\n call_id: next.toolCallId ?? String(original.call_id ?? \"\"),\n arguments: next.text ?? \"\",\n };\n }\n if (original.type === \"function_call_output\") {\n return { ...original, call_id: next.toolCallId ?? String(original.call_id ?? \"\"), output: next.text ?? \"\" };\n }\n return original;\n}\n\nexport function patchResponsesInput(projection: ResponsesProjection, messages: CoreMessage[]): string | ResponseInputItem[] {\n if (projection.stringInput) {\n const original = projection.msgs.find((message) => message.id === projection.stringInput?.coreId);\n const next = messages.find((message) => message.id === projection.stringInput?.coreId);\n if (original && next && messages.length === 1 && next.role === \"user\" && next.contentType === \"text\") {\n return next.text === original.text ? projection.stringInput.original : next.text ?? \"\";\n }\n return coreToResponses(messages, projection.customToolCallIds);\n }\n const sourceById = new Map(projection.msgs.map((message) => [message.id, message]));\n const nextById = new Map(messages.map((message) => [message.id, message]));\n const slotById = new Map<string, number>();\n projection.layout.forEach((slot, index) => {\n if (slot.coreId) slotById.set(slot.coreId, index);\n });\n const insertions = new Map<number, ResponseInputItem[]>();\n for (let index = 0; index < messages.length; index++) {\n const message = messages[index]!;\n if (sourceById.has(message.id)) continue;\n let target = projection.layout.length;\n for (let nextIndex = index + 1; nextIndex < messages.length; nextIndex++) {\n const slot = slotById.get(messages[nextIndex]!.id);\n if (slot !== undefined) {\n target = slot;\n break;\n }\n }\n const generated = coreToResponses([message], projection.customToolCallIds);\n if (generated.length > 0) insertions.set(target, [...(insertions.get(target) ?? []), ...generated]);\n }\n const out: ResponseInputItem[] = [];\n projection.layout.forEach((slot, index) => {\n out.push(...(insertions.get(index) ?? []));\n if (!slot.coreId) {\n out.push(slot.original);\n return;\n }\n const source = sourceById.get(slot.coreId);\n const next = nextById.get(slot.coreId);\n if (source && next) out.push(patchOriginalItem(slot.original, source, next));\n });\n out.push(...(insertions.get(projection.layout.length) ?? []));\n return out;\n}\n\nexport function coreToResponses(\n messages: CoreMessage[],\n customToolCallIds: Set<string> = new Set(),\n): ResponseInputItem[] {\n const out: ResponseInputItem[] = [];\n for (const message of messages) {\n const biliMessage = message as BiliMessage;\n const raw = biliMessage.rawResponsesItem as ResponseInputItem | undefined;\n if (message.role === \"system\") {\n out.push({ type: \"message\", role: \"developer\", content: message.text ?? \"\" });\n } else if (message.role === \"user\") {\n if (raw?.type === \"message\" && messageContent((raw as ResponseInputMessage).content) === (message.text ?? \"\")) out.push(raw);\n else out.push({ type: \"message\", role: \"user\", content: message.text ?? \"\" });\n } else if (message.role === \"assistant\") {\n if (message.contentType === \"text\") {\n out.push({ type: \"message\", role: \"assistant\", content: message.text ?? \"\" });\n } else if (message.contentType === \"tool-call\") {\n const callId = message.toolCallId ?? `call_${message.id}`;\n if (customToolCallIds.has(callId)) {\n out.push({ type: \"custom_tool_call\", call_id: callId, name: message.toolName ?? \"unknown\", input: message.text ?? \"\", status: \"completed\" } as ResponseInputItem);\n } else {\n out.push({ type: \"function_call\", call_id: callId, name: message.toolName ?? \"unknown\", arguments: message.text ?? \"\" });\n }\n } else if (message.contentType === \"reasoning\") {\n if (raw) out.push(raw);\n }\n } else if (message.role === \"tool\") {\n const callId = message.toolCallId ?? \"\";\n if (customToolCallIds.has(callId)) {\n out.push({ type: \"custom_tool_call_output\", call_id: callId, output: message.text ?? \"\" } as ResponseInputItem);\n } else {\n out.push({ type: \"function_call_output\", call_id: callId, output: message.text ?? \"\" });\n }\n }\n }\n return out;\n}\n\nexport function injectResponsesDeveloperMessage(\n input: string | ResponseInputItem[],\n content: string,\n): ResponseInputItem[] {\n const items: ResponseInputItem[] = typeof input === \"string\"\n ? [{ type: \"message\", role: \"user\", content: input }]\n : [...input];\n let index = 0;\n while (items[index]?.type === \"additional_tools\") index++;\n items.splice(index, 0, { type: \"message\", role: \"developer\", content });\n return items;\n}\n\nexport function conversationIdentityResponses(\n body: ResponsesRequestBody,\n headerValue?: string,\n): ConversationIdentity {\n if (headerValue?.trim()) return { value: headerValue.trim(), source: \"header\", clientProvided: true };\n if (typeof body.session_id === \"string\" && body.session_id.trim()) {\n return { value: body.session_id.trim(), source: \"body-session\", clientProvided: true };\n }\n const metadataSession = body.metadata?.session_id;\n if (typeof metadataSession === \"string\" && metadataSession.trim()) {\n return { value: metadataSession.trim(), source: \"metadata-session\", clientProvided: true };\n }\n if (typeof body.previous_response_id === \"string\" && body.previous_response_id.trim()) {\n return { value: body.previous_response_id.trim(), source: \"previous-response\", clientProvided: false };\n }\n return { value: hashId(JSON.stringify(body.input ?? [])), source: \"content-fingerprint\", clientProvided: false };\n}\n\nexport function conversationSignalResponses(body: ResponsesRequestBody, headerValue?: string): string {\n return conversationIdentityResponses(body, headerValue).value;\n}\n\n// Codex subagents (guardian approval reviewer, etc.) reuse the main\n// conversation's body.session_id, so identity alone collapses their requests\n// onto the main session's compression state — a compressed subagent request\n// loses the verbatim user authorization it must read back (#150). Subagent\n// requests carry their own `instructions` (the agent's role prompt), so the\n// FIRST instructions seen for an identity anchor the main namespace (it never\n// changes for the conversation, even if the main prompt drifts), and any other\n// instructions value maps to a separate `|sub:` namespace with its own empty\n// compression state. Subagent requests are self-contained replays, so the\n// fresh namespace is lossless.\nexport interface SubagentNamespaces {\n /** Resolve the compression-state namespace for a request: the identity\n * itself for the anchored (main) instructions, `identity|sub:<fp>` for\n * any other instructions value. First-seen instructions anchor. */\n namespaceFor(identityValue: string, instructions: unknown): string;\n}\n\n/** Host-owned subagent-namespace store.\n *\n * The anchor map is per-conversation mutable state, so it belongs to the\n * host — NOT to a library module global. Create one instance and keep it for\n * the process lifetime (or persist it alongside your session store if you\n * need namespaces to survive restarts: a fresh instance re-anchors on the\n * first request it sees, which after a restart may be a subagent request,\n * orphaning the main conversation's stored compression state). */\nexport function createSubagentNamespaces(): SubagentNamespaces {\n const anchors = new Map<string, string>();\n return {\n namespaceFor(identityValue: string, instructions: unknown): string {\n if (typeof instructions !== \"string\" || instructions.trim().length === 0) return identityValue;\n const fp = hashId(instructions);\n const anchor = anchors.get(identityValue);\n if (anchor === undefined) {\n anchors.set(identityValue, fp);\n return identityValue;\n }\n return anchor === fp ? identityValue : `${identityValue}|sub:${fp}`;\n },\n };\n}\n\n// Convenience singleton for single-process proxies that don't manage\n// per-session state themselves. Hosts needing isolation between\n// conversations, deterministic namespaces across restarts, or a bound on\n// anchor memory should create their own instance via\n// createSubagentNamespaces() and own its lifecycle.\nconst defaultNamespaces = createSubagentNamespaces();\n\nexport function subagentNamespace(identityValue: string, instructions: unknown): string {\n return defaultNamespaces.namespaceFor(identityValue, instructions);\n}\n","export const WIRE_FORMATS = [\"anthropic\", \"openai\", \"responses\"] as const;\nexport type WireFormat = (typeof WIRE_FORMATS)[number];\n\nexport function isWireFormat(value: unknown): value is WireFormat {\n return (\n typeof value === \"string\" &&\n (WIRE_FORMATS as readonly string[]).includes(value)\n );\n}\n\n/**\n * Classify a provider request body by the codec that can parse it.\n * Returns undefined when no codec handles the body — the caller must\n * pass such payloads through untransformed.\n */\nexport function detectWireFormat(payload: unknown): WireFormat | undefined {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const p = payload as Record<string, unknown>;\n if (Array.isArray(p.input)) return \"responses\";\n const messages = p.messages;\n if (!Array.isArray(messages)) return undefined;\n if (\"system\" in p || \"anthropic_version\" in p) return \"anthropic\";\n for (const m of messages as Array<Record<string, unknown>>) {\n if (m === null || typeof m !== \"object\") continue;\n const c = m.content;\n if (Array.isArray(c)) {\n for (const b of c as Array<Record<string, unknown>>) {\n if (b && typeof b === \"object\" && typeof b.type === \"string\") {\n if (\n b.type === \"tool_use\" ||\n b.type === \"tool_result\" ||\n b.type === \"thinking\"\n )\n return \"anthropic\";\n if (b.type === \"text\" && \"cache_control\" in b) return \"anthropic\";\n }\n }\n }\n if (Array.isArray(m.tool_calls)) return \"openai\";\n if (m.role === \"tool\" && typeof m.tool_call_id === \"string\")\n return \"openai\";\n if (m.role === \"system\" || m.role === \"developer\") return \"openai\";\n }\n // Both chat formats share role+messages; default to openai — the safer\n // guess for OpenAI-compatible endpoints (GLM, DeepSeek, vLLM).\n return \"openai\";\n}\n","import { anthropicToCore } from \"./anthropic.js\";\nimport { openaiToCore } from \"./openai.js\";\nimport { responsesToCore } from \"./responses.js\";\nimport type { BiliMessage } from \"./bili-message.js\";\n\n/**\n * Mirror constructors: rebuild the WIRE-SHAPE projection of a persisted\n * conversation (the mirror of \"what the host will put on the wire after a\n * restart\") for each protocol family, then fold it through the matching\n * `*ToCore` codec so the projection lands in the same identity/fingerprint\n * space as the live request.\n *\n * This used to live as three hand-rolled builders in the omp plugin\n * (wire-fold.ts) — protocol knowledge scattered across consumers is exactly\n * how the issue-#64 class of restart divergences happened (one place fixed,\n * another broke). The wire layouts now live here, next to the codecs that\n * define their identity space.\n *\n * CONTRACT: the caller maps its own persisted message shape into\n * {@link MirrorMessage} FIRST and normalizes text there (e.g. ref-tag\n * stripping is a host-app concern, not a wire concern). Builders only apply\n * host-encoder wire rules:\n * - thinking rides each wire the way the live encoder sends it\n * (openai: `reasoning_content` field — hosts that demote inline as\n * `<think>…</think>` land in the same identity space anyway because\n * `openaiToCore` normalizes the inline form; anthropic: signed\n * `{type:\"thinking\"}` blocks; responses: `{type:\"reasoning\"}` items);\n * - whitespace-only text survives on the openai wire, is dropped on the\n * anthropic/responses wires (host encoder behaviour);\n * - tool calls/results map to each wire's native shape.\n */\n\nexport type MirrorBlock =\n | { type: \"text\"; text: string }\n | { type: \"thinking\"; thinking: string; signature?: string }\n | { type: \"toolCall\"; id?: string; name?: string; arguments?: unknown };\n\nexport type MirrorMessage = {\n /** `meta` is anything the host sends as out-of-band/system-ish traffic. */\n role: \"user\" | \"assistant\" | \"toolResult\" | \"meta\";\n blocks?: MirrorBlock[];\n /** toolResult only. */\n toolCallId?: string;\n /** meta only: extracted text or summary. */\n text?: string;\n};\n\nfunction textBlocks(blocks: MirrorBlock[] | undefined): string[] {\n const out: string[] = [];\n for (const b of blocks ?? []) if (b.type === \"text\") out.push(b.text);\n return out;\n}\n\n/** Openai wire text: text blocks joined with \"\\n\" (whitespace-only kept). */\nfunction joinText(blocks: MirrorBlock[] | undefined): string {\n return textBlocks(blocks).join(\"\\n\");\n}\n\nfunction thinkingText(blocks: MirrorBlock[] | undefined): string {\n return blocks\n ?.filter((b) => b.type === \"thinking\" && b.thinking.trim().length > 0)\n .map((b) => (b as { thinking: string }).thinking)\n .join(\"\\n\") ?? \"\";\n}\n\n/** Openai/completions mirror: system message first, then the conversation\n * with thinking as the `reasoning_content` field (issue #103). */\nexport function mirrorOpenaiMessages(view: MirrorMessage[], systemText: string): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = [{ role: \"system\", content: systemText }];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) messages.push({ role: \"user\", content: text });\n } else if (message.role === \"assistant\") {\n const calls = (message.blocks ?? []).filter((b) => b.type === \"toolCall\") as Array<{ id?: string; name?: string; arguments?: unknown }>;\n const reasoning = thinkingText(message.blocks);\n const text = joinText(message.blocks);\n if (calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: text,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n tool_calls: calls.map((c) => ({\n id: c.id,\n type: \"function\",\n function: { name: c.name ?? \"\", arguments: JSON.stringify(c.arguments ?? {}) },\n })),\n });\n } else if (text || reasoning) {\n messages.push({ role: \"assistant\", content: text, ...(reasoning ? { reasoning_content: reasoning } : {}) });\n }\n } else if (message.role === \"toolResult\") {\n messages.push({ role: \"tool\", tool_call_id: message.toolCallId ?? \"\", content: joinText(message.blocks) });\n } else {\n const text = message.text ?? \"\";\n if (text) messages.push({ role: \"developer\", content: text });\n }\n }\n return messages;\n}\n\n/** Anthropic/messages mirror: no system message (the live request carries it\n * as the top-level `system` field, out of the fold space — issue #64), tool\n * results folded into user messages, thinking as signed `{type:\"thinking\"}`\n * blocks (issue #103). Unsigned thinking is demoted to text by the live\n * encoder; sending it as a thinking block diverges, so callers that persist\n * unsigned thinking should send it as a text block instead. */\nexport function mirrorAnthropicMessages(view: MirrorMessage[]): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = [];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) messages.push({ role: \"user\", content: [{ type: \"text\", text }] });\n } else if (message.role === \"assistant\") {\n const content: Array<Record<string, unknown>> = [];\n for (const b of message.blocks ?? []) {\n if (b.type === \"thinking\" && b.thinking.trim().length > 0) {\n content.push({\n type: \"thinking\",\n thinking: b.thinking,\n ...(typeof b.signature === \"string\" && b.signature ? { signature: b.signature } : {}),\n });\n } else if (b.type === \"text\" && b.text.trim().length > 0) {\n content.push({ type: \"text\", text: b.text });\n } else if (b.type === \"toolCall\") {\n let input: unknown = {};\n try {\n input = b.arguments && typeof b.arguments === \"object\" ? b.arguments : JSON.parse(JSON.stringify(b.arguments ?? {}));\n } catch {\n input = {};\n }\n content.push({ type: \"tool_use\", id: b.id, name: b.name ?? \"\", input });\n }\n }\n if (content.length > 0) messages.push({ role: \"assistant\", content });\n } else if (message.role === \"toolResult\") {\n messages.push({\n role: \"user\",\n content: [{ type: \"tool_result\", tool_use_id: message.toolCallId ?? \"\", content: joinText(message.blocks) }],\n });\n } else {\n const text = message.text ?? \"\";\n if (text) messages.push({ role: \"user\", content: [{ type: \"text\", text }] });\n }\n }\n return messages;\n}\n\n/** Responses mirror: the live /v1/responses request carries the system\n * prompt in the top-level `instructions` field and the conversation as an\n * `input` item array (issue #64, responses variant). Assistant blocks are\n * emitted in content order so the core sequence matches the live wire\n * (issue #103 parity). */\nexport function mirrorResponsesInput(view: MirrorMessage[]): Array<Record<string, unknown>> {\n const input: Array<Record<string, unknown>> = [];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) input.push({ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text }] });\n } else if (message.role === \"assistant\") {\n for (const b of message.blocks ?? []) {\n if (b.type === \"thinking\" && b.thinking.trim().length > 0) {\n input.push({ type: \"reasoning\", summary: [{ type: \"summary_text\", text: b.thinking }] });\n } else if (b.type === \"text\" && b.text.trim().length > 0) {\n input.push({ type: \"message\", role: \"assistant\", content: [{ type: \"output_text\", text: b.text }] });\n } else if (b.type === \"toolCall\") {\n let args = \"{}\";\n try {\n args = JSON.stringify(b.arguments ?? {});\n } catch {\n args = \"{}\";\n }\n input.push({ type: \"function_call\", call_id: b.id ?? \"\", name: b.name ?? \"\", arguments: args });\n }\n }\n } else if (message.role === \"toolResult\") {\n input.push({ type: \"function_call_output\", call_id: message.toolCallId ?? \"\", output: joinText(message.blocks) });\n } else {\n const text = message.text ?? \"\";\n if (text) input.push({ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text }] });\n }\n }\n return input;\n}\n\n/** Fold the openai mirror through `openaiToCore`. */\nexport function mirrorOpenaiToCore(view: MirrorMessage[], systemText: string): BiliMessage[] {\n const { msgs } = openaiToCore({\n model: \"prime-fold\",\n messages: mirrorOpenaiMessages(view, systemText) as Parameters<typeof openaiToCore>[0][\"messages\"],\n });\n return msgs;\n}\n\n/** Fold the anthropic mirror through `anthropicToCore`. */\nexport function mirrorAnthropicToCore(view: MirrorMessage[]): BiliMessage[] {\n const { msgs } = anthropicToCore({\n model: \"prime-fold\",\n messages: mirrorAnthropicMessages(view) as Parameters<typeof anthropicToCore>[0][\"messages\"],\n });\n return msgs;\n}\n\n/** Fold the responses mirror through `responsesToCore`. */\nexport function mirrorResponsesToCore(view: MirrorMessage[], systemText: string): BiliMessage[] {\n const { msgs } = responsesToCore({\n model: \"prime-fold\",\n instructions: systemText,\n input: mirrorResponsesInput(view) as Parameters<typeof responsesToCore>[0][\"input\"],\n });\n return msgs;\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAKpB,SAAS,OAAO,GAAmB;AACtC,SAAO,WAAW,QAAQ,EAAE,OAAO,GAAG,M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AAAA,EACJ;AACA,SAAO;AACX;AAGO,SAAS,mBAAmB,MAAuB,YAAmC;AACzF,QAAM,EAAE,KAAK,IAAI,aAAa;AAAA,IAC1B,OAAO;AAAA,IACP,UAAU,qBAAqB,MAAM,UAAU;AAAA,EACnD,CAAC;AACD,SAAO;AACX;AAGO,SAAS,sBAAsB,MAAsC;AACxE,QAAM,EAAE,KAAK,IAAI,gBAAgB;AAAA,IAC7B,OAAO;AAAA,IACP,UAAU,wBAAwB,IAAI;AAAA,EAC1C,CAAC;AACD,SAAO;AACX;AAGO,SAAS,sBAAsB,MAAuB,YAAmC;AAC5F,QAAM,EAAE,KAAK,IAAI,gBAAgB;AAAA,IAC7B,OAAO;AAAA,IACP,cAAc;AAAA,IACd,OAAO,qBAAqB,IAAI;AAAA,EACpC,CAAC;AACD,SAAO;AACX;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/wire/util.ts","../../src/wire/message-id.ts","../../src/wire/anthropic.ts","../../src/wire/demoted-thinking.ts","../../src/wire/bili-message.ts","../../src/wire/openai.ts","../../src/wire/responses.ts","../../src/wire/formats.ts","../../src/wire/mirror.ts","../../src/wire/compress-detect.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/** SHA-256-derived short id — kept verbatim from the proxy so message ids\n * stay byte-identical across the extraction (re-keying would orphan every\n * downstream map keyed on these ids). */\nexport function hashId(s: string): string {\n return createHash(\"sha256\").update(s, \"utf8\").digest(\"hex\").slice(0, 16);\n}\n\n/** How a conversation's identity was derived (kept verbatim from the proxy's\n * session-id.ts — only the TYPE moves; session-key derivation stays in the\n * proxy, which owns multi-tenant state). */\nexport type ConversationIdentity = {\n value: string;\n source: \"header\" | \"body-session\" | \"metadata-session\" | \"previous-response\" | \"content-fingerprint\" | \"generated\";\n clientProvided: boolean;\n};\n","import { hashId } from \"./util.js\";\n\n/**\n * Derive a stable, content-based message id.\n *\n * PROBLEM: none of the three wire protocols (Anthropic Messages, OpenAI Chat\n * Completions, OpenAI Responses) attach a stable id to request-side message\n * items. Historically each converter used `raw-${idx}` — a *position* index,\n * not an identity. As soon as a client deletes/reorders messages (other plugins\n * summarizing away old turns, multi-agent setups, etc.) the index drifts:\n * downstream ids shift, so\n * - assignRefs reuses stale `byRaw` entries, hiding new messages, and\n * - compression `effectiveMessageIds` start pointing at the *wrong* messages,\n * silently swallowing live content under an unrelated summary.\n *\n * FIX: derive the id from a SHA-256 of the message identity:\n * role + contentType + toolCallId + toolName + text\n * Two messages with identical identity collide. To keep duplicates distinct\n * (and avoid `covered` sets collapsing unrelated turns onto one id) we append a\n * within-conversation *cluster index* `_N`: the Nth occurrence of the same\n * identity, counting from 0 in arrival order.\n *\n * Trade-off vs a real client id:\n * - deleting a duplicated message only disturbs the cluster of that identity\n * (local damage), never the whole downstream (global damage like position).\n * - fully distinct messages are completely immune to reordering/deletion.\n *\n * `idx` is passed purely to break ties *within a single conversion pass*; it is\n * not part of the identity, so two passes over the same content produce the\n * same cluster numbering (deterministic).\n */\nexport function deriveMessageId(\n role: string,\n contentType: string,\n text: string,\n options: {\n toolCallId?: string;\n toolName?: string;\n } = {},\n): string {\n const seed = `${role}|${contentType}|${options.toolCallId ?? \"\"}|${options.toolName ?? \"\"}|${text}`;\n return \"h_\" + hashId(seed);\n}\n\n/**\n * Stateful cluster counter. Each converter instantiates one per conversion\n * pass; it tracks how many times each base identity has been seen so that the\n * Nth duplicate gets a `_${N}` suffix.\n */\nexport class ClusterCounter {\n private counts = new Map<string, number>();\n\n next(baseId: string): string {\n const n = this.counts.get(baseId) ?? 0;\n this.counts.set(baseId, n + 1);\n return n === 0 ? baseId : `${baseId}_${n}`;\n }\n}\n","import type { BiliMessage } from \"./bili-message.js\";\nimport { hashId } from \"./util.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\n\nexport type AnthropicTextBlock = { type: \"text\"; text: string; cache_control?: unknown };\nexport type AnthropicToolUse = {\n type: \"tool_use\";\n id: string;\n name: string;\n input: unknown;\n cache_control?: unknown;\n};\nexport type AnthropicToolResult = {\n type: \"tool_result\";\n tool_use_id: string;\n content: string | AnthropicTextBlock[];\n is_error?: boolean;\n cache_control?: unknown;\n};\nexport type AnthropicImage = { type: \"image\"; source: unknown };\nexport type AnthropicThinking = { type: \"thinking\"; thinking: string; signature?: string };\nexport type AnthropicBlock =\n | AnthropicTextBlock\n | AnthropicToolUse\n | AnthropicToolResult\n | AnthropicImage\n | AnthropicThinking;\n\nexport type AnthropicMessage = {\n role: \"user\" | \"assistant\";\n content: string | AnthropicBlock[];\n};\n\nexport type AnthropicRequestBody = {\n model?: string;\n max_tokens?: number;\n system?: string | AnthropicTextBlock[];\n messages: AnthropicMessage[];\n tools?: unknown[];\n stream?: boolean;\n temperature?: number;\n [key: string]: unknown;\n};\n\n\nexport function extractSystem(system: AnthropicRequestBody[\"system\"]): string {\n if (!system) return \"\";\n if (typeof system === \"string\") return system;\n return system.map((b) => b.text).join(\"\\n\\n\");\n}\n\nexport function buildSystem(text: string, original: AnthropicRequestBody[\"system\"]): string | AnthropicTextBlock[] {\n if (Array.isArray(original) && original.length > 0) {\n const ccBlock = original.find((b) => b.cache_control);\n return [{ type: \"text\", text, ...(ccBlock ? { cache_control: ccBlock.cache_control } : {}) }];\n }\n return text;\n}\n\ntype Flat = { msgs: BiliMessage[]; cacheControls: Map<string, unknown> };\n\nexport function anthropicToCore(body: AnthropicRequestBody): Flat {\n const msgs: BiliMessage[] = [];\n const cacheControls = new Map<string, unknown>();\n const clusters = new ClusterCounter();\n for (const m of body.messages) {\n const blocks = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n for (const b of blocks) {\n switch (b.type) {\n case \"text\": {\n const base = deriveMessageId(m.role, \"text\", b.text);\n const id = clusters.next(base);\n msgs.push({ id, role: m.role, contentType: \"text\", text: b.text });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"tool_use\": {\n const base = deriveMessageId(\"assistant\", \"tool-call\", safeStringify(b.input), {\n toolCallId: b.id,\n toolName: b.name,\n });\n const id = clusters.next(base);\n msgs.push({\n id,\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: b.name,\n toolCallId: b.id,\n text: safeStringify(b.input),\n });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"tool_result\": {\n const text = typeof b.content === \"string\" ? b.content : b.content.map((c) => c.text).join(\"\\n\");\n const base = deriveMessageId(\"tool\", \"tool-result\", text, { toolCallId: b.tool_use_id });\n const id = clusters.next(base);\n msgs.push({\n id,\n role: \"tool\",\n contentType: \"tool-result\",\n toolCallId: b.tool_use_id,\n text,\n ...(b.is_error === true ? { toolIsError: true } : {}),\n });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"thinking\": {\n const base = deriveMessageId(\"assistant\", \"reasoning\", b.thinking);\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: b.thinking,\n ...(b.signature ? { thinkingSignature: b.signature } : {}),\n });\n break;\n }\n case \"image\": {\n const base = deriveMessageId(m.role, \"text\", \"[image]\");\n msgs.push({\n id: clusters.next(base),\n role: m.role,\n contentType: \"text\",\n text: \"[image]\",\n rawAnthropicBlock: b,\n });\n break;\n }\n }\n }\n }\n return { msgs, cacheControls };\n}\n\nexport function coreToAnthropic(messages: BiliMessage[], cacheControls?: Map<string, unknown>): AnthropicMessage[] {\n const out: AnthropicMessage[] = [];\n let current: { role: \"user\" | \"assistant\"; blocks: AnthropicBlock[] } | null = null;\n const flush = () => {\n if (current && current.blocks.length > 0) {\n out.push({ role: current.role, content: current.blocks });\n }\n current = null;\n };\n const cc = (id: string): { cache_control?: unknown } => {\n const v = cacheControls?.get(id);\n return v ? { cache_control: v } : {};\n };\n for (const m of messages) {\n const target: \"user\" | \"assistant\" =\n m.role === \"assistant\" ? \"assistant\" : \"user\";\n if (!current || current.role !== target) {\n flush();\n current = { role: target, blocks: [] };\n }\n switch (m.contentType) {\n case \"text\": {\n if (m.rawAnthropicBlock) {\n current.blocks.push(m.rawAnthropicBlock as AnthropicBlock);\n break;\n }\n current.blocks.push({ type: \"text\", text: m.text ?? \"\", ...cc(m.id) });\n break;\n }\n case \"tool-call\":\n current.blocks.push({\n type: \"tool_use\",\n id: m.toolCallId ?? `call_${m.id}`,\n name: m.toolName ?? \"unknown\",\n input: safeParse(m.text),\n ...cc(m.id),\n });\n break;\n case \"tool-result\":\n current.blocks.push({\n type: \"tool_result\",\n tool_use_id: m.toolCallId ?? \"\",\n content: m.text ?? \"\",\n ...(m.toolIsError ? { is_error: true } : {}),\n ...cc(m.id),\n });\n break;\n case \"reasoning\":\n current.blocks.push({\n type: \"thinking\",\n thinking: m.text ?? \"\",\n ...(m.thinkingSignature ? { signature: m.thinkingSignature } : {}),\n });\n break;\n }\n }\n flush();\n return out;\n}\n\n/** Extract the conversation dimension for Anthropic: a client-provided\n * session header if present, else a content fingerprint of the first user\n * message. The protocol+upstream+key dimensions are mixed in by the caller\n * (server.ts) via deriveSessionId() — this function contributes only the\n * conversation axis. */\nexport function conversationSignalAnthropic(body: AnthropicRequestBody, headerValue?: string): string {\n if (headerValue && headerValue.trim()) return headerValue.trim();\n const firstUser = body.messages.find((m) => m.role === \"user\");\n const seed = firstUser ? JSON.stringify(firstUser.content) : \"default\";\n return hashId(seed);\n}\n\nfunction safeStringify(v: unknown): string {\n try {\n return JSON.stringify(v ?? {});\n } catch {\n return \"{}\";\n }\n}\n\nfunction safeParse(s: string | undefined): unknown {\n if (!s) return {};\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n}\n","/** Inline \"demoted thinking\" normalization.\n *\n * Hosts that cannot replay prior-turn reasoning as a structured block\n * (pi-ai transform-messages demotion on model switch, openai-completions\n * `requiresThinkingAsText` profiles, gateways that inline native\n * reasoning) fold it INTO the assistant content string wrapped in a\n * dialect tag:\n *\n * glm / deepseek / kimi / qwen3 / hermes : <think>\\n{text}\\n</think>\n * anthropic / minimax / xml : <thinking>\\n{text}\\n</thinking>\n * gemini : ```thinking\\n{text}\\n```\n *\n * followed by a single \"\\n\" glue before the next content block. The same\n * logical turn can therefore arrive as a `reasoning_content` field (or a\n * separate reasoning item on /v1/responses) OR as this inline form. If the\n * wire codecs kept both as one text blob, the two serializations of one\n * turn would land in DIFFERENT core-id/fingerprint spaces — exactly the\n * issue #64 \"restart loses blocks\" class, where the mirror produced one\n * form and the live wire the other.\n *\n * splitDemotedThinking() reverses the rendering byte-exactly so both\n * codecs can normalize before identity derivation (deriveMessageId). It\n * only fires when the tag opens at offset 0 of the content, which is the\n * only position the demotion renderer can produce it in.\n *\n * One form is intentionally NOT recoverable here: the pi-ai anthropic\n * dialect demotes to BARE text (no tag), which is indistinguishable from\n * ordinary assistant prose; that case must be aligned upstream (mirror\n * uses the same bare rendering), not parsed. */\n\nexport type DemotedSplit = {\n reasoning: string;\n text: string;\n};\n\ntype DelimitedForm = {\n open: string;\n close: string;\n};\n\n/** The three inline tag forms hosts actually emit (see file comment). */\nconst FORMS: readonly DelimitedForm[] = [\n { open: \"<think>\\n\", close: \"\\n</think>\" },\n { open: \"<thinking>\\n\", close: \"\\n</thinking>\" },\n { open: \"```thinking\\n\", close: \"\\n```\" },\n];\n\n/** If `content` starts with one or more inline demoted-thinking blocks,\n * split them out. Returns null when no tag opens the content (the common\n * case — including every user message and every assistant message whose\n * reasoning traveled as a field/item), in which case callers keep the\n * content as-is. Malformed (unterminated) or empty blocks do not match;\n * the content is then treated as plain text, never dropped. */\nexport function splitDemotedThinking(content: string): DemotedSplit | null {\n let rest = content;\n const parts: string[] = [];\n for (;;) {\n let matched = false;\n for (const form of FORMS) {\n if (!rest.startsWith(form.open)) continue;\n const end = rest.indexOf(form.close, form.open.length);\n if (end < 0) continue;\n const inner = rest.slice(form.open.length, end);\n if (inner.length === 0) continue;\n parts.push(inner);\n rest = rest.slice(end + form.close.length);\n // Glue the demotion renderer inserts between a demoted block\n // and the block that follows it.\n if (rest.startsWith(\"\\n\")) rest = rest.slice(1);\n matched = true;\n break;\n }\n if (!matched) break;\n }\n if (parts.length === 0) return null;\n return { reasoning: parts.join(\"\\n\"), text: rest };\n}\n","/**\n * Lossless message bridge between protocol-specific message formats and the\n * kernel's CoreMessage.\n *\n * Problem: `anthropicToCore` / `openaiToCore` / `responsesToCore` flatten\n * rich protocol blocks (images, thinking signatures, tool_result.is_error,\n * developer-role messages, image_url) into plain `{ text }` placeholders.\n * The reverse `coreToX` then can't reconstruct them — `is_error` is lost\n * (upstream can't tell a tool error from a result), `thinking.signature` is\n * lost (Anthropic rejects thinking blocks without a matching signature),\n * images become \"[image]\" (the model never sees the picture).\n *\n * Solution: `BiliMessage` extends CoreMessage with optional sidecar fields.\n * The kernel only reads `{ ...message }` (spread copy) and known fields, so\n * the extra fields survive the compression pipeline unchanged and arrive back\n * at `coreToX`, which prefers them over the flattened `text`. No `as any`\n * needed — TypeScript array covariance lets `BiliMessage[]` satisfy a\n * `CoreMessage[]` parameter.\n */\n\nimport type { CoreMessage } from \"acp-kernel\";\n\n/** A message that carries its original protocol block(s) verbatim, so the\n * reverse conversion can reconstruct losslessly. Every field is optional —\n * plain text messages (the common case) have none set. */\nexport interface BiliMessage extends CoreMessage {\n /** Anthropic: the original content block for an image or a structured\n * tool_result. Restored verbatim by coreToAnthropic. */\n rawAnthropicBlock?: unknown;\n /** OpenAI chat: the original content part for an image_url, or the\n * original message object for a developer-role message. */\n rawOpenaiContent?: unknown;\n /** Responses API: the original input item (for input_image, or a raw\n * function_call / function_call_output we pass through). */\n rawResponsesItem?: unknown;\n /** Anthropic thinking signature. Anthropic verifies thinking+signature\n * pairs; without it the request is rejected. Stored alongside the\n * reasoning text so coreToAnthropic can reattach it. */\n thinkingSignature?: string;\n /** OpenAI reasoning_content (chain-of-thought from DeepSeek-R1, GLM-4.6\n * thinking, Qwen-QwQ). These models require reasoning_content be echoed\n * back on subsequent requests or the API returns HTTP 400; stored so\n * coreToOpenai can reattach it. */\n reasoningContent?: string;\n /** Anthropic tool_result.is_error. Marks the tool result as an error so\n * the model knows the tool failed (not just returned an error string). */\n toolIsError?: boolean;\n /** OpenAI: original role was \"developer\" (reconstructed as \"system\" by\n * openaiToCore for the kernel; coreToOpenai restores \"developer\"). */\n originalRole?: \"system\" | \"developer\";\n /** The original media type for an image (image/png, image/jpeg, image/gif,\n * image/webp). Lets coreToOpenai/coreToResponses rebuild image_url /\n * input_image with the right data URL. */\n imageMediaType?: string;\n /** The base64 data of an image (without the data: prefix). Lets the\n * reverse conversion rebuild the full image payload. */\n imageBase64?: string;\n /** OpenAI chat: ALL original image_url content parts (each a data: URL\n * part) for a user message carrying more than one image, in wire order.\n * coreToOpenai re-emits these verbatim (after the text part). The\n * singular `rawOpenaiContent` still covers the single-image case and\n * legacy persisted state. Typed as unknown[] (not OpenAIContentPart) to\n * avoid a circular import with the openai codec. */\n rawOpenaiContentParts?: unknown[];\n}\n\n/** Narrow a BiliMessage[] to CoreMessage[] for the kernel. The sidecar fields\n * are transparently carried along — the kernel's `{ ...msg }` copies them. */\nexport function toCoreMessages(msgs: BiliMessage[]): CoreMessage[] {\n return msgs as CoreMessage[];\n}\n\n/** Re-decode a base64 data URL into media type + data. Returns undefined if\n * the input is not a recognized data URL. Used by openaiToCore/responsesToCore\n * to split image_url/input_image into the sidecar fields. */\nexport function parseDataUrl(url: string): { mediaType: string; base64: string } | undefined {\n const m = /^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);\n if (!m) return undefined;\n return { mediaType: m[1]!, base64: m[2]! };\n}\n","import { splitDemotedThinking } from \"./demoted-thinking.js\";\nimport { hashId } from \"./util.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\nimport { parseDataUrl, type BiliMessage } from \"./bili-message.js\";\n\nexport type OpenAIContentPart =\n | { type: \"text\"; text: string }\n | { type: \"image_url\"; image_url: { url: string } }\n | { type: string; [k: string]: unknown };\n\nexport type OpenAIToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\nexport type OpenAIMessage = {\n role: \"system\" | \"developer\" | \"user\" | \"assistant\" | \"tool\";\n content?: string | null | OpenAIContentPart[];\n reasoning_content?: string | null;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n name?: string;\n};\n\nexport type OpenAITool = {\n type: \"function\";\n function: { name: string; description?: string; parameters?: unknown };\n};\n\nexport type OpenAIRequestBody = {\n model?: string;\n messages: OpenAIMessage[];\n tools?: OpenAITool[];\n stream?: boolean;\n [key: string]: unknown;\n};\n\ntype Flat = { msgs: BiliMessage[]; systemText: string };\n\n/** Hoist the contiguous leading system/developer prefix out of the fold\n * space (openai-chat variant of the responses codec's systemParts and the\n * anthropic codec's top-level `system` field). The system prompt is host\n * runtime state: its content varies across restarts (injected reminders,\n * host-composed instructions), so keeping it inside the id space made every\n * downstream fingerprint spanning it unstable, and a compress range that\n * covered it removed the model's system prompt from the rebuilt wire\n * entirely. Mid-conversation system messages (rare, host-synthetic) stay in\n * the fold space unchanged. */\nexport function openaiToCore(body: OpenAIRequestBody): Flat {\n const msgs: BiliMessage[] = [];\n const systemParts: string[] = [];\n const clusters = new ClusterCounter();\n for (const m of body.messages) {\n switch (m.role) {\n case \"system\":\n case \"developer\": {\n if (msgs.length === 0) {\n systemParts.push(stringContent(m.content));\n break;\n }\n const base = deriveMessageId(m.role, \"text\", stringContent(m.content));\n msgs.push({ id: clusters.next(base), role: \"system\", contentType: \"text\", text: stringContent(m.content), originalRole: m.role });\n break;\n }\n case \"user\": {\n const text = stringContent(m.content);\n const imgs = allImageParts(m.content);\n const firstImg = imgs[0];\n const firstUrl = firstImg ? firstImg.image_url.url : undefined;\n const firstParsed = firstUrl ? parseDataUrl(firstUrl) : undefined;\n const base = deriveMessageId(\"user\", \"text\", text);\n msgs.push({\n id: clusters.next(base),\n role: \"user\",\n contentType: \"text\",\n text,\n ...(imgs.length === 1 && firstParsed\n ? { rawOpenaiContent: imgs[0], imageMediaType: firstParsed.mediaType, imageBase64: firstParsed.base64 }\n : imgs.length > 1\n ? { rawOpenaiContentParts: imgs }\n : {}),\n });\n break;\n }\n case \"assistant\": {\n const fieldReasoning = typeof m.reasoning_content === \"string\" ? m.reasoning_content : \"\";\n let reasoning = fieldReasoning;\n let text = stringContent(m.content);\n if (!reasoning) {\n // Hosts that cannot replay prior-turn reasoning as a\n // structured field inline it into content wrapped in a\n // dialect tag (<think>, <thinking>, ```thinking). Split\n // it back out BEFORE identity derivation so the inline\n // form and the reasoning_content field form of one turn\n // land in a single core-id/fingerprint space (issue #64\n // demoted variant).\n const split = splitDemotedThinking(text);\n if (split) {\n reasoning = split.reasoning;\n text = split.text;\n }\n }\n if (reasoning) {\n const base = deriveMessageId(\"assistant\", \"reasoning\", reasoning);\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: reasoning,\n reasoningContent: reasoning,\n });\n }\n if (text) {\n const base = deriveMessageId(\"assistant\", \"text\", text);\n msgs.push({ id: clusters.next(base), role: \"assistant\", contentType: \"text\", text });\n }\n if (Array.isArray(m.tool_calls)) {\n for (const tc of m.tool_calls) {\n const base = deriveMessageId(\"assistant\", \"tool-call\", tc.function.arguments ?? \"\", {\n toolCallId: tc.id,\n toolName: tc.function.name,\n });\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: tc.function.name,\n toolCallId: tc.id,\n text: tc.function.arguments ?? \"\",\n });\n }\n }\n break;\n }\n case \"tool\": {\n const base = deriveMessageId(\"tool\", \"tool-result\", stringContent(m.content), {\n toolCallId: m.tool_call_id ?? \"\",\n });\n msgs.push({\n id: clusters.next(base),\n role: \"tool\",\n contentType: \"tool-result\",\n toolCallId: m.tool_call_id ?? \"\",\n text: stringContent(m.content),\n });\n break;\n }\n }\n }\n return { msgs, systemText: systemParts.join(\"\\n\\n\") };\n}\n\nexport function coreToOpenai(messages: BiliMessage[]): OpenAIMessage[] {\n const out: OpenAIMessage[] = [];\n let pending: { text: string | null; toolCalls: OpenAIToolCall[]; reasoning: string | null } | null = null;\n const flush = () => {\n if (!pending) return;\n const reasoning = pending.reasoning !== null && pending.reasoning.length > 0 ? pending.reasoning : undefined;\n if (pending.toolCalls.length > 0) {\n out.push({\n role: \"assistant\",\n content: pending.text ?? null,\n tool_calls: pending.toolCalls,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n });\n } else if (pending.text !== null) {\n out.push({ role: \"assistant\", content: pending.text, ...(reasoning ? { reasoning_content: reasoning } : {}) });\n } else if (reasoning) {\n out.push({ role: \"assistant\", content: null, reasoning_content: reasoning });\n }\n pending = null;\n };\n for (const m of messages) {\n if (m.role === \"assistant\") {\n if (!pending) pending = { text: null, toolCalls: [], reasoning: null };\n if (m.contentType === \"reasoning\") {\n pending.reasoning = (pending.reasoning ?? \"\") + (m.reasoningContent ?? m.text ?? \"\");\n } else if (m.contentType === \"text\") {\n pending.text = (pending.text ?? \"\") + (m.text ?? \"\");\n } else if (m.contentType === \"tool-call\") {\n pending.toolCalls.push({\n id: m.toolCallId ?? `call_${m.id}`,\n type: \"function\",\n function: { name: m.toolName ?? \"unknown\", arguments: m.text ?? \"\" },\n });\n }\n } else {\n flush();\n if (m.role === \"system\") {\n out.push({ role: m.originalRole === \"developer\" ? \"developer\" : \"system\", content: m.text ?? \"\" });\n } else if (m.role === \"user\") {\n if (m.rawOpenaiContent || m.imageBase64 || m.rawOpenaiContentParts) {\n const parts: OpenAIContentPart[] = [];\n if (m.text) parts.push({ type: \"text\", text: m.text });\n if (m.rawOpenaiContentParts && m.rawOpenaiContentParts.length > 0) {\n for (const part of m.rawOpenaiContentParts) parts.push(part as OpenAIContentPart);\n } else if (m.rawOpenaiContent) {\n parts.push(m.rawOpenaiContent as OpenAIContentPart);\n } else if (m.imageBase64 && m.imageMediaType) {\n parts.push({ type: \"image_url\", image_url: { url: `data:${m.imageMediaType};base64,${m.imageBase64}` } });\n }\n out.push({ role: \"user\", content: parts });\n } else {\n out.push({ role: \"user\", content: m.text ?? \"\" });\n }\n } else if (m.role === \"tool\") {\n out.push({ role: \"tool\", tool_call_id: m.toolCallId ?? \"\", content: m.text ?? \"\" });\n }\n }\n }\n flush();\n return out;\n}\n\nexport function injectOpenaiSystem(messages: OpenAIMessage[], parts: string[]): OpenAIMessage[] {\n if (parts.length === 0) return messages;\n const extra = parts.join(\"\\n\\n\");\n if (messages.length > 0 && (messages[0]?.role === \"system\" || messages[0]?.role === \"developer\")) {\n const head = messages[0] as OpenAIMessage;\n const base = stringContent(head.content);\n const merged = base ? `${base}\\n\\n---\\n\\n${extra}` : extra;\n return [{ ...head, content: merged }, ...messages.slice(1)];\n }\n return [{ role: \"system\", content: extra }, ...messages];\n}\n\n/** Extract the conversation dimension for OpenAI Chat: a client-provided\n * session header if present, else a content fingerprint of the first user\n * message. See conversationSignalAnthropic for the full rationale. */\nexport function conversationSignalOpenai(body: OpenAIRequestBody, headerValue?: string): string {\n if (headerValue && headerValue.trim()) return headerValue.trim();\n const firstUser = body.messages.find((m) => m.role === \"user\");\n const seed = firstUser ? stringContent(firstUser.content) : \"default\";\n return hashId(seed);\n}\n\nfunction stringContent(content: OpenAIMessage[\"content\"]): string {\n if (content == null) return \"\";\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((p) => (typeof p === \"string\" ? p : p.type === \"text\" ? (p as { text?: string }).text ?? \"\" : \"\"))\n .join(\"\\n\");\n }\n return \"\";\n}\n\ntype OpenAIImagePart = { type: \"image_url\"; image_url: { url: string } };\n\n/** Collect ALL data-URL image parts in a user content array, in wire order.\n * (firstImagePart only kept the first, which silently dropped images 2..N\n * on the coreToOpenai rebuild.) */\nfunction allImageParts(content: OpenAIMessage[\"content\"]): OpenAIImagePart[] {\n if (!Array.isArray(content)) return [];\n const out: OpenAIImagePart[] = [];\n for (const p of content) {\n if (typeof p !== \"object\" || p === null) continue;\n if (!(\"type\" in p) || p.type !== \"image_url\" || !(\"image_url\" in p)) continue;\n // The union's index-signature member leaves image_url as `unknown`, so\n // narrow via a named const before reading the url.\n const imagePart = p as { image_url: { url?: unknown } };\n const url = imagePart.image_url.url;\n if (typeof url === \"string\" && parseDataUrl(url)) out.push(p as OpenAIImagePart);\n }\n return out;\n}\n","import type { CoreMessage } from \"../types.js\";\nimport { splitDemotedThinking } from \"./demoted-thinking.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\nimport type { ConversationIdentity } from \"./util.js\";\nimport { hashId } from \"./util.js\";\nimport { parseDataUrl, type BiliMessage } from \"./bili-message.js\";\n\nexport type ResponseContentPart =\n | { type: \"input_text\"; text: string; [key: string]: unknown }\n | { type: \"output_text\"; text: string; [key: string]: unknown }\n | { type: \"input_image\"; image_url: string; [key: string]: unknown }\n | { type: string; [key: string]: unknown };\n\nexport type ResponseInputMessage = {\n type: \"message\";\n role: \"system\" | \"developer\" | \"user\" | \"assistant\";\n content: string | ResponseContentPart[];\n [key: string]: unknown;\n};\n\nexport type ResponseFunctionCall = {\n type: \"function_call\";\n id?: string;\n call_id: string;\n name: string;\n arguments: string;\n [key: string]: unknown;\n};\n\nexport type ResponseFunctionCallOutput = {\n type: \"function_call_output\";\n call_id: string;\n output: string;\n [key: string]: unknown;\n};\n\nexport type ResponseInputItem =\n | ResponseInputMessage\n | ResponseFunctionCall\n | ResponseFunctionCallOutput\n | { type: string; [key: string]: unknown };\n\nexport type ResponsesRequestBody = {\n model?: string;\n input: string | ResponseInputItem[];\n instructions?: string;\n tools?: unknown[];\n stream?: boolean;\n session_id?: string;\n previous_response_id?: string;\n prompt_cache_key?: string;\n metadata?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\ntype ResponseLayoutSlot = {\n original: ResponseInputItem;\n coreId?: string;\n};\n\nexport type ResponsesProjection = {\n msgs: BiliMessage[];\n systemParts: string[];\n preamble: ResponseInputItem[];\n customToolCallIds: Set<string>;\n layout: ResponseLayoutSlot[];\n stringInput?: { original: string; coreId: string };\n /** Reasoning items dropped because ACP_REASONING_KEEP=none. 0 by default —\n * reasoning is normally routed through the compression pipeline so it is\n * hidden automatically once its turn is summarized. */\n droppedReasoning: number;\n};\n\n/** Item types that are host DIRECTIVES (tool/definition listings), not\n * conversation history: preserved verbatim and re-prepended at input[0..].\n * `additional_tools` carries the Codex code_mode exec/wait tool definitions\n * and MUST stay at input[0]. `mcp_list_tools` is a stable per-session listing.\n *\n * Only definitions belong here. Output/action items from a prior response\n * (reasoning, computer_call, function_call, mcp_call, ...) ARE conversation\n * history and are routed as tracked BiliMessages, so the compression pipeline\n * hides them once their turn is summarized — preserving them verbatim in the\n * preamble instead made them accumulate unbounded every turn and broke Codex's\n * prompt-cache prefix. */\nconst OPAQUE_ITEM_TYPES = new Set([\n \"additional_tools\",\n \"mcp_list_tools\",\n]);\n\nfunction isOpaqueItem(item: ResponseInputItem): boolean {\n return OPAQUE_ITEM_TYPES.has(item.type);\n}\n\nfunction shouldDropAllReasoning(): boolean {\n return (process.env.ACP_REASONING_KEEP ?? \"\").trim().toLowerCase() === \"none\";\n}\n\nfunction partText(part: ResponseContentPart): string {\n if (part.type === \"input_text\" || part.type === \"output_text\") {\n return typeof part.text === \"string\" ? part.text : \"\";\n }\n return \"\";\n}\n\nfunction messageContent(content: string | ResponseContentPart[]): string {\n return typeof content === \"string\" ? content : content.map(partText).join(\"\\n\");\n}\n\n/** Extract the reasoning text from a responses reasoning item. The host\n * carries it in `content` (reasoning_text parts); the primeFold mirror\n * carries it in `summary` (summary_text parts). Both must yield the same\n * text so the kernel derives the same core id (issue #64, responses). */\nfunction reasoningText(item: ResponseInputItem): string {\n const fromParts = (parts: unknown, type: string): string => {\n if (!Array.isArray(parts)) return \"\";\n const texts: string[] = [];\n for (const part of parts) {\n if (part && typeof part === \"object\" && \"type\" in part && \"text\" in part) {\n const rec = part as { type: unknown; text: unknown };\n if (rec.type === type && typeof rec.text === \"string\") texts.push(rec.text);\n }\n }\n return texts.join(\"\\n\");\n };\n const content = \"content\" in item ? item.content : undefined;\n const summary = \"summary\" in item ? item.summary : undefined;\n return fromParts(content, \"reasoning_text\") || fromParts(summary, \"summary_text\");\n}\n\nexport function responsesToCore(body: ResponsesRequestBody): ResponsesProjection {\n const msgs: BiliMessage[] = [];\n const systemParts: string[] = [];\n const preamble: ResponseInputItem[] = [];\n const customToolCallIds = new Set<string>();\n const layout: ResponseLayoutSlot[] = [];\n let droppedReasoning = 0;\n const clusters = new ClusterCounter();\n let idx = 0;\n if (typeof body.instructions === \"string\" && body.instructions.trim()) systemParts.push(body.instructions);\n if (typeof body.input === \"string\") {\n const id = clusters.next(deriveMessageId(\"user\", \"text\", body.input));\n msgs.push({ id, role: \"user\", contentType: \"text\", text: body.input });\n return { msgs, systemParts, preamble, customToolCallIds, layout, droppedReasoning, stringInput: { original: body.input, coreId: id } };\n }\n for (const item of body.input) {\n let coreId: string | undefined;\n if (isOpaqueItem(item)) preamble.push(item);\n switch (item.type) {\n case \"reasoning\": {\n if (shouldDropAllReasoning()) {\n droppedReasoning++;\n continue;\n }\n // Key the reasoning piece on its TEXT (deterministic), consistent\n // with the anthropic/openai codecs. The host mints a per-request\n // item id that the primeFold mirror cannot reproduce; keying on it\n // put the mirror in a different ref/fingerprint space, so restart\n // replay rejected every in-stream compress call (issue #64,\n // responses variant).\n const text = reasoningText(item);\n const rid =\n text.length > 0\n ? text\n : \"id\" in item && typeof item.id === \"string\"\n ? item.id\n : hashId(JSON.stringify(item));\n coreId = clusters.next(deriveMessageId(\"assistant\", \"reasoning\", rid));\n msgs.push({\n id: coreId,\n role: \"assistant\",\n contentType: \"reasoning\",\n text: rid,\n rawResponsesItem: item,\n });\n break;\n }\n case \"message\": {\n const message = item as ResponseInputMessage;\n const text = messageContent(message.content);\n if (message.role === \"system\" || message.role === \"developer\") {\n systemParts.push(text);\n idx++;\n continue;\n } else if (message.role === \"user\" || (message.role === \"assistant\" && text)) {\n const role = message.role;\n let effText = text;\n if (role === \"assistant\") {\n // Same normalization as openaiToCore: hosts that demote\n // prior-turn reasoning inline it as a dialect tag at the\n // head of the message text. Split it out before identity\n // derivation so the inline form and the separate\n // reasoning-item form of one turn share a single\n // core-id/fingerprint space.\n const split = splitDemotedThinking(text);\n if (split) {\n msgs.push({\n id: clusters.next(deriveMessageId(\"assistant\", \"reasoning\", split.reasoning)),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: split.reasoning,\n rawResponsesItem: item,\n });\n effText = split.text;\n }\n }\n if (effText) {\n coreId = clusters.next(deriveMessageId(role, \"text\", effText));\n const imageUrl = Array.isArray(message.content)\n ? message.content.find((part) => part.type === \"input_image\" && typeof part.image_url === \"string\")?.image_url\n : undefined;\n const image = typeof imageUrl === \"string\" ? parseDataUrl(imageUrl) : undefined;\n msgs.push({\n id: coreId,\n role,\n contentType: \"text\",\n text: effText,\n rawResponsesItem: item,\n ...(image ? { imageMediaType: image.mediaType, imageBase64: image.base64 } : {}),\n });\n }\n }\n break;\n }\n case \"function_call\": {\n const call = item as ResponseFunctionCall;\n coreId = clusters.next(deriveMessageId(\"assistant\", \"tool-call\", call.arguments ?? \"\", {\n toolCallId: call.call_id,\n toolName: call.name,\n }));\n msgs.push({\n id: coreId,\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: call.name,\n toolCallId: call.call_id,\n text: call.arguments ?? \"\",\n rawResponsesItem: item,\n });\n break;\n }\n case \"function_call_output\": {\n const output = item as ResponseFunctionCallOutput;\n const text = typeof output.output === \"string\" ? output.output : JSON.stringify(output.output);\n coreId = clusters.next(deriveMessageId(\"tool\", \"tool-result\", text, { toolCallId: output.call_id }));\n msgs.push({ id: coreId, role: \"tool\", contentType: \"tool-result\", toolCallId: output.call_id, text, rawResponsesItem: item });\n break;\n }\n case \"computer_call\":\n case \"computer_call_output\":\n case \"file_search_call\":\n case \"web_search_call\":\n case \"image_generation_call\":\n case \"code_interpreter_call\":\n case \"mcp_call\": {\n const rid =\n typeof (item as { id?: unknown }).id === \"string\"\n ? String((item as { id?: string }).id)\n : hashId(JSON.stringify(item));\n coreId = clusters.next(deriveMessageId(\"assistant\", \"responses-call\", rid));\n msgs.push({ id: coreId, role: \"assistant\", contentType: \"reasoning\", text: rid, rawResponsesItem: item });\n break;\n }\n case \"custom_tool_call\": {\n const ctc = item as { call_id?: string; name?: string; input?: string; arguments?: string };\n const callId = ctc.call_id ?? `call_${idx}`;\n customToolCallIds.add(callId);\n const argText = ctc.input ?? ctc.arguments ?? \"\";\n coreId = clusters.next(deriveMessageId(\"assistant\", \"tool-call\", argText, { toolCallId: callId, toolName: ctc.name ?? \"custom\" }));\n msgs.push({ id: coreId, role: \"assistant\", contentType: \"tool-call\", toolName: ctc.name ?? \"custom\", toolCallId: callId, text: argText, rawResponsesItem: item });\n break;\n }\n case \"custom_tool_call_output\": {\n const ctco = item as { call_id?: string; output?: string };\n const callId = ctco.call_id ?? `call_${idx}`;\n customToolCallIds.add(callId);\n const outText = typeof ctco.output === \"string\" ? ctco.output : JSON.stringify(ctco.output ?? \"\");\n coreId = clusters.next(deriveMessageId(\"tool\", \"tool-result\", outText, { toolCallId: callId }));\n msgs.push({ id: coreId, role: \"tool\", contentType: \"tool-result\", toolCallId: callId, text: outText, rawResponsesItem: item });\n break;\n }\n default:\n if (!isOpaqueItem(item)) preamble.push(item);\n break;\n }\n layout.push({ original: item, coreId });\n idx++;\n }\n return { msgs, systemParts, preamble, customToolCallIds, layout, droppedReasoning };\n}\n\nfunction patchTextParts(parts: ResponseContentPart[], text: string): ResponseContentPart[] {\n const textIndexes = parts.flatMap((part, index) =>\n part.type === \"input_text\" || part.type === \"output_text\" ? [index] : [],\n );\n if (textIndexes.length === 0) return [{ type: \"input_text\", text }, ...parts];\n const first = textIndexes[0];\n const remaining = new Set(textIndexes.slice(1));\n return parts.map((part, index) => {\n if (index === first) return { ...part, text };\n if (remaining.has(index)) return { ...part, text: \"\" };\n return part;\n });\n}\n\nfunction patchOriginalItem(original: ResponseInputItem, source: CoreMessage, next: CoreMessage): ResponseInputItem {\n if (\n source.text === next.text &&\n source.toolName === next.toolName &&\n source.toolCallId === next.toolCallId &&\n source.role === next.role &&\n source.contentType === next.contentType\n ) return original;\n if (original.type === \"message\") {\n const message = original as ResponseInputMessage;\n const content = typeof message.content === \"string\" ? next.text ?? \"\" : patchTextParts(message.content, next.text ?? \"\");\n return { ...message, content };\n }\n if (original.type === \"function_call\") {\n return {\n ...original,\n name: next.toolName ?? String(original.name ?? \"unknown\"),\n call_id: next.toolCallId ?? String(original.call_id ?? \"\"),\n arguments: next.text ?? \"\",\n };\n }\n if (original.type === \"function_call_output\") {\n return { ...original, call_id: next.toolCallId ?? String(original.call_id ?? \"\"), output: next.text ?? \"\" };\n }\n return original;\n}\n\nexport function patchResponsesInput(projection: ResponsesProjection, messages: CoreMessage[]): string | ResponseInputItem[] {\n if (projection.stringInput) {\n const original = projection.msgs.find((message) => message.id === projection.stringInput?.coreId);\n const next = messages.find((message) => message.id === projection.stringInput?.coreId);\n if (original && next && messages.length === 1 && next.role === \"user\" && next.contentType === \"text\") {\n return next.text === original.text ? projection.stringInput.original : next.text ?? \"\";\n }\n return coreToResponses(messages, projection.customToolCallIds);\n }\n const sourceById = new Map(projection.msgs.map((message) => [message.id, message]));\n const nextById = new Map(messages.map((message) => [message.id, message]));\n const slotById = new Map<string, number>();\n projection.layout.forEach((slot, index) => {\n if (slot.coreId) slotById.set(slot.coreId, index);\n });\n const insertions = new Map<number, ResponseInputItem[]>();\n for (let index = 0; index < messages.length; index++) {\n const message = messages[index]!;\n if (sourceById.has(message.id)) continue;\n let target = projection.layout.length;\n for (let nextIndex = index + 1; nextIndex < messages.length; nextIndex++) {\n const slot = slotById.get(messages[nextIndex]!.id);\n if (slot !== undefined) {\n target = slot;\n break;\n }\n }\n const generated = coreToResponses([message], projection.customToolCallIds);\n if (generated.length > 0) insertions.set(target, [...(insertions.get(target) ?? []), ...generated]);\n }\n const out: ResponseInputItem[] = [];\n projection.layout.forEach((slot, index) => {\n out.push(...(insertions.get(index) ?? []));\n if (!slot.coreId) {\n out.push(slot.original);\n return;\n }\n const source = sourceById.get(slot.coreId);\n const next = nextById.get(slot.coreId);\n if (source && next) out.push(patchOriginalItem(slot.original, source, next));\n });\n out.push(...(insertions.get(projection.layout.length) ?? []));\n return out;\n}\n\nexport function coreToResponses(\n messages: CoreMessage[],\n customToolCallIds: Set<string> = new Set(),\n): ResponseInputItem[] {\n const out: ResponseInputItem[] = [];\n for (const message of messages) {\n const biliMessage = message as BiliMessage;\n const raw = biliMessage.rawResponsesItem as ResponseInputItem | undefined;\n if (message.role === \"system\") {\n out.push({ type: \"message\", role: \"developer\", content: message.text ?? \"\" });\n } else if (message.role === \"user\") {\n if (raw?.type === \"message\" && messageContent((raw as ResponseInputMessage).content) === (message.text ?? \"\")) out.push(raw);\n else out.push({ type: \"message\", role: \"user\", content: message.text ?? \"\" });\n } else if (message.role === \"assistant\") {\n if (message.contentType === \"text\") {\n out.push({ type: \"message\", role: \"assistant\", content: message.text ?? \"\" });\n } else if (message.contentType === \"tool-call\") {\n const callId = message.toolCallId ?? `call_${message.id}`;\n if (customToolCallIds.has(callId)) {\n out.push({ type: \"custom_tool_call\", call_id: callId, name: message.toolName ?? \"unknown\", input: message.text ?? \"\", status: \"completed\" } as ResponseInputItem);\n } else {\n out.push({ type: \"function_call\", call_id: callId, name: message.toolName ?? \"unknown\", arguments: message.text ?? \"\" });\n }\n } else if (message.contentType === \"reasoning\") {\n if (raw) out.push(raw);\n }\n } else if (message.role === \"tool\") {\n const callId = message.toolCallId ?? \"\";\n if (customToolCallIds.has(callId)) {\n out.push({ type: \"custom_tool_call_output\", call_id: callId, output: message.text ?? \"\" } as ResponseInputItem);\n } else {\n out.push({ type: \"function_call_output\", call_id: callId, output: message.text ?? \"\" });\n }\n }\n }\n return out;\n}\n\nexport function injectResponsesDeveloperMessage(\n input: string | ResponseInputItem[],\n content: string,\n): ResponseInputItem[] {\n const items: ResponseInputItem[] = typeof input === \"string\"\n ? [{ type: \"message\", role: \"user\", content: input }]\n : [...input];\n let index = 0;\n while (items[index]?.type === \"additional_tools\") index++;\n items.splice(index, 0, { type: \"message\", role: \"developer\", content });\n return items;\n}\n\nexport function conversationIdentityResponses(\n body: ResponsesRequestBody,\n headerValue?: string,\n): ConversationIdentity {\n if (headerValue?.trim()) return { value: headerValue.trim(), source: \"header\", clientProvided: true };\n if (typeof body.session_id === \"string\" && body.session_id.trim()) {\n return { value: body.session_id.trim(), source: \"body-session\", clientProvided: true };\n }\n const metadataSession = body.metadata?.session_id;\n if (typeof metadataSession === \"string\" && metadataSession.trim()) {\n return { value: metadataSession.trim(), source: \"metadata-session\", clientProvided: true };\n }\n if (typeof body.previous_response_id === \"string\" && body.previous_response_id.trim()) {\n return { value: body.previous_response_id.trim(), source: \"previous-response\", clientProvided: false };\n }\n return { value: hashId(JSON.stringify(body.input ?? [])), source: \"content-fingerprint\", clientProvided: false };\n}\n\nexport function conversationSignalResponses(body: ResponsesRequestBody, headerValue?: string): string {\n return conversationIdentityResponses(body, headerValue).value;\n}\n\n// Codex subagents (guardian approval reviewer, etc.) reuse the main\n// conversation's body.session_id, so identity alone collapses their requests\n// onto the main session's compression state — a compressed subagent request\n// loses the verbatim user authorization it must read back (#150). Subagent\n// requests carry their own `instructions` (the agent's role prompt), so the\n// FIRST instructions seen for an identity anchor the main namespace (it never\n// changes for the conversation, even if the main prompt drifts), and any other\n// instructions value maps to a separate `|sub:` namespace with its own empty\n// compression state. Subagent requests are self-contained replays, so the\n// fresh namespace is lossless.\nexport interface SubagentNamespaces {\n /** Resolve the compression-state namespace for a request: the identity\n * itself for the anchored (main) instructions, `identity|sub:<fp>` for\n * any other instructions value. First-seen instructions anchor. */\n namespaceFor(identityValue: string, instructions: unknown): string;\n}\n\n/** Host-owned subagent-namespace store.\n *\n * The anchor map is per-conversation mutable state, so it belongs to the\n * host — NOT to a library module global. Create one instance and keep it for\n * the process lifetime (or persist it alongside your session store if you\n * need namespaces to survive restarts: a fresh instance re-anchors on the\n * first request it sees, which after a restart may be a subagent request,\n * orphaning the main conversation's stored compression state). */\nexport function createSubagentNamespaces(): SubagentNamespaces {\n const anchors = new Map<string, string>();\n return {\n namespaceFor(identityValue: string, instructions: unknown): string {\n if (typeof instructions !== \"string\" || instructions.trim().length === 0) return identityValue;\n const fp = hashId(instructions);\n const anchor = anchors.get(identityValue);\n if (anchor === undefined) {\n anchors.set(identityValue, fp);\n return identityValue;\n }\n return anchor === fp ? identityValue : `${identityValue}|sub:${fp}`;\n },\n };\n}\n\n// Convenience singleton for single-process proxies that don't manage\n// per-session state themselves. Hosts needing isolation between\n// conversations, deterministic namespaces across restarts, or a bound on\n// anchor memory should create their own instance via\n// createSubagentNamespaces() and own its lifecycle.\nconst defaultNamespaces = createSubagentNamespaces();\n\nexport function subagentNamespace(identityValue: string, instructions: unknown): string {\n return defaultNamespaces.namespaceFor(identityValue, instructions);\n}\n","export const WIRE_FORMATS = [\"anthropic\", \"openai\", \"responses\"] as const;\nexport type WireFormat = (typeof WIRE_FORMATS)[number];\n\nexport function isWireFormat(value: unknown): value is WireFormat {\n return (\n typeof value === \"string\" &&\n (WIRE_FORMATS as readonly string[]).includes(value)\n );\n}\n\n/**\n * Classify a provider request body by the codec that can parse it.\n * Returns undefined when no codec handles the body — the caller must\n * pass such payloads through untransformed.\n */\nexport function detectWireFormat(payload: unknown): WireFormat | undefined {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const p = payload as Record<string, unknown>;\n if (Array.isArray(p.input)) return \"responses\";\n const messages = p.messages;\n if (!Array.isArray(messages)) return undefined;\n if (\"system\" in p || \"anthropic_version\" in p) return \"anthropic\";\n for (const m of messages as Array<Record<string, unknown>>) {\n if (m === null || typeof m !== \"object\") continue;\n const c = m.content;\n if (Array.isArray(c)) {\n for (const b of c as Array<Record<string, unknown>>) {\n if (b && typeof b === \"object\" && typeof b.type === \"string\") {\n if (\n b.type === \"tool_use\" ||\n b.type === \"tool_result\" ||\n b.type === \"thinking\"\n )\n return \"anthropic\";\n if (b.type === \"text\" && \"cache_control\" in b) return \"anthropic\";\n }\n }\n }\n if (Array.isArray(m.tool_calls)) return \"openai\";\n if (m.role === \"tool\" && typeof m.tool_call_id === \"string\")\n return \"openai\";\n if (m.role === \"system\" || m.role === \"developer\") return \"openai\";\n }\n // Both chat formats share role+messages; default to openai — the safer\n // guess for OpenAI-compatible endpoints (GLM, DeepSeek, vLLM).\n return \"openai\";\n}\n","import { anthropicToCore } from \"./anthropic.js\";\nimport { openaiToCore } from \"./openai.js\";\nimport { responsesToCore } from \"./responses.js\";\nimport type { BiliMessage } from \"./bili-message.js\";\n\n/**\n * Mirror constructors: rebuild the WIRE-SHAPE projection of a persisted\n * conversation (the mirror of \"what the host will put on the wire after a\n * restart\") for each protocol family, then fold it through the matching\n * `*ToCore` codec so the projection lands in the same identity/fingerprint\n * space as the live request.\n *\n * This used to live as three hand-rolled builders in the omp plugin\n * (wire-fold.ts) — protocol knowledge scattered across consumers is exactly\n * how the issue-#64 class of restart divergences happened (one place fixed,\n * another broke). The wire layouts now live here, next to the codecs that\n * define their identity space.\n *\n * CONTRACT: the caller maps its own persisted message shape into\n * {@link MirrorMessage} FIRST and normalizes text there (e.g. ref-tag\n * stripping is a host-app concern, not a wire concern). Builders only apply\n * host-encoder wire rules:\n * - thinking rides each wire the way the live encoder sends it\n * (openai: `reasoning_content` field — hosts that demote inline as\n * `<think>…</think>` land in the same identity space anyway because\n * `openaiToCore` normalizes the inline form; anthropic: signed\n * `{type:\"thinking\"}` blocks; responses: `{type:\"reasoning\"}` items);\n * - whitespace-only text survives on the openai wire, is dropped on the\n * anthropic/responses wires (host encoder behaviour);\n * - tool calls/results map to each wire's native shape.\n */\n\nexport type MirrorBlock =\n | { type: \"text\"; text: string }\n | { type: \"thinking\"; thinking: string; signature?: string }\n | { type: \"toolCall\"; id?: string; name?: string; arguments?: unknown };\n\nexport type MirrorMessage = {\n /** `meta` is anything the host sends as out-of-band/system-ish traffic. */\n role: \"user\" | \"assistant\" | \"toolResult\" | \"meta\";\n blocks?: MirrorBlock[];\n /** toolResult only. */\n toolCallId?: string;\n /** meta only: extracted text or summary. */\n text?: string;\n};\n\nfunction textBlocks(blocks: MirrorBlock[] | undefined): string[] {\n const out: string[] = [];\n for (const b of blocks ?? []) if (b.type === \"text\") out.push(b.text);\n return out;\n}\n\n/** Openai wire text: text blocks joined with \"\\n\" (whitespace-only kept). */\nfunction joinText(blocks: MirrorBlock[] | undefined): string {\n return textBlocks(blocks).join(\"\\n\");\n}\n\nfunction thinkingText(blocks: MirrorBlock[] | undefined): string {\n return blocks\n ?.filter((b) => b.type === \"thinking\" && b.thinking.trim().length > 0)\n .map((b) => (b as { thinking: string }).thinking)\n .join(\"\\n\") ?? \"\";\n}\n\n/** Openai/completions mirror: system message first, then the conversation\n * with thinking as the `reasoning_content` field (issue #103). */\nexport function mirrorOpenaiMessages(view: MirrorMessage[], systemText: string): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = [{ role: \"system\", content: systemText }];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) messages.push({ role: \"user\", content: text });\n } else if (message.role === \"assistant\") {\n const calls = (message.blocks ?? []).filter((b) => b.type === \"toolCall\") as Array<{ id?: string; name?: string; arguments?: unknown }>;\n const reasoning = thinkingText(message.blocks);\n const text = joinText(message.blocks);\n if (calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: text,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n tool_calls: calls.map((c) => ({\n id: c.id,\n type: \"function\",\n function: { name: c.name ?? \"\", arguments: JSON.stringify(c.arguments ?? {}) },\n })),\n });\n } else if (text || reasoning) {\n messages.push({ role: \"assistant\", content: text, ...(reasoning ? { reasoning_content: reasoning } : {}) });\n }\n } else if (message.role === \"toolResult\") {\n messages.push({ role: \"tool\", tool_call_id: message.toolCallId ?? \"\", content: joinText(message.blocks) });\n } else {\n const text = message.text ?? \"\";\n if (text) messages.push({ role: \"developer\", content: text });\n }\n }\n return messages;\n}\n\n/** Anthropic/messages mirror: no system message (the live request carries it\n * as the top-level `system` field, out of the fold space — issue #64), tool\n * results folded into user messages, thinking as signed `{type:\"thinking\"}`\n * blocks (issue #103). Unsigned thinking is demoted to text by the live\n * encoder; sending it as a thinking block diverges, so callers that persist\n * unsigned thinking should send it as a text block instead. */\nexport function mirrorAnthropicMessages(view: MirrorMessage[]): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = [];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) messages.push({ role: \"user\", content: [{ type: \"text\", text }] });\n } else if (message.role === \"assistant\") {\n const content: Array<Record<string, unknown>> = [];\n for (const b of message.blocks ?? []) {\n if (b.type === \"thinking\" && b.thinking.trim().length > 0) {\n content.push({\n type: \"thinking\",\n thinking: b.thinking,\n ...(typeof b.signature === \"string\" && b.signature ? { signature: b.signature } : {}),\n });\n } else if (b.type === \"text\" && b.text.trim().length > 0) {\n content.push({ type: \"text\", text: b.text });\n } else if (b.type === \"toolCall\") {\n let input: unknown = {};\n try {\n input = b.arguments && typeof b.arguments === \"object\" ? b.arguments : JSON.parse(JSON.stringify(b.arguments ?? {}));\n } catch {\n input = {};\n }\n content.push({ type: \"tool_use\", id: b.id, name: b.name ?? \"\", input });\n }\n }\n if (content.length > 0) messages.push({ role: \"assistant\", content });\n } else if (message.role === \"toolResult\") {\n messages.push({\n role: \"user\",\n content: [{ type: \"tool_result\", tool_use_id: message.toolCallId ?? \"\", content: joinText(message.blocks) }],\n });\n } else {\n const text = message.text ?? \"\";\n if (text) messages.push({ role: \"user\", content: [{ type: \"text\", text }] });\n }\n }\n return messages;\n}\n\n/** Responses mirror: the live /v1/responses request carries the system\n * prompt in the top-level `instructions` field and the conversation as an\n * `input` item array (issue #64, responses variant). Assistant blocks are\n * emitted in content order so the core sequence matches the live wire\n * (issue #103 parity). */\nexport function mirrorResponsesInput(view: MirrorMessage[]): Array<Record<string, unknown>> {\n const input: Array<Record<string, unknown>> = [];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) input.push({ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text }] });\n } else if (message.role === \"assistant\") {\n for (const b of message.blocks ?? []) {\n if (b.type === \"thinking\" && b.thinking.trim().length > 0) {\n input.push({ type: \"reasoning\", summary: [{ type: \"summary_text\", text: b.thinking }] });\n } else if (b.type === \"text\" && b.text.trim().length > 0) {\n input.push({ type: \"message\", role: \"assistant\", content: [{ type: \"output_text\", text: b.text }] });\n } else if (b.type === \"toolCall\") {\n let args = \"{}\";\n try {\n args = JSON.stringify(b.arguments ?? {});\n } catch {\n args = \"{}\";\n }\n input.push({ type: \"function_call\", call_id: b.id ?? \"\", name: b.name ?? \"\", arguments: args });\n }\n }\n } else if (message.role === \"toolResult\") {\n input.push({ type: \"function_call_output\", call_id: message.toolCallId ?? \"\", output: joinText(message.blocks) });\n } else {\n const text = message.text ?? \"\";\n if (text) input.push({ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text }] });\n }\n }\n return input;\n}\n\n/** Fold the openai mirror through `openaiToCore`. */\nexport function mirrorOpenaiToCore(view: MirrorMessage[], systemText: string): BiliMessage[] {\n const { msgs } = openaiToCore({\n model: \"prime-fold\",\n messages: mirrorOpenaiMessages(view, systemText) as Parameters<typeof openaiToCore>[0][\"messages\"],\n });\n return msgs;\n}\n\n/** Fold the anthropic mirror through `anthropicToCore`. */\nexport function mirrorAnthropicToCore(view: MirrorMessage[]): BiliMessage[] {\n const { msgs } = anthropicToCore({\n model: \"prime-fold\",\n messages: mirrorAnthropicMessages(view) as Parameters<typeof anthropicToCore>[0][\"messages\"],\n });\n return msgs;\n}\n\n/** Fold the responses mirror through `responsesToCore`. */\nexport function mirrorResponsesToCore(view: MirrorMessage[], systemText: string): BiliMessage[] {\n const { msgs } = responsesToCore({\n model: \"prime-fold\",\n instructions: systemText,\n input: mirrorResponsesInput(view) as Parameters<typeof responsesToCore>[0][\"input\"],\n });\n return msgs;\n}\n","/**\n * Compress-call detection and replay-guard on the wire/core stream\n * (Phase K2, moved from billion-context-omp `src/wire-fold.ts`).\n *\n * Two layers:\n * - Detection: `compressToolArgs` accepts the two call shapes that exist in\n * the wild (direct `compress`; legacy `write` to `xd://compress`, args\n * JSON-encoded one or two levels deep), `findCompressCalls` /\n * `findCompressCallsCore` turn a stream tool-call into validated ranges.\n * - Guard: when compression state is REPLAYED against a rebuilt stream\n * (restart, mirror divergence, host re-serialization), every recorded\n * range must prove it still covers the same content — fingerprint match\n * (first/last piece content key), position fallback for drifted\n * boundaries, remap for dangling m-refs.\n *\n * Pure functions over BiliMessage/CoreMessage — no host types, no I/O.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { CoreMessage } from \"../types.js\";\nimport type { BiliMessage } from \"./bili-message.js\";\n\n/** A compress call carried by a stream tool-call, normalized to validated\n * ranges. `id` is the tool-call id (replay dedup key). */\nexport interface StreamCompressCall {\n id: string;\n ranges: {\n startRef: string;\n endRef: string;\n summary: string;\n topic?: string;\n summaryMaxChars?: number;\n compressCallId: string;\n }[];\n}\n\n/** Extract a compress tool's arguments from a stream toolCall. Two call\n * shapes exist: (1) top-level — the tools are registered with\n * loadMode:\"essential\" so hosts do NOT mount them as xd:// devices; the\n * stream shows name:\"compress\" directly. (2) legacy xd:// — sessions\n * recorded before that change (or hosts forcing discoverable mounting)\n * invoked compress through the write tool with path \"xd://compress\" and\n * the tool args JSON-encoded in the content field. Both shapes must replay\n * from the stream. Returns normalized compress args (content array plus\n * optional topic / summaryMaxChars from wherever they live). */\nexport function compressToolArgs(call: { name: string; arguments?: unknown }): {\n content: unknown[];\n topic?: unknown;\n summaryMaxChars?: unknown;\n} | null {\n let args = call.arguments;\n if (typeof args === \"string\") {\n try { args = JSON.parse(args); } catch { return null; }\n }\n if (!args || typeof args !== \"object\" || Array.isArray(args)) return null;\n const a = args as Record<string, unknown>;\n if (call.name === \"compress\") {\n return Array.isArray(a.content) ? { content: a.content, topic: a.topic, summaryMaxChars: a.summaryMaxChars } : null;\n }\n if (call.name !== \"write\") return null;\n const path = typeof a.path === \"string\" ? a.path.split(\"?\")[0]!.replace(/\\/+$/, \"\") : \"\";\n if (path !== \"xd://compress\") return null;\n let inner: unknown = a.content;\n if (typeof inner === \"string\") {\n try { inner = JSON.parse(inner); } catch { return null; }\n }\n if (!inner || typeof inner !== \"object\") return null;\n if (Array.isArray(inner)) return { content: inner };\n const ia = inner as Record<string, unknown>;\n return Array.isArray(ia.content) ? { content: ia.content, topic: ia.topic, summaryMaxChars: ia.summaryMaxChars } : { content: [ia] };\n}\n\n/** toolCallId → toolName for every tool-call piece (protected-piece\n * detection: compress + configured tools are never folded). */\nexport function toolCallNames(msgs: BiliMessage[]): Map<string, string> {\n const names = new Map<string, string>();\n for (const m of msgs) {\n if (m.contentType === \"tool-call\" && m.toolCallId && m.toolName) names.set(m.toolCallId, m.toolName);\n }\n return names;\n}\n\n/** toolCallId → result text for every tool-result piece (compress result\n * rendering inside rebuilt payloads). */\nexport function toolResultTextsCore(msgs: BiliMessage[]): Map<string, string> {\n const results = new Map<string, string>();\n for (const m of msgs) {\n if (m.contentType !== \"tool-result\" || !m.toolCallId) continue;\n results.set(m.toolCallId, m.text ?? \"\");\n }\n return results;\n}\n\n/** Compress calls carried by a core tool-call piece. Same two shapes as the\n * AgentMessage stream (direct compress; legacy xd://compress via write),\n * with the arguments JSON-encoded in the piece's text. */\nexport function findCompressCallsCore(msg: BiliMessage): StreamCompressCall[] {\n if (msg.contentType !== \"tool-call\" || !msg.toolName) return [];\n const args = compressToolArgs({ name: msg.toolName, arguments: msg.text });\n if (!args) return [];\n const content = args.content;\n if (!Array.isArray(content)) return [];\n const ranges: StreamCompressCall[\"ranges\"] = [];\n const callTopic = typeof args.topic === \"string\" ? args.topic : undefined;\n for (const item of content) {\n const r = item as { startId?: unknown; endId?: unknown; summary?: unknown; topic?: unknown };\n if (typeof r.startId !== \"string\" || typeof r.endId !== \"string\" || typeof r.summary !== \"string\" || r.summary.length === 0) continue;\n ranges.push({\n startRef: r.startId,\n endRef: r.endId,\n summary: r.summary,\n topic: typeof r.topic === \"string\" ? r.topic : callTopic,\n summaryMaxChars: typeof args.summaryMaxChars === \"number\" ? args.summaryMaxChars : undefined,\n compressCallId: msg.toolCallId ?? \"\",\n });\n }\n return ranges.length > 0 ? [{ id: msg.toolCallId ?? \"\", ranges }] : [];\n}\n\n/** Content key of a core piece for span fingerprints (issue #91): role,\n * contentType, toolName and the FIRST 4096 chars of text. The 4096 cap is\n * deliberate: a host re-serialization that drifts only the tail (beyond\n * char 4096, e.g. truncation of a long tool output) keeps the key intact,\n * so the replay guard tells a benign tail drift from a genuine rewrite. */\nexport function corePieceKey(cm: CoreMessage): string {\n return `${cm.role}|${cm.contentType}|${cm.toolName ?? \"\"}|${(cm.text ?? \"\").slice(0, 4096)}`;\n}\n\n/** Span fingerprint in content-hash space: hash the content keys of the\n * exact first/last covered pieces. Boundary ids are pre-resolved (byRef /\n * block lookup) — unlike the pN-space spanFingerprint there is no position\n * parsing, ids are unique per piece. */\nexport function spanFingerprintCore(coreMessages: CoreMessage[], startId: string, endId: string): string {\n const find = (id: string): CoreMessage | undefined => coreMessages.find((cm) => cm.id === id);\n const first = find(startId);\n const last = find(endId);\n if (!first || !last) return \"\";\n return createHash(\"sha1\").update(`${corePieceKey(first)}\\u0000${corePieceKey(last)}`).digest(\"hex\").slice(0, 8);\n}\n\n/** Index-based span fingerprint (issue #91 replay fallback): hash the content\n * keys of the pieces AT the given stream positions. The stored fp still\n * decides keep/drop — the position is only a recovery hint for a drifted\n * boundary whose content-hash id no longer matches, so a benign tail drift\n * (first-4096 intact) is kept while a real rewrite mismatches. */\nexport function spanFingerprintCoreIdx(coreMessages: CoreMessage[], startIdx: number, endIdx: number): string {\n const first = coreMessages[startIdx];\n const last = coreMessages[endIdx];\n if (!first || !last) return \"\";\n return createHash(\"sha1\").update(`${corePieceKey(first)}\\u0000${corePieceKey(last)}`).digest(\"hex\").slice(0, 8);\n}\n\n/** Structural subset the boundary resolvers need from a compression block\n * (kernel CompressionBlock satisfies this; keeps the guard usable from\n * downstreams that carry lighter block records). */\nexport interface BlockLike {\n blockId: string;\n effectiveMessageIds: string[];\n}\n\n/** Resolve a range boundary to the exact id of the piece it names, in\n * content-hash space. Message refs go through byRef; block refs resolve to\n * the earliest (min) or latest (max) covered piece by STREAM ORDER\n * (index in coreMessages — the hash ids carry no position). */\nexport function boundaryRawCore(\n ref: string,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n coreMessages: CoreMessage[],\n pick: \"min\" | \"max\",\n): string {\n const raw = byRef[ref];\n if (raw) return raw;\n const m = /^b(\\d+)$/i.exec(ref.trim());\n if (!m) return \"\";\n const block = blocks.find((b) => b.blockId.toLowerCase() === `b${m[1]}`);\n if (!block) return \"\";\n const idx = (id: string): number => coreMessages.findIndex((cm) => cm.id === (byRef[id] ?? id));\n let best = -1;\n for (const id of block.effectiveMessageIds) {\n const i = idx(id);\n if (i < 0) continue;\n if (best < 0 || (pick === \"min\" ? i < best : i > best)) best = i;\n }\n return best < 0 ? \"\" : (coreMessages[best]?.id ?? \"\");\n}\n\n/** Resolve a range boundary to its STREAM INDEX in content-hash space. byRef /\n * block lookup first (the exact piece it names, by array order); on a missed\n * id (a drift re-hashed the piece so its carried ref dangles) fall back to\n * the compress-time recorded index — the position hint, issue #91. -1 =\n * unresolvable. */\nexport function boundaryIndexCore(\n ref: string,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n coreMessages: CoreMessage[],\n pick: \"min\" | \"max\",\n fallbackIdx = -1,\n): number {\n const id = boundaryRawCore(ref, byRef, blocks, coreMessages, pick);\n if (id) {\n const i = coreMessages.findIndex((cm) => cm.id === id);\n if (i >= 0) return i;\n }\n return fallbackIdx >= 0 && fallbackIdx < coreMessages.length ? fallbackIdx : -1;\n}\n\n/** Structured replay-guard verdict (issue #91, rework): the position\n * fallback recovers the STREAM INDEX of a drifted boundary, but the kernel\n * resolves ranges by REF — so when a recorded m-ref dangles, the replay\n * must re-apply that boundary under the CURRENT ref of the recovered piece.\n * `remap` carries exactly that (only dangling m-refs are remapped; block\n * refs resolve themselves inside the kernel and are never touched). */\nexport type ReplayRangeVerdict = {\n /** Stale: the range must be dropped (master semantics, unchanged). */\n reject?: string;\n /** Dangling m-refs recovered by position, remapped to current refs. */\n remap?: { startRef?: string; endRef?: string };\n /** True when the result text carried a [pos=] pair for this range —\n * with `reject` set it marks a RECOVERY FAILURE (always logged). */\n hint?: boolean;\n /** Diagnostics — always logged when a recovery happens. */\n recovered?: { pos: string; startIdx: number; endIdx: number };\n};\n\n/** Current m-ref of the piece at stream index idx (inverse byRef scan).\n * \"\" when the piece has no ref (protected) — the replay must fail closed\n * rather than hand the kernel a ref it does not know. Replay-time only\n * (replayed compress calls), so the O(refs) scan stays off the hot path. */\nexport function refOfPieceCore(coreMessages: BiliMessage[], idx: number, byRef: Record<string, string>): string {\n const id = coreMessages[idx]?.id;\n if (!id) return \"\";\n for (const [ref, mapped] of Object.entries(byRef)) if (mapped === id) return ref;\n return \"\";\n}\n\nexport function staleRangeCore(\n r: { startRef: string; endRef: string },\n rangeIndex: number,\n resultText: string,\n coreMessages: BiliMessage[],\n callIndex: number,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): ReplayRangeVerdict {\n // Compress-time boundary positions (issue #91): the stream index each\n // boundary sat at when the call was recorded. A drift that re-hashes a\n // boundary piece dangles its carried ref — the position recovers it, and\n // the fingerprint below still decides keep/drop.\n const pm = resultText.match(/\\[pos=([0-9,-]+)\\]/);\n const pair = pm ? pm[1]!.split(\",\")[rangeIndex] ?? \"-\" : \"-\";\n const hinted = pair !== \"-\";\n const [ps, pe] = pair === \"-\" ? [\"\", \"\"] : pair.split(\"-\");\n const fbStart = ps && ps !== \"\" ? Number.parseInt(ps, 10) : -1;\n const fbEnd = pe && pe !== \"\" ? Number.parseInt(pe, 10) : -1;\n\n // Raw resolution (id → stream index) separately from the fallback, so a\n // dangling m-ref recovered by position can be flagged for remapping.\n const startRaw = boundaryRawCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const endRaw = boundaryRawCore(r.endRef, byRef, blocks, coreMessages, \"max\");\n const rawStartIdx = startRaw ? coreMessages.findIndex((cm) => cm.id === startRaw) : -1;\n const rawEndIdx = endRaw ? coreMessages.findIndex((cm) => cm.id === endRaw) : -1;\n const startIdx = rawStartIdx >= 0 ? rawStartIdx : fbStart >= 0 && fbStart < coreMessages.length ? fbStart : -1;\n const endIdx = rawEndIdx >= 0 ? rawEndIdx : fbEnd >= 0 && fbEnd < coreMessages.length ? fbEnd : -1;\n if (startIdx < 0 || endIdx < 0) {\n if (!/^b\\d+$/i.test(r.startRef.trim()) && !/^b\\d+$/i.test(r.endRef.trim()))\n return { reject: `unresolved ${r.startRef}..${r.endRef} -> ${startIdx}..${endIdx}`, ...(hinted ? { hint: true } : {}) };\n return {}; // block ref(s): the kernel resolves them itself (master)\n }\n // The end piece must precede the call that issued it — a rewrite moved\n // the call and the fingerprint check below is meaningless either way.\n if (endIdx > callIndex) return { reject: `end idx ${endIdx} > callIndex ${callIndex}`, ...(hinted ? { hint: true } : {}) };\n const m = resultText.match(/\\[fp=([0-9a-f,-]+)\\]/);\n if (m) {\n const want = m[1]!.split(\",\")[rangeIndex];\n if (want !== undefined && want !== \"-\") {\n const got = spanFingerprintCoreIdx(coreMessages, startIdx, endIdx);\n if (want !== got) return { reject: `fp ${r.startRef}..${r.endRef} want ${want} got ${got} @${startIdx}..${endIdx}`, ...(hinted ? { hint: true } : {}) };\n }\n }\n // Remap only the boundaries that actually dangled (m-refs whose recorded id\n // no longer resolves); resolved boundaries keep their recorded ref, block\n // refs are the kernel's to resolve.\n const remap: { startRef?: string; endRef?: string } = {};\n if (/^m\\d+$/i.test(r.startRef.trim()) && rawStartIdx < 0) {\n const ref = refOfPieceCore(coreMessages, startIdx, byRef);\n if (!ref) return { reject: `recovered ${r.startRef} @${startIdx} has no ref (protected piece)`, ...(hinted ? { hint: true } : {}) };\n remap.startRef = ref;\n }\n if (/^m\\d+$/i.test(r.endRef.trim()) && rawEndIdx < 0) {\n const ref = refOfPieceCore(coreMessages, endIdx, byRef);\n if (!ref) return { reject: `recovered ${r.endRef} @${endIdx} has no ref (protected piece)`, ...(hinted ? { hint: true } : {}) };\n remap.endRef = ref;\n }\n if (!remap.startRef && !remap.endRef) return {};\n return { remap, recovered: { pos: pair, startIdx, endIdx } };\n}\n\n/** One fingerprint per range for the replay guard, content-hash space\n * (mirrors rangeFingerprints for the pN space). */\nexport function rangeFingerprintsCore(\n ranges: Array<{ startRef: string; endRef: string }>,\n coreMessages: BiliMessage[],\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): string[] {\n return ranges.map((r) => {\n const start = boundaryRawCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const end = start ? boundaryRawCore(r.endRef, byRef, blocks, coreMessages, \"max\") : \"\";\n if (start && end) {\n const fp = spanFingerprintCore(coreMessages, start, end);\n if (fp.length > 0) return fp;\n }\n return \"-\";\n });\n}\n\n/** One boundary-index pair per range for the replay fallback (issue #91),\n * aligned with rangeFingerprintsCore: the stream index of each range's exact\n * first/last covered piece at record time (\"-1\" pair when a boundary can't\n * be positioned), so the replay can recover a drifted boundary by position. */\nexport function rangePositionsCore(\n ranges: Array<{ startRef: string; endRef: string }>,\n coreMessages: CoreMessage[],\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): string[] {\n return ranges.map((r) => {\n const s = boundaryIndexCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const e = s >= 0 ? boundaryIndexCore(r.endRef, byRef, blocks, coreMessages, \"max\") : -1;\n return s >= 0 && e >= 0 ? `${s}-${e}` : \"-\";\n });\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAKpB,SAAS,OAAO,GAAmB;AACtC,SAAO,WAAW,QAAQ,EAAE,OAAO,GAAG,MAAM,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AAC3E;;;ACwBO,SAAS,gBACZ,MACA,aACA,MACA,UAGI,CAAC,GACC;AACN,QAAM,OAAO,GAAG,IAAI,IAAI,WAAW,IAAI,QAAQ,cAAc,EAAE,IAAI,QAAQ,YAAY,EAAE,IAAI,IAAI;AACjG,SAAO,OAA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