Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(compat-proxy): moonshot 空 assistant 消息 400 的透明恢复与发送前预剥 (#821)
yanebcdb8a0ec74
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.tsindex 5d6d64d2b2..b588cf8994 100644--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts@@ -19,10 +19,12 @@import {createAnthropicCompatProxy,createActiveStripTransform,+ createEmptyAssistantMessageRecoveryRule,createEmptyTextRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,+ stripEmptyAssistantMessagesFromBody,stripEmptyTextFromBody,stripEmptyThinkingFromBody,stripEncryptedContentFromBody,@@ -51,6 +53,7 @@ import {import { createProviderUpstreamErrorObserver } from './provider-upstream-error-observer.js';import { createClaudeAutoClassifierFailureObserver } from './claude-auto-permission-fallback.js';import {+ emptyAssistantStripController,emptyTextStripController,emptyThinkingStripController,encryptedStripController,@@ -302,6 +305,14 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {enabled: () => true,strip: stripEmptyTextFromBody,}),+ // 空 assistant 消息主动剥离 —— always-on,独立 controller(moonshot/kimi 空+ // thinking 占位被中断持久化后回放 400 "with role 'assistant' must not be empty";+ // 与 kimi code 官方客户端的发送前兜底同构)。+ createActiveStripTransform({+ controller: emptyAssistantStripController,+ enabled: () => true,+ strip: stripEmptyAssistantMessagesFromBody,+ }),// LiteLLM/provider adapter 可能把 provider_specific_fields(null) 挂到 tool_use 上,// 严格 Anthropic 入站 schema 不接受该扩展字段。stripToolUseProviderSpecificFields,@@ -322,6 +333,12 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {enabled: () => true,onRetry: (threadId, model) => emptyTextStripController.markActive(threadId, model),}),+ // 空 assistant 消息 400 → 丢空消息重发,always-on(moonshot/kimi 空 thinking+ // 占位污染的会话;恢复一次后该 thread 发送前主动预剥,不再每轮撞 400)。+ createEmptyAssistantMessageRecoveryRule({+ enabled: () => true,+ onRetry: (threadId, model) => emptyAssistantStripController.markActive(threadId, model),+ }),createToolUseProviderSpecificFieldsRecoveryRule(),],logger: log,diff --git a/apps/desktop/src/main/maker-host/thread-strip-controllers.ts b/apps/desktop/src/main/maker-host/thread-strip-controllers.tsindex fcf2ff24ba..3a08d1e682 100644--- a/apps/desktop/src/main/maker-host/thread-strip-controllers.ts+++ b/apps/desktop/src/main/maker-host/thread-strip-controllers.ts@@ -17,3 +17,7 @@ export const emptyThinkingStripController = createThreadStripController();// 空 text 块主动剥离 —— always-on(bridge 修复前落进历史的 `{type:'text',text:''}`// 空块,切回真 Anthropic 模型时 400)。必须与上面是独立实例。export const emptyTextStripController = createThreadStripController();++// 空 assistant 消息主动剥离 —— always-on(moonshot/kimi 空 thinking 占位被中断+// 持久化后回放 400 "with role 'assistant' must not be empty")。必须与上面是独立实例。+export const emptyAssistantStripController = createThreadStripController();diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.tsindex 06d9ebff80..2e2936cac9 100644--- a/packages/anthropic-compat-proxy/src/index.ts+++ b/packages/anthropic-compat-proxy/src/index.ts@@ -35,11 +35,13 @@ export {} from './instructions-injection.js';export {createActiveStripTransform,+ createEmptyAssistantMessageRecoveryRule,createEmptyTextRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,createImageGenerationIdRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,+ stripEmptyAssistantMessagesFromBody,stripEmptyTextFromBody,stripEmptyThinkingFromBody,stripEncryptedContentFromBody,diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.tsindex b2c7299d22..230d1000a0 100644--- a/packages/anthropic-compat-proxy/src/server.test.ts+++ b/packages/anthropic-compat-proxy/src/server.test.ts@@ -10,6 +10,7 @@ import {} from './server.js';import {createActiveStripTransform,+ createEmptyAssistantMessageRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,createImageGenerationIdRecoveryRule,@@ -1309,6 +1310,167 @@ describe('anthropic-compat-proxy empty-thinking recovery', () => {});});+// moonshot 线上 400 原文(2026-07-28,经 LiteLLM passthrough;request_id 取自真实捕获)。+const MOONSHOT_EMPTY_ASSISTANT_ERROR_BODY = JSON.stringify({+ error: {+ type: 'invalid_request_error',+ message: "Invalid request: the message at position 395 with role 'assistant' must not be empty",+ },+ request_id: 'f1b34454-8a63-11f1-bf3c-9ac780b5488d',+ type: 'error',+});++// moonshot/kimi-k3 线上污染会话形态(2026-07-28): 完整 tool_use/tool_result 上下文里+// 夹着一条 thinking-only 空 assistant(流中断后客户端持久化的未完成占位 block)。+function kimiBodyWithEmptyAssistant(): unknown {+ return {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'run ls' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_01', name: 'Bash', input: { command: 'ls' } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_01', content: 'ok' }] },+ { role: 'assistant', content: [{ type: 'thinking', thinking: '', signature: '' }] },+ { role: 'user', content: 'continue' },+ ],+ };+}++describe('anthropic-compat-proxy empty-assistant-message recovery (moonshot/kimi)', () => {+ it('drops the empty assistant message and retries once on the moonshot 400', async () => {+ const upstream = await startFakeUpstream((idx, _body, res) => {+ if (idx === 0) {+ res.writeHead(400, { 'content-type': 'application/json' });+ res.end(MOONSHOT_EMPTY_ASSISTANT_ERROR_BODY);+ } else {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ }+ });+ upstreamClose = upstream.close;+ let marked: { threadId: string; model: string } | null = null;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [],+ recoveryRules: [createEmptyAssistantMessageRecoveryRule({+ enabled: () => true,+ onRetry: (threadId, model) => { marked = { threadId, model }; },+ })],+ });++ const r = await post(proxy.url, kimiBodyWithEmptyAssistant());++ expect(r.status).toBe(200);+ expect(upstream.bodies).toHaveLength(2);+ expect(upstream.bodies[0]).toContain('"thinking":""');+ // 重发 body: 空 thinking-only assistant 整条被丢(5 → 4 条),tool_use/tool_result 配对保留。+ const retried = JSON.parse(upstream.bodies[1]);+ expect(retried.messages).toHaveLength(4);+ expect(retried.messages.map((m: { role: string }) => m.role)).toEqual([+ 'user', 'assistant', 'user', 'user',+ ]);+ expect(upstream.bodies[1]).not.toContain('"thinking":""');+ expect(marked).toEqual({ threadId: 'thread-a', model: 'moonshot/kimi-k3' });+ });++ it('does not retry when there is no empty assistant message to drop', async () => {+ const upstream = await startFakeUpstream((_idx, _body, res) => {+ res.writeHead(400, { 'content-type': 'application/json' });+ res.end(MOONSHOT_EMPTY_ASSISTANT_ERROR_BODY);+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [],+ recoveryRules: [createEmptyAssistantMessageRecoveryRule({ enabled: () => true })],+ });++ const r = await post(proxy.url, {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'hi' },+ { role: 'assistant', content: [{ type: 'thinking', thinking: 'real reasoning', signature: '' }, { type: 'text', text: 'ok' }] },+ ],+ });++ expect(r.status).toBe(400);+ expect(upstream.bodies).toHaveLength(1);+ });++ it('does not retry a second time after the retry still returns the moonshot 400', async () => {+ const upstream = await startFakeUpstream((_idx, _body, res) => {+ res.writeHead(400, { 'content-type': 'application/json' });+ res.end(MOONSHOT_EMPTY_ASSISTANT_ERROR_BODY);+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [],+ recoveryRules: [createEmptyAssistantMessageRecoveryRule({ enabled: () => true })],+ });++ const r = await post(proxy.url, kimiBodyWithEmptyAssistant());++ expect(r.status).toBe(400);+ expect(upstream.bodies).toHaveLength(2);+ });++ it('also recovers when the stale assistant carries an empty text block instead of empty thinking', async () => {+ // PR #821 review 实测反馈形态: bridge 清理路径的 text-only 空块。+ const upstream = await startFakeUpstream((idx, _body, res) => {+ if (idx === 0) {+ res.writeHead(400, { 'content-type': 'application/json' });+ res.end(MOONSHOT_EMPTY_ASSISTANT_ERROR_BODY);+ } else {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ }+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [],+ recoveryRules: [createEmptyAssistantMessageRecoveryRule({ enabled: () => true })],+ });++ const r = await post(proxy.url, {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'hi' },+ { role: 'assistant', content: [{ type: 'text', text: '' }] },+ { role: 'user', content: 'continue' },+ ],+ });++ expect(r.status).toBe(200);+ expect(upstream.bodies).toHaveLength(2);+ expect(JSON.parse(upstream.bodies[1]).messages).toHaveLength(2);+ });++ it('decodes a gzip-encoded moonshot 400 and still triggers the retry', async () => {+ const upstream = await startFakeUpstream((idx, _body, res) => {+ if (idx === 0) {+ res.writeHead(400, { 'content-type': 'application/json', 'content-encoding': 'gzip' });+ res.end(gzipSync(Buffer.from(MOONSHOT_EMPTY_ASSISTANT_ERROR_BODY, 'utf8')));+ } else {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end('{}');+ }+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [],+ recoveryRules: [createEmptyAssistantMessageRecoveryRule({ enabled: () => true })],+ });++ const r = await post(proxy.url, kimiBodyWithEmptyAssistant());++ expect(r.status).toBe(200);+ expect(upstream.bodies).toHaveLength(2);+ expect(upstream.bodies[1]).not.toContain('"thinking":""');+ });+});+describe('anthropic-compat-proxy localHandler(路由决策交本地 handler,不转发上游)', () => {it('命中 handler:收到原始字节 + 已解析 body + ctx,自写响应(含 SSE 流式),上游零请求', async () => {const gateway = await startFakeUpstream((_i, _b, res) => { res.writeHead(200); res.end('{}'); });diff --git a/packages/anthropic-compat-proxy/src/transform.test.ts b/packages/anthropic-compat-proxy/src/transform.test.tsindex 07c232a744..0f812d5524 100644--- a/packages/anthropic-compat-proxy/src/transform.test.ts+++ b/packages/anthropic-compat-proxy/src/transform.test.ts@@ -3,11 +3,13 @@ import { describe, expect, it } from 'vitest';import { createThreadStripController } from './thread-strip-controller.js';import {createActiveStripTransform,+ createEmptyAssistantMessageRecoveryRule,createEmptyTextRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,createImageGenerationIdRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,+ stripEmptyAssistantMessagesFromBody,stripEmptyTextFromBody,stripEmptyThinkingFromBody,stripEncryptedContentFromBody,@@ -463,6 +465,159 @@ describe('stripEmptyTextFromBody', () => {});});+describe('stripEmptyAssistantMessagesFromBody', () => {+ it('drops a thinking-only empty assistant message (moonshot/kimi interrupted placeholder)', () => {+ // 线上污染形态(2026-07-28): 流首包空 thinking 占位被中断持久化。+ const body = buf({+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'hi' },+ { role: 'assistant', content: [{ type: 'thinking', thinking: '', signature: '' }] },+ { role: 'user', content: 'continue' },+ ],+ });+ const out = stripEmptyAssistantMessagesFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages).toHaveLength(2);+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual(['user', 'user']);+ });++ it('drops a native empty content-array assistant message', () => {+ const body = buf({+ messages: [+ { role: 'user', content: 'hi' },+ { role: 'assistant', content: [] },+ ],+ });+ const out = stripEmptyAssistantMessagesFromBody(body);+ expect(out).not.toBeNull();+ expect(JSON.parse(out!.toString('utf8')).messages).toHaveLength(1);+ });++ it('drops a blank string-content assistant message, keeps a non-blank one', () => {+ const body = buf({+ messages: [+ { role: 'assistant', content: ' ' },+ { role: 'assistant', content: 'real answer' },+ ],+ });+ const out = stripEmptyAssistantMessagesFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages).toHaveLength(1);+ expect(parsed.messages[0].content).toBe('real answer');+ });++ it('strips empty thinking but keeps sibling text / tool_use blocks', () => {+ const body = buf({+ messages: [+ {+ role: 'assistant',+ content: [+ { type: 'thinking', thinking: '', signature: '' },+ { type: 'tool_use', id: 't1', name: 'Bash', input: { command: 'ls' } },+ ],+ },+ {+ role: 'assistant',+ content: [+ { type: 'thinking', thinking: '', signature: '' },+ { type: 'text', text: 'done' },+ ],+ },+ ],+ });+ const out = stripEmptyAssistantMessagesFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages).toHaveLength(2);+ expect(parsed.messages[0].content).toEqual([+ { type: 'tool_use', id: 't1', name: 'Bash', input: { command: 'ls' } },+ ]);+ expect(parsed.messages[1].content).toEqual([{ type: 'text', text: 'done' }]);+ });++ it('keeps a content-bearing thinking block (empty signature is tolerated)', () => {+ const body = buf({+ messages: [+ { role: 'assistant', content: [{ type: 'thinking', thinking: 'real reasoning', signature: '' }] },+ ],+ });+ expect(stripEmptyAssistantMessagesFromBody(body)).toBeNull();+ });++ it('never touches user messages, even empty ones', () => {+ const body = buf({+ messages: [+ { role: 'user', content: [] },+ { role: 'user', content: 'hi' },+ ],+ });+ expect(stripEmptyAssistantMessagesFromBody(body)).toBeNull();+ });++ it('returns null for a clean body (cache-safe no-op)', () => {+ const body = buf({+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'hi' },+ { role: 'assistant', content: [{ type: 'text', text: 'hello' }] },+ ],+ });+ expect(stripEmptyAssistantMessagesFromBody(body)).toBeNull();+ });++ it('drops a text-only empty-block assistant message (bridge cleanup path shape)', () => {+ // PR #821 review: bridge 清理路径产出的 text-only 空块同样命中 moonshot 空消息校验,+ // 只剥 thinking 会让 strip 返回 null、重试被跳过。+ const body = buf({+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'hi' },+ { role: 'assistant', content: [{ type: 'text', text: '' }] },+ { role: 'user', content: 'continue' },+ ],+ });+ const out = stripEmptyAssistantMessagesFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages).toHaveLength(2);+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual(['user', 'user']);+ });++ it('drops a mixed empty thinking + empty text assistant message, keeps real content siblings', () => {+ const body = buf({+ messages: [+ {+ role: 'assistant',+ content: [+ { type: 'thinking', thinking: '', signature: '' },+ { type: 'text', text: '' },+ ],+ },+ {+ role: 'assistant',+ content: [+ { type: 'text', text: '' },+ { type: 'text', text: 'real' },+ ],+ },+ ],+ });+ const out = stripEmptyAssistantMessagesFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages).toHaveLength(1);+ expect(parsed.messages[0].content).toEqual([{ type: 'text', text: 'real' }]);+ });++ it('returns null for non-JSON / missing messages', () => {+ expect(stripEmptyAssistantMessagesFromBody(Buffer.from('not json', 'utf8'))).toBeNull();+ expect(stripEmptyAssistantMessagesFromBody(buf({ model: 'x' }))).toBeNull();+ });+});+describe('createThreadStripController', () => {it('marks active threads and clears them when model changes', () => {const controller = createThreadStripController();@@ -648,6 +803,35 @@ describe('recovery rule factories', () => {).not.toBeNull();});+ it('empty-assistant-message rule matches the moonshot error text, is always-on by default, and strips empty assistant messages', () => {+ const rule = createEmptyAssistantMessageRecoveryRule();+ expect(rule.id).toBe('empty_assistant_message');+ expect(rule.enabled()).toBe(true);+ // 线上实测 moonshot 400 原文(2026-07-28,经 LiteLLM passthrough,两个独立会话):+ expect(+ rule.matches(+ 'Invalid request: the message at position 693 with role \'assistant\' must not be empty',+ ),+ ).toBe(true);+ expect(+ rule.matches(+ JSON.stringify({+ error: {+ type: 'invalid_request_error',+ message: "Invalid request: the message at position 275 with role 'assistant' must not be empty",+ },+ }),+ ),+ ).toBe(true);+ expect(rule.matches('each thinking block must contain thinking')).toBe(false);+ expect(rule.matches('invalid_encrypted_content')).toBe(false);+ expect(+ rule.strip(+ buf({ messages: [{ role: 'assistant', content: [{ type: 'thinking', thinking: '', signature: '' }] }] }),+ ),+ ).not.toBeNull();+ });+it('image-generation-id rule matches only its error text, is always-on by default, and strips malformed items', () => {const rule = createImageGenerationIdRecoveryRule();expect(rule.id).toBe('image_generation_id');diff --git a/packages/anthropic-compat-proxy/src/transform.ts b/packages/anthropic-compat-proxy/src/transform.tsindex 6073f1a75e..ad1b35787f 100644--- a/packages/anthropic-compat-proxy/src/transform.ts+++ b/packages/anthropic-compat-proxy/src/transform.ts@@ -440,6 +440,86 @@ export function stripEmptyTextFromBody(rawBody: Buffer): Buffer | null {}}+/**+ * 丢弃请求历史里的空 assistant 消息(含剥掉空 thinking 块后变空壳的),返回新 Buffer;+ * 没改动 / 非 JSON / 无 messages → null。+ *+ * 背景: moonshot/kimi-k3 经 LiteLLM 原生转发(/anthropic/v1/messages passthrough)时,+ * 其 Anthropic 兼容流首包是空 thinking 占位 {type:"thinking",thinking:"",signature:""}+ * (kimi 官方确认 by design);流被 429/中断切断后,客户端把未完成的占位 block 当成完整+ * assistant 持久化,回放时 moonshot 400:+ * "Invalid request: the message at position 693 with role 'assistant' must not be empty"+ * (2026-07-28 线上实测,两个独立会话 position 693 / 275,重试 35+ 次全部失败,+ * 会话级永久卡死——每轮请求历史都带污染消息)。+ *+ * 处理(与 kimi code 官方客户端的兜底策略同构——发送出去的请求不允许带空 assistant):+ * 1. assistant 消息 content 为 string 且为空白 → 整条丢弃;+ * 2. assistant 消息 content 为数组:先剥空 thinking 块与空 text 块(判别式与+ * stripEmptyThinkingFromBody / stripEmptyTextFromBody 一致,有内容/签名空的块+ * 保留),剥完为空(含原生 content:[])→ 整条丢弃;剥完仍有 text/tool_use →+ * 保留净化后的消息。空 text 块一并剥的原因:moonshot 的 must-not-be-empty 校验+ * 对 bridge 清理路径产出的 text-only 空块消息同样命中(PR #821 review 实测反馈),+ * 只剥 thinking 会让该形态 strip 不出东西、重试被跳过,会话继续卡死。+ * user 消息一律不动(线上命中的只有 assistant;user 空消息无实测证据,不扩散)。+ *+ * 安全性: 空消息不含任何对话信息,丢弃不改变语义;含 tool_use 的轮次剥完非空,+ * tool_use/tool_result 配对不会被打破。+ *+ * @returns 丢弃/净化至少一条 → 新 Buffer; 无改动 → null (cache 安全契约:字节透传)。+ */+export function stripEmptyAssistantMessagesFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ if (!isPlainObject(parsed)) return null;+ const messages = parsed.messages;+ if (!Array.isArray(messages)) return null;++ let changed = false;+ const keptMessages: unknown[] = [];+ for (const msg of messages) {+ if (!isPlainObject(msg) || msg.role !== 'assistant') {+ keptMessages.push(msg);+ continue;+ }+ const content = msg.content;+ if (typeof content === 'string') {+ if (content.trim().length === 0) {+ changed = true; // 空 string content → 整条丢弃+ continue;+ }+ keptMessages.push(msg);+ continue;+ }+ if (!Array.isArray(content)) {+ keptMessages.push(msg); // 异常形态不猜,原样保留+ continue;+ }+ const keptContent = content.filter((block) => !isEmptyThinkingBlock(block) && !isEmptyTextBlock(block));+ if (keptContent.length === 0) {+ changed = true; // 空壳(content:[] 或剥空 thinking/空 text 后为空)→ 整条丢弃+ continue;+ }+ if (keptContent.length !== content.length) {+ changed = true;+ keptMessages.push({ ...msg, content: keptContent });+ continue;+ }+ keptMessages.push(msg);+ }++ if (!changed) return null; // ← cache 安全契约:无改动 → null → 字节透传+ parsed.messages = keptMessages;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}+// ───────────────────────────────────────────────────────────────────────────// Per-model handlers ——// 每个 model 一个独立函数,内部自由实现 strip / 翻译 / 改值。@@ -562,6 +642,11 @@ const EMPTY_THINKING_RE = /each thinking block must contain thinking/i;// 同样只匹配核心短语,不锚定下标前缀。const EMPTY_TEXT_RE = /text content blocks must (?:be non-empty|contain non-whitespace text)/i;+// moonshot 400 (经 LiteLLM /anthropic/v1/messages passthrough,2026-07-28 实测):+// "Invalid request: the message at position 693 with role 'assistant' must not be empty"+// 只匹配不变的 role + 校验短语,不锚定会变的 position 数字。+const EMPTY_ASSISTANT_MESSAGE_RE = /with role 'assistant' must not be empty/i;+// Azure/LiteLLM 400: "Image generation items without `id` are not supported for this request."const IMAGE_GENERATION_WITHOUT_ID_RE =/image generation items without [`']?id[`']? are not supported/i;@@ -664,3 +749,24 @@ export function createEmptyTextRecoveryRule(opts: {threadIdHeaders: opts.threadIdHeaders,};}++/**+ * 空 assistant 消息恢复规则: moonshot/kimi 系(Anthropic 兼容流空 thinking 占位被+ * 客户端中断持久化后)回放 400 → 丢掉空 assistant 消息重发。+ * 默认 always-on(空消息不含对话信息,丢弃零代价)。背景详见+ * stripEmptyAssistantMessagesFromBody 头注。+ */+export function createEmptyAssistantMessageRecoveryRule(opts: {+ enabled?: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+} = {}): RecoveryRule {+ return {+ id: 'empty_assistant_message',+ enabled: opts.enabled ?? (() => true),+ matches: (text) => EMPTY_ASSISTANT_MESSAGE_RE.test(text),+ strip: stripEmptyAssistantMessagesFromBody,+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}