From 67d9b830bd7956453f569a368af831ca3b444c59 Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Thu, 3 Dec 2026 15:18:28 -0800 Subject: [PATCH] fix(recorder): keep OpenRouter delta.reasoning when collapsing streams OpenRouter streams reasoning as delta.reasoning (mirrored in reasoning_details), not delta.reasoning_content, so recorded OpenRouter fixtures lost their reasoning. Read reasoning_content when it is a string, else reasoning. Take one source per delta so a delta carrying both fields is not double-counted. --- CHANGELOG.md | 1 + .../recorder-openrouter-reasoning.test.ts | 179 ++++++++++++++++++ src/stream-collapse.ts | 7 +- 3 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 src/__tests__/recorder-openrouter-reasoning.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dc0a289..ff616a44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Fixed - OpenRouter streamed chunks carry reasoning as `delta.reasoning` and `reasoning_details` (#663) +- Recording an OpenRouter stream keeps its `delta.reasoning` text in the fixture (#664) ## [1.49.0] - 2026-11-30 diff --git a/src/__tests__/recorder-openrouter-reasoning.test.ts b/src/__tests__/recorder-openrouter-reasoning.test.ts new file mode 100644 index 00000000..6bb325b9 --- /dev/null +++ b/src/__tests__/recorder-openrouter-reasoning.test.ts @@ -0,0 +1,179 @@ +/** + * Recording a real OpenRouter streaming chat completion keeps its reasoning. + * + * OpenRouter streams reasoning as `delta.reasoning` plus a mirrored + * `delta.reasoning_details` array (see the K9 expectations in + * `drift/openrouter-chat.drift.ts`), not as `delta.reasoning_content`. The + * collapser used to read only `reasoning_content`, so a recorded OpenRouter + * turn lost its reasoning. These tests drive the real record path: an aimock + * recorder proxies to a local upstream that streams the SSE body, and the + * assertions read the fixture file it writes. + */ + +import { describe, it, expect, afterEach } from "vitest"; +import http from "node:http"; +import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { collapseOpenAISSE } from "../stream-collapse.js"; +import { createServer, type ServerInstance } from "../server.js"; +import type { FixtureFile, FixtureFileEntry, TextResponse } from "../types.js"; + +let servers: http.Server[] = []; +let instance: ServerInstance | null = null; +let tmpDir: string | undefined; + +afterEach(async () => { + if (instance) { + await new Promise((r) => instance!.server.close(() => r())); + instance = null; + } + for (const s of servers) await new Promise((r) => s.close(() => r())); + servers = []; + if (tmpDir) { + rmSync(tmpDir, { recursive: true, force: true }); + tmpDir = undefined; + } +}); + +function httpPost(url: string, body: object): Promise<{ status: number; body: string }> { + return new Promise((resolve, reject) => { + const req = http.request( + url, + { method: "POST", headers: { "Content-Type": "application/json" } }, + (res) => { + const chunks: Buffer[] = []; + res.on("data", (c) => chunks.push(c)); + res.on("end", () => + resolve({ status: res.statusCode!, body: Buffer.concat(chunks).toString() }), + ); + }, + ); + req.on("error", reject); + req.write(JSON.stringify(body)); + req.end(); + }); +} + +function createUpstream(body: string): Promise { + return new Promise((resolve) => { + const srv = http.createServer((_req, res) => { + res.writeHead(200, { "Content-Type": "text/event-stream" }); + res.end(body); + }); + srv.listen(0, "127.0.0.1", () => { + const addr = srv.address() as { port: number }; + servers.push(srv); + resolve(`http://127.0.0.1:${addr.port}`); + }); + }); +} + +interface ChunkFrame { + id: string; + object: "chat.completion.chunk"; + model: string; + choices: Array<{ index: number; delta: Record; finish_reason: string | null }>; +} + +function sse(deltas: Array>, finish = "stop"): string { + const frames: ChunkFrame[] = deltas.map((delta) => ({ + id: "gen-or-1", + object: "chat.completion.chunk", + model: "openai/gpt-oss-20b", + choices: [{ index: 0, delta, finish_reason: null }], + })); + frames.push({ + id: "gen-or-1", + object: "chat.completion.chunk", + model: "openai/gpt-oss-20b", + choices: [{ index: 0, delta: {}, finish_reason: finish }], + }); + return frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join("") + "data: [DONE]\n\n"; +} + +/** One OpenRouter reasoning delta, shaped exactly as the K9 drift test expects. */ +function orReasoning(text: string): Record { + return { + role: "assistant", + content: "", + reasoning: text, + reasoning_details: [{ type: "reasoning.text", text, format: "unknown", index: 0 }], + }; +} + +function readRecordedFixture(dir: string): FixtureFileEntry { + const files = readdirSync(dir).filter((f) => f.endsWith(".json")); + expect(files).toHaveLength(1); + const file = JSON.parse(readFileSync(join(dir, files[0]), "utf-8")) as FixtureFile; + expect(file.fixtures).toHaveLength(1); + return file.fixtures[0]; +} + +async function recordThroughOpenRouter(upstreamBody: string): Promise { + const upstreamUrl = await createUpstream(upstreamBody); + tmpDir = mkdtempSync(join(tmpdir(), "aimock-or-reasoning-")); + instance = await createServer([], { + port: 0, + record: { providers: { openrouter: upstreamUrl }, fixturePath: tmpDir }, + }); + const res = await httpPost(`${instance.url}/api/v1/chat/completions`, { + model: "openai/gpt-oss-20b", + messages: [{ role: "user", content: "What is 17 * 23?" }], + reasoning: { enabled: true }, + stream: true, + }); + expect(res.status).toBe(200); + return readRecordedFixture(tmpDir).response as TextResponse; +} + +describe("recording an OpenRouter stream keeps delta.reasoning", () => { + it("writes OpenRouter delta.reasoning (with reasoning_details) into the fixture", async () => { + const response = await recordThroughOpenRouter( + sse([ + orReasoning("Work through the arithmetic"), + orReasoning(" before giving an answer."), + { content: "391" }, + ]), + ); + expect(response.reasoning).toBe("Work through the arithmetic before giving an answer."); + expect(response.content).toBe("391"); + }); + + it("does not double-count a delta that carries both reasoning_content and reasoning", async () => { + const both = (text: string) => ({ ...orReasoning(text), reasoning_content: text }); + const response = await recordThroughOpenRouter( + sse([both("Step one."), both(" Step two."), { content: "done" }]), + ); + expect(response.reasoning).toBe("Step one. Step two."); + expect(response.content).toBe("done"); + }); + + it("keeps OpenAI-style reasoning_content-only streams unchanged (control)", async () => { + const response = await recordThroughOpenRouter( + sse([ + { role: "assistant", reasoning_content: "Think" }, + { reasoning_content: "ing." }, + { content: "ok" }, + ]), + ); + expect(response.reasoning).toBe("Thinking."); + expect(response.content).toBe("ok"); + }); +}); + +describe("collapseOpenAISSE reasoning sources", () => { + it("ignores a null delta.reasoning (OpenRouter length terminal)", () => { + const result = collapseOpenAISSE( + sse([orReasoning("abc"), { content: "", reasoning: null, reasoning_details: [] }], "length"), + ); + expect(result.reasoning).toBe("abc"); + }); + + it("prefers reasoning_content per delta when both fields are strings", () => { + const result = collapseOpenAISSE( + sse([{ reasoning_content: "x", reasoning: "x" }, { reasoning: "y" }]), + ); + expect(result.reasoning).toBe("xy"); + }); +}); diff --git a/src/stream-collapse.ts b/src/stream-collapse.ts index 8c0e0b06..8eff49d9 100644 --- a/src/stream-collapse.ts +++ b/src/stream-collapse.ts @@ -881,9 +881,14 @@ export function collapseOpenAISSEWithResponsesTools( const delta = choices[0].delta as Record | undefined; if (!delta) continue; - // Reasoning content (OpenRouter / chat completions format) + // Reasoning text. DeepSeek-style streams use `reasoning_content`; OpenRouter + // streams `reasoning` (mirrored in `reasoning_details`). A delta may carry + // both with the same text, so take ONE source per delta to avoid + // double-counting: `reasoning_content` when it is a string, else `reasoning`. if (typeof delta.reasoning_content === "string") { reasoning += delta.reasoning_content; + } else if (typeof delta.reasoning === "string") { + reasoning += delta.reasoning; } // Text content