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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
179 changes: 179 additions & 0 deletions src/__tests__/recorder-openrouter-reasoning.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((r) => instance!.server.close(() => r()));
instance = null;
}
for (const s of servers) await new Promise<void>((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<string> {
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<string, unknown>; finish_reason: string | null }>;
}

function sse(deltas: Array<Record<string, unknown>>, 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<string, unknown> {
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<TextResponse> {
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");
});
});
7 changes: 6 additions & 1 deletion src/stream-collapse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -881,9 +881,14 @@ export function collapseOpenAISSEWithResponsesTools(
const delta = choices[0].delta as Record<string, unknown> | 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
Expand Down
Loading