From fdc5002319e6435613214858e41faaefa4a33b81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8B=82=E6=B0=97=E3=81=AEMad=20Scientist=E9=B3=B3?= =?UTF-8?q?=E5=87=B0=E9=99=A2=E8=83=B8=E9=87=9D?= Date: Fri, 30 Oct 2026 00:44:34 +0800 Subject: [PATCH] orcaterm 0.1.0: Tencent Cloud OrcaTerm's assistant as a provider, with WeChat QR sign-in (#460) New package @magpie-community/opencode-orcaterm-auth 0.1.0: Tencent Cloud OrcaTerm's own AI assistant (its monthly question allowance) as provider `orcaterm`, with WeChat QR sign-in (the same sign-in OrcaTerm's clients use) or a pasted console cookie. Credentials go only to Tencent's hosts (orcaterm.com, *.cloud.tencent.com) and WeChat's widget (open.weixin.qq.com, res.wx.qq.com). The nine models OrcaTerm's picker offers are listed; others resolve only as aliases. Per-account pacing at 10 chats/min, maxConcurrency 1; a JSON or SSE refusal inside a 200 becomes 429/401/502. registry.json gains its entry. Author: hg1048596-pixel (#460, replaces #422) The last review's three points are fixed at this head: the index.mjs header, toUpstreamBody and plugin-entry comments describe the code; the README's License links the package's own LICENSE; /cb accepts a bridge error without a code and shows it, and a later scan still finishes. Run at a75a2ae0fb554b3cb6ae879d5571b5dd7b2300a7 on mote (macOS, Bun 1.4.2), HOME=$(mktemp -d) as CI: - bun test packages/orcaterm: 88 pass, 0 fail - bun test (whole repo): 3624 pass, 8 skip, 0 fail - bun scripts/check.mjs: every package ok, orcaterm included - npm pack: 5 files (index.mjs, wechat.mjs, README.md, LICENSE, package.json); the extracted index.mjs imports with bun and its plugin returns provider orcaterm; node scripts/dist.mjs packs opencode-orcaterm-auth@0.1.0 - The earlier review's fake-upstream script against the packed package: 27 of 27 (JSON 429 with and without rate-limit words, SSE quota, rate and sign-in errors, envelopes in stream and JSON mode, per-account pacing, bearer headers, nine listed models, credentials only to lightai.cloud.tencent.com) - The /cb script against the packed wechat.mjs: foreign, missing and rebinding origins 403, wrong state refused, right origin and state finish the sign-in Broken by hand: requiring a string code again turns "callback preserves bridge errors without a code" red (87 pass, 1 fail). Not tried: a real OrcaTerm account, so neither the QR sign-in nor the real upstream. --- packages/orcaterm/LICENSE | 21 + packages/orcaterm/README.md | 318 ++++ packages/orcaterm/audit.test.mjs | 187 +++ packages/orcaterm/chunks.test.mjs | 121 ++ packages/orcaterm/index.mjs | 2278 ++++++++++++++++++++++++++++ packages/orcaterm/package.json | 20 + packages/orcaterm/peek.test.mjs | 138 ++ packages/orcaterm/request.test.mjs | 123 ++ packages/orcaterm/review.test.mjs | 351 +++++ packages/orcaterm/signin.test.mjs | 113 ++ packages/orcaterm/stream.test.mjs | 108 ++ packages/orcaterm/usage.test.mjs | 76 + packages/orcaterm/wechat.mjs | 481 ++++++ registry.json | 14 +- 14 files changed, 4348 insertions(+), 1 deletion(-) create mode 100644 packages/orcaterm/LICENSE create mode 100644 packages/orcaterm/README.md create mode 100644 packages/orcaterm/audit.test.mjs create mode 100644 packages/orcaterm/chunks.test.mjs create mode 100644 packages/orcaterm/index.mjs create mode 100644 packages/orcaterm/package.json create mode 100644 packages/orcaterm/peek.test.mjs create mode 100644 packages/orcaterm/request.test.mjs create mode 100644 packages/orcaterm/review.test.mjs create mode 100644 packages/orcaterm/signin.test.mjs create mode 100644 packages/orcaterm/stream.test.mjs create mode 100644 packages/orcaterm/usage.test.mjs create mode 100644 packages/orcaterm/wechat.mjs diff --git a/packages/orcaterm/LICENSE b/packages/orcaterm/LICENSE new file mode 100644 index 0000000..e6bc674 --- /dev/null +++ b/packages/orcaterm/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 magpie-community contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/orcaterm/README.md b/packages/orcaterm/README.md new file mode 100644 index 0000000..fdd3534 --- /dev/null +++ b/packages/orcaterm/README.md @@ -0,0 +1,318 @@ +# @magpie-community/opencode-orcaterm-auth + +Signs in to **Tencent Cloud OrcaTerm** (腾讯云遨驰终端) and serves its AI assistant's models — +DeepSeek, Hunyuan, GLM and Kimi — in OpenCode and magpie. Provider id: `orcaterm`. + +> **Unofficial.** This package is not affiliated with, authorised or endorsed by Tencent; its +> names and marks belong to their owners. It talks to the non-public APIs the OrcaTerm web +> client uses and identifies itself the way that client does, which may not be allowed by +> Tencent's terms, and those APIs may change at any time. Use it at your own risk, including +> the risk of restrictions on your account — see [Before you use this](#before-you-use-this-the-terms). + +## Install + +```sh +magpie plugin add @magpie-community/opencode-orcaterm-auth +magpie plugin login orcaterm +``` + +or install it from magpie's Plugins tab and sign in there. + +## Before you use this: the terms + +**This plugin uses OrcaTerm's built-in AI allowance from outside OrcaTerm, and Tencent's terms do +not clearly permit that.** Read this part before signing in. + +### What the cookie pair actually is + +`uin` and `skey` are **not an OrcaTerm token**. They are the **full Tencent Cloud console session** +— the same pair that gets you into the console, your CVM and Lighthouse instances, your billing, +your API keys. Anything holding them can act as you across Tencent Cloud, not just in OrcaTerm. + +So the account you risk is not "an OrcaTerm account". It is **the account that holds your servers +and your billing**, and Tencent Cloud's service agreement 5.8 lets Tencent limit, suspend or +terminate that account and freeze it. **Do not use an account that owns production resources.** +If you want to try this, use a separate account with nothing behind it. + +**The QR sign-in below does not have this problem.** It yields OrcaTerm's own OAuth access token, +which is confined to this product and expires in two hours — it is not a console session and cannot +reach your servers or billing. Nothing in this section applies to it. The cookie pair is the +fallback for when scanning is not possible, and it is the one that carries the risk above. + +**Every host it touches, and what for:** + +| Host | When | What goes there | +| --- | --- | --- | +| `lightai.cloud.tencent.com` | every chat | the credential, the message text | +| `api.orcaterm.cloud.tencent.com` | reading the allowance (cookie sign-ins only) | the credential | +| `orcaterm.com` | QR sign-in, and renewing its token | the credential, and the OAuth `code` | +| `res.wx.qq.com` | QR sign-in page | nothing — it serves WeChat's `wxLogin.js` | +| `open.weixin.qq.com` | the QR widget's iframe | the `appid`, `redirect_uri` and `state` OrcaTerm issued | + +Three of those are Tencent's own; the last two belong to WeChat, and only the QR sign-in page loads +them — a cookie sign-in never does. Nothing goes anywhere else. The plugin does not share, resell or +pool quota, and it makes no attempt to evade anti-abuse checks. None of that changes the paragraph +above. + +### Why the terms do not clearly allow it + +OrcaTerm's user agreement reserves everything it has not explicitly granted: + +- **2.3** — "本条及本协议其他条款未明示授权的其他一切权利仍由腾讯保留,您在行使这些权利时须另外取得腾讯的书面许可。" +- **2.1** — defines the service as OrcaTerm itself (remote connection, sign-in, file management). + The built-in AI allowance (1000 questions a month on the basic edition, 6000 on professional) is a + resource entitlement attached to the product; it is never described as an API callable from + elsewhere. + +Related clauses that this use touches: 3.5.3 (using data without permission), 3.5.5 (probing or +testing the platform), 3.5.7 (gaining advantage through a bug), 6.5(4) (using the service in a way +Tencent has not authorised). Tencent Cloud's service agreement 5.7(3) covers unauthorised access and +interference. + +The consequences are concrete: 4.4.1 and 7.2 allow Tencent to limit features, suspend the account +or terminate the service, and Tencent Cloud's agreement 5.8 allows the same plus freezing the +account. + +**One detail worth weighing:** OrcaTerm's official OpenAPI exposes session and sign-in calls — +`DescribeInstancesFeatureStatus`, `GenerateAuthLoginUrl`, `GetUserInfo`, `StartSSHTerminalSession`, +`StartRDPTerminalSession`, `VerifyOAuthUser` — and **no AI question endpoint at all**. The allowance +is not built to be called from outside the product. + +What is clearly allowed: asking OrcaTerm's assistant questions inside OrcaTerm's own web, desktop or +mini-program clients; and attaching **your own** API key through OrcaTerm's custom-model setting +(officially: "自定义 AI 模型不会消耗 AI 问答次数额度"). + +**So: if you use this plugin, the risk is yours.** This project does not claim Tencent permits it, +does not resell or share quota, and is not affiliated with Tencent. If your account matters to you, +use the custom-model path with your own key instead, or ask Tencent for written permission first. + +### On the assistant's own tools + +The assistant is attached to the user's servers, and it runs in RE_ACT mode. This plugin sends no +tools, no MCP servers and no approved tools, which is what keeps it to answering questions — but +that is the request being empty of tools, not proof the assistant can do nothing on its own side. +`hideToolMessage` is therefore left `false`, so that if anything does run, its trace stays in the +reply where you can see it. + +## Sign-in + +Two credentials can drive the assistant, and they are **not** equal in scope: + +| Credential | Comes from | Lifetime | Authority | +| --- | --- | --- | --- | +| **WeChat OAuth access token** (recommended) | scanning a QR code | 2 hours, renewed automatically | OrcaTerm only | +| `uin` + `skey` | your Tencent Cloud **console session** | until you sign out of the console | your whole Tencent Cloud account | + +The QR route is preferred: it is the same sign-in the OrcaTerm clients use, and the token it yields +cannot touch anything outside OrcaTerm. Either kind is accepted — the plugin tells them apart by the +key's shape. + +### Scan a QR code (recommended) + +```sh +magpie plugin login orcaterm # choose the first entry +``` + +magpie opens a page with a WeChat QR code on it — by default +, or another port if 4080 is taken, in which case the URL it shows is +the real one. Scan it and the plugin carries on by itself; there is no URL to copy. + +How the callback is captured: the page embeds WeChat's `qrconnect` widget through the official +`wxLogin.js` with `self_redirect: true`. After a scan, the return to +`orcaterm.com/oauth/wechat/bridge?code=…&state=…` happens inside the widget's **own inner iframe**, +so that page's `window.parent` is still our page and its `postMessage` arrives. Without +`self_redirect`, WeChat navigates the top window instead, which replaces the page and loses the +message — that is the one detail the whole flow hangs on. + +Behind a remote deploy the page listens on the server's loopback and your browser cannot reach it: + +```sh +ssh -L 4080:127.0.0.1:4080 +``` + +`ORCATERM_CAPTURE_PORT`, `ORCATERM_CAPTURE_HOST` and `ORCATERM_CAPTURE_BASE` override the address. +`ORCATERM_CAPTURE_HOST` is what the socket binds to, and it defaults to the loopback; setting it to +`0.0.0.0` means anyone who can reach the machine can load the sign-in page, and the `state` it carries +is in that page's HTML — so only do that behind something that restricts who can connect. A wildcard +bind accepts the page from this machine's own interface addresses, so reaching it by LAN address +works; every other origin is refused. + +The token is renewed before it expires through `OAuthRefreshToken`, so a normal session never asks +you to scan again. + +### Paste the cookie pair (fallback) + +1. Sign in at in a browser (the AI allowance follows the Tencent Cloud + sign-in, not a separate OrcaTerm one). +2. Open DevTools → **Application** → **Cookies** → `https://cloud.tencent.com`. +3. Copy the values of **`uin`** and **`skey`**. +4. In magpie, run `magpie plugin login orcaterm` and pick the paste entry, as + `uin=o1234567890; skey=AbCdEf…`. + +Both halves are required. The AI endpoint reads the pair as one credential: with only `skey`, or +with `p_uin`/`p_skey` under those names, it answers `NEED_UIN_AND_SKEY` and never looks further. + +## Models + +Use only what OrcaTerm's own model picker offers. The ids are **namespaced** — `TokenHub/` +and `Hunyuan3/` — and that prefix is the whole difference: sent bare, `glm-5.3` answers +`LLM(glm-5.3) is not loaded`, while `TokenHub/glm-5.3` answers. + +| id | label in the picker | reasoning | +| --- | --- | --- | +| `TokenHub/deepseek-v4-pro` | Deepseek-V4-Pro | ✓ | +| `TokenHub/deepseek-v4-flash` | DeepSeek-V4-Flash | | +| `TokenHub/deepseek-v4.1-flash` | DeepSeek-V4.1-Flash | | +| `TokenHub/glm-5.3` | GLM-5.3 | ✓ | +| `TokenHub/glm-5.3-flash` | GLM-5.3-Flash | | +| `TokenHub/glm-5.2` | GLM-5.2 | | +| `TokenHub/kimi-k3` | Kimi-K3 | | +| `Hunyuan3/hy3` | Hy3 | ✓ | +| `Hunyuan3/hy4-preview` | Hy4-preview | ✓ | + +**Do not use the others.** A few more ids answer on the endpoint but **cannot be selected in +OrcaTerm's own model picker** — `glm-4.7-thinking`, `kimi-k2-thinking`, `kimi-k2.5`, +`kimi-k2.5-thinking`, `kimi-latest`, `hunyuan-turbos`, `qwen3`, `deepseek-reasoner`. Calling them +means going around the product's own interface, which the service may treat as abnormal use, and +**your account may be restricted for it**. They are therefore **not offered in `provider.models`**; +they resolve only so that a config written against them keeps working. A new config should use the +nine above. + +Aliases work too (`deepseek`, `kimi`, `glm`, `hunyuan`), as do the picker labels themselves +(`Deepseek-V4-Pro`, `GLM-5.3`, `Hy3-preview`…), and the older ids (`deepseek-chat-latest`, +`glm-4.7`, `kimi-k2`, `hunyuan-t1`) resolve to their current equivalents. + +Context and output limits are estimates: the upstream publishes no window size per model. + +## When the upstream refuses + +OrcaTerm answers a refusal **inside the stream** — `data: [ERROR]: …` — with HTTP 200 still on the +status line. Taken at face value a used-up allowance would look like a normal reply, and magpie +would neither fail over to another account nor let this one rest. So the plugin reads the head of +the stream first (`peekAnswer`, as `packages/codearts` does) and answers with a real status. + +A rate limit is the one refusal that arrives **outside** the stream as well: a burst is answered +`HTTP 200` with a plain JSON body, `{"code":429,"data":null,"message":"Rate limit exceeded: +chat-rpm"}`. That path is classified by the same table, so it is a 429 and not a 502 — and it also +puts this account's pacer into its cool-down. + +| Upstream says | Status returned | What magpie does | +| --- | --- | --- | +| `quota`, `额度`, `次数已用完`, `余额不足` | **429** | fail over to the next account, rest this one | +| `rate limit`, `频繁`, `限流`, or the JSON body `{"code":429,…}` | **429** | same, and this account's pacer cools down | +| `NEED_UIN_AND_SKEY`, `VERIFY_SKEY_UIN_FAILED`, `VERIFY_LOGIN_FAILED`, `VERIFY_USER_FAILED` | **401** + `X-Magpie-Sign-In: expired` | mark the account, stop sending to it | +| anything else (model unavailable, internal error) | **502** | fail over | +| the connection dies mid-stream | the stream is errored, `statusCode` 499 (cancelled) or 502 | fail over | +| the connection dies without streaming | **499** / **502** | fail over | + +A refusal that arrives after the answer has started is delivered as a stream error rather than as +text, so it still counts as a failure. + +### Rate limit + +Ten chats a minute per account. The budget is the account's, not the plugin's, so it paces itself: +a sliding window holds a request until there is room, a 429 puts **that account's** pacer into a +cool-down rather than every account's, and `maxConcurrency` is 1. `ORCATERM_CHAT_RPM` lowers the +budget to leave room for the desktop client; `ORCATERM_NO_PACE=1` turns pacing off. + +## Requests + +magpie's gateway turns whatever protocol the agent speaks into a Chat Completions body and hands it +to this plugin's `fetch`. That body becomes one assistant turn: a conversation id, a user id, the last +user message as `input.input`, and any system text as a prefix, since the assistant has no system +role. + +The earlier turns are **not** sent as `historyMessages` — they go in as a plain transcript inside +`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. + +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 +`reasoning_content`. + +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. + +Two consequences worth knowing: + +- **No tool calls.** The assistant runs its own tools server-side and never emits `tool_calls`, so + the models are declared with `tool_call: false`. A client's tool calls and their results are + 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. + +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. + +## Quota + +`auth.usage` reads `DescribeUserBillingStatus` and reports the `hunyuan_ai` row — the AI answer +allowance, 1000 questions a month on the basic edition — as `amount / limit` with its reset date. +The other rows there (session sharing, secrets, space) are not shown: they are unrelated resources, +and session sharing's unlimited `-1` would read as an exhausted account. + +## Tests + +```sh +bun test +``` + +88 tests over eight files. No test signs in and none talks to Tencent: the chat tests replace `fetch`, and the only sockets are loopback listeners that the `/cb` tests stand up themselves. + +| file | what it holds | +| --- | --- | +| `signin.test.mjs` | the cookie shapes, and what each refusal means for the account | +| `request.test.mjs` | the Chat Completions → assistant body translation | +| `stream.test.mjs` | the SSE → OpenAI chunk conversion | +| `chunks.test.mjs` | frames that look cumulative but aren't; a frame split across chunks; a reset mid-stream; cancelling reaching the upstream | +| `peek.test.mjs` | a refusal read from the head of the stream becoming 429/401/502, and a real answer surviving the peek | +| `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 | +| `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. + +## 中文 + +在 OpenCode 和 magpie 里使用**腾讯云遨驰终端(OrcaTerm)** AI 助手的模型:DeepSeek、混元、 +GLM、Kimi。provider id:`orcaterm`。 + +> **非官方插件**:与腾讯、腾讯云及 OrcaTerm(遨驰终端)没有任何关联,也未获其授权或认可。 +> 插件调用的是 OrcaTerm 网页端使用的非公开接口,并以与官方客户端相同的方式标识自己, +> 这可能不符合腾讯云的服务条款,接口也可能随时变更。使用风险(包括账号受限)由使用者自行承担。 + +- **登录**:首选**微信扫码**(`magpie plugin login orcaterm` 第一项),拿到的是 OrcaTerm 自己的 + OAuth accessToken —— 两小时有效、自动续期、只能用于 OrcaTerm。备选是粘贴 `uin` + `skey`: + 这两个是**腾讯云控制台的完整会话 cookie**,不是 OrcaTerm 专用令牌 —— 拿到它们就能在腾讯云范围内 + 以你的身份操作,包括你的服务器和账单。**不要用持有生产资源的账号**,想试就用一个名下没有东西的独立账号。 +- **条款**:OrcaTerm 用户协议 2.3 保留所有未明示授权的权利,2.1 把服务限定为 OrcaTerm 本身; + 内置 AI 额度是绑在产品上的资源权益,从未被授权为可外部调用的接口。相关条款还有 3.5.3、 + 3.5.5、3.5.7、6.5(4) 与腾讯云服务协议 5.7(3),后果见 4.4.1、7.2 与 5.8(可限功能、封号、终止服务)。 + 一个细节:官方 OpenAPI 有会话与登录接口,**唯独没有任何 AI 问答接口**。 +- **模型**:只用 OrcaTerm 模型选择器里能选到的那九个 —— `TokenHub/deepseek-v4-pro`、 + `TokenHub/deepseek-v4-flash`、`TokenHub/deepseek-v4.1-flash`、`TokenHub/glm-5.3`、 + `TokenHub/glm-5.3-flash`、`TokenHub/glm-5.2`、`TokenHub/kimi-k3`、`Hunyuan3/hy3`、 + `Hunyuan3/hy4-preview`。**id 必须带命名空间前缀**,否则上游答 `LLM(x) is not loaded`。 + **其余 id 不要用**(如 `qwen3`、`deepseek-reasoner`、`kimi-latest`、`hunyuan-turbos`、 + `glm-4.7-thinking` 等):它们在选择器里选不到,属于绕过界面调用,**有封号风险**。 +- **会连到哪些主机**:`lightai.cloud.tencent.com`(每次对话)、 + `api.orcaterm.cloud.tencent.com`(读额度,仅 cookie 登录时)、`orcaterm.com`(扫码登录与续期); + 另有 `res.wx.qq.com`(提供微信的 `wxLogin.js`)与 `open.weixin.qq.com`(二维码 iframe), + 这两个只在扫码登录时加载,cookie 登录不会碰。除此之外不发往任何地方。 +- **额度**:`magpie quota` 显示每月问答次数(基础版 1000 次)与重置日期。扫码登录的账号读不到 + 配额(额度接口只认控制台会话),这不影响使用。 +- **失败会如实报错**:上游把失败写在 SSE 里(`data: [ERROR]: …`),HTTP 状态仍是 200。 + 插件会先读流头,把配额用完/限流回成 429、登录失效回成 401 并标记账号,这样 magpie 才会换账号 + 或让账号歇着,而不是把失败当成一次正常回答。限流还有一条**不走 SSE** 的路径:HTTP 200 + + `{"code":429,…}` 的 JSON,同样回成 429,并让该账号的限流器进入冷却。 +- **多轮上下文**:magpie 每个请求都给新的 session id,所以服务端会话状态靠不住;之前的轮次以 + transcript 形式写进 `input.input`,`historyMessages` 恒为空。 +- **不做工具调用、不支持图片**:助手在服务端跑自己的工具,插件只做文本往返。 + +## License + +MIT. See this package's [LICENSE](./LICENSE), included in the published package. diff --git a/packages/orcaterm/audit.test.mjs b/packages/orcaterm/audit.test.mjs new file mode 100644 index 0000000..3fc1251 --- /dev/null +++ b/packages/orcaterm/audit.test.mjs @@ -0,0 +1,187 @@ +import { test, afterEach } from "bun:test" +import assert from "node:assert/strict" +import { OrcaTermAuthPlugin, _internal as i } from "./index.mjs" + +const realFetch = globalThis.fetch +afterEach(() => { globalThis.fetch = realFetch }) +process.env.ORCATERM_NO_PACE = "1" +const bytes = (s) => new TextEncoder().encode(s) +const frame = (content) => `data: ${JSON.stringify({ content })}\n\n` +const body = (s) => new ReadableStream({ start(c) { c.enqueue(bytes(s)); c.close() } }) +const extract = (s, split = false) => { + const e = i.createAnswerExtractor() + let out = "" + for (const chunk of split ? [...s] : [s]) out += e.push(chunk) + return out + e.finish() +} +async function ask(response, stream = false, signal) { + globalThis.fetch = async () => response + const plugin = await OrcaTermAuthPlugin() + const loader = await plugin.auth.loader(async () => ({ key: "uin=o1234567890; skey=AUDIT_FAKE_ONLY" })) + return loader.fetch("https://unused.invalid", { + body: JSON.stringify({ stream, messages: [{ role: "user", content: "hi" }] }), signal, + }) +} + +test("whole envelopes allow leading whitespace and fences in any chunk shape", () => { + const envelope = '{"action":"completion","taskCompletion":"Hello"}' + for (const raw of [envelope, " \n" + envelope, "\n```json\n" + envelope + "\n```", " ```\n" + envelope + "\n``` "]) { + for (const split of [false, true]) assert.equal(extract(raw, split), "Hello") + } +}) + +test("a leading envelope-shaped example followed by prose survives intact", () => { + const raw = '{"action":"completion","taskCompletion":"example"} followed by explanation' + for (const split of [false, true]) assert.equal(extract(raw, split), raw) + const e = i.createAnswerExtractor() + let out = e.push('{"action":"completion","taskCompletion":"example"}') + out += e.push(" followed by explanation") + e.finish() + assert.equal(out, raw) +}) + +test("capitalised trailing envelopes use the same recognition as whole envelopes", () => { + const raw = 'Some prose.\n{"Action":"completion","TaskCompletion":"ignored"}' + for (const split of [false, true]) assert.equal(extract(raw, split), "Some prose.\n") +}) + +test("a long partial envelope opening never leaks before its action key arrives", () => { + const prefix = "A normal answer.\n" + const raw = prefix + "{" + " ".repeat(120) + '"action":"completion","taskCompletion":"ignored"}' + assert.equal(extract(raw, true), prefix) + assert.equal(extract(raw), prefix) +}) + +test("a whitespace-prefixed envelope yields the same non-streaming answer", async () => { + const res = await i.upstreamToJSON(body(frame('\n{"action":"completion","taskCompletion":"Hello"}') + "data: [DONE]\n\n"), { model: "m" }) + assert.equal((await res.json()).choices[0].message.content, "Hello") +}) + +for (const stream of [false, true]) { + test(`an initial error without a final newline is classified (stream=${stream})`, async () => { + const res = await ask(new Response("data: [ERROR]: quota exhausted", { headers: { "content-type": "text/event-stream" } }), stream) + assert.equal(res.status, 429) + }) + + test(`DONE cancels and releases a still-open upstream (stream=${stream})`, async () => { + let cancelled = false + const upstream = new ReadableStream({ + start(c) { c.enqueue(bytes(frame("answer") + "data: [DONE]\n\n")) }, + cancel() { cancelled = true }, + }) + const res = stream ? i.upstreamToOpenAI(upstream, { model: "m" }) : await i.upstreamToJSON(upstream, { model: "m" }) + await res.text() + assert.equal(cancelled, true) + assert.equal(upstream.locked, false) + }) + + test(`loader releases the peek reader after DONE (stream=${stream})`, async () => { + let cancelled = false + const upstream = new ReadableStream({ + start(c) { c.enqueue(bytes(frame("answer") + "data: [DONE]\n\n")) }, + cancel() { cancelled = true }, + }) + const res = await ask(new Response(upstream, { headers: { "content-type": "text/event-stream" } }), stream) + await res.text() + assert.equal(cancelled, true) + assert.equal(upstream.locked, false) + }) + + test(`a peek read failure returns an OpenAI 502 (stream=${stream})`, async () => { + const upstream = new ReadableStream({ start(c) { c.error(new Error("socket reset during peek")) } }) + const res = await ask(new Response(upstream, { headers: { "content-type": "text/event-stream" } }), stream) + assert.equal(res.status, 502) + assert.match((await res.json()).error.message, /socket reset/) + assert.equal(upstream.locked, false) + }) + + test(`an abort during peek returns 499 (stream=${stream})`, async () => { + const upstream = new ReadableStream({ start(c) { c.error(new DOMException("cancelled", "AbortError")) } }) + const res = await ask(new Response(upstream, { headers: { "content-type": "text/event-stream" } }), stream) + assert.equal(res.status, 499) + }) +} + +test("a final quota error without newline errors a stream and cools its pacer", async () => { + let penalized = false + const response = i.upstreamToOpenAI(body(frame("prefix text") + "data: [ERROR]: quota exhausted"), { + model: "m", pacer: { penalize() { penalized = true } }, + }) + await assert.rejects(response.text(), (err) => err.statusCode === 429) + assert.equal(penalized, true) +}) + +test("a non-streaming refusal stops reading a connection that stays open", async () => { + let cancelled = false + const upstream = new ReadableStream({ + start(c) { c.enqueue(bytes("data: [ERROR]: quota exhausted\n\n")) }, + cancel() { cancelled = true }, + }) + const res = await i.upstreamToJSON(upstream, { model: "m" }) + assert.equal(res.status, 429) + assert.equal(cancelled, true) + assert.equal(upstream.locked, false) +}) + +test("a JSON code 429 is authoritative without rate-limit keywords", async () => { + const saved = process.env.ORCATERM_NO_PACE + delete process.env.ORCATERM_NO_PACE + try { + for (const message of ["Too fast", "稍后再试", ""]) { + const key = `uin=o429${message.length}; skey=AUDIT_429_${message.length}` + const plugin = await OrcaTermAuthPlugin() + const loader = await plugin.auth.loader(async () => ({ key })) + globalThis.fetch = async () => new Response(JSON.stringify({ code: 429, message }), { headers: { "content-type": "application/json" } }) + const res = await loader.fetch("https://unused.invalid", { body: JSON.stringify({ stream: false }) }) + assert.equal(res.status, 429) + assert.equal((await res.json()).error.code, 429) + assert.ok(i.pacerFor({ ticket: i.parseTicket(key) }).blockedForTest() > 0) + } + } finally { + if (saved === undefined) delete process.env.ORCATERM_NO_PACE + else process.env.ORCATERM_NO_PACE = saved + } +}) + +test("a non-SSE body read failure returns 502", async () => { + const upstream = new ReadableStream({ start(c) { c.error(new Error("JSON socket reset")) } }) + const res = await ask(new Response(upstream, { headers: { "content-type": "application/json" } })) + assert.equal(res.status, 502) +}) + +test("empty SSE does not reuse an already-locked response body", async () => { + const res = await ask(new Response("", { headers: { "content-type": "text/event-stream" } })) + assert.equal(res.status, 200) + assert.ok((await res.json()).choices[0].message.content) +}) + +test("callback rejects invalid JSON shapes and remains alive for a valid scan", async () => { + const cap = i.createLocalCapture({ appid: "audit", redirectUri: "https://orcaterm.com/oauth/wechat/bridge", state: "audit-state", timeoutMs: 5000 }) + try { + const url = await cap.ready + const send = (value) => realFetch(new URL("/cb", url), { + method: "POST", headers: { "content-type": "application/json", origin: new URL(url).origin, connection: "close" }, body: JSON.stringify(value), + }) + for (const value of [null, [], 42, "text", {}, { code: {}, state: "audit-state" }, { code: "C", state: 42 }, { code: "C", state: "audit-state", error: {} }]) { + const res = await send(value) + assert.equal(res.status, 400) + assert.equal((await res.json()).ok, false) + } + assert.equal((await (await send({ code: "C", state: "audit-state" })).json()).ok, true) + assert.deepEqual(await cap.wait, { code: "C", state: "audit-state" }) + } finally { cap.close() } +}) + +test("callback preserves bridge errors without a code and still permits a later scan", async () => { + const cap = i.createLocalCapture({ appid: "audit", redirectUri: "https://orcaterm.com/oauth/wechat/bridge", state: "audit-state", timeoutMs: 5000 }) + try { + const url = await cap.ready + const send = (value) => realFetch(new URL("/cb", url), { + method: "POST", headers: { "content-type": "application/json", origin: new URL(url).origin, connection: "close" }, body: JSON.stringify(value), + }) + const res = await send({ state: "audit-state", error: "access_denied" }) + assert.equal(res.status, 200) + assert.deepEqual(await res.json(), { ok: false, error: "access_denied" }) + assert.equal((await (await send({ code: "C", state: "audit-state" })).json()).ok, true) + assert.deepEqual(await cap.wait, { code: "C", state: "audit-state" }) + } finally { cap.close() } +}) diff --git a/packages/orcaterm/chunks.test.mjs b/packages/orcaterm/chunks.test.mjs new file mode 100644 index 0000000..dbbfbae --- /dev/null +++ b/packages/orcaterm/chunks.test.mjs @@ -0,0 +1,121 @@ +// Frames that look cumulative but aren't, a frame split across network +// chunks, and a connection that dies or is cancelled: the three cases that +// decide whether the client sees the answer it was given, and whether a +// failure is reported as one. +import { expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +// The suite fires far more than the account's ten-a-minute budget; lift the +// pacer so these tests measure the plugin, not the limiter. +process.env.ORCATERM_NO_PACE = "1" + + +const frame = (o) => `data: ${JSON.stringify(o)}\n\n` + +const collect = async (res) => { + const text = await res.text() + const out = [] + for (const line of text.split("\n")) { + const t = line.trim() + if (!t.startsWith("data:")) continue + const p = t.slice(5).trim() + if (p === "[DONE]") continue + const d = JSON.parse(p).choices?.[0]?.delta + if (d?.content) out.push(d.content) + } + return out.join("") +} + +const bodyOf = (frames, close = true) => + new ReadableStream({ + start(c) { + for (const f of frames) c.enqueue(new TextEncoder().encode(f)) + if (close) c.close() + }, + }) + +// The old "cumulative content" check cut real per-frame text whenever a frame +// happened to start with everything sent so far: "ha" then "haha" streamed as +// "haha" instead of "hahaha". `content` is each frame's addition, so it must +// be passed on untouched. +test("a frame that starts with what was already sent is still an addition", async () => { + const res = _internal.upstreamToOpenAI(bodyOf([frame({ content: "ha" }), frame({ content: "haha" })]), { model: "m" }) + expect(await collect(res)).toBe("hahaha") +}) + +test("repeated and overlapping text is kept, not trimmed", async () => { + const res = _internal.upstreamToOpenAI( + bodyOf([frame({ content: "ab" }), frame({ content: "ab" }), frame({ content: "abc" })]), + { model: "m" }, + ) + expect(await collect(res)).toBe("abababc") +}) + +// fullContent is the whole answer so far: its difference is the addition. +test("fullContent still becomes a delta", async () => { + const res = _internal.upstreamToOpenAI( + bodyOf([frame({ fullContent: "你" }), frame({ fullContent: "你好" }), frame({ fullContent: "你好,世界" })]), + { model: "m" }, + ) + expect(await collect(res)).toBe("你好,世界") +}) + +// A fullContent that rewrites earlier text has no meaningful difference; the +// whole new text is sent rather than a slice from the wrong offset, which +// used to produce "abcw" from "abc" then "xyzw". +test("a fullContent that rewrites earlier text is sent whole", async () => { + const res = _internal.upstreamToOpenAI(bodyOf([frame({ fullContent: "abc" }), frame({ fullContent: "xyzw" })]), { + model: "m", + }) + expect(await collect(res)).toBe("abcxyzw") +}) + +// A frame can arrive in pieces; the split may fall inside a multi-byte +// character. Neither may lose or mangle text. +test("a frame split across chunks keeps every character", async () => { + const whole = frame({ content: "你好,世界" }) + const cut = Math.floor(whole.length / 2) + const body = new ReadableStream({ + start(c) { + const enc = new TextEncoder() + c.enqueue(enc.encode(whole.slice(0, cut))) + c.enqueue(enc.encode(whole.slice(cut))) + c.close() + }, + }) + const res = _internal.upstreamToOpenAI(body, { model: "m" }) + expect(await collect(res)).toBe("你好,世界") +}) + +// A connection that dies mid-stream must error the stream. As an ordinary +// end it would read as a complete answer, and magpie would not fail over. +test("a reset mid-stream errors the stream", async () => { + const body = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode(frame({ content: "par" }))) + c.error(new Error("socket hang up")) + }, + }) + await expect(_internal.upstreamToOpenAI(body, { model: "m" }).text()).rejects.toThrow(/socket hang up/) +}) + +// Cancelling must reach the upstream reader: the connection is not left +// open when the agent gives up. Removing releaseUpstream() turns this red. +test("cancelling the answer cancels the upstream", async () => { + let cancelled = false + const body = new ReadableStream({ + pull(c) { + c.enqueue(new TextEncoder().encode(frame({ content: "a" }))) + }, + cancel() { + cancelled = true + }, + }) + const res = _internal.upstreamToOpenAI(body, { model: "m" }) + const reader = res.body.getReader() + await reader.read() + await reader.cancel() + // the cancel propagates asynchronously + for (let i = 0; i < 20 && !cancelled; i++) await new Promise((r) => setTimeout(r, 10)) + expect(cancelled).toBe(true) +}) diff --git a/packages/orcaterm/index.mjs b/packages/orcaterm/index.mjs new file mode 100644 index 0000000..18054a2 --- /dev/null +++ b/packages/orcaterm/index.mjs @@ -0,0 +1,2278 @@ +/** + * opencode-orcaterm-auth + * + * OrcaTerm (Tencent Cloud's terminal; 腾讯云遨驰终端) AI reverse proxy: both an + * OpenCode v1 plugin and a magpie provider plugin. + * + * Upstream protocol (reverse-engineered from orcaterm.cloud.tencent.com's + * frontend bundle, the 2026-10 build): + * chat endpoint POST {ASSISTANT_BASE}/chat?name=&mode=<0|1|2>&csrfCode= + * body: {conversationId, user:{id, setting:{...}}, input:{id, type:"start", + * input:, files:[], historyMessages:[]}, stream:true} + * headers: x-seqid + cookie(uin/skey) + the browser-family headers + * response: SSE, one `data: {...}` per line; the text is in content, the + * thinking in reasoningContent + * account API POST https://api.orcaterm.cloud.tencent.com/cgi/api? + * body: {action, data}; signed head and tail (X-CsrfCode is the djb2 of + * the cookie's skey) + * + * The outward contract of this file follows magpie's docs exactly: + * config / auth{methods, loader, usage} / provider.models / chat.headers + */ +import { createHash, randomBytes, randomUUID } from "node:crypto" +import { + createLocalCapture, + exchangeCode, + looksLikeAccessToken, + readTokenClaims, + refreshAccessToken, + startWechatLogin, +} from "./wechat.mjs" + +const PROVIDER = "orcaterm" + +// ---- upstream constants (the only place to change them) --------------------- +const ASSISTANT_BASE = "https://lightai.cloud.tencent.com/assistant" +const CAPI_ORIGIN = "https://orcaterm.cloud.tencent.com" +const CAPI_URL = "https://api.orcaterm.cloud.tencent.com/cgi/api" +const WEB_TERMINAL = "https://orcaterm.cloud.tencent.com/terminal" + +/** OrcaTerm's built-in assistants (lighthouse/orcaterm/cvm...): which script and tool set runs */ +const ASSISTANT = { + orcaterm: "orcaterm", + lighthouse: "lighthouse", +} +/** 0=RE_ACT 1=PLAN_ACT 2=AUTO_ACT */ +const MODE = { react: 0, planact: 1, autoact: 2 } + +/** + * Upstream model ids (the frontend's bt.* constants, 2026-10 snapshot). + * + * `id` is what actually goes into the request body as the model; `name` is only + * shown in the picker, so it has to match the id — earlier the marketing names + * on the UI (DeepSeek-V4-Pro, GLM-5.2, Kimi-k2.6) were taken for model names. + * Those were guessed from interface copy, with nothing behind them, and they + * don't match what the server actually serves. + * + * The context and output caps are estimates too: upstream never publishes a + * window size for a model. + */ +/** + * What OrcaTerm actually serves, and what to call it. + * + * The desktop client's own table keeps two fields apart, and that is the trap + * here: `newModelId` is the id sent upstream, `modelName` is the label its + * picker shows. They are not the same string, and the ids carry a namespace — so + * the wire id is `TokenHub/glm-5.3` or `Hunyuan3/hy3`, not `glm-5.3`. Sent bare, + * upstream answers `LLM(glm-5.3) is not loaded`. + * + * `id` is what goes on the wire; `name` is what the user reads. Older ids stay in + * `aliases` so a config written against them keeps resolving. + * + * `listed: false` keeps an id resolvable but out of `provider.models`: the README + * says not to use those, because they answer on the endpoint yet cannot be + * selected in OrcaTerm's own picker, so calling them goes around the product's + * interface. They stay only so an existing config does not break. + */ +const MODEL_SPECS = [ + // ---- the desktop picker's nine, labelled as it labels them --------------- + { + id: "TokenHub/deepseek-v4-pro", + name: "Deepseek-V4-Pro", + reasoning: true, + context: 128000, + output: 32000, + tool_call: false, + aliases: ["Deepseek-V4-Pro", "deepseek-v4-pro", "deepseek-chat-latest", "deepseek-chat", "deepseek", "deepseek-v4"], + }, + { + id: "TokenHub/deepseek-v4-flash", + name: "DeepSeek-V4-Flash", + reasoning: false, + context: 128000, + output: 32000, + tool_call: false, + aliases: ["DeepSeek-V4-Flash", "deepseek-v4-flash", "deepseek-flash"], + }, + { + id: "TokenHub/deepseek-v4.1-flash", + name: "DeepSeek-V4.1-Flash", + reasoning: false, + context: 128000, + output: 32000, + tool_call: false, + aliases: ["DeepSeek-V4.1-Flash", "deepseek-v4.1-flash"], + }, + { + id: "TokenHub/glm-5.3", + name: "GLM-5.3", + reasoning: true, + context: 200000, + output: 32000, + tool_call: false, + aliases: ["GLM-5.3", "glm-5.3", "glm"], + }, + { + id: "TokenHub/glm-5.3-flash", + name: "GLM-5.3-Flash", + reasoning: false, + context: 200000, + output: 32000, + tool_call: false, + aliases: ["GLM-5.3-Flash", "glm-5.3-flash"], + }, + { + id: "TokenHub/glm-5.2", + name: "GLM-5.2", + reasoning: false, + context: 200000, + output: 32000, + tool_call: false, + // the older glm-4.7 is the same entry under its previous id + aliases: ["GLM-5.2", "glm-5.2", "glm-4.7", "bigmodel"], + }, + { + id: "TokenHub/kimi-k3", + name: "Kimi-K3", + reasoning: false, + context: 256000, + output: 32000, + tool_call: false, + // the picker used to label this entry "Kimi-k2.6" with id kimi-k2 + aliases: ["Kimi-K3", "kimi-k3", "kimi", "kimi-k2", "kimi-k2.6", "Kimi-k2.6", "moonshot"], + }, + { + id: "Hunyuan3/hy3", + name: "Hy3", + reasoning: true, + context: 256000, + output: 32000, + tool_call: false, + aliases: ["Hy3", "hy3", "hy3-preview", "Hy3-preview", "hunyuan", "hunyuan-t1", "hunyuan-3"], + }, + { + id: "Hunyuan3/hy4-preview", + name: "Hy4-preview", + reasoning: true, + context: 256000, + output: 32000, + tool_call: false, + aliases: ["Hy4-preview", "hy4-preview", "hy4", "hunyuan4"], + }, + + // ---- also served, and worth offering ------------------------------------ + { + id: "glm-4.7-thinking", + name: "GLM-5.2 Thinking", + reasoning: true, + context: 200000, + output: 32000, + tool_call: false, + listed: false, + aliases: ["glm-thinking", "glm-5.2-thinking", "GLM-5.2-Thinking"], + }, + { + id: "kimi-k2-thinking", + name: "Kimi-k2.6 Thinking", + reasoning: true, + context: 256000, + output: 32000, + tool_call: false, + listed: false, + aliases: ["kimi-thinking", "Kimi-k2.6-Thinking"], + }, + { + id: "kimi-k2.5", + name: "Kimi-k2.5", + reasoning: false, + context: 256000, + output: 32000, + tool_call: false, + listed: false, + aliases: ["Kimi-k2.5"], + }, + { + id: "kimi-k2.5-thinking", + name: "Kimi-k2.5 Thinking", + reasoning: true, + context: 256000, + output: 32000, + tool_call: false, + listed: false, + aliases: ["Kimi-k2.5-Thinking"], + }, + { + id: "kimi-latest", + name: "Kimi Latest", + reasoning: false, + context: 256000, + output: 32000, + tool_call: false, + listed: false, + aliases: ["Kimi-Latest"], + }, + { + id: "hunyuan-turbos", + name: "Hunyuan-TurboS", + reasoning: false, + context: 128000, + output: 16000, + tool_call: false, + listed: false, + aliases: ["Hunyuan-TurboS", "turbos"], + }, + { + id: "qwen3", + name: "Qwen3", + reasoning: false, + context: 128000, + output: 32000, + tool_call: false, + listed: false, + aliases: ["Qwen3", "qwen"], + }, + { + id: "deepseek-reasoner", + name: "DeepSeek Reasoner", + reasoning: true, + context: 128000, + output: 32000, + tool_call: false, + listed: false, + aliases: ["DeepSeek-Reasoner", "deepseek-r1"], + }, +] + +function createPacer({ limit = 10, windowMs = 60000, useEnv = true } = {}) { + /** When each recent chat was sent. */ + const sent = [] + /** No request may go before this time after a 429. */ + let blockedUntil = 0 + + // Read at call time, not construction time: the budget is per account and the + // operator may want to leave room for the desktop client, and the test suite + // sends far more than ten requests in a row. + const budget = () => { + if (!useEnv) return limit + const n = Number(process.env.ORCATERM_CHAT_RPM) + return Number.isFinite(n) && n > 0 ? n : limit + } + + const prune = (now) => { + while (sent.length && now - sent[0] >= windowMs) sent.shift() + } + + return { + async wait(signal) { + // A test suite (or a script driving the plugin) can turn the pacer off + // wholesale: it is a courtesy to the account budget, not a correctness rule. + if (process.env.ORCATERM_NO_PACE) return + for (;;) { + if (signal?.aborted) return + const now = Date.now() + prune(now) + if (now < blockedUntil) { + await sleep(Math.min(blockedUntil - now, 5000), signal) + continue + } + if (sent.length < budget()) { + sent.push(now) + return + } + // the oldest must fall out of the window before another may go + const waitFor = Math.max(50, windowMs - (now - sent[0]) + 5) + await sleep(Math.min(waitFor, 5000), signal) + } + }, + /** A 429 came back: hold everything for a window rather than retry into it. */ + penalize(ms = 15000) { + if (process.env.ORCATERM_NO_PACE) return + blockedUntil = Math.max(blockedUntil, Date.now() + ms) + }, + /** How long this pacer is holding requests back (for tests). */ + blockedForTest() { + return Math.max(0, blockedUntil - Date.now()) + }, + /** How many are counted right now (for tests). */ + size() { + prune(Date.now()) + return sent.length + }, + } +} + +/** + * One pacer per account, not one for the whole module. + * + * The limit is per account upstream, so a shared instance would make one + * account's sends — and its 429 cool-down — hold up every other account magpie + * has signed in. Keyed by `fingerprint(auth)`, which is the same identity the + * conversation and the account card use. + */ +const pacers = new Map() + +function pacerFor(auth) { + const key = fingerprint(auth) + let p = pacers.get(key) + if (!p) { + // Bound the map the way the session map is bounded. Evict the oldest entry + // rather than clearing: `clear()` would also drop live cool-downs, handing + // every account a fresh budget the moment the map filled up. + if (pacers.size >= 64) { + const oldest = pacers.keys().next().value + if (oldest !== undefined) pacers.delete(oldest) + } + p = createPacer() + pacers.set(key, p) + } + return p +} + +/** + * Wait `ms`, but stop early if the caller goes away. + * + * The abort listener is removed when the timeout wins, so a long-lived signal + * does not accumulate listeners across waits; and an already-aborted signal + * resolves at once instead of waiting the full time. + */ +function sleep(ms, signal) { + return new Promise((resolve) => { + if (signal?.aborted) { + resolve() + return + } + let done = false + const finish = () => { + if (done) return + done = true + clearTimeout(timer) + signal?.removeEventListener?.("abort", finish) + resolve() + } + const timer = setTimeout(finish, ms) + signal?.addEventListener?.("abort", finish, { once: true }) + }) +} + +const ALIAS_TO_ID = (() => { + const m = new Map() + for (const spec of MODEL_SPECS) { + m.set(spec.id.toLowerCase(), spec.id) + for (const a of spec.aliases) m.set(a.toLowerCase(), spec.id) + } + return m +})() + +// ---- small helpers ---------------------------------------------------------- +function uid(prefix = "") { + return prefix + randomBytes(12).toString("hex") +} + +/** + * The id the web client puts in `input.id` — a plain uuid v4, 36 characters with + * hyphens (module 73383's `Ub` is uuid v4, bundle 2026-10). + * + * This has to match, not merely be unique. Upstream rejected the ids this plugin + * used to make (`in-` + 24 hex) with `Invalid inputId`, and the bundle shows + * nothing that registers an input before `/chat`, so upstream is reading the + * shape of the id itself. + */ +function inputId() { + return randomUUID() +} + +/** Tencent's skey-style csrf: djb2 of the cookie's skey, & 0x7fffffff */ +function csrfCode(skey) { + if (!skey) return "" + let h = 5381 + for (let i = 0; i < skey.length; i++) h = ((h << 5) + h + skey.charCodeAt(i)) | 0 + return String(h & 0x7fffffff) +} + +function parseTicket(raw) { + const text = String(raw ?? "").trim() + if (!text) return null + const out = { uin: "", skey: "", p_skey: "", p_uin: "", raw: "" } + + if (text.includes("=") && text.includes(";")) { + out.raw = text + for (const part of text.split(";")) { + const eq = part.indexOf("=") + if (eq < 0) continue + const k = part.slice(0, eq).trim() + const v = part.slice(eq + 1).trim() + if (k === "uin" || k === "p_uin") out[k] = v + else if (k === "skey" || k === "p_skey") out[k] = v + } + } else if (text.includes("=")) { + // a single k=v, or k=v&k=v + const pairs = text.split(/[&\s]+/) + const obj = {} + for (const p of pairs) { + const eq = p.indexOf("=") + if (eq > 0) obj[p.slice(0, eq).trim()] = p.slice(eq + 1).trim() + } + if (obj.skey || obj.p_skey || obj.uin || obj.p_uin) { + Object.assign(out, { + uin: obj.uin || obj.p_uin || "", + skey: obj.skey || "", + p_skey: obj.p_skey || obj.skey || "", + p_uin: obj.p_uin || obj.uin || "", + }) + out.raw = text + } else { + // one value alone: treat it as the skey + out.skey = text + } + } else { + out.skey = text + } + + if (!out.skey && out.p_skey) out.skey = out.p_skey + if (!out.uin && out.p_uin) out.uin = out.p_uin + if (!out.skey) return null + if (!out.raw) { + out.raw = [out.uin && `uin=${out.uin}`, `skey=${out.skey}`].filter(Boolean).join("; ") + } + return out +} + +/** + * The cookie header upstream accepts. + * + * Measured (2026-10-26, lightai gateway): + * - skey alone → NEED_UIN_AND_SKEY + * - p_uin+p_skey alone → NEED_UIN_AND_SKEY + * - uin + skey → VERIFY_SKEY_UIN_FAILED (it reaches the verify layer; + * fake credentials stop there) + * - uin with or without the o prefix → both accepted + * So uin and skey must be a pair, and both real: no placeholder uin is derived + * here any more. + */ +function cookieHeader(auth) { + const t = auth?.ticket + if (!t?.skey || !t?.uin) return "" + const parts = [`uin=${t.uin}`, `skey=${t.skey}`] + if (t.p_skey) parts.push(`p_skey=${t.p_skey}`) + if (t.p_uin) parts.push(`p_uin=${t.p_uin}`) + return parts.join("; ") +} + +function fingerprint(auth) { + // Account identity: a WeChat access token carries a userId; a console session + // is uin + the first 12 characters of skey. + // + // The fallback is deliberately a constant, not a slice of the token: a token + // without a `userId` claim is replaced on every renewal, and keying on its + // tail would hand that account a brand-new pacer — and a brand-new budget — + // every two hours. One shared fallback key is the conservative choice. + const bearer = bearerOf(auth) + if (bearer) return `wechat:${readTokenClaims(bearer).userId || "unknown"}` + const t = auth?.ticket + const uin = t?.uin || t?.p_uin || "" + return `${uin}:${String(t?.skey ?? "").slice(0, 12)}` +} + +/** + * The WeChat OAuth access token, when this account signed in by scanning. + * + * Two credentials can drive upstream and they are not interchangeable: + * - `uin` + `skey` — the console session cookie; full account authority. + * - a WeChat OAuth access token — a 1024-character JWT, two hours, renewable, + * confined to this product. Measured 2026-10-27: it drives /assistant/chat + * fine, namespaced model ids included. + * Recognised by shape, so a pasted token works without any metadata. + */ +function bearerOf(auth) { + const candidates = [auth?.key, auth?.access, auth?.metadata?.accessToken, auth?.ticket?.raw] + for (const c of candidates) { + const s = String(c ?? "").trim() + if (looksLikeAccessToken(s)) return s + } + return "" +} + +function baseHeaders(extra = {}) { + return { + accept: "text/event-stream", + "accept-language": "zh-CN,zh;q=0.9,en;q=0.8", + "content-type": "application/json", + origin: CAPI_ORIGIN, + referer: `${WEB_TERMINAL}`, + "user-agent": + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", + ...extra, + } +} + +/** + * magpie's docs: init.body is a JSON string, **or bytes when it isn't UTF-8 + * text**. This folds the shapes (string / Uint8Array / ArrayBuffer / any object + * that isn't a readable stream) into text. + */ +function bodyToText(body) { + if (body == null) return "" + if (typeof body === "string") return body + if (body instanceof Uint8Array) return new TextDecoder().decode(body) + if (body instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(body)) + if (ArrayBuffer.isView(body)) return new TextDecoder().decode(new Uint8Array(body.buffer, body.byteOffset, body.byteLength)) + if (typeof body === "object") { + // URLSearchParams and the like + if (typeof body.toString === "function" && body.constructor?.name !== "Object") return String(body) + try { + return JSON.stringify(body) + } catch { + return "" + } + } + return String(body) +} + +// ---- model resolution ------------------------------------------------------- +function resolveModel(requested) { + const raw = String(requested ?? "").trim() + const key = raw.includes("/") ? raw.slice(raw.lastIndexOf("/") + 1).trim() : raw + // An empty string, or a bare slash ("orcaterm/"), falls back to the default + // model: an empty model must never be sent upstream + if (!key) return MODEL_SPECS[0].id + const hit = ALIAS_TO_ID.get(key.toLowerCase()) + if (hit) return hit + // so a model upstream adds later doesn't 404: pass it through as given + return key +} + + +// ---- request body: OpenAI Chat Completions → OrcaTerm assistant ------------- +/** + * OrcaTerm's assistant only takes "one user message + a list of history + * messages"; it has no system field. So OpenAI's messages are squeezed into: + * - system/developer joined together at the head of input.input (marked, so + * the model can tell them apart) + * - earlier turns become a transcript in input.input; historyMessages stays empty + * - assistant.tool_calls / tool results degrade into plain text turns + */ +function toUpstreamBody(body, { conversationId, userId }) { + const messages = Array.isArray(body?.messages) ? body.messages : [] + const systems = [] + const turns = [] + + const textOf = (content) => { + if (typeof content === "string") return content + if (Array.isArray(content)) { + return content + .map((part) => { + if (typeof part === "string") return part + if (part?.type === "text") return part.text ?? "" + if (part?.type === "image_url") return "[image]" + return "" + }) + .filter(Boolean) + .join("\n") + } + return "" + } + + for (const msg of messages) { + const role = msg?.role ?? "user" + if (role === "system" || role === "developer") { + const t = textOf(msg.content).trim() + if (t) systems.push(t) + continue + } + if (role === "tool") { + const t = textOf(msg.content).trim() + if (t) turns.push({ role: "user", content: `[tool result ${msg.tool_call_id ?? ""}]\n${t}` }) + continue + } + if (role === "assistant") { + const t = 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) { + const desc = calls + .map((c) => `${c?.function?.name ?? "tool"}(${c?.function?.arguments ?? ""})`) + .join("\n") + turns.push({ role: "assistant", content: `[called tool]\n${desc}` }) + } + continue + } + const t = textOf(msg.content) + turns.push({ role: "user", content: t }) + } + + const lastUser = (() => { + for (let i = turns.length - 1; i >= 0; i--) if (turns[i].role === "user") return i + return -1 + })() + + let inputText = "" + const history = [] + if (lastUser === -1) { + // all assistant / empty: use the last turn as the input + inputText = turns.length ? turns[turns.length - 1].content : "" + history.push(...turns.slice(0, -1)) + } else { + inputText = turns[lastUser].content + history.push(...turns.slice(0, lastUser)) + // Only what came before the last user turn is context. An assistant turn + // after it is the reply the caller wants continued, not something to put in + // front of the question. + } + + // Nothing goes up as `historyMessages`, and the conversation id can't carry the + // thread either: magpie hands every request a fresh `sessionID` + // (`magpie-`, measured 2026-10-27 — four requests, four ids), so each + // turn would otherwise reach upstream as a new conversation and the assistant + // would forget everything said before it. + // + // What magpie does give is the whole message list every time, so the earlier + // turns travel in the text as a transcript — the one thing a stateless gateway + // can rely on. + // + // (`historyMessages` itself was tried: an entry's kind is in `type`, not + // `role`, and with the wrong field upstream fails inside its own handler with + // "[type] is not a function". With the right field it is accepted but the text + // comes back echoed into the answer, so the transcript is better.) + const historyMessages = [] + + const transcript = history + .filter((t) => (t.content ?? "").trim()) + .map((t) => (t.role === "assistant" ? `assistant: ${t.content.trim()}` : `user: ${t.content.trim()}`)) + const transcriptPrefix = transcript.length + ? `[earlier in this conversation]\n${transcript.join("\n")}\n[end of earlier conversation]\n\n` + : "" + + // Tool traffic has to survive too: with no history on the wire, a tool's + // result is invisible upstream, and dropping it silently loses what the tool + // found. It is already part of `transcript`; this keeps it visible when it + // fell outside it. + const toolNotes = history + .filter((t) => (t.content ?? "").trim() && /\[(called tool|tool result)/.test(t.content)) + .map((t) => t.content.trim()) + .filter((note) => !transcriptPrefix.includes(note)) + const toolPrefix = toolNotes.length ? `${toolNotes.join("\n")}\n\n` : "" + + const prefix = systems.length + ? `[system instructions, higher priority than the conversation]\n${systems.join("\n\n")}\n[end of system instructions]\n\n` + : "" + + // Upstream requires input.content to be non-empty: an empty messages list or + // a null content can't go up blank + let content = prefix + transcriptPrefix + toolPrefix + inputText + if (!content.trim()) { + content = prefix + ? `${prefix}(no content was given; ask briefly what is needed)` + : "(no content was given; ask briefly what is needed)" + } + + return { + conversationId, + user: { + id: userId, + setting: { + model: null, // filled in by the caller + enableThinking: false, + language: "zh", + multimodal: false, + // Turn off upstream's own tools and MCP so this request is a plain + // question and answer. + // + // Note: these fields mean "give it no tools", not "forbid it to act". + // The assistant runs in RE_ACT mode, so upstream may still decide by + // itself to call a built-in ability (running a command on the user's + // server, say). That can't be confirmed from this plugin's side, so: + // - declare no tools and approve none; + // - hideToolMessage: false — if it does call one, the trace shows up + // in the reply where the user can see it, instead of being quietly + // hidden. + tools: [], + mcpServers: [], + uiServers: [], + approvedTools: [], + approvedMCPTools: [], + hideToolMessage: false, + isNormalToolMessageIgnored: false, + }, + }, + // The web client's own shape for a first turn: `type: "start"` and the text + // in `input.input` — not `content`, and not an invented `in-…` id. + input: { + id: inputId(), + type: "start", + input: content, + files: [], + historyMessages, + }, + stream: true, + } +} + +// ---- SSE parsing: upstream data lines → delta {content, reasoning} ---------- +/** + * Cut complete lines out of the buffer. + * SSE allows \r\n, \n and \r line ends, and all three are handled here. + * Returns [lines, rest]; rest is the tail that hasn't seen a line end yet. + */ +function takeSseLines(buf) { + const lines = [] + let i = 0 + let start = 0 + while (i < buf.length) { + const ch = buf[i] + if (ch === "\n") { + lines.push(buf.slice(start, i)) + i += 1 + start = i + } else if (ch === "\r") { + lines.push(buf.slice(start, i)) + i += buf[i + 1] === "\n" ? 2 : 1 + start = i + } else { + i += 1 + } + } + return [lines, buf.slice(start)] +} + +function parseSseLine(line) { + const trimmed = line.trim() + if (!trimmed) return null + if (!trimmed.startsWith("data:")) return null + const payload = trimmed.slice(5).trim() + if (!payload) return null + if (payload === "[DONE]") return { done: true } + if (payload.startsWith("[ERROR]")) { + return { error: payload.replace(/^\[ERROR\]:?\s*/, "") || "the upstream returned an error" } + } + if (payload.startsWith("[ABORTED]")) return { done: true } + try { + const obj = JSON.parse(payload) + // both wrappers have been seen: a bare object, and {data: {...}} + const d = obj?.data && typeof obj.data === "object" ? obj.data : obj + const content = typeof d?.content === "string" ? d.content : "" + const reasoning = + typeof d?.reasoningContent === "string" + ? d.reasoningContent + : typeof d?.reasoning === "string" + ? d.reasoning + : "" + const full = + typeof d?.fullContent === "string" ? d.fullContent : undefined + return { content, reasoning, full, raw: d } + } catch { + return null + } +} + +/** + * `fullContent` is the whole text so far, turned into the delta this frame + * should send. + * + * Two cases: + * - it continues on top of what was sent (same prefix) → the difference is + * the delta; + * - it rewrote what came before (different prefix) → the difference means + * nothing, so send the whole thing again and let the client see the + * complete new text, instead of gluing two halves into garbage. + * The earlier implementation only did slice(sent.length), so "xyzw" after + * "abc" came out as "w". + */ +function fullToDelta(full, sent) { + if (full === sent) return "" + if (full.startsWith(sent)) return full.slice(sent.length) + return full +} +/** + * The trailing action envelope, cut out of an answer that already arrived. + * + * Upstream sometimes puts the prose first and the envelope after it, in one + * answer: some prose followed by a ```` ```json ```` fenced + * `{"action": "completion", "taskCompletion": "…"}`. A streaming reader sees the + * prose go by before there is any envelope to recognise, so the envelope is + * removed from the tail instead. + * + * The opening is matched leniently — `{"action"`, `{" action"`, and a fence in + * front of it — because the assistant formats its own JSON and does not always + * write it the same way. + */ +function stripTrailingEnvelope(text) { + const raw = String(text ?? "") + const opening = /\{\s*"action"\s*:/gi + const starts = [] + let m + while ((m = opening.exec(raw))) starts.push(m.index) + // from the last candidate backwards: the first one whose tail parses wins + for (let k = starts.length - 1; k >= 0; k--) { + let idx = starts[k] + // a fence in front of the object belongs to it, not to the prose + const before = raw.slice(0, idx) + const fence = before.match(/```(?:json)?\s*$/i) + if (fence) idx = before.length - fence[0].length + const tail = raw + .slice(starts[k]) + .trim() + .replace(/\s*```$/, "") + .trim() + try { + 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 */ + } + } + return raw +} + +/** + * The answer arrives wrapped in the assistant's own action envelope, not as + * plain prose: + * + * {"action": "completion", "ph_1": "--", "taskCompletion": "…the answer…"} + * + * The web client parses that object (`parseJson`, module 72825) and shows + * `taskCompletion`; it also `JSON.parse`s tool-call and review actions the same + * way. Passed on raw, the extension or agent behind magpie shows the whole + * object as the reply, braces and all — which is what happened before this. + * + * Two jobs, then: + * - `taskCompletion` is the answer, so that is what comes out; + * - every other action (`review`, tool traffic) is not prose an OpenAI client + * can use, and there is none of it in practice here — the request declares + * no tools — so the raw text is kept rather than invented into prose. + * + * A reply that is not an envelope at all is returned untouched: the model may + * well answer with braces of its own. + */ +function unwrapAnswer(text) { + const raw = String(text ?? "") + // The assistant sometimes fences the envelope the way it fences code, so the + // fence comes off first — `parseJson` in the web client strips ```` ```json ```` + // the same way before parsing. + const s = raw + .trim() + .replace(/^```(?:json)?\s*/i, "") + .replace(/\s*```$/, "") + .trim() + if (!s.startsWith("{")) return raw + let obj + try { + obj = JSON.parse(s) + } catch { + // still arriving, or the model wrote braces that don't parse: leave it be + return raw + } + // Key lookup is case-insensitive, the same way `isActionEnvelope` treats the + // verb: the assistant writes its own JSON and does not always keep the case. + if (!obj || typeof obj !== "object" || Array.isArray(obj)) return raw + const action = obj.action ?? obj.Action + if (typeof action !== "string") return raw + const completion = obj.taskCompletion ?? obj.TaskCompletion + return typeof completion === "string" ? completion : raw +} + +/** JSON string escapes, for reading the envelope's answer as it arrives. */ +const JSON_ESCAPES = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" } + +/** + * How much of a plain reply is held back so an envelope appended after the + * prose is still recognised. Big enough for `{"action": …` to appear, small + * enough that a reply starting to stream is not visibly delayed. + */ +const ENVELOPE_TAIL = 48 + +/** + * The answer inside the assistant's action envelope, for a reply that is still + * arriving. + * + * Upstream does not stream bare prose. It streams the assistant's own message + * object, character by character: + * + * {"action": "completion", "ph_1": "--", "taskCompletion": "…the answer…"} + * + * The web client collects that text and parses it (`parseJson`, module 72825); + * what it shows is `taskCompletion`. So a stream that has to look like prose to + * an OpenAI client needs the envelope recognised and only its answer passed on. + * + * Sometimes the prose arrives first and the envelope after it (measured + * 2026-10-27): then the prose is the answer and the envelope is bookkeeping, so + * it is cut and nothing more is sent. + * + * The rule is kept deliberately simple: remember the whole reply, work out what + * the answer *should* be so far, and send on the part of it not sent yet. + * 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 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) + if (!m) return -1 + const j = m.index + m[0].length + if (s[j] !== '"') return -1 + return j + 1 +} + +/** Decode the JSON string body starting at `s`, as much of it as has arrived. */ +function decodeJsonString(s) { + let out = "" + let i = 0 + while (i < s.length) { + const ch = s[i] + if (ch === '"') return { text: out, ended: true } + if (ch !== "\\") { + out += ch + i += 1 + continue + } + const next = s[i + 1] + if (next === undefined) break + if (next === "u") { + if (i + 6 > s.length) break + const code = parseInt(s.slice(i + 2, i + 6), 16) + if (Number.isFinite(code)) out += String.fromCharCode(code) + i += 6 + continue + } + out += JSON_ESCAPES[next] ?? next + i += 2 + } + return { text: out, ended: false } +} + +/** True while `s` could still turn out to be an envelope, judged on what has arrived. */ +function couldBeEnvelope(s) { + const t = s.trimStart() + if (!t) return true + // A ```` ```json ```` fence may wrap it, and the fence itself arrives in + // pieces (` ```` ` then `json\n` ). While nothing but a fence has arrived the + // reply could still be either, so hold. + if (t[0] === "`") return FENCE_OPENING.startsWith(t.slice(0, FENCE_OPENING.length)) || t.startsWith("```") + const unfenced = t.replace(/^```(?:json)?\s*/i, "") + if (unfenced !== t) { + if (!unfenced) return true + return couldBeEnvelope(unfenced) + } + // The opening may still be arriving, so compare only what is there. The + // assistant writes its own JSON, so whitespace after `{` is expected + // (`{\n "action": …`), and the space before `:` is optional. + if (!t.startsWith("{")) return false + const rest = t.slice(1).replace(/^\s+/, "") + if (!rest) return true + if (rest.startsWith('"')) { + // compared lowercased, to match how `isActionEnvelope` reads the verb + const key = rest.slice(1).replace(/^\s+/, "").toLowerCase() + if (!key) return true + if (key.startsWith("action")) return true + return "action".slice(0, key.length) === key + } + return false +} + +/** How a fenced code block may open, as far as it can be judged while arriving. */ +const FENCE_OPENING = "```json\n" + +/** The verbs the client's own envelope can carry (module 82025). */ +const ENVELOPE_ACTIONS = new Set(["completion", "ask", "review", "start", "planner", "default"]) + +/** + * Whether a parsed object is the assistant's own action envelope — the message + * object its client wraps a reply in — and not merely a JSON object with an + * `action` key. + * + * The distinction matters: a Redux action, or a reducer a user asked the + * assistant to write out, has an `action` too, and cutting there truncated the + * reply. So a recognised verb has to come with one of the fields the client reads + * a reply out of, and an unrecognised verb has to carry `taskCompletion` — the + * one field a finished answer is always in. A snippet like + * `{"action": "SAVE", "content": "…"}` at the end of an answer is then left + * alone, which is what the reviewer's example was about. + */ +function isActionEnvelope(obj) { + if (!obj || typeof obj !== "object" || Array.isArray(obj)) return false + const action = obj.action ?? obj.Action + if (typeof action !== "string") return false + const hasPayload = + typeof (obj.taskCompletion ?? obj.TaskCompletion) === "string" || + typeof obj.thinking === "string" || + typeof obj.content === "string" || + typeof obj.question === "string" + if (ENVELOPE_ACTIONS.has(action.toLowerCase())) return hasPayload + return typeof (obj.taskCompletion ?? obj.TaskCompletion) === "string" +} + +/** The last position where an envelope opening starts and is followed by nothing. */ +function envelopeTailAt(s) { + const opening = /\{\s*"action"\s*:/gi + const starts = [] + let m + while ((m = opening.exec(s))) if (m.index > 0) starts.push(m.index) + return starts +} + +/** Where a *complete* trailing envelope begins in `s`, or -1. */ +function appendedEnvelopeAt(s) { + const starts = envelopeTailAt(s) + for (let k = starts.length - 1; k >= 0; k--) { + const at = starts[k] + // nothing may follow the object: this is the tail of the reply + const tail = s + .slice(at) + .trim() + .replace(/\s*```$/, "") + .trim() + let obj + try { + obj = JSON.parse(tail) + } catch { + continue + } + if (!isActionEnvelope(obj)) continue + // the fence in front of it belongs to the envelope too + const before = s.slice(0, at) + const fence = before.match(/```(?:json)?\s*$/i) + const start = fence ? before.length - fence[0].length : at + if (s.slice(0, start).trim()) return start + } + return -1 +} + +/** + * Where a *still-arriving* envelope begins, or -1. + * + * While the object is incomplete it cannot be judged, and letting the opening go + * out would show `{"action":` as prose. So hold from there — but only while it + * cannot be parsed yet: as soon as it parses and is not an envelope, it is + * ordinary text and must flow again. + */ +function appendedEnvelopePendingAt(s) { + const starts = envelopeTailAt(s) + // The opening can itself span more than ENVELOPE_TAIL characters (for + // example, a pretty-printed object with a long whitespace prefix). Hold + // a partial opening before its action key is complete as well. + const partial = s.lastIndexOf("{") + if (partial > 0 && !starts.includes(partial) && couldBeEnvelope(s.slice(partial))) starts.push(partial) + if (!starts.length) return -1 + const at = starts[starts.length - 1] + const tail = s + .slice(at) + .trim() + .replace(/\s*```$/, "") + .trim() + try { + JSON.parse(tail) + return -1 // complete, and `appendedEnvelopeAt` already rejected it + } catch { + /* still arriving */ + } + if (!couldBeEnvelope(tail)) return -1 + const before = s.slice(0, at) + const fence = before.match(/```(?:json)?\s*$/i) + const start = fence ? before.length - fence[0].length : at + return s.slice(0, start).trim() ? start : -1 +} + +function createAnswerExtractor() { + /** The whole reply as it arrives. */ + let raw = "" + /** How many characters of the answer have already been sent. */ + let sent = 0 + /** The answer can grow no more. */ + let closed = false + /** Nothing more will arrive: stop holding a tail back. */ + let final = false + + /** + * What the answer should be, given everything received so far. + * + * A reply that starts like an envelope is ambiguous until EOF: it can also + * be a JSON example followed by prose. Hold that candidate until its complete + * shape is known, so decoding it never discards later text. Ordinary prose + * and reasoning still stream as they arrive. + */ + const answerSoFar = () => { + if (couldBeEnvelope(raw)) { + if (!final) return "" + if (isEnvelope(raw)) return unwrapAnswer(raw) + // 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) + if (start >= 0) { + const decoded = decodeJsonString(raw.slice(start)) + if (!decoded.ended) return decoded.text + } + return stripTrailingEnvelope(raw) + } + const appended = appendedEnvelopeAt(raw) + if (appended > 0) return raw.slice(0, appended) + + // 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 + // not to be one, this stops matching and the text flows again. + if (!final) { + const pending = appendedEnvelopePendingAt(raw) + if (pending > 0) return raw.slice(0, pending) + } + + // no envelope at all: the reply is its own answer + if (final) return stripTrailingEnvelope(raw) + return raw.slice(0, Math.max(0, raw.length - ENVELOPE_TAIL)) + } + + const emit = () => { + const want = answerSoFar() + if (want.length <= sent) return "" + const out = want.slice(sent) + sent = want.length + return out + } + + return { + /** A raw delta in; returns the part of the answer to send on now. */ + push(delta) { + if (!delta || closed) return "" + raw += delta + // Deliberately never closes here. A complete envelope-shaped object is + // only "trailing" as far as what has arrived: if more text follows it, it + // was an example inside the answer, not the envelope, and closing early + // dropped everything after it. Cutting the *output* is enough — sending + // stops at the object — and `finish()` is what ends the stream. + return emit() + }, + /** Whatever is held back when the stream ends. */ + finish() { + if (closed) return "" + // Nothing more is coming: judge the whole text as it stands, without + // holding a tail back for an envelope that will never arrive. + final = true + const out = emit() + closed = true + return out + }, + } +} + +/** Whether `s` (all of it, now that nothing more will arrive) is an envelope. */ +function isEnvelope(s) { + const t = s + .trim() + .replace(/^```(?:json)?\s*/i, "") + .replace(/\s*```$/, "") + .trim() + if (!t.startsWith("{")) return false + try { + const o = JSON.parse(t) + return isActionEnvelope(o) + } catch { + return false + } +} + + +/** + * Upstream error codes → the status we answer magpie with. + * + * Measured (2026-10-27): OrcaTerm's AI gateway reports a failure as + * `[ERROR]: …` inside the SSE — exhausted quota, rate limiting and an + * unavailable model alike — while the HTTP status stays 200. Handed back to the + * client as body text, magpie would take it for a normal answer: it would not + * fail over to the next account, nor let this account rest — so it has to + * become an error status. + */ +const ERROR_MAP = [ + // monthly quota gone: another account is worth trying, so mark it 429 and + // magpie moves to the next one + { re: /quota|额度|次数已用完|余额不足|allowance|insufficient/i, status: 429, type: "rate_limit_error" }, + // rate limited: the same, but it has to wait a while + { re: /rate.?limit|too many|频繁|限流/i, status: 429, type: "rate_limit_error" }, + // sign-in problem: mark the account as needing to sign in again + { re: /NEED_UIN_AND_SKEY|VERIFY_SKEY_UIN_FAILED|VERIFY_LOGIN_FAILED|VERIFY_USER_FAILED|unauthorized|登录/i, status: 401, type: "authentication_error" }, +] + +/** Which status to answer with, judged from upstream's error text. */ +function errorStatus(text, pacer) { + const t = String(text ?? "") + for (const m of ERROR_MAP) { + if (m.re.test(t)) { + // A rate limit is the one error the plugin can act on: hold this account's + // next requests back instead of walking straight into the same wall. + if (m.status === 429) pacer?.penalize() + return m + } + } + // every other upstream error (model unavailable, internal error) counts as a + // server fault, so magpie fails over + return { status: 502, type: "upstream_error" } +} + +/** At most this much of the stream head is read: enough to see whether the first frame is an answer or an error. */ +const SSE_PEEK_LIMIT = 8 * 1024 + +/** Cancel without waiting for a peer that may keep its socket open. */ +function releaseReader(reader) { + if (!reader) return + try { + void reader.cancel().catch(() => {}) + } catch { + /* already released */ + } + try { + reader.releaseLock() + } catch { + /* a pending read owns the lock until cancellation completes */ + } +} + +/** + * Read the stream head until it's clear whether this is an answer or an error — + * following packages/codearts' peekAnswer. + * + * Returns { verdict, code, chunks, reader, text }: + * verdict is "answer" or "error"; chunks are the raw bytes already read, and + * they must be replayed, or the opening text is lost. + */ +async function peekAnswer(body) { + const head = { verdict: "", code: "", chunks: [], reader: null, text: "", decoder: new TextDecoder() } + if (!body) return head + head.reader = body.getReader() + let done = false + try { + for (;;) { + const v = classifyHead(head.text, done) + if (v) { + head.verdict = v + break + } + if (head.text.length >= SSE_PEEK_LIMIT) break + const r = await head.reader.read() + if (r.done) { + done = true + continue + } + head.chunks.push(r.value) + head.text += head.decoder.decode(r.value, { stream: true }) + } + } catch (err) { + releaseReader(head.reader) + throw err + } + if (head.verdict === "error") { + // an error stream is dropped outright; cancel isn't awaited, it can hang on + // a live stream + releaseReader(head.reader) + } + return head +} + +/** + * Look for an error frame among the head bytes read so far. + * When `done` is true and no error has shown up, the stream is a normal answer + * (or an empty one). + */ +function classifyHead(text, done) { + const [lines, rest] = takeSseLines(text) + if (done && rest.trim()) lines.push(rest) + for (const line of lines) { + const ev = parseSseLine(line) + if (!ev) continue + if (ev.error) return "error" + // text means it's an answer; no need to wait for more + if (ev.content || ev.reasoning || typeof ev.full === "string") return "answer" + } + if (done) return "answer" + return "" +} + +/** Pull upstream's error text out of the stream head already read. */ +function errorCodeFromHead(text) { + const [lines, rest] = takeSseLines(text) + if (rest.trim()) lines.push(rest) + for (const line of lines) { + const ev = parseSseLine(line) + if (ev?.error) return ev.error + } + return "the upstream returned an error" +} + +/** Splice the bytes peek read back into the stream, then read the rest. */ +function replayBody(head) { + let i = 0 + return new ReadableStream({ + async pull(controller) { + if (i < head.chunks.length) { + controller.enqueue(head.chunks[i++]) + return + } + try { + const r = await head.reader.read() + if (r.done) { + releaseReader(head.reader) + controller.close() + return + } + controller.enqueue(r.value) + } catch (err) { + releaseReader(head.reader) + controller.error(err) + } + }, + cancel(reason) { + releaseReader(head.reader) + }, + }) +} + +/** + * Turn the upstream SSE byte stream into an OpenAI chat.completion.chunk stream. + * Upstream sends increments (content is what this frame adds), so the delta goes + * out as is; when a frame turns out to carry the cumulative value (longer than + * what was sent and starting with it), it is converted to an increment. + */ +function upstreamToOpenAI(upstreamBody, { model, pacer }) { + const encoder = new TextEncoder() + const id = uid("chatcmpl-") + const created = Math.floor(Date.now() / 1000) + let sentContent = "" + let sentReasoning = "" + let emitText = 0 + let closed = false + let reader = null + const answer = createAnswerExtractor() + + // Upstream has to be closed when the client disconnects or cancels, or the + // connection leaks. + // + // reader only: once getReader() has been called the body is locked, and + // upstreamBody.cancel() then throws "Cannot cancel a locked ReadableStream". + // reader.cancel() returns a promise, and it isn't awaited — it can hang on a + // live stream. + const releaseUpstream = () => { + if (!reader) { + try { + upstreamBody?.cancel?.()?.catch?.(() => {}) + } catch { + /* ignore */ + } + return + } + releaseReader(reader) + } + + const chunk = (delta, finish = null, extra = {}) => + `data: ${JSON.stringify({ + id, + object: "chat.completion.chunk", + created, + model, + choices: [{ index: 0, delta, finish_reason: finish, logprobs: null }], + ...extra, + })}\n\n` + + const stream = new ReadableStream({ + async start(controller) { + const push = (s) => controller.enqueue(encoder.encode(s)) + const finishUp = (reason = "stop", { skipReasoningFallback = false } = {}) => { + if (closed) return + // Whatever the extractor is still holding belongs to the answer, and it + // 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 + } + // 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". + if (!skipReasoningFallback && emitText === 0 && sentReasoning) { + push(chunk({ content: sentReasoning })) + emitText = sentReasoning.length + } + closed = true + push(chunk({}, reason)) + // No usage is reported: upstream returns no token counts, and the + // character count here is only an estimate. Reported to magpie as real + // usage it would make both cost and context statistics wrong; better to + // report nothing and let the client know there is no such number. + push("data: [DONE]\n\n") + controller.close() + } + + // first chunk: carries the role, which is how the client builds the message + push(chunk({ role: "assistant", content: "" })) + + reader = upstreamBody.getReader() + const decoder = new TextDecoder() + let buf = "" + // A final line without a newline follows exactly the same path as every + // complete line, including error classification and account cool-down. + const absorb = (line) => { + const ev = parseSseLine(line) + if (!ev) return + if (ev.done) { + finishUp("stop") + return + } + if (ev.error) { + closed = true + const m = errorStatus(ev.error, pacer) + controller.error(Object.assign(new Error(`OrcaTerm: ${ev.error}`), { statusCode: m.status })) + return + } + const textDelta = typeof ev.full === "string" ? fullToDelta(ev.full, sentContent) : (ev.content ?? "") + if (textDelta) { + sentContent += textDelta + const visible = answer.push(textDelta) + if (visible) { + emitText += visible.length + push(chunk({ content: visible })) + } + } + const reasonDelta = ev.reasoning ?? "" + if (reasonDelta) { + sentReasoning += reasonDelta + push(chunk({ reasoning_content: reasonDelta })) + } + } + try { + for (;;) { + const { done, value } = await reader.read() + if (done) break + buf += decoder.decode(value, { stream: true }) + const [lines, rest] = takeSseLines(buf) + buf = rest + for (const line of lines) { + absorb(line) + if (closed) return + } + } + const [tailLines, tailRest] = takeSseLines(buf) + const pending = tailRest.trim() ? [...tailLines, tailRest] : tailLines + for (const line of pending) { + absorb(line) + if (closed) return + } + finishUp("stop") + } catch (err) { + // Interrupted while reading (abort / connection reset): this stream has + // to end with an error. Earlier a "connection lost" text was sent here + // and the stream stopped normally, so the client took it for an answer + // and magpie didn't fail over. + if (!closed) { + closed = true + controller.error( + Object.assign(new Error(`OrcaTerm connection broke: ${err?.message ?? err}`), { + statusCode: err?.name === "AbortError" ? 499 : 502, + }), + ) + } + } finally { + releaseUpstream() + } + }, + // cut upstream off the moment the client disconnects (the agent gave up), + // so the connection doesn't leak + cancel() { + closed = true + releaseUpstream() + }, + }) + return new Response(stream, { + status: 200, + headers: { + "content-type": "text/event-stream; charset=utf-8", + "cache-control": "no-cache, no-transform", + }, + }) +} + +async function upstreamToJSON(upstreamBody, { model, pacer }) { + const reader = upstreamBody.getReader() + const decoder = new TextDecoder() + let buf = "" + let content = "" + let reasoning = "" + let upstreamError = "" + let sawDone = false + + const absorb = (line) => { + if (sawDone || upstreamError) return + const ev = parseSseLine(line) + if (!ev) return + if (ev.done) { + sawDone = true + return + } + if (ev.error) { + upstreamError = ev.error + return + } + // same rule as the streaming path: content is an increment, only fullContent + // needs converting + if (typeof ev.full === "string") { + const d = fullToDelta(ev.full, content) + content += d + } else if (ev.content) { + content += ev.content + } + if (ev.reasoning) { + reasoning += ev.reasoning + } + } + + try { + for (;;) { + let chunkRead + try { + chunkRead = await reader.read() + } catch (err) { + // Client abort / connection lost: answer with a real error status; it + // must not be dressed up as an answer. Earlier this returned 200 plus a + // "connection lost" text, magpie took it as success, and failover stopped. + const aborted = err?.name === "AbortError" + return openaiError(aborted ? 499 : 502, `OrcaTerm connection broke: ${err?.message ?? err}`) + } + const { done, value } = chunkRead + if (done) break + buf += decoder.decode(value, { stream: true }) + const [lines, rest] = takeSseLines(buf) + buf = rest + for (const line of lines) absorb(line) + if (sawDone || upstreamError) { + buf = "" + break + } + } + } finally { + releaseReader(reader) + } + if (buf.trim() && !sawDone) absorb(buf) + + // upstream ended with an error (quota, rate limit, sign-in) → answer with the + // real error status + if (upstreamError) { + const m = errorStatus(upstreamError, pacer) + // the upstream's own code is the useful thing here, not our error class: + // pass the class as `type` and leave `code` to say what the upstream said. + return openaiError(m.status, `OrcaTerm: ${upstreamError}`, upstreamError, m.type) + } + + // The text is the assistant's action envelope, not plain prose: it is decoded + // 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 + let finalContent = visible.trimEnd() + if (!finalContent && reasoning) finalContent = reasoning + if (!finalContent) finalContent = "(OrcaTerm returned an empty reply)" + const message = { role: "assistant", content: finalContent } + if (reasoning) message.reasoning_content = reasoning + return new Response( + JSON.stringify({ + id: uid("chatcmpl-"), + object: "chat.completion", + created: Math.floor(Date.now() / 1000), + model, + choices: [{ index: 0, message, finish_reason: "stop", logprobs: null }], + }), + { status: 200, headers: { "content-type": "application/json; charset=utf-8" } }, + ) +} + +/** + * An error message can carry a full URL (with csrfCode — a djb2 derived from the + * skey). The query string is wiped before anything reaches a log or the UI, so + * the derived credential doesn't leak out. + */ +function redactUrl(text) { + return String(text ?? "").replace(/https?:\/\/[^\s"'))]+/g, (m) => { + const q = m.indexOf("?") + return q < 0 ? m : `${m.slice(0, q)}?…` + }) +} + +/** + * An OpenAI-shaped error response. + * `code` is upstream's own error code or classification; `type` is OpenAI's + * error category, honoured when it is passed (errorStatus gives a more accurate + * one than the status code alone). + */ +function openaiError(status, message, code = "upstream_error", type) { + const kind = type ?? (status === 401 ? "authentication_error" : status === 429 ? "rate_limit_error" : "upstream_error") + return new Response(JSON.stringify({ error: { message, type: kind, code } }), { + status, + headers: { "content-type": "application/json; charset=utf-8" }, + }) +} + +// ---- upstream call: one assistant/chat (streaming), failures readable ------- +async function callAssistant({ auth, upstream, model, assistant, mode, signal }) { + const bearer = bearerOf(auth) + const skey = auth?.ticket?.skey + // A Bearer token needs no csrfCode — that is derived from a skey this kind of + // account does not have. + const csrf = bearer ? "" : csrfCode(skey) + const url = `${ASSISTANT_BASE}/chat?name=${encodeURIComponent(assistant)}&mode=${mode}${csrf ? `&csrfCode=${csrf}` : ""}` + const body = structuredClone(upstream) + body.user.setting.model = model + + const headers = baseHeaders({ + // x-seqid is this request's id, not the conversation's: the web page makes a + // new one for every send, and reusing a fixed value could make upstream take + // several requests for one. + "x-seqid": body.input.id, + ...(bearer + ? { authorization: `Bearer ${bearer}`, "x-product": "orcaterm" } + : { cookie: cookieHeader(auth) }), + }) + + return fetch(url, { + method: "POST", + headers, + body: JSON.stringify(body), + signal, + }) +} + +/** Read human-readable text out of an upstream error response + decide whether a new sign-in is needed */ +async function classifyUpstreamError(res) { + let text = "" + try { + text = await res.text() + } catch { + /* ignore */ + } + let code = "" + let message = text.slice(0, 500) + try { + const j = JSON.parse(text) + code = j?.error?.name ?? j?.message ?? j?.code ?? "" + message = j?.error?.message ?? j?.message ?? message + } catch { + /* not JSON: as is */ + } + const signIn = + /NEED_UIN_AND_SKEY|VERIFY_SKEY_UIN_FAILED|VERIFY_USER_FAILED|VERIFY_LOGIN_FAILED|NOT_LOGIN|UNAUTHORIZED|LOGIN_EXPIRED/i.test(`${code} ${message}`) + return { + code: String(code || `${res.status}`), + message: String(message || `OrcaTerm answered ${res.status}`), + signIn: signIn ? "expired" : undefined, + status: res.status, + } +} + +/** + * Check the credential right at sign-in, so the user doesn't store a broken one. + * + * The evidence (measured 2026-10): + * - skey alone / p_uin+p_skey alone → NEED_UIN_AND_SKEY (the cookie was never + * accepted at all) + * - uin + skey but a fake skey → VERIFY_SKEY_UIN_FAILED (it got into the + * verify layer) + * - uin + skey and real → SSE frames start coming right away + * So "a non-auth error came back" means the credential is valid. + */ +async function capiRequest(auth, action, data = {}) { + const t = auth?.ticket ?? {} + const seq = `${Date.now()}-${Math.floor(Math.random() * 1e6)}` + const uin = t.uin || t.p_uin || "" + const url = `${CAPI_URL}?action=${encodeURIComponent(action)}&t=${seq}` + const res = await fetch(url, { + method: "POST", + headers: baseHeaders({ + accept: "application/json", + "content-type": "application/json", + "x-seqid": seq, + "x-referer": WEB_TERMINAL, + "x-csrfcode": csrfCode(t.skey), + cookie: cookieHeader(auth), + }), + // Measured: upstream validates the data field strictly, and an extra sig + // comes back as "property feature should not exist". Sending {action, data} + // as it is works. + body: JSON.stringify({ action, data }), + signal: AbortSignal.timeout(15000), + }) + const text = await res.text() + try { + return JSON.parse(text) + } catch { + return { raw: text } + } +} + +// ---- the plugin itself ------------------------------------------------------ +// The named OrcaTermAuthPlugin export is the plugin entry; _internal below is an +// object for tests, so magpie does not call it as a second plugin. +export const OrcaTermAuthPlugin = async ({ client } = {}) => { + const log = (level, message) => { + try { + // magpie: client.app.log; OpenCode has the same signature + client?.app?.log?.({ body: { service: "orcaterm", level, message } }) + } catch { + /* no client: stay quiet */ + } + } + + /** + * Each account's own state: conversation ids and temporary settings. + * 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 + * 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. + */ + const sessionFor = (auth, sid) => { + const fp = `${fingerprint(auth)}:${sid || "default"}` + let s = sessions.get(fp) + if (!s) { + if (sessions.size > 64) sessions.clear() + s = { + conversationId: `cid-${randomUUID()}-${ASSISTANT.orcaterm}`, + userId: uid("u-"), + } + sessions.set(fp, s) + } + return s + } + + /** + * 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 + * 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. + * + * Context comes from the transcript in `input.input` instead (see + * `toUpstreamBody`), and upstream answers without a registered conversation: + * measured 2026-10-27, a chat with no `/conversation` call returns a normal + * answer, and a two-turn exchange still carries the name from turn 1 through + * the transcript. + */ + + const modelsBlock = Object.fromEntries( + MODEL_SPECS.filter((spec) => spec.listed !== false).map((spec) => [ + spec.id, + { + name: spec.name, + id: spec.id, + limit: { context: spec.context, output: spec.output }, + reasoning: spec.reasoning, + // Upstream answers with text only and never produces tool_calls; + // declaring true would leave the agent waiting for a call it never gets + // and spinning up to its step cap + tool_call: false, + modalities: { input: ["text"] }, + // metered by quota, not billed, so cost is all 0 — magpie then doesn't + // price it as a paid model + cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 }, + }, + ]), + ) + + return { + // ---- provider declaration ----------------------------------------------- + config: async (cfg) => { + cfg.provider ??= {} + cfg.provider[PROVIDER] ??= { + name: "OrcaTerm", + npm: "@ai-sdk/openai-compatible", // chat completions: the gateway converts each vendor's protocol into it + api: `${ASSISTANT_BASE}/chat`, + models: modelsBlock, + } + }, + + auth: { + provider: PROVIDER, + // Also declared on the hook, not only in package.json: siblings that get + // this right (codearts, zcode) do both, and this is what the README's + // "maxConcurrency is 1" describes. OrcaTerm's budget is per account and + // shared with its own desktop client, so one in flight. + maxConcurrency: 1, + + methods: [ + { + type: "oauth", + label: "WeChat QR sign-in (recommended: smallest credential, renewed every two hours)", + /** + * OrcaTerm's own WeChat OAuth, rather than the console session cookie. + * + * A one-off page is served locally (default http://127.0.0.1:4080/login) + * and embeds WeChat's qrconnect widget with `self_redirect: true`, so + * the return lands in the widget's own iframe and OrcaTerm's bridge page + * can postMessage the code back to our page. The user only scans; no + * URL has to be copied, which also closes the window where another tab + * could consume the state first. + * + * Behind a remote deploy the page listens on the server's loopback and + * the browser cannot reach it: `ssh -L 4080:127.0.0.1:4080 `, + * then open the address. ORCATERM_CAPTURE_PORT / _HOST / _BASE override it. + */ + async authorize() { + let started + try { + started = await startWechatLogin() + } catch (err) { + return { + type: "failed", + error: `Could not read the WeChat sign-in configuration: ${err?.message ?? err}. You can paste the cookie pair instead.`, + } + } + + const cap = createLocalCapture({ + appid: started.appid, + redirectUri: started.redirectUri, + state: started.state, + }) + // `ready` rejects on a bind error, so a failure here becomes a failed + // sign-in with a reason instead of a hang. + let pageUrl + try { + pageUrl = await cap.ready + } catch (err) { + cap.close() + return { + type: "failed", + error: `Could not start the local sign-in page (${err?.code ?? err?.message ?? err}). You can paste the cookie pair instead.`, + } + } + + return { + url: pageUrl, + instructions: + "Scan the QR code in the page that opens; it carries on by itself, nothing to copy.\n" + + "(If the page did not open, visit it yourself; behind a remote install, ssh -L 4080:127.0.0.1:4080 first)", + method: "auto", + // No `opened: true` here on purpose: that field means "the plugin + // already opened a browser", and nothing has opened this page yet — + // setting it would stop magpie from opening it and leave the user + // with nothing on screen. + // Test/debug only: close the local page before a scan happens. + // magpie ignores unknown fields. + __cap: cap, + async callback() { + try { + const { code, state } = await cap.wait + const r = await exchangeCode({ code, state }) + // magpie writes the credential only when a `refresh` is present + // (host `save()`); with just a `key` it is stored as type "api" + // and never renewed. + return { + type: "success", + access: r.accessToken, + refresh: r.accessToken, + expires: r.expiresAt ?? Date.now() + 7200 * 1000, + userId: r.userId, + metadata: { + via: "wechat-qr", + userId: r.userId, + nickname: r.nickname, + avatar: r.avatar, + expires: r.expiresAt ?? undefined, + }, + } + } catch (err) { + return { + type: "failed", + error: `${err?.message ?? err}\n\nYou can paste the cookie pair instead.`, + } + } finally { + cap.close() + } + }, + } + }, + }, + { + type: "api", + label: "Paste the OrcaTerm cookie pair (uin=…; skey=…)", + placeholder: "uin=o1234567890; skey=AbCdEf123456...", + }, + ], + + /** + * Renewal. A WeChat access token lives two hours; `OAuthRefreshToken` trades + * it for a fresh one of the same length, so a normal session never sees an + * expiry. + * + * A console cookie has nothing to renew — it lasts until the user signs out + * of the console. + */ + async refresh(auth) { + const bearer = bearerOf(auth) + if (!bearer) return null + try { + const r = await refreshAccessToken(bearer) + return { + key: r.accessToken, + access: r.accessToken, + refresh: r.accessToken, + expires: r.expiresAt ?? undefined, + metadata: { ...(auth?.metadata ?? {}), via: "wechat-qr", expires: r.expiresAt ?? undefined }, + } + } catch (err) { + if (/expired|invalid|失效|过期/i.test(String(err?.message ?? ""))) { + throw Object.assign(new Error(`OrcaTerm sign-in expired, scan again: ${err?.message ?? err}`), { + signIn: "expired", + }) + } + return null + } + }, + + /** + * The exit for every request. magpie's gateway has already turned the + * agent's protocol into Chat Completions; what's left here is: + * OpenAI body → OrcaTerm body → upstream SSE → OpenAI SSE. + */ + async loader(getAuth) { + const auth = await getAuth() + // Two ways to be signed in, decided by the shape of the stored key: a + // WeChat access token (JWT) becomes a Bearer credential, anything else is + // taken as the console cookie pair. + const bearer = bearerOf(auth) + let bound + if (bearer) { + const claims = readTokenClaims(bearer) + if (claims.exp && claims.exp * 1000 < Date.now()) { + throw Object.assign(new Error("OrcaTerm sign-in expired, scan again"), { signIn: "expired" }) + } + bound = { ...auth, bearer, ticket: null } + } else { + const ticket = parseTicket(auth?.key ?? auth?.ticket?.skey ?? auth?.access ?? "") + // Not signed in: an empty object from the loader is the OpenCode + // convention (it means "not configured yet"), and the account shows as + // signed out + if (!ticket) return {} + // Measured: upstream wants uin and skey as a pair, and either one + // missing is a flat NEED_UIN_AND_SKEY. Throwing an error with signIn set + // makes magpie mark the account "needs a new sign-in", instead of + // falling back to an address that is bound to 404. + if (!ticket.uin) { + throw Object.assign( + new Error("OrcaTerm needs uin and skey together: copy uin alongside skey from F12 → Cookies"), + { signIn: "expired" }, + ) + } + bound = { ...auth, ticket } + } + + return { + baseURL: ASSISTANT_BASE, + apiKey: "orcaterm", // magpie fills Authorization with it; upstream doesn't look, but don't leave it empty + + async fetch(input, init) { + const url = typeof input === "string" ? input : input?.url ?? String(input) + // Take the headers the gateway and chat.headers added (the docs' + // 4-layer override order), especially the session id chat.headers + // writes, which is what splits conversations upstream. + const inHeaders = new Headers(init?.headers ?? {}) + const sessionId = inHeaders.get("x-orcaterm-session") || "" + const session = sessionFor(bound, sessionId) + let openaiBody + try { + openaiBody = JSON.parse(bodyToText(init?.body) || "{}") + } catch { + return openaiError(400, "The request body is not valid JSON") + } + + const requested = openaiBody?.model + const model = resolveModel(requested) + const stream = openaiBody?.stream !== false + + const upstream = toUpstreamBody(openaiBody, session) + + // One pacer per account: the limit is per account upstream, and a + // shared one would let one account's cool-down stall the others. + const pacer = pacerFor(bound) + + // Upstream allows about ten chats a minute per account and answers a + // burst with HTTP 200 + `{"code":429,…}` — not an SSE error. Other + // clients on the same account are invisible from here, so this paces + // itself and leaves the rest of the budget alone. + await pacer.wait(init?.signal) + + let res + try { + if (init?.signal?.aborted) return openaiError(499, "the client cancelled the request") + res = await callAssistant({ + auth: bound, + upstream, + model, + assistant: ASSISTANT.orcaterm, + mode: MODE.react, + signal: init?.signal, + }) + if (!res.ok) { + const info = await classifyUpstreamError(res) + // A limit reported by the status line rather than inside the body + // has to cool this account's pacer down as well, or the next + // request walks straight back into it. + if (info.status === 429 || res.status === 429) pacer.penalize() + // Only a confirmed sign-in problem answers 401 (magpie marks the + // account and stops dispatching on a 401 by default); quota gone / + // risk control / 5xx all answer 502, so magpie fails over instead + // of mistaking it for a new sign-in. + const status = info.signIn ? 401 : info.status >= 400 ? info.status : 502 + const e = openaiError(status, `OrcaTerm: ${info.message}`, info.code) + if (info.signIn) e.headers.set("x-magpie-sign-in", info.signIn) + return e + } + + // Upstream can answer 200 with something that isn't SSE at all: a + // JSON error, an HTML sign-in page, a plain-text risk-control + // notice. Anything whose content-type isn't event-stream is treated + // as an error — otherwise the SSE parser swallows it silently and + // the client sees an empty 200 answer, which is painful to diagnose. + const ctype = res.headers.get("content-type") ?? "" + const looksSSE = ctype.includes("event-stream") + const looksHTML = ctype.includes("html") || ctype.includes("xml") + if (!looksSSE) { + const text = await res.text() + let msg = text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 300) + let json = null + try { + json = JSON.parse(text) + msg = json?.error?.message ?? json?.message ?? msg + } catch { + /* HTML / plain text: use the tag-stripped text */ + } + // Classify by the upstream's own words — including the JSON body it + // sends for a rate limit, `{"code":429,"message":"Rate limit + // exceeded: chat-rpm"}`. Answering 502 for that made magpie treat a + // limit as a server fault: no account switch, and the pacer never + // cooled down, so the next request walked into the same wall. + const m = Number(json?.code) === 429 + ? errorStatus("rate limit", pacer) + : errorStatus(`${json?.code ?? ""} ${msg} ${text}`, pacer) + const signIn = /NEED_UIN_AND_SKEY|VERIFY_SKEY_UIN_FAILED|VERIFY_LOGIN_FAILED|VERIFY_USER_FAILED/i.test(msg) + ? "expired" + : undefined + const status = signIn ? 401 : m.status + const e = openaiError( + status, + `OrcaTerm${looksHTML ? " returned a non-SSE response (a gateway or sign-in page may have intercepted it)" : ""}: ${msg || "empty response"}`, + json?.code ?? "upstream_error", + signIn ? undefined : m.type, + ) + if (signIn) e.headers.set("x-magpie-sign-in", signIn) + return e + } + // a missing content-type needs its fallback too: no body is a + // straight error, not a silent empty answer + if (!res.body) return openaiError(502, "OrcaTerm returned an empty response") + + // Upstream reports a failure as `data: [ERROR]: …` while the HTTP + // status stays 200. The head is read first to tell an answer from an + // error: quota gone has to be 429 so magpie switches accounts, and a + // dead sign-in has to be 401 to mark the account — otherwise the + // failure is taken for a normal answer. + const head = await peekAnswer(res.body) + if (head.verdict === "error") { + const code = errorCodeFromHead(head.text) + const m = errorStatus(code, pacer) + const e = openaiError(m.status, `OrcaTerm: ${code}`, code, m.type) + if (m.status === 401) e.headers.set("x-magpie-sign-in", "expired") + return e + } + + // The stream head has already been read; splice it back in before + // handing the stream to the converters, or the opening text is lost + const body = replayBody(head) + + if (stream) return upstreamToOpenAI(body, { model, pacer }) + return await upstreamToJSON(body, { model, pacer }) + } catch (err) { + if (err?.name === "AbortError" || init?.signal?.aborted) { + return openaiError(499, "the client cancelled the request") + } + return openaiError(502, `cannot read OrcaTerm response: ${redactUrl(err?.message ?? err)}`) + } + }, + } + }, + + /** magpie's own hook: show OrcaTerm's Q&A quota on the account card */ + async usage(getAuth) { + const auth = await getAuth() + // A WeChat scan yields an accessToken, not uin/skey — the quota endpoint + // only speaks the console session, so such an account has no quota to + // read. Return no windows rather than an error: the account is fine, and + // "credential is missing uin" would read as a failed sign-in. + const bearer = bearerOf(auth) + if (bearer) return { user: readTokenClaims(bearer).nickname || undefined, windows: [] } + const ticket = parseTicket(auth?.key ?? "") + if (!ticket) return { error: "not signed in", windows: [] } + if (!ticket.uin) return { error: "the credential is missing uin; paste uin and skey again", windows: [] } + const bound = { ...auth, ticket } + + // A throw in usage puts an error on the account card, so everything is + // caught here; the worst case is just "can't read the quota" + try { + // Measured (2026-10-27): the real quota is in DescribeUserBillingStatus' + // usageStats[], not in DescribeUserUsageStats (whose feature only knows + // hunyuan_ai/session_share/secret). + const billing = await capiRequest(bound, "DescribeUserBillingStatus", {}) + const resp = billing?.data?.Response ?? billing?.Response + if (resp?.Error) { + const code = resp.Error.Code ?? "" + if (/VERIFY_SKEY_UIN_FAILED|VERIFY_USER_FAILED|VERIFY_LOGIN_FAILED|NOT_LOGIN/i.test(code)) { + return { error: `OrcaTerm refused the sign-in (${code}); sign in again`, windows: [], signIn: "expired" } + } + return { error: `OrcaTerm could not read the allowance: ${code || resp.Error.Message}`, windows: [] } + } + + const stats = Array.isArray(resp?.usageStats) ? resp.usageStats : [] + const windows = [] + for (const st of stats) { + const feature = st?.feature ?? "" + // hunyuan_ai = the AI Q&A turn quota; the other features are session + // sharing / keys / storage, which aren't what we want + if (feature !== "hunyuan_ai") continue + const limit = Number(st.quotaLimit) + const used = Number(st.quotaUsed) + if (!Number.isFinite(limit) || limit < 0) continue + windows.push({ + name: "AI Q&A", + used: limit > 0 ? Math.min(999, Math.round((used / limit) * 100)) : 0, + display: `${used} / ${limit}`, + amount: used, + limit, + unit: "questions", + ...(st.quotaEndDate ? { resetsAt: toIso(st.quotaEndDate) } : {}), + ...(st.quotaStartDate && st.quotaEndDate + ? { + span: Math.max( + 1, + Math.round((Date.parse(st.quotaEndDate) - Date.parse(st.quotaStartDate)) / 1000), + ), + } + : {}), + }) + } + + // also pick up the account name, so the account card reads clearly + let user + try { + const info = await capiRequest(bound, "GetUserInfo", {}) + const ir = info?.data?.Response ?? info?.Response + user = ir?.nickName ?? ir?.username ?? ir?.uin + } catch { + /* fine if it can't be read */ + } + + if (!windows.length) { + return { + user, + plan: resp?.roleType ? `OrcaTerm ${resp.roleType}` : undefined, + windows: [], + error: "OrcaTerm returned no AI question allowance field", + } + } + return { + user, + plan: resp?.roleType ? `OrcaTerm ${resp.roleType}` : undefined, + windows, + } + } catch (err) { + return { error: `could not read the allowance: ${redactUrl(err?.message ?? err)}`, windows: [] } + } + }, + + }, + + // ---- 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. + "chat.headers": async (input, output) => { + if (input?.model?.providerID !== PROVIDER) return + try { + output.headers["x-orcaterm-session"] = input.sessionID || "default" + } catch { + /* ignore */ + } + }, + } +} + +function toIso(v) { + if (v === undefined || v === null || v === "") return undefined + if (typeof v === "number") return new Date(v < 1e12 ? v * 1000 : v).toISOString() + const t = Date.parse(String(v)) + return Number.isNaN(t) ? undefined : new Date(t).toISOString() +} + +// ---- test exit (magpie calls only exported functions as plugins; _internal is +// an object, never called) ---------------------------------------------------- +// Everything the tests reach for, as the other packages do: nothing here is +// part of the provider contract. +export const _internal = { + PROVIDER, + MODEL_SPECS, + ALIAS_TO_ID, + ASSISTANT, + ASSISTANT_BASE, + CAPI_URL, + WEB_TERMINAL, + uid, + inputId, + createPacer, + pacerFor, + createLocalCapture, + isEnvelope, + isActionEnvelope, + appendedEnvelopeAt, + unwrapAnswer, + stripTrailingEnvelope, + createAnswerExtractor, + csrfCode, + parseTicket, + cookieHeader, + fingerprint, + baseHeaders, + bodyToText, + resolveModel, + toUpstreamBody, + takeSseLines, + parseSseLine, + fullToDelta, + errorStatus, + peekAnswer, + classifyHead, + errorCodeFromHead, + replayBody, + upstreamToOpenAI, + upstreamToJSON, + redactUrl, + openaiError, + callAssistant, + classifyUpstreamError, + capiRequest, + toIso, +} + + diff --git a/packages/orcaterm/package.json b/packages/orcaterm/package.json new file mode 100644 index 0000000..2ba30bb --- /dev/null +++ b/packages/orcaterm/package.json @@ -0,0 +1,20 @@ +{ + "name": "@magpie-community/opencode-orcaterm-auth", + "version": "0.1.0", + "description": "OrcaTerm (Tencent Cloud 遨驰终端) AI quota as an OpenAI-compatible provider for magpie and OpenCode", + "type": "module", + "main": "./index.mjs", + "exports": "./index.mjs", + "files": ["index.mjs", "wechat.mjs", "README.md", "LICENSE"], + "keywords": ["opencode", "opencode-plugin", "magpie", "orcaterm", "tencent"], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/orcaterm" + }, + "magpie": { + "maxConcurrency": 1, + "icon": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cdefs%3E%3ClinearGradient id='a' x1='0' y1='1' x2='1' y2='0'%3E%3Cstop offset='0' stop-color='%231C74C7'/%3E%3Cstop offset='.55' stop-color='%238870FF'/%3E%3Cstop offset='1' stop-color='%23FEAECB'/%3E%3C/linearGradient%3E%3C/defs%3E%3Cpath fill='url(%23a)' d='M56 54c-7-12.5-26.2-13.2-35.5-22.5C14.4 25.2 14 16.4 16.7 11 19.5 5.3 25.9 1 33.1 1c2.7 0 8 1 11 3 14.1 9.4 18 22.7 19.6 28.5 1.6 5.8 1.5 14.5-7.7 21.5z'/%3E%3Cpath fill='url(%23a)' opacity='.85' d='M86.2 58C78.2 75.5 48.2 70.5 33.2 64 20.6 66.3 15.2 72 15.2 81c0 9.5 6.2 17.4 15.5 18.5 9.3 1.1 22.6-5.5 33-14 9-7.4 19.8-17.6 22.5-27.5z'/%3E%3C/svg%3E" + } +} diff --git a/packages/orcaterm/peek.test.mjs b/packages/orcaterm/peek.test.mjs new file mode 100644 index 0000000..27b06f2 --- /dev/null +++ b/packages/orcaterm/peek.test.mjs @@ -0,0 +1,138 @@ +// A refusal arrives inside the stream with HTTP 200 still on the status line, +// so the status alone says nothing: the head of the stream has to be read +// before an answer is handed back. These check that a used-up allowance is +// answered as 429, a dead sign-in as 401, and a real answer as an answer — +// with the peeked bytes replayed, so no text is lost to the peek. +import { afterEach, expect, test } from "bun:test" +import { OrcaTermAuthPlugin, _internal } from "./index.mjs" + +// The suite fires far more than the account's ten-a-minute budget; lift the +// pacer so these tests measure the plugin, not the limiter. +process.env.ORCATERM_NO_PACE = "1" + + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const frame = (o) => `data: ${JSON.stringify(o)}\n\n` + +/** Answer a chat request, with the upstream body being `body`. */ +const ask = async (body, { stream = true } = {}) => { + globalThis.fetch = async () => new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } }) + const hooks = await OrcaTermAuthPlugin({ client: { app: { log: () => {} } } }) + const opts = await hooks.auth.loader(async () => ({ type: "api", key: "uin=o1234567890; skey=deadbeef" })) + return opts.fetch("https://lightai.cloud.tencent.com/assistant/chat", { + method: "POST", + body: JSON.stringify({ model: "deepseek", stream, messages: [{ role: "user", content: "hi" }] }), + }) +} + +const bodyOf = (frames) => + new ReadableStream({ + start(c) { + for (const f of frames) c.enqueue(new TextEncoder().encode(f)) + c.close() + }, + }) + +// A used-up monthly allowance looks like an answer unless the head is read +// first: magpie would neither fail over nor rest the account. +test("a quota refusal is answered 429, not as text", async () => { + const res = await ask(bodyOf([frame({}) && "data: [ERROR]: 本月问答次数已用完\n\n"])) + expect(res.status).toBe(429) + const j = await res.json() + expect(j.error.message).toContain("次数已用完") +}) + +test("a rate-limit refusal is answered 429", async () => { + const res = await ask(bodyOf(["data: [ERROR]: rate limit exceeded\n\n"])) + expect(res.status).toBe(429) +}) + +// A dead sign-in is the account's problem, not the request's: magpie marks +// it and stops sending, rather than failing over forever. +test("a refused sign-in is answered 401 and marked", async () => { + const res = await ask(bodyOf(["data: [ERROR]: VERIFY_SKEY_UIN_FAILED\n\n"])) + expect(res.status).toBe(401) + expect(res.headers.get("x-magpie-sign-in")).toBe("expired") +}) + +test("any other upstream refusal is answered 502", async () => { + const res = await ask(bodyOf(["data: [ERROR]: model unavailable\n\n"])) + expect(res.status).toBe(502) +}) + +// The peek reads bytes before deciding; those bytes have to go back into the +// stream or the start of the answer is lost. +test("a real answer passes through with its first frame intact", async () => { + const res = await ask(bodyOf([frame({ content: "你" }), frame({ content: "好" }), "data: [DONE]\n\n"])) + expect(res.status).toBe(200) + const text = await res.text() + expect(text).toContain("你") + expect(text).toContain("好") +}) + +// An answer whose head is only whitespace before the first frame must still +// be recognised as an answer rather than held until the peek limit. +test("leading noise before the first frame does not hide the answer", async () => { + const res = await ask(bodyOf(["\n\n", frame({ content: "ok" }), "data: [DONE]\n\n"])) + expect(res.status).toBe(200) + expect(await res.text()).toContain("ok") +}) + +// The same refusal without streaming must not become a 200 either. +test("a quota refusal in a non-streaming request is 429", async () => { + const res = await ask(bodyOf(["data: [ERROR]: 本月问答次数已用完\n\n"]), { stream: false }) + expect(res.status).toBe(429) +}) + +// Reading the head must not consume the whole stream: a long answer still +// arrives in full. +test("a long answer is not truncated by the peek", async () => { + const frames = [] + for (let i = 0; i < 200; i++) frames.push(frame({ content: `w${i} ` })) + frames.push("data: [DONE]\n\n") + const res = await ask(bodyOf(frames)) + expect(res.status).toBe(200) + // Compare the deltas joined, not the raw body: where a chunk boundary falls + // is the plugin's business, and asserting on the raw JSON made this fail the + // moment the extractor's hold-back changed size. + const text = await res.text() + let out = "" + for (const line of text.split("\n")) { + const t = line.trim() + if (!t.startsWith("data:")) continue + const payload = t.slice(5).trim() + if (payload === "[DONE]") continue + try { + const d = JSON.parse(payload).choices?.[0]?.delta + if (d?.content) out += d.content + } catch { + /* not a chunk */ + } + } + const expected = Array.from({ length: 200 }, (_, i) => `w${i} `).join("") + expect(out).toBe(expected) +}) + +// The OpenAI error body carries both a class and a code, and they are not +// the same thing: `type` is the class magpie reasons about, `code` says what +// the upstream said. Passing the class in both places loses the upstream's +// own words, which is what a user needs to see. +test("a refusal keeps the upstream's words in code, the class in type", async () => { + const res = await ask(bodyOf(["data: [ERROR]: 本月问答次数已用完\n\n"])) + expect(res.status).toBe(429) + const j = await res.json() + expect(j.error.type).toBe("rate_limit_error") + expect(j.error.code).toContain("次数已用完") + expect(j.error.code).not.toBe("rate_limit_error") +}) + +// classifyHead is what decides: a frame carrying text is an answer, an +// [ERROR] frame is not, and a quiet stream that has ended is an answer. +test("classifyHead tells answers from refusals", () => { + expect(_internal.errorStatus("额度已用完")).toMatchObject({ status: 429 }) + expect(_internal.errorStatus("限流")).toMatchObject({ status: 429 }) + expect(_internal.errorStatus("VERIFY_USER_FAILED")).toMatchObject({ status: 401 }) + expect(_internal.errorStatus("something else")).toMatchObject({ status: 502 }) +}) diff --git a/packages/orcaterm/request.test.mjs b/packages/orcaterm/request.test.mjs new file mode 100644 index 0000000..256ca39 --- /dev/null +++ b/packages/orcaterm/request.test.mjs @@ -0,0 +1,123 @@ +// What magpie hands the plugin is a Chat Completions body; OrcaTerm's +// assistant takes one user turn plus a history list and has no system +// role. This checks that the translation keeps the conversation's meaning: +// system text survives, turns stay in order, and tool traffic degrades to +// text instead of being dropped. +import { expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +// The suite fires far more than the account's ten-a-minute budget; lift the +// pacer so these tests measure the plugin, not the limiter. +process.env.ORCATERM_NO_PACE = "1" + + +const turn = (messages) => _internal.toUpstreamBody({ messages }, { conversationId: "cid-1", userId: "u-1" }) + +test("system text is carried as a prefix, the last user turn as the input", () => { + const up = turn([ + { role: "system", content: "you are a terminal assistant" }, + { role: "user", content: "first" }, + { role: "assistant", content: "first answer" }, + { role: "user", content: "second" }, + ]) + expect(up.conversationId).toBe("cid-1") + expect(up.input.input.startsWith("[system instructions")).toBe(true) + expect(up.input.input.endsWith("second")).toBe(true) + // The earlier turns travel as a transcript in the text: magpie gives every + // request a fresh sessionID, so nothing on the wire can rely on server-side + // conversation state (measured 2026-10-27). + expect(up.input.input).toContain("[earlier in this conversation]") + expect(up.input.input).toContain("user: first") + expect(up.input.input).toContain("assistant: first answer") + // and nothing goes up as historyMessages + expect(up.input.historyMessages).toEqual([]) + expect(up.input.type).toBe("start") + expect(up.stream).toBe(true) +}) + +// OrcaTerm runs its own tools server-side; the client's tool calls can only +// be described, so they become text the model can read. +test("tool calls and their results become text, nothing is lost", () => { + const up = turn([ + { role: "user", content: "what's the weather" }, + { role: "assistant", content: "", tool_calls: [{ id: "c1", function: { name: "get_weather", arguments: '{"city":"SZ"}' } }] }, + { role: "tool", tool_call_id: "c1", content: "sunny 30C" }, + ]) + // no history is sent, so the tool traffic has to ride along in the text + const all = up.input.input + expect(all).toContain("get_weather") + expect(all).toContain("sunny 30C") + // the tool result is the last turn, so it is what gets asked + expect(up.input.input).toContain("tool result") +}) + +// An empty input is answered with a 400 by the assistant, so an empty +// conversation has to be given something to reply to. +test("an empty conversation still sends a non-empty input", () => { + expect(turn([]).input.input.trim().length).toBeGreaterThan(0) + expect(turn([{ role: "system", content: "be brief" }]).input.input.trim().length).toBeGreaterThan(0) +}) + +test("image parts are noted, text parts kept", () => { + const up = turn([ + { + role: "user", + content: [ + { type: "text", text: "look" }, + { type: "image_url", image_url: { url: "http://x/y.png" } }, + ], + }, + ]) + expect(up.input.input).toContain("look") + expect(up.input.input).toContain("[image]") +}) + +// A model id magpie may pass with its provider prefix, in any case, with +// padding — and one it doesn't know, which must reach the endpoint as is +// rather than be swallowed. +test("model ids resolve through aliases, prefixes and case", () => { + expect(_internal.resolveModel("deepseek")).toBe("TokenHub/deepseek-v4-pro") + expect(_internal.resolveModel("orcaterm/kimi")).toBe("TokenHub/kimi-k3") + expect(_internal.resolveModel(" GLM-4.7-THINKING ")).toBe("glm-4.7-thinking") + expect(_internal.resolveModel("some-new-model")).toBe("some-new-model") + // a bare prefix must fall back to a real model, not send an empty id + expect(_internal.resolveModel("orcaterm/")).toBe("TokenHub/deepseek-v4-pro") + expect(_internal.resolveModel(undefined)).toBe("TokenHub/deepseek-v4-pro") +}) + +// OrcaTerm's picker shows a label, and the id sent upstream is a different +// string (`newModelId` vs `modelName` in its own table). Sending the label is +// what made upstream answer "LLM(x) is not loaded", and `hy3-preview` is a +// label, not an id — it answers 401. The label must resolve to the working id. +test("labels resolve to the ids upstream actually serves", () => { + expect(_internal.resolveModel("Hy3-preview")).toBe("Hunyuan3/hy3") + expect(_internal.resolveModel("hy3-preview")).toBe("Hunyuan3/hy3") + expect(_internal.resolveModel("Deepseek-V4-Pro")).toBe("TokenHub/deepseek-v4-pro") + expect(_internal.resolveModel("GLM-5.2")).toBe("TokenHub/glm-5.2") + expect(_internal.resolveModel("Kimi-k2.6")).toBe("TokenHub/kimi-k3") +}) + +// Upstream answered `Invalid inputId: in-…` to the ids this plugin used to +// invent, so the shape matters: the web client sends a plain uuid v4 in +// `input.id` (module 73383's Ub) and the same value in `x-seqid`. A prefix of +// our own, however unique, is not that. +test("the input id is the web client's uuid v4, and x-seqid is that same id", async () => { + const up = turn([{ role: "user", content: "hi" }]) + expect(up.input.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + // and a fresh one per request, never a fixed value + expect(turn([{ role: "user", content: "hi" }]).input.id).not.toBe(up.input.id) +}) + +// Upstream does not answer in prose: the whole reply is the assistant's own +// message object, and the text is its taskCompletion. Passed on raw, an agent +// showed `{"action": "completion", …}` as the answer. +test("the answer is unwrapped from the action envelope, alone or after prose", () => { + const one = JSON.stringify({ action: "completion", ph_1: "--", taskCompletion: "答案" }) + expect(_internal.unwrapAnswer(one)).toBe("答案") + // fenced the way the assistant fences code + expect(_internal.unwrapAnswer("```json\n" + one + "\n```")).toBe("答案") + // prose first, envelope after it: the prose is the answer + expect(_internal.stripTrailingEnvelope("已记住。\n" + one)).toBe("已记住。\n") + // and a reply that is not an envelope is left alone + expect(_internal.unwrapAnswer("用 {花括号} 表示集合")).toBe("用 {花括号} 表示集合") +}) diff --git a/packages/orcaterm/review.test.mjs b/packages/orcaterm/review.test.mjs new file mode 100644 index 0000000..cef0bee --- /dev/null +++ b/packages/orcaterm/review.test.mjs @@ -0,0 +1,351 @@ +import { test, expect } from "bun:test" +import { _internal, OrcaTermAuthPlugin } from "./index.mjs" + +// Point 5 — the /conversation POST is gone. Proven without the network: run one +// chat against a stubbed fetch and look at every URL it asked for. +test("a chat makes exactly one upstream request, and it is not /conversation", async () => { + const seen = [] + const realFetch = globalThis.fetch + const frame = (content) => + `data: ${JSON.stringify({ content, reasoningContent: "", type: "ai", code: 0 })}\n\n` + globalThis.fetch = async (url) => { + seen.push(String(url)) + return new Response(frame("hi") + "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 res = await loader.fetch("https://lightai.cloud.tencent.com/assistant/chat", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "TokenHub/glm-5.3", stream: false, messages: [{ role: "user", content: "hi" }] }), + }) + expect(res.status).toBe(200) + expect(seen.length).toBe(1) + expect(seen[0]).toContain("/assistant/chat") + expect(seen.some((u) => u.includes("/conversation"))).toBe(false) + } finally { + globalThis.fetch = realFetch + } +}) + +// Each case here is one of the must-fix points from the review, written so the +// old behaviour fails it. + +// Point 3 — `appendedEnvelopeAt` used to cut at any `{"action":` in the reply. +test("a JSON object with an action key inside a reply is not treated as the envelope", () => { + const redux = 'Before.\n{"action": "INCREMENT", "payload": 1}\nAfter that, more prose.' + const ex = _internal.createAnswerExtractor() + let out = ex.push(redux) + out += ex.finish() + expect(out).toBe(redux) +}) + +test("a trailing action object that is not the assistant's envelope is kept", () => { + const redux = 'Answer follows.\n{"action": "INCREMENT"}' + expect(_internal.stripTrailingEnvelope(redux)).toBe(redux) + expect(_internal.isEnvelope(redux.replace("Answer follows.\n", ""))).toBe(false) +}) + +test("a reducer the user asked for is not mistaken for an envelope", () => { + // `content` is a field the client reads a reply from, so a verb the envelope + // never uses must not be enough to cut the snippet + const snippet = 'Write the reducer like this:\n{"action": "SAVE", "content": "hello"}' + expect(_internal.stripTrailingEnvelope(snippet)).toBe(snippet) + const ex = _internal.createAnswerExtractor() + const out = ex.push(snippet) + ex.finish() + expect(out).toBe(snippet) +}) + +test("a reply that merely mentions the field name is not cut", () => { + // The extractor used to close as soon as `"taskCompletion": "` appeared + // anywhere, so a reply quoting the field was truncated and reported as a + // normal stop. + const mentioning = 'Quote the field like this: "taskCompletion": "the answer". That is all.' + const ex = _internal.createAnswerExtractor() + let out = ex.push(mentioning) + out += ex.finish() + expect(out).toBe(mentioning) +}) + +test("an inline envelope inside a longer answer is not cut", () => { + const inline = 'Example: {"action": "completion", "taskCompletion": "x"} then done.' + // both delivery shapes, because the per-character one used to close the stream + // the instant the object completed and drop the rest + const once = _internal.createAnswerExtractor() + expect(once.push(inline) + once.finish()).toBe(inline) + + const perChar = _internal.createAnswerExtractor() + let out = "" + for (const ch of inline) out += perChar.push(ch) + out += perChar.finish() + expect(out).toBe(inline) +}) + +test("a stream that ends inside the envelope does not splice raw JSON into the answer", () => { + // No [DONE]: the upstream died mid-envelope. `sent` counts decoded answer + // characters, so comparing it against the raw length used to emit garbage. + const partial = '{"action":"completion","taskCompletion":"Hello wor' + const ex = _internal.createAnswerExtractor() + const out = ex.push(partial) + ex.finish() + expect(out).toBe("Hello wor") + expect(out).not.toContain("taskCompletion") +}) + +test("a capitalised action key is still recognised as the envelope", () => { + expect(_internal.unwrapAnswer('{"Action": "completion", "taskCompletion": "Hello"}')).toBe("Hello") +}) + +test("a long run of whitespace inside the opening does not leak the envelope", () => { + const prose = "Answer text here. " + const env = `{${" ".repeat(30)}"action": "completion", "taskCompletion": "hi"}` + const ex = _internal.createAnswerExtractor() + let out = ex.push(prose) + ex.push(env) + out += ex.finish() + expect(out).toBe(prose) +}) + +test("a context-length error is not mistaken for a rate limit", () => { + // `/exceeded/` used to catch this and mark the account, which every account + // would hit for the same request. + const m = _internal.errorStatus("context length exceeded", null) + expect(m.status).toBe(502) + // the real quota wording still maps to 429 + expect(_internal.errorStatus("本月问答次数已用完", null).status).toBe(429) +}) + +test("pacing wait honours an aborted signal instead of sleeping it out", async () => { + const saved = process.env.ORCATERM_NO_PACE + delete process.env.ORCATERM_NO_PACE + try { + const p = _internal.createPacer({ limit: 1, windowMs: 60000, useEnv: false }) + await p.wait() // fills the window + const ctrl = new AbortController() + const t0 = Date.now() + const waiting = p.wait(ctrl.signal) + setTimeout(() => ctrl.abort(), 50) + await waiting + expect(Date.now() - t0).toBeLessThan(1500) + } finally { + if (saved !== undefined) process.env.ORCATERM_NO_PACE = saved + } +}) + +test("an unrecognised verb that still carries taskCompletion is treated as the envelope", () => { + const env = '{"action": "some-new-verb", "taskCompletion": "hi"}' + expect(_internal.isEnvelope(env)).toBe(true) + expect(_internal.unwrapAnswer(env)).toBe("hi") +}) + +test("the assistant's own trailing envelope is still cut", () => { + const env = JSON.stringify({ action: "completion", ph_1: "--", taskCompletion: "答案" }) + const withProse = `已记住。\n${env}` + expect(_internal.stripTrailingEnvelope(withProse)).toBe("已记住。\n") + + const ex = _internal.createAnswerExtractor() + let out = ex.push("已记住。\n") + out += ex.push(env) + out += ex.finish() + expect(out).toBe("已记住。\n") +}) + +test("a pure envelope still yields only its taskCompletion", () => { + const env = JSON.stringify({ action: "completion", taskCompletion: "hi" }) + const ex = _internal.createAnswerExtractor() + let out = ex.push(env) + out += ex.finish() + expect(out).toBe("hi") +}) + +// Point 6 — the ids the README says not to use must not appear in provider.models. +test("provider.models lists only the recommended nine", () => { + const listed = _internal.MODEL_SPECS.filter((s) => s.listed !== false).map((s) => s.id) + const hidden = _internal.MODEL_SPECS.filter((s) => s.listed === false).map((s) => s.id) + expect(listed.length).toBe(9) + expect(hidden.length).toBe(8) + // hidden ones still resolve, so an existing config does not break + for (const id of [...listed, ...hidden]) expect(_internal.resolveModel(id)).toBe(id) + expect(_internal.resolveModel("qwen3")).toBe("qwen3") + expect(_internal.resolveModel("deepseek-reasoner")).toBe("deepseek-reasoner") +}) + +// Point 4 — a pacer per account, so one account's cool-down cannot stall another. +test("pacers are per account", () => { + const a = _internal.pacerFor({ ticket: { uin: "u1", skey: "s1" } }) + const b = _internal.pacerFor({ ticket: { uin: "u2", skey: "s2" } }) + expect(a).not.toBe(b) + // the same account gets the same pacer back + const a2 = _internal.pacerFor({ ticket: { uin: "u1", skey: "s1" } }) + expect(a2).toBe(a) +}) + +// Point 2 — the JSON refusal has to reach errorStatus, so 429 stays 429. +test("a JSON rate-limit body is classified as 429", () => { + const body = '{"code":429,"data":null,"message":"Rate limit exceeded: chat-rpm"}' + const m = _internal.errorStatus(`${429} Rate limit exceeded: chat-rpm ${body}`, null) + expect(m.status).toBe(429) +}) + +test("a JSON quota refusal is classified as 429 too", () => { + const body = '{"code":500,"message":"额度已用完"}' + expect(_internal.errorStatus(`500 额度已用完 ${body}`, null).status).toBe(429) +}) + +test("errorStatus penalises the pacer it is given, and only that one", () => { + const saved = process.env.ORCATERM_NO_PACE + delete process.env.ORCATERM_NO_PACE + try { + const a = _internal.createPacer({ limit: 10, windowMs: 60000, useEnv: false }) + const b = _internal.createPacer({ limit: 10, windowMs: 60000, useEnv: false }) + _internal.errorStatus("Rate limit exceeded", a) + expect(a.blockedForTest()).toBeGreaterThan(0) + expect(b.blockedForTest()).toBe(0) + } finally { + if (saved !== undefined) process.env.ORCATERM_NO_PACE = saved + } +}) + +// The minor points: the local sign-in page must not accept a code from anyone else. +test("/cb accepts the machine's own addresses when bound to a wildcard", async () => { + // `ORCATERM_CAPTURE_HOST=0.0.0.0` is documented as a way to reach the page from + // elsewhere. It has to keep working, or the knob hands out a page whose own POST + // is refused. + const saved = process.env.ORCATERM_CAPTURE_HOST + process.env.ORCATERM_CAPTURE_HOST = "0.0.0.0" + const os = await import("node:os") + const cap = _internal.createLocalCapture({ + appid: "wxtest", + redirectUri: "https://orcaterm.com/oauth/wechat/bridge", + state: "state-abc", + timeoutMs: 5000, + }) + try { + const page = await cap.ready + const port = new URL(page).port + const lan = Object.values(os.networkInterfaces()) + .flat() + .find((n) => n && n.family === "IPv4" && !n.internal)?.address + if (lan) { + const res = await fetch(`http://127.0.0.1:${port}/cb`, { + method: "POST", + headers: { "content-type": "application/json", origin: `http://${lan}:${port}` }, + body: JSON.stringify({ code: "LAN_CODE", state: "state-abc" }), + }) + expect((await res.json()).ok).toBe(true) + } + // and a hostname is still refused, which is what rebinding would use + const forged = await fetch(`http://127.0.0.1:${port}/cb`, { + method: "POST", + headers: { "content-type": "application/json", origin: "http://evil.example" }, + body: JSON.stringify({ code: "X", state: "state-abc" }), + }) + expect(forged.status).toBe(403) + } finally { + cap.close() + if (saved === undefined) delete process.env.ORCATERM_CAPTURE_HOST + else process.env.ORCATERM_CAPTURE_HOST = saved + } +}) + +test("/cb refuses a rebinding page that matches Origin with its own Host", async () => { + // The state is in the page's HTML, so reading it is not the hard part. The + // check has to be against an origin the request cannot supply: comparing + // Origin with the request's own Host is a tautology a rebinding page satisfies. + const cap = _internal.createLocalCapture({ + appid: "wxtest", + redirectUri: "https://orcaterm.com/oauth/wechat/bridge", + state: "state-abc", + timeoutMs: 5000, + }) + try { + const page = await cap.ready + const html = await (await fetch(page)).text() + const state = /const STATE = "([^"]+)"/.exec(html)?.[1] ?? "" + expect(state).toBe("state-abc") + const res = await fetch(new URL("/cb", page), { + method: "POST", + headers: { "content-type": "application/json", origin: "http://evil.example", host: "evil.example" }, + body: JSON.stringify({ code: "ATTACKER_CODE", state }), + }) + expect(res.status).toBe(403) + expect((await res.json()).ok).toBe(false) + } finally { + cap.close() + } +}) + +test("/cb refuses a POST from another origin", async () => { + const cap = _internal.createLocalCapture({ + appid: "wxtest", + redirectUri: "https://orcaterm.com/oauth/wechat/bridge", + state: "state-abc", + timeoutMs: 5000, + }) + try { + const page = await cap.ready + const cb = new URL("/cb", page) + const res = await fetch(cb, { + method: "POST", + headers: { "content-type": "application/json", origin: "https://evil.example" }, + body: JSON.stringify({ code: "C", state: "state-abc" }), + }) + expect(res.status).toBe(403) + expect((await res.json()).ok).toBe(false) + } finally { + cap.close() + } +}) + +test("/cb refuses a state it did not issue", async () => { + const cap = _internal.createLocalCapture({ + appid: "wxtest", + redirectUri: "https://orcaterm.com/oauth/wechat/bridge", + state: "state-abc", + timeoutMs: 5000, + }) + try { + const page = await cap.ready + const origin = new URL(page).origin + const res = await fetch(new URL("/cb", page), { + method: "POST", + headers: { "content-type": "application/json", origin }, + body: JSON.stringify({ code: "C", state: "someone-elses-state" }), + }) + const j = await res.json() + expect(j.ok).toBe(false) + expect(String(j.error)).toContain("state") + } finally { + cap.close() + } +}) + +test("/cb accepts its own origin and state, and the page carries the checks", async () => { + const cap = _internal.createLocalCapture({ + appid: "wxtest", + redirectUri: "https://orcaterm.com/oauth/wechat/bridge", + state: "state-abc", + timeoutMs: 5000, + }) + try { + const page = await cap.ready + const origin = new URL(page).origin + const html = await (await fetch(page)).text() + expect(html).toContain("https://orcaterm.com") // the origin the message must come from + expect(html).toContain("self_redirect: true") + const res = await fetch(new URL("/cb", page), { + method: "POST", + headers: { "content-type": "application/json", origin }, + body: JSON.stringify({ code: "C", state: "state-abc" }), + }) + expect((await res.json()).ok).toBe(true) + expect(await cap.wait).toEqual({ code: "C", state: "state-abc" }) + } finally { + cap.close() + } +}) diff --git a/packages/orcaterm/signin.test.mjs b/packages/orcaterm/signin.test.mjs new file mode 100644 index 0000000..34f4712 --- /dev/null +++ b/packages/orcaterm/signin.test.mjs @@ -0,0 +1,113 @@ +// The credential shape OrcaTerm's AI endpoint accepts, and what it says +// when it doesn't: `uin` and `skey` must both be present and real. Only +// `skey` or only `p_uin`+`p_skey` is answered with NEED_UIN_AND_SKEY; +// a wrong pair gets as far as VERIFY_SKEY_UIN_FAILED, which is how a bad +// sign-in is told from a missing one. +import { afterEach, expect, test } from "bun:test" +import { OrcaTermAuthPlugin, _internal } from "./index.mjs" + +// The suite fires far more than the account's ten-a-minute budget; lift the +// pacer so these tests measure the plugin, not the limiter. +process.env.ORCATERM_NO_PACE = "1" + + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const plugin = () => OrcaTermAuthPlugin({ client: { app: { log: () => {} } } }) + +const sign = async (key) => { + const hooks = await plugin() + const opts = await hooks.auth.loader(async () => ({ type: "api", key })) + return opts +} + +// Every way a user may paste the pair: a whole Cookie header, a `k=v; k=v` +// fragment, a bare pair, or `p_uin`/`p_skey` under their prefixed names. +test("parseTicket reads the pair however it was pasted", () => { + const header = _internal.parseTicket("uin=o123; skey=AAA") + expect(header.uin).toBe("o123") + expect(header.skey).toBe("AAA") + + const bare = _internal.parseTicket("skinnySecret") + expect(bare.skey).toBe("skinnySecret") + expect(bare.uin).toBe("") + + // p_* names are the same cookies under another name: they are lifted to + // the plain ones, since that is what the endpoint checks for. + const prefixed = _internal.parseTicket("p_uin=o9; p_skey=BBB") + expect(prefixed.uin).toBe("o9") + expect(prefixed.skey).toBe("BBB") + + expect(_internal.parseTicket("")).toBeNull() +}) + +test("cookieHeader needs both halves; one alone makes no header", () => { + expect(_internal.cookieHeader({ ticket: { skey: "AAA" } })).toBe("") + const both = _internal.cookieHeader({ ticket: { uin: "o123", skey: "AAA" } }) + expect(both).toContain("uin=o123") + expect(both).toContain("skey=AAA") +}) + +// The sign-in is refused at the loader, before any request goes out, so a +// half pair never reaches the endpoint and never shows up as a failed +// request in the account's history. +test("a key with no uin is refused as expired, not sent", async () => { + await expect(sign("justASkey")).rejects.toMatchObject({ signIn: "expired" }) +}) + +test("no key at all leaves the account unsigned rather than failing", async () => { + expect(await sign("")).toEqual({}) +}) + +// The upstream answers 200 with a JSON body even for a refusal, so the +// status code alone would read as success: the body is what decides. +test("a refused sign-in comes back as 401 and marks the account", async () => { + globalThis.fetch = async () => + new Response(JSON.stringify({ code: 500, message: "VERIFY_SKEY_UIN_FAILED" }), { + status: 200, + headers: { "content-type": "application/json" }, + }) + const opts = await sign("uin=o1234567890; skey=deadbeef") + const res = await opts.fetch("https://lightai.cloud.tencent.com/assistant/chat", { + method: "POST", + body: JSON.stringify({ model: "deepseek", stream: true, messages: [{ role: "user", content: "hi" }] }), + }) + expect(res.status).toBe(401) + expect(res.headers.get("x-magpie-sign-in")).toBe("expired") +}) + +// NEED_UIN_AND_SKEY means the pair was never read, which is also a sign-in +// problem rather than an upstream fault. +test("a pair the endpoint won't read also marks the account", async () => { + globalThis.fetch = async () => + new Response(JSON.stringify({ code: 500, message: "NEED_UIN_AND_SKEY" }), { + status: 200, + headers: { "content-type": "application/json" }, + }) + const opts = await sign("uin=o1; skey=AA") + const res = await opts.fetch("https://lightai.cloud.tencent.com/assistant/chat", { + method: "POST", + body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }), + }) + expect(res.status).toBe(401) + expect(res.headers.get("x-magpie-sign-in")).toBe("expired") +}) + +// Anything else — a quota wall, a rate limit, an upstream 5xx — is not the +// sign-in's fault, and must not mark the account: magpie would stop sending +// to a perfectly good account. +test("a non-auth failure is passed on without marking the account", async () => { + globalThis.fetch = async () => + new Response(JSON.stringify({ code: 500, message: "model_rate_limit" }), { + status: 200, + headers: { "content-type": "application/json" }, + }) + const opts = await sign("uin=o1; skey=AA") + const res = await opts.fetch("https://lightai.cloud.tencent.com/assistant/chat", { + method: "POST", + body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }), + }) + expect(res.status).not.toBe(401) + expect(res.headers.get("x-magpie-sign-in")).toBeNull() +}) diff --git a/packages/orcaterm/stream.test.mjs b/packages/orcaterm/stream.test.mjs new file mode 100644 index 0000000..885dd87 --- /dev/null +++ b/packages/orcaterm/stream.test.mjs @@ -0,0 +1,108 @@ +// The upstream streams SSE frames whose `content` is this frame's addition +// and whose `fullContent`, when present, is the whole answer so far. Both +// have to come out as OpenAI deltas, with no word repeated and no answer +// cut short — including when a frame is split across TCP chunks. +import { expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +// The suite fires far more than the account's ten-a-minute budget; lift the +// pacer so these tests measure the plugin, not the limiter. +process.env.ORCATERM_NO_PACE = "1" + + +const sse = (frames) => frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join("") + "data: [DONE]\n\n" + +const stream = (frames) => { + const body = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode(sse(frames))) + c.close() + }, + }) + return _internal.upstreamToOpenAI(body, { model: "deepseek-chat-latest" }) +} + +const deltas = async (res) => { + const text = await res.text() + const out = [] + for (const line of text.split("\n")) { + const t = line.trim() + if (!t.startsWith("data:")) continue + const p = t.slice(5).trim() + if (p === "[DONE]") continue + const j = JSON.parse(p) + const d = j.choices?.[0]?.delta + if (d?.content) out.push(d.content) + } + return out.join("") +} + +test("per-frame additions are joined into the whole answer", async () => { + const res = stream([{ content: "你" }, { content: "好" }, { content: ",世界" }]) + expect(await deltas(res)).toBe("你好,世界") +}) + +// Some deployments send the whole answer each time; the deltas must be +// worked out, or the client would see every word again and again. +test("cumulative frames are turned into deltas", async () => { + const res = stream([ + { fullContent: "你" }, + { fullContent: "你好" }, + { fullContent: "你好,世界" }, + ]) + expect(await deltas(res)).toBe("你好,世界") +}) + +test("reasoning is streamed apart from the answer", async () => { + const res = stream([{ reasoningContent: "先想" }, { content: "答案" }]) + const text = await res.text() + const reasoning = text + .split("\n") + .map((l) => l.trim()) + .filter((l) => l.startsWith("data:") && !l.includes("[DONE]")) + .map((l) => JSON.parse(l.slice(5).trim())) + .map((j) => j.choices?.[0]?.delta?.reasoning_content ?? "") + .join("") + expect(reasoning).toBe("先想") +}) + +// A stream that stops without [DONE] still has to end the answer, or the +// client waits forever. +test("a stream with no [DONE] is still finished", async () => { + const body = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode('data: {"content":"ok"}\n\n')) + c.close() + }, + }) + const text = await _internal.upstreamToOpenAI(body, { model: "m" }).text() + expect(text).toContain("[DONE]") + const hasStop = text + .split("\n") + .map((l) => l.trim()) + .filter((l) => l.startsWith("data:") && !l.includes("[DONE]")) + .some((l) => JSON.parse(l.slice(5).trim()).choices?.[0]?.finish_reason === "stop") + expect(hasStop).toBe(true) +}) + +// A refusal arriving mid-stream must error the stream, not become answer +// text: as text it would read as a successful reply, and magpie would neither +// fail over nor rest the account. +test("an upstream error frame errors the stream", async () => { + const body = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode("data: [ERROR]: quota exhausted\n\n")) + c.close() + }, + }) + const res = _internal.upstreamToOpenAI(body, { model: "m" }) + await expect(res.text()).rejects.toThrow(/quota exhausted/) +}) + +// The OpenAI response must not carry the upstream's framing headers: the +// body is rewritten, so a content-length would be wrong. +test("the rewritten stream sets no content-length", async () => { + const res = stream([{ content: "a" }]) + expect(res.headers.get("content-length")).toBeNull() + expect(res.headers.get("content-type")).toContain("event-stream") +}) diff --git a/packages/orcaterm/usage.test.mjs b/packages/orcaterm/usage.test.mjs new file mode 100644 index 0000000..12ff078 --- /dev/null +++ b/packages/orcaterm/usage.test.mjs @@ -0,0 +1,76 @@ +// The quota magpie shows comes from DescribeUserBillingStatus's usageStats, +// where only hunyuan_ai is the AI-answer allowance. The other rows there +// (session sharing, secrets, space) are unrelated, and reporting one of +// them as the AI window would show a number that never moves. +import { afterEach, expect, test } from "bun:test" +import { OrcaTermAuthPlugin } from "./index.mjs" + +// The suite fires far more than the account's ten-a-minute budget; lift the +// pacer so these tests measure the plugin, not the limiter. +process.env.ORCATERM_NO_PACE = "1" + + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const usage = async (reply) => { + globalThis.fetch = async () => reply() + const hooks = await OrcaTermAuthPlugin({ client: { app: { log: () => {} } } }) + return hooks.auth.usage(async () => ({ type: "api", key: "uin=o1234567890; skey=deadbeef" })) +} + +const billing = (usageStats) => + new Response(JSON.stringify({ data: { Response: { roleType: "basic", usageStats } } }), { + status: 200, + headers: { "content-type": "application/json" }, + }) + +test("the AI allowance is reported as used out of its limit", async () => { + const u = await usage(() => + billing([ + { feature: "session_share", quotaLimit: -1, quotaUsed: 0 }, + { feature: "hunyuan_ai", quotaLimit: 1000, quotaUsed: 370 }, + ]), + ) + expect(u.windows).toHaveLength(1) + expect(u.windows[0].name).toBe("AI Q&A") + expect(u.windows[0].amount).toBe(370) + expect(u.windows[0].limit).toBe(1000) + expect(u.windows[0].used).toBe(37) + expect(u.plan).toContain("basic") +}) + +// The unrelated rows must not be shown: session sharing's -1 limit would +// read as an exhausted account. +test("rows that are not the AI allowance are left out", async () => { + const u = await usage(() => + billing([ + { feature: "session_share", quotaLimit: -1, quotaUsed: 0 }, + { feature: "secret", quotaLimit: 5, quotaUsed: 1 }, + ]), + ) + expect(u.windows).toHaveLength(0) + expect(u.error).toBeTruthy() +}) + +// A refusal here is the sign-in's, and magpie should mark the account +// rather than keep asking it for quota. +test("a refused quota read marks the sign-in", async () => { + const u = await usage( + () => + new Response(JSON.stringify({ data: { Response: { Error: { Code: "VERIFY_SKEY_UIN_FAILED" } } } }), { + status: 200, + headers: { "content-type": "application/json" }, + }), + ) + expect(u.signIn).toBe("expired") + expect(u.windows).toEqual([]) +}) + +// Reading quota must never throw: a broken answer would take down the +// account card instead of just leaving the number out. +test("an unreadable answer becomes an error string, not a throw", async () => { + const u = await usage(() => new Response("not json", { status: 200 })) + expect(typeof u.error).toBe("string") + expect(u.windows).toEqual([]) +}) diff --git a/packages/orcaterm/wechat.mjs b/packages/orcaterm/wechat.mjs new file mode 100644 index 0000000..189b608 --- /dev/null +++ b/packages/orcaterm/wechat.mjs @@ -0,0 +1,481 @@ +/** + * WeChat QR sign-in for OrcaTerm. + * + * This uses OrcaTerm's own OAuth rather than the console session cookie: + * + * GET {OAUTH}/oauth/wechat/config → {appid, redirect_uri, state, scope} + * → the local page below embeds WeChat's qrconnect widget + * the scan returns to {redirect_uri} (/oauth/wechat/bridge?code&state), and that + * page postMessages the result to its parent — which is our page + * POST {OAUTH}/oauth/wechat/exchange → {userId, accessToken, expiresIn, …} + * POST {CAPI}?action=OAuthRefreshToken → renews it + * + * Why `self_redirect: true` matters: after a scan, qrconnect navigates the *top* + * window by default, which replaces the host page and loses the postMessage. + * With it set, the return happens inside the widget's own inner iframe, so the + * bridge page's `window.parent` is still our page. + * + * The token this yields is a 1024-character JWT, valid two hours and renewable. + * Measured 2026-10-27: it drives /assistant/chat directly, namespaced model ids + * included — and it is a far smaller credential than uin+skey, which is the whole + * Tencent Cloud console session. + */ +import http from "node:http" +import os from "node:os" + +export const OAUTH_BASE = "https://orcaterm.com" + +const WECHAT_QRCONNECT = "https://open.weixin.qq.com/connect/qrconnect" + +export class WechatLoginError extends Error { + constructor(code, message) { + super(message || code) + this.name = "WechatLoginError" + this.code = code + } +} + +const FRIENDLY = { + STATE_EXPIRED: "The QR code expired (a WeChat code lasts about five minutes and works once). Scan again.", + STATE_MISMATCH: "The state is no longer valid. Start the sign-in again.", + INVALID_REQUEST: "WeChat's code was not accepted (it may already have been used). Scan again.", + PROVIDER_DISABLED: "OrcaTerm has disabled WeChat sign-in.", +} + +async function jsonFetch(url, init = {}, timeoutMs = 20000) { + const ctrl = new AbortController() + const t = setTimeout(() => ctrl.abort(), timeoutMs) + try { + const res = await fetch(url, { ...init, signal: ctrl.signal }) + const text = await res.text() + let body = null + try { + body = JSON.parse(text) + } catch { + /* not JSON */ + } + return { res, body, text } + } finally { + clearTimeout(t) + } +} + +/** Step 1: read appid/redirect_uri/state and build the scan URL. */ +export async function startWechatLogin({ base = OAUTH_BASE } = {}) { + const { res, body, text } = await jsonFetch(`${base}/oauth/wechat/config`, { + headers: { accept: "application/json" }, + }) + const d = body?.data + if (!res.ok || Number(body?.code) !== 0 || !d) { + throw new WechatLoginError( + String(body?.code ?? "INTERNAL_ERROR"), + body?.message || text.slice(0, 120) || `[config] http ${res.status}`, + ) + } + if (!d.appid || !d.redirect_uri || !d.state || !d.scope) { + throw new WechatLoginError("INTERNAL_ERROR", "[config] response is missing a field") + } + + const qr = new URL(WECHAT_QRCONNECT) + qr.searchParams.set("appid", d.appid) + qr.searchParams.set("redirect_uri", d.redirect_uri) + qr.searchParams.set("response_type", "code") + qr.searchParams.set("scope", d.scope) + qr.searchParams.set("state", d.state) + + return { + appid: d.appid, + redirectUri: d.redirect_uri, + state: d.state, + scope: d.scope, + url: `${qr.toString()}#wechat_redirect`, + } +} + +/** Step 4: trade the code for a token. */ +export async function exchangeCode({ code, state, base = OAUTH_BASE }) { + const { res, body, text } = await jsonFetch(`${base}/oauth/wechat/exchange`, { + method: "POST", + headers: { accept: "application/json", "content-type": "application/json" }, + body: JSON.stringify({ code, state }), + }) + const known = ["STATE_EXPIRED", "STATE_MISMATCH", "INVALID_REQUEST", "PROVIDER_DISABLED"] + const c = String(body?.code ?? "") + if (!res.ok || Number(body?.code) !== 0 || !body?.data) { + const code2 = known.includes(c) ? c : "INTERNAL_ERROR" + throw new WechatLoginError( + code2, + FRIENDLY[code2] || body?.message || text.slice(0, 160) || "WeChat sign-in failed", + ) + } + const d = body.data + if (!d.accessToken) throw new WechatLoginError("INTERNAL_ERROR", "[exchange] no accessToken in the response") + const expiresIn = Number(d.expiresIn) || 0 + return { + userId: String(d.userId ?? ""), + nickname: d.providerUsername ?? "", + avatar: d.avatar ?? "", + accessToken: d.accessToken, + expiresIn, + expiresAt: expiresIn ? Date.now() + expiresIn * 1000 : null, + } +} + +/** Renew: trade the current token for a fresh one (same two-hour life). */ +export async function refreshAccessToken(token, { base = OAUTH_BASE } = {}) { + const { body, text } = await jsonFetch( + `${base}/cgi/api?action=OAuthRefreshToken`, + { + method: "POST", + headers: { accept: "application/json", "content-type": "application/json" }, + body: JSON.stringify({ action: "OAuthRefreshToken", data: { accessToken: token } }), + }, + 15000, + ) + const r = body?.data?.Response ?? body?.data + const next = r?.accessToken ?? r?.AccessToken + if (!next) { + throw new WechatLoginError("INTERNAL_ERROR", `renewal failed: ${(r?.Error?.Message || text).slice(0, 120)}`) + } + const expiresIn = Number(r?.expiresIn ?? r?.ExpiresIn) || 0 + return { accessToken: next, expiresIn, expiresAt: expiresIn ? Date.now() + expiresIn * 1000 : null } +} + +/** Read userId/nickname/expiry out of the JWT (no signature check). */ +export function readTokenClaims(token) { + try { + const p = JSON.parse(Buffer.from(String(token).split(".")[1] ?? "", "base64url").toString("utf8")) + return { + userId: p?.userId != null ? String(p.userId) : "", + nickname: p?.providerUsername ?? "", + exp: Number(p?.exp) || 0, + } + } catch { + return { userId: "", nickname: "", exp: 0 } + } +} + +/** True for something shaped like a WeChat OAuth access token (a JWT). */ +export function looksLikeAccessToken(s) { + return /^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/.test(String(s ?? "").trim()) +} + +const PAGE = ({ appid, redirectUri, state, bridgeOrigin }) => ` + + +OrcaTerm · WeChat sign-in + +
+
+ + +` + +/** + * The local page that embeds the QR widget and hands back the code. + * Returns {ready, wait, close}: `ready` resolves to the page URL, `wait` to + * {code, state} once the scan comes back. + */ +export function createLocalCapture({ appid, redirectUri, state, timeoutMs = 300000 }) { + // The origin the bridge page will answer from, taken from the redirect_uri + // OrcaTerm issued rather than hardcoded. + let bridgeOrigin = "https://orcaterm.com" + try { + bridgeOrigin = new URL(redirectUri).origin + } catch { + /* keep the default */ + } + + let settleWait + let failWait + let resolveReady + let rejectReady + let settled = false + + // `ready` can fail: a bind error other than a busy port has to reach the + // caller as a failed sign-in rather than leave it awaiting forever. + const ready = new Promise((res, rej) => { + resolveReady = res + rejectReady = rej + }) + ready.catch(() => {}) + const wait = new Promise((res, rej) => { + settleWait = res + failWait = rej + }) + wait.catch(() => {}) + + const server = http.createServer((req, res) => { + // One bad request must not take the host process down: this handler runs in + // magpie's own event loop, where a throw is an uncaught exception. + req.on("error", () => {}) + res.on("error", () => {}) + try { + handle(req, res) + } catch (err) { + try { + res.writeHead(500, { "content-type": "application/json" }) + res.end(JSON.stringify({ ok: false, error: String(err?.message ?? err) })) + } catch { + /* the response was already gone */ + } + } + }) + + const handle = (req, res) => { + const url = new URL(req.url ?? "/", "http://127.0.0.1") + + if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/login")) { + res.writeHead(200, { "content-type": "text/html; charset=utf-8" }) + res.end(PAGE({ appid, redirectUri, state, bridgeOrigin })) + return + } + + if (req.method === "POST" && url.pathname === "/cb") { + // Only our own page may hand over a code. Any site the user has open could + // otherwise POST its own code here while the page waits, finishing the + // sign-in with a credential we did not ask for. The page is served from + // this origin, so a same-origin POST carries it; anything else — including + // a request with no Origin at all — is refused. + if (!originAllowed(req)) { + res.writeHead(403, { "content-type": "application/json" }) + res.end(JSON.stringify({ ok: false, error: "origin not allowed" })) + return + } + let raw = "" + req.on("data", (c) => { + raw += c + if (raw.length > 64 * 1024) req.destroy() + }) + req.on("end", () => { + let body = {} + try { + body = JSON.parse(raw || "{}") + } catch { + /* ignore */ + } + if (!body || typeof body !== "object" || Array.isArray(body) || + typeof body.state !== "string" || + (body.error !== undefined && typeof body.error !== "string") || + (body.code !== undefined && typeof body.code !== "string") || + (typeof body.code !== "string" && !body.error)) { + res.writeHead(400, { "content-type": "application/json" }) + res.end(JSON.stringify({ ok: false, error: "invalid callback body" })) + return + } + // the code must belong to the sign-in this page started + const stateOk = body.state === state + const ok = Boolean(body.code) && !body.error && stateOk + const why = body.error || (!stateOk ? "state mismatch" : "no code") + res.writeHead(200, { "content-type": "application/json" }) + res.end(JSON.stringify(ok ? { ok: true } : { ok: false, error: why })) + if (!ok || settled) return + settled = true + clearTimeout(timer) + settleWait({ code: body.code, state }) + }) + return + } + + res.writeHead(404).end() + } + + function close() { + clearTimeout(timer) + try { + server.close() + } catch { + /* ignore */ + } + } + + const timer = setTimeout(() => { + if (settled) return + settled = true + close() + failWait(new Error("Timed out waiting for the scan; try again.")) + }, timeoutMs) + + const wantPort = Number(process.env.ORCATERM_CAPTURE_PORT) || 4080 + const base = process.env.ORCATERM_CAPTURE_BASE || "" + const host = process.env.ORCATERM_CAPTURE_HOST || "127.0.0.1" + + // The origin the page is actually served from, known once the socket is bound. + let pageOrigin = "" + + // Origins this server may be reached by, filled in once the socket is bound. + const boundOrigins = new Set() + + /** + * Which `Origin`s a POST to /cb may carry. + * + * Only addresses this server is actually reachable on — built here from the + * bind address and, for a wildcard bind, this machine's own interface + * addresses — plus the proxy's origin when `ORCATERM_CAPTURE_BASE` points at + * one. + * + * `Origin` is deliberately **not** compared with the request's `Host`: both + * come from the request, so a DNS-rebinding page (`Host: evil.example`, + * `Origin: http://evil.example`, resolving to 127.0.0.1) satisfies that + * comparison and could settle the sign-in with a code of its own. The state is + * in the page's HTML, so it is no secret against anyone who can load the page — + * which is why the origin is checked against addresses the request cannot + * invent. A rebinding page still sends its own hostname as the origin, never a + * bare interface address, so listing those is safe and keeps + * `ORCATERM_CAPTURE_HOST=0.0.0.0` usable. + */ + const originAllowed = (req) => { + const origin = req.headers.origin ?? "" + if (!origin) return false // a plain form or a non-browser client + return boundOrigins.has(origin) + } + + const listen = (port) => { + const onErr = (e) => { + // A busy fixed port is fine — any free one will do, the URL tells the user + // where to go. But when a base URL is configured the page is reached + // through that proxy, which cannot know a random port, so falling back + // would hand out a URL that points at whatever else owns 4080. + if (e?.code === "EADDRINUSE" && port !== 0 && !base) { + listen(0) + return + } + // Any other bind error must fail the sign-in, not leave `ready` pending: + // `authorize()` awaits it, so a pending promise is a hung login with no + // explanation. + if (!settled) { + settled = true + clearTimeout(timer) + rejectReady(e) + failWait(e) + } + } + server.once("error", onErr) + // `listen()` validates the port synchronously and throws on a bad one, before + // the error handler can fire — so a bad ORCATERM_CAPTURE_PORT would escape + // `createLocalCapture` and leave the 300 s timer armed. + try { + server.listen(port, host, () => { + server.removeListener("error", onErr) + const actual = server.address().port + pageOrigin = `http://${host.includes(":") ? `[${host}]` : host}:${actual}` + + // Everything this socket answers on. `localhost` and `127.0.0.1` are the + // two spellings a browser may use for the loopback; a wildcard bind also + // answers on each of this machine's own addresses, so those are accepted + // too — otherwise `ORCATERM_CAPTURE_HOST=0.0.0.0` would hand out a page + // whose own POST gets refused. + boundOrigins.add(`http://127.0.0.1:${actual}`) + boundOrigins.add(`http://localhost:${actual}`) + boundOrigins.add(`http://[::1]:${actual}`) + if (host === "0.0.0.0" || host === "::") { + boundOrigins.add(pageOrigin) + for (const list of Object.values(os.networkInterfaces())) { + for (const nic of list ?? []) { + const addr = nic?.address + if (!addr) continue + if (nic.family === "IPv4") boundOrigins.add(`http://${addr}:${actual}`) + else if (nic.family === "IPv6") boundOrigins.add(`http://[${addr}]:${actual}`) + } + } + } else { + boundOrigins.add(pageOrigin) + } + if (base) { + try { + boundOrigins.add(new URL(base).origin) + } catch { + /* a bare host in the env var: nothing to compare */ + } + } + + // The socket must not keep the process alive on its own, and neither + // should the timer: `close()` runs when the sign-in finishes or times + // out, and `unref` means a leaked capture cannot hold the host open. + server.unref?.() + timer.unref?.() + if (base) { + // behind a proxy the page is served at the base URL; keep it as given + resolveReady(`${base.replace(/\/+$/, "")}/login`) + } else { + const shown = host === "0.0.0.0" ? "127.0.0.1" : host + resolveReady(`http://${shown}:${actual}/login`) + } + }) + } catch (err) { + server.removeListener("error", onErr) + if (!settled) { + settled = true + clearTimeout(timer) + rejectReady(err) + failWait(err) + } + } + } + + listen(wantPort) + + return { ready, wait, close } +} diff --git a/registry.json b/registry.json index c4761b3..83ec9a2 100644 --- a/registry.json +++ b/registry.json @@ -118,6 +118,18 @@ { "package": "@hoptoper/magpie-agent-wisp-science", "name": "Wisp Science", "kind": "agent", "summary": { "en": "Wisp Science on magpie's Agents page: pick one of magpie's models, set reasoning effort in the composer, and switch it off to put its config back. Needs Wisp Science 1.23.0 or later.", "zh": "把 Wisp Science 加到 magpie 的 Agent 页:选择 magpie 的模型,在输入框里设置思考强度,关掉即恢复原来的配置。需要 Wisp Science 1.23.0 或更新版本。" } }, { "package": "@magpie-community/tools-goanyapi", "name": "GoAnyAPI", "icon": "https://goanyapi.com/logo.png", "kind": "tools", "community": true, - "summary": { "en": "All GoAnyAPI website traffic, SEO, SERP, backlinks and ads intelligence tools from a live MCP catalog. Supports OAuth or API key sign-in.", "zh": "自动接入 GoAnyAPI 动态目录中的全部网站流量、SEO、SERP、外链和广告情报工具,支持 OAuth 或 API Key 登录。" } } + "summary": { "en": "All GoAnyAPI website traffic, SEO, SERP, backlinks and ads intelligence tools from a live MCP catalog. Supports OAuth or API key sign-in.", "zh": "自动接入 GoAnyAPI 动态目录中的全部网站流量、SEO、SERP、外链和广告情报工具,支持 OAuth 或 API Key 登录。" } }, + { + "package": "@magpie-community/opencode-orcaterm-auth", + "name": "OrcaTerm", + "providers": [ + "orcaterm" + ], + "community": true, + "summary": { + "en": "Tencent Cloud OrcaTerm (遨驰终端) AI assistant models — DeepSeek, Hunyuan, GLM, Kimi — on the account's monthly question allowance. Unofficial; the README sets out the terms.", + "zh": "用腾讯云遨驰终端(OrcaTerm)AI 助手的模型——DeepSeek、混元、GLM、Kimi——走账号每月问答额度。非官方,条款风险见 README。" + } + } ] }