Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(model-runtime): scope opaque reasoning state (#17694)

YuTengjing5edf44be3f0a
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index cd4162f7b31..8ba05f7ff65 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -1,6 +1,7 @@
import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { getRuntimeSignatureScopeSource } from '../../utils/signatureScope';
import type { LobeRuntimeAI } from '../BaseAI';
import { createRouterRuntime } from './createRuntime';
@@ -58,12 +59,15 @@ describe('createRouterRuntime', () => {
it('should merge router options with constructor options', async () => {
const mockConstructor = vi.fn();
+ let signatureScopeSource;
class MockRuntime implements LobeRuntimeAI {
constructor(options: any) {
mockConstructor(options);
}
- chat = vi.fn();
+ chat = vi.fn().mockImplementation(() => {
+ signatureScopeSource = getRuntimeSignatureScopeSource(this);
+ });
models = vi.fn();
embeddings = vi.fn();
textToSpeech = vi.fn();
@@ -74,7 +78,8 @@ describe('createRouterRuntime', () => {
routers: [
{
apiType: 'openai',
- options: { baseURL: 'https://api.example.com' },
+ id: 'router-a',
+ options: { baseURL: 'https://api.example.com', id: 'channel-a' },
runtime: MockRuntime as any,
models: ['test-model'],
},
@@ -93,6 +98,12 @@ describe('createRouterRuntime', () => {
id: 'test-runtime',
}),
);
+ expect(signatureScopeSource).toEqual({
+ apiType: 'openai',
+ channelId: 'channel-a',
+ provider: 'test-runtime',
+ routerId: 'router-a',
+ });
});
});
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 458cd7af722..28f4e7b0e77 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -39,6 +39,7 @@ import { isNonRetryableRequestError } from '../../utils/isNonRetryableRequestErr
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
import { postProcessModelList } from '../../utils/postProcessModelList';
import { safeParseJSON } from '../../utils/safeParseJSON';
+import { setRuntimeSignatureScopeSource } from '../../utils/signatureScope';
import type { LobeRuntimeAI } from '../BaseAI';
import type {
CreateImageOptions,
@@ -498,6 +499,12 @@ export const createRouterRuntime = ({
...this._options,
...optionOverrides,
};
+ const signatureScopeSource = {
+ apiType: resolvedApiType,
+ channelId,
+ provider: this._id,
+ routerId: router.id ?? this._id,
+ };
/**
* Vertex AI uses GoogleGenAI credentials flow rather than API keys.
@@ -530,11 +537,14 @@ export const createRouterRuntime = ({
);
}
+ const runtime = LobeVertexAI.initFromVertexAI(vertexOptions);
+ setRuntimeSignatureScopeSource(runtime, signatureScopeSource);
+
return {
channelId,
id: resolvedApiType,
remark,
- runtime: LobeVertexAI.initFromVertexAI(vertexOptions),
+ runtime,
};
}
@@ -544,6 +554,7 @@ export const createRouterRuntime = ({
? (router.runtime ?? baseRuntimeMap[resolvedApiType] ?? LobeOpenAI)
: (baseRuntimeMap[resolvedApiType] ?? LobeOpenAI);
const runtime: LobeRuntimeAI = new providerAI({ ...finalOptions, id: this._id });
+ setRuntimeSignatureScopeSource(runtime, signatureScopeSource);
if (this._id === 'lobehub') {
timing(
diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.ts
index 7c24f1048eb..93b93b4cbb0 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts
@@ -3,6 +3,7 @@ import * as imageToBase64Module from '@lobechat/utils';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChatCompletionTool, OpenAIChatMessage, UserMessageContentPart } from '../../types';
+import { serializeScopedSignature, type SignatureScope } from '../../utils/signatureScope';
import { isPublicExternalUrl, parseDataUri, validateExternalUrl } from '../../utils/uriParser';
import {
buildGoogleMessage,
@@ -24,6 +25,8 @@ vi.mock('../../utils/imageToBase64', () => ({
imageUrlToBase64: vi.fn(),
}));
+const thoughtSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+
const PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ';
describe('google contextBuilders', () => {
@@ -655,14 +658,17 @@ describe('google contextBuilders', () => {
name: 'grep____searchGitHub____mcp',
},
id: 'grep____searchGitHub____mcp_0_6RnOMTF0',
- thoughtSignature:
- 'EsUHCsIHAdHtim9/MrjP+pnhM8DVkvulyfWQVf+isXQxEAbF32gbflE1hl6Te80qtp77Ywn8opB2uhQOIH/l6SStsj3+XRy1U1DTeKtqZxDBoLP2rNK6pi3/nk0ZOQIc8f6rxB70G/zOhk7d/1XQFqhmw5H+yDVRQjGD1cNPY5ctWGxQLAIk/HMWNovUJzz2c81jGWoXu7k2vtpuur2hcAL+J79BEVUTfvU3mSiXqJFTClmFPB6Fe79i0y3TwM2XdIBxzPgVgf8B+Pnv1S6YDxHNSm46jTlXKcSw30r3ixs5xEOzerbOUW5WG9BGukw/YQVvHiuoGLIALRa2Ig7dlOMH8+o+f0mKJtyYj8yF6wyBMol+G4mhSHvQSKJLj/Z5kFHvDZKeVUEOZed6vZivYLrVezjQPXgLHJMOmbp6QrZGxqW45QxDKY5X5F8giIOM8VgsUYhDQUBown+3vvwkIBA24icDsOwdhJ/roe9GabbGfxpkSzARIFh7rSI01cRKbh6cEaVFXf2WQftPeD7dBseQLiCdUYoy4ytECrjTpknrWnVUG6Ly4SKW6uN/IJXpm9JT9GgnGLIddFtEQzm9sIKWNpGEz6++lZpiCFS6LsYSnTP3vPj/7oSABRmwWywxA8EmLh+sv+jiK5aMjFi1sTuJ0Ujsvza3/SHZKewNi9WKQUDOa9Mqtjs2YGDnJxto4l5GMUzI5vhf6/+/A5eHALfVabaFP97v8FEPrXQU94dognwx4EnNqy/KWmGIlYZYqIfjaSAy7Z74viwl+oTtL9gyyBDc/FrQvXfyrYIq8N0pkLKAEh33fa/+YVocLL1LKI9rb2bg/RRr+Ee4NyIQKhIdEJaEh74d1COd/4r06J92ThkfVo5PEVTSsr8tBKiJ5wSmX9vyhbLWzxmXoq1xfGrs8kg7NMW53XEWGlQrIVOQmUtjjjBQKj6b4rBTAO6EKk63cGFbkSPohifiUBPHbxUUPy/hf0tQpeOo3jA01AuCFLOIZ5IYJ+Rm5+aZTU3Panv+Q7Yl1w5t5swhbNZfg7MlU/sxwLijLuWDDNfw+2Zw/aa3VDPgVw6Nv2vKkHi4tUU0XlgfiQgQYUMPxpGRV837uUxvZFNep2QUlAMog5h4sMYJWIAX1kK1pzsyR/KxuCn6nUq4ovWNBQHLC4aW2ZcGgW/6CbF81F1cewUz+vWNMMkJrL0d9celGEbFuY0Q709UipaDbCg49twlnLV9XUwqC5wYTFBiJbynBDqiZAvXn2YOxNIs8CCzuu2GSCQDo09ksJy5g/o=',
+ thoughtSignature: serializeScopedSignature(
+ 'provider-signature',
+ thoughtSignatureScope,
+ 'thought_signature',
+ ),
type: 'function',
},
],
} as OpenAIChatMessage;
- const converted = await buildGoogleMessage(message);
+ const converted = await buildGoogleMessage(message, undefined, { thoughtSignatureScope });
expect(converted).toEqual({
parts: [
@@ -676,8 +682,7 @@ describe('google contextBuilders', () => {
},
name: 'grep____searchGitHub____mcp',
},
- thoughtSignature:
- 'EsUHCsIHAdHtim9/MrjP+pnhM8DVkvulyfWQVf+isXQxEAbF32gbflE1hl6Te80qtp77Ywn8opB2uhQOIH/l6SStsj3+XRy1U1DTeKtqZxDBoLP2rNK6pi3/nk0ZOQIc8f6rxB70G/zOhk7d/1XQFqhmw5H+yDVRQjGD1cNPY5ctWGxQLAIk/HMWNovUJzz2c81jGWoXu7k2vtpuur2hcAL+J79BEVUTfvU3mSiXqJFTClmFPB6Fe79i0y3TwM2XdIBxzPgVgf8B+Pnv1S6YDxHNSm46jTlXKcSw30r3ixs5xEOzerbOUW5WG9BGukw/YQVvHiuoGLIALRa2Ig7dlOMH8+o+f0mKJtyYj8yF6wyBMol+G4mhSHvQSKJLj/Z5kFHvDZKeVUEOZed6vZivYLrVezjQPXgLHJMOmbp6QrZGxqW45QxDKY5X5F8giIOM8VgsUYhDQUBown+3vvwkIBA24icDsOwdhJ/roe9GabbGfxpkSzARIFh7rSI01cRKbh6cEaVFXf2WQftPeD7dBseQLiCdUYoy4ytECrjTpknrWnVUG6Ly4SKW6uN/IJXpm9JT9GgnGLIddFtEQzm9sIKWNpGEz6++lZpiCFS6LsYSnTP3vPj/7oSABRmwWywxA8EmLh+sv+jiK5aMjFi1sTuJ0Ujsvza3/SHZKewNi9WKQUDOa9Mqtjs2YGDnJxto4l5GMUzI5vhf6/+/A5eHALfVabaFP97v8FEPrXQU94dognwx4EnNqy/KWmGIlYZYqIfjaSAy7Z74viwl+oTtL9gyyBDc/FrQvXfyrYIq8N0pkLKAEh33fa/+YVocLL1LKI9rb2bg/RRr+Ee4NyIQKhIdEJaEh74d1COd/4r06J92ThkfVo5PEVTSsr8tBKiJ5wSmX9vyhbLWzxmXoq1xfGrs8kg7NMW53XEWGlQrIVOQmUtjjjBQKj6b4rBTAO6EKk63cGFbkSPohifiUBPHbxUUPy/hf0tQpeOo3jA01AuCFLOIZ5IYJ+Rm5+aZTU3Panv+Q7Yl1w5t5swhbNZfg7MlU/sxwLijLuWDDNfw+2Zw/aa3VDPgVw6Nv2vKkHi4tUU0XlgfiQgQYUMPxpGRV837uUxvZFNep2QUlAMog5h4sMYJWIAX1kK1pzsyR/KxuCn6nUq4ovWNBQHLC4aW2ZcGgW/6CbF81F1cewUz+vWNMMkJrL0d9celGEbFuY0Q709UipaDbCg49twlnLV9XUwqC5wYTFBiJbynBDqiZAvXn2YOxNIs8CCzuu2GSCQDo09ksJy5g/o=',
+ thoughtSignature: 'provider-signature',
},
],
role: 'model',
@@ -819,7 +824,11 @@ describe('google contextBuilders', () => {
name: 'lobe-web-browsing____search',
},
id: 'call_001',
- thoughtSignature: existingSignature,
+ thoughtSignature: serializeScopedSignature(
+ existingSignature,
+ thoughtSignatureScope,
+ 'thought_signature',
+ ),
type: 'function',
},
],
@@ -832,7 +841,7 @@ describe('google contextBuilders', () => {
},
];
- const contents = await buildGoogleMessages(messages);
+ const contents = await buildGoogleMessages(messages, { thoughtSignatureScope });
expect(contents).toEqual([
{
@@ -866,6 +875,37 @@ describe('google contextBuilders', () => {
]);
});
+ it('should replace foreign and legacy thought signatures with the magic signature', async () => {
+ const foreignScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
+ const createMessages = (thoughtSignature: string): OpenAIChatMessage[] => [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'get_weather' },
+ id: 'call_001',
+ thoughtSignature,
+ type: 'function',
+ },
+ ],
+ },
+ ];
+
+ const foreign = await buildGoogleMessages(
+ createMessages(
+ serializeScopedSignature('foreign-signature', foreignScope, 'thought_signature')!,
+ ),
+ { thoughtSignatureScope },
+ );
+ const legacy = await buildGoogleMessages(createMessages('legacy-signature'), {
+ thoughtSignatureScope,
+ });
+
+ expect(foreign[0].parts?.[0].thoughtSignature).toBe(GEMINI_MAGIC_THOUGHT_SIGNATURE);
+ expect(legacy[0].parts?.[0].thoughtSignature).toBe(GEMINI_MAGIC_THOUGHT_SIGNATURE);
+ });
+
it('should add magic signature to all function calls in multi-turn scenario', async () => {
const messages: OpenAIChatMessage[] = [
{
@@ -1427,7 +1467,11 @@ describe('google contextBuilders', () => {
name: 'grep____searchGitHub____mcp',
},
id: 'grep____searchGitHub____mcp_0_6RnOMTF0',
- thoughtSignature: 'test-signature',
+ thoughtSignature: serializeScopedSignature(
+ 'test-signature',
+ thoughtSignatureScope,
+ 'thought_signature',
+ ),
type: 'function',
},
],
@@ -1440,7 +1484,7 @@ describe('google contextBuilders', () => {
},
];
- const contents = await buildGoogleMessages(messages);
+ const contents = await buildGoogleMessages(messages, { thoughtSignatureScope });
expect(contents).toEqual([
{
diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.ts
index bc5bd1eaedf..e1b4124eb4c 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.ts
@@ -8,6 +8,7 @@ import { imageUrlToBase64, resolveImageMimeTypeFromBase64 } from '@lobechat/util
import type { ChatCompletionTool, OpenAIChatMessage, UserMessageContentPart } from '../../types';
import { safeParseJSON } from '../../utils/safeParseJSON';
+import { resolveScopedSignature, type SignatureScope } from '../../utils/signatureScope';
import { isPublicExternalUrl, parseDataUri, validateExternalUrl } from '../../utils/uriParser';
const GOOGLE_SUPPORTED_IMAGE_TYPES = new Set([
@@ -31,6 +32,11 @@ const isImageTypeSupported = (mimeType: string | null | undefined): mimeType is
*/
export const GEMINI_MAGIC_THOUGHT_SIGNATURE = 'skip_thought_signature_validator';
+interface GoogleMessageBuildOptions {
+ model?: string;
+ thoughtSignatureScope?: SignatureScope;
+}
+
const getGeminiVersion = (model?: string) => {
if (!model) return null;
@@ -71,7 +77,7 @@ const supportsFunctionCallId = (model?: string) => {
const buildExternalUrlFileDataPart = async (
url: string,
- options?: { model?: string },
+ options?: GoogleMessageBuildOptions,
): Promise<Part | undefined> => {
if (!supportsExternalUrlFileData(options?.model) || !isPublicExternalUrl(url)) return undefined;
@@ -103,7 +109,7 @@ const buildExternalUrlFileDataPart = async (
*/
export const buildGooglePart = async (
content: UserMessageContentPart,
- options?: { model?: string },
+ options?: GoogleMessageBuildOptions,
): Promise<Part | undefined> => {
switch (content.type) {
default: {
@@ -232,7 +238,7 @@ export const buildGooglePart = async (
export const buildGoogleMessage = async (
message: OpenAIChatMessage,
toolCallNameMap?: Map<string, string>,
- options?: { model?: string },
+ options?: GoogleMessageBuildOptions,
): Promise<Content> => {
const content = message.content as string | UserMessageContentPart[];
@@ -283,7 +289,11 @@ export const buildGoogleMessage = async (
id: supportsFunctionCallId(options?.model) ? tool.id : undefined,
name: tool.function.name,
},
- thoughtSignature: tool.thoughtSignature,
+ thoughtSignature: resolveScopedSignature(
+ tool.thoughtSignature,
+ options?.thoughtSignatureScope,
+ 'thought_signature',
+ ),
};
}),
role: 'model',
@@ -328,7 +338,7 @@ export const buildGoogleMessage = async (
*/
export const buildGoogleMessages = async (
messages: OpenAIChatMessage[],
- options?: { model?: string },
+ options?: GoogleMessageBuildOptions,
): Promise<Content[]> => {
const toolCallNameMap = new Map<string, string>();
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.ts
index 180bf84710a..c2fbc2b0886 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts
@@ -3,6 +3,7 @@ import type OpenAI from 'openai';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { OpenAIChatMessage } from '../../types';
+import { serializeScopedSignature, type SignatureScope } from '../../utils/signatureScope';
import { parseDataUri } from '../../utils/uriParser';
import {
convertImageUrlToFile,
@@ -187,6 +188,48 @@ describe('convertMessageContent', () => {
});
describe('convertOpenAIMessages', () => {
+ it('should restore thoughtSignature only for the exact scope', async () => {
+ const scope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const foreignScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
+ const thoughtSignature = serializeScopedSignature(
+ 'google-signature',
+ scope,
+ 'thought_signature',
+ );
+ const messages = [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'get_weather' },
+ id: 'call_1',
+ thoughtSignature,
+ type: 'function',
+ },
+ ],
+ },
+ ] as any;
+
+ const matching = await convertOpenAIMessages(messages, { thoughtSignatureScope: scope });
+ const mismatching = await convertOpenAIMessages(messages, {
+ thoughtSignatureScope: foreignScope,
+ });
+ const legacy = await convertOpenAIMessages(
+ [
+ {
+ ...messages[0],
+ tool_calls: [{ ...messages[0].tool_calls[0], thoughtSignature: 'legacy-signature' }],
+ },
+ ],
+ { thoughtSignatureScope: scope },
+ );
+
+ expect((matching[0] as any).tool_calls[0].thoughtSignature).toBe('google-signature');
+ expect((mismatching[0] as any).tool_calls[0].thoughtSignature).toBeUndefined();
+ expect((legacy[0] as any).tool_calls[0].thoughtSignature).toBeUndefined();
+ });
+
it('should convert string content messages', async () => {
const messages = [
{ role: 'user', content: 'Hello' },
@@ -920,7 +963,8 @@ describe('convertOpenAIResponseInputs', () => {
]);
});
- it('should replay encrypted reasoning from a persisted message for the same provider', async () => {
+ it('should replay encrypted reasoning from a persisted message for the exact scope', async () => {
+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
const messages: OpenAIChatMessage[] = [
{
content: 'hello',
@@ -928,13 +972,17 @@ describe('convertOpenAIResponseInputs', () => {
provider: 'chatgpt',
reasoning: {
content: 'reasoning content',
- signature: 'encrypted-reasoning-content',
+ signature: serializeScopedSignature(
+ 'encrypted-reasoning-content',
+ reasoningSignatureScope,
+ 'reasoning',
+ ),
},
role: 'assistant',
},
];
- const result = await convertOpenAIResponseInputs(messages, { provider: 'chatgpt' });
+ const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
expect(result).toEqual([
{
@@ -947,16 +995,23 @@ describe('convertOpenAIResponseInputs', () => {
});
it('should preserve encrypted reasoning content without a visible summary', async () => {
+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
const messages: OpenAIChatMessage[] = [
{
content: 'hello',
provider: 'chatgpt',
- reasoning: { signature: 'encrypted-reasoning-content' },
+ reasoning: {
+ signature: serializeScopedSignature(
+ 'encrypted-reasoning-content',
+ reasoningSignatureScope,
+ 'reasoning',
+ ),
+ },
role: 'assistant',
},
];
- const result = await convertOpenAIResponseInputs(messages, { provider: 'chatgpt' });
+ const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
expect(result).toEqual([
{
@@ -968,6 +1023,38 @@ describe('convertOpenAIResponseInputs', () => {
]);
});
+ it('should keep the visible summary but reject foreign and legacy encrypted reasoning', async () => {
+ const sourceScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const targetScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
+ const baseMessage: OpenAIChatMessage = {
+ content: 'hello',
+ reasoning: {
+ content: 'reasoning content',
+ signature: serializeScopedSignature(
+ 'encrypted-reasoning-content',
+ sourceScope,
+ 'reasoning',
+ ),
+ },
+ role: 'assistant',
+ };
+
+ const foreignResult = await convertOpenAIResponseInputs([baseMessage], {
+ reasoningSignatureScope: targetScope,
+ });
+ const legacyResult = await convertOpenAIResponseInputs(
+ [{ ...baseMessage, reasoning: { ...baseMessage.reasoning, signature: 'legacy-signature' } }],
+ { reasoningSignatureScope: sourceScope },
+ );
+
+ const expected = [
+ { summary: [{ text: 'reasoning content', type: 'summary_text' }], type: 'reasoning' },
+ { content: 'hello', role: 'assistant' },
+ ];
+ expect(foreignResult).toEqual(expected);
+ expect(legacyResult).toEqual(expected);
+ });
+
it('should preserve message order when earlier messages have async content (images)', async () => {
const messages: OpenAIChatMessage[] = [
{ content: 'system prompts', role: 'system' },
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.ts
index 5099ce8b3b3..397247a8089 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts
@@ -4,8 +4,14 @@ import type OpenAI from 'openai';
import { toFile } from 'openai';
import { disableStreamModels, systemToUserModels } from '../../providers/openai/modelId';
-import type { ChatStreamPayload, OpenAIChatMessage, UserMessageContentPart } from '../../types';
+import type {
+ ChatStreamPayload,
+ MessageToolCall,
+ OpenAIChatMessage,
+ UserMessageContentPart,
+} from '../../types';
import { isDeepSeekThinkingEligibleModel } from '../../utils/modelParse';
+import { resolveScopedSignature, type SignatureScope } from '../../utils/signatureScope';
import { parseDataUri } from '../../utils/uriParser';
export type ExtendedChatCompletionContentPart = {
@@ -20,7 +26,9 @@ type ConvertMessageContentOptions = {
forceVideoBase64?: boolean;
model?: string;
provider?: string;
+ reasoningSignatureScope?: SignatureScope;
strictToolPairing?: boolean;
+ thoughtSignatureScope?: SignatureScope;
};
const isDeepSeekModel = (model: string | undefined) =>
@@ -159,7 +167,20 @@ export const convertOpenAIMessages = async (
// Add optional fields if they exist
if (msg.name !== undefined) result.name = msg.name;
- if (msg.tool_calls !== undefined) result.tool_calls = msg.tool_calls;
+ if (msg.tool_calls !== undefined) {
+ result.tool_calls = msg.tool_calls.map((toolCall: MessageToolCall) => {
+ if (!toolCall.thoughtSignature) return toolCall;
+
+ const { thoughtSignature, ...rest } = toolCall;
+ const resolvedSignature = resolveScopedSignature(
+ thoughtSignature,
+ options?.thoughtSignatureScope,
+ 'thought_signature',
+ );
+
+ return resolvedSignature ? { ...rest, thoughtSignature: resolvedSignature } : rest;
+ });
+ }
if (msg.tool_call_id !== undefined) result.tool_call_id = msg.tool_call_id;
if (msg.function_call !== undefined) result.function_call = msg.function_call;
@@ -224,10 +245,12 @@ export const convertOpenAIResponseInputs = async (
const inputGroups = await Promise.all(
messages.map(async (message) => {
const items: OpenAI.Responses.ResponseInputItem[] = [];
- const sourceProvider = message.provider;
const reasoning = message.reasoning;
- const encryptedContent =
- sourceProvider && sourceProvider === options?.provider ? reasoning?.signature : undefined;
+ const encryptedContent = resolveScopedSignature(
+ reasoning?.signature,
+ options?.reasoningSignatureScope,
+ 'reasoning',
+ );
// Preserve encrypted reasoning state for stateless Responses API requests.
if (reasoning?.content || encryptedContent) {
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index 3099944de06..8225c6551f9 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -9,6 +9,11 @@ import type { LobeOpenAICompatibleRuntime } from '../../core/BaseAI';
import type { ChatStreamCallbacks, ChatStreamPayload } from '../../types/chat';
import { AgentRuntimeErrorType } from '../../types/error';
import * as debugStreamModule from '../../utils/debugStream';
+import {
+ createSignatureChannelId,
+ createSignatureScope,
+ serializeScopedSignature,
+} from '../../utils/signatureScope';
import * as openaiHelpers from '../contextBuilders/openai';
import { createOpenAICompatibleRuntime } from './index';
@@ -22,6 +27,50 @@ const defaultBaseURL = 'https://api.groq.com/openai/v1';
const bizErrorType = 'ProviderBizError';
const invalidErrorType = 'InvalidProviderAPIKey';
+const createOpenAIThoughtSignatureScope = async ({
+ apiKey = 'test',
+ baseURL = defaultBaseURL,
+ model = 'upstream-model',
+ scopeProvider = 'mapped-provider',
+}: {
+ apiKey?: string;
+ baseURL?: string;
+ model?: string;
+ scopeProvider?: string;
+} = {}) =>
+ createSignatureScope({
+ kind: 'thought_signature',
+ model,
+ protocol: 'chat_completions',
+ source: {
+ apiType: 'openai',
+ channelId: await createSignatureChannelId(baseURL, apiKey),
+ provider: scopeProvider,
+ },
+ });
+
+const createOpenAIReasoningSignatureScope = async ({
+ apiKey = 'test',
+ baseURL = 'https://api.test.com/v1',
+ model = 'upstream-model',
+ scopeProvider = 'mapped-provider',
+}: {
+ apiKey?: string;
+ baseURL?: string;
+ model?: string;
+ scopeProvider?: string;
+} = {}) =>
+ createSignatureScope({
+ kind: 'reasoning',
+ model,
+ protocol: 'responses',
+ source: {
+ apiType: 'openai',
+ channelId: await createSignatureChannelId(baseURL, apiKey),
+ provider: scopeProvider,
+ },
+ });
+
// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mock('@lobechat/business-model-bank/model-config', () => ({
@@ -206,6 +255,91 @@ describe('LobeOpenAICompatibleFactory', () => {
);
});
+ it('should replay a thought signature scoped to the mapped upstream model', async () => {
+ const Runtime = createOpenAICompatibleRuntime({
+ baseURL: defaultBaseURL,
+ provider: 'mapped-provider',
+ });
+ const runtime = new Runtime({
+ apiKey: 'test',
+ modelIdMapping: { 'logical-model': 'upstream-model' },
+ });
+ const create = vi
+ .spyOn(runtime['client'].chat.completions, 'create')
+ .mockResolvedValue(new ReadableStream() as any);
+ const scope = await createOpenAIThoughtSignatureScope();
+
+ await runtime.chat({
+ messages: [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'search' },
+ id: 'call-1',
+ thoughtSignature: serializeScopedSignature(
+ 'upstream-signature',
+ scope,
+ 'thought_signature',
+ ),
+ type: 'function',
+ },
+ ],
+ },
+ ],
+ model: 'logical-model',
+ temperature: 0,
+ });
+
+ const request = create.mock.calls[0][0];
+ expect(request.model).toBe('upstream-model');
+ expect((request.messages[0] as any).tool_calls[0].thoughtSignature).toBe(
+ 'upstream-signature',
+ );
+ });
+
+ it.each([
+ { apiKey: 'another-key', baseURL: defaultBaseURL, label: 'credential' },
+ { apiKey: 'test', baseURL: 'https://another.example.com/v1', label: 'endpoint' },
+ ])('should reject a thought signature from another direct $label', async (source) => {
+ const Runtime = createOpenAICompatibleRuntime({
+ baseURL: defaultBaseURL,
+ provider: 'mapped-provider',
+ });
+ const runtime = new Runtime({ apiKey: 'test' });
+ const create = vi
+ .spyOn(runtime['client'].chat.completions, 'create')
+ .mockResolvedValue(new ReadableStream() as any);
+ const sourceScope = await createOpenAIThoughtSignatureScope(source);
+
+ await runtime.chat({
+ messages: [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'search' },
+ id: 'call-1',
+ thoughtSignature: serializeScopedSignature(
+ 'foreign-signature',
+ sourceScope,
+ 'thought_signature',
+ ),
+ type: 'function',
+ },
+ ],
+ },
+ ],
+ model: 'upstream-model',
+ temperature: 0,
+ });
+
+ const request = create.mock.calls[0][0];
+ expect((request.messages[0] as any).tool_calls[0].thoughtSignature).toBeUndefined();
+ });
+
describe('streaming response', () => {
it('should handle multiple data chunks correctly', async () => {
const mockStream = new ReadableStream({
@@ -1527,6 +1661,81 @@ describe('LobeOpenAICompatibleFactory', () => {
strictToolPairing: true,
}),
);
+ convertSpy.mockRestore();
+ });
+
+ it('should replay encrypted reasoning scoped to the mapped upstream model', async () => {
+ const Runtime = createOpenAICompatibleRuntime({
+ baseURL: 'https://api.test.com/v1',
+ chatCompletion: { useResponse: true },
+ provider: 'mapped-provider',
+ });
+ const inst = new Runtime({
+ apiKey: 'test',
+ modelIdMapping: { 'logical-model': 'upstream-model' },
+ });
+ const create = vi
+ .spyOn(inst['client'].responses, 'create')
+ .mockResolvedValue(new ReadableStream() as any);
+ const scope = await createOpenAIReasoningSignatureScope();
+
+ await inst.chat({
+ messages: [
+ {
+ content: 'Answer',
+ reasoning: {
+ content: 'Summary',
+ signature: serializeScopedSignature(
+ 'upstream-encrypted-content',
+ scope,
+ 'reasoning',
+ ),
+ },
+ role: 'assistant',
+ },
+ ],
+ model: 'logical-model',
+ temperature: 0,
+ });
+
+ const request = create.mock.calls[0][0];
+ expect(request.model).toBe('upstream-model');
+ expect(request.input?.[0]).toMatchObject({
+ encrypted_content: 'upstream-encrypted-content',
+ type: 'reasoning',
+ });
+ });
+
+ it('should bind encrypted reasoning to the ChatGPT subscription account', async () => {
+ const Runtime = createOpenAICompatibleRuntime({
+ baseURL: 'https://chatgpt.com/backend-api/codex',
+ chatCompletion: { useResponse: true },
+ provider: ModelProvider.ChatGPT,
+ });
+ const convertSpy = vi
+ .spyOn(openaiHelpers, 'convertOpenAIResponseInputs')
+ .mockRejectedValue({ status: 400 });
+
+ for (const chatgptAccountId of ['account-a', 'account-b']) {
+ const inst = new Runtime({ apiKey: 'oauth-token', chatgptAccountId });
+ await expect(
+ inst.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'gpt-5.6-sol',
+ temperature: 0,
+ }),
+ ).rejects.toBeDefined();
+ }
+
+ const fingerprints = convertSpy.mock.calls.map(
+ ([, options]) => options?.reasoningSignatureScope?.fingerprint,
+ );
+ expect(fingerprints[0]).toMatch(/^[\da-f]{32}$/);
+ expect(fingerprints[1]).toMatch(/^[\da-f]{32}$/);
+ expect(fingerprints[0]).not.toBe(fingerprints[1]);
+ expect(fingerprints).not.toContain('account-a');
+ expect(fingerprints).not.toContain('account-b');
+ convertSpy.mockRestore();
});
it('should keep OpenRouter OpenAI slugs on chat completions for provider payload normalization', async () => {
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index e446ca597e6..11387c7e0f8 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -61,6 +61,12 @@ import {
ContextExceededPreFlightError,
} from '../../utils/resolveSafeMaxTokens';
import { StreamingResponse } from '../../utils/response';
+import {
+ createSignatureChannelId,
+ createSignatureScope,
+ getRuntimeSignatureScopeSource,
+ type SignatureScopeKind,
+} from '../../utils/signatureScope';
import type { LobeRuntimeAI } from '../BaseAI';
import { normalizeToolsParameters } from '../contextBuilders/normalizeToolSchema';
import { convertOpenAIMessages, convertOpenAIResponseInputs } from '../contextBuilders/openai';
@@ -344,6 +350,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
private id: string;
private logPrefix: string;
private modelIdMappingOptions: ModelIdMappingOptions = {};
+ private subscriptionChannelId?: Promise<string>;
baseURL!: string;
protected _options: ConstructorOptions<T>;
@@ -375,9 +382,50 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
this.baseURL = baseURL || this.client.baseURL;
this.id = options.id || provider;
+ if (typeof inputOptions.chatgptAccountId === 'string') {
+ this.subscriptionChannelId = createSignatureChannelId(
+ 'chatgpt-account',
+ inputOptions.chatgptAccountId,
+ );
+ }
this.logPrefix = `lobe-model-runtime:${this.id}`;
}
+ /**
+ * Direct endpoints use an irreversible endpoint/credential fingerprint, while
+ * RouterRuntime injects its stable route and channel identity through a WeakMap.
+ */
+ private async getSignatureScope(
+ model: string,
+ kind: SignatureScopeKind,
+ protocol: 'chat_completions' | 'responses',
+ ) {
+ const runtimeSource = getRuntimeSignatureScopeSource(this);
+ let directChannelId: string | undefined;
+ if (!runtimeSource) {
+ if (this.subscriptionChannelId) {
+ directChannelId = await this.subscriptionChannelId;
+ } else if (this._options.apiKey) {
+ directChannelId = await createSignatureChannelId(this.baseURL, this._options.apiKey);
+ }
+ }
+
+ return createSignatureScope({
+ kind,
+ model,
+ protocol,
+ source:
+ runtimeSource ??
+ (directChannelId
+ ? {
+ apiType: 'openai',
+ channelId: directChannelId,
+ provider: this.id,
+ }
+ : undefined),
+ });
+ }
+
protected getMappedModelId(model: string) {
return resolveMappedModelId(model, this.modelIdMappingOptions);
}
@@ -657,10 +705,19 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
this.baseURL = targetBaseURL;
}
+ const requestModel =
+ this.withMappedRequestModel({ model: postPayload.model }, payload.model).model ??
+ payload.model;
+ const thoughtSignatureScope = await this.getSignatureScope(
+ requestModel,
+ 'thought_signature',
+ 'chat_completions',
+ );
const messages = await convertOpenAIMessages(postPayload.messages, {
forceImageBase64: chatCompletion?.forceImageBase64,
forceVideoBase64: chatCompletion?.forceVideoBase64,
model: postPayload.model,
+ thoughtSignatureScope,
});
const includeUsageRequested = Boolean(postPayload.stream && !chatCompletion?.excludeUsage);
@@ -675,6 +732,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
model: payload.model,
pricing: await getModelPricing(payload.model, this.id, options?.pricingContext),
provider: this.id,
+ thoughtSignatureScope,
},
};
@@ -1421,6 +1479,13 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
responses?.handlePayload
? (responses?.handlePayload(payload, this._options) as ChatStreamPayload)
: payload;
+ const requestModel =
+ this.withMappedRequestModel({ model: res.model }, usageModel).model ?? usageModel;
+ const reasoningSignatureScope = await this.getSignatureScope(
+ requestModel,
+ 'reasoning',
+ 'responses',
+ );
// remove penalty params and chat completion specific params
delete res.apiMode;
@@ -1432,6 +1497,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
forceImageBase64: chatCompletion?.forceImageBase64,
forceVideoBase64: chatCompletion?.forceVideoBase64,
provider: this.id,
+ reasoningSignatureScope,
strictToolPairing: true,
});
@@ -1496,6 +1562,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
model: usageModel,
pricing: await getModelPricing(usageModel, this.id, options?.pricingContext),
provider: this.id,
+ reasoningSignatureScope,
},
};
@@ -1577,13 +1644,20 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
model,
responseApi,
});
+ const requestModel = this.getMappedModelId(payload.model);
if (shouldUseResponses) {
log('calling responses.create for tool calling');
+ const reasoningSignatureScope = await this.getSignatureScope(
+ requestModel,
+ 'reasoning',
+ 'responses',
+ );
const input = await convertOpenAIResponseInputs(messages as any, {
forceImageBase64: chatCompletion?.forceImageBase64,
forceVideoBase64: chatCompletion?.forceVideoBase64,
provider: this.id,
+ reasoningSignatureScope,
strictToolPairing: true,
});
@@ -1636,7 +1710,17 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
}
log('calling chat.completions.create for tool calling');
- const msgs = messages;
+ const thoughtSignatureScope = await this.getSignatureScope(
+ requestModel,
+ 'thought_signature',
+ 'chat_completions',
+ );
+ const msgs = await convertOpenAIMessages(messages as any, {
+ forceImageBase64: chatCompletion?.forceImageBase64,
+ forceVideoBase64: chatCompletion?.forceVideoBase64,
+ model,
+ thoughtSignatureScope,
+ });
const res = await this.client.chat.completions.create(
this.withMappedRequestModel(
diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
index 1b200fc3498..ccb32c74c13 100644
--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
@@ -1,9 +1,14 @@
import type { GenerateContentResponse } from '@google/genai';
import { describe, expect, it, vi } from 'vitest';
+import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
import * as uuidModule from '../../../utils/uuid';
import { GoogleGenerativeAIStream, LOBE_ERROR_KEY } from './index';
+const thoughtSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+const scopedThoughtSignature = (signature: string) =>
+ serializeScopedSignature(signature, thoughtSignatureScope, 'thought_signature')!;
+
/**
* Helper function to decode stream chunks into string array
*/
@@ -1224,7 +1229,9 @@ describe('GoogleGenerativeAIStream', () => {
},
});
- const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
+ payload: { thoughtSignatureScope },
+ });
const chunks = await decodeStreamChunks(protocolStream);
@@ -1232,7 +1239,7 @@ describe('GoogleGenerativeAIStream', () => {
[
'id: chat_1',
'event: tool_calls',
- 'data: [{"function":{"arguments":"{\\"query\\":\\"\\\\\\"version\\\\\\":\\",\\"repo\\":\\"lobehub/lobe-chat\\",\\"path\\":\\"package.json\\"}","name":"grep____searchGitHub____mcp"},"id":"call_search_1","index":0,"thoughtSignature":"123","type":"function"}]\n',
+ `data: [{"function":{"arguments":"{\\"query\\":\\"\\\\\\"version\\\\\\":\\",\\"repo\\":\\"lobehub/lobe-chat\\",\\"path\\":\\"package.json\\"}","name":"grep____searchGitHub____mcp"},"id":"call_search_1","index":0,"thoughtSignature":"${scopedThoughtSignature('123')}","type":"function"}]\n`,
'id: chat_1',
'event: stop',
@@ -1362,7 +1369,9 @@ describe('GoogleGenerativeAIStream', () => {
},
});
- const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
+ payload: { thoughtSignatureScope },
+ });
const chunks = await decodeStreamChunks(protocolStream);
@@ -1370,7 +1379,7 @@ describe('GoogleGenerativeAIStream', () => {
[
'id: chat_1',
'event: tool_calls',
- 'data: [{"function":{"arguments":"{\\"location\\":\\"Paris\\"}","name":"get_current_temperature"},"id":"get_current_temperature_0_abcd1234","index":0,"thoughtSignature":"ErEDCq4DAdHtim...","type":"function"}]\n',
+ `data: [{"function":{"arguments":"{\\"location\\":\\"Paris\\"}","name":"get_current_temperature"},"id":"get_current_temperature_0_abcd1234","index":0,"thoughtSignature":"${scopedThoughtSignature('ErEDCq4DAdHtim...')}","type":"function"}]\n`,
'id: chat_1',
'event: tool_calls',
@@ -1524,7 +1533,9 @@ describe('GoogleGenerativeAIStream', () => {
},
});
- const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
+ payload: { thoughtSignatureScope },
+ });
const chunks = await decodeStreamChunks(protocolStream);
@@ -1539,7 +1550,7 @@ describe('GoogleGenerativeAIStream', () => {
// First tool call (createPlan)
'id: chat_test',
'event: tool_calls',
- 'data: [{"function":{"arguments":"{\\"goal\\":\\"Fix Linear API Argument Validation Error\\",\\"description\\":\\"Investigate the Linear API error.\\",\\"context\\":\\"The user is encountering a validation error.\\"}","name":"lobe-agent____createPlan"},"id":"lobe-agent____createPlan_0_tool_id_1","index":0,"thoughtSignature":"EoIYCv8XAXLI2nx+C18votz5l0A...","type":"function"}]\n',
+ `data: [{"function":{"arguments":"{\\"goal\\":\\"Fix Linear API Argument Validation Error\\",\\"description\\":\\"Investigate the Linear API error.\\",\\"context\\":\\"The user is encountering a validation error.\\"}","name":"lobe-agent____createPlan"},"id":"lobe-agent____createPlan_0_tool_id_1","index":0,"thoughtSignature":"${scopedThoughtSignature('EoIYCv8XAXLI2nx+C18votz5l0A...')}","type":"function"}]\n`,
// Second tool call (createTodos) - should be a SEPARATE event with index:0
'id: chat_test',
@@ -1758,7 +1769,7 @@ describe('GoogleGenerativeAIStream', () => {
});
describe('Thought filtering logic', () => {
- it('should keep text and thoughtSignature when both exist in parts', async () => {
+ it('should scope thoughtSignature across reasoning and content parts', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
const data = [
@@ -1767,6 +1778,11 @@ describe('GoogleGenerativeAIStream', () => {
{
content: {
parts: [
+ {
+ text: 'Thinking',
+ thought: true,
+ thoughtSignature: 'thought-sig',
+ },
{
text: 'Here is my answer',
thoughtSignature: 'sig123',
@@ -1797,14 +1813,20 @@ describe('GoogleGenerativeAIStream', () => {
},
});
- const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
+ payload: { thoughtSignatureScope },
+ });
const chunks = await decodeStreamChunks(protocolStream);
expect(chunks).toEqual(
[
+ 'id: chat_1',
+ 'event: reasoning_part',
+ `data: {"content":"Thinking","inReasoning":true,"partType":"text","thoughtSignature":"${scopedThoughtSignature('thought-sig')}"}\n`,
+
'id: chat_1',
'event: content_part',
- 'data: {"content":"Here is my answer","partType":"text","thoughtSignature":"sig123"}\n',
+ `data: {"content":"Here is my answer","partType":"text","thoughtSignature":"${scopedThoughtSignature('sig123')}"}\n`,
'id: chat_1',
'event: stop',
@@ -1816,6 +1838,38 @@ describe('GoogleGenerativeAIStream', () => {
].map((i) => i + '\n'),
);
});
+
+ it('should omit thoughtSignature from parts when no scope is available', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ candidates: [
+ {
+ content: {
+ parts: [{ text: 'Here is my answer', thoughtSignature: 'sig123' }],
+ role: 'model',
+ },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ candidatesTokenCount: 4,
+ promptTokenCount: 3,
+ totalTokenCount: 7,
+ },
+ });
+ controller.close();
+ },
+ });
+
+ const chunks = await decodeStreamChunks(GoogleGenerativeAIStream(mockGoogleStream));
+
+ expect(chunks).toContain('data: {"content":"Here is my answer","partType":"text"}\n\n');
+ expect(chunks.join('')).not.toContain('sig123');
+ });
});
describe('Multimodal parts (reasoning_part and content_part)', () => {
@@ -2006,7 +2060,9 @@ describe('GoogleGenerativeAIStream', () => {
},
});
- const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
+ payload: { thoughtSignatureScope },
+ });
const chunks = await decodeStreamChunks(protocolStream);
expect(chunks).toEqual(
@@ -2044,7 +2100,7 @@ describe('GoogleGenerativeAIStream', () => {
// Content image (with thoughtSignature but not thought:true)
'id: chat_1',
'event: content_part',
- 'data: {"content":"/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAEBAQEBAQEBA2Q==","mimeType":"image/jpeg","partType":"image","thoughtSignature":"EueybArjsmwB0e2Kby+QPRkacnmPuV+CqMr6tiey3M5BHLHgIiggQOMeFmnKzsoux6PI6dQMgmdbXE1OTLLcWUmUD1CgFn+C2VdI09FpHrVhxVAtSk/zFVSlsjfCuANxtkP8tCDppVZqIya0QYjzg5K1fEO0m42CZX2/MHyqL8NjzR0lT8ENdoV3RSaK2tXqPH45uIb6nGeBSuX1n2EUMzO"}\n',
+ `data: {"content":"/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAEBAQEBAQEBA2Q==","mimeType":"image/jpeg","partType":"image","thoughtSignature":"${scopedThoughtSignature('EueybArjsmwB0e2Kby+QPRkacnmPuV+CqMr6tiey3M5BHLHgIiggQOMeFmnKzsoux6PI6dQMgmdbXE1OTLLcWUmUD1CgFn+C2VdI09FpHrVhxVAtSk/zFVSlsjfCuANxtkP8tCDppVZqIya0QYjzg5K1fEO0m42CZX2/MHyqL8NjzR0lT8ENdoV3RSaK2tXqPH45uIb6nGeBSuX1n2EUMzO')}"}\n`,
// stop
'id: chat_1',
diff --git a/packages/model-runtime/src/core/streams/google/index.ts b/packages/model-runtime/src/core/streams/google/index.ts
index 88fe37e6688..a53c1e73a6f 100644
--- a/packages/model-runtime/src/core/streams/google/index.ts
+++ b/packages/model-runtime/src/core/streams/google/index.ts
@@ -2,6 +2,7 @@ import type { GenerateContentResponse, Part } from '@google/genai';
import type { GroundingSearch } from '@lobechat/types';
import type { ChatStreamCallbacks } from '../../../types';
+import { serializeScopedSignature } from '../../../utils/signatureScope';
import { nanoid } from '../../../utils/uuid';
import { convertGoogleAIUsage } from '../../usageConverters/google-ai';
import type {
@@ -79,6 +80,8 @@ const transformGoogleGenerativeAIStream = (
// maybe need another structure to add support for multiple choices
const candidate = chunk.candidates?.[0];
const { usageMetadata } = chunk;
+ const serializeThoughtSignature = (signature?: string) =>
+ serializeScopedSignature(signature, payload?.thoughtSignatureScope, 'thought_signature');
// Handle blocked terminal candidate finishReason (e.g., PROHIBITED_CONTENT, SAFETY)
const blockedReason = getCandidateBlockedReason(candidate);
@@ -136,7 +139,7 @@ const transformGoogleGenerativeAIStream = (
?.filter((part: any) => part.functionCall)
.map((part: Part) => ({
...part.functionCall,
- thoughtSignature: part.thoughtSignature,
+ thoughtSignature: serializeThoughtSignature(part.thoughtSignature),
})) || [];
if (functionCalls.length > 0) {
@@ -224,7 +227,7 @@ const transformGoogleGenerativeAIStream = (
content: part.text,
inReasoning: true,
partType: 'text',
- thoughtSignature: part.thoughtSignature,
+ thoughtSignature: serializeThoughtSignature(part.thoughtSignature),
} as StreamPartChunkData,
id: context.id,
type: 'reasoning_part',
@@ -239,7 +242,7 @@ const transformGoogleGenerativeAIStream = (
inReasoning: true,
mimeType: part.inlineData.mimeType,
partType: 'image',
- thoughtSignature: part.thoughtSignature,
+ thoughtSignature: serializeThoughtSignature(part.thoughtSignature),
} as StreamPartChunkData,
id: context.id,
type: 'reasoning_part',
@@ -252,7 +255,7 @@ const transformGoogleGenerativeAIStream = (
data: {
content: part.text,
partType: 'text',
- thoughtSignature: part.thoughtSignature,
+ thoughtSignature: serializeThoughtSignature(part.thoughtSignature),
} as StreamPartChunkData,
id: context.id,
type: 'content_part',
@@ -266,7 +269,7 @@ const transformGoogleGenerativeAIStream = (
content: part.inlineData.data,
mimeType: part.inlineData.mimeType,
partType: 'image',
- thoughtSignature: part.thoughtSignature,
+ thoughtSignature: serializeThoughtSignature(part.thoughtSignature),
} as StreamPartChunkData,
id: context.id,
type: 'content_part',
diff --git a/packages/model-runtime/src/core/streams/openai/openai.test.ts b/packages/model-runtime/src/core/streams/openai/openai.test.ts
index 77e70e6576e..0bb96e90140 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.test.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import { AgentRuntimeErrorType } from '../../../types/error';
+import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
import { FIRST_CHUNK_ERROR_KEY } from '../protocol';
import { OpenAIStream } from './openai';
@@ -1195,11 +1196,18 @@ describe('OpenAIStream', () => {
});
const onToolCallMock = vi.fn();
+ const thoughtSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const persistedSignature = serializeScopedSignature(
+ 'ErEDCq4DAdHtim...',
+ thoughtSignatureScope,
+ 'thought_signature',
+ )!;
const protocolStream = OpenAIStream(mockOpenAIStream, {
callbacks: {
onToolsCalling: onToolCallMock,
},
+ payload: { thoughtSignatureScope },
});
const decoder = new TextDecoder();
@@ -1214,7 +1222,7 @@ describe('OpenAIStream', () => {
'id: or-123\n',
'event: tool_calls\n',
// thoughtSignature should be preserved in the output
- `data: [{"function":{"arguments":"{}","name":"github__get_me"},"id":"call_123","index":0,"type":"function","thoughtSignature":"ErEDCq4DAdHtim..."}]\n\n`,
+ `data: [{"function":{"arguments":"{}","name":"github__get_me"},"id":"call_123","index":0,"type":"function","thoughtSignature":"${persistedSignature}"}]\n\n`,
]);
// Verify the callback receives thoughtSignature
@@ -1224,7 +1232,7 @@ describe('OpenAIStream', () => {
function: { arguments: '{}', name: 'github__get_me' },
id: 'call_123',
index: 0,
- thoughtSignature: 'ErEDCq4DAdHtim...',
+ thoughtSignature: persistedSignature,
type: 'function',
},
],
@@ -1232,7 +1240,7 @@ describe('OpenAIStream', () => {
{
function: { arguments: '{}', name: 'github__get_me' },
id: 'call_123',
- thoughtSignature: 'ErEDCq4DAdHtim...',
+ thoughtSignature: persistedSignature,
type: 'function',
},
],
diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.ts
index f5ce717495b..75379023ba5 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.ts
@@ -6,6 +6,7 @@ import type { ChatStreamCallbacks } from '../../../types';
import type { ILobeAgentRuntimeErrorType } from '../../../types/error';
import { AgentRuntimeErrorType } from '../../../types/error';
import { isErrorCausedByContentFilter } from '../../../utils/isErrorCausedByContentFilter';
+import { serializeScopedSignature } from '../../../utils/signatureScope';
import { convertOpenAIUsage } from '../../usageConverters';
import type {
ChatPayloadForTransformStream,
@@ -249,7 +250,11 @@ const transformOpenAIStream = (
// OpenRouter returns thoughtSignature in tool_calls for Gemini models (e.g. gemini-3-flash-preview)
// [{"id":"call_123","type":"function","function":{"name":"get_weather","arguments":"{}"},"thoughtSignature":"abc123"}]
if (hasThoughtSignature(value)) {
- baseData.thoughtSignature = value.thoughtSignature;
+ baseData.thoughtSignature = serializeScopedSignature(
+ value.thoughtSignature,
+ payload?.thoughtSignatureScope,
+ 'thought_signature',
+ );
}
return baseData;
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
index 9bd30920783..8f1504d8bd3 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import { AgentRuntimeErrorType } from '../../../types/error';
+import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
import { FIRST_CHUNK_ERROR_KEY } from '../protocol';
import { createReadableStream, readStreamChunk } from '../utils';
import { OpenAIResponsesStream } from './responsesStream';
@@ -710,6 +711,7 @@ describe('OpenAIResponsesStream', () => {
});
it('should emit encrypted reasoning content as a reasoning signature', async () => {
+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
const mockOpenAIStream = createReadableStream([
{
type: 'response.created',
@@ -730,11 +732,38 @@ describe('OpenAIResponsesStream', () => {
},
]);
- const protocolStream = OpenAIResponsesStream(mockOpenAIStream);
+ const protocolStream = OpenAIResponsesStream(mockOpenAIStream, {
+ payload: { reasoningSignatureScope },
+ });
const chunks = await readStreamChunk(protocolStream);
+ const persistedSignature = serializeScopedSignature(
+ 'encrypted-reasoning-content',
+ reasoningSignatureScope,
+ 'reasoning',
+ )!;
expect(chunks.some((chunk) => chunk.includes('event: reasoning_signature'))).toBe(true);
- expect(chunks.some((chunk) => chunk.includes('encrypted-reasoning-content'))).toBe(true);
+ expect(chunks.some((chunk) => chunk.includes(persistedSignature))).toBe(true);
+ });
+
+ it('should omit encrypted reasoning content without a stable scope', async () => {
+ const mockOpenAIStream = createReadableStream([
+ {
+ type: 'response.output_item.done',
+ output_index: 0,
+ item: {
+ encrypted_content: 'encrypted-reasoning-content',
+ id: 'reasoning_item',
+ summary: [],
+ type: 'reasoning',
+ },
+ },
+ ]);
+
+ const chunks = await readStreamChunk(OpenAIResponsesStream(mockOpenAIStream));
+
+ expect(chunks.some((chunk) => chunk.includes('event: reasoning_signature'))).toBe(false);
+ expect(chunks.some((chunk) => chunk.includes('encrypted-reasoning-content'))).toBe(false);
});
it('should handle response.completed with usage', async () => {
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.ts
index 9f67f381b54..f60645019de 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts
+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts
@@ -3,6 +3,7 @@ import type OpenAI from 'openai';
import type { Stream } from 'openai/streaming';
import { AgentRuntimeErrorType } from '../../../types/error';
+import { serializeScopedSignature } from '../../../utils/signatureScope';
import { convertOpenAIResponseUsage } from '../../usageConverters';
import type {
ChatPayloadForTransformStream,
@@ -147,8 +148,15 @@ const transformOpenAIStream = (
case 'response.output_item.done': {
if (chunk.item.type === 'reasoning' && chunk.item.encrypted_content) {
+ const signature = serializeScopedSignature(
+ chunk.item.encrypted_content,
+ payload?.reasoningSignatureScope,
+ 'reasoning',
+ );
+ if (!signature) return { data: null, id: chunk.item.id, type: 'text' };
+
return {
- data: chunk.item.encrypted_content,
+ data: signature,
id: chunk.item.id,
type: 'reasoning_signature',
};
diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.ts
index 7686a085dc4..1e99f7618eb 100644
--- a/packages/model-runtime/src/core/streams/protocol.ts
+++ b/packages/model-runtime/src/core/streams/protocol.ts
@@ -5,6 +5,7 @@ import { parseToolCalls } from '../../helpers';
import type { ChatStreamCallbacks, OnFinishData, UsageMissingDiagnostics } from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
import { safeParseJSON } from '../../utils/safeParseJSON';
+import type { SignatureScope } from '../../utils/signatureScope';
import { nanoid } from '../../utils/uuid';
import type { ComputeChatCostOptions } from '../usageConverters/utils/computeChatCost';
@@ -15,6 +16,8 @@ export type ChatPayloadForTransformStream = {
pricing?: Pricing;
pricingOptions?: ComputeChatCostOptions;
provider?: string;
+ reasoningSignatureScope?: SignatureScope;
+ thoughtSignatureScope?: SignatureScope;
};
/**
diff --git a/packages/model-runtime/src/providers/githubCopilot/index.test.ts b/packages/model-runtime/src/providers/githubCopilot/index.test.ts
index 0069180444d..cc3ee67ef54 100644
--- a/packages/model-runtime/src/providers/githubCopilot/index.test.ts
+++ b/packages/model-runtime/src/providers/githubCopilot/index.test.ts
@@ -41,6 +41,9 @@ describe('LobeGithubCopilotAI', () => {
expect(convertResponseInputsSpy).toHaveBeenCalledWith(expect.any(Array), {
forceImageBase64: true,
+ reasoningSignatureScope: {
+ fingerprint: expect.stringMatching(/^[\da-f]{32}$/),
+ },
strictToolPairing: true,
});
});
@@ -66,8 +69,42 @@ describe('LobeGithubCopilotAI', () => {
expect(convertMessagesSpy).toHaveBeenCalledWith(expect.any(Array), {
forceImageBase64: true,
+ thoughtSignatureScope: {
+ fingerprint: expect.stringMatching(/^[\da-f]{32}$/),
+ },
});
});
+
+ it('should bind signature scopes to the Copilot account', async () => {
+ const convertMessagesSpy = vi
+ .spyOn(openAIContextBuilders, 'convertOpenAIMessages')
+ .mockRejectedValue({ status: 400 });
+ const futureTime = Date.now() + 600_000;
+
+ for (const oauthAccessToken of ['ghu_account_a', 'ghu_account_b']) {
+ const instance = new LobeGithubCopilotAI({
+ bearerToken: 'cached-bearer-token',
+ bearerTokenExpiresAt: futureTime,
+ oauthAccessToken,
+ });
+
+ await expect(
+ instance.chat({
+ messages: [{ content: 'hello', role: 'user' }],
+ model: 'gpt-4o',
+ } as any),
+ ).rejects.toBeDefined();
+ }
+
+ const fingerprints = convertMessagesSpy.mock.calls.map(
+ ([, options]) => options?.thoughtSignatureScope?.fingerprint,
+ );
+ expect(fingerprints[0]).toMatch(/^[\da-f]{32}$/);
+ expect(fingerprints[1]).toMatch(/^[\da-f]{32}$/);
+ expect(fingerprints[0]).not.toBe(fingerprints[1]);
+ expect(fingerprints).not.toContain('ghu_account_a');
+ expect(fingerprints).not.toContain('ghu_account_b');
+ });
});
describe('constructor', () => {
diff --git a/packages/model-runtime/src/providers/githubCopilot/index.ts b/packages/model-runtime/src/providers/githubCopilot/index.ts
index aaf1a70bb88..793bf16d13d 100644
--- a/packages/model-runtime/src/providers/githubCopilot/index.ts
+++ b/packages/model-runtime/src/providers/githubCopilot/index.ts
@@ -18,6 +18,11 @@ import { AgentRuntimeError } from '../../utils/createError';
import { debugPayload, debugResponse, debugStream } from '../../utils/debugStream';
import { getModelPricing } from '../../utils/getModelPricing';
import { StreamingResponse } from '../../utils/response';
+import {
+ createSignatureChannelId,
+ createSignatureScope,
+ type SignatureScopeKind,
+} from '../../utils/signatureScope';
import { assertToolLimits } from '../../utils/validateToolLimits';
import { isResponsesAPIModel } from '../openai/modelId';
@@ -138,6 +143,7 @@ export interface LobeGithubCopilotAIParams {
export class LobeGithubCopilotAI implements LobeRuntimeAI {
baseURL = COPILOT_BASE_URL;
+ private accountChannelId?: Promise<string>;
private cachedBearerToken?: string;
private githubToken: string;
@@ -166,6 +172,28 @@ export class LobeGithubCopilotAI implements LobeRuntimeAI {
}
}
+ private async getSignatureScope(
+ model: string,
+ kind: SignatureScopeKind,
+ protocol: 'chat_completions' | 'responses',
+ ) {
+ const accountToken = this.githubToken || this.cachedBearerToken;
+ if (!accountToken) return undefined;
+
+ this.accountChannelId ??= createSignatureChannelId('github-copilot-account', accountToken);
+
+ return createSignatureScope({
+ kind,
+ model,
+ protocol,
+ source: {
+ apiType: 'openai',
+ channelId: await this.accountChannelId,
+ provider: ModelProvider.GithubCopilot,
+ },
+ });
+ }
+
async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {
// Pre-flight: abort before dispatching if tools exceed the Copilot 128-tool limit
if (payload.tools && payload.tools.length > 0) {
@@ -281,8 +309,14 @@ export class LobeGithubCopilotAI implements LobeRuntimeAI {
...responseRest
} = rest as any;
+ const reasoningSignatureScope = await this.getSignatureScope(
+ model,
+ 'reasoning',
+ 'responses',
+ );
const input = await convertOpenAIResponseInputs(messages as any, {
forceImageBase64: true,
+ reasoningSignatureScope,
strictToolPairing: true,
});
@@ -328,7 +362,11 @@ export class LobeGithubCopilotAI implements LobeRuntimeAI {
return StreamingResponse(
OpenAIResponsesStream(prod, {
callbacks: options?.callback,
- payload: { model, provider: ModelProvider.GithubCopilot },
+ payload: {
+ model,
+ provider: ModelProvider.GithubCopilot,
+ reasoningSignatureScope,
+ },
}),
{ headers: options?.headers },
);
@@ -344,15 +382,25 @@ export class LobeGithubCopilotAI implements LobeRuntimeAI {
OpenAIResponsesStream(responseStream, {
callbacks: options?.callback,
enableStreaming: false,
- payload: { model, provider: ModelProvider.GithubCopilot },
+ payload: {
+ model,
+ provider: ModelProvider.GithubCopilot,
+ reasoningSignatureScope,
+ },
}),
{ headers: options?.headers },
);
}
const { apiMode: _, preserveThinking: _pt, ...cleanedRest } = rest as any;
+ const thoughtSignatureScope = await this.getSignatureScope(
+ model,
+ 'thought_signature',
+ 'chat_completions',
+ );
const messages = await convertOpenAIMessages(cleanedRest.messages as any, {
forceImageBase64: true,
+ thoughtSignatureScope,
});
const chatCompletionPayload = {
@@ -386,7 +434,7 @@ export class LobeGithubCopilotAI implements LobeRuntimeAI {
return StreamingResponse(
OpenAIStream(response, {
callbacks: options?.callback,
- payload: { model, provider: ModelProvider.GithubCopilot },
+ payload: { model, provider: ModelProvider.GithubCopilot, thoughtSignatureScope },
}),
{ headers: options?.headers },
);
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index feb2210a279..63e1aa8293f 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -1,14 +1,20 @@
// @vitest-environment node
-import type { GenerateContentResponse } from '@google/genai';
+import type { Content, GenerateContentResponse } from '@google/genai';
import OpenAI from 'openai';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LOBE_ERROR_KEY } from '../../core/streams';
import { AgentRuntimeErrorType } from '../../types/error';
import * as debugStreamModule from '../../utils/debugStream';
+import {
+ createSignatureChannelId,
+ createSignatureScope,
+ serializeScopedSignature,
+} from '../../utils/signatureScope';
import { LobeGoogleAI } from './index';
const provider = 'google';
+const defaultBaseURL = 'https://generativelanguage.googleapis.com';
const bizErrorType = 'ProviderBizError';
const invalidErrorType = 'InvalidProviderAPIKey';
const getModelPricingMock = vi.hoisted(() => vi.fn());
@@ -21,6 +27,26 @@ async function* createEmptyAsyncGenerator<T>(): AsyncGenerator<T> {
yield* [] as unknown as T[];
}
+const createGoogleThoughtSignatureScope = async ({
+ apiKey = 'test',
+ baseURL = defaultBaseURL,
+ model = 'gemini-upstream',
+}: {
+ apiKey?: string;
+ baseURL?: string;
+ model?: string;
+} = {}) =>
+ createSignatureScope({
+ kind: 'thought_signature',
+ model,
+ protocol: 'google_generate_content',
+ source: {
+ apiType: 'google',
+ channelId: await createSignatureChannelId(baseURL, apiKey),
+ provider: 'google',
+ },
+ });
+
// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -72,17 +98,122 @@ describe('LobeGoogleAI', () => {
mockStreamData,
);
+ const thoughtSignatureScope = await createGoogleThoughtSignatureScope();
await mappedInstance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
+ messages: [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'search' },
+ id: 'call-1',
+ thoughtSignature: serializeScopedSignature(
+ 'upstream-signature',
+ thoughtSignatureScope,
+ 'thought_signature',
+ ),
+ type: 'function',
+ },
+ ],
+ },
+ { content: '{}', role: 'tool', tool_call_id: 'call-1' },
+ { content: 'Hello', role: 'user' },
+ ],
model: 'gemini-logical',
temperature: 0,
});
const callArgs = (mappedInstance['client'].models.generateContentStream as any).mock.calls[0];
expect(callArgs[0].model).toBe('gemini-upstream');
+ expect(callArgs[0].contents[0].parts[0].thoughtSignature).toBe('upstream-signature');
expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical', provider, undefined);
});
+ it.each([
+ { apiKey: 'another-key', baseURL: defaultBaseURL, label: 'credential' },
+ { apiKey: 'test', baseURL: 'https://another.example.com', label: 'endpoint' },
+ ])('should reject a thought signature from another direct $label', async (source) => {
+ const directInstance = new LobeGoogleAI({ apiKey: 'test' });
+ const generateContentStream = vi
+ .spyOn(directInstance['client'].models, 'generateContentStream')
+ .mockResolvedValue(createEmptyAsyncGenerator<GenerateContentResponse>());
+ const sourceScope = await createGoogleThoughtSignatureScope(source);
+
+ await directInstance.chat({
+ messages: [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'search' },
+ id: 'call-1',
+ thoughtSignature: serializeScopedSignature(
+ 'foreign-signature',
+ sourceScope,
+ 'thought_signature',
+ ),
+ type: 'function',
+ },
+ ],
+ },
+ ],
+ model: 'gemini-upstream',
+ temperature: 0,
+ });
+
+ const contents = generateContentStream.mock.calls[0][0].contents as Content[];
+ expect(contents[0]?.parts?.[0]?.thoughtSignature).not.toBe('foreign-signature');
+ });
+
+ it('should fail closed for a direct Vertex client without a stable channel identity', async () => {
+ const generateContentStream = vi
+ .fn()
+ .mockResolvedValue(createEmptyAsyncGenerator<GenerateContentResponse>());
+ const vertexInstance = new LobeGoogleAI({
+ apiKey: 'avoid-error',
+ client: { models: { generateContentStream } } as any,
+ isVertexAi: true,
+ });
+ const sourceScope = await createSignatureScope({
+ kind: 'thought_signature',
+ model: 'gemini-upstream',
+ protocol: 'google_generate_content',
+ source: {
+ apiType: 'vertexai',
+ channelId: 'configured-vertex-channel',
+ provider: 'vertexai',
+ },
+ });
+
+ await vertexInstance.chat({
+ messages: [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'search' },
+ id: 'call-1',
+ thoughtSignature: serializeScopedSignature(
+ 'vertex-signature',
+ sourceScope,
+ 'thought_signature',
+ ),
+ type: 'function',
+ },
+ ],
+ },
+ ],
+ model: 'gemini-upstream',
+ temperature: 0,
+ });
+
+ const contents = generateContentStream.mock.calls[0][0].contents as Content[];
+ expect(contents[0]?.parts?.[0]?.thoughtSignature).not.toBe('vertex-signature');
+ });
+
it('should apply upstream model compatibility after model mapping', async () => {
const mappedInstance = new LobeGoogleAI({
apiKey: 'test',
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index 58ab94013b4..c461a747a39 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -32,6 +32,11 @@ import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
import { withMappedModelId } from '../../utils/modelIdMapping';
import { StreamingResponse } from '../../utils/response';
+import {
+ createSignatureChannelId,
+ createSignatureScope,
+ getRuntimeSignatureScopeSource,
+} from '../../utils/signatureScope';
import { createGoogleImage } from './createImage';
import { createGoogleVideo, pollGoogleVideoOperation } from './createVideo';
import { createGoogleGenerateObject, createGoogleGenerateObjectWithTools } from './generateObject';
@@ -148,6 +153,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {
const { model, thinkingBudget, thinkingLevel, imageAspectRatio, imageResolution } = payload;
const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);
const requestModel = requestPayload.model;
+ const thoughtSignatureScope = await this.getThoughtSignatureScope(requestModel);
const shouldOmitDeprecatedGenerationParams =
shouldOmitDeprecatedGoogleGenerationParams(requestModel);
@@ -159,7 +165,10 @@ export class LobeGoogleAI implements LobeRuntimeAI {
thinkingLevel,
}) as unknown as ThinkingConfig;
- const contents = await buildGoogleMessages(payload.messages, { model: requestModel });
+ const contents = await buildGoogleMessages(payload.messages, {
+ model: requestModel,
+ thoughtSignatureScope,
+ });
if (shouldOmitDeprecatedGenerationParams) {
// Gemini 3.6 Flash, 3.5 Flash-Lite, and later models reject assistant prefills.
while (contents.at(-1)?.role === 'model') contents.pop();
@@ -265,7 +274,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {
const stream = GoogleGenerativeAIStream(prod, {
callbacks: options?.callback,
inputStartAt,
- payload: { model, pricing, provider: this.provider },
+ payload: { model, pricing, provider: this.provider, thoughtSignatureScope },
});
// Respond with the stream
@@ -355,10 +364,14 @@ export class LobeGoogleAI implements LobeRuntimeAI {
* @see https://ai.google.dev/gemini-api/docs/function-calling
*/
async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
+ const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);
+
// Convert OpenAI messages to Google format
- const contents = await buildGoogleMessages(payload.messages, { model: payload.model });
+ const contents = await buildGoogleMessages(payload.messages, {
+ model: requestPayload.model,
+ thoughtSignatureScope: await this.getThoughtSignatureScope(requestPayload.model),
+ });
const pricing = await getModelPricing(payload.model, this.provider, options?.pricingContext);
- const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);
// Handle tools-based structured output
if (payload.tools && payload.tools.length > 0) {
@@ -383,6 +396,34 @@ export class LobeGoogleAI implements LobeRuntimeAI {
return undefined;
}
+ /**
+ * Direct Gemini endpoints use an irreversible endpoint/credential fingerprint.
+ * Injected Vertex clients have no stable identity and therefore fail closed unless
+ * RouterRuntime supplied a channel.
+ */
+ private async getThoughtSignatureScope(model: string) {
+ const runtimeSource = getRuntimeSignatureScopeSource(this);
+ const directChannelId =
+ runtimeSource || !this.baseURL || !this.apiKey
+ ? undefined
+ : await createSignatureChannelId(this.baseURL, this.apiKey);
+
+ return createSignatureScope({
+ kind: 'thought_signature',
+ model,
+ protocol: 'google_generate_content',
+ source:
+ runtimeSource ??
+ (directChannelId
+ ? {
+ apiType: this.isVertexAi ? 'vertexai' : 'google',
+ channelId: directChannelId,
+ provider: this.provider,
+ }
+ : undefined),
+ });
+ }
+
private createEnhancedStream(originalStream: any, signal: AbortSignal): ReadableStream {
// capture provider for error payloads inside the stream closure
const provider = this.provider;
diff --git a/packages/model-runtime/src/utils/signatureScope.test.ts b/packages/model-runtime/src/utils/signatureScope.test.ts
new file mode 100644
index 00000000000..378d72bfd68
--- /dev/null
+++ b/packages/model-runtime/src/utils/signatureScope.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createSignatureChannelId,
+ createSignatureScope,
+ resolveScopedSignature,
+ serializeScopedSignature,
+} from './signatureScope';
+
+const createScope = async (
+ overrides: Partial<{
+ apiType: string;
+ channelId: string;
+ kind: 'reasoning' | 'thought_signature';
+ model: string;
+ protocol: string;
+ provider: string;
+ routerId: string;
+ }> = {},
+) =>
+ createSignatureScope({
+ kind: overrides.kind ?? 'reasoning',
+ model: overrides.model ?? 'gpt-5.6-sol',
+ protocol: overrides.protocol ?? 'responses',
+ source: {
+ apiType: overrides.apiType ?? 'openai',
+ channelId: overrides.channelId ?? 'channel-a',
+ provider: overrides.provider ?? 'chatgpt',
+ routerId: overrides.routerId ?? 'router-a',
+ },
+ });
+
+describe('signatureScope', () => {
+ it('round-trips opaque state only within the exact scope', async () => {
+ const sourceScope = await createScope();
+ const value = serializeScopedSignature('encrypted-state', sourceScope, 'reasoning');
+
+ expect(resolveScopedSignature(value, await createScope(), 'reasoning')).toBe('encrypted-state');
+ expect(
+ resolveScopedSignature(value, await createScope({ model: 'gpt-5.6-terra' }), 'reasoning'),
+ ).toBeUndefined();
+ expect(
+ resolveScopedSignature(value, await createScope({ apiType: 'vertexai' }), 'reasoning'),
+ ).toBeUndefined();
+ expect(
+ resolveScopedSignature(
+ value,
+ await createScope({ protocol: 'chat_completions' }),
+ 'reasoning',
+ ),
+ ).toBeUndefined();
+ expect(
+ resolveScopedSignature(value, await createScope({ routerId: 'router-b' }), 'reasoning'),
+ ).toBeUndefined();
+ expect(
+ resolveScopedSignature(value, await createScope({ channelId: 'channel-b' }), 'reasoning'),
+ ).toBeUndefined();
+ });
+
+ it('separates reasoning state from thought signatures', async () => {
+ const reasoningScope = await createScope();
+ const value = serializeScopedSignature('encrypted-state', reasoningScope, 'reasoning');
+ const thoughtScope = await createScope({ kind: 'thought_signature' });
+
+ expect(resolveScopedSignature(value, thoughtScope, 'thought_signature')).toBeUndefined();
+ });
+
+ it('fails closed for missing channel identity and legacy values', async () => {
+ const scopeWithoutChannel = await createSignatureScope({
+ kind: 'reasoning',
+ model: 'gpt-5.6-sol',
+ protocol: 'responses',
+ source: {
+ apiType: 'openai',
+ provider: 'chatgpt',
+ },
+ });
+
+ expect(scopeWithoutChannel).toBeUndefined();
+ expect(serializeScopedSignature('encrypted-state', scopeWithoutChannel, 'reasoning')).toBe(
+ undefined,
+ );
+ expect(
+ resolveScopedSignature('legacy-encrypted-state', await createScope(), 'reasoning'),
+ ).toBeUndefined();
+ });
+
+ it('persists only irreversible fingerprints of endpoint and credentials', async () => {
+ const endpoint = 'https://example.com/v1';
+ const credential = 'secret-api-key';
+ const channelId = await createSignatureChannelId(endpoint, credential);
+ const scope = await createScope({ channelId });
+ const value = serializeScopedSignature('opaque-state', scope, 'reasoning')!;
+
+ expect(channelId).toMatch(/^[\da-f]{32}$/);
+ expect(value).not.toContain(endpoint);
+ expect(value).not.toContain(credential);
+ });
+});
diff --git a/packages/model-runtime/src/utils/signatureScope.ts b/packages/model-runtime/src/utils/signatureScope.ts
new file mode 100644
index 00000000000..007792805ae
--- /dev/null
+++ b/packages/model-runtime/src/utils/signatureScope.ts
@@ -0,0 +1,115 @@
+export type SignatureScopeKind = 'reasoning' | 'thought_signature';
+
+export interface SignatureScopeSource {
+ apiType: string;
+ channelId?: string;
+ provider: string;
+ routerId?: string;
+}
+
+export interface SignatureScope {
+ fingerprint: string;
+}
+
+const SCOPED_SIGNATURE_PREFIX = 'lobe-scoped-state-v1:';
+const SIGNATURE_SCOPE_FINGERPRINT_LENGTH = 32;
+
+/**
+ * Keep RouterRuntime provenance off constructor options so internal routing metadata
+ * cannot leak into provider SDKs through an options spread.
+ */
+const runtimeSignatureScopeSources = new WeakMap<object, SignatureScopeSource>();
+
+const createFingerprint = async (identityParts: string[]) => {
+ const digest = await crypto.subtle.digest(
+ 'SHA-256',
+ new TextEncoder().encode(JSON.stringify(identityParts)),
+ );
+
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0'))
+ .join('')
+ .slice(0, SIGNATURE_SCOPE_FINGERPRINT_LENGTH);
+};
+
+export const setRuntimeSignatureScopeSource = (runtime: object, source: SignatureScopeSource) => {
+ runtimeSignatureScopeSources.set(runtime, source);
+};
+
+export const getRuntimeSignatureScopeSource = (runtime: object) =>
+ runtimeSignatureScopeSources.get(runtime);
+
+/**
+ * Derive a stable channel identifier without persisting credentials or endpoint secrets.
+ */
+export const createSignatureChannelId = async (...identityParts: string[]) =>
+ createFingerprint(['channel', ...identityParts]);
+
+/**
+ * Build the persisted scope fingerprint from the complete replay boundary.
+ * Missing channel identity fails closed because provider and model alone cannot
+ * distinguish credentials, endpoints, subscription accounts, or router channels.
+ */
+export const createSignatureScope = async ({
+ kind,
+ model,
+ protocol,
+ source,
+}: {
+ kind: SignatureScopeKind;
+ model: string;
+ protocol: string;
+ source?: SignatureScopeSource;
+}): Promise<SignatureScope | undefined> => {
+ if (!source?.channelId) return undefined;
+
+ return {
+ fingerprint: await createFingerprint([
+ 'scope',
+ kind,
+ source.provider,
+ model,
+ source.apiType,
+ protocol,
+ source.routerId ?? '',
+ source.channelId,
+ ]),
+ };
+};
+
+/**
+ * Store opaque provider state in its existing string field while binding it to a
+ * compact, non-secret scope fingerprint.
+ */
+export const serializeScopedSignature = (
+ signature: string | undefined,
+ scope: SignatureScope | undefined,
+ kind: SignatureScopeKind,
+) => {
+ if (!signature || !scope) return undefined;
+
+ return `${SCOPED_SIGNATURE_PREFIX}${kind}:${scope.fingerprint}:${signature}`;
+};
+
+/**
+ * Restore opaque state only for an exact scope match. Legacy unscoped values and
+ * malformed envelopes are deliberately rejected instead of being replayed blindly.
+ */
+export const resolveScopedSignature = (
+ value: string | undefined,
+ scope: SignatureScope | undefined,
+ kind: SignatureScopeKind,
+) => {
+ if (!value || !scope) return undefined;
+
+ const prefix = `${SCOPED_SIGNATURE_PREFIX}${kind}:`;
+ if (!value.startsWith(prefix)) return undefined;
+
+ const fingerprintStart = prefix.length;
+ const fingerprintEnd = fingerprintStart + SIGNATURE_SCOPE_FINGERPRINT_LENGTH;
+ if (value[fingerprintEnd] !== ':') return undefined;
+
+ const fingerprint = value.slice(fingerprintStart, fingerprintEnd);
+ if (fingerprint !== scope.fingerprint) return undefined;
+
+ return value.slice(fingerprintEnd + 1) || undefined;
+};