π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: persist complete OpenAI Responses reasoning items (#17705)
YuTengjing57b088a1d352
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.tsindex bdbfc3b5e8d..b48138dab16 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts@@ -194,6 +194,33 @@ describe('callLlmFinalizer', () => {});});+ it('persists complete reasoning response items without visible thinking content', async () => {+ const responseItem = {+ encrypted_content: 'scoped-encrypted',+ id: 'rs_hidden',+ summary: [],+ type: 'reasoning' as const,+ };++ const result = await finalizeCallLlmTurn({+ assistantMessageId: 'assistant-1',+ events: [],+ host: createHost(),+ model: 'gpt-5',+ output: createOutput({+ reasoning: { responseItems: [responseItem] },+ thinkingContent: '',+ }),+ provider: 'chatgpt',+ shouldReplayAssistantReasoning: true,+ state: AgentRuntime.createInitialState({ operationId: 'operation-1' }),+ });++ expect(result.newState.messages.at(-1)).toMatchObject({+ reasoning: { responseItems: [responseItem] },+ });+ });+it('publishes no-tool visible output end before persistence and records the marker', async () => {const messages = createMessageTransport();const stream = createStreamSink();diff --git a/packages/fetch-sse/src/__tests__/reasoningSignature.test.ts b/packages/fetch-sse/src/__tests__/reasoningSignature.test.tsindex 9a2550075ae..c0afa8e0e85 100644--- a/packages/fetch-sse/src/__tests__/reasoningSignature.test.ts+++ b/packages/fetch-sse/src/__tests__/reasoningSignature.test.ts@@ -47,4 +47,160 @@ describe('fetchSSE reasoning signatures', () => {type: 'done',});});++ it('should collect reasoning response items in stream order', async () => {+ const mockOnFinish = vi.fn();+ const firstItem = {+ encrypted_content: 'scoped-encrypted-1',+ id: 'rs_1',+ summary: [{ text: 'visible summary', type: 'summary_text' }],+ type: 'reasoning',+ };+ const secondItem = {+ encrypted_content: 'scoped-encrypted-2',+ id: 'rs_2',+ summary: [],+ type: 'reasoning',+ };++ (fetchEventSource as any).mockImplementationOnce(+ (url: string, options: FetchEventSourceInit) => {+ options.onopen!({ clone: () => ({ ok: true, headers: new Headers() }) } as any);+ options.onmessage!({+ data: JSON.stringify('visible summary'),+ event: 'reasoning',+ } as any);+ options.onmessage!({+ data: JSON.stringify(firstItem),+ event: 'reasoning_response_item',+ } as any);+ options.onmessage!({+ data: JSON.stringify(secondItem),+ event: 'reasoning_response_item',+ } as any);+ options.onmessage!({ data: JSON.stringify('Done'), event: 'text' } as any);+ },+ );++ await fetchSSE('/', {+ onFinish: mockOnFinish,+ responseAnimation: 'none',+ });++ expect(mockOnFinish).toHaveBeenCalledWith('Done', {+ observationId: null,+ reasoning: {+ content: 'visible summary',+ responseItems: [firstItem, secondItem],+ signature: undefined,+ },+ toolCalls: undefined,+ traceId: null,+ type: 'done',+ });+ });++ it('should derive reasoning content from item summaries when nothing was streamed', async () => {+ const mockOnFinish = vi.fn();+ const summaryItem = {+ encrypted_content: 'scoped-encrypted',+ id: 'rs_1',+ summary: [{ text: 'summary only text', type: 'summary_text' }],+ type: 'reasoning',+ };++ (fetchEventSource as any).mockImplementationOnce(+ (url: string, options: FetchEventSourceInit) => {+ options.onopen!({ clone: () => ({ ok: true, headers: new Headers() }) } as any);+ options.onmessage!({+ data: JSON.stringify(summaryItem),+ event: 'reasoning_response_item',+ } as any);+ options.onmessage!({ data: JSON.stringify('Done'), event: 'text' } as any);+ },+ );++ await fetchSSE('/', {+ onFinish: mockOnFinish,+ responseAnimation: 'none',+ });++ expect(mockOnFinish).toHaveBeenCalledWith('Done', {+ observationId: null,+ reasoning: {+ content: 'summary only text',+ responseItems: [summaryItem],+ signature: undefined,+ },+ toolCalls: undefined,+ traceId: null,+ type: 'done',+ });+ });++ it('should keep reasoning when only hidden response items arrive', async () => {+ const mockOnFinish = vi.fn();+ const hiddenItem = {+ encrypted_content: 'scoped-hidden',+ id: 'rs_hidden',+ summary: [],+ type: 'reasoning',+ };++ (fetchEventSource as any).mockImplementationOnce(+ (url: string, options: FetchEventSourceInit) => {+ options.onopen!({ clone: () => ({ ok: true, headers: new Headers() }) } as any);+ options.onmessage!({+ data: JSON.stringify(hiddenItem),+ event: 'reasoning_response_item',+ } as any);+ options.onmessage!({ data: JSON.stringify('Done'), event: 'text' } as any);+ },+ );++ await fetchSSE('/', {+ onFinish: mockOnFinish,+ responseAnimation: 'none',+ });++ expect(mockOnFinish).toHaveBeenCalledWith('Done', {+ observationId: null,+ reasoning: {+ content: undefined,+ responseItems: [hiddenItem],+ signature: undefined,+ },+ toolCalls: undefined,+ traceId: null,+ type: 'done',+ });+ });++ it('should ignore object payloads on the string-only reasoning_signature event', async () => {+ const mockOnFinish = vi.fn();++ (fetchEventSource as any).mockImplementationOnce(+ (url: string, options: FetchEventSourceInit) => {+ options.onopen!({ clone: () => ({ ok: true, headers: new Headers() }) } as any);+ options.onmessage!({+ data: JSON.stringify({ id: 'rs_1', type: 'reasoning' }),+ event: 'reasoning_signature',+ } as any);+ options.onmessage!({ data: JSON.stringify('Done'), event: 'text' } as any);+ },+ );++ await fetchSSE('/', {+ onFinish: mockOnFinish,+ responseAnimation: 'none',+ });++ expect(mockOnFinish).toHaveBeenCalledWith('Done', {+ observationId: null,+ reasoning: undefined,+ toolCalls: undefined,+ traceId: null,+ type: 'done',+ });+ });});diff --git a/packages/fetch-sse/src/fetchSSE.ts b/packages/fetch-sse/src/fetchSSE.tsindex ea805112f72..6614ea1bcd9 100644--- a/packages/fetch-sse/src/fetchSSE.ts+++ b/packages/fetch-sse/src/fetchSSE.ts@@ -7,6 +7,7 @@ import type {MessageToolCall,ModelPerformance,ModelReasoning,+ ModelReasoningResponseItem,ModelUsage,ResponseAnimation,ResponseAnimationStyle,@@ -282,6 +283,7 @@ export const fetchSSE = async (url: string, options: RequestInit & FetchSSEOptiolet thinking = '';let thinkingSignature: string | undefined;+ const reasoningResponseItems: ModelReasoningResponseItem[] = [];const thinkingController = createSmoothMessage({onTextUpdate: (delta, text) => {@@ -432,7 +434,14 @@ export const fetchSSE = async (url: string, options: RequestInit & FetchSSEOptio}case 'reasoning_signature': {- thinkingSignature = data;+ // Server guarantees string payloads on this event; guard against object+ // payloads so a malformed stream can't corrupt the persisted signature.+ if (typeof data === 'string') thinkingSignature = data;+ break;+ }++ case 'reasoning_response_item': {+ reasoningResponseItems.push(data as ModelReasoningResponseItem);break;}@@ -548,10 +557,28 @@ export const fetchSSE = async (url: string, options: RequestInit & FetchSSEOptiogrounding,images: images.length > 0 ? images : undefined,observationId,- reasoning:- thinking || thinkingSignature- ? { content: thinking || undefined, signature: thinkingSignature }- : undefined,+ reasoning: (() => {+ /**+ * Non-streaming Responses conversion emits reasoning items without summary+ * deltas; derive visible thinking text from item summaries when nothing was+ * streamed so the summary renders instead of being replay-only state.+ */+ const responseItemsThinking = reasoningResponseItems+ .flatMap(({ summary }) => summary ?? [])+ .map(({ text }) => text)+ .filter(Boolean)+ .join('\n');+ const reasoningContent = thinking || responseItemsThinking || undefined;++ return reasoningContent || thinkingSignature || reasoningResponseItems.length > 0+ ? {+ content: reasoningContent,+ responseItems:+ reasoningResponseItems.length > 0 ? reasoningResponseItems : undefined,+ signature: thinkingSignature,+ }+ : undefined;+ })(),speed,toolCalls,traceId,diff --git a/packages/model-runtime/src/core/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.tsindex c2fbc2b0886..e8a32b9cc5f 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts@@ -1055,6 +1055,165 @@ describe('convertOpenAIResponseInputs', () => {expect(legacyResult).toEqual(expected);});+ it('should replay complete reasoning items in original order for the exact scope', async () => {+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };+ const messages: OpenAIChatMessage[] = [+ {+ content: 'hello',+ provider: 'chatgpt',+ reasoning: {+ content: 'first summary',+ responseItems: [+ {+ encrypted_content: serializeScopedSignature(+ 'encrypted-part-1',+ reasoningSignatureScope,+ 'reasoning',+ ),+ id: 'rs_1',+ status: 'completed',+ summary: [{ text: 'first summary', type: 'summary_text' }],+ type: 'reasoning',+ },+ {+ encrypted_content: serializeScopedSignature(+ 'encrypted-part-2',+ reasoningSignatureScope,+ 'reasoning',+ ),+ id: 'rs_2',+ status: 'completed',+ summary: [],+ type: 'reasoning',+ },+ ],+ },+ role: 'assistant',+ },+ ];++ const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });++ expect(result).toEqual([+ {+ encrypted_content: 'encrypted-part-1',+ id: 'rs_1',+ status: 'completed',+ summary: [{ text: 'first summary', type: 'summary_text' }],+ type: 'reasoning',+ },+ {+ encrypted_content: 'encrypted-part-2',+ id: 'rs_2',+ status: 'completed',+ summary: [],+ type: 'reasoning',+ },+ { content: 'hello', role: 'assistant' },+ ]);+ });++ it('should replay hidden reasoning items that have no visible summary', async () => {+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };+ const messages: OpenAIChatMessage[] = [+ {+ content: 'hello',+ provider: 'chatgpt',+ reasoning: {+ responseItems: [+ {+ encrypted_content: serializeScopedSignature(+ 'hidden-encrypted',+ reasoningSignatureScope,+ 'reasoning',+ ),+ id: 'rs_hidden',+ summary: [],+ type: 'reasoning',+ },+ ],+ },+ role: 'assistant',+ },+ ];++ const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });++ expect(result).toEqual([+ {+ encrypted_content: 'hidden-encrypted',+ id: 'rs_hidden',+ summary: [],+ type: 'reasoning',+ },+ { content: 'hello', role: 'assistant' },+ ]);+ });++ it('should fall back to the visible summary when any reasoning item is foreign-scoped', async () => {+ const sourceScope: SignatureScope = { fingerprint: 'a'.repeat(32) };+ const targetScope: SignatureScope = { fingerprint: 'b'.repeat(32) };+ const messages: OpenAIChatMessage[] = [+ {+ content: 'hello',+ provider: 'chatgpt',+ reasoning: {+ content: 'visible summary',+ responseItems: [+ {+ encrypted_content: serializeScopedSignature(+ 'encrypted-part-1',+ sourceScope,+ 'reasoning',+ ),+ id: 'rs_1',+ summary: [{ text: 'visible summary', type: 'summary_text' }],+ type: 'reasoning',+ },+ ],+ signature: serializeScopedSignature('encrypted-part-1', sourceScope, 'reasoning'),+ },+ role: 'assistant',+ },+ ];++ const result = await convertOpenAIResponseInputs(messages, {+ reasoningSignatureScope: targetScope,+ });++ expect(result).toEqual([+ { summary: [{ text: 'visible summary', type: 'summary_text' }], type: 'reasoning' },+ { content: 'hello', role: 'assistant' },+ ]);+ });++ it('should strip item ids when replaying summary-only reasoning items', async () => {+ const messages: OpenAIChatMessage[] = [+ {+ content: 'hello',+ provider: 'chatgpt',+ reasoning: {+ content: 'summary only',+ responseItems: [+ {+ id: 'rs_summary_only',+ summary: [{ text: 'summary only', type: 'summary_text' }],+ type: 'reasoning',+ },+ ],+ },+ role: 'assistant',+ },+ ];++ const result = await convertOpenAIResponseInputs(messages);++ expect(result).toEqual([+ { summary: [{ text: 'summary only', type: 'summary_text' }], type: 'reasoning' },+ { content: 'hello', role: 'assistant' },+ ]);+ });+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.tsindex 397247a8089..645a2ecacbc 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts@@ -246,19 +246,63 @@ export const convertOpenAIResponseInputs = async (messages.map(async (message) => {const items: OpenAI.Responses.ResponseInputItem[] = [];const reasoning = message.reasoning;- const encryptedContent = resolveScopedSignature(- reasoning?.signature,- options?.reasoningSignatureScope,- 'reasoning',- );-- // Preserve encrypted reasoning state for stateless Responses API requests.- if (reasoning?.content || encryptedContent) {- items.push({- encrypted_content: encryptedContent,- summary: reasoning?.content ? [{ text: reasoning.content, type: 'summary_text' }] : [],- type: 'reasoning',- } as OpenAI.Responses.ResponseReasoningItem);++ /**+ * Resolve persisted Responses reasoning items for stateless replay. Encrypted+ * items must all match the current signature scope β a single foreign-scope item+ * would make OpenAI reject the whole request, so fail closed to the legacy path.+ */+ const resolveResponseItems = (): OpenAI.Responses.ResponseReasoningItem[] | undefined => {+ const responseItems = reasoning?.responseItems;+ if (!responseItems?.length) return undefined;++ const resolved: OpenAI.Responses.ResponseReasoningItem[] = [];+ for (const item of responseItems) {+ if (item.encrypted_content) {+ const encryptedContent = resolveScopedSignature(+ item.encrypted_content,+ options?.reasoningSignatureScope,+ 'reasoning',+ );+ if (!encryptedContent) return undefined;++ resolved.push({+ ...item,+ encrypted_content: encryptedContent,+ } as OpenAI.Responses.ResponseReasoningItem);+ } else {+ /**+ * Without encrypted content the server cannot look the item up by id in a+ * stateless request, so drop the id and replay the visible summary only.+ */+ const { id: _id, ...rest } = item;+ resolved.push(rest as unknown as OpenAI.Responses.ResponseReasoningItem);+ }+ }++ return resolved;+ };++ const replayableResponseItems = resolveResponseItems();++ if (replayableResponseItems) {+ // Replay complete reasoning items verbatim and in original stream order.+ items.push(...replayableResponseItems);+ } else {+ const encryptedContent = resolveScopedSignature(+ reasoning?.signature,+ options?.reasoningSignatureScope,+ 'reasoning',+ );++ // Preserve encrypted reasoning state for stateless Responses API requests.+ if (reasoning?.content || encryptedContent) {+ items.push({+ encrypted_content: encryptedContent,+ summary: reasoning?.content ? [{ text: reasoning.content, type: 'summary_text' }] : [],+ type: 'reasoning',+ } as OpenAI.Responses.ResponseReasoningItem);+ }}// if message is assistant messages with tool calls , transform it to function type itemdiff --git a/packages/model-runtime/src/core/streams/openai/__snapshots__/responsesStream.test.ts.snap b/packages/model-runtime/src/core/streams/openai/__snapshots__/responsesStream.test.ts.snapindex 6965e0190fc..daa2ee19e37 100644--- a/packages/model-runtime/src/core/streams/openai/__snapshots__/responsesStream.test.ts.snap+++ b/packages/model-runtime/src/core/streams/openai/__snapshots__/responsesStream.test.ts.snap@@ -88,9 +88,9 @@ exports[`OpenAIResponsesStream > Reasoning > summary 1`] = `","id: rs_684313b9774481908ee856625f82fb8c0b502bf083132d0d",- "event: text+ "event: reasoning_response_item",- "data: null+ "data: {"id":"rs_684313b9774481908ee856625f82fb8c0b502bf083132d0d","type":"reasoning","summary":[{"type":"summary_text","text":"**Answering a numeric comparison**\\n\\nThe user is asking in Chinese which number is larger: 9.1 or 9.92. This is straightforward since 9.92 is clearly larger, as it's greater than 9.1. We can respond with \\"9.92ε€§δΊ9.1\\" without needing to search for more information. It's simple comparison, but I could also add a little explanation, noting that 9.92 is indeed 0.82 more than 9.1. However, keeping it simple with \\"9.92 > 9.1\\" is perfectly fine!"}]}","id: resp_684313b89200819087f27686e0c822260b502bf083132d0ddiff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.test.tsindex 8f1504d8bd3..b13dc68b603 100644--- a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts@@ -766,6 +766,108 @@ describe('OpenAIResponsesStream', () => {expect(chunks.some((chunk) => chunk.includes('encrypted-reasoning-content'))).toBe(false);});+ it('should emit complete reasoning items alongside the legacy signature event', async () => {+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'b'.repeat(32) };+ const mockOpenAIStream = createReadableStream([+ {+ type: 'response.output_item.done',+ output_index: 0,+ item: {+ encrypted_content: 'encrypted-part-1',+ id: 'rs_item_1',+ status: 'completed',+ summary: [{ text: 'first summary', type: 'summary_text' }],+ type: 'reasoning',+ },+ },+ {+ type: 'response.output_item.done',+ output_index: 1,+ item: {+ encrypted_content: 'encrypted-part-2',+ id: 'rs_item_2',+ status: 'completed',+ summary: [],+ type: 'reasoning',+ },+ },+ ]);++ const protocolStream = OpenAIResponsesStream(mockOpenAIStream, {+ payload: { reasoningSignatureScope },+ });+ const chunks = await readStreamChunk(protocolStream);+ const itemEvents = chunks.filter((chunk) => chunk.includes('event: reasoning_response_item'));+ const scopedFirst = serializeScopedSignature(+ 'encrypted-part-1',+ reasoningSignatureScope,+ 'reasoning',+ )!;+ const scopedSecond = serializeScopedSignature(+ 'encrypted-part-2',+ reasoningSignatureScope,+ 'reasoning',+ )!;++ // both items are emitted as structured events, preserving stream order+ expect(itemEvents).toHaveLength(2);+ const firstIndex = chunks.findIndex((chunk) => chunk.includes('rs_item_1'));+ const secondIndex = chunks.findIndex((chunk) => chunk.includes('rs_item_2'));+ expect(firstIndex).toBeGreaterThan(-1);+ expect(secondIndex).toBeGreaterThan(firstIndex);++ // encrypted content is only ever exposed in its scope-serialized envelope+ expect(chunks.some((chunk) => chunk.includes(scopedFirst))).toBe(true);+ expect(chunks.some((chunk) => chunk.includes(scopedSecond))).toBe(true);+ expect(chunks.some((chunk) => /data:.*"encrypted-part-1"/.test(chunk))).toBe(false);++ // legacy string-only event is still emitted for released clients+ expect(chunks.some((chunk) => chunk.includes('event: reasoning_signature'))).toBe(true);+ });++ it('should emit hidden reasoning items without visible summary as structured events', async () => {+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'c'.repeat(32) };+ const mockOpenAIStream = createReadableStream([+ {+ type: 'response.output_item.done',+ output_index: 0,+ item: {+ encrypted_content: 'hidden-encrypted',+ id: 'rs_hidden',+ summary: [],+ type: 'reasoning',+ },+ },+ ]);++ const protocolStream = OpenAIResponsesStream(mockOpenAIStream, {+ payload: { reasoningSignatureScope },+ });+ const chunks = await readStreamChunk(protocolStream);++ expect(chunks.some((chunk) => chunk.includes('event: reasoning_response_item'))).toBe(true);+ });++ it('should drop reasoning items that have neither scoped encrypted content nor summary', async () => {+ const mockOpenAIStream = createReadableStream([+ {+ type: 'response.output_item.done',+ output_index: 0,+ item: {+ encrypted_content: 'unscoped-encrypted',+ id: 'rs_unscoped',+ summary: [],+ type: 'reasoning',+ },+ },+ ]);++ const chunks = await readStreamChunk(OpenAIResponsesStream(mockOpenAIStream));++ expect(chunks.some((chunk) => chunk.includes('event: reasoning_response_item'))).toBe(false);+ expect(chunks.some((chunk) => chunk.includes('unscoped-encrypted'))).toBe(false);+ });+it('should handle response.completed with usage', async () => {const mockOpenAIStream = createReadableStream([{diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.tsindex f60645019de..fb1441694f0 100644--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts@@ -147,19 +147,45 @@ 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' };+ if (chunk.item.type === 'reasoning') {+ const scopedEncryptedContent = chunk.item.encrypted_content+ ? serializeScopedSignature(+ chunk.item.encrypted_content,+ payload?.reasoningSignatureScope,+ 'reasoning',+ )+ : undefined;+ const hasSummaryText = chunk.item.summary?.some(({ text }) => !!text);- return {- data: signature,- id: chunk.item.id,- type: 'reasoning_signature',- };+ // Encrypted reasoning without a verifiable scope stays fail-closed (#17694):+ // never expose the raw provider payload to persistence.+ if (!scopedEncryptedContent && !hasSummaryText)+ return { data: null, id: chunk.item.id, type: 'text' };++ const chunks: StreamProtocolChunk[] = [+ {+ data: {+ ...chunk.item,+ encrypted_content: scopedEncryptedContent,+ },+ id: chunk.item.id,+ type: 'reasoning_response_item',+ },+ ];++ /**+ * Dual-emit the scope-serialized payload on the legacy string-only event so+ * already-released clients keep single-item reasoning continuation. New clients+ * prefer `responseItems` on replay, so the redundancy is harmless.+ */+ if (scopedEncryptedContent)+ chunks.push({+ data: scopedEncryptedContent,+ id: chunk.item.id,+ type: 'reasoning_signature',+ });++ return chunks;}if (streamContext.returnedCitationArray?.length) {diff --git a/packages/model-runtime/src/core/streams/protocol.test.ts b/packages/model-runtime/src/core/streams/protocol.test.tsindex f2f131394a1..959a0a766cf 100644--- a/packages/model-runtime/src/core/streams/protocol.test.ts+++ b/packages/model-runtime/src/core/streams/protocol.test.ts@@ -743,6 +743,169 @@ describe('createCallbacksTransformer', () => {);});+ it('should aggregate reasoning response items in stream order', async () => {+ const onCompletion = vi.fn();+ const transformer = createCallbacksTransformer({ onCompletion });++ const firstItem = {+ encrypted_content: 'scoped-encrypted-1',+ id: 'rs_1',+ summary: [{ text: 'visible summary', type: 'summary_text' }],+ type: 'reasoning',+ };+ const secondItem = {+ encrypted_content: 'scoped-encrypted-2',+ id: 'rs_2',+ summary: [],+ type: 'reasoning',+ };++ const chunks = [+ 'event: reasoning\n',+ 'data: "visible summary"\n\n',+ 'event: reasoning_response_item\n',+ `data: ${JSON.stringify(firstItem)}\n\n`,+ 'event: reasoning_response_item\n',+ `data: ${JSON.stringify(secondItem)}\n\n`,+ ];++ await processChunks(transformer, chunks);++ expect(onCompletion).toHaveBeenCalledWith(+ expect.objectContaining({+ reasoning: {+ content: 'visible summary',+ responseItems: [firstItem, secondItem],+ signature: undefined,+ },+ }),+ );+ });++ it('should derive thinking content from item summaries when nothing was streamed', async () => {+ const onCompletion = vi.fn();+ const transformer = createCallbacksTransformer({ onCompletion });++ const firstItem = {+ encrypted_content: 'scoped-encrypted-1',+ id: 'rs_1',+ summary: [{ text: 'first summary', type: 'summary_text' }],+ type: 'reasoning',+ };+ const secondItem = {+ encrypted_content: 'scoped-encrypted-2',+ id: 'rs_2',+ summary: [{ text: 'second summary', type: 'summary_text' }],+ type: 'reasoning',+ };++ // no `reasoning` delta events β mirrors the non-streaming Responses conversion+ const chunks = [+ 'event: reasoning_response_item\n',+ `data: ${JSON.stringify(firstItem)}\n\n`,+ 'event: reasoning_response_item\n',+ `data: ${JSON.stringify(secondItem)}\n\n`,+ ];++ await processChunks(transformer, chunks);++ expect(onCompletion).toHaveBeenCalledWith(+ expect.objectContaining({+ reasoning: {+ content: 'first summary\nsecond summary',+ responseItems: [firstItem, secondItem],+ signature: undefined,+ },+ thinking: 'first summary\nsecond summary',+ }),+ );+ });++ it('should keep reasoning items whose summary text contains a data: marker', async () => {+ const onCompletion = vi.fn();+ const transformer = createCallbacksTransformer({ onCompletion });++ const firstItem = {+ encrypted_content: 'scoped-encrypted-1',+ id: 'rs_1',+ summary: [{ text: 'Inspect data: sources.', type: 'summary_text' }],+ type: 'reasoning',+ };+ const secondItem = {+ encrypted_content: 'scoped-encrypted-2',+ id: 'rs_2',+ summary: [],+ type: 'reasoning',+ };++ const chunks = [+ 'event: reasoning_response_item\n',+ `data: ${JSON.stringify(firstItem)}\n\n`,+ 'event: reasoning_response_item\n',+ `data: ${JSON.stringify(secondItem)}\n\n`,+ ];++ await processChunks(transformer, chunks);++ expect(onCompletion).toHaveBeenCalledWith(+ expect.objectContaining({+ reasoning: expect.objectContaining({+ responseItems: [firstItem, secondItem],+ }),+ }),+ );+ });++ it('should keep reasoning with response items but no visible content', async () => {+ const onCompletion = vi.fn();+ const transformer = createCallbacksTransformer({ onCompletion });++ const hiddenItem = {+ encrypted_content: 'scoped-hidden',+ id: 'rs_hidden',+ summary: [],+ type: 'reasoning',+ };++ const chunks = ['event: reasoning_response_item\n', `data: ${JSON.stringify(hiddenItem)}\n\n`];++ await processChunks(transformer, chunks);++ expect(onCompletion).toHaveBeenCalledWith(+ expect.objectContaining({+ reasoning: {+ content: undefined,+ responseItems: [hiddenItem],+ signature: undefined,+ },+ }),+ );+ });++ it('should ignore non-string payloads on the reasoning_signature event', async () => {+ const onCompletion = vi.fn();+ const transformer = createCallbacksTransformer({ onCompletion });++ const chunks = [+ 'event: reasoning\n',+ 'data: "Thinking..."\n\n',+ 'event: reasoning_signature\n',+ `data: ${JSON.stringify({ id: 'rs_1', type: 'reasoning' })}\n\n`,+ ];++ await processChunks(transformer, chunks);++ expect(onCompletion).toHaveBeenCalledWith(+ expect.objectContaining({+ reasoning: {+ content: 'Thinking...',+ responseItems: undefined,+ signature: undefined,+ },+ }),+ );+ });+it('should handle base64_image chunks and call onBase64Image callback', async () => {const receivedCalls: Array<{image: { id: string; data: string };diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.tsindex 1e99f7618eb..349e5dfb43d 100644--- a/packages/model-runtime/src/core/streams/protocol.ts+++ b/packages/model-runtime/src/core/streams/protocol.ts@@ -1,4 +1,9 @@-import type { ChatCitationItem, ModelPerformance, ModelUsage } from '@lobechat/types';+import type {+ ChatCitationItem,+ ModelPerformance,+ ModelReasoningResponseItem,+ ModelUsage,+} from '@lobechat/types';import type { Pricing } from 'model-bank';import { parseToolCalls } from '../../helpers';@@ -113,6 +118,8 @@ export interface StreamProtocolChunk {| 'reasoning'// use for reasoning signature, maybe only anthropic| 'reasoning_signature'+ // complete OpenAI Responses reasoning item persisted for stateless replay+ | 'reasoning_response_item'// flagged reasoning signature| 'flagged_reasoning_signature'// multimodal content part in reasoning@@ -441,6 +448,7 @@ export function createCallbacksTransformer(let aggregatedText = '';let aggregatedThinking: string | undefined = undefined;let reasoningSignature: string | undefined;+ const reasoningResponseItems: ModelReasoningResponseItem[] = [];let usage: ModelUsage | undefined;let speed: ModelPerformance | undefined;let grounding: any;@@ -455,19 +463,32 @@ export function createCallbacksTransformer(return new TransformStream<string, Uint8Array>({async flush(): Promise<void> {+ /**+ * Non-streaming Responses conversion emits reasoning items without summary+ * deltas, so derive visible thinking text from the item summaries whenever+ * nothing was streamed β otherwise the summary would persist but never render.+ */+ const responseItemsThinking = reasoningResponseItems+ .flatMap(({ summary }) => summary ?? [])+ .map(({ text }) => text)+ .filter(Boolean)+ .join('\n');+ const reasoningContent = aggregatedThinking || responseItemsThinking || undefined;+const data: OnFinishData = {error: streamError,finishReason,grounding,speed,text: aggregatedText,- thinking: aggregatedThinking,+ thinking: reasoningContent,toolsCalling,usage,};- if (aggregatedThinking || reasoningSignature) {+ if (reasoningContent || reasoningSignature || reasoningResponseItems.length > 0) {data.reasoning = {- content: aggregatedThinking,+ content: reasoningContent,+ responseItems: reasoningResponseItems.length > 0 ? reasoningResponseItems : undefined,signature: reasoningSignature,};}@@ -499,12 +520,13 @@ export function createCallbacksTransformer(// if the message is a data chunk, handle the callbackelse if (chunk.startsWith('data:')) {// `base64_image` payloads are raw data-URIs (`data:image/png;base64,...`)- // that contain `data:` themselves, which the legacy `split('data:')[1]`- // corrupts (it splits on the embedded marker too). Strip only the leading- // field marker for that type; every other event type keeps the original- // split path unchanged for compatibility.+ // and `reasoning_response_item` payloads carry arbitrary model-authored+ // summary text β both can contain `data:` themselves, which the legacy+ // `split('data:')[1]` corrupts (it splits on the embedded marker too).+ // Strip only the leading field marker for those types; every other event+ // type keeps the original split path unchanged for compatibility.const content =- currentType === 'base64_image'+ currentType === 'base64_image' || currentType === 'reasoning_response_item'? chunk.slice('data:'.length).trim(): chunk.split('data:')[1].trim();@@ -530,7 +552,12 @@ export function createCallbacksTransformer(}case 'reasoning_signature': {- reasoningSignature = data;+ if (typeof data === 'string') reasoningSignature = data;+ break;+ }++ case 'reasoning_response_item': {+ reasoningResponseItems.push(data as ModelReasoningResponseItem);break;}diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex 7ee00f22b09..37c51692115 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -60,11 +60,7 @@ export interface OpenAIChatMessage {model?: string;name?: string;provider?: string;- reasoning?: {- content?: string;- duration?: number;- signature?: string;- };+ reasoning?: ModelReasoning;reasoning_content?: string;role: LLMRoleType;tool_call_id?: string;diff --git a/packages/types/src/message/common/base.ts b/packages/types/src/message/common/base.tsindex 8277280d7ac..2375c4deab5 100644--- a/packages/types/src/message/common/base.ts+++ b/packages/types/src/message/common/base.ts@@ -84,6 +84,22 @@ export interface MessageContentPartImage {export type MessageContentPart = MessageContentPartText | MessageContentPartImage;+/**+ * Original OpenAI Responses reasoning output item persisted verbatim so multi-turn+ * stateless requests can replay it unchanged. `encrypted_content` holds the+ * scope-serialized envelope produced by `serializeScopedSignature`, never the raw+ * provider payload.+ */+export interface ModelReasoningResponseItem {+ [key: string]: unknown;+ content?: Array<Record<string, unknown>>;+ encrypted_content?: string | null;+ id: string;+ status?: 'in_progress' | 'completed' | 'incomplete';+ summary: Array<{ text: string; type: 'summary_text' }>;+ type: 'reasoning';+}+export interface ModelReasoning {/*** Reasoning content, can be plain string or serialized JSON array of MessageContentPart[]@@ -94,13 +110,30 @@ export interface ModelReasoning {* Flag indicating if content is multimodal (serialized MessageContentPart[])*/isMultimodal?: boolean;+ /**+ * Complete OpenAI Responses reasoning items in original stream order; preferred+ * over the scalar `signature` when replaying to the Responses API+ */+ responseItems?: ModelReasoningResponseItem[];signature?: string;tempDisplayContent?: MessageContentPart[];}+export const ModelReasoningResponseItemSchema = z+ .object({+ content: z.array(z.record(z.string(), z.unknown())).optional(),+ encrypted_content: z.string().nullish(),+ id: z.string(),+ status: z.enum(['in_progress', 'completed', 'incomplete']).optional(),+ summary: z.array(z.object({ text: z.string(), type: z.literal('summary_text') })),+ type: z.literal('reasoning'),+ })+ .passthrough();+export const ModelReasoningSchema = z.object({content: z.string().optional(),duration: z.number().optional(),isMultimodal: z.boolean().optional(),+ responseItems: z.array(ModelReasoningResponseItemSchema).optional(),signature: z.string().optional(),});diff --git a/packages/types/src/openai/chat.ts b/packages/types/src/openai/chat.tsindex 86b2e0a3925..b46f36cc3f7 100644--- a/packages/types/src/openai/chat.ts+++ b/packages/types/src/openai/chat.ts@@ -1,5 +1,5 @@import type { LLMRoleType } from '../llm';-import type { MessageToolCall } from '../message';+import type { MessageToolCall, ModelReasoning } from '../message';import type { OpenAIFunctionCall } from './functionCall';export type ChatResponseFormat =@@ -62,11 +62,7 @@ export interface OpenAIChatMessage {model?: string;name?: string;provider?: string;- reasoning?: {- content?: string;- duration?: number;- signature?: string;- };+ reasoning?: ModelReasoning;reasoning_content?: string;/*** Rolediff --git a/src/store/chat/agents/StreamingHandler.test.ts b/src/store/chat/agents/StreamingHandler.test.tsindex 8a45dfafec3..aff0a02bff0 100644--- a/src/store/chat/agents/StreamingHandler.test.ts+++ b/src/store/chat/agents/StreamingHandler.test.ts@@ -592,6 +592,53 @@ describe('StreamingHandler', () => {expect(result.metadata.reasoning?.content).toBeUndefined();expect(result.metadata.reasoning?.signature).toBe('signature-only');});++ it('should preserve response items when only hidden reasoning items exist', async () => {+ const callbacks = createMockCallbacks();+ const handler = new StreamingHandler(mockContext, callbacks);+ const responseItem = {+ encrypted_content: 'scoped-encrypted',+ id: 'rs_hidden',+ summary: [],+ type: 'reasoning' as const,+ };++ handler.handleChunk({ type: 'text', text: 'Content' });++ const result = await handler.handleFinish({+ type: 'stop',+ reasoning: { responseItems: [responseItem] },+ });++ expect(result.metadata.reasoning?.responseItems).toEqual([responseItem]);+ });++ it('should carry response items alongside streamed thinking content', async () => {+ const callbacks = createMockCallbacks();+ const handler = new StreamingHandler(mockContext, callbacks);+ const responseItem = {+ encrypted_content: 'scoped-encrypted',+ id: 'rs_1',+ summary: [{ text: 'streamed thinking', type: 'summary_text' as const }],+ type: 'reasoning' as const,+ };++ handler.handleChunk({ type: 'reasoning', text: 'streamed thinking' });+ handler.handleChunk({ type: 'text', text: 'Content' });++ const result = await handler.handleFinish({+ type: 'stop',+ reasoning: {+ content: 'streamed thinking',+ responseItems: [responseItem],+ signature: 'scoped-signature',+ },+ });++ expect(result.metadata.reasoning?.content).toBe('streamed thinking');+ expect(result.metadata.reasoning?.responseItems).toEqual([responseItem]);+ expect(result.metadata.reasoning?.signature).toBe('scoped-signature');+ });});describe('getter methods', () => {diff --git a/src/store/chat/agents/StreamingHandler.ts b/src/store/chat/agents/StreamingHandler.tsindex ac4aa0b7681..0cb233ff097 100644--- a/src/store/chat/agents/StreamingHandler.ts+++ b/src/store/chat/agents/StreamingHandler.ts@@ -522,6 +522,8 @@ export class StreamingHandler {// Get signature from finishData.reasoning (provided by backend in onFinish)const reasoningSignature = finishData.reasoning?.signature;+ // Hidden Responses reasoning items stay replayable without any visible content+ const hasResponseItems = !!finishData.reasoning?.responseItems?.length;let finalReasoning: ReasoningState | undefined;if (hasReasoningImages) {@@ -533,11 +535,11 @@ export class StreamingHandler {};} else if (this.thinkingContent) {finalReasoning = {+ ...finishData.reasoning,content: this.thinkingContent,duration: finalDuration,- signature: reasoningSignature,};- } else if (finishData.reasoning?.content || reasoningSignature) {+ } else if (finishData.reasoning?.content || reasoningSignature || hasResponseItems) {finalReasoning = {...finishData.reasoning,duration: finalDuration,diff --git a/src/store/chat/agents/types/streaming.ts b/src/store/chat/agents/types/streaming.tsindex 31a0f8fcf23..e72aa6b46b6 100644--- a/src/store/chat/agents/types/streaming.ts+++ b/src/store/chat/agents/types/streaming.ts@@ -2,9 +2,9 @@ import {type ChatImageItem,type ChatToolPayload,type GroundingSearch,- type MessageContentPart,type MessageToolCall,type ModelPerformance,+ type ModelReasoning,type ModelUsage,} from '@lobechat/types';@@ -20,15 +20,9 @@ export interface StreamingContext {}/**- * Reasoning state+ * Reasoning state β same shape as the persisted message reasoning metadata*/-export interface ReasoningState {- content?: string;- duration?: number;- isMultimodal?: boolean;- signature?: string;- tempDisplayContent?: MessageContentPart[];-}+export type ReasoningState = ModelReasoning;/*** Grounding/search data - extends GroundingSearch for compatibility@@ -71,7 +65,7 @@ export interface StreamingCallbacks {export interface FinishData {grounding?: GroundingData;observationId?: string | null;- reasoning?: { content?: string; signature?: string };+ reasoning?: ModelReasoning;speed?: ModelPerformance;toolCalls?: MessageToolCall[];traceId?: string | null;