🤯 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: preserve active branch and provider failure evidence (#17860)
YuTengjing073eb6e4b0c9
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.tsindex c5e12059f95..cb1c8a34997 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts@@ -460,4 +460,64 @@ describe('ServerCallLlmAttempt', () => {}),);});++ it('records route and provider-boundary evidence with an empty completion', async () => {+ const rawResponseBody = 'data: {"type":"message_delta"}\n\ndata: {"type":"message_stop"}\n\n';+ const providerEvidence = {+ providerRequest: {+ apiMode: 'messages',+ payload: { messages: [{ content: 'Final provider prompt', role: 'user' }] },+ sentAt: 100,+ },+ providerResponse: {+ eventCount: 5,+ hasNonWhitespaceText: false,+ hasNonWhitespaceThinking: false,+ rawEvents: [+ { delta: { stop_reason: 'end_turn' }, type: 'message_delta' },+ { type: 'message_stop' },+ ],+ rawResponse: {+ body: rawResponseBody,+ byteLength: new TextEncoder().encode(rawResponseBody).byteLength,+ status: 'captured',+ },+ requestId: 'request-1',+ status: 200,+ stopReason: 'end_turn',+ thinkingChars: 1,+ },+ };+ const routeEvidence = {+ apiType: 'deepseek',+ channelId: 'deepseek',+ optionIndex: 0,+ providerId: 'lobehub',+ routerId: 'deepseek',+ success: true,+ totalOptions: 3,+ };+ const { attempt } = createAttempt(async ({ callback, diagnostics, metadata }) => {+ Object.assign(diagnostics!, providerEvidence);+ metadata!.routeAttempt = routeEvidence;+ await callback?.onThinking?.(' ');+ await callback?.onCompletion?.({+ finishReason: 'end_turn',+ text: '',+ usage: { totalInputTokens: 206_384, totalOutputTokens: 1, totalTokens: 206_385 },+ });+ });++ await expect(attempt.execute()).rejects.toMatchObject({+ errorType: 'ModelEmptyCompletion',+ });+ expect(recordModelCompletionFailureMock).toHaveBeenCalledWith(+ expect.objectContaining({+ runtime: {+ provider: providerEvidence,+ route: routeEvidence,+ },+ }),+ );+ });});diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.tsindex 64ca198a914..5353642dbaf 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts@@ -5,6 +5,7 @@ import type {ChatStreamPayload,ContentPartData,ModelRuntime,+ ModelRuntimeDiagnostics,OnFinishData,} from '@lobechat/model-runtime';import {@@ -77,7 +78,6 @@ export class ServerCallLlmAttempt {private readonly attempt: number;private readonly base64ImageEvents: Base64ImageData[] = [];private readonly chatPayload: ChatStreamPayload;- private readonly clientIp?: string;private completion?: OnFinishData;private readonly contentPartEvents: ContentPartData[] = [];private readonly ctx: RuntimeExecutorContext;@@ -94,6 +94,8 @@ export class ServerCallLlmAttempt {private reasoning?: ModelReasoning;private readonly reasoningPartEvents: ContentPartData[] = [];private readonly resolved: ServerCallLlmTooling['resolved'];+ private readonly runtimeDiagnostics: ModelRuntimeDiagnostics = {};+ private readonly runtimeMetadata: Record<string, unknown>;private speed?: ModelPerformance;private readonly streamSink: ServerCallLlmStreamSink;private streamError?: unknown;@@ -101,7 +103,6 @@ export class ServerCallLlmAttempt {private toolsCalling: ChatToolPayload[] = [];private readonly topicId?: string;private readonly trigger?: unknown;- private readonly userAgent?: string;private usage?: ModelUsage;constructor({@@ -125,7 +126,6 @@ export class ServerCallLlmAttempt {}: CreateServerCallLlmAttemptInput) {this.attempt = attempt;this.chatPayload = chatPayload;- this.clientIp = clientIp;this.ctx = ctx;this.maxAttempts = maxAttempts;this.messageCount = messageCount;@@ -135,6 +135,13 @@ export class ServerCallLlmAttempt {this.operationLogId = operationLogId;this.provider = provider;this.resolved = resolved;+ this.runtimeMetadata = {+ clientIp,+ operationId: ctx.operationId,+ topicId,+ trigger,+ userAgent,+ };this.streamSink = createServerCallLlmStreamSink({blobStore,ctx,@@ -143,7 +150,6 @@ export class ServerCallLlmAttempt {});this.topicId = topicId;this.trigger = trigger;- this.userAgent = userAgent;}async execute(): Promise<void> {@@ -247,13 +253,8 @@ export class ServerCallLlmAttempt {);},},- metadata: {- clientIp: this.clientIp,- operationId: this.ctx.operationId,- topicId: this.topicId,- trigger: this.trigger,- userAgent: this.userAgent,- },+ diagnostics: this.runtimeDiagnostics,+ metadata: this.runtimeMetadata,user: this.ctx.userId,});@@ -365,6 +366,16 @@ export class ServerCallLlmAttempt {private async recordCompletionFailure(reason: ModelCompletionFailureReason) {try {+ const providerEvidence =+ this.runtimeDiagnostics.providerRequest || this.runtimeDiagnostics.providerResponse+ ? this.runtimeDiagnostics+ : undefined;+ const routeEvidence = this.runtimeMetadata.routeAttempt;+ const runtimeEvidence =+ providerEvidence === undefined && routeEvidence === undefined+ ? undefined+ : { provider: providerEvidence, route: routeEvidence };+await recordModelCompletionFailure({attempt: this.attempt,maxAttempts: this.maxAttempts,@@ -381,6 +392,7 @@ export class ServerCallLlmAttempt {output: this.snapshot(),reasoningPartEvents: [...this.reasoningPartEvents],},+ ...(runtimeEvidence ? { runtime: runtimeEvidence } : {}),stepIndex: this.ctx.stepIndex,topicId: this.topicId,trigger: this.trigger,diff --git a/packages/business-server/src/recordModelCompletionFailure.ts b/packages/business-server/src/recordModelCompletionFailure.tsindex c271ccdad3b..896602ac6ea 100644--- a/packages/business-server/src/recordModelCompletionFailure.ts+++ b/packages/business-server/src/recordModelCompletionFailure.ts@@ -1,5 +1,10 @@export type ModelCompletionFailureReason = 'empty_completion' | 'refusal';+export interface ModelCompletionFailureRuntimeEvidence {+ provider?: unknown;+ route?: unknown;+}+export interface RecordModelCompletionFailureParams {attempt: number;maxAttempts: number;@@ -15,6 +20,8 @@ export interface RecordModelCompletionFailureParams {request: unknown;/** Full normalized completion output and callback evidence. */response: unknown;+ /** Provider-boundary and route evidence captured for this exact call. */+ runtime?: ModelCompletionFailureRuntimeEvidence;stepIndex: number;topicId?: string;trigger?: unknown;diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.tsindex 757be89e369..cfd3dcb936f 100644--- a/packages/conversation-flow/src/__tests__/parse.test.ts+++ b/packages/conversation-flow/src/__tests__/parse.test.ts@@ -269,6 +269,500 @@ describe('parse', () => {expect(ids.indexOf('first-question')).toBeLessThan(ids.indexOf('status-user'));});+ it('should keep the branch containing the latest user turn after parallel tool continuations', () => {+ const messages: Message[] = [+ { content: 'root', createdAt: 0, id: 'root-user', role: 'user', updatedAt: 0 },+ {+ agentId: 'agent-1',+ content: 'run tools in parallel',+ createdAt: 1,+ id: 'root-assistant',+ parentId: 'root-user',+ role: 'assistant',+ tools: [+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-active',+ identifier: 'internal',+ result_msg_id: 'tool-active',+ type: 'default',+ },+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-stale',+ identifier: 'internal',+ result_msg_id: 'tool-stale',+ type: 'default',+ },+ ],+ updatedAt: 1,+ },+ {+ content: 'active tool result',+ createdAt: 2,+ id: 'tool-active',+ parentId: 'root-assistant',+ role: 'tool',+ tool_call_id: 'call-active',+ updatedAt: 2,+ },+ {+ content: 'stale tool result',+ createdAt: 3,+ id: 'tool-stale',+ parentId: 'root-assistant',+ role: 'tool',+ tool_call_id: 'call-stale',+ updatedAt: 3,+ },+ {+ agentId: 'agent-2',+ content: 'active nested continuation',+ createdAt: 4,+ id: 'active-head',+ parentId: 'tool-active',+ role: 'assistant',+ tools: [+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-branch',+ identifier: 'internal',+ result_msg_id: 'tool-branch',+ type: 'default',+ },+ ],+ updatedAt: 4,+ },+ {+ agentId: 'agent-2',+ content: 'stale nested continuation',+ createdAt: 5,+ id: 'stale-head',+ parentId: 'tool-stale',+ role: 'assistant',+ tools: [+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-stale-nested',+ identifier: 'internal',+ result_msg_id: 'tool-stale-nested',+ type: 'default',+ },+ ],+ updatedAt: 5,+ },+ {+ content: 'active nested result',+ createdAt: 6,+ id: 'tool-branch',+ parentId: 'active-head',+ role: 'tool',+ tool_call_id: 'call-branch',+ updatedAt: 6,+ },+ {+ content: 'stale nested result',+ createdAt: 7,+ id: 'tool-stale-nested',+ parentId: 'stale-head',+ role: 'tool',+ tool_call_id: 'call-stale-nested',+ updatedAt: 7,+ },+ {+ agentId: 'agent-2',+ content: 'old continuation',+ createdAt: 8,+ id: 'old-continuation',+ parentId: 'tool-branch',+ role: 'assistant',+ tools: [+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-old',+ identifier: 'internal',+ result_msg_id: 'tool-old',+ type: 'default',+ },+ ],+ updatedAt: 8,+ },+ {+ agentId: 'agent-2',+ content: 'current continuation',+ createdAt: 9,+ id: 'current-continuation',+ parentId: 'tool-branch',+ role: 'assistant',+ tools: [+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-current',+ identifier: 'internal',+ result_msg_id: 'tool-current',+ type: 'default',+ },+ ],+ updatedAt: 9,+ },+ {+ content: 'old result',+ createdAt: 10,+ id: 'tool-old',+ parentId: 'old-continuation',+ role: 'tool',+ tool_call_id: 'call-old',+ updatedAt: 10,+ },+ {+ content: 'current result',+ createdAt: 11,+ id: 'tool-current',+ parentId: 'current-continuation',+ role: 'tool',+ tool_call_id: 'call-current',+ updatedAt: 11,+ },+ {+ agentId: 'agent-2',+ content: 'old branch answer',+ createdAt: 12,+ id: 'old-answer',+ parentId: 'tool-old',+ role: 'assistant',+ updatedAt: 12,+ },+ {+ agentId: 'agent-2',+ content: '...',+ createdAt: 13,+ id: 'current-answer',+ parentId: 'tool-current',+ role: 'assistant',+ updatedAt: 13,+ },+ {+ agentId: 'agent-2',+ content: 'stale parallel answer',+ createdAt: 14,+ id: 'stale-parallel-answer',+ parentId: 'tool-stale-nested',+ role: 'assistant',+ updatedAt: 14,+ },+ {+ content: 'current user request',+ createdAt: 15,+ id: 'current-user',+ parentId: 'current-answer',+ role: 'user',+ updatedAt: 15,+ },+ {+ agentId: 'agent-2',+ content: '...',+ createdAt: 16,+ id: 'current-placeholder',+ parentId: 'current-user',+ role: 'assistant',+ updatedAt: 16,+ },+ ];++ const result = parse(messages);+ const ids = result.flatList.map((message) => message.id);++ expect(ids).toContain('current-user');+ expect(ids.indexOf('stale-head')).toBeLessThan(ids.indexOf('current-user'));+ expect(ids.at(-1)).toBe('current-placeholder');++ expect(result.contextTree.map((node) => node.id)).toEqual([+ 'root-user',+ 'root-assistant',+ 'active-head',+ 'current-user',+ 'current-placeholder',+ ]);+ expect(result.contextTree.find((node) => node.id === 'active-head')).toMatchObject({+ children: [{ id: 'active-head' }, { id: 'current-continuation' }, { id: 'current-answer' }],+ type: 'assistantGroup',+ });+ });++ it('should resolve same-agent continuations across tool parents by the latest user branch', () => {+ const messages: Message[] = [+ { content: 'root', createdAt: 0, id: 'root-user', role: 'user', updatedAt: 0 },+ {+ agentId: 'agent-1',+ content: 'run tools in parallel',+ createdAt: 1,+ id: 'root-assistant',+ parentId: 'root-user',+ role: 'assistant',+ tools: [+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-active',+ identifier: 'internal',+ result_msg_id: 'tool-active',+ type: 'default',+ },+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-stale',+ identifier: 'internal',+ result_msg_id: 'tool-stale',+ type: 'default',+ },+ ],+ updatedAt: 1,+ },+ {+ content: 'active tool result',+ createdAt: 2,+ id: 'tool-active',+ parentId: 'root-assistant',+ role: 'tool',+ tool_call_id: 'call-active',+ updatedAt: 2,+ },+ {+ content: 'stale tool result',+ createdAt: 3,+ id: 'tool-stale',+ parentId: 'root-assistant',+ role: 'tool',+ tool_call_id: 'call-stale',+ updatedAt: 3,+ },+ {+ agentId: 'agent-1',+ content: 'stale continuation',+ createdAt: 4,+ id: 'stale-continuation',+ parentId: 'tool-stale',+ role: 'assistant',+ updatedAt: 4,+ },+ {+ agentId: 'agent-1',+ content: 'active continuation',+ createdAt: 5,+ id: 'active-continuation',+ parentId: 'tool-active',+ role: 'assistant',+ updatedAt: 5,+ },+ {+ content: 'current user request',+ createdAt: 6,+ id: 'current-user',+ parentId: 'active-continuation',+ role: 'user',+ updatedAt: 6,+ },+ {+ agentId: 'agent-1',+ content: '...',+ createdAt: 7,+ id: 'current-placeholder',+ parentId: 'current-user',+ role: 'assistant',+ updatedAt: 7,+ },+ ];++ const result = parse(messages);++ expect(result.flatList.map((message) => message.id)).toEqual([+ 'root-user',+ 'root-assistant',+ 'current-user',+ 'current-placeholder',+ ]);++ expect(result.contextTree.map((node) => node.id)).toEqual([+ 'root-user',+ 'root-assistant',+ 'current-user',+ 'current-placeholder',+ ]);+ expect(result.contextTree.find((node) => node.id === 'root-assistant')).toMatchObject({+ children: [{ id: 'root-assistant' }, { id: 'active-continuation' }],+ type: 'assistantGroup',+ });+ });++ it('should hide previous continuations while an optimistic branch is being created', () => {+ const messages: Message[] = [+ { content: 'root', createdAt: 0, id: 'root-user', role: 'user', updatedAt: 0 },+ {+ agentId: 'agent-1',+ content: 'run a tool',+ createdAt: 1,+ id: 'root-assistant',+ metadata: { activeBranchIndex: 2 },+ parentId: 'root-user',+ role: 'assistant',+ tools: [+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-1',+ identifier: 'internal',+ result_msg_id: 'tool-1',+ type: 'default',+ },+ ],+ updatedAt: 1,+ },+ {+ content: 'tool result',+ createdAt: 2,+ id: 'tool-1',+ parentId: 'root-assistant',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 2,+ },+ {+ agentId: 'agent-1',+ content: 'old continuation',+ createdAt: 3,+ id: 'old-continuation',+ parentId: 'root-assistant',+ role: 'assistant',+ updatedAt: 3,+ },+ {+ agentId: 'agent-1',+ content: 'current continuation',+ createdAt: 4,+ id: 'current-continuation',+ parentId: 'root-assistant',+ role: 'assistant',+ updatedAt: 4,+ },+ ];++ const result = parse(messages);++ expect(result.flatList.map((message) => message.id)).toEqual(['root-user', 'root-assistant']);+ expect(result.flatList[1]).toMatchObject({+ children: [{ id: 'root-assistant' }],+ role: 'assistantGroup',+ });+ expect(result.contextTree).toMatchObject([+ { id: 'root-user', type: 'message' },+ { children: [{ id: 'root-assistant' }], id: 'root-assistant', type: 'assistantGroup' },+ ]);+ });++ it('should resolve post-tool continuations in the non-tool branch index space', () => {+ const messages: Message[] = [+ { content: 'root', createdAt: 0, id: 'root-user', role: 'user', updatedAt: 0 },+ {+ agentId: 'agent-1',+ content: 'run tools',+ createdAt: 1,+ id: 'root-assistant',+ metadata: { activeBranchIndex: 1 },+ parentId: 'root-user',+ role: 'assistant',+ tools: [+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-1',+ identifier: 'internal',+ result_msg_id: 'tool-1',+ type: 'default',+ },+ {+ apiName: 'inspect',+ arguments: '{}',+ id: 'call-2',+ identifier: 'internal',+ result_msg_id: 'tool-2',+ type: 'default',+ },+ ],+ updatedAt: 1,+ },+ {+ content: 'first tool result',+ createdAt: 2,+ id: 'tool-1',+ parentId: 'root-assistant',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 2,+ },+ {+ content: 'second tool result',+ createdAt: 3,+ id: 'tool-2',+ parentId: 'root-assistant',+ role: 'tool',+ tool_call_id: 'call-2',+ updatedAt: 3,+ },+ {+ content: 'old first tool continuation',+ createdAt: 4,+ id: 'tool-user-1',+ parentId: 'tool-1',+ role: 'user',+ updatedAt: 4,+ },+ {+ content: 'old second tool continuation',+ createdAt: 5,+ id: 'tool-user-2',+ parentId: 'tool-2',+ role: 'user',+ updatedAt: 5,+ },+ {+ content: 'first direct branch',+ createdAt: 6,+ id: 'direct-user-1',+ parentId: 'root-assistant',+ role: 'user',+ updatedAt: 6,+ },+ {+ content: 'active direct branch',+ createdAt: 7,+ id: 'direct-user-2',+ parentId: 'root-assistant',+ role: 'user',+ updatedAt: 7,+ },+ ];++ const result = parse(messages);++ expect(result.flatList.map((message) => message.id)).toEqual([+ 'root-user',+ 'root-assistant',+ 'direct-user-2',+ ]);+ expect(result.contextTree.map((node) => node.id)).toEqual([+ 'root-user',+ 'root-assistant',+ 'direct-user-2',+ ]);+ });+it('should interleave continuations from sibling tool results by child creation time', () => {const time = (seconds: number) =>new Date(`2026-01-01T00:01:${String(seconds).padStart(2, '0')}.000Z`).getTime();diff --git a/packages/conversation-flow/src/transformation/BranchResolver.ts b/packages/conversation-flow/src/transformation/BranchResolver.tsindex 1c5cb6577b8..57dc747561e 100644--- a/packages/conversation-flow/src/transformation/BranchResolver.ts+++ b/packages/conversation-flow/src/transformation/BranchResolver.ts@@ -5,10 +5,22 @@ import type { IdNode, Message } from '../types';** Determines which branch should be active based on:* 1. metadata.activeBranchIndex (explicit index)- * 2. Inferred from which branch has children- * 3. Default to first branch+ * 2. The branch containing the latest user turn+ * 3. Inferred from which branch has children+ * 4. Default to first branch*/export class BranchResolver {+ constructor(private messageMap?: Map<string, Message>) {}++ /**+ * Return the canonical child order used by persisted `activeBranchIndex` metadata.+ * Tool results are inline members of an assistant turn, so branch controls never+ * count them as selectable siblings.+ */+ getMetadataBranchIds(childIds: string[]): string[] {+ return childIds.filter((id) => this.messageMap?.get(id)?.role !== 'tool');+ }+/*** Get active branch ID from IdNode structure (used in contextTree building)* Returns undefined for optimistic updates when the branch hasn't been created yet@@ -28,7 +40,24 @@ export class BranchResolver {// Invalid index (> children.length), ignore and continue to other strategies}- // Priority 2: Infer from which branch has children+ // Priority 2: A persisted user descendant proves which historical branch the+ // user actually continued. Prefer the newest such descendant before the+ // generic "has children" fallback, which otherwise selects an older retried+ // assistant branch and can drop the current user turn from the flat history.+ const nodeMap = new Map<string, IdNode>();+ const pendingNodes = [...idNode.children];+ while (pendingNodes.length > 0) {+ const node = pendingNodes.pop()!;+ nodeMap.set(node.id, node);+ pendingNodes.push(...node.children);+ }+ const latestUserBranchId = this.findBranchContainingLatestUser(+ idNode.children.map((child) => child.id),+ (id) => nodeMap.get(id)?.children.map((child) => child.id) ?? [],+ );+ if (latestUserBranchId) return latestUserBranchId;++ // Priority 3: Infer from which branch has childrenfor (const child of idNode.children) {if (child.children.length > 0) {return child.id;@@ -41,28 +70,38 @@ export class BranchResolver {/*** Get active branch ID from flat list (used in flatList building)+ * `metadataBranchIds` preserves the full UI branch-index space when `childIds`+ * is a filtered set of candidates owned by a specialized collector.* Returns undefined for optimistic updates when the branch hasn't been created yet*/getActiveBranchIdFromMetadata(message: Message,childIds: string[],childrenMap: Map<string | null, string[]>,+ metadataBranchIds: string[] = childIds,): string | undefined {// Priority 1: Try to get from metadata.activeBranchIndex (index-based)const activeBranchIndex = (message.metadata as any)?.activeBranchIndex;if (typeof activeBranchIndex === 'number' && activeBranchIndex >= 0) {// If index is within bounds, return the branch at that index- if (activeBranchIndex < childIds.length) {- return childIds[activeBranchIndex];+ if (activeBranchIndex < metadataBranchIds.length) {+ return metadataBranchIds[activeBranchIndex];}- // Optimistic update: index === childIds.length means branch is being created- if (activeBranchIndex === childIds.length) {+ // Optimistic update: index === metadataBranchIds.length means branch is being created+ if (activeBranchIndex === metadataBranchIds.length) {return undefined;}- // Invalid index (> childIds.length), ignore and continue to other strategies+ // Invalid index (> metadataBranchIds.length), ignore and continue to other strategies}- // Priority 2: Infer from which child has descendants+ // Priority 2: Prefer the branch that the user most recently continued.+ const latestUserBranchId = this.findBranchContainingLatestUser(+ childIds,+ (id) => childrenMap.get(id) ?? [],+ );+ if (latestUserBranchId) return latestUserBranchId;++ // Priority 3: Infer from which child has descendantsfor (const childId of childIds) {const descendants = childrenMap.get(childId);if (descendants && descendants.length > 0) {@@ -73,4 +112,48 @@ export class BranchResolver {// Default to first childreturn childIds[0];}++ /**+ * Find the candidate branch containing the newest persisted user descendant.+ * A user turn is a stronger active-path signal than descendant presence alone:+ * parallel tool results and retried operations can leave several old assistant+ * chains with descendants, while only the branch the user continued should+ * become the request tail. Thread replies are excluded because they do not+ * belong to the main conversation tree.+ */+ private findBranchContainingLatestUser(+ branchIds: string[],+ getChildren: (id: string) => string[],+ ): string | undefined {+ if (!this.messageMap) return;++ let latestTimestamp = Number.NEGATIVE_INFINITY;+ let selectedBranchId: string | undefined;++ for (const branchId of branchIds) {+ const pendingIds = [branchId];+ const visitedIds = new Set<string>();++ while (pendingIds.length > 0) {+ const messageId = pendingIds.pop()!;+ if (visitedIds.has(messageId)) continue;+ visitedIds.add(messageId);++ const descendant = this.messageMap.get(messageId);+ if (descendant?.threadId) continue;++ if (descendant?.role === 'user') {+ const timestamp = descendant.createdAt;+ if (timestamp > latestTimestamp) {+ latestTimestamp = timestamp;+ selectedBranchId = branchId;+ }+ }++ pendingIds.push(...getChildren(messageId));+ }+ }++ return selectedBranchId;+ }}diff --git a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts b/packages/conversation-flow/src/transformation/ContextTreeBuilder.tsindex fbd23f911b7..cab3b0067c8 100644--- a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts+++ b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts@@ -165,16 +165,17 @@ export class ContextTreeBuilder {// Priority 6: Branch — multiple NON-TOOL children (dual-form reader invariant: tool children are inline data, not branch candidates).// Tool children are inline data of their assistant (handled by Priority 4),// never branch candidates.- const nonToolChildren = idNode.children.filter(- (child) => this.messageMap.get(child.id)?.role !== 'tool',+ const metadataBranchIds = new Set(+ this.branchResolver.getMetadataBranchIds(idNode.children.map((child) => child.id)),);+ const nonToolChildren = idNode.children.filter((child) => metadataBranchIds.has(child.id));if (nonToolChildren.length > 1) {// Add current message nodeconst messageNode = this.createMessageNode(message);contextTree.push(messageNode);// Create branch node- const branchNode = this.createBranchNode(message, idNode);+ const branchNode = this.createBranchNode(message, nonToolChildren);contextTree.push(branchNode);// Don't continue after branch - branch is an end point@@ -273,7 +274,8 @@ export class ContextTreeBuilder {/*** Create BranchNode*/- private createBranchNode(message: Message, idNode: IdNode): BranchNode {+ private createBranchNode(message: Message, branchChildren: IdNode[]): BranchNode {+ const idNode = { children: branchChildren, id: message.id };const activeBranchId = this.branchResolver.getActiveBranchId(message, idNode);// For optimistic update (activeBranchId is undefined), use children.length as the indexdiff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.tsindex edd6de482a9..90a5fd7aa00 100644--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts@@ -55,6 +55,15 @@ export class FlatListBuilder {// Build the active path by traversing from rootthis.buildFlatListRecursive(rootParentId, flatList, processedIds, messages);+ // Assistant groups must be assembled before ordering because their members+ // are discovered through recursive tool-result chains. That traversal is+ // depth-first: when parallel tool results continue under different agents,+ // it can finish a newer user subtree and then append an older sibling subtree,+ // leaving a stale assistant response at the request tail. A stable final sort+ // restores the persisted chronology without changing group membership or the+ // order of nodes with identical timestamps.+ flatList.sort((first, second) => first.createdAt - second.createdAt);+return flatList;}@@ -304,9 +313,7 @@ export class FlatListBuilder {const childMessages = this.childrenMap.get(message.id) ?? [];// Non-tool children only are branch candidates (dual-form reader invariant: tool children are inline, not branches):// a tool child is inline data of its assistant, never a sibling branch.- const nonToolChildMessages = childMessages.filter(- (childId) => this.messageMap.get(childId)?.role !== 'tool',- );+ const nonToolChildMessages = this.branchResolver.getMetadataBranchIds(childMessages);if (this.isCompareMode(message) && childMessages.length > 1) {// Add user messageflatList.push(message);@@ -530,6 +537,10 @@ export class FlatListBuilder {allMessages: Message[],): void {const lastAssistant = assistantChain.at(-1);+ if (lastAssistant) {+ this.suppressInactiveExplicitContinuations(lastAssistant, allToolMessages, processedIds);+ }+const parentIds = [...(lastAssistant ? [lastAssistant.id] : []),...allToolMessages.map((toolMessage) => toolMessage.id),@@ -554,6 +565,44 @@ export class FlatListBuilder {}}+ /**+ * Keep AssistantGroup draining in the same canonical branch space as the UI.+ * An explicit index selects a direct non-tool child; tool-hosted continuations+ * belong to older/inactive branches and must not be appended to the model+ * history. For an optimistic index at `branchCount`, every existing+ * continuation stays hidden until the newly created branch is persisted.+ */+ private suppressInactiveExplicitContinuations(+ lastAssistant: Message,+ allToolMessages: Message[],+ processedIds: Set<string>,+ ): void {+ const directChildIds = this.childrenMap.get(lastAssistant.id) ?? [];+ const metadataBranchIds = this.branchResolver.getMetadataBranchIds(directChildIds);+ const activeBranchIndex = (lastAssistant.metadata as any)?.activeBranchIndex;+ if (+ typeof activeBranchIndex !== 'number' ||+ activeBranchIndex < 0 ||+ activeBranchIndex > metadataBranchIds.length+ ) {+ return;+ }++ const activeBranchId = metadataBranchIds[activeBranchIndex];+ const tailToolIds = allToolMessages+ .filter((toolMessage) => toolMessage.parentId === lastAssistant.id)+ .map((toolMessage) => toolMessage.id);+ const continuationParentIds = [lastAssistant.id, ...tailToolIds];++ for (const parentId of continuationParentIds) {+ for (const childId of this.childrenMap.get(parentId) ?? []) {+ if (!processedIds.has(childId) && childId !== activeBranchId) {+ processedIds.add(childId);+ }+ }+ }+ }+/*** New-shape AgentCouncil: a supervisor turn whose tool call carries* `agentCouncil` metadata renders its broadcast members — the ASSISTANTdiff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.tsindex 294827eec99..550c935dc26 100644--- a/packages/conversation-flow/src/transformation/MessageCollector.ts+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts@@ -56,8 +56,7 @@ export class MessageCollector {constructor(private messageMap: Map<string, Message>,private childrenMap: Map<string | null, string[]>,- // BranchResolver is stateless; default keeps existing 2-arg call sites working.- private branchResolver: BranchResolver = new BranchResolver(),+ private branchResolver: BranchResolver = new BranchResolver(messageMap),) {}/**@@ -249,9 +248,10 @@ export class MessageCollector {* (a post-task summary whose `parentId === currentAssistant.id`). Those are* emitted by the council/tasks flow AFTER the group, so the assistant seed* is dropped and the chain ends here.- * - **Branch resolution**: when >1 non-tool same-agent continuations share a- * parent (e.g. a regenerated continuation), pick the active one via- * `activeBranchIndex` instead of blindly taking the earliest.+ * - **Branch resolution**: when >1 non-tool same-agent continuations compete,+ * first resolve the active direct child of this assistant (including+ * continuations under different tool results), then resolve regenerated+ * siblings under that child.*/private findFlatChainContinuation(currentAssistant: Message,@@ -281,34 +281,37 @@ export class MessageCollector {.filter((m) => m.role === 'assistant' && m.agentId === groupAgentId && !getMessageSignal(m)).sort((a, b) => a.createdAt - b.createdAt);- const activeId = this.resolveActiveContinuationId(candidates);- if (!activeId) return;+ const activeId = this.resolveActiveContinuationId(candidates, currentAssistant);+ if (!activeId) {+ this.markUnselectedContinuations(undefined, candidates, processedIds);+ return;+ }const activeContinuation = candidates.find((message) => message.id === activeId);- if (!activeContinuation) return;+ if (!activeContinuation) {+ this.markUnselectedContinuations(undefined, candidates, processedIds);+ return;+ }- this.markUnselectedContinuationSiblings(activeContinuation, candidates, processedIds);+ this.markUnselectedContinuations(activeContinuation.id, candidates, processedIds);return activeContinuation;}/**- * Multiple assistant continuations can share a tool-result parent, including- * duplicate outputs left by a retried execution. Once BranchResolver selects- * the continuation for the current chain, the other same-parent assistants- * must be treated as consumed;+ * Multiple assistant continuations can share one parent or compete across+ * parallel tool-result parents. Once BranchResolver selects the continuation+ * for the current chain, every other same-step candidate must be consumed;* otherwise FlatListBuilder's post-group continuation drain emits them later- * as standalone messages, often after a much newer turn.+ * as standalone messages and leaks an inactive assistant branch into the next+ * model request.*/- private markUnselectedContinuationSiblings(- activeContinuation: Message,+ private markUnselectedContinuations(+ activeContinuationId: string | undefined,candidates: Message[],processedIds: Set<string>,): void {for (const candidate of candidates) {- if (- candidate.id !== activeContinuation.id &&- candidate.parentId === activeContinuation.parentId- ) {+ if (candidate.id !== activeContinuationId) {processedIds.add(candidate.id);}}@@ -316,24 +319,56 @@ export class MessageCollector {/*** Pick the active continuation among same-step candidates (sorted by- * createdAt). One candidate ⇒ a linear continuation. >1 non-tool siblings- * under a single parent ⇒ a branch (e.g. a regenerated continuation), so- * consult the parent's `activeBranchIndex` via BranchResolver instead of- * blindly taking the earliest — otherwise the inactive branch is silently- * chosen and the active one dropped. Returns undefined when there is no- * continuation, or the active branch is an optimistic not-yet-created one.+ * createdAt). Parallel tool results can each own a continuation, so resolve+ * the active direct child of the assistant before handling regenerated+ * siblings under one parent. Without the first step, an earlier stale tool+ * continuation wins before BranchResolver can see the latest user descendant.*/- private resolveActiveContinuationId(sortedCandidates: Message[]): string | undefined {+ private resolveActiveContinuationId(+ sortedCandidates: Message[],+ branchOwner?: Message,+ ): string | undefined {if (sortedCandidates.length === 0) return undefined;- const earliest = sortedCandidates[0];++ let candidates = sortedCandidates;+ if (branchOwner && candidates.length > 1) {+ const directChildIds = this.childrenMap.get(branchOwner.id) ?? [];+ const directChildIdSet = new Set(directChildIds);+ const candidateBranchIds = new Set(+ candidates+ .map((candidate) =>+ candidate.parentId === branchOwner.id ? candidate.id : candidate.parentId,+ )+ .filter((id): id is string => Boolean(id && directChildIdSet.has(id))),+ );++ if (candidateBranchIds.size > 1) {+ const orderedCandidateBranchIds = directChildIds.filter((id) => candidateBranchIds.has(id));+ const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(+ branchOwner,+ orderedCandidateBranchIds,+ this.childrenMap,+ this.branchResolver.getMetadataBranchIds(directChildIds),+ );+ if (!activeBranchId) return undefined;++ candidates = candidates.filter(+ (candidate) => candidate.id === activeBranchId || candidate.parentId === activeBranchId,+ );+ if (candidates.length === 0) return undefined;+ }+ }++ const earliest = candidates[0];const parentId = earliest.parentId;if (parentId == null) return earliest.id;// Branch siblings share one parent; only those under the earliest// candidate's parent participate in this branch decision. Use childrenMap// (creation) order so it lines up with how activeBranchIndex is assigned.- const eligibleIds = new Set(sortedCandidates.map((m) => m.id));- const siblingIds = (this.childrenMap.get(parentId) ?? []).filter((id) => eligibleIds.has(id));+ const eligibleIds = new Set(candidates.map((m) => m.id));+ const directSiblingIds = this.childrenMap.get(parentId) ?? [];+ const siblingIds = directSiblingIds.filter((id) => eligibleIds.has(id));if (siblingIds.length <= 1) return earliest.id;const parentMsg = this.messageMap.get(parentId);@@ -343,6 +378,7 @@ export class MessageCollector {parentMsg,siblingIds,this.childrenMap,+ this.branchResolver.getMetadataBranchIds(directSiblingIds),);}@@ -508,7 +544,10 @@ export class MessageCollector {).sort((a, b) => a.msg!.createdAt - b.msg!.createdAt);- const activeId = this.resolveActiveContinuationId(eligible.map((c) => c.msg!));+ const activeId = this.resolveActiveContinuationId(+ eligible.map((c) => c.msg!),+ this.messageMap.get(idNode.id),+ );return activeId ? eligible.find((c) => c.node.id === activeId)?.node : undefined;}@@ -647,56 +686,60 @@ export class MessageCollector {* Find next message after tools in an assistant group*/findNextAfterTools(assistantMsg: Message, idNode: IdNode): IdNode | null {- // Recursively find the last message in the assistant group (same agentId only)- const lastNode = this.findLastNodeInAssistantGroup(idNode, assistantMsg.agentId);- if (!lastNode) return null;+ const lastAssistantNode = this.findLastAssistantNodeInGroup(idNode, assistantMsg.agentId);+ const nextNode = this.resolveAssistantGroupTailChild(lastAssistantNode);+ if (!nextNode) return null;++ const nextMessage = this.messageMap.get(nextNode.id);+ if (nextMessage?.role !== 'tool') return nextNode;- // Check if lastNode is a tool with agentCouncil mode+ // Check if the selected tool has agentCouncil mode// In this case, return the tool node itself so ContextTreeBuilder can process it- const lastMsg = this.messageMap.get(lastNode.id);- if (lastMsg?.role === 'tool' && (lastMsg.metadata as any)?.agentCouncil === true) {- return lastNode;+ if ((nextMessage.metadata as any)?.agentCouncil === true) {+ return nextNode;}- // Check if lastNode is a tool with ANY task children+ // Check if the selected tool has ANY task children// In this case, return the tool node itself so ContextTreeBuilder can process tasks- if (lastMsg?.role === 'tool') {- const taskChildren = lastNode.children.filter((child) => {- const childMsg = this.messageMap.get(child.id);- return childMsg?.role === 'task';- });- if (taskChildren.length > 0) {- return lastNode;- }+ const taskChildren = nextNode.children.filter((child) => {+ const childMessage = this.messageMap.get(child.id);+ return childMessage?.role === 'task';+ });+ if (taskChildren.length > 0) {+ return nextNode;}- // Otherwise, return the first child of the last node- if (lastNode.children.length > 0) {- return lastNode.children[0];- }- return null;+ return nextNode.children[0] ?? null;}/**- * Find the last node in an AssistantGroup sequence- * Only follows messages from the SAME agent (matching agentId)+ * Return the final same-agent assistant that belongs inside this group. The+ * child selected after that assistant can be either a tool-hosted legacy+ * continuation or a direct non-tool continuation in the current storage form.*/- findLastNodeInAssistantGroup(idNode: IdNode, groupAgentId?: string): IdNode | null {- // Walk the chain to its next step (dual-form aware, see findChainContinuationNode)+ private findLastAssistantNodeInGroup(idNode: IdNode, groupAgentId?: string): IdNode {const nextNode = this.findChainContinuationNode(idNode, groupAgentId);- if (nextNode) {- return this.findLastNodeInAssistantGroup(nextNode, groupAgentId);- }+ return nextNode ? this.findLastAssistantNodeInGroup(nextNode, groupAgentId) : idNode;+ }- // No further same-agent assistant. If this step still owns tool results- // (e.g. the last tool hosts an AgentCouncil / tasks), return the last tool- // node so findNextAfterTools can inspect it; otherwise this node is the tail.- const toolChildren = idNode.children.filter(- (child) => this.messageMap.get(child.id)?.role === 'tool',+ /**+ * Resolve the first node after an AssistantGroup without applying+ * `activeBranchIndex` to tool children. Persisted branch indexes count only+ * non-tool direct children; latest-user inference may still select a legacy+ * continuation hosted below a tool result when no explicit branch is active.+ */+ private resolveAssistantGroupTailChild(idNode: IdNode): IdNode | undefined {+ const message = this.messageMap.get(idNode.id);+ if (!message) return idNode.children.at(-1);++ const childIds = idNode.children.map((child) => child.id);+ const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(+ message,+ childIds,+ this.childrenMap,+ this.branchResolver.getMetadataBranchIds(childIds),);- if (toolChildren.length === 0) {- return idNode;- }- return toolChildren.at(-1) ?? null;++ return idNode.children.find((child) => child.id === activeBranchId);}}diff --git a/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts b/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.tsindex 476d2fb298d..1b66abe0210 100644--- a/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts+++ b/packages/conversation-flow/src/transformation/__tests__/BranchResolver.test.ts@@ -149,6 +149,66 @@ describe('BranchResolver', () => {expect(resolver.getActiveBranchIdFromMetadata(message, childIds, childrenMap)).toBe('msg-3');});+ it('should ignore newer user descendants from threads when selecting the active branch', () => {+ const messages: Message[] = [+ {+ content: 'test',+ createdAt: 0,+ id: 'msg-1',+ role: 'user',+ updatedAt: 0,+ },+ {+ content: 'old branch',+ createdAt: 1,+ id: 'msg-2',+ parentId: 'msg-1',+ role: 'assistant',+ updatedAt: 1,+ },+ {+ content: 'current branch',+ createdAt: 2,+ id: 'msg-3',+ parentId: 'msg-1',+ role: 'assistant',+ updatedAt: 2,+ },+ {+ content: 'continued main flow',+ createdAt: 3,+ id: 'msg-4',+ parentId: 'msg-3',+ role: 'user',+ updatedAt: 3,+ },+ {+ content: 'newer threaded reply',+ createdAt: 4,+ id: 'msg-5',+ parentId: 'msg-2',+ role: 'user',+ threadId: 'thread-1',+ updatedAt: 4,+ },+ ];+ const resolverWithMessages = new BranchResolver(+ new Map(messages.map((item) => [item.id, item])),+ );+ const childrenMap = new Map<string | null, string[]>([+ ['msg-2', ['msg-5']],+ ['msg-3', ['msg-4']],+ ]);++ expect(+ resolverWithMessages.getActiveBranchIdFromMetadata(+ messages[0],+ ['msg-2', 'msg-3'],+ childrenMap,+ ),+ ).toBe('msg-3');+ });+it('should default to first child when no hints available', () => {const message: Message = {content: 'test',diff --git a/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts b/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.tsindex 9570c6ad41e..3757b2a66b0 100644--- a/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts+++ b/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts@@ -196,210 +196,6 @@ describe('MessageCollector', () => {});});- describe('findLastNodeInAssistantGroup', () => {- it('should return the node itself if no tool children', () => {- const messageMap = new Map<string, Message>();- const childrenMap = new Map<string | null, string[]>();- const collector = new MessageCollector(messageMap, childrenMap);-- const idNode: IdNode = {- children: [],- id: 'msg-1',- };-- const result = collector.findLastNodeInAssistantGroup(idNode);-- expect(result).toEqual(idNode);- });-- it('should return last tool node if no assistant children', () => {- const messageMap = new Map<string, Message>([- [- 'msg-1',- {- content: 'test',- createdAt: 0,- id: 'msg-1',- role: 'assistant',- updatedAt: 0,- },- ],- [- 'tool-1',- {- content: 'result',- createdAt: 0,- id: 'tool-1',- parentId: 'msg-1',- role: 'tool',- updatedAt: 0,- },- ],- ]);- const childrenMap = new Map<string | null, string[]>();- const collector = new MessageCollector(messageMap, childrenMap);-- const idNode: IdNode = {- children: [{ children: [], id: 'tool-1' }],- id: 'msg-1',- };-- const result = collector.findLastNodeInAssistantGroup(idNode);-- expect(result?.id).toBe('tool-1');- });-- it('should follow assistant chain recursively', () => {- const messageMap = new Map<string, Message>([- [- 'msg-1',- {- content: 'test1',- createdAt: 0,- id: 'msg-1',- role: 'assistant',- updatedAt: 0,- },- ],- [- 'tool-1',- {- content: 'result1',- createdAt: 0,- id: 'tool-1',- parentId: 'msg-1',- role: 'tool',- updatedAt: 0,- },- ],- [- 'msg-2',- {- content: 'test2',- createdAt: 0,- id: 'msg-2',- parentId: 'tool-1',- role: 'assistant',- updatedAt: 0,- },- ],- ]);- const childrenMap = new Map<string | null, string[]>();- const collector = new MessageCollector(messageMap, childrenMap);-- const idNode: IdNode = {- children: [- {- children: [{ children: [], id: 'msg-2' }],- id: 'tool-1',- },- ],- id: 'msg-1',- };-- const result = collector.findLastNodeInAssistantGroup(idNode);-- expect(result?.id).toBe('msg-2');- });-- it('skips signal-tagged callbacks when locating the group tail', () => {- // when [signal callback, next tool-using assistant]- // both live under the same tool, the tail finder must follow the- // real main-chain assistant — taking children[0] blindly lands on- // the callback (which is a leaf) and truncates the AssistantGroup.- const messageMap = new Map<string, Message>([- [- 'ast-0',- {- agentId: 'agent-x',- content: '',- createdAt: 0,- id: 'ast-0',- role: 'assistant',- updatedAt: 0,- },- ],- [- 'tool-1',- {- content: '',- createdAt: 0,- id: 'tool-1',- parentId: 'ast-0',- role: 'tool',- tool_call_id: 'toolu_mon',- updatedAt: 0,- },- ],- [- 'cb-1',- {- agentId: 'agent-x',- content: '',- createdAt: 0,- id: 'cb-1',- metadata: {- signal: {- sequence: 1,- sourceToolCallId: 'toolu_mon',- sourceToolName: 'Monitor',- type: 'tool-stdout',- },- } as any,- parentId: 'tool-1',- role: 'assistant',- updatedAt: 0,- },- ],- [- 'ast-4',- {- agentId: 'agent-x',- content: '',- createdAt: 0,- id: 'ast-4',- parentId: 'tool-1',- role: 'assistant',- updatedAt: 0,- },- ],- [- 'tool-2',- {- content: '',- createdAt: 0,- id: 'tool-2',- parentId: 'ast-4',- role: 'tool',- updatedAt: 0,- },- ],- ]);- const collector = new MessageCollector(messageMap, new Map());-- const idNode: IdNode = {- children: [- {- children: [- { children: [], id: 'cb-1' },- {- children: [{ children: [], id: 'tool-2' }],- id: 'ast-4',- },- ],- id: 'tool-1',- },- ],- id: 'ast-0',- };-- const result = collector.findLastNodeInAssistantGroup(idNode, 'agent-x');-- // Tail must be tool-2 (descended through ast-4), NOT cb-1.- expect(result?.id).toBe('tool-2');- });- });-// ────────────────────────────────────────────────────// external signal callback collection// ────────────────────────────────────────────────────@@ -796,6 +592,75 @@ describe('MessageCollector', () => {expect(allToolMessages.map((m) => m.id)).toEqual(['tool-1', 'tool-2']);});+ it('uses the latest user descendant when the default resolver selects a continuation', () => {+ const astRoot = mkAssistant('ast-root', {+ parentId: 'user-root',+ tools: [bashTool('tc-1')],+ });+ const tool = mkTool('tool-1', { parentId: 'ast-root', tool_call_id: 'tc-1' });+ const astOld = mkAssistant('ast-old', { createdAt: 2, parentId: 'tool-1' });+ const astCurrent = mkAssistant('ast-current', { createdAt: 3, parentId: 'tool-1' });+ const userOld: Message = {+ content: 'old follow-up',+ createdAt: 4,+ id: 'user-old',+ parentId: 'ast-old',+ role: 'user',+ updatedAt: 4,+ };+ const userCurrent: Message = {+ content: 'current follow-up',+ createdAt: 5,+ id: 'user-current',+ parentId: 'ast-current',+ role: 'user',+ updatedAt: 5,+ };+ const allMessages = [astRoot, tool, astOld, astCurrent, userOld, userCurrent];+ const messageMap = new Map(allMessages.map((message) => [message.id, message]));+ const childrenMap = new Map<string | null, string[]>([+ ['tool-1', ['ast-old', 'ast-current']],+ ['ast-old', ['user-old']],+ ['ast-current', ['user-current']],+ ]);+ const collector = new MessageCollector(messageMap, childrenMap);++ const assistantChain: Message[] = [];+ collector.collectAssistantChain(astRoot, allMessages, assistantChain, [], new Set());++ expect(assistantChain.map((message) => message.id)).toEqual(['ast-root', 'ast-current']);+ });++ it('preserves activeBranchIndex when filtered continuations use a smaller candidate set', () => {+ const astRoot = mkAssistant('ast-root', {+ metadata: { activeBranchIndex: 2 },+ parentId: 'user-root',+ tools: [bashTool('tc-1')],+ });+ const tool = mkTool('tool-1', { parentId: 'ast-root', tool_call_id: 'tc-1' });+ const otherAgent = mkAssistant('ast-other-agent', {+ agentId: 'agent-y',+ createdAt: 1,+ parentId: 'ast-root',+ });+ const astOld = mkAssistant('ast-old', { createdAt: 2, parentId: 'ast-root' });+ const astCurrent = mkAssistant('ast-current', { createdAt: 3, parentId: 'ast-root' });+ const allMessages = [astRoot, tool, otherAgent, astOld, astCurrent];+ const messageMap = new Map(allMessages.map((message) => [message.id, message]));+ const childrenMap = new Map<string | null, string[]>([+ ['ast-root', ['tool-1', 'ast-other-agent', 'ast-old', 'ast-current']],+ ]);+ const collector = new MessageCollector(messageMap, childrenMap);++ const assistantChain: Message[] = [];+ const processedIds = new Set<string>();+ collector.collectAssistantChain(astRoot, allMessages, assistantChain, [], processedIds);++ expect(assistantChain.map((message) => message.id)).toEqual(['ast-root', 'ast-current']);+ expect(processedIds.has('ast-old')).toBe(true);+ expect(processedIds.has('ast-other-agent')).toBe(false);+ });+it('continues past a duplicate edge to the current turn own tool result', () => {// A → tool(x) → B; B re-declares the SAME tool_call_id x and has its real// continuation C under B's own tool result. collectToolMessages(B) resolvesdiff --git a/packages/conversation-flow/src/transformation/index.ts b/packages/conversation-flow/src/transformation/index.tsindex 0fb091a3273..26aede9e1a7 100644--- a/packages/conversation-flow/src/transformation/index.ts+++ b/packages/conversation-flow/src/transformation/index.ts@@ -30,7 +30,7 @@ export class Transformer {this.messageMap = helperMaps.messageMap;// Initialize utility classes- this.branchResolver = new BranchResolver();+ this.branchResolver = new BranchResolver(this.messageMap);this.messageCollector = new MessageCollector(this.messageMap,helperMaps.childrenMap,diff --git a/packages/database/src/models/__tests__/messages/message.delete.test.ts b/packages/database/src/models/__tests__/messages/message.delete.test.tsindex 22cf2742175..facb0504e0a 100644--- a/packages/database/src/models/__tests__/messages/message.delete.test.ts+++ b/packages/database/src/models/__tests__/messages/message.delete.test.ts@@ -25,7 +25,6 @@ const serverDB: LobeChatDatabase = await getTestDB();const userId = 'message-delete-test';const otherUserId = 'message-delete-test-other';const messageModel = new MessageModel(serverDB, userId);-const embeddingsId = uuid();beforeEach(async () => {// Clear tables before each test case@@ -101,6 +100,86 @@ describe('MessageModel Delete Tests', () => {expect(result).toHaveLength(1);});+ it('should clear a stale active branch index when the selected branch is deleted', async () => {+ await serverDB.insert(messages).values([+ {+ content: 'parent',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'parent',+ metadata: { activeBranchIndex: 1, collapsed: true },+ role: 'assistant',+ userId,+ },+ {+ content: 'branch A',+ createdAt: new Date('2026-01-01T00:00:01.000Z'),+ id: 'branch-a',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ {+ content: 'branch B',+ createdAt: new Date('2026-01-01T00:00:02.000Z'),+ id: 'branch-b',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ ]);++ await messageModel.deleteMessage('branch-b');++ const parent = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'parent'),+ });+ expect(parent?.metadata).toEqual({ collapsed: true });+ });++ it('should remap the selected branch by identity when an earlier branch is deleted', async () => {+ await serverDB.insert(messages).values([+ {+ content: 'parent',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'parent',+ metadata: { activeBranchIndex: 1 },+ role: 'assistant',+ userId,+ },+ {+ content: 'tool result',+ createdAt: new Date('2026-01-01T00:00:00.500Z'),+ id: 'tool',+ parentId: 'parent',+ role: 'tool',+ userId,+ },+ {+ content: 'branch A',+ createdAt: new Date('2026-01-01T00:00:01.000Z'),+ id: 'branch-a',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ {+ content: 'branch B',+ createdAt: new Date('2026-01-01T00:00:02.000Z'),+ id: 'branch-b',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ ]);++ await messageModel.deleteMessage('branch-a');++ const parent = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'parent'),+ });+ expect(parent?.metadata).toEqual({ activeBranchIndex: 0 });+ });+it('should update child messages parentId to deleted message parentId', async () => {// Create a tree structure: A -> B -> C// When B is deleted, C should have parentId = A@@ -211,6 +290,86 @@ describe('MessageModel Delete Tests', () => {expect(result).toHaveLength(1);});+ it('should remap the selected branch after deleting earlier branches in a batch', async () => {+ await serverDB.insert(messages).values([+ {+ content: 'parent',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'parent',+ metadata: { activeBranchIndex: 2 },+ role: 'assistant',+ userId,+ },+ {+ content: 'branch A',+ createdAt: new Date('2026-01-01T00:00:01.000Z'),+ id: 'branch-a',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ {+ content: 'branch B',+ createdAt: new Date('2026-01-01T00:00:02.000Z'),+ id: 'branch-b',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ {+ content: 'branch C',+ createdAt: new Date('2026-01-01T00:00:03.000Z'),+ id: 'branch-c',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ ]);++ await messageModel.deleteMessages(['branch-a', 'branch-b']);++ const parent = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'parent'),+ });+ expect(parent?.metadata).toEqual({ activeBranchIndex: 0 });+ });++ it('should preserve an optimistic branch marker when deleting a sibling', async () => {+ await serverDB.insert(messages).values([+ {+ content: 'parent',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'parent',+ metadata: { activeBranchIndex: 2 },+ role: 'assistant',+ userId,+ },+ {+ content: 'branch A',+ createdAt: new Date('2026-01-01T00:00:01.000Z'),+ id: 'branch-a',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ {+ content: 'branch B',+ createdAt: new Date('2026-01-01T00:00:02.000Z'),+ id: 'branch-b',+ parentId: 'parent',+ role: 'user',+ userId,+ },+ ]);++ await messageModel.deleteMessages(['branch-a']);++ const parent = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'parent'),+ });+ expect(parent?.metadata).toEqual({ activeBranchIndex: 1 });+ });+it('should update child messages parentId when deleting parent chain', async () => {// Create a tree: A -> B -> C -> D// Delete [B, C], D should have parentId = Adiff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 3afc6b01bea..c6f54db11c9 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -32,6 +32,7 @@ import {logTimingSink as logTiming,runTimedSinkStage as runTimedStage,} from '@lobechat/utils';+import { isPlainRecord } from '@lobechat/utils/object';import type { HeatmapsProps } from '@lobehub/charts';import dayjs from 'dayjs';import type { SQL } from 'drizzle-orm';@@ -185,6 +186,14 @@ interface MessageThreadRelation {title: string | null;}+interface ActiveBranchSnapshot {+ activeBranchId?: string;+ activeBranchIndex: number;+ metadata: Record<PropertyKey, unknown>;+ parentId: string;+ wasOptimistic: boolean;+}+interface MessageFileRelations {documentsMap: Record<string, string>;relatedFileList: MessageRelatedFile[];@@ -3175,6 +3184,105 @@ export class MessageModel {// **************** Delete *************** //+ /**+ * Preserve the selected branch by identity across a deletion. Branch metadata+ * stores a positional index, while deleting or reparenting children can change+ * that index space. If the selected branch itself is deleted, remove the stale+ * index so conversation-flow can infer the remaining active branch instead of+ * mistaking `index === branchCount` for an optimistic branch creation.+ */+ private captureActiveBranchSnapshots = async (+ tx: Transaction,+ parentIds: string[],+ ): Promise<ActiveBranchSnapshot[]> => {+ const uniqueParentIds = [...new Set(parentIds)];+ if (uniqueParentIds.length === 0) return [];++ const parentRows = await tx+ .select({ id: messages.id, metadata: messages.metadata })+ .from(messages)+ .where(and(this.ownership(), inArray(messages.id, uniqueParentIds)));+ const branchIdsByParent = await this.queryDirectBranchIds(tx, uniqueParentIds);+ const snapshots: ActiveBranchSnapshot[] = [];++ for (const parent of parentRows) {+ if (!isPlainRecord(parent.metadata)) continue;++ const activeBranchIndex = parent.metadata.activeBranchIndex;+ if (typeof activeBranchIndex !== 'number' || activeBranchIndex < 0) continue;++ const branchIds = branchIdsByParent.get(parent.id) ?? [];+ snapshots.push({+ activeBranchId: branchIds[activeBranchIndex],+ activeBranchIndex,+ metadata: parent.metadata,+ parentId: parent.id,+ wasOptimistic: activeBranchIndex === branchIds.length,+ });+ }++ return snapshots;+ };++ private queryDirectBranchIds = async (tx: Transaction, parentIds: string[]) => {+ const branchRows = await tx+ .select({ id: messages.id, parentId: messages.parentId })+ .from(messages)+ .where(+ and(+ this.ownership(),+ inArray(messages.parentId, parentIds),+ not(eq(messages.role, 'tool')),+ ),+ )+ .orderBy(asc(messages.createdAt), asc(messages.id));+ const branchIdsByParent = new Map<string, string[]>();++ for (const branch of branchRows) {+ if (!branch.parentId) continue;+ const branchIds = branchIdsByParent.get(branch.parentId) ?? [];+ branchIds.push(branch.id);+ branchIdsByParent.set(branch.parentId, branchIds);+ }++ return branchIdsByParent;+ };++ private reconcileActiveBranchSnapshots = async (+ tx: Transaction,+ snapshots: ActiveBranchSnapshot[],+ ) => {+ if (snapshots.length === 0) return;++ const branchIdsByParent = await this.queryDirectBranchIds(+ tx,+ snapshots.map((snapshot) => snapshot.parentId),+ );++ for (const snapshot of snapshots) {+ const branchIds = branchIdsByParent.get(snapshot.parentId) ?? [];+ const survivingBranchIndex = snapshot.activeBranchId+ ? branchIds.indexOf(snapshot.activeBranchId)+ : -1;+ const activeBranchIndex = snapshot.wasOptimistic+ ? branchIds.length+ : survivingBranchIndex >= 0+ ? survivingBranchIndex+ : undefined;++ if (activeBranchIndex === snapshot.activeBranchIndex) continue;++ const metadata = { ...snapshot.metadata };+ delete metadata.activeBranchIndex;+ if (activeBranchIndex !== undefined) metadata.activeBranchIndex = activeBranchIndex;++ await tx+ .update(messages)+ .set({ metadata })+ .where(and(eq(messages.id, snapshot.parentId), this.ownership()));+ }+ };+deleteMessage = async (id: string) => {return this.db.transaction(async (tx) => {// 1. Query the complete information of the message to be deleted@@ -3187,6 +3295,11 @@ export class MessageModel {// If the message to be deleted is not found, return directlyif (message.length === 0) return;+ const activeBranchSnapshots = await this.captureActiveBranchSnapshots(+ tx,+ message[0].parentId ? [message[0].parentId] : [],+ );+// 2. Update child messages' parentId to the current message's parentId// This preserves the tree structure when deleting a nodeawait tx@@ -3219,6 +3332,8 @@ export class MessageModel {.delete(messages).where(and(this.ownership(), inArray(messages.id, messageIdsToDelete)));+ await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);+// 7. Keep the topic's usage rollup in sync (pure derived — a removed// assistant message must drop out of the topic totals).if (message[0].topicId) {@@ -3275,6 +3390,11 @@ export class MessageModel {findFinalAncestor(id);}+ const activeBranchSnapshots = await this.captureActiveBranchSnapshots(+ tx,+ [...new Set(finalAncestorMap.values())].filter((id): id is string => id !== null),+ );+// 4. Query child messages whose parentId points to messages being deletedconst children = await tx.select({ id: messages.id, parentId: messages.parentId })@@ -3295,6 +3415,8 @@ export class MessageModel {// 6. Delete the messagesawait tx.delete(messages).where(and(this.ownership(), inArray(messages.id, ids)));+ await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);+// 7. Recompute the usage rollup for every affected topic (pure derived).const affectedTopicIds = [...new Set(toDelete.map((m) => m.topicId).filter(Boolean) as string[]),diff --git a/packages/model-runtime/src/core/__tests__/providerDiagnostics.test.ts b/packages/model-runtime/src/core/__tests__/providerDiagnostics.test.tsnew file mode 100644index 00000000000..98493b47865--- /dev/null+++ b/packages/model-runtime/src/core/__tests__/providerDiagnostics.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest';++import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';+import {+ appendRawProviderEvent,+ captureRawProviderResponse,+ waitForRawProviderResponse,+} from '../providerDiagnostics';++const createDiagnostics = (): ProviderResponseDiagnostics => ({+ apiMode: 'test',+ droppedEventCount: 0,+ eventCount: 0,+ eventCounts: {},+ events: [],+ hasNonWhitespaceText: false,+ hasNonWhitespaceThinking: false,+ rawEvents: [],+ signatureChars: 0,+ terminalEventReceived: false,+ textChars: 0,+ thinkingChars: 0,+ toolInputChars: 0,+ toolUseCount: 0,+});++describe('providerDiagnostics', () => {+ it('caps the number of retained provider events', () => {+ const diagnostics = createDiagnostics();++ for (let index = 0; index < 129; index++) {+ appendRawProviderEvent(diagnostics, { index, type: 'chunk' });+ }++ expect(diagnostics.rawEvents).toHaveLength(128);+ expect(diagnostics.droppedRawEventCount).toBe(1);+ expect(diagnostics.rawEventByteLength).toBeGreaterThan(0);+ });++ it('drops a provider event that exceeds the retained byte budget', () => {+ const diagnostics = createDiagnostics();++ appendRawProviderEvent(diagnostics, { content: 'x'.repeat(300 * 1024) });++ expect(diagnostics.rawEvents).toEqual([]);+ expect(diagnostics.droppedRawEventCount).toBe(1);+ expect(diagnostics.rawEventByteLength).toBeUndefined();+ });++ it('stops reading a raw response after the retained byte budget', async () => {+ const diagnostics = createDiagnostics();++ captureRawProviderResponse(diagnostics, new Response('x'.repeat(300 * 1024)));+ await waitForRawProviderResponse(diagnostics);++ expect(diagnostics.rawResponse).toMatchObject({+ byteLength: 256 * 1024,+ status: 'captured',+ truncated: true,+ });+ expect(diagnostics.rawResponse?.body).toHaveLength(256 * 1024);+ });+});diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.tsindex 4e2f8075ae2..9805dfe5ce6 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts@@ -2,6 +2,7 @@import Anthropic from '@anthropic-ai/sdk';import { afterEach, describe, expect, it, vi } from 'vitest';+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';import {createAnthropicCompatibleRuntime,createDefaultAnthropicClient,@@ -213,6 +214,213 @@ describe('createAnthropicCompatibleRuntime', () => {expect(createClient.mock.calls[0][0]).not.toHaveProperty('modelIdMapping');});+ it('should retain the exact provider request and raw streaming response diagnostics', async () => {+ const rawEvents = [+ {+ message: {+ content: [],+ id: 'msg_deepseek_empty',+ model: 'deepseek-v4-pro',+ role: 'assistant',+ stop_reason: null,+ stop_sequence: null,+ type: 'message',+ usage: { input_tokens: 206_384, output_tokens: 0 },+ },+ type: 'message_start',+ },+ {+ content_block: { signature: 'provider-signature', thinking: ' ', type: 'thinking' },+ index: 0,+ type: 'content_block_start',+ },+ { index: 0, type: 'content_block_stop' },+ {+ delta: { stop_reason: 'end_turn', stop_sequence: null },+ type: 'message_delta',+ usage: { input_tokens: 206_384, output_tokens: 1 },+ },+ { type: 'message_stop' },+ ] as unknown as Anthropic.MessageStreamEvent[];+ const rawResponseBody = rawEvents.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('');+ const rawStream = {+ async *[Symbol.asyncIterator]() {+ for (const event of rawEvents) yield event;+ },+ };+ const messagesCreate = vi.fn(() => ({+ withResponse: vi.fn().mockResolvedValue({+ data: rawStream,+ request_id: 'req_deepseek_empty',+ response: new Response(rawResponseBody, {+ headers: {+ 'cf-ray': 'ray-1',+ 'content-type': 'text/event-stream',+ 'x-request-id': 'req-header-1',+ },+ status: 200,+ }),+ }),+ }));+ const Runtime = createAnthropicCompatibleRuntime({+ chatCompletion: {+ handlePayload: (payload) => ({+ max_tokens: 4096,+ messages: [{ content: 'Question', role: 'user' }],+ model: payload.model,+ thinking: { budget_tokens: 2048, type: 'enabled' },+ }),+ },+ customClient: {+ createClient: () =>+ ({+ baseURL: 'https://api.deepseek.com/anthropic',+ messages: { create: messagesCreate },+ }) as unknown as Anthropic,+ },+ provider: 'test-provider',+ });+ const runtime = new Runtime({+ apiKey: 'test-key',+ baseURL: 'https://api.deepseek.com/anthropic',+ });+ const diagnostics: ModelRuntimeDiagnostics = {};++ const response = await runtime.chat(+ {+ messages: [{ content: 'Question', role: 'user' }],+ model: 'deepseek-v4-pro',+ stream: true,+ },+ { diagnostics, user: 'user-1' },+ );+ await response.text();++ expect(diagnostics.providerRequest).toEqual(+ expect.objectContaining({+ apiMode: 'messages',+ endpoint: expect.stringMatching(/\/anthropic$/),+ payload: expect.objectContaining({+ max_tokens: 4096,+ messages: [{ content: 'Question', role: 'user' }],+ metadata: { user_id: 'user-1' },+ model: 'deepseek-v4-pro',+ stream: true,+ }),+ sentAt: expect.any(Number),+ }),+ );+ expect(diagnostics.providerResponse).toEqual(+ expect.objectContaining({+ completedAt: expect.any(Number),+ eventCount: 5,+ eventCounts: expect.objectContaining({+ 'content_block_start:thinking': 1,+ 'message_delta': 1,+ 'message_stop': 1,+ }),+ firstEventAt: expect.any(Number),+ hasNonWhitespaceText: false,+ hasNonWhitespaceThinking: false,+ headers: {+ 'cf-ray': 'ray-1',+ 'content-type': 'text/event-stream',+ 'x-request-id': 'req-header-1',+ },+ messageId: 'msg_deepseek_empty',+ model: 'deepseek-v4-pro',+ rawEvents,+ rawResponse: {+ body: rawResponseBody,+ byteLength: new TextEncoder().encode(rawResponseBody).byteLength,+ status: 'captured',+ },+ requestId: 'req_deepseek_empty',+ responseReceivedAt: expect.any(Number),+ signatureChars: 18,+ status: 200,+ stopReason: 'end_turn',+ terminalEventReceived: true,+ thinkingChars: 1,+ toolUseCount: 0,+ usage: { input_tokens: 206_384, output_tokens: 1 },+ }),+ );+ });++ it('should observe provider diagnostics from a custom ReadableStream response', async () => {+ const rawEvents = [+ {+ message: {+ content: [],+ id: 'msg_readable_stream',+ model: 'custom-model',+ role: 'assistant',+ stop_reason: null,+ stop_sequence: null,+ type: 'message',+ usage: { input_tokens: 12, output_tokens: 0 },+ },+ type: 'message_start',+ },+ {+ delta: { stop_reason: 'end_turn', stop_sequence: null },+ type: 'message_delta',+ usage: { input_tokens: 12, output_tokens: 0 },+ },+ { type: 'message_stop' },+ ] as unknown as Anthropic.MessageStreamEvent[];+ const rawStream = new ReadableStream<Anthropic.MessageStreamEvent>({+ start(controller) {+ for (const event of rawEvents) controller.enqueue(event);+ controller.close();+ },+ });+ 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://example.com/anthropic',+ 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: 'custom-model',+ stream: true,+ },+ { diagnostics },+ );+ await response.text();++ expect(diagnostics.providerResponse).toEqual(+ expect.objectContaining({+ completedAt: expect.any(Number),+ eventCount: 3,+ messageId: 'msg_readable_stream',+ rawEvents,+ stopReason: 'end_turn',+ terminalEventReceived: true,+ }),+ );+ });+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/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.tsindex fa0c457876f..57a0fa55103 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts@@ -34,12 +34,19 @@ import {} from '../contextBuilders/anthropic';import { resolveModelSamplingParameters } from '../parameterResolver';import { AnthropicStream, type AnthropicStreamOptions } from '../streams';+import { readableFromAsyncIterable } from '../streams/protocol';import { type ComputeChatCostOptions } from '../usageConverters/utils/computeChatCost';import {type AnthropicGenerateObjectConfig,createAnthropicGenerateObject,} from './generateObject';import { handleAnthropicError } from './handleAnthropicError';+import {+ initializeAnthropicDiagnostics,+ observeAnthropicStream,+ recordAnthropicNonStreamingResponse,+ recordAnthropicResponseMetadata,+} from './providerDiagnostics';import { resolveCacheTTL } from './resolveCacheTTL';import { resolveMaxTokens } from './resolveMaxTokens';import { resolveClaudeThinkingConfig } from './resolveThinkingConfig';@@ -558,20 +565,41 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =);}- if (debugParams?.chatCompletion?.()) {+ const shouldDebugChatCompletion = debugParams?.chatCompletion?.() ?? false;+ if (shouldDebugChatCompletion) {debugPayload(requestPayload);}- const response = await this.client.messages.create(- {- ...requestPayload,- metadata: options?.user ? { user_id: options.user } : undefined,- },- {- headers: options?.requestHeaders,- signal: options?.signal,- },- );+ const providerRequestPayload = {+ ...requestPayload,+ metadata: options?.user ? { user_id: options.user } : undefined,+ };+ const providerRequestStartedAt = Date.now();+ const providerResponseDiagnostics = initializeAnthropicDiagnostics({+ diagnostics: options?.diagnostics,+ endpoint: desensitizeUrl(this.baseURL),+ payload: providerRequestPayload,+ sentAt: providerRequestStartedAt,+ });+ const responsePromise = this.client.messages.create(providerRequestPayload, {+ headers: options?.requestHeaders,+ signal: options?.signal,+ });+ /**+ * Custom Anthropic-compatible clients may return a plain Promise instead+ * of the SDK's APIPromise. Prefer withResponse() for request IDs and safe+ * headers, while preserving compatibility with those clients.+ */+ const responseWithMetadata =+ typeof responsePromise.withResponse === 'function'+ ? await responsePromise.withResponse()+ : { data: await responsePromise };+ const response = responseWithMetadata.data;+ recordAnthropicResponseMetadata(providerResponseDiagnostics, {+ requestId:+ 'request_id' in responseWithMetadata ? responseWithMetadata.request_id : undefined,+ response: 'response' in responseWithMetadata ? responseWithMetadata.response : undefined,+ });const pricing = await getModelPricing(payload.model, this.id, options?.pricingContext);const pricingOptions = await chatCompletion?.getPricingOptions?.(payload, postPayload);@@ -587,16 +615,35 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =} satisfies Pick<AnthropicStreamOptions, 'callbacks' | 'payload'>;if (shouldStream) {- const streamResponse = response as Stream<Anthropic.MessageStreamEvent>;- const [prod, useForDebug] = streamResponse.tee();+ const streamResponse = response as+ Stream<Anthropic.MessageStreamEvent> | ReadableStream<Anthropic.MessageStreamEvent>;+ let prod: Stream<Anthropic.MessageStreamEvent> | ReadableStream = streamResponse;- if (debugParams?.chatCompletion?.()) {+ if (shouldDebugChatCompletion) {+ const [productionStream, useForDebug] = streamResponse.tee();+ prod = productionStream;const useForDebugStream =useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();debugStream(useForDebugStream).catch(console.error);}+ if (providerResponseDiagnostics) {+ /** Observe provider-native events before the protocol adapter transforms them. */+ const observedStream = observeAnthropicStream(+ prod,+ providerResponseDiagnostics,+ options?.signal,+ );+ prod =+ observedStream instanceof ReadableStream+ ? observedStream+ : readableFromAsyncIterable(observedStream, {+ model: payload.model,+ provider: this.id,+ });+ }+return StreamingResponse(chatCompletion?.handleStream? chatCompletion.handleStream(prod, {@@ -611,6 +658,12 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =);}+ await recordAnthropicNonStreamingResponse(+ providerResponseDiagnostics,+ response as Anthropic.Message,+ options?.signal,+ );+if (payload.responseMode === 'json') {return Response.json(response);}diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.tsnew file mode 100644index 00000000000..b1bc1344df9--- /dev/null+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.ts@@ -0,0 +1,348 @@+import type Anthropic from '@anthropic-ai/sdk';++import type {+ ModelRuntimeDiagnostics,+ ProviderResponseDiagnostics,+ ProviderResponseEventDiagnostics,+} from '../../types/providerDiagnostics';+import {+ appendRawProviderEvent,+ captureRawProviderResponse,+ waitForRawProviderResponse,+} from '../providerDiagnostics';++const MAX_RECORDED_PROVIDER_EVENTS = 128;+const MAX_RECORDED_ERROR_MESSAGE_LENGTH = 500;+const RESPONSE_HEADER_NAMES = [+ 'anthropic-request-id',+ 'cf-ray',+ 'content-length',+ 'content-type',+ 'date',+ 'request-id',+ 'server-timing',+ 'trace-id',+ 'x-aihubmix-request-id',+ 'x-ds-trace-id',+ 'x-request-id',+ 'x-stainless-request-id',+ 'x-trace-id',+] as const;++interface InitializeAnthropicDiagnosticsParams {+ diagnostics?: ModelRuntimeDiagnostics;+ endpoint?: string;+ payload: Anthropic.MessageCreateParams;+ sentAt: number;+}++interface AnthropicResponseMetadata {+ requestId?: string | null;+ response?: Response;+}++const appendEvent = (+ diagnostics: ProviderResponseDiagnostics,+ event: Omit<ProviderResponseEventDiagnostics, 'index'>,+) => {+ const indexedEvent = { ...event, index: diagnostics.eventCount };+ diagnostics.eventCount += 1;++ const eventKey = [event.type, event.blockType, event.deltaType].filter(Boolean).join(':');+ diagnostics.eventCounts[eventKey] = (diagnostics.eventCounts[eventKey] ?? 0) + 1;++ if (diagnostics.events.length >= MAX_RECORDED_PROVIDER_EVENTS) {+ diagnostics.events.shift();+ diagnostics.droppedEventCount += 1;+ }+ diagnostics.events.push(indexedEvent);+};++const recordStringContent = (+ diagnostics: ProviderResponseDiagnostics,+ event: Omit<ProviderResponseEventDiagnostics, 'index'>,+ content: string,+ kind: 'signature' | 'text' | 'thinking' | 'toolInput',+) => {+ if (kind === 'signature') {+ diagnostics.signatureChars += content.length;+ event.signatureLength = content.length;+ return;+ }++ const hasNonWhitespaceContent = content.trim().length > 0;+ event.contentLength = content.length;+ event.hasNonWhitespaceContent = hasNonWhitespaceContent;++ if (kind === 'text') {+ diagnostics.textChars += content.length;+ diagnostics.hasNonWhitespaceText ||= hasNonWhitespaceContent;+ }+ if (kind === 'thinking') {+ diagnostics.thinkingChars += content.length;+ diagnostics.hasNonWhitespaceThinking ||= hasNonWhitespaceContent;+ }+ if (kind === 'toolInput') diagnostics.toolInputChars += content.length;++ if (hasNonWhitespaceContent && diagnostics.firstNonWhitespaceOutputAt === undefined) {+ diagnostics.firstNonWhitespaceOutputAt = Date.now();+ }+};++const recordError = (diagnostics: ProviderResponseDiagnostics, error: unknown) => {+ diagnostics.error = {+ message:+ error instanceof Error+ ? error.message.slice(0, MAX_RECORDED_ERROR_MESSAGE_LENGTH)+ : undefined,+ name: error instanceof Error ? error.name : undefined,+ };+};++const finalizeResponse = async (diagnostics: ProviderResponseDiagnostics, signal?: AbortSignal) => {+ await waitForRawProviderResponse(diagnostics);+ diagnostics.aborted = signal?.aborted || undefined;+ diagnostics.completedAt ??= Date.now();+};++const recordMessageContentBlock = (+ diagnostics: ProviderResponseDiagnostics,+ block: Anthropic.ContentBlock,+ index: number,+) => {+ const event: Omit<ProviderResponseEventDiagnostics, 'index'> = {+ blockIndex: index,+ blockType: block.type,+ type: 'content_block_start',+ };++ if (block.type === 'text') recordStringContent(diagnostics, event, block.text, 'text');+ if (block.type === 'thinking') {+ recordStringContent(diagnostics, event, block.thinking, 'thinking');+ recordStringContent(diagnostics, event, block.signature, 'signature');+ }+ if (block.type === 'redacted_thinking') {+ recordStringContent(diagnostics, event, block.data, 'signature');+ }+ if (block.type === 'tool_use' || block.type === 'server_tool_use') {+ diagnostics.toolUseCount += 1;+ diagnostics.firstNonWhitespaceOutputAt ??= Date.now();+ }++ appendEvent(diagnostics, event);+};++export const initializeAnthropicDiagnostics = ({+ diagnostics,+ endpoint,+ payload,+ sentAt,+}: InitializeAnthropicDiagnosticsParams): ProviderResponseDiagnostics | undefined => {+ if (!diagnostics) return;++ const providerResponse: ProviderResponseDiagnostics = {+ apiMode: 'messages',+ droppedEventCount: 0,+ endpoint,+ eventCount: 0,+ eventCounts: {},+ events: [],+ hasNonWhitespaceText: false,+ hasNonWhitespaceThinking: false,+ rawEvents: [],+ signatureChars: 0,+ terminalEventReceived: false,+ textChars: 0,+ thinkingChars: 0,+ toolInputChars: 0,+ toolUseCount: 0,+ };+ diagnostics.providerRequest = {+ apiMode: 'messages',+ endpoint,+ payload,+ sentAt,+ };+ diagnostics.providerResponse = providerResponse;+ return providerResponse;+};++export const recordAnthropicResponseMetadata = (+ diagnostics: ProviderResponseDiagnostics | undefined,+ { requestId, response }: AnthropicResponseMetadata,+) => {+ if (!diagnostics) return;++ diagnostics.responseReceivedAt = Date.now();+ diagnostics.requestId = requestId ?? undefined;+ diagnostics.status = response?.status;+ captureRawProviderResponse(diagnostics, response);++ if (!response) return;++ const headers: Record<string, string> = {};+ for (const headerName of RESPONSE_HEADER_NAMES) {+ const value = response.headers.get(headerName);+ if (value) headers[headerName] = value;+ }+ if (Object.keys(headers).length > 0) diagnostics.headers = headers;+ diagnostics.requestId ??=+ headers['request-id'] ??+ headers['anthropic-request-id'] ??+ headers['x-request-id'] ??+ headers['x-aihubmix-request-id'] ??+ headers['x-stainless-request-id'];+};++export const recordAnthropicStreamEvent = (+ diagnostics: ProviderResponseDiagnostics,+ chunk: Anthropic.MessageStreamEvent,+) => {+ appendRawProviderEvent(diagnostics, chunk);+ const event: Omit<ProviderResponseEventDiagnostics, 'index'> = { type: chunk.type };+ diagnostics.firstEventAt ??= Date.now();++ switch (chunk.type) {+ case 'message_start': {+ diagnostics.messageId = chunk.message.id;+ diagnostics.model = chunk.message.model;+ diagnostics.usage = chunk.message.usage;+ break;+ }+ case 'content_block_start': {+ event.blockIndex = chunk.index;+ event.blockType = chunk.content_block.type;+ const block = chunk.content_block;+ if (block.type === 'text') recordStringContent(diagnostics, event, block.text, 'text');+ if (block.type === 'thinking') {+ recordStringContent(diagnostics, event, block.thinking, 'thinking');+ recordStringContent(diagnostics, event, block.signature, 'signature');+ }+ if (block.type === 'redacted_thinking') {+ recordStringContent(diagnostics, event, block.data, 'signature');+ }+ if (block.type === 'tool_use' || block.type === 'server_tool_use') {+ diagnostics.toolUseCount += 1;+ diagnostics.firstNonWhitespaceOutputAt ??= Date.now();+ }+ break;+ }+ case 'content_block_delta': {+ event.blockIndex = chunk.index;+ event.deltaType = chunk.delta.type;+ if (chunk.delta.type === 'text_delta') {+ recordStringContent(diagnostics, event, chunk.delta.text, 'text');+ }+ if (chunk.delta.type === 'thinking_delta') {+ recordStringContent(diagnostics, event, chunk.delta.thinking, 'thinking');+ }+ if (chunk.delta.type === 'signature_delta') {+ recordStringContent(diagnostics, event, chunk.delta.signature, 'signature');+ }+ if (chunk.delta.type === 'input_json_delta') {+ recordStringContent(diagnostics, event, chunk.delta.partial_json, 'toolInput');+ }+ break;+ }+ case 'message_delta': {+ diagnostics.stopReason = chunk.delta.stop_reason;+ diagnostics.stopSequence = chunk.delta.stop_sequence;+ diagnostics.usage = chunk.usage;+ break;+ }+ case 'message_stop': {+ diagnostics.terminalEventReceived = true;+ break;+ }+ }++ appendEvent(diagnostics, event);+};++const observeAsyncIterable = async function* (+ stream: AsyncIterable<Anthropic.MessageStreamEvent>,+ diagnostics: ProviderResponseDiagnostics,+ signal?: AbortSignal,+) {+ try {+ for await (const chunk of stream) {+ recordAnthropicStreamEvent(diagnostics, chunk);+ yield chunk;+ }+ } catch (error) {+ recordError(diagnostics, error);+ throw error;+ } finally {+ await finalizeResponse(diagnostics, signal);+ }+};++const observeReadableStream = (+ stream: ReadableStream<Anthropic.MessageStreamEvent>,+ diagnostics: ProviderResponseDiagnostics,+ signal?: AbortSignal,+) => {+ const reader = stream.getReader();++ return new ReadableStream<Anthropic.MessageStreamEvent>({+ async cancel(reason) {+ try {+ await reader.cancel(reason);+ } catch (error) {+ recordError(diagnostics, error);+ throw error;+ } finally {+ await finalizeResponse(diagnostics, signal);+ }+ },+ async pull(controller) {+ try {+ const { done, value } = await reader.read();+ if (done) {+ await finalizeResponse(diagnostics, signal);+ controller.close();+ return;+ }++ recordAnthropicStreamEvent(diagnostics, value);+ controller.enqueue(value);+ } catch (error) {+ recordError(diagnostics, error);+ await finalizeResponse(diagnostics, signal);+ controller.error(error);+ }+ },+ });+};++export const observeAnthropicStream = (+ stream:+ AsyncIterable<Anthropic.MessageStreamEvent> | ReadableStream<Anthropic.MessageStreamEvent>,+ diagnostics: ProviderResponseDiagnostics,+ signal?: AbortSignal,+) =>+ stream instanceof ReadableStream+ ? observeReadableStream(stream, diagnostics, signal)+ : observeAsyncIterable(stream, diagnostics, signal);++export const recordAnthropicNonStreamingResponse = async (+ diagnostics: ProviderResponseDiagnostics | undefined,+ message: Anthropic.Message,+ signal?: AbortSignal,+) => {+ 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;+ await finalizeResponse(diagnostics, signal);+};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex 8225c6551f9..74d1b64a468 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { LobeOpenAICompatibleRuntime } from '../../core/BaseAI';import type { ChatStreamCallbacks, ChatStreamPayload } from '../../types/chat';import { AgentRuntimeErrorType } from '../../types/error';+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';import * as debugStreamModule from '../../utils/debugStream';import {createSignatureChannelId,@@ -130,6 +131,227 @@ describe('LobeOpenAICompatibleFactory', () => {});describe('chat', () => {+ it('should retain the exact OpenAI Chat Completions request and raw chunks', async () => {+ const rawEvents: OpenAI.Chat.Completions.ChatCompletionChunk[] = [+ {+ choices: [+ {+ delta: { content: '', role: 'assistant' },+ finish_reason: null,+ index: 0,+ logprobs: null,+ },+ ],+ created: 1_785_670_000,+ id: 'chatcmpl_empty',+ model: 'glm-5.2',+ object: 'chat.completion.chunk',+ },+ {+ choices: [+ {+ delta: {},+ finish_reason: 'stop',+ index: 0,+ logprobs: null,+ },+ ],+ created: 1_785_670_001,+ id: 'chatcmpl_empty',+ model: 'glm-5.2',+ object: 'chat.completion.chunk',+ usage: { completion_tokens: 1, prompt_tokens: 100, total_tokens: 101 },+ },+ ];+ const rawResponseBody = rawEvents+ .map((event) => `data: ${JSON.stringify(event)}\n\n`)+ .join('');+ const rawStream = {+ async *[Symbol.asyncIterator]() {+ for (const event of rawEvents) yield event;+ },+ };+ const create = vi.fn(() => ({+ withResponse: vi.fn().mockResolvedValue({+ data: rawStream,+ request_id: 'req_openai_empty',+ response: new Response(rawResponseBody, {+ headers: {+ 'cf-ray': 'ray-openai',+ 'content-type': 'text/event-stream',+ 'x-request-id': 'req-header-openai',+ },+ status: 200,+ }),+ }),+ }));+ const Runtime = createOpenAICompatibleRuntime({+ baseURL: 'https://api.test.com/v1',+ customClient: {+ createClient: () => ({ chat: { completions: { create } } }) as unknown as OpenAI,+ },+ provider: 'test-provider',+ });+ const runtime = new Runtime({ apiKey: 'test' });+ const diagnostics: ModelRuntimeDiagnostics = {};++ const response = await runtime.chat(+ {+ messages: [{ content: 'Question', role: 'user' }],+ model: 'glm-5.2',+ stream: true,+ },+ { diagnostics, user: 'user-1' },+ );+ await response.text();++ expect(diagnostics.providerRequest).toEqual(+ expect.objectContaining({+ apiMode: 'chat_completions',+ endpoint: 'https://api.***.com/v1',+ payload: expect.objectContaining({+ messages: [{ content: 'Question', role: 'user' }],+ model: 'glm-5.2',+ stream: true,+ user: 'user-1',+ }),+ sentAt: expect.any(Number),+ }),+ );+ expect(diagnostics.providerResponse).toEqual(+ expect.objectContaining({+ apiMode: 'chat_completions',+ completedAt: expect.any(Number),+ eventCount: 2,+ headers: {+ 'cf-ray': 'ray-openai',+ 'content-type': 'text/event-stream',+ 'x-request-id': 'req-header-openai',+ },+ messageId: 'chatcmpl_empty',+ model: 'glm-5.2',+ rawEvents,+ rawResponse: {+ body: rawResponseBody,+ byteLength: new TextEncoder().encode(rawResponseBody).byteLength,+ status: 'captured',+ },+ requestId: 'req_openai_empty',+ status: 200,+ stopReason: 'stop',+ terminalEventReceived: true,+ textChars: 0,+ usage: { completion_tokens: 1, prompt_tokens: 100, total_tokens: 101 },+ }),+ );+ });++ it('should retain the exact OpenAI Responses request and raw events', async () => {+ const rawEvents = [+ {+ response: {+ id: 'resp_empty',+ model: 'gpt-5.4-mini',+ status: 'in_progress',+ usage: null,+ },+ sequence_number: 0,+ type: 'response.created',+ },+ {+ response: {+ id: 'resp_empty',+ model: 'gpt-5.4-mini',+ output: [],+ status: 'completed',+ usage: { input_tokens: 100, output_tokens: 1, total_tokens: 101 },+ },+ sequence_number: 1,+ type: 'response.completed',+ },+ ] as unknown as OpenAI.Responses.ResponseStreamEvent[];+ const rawResponseBody = rawEvents+ .map((event) => `data: ${JSON.stringify(event)}\n\n`)+ .join('');+ const rawStream = {+ async *[Symbol.asyncIterator]() {+ for (const event of rawEvents) yield event;+ },+ };+ const create = vi.fn(() => ({+ withResponse: vi.fn().mockResolvedValue({+ data: rawStream,+ request_id: 'req_responses_empty',+ response: new Response(rawResponseBody, {+ headers: {+ 'content-type': 'text/event-stream',+ 'openai-request-id': 'req-responses-header',+ },+ status: 200,+ }),+ }),+ }));+ const Runtime = createOpenAICompatibleRuntime({+ baseURL: 'https://api.test.com/v1',+ chatCompletion: { useResponse: true },+ customClient: {+ createClient: () => ({ responses: { create } }) as unknown as OpenAI,+ },+ provider: 'test-provider',+ });+ const runtime = new Runtime({ apiKey: 'test' });+ const diagnostics: ModelRuntimeDiagnostics = {};++ const response = await runtime.chat(+ {+ messages: [{ content: 'Question', role: 'user' }],+ model: 'gpt-5.4-mini',+ stream: true,+ },+ { diagnostics, user: 'user-1' },+ );+ await response.text();++ expect(diagnostics.providerRequest).toEqual(+ expect.objectContaining({+ apiMode: 'responses',+ endpoint: 'https://api.***.com/v1',+ payload: expect.objectContaining({+ input: expect.any(Array),+ model: 'gpt-5.4-mini',+ safety_identifier: 'user-1',+ store: false,+ stream: true,+ }),+ sentAt: expect.any(Number),+ }),+ );+ expect(diagnostics.providerResponse).toEqual(+ expect.objectContaining({+ apiMode: 'responses',+ completedAt: expect.any(Number),+ eventCount: 2,+ headers: {+ 'content-type': 'text/event-stream',+ 'openai-request-id': 'req-responses-header',+ },+ messageId: 'resp_empty',+ model: 'gpt-5.4-mini',+ rawEvents,+ rawResponse: {+ body: rawResponseBody,+ byteLength: new TextEncoder().encode(rawResponseBody).byteLength,+ status: 'captured',+ },+ requestId: 'req_responses_empty',+ status: 200,+ stopReason: 'completed',+ terminalEventReceived: true,+ usage: { input_tokens: 100, output_tokens: 1, total_tokens: 101 },+ }),+ );+ });+it('should return a Response on successful API call', async () => {// Arrangeconst mockStream = new ReadableStream();@@ -1486,9 +1708,7 @@ describe('LobeOpenAICompatibleFactory', () => {},});- vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue({- tee: () => [mockStream, mockStream],- } as any);+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(mockStream as any);const payload: ChatStreamPayload = {messages: [{ content: 'Test', role: 'user' }],diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 11387c7e0f8..f76771f0fdc 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -73,11 +73,20 @@ import { convertOpenAIMessages, convertOpenAIResponseInputs } from '../contextBuimport { resolveModelSamplingParameters } from '../parameterResolver';import type { OpenAIStreamOptions } from '../streams';import { OpenAIResponsesStream, OpenAIStream } from '../streams';-import type { ChatPayloadForTransformStream } from '../streams/protocol';+import { type ChatPayloadForTransformStream, readableFromAsyncIterable } from '../streams/protocol';import { convertOpenAIResponseUsage, convertOpenAIUsage } from '../usageConverters/openai';import { createOpenAICompatibleImage } from './createImage';import { createOpenAICompatibleVideo, pollOpenAICompatibleVideoStatus } from './createVideo';import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';+import {+ initializeOpenAIDiagnostics,+ observeOpenAIChatCompletionStream,+ observeOpenAIResponsesStream,+ recordOpenAIChatCompletionResponse,+ recordOpenAIResponseMetadata,+ recordOpenAIResponsesResponse,+ resolveOpenAIResponseWithMetadata,+} from './providerDiagnostics';export type { PollVideoStatusResult };export * from './createVideo';@@ -721,7 +730,11 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an});const includeUsageRequested = Boolean(postPayload.stream && !chatCompletion?.excludeUsage);- let response: Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;+ let response:+ | OpenAI.ChatCompletion+ | ReadableStream<OpenAI.Chat.Completions.ChatCompletionChunk>+ | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;+ let providerResponseDiagnostics;const streamOptions: OpenAIStreamOptions = {bizErrorTypeTransformer: chatCompletion?.handleStreamBizErrorType,@@ -754,12 +767,21 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anpreferTemperature: true,}),};+ const requestPayload = this.withMappedRequestModel(customRequestPayload, payload.model);+ providerResponseDiagnostics = initializeOpenAIDiagnostics({+ apiMode: 'chat_completions',+ diagnostics: options?.diagnostics,+ endpoint: desensitizeUrl(this.baseURL),+ payload: requestPayload,+ sentAt: Date.now(),+ });response = customClient.createChatCompletionStream(this.client,- this.withMappedRequestModel(customRequestPayload, payload.model),+ requestPayload,this,) as any;+ recordOpenAIResponseMetadata(providerResponseDiagnostics, {});} else {// Remove LobeHub-internal fields before sending to downstream API.// `preserveThinking` is only consumed by Qwen/Zhipu handlePayload (which runs above)@@ -784,24 +806,58 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = andebugPayload(requestPayload);}- response = (await this.client.chat.completions.create(requestPayload, {+ providerResponseDiagnostics = initializeOpenAIDiagnostics({+ apiMode: 'chat_completions',+ diagnostics: options?.diagnostics,+ endpoint: desensitizeUrl(this.baseURL),+ payload: requestPayload,+ sentAt: Date.now(),+ });+ const responsePromise = this.client.chat.completions.create(requestPayload, {// https://github.com/lobehub/lobe-chat/pull/318headers: { Accept: '*/*', ...options?.requestHeaders },signal: options?.signal,- })) as unknown as Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;+ });+ const responseWithMetadata = await resolveOpenAIResponseWithMetadata(responsePromise);+ response = responseWithMetadata.data as+ OpenAI.ChatCompletion | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;+ recordOpenAIResponseMetadata(providerResponseDiagnostics, {+ requestId: responseWithMetadata.request_id,+ response: responseWithMetadata.response,+ });}if (postPayload.stream) {log('processing streaming response');- const [prod, useForDebug] = response.tee();+ let prod = response as+ | ReadableStream<OpenAI.Chat.Completions.ChatCompletionChunk>+ | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;if (debugParams?.chatCompletion?.()) {+ const [productionStream, useForDebug] = prod.tee();+ prod = productionStream;const useForDebugStream =useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();debugStream(useForDebugStream).catch(console.error);}+ if (providerResponseDiagnostics) {+ /** Observe provider-native chunks before the OpenAI protocol adapter transforms them. */+ const observedStream = observeOpenAIChatCompletionStream(+ prod,+ providerResponseDiagnostics,+ options?.signal,+ );+ prod =+ observedStream instanceof ReadableStream+ ? observedStream+ : readableFromAsyncIterable(observedStream, {+ model: payload.model,+ provider: this.id,+ });+ }+return StreamingResponse(chatCompletion?.handleStream? chatCompletion.handleStream(prod, {@@ -823,6 +879,12 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = andebugResponse(response);}+ await recordOpenAIChatCompletionResponse(+ providerResponseDiagnostics,+ response as OpenAI.ChatCompletion,+ options?.signal,+ );+if (responseMode === 'json') {log('returning JSON response mode');return Response.json(response);@@ -1539,6 +1601,13 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an} as ResponseCreateParamsWithPromptCacheKey;const preparedRequest = this.prepareResponsesRequest(postPayload, usageModel);const requestPayload = preparedRequest.payload;+ const providerResponseDiagnostics = initializeOpenAIDiagnostics({+ apiMode: 'responses',+ diagnostics: options?.diagnostics,+ endpoint: desensitizeUrl(this.baseURL),+ payload: requestPayload,+ sentAt: Date.now(),+ });if (debugParams?.responses?.()) {debugPayload(requestPayload);@@ -1546,13 +1615,19 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anlog('sending responses.create request');- const response = await this.client.responses.create(requestPayload, {+ const responsePromise = this.client.responses.create(requestPayload, {headers: {...options?.requestHeaders,...preparedRequest?.headers,},signal: options?.signal,});+ const responseWithMetadata = await resolveOpenAIResponseWithMetadata(responsePromise);+ const response = responseWithMetadata.data;+ recordOpenAIResponseMetadata(providerResponseDiagnostics, {+ requestId: responseWithMetadata.request_id,+ response: responseWithMetadata.response,+ });const streamOptions: OpenAIStreamOptions = {bizErrorTypeTransformer: chatCompletion?.handleStreamBizErrorType,@@ -1568,16 +1643,35 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anif (isStreaming) {log('processing streaming Responses API response');- const stream = response as Stream<OpenAI.Responses.ResponseStreamEvent>;- const [prod, useForDebug] = stream.tee();+ let prod = response as+ | ReadableStream<OpenAI.Responses.ResponseStreamEvent>+ | Stream<OpenAI.Responses.ResponseStreamEvent>;if (debugParams?.responses?.()) {+ const [productionStream, useForDebug] = prod.tee();+ prod = productionStream;const useForDebugStream =useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();debugStream(useForDebugStream).catch(console.error);}+ if (providerResponseDiagnostics) {+ /** Observe provider-native events before the Responses protocol adapter transforms them. */+ const observedStream = observeOpenAIResponsesStream(+ prod,+ providerResponseDiagnostics,+ options?.signal,+ );+ prod =+ observedStream instanceof ReadableStream+ ? observedStream+ : readableFromAsyncIterable(observedStream, {+ model: usageModel,+ provider: this.id,+ });+ }+return StreamingResponse(OpenAIResponsesStream(prod, { ...streamOptions, inputStartAt }), {headers: options?.headers,});@@ -1590,6 +1684,12 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = andebugResponse(response);}+ await recordOpenAIResponsesResponse(+ providerResponseDiagnostics,+ response as OpenAI.Responses.Response,+ options?.signal,+ );+if (responseMode === 'json') {log('returning JSON response mode');return Response.json(response);diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/providerDiagnostics.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/providerDiagnostics.tsnew file mode 100644index 00000000000..882c7d95bf2--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/providerDiagnostics.ts@@ -0,0 +1,429 @@+import type OpenAI from 'openai';++import type {+ ModelRuntimeDiagnostics,+ ProviderResponseDiagnostics,+ ProviderResponseEventDiagnostics,+} from '../../types/providerDiagnostics';+import {+ appendRawProviderEvent,+ captureRawProviderResponse,+ waitForRawProviderResponse,+} from '../providerDiagnostics';++const MAX_RECORDED_PROVIDER_EVENTS = 128;+const MAX_RECORDED_ERROR_MESSAGE_LENGTH = 500;+const RESPONSE_HEADER_NAMES = [+ 'cf-ray',+ 'content-length',+ 'content-type',+ 'date',+ 'openai-processing-ms',+ 'openai-request-id',+ 'request-id',+ 'server-timing',+ 'trace-id',+ 'x-aihubmix-request-id',+ 'x-request-id',+ 'x-stainless-request-id',+ 'x-trace-id',+] as const;++type OpenAIAPIMode = 'chat_completions' | 'responses';++interface InitializeOpenAIDiagnosticsParams {+ apiMode: OpenAIAPIMode;+ diagnostics?: ModelRuntimeDiagnostics;+ endpoint?: string;+ payload: unknown;+ sentAt: number;+}++interface OpenAIResponseMetadata {+ requestId?: string | null;+ response?: Response;+}++export interface OpenAIResponseWithMetadata<T> {+ data: T;+ request_id?: string | null;+ response?: Response;+}++type OpenAIResponsePromise<T> = PromiseLike<T> & {+ withResponse?: () => Promise<OpenAIResponseWithMetadata<T>>;+};++const appendEvent = (+ diagnostics: ProviderResponseDiagnostics,+ event: Omit<ProviderResponseEventDiagnostics, 'index'>,+) => {+ const indexedEvent = { ...event, index: diagnostics.eventCount };+ diagnostics.eventCount += 1;++ const eventKey = [event.type, event.blockType, event.deltaType].filter(Boolean).join(':');+ diagnostics.eventCounts[eventKey] = (diagnostics.eventCounts[eventKey] ?? 0) + 1;++ if (diagnostics.events.length >= MAX_RECORDED_PROVIDER_EVENTS) {+ diagnostics.events.shift();+ diagnostics.droppedEventCount += 1;+ }+ diagnostics.events.push(indexedEvent);+};++const recordStringContent = (+ diagnostics: ProviderResponseDiagnostics,+ event: Omit<ProviderResponseEventDiagnostics, 'index'>,+ content: string,+ kind: 'text' | 'thinking' | 'toolInput',+) => {+ const hasNonWhitespaceContent = content.trim().length > 0;+ event.contentLength = (event.contentLength ?? 0) + content.length;+ event.hasNonWhitespaceContent ||= hasNonWhitespaceContent;++ if (kind === 'text') {+ diagnostics.textChars += content.length;+ diagnostics.hasNonWhitespaceText ||= hasNonWhitespaceContent;+ }+ if (kind === 'thinking') {+ diagnostics.thinkingChars += content.length;+ diagnostics.hasNonWhitespaceThinking ||= hasNonWhitespaceContent;+ }+ if (kind === 'toolInput') diagnostics.toolInputChars += content.length;++ if (hasNonWhitespaceContent && diagnostics.firstNonWhitespaceOutputAt === undefined) {+ diagnostics.firstNonWhitespaceOutputAt = Date.now();+ }+};++const recordError = (diagnostics: ProviderResponseDiagnostics, error: unknown) => {+ diagnostics.error = {+ message:+ error instanceof Error+ ? error.message.slice(0, MAX_RECORDED_ERROR_MESSAGE_LENGTH)+ : undefined,+ name: error instanceof Error ? error.name : undefined,+ };+};++const finalizeResponse = async (diagnostics: ProviderResponseDiagnostics, signal?: AbortSignal) => {+ await waitForRawProviderResponse(diagnostics);+ diagnostics.aborted = signal?.aborted || undefined;+ diagnostics.completedAt ??= Date.now();+};++const getString = (value: unknown) => (typeof value === 'string' ? value : undefined);++const recordResponseIdentity = (+ diagnostics: ProviderResponseDiagnostics,+ response: Record<string, unknown> | undefined,+) => {+ if (!response) return;++ diagnostics.messageId ??= getString(response.id);+ diagnostics.model ??= getString(response.model);+ diagnostics.stopReason ??= getString(response.status);+ if (response.usage !== undefined) diagnostics.usage = response.usage;+};++export const initializeOpenAIDiagnostics = ({+ apiMode,+ diagnostics,+ endpoint,+ payload,+ sentAt,+}: InitializeOpenAIDiagnosticsParams): ProviderResponseDiagnostics | undefined => {+ if (!diagnostics) return;++ const providerResponse: ProviderResponseDiagnostics = {+ apiMode,+ droppedEventCount: 0,+ endpoint,+ eventCount: 0,+ eventCounts: {},+ events: [],+ hasNonWhitespaceText: false,+ hasNonWhitespaceThinking: false,+ rawEvents: [],+ signatureChars: 0,+ terminalEventReceived: false,+ textChars: 0,+ thinkingChars: 0,+ toolInputChars: 0,+ toolUseCount: 0,+ };+ diagnostics.providerRequest = { apiMode, endpoint, payload, sentAt };+ diagnostics.providerResponse = providerResponse;++ return providerResponse;+};++export const resolveOpenAIResponseWithMetadata = async <T>(+ responsePromise: OpenAIResponsePromise<T>,+): Promise<OpenAIResponseWithMetadata<T>> =>+ typeof responsePromise.withResponse === 'function'+ ? responsePromise.withResponse()+ : { data: await responsePromise };++export const recordOpenAIResponseMetadata = (+ diagnostics: ProviderResponseDiagnostics | undefined,+ { requestId, response }: OpenAIResponseMetadata,+) => {+ if (!diagnostics) return;++ diagnostics.responseReceivedAt = Date.now();+ diagnostics.requestId = requestId ?? undefined;+ diagnostics.status = response?.status;+ captureRawProviderResponse(diagnostics, response);++ if (!response) return;++ const headers: Record<string, string> = {};+ for (const headerName of RESPONSE_HEADER_NAMES) {+ const value = response.headers.get(headerName);+ if (value) headers[headerName] = value;+ }+ if (Object.keys(headers).length > 0) diagnostics.headers = headers;+ diagnostics.requestId ??=+ headers['openai-request-id'] ??+ headers['request-id'] ??+ headers['x-request-id'] ??+ headers['x-aihubmix-request-id'] ??+ headers['x-stainless-request-id'];+};++export const recordOpenAIChatCompletionChunk = (+ diagnostics: ProviderResponseDiagnostics,+ chunk: OpenAI.Chat.Completions.ChatCompletionChunk,+) => {+ appendRawProviderEvent(diagnostics, chunk);+ diagnostics.firstEventAt ??= Date.now();+ diagnostics.messageId ??= chunk.id;+ diagnostics.model ??= chunk.model;+ if (chunk.usage) diagnostics.usage = chunk.usage;++ const event: Omit<ProviderResponseEventDiagnostics, 'index'> = {+ type: chunk.object || 'chat.completion.chunk',+ };++ for (const choice of chunk.choices) {+ const delta = choice.delta as typeof choice.delta & {+ reasoning?: string;+ reasoning_content?: string;+ };++ if (typeof delta.content === 'string') {+ recordStringContent(diagnostics, event, delta.content, 'text');+ }++ const reasoning = delta.reasoning_content ?? delta.reasoning;+ if (typeof reasoning === 'string') {+ recordStringContent(diagnostics, event, reasoning, 'thinking');+ }++ for (const toolCall of delta.tool_calls ?? []) {+ if (toolCall.id || toolCall.function?.name) {+ diagnostics.toolUseCount += 1;+ diagnostics.firstNonWhitespaceOutputAt ??= Date.now();+ }+ if (typeof toolCall.function?.arguments === 'string') {+ recordStringContent(diagnostics, event, toolCall.function.arguments, 'toolInput');+ }+ }++ if (choice.finish_reason) {+ diagnostics.stopReason = choice.finish_reason;+ diagnostics.terminalEventReceived = true;+ }+ }++ appendEvent(diagnostics, event);+};++export const recordOpenAIResponseStreamEvent = (+ diagnostics: ProviderResponseDiagnostics,+ chunk: OpenAI.Responses.ResponseStreamEvent,+) => {+ appendRawProviderEvent(diagnostics, chunk);+ diagnostics.firstEventAt ??= Date.now();++ const rawChunk = chunk as unknown as Record<string, unknown>;+ const type = getString(rawChunk.type) ?? 'unknown';+ const event: Omit<ProviderResponseEventDiagnostics, 'index'> = { type };+ const response =+ rawChunk.response && typeof rawChunk.response === 'object'+ ? (rawChunk.response as Record<string, unknown>)+ : undefined;+ recordResponseIdentity(diagnostics, response);++ if (type === 'response.output_text.delta' || type === 'response.output_text.done') {+ const content = getString(type.endsWith('.delta') ? rawChunk.delta : rawChunk.text);+ if (content) recordStringContent(diagnostics, event, content, 'text');+ }++ if (+ type === 'response.reasoning_summary_text.delta' ||+ type === 'response.reasoning_text.delta'+ ) {+ const content = getString(rawChunk.delta);+ if (content) recordStringContent(diagnostics, event, content, 'thinking');+ }++ if (type === 'response.output_item.added') {+ const item =+ rawChunk.item && typeof rawChunk.item === 'object'+ ? (rawChunk.item as Record<string, unknown>)+ : undefined;+ if (item?.type === 'function_call') {+ diagnostics.toolUseCount += 1;+ diagnostics.firstNonWhitespaceOutputAt ??= Date.now();+ }+ }++ if (type === 'response.function_call_arguments.delta') {+ const content = getString(rawChunk.delta);+ if (content) recordStringContent(diagnostics, event, content, 'toolInput');+ }++ if (+ type === 'response.completed' ||+ type === 'response.failed' ||+ type === 'response.incomplete'+ ) {+ diagnostics.stopReason = getString(response?.status) ?? type.slice('response.'.length);+ diagnostics.terminalEventReceived = true;+ }++ appendEvent(diagnostics, event);+};++const observeAsyncIterable = async function* <T>(+ stream: AsyncIterable<T>,+ diagnostics: ProviderResponseDiagnostics,+ recordEvent: (diagnostics: ProviderResponseDiagnostics, event: T) => void,+ signal?: AbortSignal,+) {+ try {+ for await (const chunk of stream) {+ recordEvent(diagnostics, chunk);+ yield chunk;+ }+ } catch (error) {+ recordError(diagnostics, error);+ throw error;+ } finally {+ await finalizeResponse(diagnostics, signal);+ }+};++const observeReadableStream = <T>(+ stream: ReadableStream<T>,+ diagnostics: ProviderResponseDiagnostics,+ recordEvent: (diagnostics: ProviderResponseDiagnostics, event: T) => void,+ signal?: AbortSignal,+) => {+ const reader = stream.getReader();++ return new ReadableStream<T>({+ async cancel(reason) {+ await reader.cancel(reason);+ await finalizeResponse(diagnostics, signal);+ },+ async pull(controller) {+ try {+ const { done, value } = await reader.read();+ if (done) {+ await finalizeResponse(diagnostics, signal);+ controller.close();+ return;+ }++ recordEvent(diagnostics, value);+ controller.enqueue(value);+ } catch (error) {+ recordError(diagnostics, error);+ await finalizeResponse(diagnostics, signal);+ controller.error(error);+ }+ },+ });+};++export const observeOpenAIChatCompletionStream = (+ stream:+ | AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>+ | ReadableStream<OpenAI.Chat.Completions.ChatCompletionChunk>,+ diagnostics: ProviderResponseDiagnostics,+ signal?: AbortSignal,+) =>+ stream instanceof ReadableStream+ ? observeReadableStream(stream, diagnostics, recordOpenAIChatCompletionChunk, signal)+ : observeAsyncIterable(stream, diagnostics, recordOpenAIChatCompletionChunk, signal);++export const observeOpenAIResponsesStream = (+ stream:+ | AsyncIterable<OpenAI.Responses.ResponseStreamEvent>+ | ReadableStream<OpenAI.Responses.ResponseStreamEvent>,+ diagnostics: ProviderResponseDiagnostics,+ signal?: AbortSignal,+) =>+ stream instanceof ReadableStream+ ? observeReadableStream(stream, diagnostics, recordOpenAIResponseStreamEvent, signal)+ : observeAsyncIterable(stream, diagnostics, recordOpenAIResponseStreamEvent, signal);++export const recordOpenAIChatCompletionResponse = async (+ diagnostics: ProviderResponseDiagnostics | undefined,+ completion: OpenAI.ChatCompletion,+ signal?: AbortSignal,+) => {+ if (!diagnostics) return;++ appendRawProviderEvent(diagnostics, completion);+ diagnostics.firstEventAt ??= Date.now();+ diagnostics.messageId = completion.id;+ diagnostics.model = completion.model;+ diagnostics.usage = completion.usage;++ const event: Omit<ProviderResponseEventDiagnostics, 'index'> = {+ type: completion.object,+ };+ for (const choice of completion.choices) {+ const message = choice.message as typeof choice.message & {+ reasoning?: string;+ reasoning_content?: string;+ };+ if (typeof message.content === 'string') {+ recordStringContent(diagnostics, event, message.content, 'text');+ }+ const reasoning = message.reasoning_content ?? message.reasoning;+ if (typeof reasoning === 'string') {+ recordStringContent(diagnostics, event, reasoning, 'thinking');+ }+ for (const toolCall of message.tool_calls ?? []) {+ diagnostics.toolUseCount += 1;+ diagnostics.firstNonWhitespaceOutputAt ??= Date.now();+ if (toolCall.type === 'function') {+ recordStringContent(diagnostics, event, toolCall.function.arguments, 'toolInput');+ }+ }+ if (choice.finish_reason) diagnostics.stopReason = choice.finish_reason;+ }+ appendEvent(diagnostics, event);+ diagnostics.terminalEventReceived = true;+ await finalizeResponse(diagnostics, signal);+};++export const recordOpenAIResponsesResponse = async (+ diagnostics: ProviderResponseDiagnostics | undefined,+ response: OpenAI.Responses.Response,+ signal?: AbortSignal,+) => {+ if (!diagnostics) return;++ appendRawProviderEvent(diagnostics, response);+ diagnostics.firstEventAt ??= Date.now();+ recordResponseIdentity(diagnostics, response as unknown as Record<string, unknown>);+ diagnostics.terminalEventReceived = true;+ appendEvent(diagnostics, { type: `response.${response.status}` });+ await finalizeResponse(diagnostics, signal);+};diff --git a/packages/model-runtime/src/core/providerDiagnostics.ts b/packages/model-runtime/src/core/providerDiagnostics.tsnew file mode 100644index 00000000000..ffa1bb51290--- /dev/null+++ b/packages/model-runtime/src/core/providerDiagnostics.ts@@ -0,0 +1,153 @@+import type { ProviderResponseDiagnostics } from '../types/providerDiagnostics';++const MAX_RECORDED_ERROR_MESSAGE_LENGTH = 500;+const MAX_RECORDED_RAW_EVENT_BYTES = 256 * 1024;+const MAX_RECORDED_RAW_EVENTS = 128;+const MAX_RECORDED_RAW_RESPONSE_BYTES = 256 * 1024;+const rawResponseCaptureTasks = new WeakMap<ProviderResponseDiagnostics, Promise<void>>();++/**+ * Provider SDK events originate from JSON but compatible clients may attach+ * BigInt values or circular references. Normalize each event at the provider+ * boundary so a diagnostic record can never make Redis serialization fail.+ */+const serializeProviderEvent = (value: unknown): { byteLength: number; value: unknown } => {+ const seen = new WeakSet<object>();++ try {+ const serializedValue = JSON.stringify(value, (_key, item) => {+ if (typeof item === 'bigint') return item.toString();+ if (typeof item === 'object' && item !== null) {+ if (seen.has(item)) return '[Circular]';+ seen.add(item);+ }++ return item;+ });+ const serialized = serializedValue ?? JSON.stringify(String(value));++ return {+ byteLength: new TextEncoder().encode(serialized).byteLength,+ value: JSON.parse(serialized),+ };+ } catch (error) {+ const fallback = {+ serializationError: (error instanceof Error ? error.message : String(error)).slice(+ 0,+ MAX_RECORDED_ERROR_MESSAGE_LENGTH,+ ),+ };+ const serialized = JSON.stringify(fallback);+ return { byteLength: new TextEncoder().encode(serialized).byteLength, value: fallback };+ }+};++export const appendRawProviderEvent = (+ diagnostics: ProviderResponseDiagnostics,+ event: unknown,+) => {+ const serializedEvent = serializeProviderEvent(event);+ const recordedByteLength = diagnostics.rawEventByteLength ?? 0;+ if (+ diagnostics.rawEvents.length >= MAX_RECORDED_RAW_EVENTS ||+ recordedByteLength + serializedEvent.byteLength > MAX_RECORDED_RAW_EVENT_BYTES+ ) {+ diagnostics.droppedRawEventCount = (diagnostics.droppedRawEventCount ?? 0) + 1;+ return;+ }++ diagnostics.rawEvents.push(serializedEvent.value);+ diagnostics.rawEventByteLength = recordedByteLength + serializedEvent.byteLength;+};++/** Read only a bounded prefix so diagnostic capture cannot buffer an unbounded clone. */+const readRawResponseBody = async (response: Response) => {+ const reader = response.body!.getReader();+ const chunks: Uint8Array[] = [];+ let byteLength = 0;+ let truncated = false;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ const remainingBytes = MAX_RECORDED_RAW_RESPONSE_BYTES - byteLength;+ if (value.byteLength > remainingBytes) {+ if (remainingBytes > 0) chunks.push(value.subarray(0, remainingBytes));+ byteLength += remainingBytes;+ truncated = true;+ await reader.cancel();+ break;+ }++ chunks.push(value);+ byteLength += value.byteLength;+ }++ const bodyBytes = new Uint8Array(byteLength);+ let offset = 0;+ for (const chunk of chunks) {+ bodyBytes.set(chunk, offset);+ offset += chunk.byteLength;+ }++ return {+ body: new TextDecoder().decode(bodyBytes),+ byteLength,+ status: 'captured' as const,+ truncated: truncated || undefined,+ };+};++/**+ * Clone the Fetch response before the provider SDK starts consuming its body.+ * The clone preserves the original SSE/JSON payload while the SDK-owned branch+ * continues normally. Custom clients without a Fetch response still retain+ * their provider-native parsed events and are marked unavailable here.+ */+export const captureRawProviderResponse = (+ diagnostics: ProviderResponseDiagnostics | undefined,+ response?: Response,+) => {+ if (!diagnostics) return;++ if (!response?.body || response.bodyUsed) {+ diagnostics.rawResponse = { status: 'unavailable' };+ return;+ }++ try {+ const responseClone = response.clone();+ const captureTask = readRawResponseBody(responseClone)+ .then((rawResponse) => {+ diagnostics.rawResponse = rawResponse;+ })+ .catch((error) => {+ diagnostics.rawResponse = {+ captureError:+ error instanceof Error+ ? error.message.slice(0, MAX_RECORDED_ERROR_MESSAGE_LENGTH)+ : String(error).slice(0, MAX_RECORDED_ERROR_MESSAGE_LENGTH),+ status: 'failed',+ };+ });+ rawResponseCaptureTasks.set(diagnostics, captureTask);+ } catch (error) {+ diagnostics.rawResponse = {+ captureError:+ error instanceof Error+ ? error.message.slice(0, MAX_RECORDED_ERROR_MESSAGE_LENGTH)+ : String(error).slice(0, MAX_RECORDED_ERROR_MESSAGE_LENGTH),+ status: 'failed',+ };+ }+};++export const waitForRawProviderResponse = async (+ diagnostics: ProviderResponseDiagnostics | undefined,+) => {+ if (!diagnostics) return;++ await rawResponseCaptureTasks.get(diagnostics);+ rawResponseCaptureTasks.delete(diagnostics);+};diff --git a/packages/model-runtime/src/providers/azureOpenai/index.test.ts b/packages/model-runtime/src/providers/azureOpenai/index.test.tsindex 2980d1f36ca..89eaed75af3 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.test.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.test.ts@@ -77,8 +77,7 @@ describe('LobeAzureOpenAI', () => {describe('streaming response', () => {it('should use responses API and append web_search tool when enabledSearch is true', async () => {- const mockProdStream = new ReadableStream() as any;- const mockDebugStream = new ReadableStream() as any;+ const mockStream = new ReadableStream() as any;const mockPricing = { units: [] };instance = new LobeAzureOpenAI({@@ -90,9 +89,7 @@ describe('LobeAzureOpenAI', () => {vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(new ReadableStream() as any,);- vi.spyOn(instance['client'].responses, 'create').mockResolvedValue({- tee: () => [mockProdStream, mockDebugStream],- } as any);+ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockStream);vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());@@ -122,7 +119,7 @@ describe('LobeAzureOpenAI', () => {);expect(streamsModule.OpenAIResponsesStream).toHaveBeenCalledWith(- mockProdStream,+ mockStream,expect.objectContaining({inputStartAt: expect.any(Number),payload: expect.objectContaining({@@ -136,12 +133,9 @@ describe('LobeAzureOpenAI', () => {});it('should preserve GPT-5.6 Pro mode and Max effort in Responses payloads', async () => {- const mockProdStream = new ReadableStream() as any;- const mockDebugStream = new ReadableStream() as any;+ const mockStream = new ReadableStream() as any;- vi.spyOn(instance['client'].responses, 'create').mockResolvedValue({- tee: () => [mockProdStream, mockDebugStream],- } as any);+ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockStream);vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(undefined);vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());@@ -163,8 +157,7 @@ describe('LobeAzureOpenAI', () => {});it('should use deploymentName for Azure Responses API requests while keeping logical model for pricing', async () => {- const mockProdStream = new ReadableStream() as any;- const mockDebugStream = new ReadableStream() as any;+ const mockStream = new ReadableStream() as any;const mockPricing = { units: [] };instance = new LobeAzureOpenAI({@@ -176,9 +169,7 @@ describe('LobeAzureOpenAI', () => {vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(new ReadableStream() as any,);- vi.spyOn(instance['client'].responses, 'create').mockResolvedValue({- tee: () => [mockProdStream, mockDebugStream],- } as any);+ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockStream);vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());@@ -198,7 +189,7 @@ describe('LobeAzureOpenAI', () => {expect(createCall.deploymentName).toBeUndefined();expect(streamsModule.OpenAIResponsesStream).toHaveBeenCalledWith(- mockProdStream,+ mockStream,expect.objectContaining({payload: expect.objectContaining({apiMode: 'responses',@@ -211,8 +202,7 @@ describe('LobeAzureOpenAI', () => {});it('should strip unsupported params for Azure reasoning models and include usage in stream options', async () => {- const mockProdStream = new ReadableStream() as any;- const mockDebugStream = new ReadableStream() as any;+ const mockStream = new ReadableStream() as any;const mockPricing = { units: [] };instance = new LobeAzureOpenAI({@@ -221,9 +211,7 @@ describe('LobeAzureOpenAI', () => {id: 'lobehub',});- vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue({- tee: () => [mockProdStream, mockDebugStream],- } as any);+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(mockStream);vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);vi.spyOn(streamsModule, 'OpenAIStream').mockReturnValue(new ReadableStream());@@ -262,7 +250,7 @@ describe('LobeAzureOpenAI', () => {undefined,);expect(streamsModule.OpenAIStream).toHaveBeenCalledWith(- mockProdStream,+ mockStream,expect.objectContaining({inputStartAt: expect.any(Number),payload: expect.objectContaining({@@ -277,11 +265,8 @@ describe('LobeAzureOpenAI', () => {});it('should handle multiple data chunks correctly', async () => {- const mockProdStream = new ReadableStream() as any;- const mockDebugStream = new ReadableStream() as any;- vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue({- tee: () => [mockProdStream, mockDebugStream],- } as any);+ const mockStream = new ReadableStream() as any;+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(mockStream);vi.spyOn(streamsModule, 'OpenAIStream').mockReturnValue(new ReadableStream({start(controller) {@@ -304,7 +289,7 @@ describe('LobeAzureOpenAI', () => {expect(result).toBeInstanceOf(Response);expect(streamsModule.OpenAIStream).toHaveBeenCalledWith(- mockProdStream,+ mockStream,expect.objectContaining({inputStartAt: expect.any(Number),payload: expect.objectContaining({diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex 37c51692115..a56f07d4f33 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -6,6 +6,7 @@ import type {} from '@lobechat/types';import type { ModelPricingContext } from './pricing';+import type { ModelRuntimeDiagnostics } from './providerDiagnostics';import type { MessageToolCall, MessageToolCallChunk } from './toolsCalling';export type LLMRoleType = 'user' | 'system' | 'assistant' | 'function' | 'tool';@@ -195,6 +196,12 @@ export interface ChatStreamPayload {export interface ChatMethodOptions {callback?: ChatStreamCallbacks;+ /**+ * Request-scoped provider-boundary evidence retained by the caller.+ * Keep this separate from metadata because routing hooks may retain metadata+ * after the provider returns, while diagnostics can contain a large payload.+ */+ diagnostics?: ModelRuntimeDiagnostics;/*** response headers*/diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.tsindex cd2bebf3151..71d70810063 100644--- a/packages/model-runtime/src/types/index.ts+++ b/packages/model-runtime/src/types/index.ts@@ -5,6 +5,7 @@ export * from './error';export * from './image';export * from './model';export * from './pricing';+export * from './providerDiagnostics';export * from './structureOutput';export * from './toolsCalling';export * from './tts';diff --git a/packages/model-runtime/src/types/providerDiagnostics.ts b/packages/model-runtime/src/types/providerDiagnostics.tsnew file mode 100644index 00000000000..6f8bb039bed--- /dev/null+++ b/packages/model-runtime/src/types/providerDiagnostics.ts@@ -0,0 +1,74 @@+export interface ProviderRequestDiagnostics {+ apiMode: string;+ endpoint?: string;+ payload: unknown;+ sentAt: number;+}++export interface ProviderResponseEventDiagnostics {+ blockIndex?: number;+ blockType?: string;+ contentLength?: number;+ deltaType?: string;+ hasNonWhitespaceContent?: boolean;+ index: number;+ signatureLength?: number;+ type: string;+}++export interface ProviderRawResponseDiagnostics {+ body?: string;+ /** Number of raw response bytes retained in body. */+ byteLength?: number;+ captureError?: string;+ status: 'captured' | 'failed' | 'unavailable';+ /** The provider response exceeded the diagnostic capture budget. */+ truncated?: boolean;+}++export interface ProviderResponseDiagnostics {+ aborted?: boolean;+ apiMode: string;+ completedAt?: number;+ droppedEventCount: number;+ /** Provider-native events omitted after reaching the count or byte budget. */+ droppedRawEventCount?: number;+ endpoint?: string;+ error?: {+ message?: string;+ name?: string;+ };+ eventCount: number;+ eventCounts: Record<string, number>;+ events: ProviderResponseEventDiagnostics[];+ firstEventAt?: number;+ firstNonWhitespaceOutputAt?: number;+ hasNonWhitespaceText: boolean;+ hasNonWhitespaceThinking: boolean;+ headers?: Record<string, string>;+ messageId?: string;+ model?: string;+ /** Serialized bytes retained across rawEvents, excluding JSON array delimiters. */+ rawEventByteLength?: number;+ /** Provider-native SDK events captured before LobeHub protocol transformation. */+ rawEvents: unknown[];+ /** Raw HTTP response body captured before the provider SDK consumes the stream. */+ rawResponse?: ProviderRawResponseDiagnostics;+ requestId?: string;+ responseReceivedAt?: number;+ signatureChars: number;+ status?: number;+ stopReason?: string | null;+ stopSequence?: string | null;+ terminalEventReceived: boolean;+ textChars: number;+ thinkingChars: number;+ toolInputChars: number;+ toolUseCount: number;+ usage?: unknown;+}++export interface ModelRuntimeDiagnostics {+ providerRequest?: ProviderRequestDiagnostics;+ providerResponse?: ProviderResponseDiagnostics;+}