Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 90 additions & 13 deletions src/agent/pi-msgids.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,37 @@
// entries in lockstep and accepts an id only when the pair provably denotes
// the same message:
// - each step compares an order-preserving content fingerprint (text,
// image bytes, thinking text, redacted payload, tool-call ids) with EXACT
// equality — never similarity, never position alone;
// image bytes, thinking text, redacted payload, tool-call ids) — exact
// equality modulo pi's OWN cross-model transforms (see partsLowerThrough:
// thinking flattened to text, redacted thinking dropped, non-vision image
// downgrade, tool-call id normalization), never similarity, never
// position alone;
// - entries that provably produce no wire message (empty text) are skipped;
// - anything the walker cannot prove (agent-message roles with derived
// text, compaction/branch summaries, alien block types, any mismatch)
// aborts the whole resolution — all-or-nothing: one unresolvable message
// and the turn ships WITHOUT msgIds, so the lane falls back to
// content-derived ids, exactly today's behavior.
// text, compaction/branch summaries, alien block types, any other
// mismatch) aborts the whole resolution — all-or-nothing: one
// unresolvable message and the turn ships WITHOUT msgIds, so the lane
// falls back to content-derived ids, exactly today's behavior.
//
// Why tolerate the cross-model transforms at all: the host id is the stable
// identity of the message — a model switch rewrites the WIRE bytes (thinking
// flattening, image placeholders, tool-id normalization) but the entry id
// stays the same. Treating those rewrites as mismatches dropped the id field
// on the first turn after every switch, forcing content-derived ids back on
// and re-minting identity for messages whose host id never changed — the
// churn family (#4390 D4-1). The transforms accepted here are exactly the
// ones pi-stable-ai's transformMessages performs (verified against its
// dist); alignment is still proven by role, order and the non-tool parts'
// byte equality, so a dropped/inserted message still fails the walk.
//
// Fingerprint mirroring (verified against pi 0.99.1 dist): text blocks drop
// when whitespace-only on BOTH sides; thinking blocks ride verbatim on the
// same model (empty text kept iff a signature exists) and mismatch → bail on
// cross-model rewrites; tool_use/tool_result match by call id (unique within
// a branch path — ids are minted once per call); lone surrogates are stripped
// with pi's own regex; cache_control decorations are ignored (the wire may
// add them; they never change identity).
// same model (empty text kept iff a signature exists) and lower onto text
// parts cross-model (never a bail); tool_use/tool_result match by call id
// (unique within a branch path — ids are minted once per call) with
// cross-model renumbering tolerated positionally; lone surrogates are
// stripped with pi's own regex; cache_control decorations are ignored (the
// wire may add them; they never change identity).

type FpPart = { t: "text" | "img" | "tooluse" | "toolres" | "think" | "redact"; v: string };

Expand Down Expand Up @@ -174,6 +189,66 @@ function entryFingerprint(entry: Record<string, unknown>): FpPart[] | undefined
/** Session entry types that never contribute to the LLM context. */
const CONTEXT_SILENT_ENTRY_TYPES = new Set(["thinking_level_change", "model_change", "label", "session_info", "custom"]);

/** pi's non-vision image downgrade text (transform-messages.js), verbatim —
* entry image parts lower onto this placeholder when the target model has
* no image input. */
const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";

/** Can `eParts` (branch-entry fingerprint) lower onto `wParts` (wire
* fingerprint) through pi's own transform set? Two-pointer walk: every wire
* part must be consumed by an entry part, exactly, or through one of the
* documented cross-model rewrites (thinking → text, redacted dropped,
* image → placeholder, consecutive images collapsing onto one placeholder,
* tool-call id renumbering). Anything else — different text bytes, different
* block order beyond the transforms, leftover parts — is a mismatch. */
function partsLowerThrough(eParts: FpPart[], wParts: FpPart[]): boolean {
let wi = 0;
let placeholderOpen = false; // one wire placeholder may absorb N consecutive entry images
for (const ep of eParts) {
if (wi < wParts.length) {
const wp = wParts[wi];
if (ep.t === wp.t && ep.v === wp.v) {
wi++;
placeholderOpen = false;
continue;
}
// cross-model: thinking blocks flatten to plain text blocks
if (ep.t === "think" && wp.t === "text" && wp.v === ep.v) {
wi++;
placeholderOpen = false;
continue;
}
// cross-model: non-vision target downgrades images to a text placeholder
if (ep.t === "img" && wp.t === "text" && wp.v === NON_VISION_USER_IMAGE_PLACEHOLDER) {
if (!placeholderOpen) {
wi++;
placeholderOpen = true;
}
continue;
}
// cross-model: normalizeToolCallId may renumber call ids; the
// pinned id is the ENTRY id, so the value drift never reaches
// the ledger — accept the pairing when shape and position hold.
if (ep.t === "tooluse" && wp.t === "tooluse") {
wi++;
placeholderOpen = false;
continue;
}
if (ep.t === "toolres" && wp.t === "toolres") {
wi++;
placeholderOpen = false;
continue;
}
}
// cross-model: redacted thinking is dropped entirely
if (ep.t === "redact") continue;
// extra entry images collapsing onto the LAST placeholder consumed
if (ep.t === "img" && placeholderOpen) continue;
return false;
}
return wi === wParts.length;
}

/** Walk the outgoing wire messages and the branch entries in lockstep; return
* the entry id for every wire message (aligned by index), or undefined when
* the alignment cannot be proven end-to-end (all-or-nothing). */
Expand Down Expand Up @@ -210,16 +285,18 @@ export function laneMsgIdsForWire(wire: unknown, branch: unknown): string[] | un
if (wParts === undefined || wParts.length === 0) return undefined;
if (wParts.every((p) => p.t === "toolres")) {
// Merged consecutive tool results: ONE wire message, N entries.
// Call-id values may drift cross-model (normalizeToolCallId) — the
// pairing is positional here, which the transform preserves.
for (const part of wParts) {
const n = take();
if (typeof n === "string" || n.parts.length !== 1 || n.parts[0].t !== "toolres" || n.parts[0].v !== part.v) return undefined;
if (typeof n === "string" || n.parts.length !== 1 || n.parts[0].t !== "toolres") return undefined;
ids.push(n.id);
}
continue;
}
const n = take();
if (typeof n === "string") return undefined;
if (n.parts.length !== wParts.length || n.parts.some((p, i) => p.t !== wParts[i].t || p.v !== wParts[i].v)) return undefined;
if (!partsLowerThrough(n.parts, wParts)) return undefined;
ids.push(n.id);
}
// A visible entry surviving past the wire's end means the request dropped
Expand Down
85 changes: 85 additions & 0 deletions tests/pi-msgids.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,88 @@ test("pi msgids: tool turns pin tool_use and tool_result entry ids by call id",
assert.equal(t2.body.msgIds?.length, t2.body.messages?.length, "msgIds parallel to messages");
});
});

// --- transform-tolerant walker (cross-model rewrites must not drop msgIds) ---
// laneMsgIdsForWire is a pure function over (wire, branch) — unit-test the
// pairing lattice directly. Shapes mirror pi-stable-ai's transformMessages
// output (verified against its dist): thinking→text, redacted dropped,
// non-vision image placeholder, tool-call id normalization.
import { laneMsgIdsForWire } from "../src/agent/pi-msgids.ts";

function msgEntry(id: string, role: string, content: unknown): Record<string, unknown> {
return { type: "message", id, message: { role, content } };
}

test("pi msgids unit: cross-model thinking flattens to text — id still ships", () => {
const branch = [
msgEntry("e1", "assistant", [{ type: "thinking", thinking: "plan x" }, { type: "text", text: "answer" }]),
msgEntry("e2", "user", "next question"),
];
const wire = [
{ role: "assistant", content: [{ type: "text", text: "plan x" }, { type: "text", text: "answer" }] },
{ role: "user", content: "next question" },
];
assert.deepEqual(laneMsgIdsForWire(wire, branch), ["e1", "e2"]);
});

test("pi msgids unit: redacted thinking dropped cross-model — id still ships", () => {
const branch = [
msgEntry("e1", "assistant", [{ type: "thinking", redacted: true, thinkingSignature: "sig==" }, { type: "text", text: "answer" }]),
msgEntry("e2", "user", "q"),
];
const wire = [
{ role: "assistant", content: [{ type: "text", text: "answer" }] },
{ role: "user", content: "q" },
];
assert.deepEqual(laneMsgIdsForWire(wire, branch), ["e1", "e2"]);
});

test("pi msgids unit: non-vision image downgrade (incl. collapse) — id still ships", () => {
const branch = [
{ type: "message", id: "e1", message: { role: "user", content: [{ type: "image", data: "AAAA" }, { type: "image", data: "BBBB" }] } },
msgEntry("e2", "user", "caption"),
];
const wire = [
{ role: "user", content: [{ type: "text", text: "(image omitted: model does not support images)" }] },
{ role: "user", content: "caption" },
];
assert.deepEqual(laneMsgIdsForWire(wire, branch), ["e1", "e2"]);
});

test("pi msgids unit: tool-call id renumbered cross-model — ids still ship", () => {
const branch = [
msgEntry("e1", "assistant", [{ type: "toolCall", id: "call-450char-openai|style", name: "read" }]),
{ type: "message", id: "e2", message: { role: "toolResult", toolCallId: "call-450char-openai|style", content: [{ type: "text", text: "data" }] } },
];
const wire = [
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_normalized1", name: "read", input: {} }] },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_normalized1", content: "data" }] },
];
assert.deepEqual(laneMsgIdsForWire(wire, branch), ["e1", "e2"]);
});

test("pi msgids unit: genuine text drift still refuses the whole field", () => {
const branch = [
msgEntry("e1", "assistant", [{ type: "thinking", thinking: "plan x" }, { type: "text", text: "answer" }]),
msgEntry("e2", "user", "next question"),
];
const wire = [
// thinking flattened BUT the text was edited — not a transform, refuse
{ role: "assistant", content: [{ type: "text", text: "plan x" }, { type: "text", text: "EDITED answer" }] },
{ role: "user", content: "next question" },
];
assert.equal(laneMsgIdsForWire(wire, branch), undefined);
});

test("pi msgids unit: an inserted wire message still refuses the whole field", () => {
const branch = [
msgEntry("e1", "user", "q1"),
msgEntry("e2", "user", "q2"),
];
const wire = [
{ role: "user", content: "q1" },
{ role: "user", content: "injected" },
{ role: "user", content: "q2" },
];
assert.equal(laneMsgIdsForWire(wire, branch), undefined);
});
Loading