inkstone 0.1.0: Intern InkStone (书生·端砚) Token Plan, browser sign-in, credit card and ink-* key chat (#775)

New package @magpie-community/opencode-inkstone-auth 0.1.0 for Intern
InkStone (书生·端砚, Shanghai AI Lab) Token Plan, provider id
`intern-inkstone`. Community package by yunwang2442-creator.

What it does:
- Browser sign-in (Edge/Chrome, its own profile under
  $XDG_CONFIG_HOME or ~/.config/magpie/inkstone-browser, or
  %LOCALAPPDATA%\magpie\inkstone-browser). The login window has no
  debugging port. A headless CDP read takes the uaa-token cookie, and the
  same read renews it silently later.
- Usage card: ink-credit balance, 5-hour and 7-day windows, credit packs.
- Chat: a pasted ink-* API key, or one the sign-in creates, named
  ink-<host4>-<acct4>-<rand4> (18 of the console's 20 characters). An
  idempotency clash (-15109) retries with a fresh name, up to three times.
  Pruning is on by default. It only touches this machine's and account's
  prefix, keeps the newest two and the key this sign-in created, and never
  deletes manual keys or keys of unknown age.
- Closing on Unix: SIGTERM, then SIGKILL only after a 15s grace. Leftover
  browsers are matched by --user-data-dir=<escaped profile>, and Windows
  uses .Contains().
- The login wait comes from an injected waitForLogin in tests. No env
  hook is left in production code.
- Hosts: discovery.intern-ai.org.cn, discovery-api.intern-ai.org.cn,
  127.0.0.1 (CDP).

Outside the package: scripts/opencode2.mjs lets a prompt with
`required: false` stay optional (`p.required !== false`). Every package's
copy is synced byte for byte, so all 39 copies in the merged tree are blob
afe074cb. No other package sets `required: false` on a prompt, so this
changes nothing for them. Also a root README row and a registry entry.

Review at 36412a15, on mote, HOME=$(mktemp -d), Bun 1.4.2:
- bun test packages/inkstone: 68 pass, 0 fail in Asia/Shanghai, UTC,
  America/Los_Angeles and Pacific/Kiritimati.
- bun scripts/check.mjs inkstone and bun scripts/check.mjs: ok.
- bun test (repo), on 36412a15 merged with origin/main e7cb9dc5:
  6743 pass, 20 skip, 0 fail. main has since moved by cline 0.1.14 and
  zcode 0.1.55 only, and none of the adapter copies changed.
- Broken by hand, each red: no protectName protection; prune_keys default
  off; no post-sign-in prune; no SIGTERM on close; the -15109 retry keeping
  its name.

Not tried: a real InkStone account sign-in on macOS, Linux or Windows (no
account here); a live chat request; magpie end to end with the plugin.
This commit is contained in:
我是一条没有名字的区
2026-11-07 15:07:06 +08:00
committed by GitHub
parent fa310fa9c3
commit e7004d9354
64 changed files with 4491 additions and 38 deletions
+1
View File
@@ -25,6 +25,7 @@ subscription and makes its requests. The packages work in OpenCode and in
| [factory](packages/factory) | Factory (Droid) subscription | `factory` | | [factory](packages/factory) | Factory (Droid) subscription | `factory` |
| [gcp-ai](packages/gcp-ai) | Google Cloud Vertex AI with your own gcloud / ADC login (needs `gcloud` and Chrome), plus the project's promotional credits | `gcp-ai` | | [gcp-ai](packages/gcp-ai) | Google Cloud Vertex AI with your own gcloud / ADC login (needs `gcloud` and Chrome), plus the project's promotional credits | `gcp-ai` |
| [grok](packages/grok) | Grok (SuperGrok / X Premium+), through the Grok Build CLI's sign-in | `grok` | | [grok](packages/grok) | Grok (SuperGrok / X Premium+), through the Grok Build CLI's sign-in | `grok` |
| [inkstone](packages/inkstone) | (Unofficial) 书生·端砚 Token Plan: browser sign-in gives the ink-credit balance, the 5-hour and 7-day windows and the credit packs, and creates an `ink-*` API key to serve the plan's models for chat | `intern-inkstone` |
| [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` | | [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` |
| [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` | | [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` |
| [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` | | [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` |
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+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.
+132
View File
@@ -0,0 +1,132 @@
# 书生·端砚 Token Plan
[书生·端砚](https://discovery.intern-ai.org.cn)(Intern InkStone,上海人工智能实验室)的
**墨点计划(Token Plan)** 接进 OpenCode 和 [magpie](https://usemagpie.ai):
一次控制台登录同时拿到**额度**(墨点余额、5 小时 / 7 天窗口、墨点包)
和**模型**(计划内模型的 OpenAI Chat Completions 推理)。
> Unofficial, use at your own risk. This package is not affiliated with, authorized
> or endorsed by Shanghai AI Laboratory. The "Intern InkStone" name and logo are
> trademarks of Shanghai AI Laboratory, used here solely to identify the service.
> It reads the console's non-public `/api/tokenplan/v1/*` endpoints with the browser
> session cookie, and can create (and, if enabled, delete) API keys named `ink-*`
> in your own account. None of this is documented by the platform; it may stop working
> or change at any time. It does not bypass captchas, rate limits or any platform restriction.
## 一次登录,额度与模型都在
| 凭证 | 来源 | 给什么 |
|---|---|---|
| **控制台登录态**(`uaa-token` cookie) | 浏览器登录 / 手动粘贴 | **额度**:墨点余额、5h/7d 窗口、墨点包;支持 magpie 每日签到领免费墨点 |
| **TokenPlan API Key**(`sk-…`) | 控制台「科研模型 → API Key」,或登录时自动创建 | **模型**:计划内模型,OpenAI Chat Completions |
API Key 是可选的:不填,账号仍显示额度,只是不服务模型。填了,同一个账号
既显示额度、又服务对话。
## 模型
插件只使用 **OpenAI Chat Completions**(`https://discovery-api.intern-ai.org.cn/v1`)。
模型清单是两层 live 数据的交集:
- `GET /v1/models`(API Key):这个 Key 真能调用的模型;
- `GET /api/tokenplan/v1/public/models`(无需登录):上下文、输入类型、能力、价格。
决策模型 `intern-decision-4b` 只支持 SystemOne,不是聊天接口,不列入。
**不做思考强度档位**:平台明确不支持通过请求参数开启/关闭/调整思考强度。
**免费标记与倍率(magpie 专有展示字段,OpenCode 忽略):**
- `free: true`:接口价(输入与输出)都是 0 的模型——与控制台自己的免费判定
一致。目前是 `Agents-A1 / Atria-Dawn / Sage-A1.5 / intern-s2` 四个。
- `rate`:**推导值**,不是平台的官方倍率(平台没有倍率概念,只有"墨点/百万
token"的绝对价)。归一化口径:**1000 墨点/1M 输入 token = x1**——qwen3.8-27b
x0.8、deepseek-v4.1-flash-1017 x1、minimax-m3 x2.1、kimi-k2.6 x6.5、glm-5.3 x8。
免费模型不设 rate(magpie 的 `rate: 0` 表示"未提供",不是免费)。rate 不参与
计费,平台实际按 token 扣墨点。
## 额度卡片
有控制台登录态时,magpie 的账户卡显示:
- 墨点余额与可用墨点包数量;
- **5 小时 / 7 天**两个进度条(已用/总量、重置时间);
- 每个可用墨点包一行(包名、剩余/总量、到期日);
- RPM/TPM 限速。
按模型的 token 消耗明细不在额度卡上(那是用量页的事),额度卡只管额度。
读不到的字段不会显示成 0:额度读取失败时卡片说明原因,模型调用不受影响。
## 登录方式
| 方式 | 做什么 | 产出 |
|---|---|---|
| **浏览器登录(推荐)** | 用**插件自己的专用浏览器 profile** 开一个窗口,你在里面登录控制台(密码 / 短信 / 扫码)。登录窗口**不带调试端口**(阿里验证码能过)。**Windows** 上插件用窗口标题判断登录完成、**自己关窗**;**macOS / Linux** 读不了窗口标题,登录完成后请**自己关掉窗口**,插件接着自动收尾。之后的续期/重登都静默完成 | 额度 + 模型 |
| **仅 API Key** | 只粘贴 Key;`GET /v1/models` 探活 | 只有模型 |
| **API Key + 控制台 token** | 粘贴 Key,再粘贴 `uaa-token=…` 那一项(DevTools → Application → Cookies,复制整条 `uaa-token=…` 即可,插件只取值) | 额度 + 模型 |
> 不读、不动你日常浏览器的任何数据:Edge/Chrome 136+ 禁止在默认用户目录上开调试端口,而且把真实 profile 从别的路径打开会清掉端砚登录态。插件的专用 profile 是唯一可行且安全的地方。
浏览器登录时可以把**现有 Key** 粘进 “TokenPlan API key”;留空才会
创建新 Key。账号的 Key 上限是 10 把,所以本插件建的 Key 名字是
`ink-<host>-<account>-<random>`(18 字符),清理只碰这个前缀,**手动建的 Key
永远不动**;默认保留最新两把、并始终保留本次登录创建的那把。
### 登录态复用与续期
`uaa-token` 是网页登录态,不是 OAuth refresh token;平台前端没有 refresh
逻辑。插件默认保留一个**专用浏览器 profile**,快过期时用 headless 打开控制台
页面**静默续期**(SSO 会话还在就会换新 cookie)。关掉 `keep_sign_in` 就改成
一次性 profile:登录完删除,过期后手动重登。
## 免费墨点领取(可选)
控制台首页加载时会 `POST /users/free-grant` 领当月免费墨点(幂等,没有按钮)。
本插件**不再自动调用这个接口**;改由 magpie 的 `auth.checkin` 钩子承接:
只有你在 magpie 里为该供应商的「签到」开启时,magpie 才会每天执行一次(幂等,
已领取返回 `done`)。未绑定手机号返回 `ineligible`,卡片不会因此报错。
## 安装
```sh
magpie plugin add @magpie-community/opencode-inkstone-auth
```
然后在 magpie 里给 `书生·端砚 ` 登录。
## 存储
`uaa-token` 与 API Key 和别的 magpie 钱包插件一样保存在 magpie 的
`auth.json` 里(明文)。`uaa-token` 等于网页登录态,能查看余额、创建 Key、
领取墨点:**不要分享 `auth.json`,不要把 token 贴到公开的截图或日志里**。
**专用浏览器 profile**(里面是活的登录态,等同一个能操作你账号的浏览器):
- Windows:`%LOCALAPPDATA%\magpie\inkstone-browser`
- macOS / Linux:`$XDG_CONFIG_HOME/magpie/inkstone-browser`(默认 `~/.config/magpie/inkstone-browser`)
插件不把 token 写到任何其他地方;这个 profile 只用于登录/续期,删掉它只是
退出登录态,不影响 auth.json 里的 Key。
## OpenCode 2.x
OpenCode 2.x 没有 `auth.usage` / `auth.refresh` / `auth.checkin`:额度卡片、静默续期和每日签到只在 magpie 里可用;Chat 模型在 2.x 照常可用。
## 旧入口迁移
旧的书生大模型 Chat/API 入口(`internlm.intern-ai.org.cn`)将按官方公告迁移:
2026-11-09 起只保留 Intern-S2,2027-01-26 起停用。本插件用的是新的
`discovery-api.intern-ai.org.cn`,不受该停用影响。
## 开发
```sh
bun test packages/inkstone
bun scripts/check.mjs inkstone
```
`testdata/public-models.json` 是一次真实的公共模型接口回复(模型 id 未改),
测试用它驱动解析与过滤。所有测试都在本地 fake 上跑,不触网。
## License
MIT
+177
View File
@@ -0,0 +1,177 @@
// The API-key side: the catalogue it reads, the models magpie lists for the
// account, the loader, and the sign-in methods. Everything runs against the
// local fake.
import "./nonet.mjs"
import { readFileSync } from "node:fs"
import { afterEach, expect, test } from "bun:test"
import { InkStoneAuthPlugin } from "./index.mjs"
import { fakeInkStone, json } from "./fake.mjs"
let f
afterEach(() => f?.close())
const META = JSON.parse(readFileSync(new URL("./testdata/public-models.json", import.meta.url), "utf8"))
const auth = { type: "oauth", access: "sk-test", apiKey: "sk-test", uaaToken: "uaa-token" }
async function plugin() {
return InkStoneAuthPlugin({ client: { auth: { set: async () => {} } } })
}
function serve(live = [{ id: "glm-5.3" }, { id: "Agents-A1" }, { id: "intern-decision-4b" }]) {
f.route("GET /v1/models", (r) => {
expect(r.headers.get("authorization")).toBe("Bearer sk-test")
return json({ object: "list", data: live })
})
f.route("GET /api/tokenplan/v1/public/models", () => json(META))
}
test("config declares the provider with a working npm, base URL and bootstrap models", async () => {
f = fakeInkStone()
const p = await plugin()
const cfg = {}
await p.config(cfg)
const provider = cfg.provider["intern-inkstone"]
expect(provider.name).toBe("书生·端砚")
expect(provider.npm).toBe("@ai-sdk/openai-compatible")
expect(provider.api).toBe(f.origin + "/v1")
expect(Object.keys(provider.models).length).toBeGreaterThan(0)
expect(provider.models["glm-5.3"].limit.context).toBe(1048576)
})
test("the listing is the key's live set intersected with the public metadata", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
const models = await p.provider.models({ id: "intern-inkstone", models: {} }, { auth })
expect(Object.keys(models).sort()).toEqual(["Agents-A1", "glm-5.3"])
expect(models["glm-5.3"].limit.context).toBe(1048576)
expect(models["glm-5.3"].reasoning).toBe(true)
expect(models["Agents-A1"].capabilities.input.image).toBe(true)
expect(models["glm-5.3"].variants).toBeUndefined()
// the magpie-only price markers reach provider.models too
expect(models["glm-5.3"].rate).toBe(8)
expect(models["glm-5.3"].free).toBeUndefined()
expect(models["Agents-A1"].free).toBe(true)
expect(models["Agents-A1"].rate).toBeUndefined()
})
test("config's bootstrap models carry the free/rate markers too", async () => {
f = fakeInkStone()
const p = await plugin()
const cfg = {}
await p.config(cfg)
const models = cfg.provider["intern-inkstone"].models
expect(models["Sage-A1.5"].free).toBe(true)
expect(models["Sage-A1.5"].rate).toBeUndefined()
expect(models["glm-5.3"].rate).toBe(8)
expect(models["glm-5.3"].free).toBeUndefined()
})
test("an account with no API key advertises no models", async () => {
f = fakeInkStone()
const p = await plugin()
const noKey = { type: "oauth", access: "", uaaToken: "uaa-token" }
expect(await p.provider.models({ id: "intern-inkstone", models: { "glm-5.3": {} } }, { auth: noKey })).toEqual({})
expect(await p.auth.loader(async () => noKey)).toEqual({})
})
test("a key the platform refused lists nothing, not the bootstrap set", async () => {
f = fakeInkStone()
f.route("GET /v1/models", () => json({ error: "unauthorized" }, 401))
f.route("GET /api/tokenplan/v1/public/models", () => json(META))
const p = await plugin()
expect(await p.provider.models({ id: "intern-inkstone", models: { "glm-5.3": {} } }, { auth })).toEqual({})
})
test("a catalogue read that fails keeps the declared models", async () => {
f = fakeInkStone()
f.route("GET /v1/models", () => json({ error: "boom" }, 500))
f.route("GET /api/tokenplan/v1/public/models", () => json(META))
const p = await plugin()
const given = { "glm-5.3": {} }
const got = await p.provider.models({ id: "intern-inkstone", models: given }, { auth })
expect(got).toEqual(given)
})
test("an account with no auth yet still sees the bootstrap list", async () => {
f = fakeInkStone()
const p = await plugin()
const cfg = {}
await p.config(cfg)
const declared = cfg.provider["intern-inkstone"].models
expect(await p.provider.models({ id: "intern-inkstone", models: {} }, {})).toEqual(declared)
})
test("the loader serves the models with the key at the platform's base URL", async () => {
f = fakeInkStone()
const p = await plugin()
const loader = await p.auth.loader(async () => auth)
expect(loader.apiKey).toBe("sk-test")
expect(loader.baseURL).toBe(f.origin + "/v1")
})
test("the sign-in methods cover browser, API key, and API key + console token", async () => {
const p = await plugin()
const labels = p.auth.methods.map((m) => m.label)
expect(labels[0]).toContain("Browser sign-in")
expect(labels[1]).toContain("API key only")
expect(labels[2]).toContain("console token")
// the browser method must not block the host's authorize call: the browser
// work runs in its callback (the host's authorize deadline is short)
const browser = p.auth.methods[0]
const result = browser.authorize({})
if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
// a displayless CI runner is refused up front, not left with a window it cannot open
expect(result.type).toBe("failed")
expect(result.error).toContain("no display")
} else {
expect(result.method).toBe("auto")
expect(typeof result.callback).toBe("function")
expect(result.instructions).toContain("Sign in there")
expect(result.url).toBe("")
}
// the browser method's key prompt is optional; a non-sk- one is refused
expect(browser.prompts[0].validate("")).toBeUndefined()
expect(browser.prompts[0].validate("sk-abc")).toBeUndefined()
expect(browser.prompts[0].validate("nope")).toContain("sk-")
})
test("the API-key + console-token method reads the token out of a pasted cookie", async () => {
f = fakeInkStone()
serve()
f.route("GET /api/tokenplan/v1/users/validate", () => json({ code: 0, data: { name: "张三", phone: "12345678901" } }))
const p = await plugin()
const method = p.auth.methods[2]
// a full cookie string must be reduced to just the uaa-token value
const okResult = await method.authorize({
apiKey: "sk-test",
uaaToken: "sid=SESSIONSECRET; uaa-token=abc.def.ghi; other=1",
})
expect(okResult.type).toBe("success")
expect(okResult.uaaToken).toBe("abc.def.ghi")
expect(JSON.stringify(okResult)).not.toContain("SESSIONSECRET")
// a bare token value is accepted as-is
const bare = await method.authorize({ apiKey: "sk-test", uaaToken: "abc.def.ghi" })
expect(bare.type).toBe("success")
expect(bare.uaaToken).toBe("abc.def.ghi")
// base64 padding at the end is still a bare token
const padded = await method.authorize({ apiKey: "sk-test", uaaToken: "abc.def.gh==" })
expect(padded.type).toBe("success")
// a string without a uaa-token is refused, never stored verbatim
for (const junk of ["sid=SESSIONSECRET", "Cookie: uaa-token=abc", "abc=def", "uaa-token", "abc def", "short"]) {
const bad = await method.authorize({ apiKey: "sk-test", uaaToken: junk })
expect(bad.type).toBe("failed")
expect(bad.error).toContain("uaa-token")
}
})
test("cleanDetail masks real uaa-token, sk-, Bearer and JWT runs", async () => {
const { cleanDetail } = await import("./lib/protocol.mjs")
expect(cleanDetail("failed: uaa-token=secretValue123456")).toBe("failed: ***")
expect(cleanDetail("cookie: uaa_token: secretValue123456; other")).toBe("cookie: ***; other")
expect(cleanDetail("auth header: Bearer opaqueToken123456")).toBe("auth header: ***")
expect(cleanDetail("key is sk-12345678abcdef")).toBe("key is ***")
expect(cleanDetail("jwt: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.sig")).toBe("jwt: ***")
// diagnostic words must stay
expect(cleanDetail("error: token expired")).toBe("error: token expired")
})
+96
View File
@@ -0,0 +1,96 @@
// The browser helpers that can be tested without launching a browser: the
// cookie parse, JWT expiry, argv, and the profile location.
import "./nonet.mjs"
import { join } from "node:path"
import { expect, test } from "bun:test"
import {
browserArgs,
browserCandidates,
jwtExp,
profileDir,
readUaaToken,
tokenFresh,
waitForConsoleWindow,
waitForToken,
} from "./lib/browser.mjs"
test("uaa-token is read out of document.cookie and URL-decoded", () => {
expect(readUaaToken("a=b; uaa-token=abc.def.ghi; c=d")).toBe("abc.def.ghi")
const encoded = encodeURIComponent("hello world")
expect(readUaaToken(`uaa-token=${encoded}`)).toBe("hello world")
expect(readUaaToken("")).toBe("")
expect(readUaaToken("nothing=here")).toBe("")
})
test("a JWT's exp is read, an opaque token is left to the 401", () => {
const exp = Math.floor(Date.now() / 1000) + 3600
const jwt = ["e30", Buffer.from(JSON.stringify({ exp })).toString("base64url"), "sig"].join(".")
expect(jwtExp(jwt)).toBe(exp * 1000)
expect(jwtExp("opaque-token")).toBe(0)
expect(tokenFresh(jwt, 10 * 60_000)).toBe(true)
const stale = ["e30", Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) - 1 })).toString("base64url"), "sig"].join(".")
expect(tokenFresh(stale, 10 * 60_000)).toBe(false)
expect(tokenFresh("opaque-token", 10 * 60_000)).toBe(true)
})
test("browser candidates reject a path that is not there", () => {
expect(() => browserCandidates("C:\\definitely\\not\\here.exe")).toThrow()
// an existing executable is taken as the explicit browser
expect(browserCandidates(process.execPath)).toEqual([process.execPath])
})
test("waitForToken's single read has its own timeout, the account never waits 8 minutes", async () => {
let calls = 0
const session = {
token: async () => {
calls += 1
return calls === 1 ? "" : "read-token"
},
}
expect(await waitForToken(session, { timeoutMs: 5000, pollMs: 50 })).toBe("read-token")
expect(calls).toBe(2)
const gridlock = { token: async () => new Promise(() => {}) }
const start = Date.now()
await expect(waitForToken(gridlock, { timeoutMs: 50, pollMs: 25 })).rejects.toThrow(/登录超时/)
expect(Date.now() - start).toBeLessThan(2000)
})
test("headless renewal gets its own argv and the profile is per platform", () => {
const headless = browserArgs("C:\\profile", 0, "https://discovery.intern-ai.org.cn/token-plan/home", {
headless: true,
})
expect(headless[0]).toBe("--headless=new")
expect(headless).toContain("--user-data-dir=C:\\profile")
expect(headless).toContain("--remote-debugging-port=0")
// the visible login window carries no debugging port: the console's
// CAPTCHA must see an ordinary browser, not an automation session
const visible = browserArgs("C:\\profile", 0, "https://discovery.intern-ai.org.cn/token-plan/home", {
cdp: false,
login: true,
})
expect(visible.some((a) => a.startsWith("--remote-debugging-port"))).toBe(false)
expect(visible).toContain("--window-size=1100,800")
// join() on the expected side too: the separator is the test host's, not win32's
expect(profileDir({ LOCALAPPDATA: "C:\\Users\\u\\AppData\\Local" }, "win32")).toBe(
join("C:\\Users\\u\\AppData\\Local", "magpie", "inkstone-browser"),
)
expect(profileDir({ HOME: "/home/u" }, "linux").endsWith(join("magpie", "inkstone-browser"))).toBe(true)
})
test('off Windows the login wait ends on process exit, never on a title', async () => {
const { spawn } = await import('node:child_process')
// a child that stays alive in a non-Windows run must never be treated as
// 'console': only its exit ends the wait
const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 10000)'], { stdio: 'ignore' })
try {
const early = await waitForConsoleWindow(child, { platform: 'linux', timeoutMs: 120, pollMs: 40 })
expect(early).toBe('timeout')
child.kill()
const how = await waitForConsoleWindow(child, { platform: 'linux', timeoutMs: 2000, pollMs: 50 })
expect(how).toBe('closed')
} finally {
try { child.kill() } catch {}
}
})
+146
View File
@@ -0,0 +1,146 @@
// A real end-to-end run of the browser sign-in and the silent renewal: the
// "browser" is a tiny compiled Chromium stand-in that serves the DevTools
// HTTP + WebSocket endpoints the plugin speaks, so the actual spawn →
// port-file → CDP cookie read → graceful close → key creation path runs here.
import "./nonet.mjs"
import { execSync } from "node:child_process"
import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"
import { InkStoneAuthPlugin } from "./index.mjs"
import { renewSilently } from "./lib/browser.mjs"
import { fakeInkStone, json, ok, fail } from "./fake.mjs"
let fakeExe = ""
let profile = ""
const savedEnv = {}
let f
beforeAll(() => {
// compile the fake browser once (bun build --compile takes under a second)
const out = join(mkdtempSync(join(tmpdir(), "inkstone-fake-browser-")), process.platform === "win32" ? "fake-chrome.exe" : "fake-chrome")
const entry = join(import.meta.dir, "testdata/fake-browser.mjs")
execSync(`${JSON.stringify(process.execPath)} build --compile ${JSON.stringify(entry)} --outfile ${JSON.stringify(out)}`, { stdio: "pipe" })
fakeExe = out
profile = mkdtempSync(join(tmpdir(), "inkstone-fake-profile-"))
// save what we override: bun test runs every file in one process, so these
// would leak into whatever test file runs next
for (const key of ["MAGPIE_INKSTONE_PROFILE", "MAGPIE_INKSTONE_BROWSER", "MAGPIE_INKSTONE_LOGIN_EXIT", "DISPLAY"]) {
savedEnv[key] = process.env[key]
}
process.env.MAGPIE_INKSTONE_PROFILE = profile
delete process.env.MAGPIE_INKSTONE_BROWSER
delete process.env.MAGPIE_INKSTONE_LOGIN_EXIT
// a displayless CI runner refuses the browser sign-in up front unless a
// display is claimed; the fake browser does not need a real one
process.env.DISPLAY = process.env.DISPLAY || ":99"
})
afterAll(() => {
for (const [key, value] of Object.entries(savedEnv)) {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
try {
rmSync(profile, { recursive: true, force: true })
} catch {}
})
afterEach(() => {
f?.close()
f = undefined
})
/** The plugin configured for the fake browser, with logs surfaced for debugging. */
async function pluginWithFakeBrowser(options = {}) {
return InkStoneAuthPlugin(
{ client: { auth: { set: async () => {} }, app: { log: (b) => console.log("[log]", b?.body?.message ?? "") } } },
{ browser: fakeExe, loginTimeoutMs: 30_000, waitForLogin: async () => "console", ...options },
)
}
function serveKeyRoutes() {
const keys = []
f.route("GET /api/tokenplan/v1/keys", () => ok({ total: keys.length, items: keys }))
f.route("POST /api/tokenplan/v1/keys", (r) => {
keys.push({ id: `id-${keys.length + 1}`, name: r.json?.name, status: "active", created_at: new Date().toISOString() })
return ok({ key: "sk-new" })
})
f.route("DELETE /api/tokenplan/v1/keys", () => ok({}))
// the fake routes are exact-match; deleteKey uses /keys/<id>
for (let i = 1; i <= 12; i++) {
f.route(`DELETE /api/tokenplan/v1/keys/id-${i}`, (r) => {
const id = r.url.split("/").pop()
const at = keys.findIndex((k) => k.id === id)
if (at >= 0) keys.splice(at, 1)
return ok({})
})
}
f.route("GET /v1/models", () => json({ object: "list", data: [] }))
f.route("GET /api/tokenplan/v1/users/validate", () => ok({ name: "张三", phone: "12345678901" }))
f.route("POST /api/tokenplan/v1/users/free-grant", () => ok({ has_received: true }))
return keys
}
test("the silent renewal reads the session cookie through a real CDP exchange", async () => {
const token = await renewSilently({ browserPath: fakeExe, log: (m) => console.log("[renew]", m) })
expect(token).toBe("fake-uaa-token-for-tests")
// a second renewal works too: the fake browser was closed and the profile is reusable
expect(await renewSilently({ browserPath: fakeExe })).toBe("fake-uaa-token-for-tests")
}, 30_000)
test("a full browser sign-in opens the login window, reads the session, and creates the key", async () => {
f = fakeInkStone()
const keys = serveKeyRoutes()
const p = await pluginWithFakeBrowser()
const browser = p.auth.methods[0]
const result = browser.authorize({})
expect(result.method).toBe("auto")
const saved = await result.callback("", {})
expect(saved.type).toBe("success")
expect(saved.uaaToken).toBe("fake-uaa-token-for-tests")
// the plugin created the key on the (fake) console and kept its plaintext
expect(saved.apiKey).toBe("sk-new")
expect(keys.length).toBe(1)
expect(keys[0].name.startsWith("ink-")).toBe(true)
// the login window was closed gracefully: the fake records the signal it
// received. On Windows the escalation is TerminateProcess, which nothing
// can catch — the marker is absent there by design. Everywhere else the
// marker's existence is the proof that no SIGKILL was needed.
const marker = join(profile, "close-signal.txt")
if (process.platform !== "win32") {
expect(readFileSync(marker, "utf8")).toBe("SIGTERM")
} else if (existsSync(marker)) {
expect(readFileSync(marker, "utf8")).toBe("SIGTERM")
}
}, 60_000)
test("repeated sign-ins stay inside the key budget: the newest two remain, the rest go", async () => {
f = fakeInkStone()
const keys = serveKeyRoutes()
const p = await pluginWithFakeBrowser()
const browser = p.auth.methods[0]
for (let i = 0; i < 3; i++) {
const saved = await browser.authorize({}).callback("", {})
expect(saved.type).toBe("success")
expect(saved.apiKey).toBe("sk-new")
}
// three created, prune keeps the newest two of this machine/account: the
// account's 10-key budget is never reached through repeated sign-ins
expect(keys.length).toBe(2)
expect(keys.every((k) => k.name.startsWith("ink-"))).toBe(true)
rmSync(profile, { recursive: true, force: true })
}, 60_000)
test("prune_keys off leaves every key alone, whatever the count", async () => {
f = fakeInkStone()
const keys = serveKeyRoutes()
const p = await pluginWithFakeBrowser({ prune_keys: false })
const browser = p.auth.methods[0]
for (let i = 0; i < 3; i++) {
const saved = await browser.authorize({}).callback("", {})
expect(saved.type).toBe("success")
}
expect(keys.length).toBe(3)
}, 60_000)
+103
View File
@@ -0,0 +1,103 @@
// A fake of the InkStone console and API for the tests: one local server
// standing in for the console, its credit APIs and the OpenAI-compatible
// catalogue, which the plugin's ENDPOINTS are pointed at. route(method, path)
// answers a request; seen lists what came.
import { _internal } from "./index.mjs"
export function fakeInkStone() {
const routes = new Map()
const seen = []
const server = Bun.serve({
port: 0,
hostname: "127.0.0.1",
async fetch(req) {
const url = new URL(req.url)
const text = await req.text()
const r = {
method: req.method,
path: url.pathname,
query: url.searchParams,
headers: req.headers,
text,
url: url.pathname + url.search,
}
if ((req.headers.get("content-type") ?? "").includes("x-www-form-urlencoded")) {
r.form = Object.fromEntries(new URLSearchParams(text))
} else if (text) {
try {
r.json = JSON.parse(text)
} catch {}
}
seen.push(r)
const h = routes.get(req.method + " " + url.pathname)
if (!h) return new Response("no route " + req.method + " " + url.pathname, { status: 404 })
return h(r)
},
})
const origin = `http://127.0.0.1:${server.port}`
const was = { ..._internal.ENDPOINTS }
Object.assign(_internal.ENDPOINTS, {
console: origin,
api: origin + "/v1",
})
return {
origin,
seen,
route: (key, h) => routes.set(key, h),
close() {
server.stop(true)
Object.assign(_internal.ENDPOINTS, was)
},
}
}
export const json = (v, status = 200) =>
new Response(JSON.stringify(v), { status, headers: { "content-type": "application/json" } })
/** A console success envelope. */
export const ok = (data) => json({ code: 0, msg: "success", data })
/** A console failure envelope: HTTP 200 with a negative code, as the site sends. */
export const fail = (code, msg) => json({ code, msg, data: null })
/** A JWT with the given claims (the console's uaa-token is treated as one). */
export const jwtOf = (claims) =>
["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "sig"].join(".")
export function poolUsageFixture() {
return {
available_credits: 10,
active_package_count: 2,
rpm_limit: 50,
decision_rpm_limit: 200,
tpm_limit: 2_000_000,
usage_windows: {
"5h": { enabled: true, limit_credits: 10, remaining_credits: 6.5, next_recover_at: "2026-11-05T08:00:00Z" },
"7d": { enabled: true, limit_credits: 50, remaining_credits: 41.2, next_recover_at: "2026-11-10T08:00:00Z" },
},
}
}
export function packagesFixture() {
return {
total: 2,
packages: [
{
pkg_id: "pkg-1",
status: "available",
remaining_credits: 6.5,
total_credits: 10,
current_cycle: { start_at: "2026-11-01T00:00:00Z", end_at: "2026-11-28T12:00:00Z" },
remark: "每月免费基础包",
},
{
pkg_id: "pkg-2",
status: "unused",
remaining_credits: 50,
total_credits: 50,
current_cycle: { start_at: "2026-11-01T00:00:00Z", end_at: "2026-12-28T00:00:00Z" },
remark: "扩容包",
},
],
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 11 KiB

+597
View File
@@ -0,0 +1,597 @@
/**
* 书生·端砚 TokenPlan for OpenCode and magpie.
*
* 一个账号两套凭据:
* - `uaa-token`(网页控制台登录态)读墨点:余额、5h/7d 窗口、墨点包;
* - `TOKENPLAN_API_KEY` 调模型(OpenAI Chat Completions)。
*
* 为什么要插件:直接接 API 只回 token usage,不回墨点余额;余额在控制台
* 的 /api/tokenplan/v1/credits/* 里,需要网页登录态。插件替 magpie 持有
* 这份登录态,把余额画成账户卡。
*
* provider id 是 `intern-inkstone`,不是 `intern` / `sensenova`:那些是别的
* 产品或用户自己的 custom provider,本插件不与之冲突。
*/
import {
ENDPOINTS,
cleanDetail,
fingerprint,
normalizeApiKey,
probeApiKey,
apiModels,
publicModels,
creditsBalance,
creditPackages,
usersValidate,
freeGrant,
} from "./lib/protocol.mjs"
import { bootModels, createCatalog, liveRowsOf, publicRowsOf } from "./lib/models.mjs"
import { cardOf } from "./lib/quota.mjs"
import { ensureKey, pruneKeys } from "./lib/keys.mjs"
import {
browserCandidates,
readUaaToken,
renewSilently,
signInWithBrowser,
tokenFresh,
} from "./lib/browser.mjs"
const PROVIDER_ID = "intern-inkstone"
const NPM = "@ai-sdk/openai-compatible"
const NAME = "书生·端砚"
const EARLY_MS = 10 * 60_000
const QUOTA_TTL_MS = 60_000
const DEFAULT_LOGIN_TIMEOUT_MS = 8 * 60_000
const apiBase = () => ENDPOINTS.api
const optNum = (v, fallback) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : fallback)
/** 第一个非空候选(trim 后):`??` 会放过空串,这里不会。 */
function firstNonEmpty(...values) {
for (const v of values) {
const s = String(v ?? "").trim()
if (s) return s
}
return ""
}
/**
* 粘贴框里的"裸 token"是否看起来像 token:不含空白/分号、长度 ≥ 8、
* 等号只出现在末尾(base64 padding),且不是 `uaa-token` 这种 cookie 名。
* 整串 cookie 交给 readUaaToken;这条只收单值,防止把别的 cookie 存进来。
*/
function looksLikeToken(raw) {
const s = String(raw ?? "").trim()
if (s.length < 8) return false
if (/\s|;/.test(s)) return false
if (/^uaa-token$/i.test(s)) return false
// "a=b" 是 cookie 形态;"abc==" 是 base64 padding,允许。
if (/=[^=]/.test(s)) return false
return true
}
function maskUser(value) {
const s = String(value ?? "").trim()
if (!s) return ""
if (/^\d{11}$/.test(s)) return `${s.slice(0, 3)}****${s.slice(-4)}`
if (/^[^@\s]+@[^@\s]+$/.test(s)) {
const [local, domain] = s.split("@")
return `${local.slice(0, 1)}***@${domain}`
}
return s
}
export async function InkStoneAuthPlugin({ client, magpie } = {}, options = {}) {
// The three switches live in the provider editor (auth.options below) and
// are read at the moment they matter — sign-in reads create/prune, renewal
// reads keep — so flipping one applies without a re-sign-in. A factory
// option of the same name is the fallback for hosts and tests without the
// host's option read.
const opt = (key, fallback) => {
try {
const v = magpie?.option?.(PROVIDER_ID, key)
if (typeof v === "boolean") return v
} catch {
/* older host */
}
if (typeof options?.[key] === "boolean") return options[key]
return fallback
}
const createKeyOn = () => opt("create_key", true)
const pruneOn = () => opt("prune_keys", true)
const keepSignInOn = () => opt("keep_sign_in", true)
const loginTimeoutMs = optNum(options.loginTimeoutMs, DEFAULT_LOGIN_TIMEOUT_MS)
// an injection point for tests (the fake browser has no window title to
// poll): hosts never pass it, so the real window-title wait always runs
const waitForLogin = typeof options.waitForLogin === "function" ? options.waitForLogin : undefined
const quotaTtlMs = optNum(options.quotaTtlMs, QUOTA_TTL_MS)
const browserPath = typeof options.browser === "string" && options.browser.trim() ? options.browser.trim() : undefined
const log = (level, message) => {
try {
// 兼顾 (level, message) 和单参 (message) 两种调用。
const text = message === undefined ? String(level ?? "") : String(message ?? "")
const lvl = message === undefined ? "info" : String(level ?? "info")
client?.app?.log?.({ body: { service: PROVIDER_ID, level: lvl, message: cleanDetail(text) } })
} catch {
/* logging is best effort */
}
}
const catalog = createCatalog({
fetchLive: async (key) => liveRowsOf(await apiModels(key)),
fetchMeta: async () => publicRowsOf(await publicModels()),
})
// Caches are keyed by the credential that answered, never module-global:
// two accounts must not read each other's credits or model lists.
const quotaCache = new Map() // uaa token -> { at, value }
const renewing = new Map() // account -> in-flight renew promise
const apiKeyOf = (auth) => {
if (!auth) return ""
const raw = auth.type === "api" ? (auth.key ?? "") : (auth.apiKey ?? auth.access ?? "")
return normalizeApiKey(raw)
}
const uaaTokenOf = (auth) => String(auth?.uaaToken ?? auth?.uaa_token ?? auth?.consoleToken ?? "").trim()
const usernameOf = (auth) => String(auth?.username ?? auth?.accountId ?? auth?.email ?? "").trim()
const save = async (auth) => {
if (typeof client?.auth?.set !== "function") return false
try {
await client.auth.set({ path: { id: PROVIDER_ID }, body: auth })
return true
} catch {
return false
}
}
/** 静默续期(单飞,按账号分桶):保留的 SSO 会话还在,就换一张新的 uaa-token。 */
const renew = async (auth) => {
if (!keepSignInOn()) return ""
// 桶键用凭据指纹而不是显示名:两个账号可能同名,凭据不会。
const bucket = fingerprint(apiKeyOf(auth) || uaaTokenOf(auth) || JSON.stringify(auth))
const inflight = renewing.get(bucket)
if (inflight) return inflight
const flight = (async () => {
try {
const token = await renewSilently({ browserPath, log })
if (!token) return ""
// 同一个 profile 可能同时开着另一个账号的会话:续期回来的 token 不属于
// 本页的账号,再存回去就会串号,先核对一遍再决定。
const expecting = firstNonEmpty(usernameOf(auth))
if (expecting) {
const holder = await usersValidate(token).catch(() => null)
const holderName = firstNonEmpty(
holder?.data?.name, holder?.data?.username, holder?.data?.nickname, holder?.data?.phone, holder?.data?.email,
)
if (holderName && holderName !== expecting) {
log("warn", "inkstone: the renewed session belongs to a different account, skipping")
return ""
}
}
auth.uaaToken = token
await save(auth)
return token
} finally {
renewing.delete(bucket)
}
})()
renewing.set(bucket, flight)
return flight
}
const ensureFreshToken = async (auth) => {
const token = uaaTokenOf(auth)
if (!token) return ""
if (tokenFresh(token, EARLY_MS)) return token
log("info", "inkstone: console token is near expiry; renewing silently")
return (await renew(auth)) || token
}
const readQuota = async (getAuth, auth, depth = 0) => {
let token = await ensureFreshToken(auth)
if (!token) {
return {
plan: "墨点计划 (Token Plan)",
windows: [],
error: "Sign in through the browser (or paste a console uaa-token) to see ink credits.",
signIn: "kept",
}
}
const cached = quotaCache.get(token)
if (cached && Date.now() - cached.at < quotaTtlMs) return cached.value
const [balanceRes, packagesRes, userRes] = await Promise.allSettled([
creditsBalance(token),
creditPackages(token, { query: { status: "all", page: 1, page_size: 50 } }),
usersValidate(token),
])
if (balanceRes.status === "rejected") {
const status = balanceRes.reason?.status
if (status === 403) {
return {
plan: "墨点计划 (Token Plan)",
windows: [],
error: "TokenPlan account disabled in the console",
signIn: "kept",
}
}
if (status === 401) {
// 整次额度读取只允许一次续期重试:同一枚过期 token 反复续期没有意义。
if (depth < 1) {
const fresh = await getAuth()
const next = uaaTokenOf(fresh)
if (next && next !== token) return await readQuota(getAuth, fresh, depth + 1)
const renewed = await renew(auth)
if (renewed && renewed !== token) return await readQuota(getAuth, { ...auth, uaaToken: renewed }, depth + 1)
}
return {
plan: "墨点计划 (Token Plan)",
windows: [],
error: "console session expired; sign in again to see ink credits",
signIn: "kept",
}
}
return {
plan: "墨点计划 (Token Plan)",
windows: [],
error: cleanDetail(`credit balance: ${balanceRes.reason?.message ?? balanceRes.reason}`),
signIn: "kept",
}
}
const balance = balanceRes.value?.data ?? {}
const packages = packagesRes.status === "fulfilled" ? packagesRes.value?.data : null
const userData = userRes.status === "fulfilled" ? userRes.value?.data : null
const errors = []
if (packagesRes.status === "rejected")
errors.push(`credit packs: ${cleanDetail(packagesRes.reason?.message ?? packagesRes.reason)}`)
if (userRes.status === "rejected") errors.push(`account: ${cleanDetail(userRes.reason?.message ?? userRes.reason)}`)
const user = maskUser(firstNonEmpty(userData?.phone, userData?.name, userData?.username, userData?.nickname, usernameOf(auth)))
const value = cardOf({ balance, packages, user, errors })
// 包读取失败但余额成功:余额本身仍是真数据,只把包明细的错误挂上。
quotaCache.set(token, { at: Date.now(), value })
if (quotaCache.size > 8) quotaCache.clear()
return value
}
const declareModels = () => {
const declared = {}
for (const [id, m] of Object.entries(bootModels())) declared[id] = m
return declared
}
return {
config: async (cfg) => {
cfg.provider ??= {}
const p = (cfg.provider[PROVIDER_ID] ??= {})
p.name ??= NAME
p.npm ??= NPM
p.api ??= apiBase()
p.models = { ...declareModels(), ...(p.models ?? {}) }
},
provider: {
id: PROVIDER_ID,
async models(provider, { auth } = {}) {
const declared =
provider?.models && Object.keys(provider.models).length > 0 ? provider.models : declareModels()
if (!auth) return declared
const key = apiKeyOf(auth)
if (!key) return {}
try {
const rows = await catalog.forKey(key)
if (!rows.length) return {}
return Object.fromEntries(rows.map((r) => [r.id, r.model]))
} catch (e) {
// A refused key calls nothing; a failed read keeps the known set.
if (e?.refused || e?.status === 401 || e?.status === 403) return {}
log("warn", `inkstone: keeping the declared models (${e?.message ?? e})`)
return declared
}
},
},
auth: {
provider: PROVIDER_ID,
options: [
{
key: "create_key",
label: "Create an API key on browser sign-in",
description:
"After a browser sign-in, create a TokenPlan API key on the account if none was pasted. The plaintext is shown once, so the plugin keeps it. (Key limit: 10 per account).",
labels: {
zh: "浏览器登录后创建 API Key",
"zh-TW": "瀏覽器登入後建立 API Key",
ja: "ブラウザーサインイン後にAPIキーを作成",
de: "Nach dem Browser-Login ein API-Key erstellen",
},
descriptions: {
zh: "浏览器登录时若输入框留空,就为账号新建一把 TokenPlan API Key(不检查本机已有;上限 10 把)。明文只显示一次,插件会保存它。",
"zh-TW": "瀏覽器登入時若輸入框留空,就為帳號建立一把 TokenPlan API Key(不檢查本機已有;上限 10 把)。明文只顯示一次,外掛會保存它。",
ja: "ブラウザーサインイン時に入力欄が空なら、アカウントに新しいTokenPlan APIキーを作成します(上限10個)。平文は一度だけ表示されるため保存します。",
de: "Wird beim Browser-Login kein Key eingefügt, wird ein neuer TokenPlan-API-Key für das Konto erstellt (Limit: 10). Der Klartext wird nur einmal angezeigt und gespeichert.",
},
default: true,
},
{
key: "prune_keys",
label: "Prune old inkstone API keys",
description:
"Keep the newest two ink-<host>-<account>-* keys and delete older ones on this machine. The key created on this sign-in is always kept; manual keys, and keys whose creation time cannot be read, are never deleted.",
labels: {
zh: "清理旧的端砚 API Key",
"zh-TW": "清理舊的端硯 API Key",
ja: "古いInkStone APIキーを整理",
de: "Alte InkStone-API-Keys entfernen",
},
descriptions: {
zh: "保留本机最新的两个 ink-<host>-<account>-* 密钥,删除更早的。本次登录创建的密钥始终保留;手动创建的、或无法读取创建时间的密钥绝不删除。",
"zh-TW": "保留本機最新的兩個 ink-<host>-<account>-* 金鑰,刪除較舊的。本次登入建立的金鑰始終保留;手動建立的、或無法讀取建立時間的金鑰絕不刪除。",
ja: "このマシン上の最新2つの ink-<host>-<account>-* キーだけを残し、古いものを削除します。今回のサインインで作成したキーは必ず残ります。手動で作成したキーと作成時刻を読み取れないキーは削除しません。",
de: "Behält die zwei neuesten ink-<host>-<account>-* Keys und löscht ältere. Der bei dieser Anmeldung erstellte Key bleibt immer erhalten; manuelle Keys und Keys ohne lesbare Erstellungszeit werden nie gelöscht.",
},
confirm:
"Old ink-<host>-<account>-* keys on this machine will be deleted; manual keys, unreadable keys and the key from this sign-in are kept.",
confirms: {
zh: "将删除本机旧的 ink-<host>-<account>-* 密钥;手动创建的密钥和本次登录创建的密钥会保留。",
"zh-TW": "將刪除本機舊的 ink-<host>-<account>-* 金鑰;手動建立的金鑰和本次登入建立的金鑰會保留。",
ja: "このマシン上の古い ink-<host>-<account>-* キーを削除します。手動で作成したキーと今回のサインインで作成したキーは残します。",
de: "Alte ink-<host>-<account>-* Keys werden gelöscht; manuell erstellte Keys und der bei dieser Anmeldung erstellte Key bleiben erhalten.",
},
default: true,
},
{
key: "keep_sign_in",
label: "Keep a browser profile for silent renewal",
description:
"Keep a dedicated browser profile with the console session, so an about-to-expire uaa-token is renewed headlessly. Off: a one-off profile is deleted after each login and an expired token needs a manual sign-in.",
labels: {
zh: "保留浏览器配置用于静默续期",
"zh-TW": "保留瀏覽器設定用於靜默續期",
ja: "サイレント更新用にブラウザープロファイルを保持",
de: "Browser-Profil für stilles Erneuern behalten",
},
descriptions: {
zh: "保留包含控制台会话的专用浏览器配置,以便 uaa-token 即将过期时无头续期。关闭后,每次登录后删除一次性配置,过期 token 需手动重新登录。",
"zh-TW": "保留包含控制台工作階段的專用瀏覽器設定,以便 uaa-token 即將過期時無痕續期。關閉後,每次登入後刪除一次性的設定,過期 token 需手動重新登入。",
ja: "コンソールセッションを保存した専用ブラウザープロファイルを保持し、uaa-token の期限直前にヘッドレスで更新します。無効にすると、ログインごとに一時プロファイルを削除し、期限切れトークンは手動で再サインインが必要です。",
de: "Behält ein eigenes Browser-Profil mit der Konsolen-Session, damit ein bald ablaufender uaa-token headless erneuert wird. Aus: einmaliges Profil wird nach jeder Anmeldung gelöscht; ein abgelaufener Token erfordert eine manuelle Anmeldung.",
},
default: true,
},
],
methods: [
{
type: "oauth",
label: "Browser sign-in (ink credits + creates an API key)",
/**
* 插件专用 profile 的窗口;插件实时读会话并自己关窗。
*/
prompts: [
{
type: "password",
key: "apiKey",
required: false, // empty means "create one after the browser sign-in"
message: "Leave empty to sign in in a browser (paste an existing key to reuse it)",
placeholder: "sk-...",
validate: (v) => {
const s = String(v ?? "").trim()
return s === "" || s.startsWith("sk-") ? undefined : "the key starts with sk-"
},
},
],
authorize(inputs) {
const pasted = normalizeApiKey(inputs?.apiKey)
if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
return {
type: "failed",
error: "no display for the browser sign-in; use the API key sign-in on this machine",
}
}
try {
browserCandidates(browserPath)
} catch (e) {
return { type: "failed", error: cleanDetail(e?.message ?? e) }
}
// The browser work runs in the callback: the host's authorize call
// has a short deadline, while a sign-in can take minutes.
return {
url: "",
opened: true,
instructions:
process.platform === "win32"
? "A browser window opens on the InkStone console. Sign in there (password, SMS or QR code); the plugin reads the completed sign-in by itself and closes the window. You do not need to close it. After the sign-in the plugin creates an ink-* API key on your account (leave the prompt empty; paste an existing key or turn off \"Create an API key on browser sign-in\" to skip) — the plaintext is shown once, and the plugin keeps it for you."
: "A browser window opens on the InkStone console. Sign in there (password, SMS or QR code), then quit that browser yourself — Cmd+Q on macOS (closing its last window is not enough), or close its last window on Linux. The plugin then reads the session from the profile and finishes. After the sign-in the plugin creates an ink-* API key on your account (leave the prompt empty; paste an existing key or turn off \"Create an API key on browser sign-in\" to skip) — the plaintext is shown once, and the plugin keeps it for you.",
method: "auto",
async callback(_code, { signal } = {}) {
let token = ""
try {
token = await signInWithBrowser({
browserPath,
keepSignIn: keepSignInOn(),
timeoutMs: loginTimeoutMs,
waitForLogin: typeof waitForLogin === "function" ? waitForLogin : undefined,
signal,
log,
})
} catch (e) {
if (e?.cancelled) return { type: "failed", error: "the sign-in was cancelled" }
return { type: "failed", error: cleanDetail(`InkStone sign-in: ${e?.message ?? e}`) }
}
try {
const user = await usersValidate(token).catch(() => null)
const data = user?.data ?? {}
const username = firstNonEmpty(data.name, data.username, data.nickname, data.phone, data.email)
// 如果账号段读不出,拿 token 的指纹兜底:保证两账号前缀永远不撞。
const accountIdent = username || `anon-${fingerprint(token).slice(0, 8)}`
const apiKey = await ensureKey(token, accountIdent, {
apiKey: pasted,
create: createKeyOn(),
prune: pruneOn(),
log,
})
return {
type: "success",
access: apiKey,
refresh: "",
expires: 0,
apiKey,
uaaToken: token,
accountId: username || `inkstone-${fingerprint(apiKey)}`,
username,
source: "browser",
}
} catch (e) {
return { type: "failed", error: cleanDetail(`InkStone sign-in: ${e?.message ?? e}`) }
}
},
}
},
},
{
type: "api",
label: "API key only (models, no ink-credit card)",
prompts: [
{
type: "password",
key: "apiKey",
message: "TokenPlan API key (console → 科研模型 → API Key)",
placeholder: "sk-...",
validate: (v) => (normalizeApiKey(v) ? undefined : "API key is required"),
},
],
async authorize(inputs) {
const key = normalizeApiKey(inputs?.apiKey)
if (!key) return { type: "failed", error: "API key is required" }
try {
await probeApiKey(key)
} catch (e) {
if (e?.status === 401 || e?.status === 403) return { type: "failed", error: cleanDetail(e.message) }
log("warn", `inkstone: API key probe did not finish (${e?.message ?? e})`)
}
return {
type: "success",
key,
accountId: `inkstone-${fingerprint(key)}`,
source: "api",
}
},
},
{
type: "api",
label: "API key + console token (models + ink-credit card)",
prompts: [
{
type: "password",
key: "apiKey",
message: "TokenPlan API key",
placeholder: "sk-...",
validate: (v) => (normalizeApiKey(v) ? undefined : "API key is required"),
},
{
type: "password",
key: "uaaToken",
message: "Console uaa-token (paste just the token value, or the full \"uaa-token=…\" cookie entry)",
validate: (v) => (String(v ?? "").trim() ? undefined : "console token is required"),
},
],
async authorize(inputs) {
const key = normalizeApiKey(inputs?.apiKey)
// 用户可能粘贴整串 document.cookie,也可能只粘 token 本身:
// 前者取 uaa-token 的值;后者必须是看起来像 token 的单个裸值。
// 其余(含别的 cookie 但没有 uaa-token)一律拒绝,绝不整串存进凭据库。
const raw = String(inputs?.uaaToken ?? "").trim()
const bare = looksLikeToken(raw) ? raw : ""
const token = readUaaToken(raw) || bare
if (!key) return { type: "failed", error: "API key is required" }
if (!token) {
return {
type: "failed",
error: 'could not read a uaa-token from that string — paste just the token value or the full "uaa-token=…" cookie entry',
}
}
try {
await probeApiKey(key)
} catch (e) {
if (e?.status === 401 || e?.status === 403) return { type: "failed", error: cleanDetail(e.message) }
log("warn", `inkstone: API key probe did not finish (${e?.message ?? e})`)
}
try {
const user = await usersValidate(token)
const data = user?.data ?? {}
return {
type: "success",
key,
uaaToken: token,
accountId: firstNonEmpty(data.name, data.username, data.nickname, data.phone, data.email, `inkstone-${fingerprint(key)}`),
username: firstNonEmpty(data.name, data.username),
source: "manual",
}
} catch (e) {
return { type: "failed", error: cleanDetail(`console token: ${e?.message ?? e}`) }
}
},
},
],
async loader(getAuth) {
const auth = await getAuth()
const key = apiKeyOf(auth)
if (!key) return {}
return { baseURL: apiBase(), apiKey: key }
},
/**
* 控制台首页会自动POST这个接口领月免费墨点(幂等)。
* 交给 magpie 的 checkin 钩子:是否每天执行由用户在设置里开启,
* 插件不再抢着替用户领、也不再四处轮询;需要重试交给 magpie。
*/
async checkin(getAuth) {
const auth = await getAuth?.()
if (!auth) return { outcome: "failed", message: "sign in again" }
const token = await ensureFreshToken(auth)
if (!token) return { outcome: "failed", message: "sign in again" }
try {
const res = await freeGrant(token)
// 控制台前端明确检查 has_received:为 true 表示已领到。
if (res?.data?.has_received === false) {
return { outcome: "failed", message: "free credits are not yet available" }
}
return { outcome: "done" }
} catch (e) {
// -15900: 未绑定手机号。
if (e?.code === -15900) {
return { outcome: "ineligible", message: "Bind a phone number in the InkStone console to claim free credits." }
}
// 宿主的 checkin 路径不读 signIn(只有 auth.refresh 读):过期就在这里
// 如实报 failed,30 分钟后 magpie 重试,续期由 usage/refresh 链路负责。
return { outcome: "failed", message: cleanDetail(e?.message ?? e) }
}
},
async usage(getAuth) {
const auth = await getAuth()
if (!auth) return { error: "not signed in" }
return await readQuota(getAuth, auth)
},
},
}
}
/** Tests point ENDPOINTS at a local fake and replace the browser. */
export const _internal = {
ENDPOINTS,
PROVIDER_ID,
NPM,
}
+209
View File
@@ -0,0 +1,209 @@
// API-key lifecycle: the 20-character name, create on a blank prompt, the
// ten-key guard, optional pruning that never touches manual keys, and the
// one-time plaintext rule.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { KEY_LIMIT, fingerprint } from "./lib/protocol.mjs"
import { HOST_TAG, ensureKey, keyNameFor, keyPrefixFor, pruneKeys } from "./lib/keys.mjs"
import { fakeInkStone, json, ok, fail } from "./fake.mjs"
let f
afterEach(() => f?.close())
const now = (n) => new Date(Date.UTC(2026, 10, 1, 0, 0, n)).toISOString()
function serveKeys(initial = []) {
const keys = initial.map((k) => ({ ...k }))
f.route("GET /v1/models", () => json({ object: "list", data: [] }))
f.route("GET /api/tokenplan/v1/keys", () => ok({ total: keys.length, items: keys }))
f.route("POST /api/tokenplan/v1/keys", (r) => {
const name = r.json?.name
keys.push({ id: `id-${keys.length + 1}`, name, status: "active", created_at: now(keys.length + 1) })
return ok({ key: "sk-new" })
})
return keys
}
test("a key name fits the console's 20-character limit and carries this host and account", () => {
const name = keyNameFor("u")
expect(name.length).toBeLessThanOrEqual(20)
expect(name.startsWith(keyPrefixFor("u"))).toBe(true)
expect(keyPrefixFor("u").startsWith("ink-")).toBe(true)
// the host segment comes from os.hostname() (4 hex — environment variables
// are absent in macOS GUI processes), the account segment is 4 hex, and the
// random tail is 4 hex: 1 byte only gave 256 names and two keys of one
// account collided
expect(keyPrefixFor("u")).toBe(`ink-${HOST_TAG}-${fingerprint("u").slice(0, 4)}-`)
expect(HOST_TAG).toHaveLength(4)
expect(fingerprint("u").slice(0, 4)).toHaveLength(4)
expect(name.length).toBe(keyPrefixFor("u").length + 4)
})
test("a pasted key is probed and used as-is, with no key created", async () => {
f = fakeInkStone()
serveKeys([])
expect(await ensureKey("uaa", "u", { apiKey: "sk-pasted", create: true })).toBe("sk-pasted")
expect(f.seen.some((r) => r.method === "POST" && r.path.endsWith("/keys"))).toBe(false)
})
test("a blank prompt creates one key with an idempotency key", async () => {
f = fakeInkStone()
serveKeys([])
expect(await ensureKey("uaa", "u", { create: true })).toBe("sk-new")
const post = f.seen.find((r) => r.method === "POST" && r.path.endsWith("/keys"))
expect(post.json.name.startsWith(keyPrefixFor("u"))).toBe(true)
expect(post.headers.get("idempotency-key")).toBeTruthy()
expect(post.json.name.length).toBeLessThanOrEqual(20)
})
test("an account at the ten-key limit is refused unless pruning is on", async () => {
f = fakeInkStone()
const keys = serveKeys(
Array.from({ length: KEY_LIMIT }, (_, i) => ({
id: `k${i}`,
name: `manual-${i}`,
status: "active",
created_at: now(i + 1),
})),
)
await expect(ensureKey("uaa", "u", { create: true })).rejects.toMatchObject({ code: "key_limit" })
expect(keys.length).toBe(KEY_LIMIT)
})
test("pruning frees a slot for a new key and deletes only this machine's old keys", async () => {
f = fakeInkStone()
const prefix = keyPrefixFor("u")
const keys = serveKeys([
{ id: "old", name: `${prefix}aaaa`, status: "active", created_at: now(1) },
{ id: "keep1", name: `${prefix}bbbb`, status: "active", created_at: now(2) },
{ id: "keep2", name: `${prefix}cccc`, status: "active", created_at: now(3) },
{ id: "manual", name: "my-own-key", status: "active", created_at: now(4) },
{ id: "unknown", name: `${prefix}dddd`, status: "active", created_at: "" },
])
const deleted = []
for (const k of keys) {
f.route("DELETE /api/tokenplan/v1/keys/" + k.id, () => {
deleted.push(k.id)
const i = keys.findIndex((x) => x.id === k.id)
if (i >= 0) keys.splice(i, 1)
return ok({})
})
}
const n = await pruneKeys("uaa", "u", { freeSlots: 0 })
expect(n).toBe(1)
expect(deleted).toEqual(["old"])
expect(keys.some((k) => k.id === "manual")).toBe(true)
expect(keys.some((k) => k.id === "unknown")).toBe(true)
})
test("pruning never deletes a key whose age is unknown, including created_at 0", async () => {
f = fakeInkStone()
const prefix = keyPrefixFor("u")
const keys = serveKeys([
{ id: "zero", name: `${prefix}aaaa`, status: "active", created_at: 0 },
{ id: "empty", name: `${prefix}bbbb`, status: "active", created_at: "" },
{ id: "keep1", name: `${prefix}cccc`, status: "active", created_at: now(1) },
])
const deleted = []
for (const k of keys) {
f.route("DELETE /api/tokenplan/v1/keys/" + k.id, () => {
deleted.push(k.id)
const i = keys.findIndex((x) => x.id === k.id)
if (i >= 0) keys.splice(i, 1)
return ok({})
})
}
const n = await pruneKeys("uaa", "u", { freeSlots: 0 })
expect(n).toBe(0)
expect(deleted).toEqual([])
expect(keys.length).toBe(3)
})
test("a freshly created key is protected by NAME even when it is the oldest of three", async () => {
f = fakeInkStone()
const prefix = keyPrefixFor("u")
// the newest two are newer; the protected one is the OLDEST — so keep:2
// alone could not save it, and only protectName does
const inUse = "oldest-in-use"
const keys = serveKeys([
{ id: "oldest", name: `${prefix}${inUse}`, status: "active", created_at: now(1) },
{ id: "mid", name: `${prefix}bbbb`, status: "active", created_at: now(2) },
{ id: "newest", name: `${prefix}cccc`, status: "active", created_at: now(3) },
])
const deleted = []
for (const k of keys) {
f.route("DELETE /api/tokenplan/v1/keys/" + k.id, () => {
deleted.push(k.id)
const i = keys.findIndex((x) => x.id === k.id)
if (i >= 0) keys.splice(i, 1)
return ok({})
})
}
const n = await pruneKeys("uaa", "u", { freeSlots: 0, protectName: `${prefix}${inUse}` })
// the protected key and the two newest survive; nothing older remains to delete
expect(n).toBe(0)
expect(deleted).toEqual([])
expect(keys.some((k) => k.id === "oldest")).toBe(true)
})
test("pruneKeys with a protected name really deletes the others when it should", async () => {
f = fakeInkStone()
const prefix = keyPrefixFor("u")
const keys = serveKeys([
{ id: "old1", name: `${prefix}aaaa`, status: "active", created_at: now(1) },
{ id: "old2", name: `${prefix}bbbb`, status: "active", created_at: now(2) },
{ id: "protected", name: `${prefix}cccc`, status: "active", created_at: now(3) },
{ id: "newest", name: `${prefix}dddd`, status: "active", created_at: now(4) },
])
const deleted = []
for (const k of keys) {
f.route("DELETE /api/tokenplan/v1/keys/" + k.id, () => {
deleted.push(k.id)
const i = keys.findIndex((x) => x.id === k.id)
if (i >= 0) keys.splice(i, 1)
return ok({})
})
}
const n = await pruneKeys("uaa", "u", { freeSlots: 0, protectName: `${prefix}aaaa` })
// keep:2 protects "newest" and "protected"; protectName adds "old1";
// only "old2" is a candidate. Drop protectName and this deletes 2 keys.
expect(n).toBe(1)
expect(deleted).toEqual(["old2"])
expect(keys.some((k) => k.id === "old1")).toBe(true)
})
test("a key created without a plaintext is a clear failure, not a silent empty key", async () => {
f = fakeInkStone()
f.route("GET /v1/models", () => json({ object: "list", data: [] }))
f.route("GET /api/tokenplan/v1/keys", () => ok({ total: 0, items: [] }))
f.route("POST /api/tokenplan/v1/keys", () => fail(-15108, "created but hidden"))
await expect(ensureKey("uaa", "u", { create: true })).rejects.toThrow(/plaintext|did not return/i)
})
test("an idempotency clash retries with a FRESH name and returns the key string", async () => {
f = fakeInkStone()
f.route("GET /v1/models", () => json({ object: "list", data: [] }))
f.route("GET /api/tokenplan/v1/keys", () => ok({ total: 0, items: [] }))
const posted = []
// the console refuses the first name only: a retry that kept the same name
// would keep hitting the clash, so the test goes red if the name is stale
let refusedName = ""
f.route("POST /api/tokenplan/v1/keys", (r) => {
const name = r.json?.name
posted.push(name)
if (refusedName === "") {
refusedName = name
return fail(-15109, "name clash")
}
if (name === refusedName) return fail(-15109, "name clash")
return ok({ key: "sk-retried" })
})
const key = await ensureKey("uaa", "u", { create: true })
// must be the plaintext string; an envelope object would become
// "Bearer [object Object]" for every later request
expect(typeof key).toBe("string")
expect(key).toBe("sk-retried")
expect(posted).toHaveLength(2)
expect(posted[1]).not.toBe(posted[0])
expect(posted[0]).toBe(refusedName)
})
+635
View File
@@ -0,0 +1,635 @@
// 受控浏览器登录:插件自己的专用浏览器 profile。
//
// 设计的三条硬边界(都是在这台机器上验证过的事实):
// 1. Edge/Chrome 136+ 拒绝在**默认用户数据目录**上开远程调试端口——所以
// "直接调试你日常浏览器"这条路在浏览器层面就被堵死了;
// 2. 把你日常浏览器的数据从别的路径打开(拷贝/联接),Edge 会把解不开的
// cookie(v20 应用绑定加密)直接清掉——等于毁掉你的登录态;
// 3. 所以唯一可行的路:插件自己的专用 profile(非默认目录,调试端口
// 正常),登录一次后 cookie 留在里面,之后的续期/重登都在这个
// profile 里静默完成。
//
// 登录窗口**不带**调试端口(阿里的风控看到的是普通浏览器,验证码才能过);
// 只有 headless 读取会话时才开 CDP,且全程只用 Network 域
// (Network.getAllCookies 读浏览器级 cookie),不碰 Runtime.evaluate,
// 不在页面里注入任何东西。
// Windows 上插件用窗口标题判断登录完成并自己关窗;macOS / Linux 读不了窗口
// 标题,登录完成后用户自己关窗,插件收残局。
//
// Bun 1.3.1 在 Windows 上"关掉 CDP WebSocket + 立刻杀进程/删目录"会偶发
// 原生崩溃:收尾时不调用 ws.close(),profile 目录交给系统 rmdir 删。
import { spawn, spawnSync } from "node:child_process"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const LOGIN_URL = "https://discovery.intern-ai.org.cn/token-plan/home"
// 同一时刻只允许一个浏览器实例使用插件专用 profile:登录窗口、静默续期、
// headless 读 cookie 都在这个 profile 上,两个实例同时开会把命令互相委托,
// 后启动的那个"立刻退出"。续期遇到登录进行中就跳过(下一次额度刷新再来)。
let profileBusy = 0
const exclusive = async (fn, cancelled = () => false) => {
while (profileBusy > 0) {
if (cancelled()) throw new Error("another sign-in is still using the browser profile")
await sleep(200)
}
profileBusy += 1
try {
return await fn()
} finally {
profileBusy -= 1
}
}
/** 本机可用的 Chromium 系浏览器;`MAGPIE_INKSTONE_BROWSER` 可覆盖。 */
export function browserCandidates(explicit) {
if (explicit && typeof explicit === "string") {
if (!existsSync(explicit)) throw new Error(`指定的浏览器不存在: ${explicit}`)
return [explicit]
}
const env = process.env
const out = []
const push = (p) => {
if (p && existsSync(p) && !out.includes(p)) out.push(p)
}
if (env.MAGPIE_INKSTONE_BROWSER) push(env.MAGPIE_INKSTONE_BROWSER)
const pf = env.ProgramFiles
const pf86 = env["ProgramFiles(x86)"]
const local = env.LOCALAPPDATA
const home = env.HOME
if (process.platform === "win32") {
push(pf86 && join(pf86, "Microsoft", "Edge", "Application", "msedge.exe"))
push(pf && join(pf, "Microsoft", "Edge", "Application", "msedge.exe"))
push(pf86 && join(pf86, "Google", "Chrome", "Application", "chrome.exe"))
push(pf && join(pf, "Google", "Chrome", "Application", "chrome.exe"))
push(local && join(local, "Google", "Chrome", "Application", "chrome.exe"))
push(local && join(local, "Microsoft", "Edge", "Application", "msedge.exe"))
} else if (process.platform === "darwin") {
push("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge")
push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
push("/Applications/Chromium.app/Contents/MacOS/Chromium")
push(home && join(home, "Applications", "Chromium.app", "Contents", "MacOS", "Chromium"))
} else {
push("/usr/bin/microsoft-edge")
push("/usr/bin/google-chrome")
push("/usr/bin/google-chrome-stable")
push("/usr/bin/chromium")
push("/usr/bin/chromium-browser")
}
return out
}
/** 插件专用(可续期)profile 的目录;不同平台放各自的应用数据目录。 */
export function profileDir(env = process.env, platform = process.platform) {
if (env.MAGPIE_INKSTONE_PROFILE) return env.MAGPIE_INKSTONE_PROFILE
if (platform === "win32") return join(env.LOCALAPPDATA || env.APPDATA || tmpdir(), "magpie", "inkstone-browser")
return join(env.XDG_CONFIG_HOME || join(env.HOME || tmpdir(), ".config"), "magpie", "inkstone-browser")
}
/** 一次性 profile:登录完就删,不把登录态留在磁盘上。 */
export function oneOffProfileDir() {
return mkdtempSync(join(tmpdir(), "magpie-inkstone-login-"))
}
function browserEnv() {
const env = { ...process.env }
for (const key of ["__COMPAT_LAYER", "COMPAT_LAYER", "CHROME_HEADLESS", "ELECTRON_RUN_AS_NODE"]) delete env[key]
return env
}
export function browserArgs(profile, port, url, { headless = false, cdp = true, login = false } = {}) {
const args = [`--user-data-dir=${profile}`]
if (cdp) args.push(`--remote-debugging-port=${port}`, "--remote-debugging-address=127.0.0.1")
args.push("--no-first-run", "--no-default-browser-check", "--disable-background-mode")
if (!login) {
// 隐私开关只用于 headless 续期;登录窗口保持普通浏览器的样子,
// 控制台的风控读这些开关。
args.push(
"--disable-background-networking",
"--disable-component-update",
"--disable-sync",
"--disable-default-apps",
"--no-service-autorun",
"--disable-breakpad",
"--no-pings",
)
}
args.push("--window-size=1100,800", url)
if (headless) args.unshift("--headless=new")
return args
}
/** `uaa-token` 的值:js-cookie 写的是 URL 编码,读的时候解一次。 */
export function readUaaToken(cookieString) {
const m = /(?:^|;\s*)uaa-token=([^;]*)/.exec(String(cookieString ?? ""))
if (!m || !m[1]) return ""
try {
return decodeURIComponent(m[1])
} catch {
return m[1]
}
}
/** JWT 的 exp(毫秒),不是 JWT 或读不出 → 0。 */
export function jwtExp(token) {
const parts = String(token ?? "").split(".")
if (parts.length !== 3) return 0
try {
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"))
const exp = Number(payload?.exp)
return Number.isFinite(exp) && exp > 0 ? exp * 1000 : 0
} catch {
return 0
}
}
/** token 是否还够用(不知道 exp 就当够用,交给 401 去判断)。 */
export function tokenFresh(token, leadMs) {
const exp = jwtExp(token)
return !exp || exp - Date.now() > leadMs
}
class Cdp {
constructor(ws) {
this.ws = ws
this.seq = 0
this.pending = new Map()
ws.onmessage = (e) => this.dispatch(e)
ws.onclose = () => {
for (const { reject } of this.pending.values()) reject(new Error("browser debug connection closed"))
this.pending.clear()
}
}
static async connect(port, { timeoutMs = 20_000, preferHost = "" } = {}) {
const deadline = Date.now() + timeoutMs
let page = null
while (Date.now() < deadline && !page) {
try {
const res = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(3000) })
const list = await res.json()
page =
list.find(
(t) =>
t?.type === "page" &&
t.webSocketDebuggerUrl &&
(!preferHost || (typeof t.url === "string" && t.url.includes(preferHost))),
) ?? null
} catch {
/* 端口刚起来时可能还没有页面目标 */
}
if (!page) await sleep(100)
}
if (!page) throw new Error("浏览器的调试端口没有可用的页面目标")
const ws = new WebSocket(page.webSocketDebuggerUrl)
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("连接浏览器调试 WebSocket 超时")), 10_000)
ws.onopen = () => {
clearTimeout(timer)
resolve()
}
ws.onerror = () => {
clearTimeout(timer)
reject(new Error("浏览器调试 WebSocket 连接失败"))
}
})
return new Cdp(ws)
}
dispatch(e) {
let msg
try {
msg = JSON.parse(typeof e.data === "string" ? e.data : "")
} catch {
return
}
if (msg?.id && this.pending.has(msg.id)) {
const { resolve, reject } = this.pending.get(msg.id)
this.pending.delete(msg.id)
if (msg.error) reject(new Error(msg.error.message ?? JSON.stringify(msg.error)))
else resolve(msg.result)
}
}
send(method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++this.seq
// CDP 不回答不能无限等:挂死的 send 会让静默续期永不返回,
// 上层的单飞锁也会被永久占住。
const timer = setTimeout(() => {
this.pending.delete(id)
reject(new Error(`CDP ${method} timed out`))
}, 15_000)
this.pending.set(id, {
resolve: (v) => {
clearTimeout(timer)
resolve(v)
},
reject: (e) => {
clearTimeout(timer)
reject(e)
},
})
try {
this.ws.send(JSON.stringify({ id, method, params }))
} catch (e) {
clearTimeout(timer)
this.pending.delete(id)
reject(e)
}
})
}
/** 丢掉引用但不调用 ws.close():见文件头对 Bun 段错误的说明。 */
detach() {
for (const { reject } of this.pending.values()) reject(new Error("browser debug connection closed"))
this.pending.clear()
this.ws = null
}
}
function killTree(child) {
if (!child || child.exitCode !== null || child.killed) return
try {
if (process.platform === "win32") {
spawnSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore", windowsHide: true })
} else {
child.kill("SIGKILL")
}
} catch {
/* 进程可能已经退出 */
}
}
function killProfileProcessesWindows(profile, log = () => {}) {
try {
const filter = String(profile).replace(/'/g, "''")
// .Contains() 而不是 -like:-like 会把路径里的 [ ] 当通配符。
spawnSync(
"powershell",
[
"-NoProfile",
"-Command",
`Get-CimInstance Win32_Process -Filter "name like '%msedge%' or name like '%chrome%'" | ` +
`Where-Object { $_.CommandLine -and $_.CommandLine.Contains('${filter}') } | ` +
`ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`,
],
{ stdio: "ignore", windowsHide: true, timeout: 30_000 },
)
} catch (e) {
log(`cleaning leftover browsers failed: ${e?.message ?? e}`)
}
}
function killProfileProcessesUnix(profile, log = () => {}) {
try {
// 只匹配 "--user-data-dir=<本插件 profile>":pkill -f 是对全体进程命令行
// 做正则,裸路径里的 . 会匹配任意字符、短路径会误杀无关进程。
const pattern = `--user-data-dir=${String(profile).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`
spawnSync("pkill", ["-f", "--", pattern], { stdio: "ignore" })
} catch (e) {
log(`cleaning leftover browsers failed: ${e?.message ?? e}`)
}
}
/** 杀掉仍占着这个专用 profile 的残留浏览器进程(只清插件自己的 profile)。 */
export function killProfileProcesses(profile, log = () => {}) {
if (process.platform === "win32") killProfileProcessesWindows(profile, log)
else killProfileProcessesUnix(profile, log)
}
async function removeProfile(dir) {
if (!dir || !existsSync(dir)) return true
for (let i = 0; i < 12; i++) {
if (process.platform === "win32") {
// cmd 会把 & ^ | < > 等元字符拆开;路径含元字符时改走 rmSync(只发生在
// CDP 从未建立的启动失败场景,无 Bun 崩溃风险)。
if (/[&^|<>"]/.test(dir)) {
try {
rmSync(dir, { recursive: true, force: true, maxRetries: 12, retryDelay: 500 })
return true
} catch {
/* 文件锁:稍后重试 */
}
} else {
const r = spawnSync("cmd", ["/c", "rmdir", "/s", "/q", dir], { stdio: "ignore", windowsHide: true })
if (r.status === 0) return true
}
} else {
try {
rmSync(dir, { recursive: true, force: true })
return true
} catch {
/* 文件锁:稍后重试 */
}
}
await sleep(500)
}
return !existsSync(dir)
}
async function waitForDebugPort(portFile, child, timeoutMs = 25_000) {
const deadline = Date.now() + timeoutMs
let exited = false
child.once("exit", () => {
exited = true
})
while (Date.now() < deadline) {
try {
const port = Number(readFileSync(portFile, "utf8").split("\n")[0])
if (Number.isInteger(port) && port > 0) {
// 文件可能是上一轮留下的旧端口:只有 CDP 端点真的应答才算数。
const live = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1500) })
.then((r) => r.ok)
.catch(() => false)
if (live) return port
}
} catch (e) {
if (e?.name === "AbortError") {
// 端口在但端点不应答:浏览器正在启动或已僵死,按旧端口处理继续等。
}
/* 文件还没写出来 */
}
if (exited) throw new Error("浏览器启动后立刻退出了(被策略拦截?)")
await sleep(120)
}
throw new Error("浏览器没有写出调试端口,启动失败。请重试,或改用「仅 API Key」登录。")
}
/**
* 打开一个受控浏览器(插件专用 profile)并返回会话。
* `token()` 通过 CDP 的 Network 域读浏览器级 cookie——不管当前标签页是
* Edge 的同步确认页还是别的,都能读到 `uaa-token`。
*/
export async function openSession({ browserPath, profile, headless = false, plainBrowser = false, url = LOGIN_URL, log = () => {} } = {}) {
const exe = browserCandidates(browserPath)[0]
if (!exe) throw new Error("No Chromium browser was found (Edge or Chrome); use the API key sign-in instead.")
if (!existsSync(profile)) mkdirSync(profile, { recursive: true, mode: 0o700 })
const portFile = join(profile, "DevToolsActivePort")
// 上一轮被强制关闭时可能留下端口/单例锁文件;没有浏览器运行时清掉是安全的。
for (const name of ["DevToolsActivePort", "SingletonLock", "SingletonCookie", "SingletonSocket"]) {
try {
rmSync(join(profile, name), { force: true })
} catch {}
}
const args = plainBrowser
? browserArgs(profile, 0, url, { headless, login: true })
: browserArgs(profile, 0, url, { headless })
const child = spawn(exe, args, { stdio: "ignore", env: browserEnv() })
let cdp = null
let closed = false
try {
const port = await waitForDebugPort(portFile, child)
log(`browser debug port ${port}`)
cdp = await Cdp.connect(port, { preferHost: new URL(url).host })
await cdp.send("Network.enable")
return {
async token() {
const res = await cdp.send("Network.getAllCookies")
const match = (res?.cookies ?? []).find(
(c) =>
c?.name === "uaa-token" &&
typeof c?.domain === "string" &&
// 精确匹配:includes 会放过 evilintern-ai.org.cn 这类域。
(c.domain === "intern-ai.org.cn" || c.domain.endsWith(".intern-ai.org.cn")),
)
if (match?.value) {
const value = String(match.value)
try {
return value.includes("%") ? decodeURIComponent(value) : value
} catch {
return value
}
}
return ""
},
async close() {
if (closed) return
closed = true
// 优先通过 CDP 优雅退出(Browser.close 让 Chromium 把 cookie flush 到磁盘);
// 失败或超时才强制杀进程树。
try {
await Promise.race([
cdp?.send("Browser.close"),
sleep(1500),
])
} catch {
/* 浏览器可能已退出 */
}
cdp?.detach()
killTree(child)
// Edge 在 Windows 上会"换父":启动 PID 可能已退出而浏览器还活着,
// 按 user-data-dir 兜底清一遍。
killProfileProcesses(profile, log)
await sleep(600)
},
}
} catch (e) {
cdp?.detach()
killTree(child)
killProfileProcesses(profile, log)
await sleep(300)
// Never delete the profile here: it holds the signed-in session, and a
// transient launch failure must not force a fresh sign-in.
throw e
}
}
/** 轮询直到读到 token / 超时。 */
export async function waitForToken(session, { timeoutMs = 8 * 60_000, pollMs = 750, signal, log = () => {} } = {}) {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (signal?.aborted) throw Object.assign(new Error("the sign-in was cancelled"), { cancelled: true })
try {
// 单次读也限死在剩余时间里:CDP 挂死时靠外层超时兜底退出。
const left = deadline - Date.now()
const token = await Promise.race([
session.token(),
sleep(Math.min(left, 15_000)).then(() => ""),
])
if (token) return token
} catch (e) {
log(`browser read retry: ${e?.message ?? e}`)
}
await sleep(pollMs)
}
throw new Error("登录超时:没有在浏览器里完成登录")
}
/** 我们自己的那个浏览器进程的窗口标题(只按 PID,避免误看你日常 Edge 的窗口)。 */
export function windowTitleOf(pid, platform = process.platform) {
if (platform !== "win32" || !pid) return ""
try {
const r = spawnSync(
"powershell",
["-NoProfile", "-Command", `(Get-Process -Id ${Number(pid)} -ErrorAction SilentlyContinue).MainWindowTitle`],
{ encoding: "utf8", windowsHide: true, timeout: 5000 },
)
return String(r.stdout ?? "").trim()
} catch {
return ""
}
}
/**
* 优雅关闭:Windows 发 WM_CLOSE 让 Edge 走正常退出流程(会把 cookie 刷到磁盘);
* Unix 先 SIGTERM(Chromium 收到后同样把 cookie flush 出去再退出)。
* 等它自己退出;超时才 SIGKILL——强杀会丢掉刚登录写下的 cookie。
*/
export async function closeWindowGracefully(child, { timeoutMs = 15_000, log = () => {} } = {}) {
if (!child) return
try {
if (process.platform === "win32") {
spawnSync(
"powershell",
["-NoProfile", "-Command", `(Get-Process -Id ${Number(child.pid)} -ErrorAction SilentlyContinue).CloseMainWindow()`],
{ stdio: "ignore", windowsHide: true, timeout: 10_000 },
)
} else {
// macOS/Linux 没有 powershell,也不要等它失败:直接 SIGTERM。
child.kill("SIGTERM")
}
} catch (e) {
log(`graceful close failed: ${e?.message ?? e}`)
}
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (child.exitCode !== null || child.signalCode !== null) return true
await sleep(300)
}
log("graceful close timed out; forcing")
killTree(child)
return false
}
/**
* 等登录窗口从 SSO 页跳到控制台。
*
* 登录窗口没有 CDP(否则阿里的验证码过不了),所以用窗口标题做完成信号:
* SSO 页是「上海人工智能实验室-用户认证体系」,控制台是「书生·端砚 Intern
* InkStone」。窗口被用户关掉也算结束(之后直接尝试读 cookie)。
*/
/**
* 登录窗口的完成等待。可测试:`platform` 参数让非 Windows 的"只认进程退出"
* 行为在任何宿主上都能被验证。
*/
export async function waitForConsoleWindow(child, { timeoutMs = 8 * 60_000, pollMs = 1000, signal, log = () => {}, platform = process.platform } = {}) {
const deadline = Date.now() + timeoutMs
const started = Date.now()
// 窗口标题只能靠 Windows 的 Get-Process 读;别的平台就以“用户关掉窗口”
// 作为完成信号(提示语里会说明),否则只能干等满整个超时。
const canReadTitle = platform === "win32"
let hits = 0
while (Date.now() < deadline) {
if (child.exitCode !== null || child.signalCode !== null) return "closed"
if (signal?.aborted) return "aborted"
if (!canReadTitle) {
await sleep(pollMs)
continue
}
// 只看我们自己的窗口;并且给它至少 5 秒,控制台标题在跳转 SSO 前会闪一下。
const title = Date.now() - started > 5000 ? windowTitleOf(child.pid) : ""
if (title && /Intern InkStone|端砚/i.test(title) && !/用户认证|登录/i.test(title)) {
hits += 1
if (hits >= 2) return "console"
} else {
hits = 0
}
await sleep(pollMs)
}
return "timeout"
}
/**
* 浏览器登录:两段式。
*
* 1. 可见窗口,**不带 CDP**——阿里的风控看到的是普通浏览器,验证码能过;
* 2. 用窗口标题判断登录完成(SSO → 控制台),插件自己关窗;
* 3. 同一个专用 profile 里 headless + CDP 读 `uaa-token`(此时登录已完成,
* 不再影响验证码)。
*
* 登录态留在专用 profile 里(keepSignIn),续期和下次登录都直接用它。
*/
export async function signInWithBrowser({ browserPath, keepSignIn = true, timeoutMs = 8 * 60_000, waitForLogin, signal, log = () => {} } = {}) {
const dir = keepSignIn ? profileDir() : oneOffProfileDir()
const exe = browserCandidates(browserPath)[0]
if (!exe) throw new Error("No Chromium browser was found (Edge or Chrome); use the API key sign-in instead.")
const cancelled = () => Boolean(signal?.aborted)
return await exclusive(async () => {
log("opening the sign-in window")
killProfileProcesses(dir, log)
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
try {
const child = spawn(exe, browserArgs(dir, 0, LOGIN_URL, { cdp: false, login: true }), {
stdio: "ignore",
env: browserEnv(),
})
try {
// waitForLogin is an injection point for tests: given it, the window
// wait is replaced entirely and nothing in this module reads the env.
const how = waitForLogin
? await waitForLogin({ child, signal })
: await waitForConsoleWindow(child, { timeoutMs, signal, log })
log(`login window finished (${how})`)
if (how === "aborted") throw Object.assign(new Error("the sign-in was cancelled"), { cancelled: true })
// 登录完成:让页面稳定一下,然后**优雅关闭**(WM_CLOSE),让 Edge
// 把刚写下的 cookie 刷到磁盘;直接强杀会丢掉 uaa-token。
await sleep(2000)
} finally {
await closeWindowGracefully(child, { log })
killProfileProcesses(dir, log)
await sleep(1500)
}
// 用 profile 里刚写下的会话读 token;遇到残留进程造成的"立刻退出"重试一次。
for (let attempt = 1; attempt <= 2; attempt++) {
if (cancelled()) throw Object.assign(new Error("the sign-in was cancelled"), { cancelled: true })
let s
try {
s = await openSession({ browserPath: exe, profile: dir, headless: true, log })
const token = await waitForToken(s, { timeoutMs: 20_000, signal, log })
if (!token) throw new Error("could not read the console session after the sign-in")
return token
} catch (e) {
if (cancelled()) throw Object.assign(new Error("the sign-in was cancelled"), { cancelled: true })
if (attempt === 2) throw e
log(`headless read failed (${e?.message ?? e}); cleaning the profile and retrying`)
killProfileProcesses(dir, log)
await sleep(1200)
} finally {
await s?.close().catch(() => {})
}
}
} finally {
if (!keepSignIn) await removeProfile(dir)
}
})
}
/**
* 静默续期:专用 profile 里 headless 打开控制台页,SSO 会话还在就会重新
* 下 `uaa-token`。读不到就返回空串(交给调用方提示重新登录),不抛错。
*/
export async function renewSilently({ browserPath, timeoutMs = 20_000, log = () => {} } = {}) {
const dir = profileDir()
if (!existsSync(dir)) return ""
// 登录正在进行时不要抢 profile:下一次额度刷新再续。
if (profileBusy > 0) return ""
return await exclusive(async () => {
killProfileProcesses(dir, log)
let session
try {
session = await openSession({ browserPath, profile: dir, headless: true, log })
return await waitForToken(session, { timeoutMs, log })
} catch (e) {
log(`silent renewal failed: ${e?.message ?? e}`)
return ""
} finally {
await session?.close().catch(() => {})
}
})
}
export { removeProfile, killTree, LOGIN_URL }
+205
View File
@@ -0,0 +1,205 @@
// TokenPlan API keys:命名、创建、数量守卫与可选清理。
//
// 控制台的 Key 列表只给 masked_key,明文只在创建时返回一次,所以**没有
// "从列表复用明文"这条路**:要么用户把现有 Key 粘进来,要么插件新建一把。
// Key 名上限 20 字符、单账号上限 10 把,所以名字必须短、清理必须克制:
// - 名字 `ink-<host4>-<acct4>-<rand4>`,18 字符(上限 20,留余量);
// - host 段隔离别的机器(os.hostname(),不是环境变量——macOS 的 GUI 进程
// 没有 COMPUTERNAME/HOSTNAME),acct 段 4 位隔离同机账号,随机段 4 位
// 防重名(1 位只有 256 个名字,同一账号连建两把就会撞);
// - 清理只碰 `ink-<host4>-<acct4>-*`,手动建的 Key 永远不动。
import { randomBytes, randomUUID } from "node:crypto"
import { hostname } from "node:os"
import { fingerprint, listKeys, createKey, deleteKey, probeApiKey, KEY_LIMIT } from "./protocol.mjs"
/** 4 hex:机器不撞;macOS GUI 进程没有 COMPUTERNAME/HOSTNAME,必须用 os.hostname()。 */
export const HOST_TAG = fingerprint(hostname()).slice(0, 4)
const accountTag = (username) => fingerprint(username || "account").slice(0, 4)
/** 随机段 2 字节:4+4+1+4+1+4 = 18 ≤ 20,平台 Key 名上限留了余量。 */
const randomTag = () => randomBytes(2).toString("hex")
/** 本插件建的 Key 的名字前缀(含机器与账号段),清理按它圈范围。 */
export function keyPrefixFor(username) {
return `ink-${HOST_TAG}-${accountTag(username)}-`
}
/** ≤20 字符的 Key 名:4 + 4 + 1 + 4 + 1 + 4 = 18。 */
export function keyNameFor(username) {
return `${keyPrefixFor(username)}${randomTag()}`
}
const at = (value) => {
const s = String(value ?? "").trim()
// "0"、空串、负数都不是时间:年龄未知的 Key 永远不删。
if (!s || !/^\d{4,}/.test(s)) return 0
const n = Date.parse(s)
return Number.isFinite(n) && n > 0 ? n : 0
}
/** 新 Key 生效前网关可能要几秒:给几次机会,别把"还没生效"当成"被拒绝"。 */
export async function probeWithRetry(apiKey, log) {
const delays = [0, 1500, 3000, 4500, 6000]
let last = null
for (let i = 0; i < delays.length; i++) {
if (delays[i]) await new Promise((r) => setTimeout(r, delays[i]))
try {
return await probeApiKey(apiKey)
} catch (e) {
last = e
if (e?.status !== 401 && e?.status !== 403) throw e
log?.("info", `inkstone: the new key is still taking effect (try ${i + 1}, HTTP ${e.status})`)
}
}
throw last
}
/** Key 列表的 data.items,归一化成 {id,name,status,createdAt}。 */
export function keyItems(listReply) {
const items = Array.isArray(listReply?.data?.items) ? listReply.data.items : []
return items
.filter((k) => k && k.id)
.map((k) => ({
id: String(k.id),
name: String(k.name ?? ""),
status: String(k.status ?? ""),
createdAt: k.created_at ?? "",
}))
}
/** 账号现在有几把 Key(total 缺失时按数组数)。 */
export async function keyCount(token) {
const listed = await listKeys(token, { query: { page: 1, page_size: 50 } })
const items = keyItems(listed)
const total = Number(listed?.data?.total ?? listed?.data?.total_count ?? 0)
return Math.max(Number.isFinite(total) ? total : 0, items.length)
}
/**
* 删掉本机本账号的旧 `ink-…` Key。
* freeSlots = 0:保留最新两把;freeSlots > 0:为新 Key 腾出位置,最旧先删。
* `protectName`(本轮刚创建的那把的名字)永远不删。正在使用的 Key 一定是
* 最新一次登录创建的那把,所以落在"最新两把"的保护范围内。
* 建不出来时间的 Key 永远不删(年龄未知)。
*/
export async function pruneKeys(token, username, { freeSlots = 0, keep = 2, protectName = "", log } = {}) {
let deleted = 0
try {
const listed = await listKeys(token, { query: { page: 1, page_size: 50 } })
const prefix = keyPrefixFor(username)
const ours = keyItems(listed)
.filter((k) => k.name.startsWith(prefix))
.sort((a, b) => at(b.createdAt) - at(a.createdAt))
if (!ours.length) return 0
const protectedIds = new Set(ours.slice(0, keep).map((k) => k.id))
if (protectName) {
const fresh = ours.find((k) => k.name === protectName)
if (fresh?.id) protectedIds.add(fresh.id)
}
const candidates = ours
.filter((k) => at(k.createdAt) > 0 && !protectedIds.has(k.id))
.sort((a, b) => at(a.createdAt) - at(b.createdAt))
for (const k of candidates) {
if (freeSlots > 0 && deleted >= freeSlots) continue
try {
await deleteKey(token, k.id)
deleted += 1
} catch (e) {
log?.("warn", `inkstone: pruning a key failed (${e?.message ?? e})`)
}
}
} catch (e) {
log?.("warn", `inkstone: key pruning skipped (${e?.message ?? e})`)
}
return deleted
}
/**
* 拿到一把能用的 Key:
* - 用户粘了 Key → 探活后直接用(401/403 才算被拒,网络错误不算);
* - 没粘且允许创建 → 数一下,满了先清理(可选),再创建并探活。
* 抛错时带 `code`:`key_limit`(满了且没开清理)、`refused`(Key 被平台拒)。
*/
export async function ensureKey(token, username, { apiKey = "", create = true, prune = false, log } = {}) {
const pasted = String(apiKey ?? "").trim()
if (pasted) {
await probeWithRetry(pasted, log)
return pasted
}
if (!create) throw Object.assign(new Error("no TokenPlan API key was provided"), { code: "no_key" })
let total = await keyCount(token)
if (total >= KEY_LIMIT && prune) {
const need = Math.max(1, total - (KEY_LIMIT - 1))
const freed = await pruneKeys(token, username, { freeSlots: need, log })
log?.("info", `inkstone: pre-prune removed ${freed}/${need} old key(s)`)
total = await keyCount(token)
}
if (total >= KEY_LIMIT) {
throw Object.assign(
new Error(
`this account already has ${total} API keys (the limit is ${KEY_LIMIT}). ` +
`Delete one in the console, or enable "prune old inkstone API keys" and sign in again.`,
),
{ code: "key_limit" },
)
}
let name = keyNameFor(username)
let reply
try {
reply = await createKey(token, name, randomUUID())
} catch (e) {
// 幂等冲突(-15109):换一个 Idempotency-Key 和一个新名字再试(名字也
// 可能撞),最多三次;-15108 是另一回事:创建成功但明文拿不到了。
if (e?.code === -15109) {
let last = e
for (let attempt = 0; attempt < 3; attempt++) {
try {
name = keyNameFor(username)
reply = await createKey(token, name, randomUUID())
last = null
break
} catch (e2) {
if (e2?.code !== -15109) throw e2
last = e2
}
}
if (last) throw last
}
// -15108:创建成功但明文拿不到了,这把 Key 已无法使用,直接说明。
else if (e?.code === -15108) {
throw new Error(
"the console created an API key but did not return it (the plaintext is shown only once). " +
"Create one in the console and paste it instead.",
)
} else throw e
}
const created = String(reply?.data?.key ?? "").trim()
if (!created) {
// -15108:创建成功但明文拿不到了,这把 Key 已无法使用,直接说明。
throw new Error(
"the console created an API key but did not return it (the plaintext is shown only once). " +
"Create one in the console and paste it instead.",
)
}
try {
await probeWithRetry(created, log)
} catch (e) {
if (e?.status === 401 || e?.status === 403) {
// 建出来却被拒:删掉这把,别给账号留垃圾。
try {
const listed = await listKeys(token, { query: { page: 1, page_size: 50 } })
const match = keyItems(listed).find((k) => k.name === name)
if (match) await deleteKey(token, match.id)
} catch {}
throw Object.assign(new Error(`the new API key was refused (HTTP ${e.status}); paste an existing key instead`), {
status: e.status,
})
}
log?.("warn", `inkstone: the new key's check did not finish (${e?.message ?? e})`)
}
if (prune) await pruneKeys(token, username, { protectName: name, log })
return created
}
+260
View File
@@ -0,0 +1,260 @@
// 模型目录:TokenPlan 的聊天模型清单。
//
// 事实来源分两层,且**两层都是活的**:
// 1. `GET /v1/models`(API Key):这个 Key 真能调用的模型——权威的"有谁";
// 2. `GET /api/tokenplan/v1/public/models`(无需登录):上下文、输入类型、
// 能力、协议与墨点单价——权威的"长什么样"。
//
// 官网文档的模型表与 live 不一致(文档多出已下线的 id),所以这里**不硬编码
// 模型表**:boot 清单只用于冷启动兜底,真实清单永远来自接口。决策模型
// (SystemOne)不是聊天接口,永不进入聊天清单。思考档位不做:平台明确
// 不支持通过请求参数开关/调整思考强度。
export const DEFAULT_CONTEXT = 262_144
// 文档与公共接口都没给最大输出;P0 用真实账号实测后更新。给一个保守值,
// 让 agent 能请求的输出不被人为放大。
export const DEFAULT_OUTPUT = 32_768
// 冷启动兜底清单(登录前 / 两次读取都失败时)。只列官方文档与 live 列表
// 都确认过的 id;有一个 id 在本仓库的抓包里始终被脱敏,宁缺毋滥,不硬编码。
// `free` 是文档口径的限时免费(价格 0),运行时以接口价格为准。
// `rate` 是输入价归一化(1000 墨点/1M = x1),展示用,不参与计费。
export const BOOT_MODELS = {
"Agents-A1": { context: 262_144, reasoning: false, tool: true, image: true, free: true },
"Atria-Dawn": { context: 524_288, reasoning: false, tool: false, image: false, free: true },
"Sage-A1.5": { context: 524_288, reasoning: false, tool: true, image: true, free: true },
"intern-s2": { context: 262_144, reasoning: false, tool: true, image: true, free: true },
"deepseek-v4.1-flash-1017": { context: 1_048_576, reasoning: true, tool: true, image: true, rate: 1 },
"glm-5.3": { context: 1_048_576, reasoning: true, tool: true, image: false, rate: 8 },
"minimax-m3": { context: 1_048_576, reasoning: true, tool: true, image: false, rate: 2.1 },
"qwen3.8-27b": { context: 262_144, reasoning: true, tool: true, image: true, rate: 0.8 },
}
const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined)
const num = (v) => {
const n = typeof v === "number" ? v : Number(String(v ?? "").trim())
return Number.isFinite(n) && n > 0 ? n : undefined
}
const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string" && x) : undefined)
/** 归一化一条公共元数据记录(兼容中英文能力字段)。 */
export function normalizePublic(row) {
if (!row || typeof row !== "object") return null
const id = text(row.id)
if (!id) return null
const caps = list(row.capabilities) ?? []
const capsEn = list(row.capabilities_en) ?? []
const has = (zh, en) => caps.includes(zh) || capsEn.includes(en)
// 价格字段缺失或非法 ≠ 价格为 0:只有两个字段都是有限的非负数、且都为 0,
// 才敢标免费,否则一条缺价格的记录会被误标 free,用户以为不扣墨点。
const priceOf = (v) => {
if (v === null || v === undefined) return undefined
if (typeof v === "string" && !v.trim()) return undefined
const n = typeof v === "number" ? v : Number(String(v).trim())
return Number.isFinite(n) && n >= 0 ? n : undefined
}
const inputPrice = priceOf(row.input_uncached_price)
const outputPrice = priceOf(row.output_price)
const hasPrice = inputPrice !== undefined && outputPrice !== undefined
return {
id,
name: text(row.display_name) ?? text(row.display_name_en) ?? id,
type: text(row.model_type) ?? "chat",
inputs: list(row.input_types) ?? ["text"],
context: num(row.context_length) ?? DEFAULT_CONTEXT,
reasoning: has("深度思考", "Reasoning"),
tool: has("工具调用", "Tool calling"),
...(hasPrice ? { free: inputPrice === 0 && outputPrice === 0 } : {}),
...(inputPrice > 0 ? { rate: Math.round((inputPrice / 1000) * 10) / 10 } : {}),
protocols: new Set(list(row.supported_protocols) ?? []),
marketing: text(row.marketing_label) ?? "",
}
}
/** 从各式信封里取公共模型数组({data:{models:[…]}} / {data:[…]} / 裸数组)。 */
export function publicRowsOf(payload) {
const rows =
payload?.data?.models ??
(Array.isArray(payload?.data) ? payload.data : undefined) ??
payload?.models ??
[]
return (Array.isArray(rows) ? rows : []).map(normalizePublic).filter(Boolean)
}
/** 一条 live 目录行(/v1/models 的 data[]),兼容文档示例之外的字段。 */
export function normalizeLive(row) {
if (!row || typeof row !== "object") return null
const id = text(row.id) ?? text(row.model_id)
if (!id) return null
return {
id,
context: num(row.context_length ?? row.contextLength),
output: num(row.max_output_length ?? row.maxOutputLength ?? row.max_output_tokens),
inputs: list(row.input_modalities ?? row.inputModalities),
features: list(row.supported_features ?? row.supportedFeatures) ?? [],
}
}
export function liveRowsOf(payload) {
const rows = Array.isArray(payload?.data) ? payload.data : []
return rows.map(normalizeLive).filter(Boolean)
}
const MODALITIES = ["text", "image", "audio", "video", "pdf"]
/**
* 一条模型,magpie 的 provider.models / config 两处用的形状。没有 variants:
* 平台不支持思考档位,给了也是无效选择器。
* `free`/`rate` 是 magpie 专有展示字段(模型选择器徽标),OpenCode 忽略。
*/
export function modelOf({ id, name, context, output, inputs, reasoning, tool, image, free, rate }) {
const input = inputs?.length ? inputs : ["text"]
const inputFlags = Object.fromEntries(MODALITIES.map((k) => [k, input.includes(k)]))
const attach = input.some((k) => k !== "text")
return {
name,
reasoning: reasoning === true,
tool_call: tool === true,
attachment: attach,
modalities: { input, output: ["text"] },
limit: { context: context || DEFAULT_CONTEXT, output: output || DEFAULT_OUTPUT },
capabilities: {
reasoning: reasoning === true,
toolcall: tool === true,
attachment: attach,
input: inputFlags,
output: { text: true },
},
...(free ? { free: true } : {}),
...(rate ? { rate } : {}),
}
}
/** boot 清单的一条(config 的冷启动兜底)。 */
export function bootModelOf(id, boot = BOOT_MODELS[id]) {
if (!boot) return null
return modelOf({
id,
name: id,
context: boot.context,
output: DEFAULT_OUTPUT,
inputs: boot.image ? ["text", "image"] : ["text"],
reasoning: boot.reasoning,
tool: boot.tool,
image: boot.image,
free: boot.free,
rate: boot.rate,
})
}
export function bootModels() {
const out = {}
for (const id of Object.keys(BOOT_MODELS)) {
const m = bootModelOf(id)
if (m) out[id] = m
}
return out
}
/** 是否值得列成聊天模型:live 有它,且(有元数据时)它真支持 openai_chat。 */
export function isChatCandidate(live, meta) {
if (!live?.id) return false
if (meta && meta.type === "decision") return false
if (meta && meta.protocols.size && !meta.protocols.has("openai_chat")) return false
return true
}
/** 一条目录合并结果 → provider.models 返回的一条。 */
export function mergeModel(live, meta) {
const id = live?.id ?? meta?.id
if (!id) return null
const inputs = meta?.inputs ?? live?.inputs
const reasoning = meta ? meta.reasoning : (live?.features ?? []).includes("reasoning")
const tool = meta ? meta.tool : (live?.features ?? []).includes("tools")
const image = inputs ? inputs.includes("image") : false
return modelOf({
id,
name: meta?.name ?? id,
context: meta?.context ?? live?.context,
output: live?.output ?? DEFAULT_OUTPUT,
inputs,
reasoning,
tool,
image,
free: meta?.free,
rate: meta?.rate,
})
}
/**
* 拉一次、按 Key 分桶缓存的模型目录。
*
* 缓存必须按 API Key 分桶:provider.models 是按账号调用的,A 账号的清单
* 不能给 B 账号用;公共元数据没有账号,全局缓存一段即可。并发请求不 join
* 别的账号的 in-flight。失败时保留该 Key 上次成功的清单;空清单做短负缓存,
* 避免新 Key 生效前的风暴。
*/
export function createCatalog({ fetchLive, fetchMeta, refreshMs = 6 * 3600_000, metaTtlMs = 10 * 60_000, negativeMs = 30_000 } = {}) {
let metaRows = null
let metaAt = 0
const buckets = new Map()
async function meta() {
const now = Date.now()
if (metaRows && now - metaAt < metaTtlMs) return metaRows
const rows = await fetchMeta()
if (rows.length) {
metaRows = rows
metaAt = now
}
return metaRows ?? []
}
function bucketFor(apiKey) {
let b = buckets.get(apiKey)
if (!b) buckets.set(apiKey, (b = { rows: null, rawAt: 0, inflight: null, emptyAt: 0 }))
return b
}
return {
/** 最近一次成功的公共元数据(没有则 null);boot 兜底用。 */
async meta() {
return meta()
},
/** 这个 Key 的可聊模型:[{ id, meta, live }],失败抛错。 */
async forKey(apiKey) {
if (!apiKey) throw new Error("没有 API Key")
const b = bucketFor(apiKey)
const now = Date.now()
if (b.rows && now - b.rawAt < refreshMs) return b.rows
if (b.inflight) return b.inflight
if (b.emptyAt && now - b.emptyAt < negativeMs) return b.rows ?? []
b.inflight = (async () => {
try {
const live = await fetchLive(apiKey)
const metas = await meta().catch(() => [])
const byId = new Map(metas.map((m) => [m.id, m]))
const rows = live
.map((l) => ({ live: l, meta: byId.get(l.id) }))
.filter(({ live, meta }) => isChatCandidate(live, meta))
.map(({ live, meta }) => ({ id: live.id, live, meta, model: mergeModel(live, meta) }))
.filter((r) => r.model)
if (rows.length) {
b.rows = rows
b.rawAt = Date.now()
b.emptyAt = 0
} else {
b.emptyAt = Date.now()
}
return rows.length ? rows : (b.rows ?? [])
} catch (e) {
if (b.rows) return b.rows
throw e
} finally {
b.inflight = null
}
})()
return b.inflight
},
}
}
+215
View File
@@ -0,0 +1,215 @@
// The platform's endpoints, its console APIs, and the OpenAI-compatible
// catalogue. ENDPOINTS is a mutable object on purpose: the tests point it
// at a local fake (the same shape fake.mjs uses), so no test can reach the
// real platform. Production code reads the values at call time.
import { createHash } from "node:crypto"
export const ENDPOINTS = {
console: "https://discovery.intern-ai.org.cn",
api: "https://discovery-api.intern-ai.org.cn/v1",
}
export const PUBLIC_MODELS_PATH = "/api/tokenplan/v1/public/models"
export const CONSOLE_API = "/api/tokenplan/v1"
const UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"
const TIMEOUT_MS = 20_000
export const KEY_LIMIT = 10
export const KEY_NAME_LIMIT = 20
// Vendor text goes into logs and the account card, so it must not carry a
// credential. Only token-shaped runs are masked; the diagnostic words stay.
const SECRETISH =
/(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9._-]{10,}[A-Za-z0-9._-]*|Bearer\s+[A-Za-z0-9._~+/-]{12,}|(?:uaa[-_]?token|refresh[-_]?token|access[-_]?token|id[-_]?token)\s*[=:]\s*[A-Za-z0-9._~+/-]{12,}|sk-[A-Za-z0-9-]{8,})/gi
export function cleanDetail(value) {
return String(value ?? "").replace(SECRETISH, "***")
}
export class ProtocolError extends Error {
constructor(message, { status = 0, code = 0 } = {}) {
super(message)
this.name = "ProtocolError"
this.status = status
this.code = code
}
}
/** Trim a pasted key: spaces, a stray `Bearer `, and wrapping quotes. */
export function normalizeApiKey(value) {
let s = String(value ?? "").trim()
if (/^bearer\s+/i.test(s)) s = s.replace(/^bearer\s+/i, "")
return s.replace(/^["'`]|["'`]$/g, "").trim()
}
function clientHints() {
return {
"user-agent": UA,
"sec-ch-ua": '"Chromium";v="152", "Not;A=Brand";v="24", "Google Chrome";v="152"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
}
/** The console APIs' browser-shaped headers (the platform's WAF expects them). */
export function consoleHeaders(token, extra = {}) {
return {
authorization: `Bearer ${token}`,
accept: "application/json",
"accept-language": "zh-CN",
origin: ENDPOINTS.console,
referer: `${ENDPOINTS.console}/token-plan/home`,
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
...clientHints(),
...extra,
}
}
async function readJson(res, what) {
const text = await res.text().catch(() => "")
let json = null
try {
json = text ? JSON.parse(text) : null
} catch {
/* a non-JSON body is handled by its status */
}
if (!res.ok) {
const detail = cleanDetail(
json?.msg || json?.message || json?.error?.message || text.slice(0, 200).trim() || `HTTP ${res.status}`,
)
throw new ProtocolError(`${what}: ${detail}`, { status: res.status, code: json?.code })
}
if (!json || typeof json !== "object") {
throw new ProtocolError(`${what}: non-JSON reply`, { status: res.status })
}
// The console answers {code:0,...} on success and a non-zero code with
// HTTP 200 when the account or the request is the problem: surface that
// as an error the caller can tell from a network failure.
if (typeof json.code === "number" && json.code !== 0) {
throw new ProtocolError(`${what}: ${cleanDetail(json.msg || `code ${json.code}`)}`, {
status: res.status,
code: json.code,
})
}
return json
}
async function consoleFetch(url, token, init, what, timeoutMs = TIMEOUT_MS) {
let res
try {
res = await fetch(url, {
...init,
headers: consoleHeaders(token, init?.headers),
signal: AbortSignal.timeout(timeoutMs),
})
} catch (e) {
throw new ProtocolError(`${what}: ${cleanDetail(e?.message ?? e)}`)
}
return readJson(res, what)
}
/** GET a console API. `query` is an object of search params. */
export function consoleGet(path, token, { query, timeoutMs } = {}) {
const q = query ? `?${new URLSearchParams(query)}` : ""
return consoleFetch(`${ENDPOINTS.console}${path}${q}`, token, { method: "GET" }, path, timeoutMs)
}
/** POST/PUT/DELETE a console API. */
export function consoleSend(path, token, { method = "POST", body, headers, timeoutMs } = {}) {
return consoleFetch(
`${ENDPOINTS.console}${path}`,
token,
{
method,
body: body === undefined ? undefined : JSON.stringify(body),
headers: body === undefined ? headers : { "content-type": "application/json", ...headers },
},
path,
timeoutMs,
)
}
/** The public model metadata: no credential, the page loads it signed out. */
export async function publicModels({ timeoutMs } = {}) {
let res
try {
res = await fetch(`${ENDPOINTS.console}${PUBLIC_MODELS_PATH}?page=1&page_size=50`, {
headers: { accept: "application/json", "accept-language": "zh-CN", "user-agent": UA },
signal: AbortSignal.timeout(timeoutMs ?? TIMEOUT_MS),
})
} catch (e) {
throw new ProtocolError(`public models: ${cleanDetail(e?.message ?? e)}`)
}
return readJson(res, "public models")
}
/** The catalogue the key is served: free, read-only, and it costs no credits. */
export async function apiModels(apiKey, { timeoutMs } = {}) {
let res
try {
res = await fetch(`${ENDPOINTS.api}/models`, {
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs ?? TIMEOUT_MS),
})
} catch (e) {
throw new ProtocolError(`model catalogue: ${cleanDetail(e?.message ?? e)}`)
}
if (res.status === 401 || res.status === 403) {
throw Object.assign(new ProtocolError(`TokenPlan refused the API key (HTTP ${res.status})`, { status: res.status }), {
refused: true,
})
}
// The raw envelope: the caller normalizes (live rows carry more than the
// doc example shows, and the caller wants the whole body).
return readJson(res, "model catalogue")
}
/** A best-effort key check: only 401/403 says the key is invalid. */
export async function probeApiKey(apiKey, { timeoutMs = 10_000 } = {}) {
let res
try {
res = await fetch(`${ENDPOINTS.api}/models`, {
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs),
})
} catch (e) {
throw new ProtocolError(`API key probe: ${cleanDetail(e?.message ?? e)}`)
}
if (res.status === 401 || res.status === 403) {
throw new ProtocolError(`API key refused (HTTP ${res.status})`, { status: res.status })
}
return res.ok
}
/* ------------------------------------------------------- console endpoints */
export const creditsBalance = (token, o) => consoleGet(`${CONSOLE_API}/credits/balance`, token, o)
export const creditPackages = (token, o) => consoleGet(`${CONSOLE_API}/credits/packages`, token, o)
export const usersValidate = (token, o) => consoleGet(`${CONSOLE_API}/users/validate`, token, o)
/** Claims the month's free ink points. Idempotent: has_received says so. */
export const freeGrant = (token, o) => consoleSend(`${CONSOLE_API}/users/free-grant`, token, { ...o })
export function listKeys(token, o) {
return consoleGet(`${CONSOLE_API}/keys`, token, o)
}
export function createKey(token, name, idempotencyKey, o) {
return consoleSend(`${CONSOLE_API}/keys`, token, {
body: { name },
headers: { "Idempotency-Key": idempotencyKey },
...o,
})
}
export function deleteKey(token, id, o) {
return consoleSend(`${CONSOLE_API}/keys/${encodeURIComponent(id)}`, token, { method: "DELETE", ...o })
}
/** A stable short fingerprint for names and cache buckets. */
export function fingerprint(value) {
return createHash("sha256").update(String(value ?? "")).digest("hex").slice(0, 12)
}
+195
View File
@@ -0,0 +1,195 @@
// pool/credits → magpie 账户卡的窗口与明细。
//
// 控制台的数字可能是字符串也可能是数字;时间既有 ISO 字符串也有秒级时间戳。
// 这里统一归一化,映射成 magpie 的 usage 形状:
// - 前两个窗口(5h / 7d)画成进度条:used 是**已用占比**,display 是已用/总量
// (与 Cursor / factory 等插件一致;官方卡片显示"剩余/总量",这里换算成已用);
// - 其余信息放 aside 行,tooltip 里可见:每个墨点包、限速。
//
// 读不到的字段绝不伪造:余额为 0 是"没额度",读失败是"不知道",两者不能混。
/** 容错正数:"600000" / 591300.25 / null 都能读;负数与垃圾归 0。 */
export function flexNum(value) {
const n = typeof value === "number" ? value : Number(String(value ?? "").trim())
return Number.isFinite(n) && n > 0 ? n : 0
}
/** 可缺的数:空串/undefined → undefined,供"字段缺失"与"0"区分。 */
export function optionalNum(value) {
if (value === null || value === undefined) return undefined
const s = String(value).trim()
if (!s) return undefined
const n = Number(s)
return Number.isFinite(n) ? n : undefined
}
/** 最多两位小数、无千分位(卡片自己加)。 */
export function compact(n) {
const v = Number(n)
if (!Number.isFinite(v) || v <= 0) return "0"
const s = v.toFixed(2).replace(/\.?0+$/, "")
return s === "" ? "0" : s
}
/** 整数千分位(限速这类大数字读起来省事):2000000 → "2,000,000"。 */
export function group(n) {
const v = Math.round(Number(n))
if (!Number.isFinite(v) || v <= 0) return ""
return String(v).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
/** 控制台的时间:ISO 字符串或秒/毫秒时间戳 → ISO,读不出就 undefined。 */
export function isoOf(value) {
if (value === null || value === undefined || value === "") return undefined
// 控制台的数字可能是字符串:"1700000000" 这类纯数字按时间戳读,
// "0" 不是时间,字符串垃圾也不是。
if (/^\d+$/.test(String(value).trim())) {
const n = Number(String(value).trim())
if (!(n > 0)) return undefined
const ms = n > 1e12 ? n : n * 1000
const d = new Date(ms)
return Number.isNaN(d.getTime()) ? undefined : d.toISOString()
}
if (typeof value === "number") {
if (!(value > 0)) return undefined
const ms = value > 1e12 ? value : value * 1000
const d = new Date(ms)
return Number.isNaN(d.getTime()) ? undefined : d.toISOString()
}
const s = String(value).trim()
const d = new Date(s.includes("T") || s.includes(" ") ? s.replace(" ", "T") : s)
return Number.isNaN(d.getTime()) ? undefined : d.toISOString()
}
const dayOf = (d) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`
/** 控制台的本地日历日:时刻按本机时区取日期,避免 UTC 偏移把日期退一天。 */
export function localDay(iso) {
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return undefined
return dayOf(d)
}
/**
* credits/balance → 头部与两个进度条。
* `balance` 是控制台的 data 字段。窗口缺 limit、或 used/remaining 都没有时
* 跳过(不显示成 0% 假象);`enabled` 为 false 的窗口也跳过。
*/
export function windowsOf(balance) {
const out = []
const usage = balance?.usage_windows ?? {}
for (const [key, name, span] of [
["5h", "5 hours", 5 * 3600],
["7d", "7 days", 7 * 24 * 3600],
]) {
const w = usage[key]
if (!w || w.enabled === false) continue
const limit = flexNum(w.limit_credits)
if (limit <= 0) continue
const remaining = optionalNum(w.remaining_credits)
const usedGiven = optionalNum(w.used_credits)
const spent =
usedGiven !== undefined
? Math.max(0, usedGiven)
: remaining !== undefined
? Math.max(0, limit - remaining)
: undefined
if (spent === undefined) continue
const round = (n) => Math.round(n * 100) / 100
const pct = Math.max(0, Math.min(100, (spent / limit) * 100))
out.push({
name,
used: pct,
display: `${compact(spent)} / ${compact(limit)}`,
amount: round(spent),
limit: round(limit),
unit: "墨点",
span,
...(isoOf(w.next_recover_at) ? { resetsAt: isoOf(w.next_recover_at) } : {}),
})
}
return out
}
/**
* credits/packages → 每个可用墨点包一行,直接用控制台自己的包名;
* 没名字时回退“墨点包N”。只列还剩墨点、且状态可用的包。
*/
export function packageRows(packages) {
const items = Array.isArray(packages?.packages)
? packages.packages
: Array.isArray(packages?.items)
? packages.items
: Array.isArray(packages)
? packages
: []
const ok = new Set(["available", "unused"])
const rows = []
for (const p of items) {
const remaining = flexNum(p.remaining_credits)
// total 缺失不是 0:没有总量就只显示剩余,不伪造 "剩 1 / 0"。
const total = optionalNum(p.total_credits)
const status = String(p.status ?? "").toLowerCase()
if (remaining <= 0) continue
if (status && !ok.has(status)) continue
const expiry = isoOf(p.current_cycle?.end_at)
const day = localDay(expiry)
// 控制台对每个包都给了一个名字:优先展示它,免得“墨点包1”只有内部人知道是什么。
const vendorName = typeof p?.remark === "string" && p.remark.trim() ? p.remark.trim() : typeof p?.remark_en === "string" && p.remark_en.trim() ? p.remark_en.trim() : ""
const round = (n) => Math.round(n * 100) / 100
// 面板的约定(plugin-host 的 usage 文档):amount 是**已用**、limit 是总量,
// 面板显示"剩余 = limit - amount"。amount 填剩余会被再减一次,整行数字对不上。
const spent = total > 0 ? Math.max(0, total - remaining) : undefined
const pct = spent !== undefined ? Math.max(0, Math.min(100, (spent / total) * 100)) : undefined
rows.push({
name: vendorName || `墨点包${rows.length + 1}`,
...(pct !== undefined ? { used: pct } : {}),
display: `剩 ${compact(remaining)}${total > 0 ? ` / ${compact(total)}` : ""}${day ? ` · ${day} 到期` : ""}`,
...(spent !== undefined ? { amount: round(spent), limit: round(total) } : {}),
unit: "墨点",
// 包到期不是重置:交给宿主的 runsOutAt/runsOut(hover 行),不占 resetsAt。
...(expiry ? { runsOutAt: expiry, runsOut: round(remaining) } : {}),
aside: true,
})
}
return rows
}
/**
* 组装整张卡。读失败的段单独说明,不拖垮整卡:
* 余额/窗口是主数据,包是明细,失败只留一句说明。
*/
export function cardOf({ balance, packages, user, errors = [] } = {}) {
const available = optionalNum(balance?.available_credits)
const packs = flexNum(balance?.active_package_count)
const windows = windowsOf(balance)
const packRows = packageRows(packages)
const rows = [
...packRows,
...(flexNum(balance?.rpm_limit) || flexNum(balance?.tpm_limit)
? [
{
name: "限速",
used: 0,
display: `${group(flexNum(balance.rpm_limit)) || "—"} RPM · ${group(flexNum(balance.tpm_limit)) || "—"} TPM`,
aside: true,
},
]
: []),
]
return {
plan: "墨点计划 (Token Plan)",
...(user ? { user } : {}),
...(available !== undefined
? { balance: `${compact(available)} 墨点${packs > 0 ? ` · ${packs} 个可用包` : ""}` }
: packs > 0
? { balance: `${packs} 个可用包` }
: {}),
windows: [...windows, ...rows],
...(errors.length ? { error: errors.join("; ") } : {}),
signIn: "kept",
}
}
+188
View File
@@ -0,0 +1,188 @@
// The model catalogue: the live /v1/models set intersected with the public
// metadata, without the decision model and without thinking tiers (the
// platform documents that thinking cannot be turned on or off by request).
import "./nonet.mjs"
import { readFileSync } from "node:fs"
import { expect, test } from "bun:test"
import {
BOOT_MODELS,
DEFAULT_CONTEXT,
DEFAULT_OUTPUT,
bootModelOf,
bootModels,
createCatalog,
isChatCandidate,
mergeModel,
normalizePublic,
publicRowsOf,
} from "./lib/models.mjs"
const load = (name) => JSON.parse(readFileSync(new URL("./testdata/" + name, import.meta.url), "utf8"))
const META = publicRowsOf(load("public-models.json"))
test("the real public metadata has ten models, one of them a decision model", () => {
expect(META.length).toBe(10)
expect(META.filter((m) => m.type === "decision").map((m) => m.id)).toEqual(["intern-decision-4b"])
// four of the ten are free at the captured prices
expect(META.filter((m) => m.free).map((m) => m.id).sort()).toEqual([
"Agents-A1",
"Atria-Dawn",
"Sage-A1.5",
"intern-s2",
])
})
test("paid models carry a rate derived from the input price (1000 credits/1M = x1); free ones carry none", () => {
const rates = Object.fromEntries(META.filter((m) => m.rate).map((m) => [m.id, m.rate]))
expect(rates).toEqual({
"deepseek-v4.1-flash-1017": 1,
"glm-5.3": 8,
"intern-decision-4b": 0.2,
"kimi-k2.6": 6.5,
"minimax-m3": 2.1,
"qwen3.8-27b": 0.8,
})
for (const m of META.filter((m) => m.free)) expect(m.rate).toBeUndefined()
})
test("free and rate reach the merged model", () => {
const glm = mergeModel({ id: "glm-5.3" }, META.find((m) => m.id === "glm-5.3"))
expect(glm.rate).toBe(8)
expect(glm.free).toBeUndefined()
const sage = mergeModel({ id: "Sage-A1.5" }, META.find((m) => m.id === "Sage-A1.5"))
expect(sage.free).toBe(true)
expect(sage.rate).toBeUndefined()
})
test("a model keeps the catalogue's context and capability flags", () => {
const glm = mergeModel({ id: "glm-5.3" }, META.find((m) => m.id === "glm-5.3"))
expect(glm.name).toBe("GLM-5.3")
expect(glm.limit).toEqual({ context: 1048576, output: DEFAULT_OUTPUT })
expect(glm.reasoning).toBe(true)
expect(glm.tool_call).toBe(true)
expect(glm.capabilities.input.image).toBe(false)
// no variants: the platform publishes no thinking tiers it accepts.
expect(glm.variants).toBeUndefined()
const agents = mergeModel({ id: "Agents-A1" }, META.find((m) => m.id === "Agents-A1"))
expect(agents.limit.context).toBe(262144)
expect(agents.reasoning).toBe(false)
expect(agents.tool_call).toBe(true)
expect(agents.capabilities.input.image).toBe(true)
expect(agents.modalities.input).toEqual(["text", "image"])
})
test("a model outside the metadata is kept from the live list with safe defaults", () => {
const m = mergeModel({ id: "brand-new-model", context: 131072, features: ["tools", "reasoning"] }, undefined)
expect(m.name).toBe("brand-new-model")
expect(m.limit.context).toBe(131072)
expect(m.limit.output).toBe(DEFAULT_OUTPUT)
expect(m.reasoning).toBe(true)
expect(m.tool_call).toBe(true)
})
test("the decision model is never a chat candidate", () => {
const decision = META.find((m) => m.id === "intern-decision-4b")
expect(isChatCandidate({ id: "intern-decision-4b" }, decision)).toBe(false)
// a model that only speaks Anthropic is not chat
const anth = { id: "x", type: "chat", protocols: new Set(["anthropic_messages"]) }
expect(isChatCandidate({ id: "x" }, anth)).toBe(false)
// no metadata: the live /v1/models data[] is generative by definition
expect(isChatCandidate({ id: "x" }, undefined)).toBe(true)
})
test("the catalogue intersects the key's list with the metadata and drops the decision model", async () => {
const live = [
{ id: "glm-5.3" },
{ id: "Agents-A1" },
{ id: "intern-decision-4b" },
{ id: "brand-new-model" },
]
const catalog = createCatalog({
fetchLive: async () => live,
fetchMeta: async () => META,
})
const rows = await catalog.forKey("sk-test")
expect(rows.map((r) => r.id)).toEqual(["glm-5.3", "Agents-A1", "brand-new-model"])
})
test("a live read that fails keeps the last successful list for that key", async () => {
let fail = false
const catalog = createCatalog({
fetchLive: async () => {
if (fail) throw new Error("HTTP 500")
return [{ id: "glm-5.3" }]
},
fetchMeta: async () => META,
})
expect((await catalog.forKey("k")).map((r) => r.id)).toEqual(["glm-5.3"])
fail = true
expect((await catalog.forKey("k")).map((r) => r.id)).toEqual(["glm-5.3"])
})
test("an empty answer is cached briefly and gives no models, not the bootstrap set", async () => {
const catalog = createCatalog({
fetchLive: async () => [],
fetchMeta: async () => META,
})
expect(await catalog.forKey("k")).toEqual([])
expect(await catalog.forKey("k")).toEqual([])
})
test("the bootstrap list is non-empty, every entry has a usable limit and its price tier", () => {
const boot = bootModels()
expect(Object.keys(boot).length).toBeGreaterThan(0)
expect(Object.keys(boot)).toEqual(Object.keys(BOOT_MODELS))
for (const [id, m] of Object.entries(boot)) {
expect(m.limit.context).toBeGreaterThan(0)
expect(m.limit.output).toBe(DEFAULT_OUTPUT)
expect(m.variants).toBeUndefined()
if (BOOT_MODELS[id].free) {
expect(m.free).toBe(true)
expect(m.rate).toBeUndefined()
} else {
expect(m.free).toBeUndefined()
expect(m.rate).toBeGreaterThan(0)
}
}
})
test("the bootstrap list agrees with the captured catalogue on every id it shares", () => {
const byId = new Map(META.map((m) => [m.id, m]))
for (const [id, boot] of Object.entries(BOOT_MODELS)) {
const meta = byId.get(id)
expect(meta).toBeDefined()
// free/rate must not contradict the live prices: a bootstrap entry claiming
// free for a priced model would show a "free" badge on a paid model.
expect(Boolean(boot.free)).toBe(Boolean(meta.free))
if (!boot.free) expect(boot.rate).toBe(meta.rate)
}
})
test("a metadata row without prices is not marked free", () => {
const bare = normalizePublic({ id: "no-prices", display_name: "No Prices" })
expect(bare.id).toBe("no-prices")
expect(bare.free).toBeUndefined()
expect(bare.rate).toBeUndefined()
// a zero price on both sides is free
const free = normalizePublic({ id: "zero", input_uncached_price: 0, output_price: 0 })
expect(free.free).toBe(true)
// a zero input but a priced output is not free
const outOnly = normalizePublic({ id: "out", input_uncached_price: 0, output_price: 5 })
expect(outOnly.free).toBe(false)
// an empty string, junk or a negative number is a missing price, not 0
expect(normalizePublic({ id: "dirty", input_uncached_price: "", output_price: "" }).free).toBeUndefined()
expect(normalizePublic({ id: "dirty2", input_uncached_price: -5, output_price: 0 }).free).toBeUndefined()
expect(normalizePublic({ id: "dirty3", input_uncached_price: "n/a", output_price: 0 }).free).toBeUndefined()
// junk rows do not throw
expect(normalizePublic(null)).toBeNull()
expect(normalizePublic({})).toBeNull()
expect(normalizePublic({ id: 42 })).toBeNull()
})
test("mergeModel survives two empty sides", () => {
expect(mergeModel(null, null)).toBeNull()
expect(mergeModel({}, {})).toBeNull()
expect(bootModelOf("no-such-model")).toBeNull()
})
+18
View File
@@ -0,0 +1,18 @@
// Imported first by every test here: nothing a test runs reaches the real
// InkStone hosts. fetch and HTTP/2 go to this machine (a test's fake) or fail,
// so a test left without its fake can't send a console token or API key to
// discovery.intern-ai.org.cn.
import http2 from "node:http2"
const local = (u) => /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(u)
const realFetch = globalThis.fetch
globalThis.fetch = async (input, init) => {
const u = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
if (!local(u)) throw new Error("a test asked " + u + " with no fake in place")
return realFetch(input, init)
}
const connect = http2.connect
http2.connect = (origin, ...rest) => {
if (!local(String(origin))) throw new Error("a test connected to " + origin)
return connect(origin, ...rest)
}
+5
View File
@@ -0,0 +1,5 @@
// The package's OpenCode 1.x plugins, as OpenCode 1.x and magpie's host
// load them: its plugin functions and nothing else (1.x refuses a package
// whose exports include anything but plugins). OpenCode 2.x loads
// opencode2.mjs, which runs these.
export { InkStoneAuthPlugin } from "./index.mjs"
+597
View File
@@ -0,0 +1,597 @@
// The OpenCode 2.x face of a package whose plugins are written for
// OpenCode 1.x (and magpie's plugin host).
//
// OpenCode 2.x loads a package's `exports["."]` and wants its default to be
// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions
// (plugins#657). This file is that default. It runs each 1.x plugin the
// package's opencode.mjs exports and hands 2.x what the plugin's hooks say:
//
// auth.methods → the integration's sign-in methods
// config() → the provider, its package, base URL and models
// provider.models → the signed-in account's own model list
// auth.loader → each request's base URL, key, headers and fetch
//
// What 2.x has no place for is left out: chat.headers and chat.params
// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin,
// tools and events.
//
// scripts/opencode2.mjs is the one copy that is edited. Every package that
// has it carries the same bytes as packages/<name>/opencode2.mjs, and
// scripts/check.mjs fails when a copy differs.
import { readFileSync } from "node:fs"
import * as v1 from "./opencode.mjs"
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
// The key the SDK is made with: the account's own goes on each request in
// its place (see wrapFetch), so a key read when the SDK was made can't go
// out after the account changed.
const PLACEHOLDER = "opencode2-v1-key"
// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from
// swapping @ai-sdk/* for its native providers, which never call the sdk
// hook below; openai-compatible's is the one 2.x ships, the others are AI
// SDK v6's dist-tag, the line 2.x's bridge runs.
export function packageOf(npm) {
const name = npm || "@ai-sdk/openai-compatible"
if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41"
if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6`
return `aisdk:${name}`
}
// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read
// them: a default {server} is the one plugin, else every function export
// and every {server} object.
export function pluginsOf(mod) {
const d = mod?.default
if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d))
return typeof d.server === "function" ? [d.server] : []
const out = []
for (const value of Object.values(mod ?? {})) {
const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null
if (fn && !out.includes(fn)) out.push(fn)
}
return out
}
const int = (n, fallback = 0) => {
const v = Math.trunc(Number(n))
return Number.isFinite(v) && v >= 0 ? v : fallback
}
const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0)
const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {})
const json = (v) => {
try {
return JSON.parse(JSON.stringify(v ?? null))
} catch {
return null
}
}
const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string"))
const nonEmpty = (o) => (Object.keys(o).length ? o : undefined)
// connKey names a connection the way 2.x does.
const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`)
// ---- sign-in ------------------------------------------------------------
// fields is a 1.x method's prompts as a 2.x form.
export function fieldsOf(prompts) {
const out = []
for (const p of prompts ?? []) {
if (!p?.key) continue
const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) }
if (p.placeholder) f.placeholder = String(p.placeholder)
if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required
// a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f)
}
return out.length ? out : undefined
}
// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes
// auth.json: the result without its type and provider.
function v1Saved(r) {
const { type: _t, provider: _p, ...rest } = r
if ("key" in r) return { type: "api", ...rest }
return { type: "oauth", ...rest }
}
// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for
// both kinds, the 1.x auth kept whole in its metadata. No refresh is
// registered, so 2.x hands the credential over as it is and the plugin's
// own loader renews it, as it does on 1.x.
export function credentialOf(methodID, r) {
if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed")
const saved = json(v1Saved(r))
if (saved.type === "api")
return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } }
return {
type: "oauth",
methodID,
access: String(saved.access ?? ""),
refresh: String(saved.refresh ?? ""),
expires: int(saved.expires),
metadata: { v1: saved },
}
}
// authOfValue is the 1.x auth a 2.x credential stands for.
export function authOfValue(value) {
if (!value) return null
if (value.type === "oauth") {
const v1 = record(value.metadata).v1
if (v1 && typeof v1 === "object") return v1
return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires }
}
if (value.type === "key") {
const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {}
return { type: "api", key: value.key, ...meta }
}
return null
}
const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""])
// ---- models -------------------------------------------------------------
const MODALITIES = ["text", "audio", "image", "video", "pdf"]
// internalOf is a config model as 1.x hands it to provider.models: what
// fromModelsDevModel makes of it, with the config's own variants.
export function internalOf(providerID, conf, key, m) {
const mods = record(m.modalities)
const has = (list, k) => Array.isArray(list) && list.includes(k)
const cost = record(m.cost)
return {
...m,
id: key,
providerID,
name: m.name ?? key,
api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" },
status: m.status ?? "active",
headers: m.headers ?? {},
options: m.options ?? {},
cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } },
limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) },
capabilities: {
temperature: m.temperature ?? false,
reasoning: m.reasoning ?? false,
attachment: m.attachment ?? false,
toolcall: m.tool_call ?? true,
input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])),
output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])),
interleaved: m.interleaved ?? false,
},
release_date: m.release_date ?? "",
variants: record(m.variants),
}
}
// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info.
export function modelOf(providerID, provider, key, m) {
const caps = record(m.capabilities)
const listFrom = (obj, list) => {
if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k])
if (Array.isArray(list)) return list.map(String)
return ["text"]
}
const input = listFrom(caps.input, m.modalities?.input)
const output = listFrom(caps.output, m.modalities?.output)
const c = record(m.cost)
const cache = record(c.cache)
const npm = m.api?.npm ?? m.provider?.npm
const url = m.api?.url ?? m.provider?.api
const settings = { ...record(json(m.options)) }
if (url && url !== provider.baseURL) settings.baseURL = url
const variants = Object.entries(record(m.variants))
.filter(([, v]) => !record(v).disabled)
.map(([id, v]) => {
const { disabled: _d, ...rest } = record(json(v))
return nonEmpty(rest) ? { id, settings: rest } : { id }
})
const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active"
const out = {
id: key,
modelID: String(m.api?.id ?? m.id ?? key),
providerID,
name: String(m.name ?? key),
capabilities: {
tools: caps.toolcall ?? m.tool_call ?? true,
input: input.length ? input : ["text"],
output: output.length ? output : ["text"],
...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}),
},
variants,
time: { released: Date.parse(m.release_date ?? "") || 0 },
cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }],
status,
enabled: true,
limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 },
}
if (m.limit?.input) out.limit.input = int(m.limit.input)
if (npm && npm !== provider.npm) out.package = packageOf(npm)
if (nonEmpty(settings)) out.settings = settings
const headers = strings(m.headers)
if (nonEmpty(headers)) out.headers = headers
return out
}
// ---- requests -----------------------------------------------------------
const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input))
// wrapFetch sends a request the SDK made from the provider's settings the
// way 1.x would have sent it with the loader's options: the loader's base
// URL in place of the configured one, the account's key in place of the
// placeholder, the loader's headers added, through the loader's fetch.
export function wrapFetch(next, base, options) {
return async (input, init = {}) => {
const o = await options()
let url = urlOf(input)
const from = String(base ?? "").replace(/\/+$/, "")
const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : ""
if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length)
const req = input instanceof Request ? input : null
const headers = new Headers(init.headers ?? req?.headers ?? undefined)
for (const [k, v] of [...headers.entries()]) {
if (!v.includes(PLACEHOLDER)) continue
if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key))
else headers.delete(k)
}
for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v)
const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch
if (req && init.body === undefined) {
const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text()
return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal })
}
return send(url, { ...init, headers })
}
}
// ---- one plugin ---------------------------------------------------------
async function setupPlugin(ctx, fn, live) {
const directory = ctx?.location?.directory ?? process.cwd()
// the active account each provider was last read for, and the renewed
// auth a plugin saved for it (2.x has no way for a plugin to write a
// credential back, so it is kept in the plugin's storage, under the
// credential it renews and the token it was renewed from)
const current = new Map()
const saved = new Map()
const signingIn = new Map()
const storeKey = (id, key) => `v1auth/${id}/${key}`
const client = {
auth: {
async set(arg) {
const id = arg?.path?.id
const body = json(arg?.body)
const cur = id && current.get(id)
// a sign-in's own saves belong to the credential it is about to
// make, not the one that was active when it started
if (!cur || !body || signingIn.get(id) > 0) return { data: true }
const entry = { fp: cur.fp, auth: body }
saved.set(storeKey(id, cur.key), entry)
await Promise.resolve()
.then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry))
.catch(() => {})
return { data: true }
},
async get() {
return { data: undefined }
},
},
app: { log: async () => ({ data: true }) },
}
const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {}
const cfg = { provider: {} }
try {
await hooks.config?.(cfg)
} catch {}
const auth = hooks.auth
const authID = auth?.provider ? String(auth.provider) : undefined
const providers = record(cfg.provider)
// getAuth reads the active account: the credential 2.x holds, or what the
// plugin last saved renewing it.
const getAuth = async (id) => {
const connection = await ctx.integration.connection.active(id).catch(() => undefined)
if (!connection) {
current.delete(id)
return undefined
}
const value = await ctx.integration.connection.resolve(connection).catch(() => undefined)
const base = authOfValue(value)
if (!base) {
current.delete(id)
return undefined
}
const key = connKey(connection)
const fp = fingerprint(base)
// ours: a credential one of this plugin's own sign-ins made
const ours = value?.type === "oauth" && !!record(value.metadata).v1
current.set(id, { key, fp, ours })
const sk = storeKey(id, key)
let entry = saved.get(sk)
if (!entry) {
entry = await Promise.resolve()
.then(() => ctx.storage?.get?.(sk))
.catch(() => undefined)
if (entry) saved.set(sk, entry)
}
return entry && entry.fp === fp && entry.auth ? entry.auth : base
}
// the sign-in methods
if (authID && Array.isArray(auth.methods) && auth.methods.length) {
const label = (c) => {
const a = authOfValue(c)
const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account
return typeof name === "string" && name ? name : undefined
}
const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1)
const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1))
const title = record(providers[authID]).name
// 2.x runs a transform again on every reload, from nothing
await ctx.integration.transform((editor) => {
let keyed = false
// the integration 2.x makes for an id it doesn't know is named by the
// id; the provider's own name reads better in the sign-in list
if (typeof title === "string" && title)
try {
editor.update?.(authID, (i) => {
if (i && (!i.name || i.name === authID)) i.name = title
})
} catch {}
auth.methods.forEach((m, i) => {
if (!m) return
const methodID = `v1-${i}`
const form = fieldsOf(m.prompts)
if (m.type === "api" && typeof m.authorize !== "function") {
if (keyed) return
keyed = true
editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } })
return
}
if (typeof m.authorize !== "function") return
editor.method.update({
integrationID: authID,
method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) },
async authorize(answer) {
begin()
let ended = false
const done = () => {
if (!ended) end()
ended = true
}
try {
const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)]))
const r = await m.authorize(inputs)
if (m.type === "api") {
done()
return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) }
}
if (r?.method === "code")
return {
url: String(r.url ?? ""),
instructions: String(r.instructions ?? ""),
mode: "code",
callback: async (code) => {
try {
return credentialOf(methodID, await r.callback(code))
} finally {
done()
}
},
}
const callback = Promise.resolve()
.then(() => r.callback())
.then((res) => credentialOf(methodID, res))
.finally(done)
callback.catch(() => {})
return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback }
} catch (e) {
done()
throw e
}
},
label,
})
})
})
}
// the loader's options for the account signed in now, read again when
// the account changes
let loaded = null
const loaderOptions = async (id) => {
if (id !== authID || typeof auth?.loader !== "function") {
const a = authID === id ? await getAuth(id) : undefined
return { key: a?.type === "api" ? a.key : undefined }
}
const a = await getAuth(id)
if (!a) return {}
const fp = current.get(id)?.key + "\0" + fingerprint(a)
if (loaded?.fp !== fp) {
const p = Promise.resolve()
.then(() => auth.loader(() => getAuth(id), providerOf(id)))
.then((o) => record(o))
loaded = { fp, p }
p.catch(() => {
if (loaded?.fp === fp) loaded = null
})
}
const o = await loaded.p
const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined
return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch }
}
// the providers, with the list the account's own read last gave each
const source = new Map()
// providerOf is a provider as 1.x hands it to provider.models and
// auth.loader
const providerOf = (id) => {
const conf = record(providers[id])
const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))]))
return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models }
}
const listed = new Set()
for (const [id, conf0] of Object.entries(providers)) {
const conf = record(conf0)
// a provider entry that only names the sign-in (no package, no models)
// is not a provider of models
if (!conf.npm && !Object.keys(record(conf.models)).length) continue
const options = record(conf.options)
const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options
// with no base URL the config leaves it to the loader: a name that
// can't resolve stands in for it, and each request swaps in the
// loader's (wrapFetch)
const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid`
const npm = conf.npm ?? "@ai-sdk/openai-compatible"
const info = {
id,
...(id === authID ? { integrationID: id } : {}),
name: String(conf.name ?? id),
activation: "auto",
package: packageOf(npm),
settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) },
}
const headers = { ...strings(conf.headers), ...strings(optHeaders) }
if (nonEmpty(headers)) info.headers = headers
const prov = { baseURL, npm }
const fromConfig = () =>
Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m))))
listed.add(id)
await ctx.provider.transform((editor) => {
const s = source.get(id)
editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection })
})
source.set(id, { conf, prov, models: null, connection: undefined })
}
// each request: the placeholder key, and the fetch that swaps in the
// account's. A provider the package doesn't list (one 2.x has built in
// that the plugin only signs in to) is left to 2.x unless the plugin's
// loader serves it and one of the plugin's own sign-ins is active.
const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : []
for (const id of new Set([...listed, ...own])) {
const base = source.get(id)?.prov.baseURL
await ctx.aisdk.hook(
"sdk",
async (evt) => {
const opts = evt.options
if (!opts || opts.__opencode2) return
if (!listed.has(id)) {
await getAuth(id)
if (!current.get(id)?.ours) return
}
opts.__opencode2 = true
opts.apiKey = PLACEHOLDER
opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id))
},
{ providerID: id },
)
}
// refresh reads the account's own list after a sign-in or a switch
const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined
let refreshing = null
let again = false
// the account the list was last read for: a credential.updated that
// leaves it as it was reads nothing again
let readFor = null
const stateOf = async () => {
const c = await ctx.integration.connection.active(authID).catch(() => undefined)
const a = c ? await getAuth(authID) : undefined
return connKey(c) + "\0" + (a ? fingerprint(a) : "")
}
const refresh = () => {
if (refreshing) {
again = true
return refreshing
}
refreshing = (async () => {
try {
if (!authID || !source.has(authID)) return
const s = source.get(authID)
const connection = await ctx.integration.connection.active(authID).catch(() => undefined)
const a = connection ? await getAuth(authID) : undefined
readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "")
if (!a || listID !== authID || typeof hooks.provider?.models !== "function") {
if (s.connection || s.models) {
s.connection = undefined
s.models = null
await ctx.provider.reload()
}
return
}
const provider = providerOf(authID)
let got
try {
got = await hooks.provider.models(provider, { auth: a })
} catch {
got = null
}
if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) {
again = true
return
}
s.connection = connection
s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null
await ctx.provider.reload()
await ctx.model?.reload?.()
} finally {
refreshing = null
if (again && live.on) {
again = false
void refresh()
}
}
})()
return refreshing
}
if (authID && ctx.event?.subscribe)
void (async () => {
try {
// a switch names the integration; an update (a sign-in, a removal)
// names nothing, so it reads again only when this account changed
const types = ["credential.switched", "credential.updated"]
for await (const event of ctx.event.subscribe({ types })) {
if (!live.on) return
if (event?.type === "credential.switched" && event?.data?.integrationID === authID) {
loaded = null
await refresh()
} else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) {
await refresh()
}
}
} catch {}
})()
void refresh()
}
export async function setup(ctx, mod = v1) {
const live = { on: true }
for (const fn of pluginsOf(mod)) {
try {
await setupPlugin(ctx, fn, live)
} catch (e) {
// one plugin failing to start leaves the package's others working
console.error(`${pkg.name}: ${e?.message ?? e}`)
}
}
return () => {
live.on = false
}
}
export default { id: pkg.name, setup: (ctx) => setup(ctx) }
+47
View File
@@ -0,0 +1,47 @@
// The GUI's option page keeps at most 60 characters per localized label and
// 300 per localized description or confirm. The English `label` / `description`
// / `confirm` fields are the fallback for older hosts and OpenCode, so the
// localized `labels` / `descriptions` / `confirms` carry the same rules in
// the same five languages.
import "./nonet.mjs"
import { expect, test } from "bun:test"
import { InkStoneAuthPlugin } from "./index.mjs"
const languages = ["de", "ja", "zh", "zh-TW"]
const lengthOf = (text) => [...String(text)].length
test("the config screen's strings stay inside the host's caps and stay translated", async () => {
const plugin = await InkStoneAuthPlugin({ client: { auth: { set: async () => {} } } })
const options = plugin.auth.options
expect(options.map((option) => option.key)).toEqual([
"create_key",
"prune_keys",
"keep_sign_in",
])
for (const option of options) {
expect(lengthOf(option.label)).toBeLessThanOrEqual(60)
expect(lengthOf(option.description)).toBeLessThanOrEqual(300)
for (const field of ["labels", "descriptions"]) {
const localized = option[field]
expect(localized).toBeDefined()
expect(Object.keys(localized).sort()).toEqual(languages)
const cap = field === "labels" ? 60 : 300
for (const lang of languages) {
expect(lengthOf(localized[lang])).toBeLessThanOrEqual(cap)
}
}
}
const prune = options.find((option) => option.key === "prune_keys")
expect(lengthOf(prune.confirm)).toBeLessThanOrEqual(300)
expect(Object.keys(prune.confirms).sort()).toEqual(languages)
for (const lang of languages) expect(lengthOf(prune.confirms[lang])).toBeLessThanOrEqual(300)
// The English fallback tells every account where the line is: the key
// created on this sign-in, and keys whose creation time is unreadable.
expect(prune.description).toContain("The key created on this sign-in is always kept")
expect(prune.description).toContain("manual keys")
expect(prune.description).toContain("creation time cannot be read")
})
File diff suppressed because one or more lines are too long
+126
View File
@@ -0,0 +1,126 @@
// The card's small helpers in isolation: numbers and timestamps from the
// console are loosely typed, so every shape has to degrade to "unknown" rather
// than to a fake zero.
import "./nonet.mjs"
import { expect, test } from "bun:test"
import { cardOf, compact, flexNum, isoOf, localDay, optionalNum, packageRows, windowsOf } from "./lib/quota.mjs"
test("flexNum reads loose numbers and turns junk into 0", () => {
expect(flexNum(600000)).toBe(600000)
expect(flexNum("600000")).toBe(600000)
expect(flexNum("591300.25")).toBe(591300.25)
expect(flexNum(null)).toBe(0)
expect(flexNum("")).toBe(0)
expect(flexNum("abc")).toBe(0)
expect(flexNum(-5)).toBe(0)
expect(flexNum(Infinity)).toBe(0)
})
test("optionalNum keeps 'missing' distinct from 0", () => {
expect(optionalNum(0)).toBe(0)
expect(optionalNum("0")).toBe(0)
expect(optionalNum(null)).toBeUndefined()
expect(optionalNum(undefined)).toBeUndefined()
expect(optionalNum("")).toBeUndefined()
expect(optionalNum("abc")).toBeUndefined()
})
test("compact keeps at most two decimals and no thousands separators", () => {
expect(compact(1000)).toBe("1000")
expect(compact(9831.7)).toBe("9831.7")
expect(compact(0.333)).toBe("0.33")
expect(compact(0)).toBe("0")
})
test("isoOf accepts ISO strings and second/millisecond stamps, and rejects nonsense", () => {
expect(isoOf("2026-11-05T08:00:00Z")).toBe("2026-11-05T08:00:00.000Z")
// a local wall-clock time: compare against the same parse, not a fixed UTC
// string, so the test does not depend on the runner's timezone
expect(isoOf("2026-11-05 08:00:00")).toBe(new Date("2026-11-05T08:00:00").toISOString())
// 0 is not "1970" — it is a missing timestamp, as a number or a string
expect(isoOf(0)).toBeUndefined()
expect(isoOf("0")).toBeUndefined()
// second- and millisecond-scale stamps arrive as strings too
expect(isoOf("1762320000")).toBe(new Date(1762320000 * 1000).toISOString())
expect(isoOf("1762320000000")).toBe(new Date(1762320000000).toISOString())
expect(isoOf(null)).toBeUndefined()
expect(isoOf("")).toBeUndefined()
expect(isoOf("not a date")).toBeUndefined()
})
test("localDay reads a local calendar day and ignores junk", () => {
// build the expected day from the same local-time parse, so the assertion
// holds in every timezone (a fixed UTC string fails west of UTC)
const stamp = "2026-11-28T00:00:00.000Z"
const d = new Date(stamp)
const expected = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`
expect(localDay(stamp)).toBe(expected)
expect(localDay("not a date")).toBeUndefined()
})
test("windowsOf skips disabled, limitless and unmeasurable windows", () => {
const out = windowsOf({
usage_windows: {
"5h": { enabled: false, limit_credits: 10, remaining_credits: 1 },
"7d": { enabled: true, limit_credits: 0, remaining_credits: 0 },
},
})
expect(out).toEqual([])
})
test("windowsOf clamps an over-spent window to 100% and prefers used_credits", () => {
const [five] = windowsOf({
usage_windows: {
"5h": { enabled: true, limit_credits: 10, used_credits: 25, remaining_credits: 0, next_recover_at: 0 },
},
})
expect(five.used).toBe(100)
expect(five.display).toBe("25 / 10")
expect(five.resetsAt).toBeUndefined()
})
test("packageRows tolerates every envelope and filters empty or dead packs", () => {
const packs = [
{ remark: "每月免费基础包", remaining_credits: 6.5, total_credits: 10, status: "available" },
{ remark_en: "Top-up", remaining_credits: 3, total_credits: 3, status: "unused" },
{ remark: "empty", remaining_credits: 0, total_credits: 10, status: "available" },
{ remark: "expired", remaining_credits: 5, total_credits: 5, status: "expired" },
]
const rows = packageRows({ packages: packs })
expect(rows.map((r) => r.name)).toEqual(["每月免费基础包", "Top-up"])
// amount is the *used* share: 10 - 3.5, used is the percentage, limit is the total
expect(rows[0]).toEqual({
name: "每月免费基础包",
used: 35,
display: "剩 6.5 / 10",
amount: 3.5,
limit: 10,
unit: "墨点",
aside: true,
})
expect(packageRows({ items: packs }).length).toBe(2)
expect(packageRows(packs).length).toBe(2)
expect(packageRows(null)).toEqual([])
// a pack with no name still gets a readable label
expect(packageRows([{ remaining_credits: 1, total_credits: 2 }])[0].name).toBe("墨点包1")
// a pack with no total shows only the remainder, never "剩 1 / 0"
const noTotal = packageRows([{ remaining_credits: 1, status: "available" }])[0]
expect(noTotal.display).toBe("剩 1")
expect(noTotal.limit).toBeUndefined()
expect(noTotal.amount).toBeUndefined()
// a pack with no expiry loses runsOutAt and never mutates resetsAt
expect(packageRows([{ remaining_credits: 1, total_credits: 1 }])[0].resetsAt).toBeUndefined()
})
test("cardOf with nothing at all still produces a card, not a crash", () => {
const card = cardOf()
expect(card.plan).toBe("墨点计划 (Token Plan)")
expect(card.windows).toEqual([])
expect(card.balance).toBeUndefined()
expect(card.signIn).toBe("kept")
})
test("cardOf shows a pack count even when the balance number is missing", () => {
const card = cardOf({ balance: { active_package_count: 2 } })
expect(card.balance).toBe("2 个可用包")
})
+98
View File
@@ -0,0 +1,98 @@
// A fake Chromium for tests: serves the DevTools HTTP + WebSocket endpoints
// and writes the DevToolsActivePort file, so the plugin's real openSession /
// waitForToken / CDP cookie read run against it. Modes come from argv:
// --headless=new → serve CDP (the renewal / post-sign-in read)
// (no headless) → the login window: wait for the plugin's close
import { writeFileSync, mkdirSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
const args = process.argv.slice(2)
const profile = args.find((a) => a.startsWith("--user-data-dir="))?.slice(17) ?? "."
// bun build --compile's Windows launcher mangles argument values: the drive
// letter and part of the path are eaten. The test always makes the profile
// under tmpdir(), so the safe repair is: take the last path segment and
// re-seat it under tmpdir().
const profilePath = /^[A-Za-z]:/.test(profile)
? profile
: join(tmpdir(), profile.split(/[\\/]/).filter(Boolean).pop() ?? "fake-profile")
const headless = args.includes("--headless=new")
const url = args.find((a) => a.startsWith("http")) ?? ""
let pageTargetUrl = ""
try {
if (!headless) {
// login window. On Unix it waits for the plugin's SIGTERM and records
// the signal (the test asserts no SIGKILL was needed). On Windows
// TerminateProcess is uncatchable and the plugin's WM_CLOSE cannot reach
// a windowless exe, so exit on our own — otherwise the close path waits
// its full 15s grace period per sign-in.
const exit = () => {
try {
writeFileSync(join(profilePath, "close-signal.txt"), "SIGTERM")
} catch {}
process.exit(0)
}
if (process.platform === "win32") {
setTimeout(() => process.exit(0), 500)
} else {
process.on("SIGTERM", exit)
process.on("SIGINT", exit)
setInterval(() => {}, 10_000)
}
} else {
mkdirSync(profilePath, { recursive: true })
const server = Bun.serve({
port: 0,
fetch(req, server) {
const u = new URL(req.url)
if (u.pathname === "/json/version") return Response.json({ Browser: "FakeChrome/1.0" })
if (u.pathname === "/json/list") {
// the plugin's Cdp.connect picks a type:"page" target whose URL
// matches the console host and whose webSocketDebuggerUrl it can
// open — hand it exactly that, then serve the socket on upgrade
pageTargetUrl = `ws://127.0.0.1:${server.port}/devtools/page/1`
return Response.json([
{
type: "page",
url: url || "https://discovery.intern-ai.org.cn/token-plan/home",
webSocketDebuggerUrl: pageTargetUrl,
},
])
}
// any /devtools/* request is the WebSocket the plugin opened
const up = server.upgrade(req, { data: { page: u.pathname } })
if (up) return undefined
return new Response("not found", { status: 404 })
},
websocket: {
open() {},
message(ws, raw) {
const msg = JSON.parse(String(raw))
if (msg.method === "Network.getAllCookies") {
ws.send(
JSON.stringify({
id: msg.id,
result: {
cookies: [{ name: "uaa-token", value: "fake-uaa-token-for-tests", domain: ".intern-ai.org.cn" }],
},
}),
)
} else {
ws.send(JSON.stringify({ id: msg.id, result: {} }))
}
},
},
})
// the browser-level target: /devtools/browser/<id> on the same port
writeFileSync(join(profilePath, "DevToolsActivePort"), `${server.port}\n/devtools/browser/fake\n`)
console.error("[fake-chrome] serving on", server.port)
const exit = () => process.exit(0)
process.on("SIGTERM", exit)
process.on("SIGINT", exit)
// keep alive; the plugin closes us when it has the cookie
}
} catch (e) {
console.error("[fake-chrome] FAILED:", e?.message ?? e, e?.stack?.slice(0, 400))
process.exit(1)
}
+1
View File
@@ -0,0 +1 @@
{"code":0,"msg":"success","trace_id":"e252aae144dd81d9188683cbe08f2810","data":{"page":1,"page_size":50,"total":10,"models":[{"id":"Agents-A1","display_name":"Agents-A1","display_name_en":"Agents-A1","model_type":"multimodal","input_types":["text","image"],"input_types_en":["Text","Image"],"context_length":262144,"capabilities":["工具调用","科学推理"],"capabilities_en":["Tool calling","Scientific reasoning"],"input_uncached_price":0,"output_price":0,"marketing_label":"Hot","marketing_label_en":"Hot","marketing_label_color":"#C03030","supported_protocols":["openai_chat","anthropic_messages","openai_responses"]},{"id":"Atria-Dawn","display_name":"Atria-Dawn","display_name_en":"Atria-Dawn","model_type":"chat","input_types":["text"],"input_types_en":["Text"],"context_length":524288,"capabilities":["科学推理"],"capabilities_en":["Scientific reasoning"],"input_uncached_price":0,"output_price":0,"marketing_label":"Hot","marketing_label_en":"Hot","marketing_label_color":"#C03030","supported_protocols":["openai_chat","anthropic_messages","openai_responses"]},{"id":"Sage-A1.5","display_name":"Sage-A1.5","display_name_en":"Sage-A1.5","model_type":"multimodal","input_types":["text","image"],"input_types_en":["Text","Image"],"context_length":524288,"capabilities":["工具调用","科学推理"],"capabilities_en":["Tool calling","Scientific reasoning"],"input_uncached_price":0,"output_price":0,"marketing_label":"New","marketing_label_en":"New","marketing_label_color":"#1554A8","supported_protocols":["openai_chat","anthropic_messages","openai_responses"]},{"id":"deepseek-v4.1-flash-1017","display_name":"DeepSeek-V4.1-Flash-1017","display_name_en":"DeepSeek-V4.1-Flash-1017","model_type":"multimodal","input_types":["text","image"],"input_types_en":["Text","Image"],"context_length":1048576,"capabilities":["工具调用","深度思考"],"capabilities_en":["Tool calling","Reasoning"],"input_uncached_price":1000,"output_price":4000,"supported_protocols":["openai_chat","anthropic_messages","openai_responses"]},{"id":"glm-5.3","display_name":"GLM-5.3","display_name_en":"GLM-5.3","model_type":"chat","input_types":["text"],"input_types_en":["Text"],"context_length":1048576,"capabilities":["工具调用","深度思考"],"capabilities_en":["Tool calling","Reasoning"],"input_uncached_price":8000,"output_price":28000,"supported_protocols":["openai_chat","anthropic_messages","openai_responses"]},{"id":"intern-decision-4b","display_name":"书生-Decision-4B","display_name_en":"书生-Decision-4B","model_type":"decision","input_types":["text"],"input_types_en":["Text"],"context_length":8192,"capabilities":["结构化决策"],"capabilities_en":["结构化决策"],"input_uncached_price":200,"output_price":0,"supported_protocols":["systemone"]},{"id":"intern-s2","display_name":"书生-S2","display_name_en":"书生-S2","model_type":"multimodal","input_types":["text","image"],"input_types_en":["Text","Image"],"context_length":262144,"capabilities":["工具调用","科学推理"],"capabilities_en":["Tool calling","Scientific reasoning"],"input_uncached_price":0,"output_price":0,"supported_protocols":["openai_chat","anthropic_messages"]},{"id":"kimi-k2.6","display_name":"Kimi-K2.6","display_name_en":"Kimi-K2.6","model_type":"multimodal","input_types":["text","image"],"input_types_en":["Text","Image"],"context_length":262144,"capabilities":["工具调用","深度思考"],"capabilities_en":["Tool calling","Reasoning"],"input_uncached_price":6500,"output_price":27000,"supported_protocols":["openai_chat","anthropic_messages","openai_responses"]},{"id":"minimax-m3","display_name":"MiniMax-M3","display_name_en":"MiniMax-M3","model_type":"chat","input_types":["text"],"input_types_en":["Text"],"context_length":1048576,"capabilities":["工具调用","深度思考"],"capabilities_en":["Tool calling","Reasoning"],"input_uncached_price":2100,"output_price":8400,"supported_protocols":["openai_chat","anthropic_messages","openai_responses"]},{"id":"qwen3.8-27b","display_name":"Qwen3.8-27B","display_name_en":"Qwen3.8-27B","model_type":"multimodal","input_types":["text","image"],"input_types_en":["Text","Image"],"context_length":262144,"capabilities":["工具调用","深度思考"],"capabilities_en":["Tool calling","Reasoning"],"input_uncached_price":800,"output_price":2700,"supported_protocols":["openai_chat","anthropic_messages"]}]}}
+214
View File
@@ -0,0 +1,214 @@
// The credit card: the console's balance, windows and credit packs as magpie's
// usage card. Everything runs against the local fake; a read that fails must
// say so rather than show a fake zero. Per-model token spend belongs to the
// usage page, not this card.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { InkStoneAuthPlugin } from "./index.mjs"
import { fakeInkStone, ok, poolUsageFixture, packagesFixture } from "./fake.mjs"
let f
afterEach(() => f?.close())
const auth = { type: "oauth", access: "sk-test", apiKey: "sk-test", uaaToken: "uaa-token" }
async function plugin(options = {}) {
return InkStoneAuthPlugin({ client: { auth: { set: async () => {} } } }, options)
}
function serve({ free = ok({ has_received: true }), validate = ok({ name: "张三", phone: "12345678901" }) } = {}) {
f.route("GET /api/tokenplan/v1/credits/balance", () => ok(poolUsageFixture()))
f.route("GET /api/tokenplan/v1/credits/packages", () => ok(packagesFixture()))
f.route("GET /api/tokenplan/v1/users/validate", () => validate)
f.route("POST /api/tokenplan/v1/users/free-grant", () => free)
}
test("balance, 5h/7d windows and the credit packs become the card", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
const u = await p.auth.usage(async () => auth)
expect(u.plan).toBe("墨点计划 (Token Plan)")
expect(u.user).toBe("123****8901")
expect(u.balance).toBe("10 墨点 · 2 个可用包")
expect(u.signIn).toBe("kept")
const five = u.windows.find((w) => w.name === "5 hours")
expect(five.used).toBeCloseTo(35, 1)
expect(five.display).toBe("3.5 / 10")
expect(five.resetsAt).toBe("2026-11-05T08:00:00.000Z")
const seven = u.windows.find((w) => w.name === "7 days")
expect(seven.used).toBeCloseTo(17.6, 1)
expect(seven.display).toBe("8.8 / 50")
const names = u.windows.map((w) => w.name)
expect(names).toContain("每月免费基础包")
expect(names).toContain("扩容包")
expect(names).toContain("限速")
expect(names).not.toContain("最近到期")
// the expiry day is the viewer's calendar day: derive the expected string
// from the same local parse instead of a fixed UTC date (a fixed date fails
// in far-east zones, where 2026-11-28T12:00Z is already the 29th)
const endDay = (() => {
const d = new Date("2026-11-28T12:00:00Z")
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`
})()
expect(u.windows.find((w) => w.name === "每月免费基础包").display).toBe(`剩 6.5 / 10 · ${endDay} 到期`)
// amount is the used share (10 - 6.5), not the remainder
expect(u.windows.find((w) => w.name === "每月免费基础包").used).toBe(35)
expect(u.windows.find((w) => w.name === "每月免费基础包").amount).toBe(3.5)
expect(u.windows.find((w) => w.name === "每月免费基础包").limit).toBe(10)
expect(u.windows.find((w) => w.name === "每月免费基础包").runsOutAt).toBe("2026-11-28T12:00:00.000Z")
expect(u.windows.find((w) => w.name === "每月免费基础包").runsOut).toBe(6.5)
expect(u.windows.find((w) => w.name === "限速").display).toBe("50 RPM · 2,000,000 TPM")
expect(u.windows.find((w) => w.name === "本月免费额度")).toBeUndefined()
// the card carries no per-model rows: token spend is the usage page's job
expect(names.some((n) => n.startsWith("模型 "))).toBe(false)
expect(names).not.toContain("本月已用")
expect(names).not.toContain("今日 tokens")
// the pack rows never become meters
expect(u.windows.find((w) => w.name === "每月免费基础包").aside).toBe(true)
})
test("a usage read asks only the three credit APIs — no per-model calls", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
await p.auth.usage(async () => auth)
const paths = f.seen.map((r) => r.path)
expect(paths.some((p) => p.endsWith("/models/called"))).toBe(false)
expect(paths.some((p) => p.endsWith("/usage/summary"))).toBe(false)
expect(paths.some((p) => p.endsWith("/credits/transactions"))).toBe(false)
expect(paths.some((p) => p.endsWith("/credits/balance"))).toBe(true)
expect(paths.some((p) => p.endsWith("/credits/packages"))).toBe(true)
})
test("the card is cached briefly: a second read in the same minute asks nothing new", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
await p.auth.usage(async () => auth)
const balanceCalls = f.seen.filter((r) => r.path.endsWith("/credits/balance")).length
await p.auth.usage(async () => auth)
expect(f.seen.filter((r) => r.path.endsWith("/credits/balance")).length).toBe(balanceCalls)
})
test("reading usage never claims free credits; magpie decides with auth.checkin", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
const u = await p.auth.usage(async () => auth)
expect(f.seen.some((r) => r.method === "POST" && r.path.endsWith("/users/free-grant"))).toBe(false)
expect(u.windows.some((w) => w.name === "本月免费额度")).toBe(false)
})
test("auth.checkin claims the monthly grant through magpie's hook", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
const r = await p.auth.checkin(async () => auth)
expect(r).toEqual({ outcome: "done" })
expect(f.seen.filter((r) => r.method === "POST" && r.path.endsWith("/users/free-grant")).length).toBe(1)
})
test("auth.checkin says the account can't take part when the phone is missing", async () => {
f = fakeInkStone()
serve({
free: new Response(JSON.stringify({ code: -15900, msg: "PhoneRequired", data: null }), {
status: 200,
headers: { "content-type": "application/json" },
}),
})
const p = await plugin()
const r = await p.auth.checkin(async () => auth)
expect(r.outcome).toBe("ineligible")
})
test("a console 401 for auth.checkin is a plain failure: the host's checkin path reads no signIn", async () => {
f = fakeInkStone()
// keep_sign_in off: the 401 path must not launch a browser in the test
const p = await plugin({ keep_sign_in: false })
f.route("POST /api/tokenplan/v1/users/free-grant", () => new Response("", { status: 401 }))
const r = await p.auth.checkin(async () => auth)
expect(r).toEqual({ outcome: "failed", message: expect.stringContaining("401") })
})
test("no console token: the card says how to get one, and models stay usable", async () => {
f = fakeInkStone()
const p = await plugin()
const u = await p.auth.usage(async () => ({ type: "api", key: "sk-test" }))
expect(u.error).toContain("ink credits")
expect(u.windows).toEqual([])
expect(u.signIn).toBe("kept")
})
test("a console 401 is an error, not an empty balance, and does not sign the account out", async () => {
f = fakeInkStone()
f.route("GET /api/tokenplan/v1/credits/balance", () => new Response("", { status: 401 }))
// keep_sign_in off: the 401 path must not launch a browser in the test
const p = await plugin({ keep_sign_in: false })
const u = await p.auth.usage(async () => auth)
expect(u.error).toContain("console session expired")
expect(u.signIn).toBe("kept")
})
test("a console 403 is reported as a disabled account, not as a broken balance", async () => {
f = fakeInkStone()
f.route("GET /api/tokenplan/v1/credits/balance", () => new Response("", { status: 403 }))
const p = await plugin({ keep_sign_in: false })
const u = await p.auth.usage(async () => auth)
expect(u.error).toBe("TokenPlan account disabled in the console")
expect(u.signIn).toBe("kept")
expect(u.balance).toBeUndefined()
})
test("a balance read that fails for another reason keeps the reason and no fake zero", async () => {
f = fakeInkStone()
f.route("GET /api/tokenplan/v1/credits/balance", () => new Response("", { status: 503 }))
const p = await plugin()
const u = await p.auth.usage(async () => auth)
expect(u.error).toContain("credit balance")
expect(u.balance).toBeUndefined()
expect(u.signIn).toBe("kept")
})
test("a zero balance is shown as 0 credits, never hidden or treated as a read failure", async () => {
f = fakeInkStone()
serve()
f.route("GET /api/tokenplan/v1/credits/balance", () =>
ok({
available_credits: 0,
active_package_count: 0,
usage_windows: {
"5h": { enabled: true, limit_credits: 10, remaining_credits: 0 },
},
}),
)
f.route("GET /api/tokenplan/v1/credits/packages", () => ok({ total: 0, packages: [] }))
const p = await plugin()
const u = await p.auth.usage(async () => auth)
expect(u.balance).toBe("0 墨点")
expect(u.error).toBeUndefined()
})
test("a phone number missing before free credits is reported by auth.checkin", async () => {
f = fakeInkStone()
serve({ validate: ok({ name: "张三", phone: "" }) })
f.route("POST /api/tokenplan/v1/users/free-grant", () =>
new Response(JSON.stringify({ code: -15900, msg: "PhoneRequired", data: null }), {
status: 200,
headers: { "content-type": "application/json" },
}),
)
const p = await plugin()
const u = await p.auth.usage(async () => auth)
// 插件不再自动 claim,也不会因手机号缺失污染卡片;该状态由宿主的 checkin 处理。
expect(u.error).toBeUndefined()
expect(u.windows.some((w) => w.name === "本月免费额度")).toBe(false)
const r = await p.auth.checkin(async () => auth)
expect(r).toEqual({
outcome: "ineligible",
message: "Bind a phone number in the InkStone console to claim free credits.",
})
})
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined
+2
View File
@@ -72,6 +72,8 @@
"summary": { "en": "SenseTime Raccoon (xiaohuanxiong.com) models, account credits and daily check-in, with browser sign-in or Raccoon desktop's live sign-in.", "zh": "商汤小浣熊(xiaohuanxiong.com)模型、积分余额与每日签到,支持浏览器登录或直接复用小浣熊桌面端登录态。" } }, "summary": { "en": "SenseTime Raccoon (xiaohuanxiong.com) models, account credits and daily check-in, with browser sign-in or Raccoon desktop's live sign-in.", "zh": "商汤小浣熊(xiaohuanxiong.com)模型、积分余额与每日签到,支持浏览器登录或直接复用小浣熊桌面端登录态。" } },
{ "package": "@magpie-community/opencode-sensenova-auth", "name": "SenseNova", "icon": "sensenova-color", "providers": ["sensenova-token-plan"], "community": true, { "package": "@magpie-community/opencode-sensenova-auth", "name": "SenseNova", "icon": "sensenova-color", "providers": ["sensenova-token-plan"], "community": true,
"summary": { "en": "SenseNova (SenseTime 日日新) Token Plan: a browser sign-in (or the console account and password) reads the credit pools, their 5-hour and 7-day windows and the expiring grants, and serves the plan's own models — the browser sign-in reuses or creates a Token Plan API key for you.", "zh": "商汤日日新 Token Plan:浏览器登录(或控制台账号密码)读取积分池、5 小时 / 7 天窗口与将过期的返赠余额,并直接调用计划内模型——浏览器登录会自动复用或创建 Token Plan API Key。" } }, "summary": { "en": "SenseNova (SenseTime 日日新) Token Plan: a browser sign-in (or the console account and password) reads the credit pools, their 5-hour and 7-day windows and the expiring grants, and serves the plan's own models — the browser sign-in reuses or creates a Token Plan API key for you.", "zh": "商汤日日新 Token Plan:浏览器登录(或控制台账号密码)读取积分池、5 小时 / 7 天窗口与将过期的返赠余额,并直接调用计划内模型——浏览器登录会自动复用或创建 Token Plan API Key。" } },
{ "package": "@magpie-community/opencode-inkstone-auth", "name": "书生·端砚", "icon": "https://raw.githubusercontent.com/magpie-community/plugins/main/packages/inkstone/icon.svg", "providers": ["intern-inkstone"], "community": true,
"summary": { "en": "Unofficial: Intern InkStone(书生·端砚) Token Plan: a browser sign-in reads the ink-credit balance, the 5-hour and 7-day windows and the credit packs, and creates an ink-* API key (or reuses a pasted one) to serve the plan's models for chat.", "zh": "非官方:书生·端砚(Intern InkStone)墨点计划:浏览器登录读取墨点余额、5 小时 / 7 天窗口与墨点包,并创建 ink-* API Key(或复用现有 Key)直接调用计划内模型对话。" } },
{ "package": "@magpie-community/opencode-autoclaw-auth", "name": "AutoClaw", "providers": ["autoclaw", "autoclaw-cn"], "community": true, { "package": "@magpie-community/opencode-autoclaw-auth", "name": "AutoClaw", "providers": ["autoclaw", "autoclaw-cn"], "community": true,
"summary": { "en": "AutoClaw (Zhipu OpenClaw) cloud accounts: oversea web sign-in (Google/z.ai) or CN phone SMS, credit balance and daily check-in.", "zh": "AutoClaw(智谱澳龙/OpenClaw)云端账号:国际版网页登录(Google/z.ai)或国内手机验证码,积分余额与每日签到。" } }, "summary": { "en": "AutoClaw (Zhipu OpenClaw) cloud accounts: oversea web sign-in (Google/z.ai) or CN phone SMS, credit balance and daily check-in.", "zh": "AutoClaw(智谱澳龙/OpenClaw)云端账号:国际版网页登录(Google/z.ai)或国内手机验证码,积分余额与每日签到。" } },
{ "package": "@magpie-community/opencode-codearts-auth", "name": "CodeArts / OfficeAce", "providers": ["codearts", "officeace"], "community": true, { "package": "@magpie-community/opencode-codearts-auth", "name": "CodeArts / OfficeAce", "providers": ["codearts", "officeace"], "community": true,
+4 -1
View File
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
if (p.type === "select" && Array.isArray(p.options)) if (p.type === "select" && Array.isArray(p.options))
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
// a prompt shown only when another answer says so can't be required // a prompt shown only when another answer says so can't be required
if (!p.condition) f.required = true // a prompt shown only when another answer says so can't be required, and
// neither can one whose own validate() accepts an empty answer (the
// browser sign-in's optional API key)
if (!p.condition && p.required !== false) f.required = true
out.push(f) out.push(f)
} }
return out.length ? out : undefined return out.length ? out : undefined