π€― 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(model-runtime): thinking signature crash, mid-stream error hooks (#19882)
YuTengjing0c7795454ea8
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 25d04cad93e..330324e3981 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -5458,7 +5458,11 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {});return new Response(source.pipeThrough(createCallbacksTransformer(callbacks)));});- vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);+ const handleChatStreamError = vi.fn();+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({+ chat: mockChat,+ handleChatStreamError,+ } as any);const executors = createRuntimeExecutors(ctx);const state = createMockState();@@ -5483,6 +5487,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {await rejectionExpectation;expect(mockChat).toHaveBeenCalledTimes(6);+ // Every attempt is its own `chat()` call, so each failed stream is reported once.+ expect(handleChatStreamError).toHaveBeenCalledTimes(6);const retryEvents = mockStreamManager.publishStreamEvent.mock.calls.filter(([, event]: [string, { type: string }]) => event.type === 'stream_retry',diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex b2e2addc393..bbd5fff08c4 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -312,7 +312,7 @@ export class ServerLLMTransport implements LLMTransport {private async runAttemptWithRuntime(input: LLMAttemptInput,- modelRuntime: Pick<ModelRuntime, 'chat'>,+ modelRuntime: Pick<ModelRuntime, 'chat' | 'handleChatStreamError'>,): Promise<LLMAttemptExecution> {const resolved = input.context.resolvedTools;if (!resolved) throw new Error('Resolved tools are required for a server LLM attempt');diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.tsindex 541d220ef5d..6368f459048 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts@@ -4,11 +4,21 @@ import type { ChatMethodOptions, ModelRuntime } from '@lobechat/model-runtime';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { RuntimeExecutorContext } from '../context';+import { formatErrorForState } from '../formatErrorForState';import { createServerCallLlmAttempt } from './serverCallLlmAttempt';import type { ServerCallLlmTooling } from './serverCallLlmTooling';const recordModelCompletionFailureMock = vi.hoisted(() => vi.fn());+/**+ * Behaves like a real runtime error hook: the trace id is attached only after an async side+ * effect (writing the error log), so the attempt must await the hook before rethrowing.+ */+const attachTraceIdLater = async (error: { _responseBody?: unknown }) => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ error._responseBody = { traceId: 'trace-1' };+};+vi.mock('@lobechat/model-runtime', async () => {const { isEmptyModelCompletion, ModelEmptyError } =await import('../../../../../../packages/model-runtime/src/errors/modelEmptyCompletion');@@ -79,6 +89,7 @@ const createAttempt = (await runCallbacks(options!);return new Response('done');});+ const handleChatStreamError = vi.fn();const events: AgentEvent[] = [];const onFirstChunk = vi.fn();const attempt = createServerCallLlmAttempt({@@ -95,7 +106,10 @@ const createAttempt = (maxAttempts: 3,messageCount: 1,model: 'test-model',- modelRuntime: { chat } as unknown as Pick<ModelRuntime, 'chat'>,+ modelRuntime: { chat, handleChatStreamError } as unknown as Pick<+ ModelRuntime,+ 'chat' | 'handleChatStreamError'+ >,onFirstChunk,operationLogId: 'operation-1:2',provider: 'test-provider',@@ -105,7 +119,7 @@ const createAttempt = (...attemptOverrides,});- return { attempt, chat, events, onFirstChunk, publishStreamChunk };+ return { attempt, chat, events, handleChatStreamError, onFirstChunk, publishStreamChunk };};describe('ServerCallLlmAttempt', () => {@@ -321,6 +335,96 @@ describe('ServerCallLlmAttempt', () => {expect(recordModelCompletionFailureMock).not.toHaveBeenCalled();});+ it('stores an in-band stream error with the trace id attached by the error hook', async () => {+ const { attempt, handleChatStreamError } = createAttempt(async ({ callback }) => {+ await callback?.onError?.({ errorType: 'ProviderBizError', message: 'Provider timed out' });+ });+ handleChatStreamError.mockImplementation(attachTraceIdLater);++ const error = await attempt.execute().catch((error: unknown) => error);++ expect(error).toMatchObject({ message: 'LLM stream error: Provider timed out' });+ expect(handleChatStreamError).toHaveBeenCalledWith(error, {+ options: expect.objectContaining({+ metadata: expect.objectContaining({ operationId: 'operation-1' }),+ }),+ payload: expect.objectContaining({ model: 'test-model' }),+ });+ expect(formatErrorForState(error).body).toMatchObject({ traceId: 'trace-1' });+ });++ it('stores a fallback failure raised mid-stream with the error hook trace id', async () => {+ const fallbackError = {+ error: { message: 'Access to Anthropic models is not allowed for this account.' },+ errorType: 'ProviderBizError',+ provider: 'lobehub',+ };+ const { attempt, chat, handleChatStreamError } = createAttempt(async () => {});+ chat.mockImplementationOnce(+ async () =>+ new Response(+ new ReadableStream({+ pull(controller) {+ controller.error(fallbackError);+ },+ }),+ ),+ );++ handleChatStreamError.mockImplementation(attachTraceIdLater);++ await expect(attempt.execute()).rejects.toBe(fallbackError);+ expect(handleChatStreamError).toHaveBeenCalledWith(fallbackError, expect.anything());+ expect(formatErrorForState(fallbackError).body).toMatchObject({ traceId: 'trace-1' });+ });++ it('stores a plain stream read failure with the error hook trace id', async () => {+ const readError = new TypeError('terminated');+ const { attempt, chat, handleChatStreamError } = createAttempt(async () => {});+ chat.mockImplementationOnce(+ async () =>+ new Response(+ new ReadableStream({+ pull(controller) {+ controller.error(readError);+ },+ }),+ ),+ );+ handleChatStreamError.mockImplementation(attachTraceIdLater);++ await expect(attempt.execute()).rejects.toBe(readError);+ expect(formatErrorForState(readError).body).toMatchObject({ traceId: 'trace-1' });+ });++ it('leaves errors thrown by chat() and empty completions to their own handlers', async () => {+ const { attempt: rejected, handleChatStreamError: rejectedHook } = createAttempt(async () => {+ throw new Error('upstream request failed');+ });+ await expect(rejected.execute()).rejects.toThrow('upstream request failed');+ expect(rejectedHook).not.toHaveBeenCalled();++ const { ModelEmptyError } = await import('@lobechat/model-runtime');+ const emptyError = new ModelEmptyError();+ const {+ attempt: empty,+ chat,+ handleChatStreamError: emptyHook,+ } = createAttempt(async () => {});+ chat.mockImplementationOnce(+ async () =>+ new Response(+ new ReadableStream({+ pull(controller) {+ controller.error(emptyError);+ },+ }),+ ),+ );+ await expect(empty.execute()).rejects.toBe(emptyError);+ expect(emptyHook).not.toHaveBeenCalled();+ });+it('salvages a natural-stop answer emitted only in reasoning', async () => {const { attempt } = createAttempt(async ({ callback }) => {await callback?.onThinking?.('Final answer from reasoning');diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.tsindex 79392e0d947..1e44692f67f 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts@@ -2,6 +2,7 @@ import type { AgentEvent, BlobStore, LLMAttemptOutput } from '@lobechat/agent-ruimport { ToolNameResolver } from '@lobechat/context-engine';import type {Base64ImageData,+ ChatMethodOptions,ChatStreamPayload,ContentPartData,ModelRuntime,@@ -56,7 +57,7 @@ interface CreateServerCallLlmAttemptInput {maxAttempts: number;messageCount: number;model: string;- modelRuntime: Pick<ModelRuntime, 'chat'>;+ modelRuntime: Pick<ModelRuntime, 'chat' | 'handleChatStreamError'>;onFirstChunk: () => void;operationLogId: string;provider: string;@@ -141,7 +142,7 @@ export class ServerCallLlmAttempt {private readonly maxAttempts: number;private readonly messageCount: number;private readonly model: string;- private readonly modelRuntime: Pick<ModelRuntime, 'chat'>;+ private readonly modelRuntime: Pick<ModelRuntime, 'chat' | 'handleChatStreamError'>;private readonly onFirstChunk: () => void;private readonly operationLogId: string;private readonly provider: string;@@ -240,7 +241,7 @@ export class ServerCallLlmAttempt {this.chatPayload.tools?.length ?? 0,);- const response = await this.modelRuntime.chat(this.chatPayload, {+ const chatOptions: ChatMethodOptions = {callback: {onBase64Image: async ({ image }) => {this.onFirstChunk();@@ -331,11 +332,17 @@ export class ServerCallLlmAttempt {diagnostics: this.runtimeDiagnostics,metadata: this.runtimeMetadata,user: this.ctx.userId,- });+ };+ const response = await this.modelRuntime.chat(this.chatPayload, chatOptions);- await consumeStreamUntilDone(response);+ try {+ await consumeStreamUntilDone(response);- if (this.streamError) throw createStreamExecutionError(this.streamError);+ if (this.streamError) throw createStreamExecutionError(this.streamError);+ } catch (error) {+ await this.reportStreamFailure(error, chatOptions);+ throw error;+ }await this.streamSink.flushTextBuffer();await this.streamSink.flushReasoningBuffer();@@ -375,6 +382,20 @@ export class ServerCallLlmAttempt {};}+ /**+ * `chat()` has already returned here, so its `onChatError` hook never sees these failures β+ * including routed fallbacks that all fail mid-stream. Report them so they get the same+ * sanitizing and error logging, and a trace id for the error card.+ */+ private async reportStreamFailure(error: unknown, options: ChatMethodOptions) {+ // Empty completions and refusals carry their own classification and UI.+ if (error instanceof ModelEmptyError || error instanceof ModelRefusalError) return;+ if (this.runtimeDiagnostics.providerResponse?.aborted) return;+ if (await isOperationInterrupted(this.ctx)) return;++ await this.modelRuntime.handleChatStreamError(error, { options, payload: this.chatPayload });+ }+private async assertNonEmptyCompletion() {const imageCount = this.getOutputImageCount();const isRefusal = this.finishReason?.toLowerCase() === 'refusal';diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.tsindex 11733967b30..5d5ac50b5d8 100644--- a/packages/model-runtime/src/core/ModelRuntime.test.ts+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts@@ -657,6 +657,32 @@ describe('ModelRuntime', () => {await expect(runtime.chat(chatPayload)).resolves.toBeInstanceOf(Response);});++ it('handleChatStreamError forwards a stream failure to onChatStreamError', async () => {+ const streamError = { errorType: 'ProviderBizError', error: { message: 'fail' } };+ const options = { metadata: { trigger: 'chat' } };+ const onChatStreamError = vi.fn();+ const { runtime } = createMockRuntime({ onChatStreamError });++ await runtime.handleChatStreamError(streamError, { options, payload: chatPayload });++ expect(onChatStreamError).toHaveBeenCalledWith(streamError, {+ options,+ payload: chatPayload,+ });+ });++ it('handleChatStreamError keeps a failing hook from replacing the stream error', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const onChatStreamError = vi.fn().mockRejectedValue(new Error('hook failed'));+ const { runtime } = createMockRuntime({ onChatStreamError });++ await expect(+ runtime.handleChatStreamError(new Error('stream failed'), { payload: chatPayload }),+ ).resolves.toBeUndefined();+ expect(consoleError).toHaveBeenCalled();+ consoleError.mockRestore();+ });});describe('generateObject hooks', () => {diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex d72d4efa0e5..dee393ee973 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -98,6 +98,22 @@ export interface ModelRuntimeHooks {context: { options?: ChatMethodOptions; payload: ChatStreamPayload },) => void | Promise<void>;+ /**+ * Called when a chat stream fails after `chat()` has already returned its response: an+ * in-band provider `error` event, or a body read failure such as every routed fallback+ * failing mid-stream. `onChatError` never sees these. Same side-effect contract (sanitize,+ * log, record, release held reservations).+ *+ * `onChatFinal` may or may not have run first: a committed attempt delivers it before the+ * error surfaces, but a routed fallback whose earlier attempts were discarded and whose last+ * attempt failed to start delivers none. Releases here must therefore be no-ops once+ * `onChatFinal` has charged the request.+ */+ onChatStreamError?: (+ error: unknown,+ context: { options?: ChatMethodOptions; payload: ChatStreamPayload },+ ) => void | Promise<void>;+onEmbeddingsError?: (error: ChatCompletionErrorPayload,context: { options?: EmbeddingsOptions; payload: EmbeddingsPayload },@@ -244,6 +260,21 @@ export class ModelRuntime {}}+ /**+ * Report a chat stream failure that surfaced after `chat()` returned, for callers that consume+ * the response. Hook failures are logged so they never replace the stream error itself.+ */+ async handleChatStreamError(+ error: unknown,+ context: { options?: ChatMethodOptions; payload: ChatStreamPayload },+ ) {+ try {+ await this._hooks?.onChatStreamError?.(error, context);+ } catch (hookError) {+ console.error('[ModelRuntime] onChatStreamError hook failed:', hookError);+ }+ }+/*** Apply lifecycle hooks: beforeChat (budget check) + onChatFinal (cost tracking callback injection).*/diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.tsindex 985db8e380c..3b4a3eecf54 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts@@ -583,6 +583,104 @@ describe('createAnthropicCompatibleRuntime', () => {);});+ it('should keep streaming when a thinking block starts without a signature', async () => {+ // Aihubmix omits `signature` on thinking `content_block_start`; Anthropic sends ''.+ const rawEvents = [+ {+ message: {+ content: [],+ id: 'msg_missing_signature',+ model: 'claude-opus-5-5',+ role: 'assistant',+ stop_reason: null,+ stop_sequence: null,+ type: 'message',+ usage: { input_tokens: 12, output_tokens: 0 },+ },+ type: 'message_start',+ },+ {+ content_block: { thinking: '', type: 'thinking' },+ index: 0,+ type: 'content_block_start',+ },+ {+ delta: { thinking: 'Plan', type: 'thinking_delta' },+ index: 0,+ type: 'content_block_delta',+ },+ { index: 0, type: 'content_block_stop' },+ {+ content_block: { text: '', type: 'text' },+ index: 1,+ type: 'content_block_start',+ },+ {+ delta: { text: 'Final answer', type: 'text_delta' },+ index: 1,+ type: 'content_block_delta',+ },+ { index: 1, type: 'content_block_stop' },+ {+ delta: { stop_reason: 'end_turn', stop_sequence: null },+ type: 'message_delta',+ usage: { input_tokens: 12, output_tokens: 8 },+ },+ { type: 'message_stop' },+ ] as unknown as Anthropic.MessageStreamEvent[];+ const rawStream = {+ async *[Symbol.asyncIterator]() {+ for (const event of rawEvents) yield event;+ },+ };+ const messagesCreate = vi.fn(() => ({+ withResponse: vi.fn().mockResolvedValue({ data: rawStream }),+ }));+ const Runtime = createAnthropicCompatibleRuntime({+ chatCompletion: {+ handlePayload: (payload) => ({+ max_tokens: 1024,+ messages: [{ content: 'Question', role: 'user' }],+ model: payload.model,+ }),+ },+ customClient: {+ createClient: () =>+ ({+ baseURL: 'https://aihubmix.com',+ messages: { create: messagesCreate },+ }) as unknown as Anthropic,+ },+ provider: 'test-provider',+ });+ const runtime = new Runtime({ apiKey: 'test-key' });+ const diagnostics: ModelRuntimeDiagnostics = {};++ const response = await runtime.chat(+ {+ messages: [{ content: 'Question', role: 'user' }],+ model: 'claude-opus-5-5',+ stream: true,+ },+ { diagnostics },+ );++ await expect(response.text()).resolves.toContain('Final answer');+ expect(diagnostics.providerResponse?.error).toBeUndefined();+ expect(diagnostics.providerResponse).toEqual(+ expect.objectContaining({+ eventCount: rawEvents.length,+ hasNonWhitespaceText: true,+ hasNonWhitespaceThinking: true,+ signatureChars: 0,+ stopReason: 'end_turn',+ terminalEventReceived: true,+ textChars: 'Final answer'.length,+ thinkingChars: 'Plan'.length,+ }),+ );+ });+it('should strip trailing assistant prefill when a logical id maps to a Claude 5 model', async () => {// The prefill strip inside handlePayload sees the logical id; when the// mapping only later resolves to a Claude 4.6+/5 upstream id, chat() mustdiff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.tsindex b1bc1344df9..275ed0e85a8 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.ts@@ -58,12 +58,19 @@ const appendEvent = (diagnostics.events.push(indexedEvent);};+/**+ * Provider events are recorded as received, so SDK-typed string fields can be missing.+ * Aihubmix omits `signature` on thinking `content_block_start` events, while Anthropic+ * sends an empty string there.+ */const recordStringContent = (diagnostics: ProviderResponseDiagnostics,event: Omit<ProviderResponseEventDiagnostics, 'index'>,- content: string,+ rawContent: string | null | undefined,kind: 'signature' | 'text' | 'thinking' | 'toolInput',) => {+ const content = rawContent ?? '';+if (kind === 'signature') {diagnostics.signatureChars += content.length;event.signatureLength = content.length;@@ -99,6 +106,18 @@ const recordError = (diagnostics: ProviderResponseDiagnostics, error: unknown) =};};+/**+ * Diagnostics only observe the provider response. A recording failure must not reject+ * the response itself, otherwise a valid answer is reported as an empty completion.+ */+const recordSafely = (record: () => void) => {+ try {+ record();+ } catch (error) {+ console.error('[anthropic] Failed to record provider diagnostics:', error);+ }+};+const finalizeResponse = async (diagnostics: ProviderResponseDiagnostics, signal?: AbortSignal) => {await waitForRawProviderResponse(diagnostics);diagnostics.aborted = signal?.aborted || undefined;@@ -266,7 +285,7 @@ const observeAsyncIterable = async function* () {try {for await (const chunk of stream) {- recordAnthropicStreamEvent(diagnostics, chunk);+ recordSafely(() => recordAnthropicStreamEvent(diagnostics, chunk));yield chunk;}} catch (error) {@@ -304,7 +323,7 @@ const observeReadableStream = (return;}- recordAnthropicStreamEvent(diagnostics, value);+ recordSafely(() => recordAnthropicStreamEvent(diagnostics, value));controller.enqueue(value);} catch (error) {recordError(diagnostics, error);@@ -332,17 +351,19 @@ export const recordAnthropicNonStreamingResponse = async () => {if (!diagnostics) return;- diagnostics.firstEventAt ??= Date.now();- diagnostics.messageId = message.id;- diagnostics.model = message.model;- appendRawProviderEvent(diagnostics, message);- diagnostics.usage = message.usage;- diagnostics.stopReason = message.stop_reason;- diagnostics.stopSequence = message.stop_sequence;- appendEvent(diagnostics, { type: 'message_start' });- message.content.forEach((block, index) => recordMessageContentBlock(diagnostics, block, index));- appendEvent(diagnostics, { type: 'message_delta' });- appendEvent(diagnostics, { type: 'message_stop' });- diagnostics.terminalEventReceived = true;+ recordSafely(() => {+ diagnostics.firstEventAt ??= Date.now();+ diagnostics.messageId = message.id;+ diagnostics.model = message.model;+ appendRawProviderEvent(diagnostics, message);+ diagnostics.usage = message.usage;+ diagnostics.stopReason = message.stop_reason;+ diagnostics.stopSequence = message.stop_sequence;+ appendEvent(diagnostics, { type: 'message_start' });+ message.content.forEach((block, index) => recordMessageContentBlock(diagnostics, block, index));+ appendEvent(diagnostics, { type: 'message_delta' });+ appendEvent(diagnostics, { type: 'message_stop' });+ diagnostics.terminalEventReceived = true;+ });await finalizeResponse(diagnostics, signal);};diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.test.tsindex fd1eaf0099a..68161cd5e47 100644--- a/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts@@ -65,6 +65,29 @@ describe('normalizeChatMessageError', () => {});});+ it('keeps hook display fields when a stream error already carries a provider body', () => {+ const providerBody = { message: 'Provider timed out', provider: 'lobehub' };+ const result = normalizeChatMessageError({+ _responseBody: { traceId: 'trace-1' },+ body: providerBody,+ errorType: 'ProviderBizError',+ message: 'LLM stream error: Provider timed out',+ });++ expect(result.body).toMatchObject({ ...providerBody, traceId: 'trace-1' });+ });++ it('keeps hook display fields on a plain Error', () => {+ const error = Object.assign(new TypeError('terminated'), {+ _responseBody: { traceId: 'trace-1' },+ });++ expect(normalizeChatMessageError(error)).toMatchObject({+ body: { name: 'TypeError', traceId: 'trace-1' },+ message: 'terminated',+ });+ });+it('does not infer a provider outage from an unclassified internal 500', () => {expect(normalizeChatMessageError(new Error('500 unexpected internal failure'))).toMatchObject({type: 500,diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.tsindex ee557215991..17f99fe70f3 100644--- a/packages/model-runtime/src/errors/normalizeChatMessageError.ts+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.ts@@ -70,6 +70,16 @@ const buildPayloadBody = (// layers so normalizing `{ errorType, error }` does not drop the fields the// chat error renderer needs later.const sourceBody = payload.body ?? payload._responseBody ?? payload.error ?? originalError;+ /**+ * Error hooks attach display fields such as `traceId` through `_responseBody`. A stream error+ * already carries the provider `body`, which would otherwise hide them from the error card.+ */+ const displayFields =+ payload.body !== undefined &&+ isRecord(payload._responseBody) &&+ payload._responseBody !== payload.body+ ? payload._responseBody+ : undefined;const context: Record<string, unknown> = {};if (payload.budget !== undefined) context.budget = payload.budget;@@ -80,6 +90,7 @@ const buildPayloadBody = (return {...sourceBody,+ ...displayFields,// `_responseBody` is the display-facing body, but gateway/model-runtime// still carries status/provider details in `error` for some failures:// `{ _responseBody: { error: { message } }, error: { status: 402 } }`.@@ -221,8 +232,15 @@ export const normalizeChatMessageError = (error: unknown): ChatMessageError => {// out of some `JSON.parse` those two say nothing about WHERE it blew up.// Persist a bounded stack so a recurring 500 is locatable from the stored// operation instead of needing a live repro.+ // Error hooks attach display fields such as `traceId` through `_responseBody` β also on+ // plain Errors, e.g. a provider stream that fails with `TypeError: terminated`.+ const responseBody = (error as { _responseBody?: unknown })._responseBody;return enrichWithSpec({- body: { name: error.name, stack: truncateStack(error.stack) },+ body: {+ ...(isRecord(responseBody) ? responseBody : {}),+ name: error.name,+ stack: truncateStack(error.stack),+ },message: error.message,type: ChatErrorType.InternalServerError,});