diff --git a/README.md b/README.md index f20e9dc..dc636ce 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ These packages aren't OpenCode plugins. magpie runs them in its gateway, on the | [output-strategy](packages/output-strategy) | Seven composable output styles with a selection panel; off by default, cache-stable, and Codex `instructions` stay untouched | | [word-guard](packages/word-guard) | New API's 敏感词过滤: turn away or mask words and patterns in what users send, and in replies | | [think-tags](packages/think-tags) | Take a leading ``, `` or `` block out of a reply's text, or put a Chat reply's `reasoning_content` into it (`thinking_to_content`) | +| [empty-reply](packages/empty-reply) | Drop the end of a reply that has reasoning but no text, so Claude Code and Codex retry instead of stopping | | [antigravity-cloak](packages/antigravity-cloak) | Claude Code and Claude Desktop on Antigravity: break the words Antigravity turns their system prompt away for, in what Antigravity alone is sent | | [codex-history](packages/codex-history) | Opt-in Responses history compatibility after switching providers: remove historical ciphertext and optional item IDs while preserving readable content and tool-call pairing | | [history-trim](packages/history-trim) | Send a request's history smaller: fold a run of blank lines, drop a system prompt written twice and a message repeated right after itself, and cut a past tool result longer than `maxToolLength` at a word boundary | diff --git a/packages/empty-reply/README.md b/packages/empty-reply/README.md new file mode 100644 index 0000000..372a16c --- /dev/null +++ b/packages/empty-reply/README.md @@ -0,0 +1,61 @@ +# @magpie-community/middleware-empty-reply + +Some chat models return reasoning and no text. magpie passes that on as a +finished reply: `end_turn` for Anthropic clients, `response.completed` for +Responses. Claude Code takes the turn as done and stops; Codex ends the turn +with no output (yetone/magpie#3358). + +This middleware drops the end of such a reply. The client sees the stream +break before the answer and retries. + +```sh +magpie plugin add @magpie-community/middleware-empty-reply +``` + +No options. + +## What gets dropped + +| Protocol | Dropped | Counts as an answer | +| --- | --- | --- | +| Anthropic | `message_delta` with `end_turn`, then `message_stop` | text, refusal, tool call | +| Responses | `response.completed` | output_text, refusal, function call | + +Reasoning never counts as an answer. `max_tokens` and `refusal` stops are +left alone, because the model meant to stop. + +Whole (non-streamed) replies become an error instead: an Anthropic error +body, or a Responses response with `status: "failed"`. + +Chat clients aren't covered. Their stream has no error event, and the gateway +fix is the right place for that anyway. + +## Routing + +Middleware runs after routing, so it can't ask the next group member itself. +It only makes the client retry. + +- `rotate`: the retry hits another member. This is the setup that works. +- `ordered`: the retry hits the same member, fails again, and the client gives + up with a visible error. Still better than a silent stop. + +Once your magpie build has the gateway empty-reply fix from #3358, you don't +need this plugin. + +## Tested + +Against a Chat upstream that sends reasoning then `stop`, with real clients: + +- Claude Code 2.1.319, `ordered`: three retries, then `API Error: Connection + lost before a response was produced. Try again.` +- Claude Code 2.1.319, `rotate`: the retry reached a healthy member and the + turn completed. +- codex-cli 0.167.0, `ordered`: `Reconnecting... 1/5` to `5/5`, then `stream + disconnected before completion`. +- codex-cli 0.167.0, `rotate`: one reconnect, then a normal answer. +- Normal replies and tool calls pass unchanged. + +中文:有些 Chat 上游只返回 reasoning、正文为空,翻译后却以 `end_turn` 或 +`response.completed` 结束,Claude Code / Codex 会当成回答完毕直接停下。这个中间件 +丢掉这种回复的结尾,让客户端重试;配合 `rotate` 路由会落到组里的另一个成员。 +它不是 #3358 的正解,网关自身的空回复检查才是。 diff --git a/packages/empty-reply/cases.json b/packages/empty-reply/cases.json new file mode 100644 index 0000000..02c9b11 --- /dev/null +++ b/packages/empty-reply/cases.json @@ -0,0 +1,119 @@ +[ + { "name": "anthropic stream: thinking then end_turn is dropped", + "ctx": {"protocol": "anthropic", "stream": true}, + "events": [ + {"event": "message_start", "data": {"type": "message_start", "message": {"id": "msg_1", "type": "message", "role": "assistant", "content": [], "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 9, "output_tokens": 1}}}}, + {"event": "content_block_start", "data": {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}}, + {"event": "content_block_delta", "data": {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "Let me think about that."}}}, + {"event": "content_block_stop", "data": {"type": "content_block_stop", "index": 0}}, + {"event": "message_delta", "data": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}, "usage": {"output_tokens": 7}}}, + {"event": "message_stop", "data": {"type": "message_stop"}} + ], + "expect_events": [ + {"type": "message_start", "message": {"id": "msg_1", "type": "message", "role": "assistant", "content": [], "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 9, "output_tokens": 1}}}, + {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}, + {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "Let me think about that."}}, + {"type": "content_block_stop", "index": 0} + ] }, + { "name": "anthropic stream: empty text block then end_turn is dropped", + "ctx": {"protocol": "anthropic", "stream": true}, + "events": [ + {"event": "content_block_start", "data": {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}}, + {"event": "message_delta", "data": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}}}, + {"event": "message_stop", "data": {"type": "message_stop"}} + ], + "expect_events": [ + {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}} + ] }, + { "name": "anthropic stream: text passes", + "ctx": {"protocol": "anthropic", "stream": true}, + "events": [ + {"event": "content_block_start", "data": {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}}, + {"event": "content_block_delta", "data": {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}}, + {"event": "content_block_stop", "data": {"type": "content_block_stop", "index": 0}}, + {"event": "message_delta", "data": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}}}, + {"event": "message_stop", "data": {"type": "message_stop"}} + ] }, + { "name": "anthropic stream: tool call passes", + "ctx": {"protocol": "anthropic", "stream": true}, + "events": [ + {"event": "content_block_start", "data": {"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "toolu_1", "name": "Bash", "input": {}}}}, + {"event": "content_block_delta", "data": {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": "{\"command\":\"echo hi\"}"}}}, + {"event": "content_block_stop", "data": {"type": "content_block_stop", "index": 0}}, + {"event": "message_delta", "data": {"type": "message_delta", "delta": {"stop_reason": "tool_use", "stop_sequence": null}}}, + {"event": "message_stop", "data": {"type": "message_stop"}} + ] }, + { "name": "anthropic stream: max_tokens is kept", + "ctx": {"protocol": "anthropic", "stream": true}, + "events": [ + {"event": "content_block_start", "data": {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}}, + {"event": "content_block_delta", "data": {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "over and over"}}}, + {"event": "message_delta", "data": {"type": "message_delta", "delta": {"stop_reason": "max_tokens", "stop_sequence": null}}}, + {"event": "message_stop", "data": {"type": "message_stop"}} + ] }, + { "name": "anthropic stream: refusal is kept", + "ctx": {"protocol": "anthropic", "stream": true}, + "events": [ + {"event": "message_delta", "data": {"type": "message_delta", "delta": {"stop_reason": "refusal", "stop_sequence": null}}}, + {"event": "message_stop", "data": {"type": "message_stop"}} + ] }, + { "name": "anthropic whole: thinking then end_turn becomes an error", + "response": {"id": "msg_1", "type": "message", "role": "assistant", "stop_reason": "end_turn", "content": [{"type": "thinking", "thinking": "Let me think about that.", "signature": ""}]}, + "expect_response": {"type": "error", "error": {"type": "api_error", "message": "empty reply from the model (no text; try again)"}} }, + { "name": "anthropic whole: text passes", + "response": {"id": "msg_1", "type": "message", "role": "assistant", "stop_reason": "end_turn", "content": [{"type": "text", "text": "Hello"}]} }, + { "name": "anthropic whole: tool call passes", + "response": {"id": "msg_1", "type": "message", "role": "assistant", "stop_reason": "tool_use", "content": [{"type": "tool_use", "id": "toolu_1", "name": "Bash", "input": {"command": "echo hi"}}]} }, + { "name": "responses stream: reasoning then completed is dropped", + "ctx": {"protocol": "responses", "stream": true}, + "events": [ + {"event": "response.created", "data": {"type": "response.created", "response": {"id": "resp_1", "object": "response", "status": "in_progress", "output": []}}}, + {"event": "response.output_item.added", "data": {"type": "response.output_item.added", "output_index": 0, "item": {"type": "reasoning", "id": "rs_1", "summary": []}}}, + {"event": "response.reasoning_summary_part.added", "data": {"type": "response.reasoning_summary_part.added", "item_id": "rs_1", "summary_index": 0, "part": {"type": "summary_text", "text": ""}}}, + {"event": "response.reasoning_summary_text.delta", "data": {"type": "response.reasoning_summary_text.delta", "item_id": "rs_1", "summary_index": 0, "delta": "Let me think about that."}}, + {"event": "response.reasoning_summary_text.done", "data": {"type": "response.reasoning_summary_text.done", "item_id": "rs_1", "summary_index": 0, "text": "Let me think about that."}}, + {"event": "response.output_item.done", "data": {"type": "response.output_item.done", "output_index": 0, "item": {"type": "reasoning", "id": "rs_1", "summary": [{"type": "summary_text", "text": "Let me think about that."}]}}}, + {"event": "response.completed", "data": {"type": "response.completed", "response": {"id": "resp_1", "object": "response", "status": "completed", "output": [{"type": "reasoning", "id": "rs_1", "summary": [{"type": "summary_text", "text": "Let me think about that."}]}], "usage": {"input_tokens": 9, "output_tokens": 7, "total_tokens": 16}}}} + ], + "expect_events": [ + {"type": "response.created", "response": {"id": "resp_1", "object": "response", "status": "in_progress", "output": []}}, + {"type": "response.output_item.added", "output_index": 0, "item": {"type": "reasoning", "id": "rs_1", "summary": []}}, + {"type": "response.reasoning_summary_part.added", "item_id": "rs_1", "summary_index": 0, "part": {"type": "summary_text", "text": ""}}, + {"type": "response.reasoning_summary_text.delta", "item_id": "rs_1", "summary_index": 0, "delta": "Let me think about that."}, + {"type": "response.reasoning_summary_text.done", "item_id": "rs_1", "summary_index": 0, "text": "Let me think about that."}, + {"type": "response.output_item.done", "output_index": 0, "item": {"type": "reasoning", "id": "rs_1", "summary": [{"type": "summary_text", "text": "Let me think about that."}]}} + ] }, + { "name": "responses stream: message passes", + "ctx": {"protocol": "responses", "stream": true}, + "events": [ + {"event": "response.output_item.added", "data": {"type": "response.output_item.added", "output_index": 0, "item": {"type": "message", "id": "msg_1", "role": "assistant", "content": []}}}, + {"event": "response.content_part.added", "data": {"type": "response.content_part.added", "item_id": "msg_1", "output_index": 0, "content_index": 0, "part": {"type": "output_text", "text": ""}}}, + {"event": "response.output_text.delta", "data": {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": "Hello"}}, + {"event": "response.output_item.done", "data": {"type": "response.output_item.done", "output_index": 0, "item": {"type": "message", "id": "msg_1", "role": "assistant", "content": [{"type": "output_text", "text": "Hello"}]}}}, + {"event": "response.completed", "data": {"type": "response.completed", "response": {"id": "resp_1", "object": "response", "status": "completed", "output": [{"type": "message", "id": "msg_1", "role": "assistant", "content": [{"type": "output_text", "text": "Hello"}]}]}}} + ] }, + { "name": "responses stream: function call passes", + "ctx": {"protocol": "responses", "stream": true}, + "events": [ + {"event": "response.output_item.added", "data": {"type": "response.output_item.added", "output_index": 0, "item": {"type": "function_call", "id": "fc_1", "name": "shell", "arguments": ""}}}, + {"event": "response.function_call_arguments.delta", "data": {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "output_index": 0, "delta": "{\"command\":\"echo hi\"}"}}, + {"event": "response.output_item.done", "data": {"type": "response.output_item.done", "output_index": 0, "item": {"type": "function_call", "id": "fc_1", "name": "shell", "arguments": "{\"command\":\"echo hi\"}"}}}, + {"event": "response.completed", "data": {"type": "response.completed", "response": {"id": "resp_1", "object": "response", "status": "completed", "output": [{"type": "function_call", "id": "fc_1", "name": "shell", "arguments": "{\"command\":\"echo hi\"}"}]}}} + ] }, + { "name": "responses stream: incomplete is kept", + "ctx": {"protocol": "responses", "stream": true}, + "events": [ + {"event": "response.output_item.added", "data": {"type": "response.output_item.added", "output_index": 0, "item": {"type": "reasoning", "id": "rs_1", "summary": []}}}, + {"event": "response.completed", "data": {"type": "response.completed", "response": {"id": "resp_1", "object": "response", "status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"}, "output": [{"type": "reasoning", "id": "rs_1", "summary": []}]}}} + ] }, + { "name": "responses whole: reasoning only becomes failed", + "ctx": {"protocol": "responses"}, + "response": {"id": "resp_1", "object": "response", "status": "completed", "output": [{"type": "reasoning", "id": "rs_1", "summary": [{"type": "summary_text", "text": "Let me think about that."}]}]}, + "expect_response": {"id": "resp_1", "object": "response", "status": "failed", "output": [{"type": "reasoning", "id": "rs_1", "summary": [{"type": "summary_text", "text": "Let me think about that."}]}], "error": {"code": "empty_reply", "message": "empty reply from the model (no text; try again)"}} }, + { "name": "responses whole: message passes", + "ctx": {"protocol": "responses"}, + "response": {"id": "resp_1", "object": "response", "status": "completed", "output": [{"type": "message", "id": "msg_1", "role": "assistant", "content": [{"type": "output_text", "text": "Hello"}]}]} }, + { "name": "responses whole: empty message becomes failed", + "ctx": {"protocol": "responses"}, + "response": {"id": "resp_1", "object": "response", "status": "completed", "output": [{"type": "message", "id": "msg_1", "role": "assistant", "content": [{"type": "output_text", "text": ""}]}]}, + "expect_response": {"id": "resp_1", "object": "response", "status": "failed", "output": [{"type": "message", "id": "msg_1", "role": "assistant", "content": [{"type": "output_text", "text": ""}]}], "error": {"code": "empty_reply", "message": "empty reply from the model (no text; try again)"}} }] diff --git a/packages/empty-reply/empty-reply.middleware.js b/packages/empty-reply/empty-reply.middleware.js new file mode 100644 index 0000000..0332a89 --- /dev/null +++ b/packages/empty-reply/empty-reply.middleware.js @@ -0,0 +1,128 @@ +// empty-reply.middleware.js +// +// Some chat models return reasoning and nothing else. magpie translates that +// to end_turn (Anthropic) or response.completed (Responses), the agent thinks +// the turn is done, and stops. Drop the end events and the client retries. +// +// Middleware runs after routing, so it can't start another upstream itself. +// With routing "rotate" the retry lands on the next member; with a fixed +// order it lands on the same one. Gateway-side fix: yetone/magpie#3358. + +const note = "empty reply from the model (no text; try again)" + +// Text, refusals and tool calls are answers. Reasoning is not; a reply made +// of reasoning alone is exactly what we're catching. Unknown part types +// count as answers, so new tool-call shapes keep working. +function hasAnswer(p) { + if (!p) return false + switch (p.type) { + case "text": + case "output_text": + return !!p.text + case "refusal": + return !!p.refusal + case "thinking": + case "redacted_thinking": + case "reasoning": + case "summary_text": + case "reasoning_text": + return false + case "message": + return (p.content || []).some(hasAnswer) + } + return true +} + +function contentHasAnswer(content) { + return (content || []).some(hasAnswer) +} + +function outputHasAnswer(resp) { + return ((resp && resp.output) || []).some(hasAnswer) +} + +// Tracks one Anthropic stream; an event it returns true for gets dropped. +// Only end_turn is hidden. max_tokens and refusal come from the model and +// are left alone. +function anthropic(ev, s) { + switch (ev.type) { + case "content_block_start": + if (hasAnswer(ev.content_block)) s.answered = true + return false + case "content_block_delta": { + const d = ev.delta || {} + if (d.type === "text_delta") { + if (d.text) s.answered = true + } else if (d.type !== "thinking_delta" && d.type !== "signature_delta") { + s.answered = true + } + return false + } + case "message_delta": + if (!s.answered && (ev.delta || {}).stop_reason === "end_turn") { + s.empty = true + return true + } + return false + case "message_stop": + return !!s.empty + } + return false +} + +// Same for a Responses stream. The output on response.completed is checked +// too: a completed that carries the text without the deltas still counts. +function responses(ev, s) { + switch (ev.type) { + case "response.output_item.added": + case "response.output_item.done": + if (hasAnswer(ev.item)) s.answered = true + return false + case "response.content_part.added": + case "response.content_part.done": + if (hasAnswer(ev.part)) s.answered = true + return false + case "response.output_text.delta": + if (ev.delta) s.answered = true + return false + case "response.function_call_arguments.delta": + case "response.custom_tool_call_input.delta": + case "response.mcp_call_arguments.delta": + s.answered = true + return false + case "response.completed": { + // incomplete means max_output_tokens or a filter: not our business + if ((ev.response || {}).status === "incomplete") return false + if (!s.answered && !outputHasAnswer(ev.response)) { + s.empty = true + return true + } + return false + } + } + return false +} + +// undefined keeps an event, null drops it. The agent then sees the stream +// end early, which is retryable; end_turn would have finished the turn. +export function onEvent(ev, ctx) { + const s = ctx.state + if (!s) return undefined + let drop = false + if (ctx.protocol === "responses") drop = responses(ev, s) + else if (ctx.protocol === "anthropic") drop = anthropic(ev, s) + return drop ? null : undefined +} + +// Whole replies (no streaming) get an error body instead. Middleware can't +// set the status code, so Responses goes back with status "failed". +export function onResponse(body, ctx) { + if (!body) return undefined + if (ctx.protocol === "anthropic" && body.type === "message" && body.stop_reason === "end_turn" && !contentHasAnswer(body.content)) { + return { type: "error", error: { type: "api_error", message: note } } + } + if (ctx.protocol === "responses" && body.status === "completed" && !outputHasAnswer(body)) { + return { ...body, status: "failed", error: { code: "empty_reply", message: note } } + } + return undefined +} diff --git a/packages/empty-reply/empty-reply.test.mjs b/packages/empty-reply/empty-reply.test.mjs new file mode 100644 index 0000000..8514831 --- /dev/null +++ b/packages/empty-reply/empty-reply.test.mjs @@ -0,0 +1,27 @@ +import * as mod from "./empty-reply.middleware.js" +import { check } from "../../scripts/middleware.mjs" +import { expect, test } from "bun:test" + +check(import.meta.dir, mod) + +// Claude Code 2.1.319 treated the early-ended stream as a broken connection: +// it retried three times and gave up with "Connection lost before a response +// was produced." A retry is a new request, so a rotating group can move on. +test("drops the end of a stream that said nothing", () => { + const ctx = { protocol: "anthropic", stream: true, options: {}, state: {} } + const events = [ + { type: "message_start", message: { id: "msg_1", type: "message", role: "assistant", content: [] } }, + { type: "content_block_start", index: 0, content_block: { type: "thinking", thinking: "" } }, + { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "hmm" } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null } }, + { type: "message_stop" }, + ] + const out = events.filter((ev) => mod.onEvent(structuredClone(ev), ctx) !== null) + expect(out.map((ev) => ev.type)).toEqual([ + "message_start", + "content_block_start", + "content_block_delta", + "content_block_stop", + ]) +}) diff --git a/packages/empty-reply/package.json b/packages/empty-reply/package.json new file mode 100644 index 0000000..5f128a5 --- /dev/null +++ b/packages/empty-reply/package.json @@ -0,0 +1,13 @@ +{ + "name": "@magpie-community/middleware-empty-reply", + "version": "0.1.0", + "description": "Drop the end of a reasoning-only reply, so Claude Code and Codex retry instead of treating an empty turn as finished", + "type": "module", + "files": ["empty-reply.middleware.js", "README.md"], + "keywords": ["magpie", "magpie-middleware", "empty-reply", "claude-code", "codex", "llm-gateway"], + "license": "MIT", + "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/empty-reply" }, + "magpie": { + "middleware": "./empty-reply.middleware.js" + } +} diff --git a/registry.json b/registry.json index bce5fb7..bf7c508 100644 --- a/registry.json +++ b/registry.json @@ -93,6 +93,8 @@ "summary": { "en": "New API's sensitive-word filter: turn away or mask words and patterns in what you send, and in replies.", "zh": "New API 的敏感词过滤:拒绝或替换你发出的内容和回复里的词与正则。" } }, { "package": "@magpie-community/middleware-think-tags", "name": "Think Tags", "kind": "middleware", "community": true, "summary": { "en": "Take a model's leading , or block out of its reply's text, or put a Chat reply's reasoning into it.", "zh": "去掉回复正文开头的 、 或 思考块,或把 Chat 回复的思考内容放进正文。" } }, + { "package": "@magpie-community/middleware-empty-reply", "name": "Empty Reply", "kind": "middleware", "community": true, + "summary": { "en": "Drop the end of a reply that has reasoning but no text, so Claude Code and Codex retry instead of treating an empty turn as finished. Anthropic and Responses, streamed or whole.", "zh": "丢掉「只有思考、没有正文」回复的结尾,让 Claude Code 和 Codex 重试,而不是把空回合当成正常结束。支持 Anthropic 与 Responses 的流式与整包回复。" } }, { "package": "@magpie-community/agent-nowledge-mem", "name": "Nowledge Mem / AI Now models", "kind": "agent", "community": true, "icon": "https://mem.nowledge.co/favicon.png", "summary": {"en": "Choose Nowledge Mem Default, AI Now and Background models through Magpie. Distinct from gateway-nowledge-mem recall/capture. Disconnect before uninstalling.", "zh": "在 Magpie 管理 Nowledge 的 Default、AI Now 和后台模型;与 gateway-nowledge-mem 的记忆召回、对话导入用途不同。卸载前先断开。"} }, { "package": "@magpie-community/agent-kilo", "name": "Kilo Code", "kind": "agent", "community": true, "icon": "https://github.com/Kilo-Org.png",