A local-first multi-agent app development platform, built on PenguinHarness
App attribution for OpenRouter and TokenDance, plus a TokenDance provider group (#465)
Yaowei Zheng77f24e3801ab
diff --git a/changelog/unreleased/2026-08-25-tokendance-and-app-attribution.md b/changelog/unreleased/2026-08-25-tokendance-and-app-attribution.mdnew file mode 100644index 00000000..d17df537--- /dev/null+++ b/changelog/unreleased/2026-08-25-tokendance-and-app-attribution.md@@ -0,0 +1,31 @@+# App attribution for OpenRouter and TokenDance, and a TokenDance provider group++- **Date:** 2026-08-25+- **Type:** feature+- **Scope:** `core`, `model-catalog`, `web`, `docs`+- **PR:** [#465](https://github.com/Prism-Shadow/penguin-harness/pull/465)++[中文版](2026-08-25-tokendance-and-app-attribution.zh.md)++Model requests started naming PenguinHarness to the gateways that read an app-attribution header, and the built-in catalog gained a TokenDance provider group with seven presets. The model library's provider groups were resequenced at the same time.++## App attribution++`attributionHeaders` joined the model catalog and was wired into every `GenerativeModel`, which hands it to AgentHub as `defaultHeaders` (a constructor option since `@prismshadow/agenthub` 0.4.7):++| Endpoint | Headers |+| --- | --- |+| `openrouter.ai` | `HTTP-Referer: https://penguin.ooo/`, `X-OpenRouter-Title: PenguinHarness`, `X-OpenRouter-Categories: cli-agent,personal-agent` |+| `tokendance.space` | `X-App-URL: https://penguin.ooo/` |++The headers are picked by the endpoint host of the entry's `base_url` rather than by its provider group, so a model filed under `custom` that points at one of those gateways is attributed identically. Every other endpoint receives no extra headers, and an entry carrying no `base_url` of its own is never attributed — including when `OPENAI_BASE_URL` sends it to one of these gateways.++## TokenDance++A `tokendance` group was added, reaching `https://tokendance.space/gateway/v1` over Chat Completions (`client_type = "openai-chat"`) with a blank credential falling back to `OPENAI_API_KEY`. Seven presets shipped with it — `deepseek-v4-flash-0731`, `deepseek-v4-flash-vision-exp`, `deepseek-v4-pro-0813`, `glm-5.3`, `glm-5.3-flash`, `kimi-k3` and `qwen3.8-max` — every one of them at the gateway's own CNY **list** price, the convention the two Qwen groups already follow. Two carry a running promotion, so the group over-states what those two currently bill: `glm-5.3-flash` (0.23 / 0.8 / 2.8 CNY, cache hit / input / output) is on a 2-week 50% off, and `qwen3.8-max` (1.5 / 12 / 36 CNY) on a limited-time 20% off. TokenDance's public catalog API tags both promotions in the model's `description`, so whether one is still running can be re-checked with no credential. `glm-5.3-flash` is multimodal with a 1M context window, and is the group's only model whose upstream serves Chat Completions alone.++Projects created earlier pick none of this up on their own: presets are copied into `.project_config.toml` when a Project is created and nothing rewrites them afterwards. The models page's "sync presets" is the one path — it appends the new presets and updates catalog-owned fields such as pricing on entries already there, without deleting anything or touching a stored default.++## Provider order++The model library's provider groups were resequenced to DeepSeek, OpenRouter, Fireworks AI, Google Gemini, OpenAI, Anthropic, SiliconFlow, TokenDance, Z.AI (GLM), Moonshot (Kimi), MiniMax, Qwen Pay-As-You-Go, Qwen Token Plan, Custom. The order is display-only and is read from the catalog at render time, so nothing on disk changed.diff --git a/changelog/unreleased/2026-08-25-tokendance-and-app-attribution.zh.md b/changelog/unreleased/2026-08-25-tokendance-and-app-attribution.zh.mdnew file mode 100644index 00000000..e82a898a--- /dev/null+++ b/changelog/unreleased/2026-08-25-tokendance-and-app-attribution.zh.md@@ -0,0 +1,31 @@+# OpenRouter 与 TokenDance 的应用归因,以及新增 TokenDance 分组++- **Date:** 2026-08-25+- **Type:** feature+- **Scope:** `core`, `model-catalog`, `web`, `docs`+- **PR:** [#465](https://github.com/Prism-Shadow/penguin-harness/pull/465)++[English](2026-08-25-tokendance-and-app-attribution.md)++模型请求开始向读取应用归因请求头的网关声明 PenguinHarness,内置目录新增 TokenDance 分组及其七个预设。模型库的 Provider 分组顺序同时做了调整。++## 应用归因++模型目录新增 `attributionHeaders`,并接入每一个 `GenerativeModel`——由它作为 `defaultHeaders` 传给 AgentHub(`@prismshadow/agenthub` 0.4.7 起提供的构造参数):++| 端点 | 请求头 |+| --- | --- |+| `openrouter.ai` | `HTTP-Referer: https://penguin.ooo/`、`X-OpenRouter-Title: PenguinHarness`、`X-OpenRouter-Categories: cli-agent,personal-agent` |+| `tokendance.space` | `X-App-URL: https://penguin.ooo/` |++请求头由条目 `base_url` 的端点主机名决定,而非其 Provider 分组,因此一个填在 `custom` 分组、base URL 指向上述网关的模型同样会被归因。其余端点不会收到任何额外请求头;条目自身没有 `base_url` 时一律不归因——包括由 `OPENAI_BASE_URL` 指向这些网关的情形。++## TokenDance++新增 `tokendance` 分组,经 Chat Completions(`client_type = "openai-chat"`)访问 `https://tokendance.space/gateway/v1`,凭证留空时回退到 `OPENAI_API_KEY`。随之上线七个预设——`deepseek-v4-flash-0731`、`deepseek-v4-flash-vision-exp`、`deepseek-v4-pro-0813`、`glm-5.3`、`glm-5.3-flash`、`kimi-k3` 与 `qwen3.8-max`——一律记该网关自己的 CNY **牌价**,与下方两个 Qwen 分组口径一致。其中两个正在促销,因此该分组当前高估了这两行的实际计费:`glm-5.3-flash`(0.23 / 0.8 / 2.8 CNY,缓存命中 / 输入 / 输出)正在限时两周五折,`qwen3.8-max`(1.5 / 12 / 36 CNY)正在限时八折。TokenDance 的公开模型目录 API 会把这两个促销标注在模型的 `description` 里,因此无需凭证即可复核促销是否仍在进行。`glm-5.3-flash` 支持多模态输入,上下文窗口 1M,也是该分组中唯一只提供 Chat Completions 协议的模型。++此前创建的 Project 不会自动获得上述任何改动:预设是在 Project 创建时复制进 `.project_config.toml` 的,此后不会被改写。唯一的途径是模型库页的「同步预设」——它追加新预设,并更新已有条目上归目录所有的字段(如价格),既不删除任何内容,也不改动已存的默认模型。++## Provider 顺序++模型库的 Provider 分组顺序调整为 DeepSeek、OpenRouter、Fireworks AI、Google Gemini、OpenAI、Anthropic、SiliconFlow、TokenDance、Z.AI (GLM)、Moonshot (Kimi)、MiniMax、Qwen Pay-As-You-Go、Qwen Token Plan、Custom。该顺序仅影响展示,渲染时从目录读取,磁盘上的数据没有变化。diff --git a/changelog/unreleased/2026-08-26-tokendance-oauth.md b/changelog/unreleased/2026-08-26-tokendance-oauth.mdnew file mode 100644index 00000000..f3adb5b2--- /dev/null+++ b/changelog/unreleased/2026-08-26-tokendance-oauth.md@@ -0,0 +1,28 @@+# Authorize a new TokenDance API key from the models page++- **Date:** 2026-08-26+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `docs`, `model-catalog`+- **PR:** [#470](https://github.com/Prism-Shadow/penguin-harness/pull/470)++[中文版](2026-08-26-tokendance-oauth.zh.md)++The TokenDance group header gained an **Authorize key** action. It creates a new key on the user's TokenDance account through the provider's authorization page and writes it to every model in the group, so a first run no longer needs a trip to the console to copy a key out by hand.++## Details++- The built-in catalog's `ModelProviderInfo` gained an optional `oauth` descriptor — the authorization page, the exchange endpoint, and the name recorded on the minted key — set on the `tokendance` entry. The Web App renders the action for any group whose provider declares one, and the server accepts a flow only for such a group, building both URLs from the catalog rather than from the request.+- `APP_URL` became an export of the model catalog. It is sent as the flow's `app_url`, so a key minted here is stamped with the same app URL the attribution headers already carry.+- Four owner-only routes under `/api/projects/:projectId/model-oauth`: `POST /start` opens a flow and returns the page to send the user to, `GET /callback` is where TokenDance redirects, `GET /:flowId` reports how a flow ended, and `POST /:flowId/code` redeems a code the user pasted. The callback answers a small self-contained HTML page rather than JSON.+- The PKCE verifier is generated on the server, kept in memory for ten minutes, and never sent to a client; the minted key goes straight into the provider group's models without passing through the browser, and appears in no response, log line, URL or error message. A flow belongs to one user in one Project and can be redeemed once.+- The callback URL is derived from the incoming request's own URL, so loopback, a LAN address and a custom port all work without configuration; `x-forwarded-proto` and `x-forwarded-host` are honoured only under `PENGUIN_TRUST_PROXY=1`.+- A manual mode drops the callback so the authorization page shows a one-time code instead of redirecting, for the desktop shell and any deployment the redirect cannot reach. The dialog offers it alongside the redirect path.+- Completing a flow invalidates the Project's cached Session runtimes and publishes `credentials_updated`, the same follow-up the models PUT performs.+- The group header's five actions were relabelled to one or two words — **Add model**, **Authorize key**, **Set key**, **Speed test**, **Manage keys** — and reordered so the authorized path comes before the manual one.+- The Server API and Models documents describe the routes and the user-facing flow in both languages.++## Compatibility++Nothing already on disk changes shape: the `oauth` descriptor lives in the code-side catalog, and the minted key is stored as the `api_key` / `created_at` pair every other credential write already uses. No configuration file, database or stored preference is migrated.++Existing Projects do not pick up catalog changes on their own — presets are copied into `.project_config.toml` when the Project is created, and the models page's "sync presets" is the only thing that updates them afterwards. The action therefore appears wherever a Project's table already holds TokenDance entries; a Project older than that group has to sync presets once before the group, and its new action, show up.diff --git a/changelog/unreleased/2026-08-26-tokendance-oauth.zh.md b/changelog/unreleased/2026-08-26-tokendance-oauth.zh.mdnew file mode 100644index 00000000..bf856cea--- /dev/null+++ b/changelog/unreleased/2026-08-26-tokendance-oauth.zh.md@@ -0,0 +1,28 @@+# 在模型页授权新建 TokenDance API key++- **Date:** 2026-08-26+- **Type:** feature+- **Scope:** `core`, `server`, `web`, `docs`, `model-catalog`+- **PR:** [#470](https://github.com/Prism-Shadow/penguin-harness/pull/470)++[English](2026-08-26-tokendance-oauth.md)++TokenDance 分组头部新增**自动获取密钥**动作:经供应商的授权页在用户的 TokenDance 账户下新建一个 key,并写入该分组下的每一个模型,首次配置不必再去控制台手动复制。++## 细节++- 内置目录的 `ModelProviderInfo` 新增可选的 `oauth` 描述(授权页、兑换端点、记在新 key 上的名称),配置在 `tokendance` 条目上。Web App 对任何声明了该描述的分组渲染这一动作;服务端也只对这类分组受理流程,且两个 URL 一律取自目录,不取自请求。+- `APP_URL` 改为由模型目录导出,作为流程的 `app_url` 发送——在这里新建的 key 因此被打上与归因请求头相同的应用 URL。+- 新增四个仅限 owner 的路由,位于 `/api/projects/:projectId/model-oauth`:`POST /start` 开启流程并返回要跳转的页面,`GET /callback` 是 TokenDance 跳回的地址,`GET /:flowId` 报告流程结果,`POST /:flowId/code` 兑换用户粘贴的授权码。回调返回一个自包含的小 HTML 页面,而非 JSON。+- PKCE 的 verifier 在服务端生成、在内存中保留十分钟,从不下发到客户端;新建出的 key 直接写入该分组的模型,不经过浏览器,也不出现在任何响应、日志、URL 或错误信息中。一次流程只属于某个 Project 下的某个用户,且只能兑换一次。+- 回调地址由请求自身的 URL 推导,因此环回地址、局域网地址与自定义端口都无需额外配置即可工作;`x-forwarded-proto` 与 `x-forwarded-host` 仅在 `PENGUIN_TRUST_PROXY=1` 时采信。+- 手动模式不传回调地址,授权页改为显示一次性授权码,适用于桌面端外壳以及跳转回不来的部署。对话框在跳转路径之外一并提供该入口。+- 流程完成后会使该 Project 已缓存的 Session 运行时失效并发布 `credentials_updated`,与模型 PUT 的后续动作一致。+- 分组头部的五个动作改用短标签——**添加模型**、**自动获取密钥**、**手动设置密钥**、**测速**、**前往密钥管理**——并调整顺序,自动授权排在手动设置之前。+- Server API 与模型文档以中英双语记录了这些路由与用户侧流程。++## 兼容性++磁盘上已有的数据形态不变:`oauth` 描述只存在于代码侧的目录中,新建出的 key 也按其余凭据写入路径一贯的 `api_key` / `created_at` 存放。没有任何配置文件、数据库或本地偏好需要迁移。++已有的 Project 不会自行获取目录变更——预设在创建 Project 时被复制进 `.project_config.toml`,此后只有模型页的「同步预设」会更新它们。因此,只要 Project 的模型表中已有 TokenDance 条目,该动作就会出现;早于该分组的 Project 需要先同步一次预设,分组与这个新动作才会显示。diff --git a/packages/core/src/llm/generative-model.ts b/packages/core/src/llm/generative-model.tsindex d0a2cd4c..4bc9d80c 100644--- a/packages/core/src/llm/generative-model.ts+++ b/packages/core/src/llm/generative-model.ts@@ -69,6 +69,7 @@ import type {ThinkingLevelName,ToolDefinition,} from "../interfaces/index.js";+import { attributionHeaders } from "../state/model-catalog.js";import { ToolCallIdAllocator, stripToolCallIdSuffix } from "./tool-call-ids.js";import {approximateMessagesTokens,@@ -980,12 +981,17 @@ export class GenerativeModel implements LLMInterface {// variables. clientType determines which protocol to speak (`openai-chat` means OpenAI// Chat Completions compatible; the bare `openai` spelling is a deprecated upstream alias);// when omitted, AgentHub infers it from model_id, so it only needs to be specified- // explicitly for custom-named models.+ // explicitly for custom-named models. `defaultHeaders` carries the app attribution the+ // configured endpoint reads (see attributionHeaders); AgentHub hands it to every request+ // the routed client makes, and endpoints with no attribution scheme get no extra headers+ // at all.+ const headers = attributionHeaders(config.baseUrl);this.client = new AutoLLMClient({model: config.modelId,...(config.apiKey !== undefined ? { apiKey: config.apiKey } : {}),...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl } : {}),...(config.clientType !== undefined ? { clientType: config.clientType } : {}),+ ...(headers ? { defaultHeaders: headers } : {}),});this.uniConfig = buildUniConfig(config);diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.tsindex 86838137..56830310 100644--- a/packages/core/src/state/model-catalog.ts+++ b/packages/core/src/state/model-catalog.ts@@ -4,8 +4,9 @@* Data verified as of 2026-07-10 (Qwen Token Plan entries: 2026-07-20; MiniMax: 2026-08-03;* DeepSeek, Gemini 3.7, GLM-5.3 and the whole OpenAI line-up (direct + OpenRouter):* 2026-08-18; the direct Anthropic group: 2026-08-20; the DeepSeek V4 Flash Vision Exp rows:- * 2026-08-21; the GLM-5.3 Flash rows (direct + OpenRouter) and qwen3.8-flash: 2026-08-26 —- * per each provider's docs).+ * 2026-08-21; the TokenDance group: 2026-08-25, its glm-5.3-flash row: 2026-08-26; the+ * GLM-5.3 Flash rows (direct + OpenRouter) and qwen3.8-flash: 2026-08-26 — per each+ * provider's docs).* Docs: packages/docs/content/models.{zh,en}.md (site path /docs/models) documents the* provider groups and credential resolution described here.*@@ -26,9 +27,10 @@* (delisted 2026-08-06; the Z.AI direct glm-5.1 remains), the OpenRouter* inclusionai/ling-3.0-flash:free listing (delisted from OpenRouter, removed 2026-08-18),* non-chat models (embedding / image generation / TTS), and Bedrock. Direct-vendor ids are- * auto-routed by AgentHub and leave client_type unset; the five gateway groups (OpenRouter,- * Fireworks AI, SiliconFlow, Qwen Token Plan, Qwen Pay-As-You-Go) can't be auto-routed, so- * every gateway row **always pins an explicit client_type** and inlines its preset base URL.+ * auto-routed by AgentHub and leave client_type unset; the six gateway groups (OpenRouter,+ * Fireworks AI, SiliconFlow, TokenDance, Qwen Pay-As-You-Go, Qwen Token Plan) can't be+ * auto-routed, so every gateway row **always pins an explicit client_type** and inlines its+ * preset base URL.* That pin is load-bearing, not decoration: AgentHub's AutoLLMClient matches raw substrings* against `client_type || model_id` and never looks at base_url, so an unpinned gateway id* would be routed by its own spelling — `openai/gpt-5.6-sol` would reach the first-party@@ -42,12 +44,30 @@* The MiniMax M3 preset pins AgentHub's first-party `minimax-m3` protocol and direct API* endpoint.*+ * App attribution (`attributionHeaders`, bottom of this file) rides alongside the protocol+ * pins: it names PenguinHarness to the gateways that read such a header, keyed on the+ * endpoint host rather than on the provider group.+ ** This file imports no Node built-ins (type-only imports only), so it can be bundled directly* for the browser.*/import type { ModelEntry, ModelPricing } from "./project-config.js";/** Model provider info (used for web grouping/logo and the "API key blank falls back to env var" hint). */+/**+ * A provider that mints API keys through an authorization page instead of a console visit.+ * Present only on providers that publish such a flow; its absence is what makes the harness+ * refuse to start one.+ */+export interface ModelProviderOAuth {+ /** Authorization page the user is sent to; the flow's parameters ride on its query string. */+ authorizeUrl: string;+ /** Endpoint that trades an authorization code for a newly minted key. */+ exchangeUrl: string;+ /** Name recorded on the minted key, and the app name the authorization page displays. */+ keyName: string;+}+export interface ModelProviderInfo {id: string;/** Display name (brand name, shared by Chinese and English UI). */@@ -66,6 +86,11 @@ export interface ModelProviderInfo {* vendors and custom.*/gatewayBaseUrl?: string;+ /**+ * Authorization flow that mints a key for the user (see ModelProviderOAuth); absent for+ * every provider whose keys are only obtainable from its console.+ */+ oauth?: ModelProviderOAuth;}/** A single built-in model's catalog entry (`modelId` is the upstream id; paired with `provider` it forms the catalog's unique key). */@@ -91,14 +116,21 @@ const QWEN_TOKEN_PLAN_BASE_URL ="https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1";const QWEN_PAYG_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";const FIREWORKS_BASE_URL = "https://api.fireworks.ai/inference/v1";+const TOKENDANCE_BASE_URL = "https://tokendance.space/gateway/v1";const MINIMAX_BASE_URL = "https://api.minimax.io/v1";/**- * Provider list (web model page groups in this order): DeepSeek first (the default model's- * provider), followed by the five gateways (OpenRouter, Fireworks AI, SiliconFlow, Qwen Token- * Plan, Qwen Pay-As-You-Go), then the first-party providers Google Gemini, Anthropic, OpenAI,- * Z.AI (GLM), Moonshot (Kimi), and MiniMax; custom groups custom OpenAI-protocol models and- * comes last.+ * Provider list (web model page groups in this order). The sequence is a hand-curated+ * display order: DeepSeek leads as the default model's provider and custom (custom+ * OpenAI-protocol models) is always last; in between, gateways and first-party vendors are+ * interleaved by expected use rather than sorted by kind.+ *+ * The six gateway groups — OpenRouter, Fireworks AI, SiliconFlow, TokenDance, Qwen+ * Pay-As-You-Go and Qwen Token Plan — reach their models through one of AgentHub's generic+ * OpenAI-protocol clients (`openai-chat`, or `openai-responses` for the OpenRouter+ * `openai/*` rows). Those clients read **OPENAI_API_KEY / OPENAI_BASE_URL** when the+ * credential is blank, not the gateway's own variable names, so every gateway group records+ * the OPENAI_* pair and the env fallback hint the frontend shows is accurate either way.*/export const MODEL_PROVIDERS: ModelProviderInfo[] = [{@@ -109,12 +141,6 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [apiKeyUrl: "https://platform.deepseek.com/api_keys",modelsUrl: "https://api-docs.deepseek.com/quick_start/pricing",},- // Gateways (their model ids can't be auto-routed by AgentHub, so they always pin an- // explicit client_type + a preset base URL): they go through one of AgentHub's generic- // OpenAI-protocol clients - openai-chat (Chat Completions) for most rows, openai-responses- // for the OpenRouter openai/* rows - and *both* read **OPENAI_API_KEY / OPENAI_BASE_URL**- // when the credential is blank (not the provider's own var names), so the env fallback hint- // is the same either way and must reflect that accurately.{id: "openrouter",label: "OpenRouter",@@ -133,34 +159,6 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [modelsUrl: "https://app.fireworks.ai/models",gatewayBaseUrl: FIREWORKS_BASE_URL,},- {- id: "siliconflow",- label: "SiliconFlow",- envKey: "OPENAI_API_KEY",- envBaseUrlKey: "OPENAI_BASE_URL",- apiKeyUrl: "https://cloud.siliconflow.cn/me/account/ak",- modelsUrl: "https://cloud.siliconflow.cn/models",- gatewayBaseUrl: SILICONFLOW_BASE_URL,- },- {- id: "qwen-token-plan",- label: "Qwen Token Plan",- envKey: "OPENAI_API_KEY",- envBaseUrlKey: "OPENAI_BASE_URL",- apiKeyUrl: "https://platform.qianwenai.com/pricing/token-plan",- modelsUrl:- "https://platform.qianwenai.com/docs/token-plan/personal/token-plan-personal-overview",- gatewayBaseUrl: QWEN_TOKEN_PLAN_BASE_URL,- },- {- id: "qwen-pay-as-you-go",- label: "Qwen Pay-As-You-Go",- envKey: "OPENAI_API_KEY",- envBaseUrlKey: "OPENAI_BASE_URL",- apiKeyUrl: "https://platform.qianwenai.com/docs/api-reference/preparation/api-key",- modelsUrl: "https://www.qianwenai.com/models",- gatewayBaseUrl: QWEN_PAYG_BASE_URL,- },{id: "google",label: "Google Gemini",@@ -169,6 +167,14 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [apiKeyUrl: "https://aistudio.google.com/api-keys",modelsUrl: "https://ai.google.dev/gemini-api/docs/models",},+ {+ id: "openai",+ label: "OpenAI",+ envKey: "OPENAI_API_KEY",+ envBaseUrlKey: "OPENAI_BASE_URL",+ apiKeyUrl: "https://platform.openai.com/api-keys",+ modelsUrl: "https://platform.openai.com/docs/models",+ },{id: "anthropic",label: "Anthropic",@@ -178,12 +184,28 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [modelsUrl: "https://docs.claude.com/en/docs/about-claude/models/overview",},{- id: "openai",- label: "OpenAI",+ id: "siliconflow",+ label: "SiliconFlow",envKey: "OPENAI_API_KEY",envBaseUrlKey: "OPENAI_BASE_URL",- apiKeyUrl: "https://platform.openai.com/api-keys",- modelsUrl: "https://platform.openai.com/docs/models",+ apiKeyUrl: "https://cloud.siliconflow.cn/me/account/ak",+ modelsUrl: "https://cloud.siliconflow.cn/models",+ gatewayBaseUrl: SILICONFLOW_BASE_URL,+ },+ {+ id: "tokendance",+ label: "TokenDance",+ envKey: "OPENAI_API_KEY",+ envBaseUrlKey: "OPENAI_BASE_URL",+ apiKeyUrl: "https://tokendance.space/keys",+ modelsUrl: "https://tokendance.space/models",+ gatewayBaseUrl: TOKENDANCE_BASE_URL,+ // https://tokendance.space/docs/api-key-oauth+ oauth: {+ authorizeUrl: "https://tokendance.space/auth",+ exchangeUrl: "https://tokendance.space/portal/api/v1/auth/keys",+ keyName: "PenguinHarness",+ },},{id: "zhipu",@@ -211,6 +233,25 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [apiKeyUrl: "https://platform.minimax.io/user-center/basic-information/interface-key",modelsUrl: "https://platform.minimax.io/docs/guides/models-intro",},+ {+ id: "qwen-pay-as-you-go",+ label: "Qwen Pay-As-You-Go",+ envKey: "OPENAI_API_KEY",+ envBaseUrlKey: "OPENAI_BASE_URL",+ apiKeyUrl: "https://platform.qianwenai.com/docs/api-reference/preparation/api-key",+ modelsUrl: "https://www.qianwenai.com/models",+ gatewayBaseUrl: QWEN_PAYG_BASE_URL,+ },+ {+ id: "qwen-token-plan",+ label: "Qwen Token Plan",+ envKey: "OPENAI_API_KEY",+ envBaseUrlKey: "OPENAI_BASE_URL",+ apiKeyUrl: "https://platform.qianwenai.com/pricing/token-plan",+ modelsUrl:+ "https://platform.qianwenai.com/docs/token-plan/personal/token-plan-personal-overview",+ gatewayBaseUrl: QWEN_TOKEN_PLAN_BASE_URL,+ },{ id: "custom", label: "Custom", envKey: "OPENAI_API_KEY", envBaseUrlKey: "OPENAI_BASE_URL" },];@@ -904,6 +945,96 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [clientType: "openai-chat",baseUrl: SILICONFLOW_BASE_URL,},+ // -- TokenDance (gateway: OpenAI-compatible protocol, preset base URL). Context windows and+ // vision flags from the public catalog API (GET https://tokendance.space/gateway/v1/models,+ // no credential required); prices are the gateway's own CNY rates from each model's detail+ // page, read 2026-08-25 (the detail pages need a signed-in session, so they cannot be+ // re-read anonymously). TokenDance publishes an input price and a cache-hit price with no+ // separate cache-write fee, so cache_write carries the input price.+ //+ // Discounts: every row here stores the official LIST price, the convention of the two Qwen+ // groups below. Two promotions are running, so the group currently over-states what those+ // two rows really cost: glm-5.3-flash is on a 2-week 50% off (running at the 2026-08-26+ // read, so it ends by 2026-09-09 at the latest — 2x the billed rate until then), and+ // qwen3.8-max on a limited-time 20% off with no published end date (1.25x). Both are+ // machine-checkable without a credential: the catalog API opens a discounted model's+ // `description` with a bracketed 限时 ("limited-time") tag naming the rate, so the same+ // anonymous request the context windows come from also says which promotions still run.+ // No other row is discounted, so list price and billed rate coincide for the rest. --+ {+ modelId: "deepseek-v4-flash-0731",+ displayName: "DeepSeek V4 Flash 0731",+ provider: "tokendance",+ contextWindow: 1048576,+ pricing: cny(0.05, 1.5, 4.5),+ supportsVision: false,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },+ {+ modelId: "deepseek-v4-flash-vision-exp",+ displayName: "DeepSeek V4 Flash Vision Exp",+ provider: "tokendance",+ contextWindow: 1000000,+ pricing: cny(0.05, 1.5, 4.5),+ supportsVision: true,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },+ {+ modelId: "deepseek-v4-pro-0813",+ displayName: "DeepSeek V4 Pro 0813",+ provider: "tokendance",+ contextWindow: 1000000,+ pricing: cny(0.15, 4.5, 13.5),+ supportsVision: false,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },+ {+ modelId: "glm-5.3",+ displayName: "GLM-5.3",+ provider: "tokendance",+ contextWindow: 1000000,+ pricing: cny(2, 8, 28),+ supportsVision: false,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },+ {+ // Natively multimodal per TokenDance's catalog entry, and this group's generic+ // openai-chat client forwards image_url parts, so image input works on this path. Its+ // supported_protocols is openai:chat-completions alone, so the openai-chat pin is the+ // only shape this id serves.+ modelId: "glm-5.3-flash",+ displayName: "GLM-5.3 Flash",+ provider: "tokendance",+ contextWindow: 1000000,+ pricing: cny(0.23, 0.8, 2.8),+ supportsVision: true,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },+ {+ modelId: "kimi-k3",+ displayName: "Kimi K3",+ provider: "tokendance",+ contextWindow: 1048576,+ pricing: cny(2, 20, 100),+ supportsVision: true,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },+ {+ modelId: "qwen3.8-max",+ displayName: "Qwen 3.8 Max",+ provider: "tokendance",+ contextWindow: 1000000,+ pricing: cny(1.5, 12, 36),+ supportsVision: true,+ clientType: "openai-chat",+ baseUrl: TOKENDANCE_BASE_URL,+ },// -- Qwen Token Plan (subscription gateway; vision flags per the plan's supported-model// table). Pricing and context windows from each model's page at// www.qianwenai.com/models/<id> (official CNY list prices; limited-time promotions such as@@ -1518,6 +1649,7 @@ export function modelHomepageUrl(provider: string, modelId: string): string | un? `https://app.fireworks.ai/models/${m[1]}/${m[2]}`: providerInfo(provider)?.modelsUrl;}+ if (provider === "tokendance") return `https://tokendance.space/models/${modelId}`;if (provider === "qwen-pay-as-you-go") {return `https://www.qianwenai.com/models/${encodeURIComponent(modelId)}`;}@@ -1535,3 +1667,74 @@ export function modelHomepageUrl(provider: string, modelId: string): string | unif (provider === "custom") return undefined;return providerInfo(provider)?.modelsUrl;}++/**+ * App attribution: how the harness identifies itself to gateways that rank or report the apps+ * calling them. Both values describe PenguinHarness itself, never a model or an account.+ *+ * `APP_URL` is also the `app_url` a provider OAuth flow stamps onto the key it mints, which is+ * why it is exported: a stable app URL is required there, and a second copy would let the two+ * attributions drift apart.+ */+export const APP_URL = "https://penguin.ooo/";+const APP_TITLE = "PenguinHarness";+/**+ * OpenRouter marketplace categories, comma-separated. OpenRouter accepts at most **two per+ * request** from a fixed slug list and silently drops anything else, so this string is+ * exactly two recognised slugs.+ */+const OPENROUTER_CATEGORIES = "cli-agent,personal-agent";++/**+ * Lowercase host of a base URL; undefined when it is blank or unparseable. A fully-qualified+ * trailing dot is stripped: `URL` keeps it in `hostname`, but `openrouter.ai.` names the same+ * server as `openrouter.ai` and has to match the same way. Stripping cannot widen the match —+ * a suffix-anchored comparison rejects `openrouter.ai.attacker.com` with or without the dot.+ */+function endpointHost(baseUrl: string | undefined): string | undefined {+ if (!baseUrl?.trim()) return undefined;+ try {+ return new URL(baseUrl).hostname.toLowerCase().replace(/\.$/, "");+ } catch {+ return undefined;+ }+}++/** Host equality extended to subdomains; suffix-anchored, so `notopenrouter.ai` never matches. */+function hostMatches(host: string, domain: string): boolean {+ return host === domain || host.endsWith(`.${domain}`);+}++/**+ * Attribution headers for a request's base URL, or undefined when that endpoint runs no+ * attribution scheme (every direct vendor, and every gateway that does not read one).+ *+ * Keyed on the endpoint host rather than on the catalog's provider group, because the group+ * is a display bucket while the headers are a property of the server being called: a `custom`+ * entry pointed at OpenRouter is still PenguinHarness talking to OpenRouter and is attributed+ * identically. The flip side is that an entry carrying no `base_url` of its own gets no+ * headers even when `OPENAI_BASE_URL` sends it to a gateway — that variable is read inside+ * AgentHub and never reaches this side.+ *+ * - OpenRouter (https://openrouter.ai/docs/app-attribution): `HTTP-Referer` is the identity+ * that creates the app page and drives the rankings, `X-OpenRouter-Title` is its display+ * name, `X-OpenRouter-Categories` files it under marketplace categories.+ * - TokenDance (https://tokendance.space/docs/app-attribution): `X-App-URL` alone, and it+ * takes priority over any App URL recorded on the API key — the same key may be in use by+ * other tools, so the per-request value is the accurate one.+ */+export function attributionHeaders(+ baseUrl: string | undefined,+): Record<string, string> | undefined {+ const host = endpointHost(baseUrl);+ if (!host) return undefined;+ if (hostMatches(host, "openrouter.ai")) {+ return {+ "HTTP-Referer": APP_URL,+ "X-OpenRouter-Title": APP_TITLE,+ "X-OpenRouter-Categories": OPENROUTER_CATEGORIES,+ };+ }+ if (hostMatches(host, "tokendance.space")) return { "X-App-URL": APP_URL };+ return undefined;+}diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.tsindex 7852e1b5..520eeec7 100644--- a/packages/core/test/model-catalog.test.ts+++ b/packages/core/test/model-catalog.test.ts@@ -4,11 +4,13 @@*/import { describe, expect, it } from "vitest";import {+ APP_URL,MODEL_CATALOG,MODEL_PROVIDERS,canonicalClientType,modelHomepageUrl,catalogEntryFor,+ attributionHeaders,presetModelEntries,providerInfo,fastModeProtocol,@@ -24,21 +26,22 @@ describe("model-catalog", () => {expect(new Set(pairs).size).toBe(pairs.length);const ids = MODEL_CATALOG.map((m) => m.modelId);expect(MODEL_CATALOG[0]!.provider).toBe("deepseek");- // Group order: DeepSeek first, followed by the gateway and first-party groups, with- // MiniMax immediately before custom.+ // Group order is hand-curated, interleaving gateways and first-party vendors: DeepSeek+ // first (the default model's provider) and custom always last.expect(MODEL_PROVIDERS.map((p) => p.id)).toEqual(["deepseek","openrouter","fireworks",- "siliconflow",- "qwen-token-plan",- "qwen-pay-as-you-go","google",- "anthropic","openai",+ "anthropic",+ "siliconflow",+ "tokendance","zhipu","moonshot","minimax",+ "qwen-pay-as-you-go",+ "qwen-token-plan","custom",]);expect(providerInfo("siliconflow")!.label).toBe("SiliconFlow");@@ -80,6 +83,23 @@ describe("model-catalog", () => {}});+ it("TokenDance is the only group publishing a key-minting flow, and both its endpoints are https", () => {+ const withOAuth = MODEL_PROVIDERS.filter((p) => p.oauth !== undefined).map((p) => p.id);+ expect(withOAuth).toEqual(["tokendance"]);+ const oauth = providerInfo("tokendance")!.oauth!;+ expect(oauth.authorizeUrl).toBe("https://tokendance.space/auth");+ expect(oauth.exchangeUrl).toBe("https://tokendance.space/portal/api/v1/auth/keys");+ // The key's name is also the app name the authorization page shows.+ expect(oauth.keyName).toBe("PenguinHarness");+ });++ it("the app URL a minted key is stamped with is the same one attribution headers carry", () => {+ expect(APP_URL).toBe("https://penguin.ooo/");+ expect(attributionHeaders("https://tokendance.space/gateway/v1")).toEqual({+ "X-App-URL": APP_URL,+ });+ });+it("every entry has valid three-bucket pricing; context_window is a positive integer", () => {for (const m of MODEL_CATALOG) {if (m.modelId.endsWith(":free") || m.modelId === "openrouter/free") {@@ -273,6 +293,35 @@ describe("model-catalog", () => {["qwen3.8-max", true],["qwen3.7-plus", true],]);+ const td = MODEL_CATALOG.filter((m) => m.provider === "tokendance");+ // Dictionary order by upstream id; vision flags and context windows from TokenDance's+ // public catalog API.+ expect(td.map((m) => [m.modelId, m.contextWindow, m.supportsVision])).toEqual([+ ["deepseek-v4-flash-0731", 1048576, false],+ ["deepseek-v4-flash-vision-exp", 1000000, true],+ ["deepseek-v4-pro-0813", 1000000, false],+ ["glm-5.3", 1000000, false],+ ["glm-5.3-flash", 1000000, true],+ ["kimi-k3", 1048576, true],+ ["qwen3.8-max", 1000000, true],+ ]);+ for (const m of td) {+ expect(m.clientType).toBe("openai-chat");+ expect(m.baseUrl).toBe("https://tokendance.space/gateway/v1");+ }+ // The gateway's own CNY LIST rates throughout, promotion or not: qwen3.8-max at+ // 1.5 / 12 / 36 CNY while a 20% off runs, glm-5.3-flash at 0.23 / 0.8 / 2.8 CNY while a+ // 50% off runs; no other row carries a promotion, so list price and billed rate coincide+ // for the rest.+ const tdQwen = td.find((m) => m.modelId === "qwen3.8-max")!.pricing!;+ expect([tdQwen.cache_read, tdQwen.cache_write, tdQwen.output]).toEqual([+ 0.214286, 1.714286, 5.142857,+ ]);+ // cache_write carries the input price: TokenDance charges no separate cache-write fee.+ const tdFlash = td.find((m) => m.modelId === "glm-5.3-flash")!.pricing!;+ expect([tdFlash.cache_read, tdFlash.cache_write, tdFlash.output]).toEqual([+ 0.032857, 0.114286, 0.4,+ ]);const qpayg = MODEL_CATALOG.filter((m) => m.provider === "qwen-pay-as-you-go");expect(qpayg.map((m) => [m.modelId, m.supportsVision])).toEqual([["deepseek-v4-flash-0731", false],@@ -314,6 +363,7 @@ describe("model-catalog", () => {"openrouter","fireworks","siliconflow",+ "tokendance","qwen-token-plan","qwen-pay-as-you-go","custom",@@ -331,10 +381,12 @@ describe("model-catalog", () => {"https://dashscope.aliyuncs.com/compatible-mode/v1",);expect(providerInfo("fireworks")!.gatewayBaseUrl).toBe("https://api.fireworks.ai/inference/v1");+ expect(providerInfo("tokendance")!.gatewayBaseUrl).toBe("https://tokendance.space/gateway/v1");const GATEWAYS = ["openrouter","fireworks","siliconflow",+ "tokendance","qwen-token-plan","qwen-pay-as-you-go",];@@ -343,7 +395,7 @@ describe("model-catalog", () => {expect(p.gatewayBaseUrl, p.id).toBeUndefined();}}- const gateway = [...or, ...fw, ...sf, ...qtp, ...qpayg];+ const gateway = [...or, ...fw, ...sf, ...td, ...qtp, ...qpayg];// Pricing (USD, per the 2026-08-03 models-API re-read): MiMo v2.5 and Hy3 publish a real// cache-hit price and no per-token write premium, so cache_write carries the input price.const mimo = MODEL_CATALOG.find((m) => m.modelId === "xiaomi/mimo-v2.5")!.pricing!;@@ -772,6 +824,9 @@ describe("resolveModelEnv (PRN-021: env fallback resolved by AgentHub routing ruexpect(modelHomepageUrl("qwen-token-plan", "qwen3.8-max")).toBe("https://www.qianwenai.com/models/qwen3.8-max",);+ expect(modelHomepageUrl("tokendance", "glm-5.3")).toBe(+ "https://tokendance.space/models/glm-5.3",+ );// Direct vendors link to the vendor's model docs page.expect(modelHomepageUrl("deepseek", "deepseek-v4-pro")).toBe("https://api-docs.deepseek.com/quick_start/pricing",@@ -895,3 +950,53 @@ describe("fastModeProtocol (which models may be offered AgentHub's fast_mode, anexpect(verdictOf("minimax", "MiniMax-M3")).toBe("openai");});});++describe("attributionHeaders (how the harness names itself to the gateways that read it)", () => {+ it("OpenRouter gets its three attribution headers, on the preset base URL and on any custom one", () => {+ const expected = {+ "HTTP-Referer": "https://penguin.ooo/",+ "X-OpenRouter-Title": "PenguinHarness",+ "X-OpenRouter-Categories": "cli-agent,personal-agent",+ };+ expect(attributionHeaders(providerInfo("openrouter")!.gatewayBaseUrl)).toEqual(expected);+ // The host decides, not the catalog: an entry filed under custom that points at the same+ // gateway is the same app calling it.+ expect(attributionHeaders("https://openrouter.ai/api/v1/")).toEqual(expected);+ // `URL` keeps a fully-qualified trailing dot in `hostname`; it names the same server.+ expect(attributionHeaders("https://openrouter.ai./api/v1")).toEqual(expected);+ // OpenRouter accepts at most two categories per request and drops anything unrecognised.+ expect(expected["X-OpenRouter-Categories"].split(",")).toHaveLength(2);+ });++ it("TokenDance gets the single X-App-URL header", () => {+ expect(attributionHeaders(providerInfo("tokendance")!.gatewayBaseUrl)).toEqual({+ "X-App-URL": "https://penguin.ooo/",+ });+ });++ it("every other endpoint gets no extra headers, and a blank or unparseable base URL is inert", () => {+ expect(attributionHeaders("https://api.deepseek.com")).toBeUndefined();+ expect(attributionHeaders("https://api.siliconflow.cn/v1")).toBeUndefined();+ expect(attributionHeaders(undefined)).toBeUndefined();+ expect(attributionHeaders(" ")).toBeUndefined();+ expect(attributionHeaders("not a url")).toBeUndefined();+ // Suffix-anchored host matching: a lookalike domain is not the gateway.+ expect(attributionHeaders("https://notopenrouter.ai/api/v1")).toBeUndefined();+ expect(attributionHeaders("https://tokendance.space.example.com/v1")).toBeUndefined();+ // Stripping the trailing dot must not widen that anchoring.+ expect(attributionHeaders("https://openrouter.ai.attacker.com./v1")).toBeUndefined();+ });++ it("catalog invariant: every gateway row whose host runs an attribution scheme carries it", () => {+ for (const m of MODEL_CATALOG) {+ const headers = attributionHeaders(m.baseUrl);+ if (m.provider === "openrouter") {+ expect(headers?.["HTTP-Referer"], m.modelId).toBe("https://penguin.ooo/");+ } else if (m.provider === "tokendance") {+ expect(headers?.["X-App-URL"], m.modelId).toBe("https://penguin.ooo/");+ } else {+ expect(headers, `${m.provider}/${m.modelId}`).toBeUndefined();+ }+ }+ });+});diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.mdindex 4df400a8..fe5904e1 100644--- a/packages/docs/content/configuration.en.md+++ b/packages/docs/content/configuration.en.md@@ -34,13 +34,13 @@ When a model entry has no inline `api_key`, AgentHub falls back to the provider'| --- | --- | --- || deepseek | `DEEPSEEK_API_KEY` | `DEEPSEEK_BASE_URL` || anthropic | `ANTHROPIC_API_KEY` | `ANTHROPIC_BASE_URL` |-| openai, openrouter, fireworks, siliconflow, qwen-token-plan, qwen-pay-as-you-go, custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |+| openai, openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` || minimax | `MINIMAX_API_KEY` | `MINIMAX_BASE_URL` || google | `GEMINI_API_KEY` | `GEMINI_BASE_URL` || zhipu | `ZAI_API_KEY` | `ZAI_BASE_URL` || moonshot | `MOONSHOT_API_KEY` | `MOONSHOT_BASE_URL` |-The openrouter, fireworks, siliconflow, qwen-token-plan, qwen-pay-as-you-go, and custom groups speak the OpenAI-compatible protocol, hence the shared `OPENAI_*` variables. The direct MiniMax M3 Responses client uses `MINIMAX_*`; the built-in MiniMax preset already pins the official endpoint. Provider groups and the built-in model catalog are covered in [Models & Providers](/models).+The openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, and custom groups speak the OpenAI-compatible protocol, hence the shared `OPENAI_*` variables. The direct MiniMax M3 Responses client uses `MINIMAX_*`; the built-in MiniMax preset already pins the official endpoint. Provider groups and the built-in model catalog are covered in [Models & Providers](/models).## Project configdiff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.mdindex 4e6b84f8..305dac6f 100644--- a/packages/docs/content/configuration.zh.md+++ b/packages/docs/content/configuration.zh.md@@ -34,13 +34,13 @@ CLI 与服务端启动时会自动加载工作目录下的 `.env` 文件。| --- | --- | --- || deepseek | `DEEPSEEK_API_KEY` | `DEEPSEEK_BASE_URL` || anthropic | `ANTHROPIC_API_KEY` | `ANTHROPIC_BASE_URL` |-| openai、openrouter、fireworks、siliconflow、qwen-token-plan、qwen-pay-as-you-go、custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |+| openai、openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` || minimax | `MINIMAX_API_KEY` | `MINIMAX_BASE_URL` || google | `GEMINI_API_KEY` | `GEMINI_BASE_URL` || zhipu | `ZAI_API_KEY` | `ZAI_BASE_URL` || moonshot | `MOONSHOT_API_KEY` | `MOONSHOT_BASE_URL` |-openrouter、fireworks、siliconflow、qwen-token-plan、qwen-pay-as-you-go 与 custom 分组走 OpenAI 兼容协议,因此复用 `OPENAI_*` 变量。直连 MiniMax M3 Responses 客户端使用 `MINIMAX_*`;内置 MiniMax 预设已固定官方端点。Provider 分组与内置模型目录见[模型与 Provider](/models)。+openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan 与 custom 分组走 OpenAI 兼容协议,因此复用 `OPENAI_*` 变量。直连 MiniMax M3 Responses 客户端使用 `MINIMAX_*`;内置 MiniMax 预设已固定官方端点。Provider 分组与内置模型目录见[模型与 Provider](/models)。## Project 配置diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.mdindex e2d7901e..0c551ddf 100644--- a/packages/docs/content/models.en.md+++ b/packages/docs/content/models.en.md@@ -62,22 +62,48 @@ Built-in groups and their env-var fallbacks (catalog source: `packages/core/src/| deepseek | `DEEPSEEK_API_KEY` | Group of the default model || openrouter | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://openrouter.ai/api/v1` || fireworks | `OPENAI_API_KEY` | Fireworks AI (OpenAI-compatible), preset base URL `https://api.fireworks.ai/inference/v1`; API model ids look like `accounts/fireworks/models/<slug>` |-| siliconflow | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://api.siliconflow.cn/v1` |-| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan subscription gateway, preset base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`; pricing from each model page's official list price (the preview model has only a quota-multiplier promo, no list price) |-| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen pay-as-you-go (DashScope's OpenAI-compatible endpoint), preset base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`; resold third-party models keep vendor-prefixed ids (e.g. `kimi/kimi-k3`) || google | `GEMINI_API_KEY` | |-| anthropic | `ANTHROPIC_API_KEY` | || openai | `OPENAI_API_KEY` | |+| anthropic | `ANTHROPIC_API_KEY` | |+| siliconflow | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://api.siliconflow.cn/v1` |+| tokendance | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://tokendance.space/gateway/v1`; model ids are bare, with no vendor prefix (e.g. `glm-5.3`, `kimi-k3`); pricing is the gateway's own CNY rates || zhipu | `ZAI_API_KEY` | || moonshot | `MOONSHOT_API_KEY` | || minimax | `MINIMAX_API_KEY` | Direct MiniMax M3 Responses client (`client_type = "minimax-m3"`): `MiniMax-M3` with a 1,000,000-token context window and vision; preset base URL `https://api.minimax.io/v1`; accepts a Token Plan Subscription Key or pay-as-you-go API key |+| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen pay-as-you-go (DashScope's OpenAI-compatible endpoint), preset base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`; resold third-party models keep vendor-prefixed ids (e.g. `kimi/kimi-k3`) |+| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan subscription gateway, preset base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`; pricing from each model page's official list price (the preview model has only a quota-multiplier promo, no list price) || custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint |-The gateway groups (openrouter / fireworks / siliconflow / qwen-token-plan / qwen-pay-as-you-go) go through AgentHub's generic OpenAI-protocol clients, so with blank credentials they read `OPENAI_API_KEY` — not a gateway-specific variable. Most gateway presets pin the Chat Completions client (`client_type = "openai-chat"`); the OpenRouter `openai/*` presets pin the Responses client (`client_type = "openai-responses"`) instead, because OpenRouter serves the Responses API at the same base URL and those rows' upstream is OpenAI itself. Both clients read the same `OPENAI_*` variables, so the credential rules are identical either way. The direct MiniMax M3 client reads `MINIMAX_API_KEY`. The built-in MiniMax preset pins `https://api.minimax.io/v1`; `MINIMAX_BASE_URL` is consulted only for entries without an inline `base_url`. M3 pricing records MiniMax's standard pay-as-you-go tier at 512K input tokens or below; every rate doubles above that and the priority tier is 1.5x, so long-context and priority usage is underestimated — the same base-tier convention already used for OpenAI (>272K) and Gemini 3.1 Pro (>200K).+The gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan) go through AgentHub's generic OpenAI-protocol clients, so with blank credentials they read `OPENAI_API_KEY` — not a gateway-specific variable. Most gateway presets pin the Chat Completions client (`client_type = "openai-chat"`); the OpenRouter `openai/*` presets pin the Responses client (`client_type = "openai-responses"`) instead, because OpenRouter serves the Responses API at the same base URL and those rows' upstream is OpenAI itself. Both clients read the same `OPENAI_*` variables, so the credential rules are identical either way. The direct MiniMax M3 client reads `MINIMAX_API_KEY`. The built-in MiniMax preset pins `https://api.minimax.io/v1`; `MINIMAX_BASE_URL` is consulted only for entries without an inline `base_url`. M3 pricing records MiniMax's standard pay-as-you-go tier at 512K input tokens or below; every rate doubles above that and the priority tier is 1.5x, so long-context and priority usage is underestimated — the same base-tier convention already used for OpenAI (>272K) and Gemini 3.1 Pro (>200K).The preset catalog also carries OpenRouter's free tier: the `:free` model variant `nvidia/nemotron-3-ultra-550b-a55b:free` and the `openrouter/free` unified Free Models Router. They cost nothing, but are subject to OpenRouter's free-tier rate limits and data policy.-Some models in the preset catalog: deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp (the DeepSeek group's only vision-capable model), MiniMax-M3, gemini-3.7-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, qwen3.8-max / qwen3.8-flash (not exhaustive). The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group prices record the official off-peak tier (peak hours, Beijing 9:00–12:00 and 14:00–18:00, bill double). `glm-5.3-flash` appears twice, and both rows accept images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), and the OpenRouter row `z-ai/glm-5.3-flash` goes through the generic OpenAI-compatible client, which carries them for any id. What the two rows do not share is the price — the direct row records Z.AI's list price and the OpenRouter row the discounted rate the gateway bills, so they disagree while a promotion is running.+Some models in the preset catalog: deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp (the DeepSeek group's only vision-capable model), MiniMax-M3, gemini-3.7-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, qwen3.8-max / qwen3.8-flash (not exhaustive). The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group prices record the official off-peak tier (peak hours, Beijing 9:00–12:00 and 14:00–18:00, bill double). `glm-5.3-flash` appears three times, and all three rows accept images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), while the OpenRouter row `z-ai/glm-5.3-flash` and the TokenDance row go through the generic OpenAI-compatible client, which carries them for any id. What the three rows do not share is the price — the direct row records Z.AI's list price, the TokenDance row TokenDance's, and the OpenRouter row the discounted rate that gateway bills, so they disagree while a promotion is running.++## App attribution++Some gateways read a request header that files a call under the app that made it, feeding their own app rankings and usage reports. The catalog decides those headers by **endpoint host**, not by the entry's provider group: an entry filed under custom whose base URL points at such a gateway carries the same headers. Only the entry's own `base_url` is consulted — an endpoint supplied through `OPENAI_BASE_URL` is resolved inside AgentHub, is not visible on this side, and is therefore not attributed.++| Endpoint | Header | Value |+| --- | --- | --- |+| `openrouter.ai` | `HTTP-Referer` | `https://penguin.ooo/` |+| `openrouter.ai` | `X-OpenRouter-Title` | `PenguinHarness` |+| `openrouter.ai` | `X-OpenRouter-Categories` | `cli-agent,personal-agent` |+| `tokendance.space` | `X-App-URL` | `https://penguin.ooo/` |++Every other endpoint — every direct vendor, and every gateway that reads no such header — receives no extra headers at all. The headers state the app's identity only; they carry nothing about the user, the Agent or the Session.++## Authorizing a new API key++A provider that publishes an authorization flow puts an extra action on its group header in the models page: **Authorize key**. TokenDance is the one built-in group that does. It creates a **new** key on your account — it does not read a key you already have — and writes it to every model in that group, replacing whatever key those entries carry.++Pressing it opens the provider's authorization page in a new tab. Authorize there and the provider sends the browser back to PenguinHarness, which redeems the one-time code and saves the key; the tab you started from reports the result on its own. The same app URL the attribution table above lists is stamped onto the key, so calls made with it stay attributed even from another tool.++The exchange runs entirely on the server: the PKCE verifier is generated there and never reaches the browser, and the minted key goes straight into the model table without passing through it. An authorization is good for one key and expires in ten minutes.++Where the redirect cannot come back — a desktop window that hands external links to the system browser, or a server the browser cannot reach on the address it was given — pick **Page can't redirect back? Enter the code by hand**. The authorization page then displays a one-time code instead of redirecting, and pasting it into the dialog finishes the same flow.++Only the Project owner can start or finish an authorization. The full key is shown once and never again, so if saving it fails you have to authorize again and delete the unused key in the provider's console.## Local / self-hosted OpenAI-compatible endpoints (e.g. vLLM)diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.mdindex 97e26ddc..78fbe70d 100644--- a/packages/docs/content/models.zh.md+++ b/packages/docs/content/models.zh.md@@ -62,22 +62,48 @@ api_key = "sk-..."| deepseek | `DEEPSEEK_API_KEY` | 默认模型所在分组 || openrouter | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://openrouter.ai/api/v1` || fireworks | `OPENAI_API_KEY` | Fireworks AI(OpenAI 兼容),预置 base URL `https://api.fireworks.ai/inference/v1`;API 模型 id 形如 `accounts/fireworks/models/<slug>` |-| siliconflow | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://api.siliconflow.cn/v1` |-| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan 订阅网关,预置 base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`;定价取各模型页官方牌价(预览模型仅配额倍率促销、无牌价) |-| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen 按量付费(DashScope OpenAI 兼容端),预置 base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`;转售第三方模型保留厂商前缀 id(如 `kimi/kimi-k3`) || google | `GEMINI_API_KEY` | |-| anthropic | `ANTHROPIC_API_KEY` | || openai | `OPENAI_API_KEY` | |+| anthropic | `ANTHROPIC_API_KEY` | |+| siliconflow | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://api.siliconflow.cn/v1` |+| tokendance | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://tokendance.space/gateway/v1`;模型 id 为不带厂商前缀的裸 id(如 `glm-5.3`、`kimi-k3`);价格取该网关自己的 CNY 牌价 || zhipu | `ZAI_API_KEY` | || moonshot | `MOONSHOT_API_KEY` | || minimax | `MINIMAX_API_KEY` | 直连 MiniMax M3 Responses 客户端(`client_type = "minimax-m3"`):`MiniMax-M3` 支持 1,000,000 Token 上下文和视觉输入;预置 base URL `https://api.minimax.io/v1`;接受 Token Plan Subscription Key 或按量付费 API Key |+| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen 按量付费(DashScope OpenAI 兼容端),预置 base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`;转售第三方模型保留厂商前缀 id(如 `kimi/kimi-k3`) |+| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan 订阅网关,预置 base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`;定价取各模型页官方牌价(预览模型仅配额倍率促销、无牌价) || custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点 |-网关分组(openrouter / fireworks / siliconflow / qwen-token-plan / qwen-pay-as-you-go)经 AgentHub 的通用 OpenAI 协议客户端请求,因此凭证留空时读取的是 `OPENAI_API_KEY`,而非网关自己的变量名。多数网关预置固定 Chat Completions 客户端(`client_type = "openai-chat"`);OpenRouter 的 `openai/*` 预置则固定 Responses 客户端(`client_type = "openai-responses"`)——OpenRouter 在同一 base URL 上提供 Responses API,且这些条目的上游本就是 OpenAI。两种客户端读取相同的 `OPENAI_*` 变量,凭证规则完全一致。直连 MiniMax M3 客户端读取 `MINIMAX_API_KEY`。内置 MiniMax 预设固定使用 `https://api.minimax.io/v1`;仅当模型条目未内联 `base_url` 时才读取 `MINIMAX_BASE_URL`。M3 价格取 MiniMax 按量付费的标准档、输入不超过 512K Token 的牌价;超过 512K 后各档价格翻倍,priority 档另为 1.5 倍,因此长上下文与 priority 用量会被低估——与 OpenAI(>272K)、Gemini 3.1 Pro(>200K)沿用的基准档口径一致。+网关分组(openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan)经 AgentHub 的通用 OpenAI 协议客户端请求,因此凭证留空时读取的是 `OPENAI_API_KEY`,而非网关自己的变量名。多数网关预置固定 Chat Completions 客户端(`client_type = "openai-chat"`);OpenRouter 的 `openai/*` 预置则固定 Responses 客户端(`client_type = "openai-responses"`)——OpenRouter 在同一 base URL 上提供 Responses API,且这些条目的上游本就是 OpenAI。两种客户端读取相同的 `OPENAI_*` 变量,凭证规则完全一致。直连 MiniMax M3 客户端读取 `MINIMAX_API_KEY`。内置 MiniMax 预设固定使用 `https://api.minimax.io/v1`;仅当模型条目未内联 `base_url` 时才读取 `MINIMAX_BASE_URL`。M3 价格取 MiniMax 按量付费的标准档、输入不超过 512K Token 的牌价;超过 512K 后各档价格翻倍,priority 档另为 1.5 倍,因此长上下文与 priority 用量会被低估——与 OpenAI(>272K)、Gemini 3.1 Pro(>200K)沿用的基准档口径一致。预置目录还收录了 OpenRouter 的免费档:`:free` 模型变体 `nvidia/nemotron-3-ultra-550b-a55b:free` 与统一路由 `openrouter/free`(Free Models Router),零成本可用,但受 OpenRouter 免费档速率限制与数据政策约束。-预置目录中的部分模型:deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp(DeepSeek 分组中唯一支持图像输入的模型)、MiniMax-M3、gemini-3.7-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash 等(非完整清单)。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的价格记录官方低谷时段档(高峰时段——北京时间 9:00–12:00、14:00–18:00——按双倍计费)。`glm-5.3-flash` 收录了两份,两条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而 OpenRouter 上的 `z-ai/glm-5.3-flash` 走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。两条不一致的是价格——直连条目记 Z.AI 牌价,OpenRouter 条目记网关实际计费的折后价,因此促销期间两者不同。+预置目录中的部分模型:deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp(DeepSeek 分组中唯一支持图像输入的模型)、MiniMax-M3、gemini-3.7-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash 等(非完整清单)。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的价格记录官方低谷时段档(高峰时段——北京时间 9:00–12:00、14:00–18:00——按双倍计费)。`glm-5.3-flash` 收录了三份,三条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而 OpenRouter 上的 `z-ai/glm-5.3-flash` 与 TokenDance 分组的同名条目走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。三条不一致的是价格——直连条目记 Z.AI 牌价,TokenDance 条目记 TokenDance 牌价,OpenRouter 条目记该网关实际计费的折后价,因此促销期间三者不同。++## 应用归因++部分网关会读取一个请求头,把调用归到发起它的应用名下,用于自己的应用榜单与用量报告。这类请求头由目录按**端点主机名**决定,与条目所在的 Provider 分组无关:一个填在 custom 分组、但 base URL 指向该网关的条目,同样会带上归因头。判断只看条目自己的 `base_url`——从 `OPENAI_BASE_URL` 读到的端点在 AgentHub 内部解析,这一侧看不到,因此不会归因。++| 端点 | 请求头 | 取值 |+| --- | --- | --- |+| `openrouter.ai` | `HTTP-Referer` | `https://penguin.ooo/` |+| `openrouter.ai` | `X-OpenRouter-Title` | `PenguinHarness` |+| `openrouter.ai` | `X-OpenRouter-Categories` | `cli-agent,personal-agent` |+| `tokendance.space` | `X-App-URL` | `https://penguin.ooo/` |++其余端点(所有直连厂商,以及不读归因头的网关)不会收到任何额外请求头。归因头只声明应用身份,不携带用户、Agent 或会话信息。++## 授权新建 API key++若某个供应商公开了授权流程,模型页的该分组头部会多出一个动作:**自动获取密钥**。内置分组中只有 TokenDance 提供。它会在你的账户下**新建**一个 key,而不是读取你已有的 key,并写入该分组下的每一个模型,覆盖这些条目当前的 key。++点击后会在新标签页打开供应商的授权页。在那里完成授权,供应商会把浏览器送回 PenguinHarness,由服务端兑换一次性授权码并保存 key;发起的那个标签页会自行报告结果。上文归因表中的同一个应用 URL 会写到这个 key 上,因此即便换用其他工具,用它发出的调用依然带着归因。++整个兑换过程都在服务端进行:PKCE 的 verifier 在服务端生成、从不进入浏览器,新建出的 key 也直接写入模型表,不经过浏览器。一次授权只能换一个 key,且十分钟后过期。++如果跳转回不来——桌面窗口会把外部链接交给系统浏览器,或者浏览器根本访问不到那个地址的服务——请选择**授权页跳不回来?改为手动填写授权码**。授权页会改为显示一次性授权码,粘贴到对话框即可完成同一套流程。++只有 Project owner 能发起或完成授权。完整的 key 只会出现一次,因此一旦保存失败,需要重新授权,并到供应商控制台删掉那个没用上的 key。## 本地 / 自建 OpenAI 兼容端点(如 vLLM)diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 539beb7f..e400cd6a 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -129,6 +129,19 @@ Every endpoint that names a model takes the complete `(provider, modelId)` pair.`PUT /models` also invalidates the Project's cached Session runtimes (same effective-value semantics as a vault update): no hot swap into a run already in flight, but the next Task on any Session of the Project re-resumes and reads the new `api_key` / `base_url`. It additionally publishes a `credentials_updated` event to the Project's open Session channels (see Streaming below), and the models response carries `updatedAt` (the config file's mtime) — the Web App compares it against the last auth failure to decide whether an auth-dead composer should stay disabled.+#### Provider key minting++Owner-only. A provider group that publishes an authorization flow in the built-in catalog can mint a **new** API key for the user in the browser, instead of the user copying one out of a console.++| Method | Path | Description |+| --- | --- | --- |+| POST | /api/projects/:projectId/model-oauth/start | Open a flow: `{provider, mode?: callback\|manual}` → `{flowId, authorizeUrl}` |+| GET | /api/projects/:projectId/model-oauth/callback | Where the provider redirects (`?flow=&code=`); exchanges, applies the key, answers an HTML page |+| GET | /api/projects/:projectId/model-oauth/:flowId | Poll a flow: `{status: pending\|done\|error, provider, error?}` |+| POST | /api/projects/:projectId/model-oauth/:flowId/code | Redeem a code the user pasted: `{code}` → `{ok, applied?, error?}` |++The PKCE verifier is generated server-side, held in memory for ten minutes, and never sent to a client; the minted key goes straight into the provider group's models and is never returned, logged, or put in a URL. A flow belongs to one user in one Project and is single-use — anyone else's request, and any second redemption, is refused. `mode: manual` omits the callback so the authorization page shows a one-time code to carry back by hand, for deployments the redirect cannot reach. A completed flow invalidates cached runtimes and publishes `credentials_updated`, exactly as `PUT /models` does.+### AgentsThe paths below omit the `/api/projects/:projectId` prefix.@@ -338,7 +351,7 @@ export type ServerEvent =| session_title | The model-generated title after the first turn has been persisted || session_state | The user-channel counterpart of `task_state`: the same run-state flip, named by `sessionId`, so a Session list stays live for every row and not only the conversation a client has open. Carries the row fields needed to redraw it without refetching — `lastActiveAt` as just stamped, and `hasTrace` (true whenever the state is running or compacting, since a Session that is running has by definition started a Task). Published to the user channels of the Project's owner and members || resync_required | The Last-Event-ID was evicted from the buffer; the client must refetch history |-| credentials_updated | The Project's model credentials changed (`PUT /models`): cached runtimes were invalidated, so the client clears any auth-dead composer state |+| credentials_updated | The Project's model credentials changed (`PUT /models`, or a completed key-minting flow): cached runtimes were invalidated, so the client clears any auth-dead composer state || hello | Handshake on the user channel || session_created | A new Session was registered (e.g. a subagent session) || schedule_fired | A scheduled task fired and was delivered |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 0fc2ff62..5b7d892d 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -129,6 +129,19 @@ curl -c cookies.txt -H "Content-Type: application/json" \`PUT /models` 同时会使该 Project 已缓存的 Session 运行时失效(与 vault 更新同一套生效语义):进行中的运行不做热替换,但该 Project 下任何 Session 的下一个 Task 都会重新装载并读到新的 `api_key` / `base_url`。它还会向该 Project 已打开的 Session 通道发布 `credentials_updated` 事件(见下文「流式推送」),且模型响应携带 `updatedAt`(配置文件 mtime)——Web App 用它与最近一次鉴权失败的时间比较,决定鉴权失败的输入框是否继续禁用。+#### 授权新建 API key++仅限 Owner。若某个供应商分组在内置目录中声明了授权流程,用户可以在浏览器里授权并**新建**一个 API key,不必再去控制台复制。++| 方法 | 路径 | 说明 |+| --- | --- | --- |+| POST | /api/projects/:projectId/model-oauth/start | 开启一次流程:`{provider, mode?: callback\|manual}` → `{flowId, authorizeUrl}` |+| GET | /api/projects/:projectId/model-oauth/callback | 供应商跳回的地址(`?flow=&code=`):兑换、写入 key,并返回一个 HTML 页面 |+| GET | /api/projects/:projectId/model-oauth/:flowId | 轮询流程状态:`{status: pending\|done\|error, provider, error?}` |+| POST | /api/projects/:projectId/model-oauth/:flowId/code | 兑换用户粘贴的授权码:`{code}` → `{ok, applied?, error?}` |++PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不下发到客户端;新建出的 key 直接写入该分组的模型,不回传、不记录日志、也不出现在 URL 中。一次流程只属于某个 Project 下的某个用户且只能用一次——其他人的请求、以及第二次兑换,都会被拒绝。`mode: manual` 不传回调地址,授权页改为显示一次性授权码供用户手动带回,适用于跳转回不来的部署。流程完成后同样会使缓存的运行时失效并发布 `credentials_updated`,与 `PUT /models` 一致。+### Agent以下路径均省略前缀 `/api/projects/:projectId`。@@ -335,7 +348,7 @@ export type ServerEvent =| session_title | 首轮后模型生成的标题已持久化 || session_state | `task_state` 在用户通道上的对应事件:同一次运行状态翻转,带上 `sessionId`,因此会话列表的每一行都能保持实时,而不只是客户端当前打开的那个会话。事件还携带重绘该行所需的行字段,无需重新拉取列表 —— 刚刚写入的 `lastActiveAt`,以及 `hasTrace`(状态为 running 或 compacting 时必为 true,因为正在运行的会话必然已经启动过 Task)。仅发往该 Project 拥有者与成员的用户通道 || resync_required | Last-Event-ID 已被缓冲区淘汰,客户端须重新拉取历史 |-| credentials_updated | Project 模型凭据已变更(`PUT /models`):缓存运行时已失效,客户端应清除鉴权失败的输入框禁用态 |+| credentials_updated | Project 模型凭据已变更(`PUT /models`,或一次完成的授权新建 key 流程):缓存运行时已失效,客户端应清除鉴权失败的输入框禁用态 || hello | 用户通道连接握手 || session_created | 新 Session 注册(如子 Agent 会话) || schedule_fired | 定时任务已触发并发送 |diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 8010d785..40e38ccb 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -643,6 +643,65 @@ export interface DefaultModelResponse {defaultModel: ModelRefDto;}+// ---------------------------------------------------------------------------+// Provider key-minting flows (/api/projects/:p/model-oauth, owner)+// ---------------------------------------------------------------------------++/**+ * How the authorization code travels back. `callback` sends the browser to a harness URL+ * the provider redirects to; `manual` asks the provider for a one-time code the user copies+ * back by hand, for the case where that redirect cannot reach the harness.+ */+export type ModelOAuthMode = "callback" | "manual";++/**+ * POST /api/projects/:p/model-oauth/start (owner): opens a flow for one provider group.+ * The group must declare an authorization flow in the built-in catalog — the endpoints it+ * uses come from there, never from this request.+ */+export interface ModelOAuthStartRequest {+ /** Provider group id (must be a catalog group that publishes a key-minting flow). */+ provider: string;+ /** Defaults to `callback`. */+ mode?: ModelOAuthMode;+}++/** The opaque flow handle plus the page to send the user to. No secret of the flow's is included. */+export interface ModelOAuthStartResponse {+ flowId: string;+ authorizeUrl: string;+}++/** Why a flow failed, as a code the frontend phrases; never carries a code, a verifier or a key. */+export type ModelOAuthErrorCode =+ "invalid_request" | "code_rejected" | "upstream_failed" | "unreachable" | "apply_failed";++/**+ * GET /api/projects/:p/model-oauth/:flowId (owner): where a flow stands. Unknown, expired,+ * and other users' flows are all 404 alike.+ */+export interface ModelOAuthStatusResponse {+ status: "pending" | "done" | "error";+ /** The provider group the flow mints a key for. */+ provider: string;+ error?: ModelOAuthErrorCode;+}++/**+ * POST /api/projects/:p/model-oauth/:flowId/code (owner): redeems a code the user pasted,+ * the manual counterpart of the redirect callback. A flow is single-use either way.+ */+export interface ModelOAuthCodeRequest {+ code: string;+}++/** Redemption outcome; `applied` counts the models the minted key was written to. */+export interface ModelOAuthCodeResponse {+ ok: boolean;+ applied?: number;+ error?: ModelOAuthErrorCode;+}+// ---------------------------------------------------------------------------// New-chat defaults (the `[default_chat]` block of .project_config.toml)// ---------------------------------------------------------------------------diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 22f50046..80bdc48f 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -79,6 +79,7 @@ import { AgentService } from "./services/agent-service.js";import { BenchmarkService } from "./services/benchmark-service.js";import { SnapshotService } from "./services/snapshot-service.js";import { ProjectConfigService } from "./services/project-config-service.js";+import { ModelOAuthService } from "./services/model-oauth-service.js";import { ProjectService } from "./services/project-service.js";import { SessionService } from "./services/session-service.js";import { TraceIndexService } from "./services/trace-index.js";@@ -112,6 +113,7 @@ import { eventsRoutes, userChannelKey } from "./http/routes/events.js";import { projectsRoutes } from "./http/routes/projects.js";import { membersRoutes } from "./http/routes/members.js";import { modelsRoutes } from "./http/routes/models.js";+import { modelOAuthRoutes } from "./http/routes/model-oauth.js";import { chatDefaultsRoutes } from "./http/routes/chat-defaults.js";import { commandPolicyRoutes } from "./http/routes/command-policy.js";import { vaultRoutes } from "./http/routes/vault.js";@@ -142,6 +144,8 @@ export interface AppDeps {adminService: AdminService;projectService: ProjectService;projectConfigService: ProjectConfigService;+ /** In-flight provider key-minting flows (PKCE verifiers live here and nowhere else). */+ modelOAuth: ModelOAuthService;agentService: AgentService;agentConfigService: AgentConfigService;memoryService: MemoryService;@@ -549,6 +553,12 @@ export function buildAppDeps(const goalsRepo = new GoalsRepo(db);const projectConfigService = new ProjectConfigService(config.root);+ // Per-App like the preview signer above: a flow holds a PKCE verifier and nothing durable,+ // so a push or a restart costs the user one re-authorization and leaks nothing.+ const modelOAuth = new ModelOAuthService({+ applyGroupKey: (projectId, provider, apiKey) =>+ projectConfigService.setGroupApiKey(projectId, provider, apiKey),+ });const agentConfigService = new AgentConfigService(config.root);const snapshots = new SnapshotService(config.root);const agentService = new AgentService(config.root, agentsRepo, agentConfigService, snapshots);@@ -698,6 +708,7 @@ export function buildAppDeps(adminService,projectService,projectConfigService,+ modelOAuth,agentService,agentConfigService,memoryService,@@ -793,6 +804,7 @@ export function createApp(app.route("/api/projects", projectsRoutes(deps));app.route("/api/projects/:projectId/members", membersRoutes(deps));app.route("/api/projects/:projectId/models", modelsRoutes(deps));+ app.route("/api/projects/:projectId/model-oauth", modelOAuthRoutes(deps));app.route("/api/projects/:projectId/chat-defaults", chatDefaultsRoutes(deps));app.route("/api/projects/:projectId/command-policy", commandPolicyRoutes(deps));app.route("/api/projects/:projectId/agents", agentsRoutes(deps));diff --git a/packages/server/src/http/routes/model-oauth.ts b/packages/server/src/http/routes/model-oauth.tsnew file mode 100644index 00000000..d4f9ed39--- /dev/null+++ b/packages/server/src/http/routes/model-oauth.ts@@ -0,0 +1,248 @@+/**+ * Provider key-minting routes:+ * POST /api/projects/:p/model-oauth/start,+ * GET /api/projects/:p/model-oauth/callback,+ * POST /api/projects/:p/model-oauth/:flowId/code,+ * GET /api/projects/:p/model-oauth/:flowId.+ *+ * Owner only, like every other route that spends or rewrites a Project's credentials. The+ * whole exchange runs here: the PKCE verifier is generated server-side and never leaves this+ * process, and the minted key goes straight into the Project's model config without passing+ * through the browser. A caller only ever holds an opaque flow id and a status.+ */+import { Hono } from "hono";+import type {+ ModelOAuthCodeResponse,+ ModelOAuthMode,+ ModelOAuthStartResponse,+ ModelOAuthStatusResponse,+} from "../../api/types.js";+import type { AppEnv } from "../../auth/middleware.js";+import type { AppDeps } from "../../app.js";+import { HttpError } from "../errors.js";+import { badRequest, readJson, requireString, requireValidId } from "../validate.js";+import { publishCredentialsUpdated } from "./models.js";++/** Flow ids are base64url (`randomBytes(32)`); reject anything else before it reaches the store. */+const FLOW_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;++/**+ * An authorization code as it may appear in a callback query or a paste box. Bounded and+ * restricted to the characters an opaque token can hold, so nothing shaped like markup or a+ * control sequence reaches the exchange body or the page below.+ */+const CODE_RE = /^[A-Za-z0-9._~-]{1,512}$/;++/**+ * Origin the browser reached this server on, which is the origin the provider must redirect+ * back to. Taken from the request's own URL, so loopback, a LAN address and a custom port+ * all work without configuration.+ *+ * `x-forwarded-proto` / `x-forwarded-host` are caller-supplied and are honoured only when+ * the deployment says a reverse proxy sets them (PENGUIN_TRUST_PROXY=1) — the same opt-in+ * the hot-update network gate requires, and for the same reason: without it anyone who can+ * reach the bind could choose where the authorization lands.+ */+export function requestOrigin(+ url: string,+ headers: { proto?: string; host?: string },+ trustProxy: boolean,+): string {+ const own = new URL(url);+ if (!trustProxy) return own.origin;+ // A chain of proxies appends to these headers; the client-facing hop is the first value.+ const proto = headers.proto?.split(",")[0]?.trim();+ const host = headers.host?.split(",")[0]?.trim();+ const scheme = proto === "http" || proto === "https" ? proto : own.protocol.replace(":", "");+ return `${scheme}://${host !== undefined && host !== "" ? host : own.host}`;+}++/** Validates the optional `mode` field of a start request. */+function parseMode(value: unknown): ModelOAuthMode {+ if (value === undefined) return "callback";+ if (value !== "callback" && value !== "manual") {+ throw badRequest('mode must be "callback" or "manual".');+ }+ return value;+}++/**+ * The page the provider's redirect lands on. Rendered by the browser in a tab of its own, so+ * it carries its own styling and loads nothing: no script, no font, no image. It reports the+ * outcome and nothing else — never the code, never the key, never anything about the Project.+ */+function resultPage(title: string, body: string): string {+ const esc = (s: string): string =>+ s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+ return `<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>${esc(title)}</title>+<style>+:root { color-scheme: light dark; }+body {+ margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;+ font: 15px/1.6 system-ui, -apple-system, "Segoe UI", sans-serif;+ background: #f9fafb; color: #111827;+}+main { max-width: 30rem; padding: 2rem; text-align: center; }+h1 { margin: 0 0 0.5rem; font-size: 1.125rem; font-weight: 600; }+p { margin: 0; color: #4b5563; }+@media (prefers-color-scheme: dark) {+ body { background: #0d0d0d; color: #f3f4f6; }+ p { color: #9ca3af; }+}+</style>+</head>+<body><main><h1>${esc(title)}</h1><p>${esc(body)}</p></main></body>+</html>+`;+}++/** One sentence per failure reason, phrased for the redirect page (the Web App localizes its own). */+const FAILURE_TEXT: Record<string, string> = {+ invalid_request:+ "TokenDance rejected the authorization request. Start a new one in PenguinHarness.",+ code_rejected:+ "The authorization is no longer valid — it may have expired or already been used. Start a new one in PenguinHarness.",+ upstream_failed: "The provider did not return a usable key. Start a new one in PenguinHarness.",+ unreachable:+ "The provider could not be reached. Check the network and start a new one in PenguinHarness.",+ apply_failed:+ "A key was created but could not be saved. Authorize again, then delete the unused key in the provider's console.",+};++export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ /** Credential change: same follow-up the models PUT performs, so live Sessions pick the key up. */+ const credentialsChanged = (projectId: string): void => {+ deps.manager.invalidateProjectRuntimes(projectId);+ publishCredentialsUpdated(deps, projectId);+ };++ // Opens a flow and returns the page to send the user to. The provider is looked up in the+ // built-in catalog inside the service, which is what rejects a group that publishes no+ // such flow and what keeps the authorize/exchange endpoints out of client control.+ app.post("/start", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);+ const body = await readJson(c);+ const provider = requireString(body, "provider", { minLen: 1, maxLen: 64 });+ const mode = parseMode(body.mode);+ const started = deps.modelOAuth.start({+ projectId,+ userId: c.var.user.userId,+ provider,+ mode,+ callbackOrigin: requestOrigin(+ c.req.url,+ {+ ...(c.req.header("x-forwarded-proto") !== undefined+ ? { proto: c.req.header("x-forwarded-proto")! }+ : {}),+ ...(c.req.header("x-forwarded-host") !== undefined+ ? { host: c.req.header("x-forwarded-host")! }+ : {}),+ },+ deps.config.trustProxy,+ ),+ });+ return c.json(started satisfies ModelOAuthStartResponse);+ });++ // Where the provider sends the browser back. Registered before the `:flowId` status route+ // so the literal path wins. Answers HTML throughout — a person is looking at this tab, not+ // a client parsing JSON.+ app.get("/callback", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);+ const flowId = c.req.query("flow") ?? "";+ // The provider appends `code=` to the callback URL it was given, preserving its path and+ // query, which is how the flow id rides back alongside it.+ const code = c.req.query("code") ?? "";+ if (!FLOW_ID_RE.test(flowId) || !CODE_RE.test(code)) {+ return c.html(+ resultPage(+ "Authorization failed",+ "This link is incomplete. Return to PenguinHarness and start a new authorization.",+ ),+ 400,+ );+ }+ let result: Awaited<ReturnType<typeof deps.modelOAuth.complete>>;+ try {+ result = await deps.modelOAuth.complete({+ flowId,+ userId: c.var.user.userId,+ projectId,+ code,+ });+ } catch (err) {+ const message =+ err instanceof HttpError+ ? err.message+ : "Something went wrong. Return to PenguinHarness and start a new authorization.";+ return c.html(resultPage("Authorization failed", message), 400);+ }+ if (!result.ok) {+ return c.html(resultPage("Authorization failed", FAILURE_TEXT[result.error]!), 400);+ }+ credentialsChanged(projectId);+ return c.html(+ resultPage(+ "API key created",+ "The new key has been saved to this Project's models. You can close this tab and return to PenguinHarness.",+ ),+ );+ });++ // Manual counterpart of the callback: the user pastes the one-time code the authorization+ // page displayed when it was asked not to redirect.+ app.post("/:flowId/code", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);+ const flowId = c.req.param("flowId") ?? "";+ if (!FLOW_ID_RE.test(flowId)) {+ throw new HttpError(+ 404,+ "model_oauth_flow_not_found",+ "This authorization has expired or does not exist. Start a new one.",+ );+ }+ const body = await readJson(c);+ const code = requireString(body, "code", { minLen: 1, maxLen: 512 }).trim();+ if (!CODE_RE.test(code)) throw badRequest("code is not a valid authorization code.");+ const result = await deps.modelOAuth.complete({+ flowId,+ userId: c.var.user.userId,+ projectId,+ code,+ });+ if (!result.ok) {+ return c.json({ ok: false, error: result.error } satisfies ModelOAuthCodeResponse);+ }+ credentialsChanged(projectId);+ return c.json({ ok: true, applied: result.applied } satisfies ModelOAuthCodeResponse);+ });++ // Poll target while the user is authorizing in the other tab.+ app.get("/:flowId", (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);+ const flowId = c.req.param("flowId") ?? "";+ if (!FLOW_ID_RE.test(flowId)) {+ throw new HttpError(+ 404,+ "model_oauth_flow_not_found",+ "This authorization has expired or does not exist. Start a new one.",+ );+ }+ const state = deps.modelOAuth.status({ flowId, userId: c.var.user.userId, projectId });+ return c.json(state satisfies ModelOAuthStatusResponse);+ });++ return app;+}diff --git a/packages/server/src/http/routes/models.ts b/packages/server/src/http/routes/models.tsindex 300115a2..3d89d410 100644--- a/packages/server/src/http/routes/models.ts+++ b/packages/server/src/http/routes/models.ts@@ -28,9 +28,10 @@ import type { AppDeps } from "../../app.js";* Live unlock for auth-dead composers: after a models/credential update, publish* `credentials_updated` to every EXISTING channel of this Project's Sessions (`peek` —* never creates channels: a tab that isn't subscribed learns the same fact from the models- * response's `updatedAt` when it next loads).+ * response's `updatedAt` when it next loads). Shared with the key-minting routes, which+ * change the same credentials by a different path.*/-function publishCredentialsUpdated(deps: AppDeps, projectId: string): void {+export function publishCredentialsUpdated(deps: AppDeps, projectId: string): void {const event: ServerEvent = { type: "credentials_updated" };for (const row of deps.sessionsRepo.listByProject(projectId)) {deps.channels.peek(row.sessionId)?.publish(event, "server_event");diff --git a/packages/server/src/services/model-oauth-service.ts b/packages/server/src/services/model-oauth-service.tsnew file mode 100644index 00000000..56f82b9a--- /dev/null+++ b/packages/server/src/services/model-oauth-service.ts@@ -0,0 +1,365 @@+/**+ * Provider key-minting flows (the `oauth` descriptor in core's model catalog).+ *+ * A provider that publishes such a flow lets the user authorize in a browser and get a+ * **freshly minted API key** back, instead of copying one out of a console. The upstream+ * protocol is PKCE: the harness picks a random verifier, sends only its SHA-256 challenge+ * to the authorization page, and later presents the verifier to redeem the one-time code+ * the page hands back.+ *+ * Everything secret stays on this side of the wire. The verifier is generated here, kept+ * only in this process's memory, and never sent to the browser; the minted key goes+ * straight into the Project's model config and is never echoed to a caller, a URL, or a+ * log line. What the Web App holds is an opaque flow id and a status.+ *+ * Flows are in-memory and per-App: a restart or a platform push drops the pending ones,+ * which costs the user a re-authorization and nothing else (the upstream code expires in+ * minutes anyway, and no key exists until the exchange runs).+ */+import { createHash, randomBytes, randomUUID } from "node:crypto";+import { APP_URL, providerInfo } from "@prismshadow/penguin-core/model-catalog";+import type { ModelProviderOAuth } from "@prismshadow/penguin-core/model-catalog";+import { HttpError } from "../http/errors.js";+import { badRequest } from "../http/validate.js";++/** How the user gets the authorization code back to the harness. */+export type ModelOAuthMode = "callback" | "manual";++/** A flow's terminal-or-not state, as the Web App polls it. */+export type ModelOAuthStatus = "pending" | "done" | "error";++/**+ * Lifetime of a flow. The upstream one-time code is valid for ten minutes, so a flow that+ * outlived that window can only ever fail — expiring it here keeps the verifier's residency+ * in memory bounded by the same figure.+ */+export const FLOW_TTL_MS = 10 * 60 * 1000;++/**+ * Concurrent pending flows one user may hold in one Project. Reached only by repeatedly+ * opening the dialog without finishing; the oldest is evicted rather than refusing the+ * newest, so the button a user just pressed always works.+ */+const MAX_FLOWS_PER_OWNER = 8;++interface Flow {+ flowId: string;+ projectId: string;+ userId: string;+ provider: string;+ exchangeUrl: string;+ /** PKCE verifier; dropped the moment the flow reaches a terminal state. */+ verifier: string | null;+ createdAt: number;+ expiresAt: number;+ status: ModelOAuthStatus;+ /** Machine-readable failure reason, mirrored to the Web App so it can localize. */+ errorCode?: ModelOAuthErrorCode;+}++/**+ * Failure reasons a flow can end in. Deliberately coarse: each one maps to a sentence the+ * Web App already knows how to phrase, and none of them can carry a code, a verifier or a+ * key.+ */+export type ModelOAuthErrorCode =+ /** The authorization request itself was malformed (bad callback URL, incomplete PKCE). */+ | "invalid_request"+ /** The code is unknown, expired, already redeemed, or was minted for another verifier. */+ | "code_rejected"+ /** The provider answered, but not with a usable key. */+ | "upstream_failed"+ /** The provider could not be reached at all. */+ | "unreachable"+ /** A key was minted but could not be written into the Project's models. */+ | "apply_failed";++/** What `start` hands back to the Web App: an opaque id plus the page to send the user to. */+export interface ModelOAuthStartResult {+ flowId: string;+ authorizeUrl: string;+}++/**+ * PKCE verifier: two random UUIDs concatenated, as the upstream protocol documents. 72+ * characters drawn from `[0-9a-f-]`, inside both the 43–128 length window and the+ * `[A-Za-z0-9-._~]` alphabet the spec allows.+ */+export function createVerifier(): string {+ return `${randomUUID()}${randomUUID()}`;+}++/**+ * PKCE S256 challenge: base64url of the verifier's SHA-256 digest, unpadded. Node's+ * `base64url` digest encoding already substitutes `-`/`_` and drops `=`, so this is the+ * documented `btoa(...).replace(...)` chain by another name.+ */+export function codeChallenge(verifier: string): string {+ return createHash("sha256").update(verifier, "utf8").digest("base64url");+}++/**+ * The authorization page URL for one flow.+ *+ * `callbackUrl` is omitted in manual mode, which is what makes the page display a one-time+ * code for the user to carry back by hand instead of redirecting. S256 is sent either way:+ * without it a code observed in a redirect could be redeemed by whoever observed it, and+ * the manual mode refuses to run without it at all.+ *+ * Parameter order follows the published example so a URL from here is diffable against the+ * documentation; `URLSearchParams` percent-encodes the two URL-valued parameters.+ */+export function buildAuthorizeUrl(input: {+ oauth: ModelProviderOAuth;+ challenge: string;+ /** Absent in manual mode. */+ callbackUrl?: string;+}): string {+ const params = new URLSearchParams();+ if (input.callbackUrl !== undefined) params.set("callback_url", input.callbackUrl);+ params.set("code_challenge", input.challenge);+ params.set("code_challenge_method", "S256");+ // The app's own stable URL, never the callback's ephemeral port: it is stamped onto the+ // minted key and every later call made with that key inherits it.+ params.set("app_url", APP_URL);+ params.set("key_name", input.oauth.keyName);+ return `${input.oauth.authorizeUrl}?${params.toString()}`;+}++/** Outcome of redeeming a code: the key on success, a coarse reason on failure. */+export type ExchangeResult = { ok: true; key: string } | { ok: false; error: ModelOAuthErrorCode };++/**+ * Redeem an authorization code for a newly minted key.+ *+ * The reply carries the full key exactly once, so the caller must persist it before doing+ * anything that can throw — a lost reply leaves an orphaned key on the user's account that+ * only they can delete.+ *+ * Upstream status mapping: 400 is a malformed authorization request (bad callback URL,+ * incomplete PKCE, a method other than S256), 403 covers every code-level rejection —+ * unknown, expired, already redeemed, or a verifier that does not match the challenge.+ */+export async function exchangeCode(input: {+ exchangeUrl: string;+ code: string;+ verifier: string;+ fetchImpl: typeof fetch;+}): Promise<ExchangeResult> {+ let res: Response;+ try {+ res = await input.fetchImpl(input.exchangeUrl, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ code: input.code,+ code_verifier: input.verifier,+ code_challenge_method: "S256",+ }),+ });+ } catch {+ // The reason is intentionally not carried further: a fetch failure message can quote+ // the request, and the request holds the code and the verifier.+ return { ok: false, error: "unreachable" };+ }+ if (!res.ok) {+ if (res.status === 400) return { ok: false, error: "invalid_request" };+ if (res.status === 403) return { ok: false, error: "code_rejected" };+ return { ok: false, error: "upstream_failed" };+ }+ let body: unknown;+ try {+ body = await res.json();+ } catch {+ return { ok: false, error: "upstream_failed" };+ }+ const key = (body as { key?: unknown } | null)?.key;+ if (typeof key !== "string" || key === "") return { ok: false, error: "upstream_failed" };+ return { ok: true, key };+}++/** Writes a minted key onto every model of one provider group; returns how many it touched. */+export type ApplyGroupKey = (+ projectId: string,+ provider: string,+ apiKey: string,+) => Promise<number>;++export interface ModelOAuthDeps {+ applyGroupKey: ApplyGroupKey;+ /** Injected so tests never reach the network. */+ fetchImpl?: typeof fetch;+ now?: () => number;+}++export class ModelOAuthService {+ private readonly flows = new Map<string, Flow>();+ private readonly applyGroupKey: ApplyGroupKey;+ private readonly fetchImpl: typeof fetch;+ private readonly now: () => number;++ constructor(deps: ModelOAuthDeps) {+ this.applyGroupKey = deps.applyGroupKey;+ this.fetchImpl = deps.fetchImpl ?? ((...args) => fetch(...args));+ this.now = deps.now ?? (() => Date.now());+ }++ /**+ * Open a flow for one provider group and return the page to send the user to.+ *+ * The provider is resolved in the built-in catalog, never taken from the caller: a group+ * that declares no `oauth` cannot be talked into one, and the authorize/exchange+ * endpoints are always the catalog's, so client input never chooses who receives the+ * challenge or who is asked for a key.+ */+ start(input: {+ projectId: string;+ userId: string;+ provider: string;+ mode: ModelOAuthMode;+ /** Where the provider should send the browser back to; ignored in manual mode. */+ callbackOrigin: string;+ }): ModelOAuthStartResult {+ const oauth = providerInfo(input.provider)?.oauth;+ if (oauth === undefined) {+ throw badRequest(`Provider ${input.provider} does not support authorizing a new API key.`);+ }+ this.sweep();+ this.evictOldest(input.userId, input.projectId);++ const flowId = randomBytes(32).toString("base64url");+ const verifier = createVerifier();+ const createdAt = this.now();+ // The callback keeps its own query string: the provider appends `code=` to whatever+ // path and parameters it was given, so the flow id rides back with the code.+ const callbackUrl =+ input.mode === "callback"+ ? `${input.callbackOrigin}/api/projects/${encodeURIComponent(input.projectId)}/model-oauth/callback?flow=${encodeURIComponent(flowId)}`+ : undefined;+ this.flows.set(flowId, {+ flowId,+ projectId: input.projectId,+ userId: input.userId,+ provider: input.provider,+ exchangeUrl: oauth.exchangeUrl,+ verifier,+ createdAt,+ expiresAt: createdAt + FLOW_TTL_MS,+ status: "pending",+ });+ return {+ flowId,+ authorizeUrl: buildAuthorizeUrl({+ oauth,+ challenge: codeChallenge(verifier),+ ...(callbackUrl !== undefined ? { callbackUrl } : {}),+ }),+ };+ }++ /**+ * A flow's current state for its owner. 404 for anything the caller may not see —+ * unknown, expired, or belonging to another user or Project — so a flow id is never a+ * probe for what exists.+ */+ status(input: { flowId: string; userId: string; projectId: string }): {+ status: ModelOAuthStatus;+ provider: string;+ error?: ModelOAuthErrorCode;+ } {+ const flow = this.require(input);+ return {+ status: flow.status,+ provider: flow.provider,+ ...(flow.errorCode !== undefined ? { error: flow.errorCode } : {}),+ };+ }++ /**+ * Redeem a code against a pending flow and write the minted key onto the group.+ *+ * One shot: the flow leaves `pending` before the exchange runs, so a replayed callback+ * cannot spend the same verifier twice, and the verifier is dropped from memory as soon+ * as it has been used. A key that arrives but cannot be stored is reported as+ * `apply_failed` — the user has to authorize again and delete the orphan, and saying so+ * is the only honest answer, since the provider reveals a key exactly once.+ */+ async complete(input: {+ flowId: string;+ userId: string;+ projectId: string;+ code: string;+ }): Promise<{ ok: true; applied: number } | { ok: false; error: ModelOAuthErrorCode }> {+ const flow = this.require(input);+ if (flow.status !== "pending" || flow.verifier === null) {+ throw new HttpError(+ 409,+ "model_oauth_flow_used",+ "This authorization has already been completed. Start a new one.",+ );+ }+ const verifier = flow.verifier;+ flow.verifier = null;+ const result = await exchangeCode({+ exchangeUrl: flow.exchangeUrl,+ code: input.code,+ verifier,+ fetchImpl: this.fetchImpl,+ });+ if (!result.ok) {+ flow.status = "error";+ flow.errorCode = result.error;+ return { ok: false, error: result.error };+ }+ let applied: number;+ try {+ applied = await this.applyGroupKey(flow.projectId, flow.provider, result.key);+ } catch {+ flow.status = "error";+ flow.errorCode = "apply_failed";+ return { ok: false, error: "apply_failed" };+ }+ flow.status = "done";+ return { ok: true, applied };+ }++ /** The provider group a flow belongs to (the route needs it before it can complete one). */+ providerOf(input: { flowId: string; userId: string; projectId: string }): string {+ return this.require(input).provider;+ }++ private require(input: { flowId: string; userId: string; projectId: string }): Flow {+ this.sweep();+ const flow = this.flows.get(input.flowId);+ if (+ flow === undefined ||+ flow.userId !== input.userId ||+ flow.projectId !== input.projectId ||+ flow.expiresAt <= this.now()+ ) {+ throw new HttpError(+ 404,+ "model_oauth_flow_not_found",+ "This authorization has expired or does not exist. Start a new one.",+ );+ }+ return flow;+ }++ /** Drops flows past their TTL, verifier included. */+ private sweep(): void {+ const now = this.now();+ for (const [id, flow] of this.flows) {+ if (flow.expiresAt <= now) this.flows.delete(id);+ }+ }++ private evictOldest(userId: string, projectId: string): void {+ const mine = [...this.flows.values()]+ .filter((f) => f.userId === userId && f.projectId === projectId)+ .sort((a, b) => a.createdAt - b.createdAt);+ for (const flow of mine.slice(0, Math.max(0, mine.length - (MAX_FLOWS_PER_OWNER - 1)))) {+ this.flows.delete(flow.flowId);+ }+ }+}diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.tsindex f21a5964..26ff5f6e 100644--- a/packages/server/src/services/project-config-service.ts+++ b/packages/server/src/services/project-config-service.ts@@ -1022,6 +1022,28 @@ export class ProjectConfigService {await this.writeRaw(projectId, next);return this.getModels(projectId);}++ /**+ * Writes one API key onto every model of a provider group — the credential half of the+ * bulk group-key action, performing the same `api_key` + `created_at` write `updateModels`+ * performs on the entries it rewrites. No other field is read or replaced, so a caller+ * that never saw the rest of the table cannot flatten it.+ *+ * Returns how many entries were written; an empty group writes nothing and returns 0.+ */+ async setGroupApiKey(projectId: string, provider: string, apiKey: string): Promise<number> {+ const raw = await this.readRaw(projectId);+ const createdAt = new Date().toISOString();+ let applied = 0;+ const nextModels = asArray(raw.models).map((m) => {+ if (m.provider !== provider) return m;+ applied += 1;+ return { ...m, api_key: apiKey, created_at: createdAt };+ });+ if (applied === 0) return 0;+ await this.writeRaw(projectId, { ...raw, models: nextModels });+ return applied;+ }}/**diff --git a/packages/server/test/model-oauth.test.ts b/packages/server/test/model-oauth.test.tsnew file mode 100644index 00000000..e520044b--- /dev/null+++ b/packages/server/test/model-oauth.test.ts@@ -0,0 +1,493 @@+/**+ * Provider key-minting flow: PKCE derivation, authorize-URL construction, the flow store's+ * expiry and single-use rules, the exchange's error mapping, and the routes end to end —+ * owner-only, key written to every model of the group, `credentials_updated` published.+ *+ * No test reaches the network: `exchangeCode` takes its fetch as an argument, and the route+ * cases stub the global one.+ */+import { readFile } from "node:fs/promises";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { APP_URL, providerInfo } from "@prismshadow/penguin-core/model-catalog";+import type {+ ModelOAuthCodeResponse,+ ModelOAuthStartResponse,+ ModelOAuthStatusResponse,+ ModelsResponse,+ ProjectCreateResponse,+} from "../src/api/types.js";+import type { ChannelEvent } from "../src/runtime/channel.js";+import { HttpError } from "../src/http/errors.js";+import {+ buildAuthorizeUrl,+ codeChallenge,+ createVerifier,+ exchangeCode,+ ModelOAuthService,+} from "../src/services/model-oauth-service.js";+import { requestOrigin } from "../src/http/routes/model-oauth.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++/** The catalog group under test; the flow exists only because this entry declares it. */+const TOKENDANCE = providerInfo("tokendance")!;++/** A JSON reply from the exchange endpoint, without touching the network. */+function jsonResponse(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}++describe("PKCE derivation", () => {+ it("challenge is the unpadded base64url SHA-256 of the verifier (RFC 7636 vector)", () => {+ expect(codeChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")).toBe(+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",+ );+ });++ it("challenge carries no base64 padding or non-url characters", () => {+ const challenge = codeChallenge(createVerifier());+ expect(challenge).toMatch(/^[A-Za-z0-9_-]{43}$/);+ });++ it("verifier is inside the spec's 43-128 window and alphabet, and is not reused", () => {+ const a = createVerifier();+ const b = createVerifier();+ expect(a).toMatch(/^[A-Za-z0-9._~-]{43,128}$/);+ expect(a.length).toBe(72);+ expect(a).not.toBe(b);+ });+});++describe("authorize URL", () => {+ const challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";++ it("carries the callback URL, the app URL and the key name, all percent-encoded", () => {+ const url = buildAuthorizeUrl({+ oauth: TOKENDANCE.oauth!,+ challenge,+ callbackUrl: "http://127.0.0.1:8123/api/projects/p1/model-oauth/callback?flow=abc-_1",+ });+ expect(url.startsWith(`${TOKENDANCE.oauth!.authorizeUrl}?`)).toBe(true);+ const q = new URL(url).searchParams;+ expect(q.get("callback_url")).toBe(+ "http://127.0.0.1:8123/api/projects/p1/model-oauth/callback?flow=abc-_1",+ );+ expect(q.get("code_challenge")).toBe(challenge);+ expect(q.get("code_challenge_method")).toBe("S256");+ expect(q.get("app_url")).toBe(APP_URL);+ expect(q.get("key_name")).toBe("PenguinHarness");+ // The two URL-valued parameters travel escaped, never raw.+ expect(url).toContain("app_url=https%3A%2F%2Fpenguin.ooo%2F");+ expect(url).toContain("callback_url=http%3A%2F%2F127.0.0.1%3A8123%2F");+ expect(url).not.toContain("?flow=abc-_1&code_challenge");+ });++ it("app_url is the harness's own stable URL, not the callback's ephemeral port", () => {+ const url = buildAuthorizeUrl({+ oauth: TOKENDANCE.oauth!,+ challenge,+ callbackUrl: "http://127.0.0.1:51234/api/projects/p1/model-oauth/callback?flow=x",+ });+ expect(new URL(url).searchParams.get("app_url")).toBe(APP_URL);+ expect(new URL(url).searchParams.get("app_url")).not.toContain("51234");+ });++ it("manual mode omits the callback and still pins S256", () => {+ const q = new URL(buildAuthorizeUrl({ oauth: TOKENDANCE.oauth!, challenge })).searchParams;+ expect(q.has("callback_url")).toBe(false);+ expect(q.get("code_challenge_method")).toBe("S256");+ expect(q.get("code_challenge")).toBe(challenge);+ });+});++describe("code exchange", () => {+ const call = (impl: typeof fetch) =>+ exchangeCode({+ exchangeUrl: TOKENDANCE.oauth!.exchangeUrl,+ code: "the-code",+ verifier: "the-verifier",+ fetchImpl: impl,+ });++ it("posts the code, the verifier and the method as JSON, and returns the minted key", async () => {+ const seen: { url: string; body: unknown } = { url: "", body: null };+ const res = await call((async (url: string, init: RequestInit) => {+ seen.url = url;+ seen.body = JSON.parse(String(init.body));+ return jsonResponse(200, { key: "sk-minted" });+ }) as unknown as typeof fetch);+ expect(res).toEqual({ ok: true, key: "sk-minted" });+ expect(seen.url).toBe(TOKENDANCE.oauth!.exchangeUrl);+ expect(seen.body).toEqual({+ code: "the-code",+ code_verifier: "the-verifier",+ code_challenge_method: "S256",+ });+ });++ it("400 is a malformed authorization request; 403 is a rejected code", async () => {+ const fail = (status: number) =>+ call((async () => jsonResponse(status, { error: "no" })) as unknown as typeof fetch);+ expect(await fail(400)).toEqual({ ok: false, error: "invalid_request" });+ expect(await fail(403)).toEqual({ ok: false, error: "code_rejected" });+ expect(await fail(500)).toEqual({ ok: false, error: "upstream_failed" });+ });++ it("a 200 without a usable key is a failure, not a key", async () => {+ expect(+ await call((async () => jsonResponse(200, { key: "" })) as unknown as typeof fetch),+ ).toEqual({ ok: false, error: "upstream_failed" });+ expect(await call((async () => jsonResponse(200, {})) as unknown as typeof fetch)).toEqual({+ ok: false,+ error: "upstream_failed",+ });+ expect(+ await call(+ (async () => new Response("not json", { status: 200 })) as unknown as typeof fetch,+ ),+ ).toEqual({ ok: false, error: "upstream_failed" });+ });++ it("a transport failure reports unreachable and carries no detail (the request holds the code)", async () => {+ const res = await call((async () => {+ throw new Error("connect ECONNREFUSED sk-leak");+ }) as unknown as typeof fetch);+ expect(res).toEqual({ ok: false, error: "unreachable" });+ expect(JSON.stringify(res)).not.toContain("sk-leak");+ });+});++describe("flow store", () => {+ let clock: number;+ let applied: { projectId: string; provider: string; apiKey: string }[];+ let service: ModelOAuthService;++ const start = () =>+ service.start({+ projectId: "p1",+ userId: "u1",+ provider: "tokendance",+ mode: "callback",+ callbackOrigin: "http://127.0.0.1:8123",+ });++ beforeEach(() => {+ clock = 1_700_000_000_000;+ applied = [];+ service = new ModelOAuthService({+ applyGroupKey: async (projectId, provider, apiKey) => {+ applied.push({ projectId, provider, apiKey });+ return 6;+ },+ fetchImpl: (async () => jsonResponse(200, { key: "sk-minted" })) as unknown as typeof fetch,+ now: () => clock,+ });+ });++ it("refuses a provider that declares no flow, and one that is not in the catalog at all", () => {+ for (const provider of ["deepseek", "custom", "not-a-provider"]) {+ expect(() =>+ service.start({+ projectId: "p1",+ userId: "u1",+ provider,+ mode: "callback",+ callbackOrigin: "http://127.0.0.1:8123",+ }),+ ).toThrow(HttpError);+ }+ });++ it("the callback URL keeps its query, so the flow id rides back with the code", () => {+ const { flowId, authorizeUrl } = start();+ expect(new URL(authorizeUrl).searchParams.get("callback_url")).toBe(+ `http://127.0.0.1:8123/api/projects/p1/model-oauth/callback?flow=${encodeURIComponent(flowId)}`,+ );+ // Opaque and unguessable: 32 random bytes, base64url.+ expect(flowId).toMatch(/^[A-Za-z0-9_-]{43}$/);+ });++ it("a flow belongs to one user in one Project; anyone else sees a 404", () => {+ const { flowId } = start();+ expect(service.status({ flowId, userId: "u1", projectId: "p1" }).status).toBe("pending");+ expect(() => service.status({ flowId, userId: "u2", projectId: "p1" })).toThrow(HttpError);+ expect(() => service.status({ flowId, userId: "u1", projectId: "p2" })).toThrow(HttpError);+ expect(() => service.status({ flowId: "nope", userId: "u1", projectId: "p1" })).toThrow(+ HttpError,+ );+ });++ it("expires after ten minutes, and the expired flow is gone rather than failed", async () => {+ const { flowId } = start();+ clock += 10 * 60 * 1000 - 1;+ expect(service.status({ flowId, userId: "u1", projectId: "p1" }).status).toBe("pending");+ clock += 1;+ expect(() => service.status({ flowId, userId: "u1", projectId: "p1" })).toThrow(HttpError);+ await expect(+ service.complete({ flowId, userId: "u1", projectId: "p1", code: "c" }),+ ).rejects.toThrow(HttpError);+ });++ it("is single use: the second redemption is refused and the verifier is spent only once", async () => {+ const { flowId } = start();+ expect(await service.complete({ flowId, userId: "u1", projectId: "p1", code: "c" })).toEqual({+ ok: true,+ applied: 6,+ });+ expect(applied).toEqual([{ projectId: "p1", provider: "tokendance", apiKey: "sk-minted" }]);+ expect(service.status({ flowId, userId: "u1", projectId: "p1" }).status).toBe("done");+ await expect(+ service.complete({ flowId, userId: "u1", projectId: "p1", code: "c" }),+ ).rejects.toThrow(HttpError);+ expect(applied).toHaveLength(1);+ });++ it("a failed exchange ends the flow and reports the mapped reason", async () => {+ service = new ModelOAuthService({+ applyGroupKey: async () => 6,+ fetchImpl: (async () => jsonResponse(403, {})) as unknown as typeof fetch,+ now: () => clock,+ });+ const { flowId } = start();+ expect(await service.complete({ flowId, userId: "u1", projectId: "p1", code: "c" })).toEqual({+ ok: false,+ error: "code_rejected",+ });+ const state = service.status({ flowId, userId: "u1", projectId: "p1" });+ expect(state).toEqual({ status: "error", provider: "tokendance", error: "code_rejected" });+ });++ it("a key that cannot be stored is reported as such, not as a success", async () => {+ service = new ModelOAuthService({+ applyGroupKey: async () => {+ throw new Error("disk full");+ },+ fetchImpl: (async () => jsonResponse(200, { key: "sk-minted" })) as unknown as typeof fetch,+ now: () => clock,+ });+ const { flowId } = start();+ expect(await service.complete({ flowId, userId: "u1", projectId: "p1", code: "c" })).toEqual({+ ok: false,+ error: "apply_failed",+ });+ expect(service.status({ flowId, userId: "u1", projectId: "p1" }).error).toBe("apply_failed");+ });+});++describe("callback origin", () => {+ it("follows the request's own URL when no proxy is trusted", () => {+ expect(requestOrigin("http://192.168.1.4:7364/api/x", {}, false)).toBe(+ "http://192.168.1.4:7364",+ );+ // Untrusted headers are ignored outright, so a caller cannot choose where the redirect lands.+ expect(+ requestOrigin("http://192.168.1.4:7364/api/x", { proto: "https", host: "evil.test" }, false),+ ).toBe("http://192.168.1.4:7364");+ });++ it("honours the forwarded pair once the deployment trusts it, taking the client-facing hop", () => {+ expect(+ requestOrigin(+ "http://127.0.0.1:7364/api/x",+ { proto: "https, http", host: "penguin.example, inner" },+ true,+ ),+ ).toBe("https://penguin.example");+ // Trusted but absent: the request's own URL still answers.+ expect(requestOrigin("http://127.0.0.1:7364/api/x", {}, true)).toBe("http://127.0.0.1:7364");+ });+});++describe("model-oauth routes", () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let member: ReturnType<typeof apiClient>;+ let projectId: string;+ let exchanges: { url: string; body: Record<string, unknown> }[];++ const base = () => `/api/projects/${projectId}/model-oauth`;++ beforeEach(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner_o");+ const b = await provisionUser(t.app, "member_m");+ owner = apiClient(t.app, a.cookie);+ member = apiClient(t.app, b.cookie);+ const created = (await (+ await owner.post("/api/projects", { projectId: "owner_o-td", name: "TokenDance project" })+ ).json()) as ProjectCreateResponse;+ projectId = created.project.projectId;+ expect(+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "member_m" })).status,+ ).toBe(201);++ exchanges = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string, init: RequestInit) => {+ exchanges.push({ url, body: JSON.parse(String(init.body)) as Record<string, unknown> });+ return jsonResponse(200, { key: "sk-oauth-minted-key-9911" });+ }),+ );+ });+ afterEach(async () => {+ vi.unstubAllGlobals();+ await t.cleanup();+ });++ it("owner starts a flow; a member cannot, and neither can start one for a group with no flow", async () => {+ const res = await owner.post(`${base()}/start`, { provider: "tokendance" });+ expect(res.status).toBe(200);+ const body = (await res.json()) as ModelOAuthStartResponse;+ expect(body.flowId).toMatch(/^[A-Za-z0-9_-]+$/);+ const q = new URL(body.authorizeUrl).searchParams;+ expect(q.get("callback_url")).toBe(+ `http://localhost${base()}/callback?flow=${encodeURIComponent(body.flowId)}`,+ );+ expect(q.get("key_name")).toBe("PenguinHarness");+ expect(q.get("app_url")).toBe(APP_URL);++ expect((await member.post(`${base()}/start`, { provider: "tokendance" })).status).toBe(403);+ expect((await owner.post(`${base()}/start`, { provider: "deepseek" })).status).toBe(400);+ });++ it("the callback redeems the code, writes the key to every model of the group, and reports it back in HTML", async () => {+ const started = (await (+ await owner.post(`${base()}/start`, { provider: "tokendance" })+ ).json()) as ModelOAuthStartResponse;++ // A subscribed tab of this Project must be told the credentials changed.+ t.deps.sessionsRepo.insert({+ sessionId: "td-live",+ projectId,+ agentId: "default_agent",+ modelId: "m1",+ provider: "custom",+ workspace: t.root,+ approvalMode: "allow-all",+ title: null,+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ });+ const events: ChannelEvent[] = [];+ t.deps.channels.get("td-live").subscribe((e) => events.push(e));++ const cb = await owner.get(+ `${base()}/callback?flow=${encodeURIComponent(started.flowId)}&code=auth-code-1`,+ );+ expect(cb.status).toBe(200);+ expect(cb.headers.get("content-type")).toContain("text/html");+ const page = await cb.text();+ expect(page).toContain("API key created");+ // The page tells the user the outcome and nothing else.+ expect(page).not.toContain("sk-oauth-minted-key-9911");+ expect(page).not.toContain("auth-code-1");+ expect(page).not.toContain("http://");++ // The exchange spoke the documented protocol, with a verifier this side never published.+ expect(exchanges).toHaveLength(1);+ expect(exchanges[0]!.url).toBe(TOKENDANCE.oauth!.exchangeUrl);+ expect(exchanges[0]!.body.code).toBe("auth-code-1");+ expect(exchanges[0]!.body.code_challenge_method).toBe("S256");+ expect(String(exchanges[0]!.body.code_verifier)).toMatch(/^[A-Za-z0-9._~-]{43,128}$/);+ expect(started.authorizeUrl).not.toContain(String(exchanges[0]!.body.code_verifier));++ const models = (await (+ await owner.get(`/api/projects/${projectId}/models`)+ ).json()) as ModelsResponse;+ const group = models.models.filter((m) => m.provider === "tokendance");+ expect(group.length).toBeGreaterThan(0);+ for (const m of group) expect(m.credential?.apiKeyMasked).toBeTruthy();+ // Only that group, and never in plaintext.+ for (const m of models.models.filter((m) => m.provider !== "tokendance")) {+ expect(m.credential?.apiKeyMasked).toBeUndefined();+ }+ expect(JSON.stringify(models)).not.toContain("sk-oauth-minted-key-9911");++ const cfg = await readFile(path.join(t.root, projectId, ".project_config.toml"), "utf8");+ expect(cfg).toContain("sk-oauth-minted-key-9911");++ expect(+ events+ .filter((e) => e.event === "server_event")+ .map((e) => (JSON.parse(e.data) as { type: string }).type),+ ).toContain("credentials_updated");++ const status = (await (+ await owner.get(`${base()}/${started.flowId}`)+ ).json()) as ModelOAuthStatusResponse;+ expect(status).toEqual({ status: "done", provider: "tokendance" });++ // Replaying the same callback cannot spend the flow twice.+ const replay = await owner.get(+ `${base()}/callback?flow=${encodeURIComponent(started.flowId)}&code=auth-code-1`,+ );+ expect(replay.status).toBe(400);+ expect(exchanges).toHaveLength(1);+ });++ it("a rejected code leaves the flow in error and never touches the models", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => jsonResponse(403, { error: "invalid_code" })),+ );+ const started = (await (+ await owner.post(`${base()}/start`, { provider: "tokendance" })+ ).json()) as ModelOAuthStartResponse;+ const cb = await owner.get(`${base()}/callback?flow=${started.flowId}&code=stale`);+ expect(cb.status).toBe(400);+ expect(await cb.text()).toContain("no longer valid");++ const status = (await (+ await owner.get(`${base()}/${started.flowId}`)+ ).json()) as ModelOAuthStatusResponse;+ expect(status.status).toBe("error");+ expect(status.error).toBe("code_rejected");++ const models = (await (+ await owner.get(`/api/projects/${projectId}/models`)+ ).json()) as ModelsResponse;+ for (const m of models.models) expect(m.credential?.apiKeyMasked).toBeUndefined();+ });++ it("a malformed callback link answers a page, not a stack trace", async () => {+ const res = await owner.get(`${base()}/callback?flow=&code=`);+ expect(res.status).toBe(400);+ expect(res.headers.get("content-type")).toContain("text/html");+ expect(await res.text()).toContain("Authorization failed");+ expect(exchanges).toHaveLength(0);+ });++ it("manual mode drops the callback and redeems a pasted code instead", async () => {+ const started = (await (+ await owner.post(`${base()}/start`, { provider: "tokendance", mode: "manual" })+ ).json()) as ModelOAuthStartResponse;+ expect(new URL(started.authorizeUrl).searchParams.has("callback_url")).toBe(false);++ const res = await owner.post(`${base()}/${started.flowId}/code`, { code: "pasted-code" });+ expect(res.status).toBe(200);+ const body = (await res.json()) as ModelOAuthCodeResponse;+ expect(body.ok).toBe(true);+ expect(body.applied).toBeGreaterThan(0);+ expect(exchanges[0]!.body.code).toBe("pasted-code");++ // Single use here too.+ const again = await owner.post(`${base()}/${started.flowId}/code`, { code: "pasted-code" });+ expect(again.status).toBe(409);+ });++ it("polling and redeeming both refuse a member, and 404 an unknown flow", async () => {+ const started = (await (+ await owner.post(`${base()}/start`, { provider: "tokendance" })+ ).json()) as ModelOAuthStartResponse;+ expect((await member.get(`${base()}/${started.flowId}`)).status).toBe(403);+ expect((await member.post(`${base()}/${started.flowId}/code`, { code: "x" })).status).toBe(403);+ expect((await owner.get(`${base()}/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`)).status).toBe(+ 404,+ );+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 761927fc..47e32e93 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -51,6 +51,10 @@ import type {MemoryOverviewResponse,MemoryScopeExport,MessagesResponse,+ ModelOAuthCodeResponse,+ ModelOAuthStartRequest,+ ModelOAuthStartResponse,+ ModelOAuthStatusResponse,ModelProtocolDetectRequest,ModelProtocolDetectResponse,ModelsResponse,@@ -254,6 +258,32 @@ export const detectVision = (projectId: string, body: ModelVisionDetectRequest){ method: "POST", body },);+// Provider key minting (owner) ----------------------------------------------------------++/**+ * Opens an authorization flow for a provider group that publishes one, and returns the page+ * to send the user to. The PKCE verifier and the key it eventually mints stay on the server;+ * this side only ever holds the flow id.+ */+export const startModelOAuth = (projectId: string, body: ModelOAuthStartRequest) =>+ apiFetch<ModelOAuthStartResponse>(+ `/api/projects/${encodeURIComponent(projectId)}/model-oauth/start`,+ { method: "POST", body },+ );++/** Where a flow stands; 404 once it has expired. */+export const getModelOAuthStatus = (projectId: string, flowId: string) =>+ apiFetch<ModelOAuthStatusResponse>(+ `/api/projects/${encodeURIComponent(projectId)}/model-oauth/${encodeURIComponent(flowId)}`,+ );++/** Redeems a code the user pasted, for when the provider's redirect cannot reach the harness. */+export const submitModelOAuthCode = (projectId: string, flowId: string, code: string) =>+ apiFetch<ModelOAuthCodeResponse>(+ `/api/projects/${encodeURIComponent(projectId)}/model-oauth/${encodeURIComponent(flowId)}/code`,+ { method: "POST", body: { code } },+ );+// Vault environment variables (Agent-level) -------------------------------------------------------export const getVault = (projectId: string, agentId: string) =>diff --git a/packages/web/src/components/ui/provider-logo.tsx b/packages/web/src/components/ui/provider-logo.tsxindex f766b147..e75aab14 100644--- a/packages/web/src/components/ui/provider-logo.tsx+++ b/packages/web/src/components/ui/provider-logo.tsx@@ -3,8 +3,8 @@* light and dark themes).** Anthropic / OpenAI / Google Gemini / DeepSeek / Moonshot AI / OpenRouter /- * SiliconFlow / Qwen Token Plan / Qwen Pay-As-You-Go / Fireworks AI / MiniMax use- * each vendor's brand mark (for recognition purposes, not under trademark license;+ * SiliconFlow / TokenDance / Qwen Token Plan / Qwen Pay-As-You-Go / Fireworks AI /+ * MiniMax use each vendor's brand mark (for recognition purposes, not under trademark license;* Qwen's official gradient wordmark is flattened to currentColor monochrome).* Z.AI uses a simplified geometric approximation of its branded glyph (not an* exact reproduction of the trademark); custom models use a generic cube. All@@ -90,6 +90,33 @@ const GLYPHS: Record<string, Glyph> = {<path d="M50.7172 0H27.6622C26.3877 0 25.3586 1.03397 25.3586 2.30358V9.21911C25.3586 10.4935 24.3294 11.5227 23.055 11.5227H2.30357C1.02914 11.5227 0 12.5567 0 13.8263V23.0502C0 24.3246 1.03395 25.3538 2.30357 25.3538H25.3586C26.633 25.3538 27.6622 24.3198 27.6622 23.0502V16.1347C27.6622 14.8602 28.6913 13.8311 29.9657 13.8311H50.7172C51.9916 13.8311 53.0207 12.7971 53.0207 11.5275V2.30358C53.0207 1.02916 51.9868 0 50.7172 0Z" />),},+ tokendance: {+ // The official TokenDance mark, taken from the brand SVG with its black rounded-square+ // backdrop dropped: the ribbon is a plain fill, while the two motion ticks keep the round+ // caps they are drawn with and override the wrapper's fill-only presentation. The+ // viewBox is cropped to the mark's ink, so the ribbon spans the icon's full width; at+ // 1.35:1 it letterboxes top and bottom in a square box, as the other wide marks do.+ viewBox: "50.79 100 378.72 280.5",+ path: (+ <>+ <path d="M159 162H52.789C51.4198 162 50.4555 160.655 50.8947 159.358L66.8591 112.225C69.3344 104.918 76.192 100 83.9077 100H321.388C324.459 100 327.524 100.21 330.551 100.726C336.545 101.747 347.179 103.791 354.5 106.5C395.04 121.504 418.5 160 426 191C433.5 222 432 274.5 390.5 327C349 379.5 284 380.5 282 380.5H175.767C174.399 380.5 173.451 379.159 173.886 377.863L192.567 322.275C193.123 320.623 194.677 319.52 196.42 319.545C207.729 319.703 230.558 319.865 251 319.5C279 319 286 318.5 310 305.5C334 292.5 360.5 252.5 352 209.5C345.2 175.1 315.5 163.5 301.5 162H228.992C221.236 162 214.351 166.969 211.908 174.331L147.592 368.169C145.149 375.531 138.264 380.5 130.508 380.5H73.7532C72.3943 380.5 71.4179 379.214 71.8379 377.922C89.6259 323.19 124.669 214.961 129 200C133.4 184.8 150.833 168.333 159 162Z" />+ <path+ d="M233 264L248 216"+ fill="none"+ stroke="currentColor"+ strokeWidth={25}+ strokeLinecap="round"+ />+ <path+ d="M280 264L295 216"+ fill="none"+ stroke="currentColor"+ strokeWidth={25}+ strokeLinecap="round"+ />+ </>+ ),+ },"qwen-token-plan": QWEN_GLYPH,"qwen-pay-as-you-go": QWEN_GLYPH,minimax: {diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex 4cd11f21..4995a459 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -166,6 +166,8 @@ const KEY_ICON ="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4";const EXTERNAL_LINK_ICON ="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3";+/** Arrow entering a door: authorize with the provider and come back with a key. */+const SIGN_IN_ICON = "M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4M10 17l5-5-5-5M15 12H3";/** Speed-test glyphs (24x24 line paths): gauge for the group action, clock = TTFT, zap = TPS. */const GAUGE_ICON = "M12 14l3.5-3.5M20.49 17A10 10 0 1 0 3.5 17";@@ -583,6 +585,8 @@ export function ModelsPage() {const [groupDropHint, setGroupDropHint] = useState<{ key: string; after: boolean } | null>(null);/** Vendor group (provider id) currently having its API key configured in bulk. */const [groupKeyFor, setGroupKeyFor] = useState<string | null>(null);+ /** Vendor group (provider id) whose authorization dialog is open (groups that publish a key-minting flow only). */+ const [oauthFor, setOauthFor] = useState<string | null>(null);/** User-defined group (provider id) whose delete confirmation is open (built-in groups never offer this). */const [deleteGroupFor, setDeleteGroupFor] = useState<string | null>(null);/** "Add group" popup (user-defined group): create-only hands off to that group's add-model dialog, import mode fills the group from its endpoint (see AddGroupDialog). */@@ -981,6 +985,25 @@ export function ModelsPage() {<span className="hidden @3xl:inline">{S.models.addToGroup}</span></Button>)}+ {isOwner && group.provider.oauth && (+ // Authorize-a-key action: rendered off the group's own catalog+ // descriptor, so a provider gains this button by publishing a flow+ // rather than by being named here. Same narrow-row rule as its+ // neighbours — the label goes, the icon and its names stay. It leads the+ // manual key action: where a group can mint a key, that is the shorter path.+ <Button+ size="sm"+ variant="ghost"+ className="shrink-0"+ disabled={busy}+ aria-label={`${S.models.oauthKey} ${group.provider.label}`}+ title={S.models.oauthKey}+ onClick={() => setOauthFor(group.provider.id)}+ >+ <GlyphIcon d={SIGN_IN_ICON} size={13} />+ <span className="hidden @3xl:inline">{S.models.oauthKey}</span>+ </Button>+ )}{isOwner && group.provider.id !== "custom" && (// Bulk key action: icon-only while this row is narrow, labeled from// @3xl up. The button itself never disappears — aria-label + title@@ -1149,6 +1172,22 @@ export function ModelsPage() {/>)}+ {rows && projectId && oauthFor !== null && (+ <ModelOAuthDialog+ projectId={projectId}+ provider={MODEL_PROVIDERS.find((p) => p.id === oauthFor) ?? userProviderInfo(oauthFor)}+ count={rows.filter((r) => r.provider === oauthFor).length}+ onClose={() => setOauthFor(null)}+ onApplied={(applied) => {+ setOauthFor(null);+ toastSuccess(S.models.oauthApplied(applied));+ // The key was written server-side, so the table in hand is stale in exactly one+ // place: reload rather than patch, and the masked key comes back with it.+ void load();+ }}+ />+ )}+{rows && deleteGroupFor !== null && (<ConfirmModalopen@@ -2977,3 +3016,201 @@ function GroupKeyDialog({</Modal>);}++// ---------------------------------------------------------------------------+// Authorize a new API key for a provider group+// ---------------------------------------------------------------------------++/** Where the dialog is: opening a flow, holding one, waiting on an outcome, or reporting a failure. */+type OAuthPhase = "starting" | "ready" | "waiting" | "failed";++/** How often the redirect flow's outcome is asked for while the user is in the other tab. */+const OAUTH_POLL_MS = 2000;++/**+ * Mint a fresh API key for a whole provider group by authorizing in the browser.+ *+ * The dialog never handles the key, and never handles the PKCE verifier either: it opens a+ * flow, sends the user to the provider's page, and asks the server how that flow ended. Two+ * routes back — the provider redirects to the server (polled here), or, when that redirect+ * cannot reach the harness, the user carries a one-time code across by hand.+ */+function ModelOAuthDialog({+ projectId,+ provider,+ count,+ onClose,+ onApplied,+}: {+ projectId: string;+ provider: ModelProviderInfo;+ /** Models in the group; every one of them gets the new key. */+ count: number;+ onClose: () => void;+ onApplied: (applied: number) => void;+}) {+ const [manual, setManual] = useState(false);+ const [phase, setPhase] = useState<OAuthPhase>("starting");+ const [flow, setFlow] = useState<{ flowId: string; authorizeUrl: string } | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [code, setCode] = useState("");+ /** Bumped to reopen a flow after a failure; switching modes reopens one too (the URL differs). */+ const [attempt, setAttempt] = useState(0);+ // Latest-callback ref: the parent passes an inline arrow, and depending on its identity+ // would tear down and restart the poll interval on every render.+ const onAppliedRef = useRef(onApplied);+ onAppliedRef.current = onApplied;++ // A flow is opened as soon as the dialog shows, so the authorize URL is already in hand+ // when the button is pressed — window.open then runs inside that click's own user+ // activation, which is what keeps a popup blocker out of the way.+ useEffect(() => {+ let cancelled = false;+ setPhase("starting");+ setFlow(null);+ setError(null);+ setCode("");+ void (async () => {+ try {+ const res = await api.startModelOAuth(projectId, {+ provider: provider.id,+ mode: manual ? "manual" : "callback",+ });+ if (cancelled) return;+ setFlow(res);+ setPhase("ready");+ } catch (e) {+ if (cancelled) return;+ setError(apiErrorText(e));+ setPhase("failed");+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [projectId, provider.id, manual, attempt]);++ // Redirect mode: the outcome lands on the server, so this tab only learns of it by asking.+ // A flow that has expired answers 404, which reads the same as never coming back.+ useEffect(() => {+ if (phase !== "waiting" || manual || flow === null) return;+ let stopped = false;+ const tick = async (): Promise<void> => {+ try {+ const res = await api.getModelOAuthStatus(projectId, flow.flowId);+ if (stopped) return;+ if (res.status === "done") {+ onAppliedRef.current(count);+ return;+ }+ if (res.status === "error") {+ setError(res.error ? S.models.oauthErrors[res.error] : S.models.oauthTimedOut);+ setPhase("failed");+ }+ } catch {+ if (stopped) return;+ setError(S.models.oauthTimedOut);+ setPhase("failed");+ }+ };+ const timer = window.setInterval(() => void tick(), OAUTH_POLL_MS);+ return () => {+ stopped = true;+ window.clearInterval(timer);+ };+ }, [phase, manual, flow, projectId, count]);++ const openAuthorizePage = (): void => {+ if (flow === null) return;+ window.open(flow.authorizeUrl, "_blank", "noopener,noreferrer");+ if (!manual) setPhase("waiting");+ };++ const submitCode = async (): Promise<void> => {+ if (flow === null) return;+ setPhase("waiting");+ setError(null);+ try {+ const res = await api.submitModelOAuthCode(projectId, flow.flowId, code.trim());+ if (res.ok) {+ onAppliedRef.current(res.applied ?? count);+ return;+ }+ setError(res.error ? S.models.oauthErrors[res.error] : S.models.oauthTimedOut);+ setPhase("failed");+ } catch (e) {+ setError(apiErrorText(e));+ setPhase("failed");+ }+ };++ const primary =+ phase === "failed" ? (+ <Button variant="primary" onClick={() => setAttempt((n) => n + 1)}>+ {S.models.oauthRetry}+ </Button>+ ) : manual ? (+ <Button+ variant="primary"+ disabled={flow === null || phase === "waiting" || !code.trim()}+ onClick={() => void submitCode()}+ >+ {S.models.oauthSubmitCode}+ </Button>+ ) : (+ <Button variant="primary" disabled={flow === null} onClick={openAuthorizePage}>+ {S.models.oauthAuthorize}+ </Button>+ );++ return (+ <Modal+ open+ title={S.models.oauthTitle(provider.label)}+ onClose={onClose}+ footer={+ <>+ <Button onClick={onClose}>{S.common.cancel}</Button>+ {primary}+ </>+ }+ >+ <div className="space-y-3">+ <p className="text-sm text-gray-700 dark:text-gray-300">+ {S.models.oauthIntro(provider.label, count)}+ </p>+ {manual && (+ <>+ <Button variant="ghost" disabled={flow === null} onClick={openAuthorizePage}>+ <GlyphIcon d={SIGN_IN_ICON} size={13} />+ {S.models.oauthAuthorize}+ </Button>+ <Input+ size="sm"+ label={S.models.oauthCodeLabel}+ hint={S.models.oauthManualHint}+ value={code}+ onChange={(e) => setCode(e.target.value)}+ className="font-mono"+ autoComplete="off"+ />+ </>+ )}+ {phase === "waiting" && !manual && (+ <p className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">+ <span className="inline-block h-2.5 w-2.5 shrink-0 animate-spin rounded-full border border-current border-t-transparent" />+ {S.models.oauthWaiting}+ </p>+ )}+ {error !== null && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}+ <button+ type="button"+ onClick={() => setManual((v) => !v)}+ className="text-xs text-brand-600 underline-offset-2 hover:underline dark:text-brand-300"+ >+ {manual ? S.models.oauthCallbackSwitch : S.models.oauthManualSwitch}+ </button>+ </div>+ </Modal>+ );+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 810c9f1a..d6839c22 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -769,13 +769,36 @@ export const en: Strings = {confirmDeleteTitle: "Delete model",confirmDelete: (name: string): string =>`Delete "${name}"? Its configuration and API key will be removed.`,- groupApiKey: "Set API key for group",+ groupApiKey: "Set key",groupApiKeyTitle: (label: string): string => `Set the API key for ${label}`,groupApiKeyHint: (n: number): string =>`Applies to all ${n} models in this group; leave empty to keep them unchanged.`,- getApiKey: "Get API key",+ getApiKey: "Manage keys",getModelIds: "Get model IDs",groupKeyApplied: (n: number): string => `API key set for ${n} models`,+ oauthKey: "Authorize key",+ oauthTitle: (label: string): string => `Authorize a new ${label} API key`,+ oauthIntro: (label: string, n: number): string =>+ `A new API key will be created on your ${label} account and written to all ${n} models in this group, replacing the key they use now.`,+ oauthAuthorize: "Open authorization page",+ oauthWaiting: "Waiting for the authorization to finish in the other tab…",+ oauthApplied: (n: number): string => `New API key set for ${n} models`,+ oauthManualSwitch: "Page can't redirect back? Enter the code by hand",+ oauthCallbackSwitch: "Go back to the automatic redirect",+ oauthManualHint: "Open the authorization page, then paste the one-time code it shows you here.",+ oauthCodeLabel: "Authorization code",+ oauthSubmitCode: "Submit code",+ oauthTimedOut: "The authorization never came back. Enter the code by hand, or start again.",+ oauthRetry: "Start again",+ oauthErrors: {+ invalid_request: "The authorization request was rejected. Start again.",+ code_rejected:+ "That authorization is no longer valid: it expired or was already used. Start again.",+ upstream_failed: "The provider returned no usable key. Start again.",+ unreachable: "The provider could not be reached. Check the network and start again.",+ apply_failed:+ "A key was created but could not be saved. Authorize again, then delete the unused key in the provider's console.",+ },providerEnvNotes: {zhipu:"Defaults to the Z.AI global endpoint (api.z.ai); keys from bigmodel.cn need base URL https://open.bigmodel.cn/api/paas/v4",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex c27cab14..f441f93e 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -587,7 +587,7 @@ export const zh = {models: {title: "模型配置",addCustom: "添加自定义模型",- addToGroup: "新增模型",+ addToGroup: "添加模型",editTitle: "模型配置",addTitle: "新增模型(OpenAI 协议)",addTitleVendor: "新增模型",@@ -617,7 +617,7 @@ export const zh = {groupNameHint: "小写字母 / 数字开头,可含 - 与 _",groupNameInvalid: "分组名只能用小写字母、数字、- 与 _(首字符为字母或数字),长度不超过 32",groupNameExists: "该分组名已被内置分组或既有条目占用",- groupEmptyHint: "该分组暂无模型,点「新增模型」添加",+ groupEmptyHint: "该分组暂无模型,点「添加模型」创建",deleteGroup: "删除分组",deleteGroupTitle: "删除分组",deleteGroupConfirm: (label: string, n: number): string =>@@ -741,12 +741,35 @@ export const zh = {confirmDeleteTitle: "删除模型",confirmDelete: (name: string): string =>`确定删除「${name}」?该模型的配置与 API key 将一并移除。`,- groupApiKey: "统一配置 API key",+ groupApiKey: "手动设置密钥",groupApiKeyTitle: (label: string): string => `为「${label}」统一配置 API key`,groupApiKeyHint: (n: number): string => `将写入该分组下全部 ${n} 个模型;留空不改动。`,- getApiKey: "获取 API key",+ getApiKey: "前往密钥管理",getModelIds: "获取模型 id",groupKeyApplied: (n: number): string => `已为 ${n} 个模型配置 API key`,+ // 供应商授权取 key(模型分组头部动作):整个 PKCE 流程都在服务端跑,前端只拿到一个+ // 不透明的 flow id 和状态。+ oauthKey: "自动获取密钥",+ oauthTitle: (label: string): string => `从「${label}」授权新建 API key`,+ oauthIntro: (label: string, n: number): string =>+ `将在你的 ${label} 账户下新建一个 API key,并写入该分组下全部 ${n} 个模型,覆盖它们当前的 key。`,+ oauthAuthorize: "打开授权页",+ oauthWaiting: "等待在新标签页中完成授权…",+ oauthApplied: (n: number): string => `已为 ${n} 个模型配置新的 API key`,+ oauthManualSwitch: "授权页跳不回来?改为手动填写授权码",+ oauthCallbackSwitch: "改回自动跳转",+ oauthManualHint: "先打开授权页,再把页面上显示的一次性授权码粘贴到这里。",+ oauthCodeLabel: "授权码",+ oauthSubmitCode: "提交授权码",+ oauthTimedOut: "没有等到授权结果。可以改为手动填写授权码,或重新开始。",+ oauthRetry: "重新开始",+ oauthErrors: {+ invalid_request: "授权请求被拒绝,请重新开始。",+ code_rejected: "该授权已失效:可能已过期或被用过,请重新开始。",+ upstream_failed: "供应商没有返回可用的 key,请重新开始。",+ unreachable: "连不上供应商,请检查网络后重新开始。",+ apply_failed: "key 已创建但未能保存。请重新授权,并到供应商控制台删掉那个没用上的 key。",+ },// Providers with separate domestic / international endpoints: note on the default// endpoint used when left blank via env var (the other side's key needs an explicit// base URL). Written to match AgentHub's actual behavior; rendered wherever the env fallback hint appears.diff --git a/packages/web/test/model-grouping.test.ts b/packages/web/test/model-grouping.test.tsindex fdce980e..fb46f1a8 100644--- a/packages/web/test/model-grouping.test.ts+++ b/packages/web/test/model-grouping.test.ts@@ -75,21 +75,22 @@ describe("groupModelRows", () => {expect(groups[4]!.provider.label).toBe("unknown-vendor");expect(groups[4]!.provider.envKey).toBe("OPENAI_API_KEY");expect(groups[4]!.rows.map((r) => r.modelId)).toEqual(["weird-model"]);- // Group order matches MODEL_PROVIDERS: DeepSeek and gateway groups first, then first-party- // providers, with MiniMax immediately before custom.+ // Group order matches MODEL_PROVIDERS, whose sequence is hand-curated (gateways and+ // first-party vendors interleaved): DeepSeek first, custom last.expect(MODEL_PROVIDERS.map((p) => p.id)).toEqual(["deepseek","openrouter","fireworks",- "siliconflow",- "qwen-token-plan",- "qwen-pay-as-you-go","google",- "anthropic","openai",+ "anthropic",+ "siliconflow",+ "tokendance","zhipu","moonshot","minimax",+ "qwen-pay-as-you-go",+ "qwen-token-plan","custom",]);expect(MODEL_PROVIDERS.find((p) => p.id === "siliconflow")!.label).toBe("SiliconFlow");