From 57ae7ab0da847a47c7978b144d3586935056422e Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 13 Nov 2026 18:22:01 +0800 Subject: [PATCH 1/2] msgid: wire dsh full-resend turns onto the biliMsgIds envelope (#6525) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Carrier ① (the envelope body field) had zero client wiring: the server consumes biliMsgIds on both wires (prepare-openai/anthropic, gated on pluginMode + the pluginLaneServerHistory rollout), but no client ever stamped it. dsh's stamping lived only on the anthropic-wire incremental lane (#4491), so every openai-wire full-resend turn — dsh's main path — arrived id-less and the store fell back to content-derived digests, which in turn leaves the fork msgid identity track (#6293) with nothing to match. maybeStampEnvelopeMsgIds now stamps full-resend model bodies (both wires) after the incremental lane had its chance. Resolution never re-implements the host's wire transforms: the pi-ai lockstep walkers (laneMsgIdsForWire / laneMsgIdsForOpenAiWire — the SAME functions the pi/omp lanes pin with) prove wire-element ⇔ host-message pairing by order-preserving fingerprints, bail all-or-nothing; the kernel's own converters then prove core-alignment via the #3642 wireIndex back-pointer (every non-leading wire element must own exactly one core — parallel tool calls / reasoning+text / text+image parts split one host message into N cores, and N cores cannot share one host id). System-role entries are excluded (they ride the hoisted/folded leading system, never 1:1 to a non-leading wire element). Any bail leaves the body byte-identical → content-derived ids, exactly today's behavior; with the rollout off the server strips the field, so default installs are untouched. --- docs/msgid-infrastructure.md | 2 +- src/agent/dsh-native.ts | 120 ++++++++++++++++++++++++++- tests/issue6525-dsh-envelope.test.ts | 112 +++++++++++++++++++++++++ 3 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 tests/issue6525-dsh-envelope.test.ts diff --git a/docs/msgid-infrastructure.md b/docs/msgid-infrastructure.md index deb4f2fbf7..934a8c4c41 100644 --- a/docs/msgid-infrastructure.md +++ b/docs/msgid-infrastructure.md @@ -21,7 +21,7 @@ Discipline: collectors only "obtain and pre-screen"; they hold NO identity-adjud Four carriers, **ALL stripped before forwarding to the model upstream** — the model wire still carries no message-level ids (#2821 doctrine): -1. **Envelope field** `biliMsgIds`: parallel array on full-resend model bodies, length-locked to messages, same lifecycle (stripped at ingress, src/server/prepare-anthropic.ts et al.). +1. **Envelope field** `biliMsgIds`: parallel array on full-resend model bodies, length-locked to the post-hoist core count, same lifecycle (stripped at ingress, src/server/prepare-anthropic.ts et al.). Wired for dsh full-resend turns (src/agent/dsh-native.ts `resolveEnvelopeMsgIds`, openai + anthropic wire, #6525): pairing is PROVEN by the pi-ai lockstep walkers (src/agent/pi-msgids.ts, same functions the pi/omp lanes pin with) and core-alignment by the kernel's own #3642 `wireIndex` back-pointer (every non-leading wire element must own exactly one core); any unprovable shape bails the whole request to content-derived ids — never guessed, never partial. 2. **Incremental turn payload** `msgIds`: envelope on `POST /__bili/plugin/turn` (src/agent/incremental-client.ts); server re-stamps `biliMsgIds` (src/incremental-lane.ts). 3. **Watermark headers** `x-bili-pf-tail-ids` (v2-v4, #5403/#5418): window segment only = last anchor element + all elements added since K, percent-encoded per segment, comma-separated (commas inside ids travel as `%2C`, separators stay literal); sibling `x-bili-pf-count` count stamp. pf-* headers are **protocol headers, not hop headers**: stripped before upstream via `UPSTREAM_HOP_HEADERS`. 4. **Ledger-seq sibling** `biliLedgerSeqs` / `ledgerSeq` stamps (#4316 L3 PR2/3): 1-based positive-int parallel arrays, validated by `validateMsgSeqs`, same strict-validate-then-degrade lifecycle. diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index daecb744c2..b64fec0ae8 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -69,6 +69,8 @@ import { runOutsideFetchChain } from "./fetch-chain/index.js"; import { installNativeWebSocketIntercept } from "./native-ws-intercept.js"; import { asciiHeaderValue, fetchManifest, fetchProxyVersion, fetchStatus, fetchStatusLatest, forwardTool, reportAttributionHealth, reportRuntimeInfo, waitForProxyVersion, type ManifestTool } from "./shared.js"; import { createForkAdopter, sideShapedBody } from "./fork-adopt.js"; +import { anthropicToCore, detectWireFormat, openaiToCore } from "acp-kernel/wire"; +import { laneMsgIdsForOpenAiWire, laneMsgIdsForWire } from "./pi-msgids.js"; import { clearIncrementalProbe, createPrepareDirectSend, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, rememberOriginalBody, sweepStale, wireMessagesLookAnthropic, type IncrementalWireMessage } from "./incremental-client.js"; import { declareDshCompactionActive, detectCompactionOverlayGap, dshCompactionGateTelemetry } from "./dsh-compaction-disable.js"; import { maskUrlForDiagnostics } from "../log-mask.js"; @@ -1188,6 +1190,11 @@ type GateAttribution = interface LlmDispatchScope { sid: string; msgIds: string[] | undefined; + // #6525: the raw host message list (pi-ai shape: {id, role, content, + // toolCallId}) — the full-resend envelope stamps biliMsgIds from these + // by lockstep fingerprint walk, not from the id array alone (pairing + // must be PROVEN, never assumed positional — pi-msgids.ts discipline). + messages: unknown; } const dispatchScope = new AsyncLocalStorage(); @@ -1246,6 +1253,74 @@ function runLlmDispatch(scope: LlmDispatchScope, operation: () => R): R { return runOutsideFetchChain(() => dispatchScope.run(scope, operation)); } +/** #6525: resolve the envelope (carrier ①) id array for a full-resend model + * body — CORE-aligned (== the post-hoist core count the server validates + * against, prepare-openai/anthropic) or undefined (degrade to + * content-derived ids, never guess). Pure — unit-testable without a plugin + * ctx. Never re-implements the host's wire transforms: the pi-ai lockstep + * walkers (the SAME functions the pi/omp lanes pin with) prove + * wire-element ⇔ host-message pairing by order-preserving fingerprints and + * bail all-or-nothing; the kernel's own converters then prove the pin is + * core-alignable via the #3642 wireIndex back-pointer — every non-leading + * wire element must own exactly ONE core (parallel tool calls / + * reasoning+text / text+image parts split one host message into N cores, + * and N cores cannot share one host id: validateMsgIds rejects duplicates). + */ +function resolveEnvelopeMsgIds(parsed: Record, hostMessages: unknown): string[] | undefined { + const fmt = detectWireFormat(parsed); + if (fmt !== "openai" && fmt !== "anthropic") return undefined; // google/responses stay content-derived (#6525 v1) + const wire = parsed.messages; + if (!Array.isArray(wire)) return undefined; + if (!Array.isArray(hostMessages) || hostMessages.length === 0) return undefined; + // pi-shaped entries: dsh's flat host messages share the pi-ai message + // shape ({role, content blocks} + toolCallId on results) and entry.id IS + // the host's stable message id (#4491) — the walkers consume them through + // the same makeEntryTake contract as pi's branch entries. System-role + // entries are EXCLUDED: they ride the hoisted/folded leading system (the + // bili-ps-N slots on the openai wire; the separate `system` field on + // anthropic), which never aligns 1:1 to a non-leading wire element. + const entries: Array> = []; + for (const m of hostMessages) { + if (m === null || typeof m !== "object") return; + const mm = m as Record; + if (mm.role === "system" || mm.role === "developer") continue; + entries.push({ type: "message", id: mm.id, message: { role: mm.role, content: mm.content, toolCallId: mm.toolCallId } }); + } + const wireAligned = fmt === "anthropic" ? laneMsgIdsForWire(wire, entries) : laneMsgIdsForOpenAiWire(wire, entries); + if (wireAligned === undefined) return undefined; // pairing not provable — degrade + // OpenAI wire only: the leading system/developer run becomes synthetic + // bili-ps-N slots (== the kernel's hoisted prefix) — drop them; the + // envelope must be CORE-aligned (server validates against the post-hoist + // core count). Anthropic has no hoist (system is a separate field), so + // lead stays 0 there. + let lead = 0; + while (lead < wireAligned.length && (wireAligned[lead] as string).startsWith("bili-ps-")) lead += 1; + for (let i = lead; i < wireAligned.length; i++) { + if ((wireAligned[i] as string).startsWith("bili-ps-")) return undefined; // placeholders legal only as the hoisted leading run + } + const coreAligned = wireAligned.slice(lead); + if (coreAligned.length === 0) return undefined; + const flat = fmt === "anthropic" ? anthropicToCore(parsed as Parameters[0]) : openaiToCore(parsed as Parameters[0]); + const perEl = new Map(); + for (const c of flat.msgs) { + const w = c.wireIndex; + if (w === undefined) continue; + perEl.set(w, (perEl.get(w) ?? 0) + 1); + } + for (let i = lead; i < wire.length; i++) { + if ((perEl.get(i) ?? 0) !== 1) return undefined; // element split into N cores (or vanished) — no 1:1 host pin exists + } + // Client-side reject-class parity with hostMsgIdsOf (#4491): duplicates + // would be rejected server-side anyway (validateMsgIds) — refusing here + // avoids the one-time "pin rejected" warn path for provably-bad stamps. + if (new Set(coreAligned).size !== coreAligned.length) return undefined; + return coreAligned; +} + +/** Test-only accessor (#6525 review): pins the resolver against the kernel. + * The bail matrix lives in tests/issue6525-dsh-envelope.test.ts. */ +export const _envelopeMsgIdsForTest = resolveEnvelopeMsgIds; + /** Test-only accessors (#5826 review): pins tests/msgid-rule-parity.test.ts * drives these collectors directly against the shared reject-class set. */ export const _hostMsgIdsOfForTest = hostMsgIdsOf; @@ -2047,7 +2122,7 @@ export async function apply(ctx: PluginContext): Promise { // #4491: capture the host message ids riding the same options // — undefined (all-or-nothing) when any message lacks a usable // id, so sidecar shapes degrade to id-less turns. - const scope: LlmDispatchScope = { sid, msgIds: hostMsgIdsOf(options?.messages) }; + const scope: LlmDispatchScope = { sid, msgIds: hostMsgIdsOf(options?.messages), messages: options?.messages }; // #5403/#5418 v3: feed the per-slot id sequence into the // watermark channel (the fetch chokepoint emits count + // tail-ids; core = pf-channel.ts) — "?" slots ride id-less @@ -2611,6 +2686,7 @@ export async function apply(ctx: PluginContext): Promise { await maybeRecallBeforeSend(ctx, url, init); await maybeForkAdoptBeforeSend(ctx, init); await maybeIncrementalNative(url, init); + await maybeStampEnvelopeMsgIds(ctx, url, init); emitHostParseDiagnostic(init); }; // #3304: the dsh swap stamps the turn id atomically with the body, so the @@ -2736,6 +2812,48 @@ export async function apply(ctx: PluginContext): Promise { } }; + // #6525 envelope wiring (carrier ①'s last mile): full-resend requests + // stamp the model body's own parallel id array — `biliMsgIds`, the + // SERVER-side field name, duplicated here for the same reason + // hostMsgIdsOf duplicates the reject class (host code must not import + // server modules; keep in sync with src/msgid-pin.ts MSG_IDS_BODY_FIELD). + // A pinned prefix then exists on EVERY turn, not only on the lane's + // anthropic-wire turns. Resolution never re-implements the host's wire + // transforms: the pi-ai lockstep walkers (laneMsgIdsForWire / + // laneMsgIdsForOpenAiWire, the SAME functions the pi/omp lanes pin with) + // prove wire-element ⇔ host-message pairing by order-preserving + // fingerprints and bail all-or-nothing; the kernel's own converters then + // prove the pin is core-alignable — every non-leading wire element must + // own exactly ONE core via the #3642 wireIndex back-pointer (parallel + // tool calls / reasoning+text / text+image parts split one host message + // into N cores, and N cores cannot share one host id: validateMsgIds + // rejects duplicates). Any bail leaves the body byte-identical → + // content-derived ids, exactly today's behavior. maybeIncrementalNative + // runs FIRST and swaps the body — the delta payload pins msgIds itself, + // so once it fired the envelope must not touch the body. The server + // strips the field before forwarding and gates the pin on pluginMode + + // the pluginLaneServerHistory rollout (prepare-openai/anthropic). + const ENVELOPE_MSG_IDS_FIELD = "biliMsgIds"; // == MSG_IDS_BODY_FIELD (src/msgid-pin.ts) + let envelopeStampedFor: string | undefined; // one log line per session + async function maybeStampEnvelopeMsgIds(ctx: PluginContext, _url: string, init: RequestInit | undefined): Promise { + if (!register.toolsReady || init === undefined) return; + const attr = attributionOf(ctx); + if (attr.state !== "ok") return; // non-plugin traffic carries no msgid channel + const body = init.body; + if (typeof body !== "string" || body.length === 0) return; // stream/Request bodies ride content-derived + const parsed = (await parsedBodyOnce(init)) as Record | undefined; + if (parsed === undefined) return; + const coreAligned = resolveEnvelopeMsgIds(parsed, dispatchScope.getStore()?.messages); + if (coreAligned === undefined) return; + const fmt = detectWireFormat(parsed) as string; // log detail only — the resolver already gated the wire + const stamped = { ...parsed, [ENVELOPE_MSG_IDS_FIELD]: coreAligned }; + init.body = JSON.stringify(stamped); + if (envelopeStampedFor !== attr.sid) { + envelopeStampedFor = attr.sid; + persistClientEvent(`bili-native-dsh: msgid envelope stamped on full-resend for ${attr.sid} (${coreAligned.length} ids, ${fmt} wire) — pinned prefix live from turn one (#6525)`); + } + } + // #1268: arm the interceptor's toolsReady gate — the first model request // holds until this resolves, so it stamps into plugin mode instead of // losing the boot race and silently riding wire mode. Resolves when the diff --git a/tests/issue6525-dsh-envelope.test.ts b/tests/issue6525-dsh-envelope.test.ts new file mode 100644 index 0000000000..5b85682265 --- /dev/null +++ b/tests/issue6525-dsh-envelope.test.ts @@ -0,0 +1,112 @@ +/** + * #6525: dsh full-resend envelope (carrier ①) — resolver tests. + * + * The envelope stamps the model body's own parallel id array + * (`biliMsgIds`, core-aligned) so host-pinned prefixes exist on EVERY + * full-resend turn, not only the anthropic-wire incremental lane. + * Resolution never re-implements the host's wire transforms: the pi-ai + * lockstep walkers prove wire-element ⇔ host-message pairing, and the + * kernel's own converters prove core-alignment via the #3642 wireIndex + * back-pointer. These tests pin the resulting accept/bail matrix against + * REAL kernel + REAL walker behavior (no re-implementations). + */ +import assert from "node:assert"; +import { test } from "node:test"; +import { _envelopeMsgIdsForTest as resolve } from "../src/agent/dsh-native.js"; + +// dsh host messages = pi-ai Message shape (id added by the host): +// user: string | (text|image)[]; assistant: (text|thinking|toolCall)[]; +// toolResult: toolCallId + (text|image)[]; system: hoisted/folded prefix. +const sys = (content: string) => ({ id: "s0", role: "system", content, timestamp: 1 }); +const user = (id: string, content: string | unknown[]) => ({ id, role: "user", content, timestamp: 1 }); +const asst = (id: string, content: unknown[]) => ({ id, role: "assistant", content, api: "openai-completions", provider: "fake", model: "fake-model", usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "stop", timestamp: 1 }); +const toolResult = (id: string, toolCallId: string, text: string) => ({ id, role: "toolResult", toolCallId, toolName: "bash", content: [{ type: "text", text }], isError: false, timestamp: 1 }); +const text = (t: string) => ({ type: "text", text: t }); +const oai = (messages: unknown[]) => ({ model: "fake-model", messages }); + +test("openai: leading system + plain conversation → core-aligned ids, lead dropped", () => { + const wire = oai([ + { role: "system", content: "S" }, + { role: "user", content: "hello" }, + { role: "assistant", content: "hi" }, + { role: "tool", tool_call_id: "c1", content: "r1" }, + ]); + const host = [sys("S"), user("u1", "hello"), asst("a1", [text("hi")]), toolResult("t1", "c1", "r1")]; + assert.deepStrictEqual(resolve(wire, host), ["u1", "a1", "t1"]); +}); + +test("openai: no leading system → every id", () => { + const wire = oai([{ role: "user", content: "a" }, { role: "user", content: "b" }]); + const host = [user("u1", "a"), user("u2", "b")]; + assert.deepStrictEqual(resolve(wire, host), ["u1", "u2"]); +}); + +test("openai: user [text, image_url] → bail (kernel splits one element into N cores)", () => { + const wire = oai([{ role: "user", content: [{ type: "text", text: "see" }, { type: "image_url", image_url: { url: "x" } }] }]); + const host = [user("u1", [text("see"), { type: "image", data: "x", mimeType: "image/png" }])]; + assert.strictEqual(resolve(wire, host), undefined); +}); + +test("openai: assistant with parallel tool_calls → bail (N tool_call cores, one host id)", () => { + const wire = oai([{ role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "f", arguments: "{}" } }, { id: "c2", type: "function", function: { name: "g", arguments: "{}" } }] }]); + const host = [asst("a1", [{ type: "toolCall", id: "c1", name: "f", arguments: {} }, { type: "toolCall", id: "c2", name: "g", arguments: {} }])]; + assert.strictEqual(resolve(wire, host), undefined); +}); + +test("openai: reasoning_content anywhere → bail (walker refuse, conversion not statically provable)", () => { + const wire = oai([{ role: "user", content: "a" }, { role: "assistant", content: "hi", reasoning_content: "R" }]); + const host = [user("u1", "a"), asst("a1", [text("hi")])]; + assert.strictEqual(resolve(wire, host), undefined); +}); + +test("openai: non-leading system element → bail (ambiguous placement)", () => { + const wire = oai([{ role: "user", content: "a" }, { role: "system", content: "mid" }, { role: "user", content: "b" }]); + const host = [user("u1", "a"), sys("mid"), user("u2", "b")]; + assert.strictEqual(resolve(wire, host), undefined); +}); + +test("openai: host list shorter than the wire (dropped message) → bail (leftover proof fails)", () => { + const wire = oai([{ role: "user", content: "a" }, { role: "user", content: "b" }]); + const host = [user("u1", "a")]; + assert.strictEqual(resolve(wire, host), undefined); +}); + +test("openai: host entry with a different byte stream → bail (fingerprint mismatch, never positional)", () => { + const wire = oai([{ role: "user", content: "a" }, { role: "user", content: "b" }]); + const host = [user("u1", "a"), user("u2", "c")]; + assert.strictEqual(resolve(wire, host), undefined); +}); + +test("duplicate host ids → bail (reject-class parity with hostMsgIdsOf / validateMsgIds)", () => { + const wire = oai([{ role: "user", content: "a" }, { role: "user", content: "b" }]); + const host = [user("dup", "a"), user("dup", "b")]; + assert.strictEqual(resolve(wire, host), undefined); +}); + +test("openai: host entry missing an id → bail (all-or-nothing)", () => { + const wire = oai([{ role: "user", content: "a" }, { role: "user", content: "b" }]); + const host = [user("u1", "a"), { role: "user", content: "b", timestamp: 1 }]; + assert.strictEqual(resolve(wire, host), undefined); +}); + +test("anthropic: system field separate, full conversation → 1:1 ids", () => { + const wire = { model: "fake-model", max_tokens: 100, system: "S", messages: [ + { role: "user", content: "hi" }, + { role: "assistant", content: [{ type: "text", text: "yo" }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "c1", content: "r1" }] }, + ] }; + const host = [sys("S"), user("u1", "hi"), asst("a1", [text("yo")]), toolResult("t1", "c1", "r1")]; + assert.deepStrictEqual(resolve(wire, host), ["u1", "a1", "t1"]); +}); + +test("non-openai/anthropic payload → undefined (google/responses stay content-derived, #6525 v1)", () => { + const wire = { model: "fake-model", input: [{ role: "user", content: "hi" }] }; + assert.strictEqual(resolve(wire, [user("u1", "hi")]), undefined); +}); + +test("degenerate inputs → undefined (never throws)", () => { + assert.strictEqual(resolve({ model: "m" }, []), undefined); + assert.strictEqual(resolve({ model: "m", messages: [] }, [user("u1", "a")]), undefined); + assert.strictEqual(resolve({ model: "m", messages: [{ role: "user", content: "a" }] }, null), undefined); + assert.strictEqual(resolve({ model: "m", messages: [{ role: "user", content: "a" }] }, [null]), undefined); +}); From ba30a95cd90beaccf58ba06198b147439082ae47 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 13 Nov 2026 22:05:39 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20dsh=20envelope=20bailed=20every=20to?= =?UTF-8?q?ol=20turn=20=E2=80=94=20host=20ids=20churned=20to=20digests=20(?= =?UTF-8?q?#6525=20B7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dsh's flat host messages differ from the pi-ai shape the shared walker's host-side fingerprint assumes in two places (role tool vs toolResult, block tool-call vs toolCall), so every tool-bearing turn bailed the all-or-nothing envelope and the turn-1 host-pinned rows churned back to content digests on the next full-resend. Normalize dsh's shape for fingerprinting only, in the dsh resolver: the envelope ids still come from mm.id and the wire-side pairing is untouched, so no mis-pin is possible. Found via a real-dsh e2e dump (after turn 1: live rows 11/11 content digests). Now: live rows 11/11 host-pinned UUIDs. Two regression tests pin the accept (a dsh tool turn core-aligns and stamps) and the retained bail (parallel tool_calls still refuse, one host id cannot cover N cores). --- src/agent/dsh-native.ts | 27 +++++++++++++++++++++++- tests/issue6525-dsh-envelope.test.ts | 31 ++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index b64fec0ae8..9c8b6f1ef9 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -1253,6 +1253,31 @@ function runLlmDispatch(scope: LlmDispatchScope, operation: () => R): R { return runOutsideFetchChain(() => dispatchScope.run(scope, operation)); } +/** dsh's flat host message shape differs from the pi-ai form the shared + * walkers' host-side fingerprint (entryFingerprint / assistantParts in + * pi-msgids.ts) understands in exactly two places, and the mismatch made + * every tool-bearing turn bail the all-or-nothing envelope — the host ids + * then churned back to content digests on the next full-resend (#6525 B7): + * 1. assistant tool-call blocks are `type:"tool-call"` (hyphen); the + * fingerprint only recognizes `type:"toolCall"` (camel) and reads `.id`. + * 2. tool results carry role `"tool"`; the fingerprint takes the `toolres` + * branch only for role `"toolResult"` (reading `.toolCallId`), so an + * un-normalized `tool` fell into the text branch and mismatched. + * Normalize ONLY for fingerprinting: the envelope ids come from `mm.id` and + * the wire-side pairing is unchanged, so this cannot cause a mis-pin. */ +function dshFpRole(role: unknown): unknown { + return role === "tool" ? "toolResult" : role; +} +function dshFpContent(content: unknown): unknown { + if (!Array.isArray(content)) return content; + return content.map((b) => { + if (b === null || typeof b !== "object") return b; + const o = b as Record; + if (o.type === "tool-call") return { type: "toolCall", id: o.id, name: o.name }; + return b; + }); +} + /** #6525: resolve the envelope (carrier ①) id array for a full-resend model * body — CORE-aligned (== the post-hoist core count the server validates * against, prepare-openai/anthropic) or undefined (degrade to @@ -1284,7 +1309,7 @@ function resolveEnvelopeMsgIds(parsed: Record, hostMessages: un if (m === null || typeof m !== "object") return; const mm = m as Record; if (mm.role === "system" || mm.role === "developer") continue; - entries.push({ type: "message", id: mm.id, message: { role: mm.role, content: mm.content, toolCallId: mm.toolCallId } }); + entries.push({ type: "message", id: mm.id, message: { role: dshFpRole(mm.role), content: dshFpContent(mm.content), toolCallId: mm.toolCallId } }); } const wireAligned = fmt === "anthropic" ? laneMsgIdsForWire(wire, entries) : laneMsgIdsForOpenAiWire(wire, entries); if (wireAligned === undefined) return undefined; // pairing not provable — degrade diff --git a/tests/issue6525-dsh-envelope.test.ts b/tests/issue6525-dsh-envelope.test.ts index 5b85682265..2b1b42026f 100644 --- a/tests/issue6525-dsh-envelope.test.ts +++ b/tests/issue6525-dsh-envelope.test.ts @@ -89,6 +89,37 @@ test("openai: host entry missing an id → bail (all-or-nothing)", () => { assert.strictEqual(resolve(wire, host), undefined); }); +test("openai: dsh flat host shape (role tool + block tool-call) → core-aligned (churn fix #6525 B7)", () => { + // dsh's flat host messages differ from the pi-ai form the shared walker's + // host fingerprint assumes: tool results carry role "tool" (not + // "toolResult") and assistant tool-call blocks are type "tool-call" + // (hyphen, not camel "toolCall"). Without the resolver's fingerprint-only + // normalization, EVERY tool-bearing turn bailed the all-or-nothing + // envelope and the host ids churned back to content digests on the next + // full-resend (the B7 root cause found via a real-dsh e2e dump). + const wire = oai([ + { role: "system", content: "S" }, + { role: "user", content: "hello" }, + { role: "assistant", content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "acp_status", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "call_1", content: "r1" }, + { role: "assistant", content: "done" }, + ]); + const host = [ + sys("S"), + user("u1", "hello"), + { id: "a1", role: "assistant", content: [{ type: "tool-call", id: "call_1", name: "acp_status", arguments: "{}" }], timestamp: 1 }, + { id: "t1", role: "tool", toolCallId: "call_1", content: [{ type: "text", text: "r1" }], timestamp: 1 }, + { id: "a2", role: "assistant", content: [{ type: "text", text: "done" }], timestamp: 1 }, + ]; + assert.deepStrictEqual(resolve(wire, host), ["u1", "a1", "t1", "a2"]); +}); + +test("openai: dsh parallel tool_calls still bail (one host id cannot cover N cores)", () => { + const wire = oai([{ role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "f", arguments: "{}" } }, { id: "c2", type: "function", function: { name: "g", arguments: "{}" } }] }]); + const host = [{ id: "a1", role: "assistant", content: [{ type: "tool-call", id: "c1", name: "f", arguments: "{}" }, { type: "tool-call", id: "c2", name: "g", arguments: "{}" }], timestamp: 1 }]; + assert.strictEqual(resolve(wire, host), undefined); +}); + test("anthropic: system field separate, full conversation → 1:1 ids", () => { const wire = { model: "fake-model", max_tokens: 100, system: "S", messages: [ { role: "user", content: "hi" },