Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(format): merge adjacent user messages and close an orphan tool round (item 13)

Jack Rudenkob9e21638283a
diff --git a/packages/cli/src/format-translation.test.ts b/packages/cli/src/format-translation.test.ts
index 10c1b8aa..df5dcd25 100644
--- a/packages/cli/src/format-translation.test.ts
+++ b/packages/cli/src/format-translation.test.ts
@@ -601,6 +601,15 @@ describe("Adapter: convertMessagesToOpenAI", () => {
const convert = await getConverter();
const req = {
messages: [
+ // The assistant turn that made the call. It was absent when this test
+ // was written; item 13 made the sequence matter, because a `tool`
+ // message that answers no open round is a 400 on the real wire.
+ {
+ role: "assistant",
+ content: [
+ { type: "tool_use", id: "call_123", name: "Read", input: { file_path: "/tmp/a" } },
+ ],
+ },
{
role: "user",
content: [
@@ -611,10 +620,10 @@ describe("Adapter: convertMessagesToOpenAI", () => {
};
const messages = convert(req, "test-model");
- expect(messages).toHaveLength(1);
- expect(messages[0].role).toBe("tool");
- expect(messages[0].tool_call_id).toBe("call_123");
- expect(messages[0].content).toBe("file contents here");
+ expect(messages).toHaveLength(2);
+ expect(messages[1].role).toBe("tool");
+ expect(messages[1].tool_call_id).toBe("call_123");
+ expect(messages[1].content).toBe("file contents here");
});
test("Kimi K2.5: empty thinking block still produces reasoning_content field", async () => {
@@ -699,6 +708,111 @@ describe("Adapter: convertMessagesToOpenAI", () => {
});
});
+// ─── Item 13: message-sequence normalization ────────────────────────────────
+//
+// These inputs are CONSTRUCTED Anthropic request bodies, not captures. No real
+// inbound body exists anywhere under test-fixtures/ (the one file under
+// transcripts/ is a tool-id ledger, and .sse captures are response-side), so
+// there is nothing to replay here. They are written in the same inline style as
+// the sibling `convertMessagesToOpenAI` tests above, and they assert only the
+// conversion contract — never a provider's wire behaviour.
+describe("Adapter: normalizeMessageSequence (item 13)", () => {
+ async function getConverter() {
+ const mod = await import("./handlers/shared/openai-compat.js");
+ return mod.convertMessagesToOpenAI;
+ }
+
+ test("adjacent user messages merge into one", async () => {
+ const convert = await getConverter();
+ const messages = convert(
+ {
+ messages: [
+ { role: "user", content: "first" },
+ { role: "user", content: "second" },
+ ],
+ },
+ "test-model"
+ );
+
+ expect(messages).toHaveLength(1);
+ expect(messages[0].role).toBe("user");
+ expect(messages[0].content).toBe("first\n\nsecond");
+ });
+
+ test("a string user turn and a block-array user turn merge into content parts", async () => {
+ const convert = await getConverter();
+ const messages = convert(
+ {
+ messages: [
+ { role: "user", content: "first" },
+ { role: "user", content: [{ type: "text", text: "second" }] },
+ ],
+ },
+ "test-model"
+ );
+
+ expect(messages).toHaveLength(1);
+ expect(messages[0].content).toEqual([
+ { type: "text", text: "first" },
+ { type: "text", text: "second" },
+ ]);
+ });
+
+ test("a user turn after a tool round is NOT merged across the tool message", async () => {
+ const convert = await getConverter();
+ const messages = convert(
+ {
+ messages: [
+ { role: "user", content: "read it" },
+ { role: "assistant", content: [{ type: "tool_use", id: "c1", name: "Read", input: {} }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "c1", content: "ok" }] },
+ { role: "user", content: "now what?" },
+ ],
+ },
+ "test-model"
+ );
+
+ // user, assistant(tool_calls), tool, user — and no synthetic assistant turn
+ // between the tool output and the following user turn (design ruling; FCC
+ // inserts `assistant: " "` there).
+ expect(messages.map((m: any) => m.role)).toEqual(["user", "assistant", "tool", "user"]);
+ expect(messages[3].content).toBe("now what?");
+ });
+
+ test("a tool result answering no open round degrades to a user message", async () => {
+ const convert = await getConverter();
+ const messages = convert(
+ {
+ messages: [
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "c9", content: "ok" }] },
+ ],
+ },
+ "test-model"
+ );
+
+ expect(messages).toHaveLength(1);
+ expect(messages[0].role).toBe("user");
+ expect(messages[0].content).toBe("[Tool Result]: ok");
+ });
+
+ test("a degraded tool result merges into the user turn before it", async () => {
+ const convert = await getConverter();
+ const messages = convert(
+ {
+ messages: [
+ { role: "user", content: "hello" },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "c9", content: "ok" }] },
+ ],
+ },
+ "test-model"
+ );
+
+ expect(messages).toHaveLength(1);
+ expect(messages[0].role).toBe("user");
+ expect(messages[0].content).toBe("hello\n\n[Tool Result]: ok");
+ });
+});
+
describe("Adapter: AnthropicAPIFormat", () => {
async function getAdapter() {
const mod = await import("./adapters/anthropic-api-format.js");
diff --git a/packages/cli/src/handlers/shared/format/openai-messages.ts b/packages/cli/src/handlers/shared/format/openai-messages.ts
index 7dd1d1b4..8b16ad3b 100644
--- a/packages/cli/src/handlers/shared/format/openai-messages.ts
+++ b/packages/cli/src/handlers/shared/format/openai-messages.ts
@@ -44,7 +44,108 @@ export function convertMessagesToOpenAI(
}
}
- return messages;
+ return normalizeMessageSequence(messages);
+}
+
+/**
+ * Merge two adjacent `user` contents, or return `undefined` for "do not merge".
+ *
+ * Two shapes reach here: a plain string (a Claude turn whose content was not a
+ * block array) and an array of OpenAI content parts. A string pair stays a
+ * string — keeping the simple shape matters for providers that only accept one.
+ * A mixed pair is lifted to parts. Anything else (a null content, an object) is
+ * left alone rather than guessed at.
+ */
+function mergeUserContent(a: any, b: any): any | undefined {
+ if (typeof a === "string" && typeof b === "string") {
+ if (!a) return b;
+ if (!b) return a;
+ return `${a}\n\n${b}`;
+ }
+ const toParts = (c: any): any[] | undefined => {
+ if (typeof c === "string") return c ? [{ type: "text", text: c }] : [];
+ if (Array.isArray(c)) return c;
+ return undefined;
+ };
+ const pa = toParts(a);
+ const pb = toParts(b);
+ if (!pa || !pb) return undefined;
+ return [...pa, ...pb];
+}
+
+/** Push a `user` message, merging it into the preceding one when there is one. */
+function pushUserMessage(out: any[], msg: any) {
+ const prev = out[out.length - 1];
+ if (prev?.role === "user") {
+ const merged = mergeUserContent(prev.content, msg.content);
+ if (merged !== undefined) {
+ prev.content = merged;
+ return;
+ }
+ }
+ out.push(msg);
+}
+
+/**
+ * Post-pass over the converted message list, fixing two sequence-level defects
+ * that are only visible AFTER conversion.
+ *
+ * It has to be a post-pass rather than an edit inside `processUserMessage`,
+ * because the converter itself emits up to three messages for a single Claude
+ * user turn (the tool results, the images lifted out of them, and the turn's own
+ * content). The adjacency is created here, so it can only be seen from here.
+ *
+ * 1. **Adjacent `user` messages merge.** Chat Completions does not require
+ * strict alternation, but several relays and local runtimes do, and a
+ * provider that silently keeps only the last of a run drops the user's words.
+ *
+ * 2. **A `tool` message must answer an open tool round** — it must follow either
+ * an `assistant` carrying `tool_calls` or another `tool` message in the same
+ * round. An orphan (the assistant turn was compacted out of history, or the
+ * client replayed a result alone) is rejected by OpenAI with
+ * `messages with role 'tool' must be a response to a preceding message with
+ * tool_calls`, which reaches the user as an opaque 400. It is re-emitted as a
+ * `user` message prefixed `[Tool Result]:` — the same degradation
+ * `simpleFormat` already applies — so the content survives.
+ *
+ * FCC additionally inserts a synthetic `assistant: " "` between a tool round and
+ * a following user turn. That is NOT done here, per the design's ruling: the
+ * synthetic turn is itself a fidelity cost (it enters history as words the
+ * assistant never said, and is replayed on every later turn), and
+ * `assistant(tool_calls) → tool → user` is legal OpenAI on its own. What
+ * "closing the round" means here is rule 2 — a tool message outside a round
+ * stops being one.
+ *
+ * No message is ever moved or dropped by this pass.
+ */
+export function normalizeMessageSequence(messages: any[]): any[] {
+ const out: any[] = [];
+ // True while the last non-tool message was an assistant carrying tool_calls.
+ let toolRoundOpen = false;
+
+ for (const msg of messages) {
+ if (msg.role === "tool") {
+ if (toolRoundOpen) {
+ out.push(msg);
+ continue;
+ }
+ log(
+ `[OpenAIMessages] error — tool result ${msg.tool_call_id} answers no open tool round; ` +
+ "re-emitted as a user message"
+ );
+ const text = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
+ pushUserMessage(out, { role: "user", content: `[Tool Result]: ${text}` });
+ continue;
+ }
+
+ toolRoundOpen =
+ msg.role === "assistant" && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0;
+
+ if (msg.role === "user") pushUserMessage(out, msg);
+ else out.push(msg);
+ }
+
+ return out;
}
/**