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): sanitize replayed thinking history for anthropic-compatible providers (#17629)

YuTengjingb36a003ac5f6
diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.ts
index 406f2b3e9ad..b6b98fcc2c8 100644
--- a/packages/context-engine/src/processors/MessageContent.ts
+++ b/packages/context-engine/src/processors/MessageContent.ts
@@ -337,7 +337,12 @@ export class MessageContentProcessor extends BaseProcessor {
const contentParts: UserMessageContentPart[] = [
{
signature: message.reasoning!.signature,
- thinking: message.reasoning!.content,
+ // Signature-only reasoning (e.g. Claude 5 `thinking.display: 'omitted'`)
+ // has no thinking text. Emit an explicit empty string instead of
+ // `undefined`, which JSON serialization drops entirely β€” strict
+ // Anthropic-compatible endpoints (e.g. DeepSeek) reject thinking parts
+ // missing the `thinking` field with 400 `missing field 'thinking'`.
+ thinking: message.reasoning!.content ?? '',
type: 'thinking',
},
{
diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
index 743455b09a2..9c99a614afb 100644
--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
@@ -662,6 +662,46 @@ describe('MessageContentProcessor', () => {
},
]);
});
+
+ it('should serialize an explicit empty thinking string for signature-only reasoning', async () => {
+ const processor = new MessageContentProcessor({
+ model: 'claude-sonnet-5',
+ provider: 'anthropic',
+ isCanUseVision: mockIsCanUseVision,
+ fileContext: { enabled: false },
+ });
+
+ const messages: UIChatMessage[] = [
+ {
+ id: 'test',
+ role: 'assistant',
+ content: 'The answer is 42.',
+ // Claude 5 `thinking.display: 'omitted'` returns a signature without
+ // any thinking text β€” the replayed part must still carry the
+ // `thinking` key, otherwise JSON serialization drops it and strict
+ // Anthropic-compatible endpoints (e.g. DeepSeek) reject the request
+ // with 400 `missing field 'thinking'`.
+ reasoning: {
+ signature: 'signature-only',
+ },
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ const content = result.messages[0].content as any[];
+ expect(content[0]).toEqual({
+ signature: 'signature-only',
+ thinking: '',
+ type: 'thinking',
+ });
+ // Intentional JSON round-trip (not a deep clone): asserts the `thinking`
+ // key survives serialization the way the HTTP client would send it.
+ // eslint-disable-next-line unicorn/prefer-structured-clone
+ expect(JSON.parse(JSON.stringify(content[0]))).toHaveProperty('thinking', '');
+ });
});
describe('Message processing metadata', () => {
diff --git a/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts b/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts
index 15c6aa2ca2a..82e383c1e5e 100644
--- a/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts
+++ b/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts
@@ -44,3 +44,96 @@ describe('buildDeepSeekAnthropicPayload β€” completion budget', () => {
expect(payload.max_tokens).toBeLessThanOrEqual(393_216);
});
});
+
+describe('buildDeepSeekAnthropicPayload β€” thinking history normalization', () => {
+ const getAssistantMessages = (payload: any) =>
+ payload.messages.filter((m: any) => m.role === 'assistant');
+
+ // Regression for the production 400 `missing field 'thinking'`: signature-only
+ // reasoning (Claude 5 `thinking.display: 'omitted'`) reaches this builder as a
+ // context-engine thinking part whose `thinking` key vanishes on JSON
+ // serialization. DeepSeek's strict deserializer rejects it, so the part must
+ // be dropped and replaced by the proven `' '` placeholder.
+ it('drops signature-only thinking parts and falls back to the placeholder block', async () => {
+ const payload = await buildDeepSeekAnthropicPayload({
+ messages: [
+ { content: 'hi', role: 'user' },
+ {
+ content: [
+ { signature: 'claude-signature', type: 'thinking' },
+ { text: 'previous answer', type: 'text' },
+ ],
+ reasoning: { signature: 'claude-signature' },
+ role: 'assistant',
+ },
+ { content: 'continue', role: 'user' },
+ ],
+ model: 'deepseek-v4-pro',
+ } as any);
+
+ const [assistant] = getAssistantMessages(payload);
+ const thinkingParts = assistant.content.filter((p: any) => p.type === 'thinking');
+ expect(thinkingParts).toEqual([{ thinking: ' ', type: 'thinking' }]);
+ // Foreign signatures are not verifiable by DeepSeek and must never be forwarded.
+ expect(JSON.stringify(payload.messages)).not.toContain('claude-signature');
+ });
+
+ it('strips foreign signatures but keeps thinking text without duplicating blocks', async () => {
+ const payload = await buildDeepSeekAnthropicPayload({
+ messages: [
+ { content: 'hi', role: 'user' },
+ {
+ content: [
+ { signature: 'claude-signature', thinking: 'claude thoughts', type: 'thinking' },
+ { text: 'previous answer', type: 'text' },
+ ],
+ reasoning: { content: 'claude thoughts', signature: 'claude-signature' },
+ role: 'assistant',
+ },
+ { content: 'continue', role: 'user' },
+ ],
+ model: 'deepseek-v4-pro',
+ } as any);
+
+ const [assistant] = getAssistantMessages(payload);
+ const thinkingParts = assistant.content.filter((p: any) => p.type === 'thinking');
+ expect(thinkingParts).toEqual([{ thinking: 'claude thoughts', type: 'thinking' }]);
+ });
+
+ it('serializes every thinking part with a string thinking field', async () => {
+ const payload = await buildDeepSeekAnthropicPayload({
+ messages: [
+ { content: 'hi', role: 'user' },
+ {
+ content: [
+ { signature: 'sig-a', type: 'thinking' },
+ { text: 'a', type: 'text' },
+ ],
+ role: 'assistant',
+ },
+ { content: 'and then', role: 'user' },
+ {
+ content: 'plain answer',
+ reasoning: { content: '', signature: 'sig-b' },
+ role: 'assistant',
+ },
+ { content: 'continue', role: 'user' },
+ ],
+ model: 'deepseek-v4-pro',
+ } as any);
+
+ // Intentional JSON round-trip (not a deep clone) like the HTTP client does β€”
+ // this is where `thinking: undefined` used to disappear.
+ // eslint-disable-next-line unicorn/prefer-structured-clone
+ const serialized = JSON.parse(JSON.stringify(payload.messages));
+ for (const message of serialized) {
+ if (!Array.isArray(message.content)) continue;
+ for (const part of message.content) {
+ if (part.type !== 'thinking') continue;
+ expect(typeof part.thinking).toBe('string');
+ expect(part.thinking.length).toBeGreaterThan(0);
+ expect(part.signature).toBeUndefined();
+ }
+ }
+ });
+});
diff --git a/packages/model-runtime/src/providers/deepseek/chatPayload.ts b/packages/model-runtime/src/providers/deepseek/chatPayload.ts
index 422a687eb18..ffd698745ce 100644
--- a/packages/model-runtime/src/providers/deepseek/chatPayload.ts
+++ b/packages/model-runtime/src/providers/deepseek/chatPayload.ts
@@ -7,12 +7,16 @@ import type { ChatStreamPayload } from '../../types';
import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { isDeepSeekV4FamilyModel } from '../../utils/modelParse';
import { resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';
+import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';
import { sanitizeDeepSeekJsonPayload } from './sanitizePayload';
export const isDeepSeekV4Model = (model: string | undefined) => isDeepSeekV4FamilyModel(model);
const isEmptyContent = (content: unknown) =>
content === '' || content === null || content === undefined;
-const hasReasoningContent = (reasoning: any) => typeof reasoning?.content === 'string';
+// Require non-empty text: an empty-string `thinking` has never been validated
+// against DeepSeek β€” empty reasoning falls back to the proven `' '` placeholder.
+const hasReasoningContent = (reasoning: any) =>
+ typeof reasoning?.content === 'string' && reasoning.content !== '';
const buildThinkingBlock = (reasoning: any) =>
hasReasoningContent(reasoning)
@@ -78,9 +82,31 @@ const normalizeMessagesForAnthropic = (
if (message.role !== 'assistant') return message;
const { reasoning, ...rest } = message;
- const thinkingBlock = buildThinkingBlock(reasoning);
+ // Array content may already carry thinking parts built by the context
+ // engine (possibly Claude-signed or signature-only) β€” sanitize them for
+ // DeepSeek's thinking contract instead of stacking another block on top.
+ const existingParts = Array.isArray(message.content)
+ ? sanitizeAnthropicThinkingParts(message.content)
+ : undefined;
+ const hasThinkingPart = existingParts?.some((part: any) => part.type === 'thinking');
+
+ const thinkingBlock = hasThinkingPart ? undefined : buildThinkingBlock(reasoning);
const effectiveThinkingBlock =
- thinkingBlock || (forceThinking ? { thinking: ' ', type: 'thinking' as const } : undefined);
+ thinkingBlock ||
+ (!hasThinkingPart && forceThinking
+ ? { thinking: ' ', type: 'thinking' as const }
+ : undefined);
+
+ if (existingParts) {
+ const contentParts = effectiveThinkingBlock
+ ? [effectiveThinkingBlock, ...existingParts]
+ : existingParts;
+
+ return {
+ ...rest,
+ content: contentParts.length > 0 ? contentParts : [{ text: ' ', type: 'text' as const }],
+ };
+ }
if (!effectiveThinkingBlock) return rest;
diff --git a/packages/model-runtime/src/providers/kimiCodingPlan/index.test.ts b/packages/model-runtime/src/providers/kimiCodingPlan/index.test.ts
index 9f46d788959..d5ee3bda788 100644
--- a/packages/model-runtime/src/providers/kimiCodingPlan/index.test.ts
+++ b/packages/model-runtime/src/providers/kimiCodingPlan/index.test.ts
@@ -212,6 +212,36 @@ describe('LobeKimiCodingPlanAI', () => {
expect(payload.thinking!.budget_tokens).toBe(32_767);
});
+ // Regression: context-engine history may carry Claude-signed (or
+ // signature-only) thinking parts inside array content β€” foreign
+ // signatures must be stripped, empty parts dropped and replaced by the
+ // `' '` placeholder, without stacking a duplicate block.
+ it('should sanitize context-engine thinking parts in assistant array content', async () => {
+ await instance.chat({
+ messages: [
+ { content: 'Hello', role: 'user' },
+ {
+ content: [
+ { signature: 'claude-signature', type: 'thinking' },
+ { text: 'previous answer', type: 'text' },
+ ],
+ reasoning: { signature: 'claude-signature' },
+ role: 'assistant',
+ },
+ { content: 'continue', role: 'user' },
+ ] as any,
+ model: 'kimi-k2.5',
+ });
+
+ const payload = getLastRequestPayload();
+ const assistant = payload.messages.find((m: any) => m.role === 'assistant');
+ expect(assistant.content).toEqual([
+ { thinking: ' ', type: 'thinking' },
+ { text: 'previous answer', type: 'text' },
+ ]);
+ expect(JSON.stringify(payload.messages)).not.toContain('claude-signature');
+ });
+
it('should not add thinking params for unknown models', async () => {
await instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
diff --git a/packages/model-runtime/src/providers/kimiCodingPlan/index.ts b/packages/model-runtime/src/providers/kimiCodingPlan/index.ts
index e7515c5866b..4d8c515cb91 100644
--- a/packages/model-runtime/src/providers/kimiCodingPlan/index.ts
+++ b/packages/model-runtime/src/providers/kimiCodingPlan/index.ts
@@ -8,6 +8,7 @@ import {
} from '../../core/anthropicCompatibleFactory';
import type { ChatStreamPayload } from '../../types';
import { processMultiProviderModelList } from '../../utils/modelParse';
+import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';
const DEFAULT_KIMI_CODING_BASE_URL = 'https://api.kimi.com/coding';
@@ -51,9 +52,27 @@ const normalizeMessagesForAnthropic = (
if (message.role !== 'assistant') return message;
const { reasoning, ...rest } = message;
- const thinkingBlock = buildThinkingBlock(reasoning);
+ // Array content may already carry thinking parts built by the context
+ // engine (possibly Claude-signed or signature-only) β€” sanitize them for
+ // Kimi's thinking contract instead of stacking another block on top.
+ const existingParts = Array.isArray(message.content)
+ ? sanitizeAnthropicThinkingParts(message.content)
+ : undefined;
+ const hasThinkingPart = existingParts?.some((part: any) => part.type === 'thinking');
+
+ const thinkingBlock = hasThinkingPart ? null : buildThinkingBlock(reasoning);
const effectiveBlock =
- thinkingBlock || (forceThinking ? { thinking: ' ', type: 'thinking' as const } : null);
+ thinkingBlock ||
+ (!hasThinkingPart && forceThinking ? { thinking: ' ', type: 'thinking' as const } : null);
+
+ if (existingParts) {
+ const contentParts = effectiveBlock ? [effectiveBlock, ...existingParts] : existingParts;
+
+ return {
+ ...rest,
+ content: contentParts.length > 0 ? contentParts : [{ text: ' ', type: 'text' as const }],
+ };
+ }
if (isEmptyContent(message.content)) {
const placeholder = { text: ' ', type: 'text' as const };
diff --git a/packages/model-runtime/src/providers/minimax/index.test.ts b/packages/model-runtime/src/providers/minimax/index.test.ts
index 25fc0c7cdaf..f3a4a11175a 100644
--- a/packages/model-runtime/src/providers/minimax/index.test.ts
+++ b/packages/model-runtime/src/providers/minimax/index.test.ts
@@ -541,4 +541,51 @@ describe('LobeMinimaxAnthropicAI - handlePayload', () => {
role: 'assistant',
});
});
+
+ // Regression: context-engine history may carry Claude-signed (or
+ // signature-only) thinking parts inside array content. Foreign signatures
+ // must be stripped, parts without thinking text dropped, and no duplicate
+ // block prepended from `reasoning`.
+ it('sanitizes context-engine thinking parts in assistant array content', async () => {
+ const result = await handleAnthropicPayload(
+ {
+ max_tokens: 4096,
+ messages: [
+ {
+ content: [
+ { signature: 'claude-signature', type: 'thinking' },
+ { text: 'first answer', type: 'text' },
+ ],
+ reasoning: { signature: 'claude-signature' },
+ role: 'assistant',
+ },
+ { content: 'next', role: 'user' },
+ {
+ content: [
+ { signature: 'claude-signature-2', thinking: 'claude thoughts', type: 'thinking' },
+ { text: 'second answer', type: 'text' },
+ ],
+ reasoning: { content: 'claude thoughts', signature: 'claude-signature-2' },
+ role: 'assistant',
+ },
+ { content: 'continue', role: 'user' },
+ ],
+ model: 'MiniMax-M3',
+ } as any,
+ {} as any,
+ );
+
+ expect(result.messages[0]).toEqual({
+ content: [{ text: 'first answer', type: 'text' }],
+ role: 'assistant',
+ });
+ expect(result.messages[2]).toEqual({
+ content: [
+ { thinking: 'claude thoughts', type: 'thinking' },
+ { text: 'second answer', type: 'text' },
+ ],
+ role: 'assistant',
+ });
+ expect(JSON.stringify(result.messages)).not.toContain('claude-signature');
+ });
});
diff --git a/packages/model-runtime/src/providers/minimax/index.ts b/packages/model-runtime/src/providers/minimax/index.ts
index 8bdc4f3cb3f..785bfaec02a 100644
--- a/packages/model-runtime/src/providers/minimax/index.ts
+++ b/packages/model-runtime/src/providers/minimax/index.ts
@@ -14,6 +14,7 @@ import { createRouterRuntime } from '../../core/RouterRuntime';
import type { ChatStreamPayload, OpenAIChatMessage } from '../../types';
import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';
+import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';
import { createMiniMaxImage } from './createImage';
import { createMiniMaxVideo } from './createVideo';
@@ -30,7 +31,10 @@ type MiniMaxSDKType = 'anthropic' | 'openai';
const isEmptyContent = (content: unknown) =>
content === '' || content === null || content === undefined;
-const hasReasoningContent = (reasoning: any) => typeof reasoning?.content === 'string';
+// Require non-empty text: an empty-string `thinking` has never been validated
+// against MiniMax's Anthropic-compatible endpoint.
+const hasReasoningContent = (reasoning: any) =>
+ typeof reasoning?.content === 'string' && reasoning.content !== '';
// MiniMax accepts `low`, `default`, and `high`, but rejects OpenAI's `auto`.
// Omit `auto` so MiniMax applies its equivalent `default` behavior.
@@ -94,7 +98,24 @@ const normalizeMessagesForAnthropic = (messages: ChatStreamPayload['messages'])
if (message.role !== 'assistant') return message;
const { reasoning, ...rest } = message;
- const thinkingBlock = buildThinkingBlock(reasoning);
+ // Array content may already carry thinking parts built by the context
+ // engine (possibly Claude-signed or signature-only) β€” sanitize them for
+ // MiniMax's thinking contract instead of stacking another block on top.
+ const existingParts = Array.isArray(message.content)
+ ? sanitizeAnthropicThinkingParts(message.content)
+ : undefined;
+ const hasThinkingPart = existingParts?.some((part: any) => part.type === 'thinking');
+
+ const thinkingBlock = hasThinkingPart ? undefined : buildThinkingBlock(reasoning);
+
+ if (existingParts) {
+ const contentParts = thinkingBlock ? [thinkingBlock, ...existingParts] : existingParts;
+
+ return {
+ ...rest,
+ content: contentParts.length > 0 ? contentParts : [{ text: ' ', type: 'text' as const }],
+ };
+ }
if (!thinkingBlock) return rest;
diff --git a/packages/model-runtime/src/providers/moonshot/index.test.ts b/packages/model-runtime/src/providers/moonshot/index.test.ts
index e0c2f338f55..b6e8c28b0d5 100644
--- a/packages/model-runtime/src/providers/moonshot/index.test.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.test.ts
@@ -930,6 +930,36 @@ describe('LobeMoonshotAnthropicAI', () => {
]);
});
+ // Regression: context-engine history may carry Claude-signed (or
+ // signature-only) thinking parts inside array content β€” foreign
+ // signatures must be stripped, empty parts dropped and replaced by the
+ // `' '` placeholder, without stacking a duplicate block.
+ it('should sanitize context-engine thinking parts in assistant array content', async () => {
+ await instance.chat({
+ messages: [
+ { content: 'Hello', role: 'user' },
+ {
+ content: [
+ { signature: 'claude-signature', type: 'thinking' },
+ { text: 'previous answer', type: 'text' },
+ ],
+ reasoning: { signature: 'claude-signature' },
+ role: 'assistant',
+ },
+ { content: 'continue', role: 'user' },
+ ] as any,
+ model: 'kimi-k2-thinking',
+ });
+
+ const payload = getLastRequestPayload();
+ const assistant = payload.messages.find((m: any) => m.role === 'assistant');
+ expect(assistant.content).toEqual([
+ { thinking: ' ', type: 'thinking' },
+ { text: 'previous answer', type: 'text' },
+ ]);
+ expect(JSON.stringify(payload.messages)).not.toContain('claude-signature');
+ });
+
it('should force thinking block on assistant messages for kimi-k2.7-code', async () => {
await instance.chat({
messages: [
diff --git a/packages/model-runtime/src/providers/moonshot/index.ts b/packages/model-runtime/src/providers/moonshot/index.ts
index 579caed8185..c9573039680 100644
--- a/packages/model-runtime/src/providers/moonshot/index.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.ts
@@ -14,6 +14,7 @@ import { createRouterRuntime } from '../../core/RouterRuntime';
import type { ChatStreamPayload } from '../../types';
import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';
+import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';
import {
isKimiNativeThinkingModel,
isKimiPreserveThinkingModel,
@@ -95,9 +96,27 @@ const normalizeMessagesForAnthropic = (
if (message.role !== 'assistant') return message;
const { reasoning, ...rest } = message;
- const thinkingBlock = buildThinkingBlock(reasoning);
+ // Array content may already carry thinking parts built by the context
+ // engine (possibly Claude-signed or signature-only) β€” sanitize them for
+ // Moonshot's thinking contract instead of stacking another block on top.
+ const existingParts = Array.isArray(message.content)
+ ? sanitizeAnthropicThinkingParts(message.content)
+ : undefined;
+ const hasThinkingPart = existingParts?.some((part: any) => part.type === 'thinking');
+
+ const thinkingBlock = hasThinkingPart ? null : buildThinkingBlock(reasoning);
const effectiveBlock =
- thinkingBlock || (forceThinking ? { thinking: ' ', type: 'thinking' as const } : null);
+ thinkingBlock ||
+ (!hasThinkingPart && forceThinking ? { thinking: ' ', type: 'thinking' as const } : null);
+
+ if (existingParts) {
+ const contentParts = effectiveBlock ? [effectiveBlock, ...existingParts] : existingParts;
+
+ return {
+ ...rest,
+ content: contentParts.length > 0 ? contentParts : [{ text: ' ', type: 'text' as const }],
+ };
+ }
if (isEmptyContent(message.content)) {
const placeholder = { text: ' ', type: 'text' as const };
diff --git a/packages/model-runtime/src/utils/sanitizeAnthropicThinkingParts.test.ts b/packages/model-runtime/src/utils/sanitizeAnthropicThinkingParts.test.ts
new file mode 100644
index 00000000000..307bc3c94f1
--- /dev/null
+++ b/packages/model-runtime/src/utils/sanitizeAnthropicThinkingParts.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest';
+
+import { sanitizeAnthropicThinkingParts } from './sanitizeAnthropicThinkingParts';
+
+describe('sanitizeAnthropicThinkingParts', () => {
+ it('should strip signatures from thinking parts while keeping the text', () => {
+ const result = sanitizeAnthropicThinkingParts([
+ { signature: 'claude-base64-signature', thinking: 'let me think', type: 'thinking' },
+ { text: 'answer', type: 'text' },
+ ]);
+
+ expect(result).toEqual([
+ { thinking: 'let me think', type: 'thinking' },
+ { text: 'answer', type: 'text' },
+ ]);
+ });
+
+ it('should drop signature-only thinking parts missing the thinking field', () => {
+ // Claude 5 `thinking.display: 'omitted'` history: `thinking: undefined` is
+ // dropped by JSON serialization, so DeepSeek rejects the part with
+ // 400 `missing field 'thinking'` β€” the whole part must be removed.
+ const result = sanitizeAnthropicThinkingParts([
+ { signature: 'signature-only', type: 'thinking' },
+ { text: 'answer', type: 'text' },
+ ]);
+
+ expect(result).toEqual([{ text: 'answer', type: 'text' }]);
+ });
+
+ it('should drop thinking parts with empty-string thinking', () => {
+ const result = sanitizeAnthropicThinkingParts([
+ { signature: 'sig', thinking: '', type: 'thinking' },
+ { text: 'answer', type: 'text' },
+ ]);
+
+ expect(result).toEqual([{ text: 'answer', type: 'text' }]);
+ });
+
+ it('should keep the single-space placeholder thinking part', () => {
+ const result = sanitizeAnthropicThinkingParts([{ thinking: ' ', type: 'thinking' }]);
+
+ expect(result).toEqual([{ thinking: ' ', type: 'thinking' }]);
+ });
+
+ it('should drop redacted_thinking parts', () => {
+ const result = sanitizeAnthropicThinkingParts([
+ { data: 'encrypted', type: 'redacted_thinking' },
+ { text: 'answer', type: 'text' },
+ ]);
+
+ expect(result).toEqual([{ text: 'answer', type: 'text' }]);
+ });
+
+ it('should pass through non-thinking parts untouched', () => {
+ const parts = [
+ { text: 'hello', type: 'text' },
+ { id: 'toolu_1', input: {}, name: 'search', type: 'tool_use' },
+ ];
+
+ expect(sanitizeAnthropicThinkingParts(parts)).toEqual(parts);
+ });
+});
diff --git a/packages/model-runtime/src/utils/sanitizeAnthropicThinkingParts.ts b/packages/model-runtime/src/utils/sanitizeAnthropicThinkingParts.ts
new file mode 100644
index 00000000000..35962b48704
--- /dev/null
+++ b/packages/model-runtime/src/utils/sanitizeAnthropicThinkingParts.ts
@@ -0,0 +1,37 @@
+/**
+ * Sanitize history `thinking` content parts for third-party Anthropic-compatible
+ * endpoints (DeepSeek / Moonshot / Kimi / MiniMax).
+ *
+ * The context engine replays assistant reasoning as Anthropic `thinking` content
+ * parts, and history may carry signature-only reasoning (e.g. Claude 5
+ * `thinking.display: 'omitted'`), whose `thinking: undefined` disappears entirely
+ * on JSON serialization. Third-party endpoints have their own thinking contracts:
+ *
+ * - DeepSeek deserializes strictly and rejects a thinking part without the
+ * `thinking` field with 400 `missing field 'thinking'`.
+ * - Thinking signatures are provider-specific (Claude long base64 vs DeepSeek
+ * UUID-like) and are not verifiable across providers, so they must not be
+ * forwarded. This mirrors `normalizeClaudeThinkingHistoryMessages`, which
+ * protects the Claude side of the same boundary.
+ *
+ * Rules:
+ * - keep thinking text but never forward `signature` β€” these endpoints accepted
+ * unsigned thinking blocks long before signatures were ever persisted
+ * - drop thinking parts without non-empty thinking text β€” callers' placeholder
+ * logic (`{ thinking: ' ' }`) guarantees a block when the API requires one,
+ * and an empty-string `thinking` has never been validated against these APIs
+ * - drop `redacted_thinking` parts β€” they are Claude-encrypted and meaningless
+ * to other providers
+ */
+export const sanitizeAnthropicThinkingParts = (content: any[]): any[] =>
+ content
+ .map((part) => {
+ if (part?.type === 'redacted_thinking') return undefined;
+ if (part?.type !== 'thinking') return part;
+
+ const thinking = typeof part.thinking === 'string' ? part.thinking : '';
+ if (!thinking) return undefined;
+
+ return { thinking, type: 'thinking' as const };
+ })
+ .filter((part) => part !== undefined);