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.
This commit is contained in:
Haozhe 2026-09-18 21:06:08 +08:00 • committed by GitHub
parent 92c3c59b22
commit 7dc253c5ce
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 296 additions and 48 deletions

View file

@ -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.

View file

@ -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: {

View file

@ -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(

View file

@ -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':

View file

@ -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'),

View file

@ -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;

View file

@ -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<string, unknown> {
@ -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 });

View file

@ -121,19 +121,49 @@ export function lowerMessage(message: Message, lower: OpenAILowerContext): OpenA
converted = { role: message.role, content: content ?? '' };
}
const reasoningDetails: Record<string, unknown>[] = [];
const stringFields = new Map<string, string>();
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<string, unknown>)[REASONING_DETAILS_KEY] = reasoningDetails;
(converted as Record<string, unknown>)[DEFAULT_REASONING_KEY] = reasoningContent;
} else if (hasReasoningPart || (preserveThinking && message.role === 'assistant')) {
(converted as Record<string, unknown>)[DEFAULT_REASONING_KEY] =
stringFields.get(DEFAULT_REASONING_KEY) ?? reasoningContent;
}
for (const [key, value] of stringFields) {
(converted as Record<string, unknown>)[key] = value;
}
if (
stringFields.size === 0 &&
reasoningDetails.length === 0 &&
(hasReasoningPart || (preserveThinking && message.role === 'assistant'))
) {
(converted as Record<string, unknown>)[reasoningKey] = reasoningContent;
}
return [converted];

View file

@ -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<string, unknown>;
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<string, unknown>;
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<string, unknown>)[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);
}
}

View file

@ -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' },
]);
});