From 9fb09a0f4101fe3c3ffad4d46447dcfb495e4431 Mon Sep 17 00:00:00 2001 From: 1sh1ro <2855020996@qq.com> Date: Wed, 11 Nov 2026 16:07:38 +0800 Subject: [PATCH] orcaterm 0.1.7: a tool call the model writes as text is not sent on as the answer (#969) orcaterm 0.1.7 reads the tool call a model writes as text (DSML, , , in TEXT_CALL_OPEN and TEXT_CALL_MARKS is and its antml:-prefixed form. Our tooling had shown both lines the same. Not a duplicate. Not tried: a real OrcaTerm account (none used from this PR), and an end-to-end magpie gateway run. Edges noted, not blocking: an ask carrying both taskCompletion and question answers with taskCompletion when it is valid JSON, and with question when it is hand-written. A hand-written ask whose option string contains "]" still goes out raw. --- packages/orcaterm/README.md | 22 ++ packages/orcaterm/index.mjs | 358 ++++++++++++++++++++++++++-- packages/orcaterm/package.json | 2 +- packages/orcaterm/request.test.mjs | 94 ++++++++ packages/orcaterm/textcall.test.mjs | 261 ++++++++++++++++++++ 5 files changed, 711 insertions(+), 26 deletions(-) create mode 100644 packages/orcaterm/textcall.test.mjs diff --git a/packages/orcaterm/README.md b/packages/orcaterm/README.md index 1781f39..e650399 100644 --- a/packages/orcaterm/README.md +++ b/packages/orcaterm/README.md @@ -257,6 +257,28 @@ Two consequences worth knowing: written into the conversation as text so nothing is lost, but the agent does the calling itself. - **No images.** `image_url` parts become an `[image]` note. +The models still write calls into the answer text sometimes — DeepSeek's `<||DSML|| invoke name="…">` +blocks, or the `` shape — because the request declares no tools for them to be a call to. +That block is not an answer: the text stops where it begins, and the turn ends with an error frame +(the stream) or a 502 (a request that isn't streamed). Sending it on as prose is what the agent then +reads as its reply, and what the user sees as a turn that stops inside a tag. + +What magpie can do with that error depends on when it arrives. Its gateway holds a stream for +another account only until the first content has gone out, so a reply that opens with the call fails +over, while one that streamed prose first reaches the agent as a mid-stream error and no failover +happens — and the same prompt tends to produce the same call on the next account too. A 502 is a +passing status there, so the same account is asked again before another is tried. + +A call being shown rather than written — inside a code fence or in backticks — is prose, not a call, +and the reply goes on. The rule is trae's, so a client quoting a file, a log or a page about the +format is not answered with an error. + +An `ask` is unwrapped the same way, to its `question` with the `options` under it one per line, and +in every shape it arrives in: a complete object, a hand-written one with a bare line break inside the +question, one the stream ended inside, and one appended after prose — where a `completion`'s envelope +is dropped as bookkeeping but an ask's is the part the user has to answer. Only an `ask` is read this +way; another action's `question` is a note, not an answer. + Token counts are not reported: the upstream returns none, and an estimate passed off as real usage would make both cost and context accounting wrong. A caller that asks for `include_usage` gets the answer without a usage block. diff --git a/packages/orcaterm/index.mjs b/packages/orcaterm/index.mjs index 30ad62c..529848c 100644 --- a/packages/orcaterm/index.mjs +++ b/packages/orcaterm/index.mjs @@ -820,17 +820,40 @@ function stripTrailingEnvelope(text) { .trim() try { const obj = JSON.parse(tail) - if (isActionEnvelope(obj) && raw.slice(0, idx).trim()) return raw.slice(0, idx) + if (isActionEnvelope(obj) && raw.slice(0, idx).trim()) return proseWithTrailingEnvelope(raw.slice(0, idx), tail) } catch { // not JSON from here: it is still the envelope when its answer was // written with bare line breaks or quotes (#564); else try an earlier // opening - if (looseEnvelopeAnswer(tail) !== null && raw.slice(0, idx).trim()) return raw.slice(0, idx) + if (looseEnvelopeAnswer(tail) !== null && raw.slice(0, idx).trim()) { + return proseWithTrailingEnvelope(raw.slice(0, idx), tail) + } } } return raw } +/** + * What a reply leaves when a trailing envelope is taken off it: the prose, and, + * when the envelope is an ask, the question it asks. + * + * A completion's envelope is the model's own bookkeeping for the prose in front + * of it, and is dropped, as it always was. An ask's is not bookkeeping: the + * question is what the user has to answer, and dropping it left the user with + * prose and no way to reply (found in review). + */ +function proseWithTrailingEnvelope(prose, tail) { + let asked = null + try { + const obj = JSON.parse(tail) + asked = isActionEnvelope(obj) ? askAnswer(obj) : null + } catch { + if (/^\{\s*"action"\s*:\s*"ask"\s*,/i.test(tail)) asked = looseEnvelopeAnswer(tail) + } + if (!asked) return prose + return prose.endsWith("\n") ? prose + asked : `${prose}\n${asked}` +} + /** * The answer arrives wrapped in the assistant's own action envelope, not as * plain prose: @@ -875,7 +898,14 @@ function unwrapAnswer(text) { const action = obj.action ?? obj.Action if (typeof action !== "string") return raw const completion = obj.taskCompletion ?? obj.TaskCompletion - return typeof completion === "string" ? completion : raw + if (typeof completion === "string") return completion + // An ask carries its answer in `question`, with the choices the client shows + // under it. Only `taskCompletion` was read here, so the whole object went out + // as the reply. Only an `ask` is read this way: another action's `question` is + // a note rather than an answer, and taking it for one would turn a reply into + // half of itself. + if (action.toLowerCase() !== "ask") return raw + return askAnswer(obj) ?? raw } /** JSON string escapes, for reading the envelope's answer as it arrives. */ @@ -888,6 +918,123 @@ const JSON_ESCAPES = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n" */ const ENVELOPE_TAIL = 48 +// ---- a tool call the model wrote into its text ------------------------------- +// The request goes up with no tools at all (`tools: []`, see toUpstreamBody), yet +// the models behind the assistant write calls into the text anyway: DeepSeek's +// `<||DSML|| invoke name="…">` blocks, and the `` shape the other +// providers' packages already read. Nothing here can run one, so a block that +// reaches the client is not an answer — it is the raw protocol, which the agent +// reads as prose and the user sees as garbage (measured 2026-11-11: three turns +// of `auto/deepseek-v4.1-flash` via orcaterm, one of them 2477 characters). +// +// So the answer is cut at the first opening tag and the turn ends as an error, +// the same way trae (plugins#38) and qoder (plugins#132) treat a call that +// cannot be honoured: a 200 with the block as text is something nothing can fail +// over on. +// +// What magpie can do with that error depends on when it arrives, which is worth +// knowing before choosing this over sending the block on: the gateway holds a +// stream for another account only until the first content has gone out. A reply +// that opens with the call therefore fails over; one that streamed prose first +// reaches the agent as a mid-stream error, with no failover at all, and the same +// prompt tends to produce the same call on the next account too. +const TEXT_CALL_OPEN = new RegExp( + [ + // DeepSeek's, with the bars on each side counted once or twice (the + // observed reply wrote <||DSML||). + String.raw`<\s*\/?\s*[||][\s||]*DSML[\s||]*`, + // and . `` is not one: `_` is a word + // character, so the boundary fails there. + String.raw``, + String.raw``, + String.raw`` looks like on its + * way in, and `\b` fires at the end of any string, so latching on one would cut + * an answer that merely mentions the tag. A tag with text after it is one; at + * `final` the text as it stands is all there will be, and an opener the stream + * ended inside is a call cut short rather than prose. + */ +function textCallAt(s, final = false) { + const m = s.match(TEXT_CALL_OPEN) + if (!m) return -1 + return final || m.index + m[0].length < s.length ? m.index : -1 +} + +/** + * Whether `s` ends inside a code fence or inline code: a tag there is being + * shown, not written. The rule is trae's (packages/trae), so a client that + * quotes a file, a log or a page about the format is not answered with an error. + */ +function quoted(s) { + if ((s.match(/```/g)?.length ?? 0) % 2) return true + const line = s.slice(s.lastIndexOf("\n") + 1).replace(/```/g, "") + return (line.match(/`/g)?.length ?? 0) % 2 === 1 +} + +/** Where a call begins in a reply whose text is all here, or -1 when it is prose. */ +function textCallIn(s) { + const at = textCallAt(s, true) + return at >= 0 && !quoted(s.slice(0, at)) ? at : -1 +} + +/** + * The openers as literal text, for the one thing a regex can't answer while the + * reply is still arriving: whether the `<` that just came in is the start of one. + * Every opener begins with `<`, so a tail running from the last `<` that is a + * prefix of any of these is held back rather than sent. Without that, the two + * bars opening a DSML tag go out and the block behind it is cut off halfway: + * the turn then reads as prose that stops mid-tag, the worst of both. + */ +const TEXT_CALL_MARKS = [ + "<|DSML|", + "<\uFF5CDSML\uFF5C", + "<||DSML||", + "<\uFF5C\uFF5CDSML\uFF5C\uFF5C", + "", + "", + " m.toLowerCase().startsWith(low)) ? at : -1 +} + +/** A call the model wrote as text, with nothing left to send. */ +const TEXT_CALL = + "the model wrote a tool call as text; OrcaTerm was sent no tools, so it can't be run, and it is not sent on as the answer" + /** * The answer inside the assistant's action envelope, for a reply that is still * arriving. @@ -910,13 +1057,56 @@ const ENVELOPE_TAIL = 48 * Plain prose falls out of the same rule — its answer is itself. */ -/** The `"taskCompletion"` value's opening quote in `s`, or -1 while it hasn't shown up. */ -function answerStart(s) { +/** + * The field a reply's answer is in, once its verb is known. + * + * A completion and a review answer in `taskCompletion`; an ask answers in + * `question`, with the choices in `options`. Reading only `taskCompletion` is + * what sent whole ask objects out as replies, and what sent a cut-short ask out + * raw as well: `answerStart`, `looseEnvelopeAnswer` and `stripTrailingEnvelope` + * all followed that one field. + */ +function answerField(s) { + const m = /"action"\s{0,8}:\s{0,8}"([A-Za-z_]+)"/i.exec(String(s ?? "")) + return m && m[1].toLowerCase() === "ask" ? "question" : "taskCompletion" +} + +/** + * An ask's answer: its question, and the choices it offers one per line. + * + * Prose is what an OpenAI client has room for, and the question is the part the + * user has to answer. `null` when the object carries no question of its own; an + * empty string answers nothing, so it counts as none. + */ +function askAnswer(obj) { + const question = obj.question ?? obj.Question + if (typeof question !== "string" || !question.trim()) return null + const raw = obj.options ?? obj.Options + const choices = (Array.isArray(raw) ? raw : []) + .map((o) => { + if (typeof o === "string") return o.trim() + // an option the client shows as a button arrives as an object sometimes; + // its label is the part worth showing + if (o && typeof o === "object") { + for (const k of ["label", "text", "title", "value"]) { + if (typeof o[k] === "string" && o[k].trim()) return o[k].trim() + } + } + return "" + }) + .filter(Boolean) + .map((o) => `- ${o}`) + const q = question.trimEnd() + return choices.length ? `${q}\n\n${choices.join("\n")}` : q +} + +/** The `answerField` value's opening quote in `s`, or -1 while it hasn't shown up. */ +function answerStart(s, field = answerField(s)) { // The field name, matched the way the client matches it — case-insensitively — // and with only the small amount of whitespace the assistant actually emits. // It is checked only after the reply has been established to be an envelope, // so a reply that merely quotes the field name is never read as one. - const m = /"taskCompletion"\s{0,8}:\s{0,8}/i.exec(s) + const m = new RegExp(`"${field}"\\s{0,8}:\\s{0,8}`, "i").exec(s) if (!m) return -1 const j = m.index + m[0].length if (s[j] !== '"') return -1 @@ -1091,6 +1281,8 @@ function createAnswerExtractor() { let closed = false /** Nothing more will arrive: stop holding a tail back. */ let final = false + /** Where the call the model wrote as text begins, once one is seen. */ + let callAt = -1 /** * What the answer should be, given everything received so far. @@ -1108,7 +1300,9 @@ function createAnswerExtractor() { if (loose !== null) return loose // Preserve the decoded prefix if upstream ended inside the answer string. // A closed string followed by prose is an example, so keep it verbatim. - const start = answerStart(raw) + // The field is the verb's: a cut-short ask ends inside `question`, and + // reading only `taskCompletion` sent the raw object out instead. + const start = answerStart(raw, answerField(raw)) if (start >= 0) { const decoded = decodeJsonString(raw.slice(start)) if (!decoded.ended) return decoded.text @@ -1116,7 +1310,17 @@ function createAnswerExtractor() { return stripTrailingEnvelope(raw) } const appended = appendedEnvelopeAt(raw) - if (appended > 0) return raw.slice(0, appended) + if (appended > 0) { + // A completion after prose is bookkeeping; an ask after prose is the + // question, and dropping it left the user with prose and nothing to answer. + const tail = raw + .slice(appended) + .trim() + .replace(/^```(?:json)?\s*/i, "") + .replace(/\s*```$/, "") + .trim() + return proseWithTrailingEnvelope(raw.slice(0, appended), tail) + } // A trailing object is still arriving and could be the envelope: hold from // there rather than show `{"action":` as prose. Once it parses and turns out @@ -1131,8 +1335,34 @@ function createAnswerExtractor() { return raw.slice(0, Math.max(0, raw.length - ENVELOPE_TAIL)) } - const emit = () => { + /** + * The answer, cut where a tool call the model wrote as text begins. + * + * Nothing after that point is the answer: it is the call, and OrcaTerm was + * sent no tools for it to be a call to. Holding it back is also what keeps a + * half-arrived tag from going out: the whole point is that the client never + * sees the opening bars of a DSML invoke as prose. + * + * What is in a code fence or in backticks is being shown, not written, so a + * quoted tag is ordinary text and the reply goes on (trae's rule). + */ + const answerCut = () => { const want = answerSoFar() + const at = textCallAt(want, final) + if (at >= 0 && !quoted(want.slice(0, at))) { + callAt = at + return want.slice(0, at) + } + // Still arriving: the `<` at the tail may be the start of one, so hold it. + // At the end there is nothing more to wait for, and the text as it stands is + // the answer — `the answer is a < b` must not lose its ` < b`. + if (final) return want + const hold = textCallHold(want) + return hold >= 0 ? want.slice(0, hold) : want + } + + const emit = () => { + const want = answerCut() if (want.length <= sent) return "" const out = want.slice(sent) sent = want.length @@ -1161,6 +1391,15 @@ function createAnswerExtractor() { closed = true return out }, + /** + * The call the model wrote as text, once the stream is over: an error string + * when there was one, "" when the reply was an answer. Read after `finish()`, + * so the answer up to the call has already gone out and nothing of the call + * itself has. + */ + textCall() { + return callAt >= 0 ? TEXT_CALL : "" + }, } } @@ -1206,16 +1445,33 @@ function looseEnvelopeAnswer(s) { .replace(/\s*```$/, "") .trim() if (!/^\{\s*"action"\s*:\s*"[A-Za-z_]+"\s*,/i.test(t)) return null - const start = answerStart(t) + const field = answerField(t) + const start = answerStart(t, field) if (start < 0) return null let body = t.slice(start) const close = /\s*\}$/.exec(body) if (!close) return null body = body.slice(0, close.index) - const field = /\s*,\s*"[A-Za-z_]\w*"\s*:\s*(?:"[^"\n\\]*"|[-\w.]+)\s*$/ - for (let m; (m = field.exec(body)); ) body = body.slice(0, m.index) + // Fields written after the answer are not part of it: a short "ph_2": "--", + // and behind an ask's question the "options": [...] when the question was + // written with its bare line breaks and its string never closed. + const after = /\s*,\s*"[A-Za-z_]\w*"\s*:\s*(?:"[^"\n\\]*"|[-\w.]+|\[[^\[\]]*\]|\{[^{}]*\})\s*$/ + for (let m; (m = after.exec(body)); ) body = body.slice(0, m.index) if (!body.endsWith('"')) return null - return decodeLooseString(body.slice(0, -1)) + const answer = decodeLooseString(body.slice(0, -1)) + if (field !== "question") return answer + // The choices are behind the question, still as written: read them when the + // array parses, and answer with both as usual. + const opts = /\s*"options"\s*:\s*(\[[^\[\]]*\])\s*\}/i.exec(t) + let choices = [] + if (opts) { + try { + choices = JSON.parse(opts[1]) + } catch { + choices = [] + } + } + return askAnswer({ question: answer, options: choices }) } /** A JSON string's body as written by hand: escapes decoded, a bare quote or line break kept. */ @@ -1242,8 +1498,23 @@ function decodeLooseString(s) { /** The answer in a whole reply: the envelope's, or the reply itself when it is prose. */ function answerOf(text) { + return answerAndCall(text).text +} + +/** + * The answer in a whole reply, and whether a call written as text was cut out of + * it. + * + * The call has to come from the extractor that did the cutting: answerOf returns + * the prose in front of the block, so scanning that output again for a tag + * always says no. A call carried only as thinking was then handed over as a + * normal answer with a 200, which is the harm this reading exists to stop + * (found in review). + */ +function answerAndCall(text) { const ex = createAnswerExtractor() - return ex.push(String(text ?? "")) + ex.finish() + const body = ex.push(String(text ?? "")) + ex.finish() + return { text: body, call: ex.textCall() } } /** @@ -1454,20 +1725,41 @@ function upstreamToOpenAI(upstreamBody, { model, pacer }) { // has to go out before the "thinking but no text" fallback decides there // was no text at all. const held = skipReasoningFallback ? "" : answer.finish() - if (held) { - push(chunk({ content: held })) - emitText += held.length - } + // A tool call the model wrote as text: the answer stops where it begins + // and the turn ends as an error frame, so magpie asks again or of another + // account. Sent on as text it would be prose that runs into a DSML + // invoke block: neither an answer nor a call (plugins#38, plugins#132; + // orcaterm had no reader at all). + let written = skipReasoningFallback ? "" : answer.textCall() + let tail = held // Upstream sent thinking but no text: turn the thinking into text // before closing, so the client doesn't show a blank answer. // The error path (skipReasoningFallback) must not — otherwise the error // text is pushed out by the thinking, and what the user finally sees is // "let me think" instead of "quota used up". - // Thinking can be the envelope too (#564): its answer is the text. - if (!skipReasoningFallback && emitText === 0 && sentReasoning) { - const text = answerOf(sentReasoning) || sentReasoning - push(chunk({ content: text })) - emitText = text.length + // Thinking can be the envelope too (#564): its answer is the text, and + // it can carry the call as well, so it passes the same guard. The call + // is read from the extractor that finds it, not from its own cut output: + // scanning that always said no, so a call behind a line of thinking went + // out as the answer with a 200. + if (!skipReasoningFallback && emitText === 0 && !written && !tail && sentReasoning) { + const ans = answerAndCall(sentReasoning) + if (ans.call) { + tail = ans.text + written = TEXT_CALL + } else { + tail = ans.text || sentReasoning + } + } + if (tail) { + push(chunk({ content: tail })) + emitText += tail.length + } + if (written) { + closed = true + push(`data: ${JSON.stringify({ error: { message: `OrcaTerm: ${written}`, type: "api_error", code: "text_tool_call" } })}\n\n`) + controller.close() + return } closed = true push(chunk({}, reason)) @@ -1642,9 +1934,20 @@ async function upstreamToJSON(upstreamBody, { model, pacer }) { // by the same extractor the streaming path uses, so the two can't drift apart. const extractor = createAnswerExtractor() const visible = extractor.push(content) + extractor.finish() - // An empty text can't go up blank: the thinking is used first, then a note + // A tool call the model wrote as text, the same as in the streamed path: a 502 + // magpie asks again on, not a 200 whose answer is the raw protocol. + const written = extractor.textCall() + if (written) return openaiError(502, `OrcaTerm: ${written}`, "text_tool_call") + // An empty text can't go up blank: the thinking is used first, then a note. + // The thinking carries the call too, and the call is read from the extractor + // that finds it: scanning its cut output always said no, and a thinking-only + // call went out as a 200 with the answer. let finalContent = visible.trimEnd() - if (!finalContent && reasoning) finalContent = answerOf(reasoning).trimEnd() || reasoning + if (!finalContent && reasoning) { + const ans = answerAndCall(reasoning) + if (ans.call) return openaiError(502, `OrcaTerm: ${TEXT_CALL}`, "text_tool_call") + finalContent = (ans.text || reasoning).trimEnd() + } if (!finalContent) finalContent = "(OrcaTerm returned an empty reply)" const message = { role: "assistant", content: finalContent } if (reasoning) message.reasoning_content = reasoning @@ -2387,6 +2690,11 @@ export const _internal = { answerOf, stripTrailingEnvelope, createAnswerExtractor, + textCallAt, + textCallHold, + textCallIn, + quoted, + TEXT_CALL, csrfCode, parseTicket, cookieHeader, diff --git a/packages/orcaterm/package.json b/packages/orcaterm/package.json index a0cacca..ef352ab 100644 --- a/packages/orcaterm/package.json +++ b/packages/orcaterm/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-orcaterm-auth", - "version": "0.1.6", + "version": "0.1.7", "description": "OrcaTerm (Tencent Cloud 遨驰终端) AI quota as an OpenAI-compatible provider for magpie and OpenCode", "type": "module", "main": "./opencode.mjs", diff --git a/packages/orcaterm/request.test.mjs b/packages/orcaterm/request.test.mjs index 256ca39..17393a5 100644 --- a/packages/orcaterm/request.test.mjs +++ b/packages/orcaterm/request.test.mjs @@ -121,3 +121,97 @@ test("the answer is unwrapped from the action envelope, alone or after prose", ( // and a reply that is not an envelope is left alone expect(_internal.unwrapAnswer("用 {花括号} 表示集合")).toBe("用 {花括号} 表示集合") }) + +// An `ask` keeps its answer in `question`, not `taskCompletion`, so the whole +// object used to go out as the reply — braces, `ph_1` and all (seen live +// 2026-11-11, the model asking which of five options to take). +test("an ask is unwrapped to its question and choices", () => { + const ask = JSON.stringify({ + action: "ask", + ph_1: "--", + question: "要处理哪个目标?", + options: ["检查运行状态", "排查服务异常", ""], + }) + expect(_internal.unwrapAnswer(ask)).toBe("要处理哪个目标?\n\n- 检查运行状态\n- 排查服务异常") + // no choices to show: the question alone + expect(_internal.unwrapAnswer(JSON.stringify({ action: "ask", question: "继续吗?", options: [] }))).toBe("继续吗?") + // an ask with no question is not an answer to unwrap + const empty = JSON.stringify({ action: "ask", ph_1: "--" }) + expect(_internal.unwrapAnswer(empty)).toBe(empty) + // another action's `question` is not one: only an ask is read this way + const review = JSON.stringify({ action: "review", question: "这是审查的备注", tool: {} }) + expect(_internal.unwrapAnswer(review)).toBe(review) +}) + +// And it holds while the ask streams in, one character at a time: the answer +// the client builds out of the deltas is the same one, and no brace of it goes +// out. +test("a streamed ask reaches the client as its answer, not as its JSON", async () => { + const ask = JSON.stringify({ + action: "ask", + ph_1: "--", + question: "要处理哪个目标?", + options: ["检查运行状态", "排查服务异常"], + }) + const resp = _internal.upstreamToOpenAI( + new ReadableStream({ + start(c) { + const all = `data: ${JSON.stringify({ content: ask, reasoningContent: "", type: "ai", code: 0 })}\n\ndata: [DONE]\n\n` + for (const ch of all) c.enqueue(new TextEncoder().encode(ch)) + c.close() + }, + }), + { model: "m" }, + ) + let content = "" + for (const line of (await resp.text()).split("\n")) { + if (!line.startsWith("data: ") || line.trim() === "data: [DONE]") continue + content += JSON.parse(line.slice(6)).choices?.[0]?.delta?.content ?? "" + } + expect(content).toBe("要处理哪个目标?\n\n- 检查运行状态\n- 排查服务异常") + expect(content).not.toContain("{") +}) + +// The three shapes the reviewer listed as still going out raw. +const streamedAsk = async (raw, size = 3) => { + const all = `data: ${JSON.stringify({ content: raw, reasoningContent: "", type: "ai", code: 0 })}\n\ndata: [DONE]\n\n` + const pieces = [] + for (let i = 0; i < all.length; i += size) pieces.push(all.slice(i, i + size)) + const resp = _internal.upstreamToOpenAI( + new ReadableStream({ + start(c) { + for (const p of pieces) c.enqueue(new TextEncoder().encode(p)) + c.close() + }, + }), + { model: "m" }, + ) + let content = "" + for (const line of (await resp.text()).split("\n")) { + if (!line.startsWith("data: ") || line.trim() === "data: [DONE]") continue + content += JSON.parse(line.slice(6)).choices?.[0]?.delta?.content ?? "" + } + return content +} + +// 1. Written by hand, with a bare line break in the question, the way a long +// answer comes (#564). Only `taskCompletion` was read this loosely. +test("a hand-written ask with a bare line break still comes out as its answer", async () => { + const raw = '{"action": "ask", "ph_1": "--", "question": "Which one?\nPick:", "options": ["a", "b"]}' + expect(await streamedAsk(raw)).toBe("Which one?\nPick:\n\n- a\n- b") +}) + +// 2. The stream ends inside the question: a completion keeps its decoded prefix, +// and the ask must do the same. +test("an ask the stream ended inside keeps its question", async () => { + const raw = '{"action":"ask","ph_1":"--","question":"Which target?","options":["a"]}' + const cut = raw.slice(0, raw.indexOf("target?") + "target?".length) + expect(await streamedAsk(cut)).toBe("Which target?") +}) + +// 3. Prose, then the ask appended: dropping the envelope is right for a +// completion, and wrong for an ask — the question is what the user answers. +test("an ask appended after prose keeps the question", async () => { + const raw = 'I found two targets.\n{"action":"ask","ph_1":"--","question":"Which target?","options":["a","b"]}' + expect(await streamedAsk(raw)).toBe("I found two targets.\nWhich target?\n\n- a\n- b") +}) diff --git a/packages/orcaterm/textcall.test.mjs b/packages/orcaterm/textcall.test.mjs new file mode 100644 index 0000000..523cb6e --- /dev/null +++ b/packages/orcaterm/textcall.test.mjs @@ -0,0 +1,261 @@ +// A tool call the model wrote into the answer text, when the request carried no +// tools at all for it to be a call to. Measured 2026-11-11 on +// `auto/deepseek-v4.1-flash` through magpie: three turns came back as the raw +// block, one of them 2477 characters, and the agent read it as prose. The bytes +// below are that reply's, opener for opener. +// +// Nothing here can honour a call, so the block must not go out as the answer: +// the text stops where the call begins, and the turn ends with the error frame +// magpie fails over on — as trae (plugins#38) and qoder (plugins#132) already do. +import { test, expect } from "bun:test" +import { _internal } from "./index.mjs" + +process.env.ORCATERM_NO_PACE = "1" + +// DeepSeek writes the tag with two full-width bars on each side: +// <||DSML|| invoke name="…">. Kept as an escape so the file stays ASCII. +const BAR = "\uFF5C\uFF5C" +const CALL = [ + `<${BAR}DSML${BAR} calls>`, + `<${BAR}DSML${BAR} invoke name="pwsh">`, + `<${BAR}DSML${BAR} parameter name="command" string="true">Get-ChildItem`, + `<${BAR}DSML${BAR} parameter name="description" string="true">List files`, + ``, + ``, + "", + "```json", + '{"action": "review", "ph_1": "--"}', + "```", +].join("\n") + +const frame = (content, reasoningContent = "") => + `data: ${JSON.stringify({ content, reasoningContent, type: "ai", code: 0 })}\n\n` + +const sse = (frames) => + new ReadableStream({ + start(c) { + for (const f of frames) c.enqueue(new TextEncoder().encode(f)) + c.close() + }, + }) + +const pieces = (s, n) => { + const out = [] + for (let i = 0; i < s.length; i += n) out.push(s.slice(i, i + n)) + return out +} + +/** What the client would read as the answer, and the error frame if one came. */ +function read(text) { + let content = "" + let error = null + for (const line of text.split("\n")) { + if (!line.startsWith("data: ") || line.trim() === "data: [DONE]") continue + const j = JSON.parse(line.slice(6)) + if (j.error) error = j.error + content += j.choices?.[0]?.delta?.content ?? "" + } + return { content, error } +} + +async function asked(content) { + const res = _internal.upstreamToOpenAI(sse([frame(content)]), { model: "deepseek-chat-latest" }) + return read(await res.text()) +} + +test("a reply that is only a text-form call is not sent out as the answer", async () => { + const { content, error } = await asked(CALL) + expect(content).toBe("") + expect(error?.code).toBe("text_tool_call") +}) + +for (const size of [1, 7, 50, 4096]) { + test(`the same call, in ${size}-character frames, never reaches the answer`, async () => { + const res = _internal.upstreamToOpenAI(sse(pieces(CALL, size).map(frame)), { model: "m" }) + const { content, error } = read(await res.text()) + expect(content).toBe("") + expect(error?.code).toBe("text_tool_call") + }) +} + +test("prose before the call is still the answer, and the call still ends the turn", async () => { + const { content, error } = await asked(`Here is what I found.\n${CALL}`) + expect(content).toBe("Here is what I found.\n") + expect(error?.code).toBe("text_tool_call") +}) + +test("a block is refused the same way", async () => { + const { content, error } = await asked('Sure.\n{"name":"read","arguments":{"path":"a"}}') + expect(content).toBe("Sure.\n") + expect(error?.code).toBe("text_tool_call") +}) + +// A call cut short at the end of the stream is still a call: the opening tag is +// the whole signal, whatever follows it. +test("a call the stream ended inside is refused too", async () => { + const { content, error } = await asked(`Reading.\n<${BAR}DSML${BAR} invoke name="pwsh">\n<${BAR}DSML${BAR} param`) + expect(content).toBe("Reading.\n") + expect(error?.code).toBe("text_tool_call") +}) + +// The guard must not eat ordinary prose: a `<` that starts no tag stays, and so +// does a tag-shaped word that never opens a block. +test("a lone < in prose is answered, not held back", async () => { + const { content, error } = await asked("if a < b then the answer is a.\n") + expect(content).toBe("if a < b then the answer is a.\n") + expect(error).toBeNull() +}) + +test("a reply that mentions the words tool_call without a tag is left alone", async () => { + const { content, error } = await asked("The tool_call field is described in the schema.\n") + expect(content).toBe("The tool_call field is described in the schema.\n") + expect(error).toBeNull() +}) + +test("a reply that ends on < keeps it", async () => { + const { content, error } = await asked("a <") + expect(content).toBe("a <") + expect(error).toBeNull() +}) + +// The 48-char envelope hold makes what's judged end on an arbitrary character, +// and `` looks like on its way in: a word +// boundary at the end of that window used to latch and kill the answer +// (yetone's review). Every frame size, and the sentence naming the tag. +const MENTIONS = "The response carries a `` array, and the client reads it before it dispatches anything." +for (const size of [1, 3, 47, 4096]) { + test(`a tag-shaped word in prose survives ${size}-character frames`, async () => { + const res = _internal.upstreamToOpenAI(sse(pieces(MENTIONS, size).map((c) => frame(c))), { model: "m" }) + const { content, error } = read(await res.text()) + expect(content).toBe(MENTIONS) + expect(error).toBeNull() + }) +} + +test("and the same sentence is not cut by the non-streamed path", async () => { + const res = await _internal.upstreamToJSON(sse([frame(MENTIONS)]), { model: "m" }) + expect(res.status).toBe(200) + expect((await res.json()).choices[0].message.content).toBe(MENTIONS) +}) + +// The same sentence without backticks, which is what the guard actually turns +// on: with them it is "quoted" and shown for that reason, so the boundary rule +// was never tested (yetone's review: breaking it left 0 red). +const PLAIN = "The response carries a array, and the client reads it before it dispatches anything." +for (const size of [1, 3, 47, 4096]) { + test(`an unquoted tag-shaped word survives ${size}-character frames`, async () => { + const res = _internal.upstreamToOpenAI(sse(pieces(PLAIN, size).map((c) => frame(c))), { model: "m" }) + const { content, error } = read(await res.text()) + expect(content).toBe(PLAIN) + expect(error).toBeNull() + }) +} + +test("and so does , which is not a call at all", async () => { + const text = "Each message has a field beside its role, as the schema says.\n" + const { content, error } = await asked(text) + expect(content).toBe(text) + expect(error).toBeNull() +}) + +// The tag is written in whatever case the model felt like; the hold list is +// compared lowercased, so the reader must be too. +test("an upper-case block is refused", async () => { + const { content, error } = await asked('Sure.\n{"name":"read"}') + expect(content).toBe("Sure.\n") + expect(error?.code).toBe("text_tool_call") +}) + +test("an upper-case block split across frames is refused", async () => { + const res = _internal.upstreamToOpenAI( + sse(pieces('{"name":"read"}', 1).map((c) => frame(c))), + { model: "m" }, + ) + const { content, error } = read(await res.text()) + expect(content).toBe("") + expect(error?.code).toBe("text_tool_call") +}) + +// A call being shown, not written: inside a code fence or inline code it is +// prose, and trae's reader has always treated it that way (yetone's review). +const FENCED = [ + "Here is the format:", + "", + "```xml", + '{"name":"read","arguments":{"path":"a"}}', + "```", + "", + "That is all.", +].join("\n") + +for (const size of [1, 5, 4096]) { + test(`a fenced call is shown, not refused, in ${size}-character frames`, async () => { + const res = _internal.upstreamToOpenAI(sse(pieces(FENCED, size).map((c) => frame(c))), { model: "m" }) + const { content, error } = read(await res.text()) + expect(content).toBe(FENCED) + expect(error).toBeNull() + }) +} + +test("a call in backticks is shown too", async () => { + const text = "Use `` to call a tool.\n" + const { content, error } = await asked(text) + expect(content).toBe(text) + expect(error).toBeNull() +}) + +test("a fenced call is shown by the non-streamed path as well", async () => { + const res = await _internal.upstreamToJSON(sse([frame(FENCED)]), { model: "m" }) + expect(res.status).toBe(200) + expect((await res.json()).choices[0].message.content).toBe(FENCED) +}) + +// Thinking is turned into the answer when no text came, so a call carried only +// as thinking must not be handed over as prose either. +test("a call that arrives only as thinking still ends the turn", async () => { + const res = _internal.upstreamToOpenAI(sse([frame("", CALL)]), { model: "m" }) + const { content, error } = read(await res.text()) + expect(content).toBe("") + expect(error?.code).toBe("text_tool_call") +}) + +// And it does so whatever the call sits behind. `answerOf` runs its own +// extractor, which already cuts at the call, so scanning its output for a tag +// said no and the call went out as the answer — the exact harm this change is +// for (yetone's review, must-fix 1). +test("a call behind a line of thinking still ends the turn", async () => { + const res = _internal.upstreamToOpenAI(sse([frame("", "Let me look at the files.\n" + CALL)]), { model: "m" }) + const { content, error } = read(await res.text()) + expect(content).toBe("Let me look at the files.\n") + expect(error?.code).toBe("text_tool_call") +}) + +test("the same thinking-only call is a 502 when the request isn't streamed", async () => { + const res = await _internal.upstreamToJSON(sse([frame("", "Let me look at the files.\n" + CALL)]), { model: "m" }) + expect(res.status).toBe(502) +}) + +test("a call inside a thinking envelope is refused too", async () => { + const envelope = '{"action":"completion","ph_1":"--","taskCompletion":"Reading.\n' + CALL + '"}' + const res = _internal.upstreamToOpenAI(sse([frame("", envelope)]), { model: "m" }) + const { content, error } = read(await res.text()) + expect(content).toBe("Reading.\n") + expect(error?.code).toBe("text_tool_call") +}) + +// A fenced call in the thinking is being shown, not written: the quoted rule +// holds on this path as well, so it is turned into the answer as usual. +test("a fenced call in the thinking is shown, not refused", async () => { + const res = _internal.upstreamToOpenAI(sse([frame("", FENCED)]), { model: "m" }) + const { content, error } = read(await res.text()) + expect(content).toBe(FENCED) + expect(error).toBeNull() +}) + +// The whole reply as one non-streamed body: magpie asks again on a 502. +test("a request that isn't streamed ends as 502, not as a 200 carrying the call", async () => { + const res = await _internal.upstreamToJSON(sse([frame(CALL)]), { model: "m" }) + expect(res.status).toBe(502) + const body = await res.json() + expect(body.error.message).toContain("tool call as text") +}) \ No newline at end of file