sensenova 0.1.0: SenseNova Token Plan provider plugin (#577, yihheng)

A new provider plugin, @magpie-community/opencode-sensenova-auth 0.1.0, for the SenseNova (SenseTime 日日新) Token Plan, provider id `sensenova-token-plan`.

- Sign-in: a console sign-in (OIDC + PKCE). The password is sealed to JWE under the platform's JWKS key and is not stored.
- Quota: the account's credit pools (5h/7d windows, expiring grants) from pool-usage.
- Chat: with an optional pasted API key, it serves the plan's chat models at token.sensenova.cn/v1. The list is filtered per account to models the plan covers.
- Also adds a registry.json entry and a root README row.

Hosts:
- platform.sensenova.cn gets the access JWT.
- iam.sensecoreapi.cn gets the sealed password.
- signin.sensecore.cn gets the refresh token and the code.
- token.sensenova.cn gets the API key.

There are no dependencies and no install scripts.

Run at head 3804ab46ae6c6c16d393e5dc08d6ae81c63da668 on mote (macOS 27.2, Bun 1.4.2), with a fresh HOME:
- `bun test packages/sensenova`: 43 pass, 0 fail.
- `bun scripts/check.mjs sensenova` passed.
- Full `bun test`: 4455 pass, 9 skip, 0 fail.
- Broken by hand: I removed each of the two `redirect: "manual"` lines that the last review found untested (IAM login, code exchange). Each time, its new 307 test went red (42/1). The earlier reviews' reverts went red at 0aa00b5 and 10984cf.

Not tried: a real sign-in, quota read or chat. There is no SenseNova account. Unauthenticated probes of the real hosts (in the last review) match the walk's shape.

This is the first version, not on npm yet, so the dist branch serves it until it is published.
This commit is contained in:
yihheng
2026-11-02 03:45:35 +08:00
committed by GitHub
parent cc7f4327e5
commit 04f3608d49
14 changed files with 2200 additions and 0 deletions
+1
View File
@@ -36,6 +36,7 @@ subscription and makes its requests. The packages work in OpenCode and in
| [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` |
| [raccoon](packages/raccoon) | SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com): account credits and daily check-in, with browser sign-in or Raccoon desktop's sign-in | `raccoon` |
| [river](packages/river) | River (river.ai) pay-as-you-go inference, with your API key: per-account models, documented reasoning efforts and live prices | `river` |
| [sensenova](packages/sensenova) | SenseNova (商汤日日新) Token Plan: one console sign-in gives the credit pools, windows and grants, and (with an optional API key) the plan's models for chat | `sensenova-token-plan` |
| [trae](packages/trae) | Trae CN (trae.cn) and Trae international (trae.ai), free tier included, with Trae's browser sign-in (experimental) | `trae-cn`, `trae-global` |
| [workbuddy](packages/workbuddy) | WorkBuddy (China build, CodeBuddy plan) | `workbuddy` |
| [workbuddy](packages/workbuddy) | WorkBuddy (international build) | `workbuddy-ai` |
+101
View File
@@ -0,0 +1,101 @@
# SenseNova (SenseTime 日日新) Token Plan
SenseNova(商汤日日新)**Token Plan** 的积分额度与模型,接进 OpenCode 和
[magpie](https://usemagpie.ai):一次登录同时拿到**额度**(积分池、5 小时 /
7 天窗口、返赠余额与到期)和**模型**(控制台计划内的模型,OpenAI 兼容推理)。
## 一次登录,额度与模型都在
控制台账号(`platform.sensenova.cn`,账号密码)登录时,可同时填入一个
API Key(`sk-…`,可选)。控制台 JWT 读额度,API Key 转发对话——一个账号,
两套凭证,和 workbuddy 式的接入体验一致。
| 凭证 | 来源 | 给什么 |
|---|---|---|
| **控制台 JWT** | OIDC 授权码流(PKCE + IAM) | **额度**:积分池、5h / 7d 窗口、返赠余额与到期 |
| **API Key**(`sk-…`) | 控制台「API Keys」页 | **模型**:计划内的模型清单,OpenAI 兼容推理 |
API Key 是可选的:不填,账号仍显示额度,只是不服务模型。填了,同一个账号
既显示额度、又服务对话。
## 额度
读 `GET /lite/console/v1/tokenplan/pool-usage`,把每个积分池的
`window_5h` / `window_7d` 显示成额度窗口,把 `grant_balance` 显示成会过期
的返赠余额。每个池的窗口标注它覆盖的模型(`models` 字段),让 magpie 按模型
分组渲染——通用积分池与 Flash-Lite 积分池各自独立显示,不挤进同一个 tooltip。
## 模型
API Key 读 `GET /v1/models`(免费、只读、不计费),目录里的 `context_length`
与 `max_output_length` 就是模型声明的窗口与输出上限。请求走
`https://token.sensenova.cn/v1`(OpenAI 兼容)。
模型列表按**计划覆盖**过滤:只列出控制台积分池 `model_ids` 内、且可对话
(非画图)的模型。计划外的模型(如 `deepseek-v4.1-flash`)不列出,避免选到
后 403。会推理的模型给出三档 reasoning effort(`none` / `low` / `high`),
magpie 出思考强度选择器;「会不会推理」取自目录自己的 `supported_features`。
## 数据来源与可核查性
商汤没有公开列出这些内容的文档页(`platform.sensenova.cn/docs` 由 JS 渲染,
`sensenova.cn/token-plan` 只点名了两个模型)。所以本插件的口径来自**一个免费
Token Plan 账号的实测**,并且把抓到的字面响应放进了仓库:
- `testdata/models.json` —— 一次真实 `GET /v1/models` 回复(7 个模型)
- `testdata/pool-usage.json` —— 一次真实 `pool-usage` 回复(两个积分池)
两份都只替换了账号自己的 pool id,其余按原样保留(包括额度数字是**字符串**
这件事)。`testdata.test.mjs` 拿这两份的**值**跑解析与过滤——它证明的是解析器
吃得下这些值;字节来自哪,是对我自己账号抓包的陈述,测试本身无法自证来源。
一个实测结论值得注意:目录里 7 个模型**全都**标着 `businesses:
["tokenplan","metered"]`,但计划的积分池只覆盖其中 6 个,而第 7 个
(`deepseek-v4.1-flash`)调用会被平台拒为 403。**目录自己区分不出来**,所以
必须用该账号的池去过滤——这也是每次列模型都重新读一次池、不缓存全局的原因。
还有一条边界要说清:测试用的 fake(`fake.mjs`)是按公开的 magpie host 契约和
抓到的响应形状写的,但它是我的模型,不是商汤的服务本身。真实登录链路在这一头
仍未跑过,这是本包目前唯一没有实测覆盖的部分。
reasoning effort 档位给的是**一套刻意收窄的通用值**(`none` / `low` / `high`),
对所有模型一视同仁。要说清楚的是:这**不是**「已核实这三个档位每个模型都支持」——
平台没有公开列出档位,某模型真实接受哪些只有从账号内部逐个请求才知道。这里刻意不
去声称那种查不动的事,是因为猜错的代价不对称:少给一档只是少一个选项,多给一档则会
在任务中途冒出一个莫名其妙的 400。猜错时平台直接报错,不会静默出错。
真正可核验的是「这个模型会不会推理」:目录回复里的 `supported_features` 直接写了,
`testdata/models.json` 就是证据。所以唯一的开关取自它,而不是取自一张手写的表。
## 安装
```sh
magpie plugin add @magpie-community/opencode-sensenova-auth
magpie plugin login sensenova-token-plan
```
登录时填控制台账号、密码,以及(可选)API Key。
## 登录的实现
控制台登录走它自己的 OIDC 授权码流(PKCE + IAM):密码用平台 JWKS 公钥
封成 JWE(RSA-OAEP + A256GCM),明文不上网、不落盘。控制台 JWT 只有约
180 分钟,拿到 `refresh_token` 后自动续期(Hydra 会轮换 refresh token,
每次续期后的新值都会被保存),不需要再输密码。API Key 不参与轮换,续期时
保留在账号上。
## provider id
`sensenova-token-plan`。**不是** `sensenova`:那个 id 留给用户自己的 custom
provider(sk- key,`token.sensenova.cn`),本插件不与之冲突。
## 边界
- 面板显示的是**商汤控制台自己的口径**,与网页控制台一致。
- 免费公测的 key 有 TPM/RPM 限额与 5h / 7d 窗口额度,限流时商汤回 429 或
`token plan entitlement exhausted`。
- 平台若变更接口或加密参数,插件可能失效。
## 许可证
MIT
+219
View File
@@ -0,0 +1,219 @@
// The API key side: the catalogue it reads, the models magpie lists for the
// account (its own plan's coverage ∩ what the key serves ∩ what answers a chat
// request), the reasoning effort levels each declares, and the chat loader.
// Everything runs against the local fake.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { SenseNovaAuthPlugin, _internal } from "./index.mjs"
import { fakeSenseNova, json } from "./fake.mjs"
let f
afterEach(() => f?.close())
// the account one sign-in leaves behind: the console JWT for the pools, the
// API key (kept beside it) for the models and chat
const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "yiheng13", apiKey: "sk-test" }
// the catalogue the key is served: two models the plan covers and chat
// answers, one the plan doesn't cover (the vendor 403s it), one that draws
// (a chat endpoint 404s it)
const CATALOGUE = {
data: [
{ id: "glm-5.2", name: "glm-5.2", context_length: 1048576, max_output_length: 131072, input_modalities: ["text"], output_modalities: ["text"], supported_features: ["tools", "json_mode", "reasoning"] },
{ id: "sensenova-6.8-flash-lite", name: "sensenova-6.8-flash-lite", context_length: 262144, max_output_length: 65536, input_modalities: ["text", "image"], output_modalities: ["text"], supported_features: ["tools", "json_mode", "reasoning"] },
{ id: "deepseek-v4.1-flash", name: "deepseek-v4.1-flash", context_length: 1048576, max_output_length: 65536, input_modalities: ["text"], output_modalities: ["text"], supported_features: ["reasoning"] },
{ id: "sensenova-u1.5-lite", name: "sensenova-u1.5-lite", context_length: 262144, max_output_length: 65536, input_modalities: ["text"], output_modalities: ["image"], supported_features: ["tools"] },
],
}
// the plan this account's pools cover
const PLAN = (ids) => ({ plan: { name: "Free Plan" }, pools: [{ name: "通用积分池", pool_type: "default", model_ids: ids }] })
// routes for a listing: the pools the console shows and the catalogue the key
// is served. Both are counted so a test can say what was asked for.
function serve(list = CATALOGUE, planIds = ["glm-5.2", "sensenova-6.8-flash-lite", "sensenova-u1.5-lite"]) {
f.route("GET /models", (r) => {
expect(r.headers.get("authorization")).toBe("Bearer sk-test")
return json(list)
})
f.route("GET /lite/console/v1/tokenplan/pool-usage", (r) => {
expect(r.headers.get("authorization")).toBe("Bearer tok")
return json(PLAN(planIds))
})
}
async function plugin() {
return SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
}
// the host's own default for a lead it isn't told (host.js RENEW_LEAD)
const HOST_DEFAULT_LEAD = 5 * 60 * 1000
test("a cold listing gives the plan's models, not the raw catalogue", async () => {
// no usage() read first: this is a fresh host process, or the first listing
// after a sign-in. What the plan covers is read here, from this account.
f = fakeSenseNova()
serve()
const p = await plugin()
const models = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth })
// deepseek-v4.1-flash is in the catalogue but not the plan (403 from the
// vendor); sensenova-u1.5-lite is in the plan but draws (404 at chat)
expect(Object.keys(models).sort()).toEqual(["glm-5.2", "sensenova-6.8-flash-lite"])
})
test("the listing carries each model's limits, input kinds and effort tiers", async () => {
f = fakeSenseNova()
serve()
const p = await plugin()
const models = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth })
expect(models["glm-5.2"].limit).toEqual({ context: 1048576, output: 131072 })
// the tiers are the same for every model: the platform publishes no per-model
// list, so nothing narrower than "these are offered" is claimed
expect(Object.keys(models["glm-5.2"].variants)).toEqual(["none", "low", "high"])
expect(Object.keys(models["sensenova-6.8-flash-lite"].variants)).toEqual(["none", "low", "high"])
// what is claimed is checkable from the reply itself: whether it takes images
expect(models["sensenova-6.8-flash-lite"].capabilities.input.image).toBe(true)
expect(models["glm-5.2"].capabilities.input.image).toBe(false)
})
test("a model the catalogue says doesn't reason gets no effort tiers", () => {
// the gate is the catalogue's own supported_features, not a hand-kept table:
// a model that stops reasoning stops offering tiers, with nothing to update
const flat = _internal.modelOf({ id: "x", name: "x", context: 1000, output: 100, reasoning: false })
expect(flat.reasoning).toBe(false)
expect(flat.variants).toBeUndefined()
const deep = _internal.modelOf({ id: "y", name: "y", context: 1000, output: 100, reasoning: true })
expect(Object.keys(deep.variants)).toEqual(["none", "low", "high"])
})
test("two accounts on different plans list different models", async () => {
// nothing about the plan is kept between calls: a module global would let
// the first account's plan filter the second's list
f = fakeSenseNova()
const p = await plugin()
const wide = { ...auth, access: "tok-wide", apiKey: "sk-wide" }
const narrow = { ...auth, access: "tok-narrow", apiKey: "sk-narrow" }
f.route("GET /models", (r) => {
const want = r.headers.get("authorization") === "Bearer sk-wide" ? CATALOGUE : { data: CATALOGUE.data.slice(0, 1) }
return json(want)
})
f.route("GET /lite/console/v1/tokenplan/pool-usage", (r) => {
const ids = r.headers.get("authorization") === "Bearer tok-wide"
? ["glm-5.2", "sensenova-6.8-flash-lite"]
: ["glm-5.2"]
return json(PLAN(ids))
})
const a = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth: wide })
const b = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth: narrow })
expect(Object.keys(a).sort()).toEqual(["glm-5.2", "sensenova-6.8-flash-lite"])
expect(Object.keys(b)).toEqual(["glm-5.2"])
})
test("a plan read that fails keeps the bootstrap list rather than the catalogue", async () => {
// the vendor refusing the pools says nothing about what the key can call,
// so the raw catalogue (which holds a model that 403s) must not be listed
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json({ error: "no" }, 500))
f.route("GET /models", () => json(CATALOGUE))
const p = await plugin()
const given = { "glm-5.2": {} }
expect(await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })).toEqual(given)
})
test("a key the platform has refused lists nothing, not the bootstrap set", async () => {
// a refused key calls nothing, whatever the plan covers: falling back to the
// bootstrap list here would advertise five models that every request to them
// would fail on
f = fakeSenseNova()
serve()
f.route("GET /models", () => json({ error: "unauthorized" }, 401))
const p = await plugin()
const given = { "glm-5.2": {} }
expect(await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })).toEqual({})
})
test("a 200 that carries no pools is a failed read, so the bootstrap list stands", async () => {
// an empty plan and a reply that isn't the console's shape must not be read
// the same way: the first means the account can call nothing, the second
// means we don't know, and only the second falls back
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json({ plan: { name: "Free Plan" } }))
f.route("GET /models", () => json(CATALOGUE))
const p = await plugin()
const given = { "glm-5.2": {} }
expect(await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })).toEqual(given)
})
test("an account with no API key advertises no models and serves no chat", async () => {
// the five models in the provider's config belong to an account that has a
// key; without one, listing them would offer models whose requests go out
// with no auth at all
f = fakeSenseNova()
const p = await plugin()
const noKey = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "yiheng13" }
expect(await p.provider.models({ id: "sensenova-token-plan", models: { "glm-5.2": {} } }, { auth: noKey })).toEqual({})
expect(await p.auth.loader(async () => noKey)).toEqual({})
})
test("the loader serves the models with the key, at the platform's base URL", async () => {
f = fakeSenseNova()
const p = await plugin()
const loader = await p.auth.loader(async () => auth)
// magpie sends "Authorization: Bearer <apiKey>" for @ai-sdk/openai-compatible
// itself (host.js sdkHeaders), so the loader only says where and with what
expect(loader.apiKey).toBe("sk-test")
expect(loader.baseURL).toBe(f.origin)
expect(loader.fetch).toBeUndefined()
})
test("the renewal lead is where the host reads it", async () => {
// host.js takes the lead from auth (leadOf(a), a = auth), not from the
// hooks object: on the wrong side of auth it is silently the host's default
const p = await plugin()
expect(p.refreshLead).toBeUndefined()
expect(p.auth.refreshLead).toBe(_internal.EARLY_MS)
expect(p.auth.refreshLead).toBeGreaterThan(HOST_DEFAULT_LEAD)
})
test("the sign-in asks for the account, its password and an optional key", async () => {
const p = await plugin()
const m = p.auth.methods[0]
expect(m.prompts.map((x) => x.key)).toEqual(["username", "password", "apiKey"])
// the key is optional: an empty one passes, a non-sk- one doesn't
expect(m.prompts[2].validate("")).toBeUndefined()
expect(m.prompts[2].validate("sk-abc")).toBeUndefined()
expect(m.prompts[2].validate("nope")).toContain("sk-")
// the sign-in runs in the background: a url would open the console for nothing
expect(m.authorize({ username: "u", password: "p", apiKey: "" }).url).toBe("")
})
test("a plan that names no models lists none, rather than the bootstrap set", async () => {
// an empty plan is an answer, not a failed read: falling back to the
// bootstrap list would offer models the vendor then refuses. The pools must
// be read for this to mean anything — a test that returns {} before reading
// them would pass whatever this branch does.
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json({ plan: { name: "Free Plan" }, pools: [] }))
f.route("GET /models", () => json(CATALOGUE))
const p = await plugin()
const given = { "glm-5.2": {} }
const models = await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })
expect(models).toEqual({})
// it got as far as the plan, and stopped there: the catalogue was never asked
expect(f.seen.some((r) => r.path.includes("pool-usage"))).toBe(true)
expect(f.seen.some((r) => r.path === "/models")).toBe(false)
})
test("a plan and a catalogue that share no model list none", async () => {
// both reads succeeded and agree there is nothing to offer: that is an
// answer too, and the bootstrap set must not reappear to cover it up
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json(PLAN(["some-model-the-key-isnt-served"])))
f.route("GET /models", () => json(CATALOGUE))
const p = await plugin()
const given = { "glm-5.2": {} }
expect(await p.provider.models({ id: "sensenova-token-plan", models: given }, { auth })).toEqual({})
// both were really consulted this time
expect(f.seen.some((r) => r.path.includes("pool-usage"))).toBe(true)
expect(f.seen.some((r) => r.path === "/models")).toBe(true)
})
+63
View File
@@ -0,0 +1,63 @@
// A fake of SenseNova's hosts for the tests: one local server standing in
// for the console, the IAM login and the token endpoint, which the plugin's
// ENDPOINTS are pointed at. route(method, path) answers a request; seen
// lists what came.
import { generateKeyPairSync } from "node:crypto"
import { _internal } from "./index.mjs"
export function fakeSenseNova() {
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 }
// the plugin appends its own paths to these: the token endpoint's
// "/oauth2/token", the IAM login's "/iam/authn/...", the JWKS document's
// "/.well-known/jwks.json"
Object.assign(_internal.ENDPOINTS, {
console: origin,
iam: origin,
token: origin + "/oauth2/token",
jwks: origin + "/.well-known/jwks.json",
api: origin,
})
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 JWT as the console's tokens are, with the claims given
export const jwtOf = (claims) => ["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "sig"].join(".")
// a JWKS as the platform publishes it: the RSA key the password is sealed to
export const jwksOf = (kid = "public:hydra.openid.id-token") => ({
keys: [{ kid, kty: "RSA", alg: "RSA-OAEP", use: "enc", n: jwkN, e: "AQAB" }],
})
// a 2048-bit RSA modulus, base64url, as a JWKS gives it
const jwkN = (() => {
const jwk = generateKeyPairSync("rsa", { modulusLength: 2048 }).publicKey.export({ format: "jwk" })
return jwk.n
})()
+785
View File
@@ -0,0 +1,785 @@
// OpenCode provider plugin for SenseNova (SenseTime 日日新) Token Plan:
// a SenseNova console account's credit pools, windows and grants, on the
// account's own models.
//
// One sign-in gives both, like workbuddy's: the console account (with its
// password, sealed into a JWE so it never travels in plaintext) holds the
// quota — the pools, their 5-hour and weekly windows, the grants that
// expire — and an API key (sk-…) pasted with it is what the models are
// spoken to with. The console JWT is what reads the pools; the key is what
// serves chat. The two are one account in magpie.
//
// The console JWT lives ~180 minutes, so a refresh token that renews itself
// (Hydra rotates it — every refresh's new refresh token is saved) is the
// whole point of the sign-in.
//
// The provider id is "sensenova-token-plan", NOT "sensenova": that one is
// the user's own custom provider (an sk- key at token.sensenova.cn), and a
// plugin claiming it would take over the models it already serves.
// ---- the platform's endpoints, as the console's own traffic uses them
// They live in ENDPOINTS so a test can point them at a local fake; the
// plugin itself never changes them.
const ENDPOINTS = {
console: "https://platform.sensenova.cn",
iam: "https://iam.sensecoreapi.cn",
token: "https://signin.sensecore.cn/oauth2/token",
jwks: "https://signin.sensecore.cn/.well-known/jwks.json",
api: "https://token.sensenova.cn/v1",
}
const CONSOLE = () => ENDPOINTS.console
const IAM_ORIGIN = () => ENDPOINTS.iam
const TOKEN_ENDPOINT = () => ENDPOINTS.token
const JWKS_ENDPOINT = () => ENDPOINTS.jwks
const API_BASE = () => ENDPOINTS.api
const CLIENT_ID = "nova"
const SCOPE = "openid offline offline_access"
const ENC_KEY_ID = "public:hydra.openid.id-token"
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
const MAX_HOPS = 8
const EARLY_MS = 10 * 60 * 1000 // renew this close to a token's end (auth.refresh lead)
const poolUsageUrl = () => CONSOLE() + "/lite/console/v1/tokenplan/pool-usage"
const NPM = "@ai-sdk/openai-compatible"
// ---- small helpers
const str = (o, k) => (typeof o?.[k] === "string" && o[k].trim() ? o[k].trim() : undefined)
const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined)
const num = (v) => {
if (typeof v === "number" && Number.isFinite(v)) return v
if (typeof v === "string" && v.trim() && Number.isFinite(Number(v))) return Number(v)
return undefined
}
const b64url = (bytes) => Buffer.from(bytes).toString("base64url")
// ---- the crypto: JWE password sealing, PKCE, JWT expiry
// Seal the password into the 5-segment compact JWE the IAM endpoint wants:
// RSA-OAEP (OAEP over SHA-1 — the SHA-256 variants are refused) + A256GCM.
// The protected header's base64url SEGMENT is the AAD (RFC 7516 §5.1), and
// WebCrypto's ciphertext||tag buffer is split into the last two segments.
async function sealPassword(password) {
const jwksRes = await fetch(JWKS_ENDPOINT(), { headers: { accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS) })
if (!jwksRes.ok) throw new Error(`JWKS endpoint: HTTP ${jwksRes.status}`)
const keys = (await jwksRes.json())?.keys ?? []
const key = keys.find((k) => k.kid === ENC_KEY_ID)
if (!key) throw new Error(`JWKS has no key ${ENC_KEY_ID}`)
const rsaKey = await crypto.subtle.importKey(
"jwk",
{ kty: "RSA", n: key.n, e: key.e, alg: "RSA-OAEP", ext: true },
{ name: "RSA-OAEP", hash: "SHA-1" },
false,
["encrypt"],
)
const contentKey = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt"])
const rawKey = new Uint8Array(await crypto.subtle.exportKey("raw", contentKey))
const iv = crypto.getRandomValues(new Uint8Array(12))
const protectedHeader = b64url(new TextEncoder().encode(JSON.stringify({ alg: "RSA-OAEP", enc: "A256GCM" })))
const sealed = new Uint8Array(
await crypto.subtle.encrypt(
{ name: "AES-GCM", iv, additionalData: new TextEncoder().encode(protectedHeader), tagLength: 128 },
contentKey,
new TextEncoder().encode(password),
),
)
const ciphertext = sealed.subarray(0, sealed.length - 16)
const tag = sealed.subarray(sealed.length - 16)
const encryptedKey = await crypto.subtle.encrypt({ name: "RSA-OAEP" }, rsaKey, rawKey)
return [protectedHeader, b64url(encryptedKey), b64url(iv), b64url(ciphertext), b64url(tag)].join(".")
}
const pkce = async () => {
const verifier = b64url(crypto.getRandomValues(new Uint8Array(48)))
const challenge = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))))
return { verifier, challenge }
}
// ---- the redirect walk (cookies kept per host; fetch can't do this itself)
// The domains the walk may visit. It carries Hydra session and CSRF cookies,
// so a hop found in a page body to some other domain must not be taken. The
// hosts the endpoints are set to are allowed too, which is how a test running
// the whole flow against a local fake gets through.
const SENSENOVA_HOSTS = [/(^|\.)sensenova\.cn$/, /(^|\.)sensecore\.cn$/, /(^|\.)sensecoreapi\.cn$/]
function allowedHost(url) {
let u
try {
u = new URL(url)
} catch {
return false
}
// a test points ENDPOINTS at a local fake (http on loopback). The match is
// per origin, protocol included: matching the host alone would let an
// http:// downgrade of a production https endpoint through this line, before
// the check below ever got to see it — and the jar keys off .host too, so
// the session cookie would go with it in the clear
const sameOrigin = (e) => {
try {
const x = new URL(e)
return x.host === u.host && x.protocol === u.protocol
} catch {
return false
}
}
if (Object.values(ENDPOINTS).some(sameOrigin)) return true
// the platform itself is https only: an http://sensenova.cn is not the
// platform but a downgrade or a spoof of it
if (u.protocol !== "https:") return false
return SENSENOVA_HOSTS.some((re) => re.test(u.hostname))
}
// cookies keyed by host: one that set a cookie is the only one it goes back to
function newJar() {
return new Map()
}
const hostOf = (url) => {
try {
return new URL(url).host
} catch {
return ""
}
}
function cookieHeader(jar, url) {
const own = jar.get(hostOf(url))
return own && own.size ? [...own.entries()].map(([n, v]) => `${n}=${v}`).join("; ") : ""
}
function collectCookies(response, jar, url) {
const host = hostOf(url)
if (!host) return
const raw = typeof response.headers.getSetCookie === "function" ? response.headers.getSetCookie() : []
let own = jar.get(host)
if (!own) jar.set(host, (own = new Map()))
for (const line of raw) {
const [pair = ""] = line.split(";")
const i = pair.indexOf("=")
if (i > 0) own.set(pair.slice(0, i).trim(), pair.slice(i + 1).trim())
}
}
async function httpGet(url, jar) {
if (!allowedHost(url)) throw new Error(`refusing to visit ${url}: outside the SenseNova hosts`)
const headers = { "user-agent": UA, accept: "*/*" }
const cookie = cookieHeader(jar, url)
if (cookie) headers.cookie = cookie
return fetch(url, { redirect: "manual", headers, signal: AbortSignal.timeout(TIMEOUT_MS) })
}
// Some transitions are rendered client-side: scan a 200 body for the next hop.
// Only a hop to an allowed host is taken, so a page that points elsewhere
// can't pull the walk (and the cookies it holds) off-site.
function nextFromBody(body, wanted) {
if (!body) return ""
const found = []
for (const m of body.matchAll(/https?:\/\/[^"'\s<>]+[?&][^"'\s<>]*/g)) found.push(m[0])
const meta = /<meta[^>]+http-equiv=["']refresh["'][^>]+url=["']([^"']+)/i.exec(body)
if (meta) found.push(meta[1])
for (const p of [
/window\.location\.replace\(["']([^"']+)["']/,
/window\.location\.href\s*=\s*["']([^"']+)["']/,
/location\.href\s*=\s*["']([^"']+)["']/,
]) {
const f = p.exec(body)
if (f) found.push(f[1])
}
for (const u of found) if (allowedHost(u) && wanted.test(u)) return u
return ""
}
async function followUntil(start, wanted, jar) {
let location = start
for (let hop = 0; hop < MAX_HOPS && location; hop++) {
// the host is checked before what the hop carries: a URL holding the very
// parameter we're looking for, on a domain we have no business visiting, is
// not the answer — taking it would walk off-site with the Hydra session
// and CSRF cookies the jar holds
if (!allowedHost(location)) throw new Error(`the sign-in walk left the SenseNova hosts for ${location}`)
if (wanted.test(location)) return location
const res = await httpGet(location, jar)
collectCookies(res, jar, location)
const next = res.headers.get("location") ?? ""
location = next !== "" ? next : nextFromBody(await res.text(), wanted)
}
// the last hop's target is a hop too, so it is checked like any other: a
// walk that used up its budget must not hand back an off-site URL merely
// because it looks like the thing it was looking for
if (location && wanted.test(location)) {
if (!allowedHost(location)) throw new Error(`the sign-in walk left the SenseNova hosts for ${location}`)
return location
}
return ""
}
const paramOf = (url, name) => {
try {
return new URL(url).searchParams.get(name) ?? ""
} catch {
return ""
}
}
// ---- the login flow and the refresh
async function refreshToken(refresh) {
const res = await fetch(TOKEN_ENDPOINT(), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": UA, accept: "application/json" },
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refresh,
client_id: CLIENT_ID,
scope: SCOPE,
}).toString(),
// a 307 or 308 replays this POST, body included, to wherever the reply
// points — a refresh token must never leave with a redirect, so one is an
// error here rather than a step to follow
redirect: "manual",
signal: AbortSignal.timeout(TIMEOUT_MS),
})
const body = await res.json().catch(() => ({}))
if (!res.ok || !body.access_token) {
// only invalid_grant means the refresh token itself is dead; any other
// 400 says nothing about it and must not purge a healthy pair
const dead = res.status === 400 && body.error === "invalid_grant"
throw Object.assign(
new Error(`refresh rejected (HTTP ${res.status}): ${body.error_description ?? body.error ?? ""}`),
// the host only marks an account signed-out on an error that says so
// (host.js: e?.signIn === "expired"); without it a dead token is
// retried every RENEW_RETRY (30 s) and never shown as needing a sign-in
{ dead, ...(dead ? { signIn: "expired" } : {}) },
)
}
return {
access: body.access_token,
refresh: body.refresh_token ?? refresh,
expires: Date.now() + (Number(body.expires_in) || 10800) * 1000,
}
}
async function passwordLogin(username, password) {
const user = String(username ?? "").trim()
const secret = String(password ?? "")
if (!user || !secret.trim()) throw new Error("username and password are required")
const jar = newJar()
const { verifier, challenge } = await pkce()
const nonce = b64url(crypto.getRandomValues(new Uint8Array(16)))
// step 1 — start the OIDC walk on the console origin (the CSRF cookie is
// bound to this host; starting anywhere else kills the flow)
const authUrl =
CONSOLE() +
"/oauth2/auth?" +
new URLSearchParams({
client_id: CLIENT_ID,
code_challenge: challenge,
code_challenge_method: "S256",
redirect_uri: CONSOLE(),
response_type: "code",
scope: SCOPE,
state: nonce,
}).toString()
const first = await httpGet(authUrl, jar)
collectCookies(first, jar, authUrl)
const challengeUrl = await followUntil(first.headers.get("location") ?? authUrl, /[?&]login_challenge=/, jar)
const loginChallenge = paramOf(challengeUrl, "login_challenge")
if (!loginChallenge) throw new Error("could not obtain a login challenge from the authorization endpoint")
// step 2 — seal the password and sign in at IAM
const encrypted = await sealPassword(secret)
const iamUrl = `${IAM_ORIGIN()}/iam/authn/v1/auth/nova/login`
const iamRes = await fetch(iamUrl, {
method: "POST",
headers: {
"content-type": "application/json",
"user-agent": UA,
accept: "application/json",
origin: CONSOLE(),
referer: CONSOLE() + "/",
cookie: cookieHeader(jar, iamUrl),
},
body: JSON.stringify({ username: user, password: encrypted, challenge: loginChallenge, is_encrypt: true }),
redirect: "manual", // the sealed password must not be replayed off-origin
signal: AbortSignal.timeout(TIMEOUT_MS),
})
const iamBody = await iamRes.json().catch(() => ({}))
const redirect = iamBody?.redirect ?? ""
if (!iamRes.ok || !redirect) {
// the real reason lives in details[].reason, not the top-level message
const reason =
iamBody?.details?.find?.((d) => d?.reason)?.reason ?? iamBody?.message ?? `HTTP ${iamRes.status}`
throw Object.assign(new Error(`login refused: ${reason}`), {
// time-based refusals carry a window; credential ones never retry
kind: /locked|disabled|tooMany|rateLimit|tooManyRequests/i.test(String(reason)) ? "retryable" : "credential",
})
}
// step 3 — walk the callback for the code (state must round-trip)
const codeUrl = await followUntil(redirect, /[?&]code=/, jar)
const code = paramOf(codeUrl, "code")
if (!code) throw new Error("callback ended without an authorization code")
if (paramOf(codeUrl, "state") !== nonce) throw new Error("callback state did not match the issued nonce")
// step 4 — exchange code + verifier for the token pair
const tokenRes = await fetch(TOKEN_ENDPOINT(), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": UA, accept: "application/json" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
code_verifier: verifier,
client_id: CLIENT_ID,
redirect_uri: CONSOLE(),
scope: SCOPE,
}).toString(),
redirect: "manual", // nor the authorization code with its PKCE verifier
signal: AbortSignal.timeout(TIMEOUT_MS),
})
const tokenBody = await tokenRes.json().catch(() => ({}))
if (!tokenRes.ok || !tokenBody.access_token)
throw new Error(`token exchange failed: ${tokenBody.error_description ?? tokenBody.error ?? `HTTP ${tokenRes.status}`}`)
return {
access: tokenBody.access_token,
refresh: tokenBody.refresh_token ?? "",
expires: Date.now() + (Number(tokenBody.expires_in) || 10800) * 1000,
}
}
// ---- the model catalogue (an API key's models)
// The reasoning effort levels this plugin offers. The platform publishes no
// list of them, and what a given model actually answers can only be learned by
// asking from inside an account — so this table claims no knowledge of any
// model's real tiers. The three are a deliberately narrow common set (`none`
// being thinking off), and being wrong here is loud rather than silent: a
// level the vendor doesn't take answers 400 and magpie shows that, where a
// guessed-at tier would only show up as a confusing failure mid-task. What
// *is* checkable is whether a model reasons at all — the catalogue's own
// `supported_features` says so, and testdata/models.json holds a real reply —
// so that is the only gate here.
const EFFORTS = ["none", "low", "high"]
// the models the plan ships, as magpie's provider starts with: the same ids
// the catalogue serves, with the limits the platform declared when this was
// written and the reasoning levels each takes. The API key's account
// refreshes them with the live catalogue (provider.models below); the
// plan's pools filter that list to what the key can call.
const BOOT_MODELS = {
"glm-5.2": { name: "glm-5.2", context: 1048576, output: 131072 },
"deepseek-v4-flash": { name: "deepseek-v4-flash", context: 1048576, output: 65536 },
"deepseek-flash": { name: "deepseek-flash", context: 1048576, output: 65536 },
"sensenova-6.8-flash-lite": { name: "sensenova-6.8-flash-lite", context: 262144, output: 65536 },
"kimi-k3": { name: "kimi-k3", context: 1048576, output: 65536 },
}
// What the plan covers is read from the account's own pools each time its
// models are listed (provider.models below) and never kept in a module
// global: a global would be shared between accounts (two SenseNova accounts
// on different plans would filter each other's lists) and would be cold in a
// fresh host process, where it would list a model the vendor answers 403 to.
// The catalogue the platform serves: free, read-only, and it costs no
// inference allowance. Its own fields are the authority on a model's
// context window and output limit.
async function apiModels(key) {
const res = await fetch(API_BASE() + "/models", {
headers: { authorization: "Bearer " + key, accept: "application/json" },
signal: AbortSignal.timeout(TIMEOUT_MS),
})
if (res.status === 401 || res.status === 403)
throw Object.assign(new Error(`SenseNova refused the API key (HTTP ${res.status})`), { refused: true })
if (!res.ok) throw new Error(`model catalogue: HTTP ${res.status}`)
const body = await res.json().catch(() => ({}))
const data = Array.isArray(body?.data) ? body.data : []
return data.map((m) => ({
id: str(m, "id") ?? "",
name: str(m, "name") ?? str(m, "id") ?? "",
context: num(m?.context_length) ?? 0,
output: num(m?.max_output_length) ?? 0,
// a model that takes images in, and one that draws them out
image: Array.isArray(m?.input_modalities) && m.input_modalities.includes("image"),
draws: Array.isArray(m?.output_modalities) && m.output_modalities.includes("image"),
reasoning: Array.isArray(m?.supported_features) && m.supported_features.includes("reasoning"),
})).filter((m) => m.id)
}
// a model as OpenCode's provider lists it: id, name, limits, what it can do
// and the reasoning effort levels it takes. The API it is spoken on comes
// from the provider's own npm and api (the config hook below), so a model
// says nothing about where it goes.
function modelOf(m, provider) {
const image = m.image === true
const efforts = m.reasoning !== false ? EFFORTS : undefined
return {
id: m.id,
name: m.name || m.id,
limit: { context: m.context ?? 0, output: m.output ?? 0 },
reasoning: m.reasoning !== false,
tool_call: true,
modalities: { input: image ? ["text", "image"] : ["text"], output: ["text"] },
capabilities: {
reasoning: m.reasoning !== false,
toolcall: true,
attachment: image,
input: { text: true, image },
output: { text: true },
},
// the effort levels this model takes, each a variant: the gateway sends
// one as `reasoning_effort`, `none` is thinking off. A model that takes
// none is the family's, listed at its own name; one that does not has
// no variants.
...(efforts && efforts.length ? { variants: Object.fromEntries(efforts.map((e) => [e, { reasoningEffort: e }])) } : {}),
}
}
// ---- the pool usage (the console's data source)
// pools → the card's windows and balance. The console returns its numbers
// as strings: limit/used/remaining per window, reset_at as epoch seconds.
//
// The GUI draws only an account's first two windows as meters and puts the
// rest in the row's tooltip, so each window says which models its pool covers
// — the host keeps that field (`ids(w?.models)`) and the GUI groups windows by
// it, which gives every pool its own meters instead of one pool's meters with
// the rest hidden. The grants — a balance that expires, not a window that gets
// spent — go to `balance`, which the GUI draws as its own chip beside them.
function usageOf(pools) {
const round = (n) => Math.round(n * 100) / 100
const windows = []
let grants = ""
const ordered = [...(Array.isArray(pools) ? pools : [])].sort(
(a, b) => (a?.pool_type === "default" ? -1 : 1) - (b?.pool_type === "default" ? -1 : 1),
)
for (const pool of ordered) {
const poolName = str(pool, "name") ?? "pool"
// the models this pool covers: the GUI groups a window by them, so the
// Flash-Lite pool's windows hang under the flash-lite models instead of
// vanishing into the account's first-two-meters row
const models = (Array.isArray(pool?.model_ids) ? pool.model_ids : []).filter((x) => typeof x === "string" && x)
for (const [key, label, span] of [
["window_5h", "5 hours", 5 * 3600],
["window_7d", "7 days", 7 * 86400],
]) {
const w = obj(pool?.[key])
if (!w) continue
const limit = num(w.limit)
if (limit === undefined || limit <= 0) continue
const used = num(w.used) ?? 0
const resetAt = num(w.reset_at)
windows.push({
name: `${poolName} · ${label}`,
used: Math.max(0, Math.min(100, (100 * used) / limit)),
display: `${round(used)} / ${round(limit)}`,
amount: round(used),
limit: round(limit),
unit: "credits",
span,
...(models.length ? { models } : {}),
...(resetAt && resetAt > 0 ? { resetsAt: new Date(resetAt * 1000).toISOString() } : {}),
})
}
const grant = num(pool?.grant_balance)
if (grant !== undefined && grant > 0) {
const expiry = num(pool?.nearest_grant_expiry)
grants = `${round(grant)} credits granted${expiry && expiry > 0 ? " · expires " + new Date(expiry * 1000).toISOString().slice(0, 10) : ""}`
}
}
return { windows, ...(grants ? { balance: grants } : {}) }
}
async function poolUsage(access) {
if (!access) throw new Error("no console token to read the plan with")
const res = await fetch(poolUsageUrl(), {
headers: { authorization: "Bearer " + access, accept: "application/json", "user-agent": UA },
signal: AbortSignal.timeout(TIMEOUT_MS),
})
if (res.status === 401 || res.status === 403)
throw Object.assign(new Error(`console refused the token (HTTP ${res.status})`), { status: res.status })
if (!res.ok) throw new Error(`pool-usage: HTTP ${res.status}`)
const body = await res.json().catch(() => ({}))
// a 200 that isn't the shape the console sends is a failed read, not an
// empty plan: read the other way it would list no models for an account that
// has a whole plan, and hide that the platform changed under us
if (!body || typeof body !== "object" || !Array.isArray(body.pools))
throw new Error("pool-usage: the reply carries no pools to read")
const plan = obj(body?.plan)
const pools = body.pools
const ids = pools.flatMap((p) => (Array.isArray(p?.model_ids) ? p.model_ids : [])).filter((x) => typeof x === "string" && x)
return {
plan: str(plan, "name") ?? str(plan, "id") ?? "SenseNova",
// the ids this account's plan covers: provider.models lists against these
models: ids,
...usageOf(pools),
}
}
// ---- the plugin
// The provider id magpie files this plugin's card under.
const PROVIDER_ID = "sensenova-token-plan"
function makePlugin() {
return async ({ client }) => {
// magpie saves what refresh gives; used by the login method and renewals.
// The API key is kept beside the access/refresh tokens as `apiKey`, the
// way minimax keeps `realUserID` — not its own account, part of this one.
const save = async (a) => {
if (typeof client?.auth?.set !== "function") return false
try {
await client.auth.set({ path: { id: PROVIDER_ID }, body: a })
return true
} catch {
return false
}
}
// the account's API key, wherever it is stored (the account's `apiKey`)
const apiKeyOf = (auth) => auth?.apiKey
return {
// magpie's provider config: the name, the AI SDK package and the
// endpoint the requests go to, with the models the provider starts
// with (the account's own catalogue replaces them once it answers).
config: async (cfg) => {
cfg.provider ??= {}
// `??=` keeps a provider the user configured in plugins.json
cfg.provider[PROVIDER_ID] ??= {
name: "SenseNova",
npm: NPM, // chat completions
api: API_BASE(),
models: Object.fromEntries(
Object.entries(BOOT_MODELS).map(([id, m]) => [
id,
modelOf({ id, name: m.name, context: m.context, output: m.output, image: false, draws: false, reasoning: true }, undefined),
]),
),
}
},
// magpie's provider hook: the id and the model list. The models come
// from the API key's catalogue; a model outside the plan's pools, or
// one that draws (a chat endpoint answers 404 to it), stays unlisted.
provider: {
id: PROVIDER_ID,
// The account's models: what its own plan covers, ∩ what its key
// serves, ∩ what a chat endpoint answers (a drawing model 404s there).
// Both reads are this account's and both happen here, so a cold host
// lists the same set a warm one does. Either read failing gives the
// bootstrap list back — every id in which the plan does cover — rather
// than a raw catalogue that would carry deepseek-v4.1-flash, which the
// vendor refuses with 403.
async models(provider, { auth }) {
const key = apiKeyOf(auth)
// no key: this account can call nothing, so it advertises nothing
if (!key) return {}
let plan
try {
plan = await poolUsage(auth?.access)
} catch {
return provider.models
}
// An empty plan, and an empty overlap with the catalogue, are both
// answers: this account has nothing to offer. Only a read that
// failed falls back to the bootstrap list — that list is the one set
// known to sit inside a free plan, so falling back is safe where
// guessing an unfiltered catalogue would not be.
const covered = new Set(plan.models)
if (!covered.size) return {}
let list
try {
list = await apiModels(key)
} catch (e) {
// the key itself refused: it calls nothing, whatever the plan
// covers, so nothing is listed rather than the bootstrap set
if (e?.refused) return {}
return provider.models
}
const models = list.filter((m) => !m.draws && covered.has(m.id))
if (!models.length) return {}
return Object.fromEntries(models.map((m) => [m.id, modelOf(m, provider)]))
},
},
auth: {
// which provider this sign-in belongs to: magpie files the card and
// the account under it (host.js reads auth.provider, not the hook's
// own provider field)
provider: PROVIDER_ID,
// the host reads the lead off auth (leadOf(a), with a = auth), not off
// the hooks object: where it sits decides whether magpie renews this
// far ahead of the token's end or at its own default of 5 minutes
refreshLead: EARLY_MS,
// magpie renews ahead of the token's end, once per account
async refresh(auth) {
if (auth?.type !== "oauth" || !auth.access || !auth.refresh) return undefined
// every failure goes back as an error, not as undefined: host.js
// records its RENEW_RETRY cooldown only when auth.refresh throws, so
// returning undefined would have magpie retry the same failing call
// on every hook until the token's own expiry passed. Only a dead
// token carries signIn "expired" and ends the sign-in; a transient
// one leaves it as it was, for the vendor's answer to tell.
return await refreshToken(auth.refresh)
},
// the chat loader: an account with an API key serves the models
// (OpenAI-compatible at token.sensenova.cn/v1). magpie sends
// `Authorization: Bearer <apiKey>` for @ai-sdk/openai-compatible
// itself, so no custom fetch is needed — the key (kept on the
// account as `apiKey`) goes in as the apiKey the loader returns.
async loader(getAuth) {
const auth = await getAuth()
const key = apiKeyOf(auth)
if (!key) return {}
return { baseURL: API_BASE(), apiKey: key }
},
// the account's credit pools (the console JWT, not the API key).
// Renewal is the host's job: it renews through auth.refresh, this far
// ahead of the token's end, under a cross-process lock. So usage reads
// with the token in hand and touches a refresh token only when the
// console refuses that token with a 401 — and it first looks for a
// renewal someone else already made. That narrows the window rather
// than closing it: a plugin can't take the host's lock, so if the host
// is mid-renewal at this exact moment the two can still spend one
// rotating token twice and the second is refused. The next read recovers.
async usage(getAuth) {
const auth = await getAuth()
if (auth?.type !== "oauth" || !auth.access) return { error: "not signed in" }
const card = (u, signIn) => ({
plan: u.plan,
...(u.balance ? { balance: u.balance } : {}),
windows: u.windows,
user: auth.accountId ?? auth.email ?? "sensenova",
signIn,
})
try {
return card(await poolUsage(auth.access), "kept")
} catch (e) {
if (e?.status !== 401) return { error: e?.message ?? String(e), signIn: "kept" }
}
// refused mid-life: another renewal may have landed while this read
// was in flight, and Hydra spends a refresh token once, so look
// before spending one of our own
const now = await getAuth()
if (now?.access && now.access !== auth.access) {
try {
return card(await poolUsage(now.access), "renewed")
} catch (e) {
return { error: e?.message ?? String(e), signIn: "kept" }
}
}
if (!now?.refresh) return { error: "no refresh token; sign in again", signIn: "expired" }
try {
const t = await refreshToken(now.refresh)
// the API key rides through: the JWT changes, the key doesn't
if (!(await save({ ...now, ...t })))
// an unsaved pair is no recovery: the next host would spend a
// refresh token that is already spent
return { error: "renewed, but the new tokens could not be saved; sign in again", signIn: "kept" }
return card(await poolUsage(t.access), "renewed")
} catch (e) {
const why = e?.message ?? String(e)
if (e?.dead) return { error: `${why}; sign in again`, signIn: "expired" }
return { error: why, signIn: "kept" }
}
},
methods: [
{
// one sign-in: the console account (its password, sealed to a
// JWE) for the quota, and the API key pasted with it for the
// models. The key is optional — without it the card still shows
// the quota, only no models — but with it the account serves
// chat too, the way workbuddy's one account does both.
type: "oauth",
label: "Sign in with SenseNova account",
prompts: [
{
type: "input",
key: "username",
message: "Your SenseNova console account (platform.sensenova.cn)",
validate: (v) => (String(v ?? "").trim() ? undefined : "account is required"),
},
{
type: "password",
key: "password",
message: "Your SenseNova console password (sealed to JWE before it leaves this machine)",
validate: (v) => (String(v ?? "").trim() ? undefined : "password is required"),
},
{
type: "password",
key: "apiKey",
message: "Your SenseNova API key (sk-…, optional, for the models)",
placeholder: "sk-...",
validate: (v) => {
const s = String(v ?? "").trim()
return s === "" || s.startsWith("sk-") ? undefined : "the key starts with sk-"
},
},
],
authorize: (inputs) => {
const username = String(inputs?.username ?? "").trim()
const password = String(inputs?.password ?? "")
const apiKey = String(inputs?.apiKey ?? "").trim()
if (!username || !password) throw new Error("enter your SenseNova account and password")
return {
// no page to open: the sign-in runs in the background from the
// prompts, as loomy and the other prompt sign-ins do it. A url
// here would have magpie open the console for nothing.
url: "",
instructions: "Signs in to the SenseNova console with your account; the password is sealed (JWE) and never stored.",
method: "auto",
async callback() {
try {
const t = await passwordLogin(username, password)
return {
type: "success",
access: t.access,
refresh: t.refresh,
expires: t.expires,
accountId: username,
uid: username,
// the API key rides along on the account: magpie keeps
// every field the result carries
...(apiKey ? { apiKey } : {}),
}
} catch (e) {
return { type: "failed", error: `SenseNova sign-in: ${e?.message ?? e}` }
}
},
}
},
},
],
},
}
}
}
export const SenseNovaAuthPlugin = makePlugin()
export default SenseNovaAuthPlugin
// for tests
export const _internal = {
sealPassword,
pkce,
passwordLogin,
refreshToken,
usageOf,
poolUsage,
apiModels,
modelOf,
ENDPOINTS,
EFFORTS,
BOOT_MODELS,
EARLY_MS,
allowedHost,
newJar,
cookieHeader,
collectCookies,
followUntil,
}
+18
View File
@@ -0,0 +1,18 @@
// Imported first by every test here: nothing a test runs reaches
// SenseNova. 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 password or a token to
// platform.sensenova.cn, iam.sensecoreapi.cn or signin.sensecore.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)
}
+35
View File
@@ -0,0 +1,35 @@
{
"name": "@magpie-community/opencode-sensenova-auth",
"version": "0.1.0",
"description": "SenseNova (SenseTime 日日新) Token Plan in OpenCode and magpie: one sign-in gives the console account's credit pools, windows and grants, and (with an optional API key) the plan's models for chat",
"type": "module",
"main": "./index.mjs",
"exports": "./index.mjs",
"files": [
"index.mjs",
"README.md"
],
"keywords": [
"opencode",
"opencode-plugin",
"magpie",
"sensenova",
"sensetime",
"日日新",
"token-plan",
"credits",
"quota",
"glm"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/magpie-community/plugins.git",
"directory": "packages/sensenova"
},
"magpie": {
"options": {
"signin": false
}
}
}
+244
View File
@@ -0,0 +1,244 @@
// The sign-in: the console's OIDC walk with PKCE, the password sealed into
// a JWE under the platform's JWKS key, the code exchanged for a token pair.
// Everything runs against a local fake of the console, the IAM login and
// the token endpoint, with a JWKS the fake generates.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { SenseNovaAuthPlugin, _internal } from "./index.mjs"
import { fakeSenseNova, json, jwksOf } from "./fake.mjs"
let f
afterEach(() => f?.close())
// one sign-in, start to finish, against whatever the fake answers
const signIn = async () => {
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
return p.auth.methods[0].authorize({ username: "u", password: "secret", apiKey: "" }).callback()
}
// the JWKS the fake serves (a real RSA key the seal can encrypt to)
const JWKS_PATH = "/.well-known/jwks.json"
const AUTH_PATH = "/oauth2/auth"
const IAM_PATH = "/iam/authn/v1/auth/nova/login"
const TOKEN_PATH = "/oauth2/token"
// a one-hop authorize: the console's /oauth2/auth answers 302 to a URL that
// carries login_challenge, the walk the plugin follows to it. It sets the
// CSRF/session cookie a real Hydra does on the way out, which the IAM request
// must then carry back — the one thing a jar that lost its URL argument would
// silently drop.
function authRedirect(req) {
const challenge = 'challenge-abc'
const state = req.query.get('state')
authState = state // kept for the IAM answer's callback
const redirectUri = req.query.get('redirect_uri')
return new Response(null, {
status: 302,
headers: {
location: redirectUri + '?login_challenge=' + challenge + '&state=' + state,
'set-cookie': 'hydra_session=csrf-123; Path=/',
},
})
}
// IAM accepts the sealed password and answers a redirect to the callback
// that carries the authorization code (and the round-tripped state)
let authState = ''
function iamAccept(req) {
// the password is sealed: the request body carries is_encrypt true and a
// 5-segment JWE, never the plaintext
expect(req.json?.is_encrypt).toBe(true)
expect(String(req.json?.password ?? '').split('.').length).toBe(5)
expect(req.json?.challenge).toBe('challenge-abc')
// the cookie the authorize set on this host comes back on the IAM request
expect(req.headers.get("cookie") ?? "").toContain("hydra_session=csrf-123")
// the state the authorize issued, kept from its hop; the callback comes
// back on the console's own origin, as the real redirect_uri does
return json({ redirect: f.origin + '/callback?code=auth-code-123&state=' + authState })
}
test("a password is sealed into a JWE and the tokens come back", async () => {
f = fakeSenseNova()
f.route("GET " + JWKS_PATH, () => json(jwksOf()))
f.route("GET " + AUTH_PATH, (r) => authRedirect(r))
f.route("POST " + IAM_PATH, (r) => iamAccept(r))
f.route("POST " + TOKEN_PATH, (r) => {
// the code is exchanged with the PKCE verifier and the client id
expect(r.form?.grant_type).toBe("authorization_code")
expect(r.form?.code).toBe("auth-code-123")
expect(r.form?.code_verifier).toBeTruthy()
return json({ access_token: "jwt-123", refresh_token: "r-123", expires_in: 10800 })
})
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const m = p.auth.methods[0]
const r = m.authorize({ username: "yiheng13", password: "secret", apiKey: "sk-abc" })
const out = await r.callback()
expect(out.type).toBe("success")
expect(out.access).toBe("jwt-123")
expect(out.refresh).toBe("r-123")
expect(out.accountId).toBe("yiheng13")
// the API key rides along on the account
expect(out.apiKey).toBe("sk-abc")
})
test("a password the platform refuses is a failed sign-in, its reason kept", async () => {
f = fakeSenseNova()
f.route("GET " + JWKS_PATH, () => json(jwksOf()))
f.route("GET " + AUTH_PATH, (r) => authRedirect(r))
f.route("POST " + IAM_PATH, () =>
json({ message: "InvalidArgument", details: [{ "@type": "x", reason: "invalidAccountOrPassword" }] }, 400),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const m = p.auth.methods[0]
const r = m.authorize({ username: "yiheng13", password: "wrong", apiKey: "" })
const out = await r.callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("invalidAccountOrPassword")
})
test("a refresh token is renewed, and the new one replaces the old", async () => {
f = fakeSenseNova()
f.route("POST " + TOKEN_PATH, (r) => {
expect(r.form?.grant_type).toBe("refresh_token")
expect(r.form?.refresh_token).toBe("old-r")
// Hydra rotates the refresh token: a new one comes back
return json({ access_token: "jwt-2", refresh_token: "new-r", expires_in: 10800 })
})
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const renewed = await p.auth.refresh({ type: "oauth", access: "old", refresh: "old-r", expires: Date.now() + 1000 })
expect(renewed.access).toBe("jwt-2")
expect(renewed.refresh).toBe("new-r")
})
test("a refresh token the platform has revoked says the sign-in is gone", async () => {
f = fakeSenseNova()
f.route("POST " + TOKEN_PATH, () => json({ error: "invalid_grant" }, 400))
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
// the host only marks an account signed-out on an error that says so
// (host.js: e?.signIn === "expired"); without it the dead token is retried
// every RENEW_RETRY (30 s) and the account never asks to be signed in again
const err = await p
.auth.refresh({ type: "oauth", access: "old", refresh: "dead", expires: Date.now() + 1000 })
.then(() => null, (e) => e)
expect(err).toBeInstanceOf(Error)
expect(err.dead).toBe(true)
expect(err.signIn).toBe("expired")
})
test("a refresh that fails for any reason other than a dead token keeps the sign-in", async () => {
// a 500, and a 400 naming something other than invalid_grant, say nothing
// about the token: the pair in hand is still good and the account must not
// be signed out. Both still go back as an error, because host.js records its
// RENEW_RETRY cooldown only when auth.refresh throws — returning undefined
// would have magpie retry the same failing call on every hook until the
// token's own expiry passed.
f = fakeSenseNova()
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
for (const [status, error] of [[500, "server_error"], [400, "invalid_request"]]) {
f.route("POST " + TOKEN_PATH, () => json({ error }, status))
const err = await p
.auth.refresh({ type: "oauth", access: "old", refresh: "r", expires: Date.now() + 1000 })
.then(() => null, (e) => e)
expect(err).toBeInstanceOf(Error)
expect(err.dead).toBe(false)
expect(err.signIn).toBeUndefined()
}
})
test("a walk that leaves the SenseNova hosts is refused, not followed", async () => {
// the walk carries Hydra session and CSRF cookies: a redirect to another
// domain must not be fetched, or those cookies go with it
f = fakeSenseNova()
f.route("GET " + JWKS_PATH, () => json(jwksOf()))
f.route("GET " + AUTH_PATH, () =>
new Response(null, { status: 302, headers: { location: "https://not-sensenova.example/continue" } }),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const out = await p.auth.methods[0].authorize({ username: "u", password: "p", apiKey: "" }).callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("SenseNova hosts")
})
test("a page body pointing off-site is not taken as the next hop", async () => {
// nextFromBody reads client-side redirects out of a 200 body; an off-site
// one is dropped, so the walk ends without a challenge rather than leaving
f = fakeSenseNova()
f.route("GET " + JWKS_PATH, () => json(jwksOf()))
f.route("GET " + AUTH_PATH, () =>
new Response('<script>window.location.href="https://evil.example/?login_challenge=stolen"</script>', {
status: 200,
headers: { "content-type": "text/html" },
}),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const out = await p.auth.methods[0].authorize({ username: "u", password: "p", apiKey: "" }).callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("login challenge")
})
test("a hop carrying what the walk seeks, on another domain, is not the answer", async () => {
// the walk looks for a login_challenge. An off-site URL holding one must not
// count as found: if what a hop looks like outranked where it points, the
// session and CSRF cookies would leave with it
f = fakeSenseNova()
f.route("GET " + JWKS_PATH, () => json(jwksOf()))
f.route("GET " + AUTH_PATH, () =>
new Response(null, { status: 302, headers: { location: "https://evil.example/?login_challenge=stolen&state=x" } }),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const out = await p.auth.methods[0].authorize({ username: "u", password: "p", apiKey: "" }).callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("SenseNova hosts")
})
test("a downgraded http:// hop to a SenseNova domain is refused", async () => {
// the platform is https only. A plain-http hop would carry the sealed
// password and the session cookie where any link on the path can read them
f = fakeSenseNova()
f.route("GET " + JWKS_PATH, () => json(jwksOf()))
f.route("GET " + AUTH_PATH, () =>
new Response(null, { status: 302, headers: { location: "http://platform.sensenova.cn/continue" } }),
)
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const out = await p.auth.methods[0].authorize({ username: "u", password: "p", apiKey: "" }).callback()
expect(out.type).toBe("failed")
expect(out.error).toContain("SenseNova hosts")
})
test("a refresh answered with a 307 does not replay the token", async () => {
// redirect: "manual" exists so that a 307 or 308 cannot carry this POST —
// body included, refresh token and all — to wherever the reply points
f = fakeSenseNova()
f.route("POST " + TOKEN_PATH, () =>
new Response(null, { status: 307, headers: { location: f.origin + "/elsewhere" } }))
f.route("POST /elsewhere", () => json({ access_token: "x" }))
await expect(_internal.refreshToken("r-secret")).rejects.toThrow()
expect(f.seen.some((r) => r.path === "/elsewhere")).toBe(false)
})
test("an IAM login answered with a 307 does not replay the sealed password", async () => {
// the IAM request is the one that carries the sealed password; a redirect
// there has to die rather than deliver it to the reply's target
f = fakeSenseNova()
f.route("GET " + JWKS_PATH, () => json(jwksOf()))
f.route("GET " + AUTH_PATH, (r) => authRedirect(r))
f.route("POST " + IAM_PATH, () =>
new Response(null, { status: 307, headers: { location: f.origin + "/elsewhere" } }))
f.route("POST /elsewhere", () => json({ redirect: f.origin + "/cb?code=x" }))
expect((await signIn()).type).toBe("failed")
expect(f.seen.some((r) => r.path === "/elsewhere")).toBe(false)
})
test("a code exchange answered with a 307 does not replay the code and verifier", async () => {
// the code and its PKCE verifier ride this POST; replaying them somewhere
// else is how an authorization code gets stolen
f = fakeSenseNova()
f.route("GET " + JWKS_PATH, () => json(jwksOf()))
f.route("GET " + AUTH_PATH, (r) => authRedirect(r))
f.route("POST " + IAM_PATH, (r) => iamAccept(r))
f.route("POST " + TOKEN_PATH, () =>
new Response(null, { status: 307, headers: { location: f.origin + "/elsewhere" } }))
f.route("POST /elsewhere", () => json({ access_token: "a", refresh_token: "r" }))
expect((await signIn()).type).toBe("failed")
expect(f.seen.some((r) => r.path === "/elsewhere")).toBe(false)
})
+93
View File
@@ -0,0 +1,93 @@
// The parsers against the platform's literal bytes. testdata/ holds one
// real /v1/models reply and one real pool-usage reply from a free Token Plan
// account (only the account's pool ids are replaced), so what the fake serves
// is what the console actually sent — including its numbers as strings.
import "./nonet.mjs"
import { readFileSync } from "node:fs"
import { afterEach, expect, test } from "bun:test"
import { SenseNovaAuthPlugin, _internal } from "./index.mjs"
import { fakeSenseNova, json } from "./fake.mjs"
let f
afterEach(() => f?.close())
const load = (name) => JSON.parse(readFileSync(new URL("./testdata/" + name, import.meta.url), "utf8"))
const POOLS = load("pool-usage.json")
const MODELS = load("models.json")
const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "acct", apiKey: "sk-test" }
test("the real pools become one window per pool per span, with the models each covers", () => {
const u = _internal.usageOf(POOLS.pools)
// two pools × (5h, 7d): the console's own numbers, which arrive as strings
expect(u.windows.map((w) => w.name)).toEqual([
"通用积分池 · 5 hours",
"通用积分池 · 7 days",
"Flash-Lite积分池 · 5 hours",
"Flash-Lite积分池 · 7 days",
])
// the default pool leads, so its meters show whatever groups by model
expect(u.windows[0].models).toContain("glm-5.2")
expect(u.windows[0].models.length).toBe(18)
expect(u.windows[2].models).toEqual(["sensenova-6.7-flash-lite", "sensenova-6.8-flash-lite"])
// the counts are the console's, the share is computed from them
expect(u.windows[0].display).toBe("120000 / 120000")
expect(u.windows[0].used).toBe(100)
expect(u.windows[1].display).toBe("438285.55 / 1200000")
// reset_at is epoch seconds, turned into a time the GUI can count down to
expect(new Date(u.windows[0].resetsAt).getTime()).toBe(1793483140 * 1000)
// a grant of 0 is no balance to show
expect(u.balance).toBeUndefined()
})
test("the real catalogue is filtered to what this account's plan can chat with", async () => {
f = fakeSenseNova()
f.route("GET /models", () => json(MODELS))
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json(POOLS))
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const models = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth })
// the catalogue serves seven, all of them marked "tokenplan"; the plan's
// pools cover six of those, and one of the six only draws images
expect(MODELS.data.length).toBe(7)
expect(Object.keys(models).sort()).toEqual([
"deepseek-flash",
"deepseek-v4-flash",
"glm-5.2",
"kimi-k3",
"sensenova-6.8-flash-lite",
])
// the one the plan doesn't cover is left out: the vendor answers 403 to it
expect(models["deepseek-v4.1-flash"]).toBeUndefined()
// the one that draws is left out: a chat endpoint answers 404 to it
expect(models["sensenova-u1.5-lite"]).toBeUndefined()
})
test("the real catalogue's own fields are what the models declare", async () => {
f = fakeSenseNova()
f.route("GET /models", () => json(MODELS))
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json(POOLS))
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const models = await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth })
const byId = Object.fromEntries(MODELS.data.map((m) => [m.id, m]))
for (const id of Object.keys(models)) {
expect(models[id].limit).toEqual({ context: byId[id].context_length, output: byId[id].max_output_length })
const takesImage = byId[id].input_modalities.includes("image")
expect(models[id].capabilities.input.image).toBe(takesImage)
expect(models[id].modalities.input).toEqual(takesImage ? ["text", "image"] : ["text"])
}
})
test("the bootstrap list is a subset of what the plan and catalogue agree on", async () => {
// config() declares models before any account is read: those ids must be
// ones a free Token Plan account can actually call, or a cold host would
// offer a model the vendor refuses
f = fakeSenseNova()
f.route("GET /models", () => json(MODELS))
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json(POOLS))
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const cfg = {}
await p.config(cfg)
const declared = Object.keys(cfg.provider["sensenova-token-plan"].models)
const listed = Object.keys(await p.provider.models({ id: "sensenova-token-plan", models: {} }, { auth }))
expect(declared.sort()).toEqual(listed.sort())
})
+313
View File
@@ -0,0 +1,313 @@
{
"data": [
{
"id": "deepseek-v4-flash",
"hugging_face_id": "",
"name": "deepseek-v4-flash",
"created": 1777392000,
"input_modalities": [
"text"
],
"output_modalities": [
"text"
],
"quantization": "fp8",
"context_length": 1048576,
"max_output_length": 65536,
"pricing": {
"prompt": "0",
"completion": "0",
"image": "0",
"request": "0",
"input_cache_read": "0"
},
"supported_sampling_parameters": [
"temperature",
"stop"
],
"supported_features": [
"tools",
"json_mode",
"reasoning"
],
"description": "DeepSeek V4 Flash is a high-performance conversational model by DeepSeek, supporting thinking/non-thinking modes, 1M context window, and tool calling.",
"openrouter": {
"slug": "sensenova/deepseek-v4-flash"
},
"datacenters": [
{
"country_code": "CN"
}
],
"businesses": [
"tokenplan",
"metered"
]
},
{
"id": "glm-5.2",
"hugging_face_id": "",
"name": "glm-5.2",
"created": 1777392000,
"input_modalities": [
"text"
],
"output_modalities": [
"text"
],
"quantization": "fp8",
"context_length": 1048576,
"max_output_length": 131072,
"pricing": {
"prompt": "0",
"completion": "0",
"image": "0",
"request": "0",
"input_cache_read": "0"
},
"supported_sampling_parameters": [
"temperature",
"stop"
],
"supported_features": [
"tools",
"json_mode",
"reasoning"
],
"description": "GLM-5.2 is the flagship model for the era of long-horizon tasks. It supports a truly usable 1M context window, with practical tests showing it can handle project-level engineering contexts. Long-sequence task execution is more stable, adherence to engineering standards is more reliable, and success rates in development scenarios are further improved. A single task can complete the entire development pipeline—from requirements to deployable multi-platform deliverables.",
"openrouter": {
"slug": "sensenova/glm-5.2"
},
"datacenters": [
{
"country_code": "CN"
}
],
"businesses": [
"tokenplan",
"metered"
]
},
{
"id": "sensenova-6.8-flash-lite",
"hugging_face_id": "",
"name": "sensenova-6.8-flash-lite",
"created": 1777392000,
"input_modalities": [
"text",
"image"
],
"output_modalities": [
"text"
],
"quantization": "fp8",
"context_length": 262144,
"max_output_length": 65536,
"pricing": {
"prompt": "0",
"completion": "0",
"image": "0",
"request": "0",
"input_cache_read": "0"
},
"supported_sampling_parameters": [
"temperature",
"stop"
],
"supported_features": [
"tools",
"json_mode",
"reasoning"
],
"description": "SenseNova 6.8 Flash-Lite is a lightweight multimodal agent model designed for real-world workflows, supporting text conversation and image input understanding.",
"openrouter": {
"slug": "sensenova/sensenova-6.8-flash-lite"
},
"datacenters": [
{
"country_code": "CN"
}
],
"businesses": [
"tokenplan",
"metered"
]
},
{
"id": "sensenova-u1.5-lite",
"hugging_face_id": "",
"name": "sensenova-u1.5-lite",
"created": 1777392000,
"input_modalities": [
"text"
],
"output_modalities": [
"image"
],
"quantization": "fp8",
"context_length": 262144,
"max_output_length": 65536,
"pricing": {
"prompt": "0",
"completion": "0",
"image": "0",
"request": "0",
"input_cache_read": "0"
},
"supported_sampling_parameters": [
"temperature",
"stop"
],
"supported_features": [
"tools",
"json_mode",
"reasoning"
],
"description": "SenseNova U1.5 Lite is an accelerated version based on SenseNova U1.5, specialized for infographics generation.",
"openrouter": {
"slug": "sensenova/sensenova-u1.5-lite"
},
"datacenters": [
{
"country_code": "CN"
}
],
"businesses": [
"tokenplan",
"metered"
]
},
{
"id": "kimi-k3",
"hugging_face_id": "",
"name": "kimi-k3",
"created": 1777392000,
"input_modalities": [
"text"
],
"output_modalities": [
"text"
],
"quantization": "fp8",
"context_length": 1048576,
"max_output_length": 65536,
"pricing": {
"prompt": "0",
"completion": "0",
"image": "0",
"request": "0",
"input_cache_read": "0"
},
"supported_sampling_parameters": [
"temperature",
"stop"
],
"supported_features": [
"tools",
"json_mode",
"reasoning"
],
"description": "Kimi K3 is a high-performance conversational model by Kimi, supporting thinking/non-thinking modes, 1M context window, and tool calling.",
"openrouter": {
"slug": "sensenova/kimi-k3"
},
"datacenters": [
{
"country_code": "CN"
}
],
"businesses": [
"tokenplan",
"metered"
]
},
{
"id": "deepseek-flash",
"hugging_face_id": "",
"name": "deepseek-flash",
"created": 1777392000,
"input_modalities": [
"text"
],
"output_modalities": [
"text"
],
"quantization": "fp8",
"context_length": 1048576,
"max_output_length": 65536,
"pricing": {
"prompt": "0",
"completion": "0",
"image": "0",
"request": "0",
"input_cache_read": "0"
},
"supported_sampling_parameters": [
"temperature",
"stop"
],
"supported_features": [
"tools",
"json_mode",
"reasoning"
],
"description": "DeepSeek Flash is a high-performance conversational model by DeepSeek, supporting thinking/non-thinking modes, 1M context window, and tool calling.",
"openrouter": {
"slug": "sensenova/deepseek-flash"
},
"datacenters": [
{
"country_code": "CN"
}
],
"businesses": [
"tokenplan",
"metered"
]
},
{
"id": "deepseek-v4.1-flash",
"hugging_face_id": "",
"name": "deepseek-v4.1-flash",
"created": 1777392000,
"input_modalities": [
"text"
],
"output_modalities": [
"text"
],
"quantization": "fp8",
"context_length": 1048576,
"max_output_length": 65536,
"pricing": {
"prompt": "0",
"completion": "0",
"image": "0",
"request": "0",
"input_cache_read": "0"
},
"supported_sampling_parameters": [
"temperature",
"stop"
],
"supported_features": [
"tools",
"json_mode",
"reasoning"
],
"description": "DeepSeek V4.1 Flash is a high-performance conversational model by DeepSeek, supporting thinking/non-thinking modes, 1M context window, and tool calling.",
"openrouter": {
"slug": "sensenova/deepseek-v4.1-flash"
},
"datacenters": [
{
"country_code": "CN"
}
],
"businesses": [
"tokenplan",
"metered"
]
}
]
}
+73
View File
@@ -0,0 +1,73 @@
{
"plan": {
"id": "free",
"name": "Free Plan",
"type": "TOKEN_PLAN_PLAN_TYPE_FREE"
},
"pools": [
{
"id": "pool_00000000-0000-4000-8000-000000000001",
"name": "通用积分池",
"model_ids": [
"deepseek-flash",
"deepseek-v4-flash",
"deepseek-v4-pro",
"glm-5.1",
"glm-5.2",
"kimi-k2.6",
"kimi-k3",
"minimax-m2.7",
"qwen3.6-27b",
"sensenova-6.7-flash-lite",
"sensenova-6.8-flash",
"sensenova-6.8-flash-lite",
"sensenova-mask",
"sensenova-pe",
"sensenova-u1-fast",
"sensenova-u1-pro-previews-v2.3",
"sensenova-u1.5-fast",
"sensenova-u1.5-lite"
],
"window_5h": {
"limit": "120000",
"used": "120000",
"remaining": "0",
"reset_at": "1793483140"
},
"window_7d": {
"limit": "1200000",
"used": "438285.55472",
"remaining": "761714.44528",
"reset_at": "1793673940"
},
"grant_balance": "0",
"nearest_grant_expiry": "0",
"nearest_grant_expiring_balance": "0",
"pool_type": "default"
},
{
"id": "pool_00000000-0000-4000-8000-000000000002",
"name": "Flash-Lite积分池",
"model_ids": [
"sensenova-6.7-flash-lite",
"sensenova-6.8-flash-lite"
],
"window_5h": {
"limit": "120000",
"used": "2877.6448",
"remaining": "117122.3552",
"reset_at": "1793483140"
},
"window_7d": {
"limit": "1200000",
"used": "12747.1272",
"remaining": "1187252.8728",
"reset_at": "1793673940"
},
"grant_balance": "0",
"nearest_grant_expiry": "0",
"nearest_grant_expiring_balance": "0",
"pool_type": "dedicated"
}
]
}
+158
View File
@@ -0,0 +1,158 @@
// The credit pools: what the console's pool-usage answers, as magpie's
// usage windows. Everything runs against the local fake.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { SenseNovaAuthPlugin } from "./index.mjs"
import { fakeSenseNova, json } from "./fake.mjs"
let f
afterEach(() => f?.close())
// the token endpoint's own path, as the fake registers it
const TOKEN_PATH = "/oauth2/token"
const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "yiheng13" }
const pool = (over = {}) => ({
name: "通用积分池",
pool_type: "default",
model_ids: ["glm-5.2"],
window_5h: { limit: "120000", used: "39657.43456", remaining: "80342.56544", reset_at: "1730000000" },
window_7d: { limit: "1200000", used: "237942.98928", remaining: "962057.01072", reset_at: "1731000000" },
grant_balance: "12733.76104",
nearest_grant_expiry: "1732000000",
...over,
})
async function usage() {
const plugin = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
return plugin.auth.usage(async () => auth)
}
test("a pool's windows are the card's windows: the spent share, the count and the reset", async () => {
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", (r) => {
expect(r.headers.get("authorization")).toBe("Bearer tok")
return json({ plan: { id: "free", name: "Free Plan" }, pools: [pool()] })
})
const u = await usage()
expect(u.plan).toBe("Free Plan")
expect(u.user).toBe("yiheng13")
const w = u.windows.find((x) => x.name.endsWith("5 hours"))
expect(w.used).toBeCloseTo(33.05, 1) // the SPENT share: 39657.43 / 120000
expect(w.amount).toBe(39657.43)
expect(w.limit).toBe(120000)
expect(w.unit).toBe("credits")
expect(w.display).toBe("39657.43 / 120000")
expect(w.resetsAt).toBe(new Date(1730000000 * 1000).toISOString())
expect(w.name).toBe("通用积分池 · 5 hours")
})
test("the default pool's two windows come first, a dedicated pool's after them", async () => {
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () =>
json({
plan: { name: "Free Plan" },
pools: [
pool({ name: "Flash-Lite积分池", pool_type: "dedicated", window_5h: { limit: "120000", used: "897.29", remaining: "119102.71", reset_at: "1730000000" }, grant_balance: undefined }),
pool(),
],
}),
)
const u = await usage()
// the GUI draws the first two windows as meters: the default pool's own
expect(u.windows[0].name).toStartWith("通用积分池")
expect(u.windows[1].name).toBe("通用积分池 · 7 days")
expect(u.windows.slice(2).map((w) => w.name)).toEqual(["Flash-Lite积分池 · 5 hours", "Flash-Lite积分池 · 7 days"])
})
test("a grant is a balance that expires, told as the account's balance", async () => {
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json({ plan: { name: "Free Plan" }, pools: [pool()] }))
const u = await usage()
// the GUI draws a usage balance as its own chip; a grant is never a window
expect(u.balance).toContain("12733.76")
expect(u.balance).toContain("granted")
expect(u.windows.some((w) => w.name.includes("grants"))).toBe(false)
})
test("a pool with no window of its own is left out", async () => {
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () =>
json({
plan: { name: "Free Plan" },
pools: [pool({ window_5h: undefined, window_7d: undefined, grant_balance: undefined, nearest_grant_expiry: undefined })],
}),
)
const u = await usage()
expect(u.windows).toEqual([])
})
test("a pool the console reports no limit for is skipped", async () => {
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () =>
json({ plan: { name: "Free Plan" }, pools: [pool({ window_5h: { limit: "0", used: "0" } })] }),
)
const u = await usage()
expect(u.windows.some((x) => x.name.endsWith("5 hours"))).toBe(false)
})
test("the console refusing the token is an error, not an empty card", async () => {
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", () => json({ code: 16, message: "Unauthenticated" }, 401))
f.route("POST /oauth2/token", () => json({ error: "invalid_grant" }, 400))
const u = await usage()
expect(u.error).toContain("sign in again")
expect(u.signIn).toBe("expired")
})
test("a token the console refuses is renewed and the read tried again", async () => {
f = fakeSenseNova()
let calls = 0
f.route("GET /lite/console/v1/tokenplan/pool-usage", (r) => {
calls++
if (r.headers.get("authorization") === "Bearer tok") return json({ code: 16 }, 401)
return json({ plan: { name: "Free Plan" }, pools: [pool()] })
})
f.route("POST /oauth2/token", () => json({ access_token: "tok2", refresh_token: "r2", expires_in: 3600 }))
const u = await usage()
expect(u.error).toBeUndefined()
expect(u.plan).toBe("Free Plan")
expect(calls).toBe(2) // refused, renewed, tried again
})
test("not signed in says so", async () => {
const plugin = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
const u = await plugin.auth.usage(async () => ({ type: "oauth" }))
expect(u.error).toBe("not signed in")
})
test("usage spends a renewal that already landed instead of its own refresh token", async () => {
// the host renews under its own lock ahead of expiry; if one lands while a
// usage read is in flight, that renewal's token is the one to use, and the
// refresh token this account holds must stay unspent — Hydra spends it once
f = fakeSenseNova()
let spent = 0
f.route("GET /lite/console/v1/tokenplan/pool-usage", (r) =>
r.headers.get("authorization") === "Bearer old" ? json({}, 401) : json({ plan: { name: "P" }, pools: [] }))
f.route("POST " + TOKEN_PATH, () => (spent++, json({ access_token: "mine", refresh_token: "r3" })))
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => {} } } })
let n = 0
const u = await p.auth.usage(async () => (n++ === 0
? { type: "oauth", access: "old", refresh: "r1", expires: Date.now() + 3600e3 }
: { type: "oauth", access: "theirs", refresh: "r2", expires: Date.now() + 3600e3 }))
expect(u.signIn).toBe("renewed")
expect(spent).toBe(0)
})
test("a renewal that can't be saved is not reported as renewed", async () => {
// an unsaved pair is no recovery: the next host would spend a refresh token
// that is already spent, so this reads as a failure and nothing is claimed
f = fakeSenseNova()
f.route("GET /lite/console/v1/tokenplan/pool-usage", (r) =>
r.headers.get("authorization") === "Bearer old" ? json({}, 401) : json({ plan: { name: "P" }, pools: [] }))
f.route("POST " + TOKEN_PATH, () => json({ access_token: "new", refresh_token: "r2" }))
const p = await SenseNovaAuthPlugin({ client: { auth: { set: async () => { throw new Error("disk") } } } })
const u = await p.auth.usage(async () => ({ type: "oauth", access: "old", refresh: "r1", expires: Date.now() + 3600e3 }))
expect(u.error).toContain("could not be saved")
expect(u.signIn).not.toBe("renewed")
})
+95
View File
@@ -0,0 +1,95 @@
// The walk's guards, tested as the pure helpers they are. The fake gives every
// host a single origin, so it cannot show a cookie crossing from one host to
// another, a downgrade of a *production* endpoint, or a walk that runs out of
// hops onto an off-site URL. These do, against the real endpoint values.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { _internal } from "./index.mjs"
const { allowedHost, newJar, cookieHeader, collectCookies, followUntil, ENDPOINTS } = _internal
const PROD = {
console: "https://platform.sensenova.cn",
iam: "https://iam.sensecoreapi.cn",
token: "https://signin.sensecore.cn/oauth2/token",
jwks: "https://signin.sensecore.cn/.well-known/jwks.json",
api: "https://token.sensenova.cn/v1",
}
let was
afterEach(() => {
if (was) Object.assign(ENDPOINTS, was)
was = undefined
})
function production() {
was = { ...ENDPOINTS }
Object.assign(ENDPOINTS, PROD)
}
test("an endpoint authorises its own scheme, not merely its host", () => {
production()
expect(allowedHost("https://platform.sensenova.cn/oauth2/auth")).toBe(true)
// the same host over http is a downgrade of it, not it. Matching the host
// alone let this through the endpoint exemption, ahead of the https check
// below — and the jar keys off .host too, so the session cookie would have
// travelled in the clear. The fake never caught this because its endpoints
// are 127.0.0.1, where the exemption doesn't match the name under test.
expect(allowedHost("http://platform.sensenova.cn/continue")).toBe(false)
expect(allowedHost("http://token.sensenova.cn/v1/models")).toBe(false)
expect(allowedHost("http://signin.sensecore.cn/oauth2/token")).toBe(false)
})
test("the SenseTime domains are walkable and look-alikes are not", () => {
production()
expect(allowedHost("https://console.sensenova.cn/x")).toBe(true)
expect(allowedHost("https://evil.example/?login_challenge=stolen")).toBe(false)
// a suffix that reads like the domain is not the domain
expect(allowedHost("https://sensenova.cn.evil.example/x")).toBe(false)
expect(allowedHost("https://notsensecore.cn/x")).toBe(false)
expect(allowedHost("not a url")).toBe(false)
})
test("a cookie goes back only to the host that set it", () => {
const jar = newJar()
const set = (url, line) => collectCookies(new Response(null, { headers: { "set-cookie": line } }), jar, url)
set("https://platform.sensenova.cn/oauth2/auth", "hydra_session=s-1; Path=/")
set("https://iam.sensecoreapi.cn/iam/login", "iam_csrf=c-9; Path=/")
expect(cookieHeader(jar, "https://platform.sensenova.cn/callback")).toBe("hydra_session=s-1")
expect(cookieHeader(jar, "https://iam.sensecoreapi.cn/iam/authn/v1/auth/nova/login")).toBe("iam_csrf=c-9")
// neither leaks to the other, and a third host gets nothing at all
expect(cookieHeader(jar, "https://evil.example/")).toBe("")
// dropping the url is what once sent the IAM request out with no cookie: the
// answer is an empty header, never every cookie in the jar
expect(cookieHeader(jar, undefined)).toBe("")
})
test("a walk that runs out of hops does not hand back an off-site target", async () => {
// the check inside the loop stops the fetching; the one after it has to stop
// the *returning*. To reach it the off-site URL must arrive on the last hop,
// so the loop has no iteration left in which to notice.
production()
let hops = 0
let base = ""
const server = Bun.serve({
port: 0,
hostname: "127.0.0.1",
fetch() {
hops++
if (hops >= 8)
return new Response(null, { status: 302, headers: { location: "https://evil.example/final?login_challenge=stolen" } })
return new Response(null, { status: 302, headers: { location: `${base}/step` } })
},
})
base = `http://127.0.0.1:${server.port}`
Object.assign(ENDPOINTS, { console: base })
try {
await expect(followUntil(`${base}/start`, /login_challenge=/, newJar())).rejects.toThrow(
"left the SenseNova hosts",
)
// it really did spend the whole budget before the last hop answered
expect(hops).toBe(8)
} finally {
server.stop(true)
}
})
+2
View File
@@ -58,6 +58,8 @@
"summary": { "en": "Nous Portal models, with Nous Portal's device sign-in.", "zh": "通过 Nous Portal 自己的设备码登录使用 Nous Portal 模型。" } },
{ "package": "@magpie-community/opencode-raccoon-auth", "name": "商汤小浣熊", "icon": "sensenova-color", "providers": ["raccoon"], "community": true,
"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,
"summary": { "en": "SenseNova (SenseTime 日日新) Token Plan: one console sign-in reads the credit pools, their 5-hour and 7-day windows and the expiring grants, and — with an API key pasted at sign-in — serves the plan's own models for chat.", "zh": "商汤日日新 Token Plan:一次控制台登录即可读取积分池、5 小时 / 7 天窗口与将过期的返赠余额;登录时粘贴 API Key,同一个账号就能直接调用计划内模型对话。" } },
{ "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)或国内手机验证码,积分余额与每日签到。" } },
{ "package": "@magpie-community/opencode-codearts-auth", "name": "CodeArts / OfficeAce", "providers": ["codearts", "officeace"], "community": true,