🤯 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: treat Anthropic streams closed early as interrupted (#20984)
YuTengjinge5d94b1c0218
diff --git a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts b/apps/server/src/services/toolExecution/__tests__/builtin.test.tsindex ad61cca57eb..cacd64bc380 100644--- a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/builtin.test.ts@@ -124,7 +124,11 @@ describe('BuiltinToolsExecutor truncated arguments', () => {expect(result.success).toBe(false);expect(result.error?.code).toBe('TRUNCATED_ARGUMENTS');expect(result.content).toMatch(/truncated/i);- expect(result.content).toMatch(/max_tokens/);+ // Both causes are listed and neither is asserted: blaming max_tokens made+ // models tell users the platform caps output when the stream was cut.+ expect(result.content).toMatch(/output length limit/);+ expect(result.content).toMatch(/stream was interrupted/);+ expect(result.content).not.toMatch(/max_tokens/);// The raw truncated payload is echoed back so the model sees exactly what// it produced and cannot blame upstream for a different payload.expect(result.content).toContain(truncated);diff --git a/apps/server/src/services/toolExecution/builtin.ts b/apps/server/src/services/toolExecution/builtin.tsindex 0c0b21e2f67..f34765a5c34 100644--- a/apps/server/src/services/toolExecution/builtin.ts+++ b/apps/server/src/services/toolExecution/builtin.ts@@ -149,20 +149,26 @@ export class BuiltinToolsExecutor implements IToolExecutor {// When JSON.parse fails, return a dedicated error rather than silently// falling back to `{}`. Passing `{}` to the tool produced generic// "required field missing" errors, which led the model to retry with the- // same broken payload. Distinguish a truncated payload (typical when- // max_tokens is exhausted mid-tool-call) from plain malformed JSON, and- // echo the raw arguments string so the model can verify it is exactly- // what it produced.+ // same broken payload. Distinguish a truncated payload from plain+ // malformed JSON, and echo the raw arguments string so the model can+ // verify it is exactly what it produced.+ //+ // The truncation cause is unknown at this point: an exhausted output+ // budget and an upstream that closed the stream early look identical.+ // Naming max_tokens made models tell users the platform caps output and+ // that they should raise a setting, which was wrong for interrupted streams+ // (LOBE-14901), so the message lists both causes and asks the model not to+ // assert either one.if (parsed === undefined && argsStr?.trim()) {const truncationReason = detectTruncatedJSON(argsStr);const explanation = truncationReason? `The tool call arguments JSON appears to be truncated (${truncationReason}), ` +- `likely because the model's max_tokens budget was exhausted ` +- `(possibly by extended-thinking tokens). ` +- `Either reduce the size of the content you are about to write, ` +- `or ask the user to increase the model's max_tokens ` +- `(and/or disable extended thinking or set a separate thinking budget). ` +- `Do not retry with the same payload.`+ `so the tool was not invoked. The output was cut off before the call was complete, ` ++ `either because the output length limit was reached or because the response stream ` ++ `was interrupted; the cause cannot be determined here, so do not tell the user it ` ++ `was a specific limit or setting. ` ++ `If the arguments carry large content, split it into smaller pieces across several calls. ` ++ `Do not resend the same truncated arguments.`: `The tool call arguments string is not valid JSON and could not be parsed, ` +`so the tool was not invoked. Fix the JSON syntax and try again.`;const content = `${explanation}\n\nThe received arguments string was:\n${argsStr}`;diff --git a/packages/model-runtime/src/core/streams/anthropic.interruption.test.ts b/packages/model-runtime/src/core/streams/anthropic.interruption.test.tsnew file mode 100644index 00000000000..ed1889109e2--- /dev/null+++ b/packages/model-runtime/src/core/streams/anthropic.interruption.test.ts@@ -0,0 +1,139 @@+import type { Stream } from '@anthropic-ai/sdk/streaming';+import { describe, expect, it, vi } from 'vitest';++import { AnthropicStream } from './anthropic';++describe('AnthropicStream interruptions', () => {+ it('should report a stream closed without message_delta / message_stop as interrupted', async () => {+ // A relay closed the connection mid tool call: no `message_delta`, no `message_stop`.+ const mockReadableStream = new ReadableStream({+ start(controller) {+ controller.enqueue({+ type: 'message_start',+ message: { id: 'msg_1', usage: { input_tokens: 10, output_tokens: 1 } },+ });+ controller.enqueue({+ type: 'content_block_start',+ index: 0,+ content_block: { type: 'tool_use', id: 'toolu_1', name: 'writeFile', input: {} },+ });+ controller.enqueue({+ type: 'content_block_delta',+ index: 0,+ delta: { type: 'input_json_delta', partial_json: '{"content":"Inizia il ' },+ });+ controller.close();+ },+ });++ const onErrorMock = vi.fn();+ const onCompletionMock = vi.fn();+ const protocolStream = AnthropicStream(mockReadableStream, {+ callbacks: { onCompletion: onCompletionMock, onError: onErrorMock },+ });++ const decoder = new TextDecoder();+ const chunks: string[] = [];+ // @ts-ignore+ for await (const chunk of protocolStream) {+ chunks.push(decoder.decode(chunk, { stream: true }));+ }++ expect(chunks.slice(-3)).toEqual([+ 'id: msg_1\n',+ 'event: error\n',+ expect.stringContaining('"type":"StreamChunkError"'),+ ]);+ expect(onErrorMock).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'Stream ended unexpectedly', type: 'StreamChunkError' }),+ );+ expect(onCompletionMock.mock.calls[0]?.[0].error).toMatchObject({ type: 'StreamChunkError' });+ });+ it('should report a dropped connection as a stream error instead of ending normally', async () => {+ // @ts-ignore+ const mockAnthropicStream: Stream = {+ [Symbol.asyncIterator]() {+ let count = 0;+ return {+ next: async () => {+ if (count++ === 0) {+ return {+ done: false,+ value: { type: 'message_start', message: { id: 'message_1', usage: {} } },+ };+ }+ throw new TypeError('terminated');+ },+ };+ },+ };++ const onErrorMock = vi.fn();+ const onFinalMock = vi.fn();+ const protocolStream = AnthropicStream(mockAnthropicStream, {+ callbacks: { onError: onErrorMock, onFinal: onFinalMock },+ payload: { apiMode: 'messages', model: 'deepseek-flash', provider: 'deepseek' },+ });++ const decoder = new TextDecoder();+ const chunks: string[] = [];+ // @ts-ignore+ for await (const chunk of protocolStream) {+ chunks.push(decoder.decode(chunk, { stream: true }));+ }++ expect(chunks).toContain('event: error\n');+ expect(onErrorMock).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'terminated', type: 'ProviderBizError' }),+ );+ expect(onFinalMock).toHaveBeenCalledWith(+ expect.objectContaining({ error: expect.objectContaining({ message: 'terminated' }) }),+ );+ });++ describe('relay-shaped failures', () => {+ const collect = async (events: any[]) => {+ const onCompletion = vi.fn();+ const stream = new ReadableStream({+ start(controller) {+ for (const event of events) controller.enqueue(event);+ controller.close();+ },+ });+ const chunks: string[] = [];+ const reader = AnthropicStream(stream, { callbacks: { onCompletion } }).getReader();+ const decoder = new TextDecoder();+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ chunks.push(decoder.decode(value, { stream: true }));+ }+ return { chunks, completion: onCompletion.mock.calls[0]?.[0] };+ };++ it('surfaces an inline error event instead of an empty completion', async () => {+ const { chunks, completion } = await collect([+ {+ message: { id: 'msg_1', usage: { input_tokens: 100, output_tokens: 1 } },+ type: 'message_start',+ },+ { error: { message: 'Overloaded', type: 'overloaded_error' }, type: 'error' },+ ]);++ expect(chunks.some((c) => c.includes('event: error'))).toBe(true);+ expect(completion.error).toMatchObject({ message: 'Overloaded' });+ });++ it('names an OpenAI-format answer on an Anthropic endpoint as a malformed response', async () => {+ const { completion } = await collect([+ {+ choices: [{ delta: { content: 'Hello' }, finish_reason: null, index: 0 }],+ id: 'chatcmpl_1',+ object: 'chat.completion.chunk',+ },+ ]);++ expect(completion.error).toMatchObject({ type: 'UpstreamMalformedResponse' });+ });+ });+});diff --git a/packages/model-runtime/src/core/streams/anthropic.test.ts b/packages/model-runtime/src/core/streams/anthropic.test.tsindex fb861b69771..5f6cbcda0d7 100644--- a/packages/model-runtime/src/core/streams/anthropic.test.ts+++ b/packages/model-runtime/src/core/streams/anthropic.test.ts@@ -873,6 +873,7 @@ describe('AnthropicStream', () => {index: 0,delta: { type: 'abc', abc: '123' },},+ { type: 'message_stop' },];const mockReadableStream = new ReadableStream({@@ -914,94 +915,10 @@ describe('AnthropicStream', () => {'id: msg_01MNsLe7n1uVLtu6W8rCFujD','event: data','data: {"type":"content_block_delta","index":0,"delta":{"type":"abc","abc":"123"}}\n',+ 'id: msg_01MNsLe7n1uVLtu6W8rCFujD',+ 'event: stop',+ 'data: "message_stop"\n',].map((item) => `${item}\n`),);});- it('should report a dropped connection as a stream error instead of ending normally', async () => {- // @ts-ignore- const mockAnthropicStream: Stream = {- [Symbol.asyncIterator]() {- let count = 0;- return {- next: async () => {- if (count++ === 0) {- return {- done: false,- value: { type: 'message_start', message: { id: 'message_1', usage: {} } },- };- }- throw new TypeError('terminated');- },- };- },- };-- const onErrorMock = vi.fn();- const onFinalMock = vi.fn();- const protocolStream = AnthropicStream(mockAnthropicStream, {- callbacks: { onError: onErrorMock, onFinal: onFinalMock },- payload: { apiMode: 'messages', model: 'deepseek-flash', provider: 'deepseek' },- });-- const decoder = new TextDecoder();- const chunks: string[] = [];- // @ts-ignore- for await (const chunk of protocolStream) {- chunks.push(decoder.decode(chunk, { stream: true }));- }-- expect(chunks).toContain('event: error\n');- expect(onErrorMock).toHaveBeenCalledWith(- expect.objectContaining({ message: 'terminated', type: 'ProviderBizError' }),- );- expect(onFinalMock).toHaveBeenCalledWith(- expect.objectContaining({ error: expect.objectContaining({ message: 'terminated' }) }),- );- });-- describe('relay-shaped failures', () => {- const collect = async (events: any[]) => {- const onCompletion = vi.fn();- const stream = new ReadableStream({- start(controller) {- for (const event of events) controller.enqueue(event);- controller.close();- },- });- const chunks: string[] = [];- const reader = AnthropicStream(stream, { callbacks: { onCompletion } }).getReader();- const decoder = new TextDecoder();- for (;;) {- const { done, value } = await reader.read();- if (done) break;- chunks.push(decoder.decode(value, { stream: true }));- }- return { chunks, completion: onCompletion.mock.calls[0]?.[0] };- };-- it('surfaces an inline error event instead of an empty completion', async () => {- const { chunks, completion } = await collect([- {- message: { id: 'msg_1', usage: { input_tokens: 100, output_tokens: 1 } },- type: 'message_start',- },- { error: { message: 'Overloaded', type: 'overloaded_error' }, type: 'error' },- ]);-- expect(chunks.some((c) => c.includes('event: error'))).toBe(true);- expect(completion.error).toMatchObject({ message: 'Overloaded' });- });-- it('names an OpenAI-format answer on an Anthropic endpoint as a malformed response', async () => {- const { completion } = await collect([- {- choices: [{ delta: { content: 'Hello' }, finish_reason: null, index: 0 }],- id: 'chatcmpl_1',- object: 'chat.completion.chunk',- },- ]);-- expect(completion.error).toMatchObject({ type: 'UpstreamMalformedResponse' });- });- });});diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/streams/anthropic.tsindex ffe393a00c5..1844cd216b7 100644--- a/packages/model-runtime/src/core/streams/anthropic.ts+++ b/packages/model-runtime/src/core/streams/anthropic.ts@@ -335,6 +335,13 @@ export const AnthropicStream = (streamStack,}),)- .pipeThrough(createSSEProtocolTransformer((c) => c, streamStack))+ .pipeThrough(+ /**+ * A Messages stream always ends with `message_delta` + `message_stop`. Some relays close the+ * connection mid-response without either; without this flag the truncated output was+ * treated as a normal completion, so half-written tool arguments got executed.+ */+ createSSEProtocolTransformer((c) => c, streamStack, { requireTerminalEvent: true }),+ ).pipeThrough(createCallbacksTransformer(callbacks, { streamStack }));};diff --git a/packages/model-runtime/src/core/streams/bedrock/claude.ts b/packages/model-runtime/src/core/streams/bedrock/claude.tsindex 51c2af38d89..4efd3113d6c 100644--- a/packages/model-runtime/src/core/streams/bedrock/claude.ts+++ b/packages/model-runtime/src/core/streams/bedrock/claude.ts@@ -33,6 +33,9 @@ export const AWSBedrockClaudeStream = (streamStack,}),)- .pipeThrough(createSSEProtocolTransformer((c) => c, streamStack))+ .pipeThrough(+ // Same Messages event contract as `AnthropicStream`: closing without a terminal event is a truncation.+ createSSEProtocolTransformer((c) => c, streamStack, { requireTerminalEvent: true }),+ ).pipeThrough(createCallbacksTransformer(options?.callbacks));};