diff --git a/README.md b/README.md
index 98e24fb..6c88f9b 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,7 @@ These packages aren't OpenCode plugins. magpie runs them in its gateway, on the
| [model-map](packages/model-map) | New API's 模型重定向 (`model_mapping`): send a model under another name, by name or `/pattern/`; replies name the model asked for |
| [system-prompt](packages/system-prompt) | Your own system prompt on every request, or on some agents' or models', in each API's own place |
| [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 `…` out of a reply's text, or put a Chat reply's `reasoning_content` into it (`thinking_to_content`) |
+| [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`) |
| [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/think-tags/README.md b/packages/think-tags/README.md
index 822d185..fdee999 100644
--- a/packages/think-tags/README.md
+++ b/packages/think-tags/README.md
@@ -10,10 +10,10 @@ Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @m
{ "mode": "strip" }
```
-**`strip`** (the default). Some models (open reasoning models served by vLLM, Ollama and many relays) write their thinking into the reply as `…`. This mode takes that block out, so an agent doesn't keep it in its history and send it back every turn.
+**`strip`** (the default). Some models (open reasoning models served by vLLM, Ollama and many relays) write their thinking into the reply as `…`, `…` or `…`. This mode takes that block out, so an agent doesn't keep it in its history and send it back every turn.
-- Only a block at the start of the text is taken out. A `` the model writes later, in code for example, stays.
-- A `` inside the block in Markdown code (`` `` ``, or a fenced block) is part of the thinking, an example written out, not its end.
+- Only a block at the start of the text is taken out, and it ends at its own close tag. A tag the model writes later, in code for example, stays.
+- A close tag inside the block in Markdown code (`` `` ``, or a fenced block) is part of the thinking, an example written out, not its end.
- A tag split across streamed chunks is still found.
- It works on Anthropic, Chat and Responses replies, streamed or whole.
@@ -22,4 +22,4 @@ Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @m
- This mode works on Chat replies only. An Anthropic thinking block carries a signature, and turned into text it would fail the next turn.
- It changes what the agent keeps and sends back, so it suits a chat client better than a coding agent.
-中文:`strip` 去掉回复开头模型写出的 `…`;`to_content` 把 Chat 回复的 reasoning_content 放进正文(New API 的 thinking_to_content)。
+中文:`strip` 去掉回复开头模型写出的 `…`、`…` 或 `…`;`to_content` 把 Chat 回复的 reasoning_content 放进正文(New API 的 thinking_to_content)。
diff --git a/packages/think-tags/package.json b/packages/think-tags/package.json
index d85e231..e8233c0 100644
--- a/packages/think-tags/package.json
+++ b/packages/think-tags/package.json
@@ -1,7 +1,7 @@
{
"name": "@magpie-community/middleware-think-tags",
- "version": "0.1.1",
- "description": "Take a model's … out of its reply's text, or put a Chat reply's reasoning_content into it (New API's thinking_to_content), as magpie gateway middleware",
+ "version": "0.1.2",
+ "description": "Take a model's leading , or block out of its reply's text, or put a Chat reply's reasoning_content into it (New API's thinking_to_content), as magpie gateway middleware",
"type": "module",
"files": ["think-tags.middleware.js", "README.md"],
"keywords": ["magpie", "magpie-middleware", "new-api", "reasoning", "think", "llm-gateway"],
diff --git a/packages/think-tags/think-tags.middleware.js b/packages/think-tags/think-tags.middleware.js
index 5973d7e..9d2f1fa 100644
--- a/packages/think-tags/think-tags.middleware.js
+++ b/packages/think-tags/think-tags.middleware.js
@@ -5,13 +5,16 @@
// {"mode": "to_content"}
//
// "strip": a model that writes its thinking into the reply as
-// … at the start of its text has that block taken out, so
-// an agent doesn't keep it in its history and send it back each turn. Only
-// a block that opens the text is taken; later on, in code the model
-// writes, stays. Within the block, a in Markdown code (an inline
-// span, or a fenced block) is the thinking's words, an example written out,
-// not its end (magpie-community/plugins#176, as magpie's gateway reads it
-// since #2634). Anthropic, Chat and Responses replies, streamed or whole.
+// …, … or … at the
+// start of its text has that block taken out, so an agent doesn't keep it
+// in its history and send it back each turn. Each block ends at its own
+// close tag. Only a block that opens the text is taken; a tag later on, in
+// code the model writes, stays. Within the block, a close tag in Markdown
+// code (an inline span, or a fenced block) is the thinking's words, an
+// example written out, not its end (magpie-community/plugins#176, as
+// magpie's gateway reads it since #2634). The three tags are magpie's
+// thoughtTags (yetone/magpie#5106, plugins#777). Anthropic, Chat and
+// Responses replies, streamed or whole.
//
// "to_content": a Chat reply's reasoning_content (or reasoning) is put in
// its text as …, for a client that shows only the text.
@@ -22,6 +25,23 @@
const OPEN = ""
const CLOSE = ""
+// TAGS are the tags a leading block of thinking comes between, by its
+// opening tag. No opening tag is a prefix of another's whole tag (
+// and part at the seventh character), so at most one matches.
+const TAGS = { "": "", "": "", "": "" }
+
+// opening is the opening tag t starts with, or "" when none does
+function opening(t) {
+ for (const open in TAGS) if (t.startsWith(open)) return open
+ return ""
+}
+
+// mayOpen is whether t, shorter than a whole tag, may be the start of one
+function mayOpen(t) {
+ for (const open in TAGS) if (t.length < open.length && open.startsWith(t)) return true
+ return false
+}
+
export function onEvent(ev, ctx) {
const toContent = ctx.options && ctx.options.mode === "to_content"
if (toContent) return Array.isArray(ev.choices) ? reasoningToText(ev, ctx.state) : undefined
@@ -115,24 +135,26 @@ function stripItem(it) {
return true
}
-// stripWhole takes a think block off the start of a whole text: up to its
-// first outside Markdown code
+// stripWhole takes a thinking block off the start of a whole text: up to
+// the first of its own close tag outside Markdown code
function stripWhole(t) {
const lead = /^\s*/.exec(t)[0]
- if (!t.startsWith(OPEN, lead.length)) return t
- const rest = t.slice(lead.length + OPEN.length)
- const [at] = findClose({ span: 0, fence: 0, mid: false }, rest, true)
- return at < 0 ? t : rest.slice(at + CLOSE.length).replace(/^\s+/, "")
+ const open = opening(t.slice(lead.length))
+ if (!open) return t
+ const close = TAGS[open]
+ const rest = t.slice(lead.length + open.length)
+ const [at] = findClose({ span: 0, fence: 0, mid: false }, rest, true, close)
+ return at < 0 ? t : rest.slice(at + close.length).replace(/^\s+/, "")
}
-// findClose gives where is first outside Markdown code in s, read
+// findClose gives where close is first outside Markdown code in s, read
// on from the pieces before (m: the open inline span's backticks, the open
// fence's, and whether the line is past its leading spaces), or -1 and how
// much of the end of s to hold back for the next piece: a close tag or a
// run of backticks that may go on there. Unless last; then nothing is
// held. An inline span is taken to end with its line, so a stray backtick
// can't swallow the answer. magpie's mdCode (internal/gateway/chat.go).
-function findClose(m, s, last) {
+function findClose(m, s, last, close) {
for (let j = 0; j < s.length; ) {
const c = s[j]
if (c === "`") {
@@ -155,8 +177,8 @@ function findClose(m, s, last) {
} else if (c === " " || c === "\t") {
j++
} else if (c === "<" && m.span === 0 && m.fence === 0) {
- if (s.startsWith(CLOSE, j)) return [j, 0]
- if (!last && CLOSE.startsWith(s.slice(j))) return [-1, s.length - j]
+ if (s.startsWith(close, j)) return [j, 0]
+ if (!last && close.startsWith(s.slice(j))) return [-1, s.length - j]
m.mid = true
j++
} else {
@@ -167,12 +189,13 @@ function findClose(m, s, last) {
return [-1, 0]
}
-// strip is a stream's text, a piece at a time, without a think block at
-// its start. Its state, by stream: inside the block, text held back that
-// may be the start of a tag (or, inside, a run of backticks), whether the
-// text has begun, and where the block is in Markdown code.
+// strip is a stream's text, a piece at a time, without a thinking block at
+// its start. Its state, by stream: inside the block (and the close tag it
+// waits for), text held back that may be the start of a tag (or, inside, a
+// run of backticks), whether the text has begun, and where the block is in
+// Markdown code.
function strip(state, key) {
- const st = state[key] || (state[key] = { inside: false, carry: "", begun: false, trim: false, code: { span: 0, fence: 0, mid: false } })
+ const st = state[key] || (state[key] = { inside: false, close: "", carry: "", begun: false, trim: false, code: { span: 0, fence: 0, mid: false } })
return (piece) => {
if (st.begun) return piece
let s = st.carry + piece
@@ -180,12 +203,12 @@ function strip(state, key) {
let out = ""
for (;;) {
if (st.inside) {
- const [i, hold] = findClose(st.code, s, false)
+ const [i, hold] = findClose(st.code, s, false, st.close)
if (i < 0) {
st.carry = hold ? s.slice(s.length - hold) : ""
return out
}
- s = s.slice(i + CLOSE.length)
+ s = s.slice(i + st.close.length)
st.inside = false
st.trim = true
continue
@@ -199,13 +222,15 @@ function strip(state, key) {
}
const lead = /^\s*/.exec(s)[0]
const rest = s.slice(lead.length)
- if (rest.startsWith(OPEN)) {
- s = rest.slice(OPEN.length)
+ const open = opening(rest)
+ if (open) {
+ s = rest.slice(open.length)
+ st.close = TAGS[open]
st.inside = true
continue
}
- if (rest.length < OPEN.length && OPEN.startsWith(rest)) {
- // maybe the start of : wait for the next piece
+ if (mayOpen(rest)) {
+ // maybe the start of an opening tag: wait for the next piece
st.carry = s
return out
}
diff --git a/packages/think-tags/think-tags.test.mjs b/packages/think-tags/think-tags.test.mjs
index a192b9f..0f01caf 100644
--- a/packages/think-tags/think-tags.test.mjs
+++ b/packages/think-tags/think-tags.test.mjs
@@ -81,3 +81,48 @@ test("a whole reply with a close only in code keeps its text", () => {
expect(mod.onResponse({ choices: [{ message: { content: t } }] }, ctx)).toBeUndefined()
expect(mod.onResponse({ choices: [{ message: { content: "like\n```\n\n```\n\n\nok" } }] }, ctx).choices[0].message.content).toBe("ok")
})
+
+// #777: the three tags magpie's gateway reads a leading block between
+// (yetone/magpie#5106), each closed by its own end tag, magpie's
+// TestChatThoughtTags cases for
+const tagged = [
+ [" whole", ["Let me thinkHi"], "Hi"],
+ [" split tags", ["Let me", " thinkHi"], "Hi"],
+ [" the open tag a chunk alone", ["", "Let me think", "", "Hi"], "Hi"],
+ [" a character a delta", chars("ab\n\ncd"), "cd"],
+ [" never closed stays thinking", ["half", " a thought whole", ["Greeting.Hello"], "Hello"],
+ [" split tags", ["Let me", " think\n\nHello", " there"], "Hello there"],
+ [" a character a delta", chars("\nabcd"), "cd"],
+ [" split where could still start", ["ab"], "b"],
+ ["a block ends at , not ", ["a bc"], "c"],
+ ["a block ends at , not ", ["a bc"], "c"],
+ ["a block ends at , not ", ["a bc"], "c"],
+ ["a in inline code doesn't end the block", ["use `` here\nok"], "ok"],
+ ["a later on stays", ["Hi x"], "Hi x"],
+ ["a tag that only looks like one stays", ["ab"], "ab"],
+ [" is not ", chars("ab"), "ab"],
+]
+for (const [name, parts, want] of tagged) {
+ test("#777: " + name, () => {
+ expect(streamed(parts)).toBe(want)
+ expect(anthropic(parts)).toBe(want)
+ })
+}
+
+test("#777: whole replies with and ", () => {
+ const ctx = { protocol: "chat", options: {}, state: {}, status: 200 }
+ for (const [t, want] of [
+ ["a\nb", "b"],
+ ["ab", "b"],
+ [" \na\n\n\nb", "b"],
+ ["a bc", "c"],
+ ]) {
+ expect(mod.onResponse({ choices: [{ message: { content: t } }] }, ctx).choices[0].message.content).toBe(want)
+ expect(mod.onResponse({ content: [{ type: "text", text: t }] }, ctx).content[0].text).toBe(want)
+ expect(mod.onResponse({ output: [{ type: "message", content: [{ type: "output_text", text: t }] }] }, ctx).output[0].content[0].text).toBe(want)
+ }
+ // never closed: the text stays as it was, as magpie's afterThought leaves it
+ expect(mod.onResponse({ choices: [{ message: { content: "never closed" } }] }, ctx)).toBeUndefined()
+ expect(mod.onResponse({ choices: [{ message: { content: "a b" } }] }, ctx)).toBeUndefined()
+})
diff --git a/registry.json b/registry.json
index c269045..516f1b7 100644
--- a/registry.json
+++ b/registry.json
@@ -85,7 +85,7 @@
{ "package": "@magpie-community/middleware-word-guard", "name": "Word Guard", "kind": "middleware", "community": true,
"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 … out of its reply's text, or put a Chat reply's reasoning into it.", "zh": "去掉回复正文开头的 …,或把 Chat 回复的思考内容放进正文。" } },
+ "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/agent-kilo", "name": "Kilo Code", "kind": "agent", "community": true, "icon": "https://github.com/Kilo-Org.png",
"summary": { "en": "Kilo Code (kilo.ai) on magpie's Agents page: pick one of magpie's models for it, and switch it off to put its config back.", "zh": "把 Kilo Code(kilo.ai)加到 magpie 的 Agent 页:选择 magpie 的模型,关掉即恢复原来的配置。" } },
{ "package": "@magpie-community/middleware-antigravity-cloak", "name": "Antigravity Cloak", "kind": "middleware", "community": true,