From 7dc253c5cefac7c277e5fc7071acf3e855fd503e Mon Sep 17 00:00:00 2001 From: Haozhe Date: Fri, 18 Sep 2026 21:06:08 +0800 Subject: [PATCH] fix(agent-core-v2): restore thinking for the openrouter reasoning dialect (#3910) Keep string reasoning fields when a reasoning_details array is present, stamp each think part by source, and replay those fields on the next request. --- .changeset/openrouter-reasoning-display.md | 5 + .../agent-core-v2/docs/state-manifest.d.ts | 2 + .../src/agent/loop/loopService.ts | 1 + .../src/agent/loop/machine/engine.ts | 2 + .../src/human/agent/historySchema.ts | 1 + .../agent-core-v2/src/human/llm/message.ts | 4 + .../llm/requester/bases/openai/format.ts | 23 +- .../human/llm/requester/bases/openai/lower.ts | 44 +++- .../requester/bases/openai/reasoning-key.ts | 29 ++- .../src/human/test/llm/thinking.test.ts | 233 ++++++++++++++++-- 10 files changed, 296 insertions(+), 48 deletions(-) create mode 100644 .changeset/openrouter-reasoning-display.md diff --git a/.changeset/openrouter-reasoning-display.md b/.changeset/openrouter-reasoning-display.md new file mode 100644 index 00000000000..3b874d293cf --- /dev/null +++ b/.changeset/openrouter-reasoning-display.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/kimi-code": patch +--- + +Restore thinking display for OpenAI-compatible providers that send a reasoning string next to an unrecognized reasoning_details array. diff --git a/packages/agent-core-v2/docs/state-manifest.d.ts b/packages/agent-core-v2/docs/state-manifest.d.ts index 29487f4b8e9..48a2ffa8c08 100644 --- a/packages/agent-core-v2/docs/state-manifest.d.ts +++ b/packages/agent-core-v2/docs/state-manifest.d.ts @@ -730,6 +730,7 @@ export interface AgentStateSnapshot { encrypted?: string; detailsIndex?: number; hidden?: boolean; + reasoningKey?: string; } | /* ImageURLPart — packages/agent-core-v2/src/human/llm/message.ts */ { type: 'image_url'; imageUrl: { @@ -1027,6 +1028,7 @@ export interface AgentStateSnapshot { encrypted?: string; detailsIndex?: number; hidden?: boolean; + reasoningKey?: string; } | /* ImageURLPart — packages/agent-core-v2/src/human/llm/message.ts */ { type: 'image_url'; imageUrl: { diff --git a/packages/agent-core-v2/src/agent/loop/loopService.ts b/packages/agent-core-v2/src/agent/loop/loopService.ts index 5838bd85d40..4df14baaf4c 100644 --- a/packages/agent-core-v2/src/agent/loop/loopService.ts +++ b/packages/agent-core-v2/src/agent/loop/loopService.ts @@ -1426,6 +1426,7 @@ export class AgentLoopService extends Disposable implements IAgentLoopService { encrypted: delta.encrypted, detailsIndex: delta.detailsIndex, hidden: delta.hidden, + reasoningKey: delta.reasoningKey, }); if (part?.type === 'think' && part.hidden === true) return; void this.dispatcher.dispatch( diff --git a/packages/agent-core-v2/src/agent/loop/machine/engine.ts b/packages/agent-core-v2/src/agent/loop/machine/engine.ts index 590ff8adaac..8ec6620a41e 100644 --- a/packages/agent-core-v2/src/agent/loop/machine/engine.ts +++ b/packages/agent-core-v2/src/agent/loop/machine/engine.ts @@ -40,6 +40,7 @@ export type MachineEngineDelta = readonly encrypted?: string; readonly detailsIndex?: number; readonly hidden?: boolean; + readonly reasoningKey?: string; } | { readonly kind: 'toolCall'; @@ -227,6 +228,7 @@ function createDeltaSplitter(): (part: StreamedMessagePart) => MachineEngineDelt encrypted: part.encrypted, detailsIndex: part.detailsIndex, hidden: part.hidden, + reasoningKey: part.reasoningKey, }; case 'image_url': case 'audio_url': diff --git a/packages/agent-core-v2/src/human/agent/historySchema.ts b/packages/agent-core-v2/src/human/agent/historySchema.ts index cc9adf95fac..a7ee96ea11b 100644 --- a/packages/agent-core-v2/src/human/agent/historySchema.ts +++ b/packages/agent-core-v2/src/human/agent/historySchema.ts @@ -10,6 +10,7 @@ const thinkPartSchema = z.object({ encrypted: z.string().optional(), detailsIndex: z.number().optional(), hidden: z.boolean().optional(), + reasoningKey: z.string().optional(), }); const imageUrlPartSchema = z.object({ type: z.literal('image_url'), diff --git a/packages/agent-core-v2/src/human/llm/message.ts b/packages/agent-core-v2/src/human/llm/message.ts index a823b9a84d3..51dc1dc836f 100644 --- a/packages/agent-core-v2/src/human/llm/message.ts +++ b/packages/agent-core-v2/src/human/llm/message.ts @@ -18,6 +18,7 @@ export interface ThinkPart { encrypted?: string; detailsIndex?: number; hidden?: boolean; + reasoningKey?: string; } export interface ImageURLPart { @@ -111,6 +112,9 @@ export function mergeInPlace(target: StreamedMessagePart, source: StreamedMessag if (target.hidden !== source.hidden) { return false; } + if (target.reasoningKey !== source.reasoningKey) { + return false; + } target.think += source.think; if (source.encrypted !== undefined) { target.encrypted = source.encrypted; diff --git a/packages/agent-core-v2/src/human/llm/requester/bases/openai/format.ts b/packages/agent-core-v2/src/human/llm/requester/bases/openai/format.ts index c5384ecca4b..d074e9c1fb3 100644 --- a/packages/agent-core-v2/src/human/llm/requester/bases/openai/format.ts +++ b/packages/agent-core-v2/src/human/llm/requester/bases/openai/format.ts @@ -39,8 +39,8 @@ import { lowerMessage } from './lower'; import { extractToolMedia } from './patterns'; import { convertReasoningDetails, - extractReasoning, extractReasoningDetails, + extractReasoningStrings, } from './reasoning-key'; export function responseFormatToOpenAI(format: ResponseFormat): Record { @@ -299,23 +299,20 @@ export function createOpenAIFormat(): OpenAIProtocolFormat { } const reasoningDetails = options?.reasoningKey === undefined ? extractReasoningDetails(delta) : undefined; - if (reasoningDetails !== undefined) { - const inline = extractReasoning(delta, 'reasoning_content'); - if (inline !== undefined) { + for (const reasoning of extractReasoningStrings(delta)) { + if (reasoning.key === 'reasoning_content') { seenReasoningContent = true; - sink.onDelta({ type: 'think', think: inline.value }); } + sink.onDelta({ + type: 'think', + think: reasoning.value, + reasoningKey: reasoning.key, + }); + } + if (reasoningDetails !== undefined) { for (const part of convertReasoningDetails(reasoningDetails, seenReasoningContent)) { sink.onDelta(part); } - } else { - const reasoning = extractReasoning(delta); - if (reasoning !== undefined) { - if (reasoning.key === 'reasoning_content') { - seenReasoningContent = true; - } - sink.onDelta({ type: 'think', think: reasoning.value }); - } } if (typeof delta.content === 'string' && delta.content.length > 0) { sink.onDelta({ type: 'text', text: delta.content }); diff --git a/packages/agent-core-v2/src/human/llm/requester/bases/openai/lower.ts b/packages/agent-core-v2/src/human/llm/requester/bases/openai/lower.ts index 93a75c0d12a..16b5e7b7760 100644 --- a/packages/agent-core-v2/src/human/llm/requester/bases/openai/lower.ts +++ b/packages/agent-core-v2/src/human/llm/requester/bases/openai/lower.ts @@ -121,19 +121,49 @@ export function lowerMessage(message: Message, lower: OpenAILowerContext): OpenA converted = { role: message.role, content: content ?? '' }; } const reasoningDetails: Record[] = []; + const stringFields = new Map(); + let unstamped = ''; + let hasUnstamped = false; for (const part of message.content) { - if (part.type !== 'think' || part.detailsIndex === undefined) continue; - if (part.think.length > 0) { - reasoningDetails.push({ type: 'summary', summary: part.think }); + if (part.type !== 'think') continue; + if (part.detailsIndex !== undefined) { + if (part.think.length > 0) { + reasoningDetails.push({ type: 'summary', summary: part.think }); + } + if (part.encrypted !== undefined) { + reasoningDetails.push({ type: 'encrypted', encrypted: part.encrypted }); + } + continue; } - if (part.encrypted !== undefined) { - reasoningDetails.push({ type: 'encrypted', encrypted: part.encrypted }); + if (part.reasoningKey !== undefined && part.reasoningKey !== REASONING_DETAILS_KEY) { + const current = stringFields.get(part.reasoningKey) ?? ''; + stringFields.set( + part.reasoningKey, + part.hidden === true ? current : current + part.think, + ); + continue; } + hasUnstamped = true; + if (part.hidden !== true) { + unstamped += part.think; + } + } + if (hasUnstamped) { + stringFields.set(reasoningKey, (stringFields.get(reasoningKey) ?? '') + unstamped); } if (reasoningDetails.length > 0) { (converted as Record)[REASONING_DETAILS_KEY] = reasoningDetails; - (converted as Record)[DEFAULT_REASONING_KEY] = reasoningContent; - } else if (hasReasoningPart || (preserveThinking && message.role === 'assistant')) { + (converted as Record)[DEFAULT_REASONING_KEY] = + stringFields.get(DEFAULT_REASONING_KEY) ?? reasoningContent; + } + for (const [key, value] of stringFields) { + (converted as Record)[key] = value; + } + if ( + stringFields.size === 0 && + reasoningDetails.length === 0 && + (hasReasoningPart || (preserveThinking && message.role === 'assistant')) + ) { (converted as Record)[reasoningKey] = reasoningContent; } return [converted]; diff --git a/packages/agent-core-v2/src/human/llm/requester/bases/openai/reasoning-key.ts b/packages/agent-core-v2/src/human/llm/requester/bases/openai/reasoning-key.ts index bd4b2b570bb..047a53479dc 100644 --- a/packages/agent-core-v2/src/human/llm/requester/bases/openai/reasoning-key.ts +++ b/packages/agent-core-v2/src/human/llm/requester/bases/openai/reasoning-key.ts @@ -10,18 +10,29 @@ export type ReasoningKey = (typeof KNOWN_REASONING_KEYS)[number]; export const DEFAULT_REASONING_KEY: ReasoningKey = KNOWN_REASONING_KEYS[0]; +export function extractReasoningStrings( + source: unknown, +): { key: string; value: string }[] { + if (typeof source !== 'object' || source === null) return []; + const record = source as Record; + const found: { key: string; value: string }[] = []; + for (const key of KNOWN_REASONING_KEYS) { + const value = record[key]; + if (typeof value === 'string') found.push({ key, value }); + } + return found; +} + export function extractReasoning( source: unknown, explicitKey?: string, ): { key: string; value: string } | undefined { - if (typeof source !== 'object' || source === null) return undefined; - const record = source as Record; - const keys: readonly string[] = explicitKey !== undefined ? [explicitKey] : KNOWN_REASONING_KEYS; - for (const key of keys) { - const value = record[key]; - if (typeof value === 'string') return { key, value }; + if (explicitKey !== undefined) { + if (typeof source !== 'object' || source === null) return undefined; + const value = (source as Record)[explicitKey]; + return typeof value === 'string' ? { key: explicitKey, value } : undefined; } - return undefined; + return extractReasoningStrings(source)[0]; } export class ReasoningKeyDialect { @@ -32,7 +43,7 @@ export class ReasoningKeyDialect { observe(source: unknown): string | undefined { const found = extractReasoning(source, this._explicitKey); if (found === undefined) return undefined; - if (this._explicitKey === undefined) { + if (this._explicitKey === undefined && this._detected === undefined) { this._detected = found.key; } return found.value; @@ -92,6 +103,7 @@ export function convertReasoningDetails( think: element.summary, detailsIndex: element.index, hidden: hiddenSummary ? true : undefined, + reasoningKey: REASONING_DETAILS_KEY, } satisfies ThinkPart); } if (element.type !== 'summary' && element.encrypted !== undefined && element.encrypted.length > 0) { @@ -100,6 +112,7 @@ export function convertReasoningDetails( think: '', encrypted: element.encrypted, detailsIndex: element.index, + reasoningKey: REASONING_DETAILS_KEY, } satisfies ThinkPart); } } diff --git a/packages/agent-core-v2/src/human/test/llm/thinking.test.ts b/packages/agent-core-v2/src/human/test/llm/thinking.test.ts index 780bbc5ab33..61a1afdf4f7 100644 --- a/packages/agent-core-v2/src/human/test/llm/thinking.test.ts +++ b/packages/agent-core-v2/src/human/test/llm/thinking.test.ts @@ -429,9 +429,21 @@ describe('openai requester thinking', () => { ); const finished = accumulator.finish(); expect(finished.content).toEqual([ - { type: 'think', think: '原文一原文二' }, - { type: 'think', think: '摘', detailsIndex: 0, hidden: true }, - { type: 'think', think: '', encrypted: 'cipher', detailsIndex: 1 }, + { type: 'think', think: '原文一原文二', reasoningKey: 'reasoning_content' }, + { + type: 'think', + think: '摘', + detailsIndex: 0, + hidden: true, + reasoningKey: 'reasoning_details', + }, + { + type: 'think', + think: '', + encrypted: 'cipher', + detailsIndex: 1, + reasoningKey: 'reasoning_details', + }, { type: 'text', text: 'ok' }, ]); @@ -452,6 +464,119 @@ describe('openai requester thinking', () => { ]); expect(continued['reasoning_content']).toBe('原文一原文二'); expect(continued['content']).toBe('ok'); + + const dual = stubOpenAIClient( + chatCompletionChunks([ + { + reasoning_content: 'A', + reasoning: 'B', + reasoning_details: [ + { index: 0, type: 'summary', summary: '摘' }, + { index: 1, type: 'encrypted', encrypted: 'cipher' }, + ], + }, + { content: 'ok' }, + ]), + ); + const dualAccumulator = createMessageAccumulator(); + await createOpenAIRequester({ + clientFactory: dual.clientFactory, + }).generate( + { model }, + { messages }, + { + signal: new AbortController().signal, + onEvent: (event) => { + if (event.type === 'llm.streaming.part') { + dualAccumulator.push(event.part); + } + }, + }, + ); + const dualFinished = dualAccumulator.finish(); + expect(dualFinished.content).toEqual([ + { type: 'think', think: 'A', reasoningKey: 'reasoning_content' }, + { type: 'think', think: 'B', reasoningKey: 'reasoning' }, + { + type: 'think', + think: '摘', + detailsIndex: 0, + hidden: true, + reasoningKey: 'reasoning_details', + }, + { + type: 'think', + think: '', + encrypted: 'cipher', + detailsIndex: 1, + reasoningKey: 'reasoning_details', + }, + { type: 'text', text: 'ok' }, + ]); + const dualOutbound = stubOpenAIClient(chatCompletionChunks()); + await createOpenAIRequester({ + clientFactory: dualOutbound.clientFactory, + }).generate( + { model, thinking: { effort: 'off' } }, + { messages: [createUserMessage('hi'), dualFinished] }, + { signal: new AbortController().signal }, + ); + const dualReplayed = bodyMessages(dualOutbound.body())[1]!; + expect(dualReplayed['reasoning_content']).toBe('A'); + expect(dualReplayed['reasoning']).toBe('B'); + expect(dualReplayed['reasoning_details']).toEqual([ + { type: 'summary', summary: '摘' }, + { type: 'encrypted', encrypted: 'cipher' }, + ]); + + const openrouter = stubOpenAIClient( + chatCompletionChunks([ + { + reasoning: 'We', + reasoning_details: [ + { + index: 0, + type: 'reasoning.text', + text: 'We', + format: 'unknown', + }, + ], + }, + { content: 'ok' }, + ]), + ); + const openrouterAccumulator = createMessageAccumulator(); + await createOpenAIRequester({ + clientFactory: openrouter.clientFactory, + }).generate( + { model }, + { messages }, + { + signal: new AbortController().signal, + onEvent: (event) => { + if (event.type === 'llm.streaming.part') { + openrouterAccumulator.push(event.part); + } + }, + }, + ); + const openrouterFinished = openrouterAccumulator.finish(); + expect(openrouterFinished.content).toEqual([ + { type: 'think', think: 'We', reasoningKey: 'reasoning' }, + { type: 'text', text: 'ok' }, + ]); + const openrouterOutbound = stubOpenAIClient(chatCompletionChunks()); + await createOpenAIRequester({ + clientFactory: openrouterOutbound.clientFactory, + }).generate( + { model, thinking: { effort: 'off' } }, + { messages: [createUserMessage('hi'), openrouterFinished] }, + { signal: new AbortController().signal }, + ); + const openrouterReplayed = bodyMessages(openrouterOutbound.body())[1]!; + expect(openrouterReplayed['reasoning']).toBe('We'); + expect('reasoning_content' in openrouterReplayed).toBe(false); + expect('reasoning_details' in openrouterReplayed).toBe(false); }); it('echoes an empty reasoning_content on think-less assistant messages only when keeping all', async () => { @@ -580,10 +705,14 @@ describe('openai requester thinking', () => { }; await expect( collect(chatCompletionChunks([{ reasoning: 'stream-think' }, { content: 'hi' }])), - ).resolves.toContainEqual({ type: 'think', think: 'stream-think' }); + ).resolves.toContainEqual({ + type: 'think', + think: 'stream-think', + reasoningKey: 'reasoning', + }); await expect( collect(chatCompletionChunks([{ reasoning: '' }, { content: 'hi' }])), - ).resolves.toContainEqual({ type: 'think', think: '' }); + ).resolves.toContainEqual({ type: 'think', think: '', reasoningKey: 'reasoning' }); await expect( collect( chatCompletionChunks([ @@ -592,14 +721,14 @@ describe('openai requester thinking', () => { ]), ), ).resolves.toEqual([ - { type: 'think', think: '' }, + { type: 'think', think: '', reasoningKey: 'reasoning' }, { type: 'text', text: 'hello' }, ]); await expect( collect(chatCompletionChunks([{ content: 'hi' }, { reasoning: '' }])), ).resolves.toEqual([ { type: 'text', text: 'hi' }, - { type: 'think', think: '' }, + { type: 'think', think: '', reasoningKey: 'reasoning' }, ]); await expect( collect( @@ -619,10 +748,28 @@ describe('openai requester thinking', () => { ]), ), ).resolves.toEqual([ - { type: 'think', think: '第一段' }, - { type: 'think', think: '第一段续', detailsIndex: 0, hidden: true }, - { type: 'think', think: '第二段', detailsIndex: 1, hidden: true }, - { type: 'think', think: '', encrypted: 'cipher', detailsIndex: 2 }, + { type: 'think', think: '第一段', reasoningKey: 'reasoning_content' }, + { + type: 'think', + think: '第一段续', + detailsIndex: 0, + hidden: true, + reasoningKey: 'reasoning_details', + }, + { + type: 'think', + think: '第二段', + detailsIndex: 1, + hidden: true, + reasoningKey: 'reasoning_details', + }, + { + type: 'think', + think: '', + encrypted: 'cipher', + detailsIndex: 2, + reasoningKey: 'reasoning_details', + }, { type: 'text', text: 'ok' }, ]); await expect( @@ -638,7 +785,7 @@ describe('openai requester thinking', () => { ]), ), ).resolves.toEqual([ - { type: 'think', think: 'kept', detailsIndex: 1 }, + { type: 'think', think: 'kept', detailsIndex: 1, reasoningKey: 'reasoning_details' }, { type: 'text', text: 'ok' }, ]); await expect( @@ -655,9 +802,21 @@ describe('openai requester thinking', () => { ]), ), ).resolves.toEqual([ - { type: 'think', think: '原文' }, - { type: 'think', think: '摘', detailsIndex: 0, hidden: true }, - { type: 'think', think: '', encrypted: 'cipher', detailsIndex: 1 }, + { type: 'think', think: '原文', reasoningKey: 'reasoning_content' }, + { + type: 'think', + think: '摘', + detailsIndex: 0, + hidden: true, + reasoningKey: 'reasoning_details', + }, + { + type: 'think', + think: '', + encrypted: 'cipher', + detailsIndex: 1, + reasoningKey: 'reasoning_details', + }, { type: 'text', text: 'ok' }, ]); await expect( @@ -676,9 +835,21 @@ describe('openai requester thinking', () => { ]), ), ).resolves.toEqual([ - { type: 'think', think: '原文一原文二' }, - { type: 'think', think: '摘一摘二', detailsIndex: 0, hidden: true }, - { type: 'think', think: '', encrypted: 'cipher', detailsIndex: 1 }, + { type: 'think', think: '原文一原文二', reasoningKey: 'reasoning_content' }, + { + type: 'think', + think: '摘一摘二', + detailsIndex: 0, + hidden: true, + reasoningKey: 'reasoning_details', + }, + { + type: 'think', + think: '', + encrypted: 'cipher', + detailsIndex: 1, + reasoningKey: 'reasoning_details', + }, { type: 'text', text: 'ok' }, ]); await expect( @@ -694,8 +865,30 @@ describe('openai requester thinking', () => { ]), ), ).resolves.toEqual([ - { type: 'think', think: '摘', detailsIndex: 0 }, - { type: 'think', think: '', encrypted: 'cipher', detailsIndex: 1 }, + { type: 'think', think: '摘', detailsIndex: 0, reasoningKey: 'reasoning_details' }, + { + type: 'think', + think: '', + encrypted: 'cipher', + detailsIndex: 1, + reasoningKey: 'reasoning_details', + }, + { type: 'text', text: 'ok' }, + ]); + await expect( + collect( + chatCompletionChunks([ + { + reasoning: 'We', + reasoning_details: [ + { index: 0, type: 'reasoning.text', text: 'We', format: 'unknown' }, + ], + }, + { content: 'ok' }, + ]), + ), + ).resolves.toEqual([ + { type: 'think', think: 'We', reasoningKey: 'reasoning' }, { type: 'text', text: 'ok' }, ]); });