Skip to content

Commit d92d68a

Browse files
steipetePeter Steinberger
andauthored
fix(providers): canonicalize model families and stream outcomes (#116998)
* fix(providers): canonicalize live model families and stream finalization * test(openrouter): use canonical typed stream fixture --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 2a56ce9 commit d92d68a

6 files changed

Lines changed: 260 additions & 35 deletions

File tree

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import {
2+
BedrockRuntimeClient,
3+
ConversationRole,
4+
StopReason as BedrockStopReason,
5+
} from "@aws-sdk/client-bedrock-runtime";
6+
import { afterEach, describe, expect, it, vi } from "vitest";
7+
import { streamSimpleBedrock } from "./stream.runtime.js";
8+
9+
const model = {
10+
api: "bedrock-converse-stream",
11+
provider: "amazon-bedrock",
12+
id: "amazon.nova-micro-v1:0",
13+
name: "Nova Micro",
14+
baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
15+
reasoning: true,
16+
input: ["text"],
17+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
18+
contextWindow: 128_000,
19+
maxTokens: 4096,
20+
} as const;
21+
22+
async function* events(items: unknown[]) {
23+
yield* items;
24+
}
25+
26+
afterEach(() => {
27+
vi.restoreAllMocks();
28+
});
29+
30+
describe("Bedrock provider-owned stream lifecycle", () => {
31+
it.each([
32+
{
33+
label: "text",
34+
blocks: [{ contentBlockDelta: { contentBlockIndex: 0, delta: { text: "ready" } } }],
35+
endEvent: "text_end",
36+
stopReason: BedrockStopReason.END_TURN,
37+
},
38+
{
39+
label: "thinking",
40+
blocks: [
41+
{
42+
contentBlockDelta: {
43+
contentBlockIndex: 0,
44+
delta: { reasoningContent: { text: "considered" } },
45+
},
46+
},
47+
],
48+
endEvent: "thinking_end",
49+
stopReason: BedrockStopReason.END_TURN,
50+
},
51+
{
52+
label: "redacted thinking",
53+
blocks: [
54+
{
55+
contentBlockDelta: {
56+
contentBlockIndex: 0,
57+
delta: { reasoningContent: { redactedContent: new Uint8Array([1, 2, 3]) } },
58+
},
59+
},
60+
],
61+
endEvent: "thinking_end",
62+
stopReason: BedrockStopReason.END_TURN,
63+
},
64+
{
65+
label: "tool call",
66+
blocks: [
67+
{
68+
contentBlockStart: {
69+
contentBlockIndex: 0,
70+
start: { toolUse: { toolUseId: "call_lookup", name: "lookup" } },
71+
},
72+
},
73+
{
74+
contentBlockDelta: {
75+
contentBlockIndex: 0,
76+
delta: { toolUse: { input: '{"query":"ready"}' } },
77+
},
78+
},
79+
],
80+
endEvent: "toolcall_end",
81+
stopReason: BedrockStopReason.TOOL_USE,
82+
},
83+
])("finalizes the active $label block at the provider terminal boundary", async (scenario) => {
84+
vi.spyOn(BedrockRuntimeClient.prototype, "send").mockResolvedValue({
85+
$metadata: { httpStatusCode: 200 },
86+
stream: events([
87+
{ messageStart: { role: ConversationRole.ASSISTANT } },
88+
...scenario.blocks,
89+
{ messageStop: { stopReason: scenario.stopReason } },
90+
]),
91+
} as never);
92+
93+
const stream = streamSimpleBedrock(model as never, {
94+
messages: [{ role: "user", content: "Continue", timestamp: 0 }],
95+
});
96+
const observed = [];
97+
for await (const event of stream) {
98+
observed.push(event.type);
99+
}
100+
const output = await stream.result();
101+
102+
expect(observed.at(-2)).toBe(scenario.endEvent);
103+
expect(observed.at(-1)).toBe("done");
104+
expect(output.content[0]).not.toHaveProperty("index");
105+
expect(output.content[0]).not.toHaveProperty("partialJson");
106+
if (scenario.label === "redacted thinking") {
107+
expect(output.content[0]).toMatchObject({ redacted: true, thinkingSignature: "AQID" });
108+
}
109+
});
110+
});

‎extensions/amazon-bedrock/stream.runtime.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,18 @@ const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOptions> =
357357
throw new Error(output.errorMessage ?? "An unknown error occurred");
358358
}
359359

360+
// Some valid provider streams omit contentBlockStop; never persist their scratch state.
361+
for (const block of blocks) {
362+
if (block.index !== undefined) {
363+
handleContentBlockStop(
364+
{ contentBlockIndex: block.index },
365+
blocks,
366+
output,
367+
eventSink,
368+
redactedReasoningChunks,
369+
);
370+
}
371+
}
360372
refusalBuffer?.flush();
361373
stream.push({ type: "done", reason: output.stopReason, message: output });
362374
stream.end();
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
2+
import { createAssistantMessageEventStream } from "openclaw/plugin-sdk/llm";
3+
import { registerSingleProviderPlugin } from "openclaw/plugin-sdk/plugin-test-runtime";
4+
import { describe, expect, it, vi } from "vitest";
5+
import openrouterPlugin from "./index.js";
6+
7+
async function captureProviderPayload(
8+
modelId: string,
9+
thinkingLevel: string,
10+
payload: Record<string, unknown>,
11+
) {
12+
const provider = await registerSingleProviderPlugin(openrouterPlugin);
13+
const baseStreamFn = vi.fn((...args: Parameters<StreamFn>): ReturnType<StreamFn> => {
14+
void args[2]?.onPayload?.(payload, args[0]);
15+
return createAssistantMessageEventStream();
16+
});
17+
const wrapped = provider.wrapStreamFn?.({
18+
provider: "openrouter",
19+
modelId,
20+
thinkingLevel,
21+
streamFn: baseStreamFn,
22+
} as never);
23+
24+
void wrapped?.(
25+
{
26+
provider: "openrouter",
27+
api: "openai-completions",
28+
id: modelId,
29+
baseUrl: "https://openrouter.ai/api/v1",
30+
compat: {},
31+
} as never,
32+
{ messages: [] },
33+
{},
34+
);
35+
36+
expect(baseStreamFn).toHaveBeenCalledOnce();
37+
return payload;
38+
}
39+
40+
describe("OpenRouter chat owner invariants", () => {
41+
it.each([
42+
"openrouter/anthropic/claude-sonnet-5",
43+
"openrouter/deepseek/deepseek-v4-pro",
44+
"openrouter/moonshotai/kimi-k3",
45+
"z-ai/glm-5.2",
46+
"openrouter/z-ai/glm-5.2",
47+
"~anthropic/claude-opus-latest",
48+
"~moonshotai/kimi-latest",
49+
])("recognizes the live upstream cacheable model reference %s", async (modelId) => {
50+
const provider = await registerSingleProviderPlugin(openrouterPlugin);
51+
52+
expect(provider.isCacheTtlEligible?.({ provider: "openrouter", modelId } as never)).toBe(true);
53+
});
54+
55+
it.each(["openai/gpt-5.4", "~openai/gpt-5.4", "openrouter/openai/gpt-5.4"])(
56+
"does not infer provider cache support for unrelated model reference %s",
57+
async (modelId) => {
58+
const provider = await registerSingleProviderPlugin(openrouterPlugin);
59+
60+
expect(provider.isCacheTtlEligible?.({ provider: "openrouter", modelId } as never)).toBe(
61+
false,
62+
);
63+
},
64+
);
65+
66+
it("preserves assistant prefill when the provider reasoning object disables reasoning", async () => {
67+
const payload = await captureProviderPayload("anthropic/claude-opus-5", "off", {
68+
reasoning: { enabled: false },
69+
messages: [
70+
{ role: "user", content: "Return JSON." },
71+
{ role: "assistant", content: "{" },
72+
],
73+
});
74+
75+
expect(payload.messages).toEqual([
76+
{ role: "user", content: "Return JSON." },
77+
{ role: "assistant", content: "{" },
78+
]);
79+
});
80+
81+
it.each(["~anthropic/claude-opus-latest", "openrouter/~anthropic/claude-opus-latest"])(
82+
"removes unsupported assistant prefill for reasoning model alias %s",
83+
async (modelId) => {
84+
const payload = await captureProviderPayload(modelId, "high", {
85+
reasoning: { effort: "high" },
86+
messages: [
87+
{ role: "user", content: "Continue." },
88+
{ role: "assistant", content: "{" },
89+
],
90+
});
91+
92+
expect(payload.messages).toEqual([{ role: "user", content: "Continue." }]);
93+
},
94+
);
95+
96+
it("recognizes the live dated DeepSeek V4 model in its owner thinking profile", async () => {
97+
const provider = await registerSingleProviderPlugin(openrouterPlugin);
98+
99+
expect(
100+
provider.resolveThinkingProfile?.({
101+
provider: "openrouter",
102+
modelId: "deepseek/deepseek-v4-flash-0731",
103+
} as never),
104+
).toMatchObject({ defaultLevel: "high" });
105+
});
106+
107+
it("backfills reasoning replay for the live dated DeepSeek V4 model", async () => {
108+
const payload = await captureProviderPayload("deepseek/deepseek-v4-flash-0731", "high", {
109+
messages: [{ role: "assistant", content: "done" }],
110+
});
111+
112+
expect(payload.reasoning).toEqual({ effort: "high" });
113+
expect(payload.messages).toEqual([
114+
{ role: "assistant", content: "done", reasoning_content: "" },
115+
]);
116+
});
117+
});

‎extensions/openrouter/index.ts‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@ import { asOptionalRecord as readRecord } from "openclaw/plugin-sdk/string-coerc
1818
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
1919
import { buildOpenRouterImageGenerationProvider } from "./image-generation-provider.js";
2020
import { openrouterMediaUnderstandingProvider } from "./media-understanding-provider.js";
21-
import { isOpenRouterMistralModelId, normalizeOpenRouterApiModelId } from "./models.js";
21+
import {
22+
isOpenRouterMistralModelId,
23+
normalizeOpenRouterApiModelId,
24+
normalizeOpenRouterModelFamilyId,
25+
} from "./models.js";
2226
import { buildOpenRouterMusicGenerationProvider } from "./music-generation-provider.js";
2327
import { createOpenRouterOAuthAuthMethod } from "./oauth.js";
2428
import { applyOpenrouterConfig, OPENROUTER_DEFAULT_MODEL_REF } from "./onboard.js";
@@ -43,13 +47,7 @@ import {
4347
const PROVIDER_ID = "openrouter";
4448
const OPENROUTER_DEFAULT_MAX_TOKENS = 8192;
4549
const OPENROUTER_FUSION_MODEL_ID = "openrouter/fusion";
46-
const OPENROUTER_CACHE_TTL_MODEL_PREFIXES = [
47-
"anthropic/",
48-
"deepseek/",
49-
"moonshot/",
50-
"moonshotai/",
51-
"zai/",
52-
] as const;
50+
const OPENROUTER_CACHE_TTL_MODEL_FAMILY = /^(?:anthropic|deepseek|moonshot(?:ai)?|z-?ai)\//;
5351
const MAX_PROMPT_MODEL_ID_DISPLAY_CHARS = 256;
5452

5553
type OpenRouterFusionPromptContext = {
@@ -253,10 +251,6 @@ export default defineSingleProviderPluginEntry({
253251
};
254252
}
255253

256-
function isOpenRouterCacheTtlModel(modelId: string): boolean {
257-
return OPENROUTER_CACHE_TTL_MODEL_PREFIXES.some((prefix) => modelId.startsWith(prefix));
258-
}
259-
260254
const passthroughGeminiReplayHooks = buildProviderReplayFamilyHooks({
261255
family: "passthrough-gemini",
262256
});
@@ -335,7 +329,8 @@ export default defineSingleProviderPluginEntry({
335329
resolveSystemPromptContribution: resolveOpenRouterFusionPromptContribution,
336330
extraParamsForTransport: resolveOpenRouterExtraParamsForTransport,
337331
wrapStreamFn: wrapOpenRouterProviderStream,
338-
isCacheTtlEligible: (ctx) => isOpenRouterCacheTtlModel(ctx.modelId),
332+
isCacheTtlEligible: ({ modelId }) =>
333+
OPENROUTER_CACHE_TTL_MODEL_FAMILY.test(normalizeOpenRouterModelFamilyId(modelId) ?? ""),
339334
resolveUsageAuth: async (ctx) => {
340335
const apiKey = ctx.resolveApiKeyFromConfigAndStore({
341336
envDirect: [ctx.env.OPENROUTER_API_KEY],

‎extensions/openrouter/models.ts‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,12 @@ const OPENROUTER_SHORT_TO_API_MODEL_ID = new Map([
2121
["deepseek-v4-pro", "deepseek/deepseek-v4-pro"],
2222
]);
2323

24-
function normalizeOpenRouterModelId(modelId: unknown): string | undefined {
24+
export function normalizeOpenRouterModelFamilyId(modelId: unknown): string | undefined {
2525
if (typeof modelId !== "string") {
2626
return undefined;
2727
}
2828
const normalized = normalizeLowercaseStringOrEmpty(modelId);
29-
return normalized.startsWith(OPENROUTER_MODEL_PREFIX)
30-
? normalized.slice(OPENROUTER_MODEL_PREFIX.length)
31-
: normalized;
29+
return normalized.replace(/^openrouter\//, "").replace(/^~/, "");
3230
}
3331

3432
export function normalizeOpenRouterApiModelId(modelId: unknown): string | undefined {
@@ -50,17 +48,14 @@ export function normalizeOpenRouterApiModelId(modelId: unknown): string | undefi
5048
}
5149

5250
export function isOpenRouterMistralModelId(modelId: unknown): boolean {
53-
const normalized = normalizeOpenRouterModelId(modelId);
51+
const normalized = normalizeOpenRouterModelFamilyId(modelId);
5452
return Boolean(
5553
normalized && OPENROUTER_MISTRAL_MODEL_PREFIXES.some((prefix) => normalized.startsWith(prefix)),
5654
);
5755
}
5856

5957
export function isOpenRouterDeepSeekV4ModelId(modelId: unknown): boolean {
60-
const normalized = normalizeOpenRouterModelId(modelId);
61-
if (!normalized?.startsWith("deepseek/")) {
62-
return false;
63-
}
64-
const deepSeekModelId = normalized.slice("deepseek/".length).split(":", 1)[0];
65-
return deepSeekModelId === "deepseek-v4-flash" || deepSeekModelId === "deepseek-v4-pro";
58+
return /^deepseek\/deepseek-v4-(?:flash|pro)(?:-\d{4,8})?(?::[^/]*)?$/.test(
59+
normalizeOpenRouterModelFamilyId(modelId) ?? "",
60+
);
6661
}

‎extensions/openrouter/stream.ts‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
normalizeOpenAICompatibleReasoningReplay,
99
} from "openclaw/plugin-sdk/provider-stream-shared";
1010
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
11-
import { isOpenRouterDeepSeekV4ModelId } from "./models.js";
11+
import { isOpenRouterDeepSeekV4ModelId, normalizeOpenRouterModelFamilyId } from "./models.js";
1212
import {
1313
isOpenRouterProxyReasoningUnsupportedModel,
1414
normalizeOpenRouterBaseUrl,
@@ -22,14 +22,6 @@ function readString(value: unknown): string | undefined {
2222
return typeof value === "string" ? value.trim() : undefined;
2323
}
2424

25-
function isOpenRouterAnthropicModelId(modelId: unknown): boolean {
26-
const normalized = readString(modelId)?.toLowerCase();
27-
return (
28-
normalized?.startsWith("anthropic/") === true ||
29-
normalized?.startsWith("openrouter/anthropic/") === true
30-
);
31-
}
32-
3325
function isVerifiedOpenRouterRoute(model: Parameters<StreamFn>[0]): boolean {
3426
const provider = readString(model.provider)?.toLowerCase();
3527
const baseUrl = readString(model.baseUrl);
@@ -43,7 +35,7 @@ function shouldPatchAnthropicOpenRouterPayload(model: Parameters<StreamFn>[0]):
4335
const api = readString(model.api);
4436
return (
4537
(api === undefined || api === "openai-completions") &&
46-
isOpenRouterAnthropicModelId(model.id) &&
38+
normalizeOpenRouterModelFamilyId(model.id)?.startsWith("anthropic/") === true &&
4739
isVerifiedOpenRouterRoute(model)
4840
);
4941
}
@@ -154,7 +146,11 @@ function isEnabledReasoningValue(value: unknown): boolean {
154146
return normalized !== "" && normalized !== "off" && normalized !== "none";
155147
}
156148
if (typeof value === "object" && !Array.isArray(value)) {
157-
const effort = (value as Record<string, unknown>).effort;
149+
const reasoning = value as Record<string, unknown>;
150+
if (reasoning.enabled === false) {
151+
return false;
152+
}
153+
const effort = reasoning.effort;
158154
if (typeof effort === "string") {
159155
const normalized = effort.trim().toLowerCase();
160156
return normalized !== "" && normalized !== "off" && normalized !== "none";

0 commit comments

Comments
 (0)