From 2fc8945de447c98e3a1df84760a6f47e9c10f07a Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 20:36:11 +0800 Subject: [PATCH] orcaterm 0.1.2: a new upstream conversation per request, and the envelope unwrapped wherever it shows (#564) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ferocknew saw a reply come out as the assistant's own envelope ({"action":"completion","ph_1":"--","taskCompletion":"…"}) and another session's transcript end with OrcaTerm's output format. Cause: the plugin kept one upstream conversationId per account and session (and "default" when no session was named). OrcaTerm keeps a conversation's turns by its id, while the plugin already sends the whole transcript, so a reused id put upstream's copy of earlier turns (the RE_ACT output format and raw envelopes) in front of each request; two sessions on one id (no session id, or magpie's first-user-turn hash shared by a title request or a same-opening chat) read each other's. Three more routes let an envelope through: one written with bare line breaks or quotes is not JSON and went out whole; an envelope sent only as thinking was the fallback text as it was; and an earlier envelope the agent kept in its history went back up as the assistant's turn, which the model then imitated. Now every request gets a fresh cid--orcaterm (the user id stays per session), a hand-written envelope is read for its answer (looseEnvelopeAnswer), the thinking fallback and the history turns go through the same extractor. The plugin adds nothing to other providers' requests: its only non-auth hook is chat.headers, gated on providerID. Run on mote: bun test in packages/orcaterm 110/110 pass; bun scripts/check.mjs orcaterm ok; bun test scripts 3/3. leak.test.mjs at the old index.mjs: 4 of 7 red (bare line breaks, thinking-only, history turn, shared conversation id); the reporter's literal envelope itself already unwrapped when clean. Not tried: a real OrcaTerm account (none here), so upstream's keeping of turns by conversationId is from the plugin's own measurements, not re-run. --- packages/orcaterm/README.md | 22 ++++- packages/orcaterm/index.mjs | 147 +++++++++++++++++++++------- packages/orcaterm/leak.test.mjs | 163 ++++++++++++++++++++++++++++++++ packages/orcaterm/package.json | 2 +- 4 files changed, 293 insertions(+), 41 deletions(-) create mode 100644 packages/orcaterm/leak.test.mjs diff --git a/packages/orcaterm/README.md b/packages/orcaterm/README.md index cc78aeb..6acd57f 100644 --- a/packages/orcaterm/README.md +++ b/packages/orcaterm/README.md @@ -230,8 +230,12 @@ The earlier turns are **not** sent as `historyMessages` — they go in as a plai `input.input`, and `historyMessages` is always empty. Two reasons, both measured: a history entry's kind lives in `type` (`human`/`ai`), not `role`, and the wrong shape fails inside upstream's own handler with `[type] is not a function`; and with the right shape the text comes back echoed into the -answer. A transcript is what the assistant reads reliably — and magpie hands every request a fresh -session id, so nothing can rely on server-side conversation state anyway. +answer. A transcript is what the assistant reads reliably. + +Every request goes up as a new upstream conversation. OrcaTerm keeps a conversation's turns by its +id, so an id used twice put upstream's copy of the earlier turns — the assistant's own output format +and its JSON envelopes — in front of a transcript that already had them, and two sessions that +shared an id read each other's (#564). The upstream answers in SSE frames whose `content` is that frame's addition (and whose `fullContent`, when present, is everything so far); those become OpenAI deltas, with reasoning kept in @@ -239,7 +243,10 @@ The upstream answers in SSE frames whose `content` is that frame's addition (and If a reply starts like the assistant's JSON envelope, its text is held until the reply ends so a JSON example followed by more explanation cannot be mistaken for metadata. Plain prose and -reasoning still stream normally. Leading whitespace and JSON fences are accepted. +reasoning still stream normally. Leading whitespace and JSON fences are accepted, and so is an +envelope whose answer has bare line breaks or quotes, which isn't JSON. A reply that comes only as +thinking, and an earlier reply an agent sends back in the envelope's shape, are read for their +answer the same way. Two consequences worth knowing: @@ -281,6 +288,7 @@ bun test | `usage.test.mjs` | which `usageStats` row is the AI allowance | | `audit.test.mjs` | invalid callback bodies; envelope whitespace and examples; EOF error frames; JSON error codes; reader cleanup; read failures and cancellation | | `identity.test.mjs` | stable identity across QR re-sign-ins with rotated tokens or changed nicknames; distinct users staying separate; token user ID fallback; refusing missing identity; renewal and account-scoped backfill preserving credentials and metadata | +| `leak.test.mjs` | #564: the reported envelope, hand-written envelopes that aren't JSON, an envelope sent as thinking or kept in the history, a new upstream conversation on every request, and nothing added to another provider's request | | `review.test.mjs` | the cases the reviews turned up: a reply containing `{"action": …}` is not truncated (including one character at a time, and one that ends mid-envelope); the JSON 429 is a 429; pacers are per account; only nine models are listed; a chat makes exactly one request and it is not `/conversation`; and `/cb` refuses a foreign `Origin`, a rebinding page, and a `state` it did not issue | `chunks.test.mjs`'s cancel case fails if `releaseUpstream()` is removed, so the leak stays fixed. @@ -322,8 +330,12 @@ GLM、Kimi。provider id:`orcaterm`。 插件会先读流头,把配额用完/限流回成 429、登录失效回成 401 并标记账号,这样 magpie 才会换账号 或让账号歇着,而不是把失败当成一次正常回答。限流还有一条**不走 SSE** 的路径:HTTP 200 + `{"code":429,…}` 的 JSON,同样回成 429,并让该账号的限流器进入冷却。 -- **多轮上下文**:magpie 每个请求都给新的 session id,所以服务端会话状态靠不住;之前的轮次以 - transcript 形式写进 `input.input`,`historyMessages` 恒为空。 +- **多轮上下文**:之前的轮次以 transcript 形式写进 `input.input`,`historyMessages` 恒为空; + 每个请求在上游都是一个新会话,不复用会话 id —— 复用时上游会把它自己存的旧轮次(助手的输出格式和 + JSON 信封)再加一遍,两个会话共用一个 id 时还会读到对方的(#564)。 +- **回复信封**:上游回复是助手自己的 JSON 信封(`{"action":"completion","taskCompletion":"…"}`), + 插件只把 `taskCompletion` 交出去;信封里有未转义的换行或引号、只出现在思考里、或被 agent 当作历史 + 回复再发回来时,也一样只取答案。 - **不做工具调用、不支持图片**:助手在服务端跑自己的工具,插件只做文本往返。 ## License diff --git a/packages/orcaterm/index.mjs b/packages/orcaterm/index.mjs index 004f861..6a803a5 100644 --- a/packages/orcaterm/index.mjs +++ b/packages/orcaterm/index.mjs @@ -586,7 +586,10 @@ function toUpstreamBody(body, { conversationId, userId }) { continue } if (role === "assistant") { - const t = textOf(msg.content).trim() + // An earlier reply the agent kept in the envelope's shape goes up as its + // answer: sent back as the assistant's own turn, the model took it as + // the format to answer in (#564). + const t = answerOf(textOf(msg.content)).trim() const calls = Array.isArray(msg.tool_calls) ? msg.tool_calls : [] if (t) turns.push({ role: "assistant", content: t }) if (calls.length) { @@ -818,7 +821,10 @@ function stripTrailingEnvelope(text) { const obj = JSON.parse(tail) if (isActionEnvelope(obj) && raw.slice(0, idx).trim()) return raw.slice(0, idx) } catch { - /* not a whole object from here; try an earlier opening */ + // 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) } } return raw @@ -1097,6 +1103,8 @@ function createAnswerExtractor() { if (couldBeEnvelope(raw)) { if (!final) return "" if (isEnvelope(raw)) return unwrapAnswer(raw) + const loose = looseEnvelopeAnswer(raw) + 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) @@ -1172,6 +1180,71 @@ function isEnvelope(s) { } +/** + * The answer of an envelope that is not JSON, or null when `s` (all of it) + * isn't one. + * + * The assistant writes the envelope itself, and a long Markdown answer comes + * with its line breaks written as they are and its quotes left bare (#564): + * + * {"action": "completion", "ph_1": "--", "taskCompletion": "## 结论 + * + * 把 "案例模块" 改成…"} + * + * `JSON.parse` refuses that, and the whole object went out as the reply. The + * shape is still unmistakable: it opens with the action key, it carries + * `taskCompletion`, and nothing follows its closing brace. So the answer is + * everything from the field's opening quote to the last quote before that + * brace (after any short fields written after it, such as `"ph_2": "--"`), + * with the escapes that are there decoded and everything else kept. + */ +function looseEnvelopeAnswer(s) { + const t = String(s ?? "") + .trim() + .replace(/^```(?:json)?\s*/i, "") + .replace(/\s*```$/, "") + .trim() + if (!/^\{\s*"action"\s*:\s*"[A-Za-z_]+"\s*,/i.test(t)) return null + const start = answerStart(t) + 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) + if (!body.endsWith('"')) return null + return decodeLooseString(body.slice(0, -1)) +} + +/** A JSON string's body as written by hand: escapes decoded, a bare quote or line break kept. */ +function decodeLooseString(s) { + let out = "" + for (let i = 0; i < s.length; i++) { + const ch = s[i] + const next = s[i + 1] + if (ch !== "\\" || next === undefined) { + out += ch + continue + } + if (next === "u" && /^[0-9a-f]{4}$/i.test(s.slice(i + 2, i + 6))) { + out += String.fromCharCode(parseInt(s.slice(i + 2, i + 6), 16)) + i += 5 + continue + } + // an escape JSON doesn't have (a Windows path's `\U`) stays as written + out += JSON_ESCAPES[next] ?? ch + next + i += 1 + } + return out +} + +/** The answer in a whole reply: the envelope's, or the reply itself when it is prose. */ +function answerOf(text) { + const ex = createAnswerExtractor() + return ex.push(String(text ?? "")) + ex.finish() +} + /** * Upstream error codes → the status we answer magpie with. * @@ -1389,9 +1462,11 @@ function upstreamToOpenAI(upstreamBody, { model, pacer }) { // 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) { - push(chunk({ content: sentReasoning })) - emitText = sentReasoning.length + const text = answerOf(sentReasoning) || sentReasoning + push(chunk({ content: text })) + emitText = text.length } closed = true push(chunk({}, reason)) @@ -1568,7 +1643,7 @@ async function upstreamToJSON(upstreamBody, { model, pacer }) { const visible = extractor.push(content) + extractor.finish() // An empty text can't go up blank: the thinking is used first, then a note let finalContent = visible.trimEnd() - if (!finalContent && reasoning) finalContent = reasoning + if (!finalContent && reasoning) finalContent = answerOf(reasoning).trimEnd() || reasoning if (!finalContent) finalContent = "(OrcaTerm returned an empty reply)" const message = { role: "assistant", content: finalContent } if (reasoning) message.reasoning_content = reasoning @@ -1730,44 +1805,49 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => { } /** - * Each account's own state: conversation ids and temporary settings. + * Each account's own state: the user id each session asks as. * Keyed by the sign-in fingerprint rather than the provider — with several * accounts on magpie, none of them gets in another's way. */ const sessions = new Map() /** - * Session key = account fingerprint + magpie session id. - * Upstream keeps conversations by conversationId, so with the account - * fingerprint alone, different chats on one account would share context. - * There is a cap as well, so signing in over and over doesn't pile up without + * Session key = account fingerprint + magpie session id, for the user id + * only. There is a cap, so signing in over and over doesn't pile up without * limit. * - * The conversation id is built the way the web client builds it - * (`generateConversationId`, module 72535): `cid-` plus `-` - * for any assistant that isn't lighthouse, plus `-` for any mode that - * isn't RE_ACT. This plugin always asks as orcaterm in RE_ACT, so no mode - * suffix. + * The conversation id is new on every request (#564). OrcaTerm keeps a + * conversation's turns by its id, and this plugin already sends the whole + * transcript each time, so an id used twice made upstream put its own copy + * of the earlier turns in front: the assistant's output protocol and its + * JSON envelopes. And the id was shared more widely than one chat: every + * request with no session id fell on "default", and magpie's conversation + * id is a hash of the first user turn, so two sessions that open the same + * way (or a title request beside its chat) shared one upstream + * conversation, and one session's protocol turns ended up at the end of + * another's. + * + * It is built the way the web client builds one (`generateConversationId`, + * module 72535): `cid-` plus `-` for any assistant that + * isn't lighthouse, plus `-` for any mode that isn't RE_ACT. This + * plugin always asks as orcaterm in RE_ACT, so no mode suffix. */ const sessionFor = (auth, sid) => { const fp = `${fingerprint(auth)}:${sid || "default"}` - let s = sessions.get(fp) - if (!s) { + let userId = sessions.get(fp) + if (!userId) { if (sessions.size > 64) sessions.clear() - s = { - conversationId: `cid-${randomUUID()}-${ASSISTANT.orcaterm}`, - userId: uid("u-"), - } - sessions.set(fp, s) + userId = uid("u-") + sessions.set(fp, userId) } - return s + return { conversationId: `cid-${randomUUID()}-${ASSISTANT.orcaterm}`, userId } } /** * There is deliberately no `POST /conversation` here. * * The web client registers a conversation once and lets upstream keep the - * thread. This plugin cannot do the same: magpie hands every request a fresh - * session id, so `sessionFor` mints a new conversation id per request, and + * thread. This plugin cannot do the same: `sessionFor` mints a new + * conversation id per request (#564), and * registering each one filled the user's OrcaTerm history with an entry per * request — visible to them, and pointless, because the id is never reused. * @@ -2225,16 +2305,11 @@ export const OrcaTermAuthPlugin = async ({ client } = {}) => { }, - // ---- conversation header: carry magpie's session id to fetch, to split - // conversations upstream --------------------------------------------------- - // magpie's input.sessionID stays the same across the turns of one - // conversation, so conversationId is derived from it: different chats on one - // account don't share context. - // - // When magpie passes no session id — it does not for every caller — the - // fallback has to be steady too: a fresh id per request opened a new - // conversation upstream every turn and the thread was lost, while the same - // turns went through when the plugin was driven directly. + // ---- session header: carry magpie's session id to fetch ---------------- + // It picks the user id a session's requests go up under. It no longer + // picks the upstream conversation: that is new on every request, since + // the transcript carries the thread (#564). Only this provider's requests + // get it; nothing is added to any other provider's. "chat.headers": async (input, output) => { if (input?.model?.providerID !== PROVIDER) return try { @@ -2274,6 +2349,8 @@ export const _internal = { isActionEnvelope, appendedEnvelopeAt, unwrapAnswer, + looseEnvelopeAnswer, + answerOf, stripTrailingEnvelope, createAnswerExtractor, csrfCode, diff --git a/packages/orcaterm/leak.test.mjs b/packages/orcaterm/leak.test.mjs new file mode 100644 index 0000000..66fb4e3 --- /dev/null +++ b/packages/orcaterm/leak.test.mjs @@ -0,0 +1,163 @@ +import { test, expect } from "bun:test" +import { _internal, OrcaTermAuthPlugin } from "./index.mjs" + +// magpie-community/plugins#564 (ferocknew): a session's reply came out as the +// assistant's own action envelope, and another session's transcript ended with +// OrcaTerm's output protocol. These are the reporter's literal bytes. +const ANSWER = "## 一句话结论\n\n这个提交(2b40776,把案例模块改成「构造时注入数据库连接」的重构)xxxxxx....." +const REPORTED = `{ + "action": "completion", + "ph_1": "--", + "taskCompletion": "## 一句话结论\\n\\n这个提交(2b40776,把案例模块改成「构造时注入数据库连接」的重构)xxxxxx....." +}` +const REPORTED_COMPACT = '{"action":"completion","ph_1":"--","taskCompletion":"## 一句话结论\\n\\n这个提交(2b40776,把案例模块改成「构造时注入数据库连接」的重构)xxxxxx....."}' + +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 +} + +async function streamed(res) { + const text = await res.text() + let content = "" + for (const line of text.split("\n")) { + if (!line.startsWith("data: ") || line === "data: [DONE]") continue + content += JSON.parse(line.slice(6)).choices[0].delta.content ?? "" + } + return content +} + +for (const [name, raw] of [ + ["pretty-printed", REPORTED], + ["compact", REPORTED_COMPACT], +]) { + test(`the reported envelope (${name}) comes out as its answer, streamed and not`, async () => { + for (const n of [1, 3, 17, raw.length]) { + const res = _internal.upstreamToOpenAI(sse(pieces(raw, n).map((p) => frame(p))), { model: "m" }) + expect(await streamed(res)).toBe(ANSWER) + } + const res = await _internal.upstreamToJSON(sse([frame(raw)]), { model: "m" }) + expect((await res.json()).choices[0].message.content).toBe(ANSWER) + }) +} + +// The assistant writes its own JSON, and a long Markdown answer comes with the +// line breaks written as they are and quotes left unescaped. That is not JSON, +// and the whole object went out as the reply. +test("an envelope whose answer has raw line breaks and bare quotes is still unwrapped", async () => { + const answer = '## 一句话结论\n\n这个提交把 "案例模块" 改成\t构造时注入。\n- 第一点' + const raw = `{\n "action": "completion",\n "ph_1": "--",\n "taskCompletion": "${answer}"\n}` + expect(() => JSON.parse(raw)).toThrow() + for (const n of [1, 5, raw.length]) { + const res = _internal.upstreamToOpenAI(sse(pieces(raw, n).map((p) => frame(p))), { model: "m" }) + expect(await streamed(res)).toBe(answer) + } + const res = await _internal.upstreamToJSON(sse([frame(raw)]), { model: "m" }) + expect((await res.json()).choices[0].message.content).toBe(answer) +}) + +// Upstream sent the envelope as thinking and no text: the reply fell back to +// the thinking, envelope and all. +test("an envelope that arrives as thinking only falls back to its answer, not its JSON", async () => { + const res = _internal.upstreamToOpenAI(sse([frame("", REPORTED)]), { model: "m" }) + expect(await streamed(res)).toBe(ANSWER) + const j = await _internal.upstreamToJSON(sse([frame("", REPORTED)]), { model: "m" }) + expect((await j.json()).choices[0].message.content).toBe(ANSWER) +}) + +// An agent that kept an earlier envelope in its history sent it back up as the +// assistant's turn, and the model then answered in the same shape. +test("an earlier assistant turn in the envelope's shape goes up as its answer", () => { + const up = _internal.toUpstreamBody( + { + messages: [ + { role: "user", content: "review 2b40776" }, + { role: "assistant", content: REPORTED }, + { role: "user", content: "thanks, and the tests?" }, + ], + }, + { conversationId: "cid-1", userId: "u-1" }, + ) + expect(up.input.input).not.toContain('"action"') + expect(up.input.input).not.toContain("taskCompletion") + expect(up.input.input).toContain("assistant: ## 一句话结论") +}) + +// OrcaTerm keeps a conversation's turns by its id. The plugin sends the whole +// transcript every time, so an id reused across requests added upstream's copy +// of earlier turns — the assistant's protocol and its envelopes, and with no +// session id (or the same one) another session's too. +test("no two requests share an upstream conversation, whatever session they name", async () => { + const ids = [] + const realFetch = globalThis.fetch + globalThis.fetch = async (_url, init) => { + ids.push(JSON.parse(init.body).conversationId) + return new Response(frame("ok") + "data: [DONE]\n\n", { status: 200, headers: { "content-type": "text/event-stream" } }) + } + try { + const plugin = await OrcaTermAuthPlugin({ client: { app: { log: () => {} } } }) + const loader = await plugin.auth.loader(async () => ({ type: "api", key: "uin=o1234567890; skey=SECRET123456" })) + const ask = async (session) => { + const headers = { "content-type": "application/json" } + const h = {} + await plugin["chat.headers"]({ sessionID: session, model: { providerID: "orcaterm" } }, { headers: h }) + Object.assign(headers, h) + const res = await loader.fetch("https://lightai.cloud.tencent.com/assistant/chat", { + method: "POST", + headers, + body: JSON.stringify({ model: "TokenHub/glm-5.3", stream: false, messages: [{ role: "user", content: "hi" }] }), + }) + await res.text() + } + await ask("") + await ask("") + await ask("magpie-a083915a") + await ask("magpie-a083915a") + await ask("magpie-other") + expect(ids.length).toBe(5) + expect(new Set(ids).size).toBe(5) + for (const id of ids) expect(id).toMatch(/^cid-[0-9a-f-]{36}-orcaterm$/) + } finally { + globalThis.fetch = realFetch + } +}) + +// The plugin's only hook on other providers' requests is chat.headers, and it +// adds nothing to them. +test("another provider's request gets nothing from this plugin", async () => { + const plugin = await OrcaTermAuthPlugin({ client: { app: { log: () => {} } } }) + const out = { headers: {} } + await plugin["chat.headers"]({ sessionID: "s", model: { providerID: "anthropic" } }, out) + expect(out.headers).toEqual({}) + const hooks = Object.keys(plugin).filter((k) => k !== "auth" && k !== "config") + expect(hooks).toEqual(["chat.headers"]) +}) + +test("prose followed by a hand-written envelope that isn't JSON keeps the prose only", async () => { + const prose = "结论:重构把连接改成构造时注入。\n\n" + const raw = prose + '```json\n{"action": "completion", "ph_1": "--", "taskCompletion": "结论:\n"注入"连接"}\n```' + for (const n of [1, 7, raw.length]) { + const res = _internal.upstreamToOpenAI(sse(pieces(raw, n).map((p) => frame(p))), { model: "m" }) + expect(await streamed(res)).toBe(prose) + } +}) + +test("a hand-written envelope keeps what it doesn't escape, and an object that isn't one is left alone", () => { + expect(_internal.looseEnvelopeAnswer('{"action": "completion", "taskCompletion": "C:\\Users\\me "a"\n\\u4e2d", "ph_2": "--"}')).toBe('C:\\Users\\me "a"\n中') + expect(_internal.looseEnvelopeAnswer('{"type": "completion", "taskCompletion": "x\ny"}')).toBe(null) + expect(_internal.looseEnvelopeAnswer('{"action": "completion", "taskCompletion": "x\ny"} and then prose')).toBe(null) + const example = 'Here is the shape:\n{"action": "SAVE", "content": "a\nb"}' + expect(_internal.answerOf(example)).toBe(example) +}) diff --git a/packages/orcaterm/package.json b/packages/orcaterm/package.json index bd4c343..8443899 100644 --- a/packages/orcaterm/package.json +++ b/packages/orcaterm/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-orcaterm-auth", - "version": "0.1.1", + "version": "0.1.2", "description": "OrcaTerm (Tencent Cloud 遨驰终端) AI quota as an OpenAI-compatible provider for magpie and OpenCode", "type": "module", "main": "./index.mjs",