Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(models): add ModelScope authorization and refresh (#814)

Laodouuud127b6eea843
diff --git a/changelog/unreleased/2026-09-21-backward-compatibility.md b/changelog/unreleased/2026-09-21-backward-compatibility.md
new file mode 100644
index 00000000..01b60812
--- /dev/null
+++ b/changelog/unreleased/2026-09-21-backward-compatibility.md
@@ -0,0 +1,22 @@
+# ModelScope refresh-token compatibility
+
+- **Date:** 2026-09-21
+- **Type:** process
+- **Scope:** `server`, `model-catalog`
+- **PR:** [#814](https://github.com/Prism-Shadow/penguin-harness/pull/814)
+
+[中文版](2026-09-21-backward-compatibility.zh.md)
+
+The [ModelScope authorization change](2026-09-21-modelscope-authorization.md) added server-side refresh metadata without changing the Project TOML schema or invalidating existing model credentials.
+
+## Existing data
+
+Database migration 10 adds the `model_provider_auth_tokens` table for refresh tokens and access-token expiry. Existing `.project_config.toml` files require no migration: the active credential remains in the existing `api_key` field, and an access token saved before this change continues working until it expires. Existing Projects add the ModelScope presets through **Sync presets**.
+
+## Rollback
+
+Earlier builds ignore the new table and continue using the access token from the Project file. Rolling the database back below version 10 drops the stored refresh metadata, so ModelScope requests continue only until that access token expires; authorizing again after returning to this version restores silent renewal.
+
+## Removal schedule
+
+The version-10 migration block and its version-9 fixture stay while upgrades from schema 9 or earlier are supported. The release that raises the minimum supported database baseline above 9 owns removing that migration block and fixture. The `model_provider_auth_tokens` table remains part of the current schema for as long as provider token refresh depends on it.
diff --git a/changelog/unreleased/2026-09-21-backward-compatibility.zh.md b/changelog/unreleased/2026-09-21-backward-compatibility.zh.md
new file mode 100644
index 00000000..56a16bd2
--- /dev/null
+++ b/changelog/unreleased/2026-09-21-backward-compatibility.zh.md
@@ -0,0 +1,22 @@
+# ModelScope refresh token 向后兼容
+
+- **Date:** 2026-09-21
+- **Type:** process
+- **Scope:** `server`, `model-catalog`
+- **PR:** [#814](https://github.com/Prism-Shadow/penguin-harness/pull/814)
+
+[English](2026-09-21-backward-compatibility.md)
+
+[ModelScope 授权改动](2026-09-21-modelscope-authorization.zh.md)新增服务端 refresh 元数据,同时不修改 Project TOML schema,也不让既有模型凭据失效。
+
+## 既有数据
+
+数据库 migration 10 新增 `model_provider_auth_tokens` 表,用于保存 refresh token 与 access token 到期时间。既有 `.project_config.toml` 文件无需迁移:当前凭据继续使用既有的 `api_key` 字段,本次改动前保存的 access token 在到期前仍然可用。既有 Project 通过**同步预置**加入 ModelScope 预置模型。
+
+## 回滚
+
+旧版本会忽略新表,并继续使用 Project 文件中的 access token。数据库回滚到版本 10 以下会删除已保存的 refresh 元数据,因此 ModelScope 请求只能继续到该 access token 过期;重新升级到当前版本后再次授权,即可恢复静默续期。
+
+## 移除计划
+
+只要仍支持从 schema 9 或更早版本升级,版本 10 的 migration 代码与版本 9 fixture 就会保留。将最低支持数据库基线提升到 9 以上的发布负责移除该 migration 代码与 fixture。只要模型组令牌刷新仍依赖 `model_provider_auth_tokens` 表,该表就继续保留在当前 schema 中。
diff --git a/changelog/unreleased/2026-09-21-modelscope-authorization.md b/changelog/unreleased/2026-09-21-modelscope-authorization.md
new file mode 100644
index 00000000..01f92176
--- /dev/null
+++ b/changelog/unreleased/2026-09-21-modelscope-authorization.md
@@ -0,0 +1,25 @@
+# ModelScope authorization and token renewal
+
+- **Date:** 2026-09-21
+- **Type:** feature
+- **Scope:** `model-catalog`, `server`, `web`, `docs`, `core`
+- **PR:** [#814](https://github.com/Prism-Shadow/penguin-harness/pull/814)
+
+[中文版](2026-09-21-modelscope-authorization.zh.md)
+
+Added ModelScope as an authorized aggregate model group with three presets, model-specific AgentHub protocols, and server-managed token renewal.
+
+## Models and authorization
+
+- Added `deepseek-ai/DeepSeek-V4.1-Flash` through `deepseek-v4` and `Qwen/Qwen3.8-27B` plus `Qwen/Qwen3.8-Flash-Next` through `openai-chat-vllm-adapter` at ModelScope's API-Inference endpoint.
+- Added the monochrome ModelScope mark and an authorization dialog that sends the browser through the ModelScope bridge without exposing delivered credentials to the Web App.
+
+## Token renewal
+
+- Stored refresh tokens and access-token expiry server-side, while continuing to store the current access token in the existing Project `api_key` field.
+- Refreshed an expiring credential before ModelScope requests, serialized refresh and model-config writes, and asked the user to authorize again after repeated refresh failures.
+- Recorded the database and rollback behavior in [ModelScope refresh-token compatibility](2026-09-21-backward-compatibility.md).
+
+## Existing projects
+
+New Projects receive the three ModelScope presets. Existing Projects receive them only after the user runs **Sync presets** on the models page; synchronization appends and updates catalog-owned fields without deleting models or changing the stored default.
diff --git a/changelog/unreleased/2026-09-21-modelscope-authorization.zh.md b/changelog/unreleased/2026-09-21-modelscope-authorization.zh.md
new file mode 100644
index 00000000..5892b7c3
--- /dev/null
+++ b/changelog/unreleased/2026-09-21-modelscope-authorization.zh.md
@@ -0,0 +1,25 @@
+# ModelScope 授权与令牌续期
+
+- **Date:** 2026-09-21
+- **Type:** feature
+- **Scope:** `model-catalog`, `server`, `web`, `docs`, `core`
+- **PR:** [#814](https://github.com/Prism-Shadow/penguin-harness/pull/814)
+
+[English](2026-09-21-modelscope-authorization.md)
+
+新增 ModelScope 授权聚合模型组、三条预置模型、按模型区分的 AgentHub 协议,以及由服务端管理的令牌续期。
+
+## 模型与授权
+
+- 在 ModelScope API-Inference 端点新增通过 `deepseek-v4` 请求的 `deepseek-ai/DeepSeek-V4.1-Flash`,以及通过 `openai-chat-vllm-adapter` 请求的 `Qwen/Qwen3.8-27B` 和 `Qwen/Qwen3.8-Flash-Next`。
+- 新增纯色 ModelScope 标识与授权弹窗;浏览器通过 ModelScope bridge 完成授权,交付的凭据不会暴露给 Web App。
+
+## 令牌续期
+
+- refresh token 与 access token 到期时间保存在服务端,当前 access token 继续使用 Project 中既有的 `api_key` 字段。
+- 在 ModelScope 请求前刷新即将过期的凭据,串行处理刷新与模型配置写入,并在连续刷新失败后提示用户重新授权。
+- 数据库与回滚行为记录在 [ModelScope refresh token 向后兼容](2026-09-21-backward-compatibility.zh.md)中。
+
+## 既有 Project
+
+新建 Project 会带有三条 ModelScope 预置模型。既有 Project 只有在用户于模型页面执行**同步预置**后才会获得这些模型;同步会追加模型并更新目录管理的字段,不会删除模型或修改已保存的默认模型。
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 117b2c1b..0d3d06fb 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -171,6 +171,19 @@ export interface AgentAssembly {
* text. Empty = the prompt is exactly the Agent's own.
*/
promptSections?(): readonly PromptSection[];
+ /**
+ * Resolves a model credential immediately before an upstream request. Hosting processes can
+ * rotate short-lived credentials here; core neither knows nor interprets the provider.
+ */
+ resolveModelApiKey?(context: ModelRequestContext): Promise<string | undefined>;
+}
+
+export interface ModelRequestContext {
+ projectId: string;
+ agentId?: string;
+ sessionId?: string;
+ provider: string;
+ modelId: string;
}
export interface PromptSection {
@@ -1119,6 +1132,18 @@ export class Agent {
new GenerativeModel({
modelId: visionEntry.model_id,
...(visionEntry.api_key !== undefined ? { apiKey: visionEntry.api_key } : {}),
+ ...(this.assembly?.resolveModelApiKey
+ ? {
+ resolveApiKey: () =>
+ this.assembly!.resolveModelApiKey!({
+ projectId: this.state.projectId,
+ agentId: this.state.agentId,
+ sessionId,
+ provider: visionEntry.provider,
+ modelId: visionEntry.model_id,
+ }),
+ }
+ : {}),
...(visionEntry.base_url !== undefined ? { baseUrl: visionEntry.base_url } : {}),
...(visionEntry.client_type !== undefined
? { clientType: visionEntry.client_type }
@@ -1194,6 +1219,18 @@ export class Agent {
modelId: modelEntry.model_id,
toolCallIds,
...(apiKey !== undefined ? { apiKey } : {}),
+ ...(this.assembly?.resolveModelApiKey
+ ? {
+ resolveApiKey: () =>
+ this.assembly!.resolveModelApiKey!({
+ projectId: this.state.projectId,
+ agentId: this.state.agentId,
+ sessionId,
+ provider: modelEntry.provider,
+ modelId: modelEntry.model_id,
+ }),
+ }
+ : {}),
...(baseUrl !== undefined ? { baseUrl } : {}),
...(modelEntry.client_type !== undefined ? { clientType: modelEntry.client_type } : {}),
tools,
@@ -1268,6 +1305,18 @@ export class Agent {
new GenerativeModel({
modelId: modelEntry.model_id,
...(apiKey !== undefined ? { apiKey } : {}),
+ ...(this.assembly?.resolveModelApiKey
+ ? {
+ resolveApiKey: () =>
+ this.assembly!.resolveModelApiKey!({
+ projectId: this.state.projectId,
+ agentId: this.state.agentId,
+ sessionId,
+ provider: modelEntry.provider,
+ modelId: modelEntry.model_id,
+ }),
+ }
+ : {}),
...(baseUrl !== undefined ? { baseUrl } : {}),
...(modelEntry.client_type !== undefined ? { clientType: modelEntry.client_type } : {}),
tools: [],
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 4c48d2b2..1577606e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -50,7 +50,7 @@ export type {
} from "./engine/context-engine.js";
export { Session } from "./session.js";
export type { SessionConfig } from "./session.js";
-export type { AgentAssembly, PromptSection } from "./agent.js";
+export type { AgentAssembly, ModelRequestContext, PromptSection } from "./agent.js";
// Session-title generation lives in internal/ (an assembly detail of Session.generateTitle);
// only its narrow public surface is re-exported: the result type (part of
// Session.generateTitle's signature) and the two cleaners, sanitizeTitle and truncateTitle,
diff --git a/packages/core/src/interfaces/llm.ts b/packages/core/src/interfaces/llm.ts
index 2502437d..dba5af98 100644
--- a/packages/core/src/interfaces/llm.ts
+++ b/packages/core/src/interfaces/llm.ts
@@ -20,6 +20,12 @@ import type { ToolCallIdAllocator } from "../llm/tool-call-ids.js";
export interface GenerativeModelConfig {
modelId: string;
apiKey?: string;
+ /**
+ * Optional host-owned credential resolver, called before every upstream request. When it
+ * returns a different key, the AgentHub client is rebuilt with its stateful history intact.
+ * Core assigns no provider semantics to this hook.
+ */
+ resolveApiKey?: () => Promise<string | undefined>;
baseUrl?: string;
/**
* AgentHub client protocol (`openai-chat` / `openai-responses` / `claude-4-8` /
diff --git a/packages/core/src/llm/generative-model.ts b/packages/core/src/llm/generative-model.ts
index 41a0fc25..b5f02fb9 100644
--- a/packages/core/src/llm/generative-model.ts
+++ b/packages/core/src/llm/generative-model.ts
@@ -932,7 +932,10 @@ export function isFatalProviderRejection(error: unknown): boolean {
* handled by `context_engine`.
*/
export class GenerativeModel implements LLMInterface {
- private readonly client: AutoLLMClient;
+ private client: AutoLLMClient;
+ private readonly clientOptions: Omit<ConstructorParameters<typeof AutoLLMClient>[0], "apiKey">;
+ private currentApiKey: string | undefined;
+ private readonly resolveApiKey: (() => Promise<string | undefined>) | undefined;
private readonly uniConfig: UniConfig;
/**
* Construction-time default thinking level. Kept **out of the frozen uniConfig**: the
@@ -984,12 +987,17 @@ export class GenerativeModel implements LLMInterface {
// at all. The Session's id rides along for the schemes that name the conversation rather
// than the app.
const headers = attributionHeaders(config.baseUrl, config.sessionId);
- this.client = new AutoLLMClient({
+ this.clientOptions = {
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.currentApiKey = config.apiKey;
+ this.resolveApiKey = config.resolveApiKey;
+ this.client = new AutoLLMClient({
+ ...this.clientOptions,
+ ...(this.currentApiKey !== undefined ? { apiKey: this.currentApiKey } : {}),
});
this.uniConfig = buildUniConfig(config);
@@ -1004,6 +1012,18 @@ export class GenerativeModel implements LLMInterface {
this.lastRequestTotal = this.baseInputTokens;
}
+ /** Swap a rotated credential into AgentHub without losing its stateful conversation. */
+ private async refreshApiKey(): Promise<void> {
+ if (this.resolveApiKey === undefined) return;
+ const nextApiKey = await this.resolveApiKey();
+ if (nextApiKey === undefined || nextApiKey === this.currentApiKey) return;
+ const history = this.client.getHistory();
+ const next = new AutoLLMClient({ ...this.clientOptions, apiKey: nextApiKey });
+ if (history.length > 0) next.setHistory(history);
+ this.client = next;
+ this.currentApiKey = nextApiKey;
+ }
+
/**
* The UniConfig for one request: the shared frozen config plus this request's effective
* thinking level (per-request override, else the construction-time default; neither → the
@@ -1169,6 +1189,7 @@ export class GenerativeModel implements LLMInterface {
// rejections) / aborted (user). null means it ended normally.
let outcome: LLMOutcome | null = null;
try {
+ await this.refreshApiKey();
const it = this.openStream(
uniMessage,
ac.signal,
diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.ts
index 00ba0a66..c864468c 100644
--- a/packages/core/src/state/model-catalog.ts
+++ b/packages/core/src/state/model-catalog.ts
@@ -19,7 +19,9 @@
* lists, TokenDance's deepseek-v4-flash-0731 / deepseek-v4-pro-0813 / kimi-k3 promotions, the
* OpenRouter qwen/qwen3.8-27b row, the Fireworks AI and SiliconFlow additions, and both Qwen
* groups' line-ups with their peak/off-peak DeepSeek rows: 2026-09-16 — per each provider's
- * docs).
+ * docs; and the ModelScope group, whose preset ids were read from public model pages and
+ * endpoint listings — their windows, vision flags and prices are NOT verified and say so on the
+ * rows themselves: 2026-09-18 and 2026-09-20).
* Docs: packages/docs/content/models.{zh,en}.md (site path /docs/models) documents the
* provider groups and credential resolution described here.
*
@@ -40,10 +42,12 @@
* (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 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. Two groups pin at GROUP level as well (ModelProviderInfo.clientType, read
+ * auto-routed by AgentHub and leave client_type unset; six gateway groups (OpenRouter,
+ * Fireworks AI, SiliconFlow, TokenDance, Qwen Pay-As-You-Go and Qwen Token Plan)
+ * can't be auto-routed, so every gateway row **always pins an explicit client_type** and
+ * inlines its preset base URL. ModelScope is a mixed-protocol aggregator like Penguin Go:
+ * each row pins the AgentHub protocol that its upstream model should display and use.
+ * Two groups pin at GROUP level as well (ModelProviderInfo.clientType, read
* through providerClientType), so that a model the user adds there speaks the same protocol
* as the presets: vLLM, whose added models have no preset base URL to inherit either, and
* OpenRouter, whose do — see each group's own block comment.
@@ -55,12 +59,16 @@
* - `openai-responses` for every OpenRouter row: OpenRouter serves the Responses API for
* every upstream at the same base URL the rows already carry, and the group pins the same
* protocol so a user-added entry inherits it;
- * - `openai-chat` for the other gateway rows (AgentHub 0.4.2's canonical name for the
- * generic Chat Completions client — the bare "openai" spelling is a deprecated upstream
- * alias, see canonicalClientType);
+ * - `openai-chat` for the other OpenAI-compatible gateway rows (AgentHub 0.4.2's canonical
+ * name for the generic Chat Completions client — the bare "openai" spelling is a
+ * deprecated upstream alias, see canonicalClientType);
* - `openai-chat-vllm-adapter` for the vLLM group, which is Chat Completions on the wire
* but maps the thinking level onto the served model's own chat template
* (VLLM_CLIENT_TYPE).
+ * ModelScope's rows follow the same explicit-row rule as Penguin Go even though the endpoint is
+ * one gateway: its Qwen rows pin the vLLM adapter, while its DeepSeek row pins `deepseek-v4` so
+ * the frontend shows each model's actual AgentHub protocol instead of flattening the group.
+ *
* Two direct-vendor rows pin anyway, because their own id does not route: the MiniMax M3
* preset pins AgentHub's first-party `minimax-m3` protocol and direct API endpoint, and
* `deepseek-flash` pins `deepseek-v4` because AgentHub 0.4.11 routes DeepSeek on that
@@ -90,6 +98,26 @@ export interface ModelProviderOAuth {
keyName: string;
}
+/**
+ * A group whose credential the App obtains through its own authorization flow rather than by
+ * asking the vendor: the client registers a one-time code and device secret with an external
+ * bridge, sends the user to the page that bridge hands back, and polls until the bridge
+ * delivers the credential. Distinct from `oauth`, where the App itself speaks the vendor's
+ * PKCE page — here the App never reaches the vendor at all, because the bridge holds the
+ * client secret that conversation would need.
+ *
+ * The bridge's own address is deliberately NOT here: this file is bundled for the browser and
+ * cannot read configuration, so the App resolves the bridge server-side from its environment
+ * (PENGUIN_GO_ORIGIN / MODELSCOPE_BRIDGE_URL), keyed by the group's id.
+ */
+export interface ModelProviderBridgeAuth {
+ /**
+ * Which App-side flow serves this group — one route family and one service per value, so
+ * the Web App picks from the group's descriptor rather than from its id.
+ */
+ flow: "penguin-go" | "modelscope";
+}
+
export interface ModelProviderInfo {
id: string;
/** Display name (brand name, shared by Chinese and English UI). */
@@ -113,6 +141,13 @@ export interface ModelProviderInfo {
* every provider whose keys are only obtainable from its console.
*/
oauth?: ModelProviderOAuth;
+ /**
+ * The App-side authorization flow that obtains this group's credential (see
+ * ModelProviderBridgeAuth); absent for every group whose credential comes from a console or
+ * from the vendor's own page. Declaring it is what puts the "authorize a key" action on the
+ * group in the Web App.
+ */
+ bridgeAuth?: ModelProviderBridgeAuth;
/**
* The AgentHub protocol EVERY entry in this group speaks, models the user adds included.
*
@@ -213,11 +248,15 @@ 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";
const DEEPSEEK_BASE_URL = "https://api.deepseek.com";
+const MODELSCOPE_BASE_URL = "https://api-inference.modelscope.cn/v1";
export const PENGUIN_GO_BASE_URL = "https://token.penguin.ooo/api";
/** Provider id for the preconfigured Penguin Go relay group. */
export const PENGUIN_GO_PROVIDER_ID = "penguin-go";
+/** Provider id for the ModelScope group. */
+export const MODELSCOPE_PROVIDER_ID = "modelscope";
+
/**
* Provider list (web model page groups in this order BY DEFAULT — a user's dragged
* arrangement is stored per Project and wins over this sequence; see the web's
@@ -229,12 +268,14 @@ export const PENGUIN_GO_PROVIDER_ID = "penguin-go";
* moves when the curation changes: a Project that has ever reordered its groups has every
* key stored already, so it keeps the arrangement its user built.
*
- * 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
+ * The six OpenAI-compatible 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-responses` for OpenRouter, `openai-chat` for the rest).
* 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.
+ * the gateway's own variable names, so every such gateway group records the OPENAI_* pair and the
+ * env fallback hint the frontend shows is accurate either way. ModelScope also records the
+ * OPENAI_* pair because its group credential is an api-inference access token even when a row's
+ * protocol is model-specific.
*/
export const MODEL_PROVIDERS: ModelProviderInfo[] = [
{
@@ -262,6 +303,7 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [
envBaseUrlKey: "PENGUIN_GO_BASE_URL",
apiKeyUrl: "https://token.penguin.ooo/",
modelsUrl: "https://token.penguin.ooo/",
+ bridgeAuth: { flow: "penguin-go" },
},
{
id: "deepseek",
@@ -370,6 +412,28 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [
"https://platform.qianwenai.com/docs/token-plan/personal/token-plan-personal-overview",
gatewayBaseUrl: QWEN_TOKEN_PLAN_BASE_URL,
},
+ {
+ // ModelScope's own inference service: OpenAI-compatible, reselling other vendors' models
+ // under `org/Model-Name` ids. Two things set it apart from the gateways above.
+ //
+ // Its credential is the account's access token rather than a minted API key, and the
+ // group obtains one through the authorization bridge instead of sending the user to copy
+ // it out of the console (bridgeAuth below; the console link stays for anyone who already
+ // has a token). ModelScope is the vendor here as well as the gateway — the bridge exists
+ // because its OAuth requires a client secret the desktop App cannot keep locally, not
+ // because inference requests are routed through that bridge.
+ //
+ // The endpoint host is still inlined on every preset row; the row's own `client_type` tells
+ // the frontend which AgentHub protocol that upstream model uses, as with Penguin Go.
+ id: MODELSCOPE_PROVIDER_ID,
+ label: "ModelScope",
+ envKey: "OPENAI_API_KEY",
+ envBaseUrlKey: "OPENAI_BASE_URL",
+ apiKeyUrl: "https://www.modelscope.cn/my/myaccesstoken",
+ modelsUrl: "https://www.modelscope.cn/models",
+ gatewayBaseUrl: MODELSCOPE_BASE_URL,
+ bridgeAuth: { flow: "modelscope" },
+ },
{
// Self-hosted: the user runs the server, so there is no console to mint a key at
// (apiKeyUrl) and no endpoint to preset (gatewayBaseUrl). modelsUrl points at the recipe
@@ -1927,6 +1991,52 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
clientType: "openai-chat",
baseUrl: QWEN_PAYG_BASE_URL,
},
+ // -- ModelScope (api-inference aggregate, preset base URL). Preset ids keep ModelScope's
+ // own `org/Model-Name` spelling; DeepSeek was read from the endpoint's public /v1/models
+ // listing (2026-09-18), and the Qwen additions from their public model pages (2026-09-20).
+ //
+ // Like Penguin Go, this is a mixed-protocol aggregate: rows pin the AgentHub protocol the
+ // upstream model should display and use. The Qwen ids have no native AgentHub qwen client and
+ // therefore use the vLLM Chat Completions adapter, which maps thinking controls onto their
+ // chat templates; the DeepSeek id pins `deepseek-v4` so it shows the same protocol family as
+ // the direct and Penguin Go DeepSeek V4 rows instead of flattening the group to one protocol.
+ //
+ // The window and vision flags are NOT read from ModelScope's own docs — its model pages are
+ // client-rendered and carry no price. They repeat what other rows of the same models record,
+ // because ModelScope serves the same upstream ids.
+ //
+ // `pricing` is deliberately absent. ModelScope bills for api-inference and does not publish a
+ // read-able rate, so an absent pricing — which the catalog reads as "nobody has looked this
+ // up", leaving the row unbadged and the group's usage uncosted — is the honest state. A
+ // three-zero pricing would be worse than absent here, not better: `isFreeModel` would badge a
+ // billed gateway as "Free". Whoever next reads ModelScope's pricing page should fill it in. --
+ {
+ modelId: "deepseek-ai/DeepSeek-V4.1-Flash",
+ displayName: "DeepSeek V4.1 Flash",
+ provider: MODELSCOPE_PROVIDER_ID,
+ contextWindow: 1000000,
+ supportsVision: true,
+ clientType: "deepseek-v4",
+ baseUrl: MODELSCOPE_BASE_URL,
+ },
+ {
+ modelId: "Qwen/Qwen3.8-27B",
+ displayName: "Qwen 3.8 27B",
+ provider: MODELSCOPE_PROVIDER_ID,
+ contextWindow: 262144,
+ supportsVision: true,
+ clientType: VLLM_CLIENT_TYPE,
+ baseUrl: MODELSCOPE_BASE_URL,
+ },
+ {
+ modelId: "Qwen/Qwen3.8-Flash-Next",
+ displayName: "Qwen 3.8 Flash Next",
+ provider: MODELSCOPE_PROVIDER_ID,
+ contextWindow: 262144,
+ supportsVision: true,
+ clientType: VLLM_CLIENT_TYPE,
+ baseUrl: MODELSCOPE_BASE_URL,
+ },
// -- MiniMax (direct M3 Responses client; official USD pay-as-you-go list prices, standard
// tier at <=512K input — every rate doubles above 512K, and the priority tier is 1.5x). --
{
@@ -2486,16 +2596,17 @@ export function resolveModelEnv(modelId: string, clientType?: string): ModelEnvI
/**
* Resolves the credential environment for a configured model entry. Most groups follow the
- * AgentHub client selected by model id / protocol. The Penguin Go relay is deliberately
- * different: its Google and OpenAI routes share one relay credential, so its provider-scoped
- * variable must win over both clients' vendor variables everywhere the harness resolves a key.
+ * AgentHub client selected by model id / protocol. Aggregate groups are deliberately different:
+ * Penguin Go's Google and DeepSeek routes share one relay credential, and ModelScope's Qwen and
+ * DeepSeek routes share one api-inference token, so the provider-scoped variable must win over
+ * the selected protocol everywhere the harness resolves a key.
*/
export function resolveProviderModelEnv(
provider: string,
modelId: string,
clientType?: string,
): ModelEnvInfo | undefined {
- if (provider === PENGUIN_GO_PROVIDER_ID) {
+ if (provider === PENGUIN_GO_PROVIDER_ID || provider === MODELSCOPE_PROVIDER_ID) {
const group = providerInfo(provider);
return group === undefined
? undefined
diff --git a/packages/core/test/llm.test.ts b/packages/core/test/llm.test.ts
index c3e11171..9707d5e3 100644
--- a/packages/core/test/llm.test.ts
+++ b/packages/core/test/llm.test.ts
@@ -1621,6 +1621,65 @@ describe("GenerativeModel per-request output cap (window clamp, issue #218)", ()
});
});
+describe("GenerativeModel rotating credentials", () => {
+ it("resolves before every request and rebuilds the client only when the key changes", async () => {
+ const resolvedKeys = ["new-key", "new-key", "newer-key"];
+ let resolutions = 0;
+ const observed: Array<{ apiKey: string | undefined; client: unknown; historyLength: number }> =
+ [];
+
+ class RotatingKeyModel extends GenerativeModel {
+ protected override openStream(): AsyncIterable<UniEvent> {
+ const internals = this as unknown as {
+ currentApiKey: string | undefined;
+ client: { getHistory(): UniMessage[] };
+ };
+ observed.push({
+ apiKey: internals.currentApiKey,
+ client: internals.client,
+ historyLength: internals.client.getHistory().length,
+ });
+ return (async function* () {
+ yield ev({
+ content_items: [{ type: "text", text: "ok" }],
+ finish_reason: "stop",
+ usage_metadata: {
+ cached_tokens: 0,
+ prompt_tokens: 1,
+ thoughts_tokens: 0,
+ response_tokens: 1,
+ },
+ });
+ })();
+ }
+ }
+
+ const model = new RotatingKeyModel({
+ modelId: "modelscope-model",
+ apiKey: "old-key",
+ clientType: "openai-chat",
+ tools: [],
+ resolveApiKey: async () => resolvedKeys[resolutions++]!,
+ });
+ model.setHistory([userText("prior turn")]);
+
+ const drain = async (): Promise<void> => {
+ const stream = model.streamGenerate({ newMessages: [userText("next")] });
+ let result = await stream.next();
+ while (!result.done) result = await stream.next();
+ };
+ await drain();
+ await drain();
+ await drain();
+
+ expect(resolutions).toBe(3);
+ expect(observed.map((item) => item.apiKey)).toEqual(["new-key", "new-key", "newer-key"]);
+ expect(observed[1]!.client).toBe(observed[0]!.client);
+ expect(observed[2]!.client).not.toBe(observed[1]!.client);
+ expect(observed.map((item) => item.historyLength)).toEqual([1, 1, 1]);
+ });
+});
+
describe("GenerativeModel.streamGenerate outcome classification (PRN-013)", () => {
// Injects a controlled UniEvent stream through the protected openStream seam to verify the
// outcome classification of timeout/network-drop/interrupt/error, without needing a real API.
diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.ts
index ac5c9cd1..9b189f62 100644
--- a/packages/core/test/model-catalog.test.ts
+++ b/packages/core/test/model-catalog.test.ts
@@ -56,6 +56,7 @@ describe("model-catalog", () => {
"minimax",
"qwen-pay-as-you-go",
"qwen-token-plan",
+ "modelscope",
"vllm",
"custom",
]);
@@ -123,6 +124,24 @@ describe("model-catalog", () => {
expect(oauth.keyName).toBe("PenguinHarness");
});
+ it("exactly the bridged groups publish an authorization flow, and each names its own", () => {
+ // The descriptor is what puts the "authorize a key" action on a group in the Web App, so
+ // it has to name the App-side flow rather than the vendor: the Web App picks the service
+ // from this value, and the group's id is not a contract.
+ const withBridgeAuth = MODEL_PROVIDERS.filter((p) => p.bridgeAuth !== undefined).map((p) => [
+ p.id,
+ p.bridgeAuth!.flow,
+ ]);
+ expect(withBridgeAuth).toEqual([
+ ["penguin-go", "penguin-go"],
+ ["modelscope", "modelscope"],
+ ]);
+ // No group publishes both flows: a credential comes from one place.
+ for (const p of MODEL_PROVIDERS) {
+ expect(p.oauth === undefined || p.bridgeAuth === undefined).toBe(true);
+ }
+ });
+
it("prebuilds Penguin Go with fixed relay routes and list prices, leaving promotions to the platform", () => {
const penguinGoModels = MODEL_CATALOG.filter((model) => model.provider === "penguin-go");
// The DeepSeek rows follow DeepSeek's own lineup: V4.1 Flash and V4 Pro 0813. The two
@@ -189,9 +208,22 @@ describe("model-catalog", () => {
});
});
- it("every entry has valid three-bucket pricing; context_window is a positive integer", () => {
+ it("every entry is priced or deliberately unpriced; context_window is a positive integer", () => {
+ // An absent `pricing` is a supported state — the model card leaves the row unbadged and the
+ // cost center reports the usage as uncosted, which is what "nobody has read this vendor's
+ // price" should look like. This list is what keeps it deliberate: a row belongs here only
+ // when the vendor publishes no read-able rate, never as a way to skip looking.
+ const UNPRICED = new Set([
+ // ModelScope bills for api-inference but its model pages are client-rendered and carry
+ // no rate. Recording $0 instead would have isFreeModel badge a billed gateway "Free".
+ "deepseek-ai/DeepSeek-V4.1-Flash",
+ "Qwen/Qwen3.8-27B",
+ "Qwen/Qwen3.8-Flash-Next",
+ ]);
for (const m of MODEL_CATALOG) {
- if (
+ if (m.pricing === undefined) {
+ expect(UNPRICED.has(m.modelId), m.modelId).toBe(true);
+ } else if (
m.provider === "vllm" ||
m.modelId.endsWith(":free") ||
m.modelId === "openrouter/free" ||
@@ -426,7 +458,7 @@ describe("model-catalog", () => {
expect(promotions.filter((p) => p.provider === "penguin-go")).toEqual([]);
});
- it("gateway models (OpenRouter / SiliconFlow / Qwen Token Plan): OpenRouter pins Responses and the rest Chat Completions, all on a preset base URL; env fallback is OPENAI_API_KEY", () => {
+ it("gateway models pin explicit protocols and preset base URLs; env fallback stays OPENAI_API_KEY", () => {
const or = MODEL_CATALOG.filter((m) => m.provider === "openrouter");
// Dictionary order, newer versions of a series first (gpt-6-* before gpt-5.6-*,
// gpt-5.6-* before gpt-5.5, opus-4.8 before 4.7) — precomputed in the catalog, no
@@ -706,6 +738,38 @@ describe("model-catalog", () => {
expect(m.clientType).toBe("openai-chat");
expect(m.baseUrl).toBe("https://dashscope.aliyuncs.com/compatible-mode/v1");
}
+ const ms = MODEL_CATALOG.filter((m) => m.provider === "modelscope");
+ // Preset rows keep ModelScope's upstream ids. Like Penguin Go, this group is an aggregate:
+ // the row's client type tracks the upstream model family for display/request semantics, while
+ // the group credential remains ModelScope's api-inference token. Pricing is deliberately
+ // absent (see UNPRICED above); the windows and vision flags repeat what other rows of the
+ // same models record.
+ expect(
+ ms.map((m) => [m.modelId, m.contextWindow, m.supportsVision, m.clientType, m.baseUrl]),
+ ).toEqual([
+ [
+ "deepseek-ai/DeepSeek-V4.1-Flash",
+ 1000000,
+ true,
+ "deepseek-v4",
+ "https://api-inference.modelscope.cn/v1",
+ ],
+ [
+ "Qwen/Qwen3.8-27B",
+ 262144,
+ true,
+ "openai-chat-vllm-adapter",
+ "https://api-inference.modelscope.cn/v1",
+ ],
+ [
+ "Qwen/Qwen3.8-Flash-Next",
+ 262144,
+ true,
+ "openai-chat-vllm-adapter",
+ "https://api-inference.modelscope.cn/v1",
+ ],
+ ]);
+ expect(ms.every((m) => m.pricing === undefined)).toBe(true);
const minimax = MODEL_CATALOG.filter((m) => m.provider === "minimax");
expect(
minimax.map((m) => [
@@ -737,6 +801,7 @@ describe("model-catalog", () => {
"tokendance",
"qwen-token-plan",
"qwen-pay-as-you-go",
+ "modelscope",
"vllm",
"custom",
]) {
@@ -754,6 +819,9 @@ describe("model-catalog", () => {
);
expect(providerInfo("fireworks")!.gatewayBaseUrl).toBe("https://api.fireworks.ai/inference/v1");
expect(providerInfo("tokendance")!.gatewayBaseUrl).toBe("https://tokendance.space/gateway/v1");
+ expect(providerInfo("modelscope")!.gatewayBaseUrl).toBe(
+ "https://api-inference.modelscope.cn/v1",
+ );
const GATEWAYS = [
"openrouter",
"fireworks",
@@ -761,13 +829,14 @@ describe("model-catalog", () => {
"tokendance",
"qwen-token-plan",
"qwen-pay-as-you-go",
+ "modelscope",
];
for (const p of MODEL_PROVIDERS) {
if (!GATEWAYS.includes(p.id)) {
expect(p.gatewayBaseUrl, p.id).toBeUndefined();
}
}
- const gateway = [...or, ...fw, ...sf, ...td, ...qtp, ...qpayg];
+ const gateway = [...or, ...fw, ...sf, ...td, ...qtp, ...qpayg, ...ms];
// 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!;
@@ -1216,6 +1285,10 @@ describe("resolveModelEnv (PRN-021: env fallback resolved by AgentHub routing ru
expect(resolveProviderModelEnv("penguin-go", "deepseek-flash", "openai-chat")?.envKey).toBe(
"PENGUIN_GO_API_KEY",
);
+ expect(
+ resolveProviderModelEnv("modelscope", "deepseek-ai/DeepSeek-V4.1-Flash", "deepseek-v4")
+ ?.envKey,
+ ).toBe("OPENAI_API_KEY");
expect(resolveProviderModelEnv("deepseek", "deepseek-v4-pro")?.envKey).toBe("DEEPSEEK_API_KEY");
expect(resolveProviderModelEnv("openrouter", "any-model", "openai-chat")?.envKey).toBe(
"OPENAI_API_KEY",
@@ -1309,10 +1382,13 @@ describe("resolveModelEnv (PRN-021: env fallback resolved by AgentHub routing ru
const env = resolveModelEnv(m.modelId, m.clientType);
const provider = providerInfo(m.provider)!;
expect(env, `${m.provider}/${m.modelId}`).toBeDefined();
- if (m.provider === "penguin-go") {
- // Penguin Go mixes routed clients behind one relay, so its provider-scoped
- // environment name intentionally differs from each client's vendor variable.
- expect(provider.envKey).toBe("PENGUIN_GO_API_KEY");
+ if (m.provider === "penguin-go" || m.provider === "modelscope") {
+ // Aggregate groups mix routed clients behind one group credential, so their
+ // provider-scoped environment name intentionally differs from some client variables.
+ expect(resolveProviderModelEnv(m.provider, m.modelId, m.clientType)).toEqual({
+ envKey: provider.envKey,
+ envBaseUrlKey: provider.envBaseUrlKey,
+ });
continue;
}
if (m.provider === "custom") {
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index 3f934aa2..d4c33799 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -18,6 +18,7 @@ The CLI and the server load a `.env` file from the working directory on startup.
| `PENGUIN_WEB_DIST` | Front-end static assets directory | The server package's bundled `web-dist` (in a source checkout, `packages/web/dist`) |
| `PENGUIN_PREVIEW_ORIGIN` | Origin that serves Workspace HTML previews, e.g. `https://preview.example.com` | Unset: the loopback counterpart is derived per request |
| `PENGUIN_GO_ORIGIN` | Trusted origin the server-side Penguin Go key authorization calls | `https://token.penguin.ooo` |
+| `MODELSCOPE_BRIDGE_URL` | Address of the authorization bridge the server-side ModelScope key authorization calls | `https://go.penguin.ooo/modelscope` |
| `PENGUIN_TRUST_PROXY` | `1` trusts the `x-forwarded-proto` header | Unset: the header is ignored |
| `PENGUIN_SEED_ADMIN_PASSWORD` | Fixed initial password for the seeded built-in admin (automated tests / e2e) | Unset: a random password is generated |
| `PENGUIN_LANG` | CLI language (`en` / `zh`), set with `penguin config lang` | `en` |
@@ -31,6 +32,7 @@ Notes:
- `PENGUIN_TRUST_PROXY`: set it behind a reverse proxy that terminates TLS and sets or strips the header itself. Session cookies are then marked `Secure`, and the hot-update network gate sees HTTPS.
- `PENGUIN_SEED_ADMIN_PASSWORD`: without it, the seed generates a random password that is hashed and discarded unseen, and you claim the account through the first-login link.
- `PENGUIN_GO_ORIGIN`: server configuration, not an endpoint the browser can name. It must be a bare HTTPS origin; plain HTTP is accepted only for `localhost`, `127.0.0.1` and `[::1]`, for integration environments. A path, credentials, a query string or a fragment is rejected at startup. See [Authorize a new API key](/models#authorize-a-new-api-key).
+- `MODELSCOPE_BRIDGE_URL`: server configuration like `PENGUIN_GO_ORIGIN`, not an endpoint the browser can name. It must be an HTTPS address with no credentials, query string or fragment. Unlike `PENGUIN_GO_ORIGIN`, a path prefix **is** allowed, because the production bridge lives under `https://go.penguin.ooo/modelscope`. See [Authorize a new API key](/models#authorize-a-new-api-key).
- `PENGUIN_UPDATE_CHECK`: `off` turns off the automatic release check, nothing else. Model requests, an enabled remote-control connection, provider key authorization and the proxy test still reach the network.
- `PENGUIN_NO_LOGIN_SHELL_ENV`: without it, the import fills only variables the launch left unset. See [Desktop quickstart](/quickstart-desktop).
- `PENGUIN_CLI_ENTRY`: when the server was started from a source checkout, it falls back to that checkout's `packages/cli/dist/penguin.js`.
@@ -70,14 +72,14 @@ 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, tokendance, qwen-pay-as-you-go, qwen-token-plan, vllm, custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
+| openai, openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, modelscope, vllm, custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
| penguin-go | `PENGUIN_GO_API_KEY` | `PENGUIN_GO_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, tokendance, qwen-pay-as-you-go, qwen-token-plan, vllm and custom groups speak an OpenAI-compatible protocol, hence the shared `OPENAI_*` variables. The Penguin Go relay keeps a pair of its own, so the app never offers a vendor credential for it. The direct MiniMax M3 Responses client uses `MINIMAX_*`, and the built-in MiniMax preset already pins the official endpoint. For provider groups and the built-in model catalog, see [Models & Providers](/models).
+The openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, vllm and custom groups speak an OpenAI-compatible protocol, hence the shared `OPENAI_*` variables. ModelScope also shares `OPENAI_*` because its group credential is an api-inference token, even when a preset row pins a model-specific protocol. The Penguin Go relay keeps a pair of its own, so the app never offers a vendor credential for it. The direct MiniMax M3 Responses client uses `MINIMAX_*`, and the built-in MiniMax preset already pins the official endpoint. For provider groups and the built-in model catalog, see [Models & Providers](/models).
## Project config
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index 8fa014a9..aca43b48 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -18,6 +18,7 @@ CLI 和服务器启动时会从工作目录加载 `.env` 文件。
| `PENGUIN_WEB_DIST` | 前端静态资源目录 | 服务器包自带的 `web-dist`(源码检出中为 `packages/web/dist`) |
| `PENGUIN_PREVIEW_ORIGIN` | 提供 Workspace HTML 预览的源,例如 `https://preview.example.com` | 未设置:每次请求推导对应的回环地址 |
| `PENGUIN_GO_ORIGIN` | 服务端发起 Penguin Go Key 授权时调用的可信源 | `https://token.penguin.ooo` |
+| `MODELSCOPE_BRIDGE_URL` | 服务端发起 ModelScope Key 授权时调用的授权中转层地址 | `https://go.penguin.ooo/modelscope` |
| `PENGUIN_TRUST_PROXY` | 设为 `1` 时信任 `x-forwarded-proto` 请求头 | 未设置:忽略请求头 |
| `PENGUIN_SEED_ADMIN_PASSWORD` | 预置内置管理员的固定初始密码(自动化测试 / e2e) | 未设置:生成随机密码 |
| `PENGUIN_LANG` | CLI 语言(`en` / `zh`),用 `penguin config lang` 设置 | `en` |
@@ -31,6 +32,7 @@ CLI 和服务器启动时会从工作目录加载 `.env` 文件。
- `PENGUIN_TRUST_PROXY`:只在反向代理终结 TLS、并由代理自己设置或清除这个请求头时启用。启用后,会话 Cookie 会带上 `Secure` 标记,热更新的网络检查也能识别出 HTTPS。
- `PENGUIN_SEED_ADMIN_PASSWORD`:不设置时,预置管理员时会生成一个随机密码,哈希后立即丢弃,没有人见过;账号通过首次登录链接认领。
- `PENGUIN_GO_ORIGIN`:它是服务端配置,不接受浏览器指定的端点。取值必须是不带路径的 HTTPS 源;只有 `localhost`、`127.0.0.1` 和 `[::1]` 这类集成环境可以用明文 HTTP。带路径、凭据、查询参数或 fragment 的取值会在启动时被拒绝。见[授权获取新 API key](/models#授权获取新-api-key)。
+- `MODELSCOPE_BRIDGE_URL`:与 `PENGUIN_GO_ORIGIN` 一样是服务端配置,不接受浏览器指定的端点。它必须是不带凭据、查询参数或 fragment 的 HTTPS 地址。不同之处是**它允许带路径前缀**,因为生产环境的中转层就挂在 `https://go.penguin.ooo/modelscope` 下。见[授权获取新 API key](/models#授权获取新-api-key)。
- `PENGUIN_UPDATE_CHECK`:设为 `off` 只关闭自动的版本检查,不影响其他对外请求:模型请求、已启用的远程控制连接、Key 授权和代理测试照常联网。
- `PENGUIN_NO_LOGIN_SHELL_ENV`:不设置时,导入只填补启动过程没有设置的变量。见[桌面应用快速开始](/quickstart-desktop)。
- `PENGUIN_CLI_ENTRY`:服务器从源码检出启动时,会回退到检出目录中的 `packages/cli/dist/penguin.js`。
@@ -70,14 +72,14 @@ Agent 运行的每条命令,PATH 的第一位都是本安装自带的 `penguin
| --- | --- | --- |
| deepseek | `DEEPSEEK_API_KEY` | `DEEPSEEK_BASE_URL` |
| anthropic | `ANTHROPIC_API_KEY` | `ANTHROPIC_BASE_URL` |
-| openai、openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、vllm、custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
+| openai、openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、modelscope、vllm、custom | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
| penguin-go | `PENGUIN_GO_API_KEY` | `PENGUIN_GO_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、tokendance、qwen-pay-as-you-go、qwen-token-plan、vllm 和 custom 这几组供应商使用 OpenAI 兼容协议,因此共用 `OPENAI_*` 变量。Penguin Go 中转分组单独使用一对自己的变量,应用因此不会为它推荐任何厂商凭证。MiniMax M3 的直连 Responses 客户端使用 `MINIMAX_*`,内置的 MiniMax 预设也已经固定为官方端点。供应商分组和内置模型目录见[模型与供应商](/models)。
+openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、vllm 和 custom 这几组供应商使用 OpenAI 兼容协议,因此共用 `OPENAI_*` 变量。ModelScope 也共用 `OPENAI_*`,因为它的分组凭据是 api-inference token,即使某条预置固定了模型专属协议也是如此。Penguin Go 中转分组单独使用一对自己的变量,应用因此不会为它推荐任何厂商凭证。MiniMax M3 的直连 Responses 客户端使用 `MINIMAX_*`,内置的 MiniMax 预设也已经固定为官方端点。供应商分组和内置模型目录见[模型与供应商](/models)。
## Project 配置
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index 1b1bf59e..b6716dc8 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -102,7 +102,7 @@ Which protocol a new model uses depends on its group:
- **Vendor groups** (DeepSeek, Google Gemini, OpenAI, Anthropic, Z.AI, Moonshot, MiniMax) support only the vendor's own API. If a model id cannot be routed that way, the dialog warns you and offers **Move to Custom**. Use Custom for OpenAI-compatible endpoints.
- **OpenRouter** always uses `openai-responses`, and **vLLM** always uses `openai-chat-vllm-adapter`.
-- **Other gateway groups** use OpenAI Chat Completions.
+- **OpenAI-compatible gateway groups** use OpenAI Chat Completions, except for aggregate presets that pin a model-specific protocol.
- **Custom** and groups you created: pick the protocol from the base URL field, or detect it. See [Detect a custom model's protocol](#detect-a-custom-models-protocol).
### Edit or delete a model
@@ -194,7 +194,7 @@ A key you type is stored in the hidden Project config file, which has mode 0600.
### Authorize a new API key
-A provider that supports automatic key authorization adds **Authorize key** to its group header. Two built-in groups do: TokenDance and Penguin Go. The key is written to every model in the group, replacing the key those models use now.
+A provider that supports automatic key authorization adds **Authorize key** to its group header. Three built-in groups do: TokenDance, Penguin Go and ModelScope. The key is written to every model in the group, replacing the key those models use now.
1. On the group's header, select **Authorize key**.
2. Select **Open authorization page**. The provider's authorization page opens in a new tab.
@@ -212,11 +212,18 @@ Penguin Go differs in four ways:
- A key the platform reports as invalid or revoked reopens authorization on the **Models** page.
- If writing the delivered key locally fails, the server keeps that one delivery for a short while, so the write can be retried without authorizing again.
+ModelScope differs in three ways:
+
+- Authorization does not go through ModelScope's own pages but through an **authorization bridge**. The bridge holds ModelScope's client secret, runs the OAuth exchange on PenguinHarness's behalf, and hands back an access token that calls api-inference directly. The bridge's address comes from the server-side `MODELSCOPE_BRIDGE_URL` environment variable; see [Environment variables](/configuration#environment-variables).
+- The authorization page's address is the bridge's, opened as given, rather than assembled here the way Penguin Go's is. This group likewise has no manual-code mode.
+- The access token **expires**; PenguinHarness stores the refresh credential on the server and silently renews before model requests. Re-authorize with **Authorize key** only when the refresh credential is missing or no longer valid.
+
Keep in mind:
- Only the Project owner can start an authorization. With TokenDance, only their own signed-in session can finish it, which in practice is the tab the dialog is open in. The redirect itself is received without a session, because the browser the provider sends back is not always the one you started in, but it only hands the code over: nothing is exchanged and no key is saved until the dialog asks for the result.
-- The whole exchange runs on the server. Neither TokenDance's PKCE verifier nor Penguin Go's device secret ever reaches the browser, and the new key goes straight into the model table without passing through it.
-- An authorization delivers one key and expires at the provider's own deadline, and never later than ten minutes.
+- The whole exchange runs on the server. Neither TokenDance's PKCE verifier, Penguin Go's device secret, nor ModelScope's code and device secret ever reaches the browser, and the new key goes straight into the model table without passing through it. ModelScope's client secret is never in PenguinHarness at all; only the bridge holds it.
+- An authorization flow waits for at most ten minutes. ModelScope delivers an access token / refresh token pair: the access token is written to the model table, while the refresh token stays only in the server DB and is never returned to the frontend or written to the Project config.
+- A delivered key is handed over only once. Penguin Go and ModelScope both keep that one delivery briefly if saving it locally fails, so the write can be retried without authorizing again. ModelScope leaves nothing to clean up in ModelScope's console — what it returns is a token for your own account, not a newly minted key.
- TokenDance hands over the new key only once. If saving it fails, authorize again and delete the unused key in the provider's console.
- A TokenDance key carries PenguinHarness's app URL from the [App attribution](#app-attribution) table, so calls made with it stay attributed even from another tool.
@@ -409,14 +416,16 @@ The table below lists the built-in groups and the environment variables their mo
| 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) |
+| modelscope | `OPENAI_API_KEY` | ModelScope's OpenAI-compatible api-inference gateway, preset base URL `https://api-inference.modelscope.cn/v1`; ids are the upstream repo names (`deepseek-ai/DeepSeek-V4.1-Flash`, `Qwen/Qwen3.8-27B`); the group's header authorizes a token for you through an authorization bridge, or takes one you set by hand. See [The ModelScope group](#the-modelscope-group) |
| vllm | `OPENAI_API_KEY` | Self-hosted vLLM servers: protocol fixed to `openai-chat-vllm-adapter`, no preset base URL, eight preset models priced at 0 (see [Connect a local or self-hosted endpoint](#connect-a-local-or-self-hosted-endpoint)) |
| custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint; ships one preset, Atria Dawn Preview (Anthropic Messages API at `api.atria-asi.ai`, credential from `ANTHROPIC_API_KEY` when the entry has none, 256K window, priced at $0 until the vendor publishes prices) |
-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.
+The OpenAI-compatible 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. ModelScope also uses the `OPENAI_*` credential variables because its credential is an api-inference token, but its preset rows can pin a model-specific protocol.
- The OpenRouter group uses the Responses client (`client_type = "openai-responses"`) for its presets and for any model you add to it, because OpenRouter serves the Responses API at that same base URL for every model it resells.
- The other gateway presets use the Chat Completions client (`client_type = "openai-chat"`).
-- Both clients read the same `OPENAI_*` variables, so the credential rules are identical either way.
+- ModelScope is an aggregate gateway like Penguin Go: its Qwen presets use `openai-chat-vllm-adapter`, carrying Qwen template thinking controls over Chat Completions, while its DeepSeek preset pins `deepseek-v4` and uses AgentHub's Responses client.
+- Those gateway 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 uses `https://api.minimax.io/v1`. `MINIMAX_BASE_URL` is read only for entries without their own `base_url`.
@@ -432,6 +441,14 @@ The group's key comes from its header; see [Authorize a new API key](#authorize-
The platform quotes peak rates in USD per million Tokens. The group's DeepSeek rows follow DeepSeek's current line-up, `deepseek-flash` and `deepseek-v4-pro`, and declare the same off-peak schedule as the direct DeepSeek group, so their cards and cost records use half price outside Beijing weekday 9:00–12:00 and 14:00–18:00.
+### The ModelScope group
+
+`modelscope` is an aggregate gateway group: one ModelScope api-inference endpoint behind the preset base URL `https://api-inference.modelscope.cn/v1`, with each preset row carrying the protocol that AgentHub should use for that upstream model. Model ids are upstream repo names, so they keep their vendor prefix (`deepseek-ai/DeepSeek-V4.1-Flash`, `Qwen/Qwen3.8-27B`). The Qwen rows use `openai-chat-vllm-adapter`, retaining Chat Completions on the wire while mapping thinking controls to the Qwen template; the DeepSeek row pins `deepseek-v4`, matching the direct and Penguin Go DeepSeek V4 rows. A new Project gets these presets right away; a Project created earlier adds them with **Sync presets**.
+
+The group's key comes from its header; see [Authorize a new API key](#authorize-a-new-api-key). Authorization goes through an authorization bridge, which holds the ModelScope client secret and returns an api-inference access token / refresh token pair, rather than through ModelScope's own pages. Nothing else about the group is special: inference requests go straight to `https://api-inference.modelscope.cn/v1` and never through the bridge. The access token is written into `.project_config.toml` like any other group key, while the refresh token stays only in the server DB. The access token expires, and PenguinHarness silently renews it before model requests; re-authorize from the header only when the refresh token is missing or no longer valid.
+
+The preset rows carry no price. ModelScope bills for api-inference and its model pages publish no read-able rate, so the rows are left unpriced: the models page shows no price badge on them and the cost center reports their usage as uncosted. That is the catalog's way of recording "nobody has looked this up" — see [Prices and promotions](#prices-and-promotions).
+
### Preset models
The preset catalog includes, among others:
@@ -446,6 +463,7 @@ The preset catalog includes, among others:
- `qwen3.8-max` / `qwen3.8-flash`
- `seed-2.1-pro` / `seed-2.1-turbo` / `seed-evolving`
- `dots-3-note-preview` (free on TokenDance, 512K context)
+- `deepseek-ai/DeepSeek-V4.1-Flash`, `Qwen/Qwen3.8-27B`, `Qwen/Qwen3.8-Flash-Next` (ModelScope's api-inference; preset rows with no price)
The list is not exhaustive.
@@ -458,6 +476,7 @@ The list is not exhaustive.
### Prices and promotions
- **Three price buckets.** Each model records `cache_read`, `cache_write` and `output` prices in USD per million Tokens. The cost center bills usage against them.
+- **Rows with no price.** The pricing block can be absent altogether, which records "nobody has looked this vendor's price up" rather than "free": such a row shows no price badge on the **Models** page, and the cost center reports its usage as uncosted. ModelScope's preset rows are the catalog's only ones — ModelScope bills for api-inference, but its model pages are client-rendered and carry no read-able rate. Three zeros would be worse than absent: they would read as the free tier and badge a billed gateway "Free".
- **Base tier only.** Where a vendor's prices step up with input size, the catalog records the base tier. MiniMax M3 records MiniMax's standard pay-as-you-go tier at 512K input tokens or below; above that, every rate doubles, and the priority tier is 1.5x, so long-context and priority usage is underestimated. OpenAI (above 272K) and Gemini 3.1 Pro (above 200K) follow the same convention.
- **DeepSeek off-peak.** The direct DeepSeek rows record the official peak prices and declare DeepSeek's off-peak schedule: outside Beijing time 9:00–12:00 and 14:00–18:00 on weekdays, every bucket is halved. The **Models** page shows a `50% off` tag during those hours, and the cost center bills at that rate.
- Four resold rows follow the same schedule because their sellers pass DeepSeek's windows through: TokenDance's `deepseek-v4.1-flash`, OpenRouter's `deepseek/deepseek-v4.1-flash`, and Penguin Go's `deepseek-flash` and `deepseek-v4-pro`.
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index 45ef7bfc..1ba78448 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -102,7 +102,7 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择
- **厂商分组**(DeepSeek、Google Gemini、OpenAI、Anthropic、Z.AI、Moonshot、MiniMax)只支持厂商自己的 API。如果模型 id 无法按这种方式路由,弹窗会警告你,并提供**转为自定义模型**。OpenAI 兼容的端点请放进 **Custom** 分组。
- **OpenRouter** 总是使用 `openai-responses`,**vLLM** 总是使用 `openai-chat-vllm-adapter`。
-- **其他网关分组**使用 OpenAI Chat Completions。
+- **OpenAI 兼容网关分组**使用 OpenAI Chat Completions,但聚合分组的预置条目可以逐条固定模型专属协议。
- **Custom** 和你创建的分组:在 base URL 字段里选择协议,或者检测协议。见[检测自定义模型的协议](#检测自定义模型的协议)。
### 编辑或删除模型
@@ -194,7 +194,7 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择
### 授权获取新 API key
-支持自动授权取 key 的供应商,会在分组标题栏上加上**自动获取密钥**。内置分组里有两个提供了这个流程:TokenDance 和 Penguin Go。取得的 key 会写入分组里的每个模型,替换它们现在使用的 key。
+支持自动授权取 key 的供应商,会在分组标题栏上加上**自动获取密钥**。内置分组里有三个提供了这个流程:TokenDance、Penguin Go 和 ModelScope。取得的 key 会写入分组里的每个模型,替换它们现在使用的 key。
1. 在分组的标题栏上,点击**自动获取密钥**。
2. 点击**打开授权页**。供应商的授权页会在新标签页中打开。
@@ -212,12 +212,18 @@ Penguin Go 有四处不同:
- 平台报告 key 失效或被吊销时,**模型库**页面会重新打开授权。
- 取到的 key 写入本地失败时,服务端会把这一次交付短暂保留,可以直接重试写入,不必再次授权。
+ModelScope 有三处不同:
+
+- 授权不经过魔搭自己的页面,而是经过一台**授权中转层**。中转层持有魔搭的 client secret,代 PenguinHarness 走完 OAuth,再把一把可直接调用 api-inference 的 access token 交回来。中转层的地址来自服务端环境变量 `MODELSCOPE_BRIDGE_URL`,见[环境变量](/configuration#环境变量)。
+- 授权页的地址由中转层给出,PenguinHarness 原样打开,不像 Penguin Go 那样自己拼。同样没有手动填写授权码的方式。
+- 拿到的 access token 是**会过期**的;PenguinHarness 会在服务端保存刷新凭据,并在模型请求前静默续期。刷新凭据失效或缺失时,才需要重新点一次**自动获取密钥**。
+
注意事项:
- 只有 Project owner 能发起授权。TokenDance 还要求由他本人已登录的会话完成授权,实际上就是打开着弹窗的那个标签页。重定向本身不要求会话就能接收,因为供应商带回的浏览器未必是你发起授权时用的那个;但它只交回授权码:在弹窗来取结果之前,不会发生任何换取,也不会保存任何 key。
-- 整个换取过程都在服务端完成。TokenDance 的 PKCE verifier 和 Penguin Go 的设备密钥都不会进入浏览器;新 key 直接写入模型表,同样不经过浏览器。
-- 一次授权只交付一把 key,有效期取供应商给出的截止时间,且不超过十分钟。
-- TokenDance 只交付一次新 key。如果保存失败,请重新授权,并到供应商的控制台删除没用上的那把 key。
+- 整个换取过程都在服务端完成。TokenDance 的 PKCE verifier、Penguin Go 的设备密钥、以及 ModelScope 的授权码和设备密钥都不会进入浏览器;新 key 直接写入模型表,同样不经过浏览器。ModelScope 的 client secret 从头到尾都不在 PenguinHarness 里,只有中转层持有。
+- 一次授权流程最多等待十分钟。ModelScope 交付的是一组 access token / refresh token:access token 写入模型表,refresh token 只保存在服务端 DB,不返回给前端,也不写入 Project 配置。
+- 交付回来的 key 只交一次。Penguin Go 和 ModelScope 都会在本地保存失败时短暂保留这一次交付,因此可以直接重试写入,不必再次授权。ModelScope 下无需去魔搭控制台清理——它交回的是你自己账号的 token,不是新造的 key。
- TokenDance 的 key 携带[应用归因](#应用归因)表中 PenguinHarness 的应用 URL,所以即使用其他工具发起调用,用量也仍会归到 PenguinHarness 名下。
## 设置默认模型
@@ -409,14 +415,16 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr
| 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 订阅密钥或按量付费 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`;价格取自各模型页面的官方牌价(预览模型只有配额倍率优惠,没有牌价) |
+| modelscope | `OPENAI_API_KEY` | 魔搭的 OpenAI 兼容 api-inference 网关,预置 base URL `https://api-inference.modelscope.cn/v1`;id 就是上游仓库名(如 `deepseek-ai/DeepSeek-V4.1-Flash`、`Qwen/Qwen3.8-27B`);分组标题栏可以经授权中转层为你自动授权一把 token,也可以手动设置。见 [ModelScope 分组](#modelscope-分组) |
| vllm | `OPENAI_API_KEY` | 自托管 vLLM 服务器:协议固定为 `openai-chat-vllm-adapter`,无预置 base URL,八个预置模型价格均为 0(见[连接本地或自托管端点](#连接本地或自托管端点)) |
| custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点;自带一个预置模型 Atria Dawn Preview(Anthropic Messages API,地址 `api.atria-asi.ai`,条目没有凭据时使用 `ANTHROPIC_API_KEY`,上下文窗口 256K,供应商公布价格之前定价 $0) |
-网关分组(openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan)走的是 AgentHub 通用的 OpenAI 协议客户端,凭据留空时读取 `OPENAI_API_KEY`,而不是某个网关专属的变量。
+OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan)走的是 AgentHub 通用的 OpenAI 协议客户端,凭据留空时读取 `OPENAI_API_KEY`,而不是某个网关专属的变量。ModelScope 也使用 `OPENAI_*` 凭据变量,因为它的凭据是 api-inference token,但它的预置条目可以逐条固定模型专属协议。
- OpenRouter 分组的预置模型,以及你添加到该分组的任何模型,都使用 Responses 客户端(`client_type = "openai-responses"`),因为 OpenRouter 在同一个 base URL 上为它转售的每一个模型提供 Responses API。
- 其他网关的预置模型使用 Chat Completions 客户端(`client_type = "openai-chat"`)。
-- 两种客户端读取相同的 `OPENAI_*` 变量,所以无论哪种方式,凭据规则完全一致。
+- ModelScope 像 Penguin Go 一样是聚合网关:Qwen 预置使用 `openai-chat-vllm-adapter`,在 Chat Completions 上按 Qwen 模板传递思考参数;DeepSeek 预置固定为 `deepseek-v4`,运行时走 AgentHub Responses client。
+- 这些网关客户端读取相同的 `OPENAI_*` 变量,所以无论哪种方式,凭据规则完全一致。
直连 MiniMax M3 的客户端读取 `MINIMAX_API_KEY`。内置的 MiniMax 预置模型使用 `https://api.minimax.io/v1`。只有条目没有自己的 `base_url` 时,才会读取 `MINIMAX_BASE_URL`。
@@ -432,6 +440,14 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr
平台报的是高峰档费率,单位是每百万 Token 多少美元。分组里的 DeepSeek 条目跟随 DeepSeek 当前的模型阵容,只有 `deepseek-flash` 和 `deepseek-v4-pro`,并声明与直连 DeepSeek 分组相同的空闲时段,因此在北京时间工作日 9:00–12:00、14:00–18:00 之外,卡片和成本记录都按半价计算。
+### ModelScope 分组
+
+`modelscope` 是聚合网关分组:同一个魔搭 api-inference 端点,预置 base URL `https://api-inference.modelscope.cn/v1`,每条预置各自写明 AgentHub 应该为这个上游模型使用的协议。模型 id 就是上游仓库名,因此保留供应商前缀(`deepseek-ai/DeepSeek-V4.1-Flash`、`Qwen/Qwen3.8-27B`)。Qwen 条目使用 `openai-chat-vllm-adapter`,在线路仍为 Chat Completions 的同时正确控制 Qwen 模板的思考参数;DeepSeek 条目固定为 `deepseek-v4`,与直连 DeepSeek 和 Penguin Go 的 DeepSeek V4 条目保持一致。新建的 Project 立即带上这些预置;更早创建的 Project 用**同步预置**补上。
+
+分组的 key 从标题栏取得,见[授权获取新 API key](#授权获取新-api-key)。授权走一台授权中转层,由中转层持有魔搭的 client secret 并交回一组 api-inference access token / refresh token,而不是经过魔搭自己的页面。除此之外这个分组没有特别之处:推理请求直接发给 `https://api-inference.modelscope.cn/v1`,从不经过中转层;access token 和其他分组的 key 一样写进 `.project_config.toml`,refresh token 只保存在服务端 DB。access token 会过期,PenguinHarness 会在模型请求前静默续期;refresh token 缺失或失效时,才需要从标题栏重新授权一次。
+
+预置条目不带价格。魔搭的 api-inference 是计费的,但它的模型页面读不到费率,所以这些条目按未定价处理:模型页在它们上面不显示价格徽标,成本中心把它们的用量报为未计价。这是目录记录「没人查过这个价格」的方式,见[价格与促销](#价格与促销)。
+
### 预置模型
预置模型目录包含以下模型:
@@ -446,6 +462,7 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr
- `qwen3.8-max` / `qwen3.8-flash`
- `seed-2.1-pro` / `seed-2.1-turbo` / `seed-evolving`
- `dots-3-note-preview`(TokenDance 上免费,512K 上下文)
+- `deepseek-ai/DeepSeek-V4.1-Flash`、`Qwen/Qwen3.8-27B`、`Qwen/Qwen3.8-Flash-Next`(ModelScope 的 api-inference,没有价格的预置条目)
列表并未穷尽所有模型。
@@ -458,6 +475,7 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr
### 价格与促销
- **三类价格。** 每个模型都记录 `cache_read`、`cache_write` 和 `output` 三项价格,单位是每百万 Token 多少美元。成本中心按这些价格结算用量。
+- **没有价格的条目。** 价格字段可以整体缺席,含义是「没人查过这家的价格」,而不是免费:这类条目在**模型库**页面不显示价格徽标,成本中心把它的用量报为未计价。目录里目前只有 ModelScope 的预置条目是这样——魔搭的 api-inference 是计费的,但它的模型页面是客户端渲染的,读不到费率。写成三个 0 反而更糟:那会被当作免费档,给一个计费网关打上「Free」徽标。
- **仅记录基础档。** 供应商的价格随输入规模上调时,目录只记录基础档。MiniMax M3 记录的是 MiniMax 标准按量付费档在 512K 输入 Token 及以下的价格;超过后每项费率翻倍,priority 档为 1.5 倍,所以长上下文和 priority 用量的成本估算会偏低。OpenAI(272K 以上)和 Gemini 3.1 Pro(200K 以上)遵循同样的约定。
- **DeepSeek 空闲时段。** 直连 DeepSeek 的条目记录官方高峰价格,并声明 DeepSeek 的空闲时段规则:工作日北京时间 9:00–12:00 和 14:00–18:00 以外的时段,三项价格全部减半。**模型库**页面在这些时段显示 `省 50%` 标签,成本中心也按这个费率计费。
- 四条转售条目遵循同样的时段,因为各自的卖家沿用了 DeepSeek 的时间窗口:TokenDance 的 `deepseek-v4.1-flash`、OpenRouter 的 `deepseek/deepseek-v4.1-flash`,以及 Penguin Go 的 `deepseek-flash` 和 `deepseek-v4-pro`。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 1d408ac5..af477735 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -888,6 +888,22 @@ export interface PlatformModelSyncResponse extends ModelsResponse {
updated: number;
}
+// ---------------------------------------------------------------------------
+// ModelScope key authorization (/api/projects/:p/modelscope-auth, owner)
+// ---------------------------------------------------------------------------
+
+/**
+ * The wire shapes are Penguin Go's, deliberately: both flows create a request, poll it, and
+ * report the same six states and the same seven failure codes, so the App drives both with one
+ * dialog. They are aliases rather than a second declaration because a copy would be the same
+ * fields with the same meaning, and a shape that drifted apart in one of the two would be a
+ * bug rather than a distinction. The endpoints stay separate regardless — a flow id issued by
+ * one is not accepted by the other.
+ */
+export type ModelScopeAuthStartResponse = PlatformAuthStartResponse;
+export type ModelScopeAuthFlowErrorCode = PlatformAuthFlowErrorCode;
+export type ModelScopeAuthFlowStatusResponse = PlatformAuthFlowStatusResponse;
+
// ---------------------------------------------------------------------------
// New-chat defaults (the `[default_chat]` block of .project_config.toml)
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/config.ts b/packages/server/src/config.ts
index 2f8d77a0..b408b8f1 100644
--- a/packages/server/src/config.ts
+++ b/packages/server/src/config.ts
@@ -41,6 +41,14 @@ export interface ServerConfig {
previewOrigin: string | null;
/** Trusted Penguin Go origin; never supplied by a browser request. */
penguinGoOrigin: string;
+ /**
+ * Base URL of the ModelScope authorization bridge (MODELSCOPE_BRIDGE_URL), without a
+ * trailing slash — e.g. `https://go.penguin.ooo/modelscope`. The harness sends the
+ * start/poll exchange here and never to ModelScope itself: the bridge holds the OAuth
+ * client secret. Unlike `penguinGoOrigin` this value carries a path prefix in production,
+ * because the bridge is mounted under one and strips it from the incoming request.
+ */
+ modelscopeBridgeUrl: string;
/**
* Fixed initial password for the seeded built-in admin (PENGUIN_SEED_ADMIN_PASSWORD),
* used by automated tests and e2e. Null is the norm: the seed then generates a random
@@ -183,7 +191,37 @@ export function normalizePenguinGoOrigin(raw: string | undefined): string {
return url.origin;
}
-/** Parses server config from environment variables (PORT / HOST / PENGUIN_HOME / PENGUIN_WEB_DIST / PENGUIN_WEB_DB / PENGUIN_PREVIEW_ORIGIN / PENGUIN_GO_ORIGIN / PENGUIN_SEED_ADMIN_PASSWORD / PENGUIN_DESKTOP_TOKEN / PENGUIN_PORT_FILE / PENGUIN_TRUST_PROXY / PENGUIN_CLI_ENTRY). */
+/**
+ * Validates MODELSCOPE_BRIDGE_URL into a base URL with no trailing slash, or throws.
+ *
+ * Deliberately looser than normalizePenguinGoOrigin in exactly one place: a PATH PREFIX is
+ * allowed, because the bridge is mounted under one in production
+ * (`https://go.penguin.ooo/modelscope`) and strips it from the request itself — so the
+ * prefix is part of the address the client must call. Credentials, query, fragment and
+ * plaintext HTTP stay rejected.
+ */
+export function normalizeModelScopeBridgeUrl(raw: string | undefined): string {
+ const value = raw?.trim() || "https://go.penguin.ooo/modelscope";
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new Error(`Invalid MODELSCOPE_BRIDGE_URL=${value} (expected an absolute HTTP(S) URL)`);
+ }
+ if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") {
+ throw new Error(
+ `Invalid MODELSCOPE_BRIDGE_URL=${value} (credentials, query and fragment are not allowed)`,
+ );
+ }
+ if (url.protocol !== "https:") {
+ throw new Error(`Invalid MODELSCOPE_BRIDGE_URL=${value} (HTTPS required)`);
+ }
+ // A bare origin parses as pathname "/", which must become "" rather than stay a slash, or
+ // every appended route would read `//oauth/start`.
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
+}
+
+/** Parses server config from environment variables (PORT / HOST / PENGUIN_HOME / PENGUIN_WEB_DIST / PENGUIN_WEB_DB / PENGUIN_PREVIEW_ORIGIN / PENGUIN_GO_ORIGIN / MODELSCOPE_BRIDGE_URL / PENGUIN_SEED_ADMIN_PASSWORD / PENGUIN_DESKTOP_TOKEN / PENGUIN_PORT_FILE / PENGUIN_TRUST_PROXY / PENGUIN_CLI_ENTRY). */
export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): ServerConfig {
const root = env.PENGUIN_HOME ?? resolveRoot();
// An empty PORT string is treated as unset (the common `.env` case of an empty
@@ -207,6 +245,7 @@ export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): Serve
webDist: env.PENGUIN_WEB_DIST ?? defaultWebDist(),
previewOrigin: normalizePreviewOrigin(env.PENGUIN_PREVIEW_ORIGIN),
penguinGoOrigin: normalizePenguinGoOrigin(env.PENGUIN_GO_ORIGIN),
+ modelscopeBridgeUrl: normalizeModelScopeBridgeUrl(env.MODELSCOPE_BRIDGE_URL),
// An empty/whitespace value is treated as unset, which leaves the seed to generate one.
seedAdminPassword: env.PENGUIN_SEED_ADMIN_PASSWORD?.trim() || null,
authSessionTtlMs: 30 * DAY_MS,
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
index 565aa2f1..e88a84dc 100644
--- a/packages/server/src/db/migrations.ts
+++ b/packages/server/src/db/migrations.ts
@@ -460,6 +460,37 @@ export const MIGRATIONS: readonly Migration[] = [
db.exec("DROP TABLE IF EXISTS model_promotions");
},
},
+ {
+ version: 10,
+ name: "model-provider-auth-tokens",
+ // Additive: one new table, nothing existing touched. A predecessor build never reads it;
+ // the access token already written into .project_config.toml keeps working until it
+ // expires, so rollback only loses silent refresh state.
+ // KEEP until every supported upgrade starts from schema 10 or newer. The release that
+ // raises the minimum database baseline past 9 owns removing this migration block and its
+ // version-9 fixture; the table itself remains while provider token refresh uses it.
+ swapSafe: true,
+ up(db) {
+ // Frozen copy of the DDL as of the provider-auth-token feature; do not re-derive from
+ // schema.ts. IF NOT EXISTS because the declarative track may already have created it
+ // (ADOPTION).
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS model_provider_auth_tokens ( -- Server-side OAuth refresh metadata for provider groups. The current request token remains in .project_config.toml as api_key; this table holds only the refresh material that must never be returned to the frontend or written into Project files.
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
+ provider TEXT NOT NULL,
+ refresh_token TEXT NOT NULL,
+ access_token_expires_at TEXT,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (project_id, provider)
+ );
+ `);
+ },
+ // LOSES every stored refresh token and access-token expiry. Existing access tokens in
+ // Project files remain until they expire; users re-authorize to restore silent refresh.
+ down(db) {
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ },
+ },
];
/** The highest version this build knows how to reach. */
diff --git a/packages/server/src/db/repos/model-provider-auth-tokens.ts b/packages/server/src/db/repos/model-provider-auth-tokens.ts
new file mode 100644
index 00000000..81bffb95
--- /dev/null
+++ b/packages/server/src/db/repos/model-provider-auth-tokens.ts
@@ -0,0 +1,60 @@
+/**
+ * Server-side OAuth refresh metadata for provider groups.
+ *
+ * The user-visible credential remains the ordinary model `api_key` in .project_config.toml.
+ * This table stores only refresh material and expiry metadata that must stay on the server:
+ * never return it through model APIs and never write it into Project files.
+ */
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
+import type { ModelProviderAuthToken, ModelProviderAuthTokens } from "../../mechanisms/projects.js";
+
+@Component()
+export class ModelProviderAuthTokensRepo implements ModelProviderAuthTokens {
+ @Use() private readonly db!: Db;
+
+ get(projectId: string, provider: string): ModelProviderAuthToken | undefined {
+ const row = this.db
+ .prepare(
+ `SELECT provider, refresh_token, access_token_expires_at, updated_at
+ FROM model_provider_auth_tokens
+ WHERE project_id = ? AND provider = ?`,
+ )
+ .get(projectId, provider);
+ if (!row) return undefined;
+ return {
+ provider: row.provider as string,
+ refreshToken: row.refresh_token as string,
+ ...(typeof row.access_token_expires_at === "string"
+ ? { accessTokenExpiresAt: row.access_token_expires_at }
+ : {}),
+ updatedAt: row.updated_at as string,
+ };
+ }
+
+ upsert(projectId: string, row: Omit<ModelProviderAuthToken, "updatedAt">): void {
+ this.db
+ .prepare(
+ `INSERT INTO model_provider_auth_tokens
+ (project_id, provider, refresh_token, access_token_expires_at, updated_at)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(project_id, provider) DO UPDATE SET
+ refresh_token = excluded.refresh_token,
+ access_token_expires_at = excluded.access_token_expires_at,
+ updated_at = excluded.updated_at`,
+ )
+ .run(
+ projectId,
+ row.provider,
+ row.refreshToken,
+ row.accessTokenExpiresAt ?? null,
+ new Date().toISOString(),
+ );
+ }
+
+ delete(projectId: string, provider: string): void {
+ this.db
+ .prepare("DELETE FROM model_provider_auth_tokens WHERE project_id = ? AND provider = ?")
+ .run(projectId, provider);
+ }
+}
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 5339ceb4..5d779f68 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -22,6 +22,16 @@ CREATE TABLE IF NOT EXISTS model_promotions ( -- NOT a cache rebuildable from fi
PRIMARY KEY (project_id, provider, model_id)
);`;
+export const MODEL_PROVIDER_AUTH_TOKENS_SQL = `
+CREATE TABLE IF NOT EXISTS model_provider_auth_tokens ( -- Server-side OAuth refresh metadata for provider groups. The current request token remains in .project_config.toml as api_key; this table holds only the refresh material that must never be returned to the frontend or written into Project files.
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
+ provider TEXT NOT NULL,
+ refresh_token TEXT NOT NULL,
+ access_token_expires_at TEXT,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (project_id, provider)
+);`;
+
export const SCHEMA_SQL = `
CREATE TABLE IF NOT EXISTS users (
user_id TEXT PRIMARY KEY, -- semantic id doubles as login name: ^[a-z][a-z0-9_-]{1,31}$
@@ -59,6 +69,7 @@ CREATE TABLE IF NOT EXISTS project_members ( -- member grants only; owners are
PRIMARY KEY (project_id, user_id)
);
${MODEL_PROMOTIONS_SQL}
+${MODEL_PROVIDER_AUTH_TOKENS_SQL}
CREATE TABLE IF NOT EXISTS agents ( -- index only; name/description live in system_config.yaml
project_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
diff --git a/packages/server/src/http/routes/modelscope-auth.ts b/packages/server/src/http/routes/modelscope-auth.ts
new file mode 100644
index 00000000..d72a142b
--- /dev/null
+++ b/packages/server/src/http/routes/modelscope-auth.ts
@@ -0,0 +1,96 @@
+/** Project-owner routes for authorizing a ModelScope key through the harness's bridge. */
+import { Hono } from "hono";
+import type {
+ ModelScopeAuthFlowStatusResponse,
+ ModelScopeAuthStartResponse,
+} from "../../api/types.js";
+import type { AppEnv } from "../../auth/middleware.js";
+import type { ModelScopeAuth } from "../../services/modelscope-auth-service.js";
+import { HttpError } from "../errors.js";
+import { requireValidId } from "../validate.js";
+import { modelConfigChanged } from "./models.js";
+import type { ModelsRouteDeps } from "./models.js";
+
+export interface ModelScopeAuthRouteDeps extends ModelsRouteDeps {
+ modelScopeAuth: ModelScopeAuth;
+}
+
+const FLOW_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
+
+function flowId(value: string): string {
+ if (!FLOW_ID_RE.test(value)) {
+ throw new HttpError(
+ 404,
+ "modelscope_auth_flow_not_found",
+ "This login has expired or does not exist.",
+ );
+ }
+ return value;
+}
+
+function owner(deps: ModelScopeAuthRouteDeps, userId: string, projectId: string): void {
+ deps.access.requireProjectOwner(userId, projectId);
+}
+
+function publishIfChanged(
+ deps: ModelScopeAuthRouteDeps,
+ projectId: string,
+ changed: boolean,
+): void {
+ if (changed) modelConfigChanged(deps, projectId);
+}
+
+export function modelScopeAuthRoutes(deps: ModelScopeAuthRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.post("/start", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ owner(deps, c.var.user.userId, projectId);
+ return c.json(
+ (await deps.modelScopeAuth.start({
+ projectId,
+ userId: c.var.user.userId,
+ })) satisfies ModelScopeAuthStartResponse,
+ 201,
+ );
+ });
+
+ app.get("/:flowId/status", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ owner(deps, c.var.user.userId, projectId);
+ const result = await deps.modelScopeAuth.status({
+ projectId,
+ userId: c.var.user.userId,
+ flowId: flowId(c.req.param("flowId") ?? ""),
+ });
+ publishIfChanged(deps, projectId, result.changed === true);
+ const { changed: _changed, ...response } = result;
+ return c.json(response satisfies ModelScopeAuthFlowStatusResponse);
+ });
+
+ app.post("/:flowId/retry", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ owner(deps, c.var.user.userId, projectId);
+ const result = await deps.modelScopeAuth.retryApply({
+ projectId,
+ userId: c.var.user.userId,
+ flowId: flowId(c.req.param("flowId") ?? ""),
+ });
+ publishIfChanged(deps, projectId, result.changed === true);
+ const { changed: _changed, ...response } = result;
+ return c.json(response satisfies ModelScopeAuthFlowStatusResponse);
+ });
+
+ app.post("/:flowId/cancel", (c) => {
+ const projectId = requireValidId(c, "projectId");
+ owner(deps, c.var.user.userId, projectId);
+ deps.modelScopeAuth.cancel({
+ projectId,
+ userId: c.var.user.userId,
+ flowId: flowId(c.req.param("flowId") ?? ""),
+ });
+ return c.json({ ok: true });
+ });
+
+ return app;
+}
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 4cc79450..e43815ce 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -118,12 +118,14 @@ import { vaultRoutes } from "./vault.js";
import { modelsRoutes } from "./models.js";
import { modelOAuthCallbackRoutes, modelOAuthRoutes } from "./model-oauth.js";
import { platformAuthRoutes } from "./platform-auth.js";
+import { modelScopeAuthRoutes } from "./modelscope-auth.js";
import { chatDefaultsRoutes } from "./chat-defaults.js";
import { commandPolicyRoutes } from "./command-policy.js";
import { usageRoutes } from "./usage.js";
import { PreviewTokens } from "./preview.js";
import type { Access, ModelOAuth, ProjectConfigStore } from "../../mechanisms/projects.js";
import type { PlatformAuth } from "../../services/platform-auth-service.js";
+import type { ModelScopeAuth } from "../../services/modelscope-auth-service.js";
import type { Schedules, SessionIndex, SessionOrigins } from "../../mechanisms/sessions.js";
import type { ErrorLog, UsageQueries } from "../../mechanisms/observability.js";
import type { TraceIndex, Traces } from "../../mechanisms/traces.js";
@@ -1606,6 +1608,12 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
auth: "user",
order: 115,
},
+ {
+ id: "session-api.modelscope-auth",
+ prefix: "/api/projects/:projectId/modelscope-auth",
+ auth: "user",
+ order: 116,
+ },
{
id: "session-api.chat-defaults",
prefix: "/api/projects/:projectId/chat-defaults",
@@ -1671,6 +1679,7 @@ export class SessionApiRoutes {
@Use() private readonly projectConfig!: ProjectConfigStore;
@Use() private readonly modelOAuth!: ModelOAuth;
@Use() private readonly platformAuth!: PlatformAuth;
+ @Use() private readonly modelScopeAuth!: ModelScopeAuth;
@Use() private readonly traceIndex!: TraceIndex;
@Use() private readonly traces!: Traces;
@Use() private readonly workspaceFiles!: WorkspaceFiles;
@@ -1686,6 +1695,7 @@ export class SessionApiRoutes {
@Bind("session-api.models") modelsRoutes!: Hono<AppEnv>;
@Bind("session-api.model-oauth") modelOauthRoutes!: Hono<AppEnv>;
@Bind("session-api.platform-auth") platformAuthRoutes!: Hono<AppEnv>;
+ @Bind("session-api.modelscope-auth") modelScopeAuthRoutes!: Hono<AppEnv>;
@Bind("session-api.chat-defaults") chatDefaultsRoutes!: Hono<AppEnv>;
@Bind("session-api.command-policy") commandPolicyRoutes!: Hono<AppEnv>;
@Bind("session-api.agents") agentsRoutes!: Hono<AppEnv>;
@@ -1744,6 +1754,10 @@ export class SessionApiRoutes {
this.modelsRoutes = modelsRoutes(modelDeps);
this.modelOauthRoutes = modelOAuthRoutes(modelOAuthDeps);
this.platformAuthRoutes = platformAuthRoutes({ ...modelDeps, platformAuth: this.platformAuth });
+ this.modelScopeAuthRoutes = modelScopeAuthRoutes({
+ ...modelDeps,
+ modelScopeAuth: this.modelScopeAuth,
+ });
this.chatDefaultsRoutes = chatDefaultsRoutes({
agentConfigService,
projectConfigService,
diff --git a/packages/server/src/mechanisms/projects.ts b/packages/server/src/mechanisms/projects.ts
index b03932bb..4d9eb23a 100644
--- a/packages/server/src/mechanisms/projects.ts
+++ b/packages/server/src/mechanisms/projects.ts
@@ -27,6 +27,7 @@ import type { UserRow } from "../db/repos/users.js";
import type { RawTable, UtilityCompletion } from "../services/project-config-service.js";
import type {
ListEndpointModelsOptions,
+ ModelRequestContext,
ModelRef,
PluginTable,
ProjectConfig,
@@ -147,7 +148,17 @@ export abstract class ProjectConfigStore extends Interface<{
getModels(projectId: string): Promise<ModelsResponse>;
updateModels(projectId: string, req: ModelsUpdateRequest): Promise<ModelsResponse>;
setGroupApiKey(projectId: string, provider: string, apiKey: string): Promise<number>;
+ setGroupApiKeyWithProviderAuthToken(
+ projectId: string,
+ provider: string,
+ apiKey: string,
+ token: Omit<ModelProviderAuthToken, "provider" | "updatedAt">,
+ options?: { expectedRefreshToken?: string },
+ ): Promise<number>;
getGroupApiKey(projectId: string, provider: string): Promise<string | undefined>;
+ setModelApiKeyResolver(
+ resolver: (context: ModelRequestContext) => Promise<string | undefined>,
+ ): void;
mergePlatformModels(
projectId: string,
provider: string,
@@ -174,6 +185,20 @@ export abstract class ModelPromotions extends Interface<{
replaceProvider(projectId: string, provider: string, rows: readonly ModelPromotion[]): void;
}>() {}
+export interface ModelProviderAuthToken {
+ provider: string;
+ refreshToken: string;
+ accessTokenExpiresAt?: string;
+ updatedAt: string;
+}
+
+/** Server-side OAuth refresh metadata for provider groups (web.db `model_provider_auth_tokens`). */
+export abstract class ModelProviderAuthTokens extends Interface<{
+ get(projectId: string, provider: string): ModelProviderAuthToken | undefined;
+ upsert(projectId: string, row: Omit<ModelProviderAuthToken, "updatedAt">): void;
+ delete(projectId: string, provider: string): void;
+}>() {}
+
/** ModelOAuth: the mechanism ModelOAuthService implements. */
export abstract class ModelOAuth extends Interface<{
start(input: {
diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.ts
index 0bd70f47..a1f81877 100644
--- a/packages/server/src/platform.ts
+++ b/packages/server/src/platform.ts
@@ -69,6 +69,7 @@ import { UiPrefsRepo } from "./db/repos/ui-prefs.js";
import { SessionsRepo } from "./db/repos/sessions.js";
import { ProjectsRepo } from "./db/repos/projects.js";
import { ModelPromotionsRepo } from "./db/repos/model-promotions.js";
+import { ModelProviderAuthTokensRepo } from "./db/repos/model-provider-auth-tokens.js";
import { MembersRepo } from "./db/repos/members.js";
import { AgentsRepo } from "./db/repos/agents.js";
import { UsageRepo } from "./db/repos/usage.js";
@@ -84,6 +85,7 @@ import { UsageService } from "./services/usage-service.js";
import { ProjectConfigService } from "./services/project-config-service.js";
import { ModelOAuthService } from "./services/model-oauth-service.js";
import { PlatformAuth, PlatformAuthProvider } from "./services/platform-auth-service.js";
+import { ModelScopeAuth, ModelScopeAuthProvider } from "./services/modelscope-auth-service.js";
import { TraceIndexService } from "./services/trace-index.js";
import { TraceService } from "./services/trace-service.js";
import { WorkspaceFilesService } from "./services/workspace-files-service.js";
@@ -125,6 +127,7 @@ import {
AgentIndex,
Members,
ModelOAuth,
+ ModelProviderAuthTokens,
ProjectConfigStore,
ProjectLifecycle,
Projects,
@@ -255,6 +258,7 @@ export class IdentityModule {}
children: [
ProjectsRepo,
ModelPromotionsRepo,
+ ModelProviderAuthTokensRepo,
MembersRepo,
AgentsRepo,
ProjectAccess,
@@ -262,6 +266,7 @@ export class IdentityModule {}
ProjectConfigService,
ModelOAuthService,
PlatformAuthProvider,
+ ModelScopeAuthProvider,
ProjectsRoutes,
ProjectAdminRoutes,
],
@@ -272,8 +277,10 @@ export class IdentityModule {}
Access,
ProjectLifecycle,
ProjectConfigStore,
+ ModelProviderAuthTokens,
ModelOAuth,
PlatformAuth,
+ ModelScopeAuth,
InitialProjectProvisioner,
],
})
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index bae40f59..a467a550 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -48,6 +48,7 @@ import type {
BackgroundSubagentInfo,
CompactAvailability,
ControlEnvContext,
+ AgentAssembly,
OmniMessage,
ProxyEnvPolicy,
SpawnConfiner,
@@ -85,6 +86,7 @@ import type { SessionService as SessionServiceImpl } from "../services/session-s
import type { ClassCtx, Opaque } from "@prismshadow/penguin-core/kernel";
import { Sandbox, SandboxModule } from "../sandbox/service.js";
import { SessionService } from "../services/session-service.js";
+import { ModelScopeAuth } from "../services/modelscope-auth-service.js";
import { TitleGenerator } from "./title-generator.js";
import { loopbackHostRoles } from "../services/preview-token.js";
import { mergedNoProxy } from "../net/proxy.js";
@@ -99,6 +101,7 @@ import type { Settings } from "../mechanisms/settings.js";
import type { MessagingBindings } from "../mechanisms/messaging.js";
import type { OrgCache } from "../mechanisms/organization.js";
import { enabledMessagingChannel } from "./messaging/enabled-channel.js";
+import { MODELSCOPE_PROVIDER_ID } from "@prismshadow/penguin-core/model-catalog";
/**
* 409 for when there's nothing to compact: give the specific reason rather than a
@@ -259,6 +262,7 @@ export function createCoreSessionLoader(
controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;
pathPrepend?: () => string[];
confineSpawn?: () => SpawnConfiner | null;
+ assembly?: AgentAssembly;
} = {},
): SessionLoader {
return {
@@ -271,6 +275,7 @@ export function createCoreSessionLoader(
...(opts.controlEnv ? { controlEnv: opts.controlEnv } : {}),
...(opts.pathPrepend ? { pathPrepend: opts.pathPrepend } : {}),
...(opts.confineSpawn ? { confineSpawn: opts.confineSpawn } : {}),
+ ...(opts.assembly ? { assembly: opts.assembly } : {}),
});
const located = await findLatestTraceFile(
tracesDir(root, row.projectId, row.agentId),
@@ -351,6 +356,8 @@ export interface SessionManagerDeps {
titles?: TitleNotifier;
/** Error persistence (optional: without it, only logs — same as before this was wired up). */
errors?: ErrorSink;
+ /** Provider auth refresh (optional for tests that do not exercise external model credentials). */
+ modelScopeAuth?: ModelScopeAuth;
log?: (line: string) => void;
/** Goal run-state persistence (optional like `titles`: without it, goals run but leave no restorable record). */
/**
@@ -1691,12 +1698,25 @@ export class SessionManager {
return this.agentGenerations.get(agentKey(projectId, agentId)) ?? 0;
}
+ private async refreshProviderCredentialIfNeeded(row: {
+ projectId: string;
+ agentId: string;
+ provider: string;
+ }): Promise<void> {
+ const refreshed = await this.deps.modelScopeAuth?.ensureFresh({
+ projectId: row.projectId,
+ provider: row.provider,
+ });
+ if (refreshed?.changed) this.invalidateProjectRuntimes(row.projectId);
+ }
+
/** get-or-resume-or-heal: use directly on an active-table hit; otherwise load via the loader, updating the index's primary key on self-heal. */
private async ensureEntry(sessionId: string): Promise<RuntimeEntry> {
const existing = this.entries.get(sessionId);
/** Background-task counts the discarded runtime last reported (see the publish below). */
let discardedBackgroundTasks: SessionBackgroundTasks | undefined;
if (existing) {
+ await this.refreshProviderCredentialIfNeeded(existing);
if (existing.generation === this.generationOf(existing.projectId, existing.agentId)) {
return existing;
}
@@ -1722,6 +1742,7 @@ export class SessionManager {
"Session does not exist or you do not have access.",
);
}
+ await this.refreshProviderCredentialIfNeeded(row);
// Captured before the (awaited) load: an invalidation racing with the load leaves
// this entry stale, so the access after next rebuilds it with the new values.
const generation = this.generationOf(row.projectId, row.agentId);
@@ -2305,6 +2326,7 @@ export class SessionsModule {
@Use() private readonly sources!: SessionOrigins;
@Use() private readonly recorder!: UsageRecording;
@Use() private readonly errors!: Errors;
+ @Use() private readonly modelScopeAuth!: ModelScopeAuth;
@Use() private readonly projectConfig!: ProjectConfigStore;
@Use() private readonly traceIndex!: TraceIndex;
@Use() private readonly traceStore!: TraceIndexStore;
@@ -2328,6 +2350,18 @@ export class SessionsModule {
const projectConfig = this.projectConfig;
const sandbox = this.sandbox as SandboxService;
const orgCache = this.orgCache;
+ const modelScopeAuth = this.modelScopeAuth;
+
+ const assembly: AgentAssembly = {
+ resolveModelApiKey: async ({ projectId, provider, modelId }) => {
+ if (provider !== MODELSCOPE_PROVIDER_ID) return undefined;
+ await modelScopeAuth.ensureFresh({ projectId, provider });
+ const apiKey = await projectConfig.getGroupApiKey(projectId, provider);
+ if (apiKey === undefined) throw modelCredentialMissing(modelId);
+ return apiKey;
+ },
+ };
+ projectConfig.setModelApiKeyResolver(assembly.resolveModelApiKey!);
// Which commands run confined, under which policy, by which backend is policy — the
// sandbox module's; core only carries the spawn seam, reached through this getter.
@@ -2393,10 +2427,12 @@ export class SessionsModule {
controlEnv: env.controlEnv,
pathPrepend: env.pathPrepend,
confineSpawn: env.confineSpawn,
+ assembly,
}),
sources,
recorder,
errors,
+ modelScopeAuth: this.modelScopeAuth,
titles,
log,
notifyProjectUsers,
@@ -2427,6 +2463,7 @@ export class SessionsModule {
orgIdsOfProject: (projectId) => orgCache.orgIdsOfProject(projectId),
pathPrepend: env.pathPrepend,
confineSpawn: env.confineSpawn,
+ assembly,
});
this.manager = manager;
this.sessionService = sessionService;
diff --git a/packages/server/src/services/modelscope-auth-service.ts b/packages/server/src/services/modelscope-auth-service.ts
new file mode 100644
index 00000000..1f03e210
--- /dev/null
+++ b/packages/server/src/services/modelscope-auth-service.ts
@@ -0,0 +1,660 @@
+/**
+ * Project-scoped ModelScope key authorization, through the harness's own bridge.
+ *
+ * ModelScope's OAuth cannot run inside the App: the code exchange needs a client secret the
+ * desktop App must not hold, and ModelScope returns that code to a redirect URI the App does
+ * not own. The bridge at `config.modelscopeBridgeUrl` keeps the secret and runs the exchange.
+ * The App speaks only the device-style start/poll pair below to the bridge, and receives
+ * exactly once an api-inference token delivery, which it then writes across the ModelScope
+ * group the same way any other group key is written.
+ *
+ * Two consequences of that single delivery shape most of this file. A poll that has already
+ * succeeded can never be re-polled — the bridge clears its server-side copy on delivery — so a
+ * write that fails afterwards keeps the token on the flow for `retryApply` instead of asking
+ * the user to authorize again. The refresh token is stored in web.db, never in
+ * .project_config.toml; model requests call `ensureFresh` before loading a runtime and again
+ * immediately before each upstream request, silently rotating the access token near expiry.
+ */
+import { randomBytes } from "node:crypto";
+import { Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import { MODELSCOPE_PROVIDER_ID } from "@prismshadow/penguin-core/model-catalog";
+import { HttpError } from "../http/errors.js";
+import { Config } from "../hmr/capabilities.js";
+import type {
+ ModelProviderAuthToken,
+ ModelProviderAuthTokens,
+ ProjectConfigStore,
+} from "../mechanisms/projects.js";
+import type { ModelScopeAuthFlowStatusResponse } from "../api/types.js";
+
+/** Recorded by the bridge alongside the flow; it identifies the App but does not gate it. */
+export const MODELSCOPE_BRIDGE_CLIENT_ID = "penguin-harness";
+
+const FLOW_TTL_MS = 10 * 60 * 1000;
+const MAX_FLOWS_PER_OWNER = 8;
+const MAX_RESPONSE_BYTES = 512 * 1024;
+const REQUEST_TIMEOUT_MS = 10_000;
+const MAX_ACCESS_TOKEN_LENGTH = 4096;
+const MAX_REFRESH_TOKEN_LENGTH = 4096;
+const MAX_AUTHORIZE_URL_LENGTH = 2048;
+const DEFAULT_RETRY_AFTER_MS = 1_000;
+const MAX_RETRY_AFTER_MS = 60_000;
+const REFRESH_SKEW_MS = 5 * 60 * 1000;
+const MAX_CONSECUTIVE_REFRESH_FAILURES = 3;
+const REFRESH_FAILURE_BACKOFF_MS = 30_000;
+
+type FlowStatus = "pending" | "applying" | "completed" | "cancelled" | "apply_failed" | "error";
+
+interface Flow {
+ flowId: string;
+ projectId: string;
+ userId: string;
+ code: string | null;
+ deviceSecret: string | null;
+ authorizeUrl: string;
+ expiresAt: number;
+ status: FlowStatus;
+ error?: ModelScopeAuthFlowStatusResponse["error"];
+ applied?: number;
+ credential?: ModelScopeCredential;
+ polling?: Promise<void>;
+ retryPollAt?: number;
+ changed?: boolean;
+}
+
+export type ModelScopeAuthStatusResult = ModelScopeAuthFlowStatusResponse & { changed?: true };
+
+export interface ModelScopeCredential {
+ accessToken: string;
+ refreshToken?: string;
+ expiresAt?: string;
+}
+
+export interface ModelScopeRefreshResult {
+ changed: boolean;
+}
+
+interface ModelScopeAuthDeps {
+ /** Base URL of the bridge, without a trailing slash (config.modelscopeBridgeUrl). */
+ bridgeUrl: string;
+ /** Writes the delivered credential; resolves to how many rows took the access token. */
+ applyCredential: (
+ projectId: string,
+ credential: ModelScopeCredential,
+ options?: { expectedRefreshToken?: string },
+ ) => Promise<number>;
+ /** Reads the server-side refresh metadata for the group. */
+ readStoredCredential?: (projectId: string) => ModelProviderAuthToken | undefined;
+ fetchImpl?: typeof fetch;
+ now?: () => number;
+}
+
+function asRecord(value: unknown): Record<string, unknown> {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+async function readJsonBounded(response: Response): Promise<unknown> {
+ if (response.body === null) return null;
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ try {
+ while (true) {
+ const part = await reader.read();
+ if (part.done) break;
+ size += part.value.byteLength;
+ if (size > MAX_RESPONSE_BYTES) {
+ await reader.cancel("Bridge response is too large.");
+ throw new Error("Bridge response is too large.");
+ }
+ chunks.push(part.value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ const body = Buffer.concat(chunks).toString("utf8");
+ return body === "" ? null : JSON.parse(body);
+}
+
+function requiredString(value: unknown, maxLength: number, label: string): string {
+ if (typeof value !== "string" || value.length === 0 || value.length > maxLength) {
+ throw new Error(`The bridge returned an invalid ${label}.`);
+ }
+ return value;
+}
+
+/**
+ * The authorize URL is opened in a browser tab, so it is validated as an address rather than
+ * merely copied: the bridge generates it, and a value that is not an absolute http(s) URL with
+ * no embedded credentials has no business reaching `window.open`.
+ */
+function authorizeEndpoint(value: unknown): string {
+ const raw = requiredString(value, MAX_AUTHORIZE_URL_LENGTH, "authorize URL");
+ const parsed = new URL(raw);
+ if (
+ (parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
+ parsed.username !== "" ||
+ parsed.password !== ""
+ ) {
+ throw new Error("The bridge returned an invalid authorize URL.");
+ }
+ return raw;
+}
+
+function optionalTokenString(value: unknown, maxLength: number, label: string): string | undefined {
+ if (value === undefined || value === null || value === "") return undefined;
+ return requiredString(value, maxLength, label);
+}
+
+function optionalIsoDate(value: unknown, label: string): string | undefined {
+ if (value === undefined || value === null || value === "") return undefined;
+ const raw = requiredString(value, 128, label);
+ const ms = Date.parse(raw);
+ if (!Number.isFinite(ms)) throw new Error(`The bridge returned an invalid ${label}.`);
+ return new Date(ms).toISOString();
+}
+
+/** Validates the one-time delivery and extracts the api-inference credential. */
+export function modelscopeCredential(
+ value: unknown,
+ fallbackRefreshToken?: string,
+): ModelScopeCredential {
+ const body = asRecord(value);
+ if (body.status !== "completed") throw new Error("The bridge returned another status.");
+ return modelscopeToken(body.token, fallbackRefreshToken);
+}
+
+/** Validates POST /oauth/refresh, whose successful envelope is `{ token }` without flow status. */
+export function modelscopeRefreshCredential(
+ value: unknown,
+ fallbackRefreshToken?: string,
+): ModelScopeCredential {
+ return modelscopeToken(asRecord(value).token, fallbackRefreshToken);
+}
+
+function modelscopeToken(value: unknown, fallbackRefreshToken?: string): ModelScopeCredential {
+ const token = asRecord(value);
+ const refreshToken =
+ optionalTokenString(token.refreshToken, MAX_REFRESH_TOKEN_LENGTH, "refresh token") ??
+ fallbackRefreshToken;
+ const expiresAt = optionalIsoDate(token.expiresAt, "access token expiry");
+ return {
+ accessToken: requiredString(token.accessToken, MAX_ACCESS_TOKEN_LENGTH, "access token"),
+ ...(refreshToken !== undefined ? { refreshToken } : {}),
+ ...(expiresAt !== undefined ? { expiresAt } : {}),
+ };
+}
+
+/** Backward-compatible helper used by older tests and small validators. */
+export function modelscopeAccessToken(value: unknown): string {
+ return modelscopeCredential(value).accessToken;
+}
+
+function retryAfterMs(value: unknown): number {
+ const seconds = asRecord(value).retryAfterSeconds;
+ if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds <= 0) {
+ return DEFAULT_RETRY_AFTER_MS;
+ }
+ return Math.min(MAX_RETRY_AFTER_MS, Math.ceil(seconds * 1000));
+}
+
+function retryAfterSeconds(value: unknown): number {
+ return Math.ceil(retryAfterMs(value) / 1000);
+}
+
+export class ModelScopeAuthService {
+ private readonly flows = new Map<string, Flow>();
+ private readonly refreshes = new Map<string, Promise<ModelScopeRefreshResult>>();
+ private readonly refreshFailures = new Map<
+ string,
+ { refreshToken: string; count: number; retryAt: number }
+ >();
+ private readonly fetchImpl: typeof fetch;
+ private readonly now: () => number;
+
+ constructor(private readonly deps: ModelScopeAuthDeps) {
+ this.fetchImpl = deps.fetchImpl ?? ((...args) => fetch(...args));
+ this.now = deps.now ?? (() => Date.now());
+ }
+
+ private url(path: string): string {
+ return `${this.deps.bridgeUrl}${path}`;
+ }
+
+ private isPending(flow: Flow): boolean {
+ return (
+ this.flows.get(flow.flowId) === flow &&
+ flow.status === "pending" &&
+ flow.expiresAt > this.now()
+ );
+ }
+
+ private async request(path: string, init: RequestInit): Promise<Response> {
+ return this.fetchImpl(this.url(path), {
+ ...init,
+ redirect: "manual",
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+ }
+
+ async ensureFresh(input: {
+ projectId: string;
+ provider: string;
+ }): Promise<ModelScopeRefreshResult> {
+ if (input.provider !== MODELSCOPE_PROVIDER_ID) return { changed: false };
+ const stored = this.deps.readStoredCredential?.(input.projectId);
+ const state = this.refreshState(stored);
+ if (stored === undefined || state === "fresh") return { changed: false };
+ const key = `${input.projectId}:${input.provider}`;
+ const recordedFailures = this.refreshFailures.get(key);
+ const failures =
+ recordedFailures?.refreshToken === stored.refreshToken ? recordedFailures : undefined;
+ if (recordedFailures !== undefined && failures === undefined) {
+ this.refreshFailures.delete(key);
+ }
+ if (failures !== undefined) {
+ if (failures.count >= MAX_CONSECUTIVE_REFRESH_FAILURES) {
+ throw this.reauthorizationRequired();
+ }
+ if (state === "refresh" && failures.retryAt > this.now()) return { changed: false };
+ }
+ const existing = this.refreshes.get(key);
+ if (existing) return existing;
+ const refresh = this.refreshNow(input.projectId, input.provider, stored, state).finally(() => {
+ this.refreshes.delete(key);
+ });
+ this.refreshes.set(key, refresh);
+ return refresh;
+ }
+
+ async start(input: { projectId: string; userId: string }): Promise<{
+ flowId: string;
+ authorizeUrl: string;
+ expiresAt: string;
+ }> {
+ this.sweep();
+ const flowId = randomBytes(32).toString("base64url");
+ const code = randomBytes(32).toString("base64url");
+ const deviceSecret = randomBytes(32).toString("base64url");
+ let response: Response;
+ try {
+ response = await this.request("/oauth/start", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ code,
+ deviceSecret,
+ client: { id: MODELSCOPE_BRIDGE_CLIENT_ID },
+ }),
+ });
+ } catch {
+ throw new HttpError(
+ 502,
+ "modelscope_unreachable",
+ "The ModelScope bridge could not be reached.",
+ );
+ }
+ if (response.status === 429) {
+ let body: unknown = null;
+ try {
+ body = await readJsonBounded(response);
+ } catch {
+ // A malformed rate-limit response still gets the bounded default delay.
+ }
+ const retryAfter = retryAfterSeconds(body);
+ throw new HttpError(
+ 429,
+ "modelscope_rate_limited",
+ "The ModelScope bridge is receiving too many authorization requests. Try again shortly.",
+ retryAfter,
+ );
+ }
+ if (response.status !== 201) {
+ throw new HttpError(
+ 502,
+ "modelscope_start_failed",
+ "The ModelScope bridge refused the key flow.",
+ );
+ }
+ let body: Record<string, unknown>;
+ let authorizeUrl: string;
+ try {
+ body = asRecord(await readJsonBounded(response));
+ authorizeUrl = authorizeEndpoint(body.authorizeUrl);
+ } catch {
+ throw new HttpError(
+ 502,
+ "modelscope_start_failed",
+ "The ModelScope bridge returned an invalid response.",
+ );
+ }
+ const expiresAt = typeof body.expiresAt === "string" ? Date.parse(body.expiresAt) : NaN;
+ if (!Number.isFinite(expiresAt) || expiresAt <= this.now()) {
+ throw new HttpError(
+ 502,
+ "modelscope_start_failed",
+ "The ModelScope bridge returned an invalid expiry.",
+ );
+ }
+ this.evictOldest(input.userId, input.projectId);
+ // The bridge builds this URL itself (it is the one that knows the redirect URI and its own
+ // public prefix), so it is passed through rather than assembled here.
+ const localExpiresAt = Math.min(expiresAt, this.now() + FLOW_TTL_MS);
+ this.flows.set(flowId, {
+ flowId,
+ projectId: input.projectId,
+ userId: input.userId,
+ code,
+ deviceSecret,
+ authorizeUrl,
+ expiresAt: localExpiresAt,
+ status: "pending",
+ });
+ return { flowId, authorizeUrl, expiresAt: new Date(localExpiresAt).toISOString() };
+ }
+
+ async status(input: {
+ flowId: string;
+ projectId: string;
+ userId: string;
+ }): Promise<ModelScopeAuthStatusResult> {
+ const flow = this.requireFlow(input);
+ if (
+ flow.status === "pending" &&
+ (flow.retryPollAt === undefined || flow.retryPollAt <= this.now())
+ ) {
+ flow.polling ??= this.pollBridge(flow).finally(() => {
+ flow.polling = undefined;
+ });
+ await flow.polling;
+ }
+ return this.publicFlow(flow);
+ }
+
+ async retryApply(input: {
+ flowId: string;
+ projectId: string;
+ userId: string;
+ }): Promise<ModelScopeAuthStatusResult> {
+ const flow = this.requireFlow(input);
+ if (flow.status !== "apply_failed" || flow.credential === undefined) {
+ throw new HttpError(
+ 409,
+ "modelscope_auth_not_retryable",
+ "This key cannot be applied again.",
+ );
+ }
+ await this.apply(flow);
+ return this.publicFlow(flow);
+ }
+
+ cancel(input: { flowId: string; projectId: string; userId: string }): void {
+ const flow = this.requireFlow(input);
+ if (flow.status === "completed" || flow.status === "applying") {
+ throw new HttpError(
+ 409,
+ "modelscope_auth_flow_used",
+ "This key flow can no longer be cancelled.",
+ );
+ }
+ flow.status = "cancelled";
+ // Best effort: the flow is cancelled locally whatever the bridge answers, and the code and
+ // secret are dropped either way so a later poll cannot revive it. The bridge also expires
+ // the flow on its own.
+ if (flow.code !== null && flow.deviceSecret !== null) {
+ const body = JSON.stringify({ code: flow.code, deviceSecret: flow.deviceSecret });
+ void this.request("/oauth/cancel", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body,
+ })
+ .then((response) => response.body?.cancel())
+ .catch(() => {});
+ }
+ flow.code = null;
+ flow.deviceSecret = null;
+ flow.credential = undefined;
+ }
+
+ private refreshState(
+ stored: ModelProviderAuthToken | undefined,
+ ): "fresh" | "refresh" | "expired" {
+ if (stored === undefined || stored.accessTokenExpiresAt === undefined) return "fresh";
+ const expiresAt = Date.parse(stored.accessTokenExpiresAt);
+ if (!Number.isFinite(expiresAt)) return "fresh";
+ const now = this.now();
+ if (expiresAt <= now) return "expired";
+ return expiresAt <= now + REFRESH_SKEW_MS ? "refresh" : "fresh";
+ }
+
+ private async refreshNow(
+ projectId: string,
+ provider: string,
+ stored: ModelProviderAuthToken,
+ state: "refresh" | "expired",
+ ): Promise<ModelScopeRefreshResult> {
+ const key = `${projectId}:${provider}`;
+ try {
+ const response = await this.request("/oauth/refresh", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ refreshToken: stored.refreshToken }),
+ });
+ if (!response.ok) throw new Error(`Bridge refresh failed: ${response.status}`);
+ const credential = modelscopeRefreshCredential(
+ await readJsonBounded(response),
+ stored.refreshToken,
+ );
+ const applied = await this.deps.applyCredential(projectId, credential, {
+ expectedRefreshToken: stored.refreshToken,
+ });
+ if (applied === 0) return { changed: false };
+ this.refreshFailures.delete(key);
+ return { changed: true };
+ } catch (error) {
+ const previous = this.refreshFailures.get(key);
+ const count = (previous?.refreshToken === stored.refreshToken ? previous.count : 0) + 1;
+ this.refreshFailures.set(key, {
+ refreshToken: stored.refreshToken,
+ count,
+ retryAt: this.now() + REFRESH_FAILURE_BACKOFF_MS * 2 ** (count - 1),
+ });
+ if (state === "refresh" && count < MAX_CONSECUTIVE_REFRESH_FAILURES) {
+ return { changed: false };
+ }
+ throw this.reauthorizationRequired();
+ }
+ }
+
+ private reauthorizationRequired(): HttpError {
+ return new HttpError(
+ 409,
+ "modelscope_refresh_failed",
+ "ModelScope authorization could not be refreshed after repeated attempts. Authorize ModelScope again on the Models page.",
+ );
+ }
+
+ private async pollBridge(flow: Flow): Promise<void> {
+ if (!this.isPending(flow) || flow.code === null || flow.deviceSecret === null) return;
+ let response: Response;
+ try {
+ response = await this.request("/oauth/poll", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ code: flow.code, deviceSecret: flow.deviceSecret }),
+ });
+ } catch {
+ if (!this.isPending(flow)) return;
+ flow.status = "error";
+ flow.error = "unreachable";
+ return;
+ }
+ if (!this.isPending(flow)) return;
+ if (response.status === 429) {
+ let body: unknown = null;
+ try {
+ body = await readJsonBounded(response);
+ } catch {
+ // A malformed rate-limit response still gets a bounded default backoff.
+ }
+ if (!this.isPending(flow)) return;
+ flow.retryPollAt = this.now() + retryAfterMs(body);
+ return;
+ }
+ if (!response.ok) {
+ flow.status = "error";
+ flow.error = "upstream_failed";
+ return;
+ }
+ flow.retryPollAt = undefined;
+ let body: unknown;
+ try {
+ body = await readJsonBounded(response);
+ } catch {
+ if (!this.isPending(flow)) return;
+ flow.status = "error";
+ flow.error = "invalid_key";
+ return;
+ }
+ if (!this.isPending(flow)) return;
+ const status = asRecord(body).status;
+ if (status === "pending") return;
+ if (status === "completed") {
+ try {
+ flow.credential = modelscopeCredential(body);
+ } catch {
+ flow.status = "error";
+ flow.error = "invalid_key";
+ flow.code = null;
+ flow.deviceSecret = null;
+ return;
+ }
+ // The token is now in hand and the bridge's copy is gone: nothing may poll again.
+ flow.code = null;
+ flow.deviceSecret = null;
+ await this.apply(flow);
+ return;
+ }
+ flow.status = status === "cancelled" ? "cancelled" : "error";
+ flow.error =
+ status === "expired"
+ ? "expired"
+ : status === "locked"
+ ? "locked"
+ : status === "delivered"
+ ? "already_delivered"
+ : status === "cancelled"
+ ? undefined
+ : "upstream_failed";
+ flow.code = null;
+ flow.deviceSecret = null;
+ }
+
+ private async apply(flow: Flow): Promise<void> {
+ if (flow.credential === undefined) return;
+ flow.status = "applying";
+ flow.error = undefined;
+ try {
+ const applied = await this.deps.applyCredential(flow.projectId, flow.credential);
+ // A group with no rows would silently swallow the token, leaving the user authorized
+ // with nothing to show for it.
+ if (applied === 0) throw new Error("The ModelScope group is empty.");
+ this.refreshFailures.delete(`${flow.projectId}:${MODELSCOPE_PROVIDER_ID}`);
+ flow.applied = applied;
+ flow.credential = undefined;
+ flow.status = "completed";
+ flow.changed = true;
+ } catch {
+ // The token stays on the flow: the bridge cannot deliver it a second time, so the only
+ // way forward is retrying the write.
+ flow.status = "apply_failed";
+ flow.error = "apply_failed";
+ }
+ }
+
+ private publicFlow(flow: Flow): ModelScopeAuthStatusResult {
+ const changed = flow.changed === true;
+ flow.changed = false;
+ return {
+ status: flow.status,
+ ...(flow.error !== undefined ? { error: flow.error } : {}),
+ ...(flow.applied !== undefined ? { applied: flow.applied } : {}),
+ ...(changed ? { changed: true as const } : {}),
+ };
+ }
+
+ private requireFlow(input: { flowId: string; projectId: string; userId: string }): Flow {
+ this.sweep();
+ const flow = this.flows.get(input.flowId);
+ if (
+ flow === undefined ||
+ flow.projectId !== input.projectId ||
+ flow.userId !== input.userId ||
+ flow.expiresAt <= this.now()
+ ) {
+ throw new HttpError(
+ 404,
+ "modelscope_auth_flow_not_found",
+ "This key flow has expired or does not exist.",
+ );
+ }
+ return flow;
+ }
+
+ 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(
+ (flow) => flow.userId === userId && flow.projectId === projectId,
+ );
+ for (const flow of mine.slice(0, Math.max(0, mine.length - (MAX_FLOWS_PER_OWNER - 1)))) {
+ this.flows.delete(flow.flowId);
+ }
+ }
+}
+
+/** The per-App ModelScope key authorization capability consumed by Project model routes. */
+export abstract class ModelScopeAuth extends Interface<
+ Pick<ModelScopeAuthService, "start" | "status" | "retryApply" | "cancel" | "ensureFresh">
+>() {}
+
+/** Keep in-flight flows on the current bridge, like PlatformAuthProvider keeps them on Penguin Go. */
+@Module()
+export class ModelScopeAuthProvider {
+ @Use() private readonly config!: Config;
+ @Use() private readonly projectConfig!: ProjectConfigStore;
+ @Use() private readonly providerAuthTokens!: ModelProviderAuthTokens;
+ @Provide() auth!: ModelScopeAuth;
+
+ setup() {
+ this.auth = new ModelScopeAuthService({
+ bridgeUrl: this.config.modelscopeBridgeUrl,
+ applyCredential: async (projectId, credential, options) => {
+ if (credential.refreshToken !== undefined) {
+ return this.projectConfig.setGroupApiKeyWithProviderAuthToken(
+ projectId,
+ MODELSCOPE_PROVIDER_ID,
+ credential.accessToken,
+ {
+ refreshToken: credential.refreshToken,
+ accessTokenExpiresAt: credential.expiresAt,
+ },
+ options,
+ );
+ }
+ return this.projectConfig.setGroupApiKey(
+ projectId,
+ MODELSCOPE_PROVIDER_ID,
+ credential.accessToken,
+ );
+ },
+ readStoredCredential: (projectId) =>
+ this.providerAuthTokens.get(projectId, MODELSCOPE_PROVIDER_ID),
+ });
+ }
+}
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index aec2521a..aa63a646 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -38,6 +38,7 @@ import {
GenerativeModel,
canonicalClientType,
listEndpointModels as coreListEndpointModels,
+ MODELSCOPE_PROVIDER_ID,
PENGUIN_GO_PROVIDER_ID,
catalogEntryFor,
defaultProjectConfig,
@@ -56,6 +57,7 @@ import type {
CommandPolicyRule,
GenerativeModelConfig,
LLMOutcome,
+ ModelRequestContext,
ModelRef,
OmniMessage,
ProjectConfig,
@@ -99,6 +101,8 @@ import { Component, Use } from "@prismshadow/penguin-core/kernel";
import type { Config, Paths } from "../hmr/capabilities.js";
import type {
ModelPromotion,
+ ModelProviderAuthToken,
+ ModelProviderAuthTokens,
ModelPromotions,
ProjectConfigStore,
} from "../mechanisms/projects.js";
@@ -463,10 +467,15 @@ export class ProjectConfigService implements ProjectConfigStore {
* entry) falls back to a full read.
*/
private readonly cache = new Map<string, { mtimeMs: number; table: RawTable }>();
+ private readonly providerCredentialLocks = new Map<string, Promise<unknown>>();
+ private modelApiKeyResolver:
+ ((context: ModelRequestContext) => Promise<string | undefined>) | undefined;
@Use() private readonly paths!: Paths;
/** Optional for narrow service tests; the production Projects module always provides it. */
@Use() private readonly promotions?: ModelPromotions;
+ /** Optional for narrow service tests; OAuth refresh metadata lives in web.db, not TOML. */
+ @Use() private readonly providerAuthTokens?: ModelProviderAuthTokens;
private get root(): string {
return this.paths.root;
}
@@ -475,6 +484,45 @@ export class ProjectConfigService implements ProjectConfigStore {
return projectConfigPath(this.root, projectId);
}
+ setModelApiKeyResolver(
+ resolver: (context: ModelRequestContext) => Promise<string | undefined>,
+ ): void {
+ this.modelApiKeyResolver = resolver;
+ }
+
+ private requestApiKeyResolver(
+ projectId: string,
+ provider: string,
+ modelId: string,
+ enabled = true,
+ ): Pick<GenerativeModelConfig, "resolveApiKey"> | Record<string, never> {
+ if (!enabled || this.modelApiKeyResolver === undefined) return {};
+ return {
+ resolveApiKey: () => this.modelApiKeyResolver!({ projectId, provider, modelId }),
+ };
+ }
+
+ private async withProviderCredentialLock<T>(
+ projectId: string,
+ provider: string,
+ task: () => Promise<T>,
+ ): Promise<T> {
+ const key = `${projectId}\0${provider}`;
+ const previous = this.providerCredentialLocks.get(key) ?? Promise.resolve();
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => (release = resolve));
+ const current = previous.catch(() => undefined).then(() => gate);
+ this.providerCredentialLocks.set(key, current);
+ await previous.catch(() => undefined);
+ try {
+ return await task();
+ } finally {
+ release();
+ if (this.providerCredentialLocks.get(key) === current)
+ this.providerCredentialLocks.delete(key);
+ }
+ }
+
/**
* When the Project config (models/credentials) last changed: the config file's mtime as
* ISO — an honest persistent source that survives server restarts (every models update
@@ -849,6 +897,12 @@ export class ProjectConfigService implements ProjectConfigStore {
const llm = new GenerativeModel({
modelId: req.modelId,
...(apiKey ? { apiKey } : {}),
+ ...this.requestApiKeyResolver(
+ projectId,
+ req.provider,
+ req.modelId,
+ req.apiKey === undefined && req.clearApiKey !== true,
+ ),
...(baseUrl ? { baseUrl } : {}),
...(clientType ? { clientType } : {}),
tools: [],
@@ -917,7 +971,10 @@ export class ProjectConfigService implements ProjectConfigStore {
// Inside the try for the same reason as the probes: the SDK throws during
// construction when a credential is missing, and that must read as a failure with a
// reason rather than an exception out of a dialog's helper.
- const llm = new GenerativeModel(utilityCompletionConfig(ref.model_id, entry));
+ const llm = new GenerativeModel({
+ ...utilityCompletionConfig(ref.model_id, entry),
+ ...this.requestApiKeyResolver(projectId, ref.provider, ref.model_id),
+ });
return await collectUtilityCompletion(
llm.streamGenerate({ newMessages: [userText(prompt)] }),
);
@@ -966,6 +1023,12 @@ export class ProjectConfigService implements ProjectConfigStore {
const llm = new GenerativeModel({
modelId: req.modelId,
...(apiKey ? { apiKey } : {}),
+ ...this.requestApiKeyResolver(
+ projectId,
+ req.provider,
+ req.modelId,
+ req.apiKey === undefined && req.clearApiKey !== true,
+ ),
...(baseUrl ? { baseUrl } : {}),
...(clientType ? { clientType } : {}),
...(fastMode ? { fastMode: true } : {}),
@@ -1234,6 +1297,15 @@ export class ProjectConfigService implements ProjectConfigStore {
* promotion with it. A `discount` outside (0, 1) rejects the request before any write.
*/
async updateModels(projectId: string, req: ModelsUpdateRequest): Promise<ModelsResponse> {
+ return this.withProviderCredentialLock(projectId, MODELSCOPE_PROVIDER_ID, () =>
+ this.updateModelsUnlocked(projectId, req),
+ );
+ }
+
+ private async updateModelsUnlocked(
+ projectId: string,
+ req: ModelsUpdateRequest,
+ ): Promise<ModelsResponse> {
req.models.forEach((entry, i) => {
const { discount } = entry;
if (discount === undefined || discount === null) return;
@@ -1243,9 +1315,14 @@ export class ProjectConfigService implements ProjectConfigStore {
});
const raw = await this.readRaw(projectId);
const prevModels = asArray(raw.models);
+ const hadModelScopeGroup = prevModels.some(
+ (model) => model.provider === MODELSCOPE_PROVIDER_ID,
+ );
const seen = new Set<string>();
const nextModels: RawTable[] = [];
+ let keepModelScopeGroup = false;
+ let clearModelScopeProviderAuthToken = false;
// Rename mapping (old reference key -> new reference): default model / vision model pointers follow a key change instead of being lost on a full table replacement.
const renamed = new Map<string, ModelRefDto>();
// Each row's promotion, settled against the stored set once the file is written.
@@ -1347,15 +1424,19 @@ export class ProjectConfigService implements ProjectConfigStore {
if (entry.clearApiKey) {
delete next.api_key;
delete next.created_at;
+ if (entry.provider === MODELSCOPE_PROVIDER_ID) clearModelScopeProviderAuthToken = true;
}
if (entry.apiKey !== undefined) {
next.api_key = entry.apiKey;
next.created_at = new Date().toISOString();
+ if (entry.provider === MODELSCOPE_PROVIDER_ID) clearModelScopeProviderAuthToken = true;
}
if (entry.baseUrl === null) delete next.base_url;
else if (entry.baseUrl !== undefined) next.base_url = entry.baseUrl;
+ if (entry.provider === MODELSCOPE_PROVIDER_ID) keepModelScopeGroup = true;
nextModels.push(next);
}
+ if (hadModelScopeGroup && !keepModelScopeGroup) clearModelScopeProviderAuthToken = true;
// default_model: when provided it must be present in models; when omitted the previous value is kept (the pointer follows a key rename; if it was deleted, it's removed).
let defaultModel: ModelRefDto | undefined;
@@ -1418,20 +1499,27 @@ export class ProjectConfigService implements ProjectConfigStore {
else delete next.default_model;
if (visionModel !== undefined) next.vision_model = toRaw(visionModel);
else delete next.vision_model;
- await this.writeRaw(projectId, next);
- if (this.promotions !== undefined) {
- const stored = new Map(
- this.promotions.list(projectId).map((p) => [refKey(p.provider, p.modelId), p.discount]),
- );
- const rows: ModelPromotion[] = [];
- for (const { provider, modelId, declared, keep } of promotionPlan) {
- const discount = keep ? stored.get(refKey(provider, modelId)) : declared;
- if (discount !== undefined && discount !== null) rows.push({ provider, modelId, discount });
+ const commit = async (): Promise<ModelsResponse> => {
+ await this.writeRaw(projectId, next);
+ if (this.promotions !== undefined) {
+ const stored = new Map(
+ this.promotions.list(projectId).map((p) => [refKey(p.provider, p.modelId), p.discount]),
+ );
+ const rows: ModelPromotion[] = [];
+ for (const { provider, modelId, declared, keep } of promotionPlan) {
+ const discount = keep ? stored.get(refKey(provider, modelId)) : declared;
+ if (discount !== undefined && discount !== null)
+ rows.push({ provider, modelId, discount });
+ }
+ // Built from the new table alone, so a dropped row's promotion is gone with it.
+ this.promotions.replaceAll(projectId, rows);
}
- // Built from the new table alone, so a dropped row's promotion is gone with it.
- this.promotions.replaceAll(projectId, rows);
- }
- return this.getModels(projectId);
+ if (clearModelScopeProviderAuthToken) {
+ this.providerAuthTokens?.delete(projectId, MODELSCOPE_PROVIDER_ID);
+ }
+ return this.getModels(projectId);
+ };
+ return commit();
}
/**
@@ -1443,6 +1531,45 @@ export class ProjectConfigService implements ProjectConfigStore {
* Returns how many entries were written; an empty group writes nothing and returns 0.
*/
async setGroupApiKey(projectId: string, provider: string, apiKey: string): Promise<number> {
+ if (provider === MODELSCOPE_PROVIDER_ID) {
+ return this.withProviderCredentialLock(projectId, provider, async () => {
+ const applied = await this.setGroupApiKeyUnlocked(projectId, provider, apiKey);
+ if (applied > 0) this.providerAuthTokens?.delete(projectId, MODELSCOPE_PROVIDER_ID);
+ return applied;
+ });
+ }
+ return this.setGroupApiKeyUnlocked(projectId, provider, apiKey);
+ }
+
+ async setGroupApiKeyWithProviderAuthToken(
+ projectId: string,
+ provider: string,
+ apiKey: string,
+ token: Omit<ModelProviderAuthToken, "provider" | "updatedAt">,
+ options: { expectedRefreshToken?: string } = {},
+ ): Promise<number> {
+ return this.withProviderCredentialLock(projectId, provider, async () => {
+ if (options.expectedRefreshToken !== undefined) {
+ const current = this.providerAuthTokens?.get(projectId, provider);
+ if (current?.refreshToken !== options.expectedRefreshToken) return 0;
+ }
+ const applied = await this.setGroupApiKeyUnlocked(projectId, provider, apiKey);
+ if (applied > 0) {
+ this.providerAuthTokens?.upsert(projectId, {
+ provider,
+ refreshToken: token.refreshToken,
+ accessTokenExpiresAt: token.accessTokenExpiresAt,
+ });
+ }
+ return applied;
+ });
+ }
+
+ private async setGroupApiKeyUnlocked(
+ projectId: string,
+ provider: string,
+ apiKey: string,
+ ): Promise<number> {
const raw = await this.readRaw(projectId);
const createdAt = new Date().toISOString();
let applied = 0;
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 7508e028..8b8ed630 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -15,7 +15,12 @@
*/
import fs from "node:fs/promises";
import { agentsDir, createAgent, isSessionMeta } from "@prismshadow/penguin-core";
-import type { ControlEnvContext, ProxyEnvPolicy, SpawnConfiner } from "@prismshadow/penguin-core";
+import type {
+ AgentAssembly,
+ ControlEnvContext,
+ ProxyEnvPolicy,
+ SpawnConfiner,
+} from "@prismshadow/penguin-core";
import type {
ApprovalMode,
MessagingChannel,
@@ -98,6 +103,8 @@ export interface SessionServiceDeps {
orgIdsOfProject?: (projectId: string) => ReadonlyMap<string, string>;
/** Spawn-confinement getter (the sandbox module's), forwarded into core beside proxyEnv. */
confineSpawn?: () => SpawnConfiner | null;
+ /** Host-owned model-request hooks, forwarded to core for every Session LLM. */
+ assembly?: AgentAssembly;
}
export class SessionService {
@@ -426,6 +433,7 @@ export class SessionService {
...(this.deps.controlEnv ? { controlEnv: this.deps.controlEnv } : {}),
...(this.deps.pathPrepend ? { pathPrepend: this.deps.pathPrepend } : {}),
...(this.deps.confineSpawn ? { confineSpawn: this.deps.confineSpawn } : {}),
+ ...(this.deps.assembly ? { assembly: this.deps.assembly } : {}),
});
let session;
try {
diff --git a/packages/server/test/config.test.ts b/packages/server/test/config.test.ts
index df7e531f..ebe46704 100644
--- a/packages/server/test/config.test.ts
+++ b/packages/server/test/config.test.ts
@@ -112,3 +112,31 @@ describe("resolveServerConfig: PENGUIN_GO_ORIGIN parsing", () => {
}
});
});
+
+describe("resolveServerConfig: MODELSCOPE_BRIDGE_URL parsing", () => {
+ it("defaults to the production bridge URL", () => {
+ expect(resolveServerConfig({ ...base }).modelscopeBridgeUrl).toBe(
+ "https://go.penguin.ooo/modelscope",
+ );
+ });
+
+ it("allows a path prefix but rejects plaintext HTTP, credentials, query and fragment", () => {
+ expect(
+ resolveServerConfig({
+ ...base,
+ MODELSCOPE_BRIDGE_URL: " https://go.penguin.ooo/modelscope/ ",
+ }).modelscopeBridgeUrl,
+ ).toBe("https://go.penguin.ooo/modelscope");
+
+ for (const bad of [
+ "http://go.penguin.ooo/modelscope",
+ "https://user:[email protected]/modelscope",
+ "https://go.penguin.ooo/modelscope?next=x",
+ "https://go.penguin.ooo/modelscope#token",
+ ]) {
+ expect(() => resolveServerConfig({ ...base, MODELSCOPE_BRIDGE_URL: bad }), bad).toThrow(
+ /Invalid MODELSCOPE_BRIDGE_URL/,
+ );
+ }
+ });
+});
diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.ts
index 5e54cd60..06cb83ef 100644
--- a/packages/server/test/db-migrations.test.ts
+++ b/packages/server/test/db-migrations.test.ts
@@ -69,6 +69,7 @@ function dropCompanyModeTables(db: DatabaseSync): void {
function open024(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
db.exec("DROP TABLE IF EXISTS model_promotions");
dropCompanyModeTables(db);
db.exec("DROP TABLE messaging_bindings");
@@ -110,6 +111,7 @@ const PRE_CHANNEL_CHAT_DDL = `
function open6(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
db.exec("DROP TABLE IF EXISTS model_promotions");
db.exec(PRE_CHANNEL_CHAT_DDL);
// SCHEMA_SQL declares the CURRENT shape; migration 8's queue came after 6.
@@ -123,6 +125,7 @@ function open7(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
db.exec("DROP TABLE IF EXISTS org_desk_notices");
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
db.exec("DROP TABLE IF EXISTS model_promotions");
db.exec("PRAGMA user_version = 7");
return db;
@@ -132,15 +135,26 @@ function open7(): DatabaseSync {
function open8(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
db.exec("DROP TABLE IF EXISTS model_promotions");
db.exec("PRAGMA user_version = 8");
return db;
}
+/** A database stamped at migration 9: promotions exist, but provider auth refresh tokens do not. */
+function open9(): DatabaseSync {
+ const db = new sqlite.DatabaseSync(":memory:");
+ db.exec(SCHEMA_SQL);
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
+ db.exec("PRAGMA user_version = 9");
+ return db;
+}
+
/** A 0.2.9 database: everything 0.2.4 had plus what versions 1 and 2 added, and still goal_state. */
function open029(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
db.exec("DROP TABLE IF EXISTS model_promotions");
dropCompanyModeTables(db);
db.exec(GOAL_STATE_DDL);
@@ -161,6 +175,7 @@ function open029(): DatabaseSync {
function openPreProfile(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
db.exec("DROP TABLE IF EXISTS model_promotions");
dropProfileColumns(db);
// Version 4 predates company mode as well: its three migrations (6–8) come after the
@@ -543,18 +558,26 @@ describe("migration 7 → current: company-mode-desk-notices", () => {
describe("migration 8 → current: model-promotions", () => {
it("creates the promotions table, and its down drops it again", () => {
const db = open8();
- const tableExists = () =>
+ const promotionsTableExists = () =>
db
.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'model_promotions'")
.get();
+ const authTokensTableExists = () =>
+ db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'model_provider_auth_tokens'",
+ )
+ .get();
try {
- expect(migrate(db).applied).toEqual(["model-promotions"]);
- expect(schemaVersion(db)).toBe(9);
- expect(tableExists()).toEqual({ "1": 1 });
+ expect(migrate(db).applied).toEqual(["model-promotions", "model-provider-auth-tokens"]);
+ expect(schemaVersion(db)).toBe(10);
+ expect(promotionsTableExists()).toEqual({ "1": 1 });
+ expect(authTokensTableExists()).toEqual({ "1": 1 });
rollbackTo(db, 8);
expect(schemaVersion(db)).toBe(8);
- expect(tableExists()).toBeUndefined();
+ expect(promotionsTableExists()).toBeUndefined();
+ expect(authTokensTableExists()).toBeUndefined();
} finally {
db.close();
}
@@ -563,8 +586,49 @@ describe("migration 8 → current: model-promotions", () => {
it("is safe to create while a pushed platform boots", () => {
const db = open8();
try {
- expect(migrate(db, { swapPath: true }).applied).toEqual(["model-promotions"]);
+ expect(migrate(db, { swapPath: true }).applied).toEqual([
+ "model-promotions",
+ "model-provider-auth-tokens",
+ ]);
+ expect(schemaVersion(db)).toBe(10);
+ } finally {
+ db.close();
+ }
+ });
+});
+
+describe("migration 9 → current: model-provider-auth-tokens", () => {
+ it("creates the server-side refresh-token table, writable and rollback-safe", () => {
+ const db = open9();
+ const tableExists = () =>
+ db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'model_provider_auth_tokens'",
+ )
+ .get();
+ try {
+ expect(migrate(db).applied).toEqual(["model-provider-auth-tokens"]);
+ expect(schemaVersion(db)).toBe(10);
+ expect(tableExists()).toEqual({ "1": 1 });
+ db.exec(
+ "INSERT INTO users (user_id, password_hash, is_admin, created_at)" +
+ " VALUES ('owner', 'hash', 1, '2026-09-20T00:00:00.000Z')",
+ );
+ db.exec(
+ "INSERT INTO projects (project_id, owner_user_id, created_at)" +
+ " VALUES ('p1', 'owner', '2026-09-20T00:00:00.000Z')",
+ );
+ db.exec(
+ "INSERT INTO model_provider_auth_tokens (project_id, provider, refresh_token, access_token_expires_at, updated_at)" +
+ " VALUES ('p1', 'modelscope', 'refresh', '2026-09-20T00:00:00.000Z', '2026-09-20T00:00:00.000Z')",
+ );
+ expect(db.prepare("SELECT refresh_token FROM model_provider_auth_tokens").all()).toEqual([
+ { refresh_token: "refresh" },
+ ]);
+
+ rollbackTo(db, 9);
expect(schemaVersion(db)).toBe(9);
+ expect(tableExists()).toBeUndefined();
} finally {
db.close();
}
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index 8b74a03c..496ff25a 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -108,6 +108,9 @@ export function testConfig(root: string): ServerConfig {
dbPath: ":memory:",
previewOrigin: null,
penguinGoOrigin: "https://token.penguin.ooo",
+ // The production bridge address, path prefix included. Nothing reaches it in tests: the
+ // ModelScope cases construct the service themselves with a stubbed fetch.
+ modelscopeBridgeUrl: "https://go.penguin.ooo/modelscope",
// Points to a nonexistent directory: static hosting is disabled in tests.
webDist: path.join(root, "__no_web_dist__"),
// Fixed seed password so loginAdmin needs no seed-time capture.
diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.ts
index 606728e0..b19b0d1d 100644
--- a/packages/server/test/models.test.ts
+++ b/packages/server/test/models.test.ts
@@ -618,6 +618,63 @@ describe("model-reference rekeying and the connectivity test", () => {
expect(moved.envKey).toBe("DEEPSEEK_API_KEY");
});
+ it("serializes a ModelScope settings save with a group credential write", async () => {
+ const svc = wire(ProjectConfigService, { paths: { root: t.root } });
+ const raceProject = "modelscope-save-refresh-race";
+ await svc.writeRaw(raceProject, {
+ models: [
+ {
+ provider: "modelscope",
+ model_id: "Qwen/Qwen3.8-27B",
+ api_key: "old-access",
+ client_type: "openai-chat-vllm-adapter",
+ },
+ ],
+ });
+
+ const readRaw = svc.readRaw.bind(svc);
+ let releaseRead!: () => void;
+ const readGate = new Promise<void>((resolve) => (releaseRead = resolve));
+ let announceRead!: () => void;
+ const readStarted = new Promise<void>((resolve) => (announceRead = resolve));
+ let firstRead = true;
+ svc.readRaw = async (id: string) => {
+ const raw = await readRaw(id);
+ if (firstRead) {
+ firstRead = false;
+ announceRead();
+ await readGate;
+ }
+ return raw;
+ };
+
+ const save = svc.updateModels(raceProject, {
+ models: [
+ {
+ provider: "modelscope",
+ modelId: "Qwen/Qwen3.8-27B",
+ clientType: "openai-chat-vllm-adapter",
+ },
+ ],
+ });
+ await readStarted;
+ let credentialWriteSettled = false;
+ const credentialWrite = svc
+ .setGroupApiKey(raceProject, "modelscope", "new-access")
+ .finally(() => {
+ credentialWriteSettled = true;
+ });
+ await Promise.resolve();
+ expect(credentialWriteSettled).toBe(false);
+
+ releaseRead();
+ await Promise.all([save, credentialWrite]);
+ const stored = await readRaw(raceProject);
+ expect((stored.models as Array<Record<string, unknown>>)[0]?.api_key).toBe("new-access");
+ expect(JSON.stringify(stored)).not.toContain("refreshToken");
+ expect(JSON.stringify(stored)).not.toContain("accessTokenExpiresAt");
+ });
+
it("the display name is editable: not persisted when it matches the built-in catalog; provider is always persisted as an entry field", async () => {
// Preset model: saved as-is → the display name falls back to the built-in catalog, and display_name isn't written to the config file.
await api.put(url(), {
diff --git a/packages/server/test/modelscope-auth.test.ts b/packages/server/test/modelscope-auth.test.ts
new file mode 100644
index 00000000..7e571c4d
--- /dev/null
+++ b/packages/server/test/modelscope-auth.test.ts
@@ -0,0 +1,653 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type {
+ ModelScopeAuthFlowStatusResponse,
+ ModelScopeAuthStartResponse,
+ ModelsResponse,
+ ProjectCreateResponse,
+} from "../src/api/types.js";
+import {
+ ModelScopeAuthService,
+ modelscopeAccessToken,
+} from "../src/services/modelscope-auth-service.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** The production bridge address, path prefix included: the prefix must survive into every call. */
+const BRIDGE = "https://go.penguin.ooo/modelscope";
+
+function json(status: number, body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+function started(expiresInMs = 60_000): Response {
+ return json(201, {
+ authorizeUrl: `${BRIDGE}/oauth/authorize?code=abc`,
+ expiresAt: new Date(Date.now() + expiresInMs).toISOString(),
+ });
+}
+
+function pathOf(input: string | URL | Request): string {
+ return new URL(typeof input === "string" || input instanceof URL ? input : input.url).pathname;
+}
+
+/** What the bridge answers once the user has finished ModelScope's own consent screen. */
+const delivery = {
+ status: "completed",
+ token: {
+ accessToken: "ms-token-0001",
+ refreshToken: "ms-refresh-0001",
+ tokenType: "Bearer",
+ scope: "openid profile api-inference",
+ expiresAt: new Date(Date.now() + 3_600_000).toISOString(),
+ },
+ userinfo: { sub: "42", name: "ModelScope User" },
+ api: {
+ baseUrl: "https://api-inference.modelscope.cn/v1",
+ defaultModel: "Qwen/Qwen3.8-Flash-Next",
+ clientType: "openai-chat",
+ },
+};
+
+const owner = { projectId: "p1", userId: "u1" };
+
+describe("ModelScope key authorization service", () => {
+ it("carries the bridge's own authorize URL through and writes the delivered token", async () => {
+ const applied: { projectId: string; token: string }[] = [];
+ let polls = 0;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async (projectId, credential) => {
+ applied.push({ projectId, token: credential.accessToken });
+ return 1;
+ },
+ fetchImpl: async (input, init) => {
+ if (pathOf(input) === "/modelscope/oauth/start") {
+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
+ expect(body.client).toEqual({ id: "penguin-harness" });
+ // The bridge rejects anything that is not base64url decoding to 16+ bytes.
+ expect(String(body.code)).toMatch(/^[A-Za-z0-9_-]{43}$/);
+ expect(String(body.deviceSecret)).toMatch(/^[A-Za-z0-9_-]{43}$/);
+ return started();
+ }
+ expect(init?.redirect).toBe("manual");
+ polls += 1;
+ return polls === 1 ? json(200, { status: "pending" }) : json(200, delivery);
+ },
+ });
+
+ const flow = await service.start(owner);
+ // The bridge builds this URL itself — it knows the redirect URI and its own public prefix —
+ // so the harness passes it through untouched.
+ expect(flow.authorizeUrl).toBe(`${BRIDGE}/oauth/authorize?code=abc`);
+ expect(JSON.stringify(flow)).not.toContain("deviceSecret");
+
+ expect(await service.status({ ...owner, flowId: flow.flowId })).toEqual({ status: "pending" });
+ expect(await service.status({ ...owner, flowId: flow.flowId })).toEqual({
+ status: "completed",
+ applied: 1,
+ changed: true,
+ });
+ expect(applied).toEqual([{ projectId: "p1", token: "ms-token-0001" }]);
+ expect(polls).toBe(2);
+ });
+
+ it("keeps the token on the flow after a failed write and retries it without polling again", async () => {
+ let applies = 0;
+ let polls = 0;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => {
+ applies += 1;
+ if (applies === 1) throw new Error("disk busy");
+ return 1;
+ },
+ fetchImpl: async (input) => {
+ if (pathOf(input).endsWith("/start")) return started();
+ polls += 1;
+ return json(200, delivery);
+ },
+ });
+ const flow = await service.start(owner);
+ expect(await service.status({ ...owner, flowId: flow.flowId })).toMatchObject({
+ status: "apply_failed",
+ error: "apply_failed",
+ });
+ // The bridge clears its own copy on delivery, so this retry is the only way the token can
+ // still reach the group.
+ expect(await service.retryApply({ ...owner, flowId: flow.flowId })).toMatchObject({
+ status: "completed",
+ applied: 1,
+ changed: true,
+ });
+ expect(polls).toBe(1);
+ expect(applies).toBe(2);
+ });
+
+ it("treats a group that swallowed the token as a failed write, not as success", async () => {
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => 0,
+ fetchImpl: async (input) =>
+ pathOf(input).endsWith("/start") ? started() : json(200, delivery),
+ });
+ const flow = await service.start(owner);
+ expect(await service.status({ ...owner, flowId: flow.flowId })).toMatchObject({
+ status: "apply_failed",
+ });
+ // Still retryable: an empty group is an operator problem, not a reason to re-authorize.
+ expect(await service.retryApply({ ...owner, flowId: flow.flowId })).toMatchObject({
+ status: "apply_failed",
+ });
+ });
+
+ it("maps every terminal status the bridge can report onto the flow's own states", async () => {
+ // `delivered` is the one that matters most: it means somebody else already collected this
+ // token, so the flow must end rather than keep polling for a token that is gone.
+ const cases: Array<[string, ModelScopeAuthFlowStatusResponse]> = [
+ ["expired", { status: "error", error: "expired" }],
+ ["locked", { status: "error", error: "locked" }],
+ ["delivered", { status: "error", error: "already_delivered" }],
+ ["cancelled", { status: "cancelled" }],
+ // A status this build has never heard of is an upstream change, not a reason to keep a
+ // flow alive.
+ ["something-else", { status: "error", error: "upstream_failed" }],
+ ];
+ for (const [reported, expected] of cases) {
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => 1,
+ fetchImpl: async (input) =>
+ pathOf(input).endsWith("/start") ? started() : json(200, { status: reported }),
+ });
+ const flow = await service.start(owner);
+ const result = await service.status({ ...owner, flowId: flow.flowId });
+ expect(result, reported).toEqual(expected);
+ // Nothing was applied, and a cancelled flow is what a second poll sees.
+ expect(await service.status({ ...owner, flowId: flow.flowId }), reported).toEqual(expected);
+ }
+ });
+
+ it("stops polling once the bridge reports a terminal status", async () => {
+ let polls = 0;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => 1,
+ fetchImpl: async (input) => {
+ if (pathOf(input).endsWith("/start")) return started();
+ polls += 1;
+ return json(200, { status: "expired" });
+ },
+ });
+ const flow = await service.start(owner);
+ await service.status({ ...owner, flowId: flow.flowId });
+ await service.status({ ...owner, flowId: flow.flowId });
+ expect(polls).toBe(1);
+ });
+
+ it("reports an unreachable bridge and a rejected start as upstream failures", async () => {
+ const unreachable = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => 1,
+ fetchImpl: async () => {
+ throw new Error("ECONNREFUSED");
+ },
+ });
+ await expect(unreachable.start(owner)).rejects.toMatchObject({
+ status: 502,
+ code: "modelscope_unreachable",
+ });
+
+ const refused = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => 1,
+ fetchImpl: async () => json(409, { error: "flow_conflict" }),
+ });
+ await expect(refused.start(owner)).rejects.toMatchObject({
+ status: 502,
+ code: "modelscope_start_failed",
+ });
+ });
+
+ it("refuses an authorize URL that is not an address a browser tab may be sent to", async () => {
+ for (const authorizeUrl of ["javascript:alert(1)", "https://user:[email protected]/x", ""]) {
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => 1,
+ fetchImpl: async () =>
+ json(201, {
+ authorizeUrl,
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ }),
+ });
+ await expect(service.start(owner)).rejects.toMatchObject({
+ status: 502,
+ code: "modelscope_start_failed",
+ });
+ }
+ });
+
+ it("surfaces the bridge's rate limit on start with its own Retry-After", async () => {
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => 1,
+ fetchImpl: async () => json(429, { error: "rate_limited", retryAfterSeconds: 12 }),
+ });
+ await expect(service.start(owner)).rejects.toMatchObject({
+ status: 429,
+ code: "modelscope_rate_limited",
+ retryAfterSeconds: 12,
+ });
+ });
+
+ it("keeps a rate-limited poll pending and retries it after the bridge's backoff", async () => {
+ let now = 1_000;
+ let polls = 0;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ now: () => now,
+ applyCredential: async () => 1,
+ fetchImpl: async (input) => {
+ if (pathOf(input).endsWith("/start")) {
+ return json(201, {
+ authorizeUrl: `${BRIDGE}/oauth/authorize?code=abc`,
+ expiresAt: new Date(now + 60_000).toISOString(),
+ });
+ }
+ polls += 1;
+ return polls === 1
+ ? json(429, { error: "rate_limited", retryAfterSeconds: 2 })
+ : json(200, delivery);
+ },
+ });
+ const flow = await service.start(owner);
+ expect(await service.status({ ...owner, flowId: flow.flowId })).toEqual({ status: "pending" });
+ now += 1_999;
+ expect(await service.status({ ...owner, flowId: flow.flowId })).toEqual({ status: "pending" });
+ expect(polls).toBe(1);
+ now += 1;
+ expect(await service.status({ ...owner, flowId: flow.flowId })).toMatchObject({
+ status: "completed",
+ applied: 1,
+ });
+ expect(polls).toBe(2);
+ });
+
+ it("silently refreshes a stored token that is about to expire", async () => {
+ let now = 1_000;
+ const applied: string[] = [];
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ now: () => now,
+ readStoredCredential: () => ({
+ provider: "modelscope",
+ refreshToken: "old-refresh",
+ accessTokenExpiresAt: new Date(now + 10_000).toISOString(),
+ updatedAt: new Date(now - 1_000).toISOString(),
+ }),
+ applyCredential: async (_projectId, credential) => {
+ applied.push(credential.accessToken);
+ expect(credential.refreshToken).toBe("new-refresh");
+ return 3;
+ },
+ fetchImpl: async (input, init) => {
+ expect(pathOf(input)).toBe("/modelscope/oauth/refresh");
+ expect(JSON.parse(String(init?.body))).toEqual({ refreshToken: "old-refresh" });
+ return json(200, {
+ token: {
+ accessToken: "new-access",
+ refreshToken: "new-refresh",
+ expiresAt: new Date(now + 3_600_000).toISOString(),
+ },
+ });
+ },
+ });
+ await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual(
+ { changed: true },
+ );
+ expect(applied).toEqual(["new-access"]);
+ });
+
+ it("drops a refreshed token when the stored refresh token changed before apply", async () => {
+ let now = 1_000;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ now: () => now,
+ readStoredCredential: () => ({
+ provider: "modelscope",
+ refreshToken: "old-refresh",
+ accessTokenExpiresAt: new Date(now + 10_000).toISOString(),
+ updatedAt: new Date(now - 1_000).toISOString(),
+ }),
+ applyCredential: async (_projectId, credential, options) => {
+ expect(credential.accessToken).toBe("new-access");
+ expect(options).toEqual({ expectedRefreshToken: "old-refresh" });
+ return 0;
+ },
+ fetchImpl: async () =>
+ json(200, {
+ token: {
+ accessToken: "new-access",
+ refreshToken: "new-refresh",
+ expiresAt: new Date(now + 3_600_000).toISOString(),
+ },
+ }),
+ });
+ await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual(
+ { changed: false },
+ );
+ });
+
+ it("keeps a nearly expired token usable when a proactive refresh fails", async () => {
+ let now = 1_000;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ now: () => now,
+ readStoredCredential: () => ({
+ provider: "modelscope",
+ refreshToken: "old-refresh",
+ accessTokenExpiresAt: new Date(now + 10_000).toISOString(),
+ updatedAt: new Date(now - 1_000).toISOString(),
+ }),
+ applyCredential: async () => {
+ throw new Error("must not apply");
+ },
+ fetchImpl: async () => json(502, { error: "bridge_down" }),
+ });
+ await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual(
+ { changed: false },
+ );
+ });
+
+ it("asks for re-authorization when an expired token cannot be refreshed", async () => {
+ let now = 1_000;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ now: () => now,
+ readStoredCredential: () => ({
+ provider: "modelscope",
+ refreshToken: "old-refresh",
+ accessTokenExpiresAt: new Date(now - 1).toISOString(),
+ updatedAt: new Date(now - 1_000).toISOString(),
+ }),
+ applyCredential: async () => 1,
+ fetchImpl: async () => json(401, { error: "invalid_grant" }),
+ });
+ await expect(
+ service.ensureFresh({ projectId: "p1", provider: "modelscope" }),
+ ).rejects.toMatchObject({ status: 409, code: "modelscope_refresh_failed" });
+ });
+
+ it("prompts for re-authorization after three proactive refresh failures", async () => {
+ let now = 1_000;
+ let attempts = 0;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ now: () => now,
+ readStoredCredential: () => ({
+ provider: "modelscope",
+ refreshToken: "old-refresh",
+ accessTokenExpiresAt: new Date(241_000).toISOString(),
+ updatedAt: new Date(0).toISOString(),
+ }),
+ applyCredential: async () => 1,
+ fetchImpl: async () => {
+ attempts += 1;
+ return json(502, { error: "bridge_down" });
+ },
+ });
+
+ await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual(
+ { changed: false },
+ );
+ now += 30_000;
+ await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual(
+ { changed: false },
+ );
+ now += 60_000;
+ await expect(
+ service.ensureFresh({ projectId: "p1", provider: "modelscope" }),
+ ).rejects.toMatchObject({ status: 409, code: "modelscope_refresh_failed" });
+ await expect(
+ service.ensureFresh({ projectId: "p1", provider: "modelscope" }),
+ ).rejects.toMatchObject({ status: 409, code: "modelscope_refresh_failed" });
+ expect(attempts).toBe(3);
+ });
+
+ it("forgets an old failure ceiling after the stored refresh token changes", async () => {
+ let now = 1_000;
+ let refreshToken = "old-refresh";
+ let attempts = 0;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ now: () => now,
+ readStoredCredential: () => ({
+ provider: "modelscope",
+ refreshToken,
+ accessTokenExpiresAt: new Date(now + 10_000).toISOString(),
+ updatedAt: new Date(now - 1_000).toISOString(),
+ }),
+ applyCredential: async () => 3,
+ fetchImpl: async () => {
+ attempts += 1;
+ if (refreshToken === "old-refresh") return json(502, { error: "bridge_down" });
+ return json(200, {
+ token: {
+ accessToken: "reauthorized-access",
+ refreshToken,
+ expiresAt: new Date(now + 3_600_000).toISOString(),
+ },
+ });
+ },
+ });
+
+ await service.ensureFresh({ projectId: "p1", provider: "modelscope" });
+ now += 30_000;
+ await service.ensureFresh({ projectId: "p1", provider: "modelscope" });
+ now += 60_000;
+ await expect(
+ service.ensureFresh({ projectId: "p1", provider: "modelscope" }),
+ ).rejects.toMatchObject({ status: 409, code: "modelscope_refresh_failed" });
+
+ refreshToken = "reauthorized-refresh";
+ await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual(
+ { changed: true },
+ );
+ expect(attempts).toBe(4);
+ });
+
+ it("cancels at the bridge as well as locally, and never applies the token", async () => {
+ let cancelled = 0;
+ let applied = 0;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ applyCredential: async () => {
+ applied += 1;
+ return 1;
+ },
+ fetchImpl: async (input) => {
+ if (pathOf(input).endsWith("/start")) return started();
+ if (pathOf(input).endsWith("/cancel")) {
+ cancelled += 1;
+ return json(200, { ok: true });
+ }
+ return json(200, delivery);
+ },
+ });
+ const flow = await service.start(owner);
+ service.cancel({ ...owner, flowId: flow.flowId });
+ // The local state is what the next status call reads; the bridge call is best effort.
+ expect(await service.status({ ...owner, flowId: flow.flowId })).toEqual({
+ status: "cancelled",
+ });
+ expect(applied).toBe(0);
+ await vi.waitFor(() => expect(cancelled).toBe(1));
+ });
+
+ it("hides a flow from another Project or user, and forgets an expired one", async () => {
+ let now = 1_000;
+ const service = new ModelScopeAuthService({
+ bridgeUrl: BRIDGE,
+ now: () => now,
+ applyCredential: async () => 1,
+ fetchImpl: async () => started(600_000),
+ });
+ const flow = await service.start(owner);
+ const gone = { status: 404, code: "modelscope_auth_flow_not_found" };
+ await expect(
+ service.status({ ...owner, flowId: flow.flowId, userId: "u2" }),
+ ).rejects.toMatchObject(gone);
+ await expect(
+ service.status({ ...owner, flowId: flow.flowId, projectId: "p2" }),
+ ).rejects.toMatchObject(gone);
+ await expect(service.status({ ...owner, flowId: "nope" })).rejects.toMatchObject(gone);
+ now += 10 * 60 * 1000 + 1;
+ await expect(service.status({ ...owner, flowId: flow.flowId })).rejects.toMatchObject(gone);
+ });
+
+ it("validates the delivery rather than trusting it", () => {
+ expect(modelscopeAccessToken(delivery)).toBe("ms-token-0001");
+ expect(() => modelscopeAccessToken({ ...delivery, status: "pending" })).toThrow(
+ "another status",
+ );
+ expect(() => modelscopeAccessToken({ status: "completed", token: {} })).toThrow(
+ "invalid access token",
+ );
+ expect(() =>
+ modelscopeAccessToken({ status: "completed", token: { accessToken: 42 } }),
+ ).toThrow("invalid access token");
+ });
+});
+
+describe("ModelScope key authorization routes", () => {
+ let t: TestApp;
+ let ownerClient: ReturnType<typeof apiClient>;
+ let memberClient: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let pollCount: number;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const ownerUser = await provisionUser(t.app, "modelscope_api_owner");
+ ownerClient = apiClient(t.app, ownerUser.cookie);
+ const memberUser = await provisionUser(t.app, "modelscope_api_member");
+ memberClient = apiClient(t.app, memberUser.cookie);
+ projectId = (
+ (await (
+ await ownerClient.post("/api/projects", {
+ projectId: "modelscope_api_owner-project",
+ name: "ModelScope Project",
+ })
+ ).json()) as ProjectCreateResponse
+ ).project.projectId;
+ expect(
+ (
+ await ownerClient.post(`/api/projects/${projectId}/members`, {
+ userId: "modelscope_api_member",
+ })
+ ).status,
+ ).toBe(201);
+
+ pollCount = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const path = pathOf(input);
+ // Every call carries the bridge's path prefix; a lost prefix is a 404 at the bridge.
+ if (path === "/modelscope/oauth/start") {
+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
+ expect(body.client).toEqual({ id: "penguin-harness" });
+ return started();
+ }
+ if (path === "/modelscope/oauth/poll") {
+ pollCount += 1;
+ return pollCount === 1 ? json(200, { status: "pending" }) : json(200, delivery);
+ }
+ throw new Error(`Unexpected bridge request: ${path}`);
+ }),
+ );
+ });
+
+ afterEach(async () => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ await t.cleanup();
+ });
+
+ it("writes the delivered token to the group's preset row and exposes no account state", async () => {
+ const base = `/api/projects/${projectId}/modelscope-auth`;
+ const before = (await (
+ await ownerClient.get(`/api/projects/${projectId}/models`)
+ ).json()) as ModelsResponse;
+ const preset = before.models.filter((model) => model.provider === "modelscope");
+ expect(preset.map((model) => model.modelId)).toEqual([
+ "deepseek-ai/DeepSeek-V4.1-Flash",
+ "Qwen/Qwen3.8-27B",
+ "Qwen/Qwen3.8-Flash-Next",
+ ]);
+ expect(preset.every((model) => model.credential?.apiKeyMasked === undefined)).toBe(true);
+
+ expect((await memberClient.post(`${base}/start`, {})).status).toBe(403);
+
+ const startResponse = await ownerClient.post(`${base}/start`, {});
+ expect(startResponse.status).toBe(201);
+ const flow = (await startResponse.json()) as ModelScopeAuthStartResponse;
+ expect(flow.authorizeUrl).toBe(`${BRIDGE}/oauth/authorize?code=abc`);
+ expect(JSON.stringify(flow)).not.toContain("deviceSecret");
+
+ const pending = (await (
+ await ownerClient.get(`${base}/${flow.flowId}/status`)
+ ).json()) as ModelScopeAuthFlowStatusResponse;
+ expect(pending).toEqual({ status: "pending" });
+
+ const done = (await (
+ await ownerClient.get(`${base}/${flow.flowId}/status`)
+ ).json()) as ModelScopeAuthFlowStatusResponse;
+ expect(done).toEqual({ status: "completed", applied: 3 });
+ expect(JSON.stringify(done)).not.toContain("ms-token");
+
+ const after = (await (
+ await ownerClient.get(`/api/projects/${projectId}/models`)
+ ).json()) as ModelsResponse;
+ const authorized = after.models.filter((model) => model.provider === "modelscope");
+ expect(authorized).toHaveLength(3);
+ // The token is reported masked, never in the clear.
+ expect(authorized.every((model) => model.credential?.apiKeyMasked)).toBe(true);
+
+ const stored = (await t.deps.projectConfigService.readRaw(projectId)).models as Record<
+ string,
+ unknown
+ >[];
+ expect(
+ stored.filter((model) => model.provider === "modelscope").map((model) => model.api_key),
+ ).toEqual(["ms-token-0001", "ms-token-0001", "ms-token-0001"]);
+ const tokenRow = t.deps.db
+ .prepare(
+ `SELECT refresh_token, access_token_expires_at
+ FROM model_provider_auth_tokens
+ WHERE project_id = ? AND provider = ?`,
+ )
+ .get(projectId, "modelscope") as
+ { refresh_token: string; access_token_expires_at: string } | undefined;
+ expect(tokenRow).toMatchObject({ refresh_token: "ms-refresh-0001" });
+ expect(Date.parse(tokenRow?.access_token_expires_at ?? "")).toBeGreaterThan(Date.now());
+ });
+
+ it("answers an unknown or foreign flow with its own not-found code", async () => {
+ const base = `/api/projects/${projectId}/modelscope-auth`;
+ const missing = await ownerClient.get(`${base}/not-a-flow/status`);
+ expect(missing.status).toBe(404);
+ expect(await missing.json()).toMatchObject({
+ error: { code: "modelscope_auth_flow_not_found" },
+ });
+ // A path-invalid id never reaches the service but reports the same way, so the dialog has
+ // one condition to branch on.
+ const invalid = await ownerClient.get(`${base}/has%2Fslash/status`);
+ expect(invalid.status).toBe(404);
+ expect(await invalid.json()).toMatchObject({
+ error: { code: "modelscope_auth_flow_not_found" },
+ });
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index cfd387d4..732a5f9d 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -409,30 +409,55 @@ export const submitModelOAuthCode = (projectId: string, flowId: string, code: st
{ method: "POST", body: { code } },
);
-// Penguin Go key authorization (owner) -------------------------------------------
-
-export const startPlatformAuth = (projectId: string) =>
- apiFetch<PlatformAuthStartResponse>(
- `/api/projects/${encodeURIComponent(projectId)}/platform-auth/start`,
- { method: "POST", body: {} },
- );
-
-export const getPlatformAuthFlow = (projectId: string, flowId: string) =>
- apiFetch<PlatformAuthFlowStatusResponse>(
- `/api/projects/${encodeURIComponent(projectId)}/platform-auth/${encodeURIComponent(flowId)}/status`,
- );
-
-export const retryPlatformAuthApply = (projectId: string, flowId: string) =>
- apiFetch<PlatformAuthFlowStatusResponse>(
- `/api/projects/${encodeURIComponent(projectId)}/platform-auth/${encodeURIComponent(flowId)}/retry`,
- { method: "POST", body: {} },
- );
-
-export const cancelPlatformAuth = (projectId: string, flowId: string) =>
- apiFetch<{ ok: boolean }>(
- `/api/projects/${encodeURIComponent(projectId)}/platform-auth/${encodeURIComponent(flowId)}/cancel`,
- { method: "POST", body: {} },
- );
+// Bridge-authorized groups (owner) -----------------------------------------------
+//
+// Penguin Go and ModelScope both hand a group an API key by creating a server-side flow,
+// polling it, and reporting the same six states and seven failure codes; only the route and
+// the name of the "this flow is gone" code differ. Each group therefore gets one descriptor
+// here rather than four loose exports, and the dialog they share takes one as a prop — a
+// third such group is an entry in this section, not a third copy of the dialog.
+
+export interface KeyAuthEndpoints {
+ /**
+ * The code the server answers with once a flow no longer exists (expired or unknown). The
+ * dialog drops its handle on it and offers a fresh start instead of a retry.
+ */
+ flowNotFoundCode: string;
+ start: (projectId: string) => Promise<PlatformAuthStartResponse>;
+ status: (projectId: string, flowId: string) => Promise<PlatformAuthFlowStatusResponse>;
+ retryApply: (projectId: string, flowId: string) => Promise<PlatformAuthFlowStatusResponse>;
+ cancel: (projectId: string, flowId: string) => Promise<{ ok: boolean }>;
+}
+
+function keyAuth(route: string, flowNotFoundCode: string): KeyAuthEndpoints {
+ const prefix = (projectId: string): string =>
+ `/api/projects/${encodeURIComponent(projectId)}/${route}`;
+ const flow = (projectId: string, flowId: string): string =>
+ `${prefix(projectId)}/${encodeURIComponent(flowId)}`;
+ return {
+ flowNotFoundCode,
+ start: (projectId) =>
+ apiFetch<PlatformAuthStartResponse>(`${prefix(projectId)}/start`, {
+ method: "POST",
+ body: {},
+ }),
+ status: (projectId, flowId) =>
+ apiFetch<PlatformAuthFlowStatusResponse>(`${flow(projectId, flowId)}/status`),
+ retryApply: (projectId, flowId) =>
+ apiFetch<PlatformAuthFlowStatusResponse>(`${flow(projectId, flowId)}/retry`, {
+ method: "POST",
+ body: {},
+ }),
+ cancel: (projectId, flowId) =>
+ apiFetch<{ ok: boolean }>(`${flow(projectId, flowId)}/cancel`, { method: "POST", body: {} }),
+ };
+}
+
+/** Penguin Go's relay authorization. */
+export const platformAuthEndpoints = keyAuth("platform-auth", "platform_auth_flow_not_found");
+
+/** ModelScope's, run through the harness's own authorization bridge. */
+export const modelScopeAuthEndpoints = keyAuth("modelscope-auth", "modelscope_auth_flow_not_found");
export const syncPlatformModels = (projectId: string) =>
apiFetch<PlatformModelSyncResponse>(
diff --git a/packages/web/src/components/ui/provider-logo.tsx b/packages/web/src/components/ui/provider-logo.tsx
index 66b433e7..9fa0d548 100644
--- a/packages/web/src/components/ui/provider-logo.tsx
+++ b/packages/web/src/components/ui/provider-logo.tsx
@@ -6,8 +6,9 @@
* 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); vLLM uses its official mark from the
+ * Z.AI uses a simplified geometric approximation of its branded glyph (not an exact reproduction
+ * of the trademark); ModelScope uses its official pixel mark flattened to currentColor; vLLM uses
+ * its official mark from the
* project's media kit, its two brand colours flattened to currentColor like
* Qwen's gradient; custom models use a generic cube. All are pure paths, no
* external image assets.
@@ -137,6 +138,14 @@ const GLYPHS: Record<string, Glyph> = {
},
"qwen-token-plan": QWEN_GLYPH,
"qwen-pay-as-you-go": QWEN_GLYPH,
+ modelscope: {
+ // ModelScope's official favicon/social mark, with the purple tile dropped and the white
+ // pixel glyph flattened to currentColor so it matches the provider-logo family.
+ viewBox: "0 0 16 16",
+ path: (
+ <path d="M2 4h4v1H2zM10 4h4v1h-4zM1 5h5v1H1zM10 5h5v1h-5zM2 6h2v1H2zM12 6h3v1h-3zM1 7h2v1H1zM5 7h2v1H5zM9 7h2v1H9zM13 7h2v1h-2zM1 8h3v1H1zM5 8h6v1H5zM12 8h3v1h-3zM2 9h2v1H2zM7 9h2v1H7zM12 9h2v1h-2zM2 10h4v1H2zM7 10h2v1H7zM10 10h4v1h-4zM2 11h4v1H2zM10 11h4v1h-4z" />
+ ),
+ },
minimax: {
// The official MiniMax stream-lines mark (evenodd fill preserved from the brand SVG).
path: (
diff --git a/packages/web/src/features/models/platform-key-auth-dialog.tsx b/packages/web/src/features/models/key-auth-dialog.tsx
similarity index 77%
rename from packages/web/src/features/models/platform-key-auth-dialog.tsx
rename to packages/web/src/features/models/key-auth-dialog.tsx
index 2bee23c7..db09674c 100644
--- a/packages/web/src/features/models/platform-key-auth-dialog.tsx
+++ b/packages/web/src/features/models/key-auth-dialog.tsx
@@ -4,8 +4,8 @@ import type {
PlatformAuthFlowStatusResponse,
PlatformAuthStartResponse,
} from "@prismshadow/penguin-server/api";
+import type { KeyAuthEndpoints } from "../../api/endpoints";
import { ApiError } from "../../api/client";
-import * as api from "../../api/endpoints";
import { Button } from "../../components/ui/button";
import { Modal } from "../../components/ui/modal";
import { apiErrorText } from "../../lib/api-error";
@@ -15,25 +15,38 @@ const POLL_MS = 3_000;
type Phase = "starting" | "ready" | "waiting" | "applying" | "failed" | "done";
-function flowError(code: PlatformAuthFlowErrorCode | undefined): string {
- return code ? S.models.platformKeyErrors[code] : S.models.platformKeyErrors.upstream_failed;
+/**
+ * The localized copy a group's dialog shows. Everything else — the phases, the poll, the
+ * apply/retry path — is the same for every group that uses this component, so the vendor's
+ * name appears in these three and nowhere else.
+ */
+export interface KeyAuthTexts {
+ intro: (count: number) => string;
+ appliedBody: (applied: number) => string;
+ errors: Record<PlatformAuthFlowErrorCode, string>;
}
/**
- * Penguin Go uses a device-style start/poll exchange internally, but presents the
- * same group-level "authorize a key" interaction as TokenDance. Account metadata never
- * enters this component; the completed flow only reports how many preset rows got the key.
+ * A group whose credential the server fetches for the user, presented like any other provider's
+ * "authorize a key" action. The wire protocol behind it is a device-style start/poll rather
+ * than OAuth/PKCE, and which one applies is the `endpoints` prop's business: Penguin Go polls
+ * its own relay, ModelScope polls the harness's authorization bridge. Account metadata never
+ * enters this component; a completed flow only reports how many preset rows took the key.
*/
-export function PlatformKeyAuthDialog({
+export function KeyAuthDialog({
projectId,
providerLabel,
count,
+ endpoints,
+ texts,
onClose,
onApplied,
}: {
projectId: string;
providerLabel: string;
count: number;
+ endpoints: KeyAuthEndpoints;
+ texts: KeyAuthTexts;
onClose: () => void;
onApplied: (applied: number) => void;
}) {
@@ -47,6 +60,17 @@ export function PlatformKeyAuthDialog({
const startGenerationRef = useRef(0);
const onAppliedRef = useRef(onApplied);
onAppliedRef.current = onApplied;
+ // The poll effect below must not depend on these two: a caller building its `texts` inline
+ // would hand this component a new object every render, and the effect would restart the poll
+ // on each one.
+ const endpointsRef = useRef(endpoints);
+ endpointsRef.current = endpoints;
+ const textsRef = useRef(texts);
+ textsRef.current = texts;
+
+ const flowError = (code: PlatformAuthFlowErrorCode | undefined): string =>
+ (code !== undefined ? textsRef.current.errors[code] : undefined) ??
+ textsRef.current.errors.upstream_failed;
useEffect(
() => () => {
@@ -68,9 +92,10 @@ export function PlatformKeyAuthDialog({
if ((phase !== "waiting" && phase !== "applying") || flow === null) return;
let stopped = false;
let timer: number | undefined;
+ const { current: auth } = endpointsRef;
const tick = async (): Promise<void> => {
try {
- const next = await api.getPlatformAuthFlow(projectId, flow.flowId);
+ const next = await auth.status(projectId, flow.flowId);
if (stopped) return;
if (next.status === "pending") {
timer = window.setTimeout(() => void tick(), POLL_MS);
@@ -100,7 +125,7 @@ export function PlatformKeyAuthDialog({
if (stopped) return;
setError(apiErrorText(cause));
setRetryableApply(false);
- if (cause instanceof ApiError && cause.code === "platform_auth_flow_not_found") {
+ if (cause instanceof ApiError && cause.code === auth.flowNotFoundCode) {
setFlow(null);
}
setPhase("failed");
@@ -116,7 +141,7 @@ export function PlatformKeyAuthDialog({
const close = (): void => {
startGenerationRef.current += 1;
if (flow !== null && phase !== "done") {
- void api.cancelPlatformAuth(projectId, flow.flowId).catch(() => {});
+ void endpoints.cancel(projectId, flow.flowId).catch(() => {});
}
onClose();
};
@@ -124,7 +149,7 @@ export function PlatformKeyAuthDialog({
const beginAuthorization = async (): Promise<void> => {
if (phase === "starting" || retrySeconds > 0) return;
if (flow !== null) {
- void api.cancelPlatformAuth(projectId, flow.flowId).catch(() => {});
+ void endpoints.cancel(projectId, flow.flowId).catch(() => {});
}
completedRef.current = false;
setFlow(null);
@@ -138,10 +163,10 @@ export function PlatformKeyAuthDialog({
const authorizationTab = window.open("about:blank", "_blank");
if (authorizationTab !== null) authorizationTab.opener = null;
try {
- const started = await api.startPlatformAuth(projectId);
+ const started = await endpoints.start(projectId);
if (generation !== startGenerationRef.current) {
authorizationTab?.close();
- void api.cancelPlatformAuth(projectId, started.flowId).catch(() => {});
+ void endpoints.cancel(projectId, started.flowId).catch(() => {});
return;
}
setFlow(started);
@@ -169,7 +194,7 @@ export function PlatformKeyAuthDialog({
setError(null);
setPhase("applying");
try {
- const next: PlatformAuthFlowStatusResponse = await api.retryPlatformAuthApply(
+ const next: PlatformAuthFlowStatusResponse = await endpoints.retryApply(
projectId,
flow.flowId,
);
@@ -244,9 +269,7 @@ export function PlatformKeyAuthDialog({
>
<div className="space-y-3">
<p className="text-sm text-gray-700 dark:text-gray-300">
- {phase === "done"
- ? S.models.platformKeyAppliedBody(applied)
- : S.models.platformKeyIntro(count)}
+ {phase === "done" ? texts.appliedBody(applied) : texts.intro(count)}
</p>
{(phase === "starting" || phase === "waiting" || phase === "applying") && (
<p className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index 918a7992..01fa3fa9 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -89,7 +89,11 @@ import {
providerInfo,
resolveProviderModelEnv,
} from "@prismshadow/penguin-core/model-catalog";
-import type { FastModeProtocol, ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";
+import type {
+ FastModeProtocol,
+ ModelProviderBridgeAuth,
+ ModelProviderInfo,
+} from "@prismshadow/penguin-core/model-catalog";
import {
allGroupKeys,
discountedPrice,
@@ -137,7 +141,36 @@ import { tpsTone, ttftTone } from "./speed-test";
import type { SpeedResult, SpeedTone } from "./speed-test";
import { toneInk, toneStrip } from "../../lib/tone";
import { InfoPopover } from "../../components/ui/info-popover";
-import { PlatformKeyAuthDialog } from "./platform-key-auth-dialog";
+import { KeyAuthDialog } from "./key-auth-dialog";
+import type { KeyAuthTexts } from "./key-auth-dialog";
+
+/**
+ * The authorization flows a group's "authorize a key" dialog can run, keyed by the flow named
+ * in that group's catalog descriptor. Everything the two differ in lives here — the four
+ * endpoint calls and the copy — because everything else about the dialog is shared, and a
+ * group picks its entry by carrying `bridgeAuth` rather than by being named in this file.
+ */
+const KEY_AUTH: Record<
+ ModelProviderBridgeAuth["flow"],
+ { endpoints: api.KeyAuthEndpoints; texts: KeyAuthTexts }
+> = {
+ "penguin-go": {
+ endpoints: api.platformAuthEndpoints,
+ texts: {
+ intro: S.models.platformKeyIntro,
+ appliedBody: S.models.platformKeyAppliedBody,
+ errors: S.models.platformKeyErrors,
+ },
+ },
+ modelscope: {
+ endpoints: api.modelScopeAuthEndpoints,
+ texts: {
+ intro: S.models.modelScopeKeyIntro,
+ appliedBody: S.models.modelScopeKeyAppliedBody,
+ errors: S.models.modelScopeKeyErrors,
+ },
+ },
+};
/** Display currency follows the user setting (pricing is always stored in USD/million tokens; conversion happens only for display and input). */
const CURRENCY_SYMBOL: Record<Currency, string> = { USD: "$", CNY: "¥" };
@@ -1078,6 +1111,12 @@ export function ModelsPage() {
};
};
+ // Which dialog the open authorization runs: the group's descriptor decides, so a group with
+ // a bridge flow gets the shared bridge dialog and every other authorizable group gets the
+ // PKCE one. Null means the open group authorizes some other way (or none).
+ const oauthFlow = oauthFor === null ? undefined : providerInfo(oauthFor)?.bridgeAuth?.flow;
+ const oauthKeyAuth = oauthFlow === undefined ? null : KEY_AUTH[oauthFlow];
+
return (
<div className="h-full overflow-y-auto p-4 md:p-6">
<div className="mx-auto max-w-5xl">
@@ -1292,10 +1331,12 @@ export function ModelsPage() {
</Button>
)}
{isOwner &&
- (group.provider.oauth || group.provider.id === PENGUIN_GO_PROVIDER_ID) && (
+ (group.provider.oauth || group.provider.bridgeAuth !== undefined) && (
// 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
+ // rather than by being named here — `oauth` for the ones whose PKCE
+ // round-trip the App runs itself, `bridgeAuth` for the ones an
+ // authorization bridge runs for it. 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
@@ -1489,13 +1530,15 @@ export function ModelsPage() {
momentary absence of rows reads as zero and is never seen. */}
{projectId &&
oauthFor !== null &&
- (oauthFor === PENGUIN_GO_PROVIDER_ID ? (
- <PlatformKeyAuthDialog
+ (oauthKeyAuth !== null ? (
+ <KeyAuthDialog
projectId={projectId}
providerLabel={
MODEL_PROVIDERS.find((provider) => provider.id === oauthFor)?.label ?? oauthFor
}
count={rows?.filter((row) => row.provider === oauthFor).length ?? 0}
+ endpoints={oauthKeyAuth.endpoints}
+ texts={oauthKeyAuth.texts}
onClose={() => {
setOauthFor(null);
if (keyLanded.current) void load();
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 0aed9030..8b10b624 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1280,6 +1280,24 @@ export const en: Strings = {
apply_failed:
"The API key was received but could not be written to the model group. Retry without authorizing again.",
},
+ // ModelScope goes through the authorization bridge: the harness never talks to ModelScope
+ // itself, and the bridge holds the client secret that buys an api-inference token. The
+ // access token is written to the model table; the refresh token stays in the server DB.
+ modelScopeKeyIntro: (n: number): string =>
+ `Authorization automatically obtains a ModelScope API token and writes it to all ${n} preset models in this group, replacing their current key; later requests renew it silently on the server, and repeated renewal failures prompt you to authorize again.`,
+ modelScopeKeyAppliedBody: (n: number): string =>
+ `Authorized. The ModelScope API token is set on ${n} model${n === 1 ? "" : "s"} and ready to use.`,
+ modelScopeKeyErrors: {
+ unreachable:
+ "The authorization bridge could not be reached. Check the network and start again.",
+ upstream_failed: "The bridge could not complete authorization. Start again.",
+ invalid_key: "The bridge returned no usable API token. Start again.",
+ expired: "The authorization expired. Start again.",
+ locked: "The authorization was locked. Start again.",
+ already_delivered: "That authorization was already delivered. Start again.",
+ apply_failed:
+ "The API token was received but could not be written to the model group. Retry without authorizing again.",
+ },
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",
@@ -4253,6 +4271,8 @@ Scenarios:
agent_deleting: "This agent is being deleted.",
project_exists: "This Project id is already taken.",
project_not_found: "This Project no longer exists, or you do not have access.",
+ modelscope_refresh_failed:
+ "ModelScope authorization could not be renewed after repeated attempts. Re-authorize it on the Models page.",
cannot_delete_last_project: "This is the last Project and cannot be deleted.",
user_exists: "This username is already taken.",
user_not_found: "This user no longer exists.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 4becfcd8..7f710b16 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1284,6 +1284,21 @@ export const zh = {
already_delivered: "该授权结果已经交付,请重新开始。",
apply_failed: "API key 已取得,但未能写入模型组。可以直接重试,无需再次授权。",
},
+ // 魔搭走的是授权中转层:harness 不直接与魔搭对话,中转层拿着 client secret 换回
+ // api-inference token。access token 会写入模型表;refresh token 只保存在服务端 DB。
+ modelScopeKeyIntro: (n: number): string =>
+ `授权后会自动获取一个魔搭 API token,并写入该分组下全部 ${n} 个预置模型,覆盖它们当前的 key;后续请求会在服务端静默续期,连续续期失败时会提示你重新授权。`,
+ modelScopeKeyAppliedBody: (n: number): string =>
+ `已完成授权:魔搭 API token 已配置到 ${n} 个模型上,可以直接使用了。`,
+ modelScopeKeyErrors: {
+ unreachable: "无法连接授权中转层,请检查网络后重新开始。",
+ upstream_failed: "中转层未能完成授权,请重新开始。",
+ invalid_key: "中转层未返回可用的 API token,请重新开始。",
+ expired: "授权已过期,请重新开始。",
+ locked: "授权已锁定,请重新开始。",
+ already_delivered: "该授权结果已经交付,请重新开始。",
+ apply_failed: "API token 已取得,但未能写入模型组。可以直接重试,无需再次授权。",
+ },
// 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.
@@ -4214,6 +4229,7 @@ Benchmark:
agent_deleting: "该 Agent 正在删除中。",
project_exists: "该 Project id 已被占用。",
project_not_found: "该 Project 已不存在,或你没有访问权限。",
+ modelscope_refresh_failed: "魔搭授权连续自动续期失败,请在「模型」页重新授权。",
cannot_delete_last_project: "这是最后一个 Project,不能删除。",
user_exists: "该用户名已被占用。",
user_not_found: "该用户已不存在。",
diff --git a/packages/web/test/model-grouping.test.ts b/packages/web/test/model-grouping.test.ts
index 921f6e63..a3a04d35 100644
--- a/packages/web/test/model-grouping.test.ts
+++ b/packages/web/test/model-grouping.test.ts
@@ -107,6 +107,7 @@ describe("groupModelRows", () => {
"minimax",
"qwen-pay-as-you-go",
"qwen-token-plan",
+ "modelscope",
"vllm",
"custom",
]);
diff --git a/packages/web/test/protocol-path.test.ts b/packages/web/test/protocol-path.test.ts
index b73c51b9..bbfaa7fd 100644
--- a/packages/web/test/protocol-path.test.ts
+++ b/packages/web/test/protocol-path.test.ts
@@ -29,6 +29,13 @@ describe("protocolPathForModel", () => {
expect(protocolPathForModel("myproxy", "deepseek-v4")).toBe("/responses");
});
+ it("ModelScope aggregate presets display the path for their pinned protocol", () => {
+ expect(protocolPathForModel("modelscope", "deepseek-v4")).toBe("/responses");
+ expect(protocolPathForModel("modelscope", "openai-chat-vllm-adapter")).toBe(
+ "/chat/completions",
+ );
+ });
+
it("the remaining direct vendors speak chat completions", () => {
expect(protocolPathForModel("zhipu", "")).toBe("/chat/completions");
expect(protocolPathForModel("moonshot", "")).toBe("/chat/completions");