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.
This commit is contained in:
狂気のMad Scientist鳳凰院胸針
2026-10-30 00:44:34 +08:00
committed by GitHub
parent ecc4df3076
commit fdc5002319
14 changed files with 4348 additions and 1 deletions
+21
View File
@@ -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.
+318
View File
@@ -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
<http://127.0.0.1:4080/login>, 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 <server>
```
`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 <https://cloud.tencent.com> 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/<model>`
and `Hunyuan3/<model>` — 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.
+187
View File
@@ -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() }
})
+121
View File
@@ -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)
})
File diff suppressed because it is too large Load Diff
+20
View File
@@ -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"
}
}
+138
View File
@@ -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 })
})
+123
View File
@@ -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("用 {花括号} 表示集合")
})
+351
View File
@@ -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()
}
})
+113
View File
@@ -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()
})
+108
View File
@@ -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")
})
+76
View File
@@ -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([])
})
+481
View File
@@ -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 }) => `<!doctype html>
<html lang="zh"><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OrcaTerm · WeChat sign-in</title>
<style>
html,body{margin:0;height:100%;background:#0b0d10;color:#e6e6e6;
font:14px/1.6 -apple-system,system-ui,"PingFang SC",sans-serif}
#wrap{display:flex;align-items:center;justify-content:center;height:100%}
#done{display:none;align-items:center;justify-content:center;height:100%;text-align:center;padding:24px}
.err{color:#ff8a8a}
</style>
<div id="wrap"><div id="wxqr"></div></div>
<div id="done"></div>
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<script>
const APPID = ${JSON.stringify(appid)};
const REDIRECT = ${JSON.stringify(redirectUri)};
const STATE = ${JSON.stringify(state)};
// self_redirect: true keeps the return inside the widget's own iframe, so the
// host page (this one) survives to receive the postMessage.
new WxLogin({
self_redirect: true,
id: 'wxqr',
appid: APPID,
scope: 'snsapi_login',
redirect_uri: encodeURIComponent(REDIRECT),
state: STATE,
style: 'black',
href: '',
});
function done(text, isErr) {
document.getElementById('wrap').style.display = 'none';
const d = document.getElementById('done');
d.className = isErr ? 'err' : '';
d.textContent = text;
d.style.display = 'flex';
}
// Only the bridge page this sign-in is talking to may answer it. Without the
// origin check any window that has a handle on this one could post a code.
// Taken from the redirect_uri OrcaTerm itself issued, so a move of the bridge
// to another host does not silently stall every scan.
const TRUSTED_ORIGIN = ${JSON.stringify(bridgeOrigin)};
window.addEventListener('message', async (e) => {
if (e.origin !== TRUSTED_ORIGIN) return;
const d = e.data;
if (!d || d.type !== 'wechat-oauth-callback') return;
// If the bridge repeats the state, it must be the one this page issued. When
// it does not carry one, our own copy is used below, so the server still
// compares against a value only this page knows.
if (d.state && d.state !== STATE) return;
try {
// Relative to this page, not root-absolute: with ORCATERM_CAPTURE_BASE set
// to a URL with a path, '/cb' would leave the path and never reach this
// server.
const r = await fetch(new URL('cb', location.href), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ code: d.code, state: d.state || STATE, error: d.error }),
});
const j = await r.json();
done(j.ok ? 'Scanned — signing in… (you can close this page once it finishes)'
: ('Sign-in failed: ' + (j.error || 'unknown error')), !j.ok);
} catch (err) {
done('Sign-in failed: ' + err, true);
}
});
</script>
</html>`
/**
* 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 }
}
+13 -1
View File
@@ -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。"
}
}
]
}