A local-first multi-agent app development platform, built on PenguinHarness
feat(models): add Penguin Go authorization and catalog sync (#716)
Laodouuu5b595e2545f0
diff --git a/changelog/unreleased/2026-09-16-model-promotions-in-database.md b/changelog/unreleased/2026-09-16-model-promotions-in-database.mdnew file mode 100644index 00000000..98dba9fa--- /dev/null+++ b/changelog/unreleased/2026-09-16-model-promotions-in-database.md@@ -0,0 +1,22 @@+# A Project's model file keeps list prices, and the server stores promotions++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `model-catalog`, `server`, `web`, `docs`+- **PR:** [#716](https://github.com/Prism-Shadow/penguin-harness/pull/716)++[中文版](2026-09-16-model-promotions-in-database.zh.md)++The `pricing` of every model in `.project_config.toml` now holds the list price, in every group. A flat promotion is a fraction the server keeps in a new `model_promotions` table in `web.db`, and cost is computed as list × (1 − discount). Presets and **Sync presets** used to write the discounted number into the file.++## Details++- Three things write promotions: creating a Project (the catalog's promotions are stored with the preset models, and for an adopted `default_project` whenever its presets are written); **Sync presets**, which gives every preset row the catalog's promotion or none (a Penguin Go row keeps the promotion its platform set); and Penguin Go authorization and Sync, which store the platform's.+- `GET /api/projects/:projectId/models` reports a row's promotion as `discount`. `PUT` accepts an optional `discount` per entry: a number between 0 and 1 stores it, `null` clears it, and omitting it keeps the stored one unless the entry renames the row or changes its pricing, which clears it. A row left out of the table loses its promotion. The model dialog notes a running promotion under the price fields and says that changing the price cancels it.+- The cost center, session costs, the chat's live per-turn estimate and company-mode budgets all price usage at the promoted rate. An off-peak tier still applies on top while the stored price is the catalog's peak price, and the card's badge shows the combined saving.+- In core, `presetModelEntries()` writes list prices and the new `presetPromotions()` lists the catalog's flat promotions.+- Database migration 9, `model-promotions`, creates the table. It is swap-safe; its `down` drops every stored promotion.++## Existing Projects++Nothing is migrated. A Project whose file holds discounted numbers from an earlier preset or sync keeps billing at those numbers, without a promotion badge, and the Models page counts those rows as preset updates; running **Sync presets** rewrites them to list prices and stores their promotions. A Project whose presets were written without the server (by the CLI or the SDK) is priced at list until the same sync.diff --git a/changelog/unreleased/2026-09-16-model-promotions-in-database.zh.md b/changelog/unreleased/2026-09-16-model-promotions-in-database.zh.mdnew file mode 100644index 00000000..1e1ce651--- /dev/null+++ b/changelog/unreleased/2026-09-16-model-promotions-in-database.zh.md@@ -0,0 +1,22 @@+# Project 的模型文件只存牌价,促销由服务端存储++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `model-catalog`, `server`, `web`, `docs`+- **PR:** [#716](https://github.com/Prism-Shadow/penguin-harness/pull/716)++[English](2026-09-16-model-promotions-in-database.md)++`.project_config.toml` 中每个模型的 `pricing` 现在一律是牌价,所有分组都如此。固定促销是服务端存在 `web.db` 新表 `model_promotions` 里的一个比例,成本按「牌价 ×(1 − 折扣)」计算。此前预置与**同步预置**写进文件的是折后价。++## 细节++- 促销只由三处写入:新建 Project(目录的促销随预置模型一并存入;纳管 `default_project` 时只要写入了预置,同样存入);**同步预置**,为每个预置行写入目录的促销或清除(Penguin Go 行保留其平台设定的促销);以及 Penguin Go 的授权与同步,存入平台下发的促销。+- `GET /api/projects/:projectId/models` 以 `discount` 报告行上的促销。`PUT` 的每个条目可带 `discount`:0 到 1 之间的数值即存入,`null` 即清除,省略则保留已存的促销——但该条目改名或改了定价时清除。整表里不再出现的行,其促销一并删除。模型配置弹窗在价格下方注明当前促销,并说明改价会取消促销。+- 成本中心、会话成本、对话里的实时单轮估算与公司模式的预算都按促销后的价格计价。存的仍是目录高峰价时,空闲时段档位照旧在其上叠加,卡片徽标显示合计的优惠。+- core 的 `presetModelEntries()` 改为写牌价,新增 `presetPromotions()` 列出目录的固定促销。+- 数据库迁移 9 `model-promotions` 建表;可热更新(swap-safe),其 `down` 会删掉全部已存促销。++## 既有 Project++不做迁移。文件里存着此前预置或同步写入的折后价的 Project,照旧按这些数字计费、不显示促销徽标,模型库页把这些行算作可同步的预置更新;执行**同步预置**后改写为牌价并存入促销。预置不经服务端写入的 Project(由 CLI 或 SDK 创建)在同样同步之前按牌价计价。diff --git a/changelog/unreleased/2026-09-16-penguin-go.md b/changelog/unreleased/2026-09-16-penguin-go.mdnew file mode 100644index 00000000..53af662c--- /dev/null+++ b/changelog/unreleased/2026-09-16-penguin-go.md@@ -0,0 +1,20 @@+# Penguin Go: a built-in model group whose key is authorized from the Models page++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `model-catalog`, `server`, `web`, `desktop`, `docs`+- **PR:** [#716](https://github.com/Prism-Shadow/penguin-harness/pull/716)++[中文版](2026-09-16-penguin-go.zh.md)++The model catalog gained a **Penguin Go** group (`penguin-go`), the relay at `https://token.penguin.ooo/api`, placed after TokenDance. Its header offers the same "authorize a key" action as TokenDance, backed by the platform's own device flow, and a **Sync** action that refreshes the group from the platform's catalog with the key already stored.++## Details++- The group ships preset rows for the Gemini 3.8 / 3.7 / 3.6 / 3.5 Flash, 3.5 Flash-Lite, 3.1 Flash-Lite and 3.1 Pro (Preview) models on the Google protocol, and `deepseek-flash` (**DeepSeek V4.1 Flash**) and `deepseek-v4-pro` (**DeepSeek V4 Pro 0813**) on the DeepSeek client. The rows carry list prices; the platform's promotions arrive with authorization and Sync (see [promotions stored outside the Project file](2026-09-16-model-promotions-in-database.md)).+- **Authorize key** runs through the server: `POST /api/projects/:projectId/platform-auth/start` registers a device secret with the platform and returns a local flow id and the authorization URL, `GET …/:flowId/status` polls the one-time delivery, and `…/retry` and `…/cancel` retry a failed write or abandon the flow. Owners only. The device secret and the delivered key stay in the server process; flows expire within ten minutes. On success the key is written across the group's rows and the platform catalog adds any missing models.+- **Sync** (`POST /api/projects/:projectId/platform-auth/sync`, owner) fetches the platform catalog with the stored key, adds missing models, refreshes list prices, protocols and promotions, and never deletes a local row. It reports "added N, updated M" or "already up to date" like Sync presets; a key the platform rejects sends the owner back to authorization.+- The platform's responses are validated (size, client id, key length, model ids, routes, endpoints, context and output limits, vision flags, USD pricing and discount consistency) before anything is written. A platform 429 surfaces as HTTP 429 with `Retry-After`.+- The group's credential resolves from `PENGUIN_GO_API_KEY` / `PENGUIN_GO_BASE_URL` for both protocols, never from the Google or DeepSeek variables, and connectivity, vision and protocol probes use it. A model added to the group by hand requires the relay base URL.+- The platform origin is server configuration, `PENGUIN_GO_ORIGIN` (default `https://token.penguin.ooo`): HTTPS only, plain HTTP accepted for loopback integration environments.+- The desktop shell opens the authorization page in the system browser, so Windows no longer shows a protocol-selection prompt for `about:blank`.diff --git a/changelog/unreleased/2026-09-16-penguin-go.zh.md b/changelog/unreleased/2026-09-16-penguin-go.zh.mdnew file mode 100644index 00000000..81edb140--- /dev/null+++ b/changelog/unreleased/2026-09-16-penguin-go.zh.md@@ -0,0 +1,20 @@+# Penguin Go:在模型库页授权密钥的内置模型分组++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `model-catalog`, `server`, `web`, `desktop`, `docs`+- **PR:** [#716](https://github.com/Prism-Shadow/penguin-harness/pull/716)++[English](2026-09-16-penguin-go.md)++模型目录新增 **Penguin Go** 分组(`penguin-go`),即 `https://token.penguin.ooo/api` 中转,排在 TokenDance 之后。组头提供与 TokenDance 相同的「授权密钥」操作,背后走平台自己的设备授权流程;另有「同步」操作,用已存的 key 按平台目录刷新该分组。++## 细节++- 分组预置 Gemini 3.8 / 3.7 / 3.6 / 3.5 Flash、3.5 Flash-Lite、3.1 Flash-Lite 与 3.1 Pro(Preview),走 Google 协议;以及 `deepseek-flash`(**DeepSeek V4.1 Flash**)与 `deepseek-v4-pro`(**DeepSeek V4 Pro 0813**),走 DeepSeek 客户端。预置行存牌价,平台的促销随授权与同步下发(见[促销存到 Project 文件之外](2026-09-16-model-promotions-in-database.zh.md))。+- **授权密钥**由服务端代办:`POST /api/projects/:projectId/platform-auth/start` 向平台登记设备密钥,返回本地流程 id 与授权地址;`GET …/:flowId/status` 轮询一次性投递;`…/retry` 与 `…/cancel` 分别重试失败的写入、放弃流程。仅 owner 可用。设备密钥与签发的 key 只留在服务端进程内,流程十分钟内过期。成功后 key 写进该分组全部模型,并按平台目录补齐缺失模型。+- **同步**(`POST /api/projects/:projectId/platform-auth/sync`,仅 owner)用已存的 key 拉取平台目录:补齐缺失模型,刷新牌价、协议与促销,从不删除本地行;结果与「同步预置」同一口径报「新增 N、更新 M」或「已是最新」;key 被平台拒绝时引导回授权。+- 平台响应在写入前逐项校验(大小、client id、key 长度、模型 id、路由、端点、上下文与输出上限、视觉标志、美元定价及折扣一致性)。平台返回 429 时,服务端以 HTTP 429 加 `Retry-After` 透出。+- 该分组两种协议的凭据都从 `PENGUIN_GO_API_KEY` / `PENGUIN_GO_BASE_URL` 解析,绝不借用 Google 或 DeepSeek 的变量,连通性、视觉与协议探测同样如此。手动加入该分组的模型必须填中转的 base URL。+- 平台地址是服务端配置 `PENGUIN_GO_ORIGIN`(缺省 `https://token.penguin.ooo`):只接受 HTTPS,仅环回地址的集成环境允许明文 HTTP。+- 桌面端改为在系统浏览器中打开授权页,Windows 不再为 `about:blank` 弹出协议选择框。diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.tsindex 5a57397c..1e1726e8 100644--- a/packages/core/src/state/model-catalog.ts+++ b/packages/core/src/state/model-catalog.ts@@ -17,8 +17,10 @@* group (V4.1 Flash released as `deepseek-flash`, the two V4 Flash ids retired into it —* `deepseek-v4-flash` text-only even so, AgentHub's DeepSeek client refusing image parts for* that id), the OpenRouter and TokenDance V4.1 Flash rows, and TokenDance's running promotions- * plus its Doubao Seed display names: 2026-09-10; the OpenRouter z-ai/glm-5.3-flash row:- * 2026-09-16 — per each provider's docs).+ * plus its Doubao Seed display names: 2026-09-10; the Penguin Go resale lineup, matched to the+ * relay's current generic-client model export: 2026-09-11, its DeepSeek rows to DeepSeek's own+ * lineup: 2026-09-16; the OpenRouter z-ai/glm-5.3-flash row: 2026-09-16 — per each provider's+ * docs).* Docs: packages/docs/content/models.{zh,en}.md (site path /docs/models) documents the* provider groups and credential resolution described here.*@@ -148,8 +150,9 @@ export interface ModelCatalogEntry {* Fraction off the list price the seller is currently running (0.5 = 50% off), applied to* every bucket. `pricing` stays the LIST price whatever promotion is live, so a lapsed* promotion is one field to delete rather than three numbers to reconstruct;- * effectivePricing is the rate actually billed, and presetModelEntries writes THAT into a- * Project so the cost center charges what the seller charges.+ * effectivePricing is the rate actually billed. A Project stores the list price too: the+ * fraction is seeded beside it as a promotion (presetPromotions), which the cost center+ * applies when it prices usage, so it charges what the seller charges.*/discount?: number;/**@@ -157,8 +160,9 @@ export interface ModelCatalogEntry {* cheaper off-hours. `pricing` holds the PEAK price, the one billed inside the windows, and* the rate applies everywhere else.*- * Unlike `discount`, this one changes twice a day, so it is never baked into a Project:- * `presetModelEntries` writes the peak price and the rate is applied when a price is read.+ * Like `discount`, this one is never baked into a Project, and here there is no choice: it+ * changes twice a day. `presetModelEntries` writes the peak price and the rate is applied+ * when a price is read.* A number on disk that silently meant something different at 09:00 than at 08:00 would be* unreadable, and re-syncing presets would rewrite prices by the clock. Mutually exclusive* with `discount`; an entry declaring both is a catalog error.@@ -191,12 +195,17 @@ 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";+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 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* model-group-order.ts). The sequence is a hand-curated display order: TokenDance leads as- * the recommended group, DeepSeek follows as the default model's provider, and custom+ * the recommended group, Penguin Go follows, then DeepSeek as the default model's+ * provider, and custom* (custom OpenAI-protocol models) is always last; in between, gateways and first-party* vendors are interleaved by expected use rather than sorted by kind. Only this default* moves when the curation changes: a Project that has ever reordered its groups has every@@ -226,6 +235,16 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [keyName: "PenguinHarness",},},+ {+ id: PENGUIN_GO_PROVIDER_ID,+ label: "Penguin Go",+ // The authorization flow writes one inlined relay key across the group. Keep the env+ // names private to this relay so the UI never suggests using a vendor credential here.+ envKey: "PENGUIN_GO_API_KEY",+ envBaseUrlKey: "PENGUIN_GO_BASE_URL",+ apiKeyUrl: "https://token.penguin.ooo/",+ modelsUrl: "https://token.penguin.ooo/",+ },{id: "deepseek",label: "DeepSeek",@@ -435,13 +454,14 @@ export function offPeakScheduledRefs(): Array<{/*** What the seller actually bills for an entry: its list `pricing` less any running `discount`,- * on every bucket. Rounded to the six decimals cny() already stores at, so a promotional rate is- * written into a Project as a price rather than as a float artifact. An entry with no discount- * (or no pricing at all) is returned untouched.+ * on every bucket. Rounded to the six decimals cny() already stores at, so a promotional rate+ * reads as a price rather than as a float artifact. An entry with no discount (or no pricing at+ * all) is returned untouched.*- * A row on a SCHEDULE is a deliberate exception: `presetModelEntries` writes its peak price,- * because which tier a request ran in is decided from that request's own timestamp when the- * usage is aggregated, not from what a Project happened to store.+ * Nothing writes this rate into a Project: `presetModelEntries` writes the list price (a+ * scheduled row's peak price), a flat promotion is stored beside it as a fraction, and which+ * tier a request ran in is decided from that request's own timestamp when the usage is+ * aggregated.*/export function effectivePricing(entry: ModelCatalogEntry,@@ -1269,8 +1289,9 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [// Discounts: every row here stores the official LIST price, the convention of the two Qwen// groups below, and a promoted row declares its rate in `discount` rather than having its// price rewritten — a promotion that lapses is then one field to delete, with the rate to- // return to still on the row. effectivePricing() applies it and presetModelEntries writes- // that billed rate into a Project, so the cost center charges what the gateway charges.+ // return to still on the row. effectivePricing() applies it; a new Project stores the list+ // price and the fraction as a promotion beside it, which the cost center applies, so it+ // charges what the gateway charges.// Nine rows are promoted (rates re-confirmed 2026-09-10): deepseek-v4-flash-0731,// deepseek-v4-pro-0813 and kimi-k3 at 20% off; glm-5.3, glm-5.3-flash and qwen3.8-max at// 10%; the three Doubao Seed rows (seed-2.1-pro, seed-2.1-turbo, seed-evolving) at 50%.@@ -1502,6 +1523,107 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [clientType: "openai-chat",baseUrl: TOKENDANCE_BASE_URL,},+ // -- Penguin Go (mixed-protocol relay). The model ids are the generation rows+ // provisioned by Penguin Go's generic-client authorization contract. Both+ // protocols share the /api base: the Google client appends /v1beta itself, while the+ // DeepSeek Responses client appends /responses. The rows carry Penguin Go's current list+ // prices so a new Project is complete before its first authorization, and no `discount`:+ // the platform delivers any promotion it runs at authorization and Sync, and both stay+ // authoritative when the relay later publishes changed metadata. The DeepSeek rows follow+ // DeepSeek's own lineup (re-read 2026-09-16): V4.1 Flash as `deepseek-flash` and V4 Pro 0813+ // as `deepseek-v4-pro`; the two retired V4 Flash ids, served from V4.1 Flash, are not resold.+ {+ modelId: "gemini-3.8-flash",+ displayName: "Gemini 3.8 Flash",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1048576,+ pricing: usd(0.075, 0.75, 3.75),+ supportsVision: true,+ clientType: "gemini-3.8",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ modelId: "gemini-3.7-flash",+ displayName: "Gemini 3.7 Flash",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1048576,+ pricing: usd(0.075, 0.75, 3.75),+ supportsVision: true,+ clientType: "gemini-3.8",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ modelId: "gemini-3.6-flash",+ displayName: "Gemini 3.6 Flash",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1048576,+ pricing: usd(0.075, 0.75, 3.75),+ supportsVision: true,+ clientType: "gemini-3.8",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ modelId: "gemini-3.5-flash",+ displayName: "Gemini 3.5 Flash",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1048576,+ pricing: usd(0.15, 1.5, 9),+ supportsVision: true,+ clientType: "gemini-3.8",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ modelId: "gemini-3.5-flash-lite",+ displayName: "Gemini 3.5 Flash-Lite",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1048576,+ pricing: usd(0.03, 0.3, 2.5),+ supportsVision: true,+ clientType: "gemini-3.8",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ modelId: "gemini-3.1-flash-lite",+ displayName: "Gemini 3.1 Flash-Lite",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1048576,+ pricing: usd(0.025, 0.25, 1.5),+ supportsVision: true,+ clientType: "gemini-3.8",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ modelId: "gemini-3.1-pro-preview",+ displayName: "Gemini 3.1 Pro (Preview)",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1048576,+ pricing: usd(0.2, 2, 12),+ supportsVision: true,+ clientType: "gemini-3.8",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ modelId: "deepseek-flash",+ displayName: "DeepSeek V4.1 Flash",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1000000,+ pricing: cny(0.04, 2, 8),+ offPeakDiscount: DEEPSEEK_OFF_PEAK,+ supportsVision: true,+ clientType: "deepseek-v4",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ modelId: "deepseek-v4-pro",+ displayName: "DeepSeek V4 Pro 0813",+ provider: PENGUIN_GO_PROVIDER_ID,+ contextWindow: 1000000,+ pricing: cny(0.3, 9, 27),+ offPeakDiscount: DEEPSEEK_OFF_PEAK,+ supportsVision: false,+ clientType: "deepseek-v4",+ baseUrl: PENGUIN_GO_BASE_URL,+ },// -- Qwen Token Plan (subscription gateway; vision flags per the plan's supported-model// table). Pricing and context windows from each model's page at// www.qianwenai.com/models/<id> (official CNY list prices; limited-time promotions such as@@ -1641,9 +1763,10 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [{// Same list price and same launch discount as the gemini-3.7-flash and gemini-3.6-flash// rows below: Google halves all three rates through 2026-12-31. Like those rows this one- // declares the promotion in `discount`, so the list price stays on file while a Project is- // preset with — and the cost center bills — the 0.075/0.75/3.75 Google actually charges- // today. One field to delete when the promotion lapses.+ // declares the promotion in `discount`, so the list price stays on file — here and in a+ // Project, which is seeded with the fraction beside it — while the cost center bills the+ // 0.075/0.75/3.75 Google actually charges today. One field to delete when the promotion+ // lapses.modelId: "gemini-3.8-flash",displayName: "Gemini 3.8 Flash",provider: "google",@@ -2181,6 +2304,26 @@ export function resolveModelEnv(modelId: string, clientType?: string): ModelEnvIreturn undefined;}+/**+ * 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.+ */+export function resolveProviderModelEnv(+ provider: string,+ modelId: string,+ clientType?: string,+): ModelEnvInfo | undefined {+ if (provider === PENGUIN_GO_PROVIDER_ID) {+ const group = providerInfo(provider);+ return group === undefined+ ? undefined+ : { envKey: group.envKey, envBaseUrlKey: group.envBaseUrlKey };+ }+ return resolveModelEnv(modelId, clientType);+}+/*** The wire protocol that would carry AgentHub's `fast_mode` for a model: `"openai"` for the* OpenAI-protocol clients (openai_chat / openai_responses / gpt6 / minimax_m3), which send@@ -2277,31 +2420,34 @@ export function fastModeProtocol(* rest — and inline a preset base_url. The direct MiniMax M3 entry also pins its protocol and* endpoint. No secrets are included, so only an API key is needed.*- * Pricing is written as the EFFECTIVE rate (effectivePricing: list less any running- * discount), not the list price the catalog records. A Project's stored pricing is the only- * thing the cost center ever prices against, so writing anything but what the seller bills- * would report a cost nobody was charged; the list price and the promotion that produced the- * difference stay in the catalog, where they can be read and restored.+ * Pricing is written as the LIST price the catalog records (a scheduled row's PEAK price),+ * never a discounted number. What is on disk then stays true whatever promotion is live and+ * whatever hour the Project is created or re-synced in: a flat promotion is stored beside the+ * file as a per-Project fraction (presetPromotions), and both it and an off-peak tier are+ * applied when the price is read, by the models page and by the cost center alike.*/export function presetModelEntries(): ModelEntry[] {- return MODEL_CATALOG.map((m) => {- // A scheduled discount writes the PEAK price, which is the same number whatever hour the- // Project is created or re-synced in. What is on disk has to be stable: the off-peak rate- // is applied when the price is read, by the models page and by the cost center alike.- const pricing = m.offPeakDiscount !== undefined ? m.pricing : effectivePricing(m);- return {- provider: m.provider,- model_id: m.modelId,- ...(m.contextWindow !== undefined ? { context_window: m.contextWindow } : {}),- ...(m.clientType !== undefined ? { client_type: m.clientType } : {}),- ...(pricing ? { pricing: { ...pricing } } : {}),- // ModelEntry.vision defaults to supported: only models that don't support images- // explicitly persist false (drives read_file's hand-off of images to the vision model and input- // image hand-off, see project-config.ts).- ...(m.supportsVision ? {} : { vision: false }),- ...(m.baseUrl !== undefined ? { base_url: m.baseUrl } : {}),- };- });+ return MODEL_CATALOG.map((m) => ({+ provider: m.provider,+ model_id: m.modelId,+ ...(m.contextWindow !== undefined ? { context_window: m.contextWindow } : {}),+ ...(m.clientType !== undefined ? { client_type: m.clientType } : {}),+ ...(m.pricing ? { pricing: { ...m.pricing } } : {}),+ // ModelEntry.vision defaults to supported: only models that don't support images+ // explicitly persist false (drives read_file's hand-off of images to the vision model and input+ // image hand-off, see project-config.ts).+ ...(m.supportsVision ? {} : { vision: false }),+ ...(m.baseUrl !== undefined ? { base_url: m.baseUrl } : {}),+ }));+}++/** The catalog's flat promotions, as a new Project is seeded with them: every row whose `discount` is a fraction in (0, 1). */+export function presetPromotions(): Array<{ provider: string; modelId: string; discount: number }> {+ return MODEL_CATALOG.flatMap((m) =>+ m.discount !== undefined && m.discount > 0 && m.discount < 1+ ? [{ provider: m.provider, modelId: m.modelId, discount: m.discount }]+ : [],+ );}/**diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.tsindex 96877386..1bdff710 100644--- a/packages/core/test/model-catalog.test.ts+++ b/packages/core/test/model-catalog.test.ts@@ -15,14 +15,16 @@ import {offPeakAt,DEEPSEEK_OFF_PEAK,presetModelEntries,+ presetPromotions,providerClientType,providerInfo,fastModeProtocol,resolveModelEnv,+ resolveProviderModelEnv,} from "../src/state/index.js";describe("model-catalog", () => {- it("(provider, model_id) pairs are unique; DeepSeek comes first (the default model's provider)", () => {+ it("(provider, model_id) pairs are unique and provider order keeps the recommendation first", () => {// Bare model ids may repeat across providers (a gateway reselling a vendor model keeps the// vendor's upstream id, e.g. Qwen Token Plan's glm-5.2 / deepseek-v4-pro) — uniqueness is// the (provider, model_id) pair, matching the catalog's sole lookup key (catalogEntryFor).@@ -30,13 +32,15 @@ describe("model-catalog", () => {expect(new Set(pairs).size).toBe(pairs.length);const ids = MODEL_CATALOG.map((m) => m.modelId);expect(MODEL_CATALOG[0]!.provider).toBe("deepseek");- // Group order is hand-curated, interleaving gateways and first-party vendors: TokenDance- // first (the recommended group), DeepSeek next (the default model's provider), vLLM last+ // Group order is hand-curated, interleaving gateways and first-party vendors: the+ // recommended TokenDance first, the prebuilt Penguin Go group next, DeepSeek after it,+ // and vLLM last// among the vendors (self-hosted, so nothing in it runs until the user names a server)// and custom always last. This is the page's DEFAULT only — a Project that has reordered// its groups stores every key and keeps its own arrangement (web's model-group-order.ts).expect(MODEL_PROVIDERS.map((p) => p.id)).toEqual(["tokendance",+ "penguin-go","deepseek","openrouter","fireworks",@@ -55,10 +59,11 @@ describe("model-catalog", () => {// Exactly one group is marked recommended, and it is the one that leads the default// order: the caption and the placement are two statements of the same curation.expect(MODEL_PROVIDERS.filter((p) => p.recommended).map((p) => p.id)).toEqual(["tokendance"]);- expect(MODEL_PROVIDERS[0]!.recommended).toBe(true);+ expect(providerInfo("tokendance")!.recommended).toBe(true);expect(providerInfo("siliconflow")!.label).toBe("SiliconFlow");expect(providerInfo("minimax")!.label).toBe("MiniMax");expect(providerInfo("minimax")!.envKey).toBe("MINIMAX_API_KEY");+ expect(providerInfo("penguin-go")!.label).toBe("Penguin Go");// The catalog no longer includes GLM-5-Turbo.expect(ids).not.toContain("glm-5-turbo");// The OpenRouter and SiliconFlow gateway listings of GLM-5.1 were delisted 2026-08-06;@@ -115,6 +120,65 @@ describe("model-catalog", () => {expect(oauth.keyName).toBe("PenguinHarness");});+ 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+ // retired V4 Flash ids are not resold.+ expect(penguinGoModels.map((model) => model.modelId)).toEqual([+ "gemini-3.8-flash",+ "gemini-3.7-flash",+ "gemini-3.6-flash",+ "gemini-3.5-flash",+ "gemini-3.5-flash-lite",+ "gemini-3.1-flash-lite",+ "gemini-3.1-pro-preview",+ "deepseek-flash",+ "deepseek-v4-pro",+ ]);+ expect(+ penguinGoModels.every((model) => model.baseUrl === "https://token.penguin.ooo/api"),+ ).toBe(true);+ expect(+ penguinGoModels.every(+ (model) => model.pricing !== undefined && model.pricing.unit === "usd_per_mtok",+ ),+ ).toBe(true);+ expect(+ penguinGoModels+ .filter((model) => model.modelId.startsWith("gemini-"))+ .every((model) => model.clientType === "gemini-3.8"),+ ).toBe(true);+ expect(+ penguinGoModels+ .filter((model) => model.modelId.startsWith("deepseek-"))+ .every((model) => model.clientType === "deepseek-v4"),+ ).toBe(true);+ expect(catalogEntryFor("penguin-go", "deepseek-flash")?.supportsVision).toBe(true);+ expect(catalogEntryFor("penguin-go", "deepseek-v4-pro")).toMatchObject({+ displayName: "DeepSeek V4 Pro 0813",+ supportsVision: false,+ });+ // No static promotion: the platform delivers whatever it runs at authorization and Sync,+ // so every row here is its list price and nothing else.+ expect(penguinGoModels.filter((model) => model.discount !== undefined)).toEqual([]);+ for (const modelId of ["gemini-3.8-flash", "gemini-3.7-flash", "gemini-3.6-flash"]) {+ expect(catalogEntryFor("penguin-go", modelId)!.pricing, modelId).toEqual({+ unit: "usd_per_mtok",+ cache_read: 0.075,+ cache_write: 0.75,+ output: 3.75,+ });+ }+ expect(catalogEntryFor("penguin-go", "deepseek-flash")).toMatchObject({+ pricing: {+ cache_read: 0.005714,+ cache_write: 0.285714,+ output: 1.142857,+ },+ offPeakDiscount: DEEPSEEK_OFF_PEAK,+ });+ });+it("the app URL a minted key is stamped with is the same one attribution headers carry", () => {expect(APP_URL).toBe("https://penguin.ooo/");expect(attributionHeaders("https://tokendance.space/gateway/v1")).toEqual({@@ -321,14 +385,11 @@ describe("model-catalog", () => {expect(entry.provider).toBe(cat.provider);expect(entry.model_id).toBe(cat.modelId);expect(entry.context_window).toBe(cat.contextWindow);- // A Project stores the BILLED rate, not the catalog's list price: the cost center- // prices only against what is written here, so a promoted row must arrive discounted.- // The exception is a row on a peak/off-peak schedule, which stores the PEAK price: the- // rate changes twice a day, so baking one in would make the number on disk depend on the- // hour the Project happened to be created or re-synced in.- expect(entry.pricing, entry.model_id).toEqual(- cat.offPeakDiscount !== undefined ? cat.pricing : effectivePricing(cat),- );+ // A Project stores the catalog's LIST price (a scheduled row's PEAK price), never a+ // discounted one: a promotion is seeded beside it as a fraction (presetPromotions), and+ // baking either rate in would make the number on disk depend on which promotion was+ // live, or which hour it was, when the Project was created or re-synced.+ expect(entry.pricing, entry.model_id).toEqual(cat.pricing);expect(entry.vision).toBe(cat.supportsVision ? undefined : false);// Gateway presets pin a client protocol, and so do the two direct rows whose own id// does not route (MiniMax M3, DeepSeek deepseek-flash); other direct models auto-route.@@ -341,6 +402,17 @@ describe("model-catalog", () => {}});+ it("presetPromotions: a promoted row is seeded with its fraction, a Penguin Go row never is", () => {+ const promotions = presetPromotions();+ expect(promotions).toContainEqual({+ provider: "tokendance",+ modelId: "glm-5.3-flash",+ discount: 0.1,+ });+ // Penguin Go's promotions are the platform's to deliver, at authorization and Sync.+ 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", () => {const or = MODEL_CATALOG.filter((m) => m.provider === "openrouter");// Dictionary order, newer versions of a series first (gpt-6-* before gpt-5.6-*,@@ -714,7 +786,13 @@ describe("model-catalog", () => {const customPresets = MODEL_CATALOG.filter((m) => m.provider === "custom");const withBaseUrl = presetModelEntries().filter((e) => e.base_url !== undefined);expect(withBaseUrl.map((e) => [e.provider, e.model_id]).sort()).toEqual(- [...gateway, ...minimax, ...pinnedDirect, ...customPresets]+ [+ ...gateway,+ ...minimax,+ ...pinnedDirect,+ ...customPresets,+ ...MODEL_CATALOG.filter((m) => m.provider === "penguin-go"),+ ].map((m) => [m.provider, m.modelId]).sort(),);@@ -1096,6 +1174,19 @@ describe("model-catalog", () => {});describe("resolveModelEnv (PRN-021: env fallback resolved by AgentHub routing rules)", () => {+ it("keeps Penguin Go relay credentials separate from both vendor protocols", () => {+ expect(resolveProviderModelEnv("penguin-go", "gemini-3.8-flash")?.envKey).toBe(+ "PENGUIN_GO_API_KEY",+ );+ expect(resolveProviderModelEnv("penguin-go", "deepseek-flash", "openai-chat")?.envKey).toBe(+ "PENGUIN_GO_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",+ );+ });+it("first-party model ids route to the provider client's env var", () => {expect(resolveModelEnv("deepseek-v4-pro")?.envKey).toBe("DEEPSEEK_API_KEY");// The dotted V4.1 spelling still carries the deepseek-v4 substring AutoLLMClient routes@@ -1183,6 +1274,12 @@ describe("resolveModelEnv (PRN-021: env fallback resolved by AgentHub routing ruconst 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");+ continue;+ }if (m.provider === "custom") {// The custom group's pair is the fallback for its OpenAI-protocol default; an entry// pinned to another generic protocol reads that protocol's pair instead, exactly as a@@ -1437,12 +1534,13 @@ describe("off-peak schedules", () => {const beijing = (iso: string): Date => new Date(`${iso}+08:00`);it("the DeepSeek rows store the peak price and declare the schedule", () => {- // Every direct row, plus the three resold rows whose sellers pass DeepSeek's own windows- // through: two on TokenDance and one on OpenRouter. A gateway row on the schedule carries- // no flat `discount` — the two are mutually exclusive, pinned by the last case here.+ // Every direct row, plus the resold rows whose sellers pass DeepSeek's own windows through:+ // two on Penguin Go, two on TokenDance and one on OpenRouter. A gateway row on the schedule+ // carries no flat `discount` — the two are mutually exclusive, pinned by the last case here.const rows = MODEL_CATALOG.filter((m) =>m.provider === "deepseek" ||+ (m.provider === "penguin-go" && m.modelId.startsWith("deepseek-")) ||(m.provider === "tokendance" &&["deepseek-v4.1-flash", "deepseek-v4-flash-vision-exp"].includes(m.modelId)) ||(m.provider === "openrouter" && m.modelId === "deepseek/deepseek-v4.1-flash"),@@ -1511,9 +1609,10 @@ describe("off-peak schedules", () => {]);});it("no entry declares both a flat discount and a schedule", () => {- // effectivePricing, discountedPrice and presetModelEntries all silently prefer the schedule,- // so a row declaring both would be billed at its list price during peak with nothing failing.- // The rule is stated in the field's doc; this is what makes it true.+ // effectivePricing silently prefers the schedule, while the cost center would apply the+ // seeded promotion on top of it, so a row declaring both would be shown at one rate and+ // billed at another with nothing failing. The rule is stated in the field's doc; this is+ // what makes it true.const both = MODEL_CATALOG.filter((m) => m.discount !== undefined && m.offPeakDiscount !== undefined,).map((m) => `${m.provider}/${m.modelId}`);diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex 2d01082e..77f88163 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -64,6 +64,7 @@ import {desktopLoginUrl,hidesOnClose,isAppUrl,+ isAuthorizationBridgeUrl,isLocalSurfaceUrl,MAX_SERVER_RESTARTS,restartDelayMs,@@ -148,6 +149,17 @@ function createWindow(url: string): void {// Denying it outright (as this did at first) made the entry silently do nothing.// Genuinely external links still go to the system browser.win.webContents.setWindowOpenHandler(({ url: target }) => {+ if (isAuthorizationBridgeUrl(target)) {+ return {+ action: "allow",+ // The bridge is an implementation detail, not a second app window. The Web App+ // either navigates it to the platform URL or closes it when `/start` fails.+ overrideBrowserWindowOptions: {+ show: false,+ webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },+ },+ };+ }if (isLocalSurfaceUrl(target, appOrigin)) {return {action: "allow",@@ -168,7 +180,8 @@ function createWindow(url: string): void {// The child lands on the preview origin after the redirect, so its policy is "stay// within this instance's loopback surface, everything else to the system browser" —// the main window's stricter app-origin-only rule would bounce the preview itself out.- win.webContents.on("did-create-window", (child) => {+ win.webContents.on("did-create-window", (child, details) => {+ const authorizationBridge = isAuthorizationBridgeUrl(details.url);child.webContents.setWindowOpenHandler(({ url: target }) => {if (isLocalSurfaceUrl(target, appOrigin)) return { action: "allow" };void shell.openExternal(target);@@ -178,6 +191,9 @@ function createWindow(url: string): void {if (!isLocalSurfaceUrl(target, appOrigin)) {event.preventDefault();void shell.openExternal(target);+ // A preview window stays open when one of its links opens externally. The hidden+ // authorization bridge has completed its only job and must not linger.+ if (authorizationBridge) child.close();}});});diff --git a/packages/desktop/src/util.ts b/packages/desktop/src/util.tsindex 47f592d8..bf3b8f52 100644--- a/packages/desktop/src/util.ts+++ b/packages/desktop/src/util.ts@@ -59,6 +59,16 @@ export function isLocalSurfaceUrl(url: string, origin: string | null): boolean {return loopback.has(target.hostname) && loopback.has(app.hostname);}+/**+ * The one inert window the Web App opens synchronously while Penguin Go creates an+ * authorization flow. It must stay inside Electron until the real HTTPS URL arrives:+ * handing `about:blank` to Windows asks the OS to find an application for the `about:`+ * scheme and raises a system dialog instead of opening the user's browser.+ */+export function isAuthorizationBridgeUrl(url: string): boolean {+ return url === "about:blank";+}+/** Max automatic server restarts before giving up with an error dialog. */export const MAX_SERVER_RESTARTS = 3;diff --git a/packages/desktop/test/util.test.ts b/packages/desktop/test/util.test.tsindex c11d8808..54a4e6e9 100644--- a/packages/desktop/test/util.test.ts+++ b/packages/desktop/test/util.test.ts@@ -4,6 +4,7 @@ import {desktopLoginUrl,hidesOnClose,isAppUrl,+ isAuthorizationBridgeUrl,isLocalSurfaceUrl,parsePortFile,restartDelayMs,@@ -61,6 +62,15 @@ describe("isLocalSurfaceUrl", () => {});});+describe("isAuthorizationBridgeUrl", () => {+ it("accepts only the inert blank window used while authorization starts", () => {+ expect(isAuthorizationBridgeUrl("about:blank")).toBe(true);+ expect(isAuthorizationBridgeUrl("about:blank#other")).toBe(false);+ expect(isAuthorizationBridgeUrl("about:srcdoc")).toBe(false);+ expect(isAuthorizationBridgeUrl("https://example.com")).toBe(false);+ });+});+describe("restartDelayMs", () => {it("doubles from 1s and caps at 8s", () => {expect([0, 1, 2, 3, 4].map(restartDelayMs)).toEqual([1000, 2000, 4000, 8000, 8000]);diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.mdindex 324ab0e0..202d4091 100644--- a/packages/docs/content/configuration.en.md+++ b/packages/docs/content/configuration.en.md@@ -17,10 +17,11 @@ The CLI and the server automatically load a `.env` file from the working directo| `PENGUIN_WEB_DB` | Server SQLite database path | `<root>/web.db` || `PENGUIN_WEB_DIST` | Front-end static assets directory | the npm server package falls back to its bundled 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 used by the server-side Penguin Go key authorization flow | `https://token.penguin.ooo` || `PENGUIN_TRUST_PROXY` | `1` trusts the `x-forwarded-proto` header — set it behind a reverse proxy that terminates TLS (and sets/strips the header itself) so session cookies are marked `Secure` and the hot-update network gate sees HTTPS | unset — the header is ignored || `PENGUIN_SEED_ADMIN_PASSWORD` | Fixed initial password for the seeded built-in admin (automated tests / e2e) | unset — the seed generates a random password, hashed and discarded unseen; the account is claimed through the first-login link || `PENGUIN_LANG` | CLI language (`en` / `zh`), set via `penguin config lang` | `en` |-| `PENGUIN_UPDATE_CHECK` | `off` disables the web app's new-release check (the server's only outbound internet call) | enabled |+| `PENGUIN_UPDATE_CHECK` | `off` disables the web app's new-release check | enabled || `PENGUIN_NO_LOGIN_SHELL_ENV` | Any non-empty value stops the desktop app from importing the login shell's environment on macOS/Linux GUI launches (see [Desktop quickstart](/quickstart-desktop)) | unset — the import runs, filling only variables the launch left unset || `PENGUIN_CLI_ENTRY` | The CLI entry script this installation offers the Agents it runs (see below) | set for you by `penguin server` / `penguin web` and by the desktop app; falls back to the checkout's own `packages/cli/dist/penguin.js` when the server was started from one |@@ -30,6 +31,8 @@ One thing travels the other way: **this installation's own `penguin` is first on`PENGUIN_PREVIEW_ORIGIN` must differ from the app's origin by **hostname**, not just port: cookies ignore ports, so a second port would still share the session cookie. Leave it unset for local use — the app is canonicalized onto `localhost` and previews are served from `127.0.0.1`, which needs no configuration and no DNS. Set it when the app is reached over a LAN address or a real domain; otherwise previews there fall back to a same-origin sandbox where `localStorage`, cookies and third-party embeds do not work. When you do set it on a real domain, keep the session cookie host-only (no `Domain=`), or a sibling subdomain shares it. An unparseable value is a startup error rather than a silent fallback.+`PENGUIN_GO_ORIGIN` is server configuration, not a browser-supplied endpoint. It must be a bare HTTPS origin; plain HTTP is accepted only for `localhost`, `127.0.0.1`, or `[::1]` integration environments. Paths, credentials, query strings, and fragments are rejected at startup.+### Provider credential variablesWhen a model entry has no inline `api_key`, AgentHub falls back to the provider's environment variable. A `*_BASE_URL` value is used only when the entry does not already inline `base_url`:@@ -70,7 +73,7 @@ Model entry (`[[models]]`) fields:| `vision` | Whether image input is supported; defaults to supported || `max_tokens` | Per-model max output tokens; overrides the Agent's `model.max_tokens` when set, omitted = inherit it || `fast_mode` | Per-model fast mode (premium faster serving tier); off by default, only `true` is persisted. Offered only for models whose AgentHub client can serve it; the others reject requests carrying it — see [Models](/models#fast-mode) |-| `pricing` | Three price buckets `cache_read` / `cache_write` / `output`, in USD per million Tokens (`unit = "usd_per_mtok"`) |+| `pricing` | Three price buckets `cache_read` / `cache_write` / `output`, in USD per million Tokens (`unit = "usd_per_mtok"`). Always the list price: a running promotion is stored by the server in `web.db` and taken off when cost is computed — see [Models](/models#built-in-provider-groups) || `api_key` | Inline credential; when empty, falls back to the provider environment variable || `base_url` | Custom base URL; preset by the built-in catalog for gateways and for the direct rows that pin a client — MiniMax M3 and DeepSeek `deepseek-flash` || `created_at` | Write timestamp of `api_key` (ISO 8601; a display field maintained by the interface layer) |diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.mdindex c8e476ff..cc900280 100644--- a/packages/docs/content/configuration.zh.md+++ b/packages/docs/content/configuration.zh.md@@ -17,10 +17,11 @@ CLI 与服务端启动时会自动加载工作目录下的 `.env` 文件。| `PENGUIN_WEB_DB` | 服务端 SQLite 数据库路径 | `<root>/web.db` || `PENGUIN_WEB_DIST` | 前端静态资源目录 | npm 安装的服务端包回退到内置 web-dist || `PENGUIN_PREVIEW_ORIGIN` | 提供 Workspace HTML 预览的独立源,如 `https://preview.example.com` | 未设置,按请求推导回环对应名 |+| `PENGUIN_GO_ORIGIN` | 服务端发起 Penguin Go Key 授权时使用的可信源 | `https://token.penguin.ooo` || `PENGUIN_TRUST_PROXY` | 设为 `1` 信任 `x-forwarded-proto` 请求头——在终结 TLS 的反向代理(且由代理自行设置/清除该头)之后设置,使会话 Cookie 带 `Secure` 标记、热更新网络门禁识别 HTTPS | 未设置,忽略该请求头 || `PENGUIN_SEED_ADMIN_PASSWORD` | 固定内置管理员的种子初始密码(自动化测试 / e2e 使用) | 未设置,种子时随机生成一个密码,哈希后即丢弃、无人见过;账号通过首次登录链接认领 || `PENGUIN_LANG` | CLI 语言(`en` / `zh`),用 `penguin config lang` 设置 | `en` |-| `PENGUIN_UPDATE_CHECK` | 设为 `off` 关闭 Web 应用的新版本检查(服务端唯一的对外网络请求) | 开启 |+| `PENGUIN_UPDATE_CHECK` | 设为 `off` 关闭 Web 应用的新版本检查 | 开启 || `PENGUIN_NO_LOGIN_SHELL_ENV` | 任意非空值可禁止桌面版在 macOS/Linux 图形界面启动时导入登录 shell 环境变量(见[桌面版速上手](/quickstart-desktop)) | 未设置,导入开启,且只补启动环境中缺失的变量 || `PENGUIN_CLI_ENTRY` | 本安装提供给其所运行 Agent 的 CLI 入口脚本(见下文) | 由 `penguin server` / `penguin web` 与桌面版自动设置;若服务端从仓库检出启动,则回退到该检出的 `packages/cli/dist/penguin.js` |@@ -30,6 +31,8 @@ CLI 与服务端启动时会自动加载工作目录下的 `.env` 文件。`PENGUIN_PREVIEW_ORIGIN` 必须与应用源在**主机名**上不同,只换端口不行:Cookie 不区分端口,换端口仍然共用会话 Cookie。本地使用不必配置——App 固定在规范主机 `localhost`,预览用 `127.0.0.1`,既不需要配置也不需要 DNS。经 LAN 地址或真实域名访问时才需要设置,否则那里的预览会回退到同源沙箱,`localStorage`、Cookie 与第三方 embed 都不可用。在真实域名上设置时,会话 Cookie 必须保持 host-only(不带 `Domain=`),否则同注册域下的兄弟子域会共享它。取值无法解析时启动即报错,不会静默回退。+`PENGUIN_GO_ORIGIN` 是服务端配置,不允许由浏览器指定端点。它必须是一个不带路径的 HTTPS 源;仅本地集成环境的 `localhost`、`127.0.0.1` 或 `[::1]` 可以使用明文 HTTP。带路径、凭据、查询参数或 fragment 的取值会使服务端在启动时直接报错。+### Provider 凭证环境变量当模型条目未内联 `api_key` 时,AgentHub 按 Provider 回退读取对应环境变量;仅当条目未内联 `base_url` 时才使用 `*_BASE_URL`:@@ -70,7 +73,7 @@ openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-to| `vision` | 是否支持图片输入;缺省视为支持 || `max_tokens` | 单模型最大输出 Token;设置后覆盖 Agent 的 `model.max_tokens`,缺省则继承 || `fast_mode` | 单模型快速模式(厂商的溢价快速推理档位);默认关闭,只持久化 `true`。只对 AgentHub client 支持该档位的模型开放,其余模型会拒绝携带该参数的请求——见[模型与 Provider](/models#快速模式) |-| `pricing` | 三档价格 `cache_read` / `cache_write` / `output`,单位 USD 每百万 Token(`unit = "usd_per_mtok"`) |+| `pricing` | 三档价格 `cache_read` / `cache_write` / `output`,单位 USD 每百万 Token(`unit = "usd_per_mtok"`)。恒为牌价:促销折扣由服务端存于 `web.db`,计算成本时扣除——见[模型与 Provider](/models#内置-provider-分组) || `api_key` | 内联凭证;留空回退到 Provider 环境变量 || `base_url` | 自定义 Base URL;内置目录会为网关,以及固定了 client 的直连条目——MiniMax M3 与 DeepSeek `deepseek-flash`——预置 || `created_at` | `api_key` 写入时间(ISO 8601,界面维护的展示字段) |diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.mdindex 8f854a31..6b410a2f 100644--- a/packages/docs/content/models.en.md+++ b/packages/docs/content/models.en.md@@ -61,7 +61,8 @@ Built-in groups and their env-var fallbacks (catalog source: `packages/core/src/| Provider | API key env var | Notes || --- | --- | --- |-| tokendance | `OPENAI_API_KEY` | The recommended group, listed first by default. OpenAI-compatible gateway, preset base URL `https://tokendance.space/gateway/v1`; model ids are bare, with no vendor prefix (e.g. `glm-5.3`, `kimi-k3`); pricing is the gateway's own CNY rates, several of them currently discounted |+| tokendance | `OPENAI_API_KEY` | The recommended vendor group. OpenAI-compatible gateway, preset base URL `https://tokendance.space/gateway/v1`; model ids are bare, with no vendor prefix (e.g. `glm-5.3`, `kimi-k3`); pricing is the gateway's own CNY rates, several of them currently discounted |+| penguin-go | `PENGUIN_GO_API_KEY` | Preset relay group with fixed base URL `https://token.penguin.ooo/api`; its header can authorize a key automatically or set one manually || deepseek | `DEEPSEEK_API_KEY` | Group of the default model || openrouter | `OPENAI_API_KEY` | OpenAI-compatible gateway, preset base URL `https://openrouter.ai/api/v1` || fireworks | `OPENAI_API_KEY` | Fireworks AI (OpenAI-compatible), preset base URL `https://api.fireworks.ai/inference/v1`; API model ids look like `accounts/fireworks/models/<slug>` |@@ -80,9 +81,9 @@ The gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-payThe preset catalog also carries OpenRouter's free tier: the `:free` model variant `nvidia/nemotron-3-ultra-550b-a55b:free` and the `openrouter/free` unified Free Models Router. They cost nothing, but are subject to OpenRouter's free-tier rate limits and data policy.-Some models in the preset catalog: deepseek-flash / deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp (`deepseek-flash` and `deepseek-v4-flash-vision-exp` read images; `deepseek-v4-flash` and `deepseek-v4-pro` are text-only. Since 2026-09-10 the two legacy Flash ids are retired names that DeepSeek serves from V4.1 Flash at the Flash price, which changes what they cost but not what V4 Flash reads: send an image to `deepseek-flash`), MiniMax-M3, gemini-3.8-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-6-astra / gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, 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) (not exhaustive). The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group rows record the official peak tier and declare its off-peak schedule: outside Beijing weekday 9:00–12:00 and 14:00–18:00 every bucket is halved, which the models page marks with a `50% off` badge and the cost center bills at. Three resold rows follow the same schedule, because their sellers pass DeepSeek's own windows through: TokenDance's `deepseek-v4.1-flash` and `deepseek-v4-flash-vision-exp`, and OpenRouter's `deepseek/deepseek-v4.1-flash`. The stored price is always the peak one, so what is on disk does not depend on the hour a Project was created or re-synced in. `glm-5.3-flash` appears three times, and all three rows accept images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), while the OpenRouter row `z-ai/glm-5.3-flash` and the TokenDance row go through the generic OpenAI-compatible client, which carries them for any id. What the three rows do not share is the price: each records what its own seller charges, so they disagree while a promotion is running.+Some models in the preset catalog: deepseek-flash / deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp (`deepseek-flash` and `deepseek-v4-flash-vision-exp` read images; `deepseek-v4-flash` and `deepseek-v4-pro` are text-only. Since 2026-09-10 the two legacy Flash ids are retired names that DeepSeek serves from V4.1 Flash at the Flash price, which changes what they cost but not what V4 Flash reads: send an image to `deepseek-flash`), MiniMax-M3, gemini-3.8-flash, claude-opus-5 / claude-opus-4-8 / claude-sonnet-5, gpt-6-astra / gpt-5.6 / gpt-5.5, glm-5.3 / glm-5.3-flash, kimi-k3, 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) (not exhaustive). Penguin Go's DeepSeek rows follow DeepSeek's current lineup and carry only `deepseek-flash` and `deepseek-v4-pro`. The whole OpenAI line-up is listed twice — directly (your own OpenAI key, list prices) and on OpenRouter as `openai/<id>` (the gateway's rates, which follow its running promotions). DeepSeek's direct-group rows record the official peak tier and declare its off-peak schedule: outside Beijing weekday 9:00–12:00 and 14:00–18:00 every bucket is halved, which the models page marks with a `50% off` badge and the cost center bills at. Three resold rows follow the same schedule, because their sellers pass DeepSeek's own windows through: TokenDance's `deepseek-v4.1-flash` and `deepseek-v4-flash-vision-exp`, and OpenRouter's `deepseek/deepseek-v4.1-flash`. The stored price is always the peak one, so what is on disk does not depend on the hour a Project was created or re-synced in. `glm-5.3-flash` appears three times, and all three rows accept images: AgentHub's GLM client forwards image parts for this one GLM id (every other GLM id refuses them), while the OpenRouter row `z-ai/glm-5.3-flash` and the TokenDance row go through the generic OpenAI-compatible client, which carries them for any id. What the three rows do not share is the price: each records what its own seller charges, so they disagree while a promotion is running.-TokenDance rows record the gateway's list price and, where a promotion is running, the rate off it. Nine models are discounted today — `deepseek-v4-flash-0731`, `deepseek-v4-pro-0813` and `kimi-k3` at 20% off, `glm-5.3`, `glm-5.3-flash` and `qwen3.8-max` at 10%, and the three Doubao Seed rows (`seed-2.1-pro`, `seed-2.1-turbo`, `seed-evolving`) at 50%. Two further rows carry no flat discount and instead follow DeepSeek's own off-peak schedule, described above. Their model cards show the price being billed right now, with the rate as a badge, and a Project is preset with the **discounted** price, so the cost center charges what the gateway charges. Prices you edit yourself keep the discount decoration off the card: the figure is then yours, not the gateway's.+TokenDance rows record the gateway's list price and, where a promotion is running, the rate off it. Nine models are discounted today — `deepseek-v4-flash-0731`, `deepseek-v4-pro-0813` and `kimi-k3` at 20% off, `glm-5.3`, `glm-5.3-flash` and `qwen3.8-max` at 10%, and the three Doubao Seed rows (`seed-2.1-pro`, `seed-2.1-turbo`, `seed-evolving`) at 50%. Two further rows carry no flat discount and instead follow DeepSeek's own off-peak schedule, described above. Their model cards show the price being billed right now, with the rate as a badge. A Project is preset with the **list** price: the server stores the promotion beside it (in `web.db`, not in `.project_config.toml`) and takes it off when usage is priced, so the cost center charges what the gateway charges. Editing a row's price yourself cancels its promotion and keeps any off-peak decoration off the card: the figure is then yours, not the gateway's.## App attribution@@ -97,17 +98,25 @@ Some gateways read a request header that files a call under the app that made itEvery other endpoint — every direct vendor, and every gateway that reads no such header — receives no extra headers at all. The headers state the app's identity only; they carry nothing about the user, the Agent or the Session.+## Penguin Go preset group++`penguin-go` is a built-in model group, like TokenDance. New Projects contain the group's catalog models immediately; existing Projects add them through **Sync presets** on the Models page. The built-in rows provide a stable initial route to `https://token.penguin.ooo/api`, while the platform catalog returned during authorization or **Sync** can add model ids that are missing locally, together with their protocol, endpoint, display name, context window, vision capability, and platform price. Like every built-in group, synchronized models leave the user-owned `max_tokens` override unset and inherit the Agent setting. Existing rows refresh their three platform price buckets and client protocol; their endpoint and other Project-owned configuration are not overwritten, and rows are never deleted. Pure embedding rows are excluded. As in every other group, `.project_config.toml` holds the list price, and a flat promotion the platform runs is stored by the server in `web.db`, taken off when usage is priced, and shown as the model card's badge. These promotions come only from the platform: **Sync presets** does not set them, and each authorization or Sync replaces them. If that record is lost, usage is priced at the list price until the next authorization or Sync writes it back. The platform reports peak rates in USD per million tokens. The current built-in Penguin Go DeepSeek rows declare the same Beijing off-peak schedule as the direct DeepSeek group, so their model cards and cost records use half price outside weekday 9:00–12:00 and 14:00–18:00.++Before the group has a platform key, its **Authorize key** action creates a one-time request only after the user clicks it, then opens Penguin Go in a new tab while the local server polls. The browser receives only an authorization URL and local flow id; the device secret and delivered API key remain server-side. On success PenguinHarness validates `connection.apiKey`, the endpoints, and the model catalog. It writes the key to every existing group model, adds newly advertised models with their recommended protocol, endpoint, name, context window, vision capability, and list price, refreshes existing platform-model prices and client protocols, then replaces the group's promotions with the platform's. Synchronization preserves existing endpoints and other Project-owned configuration and never deletes models. Account and balance data are neither saved nor displayed.++After a platform key is configured, a separate **Sync** action appears immediately before **Add model**. **Authorize key** remains available so the owner can replace the key with one from another platform account. Sync uses the stored key to request the latest catalog, adds new models, refreshes existing platform-owned metadata, and leaves the config file untouched when the catalog produces no changes. If the platform reports that the key is invalid or revoked, the Models page automatically opens authorization again. Penguin Go's browser session and API key are separate: an expired browser session does not prevent a valid key from synchronizing; reauthorization is needed only when the key itself is invalid.+## Authorizing a new API key-A provider that publishes an authorization flow puts an extra action on its group header in the models page: **Authorize key**. TokenDance is the one built-in group that does. It creates a **new** key on your account — it does not read a key you already have — and writes it to every model in that group, replacing whatever key those entries carry.+A provider that supports automatic key authorization puts an extra action on its group header in the Models page: **Authorize key**. TokenDance and Penguin Go both do. A successful flow writes the new key to every model in that group, replacing whatever key those entries carry. After Penguin Go authorization succeeds, a separate **Sync** action incrementally discovers models the platform later makes available while authorization remains available for switching accounts.-Pressing it opens the provider's authorization page in a new tab. Authorize there and the provider sends the browser back to PenguinHarness, which redeems the one-time code and saves the key; the tab you started from reports the result on its own. The same app URL the attribution table above lists is stamped onto the key, so calls made with it stay attributed even from another tool.+Pressing it opens the provider's authorization page in a new tab, while the dialog in the Models page waits for and reports the result. TokenDance uses a PKCE callback and exchange; Penguin Go uses device authorization start and poll endpoints. That protocol difference stays server-side, so the user interaction and group-key result are the same.-The exchange runs entirely on the server: the PKCE verifier is generated there and never reaches the browser, and the minted key goes straight into the model table without passing through it. An authorization is good for one key and expires in ten minutes.+The exchange runs entirely on the server: neither a PKCE verifier nor a device secret reaches the browser, and the minted key goes straight into the model table. An authorization delivers one key and expires at the deadline returned by the provider; PenguinHarness never keeps a local flow for longer than ten minutes.-Where the redirect cannot come back — a server the browser cannot reach on the address it was given — pick **Page can't redirect back? Enter the code by hand**. The authorization page then displays a one-time code instead of redirecting, and pasting it into the dialog finishes the same flow.+TokenDance supports entering a one-time code when its redirect cannot return. Penguin Go is polled by the Models page and therefore has no manual-code mode.-Only the Project owner can start an authorization, and only their own signed-in session finishes one — in practice, the tab the dialog is open in. The redirect itself is received without a session, and has to be, because the browser the provider sends back is not always the one you started in. But all that redirect does is hand the code over: nothing is redeemed and no key is saved until the dialog asks for the result. The full key is shown once and never again, so if saving it fails you have to authorize again and delete the unused key in the provider's console.+Only the Project owner can start authorization. The full key never returns to the Web app. If writing a Penguin Go key locally fails, the server keeps that single delivery briefly so the write can be retried without authorizing again.## Local / self-hosted OpenAI-compatible endpoints (e.g. vLLM)diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.mdindex 27babdc5..13a92e34 100644--- a/packages/docs/content/models.zh.md+++ b/packages/docs/content/models.zh.md@@ -61,7 +61,8 @@ api_key = "sk-..."| Provider | API Key 环境变量 | 说明 || --- | --- | --- |-| tokendance | `OPENAI_API_KEY` | 官方推荐分组,默认排在首位。OpenAI 兼容网关,预置 base URL `https://tokendance.space/gateway/v1`;模型 id 为不带厂商前缀的裸 id(如 `glm-5.3`、`kimi-k3`);价格取该网关自己的 CNY 牌价,其中若干条目当前处于折扣中 |+| tokendance | `OPENAI_API_KEY` | 官方推荐的厂商分组。OpenAI 兼容网关,预置 base URL `https://tokendance.space/gateway/v1`;模型 id 为不带厂商前缀的裸 id(如 `glm-5.3`、`kimi-k3`);价格取该网关自己的 CNY 牌价,其中若干条目当前处于折扣中 |+| penguin-go | `PENGUIN_GO_API_KEY` | 预置中转站分组,固定 base URL `https://token.penguin.ooo/api`;未授权时可自动获取密钥,授权后可同步平台新增模型,也可以手动统一设置 || deepseek | `DEEPSEEK_API_KEY` | 默认模型所在分组 || openrouter | `OPENAI_API_KEY` | OpenAI 兼容网关,预置 base URL `https://openrouter.ai/api/v1` || fireworks | `OPENAI_API_KEY` | Fireworks AI(OpenAI 兼容),预置 base URL `https://api.fireworks.ai/inference/v1`;API 模型 id 形如 `accounts/fireworks/models/<slug>` |@@ -80,9 +81,9 @@ api_key = "sk-..."预置目录还收录了 OpenRouter 的免费档:`:free` 模型变体 `nvidia/nemotron-3-ultra-550b-a55b:free` 与统一路由 `openrouter/free`(Free Models Router),零成本可用,但受 OpenRouter 免费档速率限制与数据政策约束。-预置目录中的部分模型:deepseek-flash / deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp(其中 `deepseek-flash`、`deepseek-v4-flash-vision-exp` 支持图像输入,`deepseek-v4-flash` 与 `deepseek-v4-pro` 为纯文本。自 2026-09-10 起,两个 V4 Flash id 已是退役名称,DeepSeek 改由 V4.1 Flash 承接、按 Flash 价计费——变的是价格,不是 V4 Flash 能读什么:要发图请用 `deepseek-flash`)、MiniMax-M3、gemini-3.8-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-6-astra / gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash、seed-2.1-pro / seed-2.1-turbo / seed-evolving、dots-3-note-preview(TokenDance 上免费,512K 上下文)等(非完整清单)。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的条目记录官方高峰档,并声明其空闲时段规则:在北京时间周一至周五 9:00–12:00、14:00–18:00 之外,各档价格减半——模型页以「省 50%」徽标标记,成本中心按此计价。另有三条转售条目沿用同一套时段,因为卖家原样传递了 DeepSeek 自己的窗口:TokenDance 的 `deepseek-v4.1-flash` 与 `deepseek-v4-flash-vision-exp`,以及 OpenRouter 的 `deepseek/deepseek-v4.1-flash`。存盘的始终是高峰价,因此磁盘上的数字不会随 Project 创建或同步预置的时刻而变。`glm-5.3-flash` 收录了三份,三条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而 OpenRouter 上的 `z-ai/glm-5.3-flash` 与 TokenDance 分组的同名条目走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。三条不一致的是价格:每一条都记录各自卖家的收费,因此促销期间三者不同。+预置目录中的部分模型:deepseek-flash / deepseek-v4-pro / deepseek-v4-flash / deepseek-v4-flash-vision-exp(其中 `deepseek-flash`、`deepseek-v4-flash-vision-exp` 支持图像输入,`deepseek-v4-flash` 与 `deepseek-v4-pro` 为纯文本。自 2026-09-10 起,两个 V4 Flash id 已是退役名称,DeepSeek 改由 V4.1 Flash 承接、按 Flash 价计费——变的是价格,不是 V4 Flash 能读什么:要发图请用 `deepseek-flash`)、MiniMax-M3、gemini-3.8-flash、claude-opus-5 / claude-opus-4-8 / claude-sonnet-5、gpt-6-astra / gpt-5.6 / gpt-5.5、glm-5.3 / glm-5.3-flash、kimi-k3、qwen3.8-max / qwen3.8-flash、seed-2.1-pro / seed-2.1-turbo / seed-evolving、dots-3-note-preview(TokenDance 上免费,512K 上下文)等(非完整清单)。Penguin Go 分组的 DeepSeek 条目跟随 DeepSeek 当前的模型阵容,只收录 `deepseek-flash` 与 `deepseek-v4-pro`。OpenAI 全系列都收录了两份——直连(用自己的 OpenAI Key,记牌价)与 OpenRouter 上的 `openai/<id>`(记网关实际计费价,会随其促销浮动)。DeepSeek 直连分组的条目记录官方高峰档,并声明其空闲时段规则:在北京时间周一至周五 9:00–12:00、14:00–18:00 之外,各档价格减半——模型页以「省 50%」徽标标记,成本中心按此计价。另有三条转售条目沿用同一套时段,因为卖家原样传递了 DeepSeek 自己的窗口:TokenDance 的 `deepseek-v4.1-flash` 与 `deepseek-v4-flash-vision-exp`,以及 OpenRouter 的 `deepseek/deepseek-v4.1-flash`。存盘的始终是高峰价,因此磁盘上的数字不会随 Project 创建或同步预置的时刻而变。`glm-5.3-flash` 收录了三份,三条都支持图像输入:AgentHub 的 GLM 客户端只为这一个 GLM id 转发图像部件(其余 GLM id 一律拒绝),而 OpenRouter 上的 `z-ai/glm-5.3-flash` 与 TokenDance 分组的同名条目走通用 OpenAI 兼容客户端,对任何 id 都能携带图片。三条不一致的是价格:每一条都记录各自卖家的收费,因此促销期间三者不同。-TokenDance 分组的条目记录该网关的牌价,并在有促销时记录折扣率。当前有九个模型处于折扣中——`deepseek-v4-flash-0731`、`deepseek-v4-pro-0813` 与 `kimi-k3` 八折,`glm-5.3`、`glm-5.3-flash` 与 `qwen3.8-max` 九折,三条 Doubao Seed 条目(`seed-2.1-pro`、`seed-2.1-turbo`、`seed-evolving`)五折。另有两条条目不走固定折扣,而是沿用上文所述 DeepSeek 自己的空闲时段规则。它们的模型卡片显示当前实际计费的那个价格,并以徽标标出折扣率;新建 Project 预置的是**折后价**,因此成本中心按网关实际收费计价。自行修改过价格的条目不再显示折扣标记:此时那个数字属于你,而不是网关。+TokenDance 分组的条目记录该网关的牌价,并在有促销时记录折扣率。当前有九个模型处于折扣中——`deepseek-v4-flash-0731`、`deepseek-v4-pro-0813` 与 `kimi-k3` 八折,`glm-5.3`、`glm-5.3-flash` 与 `qwen3.8-max` 九折,三条 Doubao Seed 条目(`seed-2.1-pro`、`seed-2.1-turbo`、`seed-evolving`)五折。另有两条条目不走固定折扣,而是沿用上文所述 DeepSeek 自己的空闲时段规则。它们的模型卡片显示当前实际计费的那个价格,并以徽标标出折扣率。新建 Project 预置的是**牌价**:折扣率由服务端另行保存(存于 `web.db`,不写入 `.project_config.toml`),计算成本时再从牌价中扣除,因此成本中心按网关实际收费计价。自行修改条目的价格会取消其促销,也不再显示空闲时段折扣标记:此时那个数字属于你,而不是网关。## 应用归因@@ -97,17 +98,25 @@ TokenDance 分组的条目记录该网关的牌价,并在有促销时记录折其余端点(所有直连厂商,以及不读归因头的网关)不会收到任何额外请求头。归因头只声明应用身份,不携带用户、Agent 或会话信息。+## Penguin Go 预置分组++`penguin-go` 与 TokenDance 一样是内置模型分组。新建 Project 会直接带上该分组在目录中的模型;已有 Project 通过模型页的「同步预置」补入。内置条目提供指向 `https://token.penguin.ooo/api` 的稳定初始路由;授权或「同步」时返回的平台模型清单还可以把本地缺失的模型 id 连同协议、端点、显示名称、上下文窗口、视觉能力和平台价格一起补入。与其他内置分组一样,同步新增的模型不会设置由用户管理的 `max_tokens` 覆盖值,而是沿用 Agent 设置。对已有条目会刷新三档平台价格和客户端协议;端点及其他由 Project 管理的配置不被覆盖,条目也不会被删除;纯 Embedding 条目不加入。与其他分组一样,`.project_config.toml` 记录的是牌价;平台的固定促销折扣由服务端存入 `web.db`,计算成本时从牌价中扣除,并显示为模型卡片的折扣标识。这些折扣只来自平台:「同步预置」不会写入,每次授权或「同步」都会整体替换。折扣记录丢失时按牌价计价,直到下一次授权或「同步」写回。平台返回的是 USD 每百万 Token 的峰值价格。当前内置的 Penguin Go DeepSeek 条目声明了与 DeepSeek 直连分组相同的北京时间空闲时段规则,因此模型卡片和成本记录会在工作日 9:00–12:00、14:00–18:00 之外按半价计算。++分组尚未配置平台 Key 时,「自动获取密钥」会在用户点击授权后创建一次性请求,并在新标签页打开 Penguin Go 授权页,由本地服务端完成轮询。浏览器只拿到授权 URL 和本地 flow id;设备密钥与交付的 API Key 都留在服务端。授权成功后会校验 `connection.apiKey`、端点和模型清单:Key 写入该分组全部既有模型,平台新增模型则连同推荐协议、端点、名称、上下文窗口、视觉能力和牌价一起加入,已有平台模型的价格和客户端协议同步为平台返回值,随后用平台返回的折扣整体替换该分组的促销折扣。同步会保留既有端点和其他由 Project 管理的配置,也不会删除模型;账户和余额不保存也不展示。++配置过平台 Key 后,分组会在「添加模型」左侧显示独立的「同步」动作,「自动获取密钥」仍然保留,方便改用另一个平台账户的 Key。「同步」使用已保存的 Key 请求平台最新模型清单,并补充新增模型、刷新已有模型的平台元数据;模型清单没有产生变化时保持配置文件不变。若平台返回 Key 已失效或被撤销,模型页会自动重新打开授权流程。Penguin Go 的网页登录会话和 API Key 是两套状态:网页登录过期不会阻止有效 Key 继续同步,只有 Key 本身无效时才需要重新授权。+## 授权新建 API key-若某个供应商公开了授权流程,模型页的该分组头部会多出一个动作:**自动获取密钥**。内置分组中只有 TokenDance 提供。它会在你的账户下**新建**一个 key,而不是读取你已有的 key,并写入该分组下的每一个模型,覆盖这些条目当前的 key。+若某个供应商提供自动授权取 Key,模型页的该分组头部会多出一个动作:**自动获取密钥**。内置分组中 TokenDance 与 Penguin Go 都提供,成功后都会把新 Key 写入该分组下每一个模型,覆盖这些条目当前的 Key。Penguin Go 授权成功后还会显示独立的「同步」动作,用于增量获取平台后来开放的模型;原授权动作仍可用于更换账户。-点击后会在新标签页打开供应商的授权页。在那里完成授权,供应商会把浏览器送回 PenguinHarness,由服务端兑换一次性授权码并保存 key;发起的那个标签页会自行报告结果。上文归因表中的同一个应用 URL 会写到这个 key 上,因此即便换用其他工具,用它发出的调用依然带着归因。+点击后会在新标签页打开供应商的授权页,发起操作的模型页对话框会等待并报告结果。TokenDance 使用 PKCE 回调与兑换;Penguin Go 使用设备授权的 start / poll 接口。协议差异只存在于服务端,前端交互与写入分组 Key 的结果一致。-整个兑换过程都在服务端进行:PKCE 的 verifier 在服务端生成、从不进入浏览器,新建出的 key 也直接写入模型表,不经过浏览器。一次授权只能换一个 key,且十分钟后过期。+整个过程都在服务端进行:PKCE verifier 或设备密钥从不进入浏览器,新建出的 Key 直接写入模型表。一次授权只能交付一个 Key,并按供应商返回的截止时间过期;PenguinHarness 本地流程最长保留十分钟。-如果跳转回不来——比如浏览器根本访问不到那个地址的服务——请选择**授权页跳不回来?改为手动填写授权码**。授权页会改为显示一次性授权码,粘贴到对话框即可完成同一套流程。+TokenDance 在跳转回不来时支持手动填写一次性授权码;Penguin Go 由模型页轮询平台状态,不需要也不提供手动授权码入口。-只有 Project owner 能发起授权,也只有他自己已登录的会话能完成授权——实际上就是打开着对话框的那个标签页。跳回地址本身不要求会话,也只能如此:供应商送回的浏览器未必就是你发起时的那一个。但跳回所做的只是把授权码交出来——在对话框去取结果之前,不会发生任何兑换,也不会有 key 被保存。完整的 key 只会出现一次,因此一旦保存失败,需要重新授权,并到供应商控制台删掉那个没用上的 key。+只有 Project owner 能发起授权。完整 Key 不会回传 Web 前端;若 Penguin Go 的本地写入失败,服务端会短暂保留这次单次交付,允许直接重试写入而不再次授权。## 本地 / 自建 OpenAI 兼容端点(如 vLLM)diff --git a/packages/docs/content/quickstart-docker.en.md b/packages/docs/content/quickstart-docker.en.mdindex f52dac67..83802636 100644--- a/packages/docs/content/quickstart-docker.en.md+++ b/packages/docs/content/quickstart-docker.en.md@@ -118,7 +118,7 @@ The full list is in the [Configuration Reference](/configuration); these are the| `PENGUIN_SEED_ADMIN_PASSWORD` | Pins the initial admin password, first boot only (see above) || `PENGUIN_TRUST_PROXY` | Set to `1` behind a TLS-terminating reverse proxy, so session cookies are marked `Secure` || `PENGUIN_PREVIEW_ORIGIN` | A second hostname routed to the same container, for Workspace HTML previews |-| `PENGUIN_UPDATE_CHECK` | `off` disables the release check — the server's only outbound non-model request |+| `PENGUIN_UPDATE_CHECK` | `off` disables the automatic release check; owner-initiated provider key authorization may still make outbound requests |### Behind a reverse proxydiff --git a/packages/docs/content/quickstart-docker.zh.md b/packages/docs/content/quickstart-docker.zh.mdindex d378b6b7..15ab7cfb 100644--- a/packages/docs/content/quickstart-docker.zh.md+++ b/packages/docs/content/quickstart-docker.zh.md@@ -118,7 +118,7 @@ USER penguin| `PENGUIN_SEED_ADMIN_PASSWORD` | 钉死初始管理员密码,仅首次启动生效(见上文) || `PENGUIN_TRUST_PROXY` | 在终结 TLS 的反向代理之后设为 `1`,使会话 Cookie 带上 `Secure` || `PENGUIN_PREVIEW_ORIGIN` | 指向同一容器的第二个主机名,用于 Workspace 的 HTML 预览 |-| `PENGUIN_UPDATE_CHECK` | `off` 关闭新版本检查——服务端唯一一个非模型的出网请求 |+| `PENGUIN_UPDATE_CHECK` | `off` 关闭自动版本检查;Owner 主动发起的供应商 Key 授权仍可能产生出网请求 |### 反向代理之后diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 70ad3c3e..9a81eac8 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -152,7 +152,7 @@ Refusals decided before any ssh runs have their own codes: `409` `install_runnin| POST | /api/version/update | **Admin only.** Starts the self-update job — `penguin update --yes` on the server host, in the background — unless one is running (then it is joined); answers with the status exactly as GET does. A finished run may be started again (a retry) || POST | /api/version/restart | **Admin only.** Asks the process to exit with the supervisor's restart code after a graceful shutdown, so `penguin server \| penguin web` relaunches it on the installed release: `{restarting: true}`; `{restarting: false, reason: "no_supervisor"}` when nothing supervises the process |-`update-check` is the server's only outbound internet call and is strictly fail-soft: a failed lookup still returns 200 with `error` set (`network` / `rate_limited` / `bad_response`) and `latestVersion: null`, results are cached in memory (success 1 h, failure 10 min), and setting `PENGUIN_UPDATE_CHECK=off` disables the lookup entirely (`disabled: true`, no network call). The update `status` is `updated` (restart the service to run the new version), `failed`, or `unsupported` — the latter both when the server was not started via `penguin server|web` (`reason: "not_launched_via_cli"`) and when the CLI refuses (source checkout, unrecognized install layout, Windows); `output` carries the tail of the CLI's own output.+`update-check` is the server's only automatic outbound internet call and is strictly fail-soft: a failed lookup still returns 200 with `error` set (`network` / `rate_limited` / `bad_response`) and `latestVersion: null`, results are cached in memory (success 1 h, failure 10 min), and setting `PENGUIN_UPDATE_CHECK=off` disables the lookup entirely (`disabled: true`, no network call). Owner-initiated provider key authorization makes its own outbound requests. The update `status` is `updated` (restart the service to run the new version), `failed`, or `unsupported` — the latter both when the server was not started via `penguin server|web` (`reason: "not_launched_via_cli"`) and when the CLI refuses (source checkout, unrecognized install layout, Windows); `output` carries the tail of the CLI's own output.### Projects and Members@@ -171,8 +171,8 @@ Member writes are owner-only. The member routes also answer `403 desktop_single_| Method | Path | Description || --- | --- | --- |-| GET | /api/projects/:projectId/models | List models (api_key masked) |-| PUT | /api/projects/:projectId/models | Full-table replace, keyed by `(provider, modelId)` |+| GET | /api/projects/:projectId/models | List models (api_key masked); a row with a running promotion carries it as `discount` |+| PUT | /api/projects/:projectId/models | Full-table replace, keyed by `(provider, modelId)`; an entry's `discount` stores or clears its promotion (see below) || POST | /api/projects/:projectId/models/test | Connectivity test: `{provider, modelId, …}` → `{ok, latencyMs?, message?}` || POST | /api/projects/:projectId/models/detect | Protocol auto-detection for a custom base URL: probes `openai-responses` → `ant-messages` → `openai-chat` in order, first on the URL as typed (normalized, a pasted endpoint path stripped) and then on its neighbouring `/v1` form, reporting the first served protocol and the base URL that served it: `{baseUrl, apiKey?, …}` → `{detected?, baseUrl?, probes}` || POST | /api/projects/:projectId/models/list | Endpoint model listing for the add-group import: the ids the endpoint serves on a detected protocol: `{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}` |@@ -180,8 +180,24 @@ Member writes are owner-only. The member routes also answer `403 desktop_single_Every endpoint that names a model takes the complete `(provider, modelId)` pair. Nothing is inferred: a request carrying only one half is a 400, never a lookup. Where the reference itself is optional (Session creation, Schedules), omitting both halves selects the Project's default model.+A row's `pricing` is always the list price. A promotion — a fraction in (0, 1) off that price — is not written to `.project_config.toml`: the server keeps it per row in `web.db` and takes it off when it prices usage. On `PUT /models`, an entry that carries `discount` gets exactly that: a number stores it, `null` clears it, and any other value is a 400 before anything is written. An entry that omits it keeps the stored promotion, unless the entry renames the row (`renamedFrom` naming a different pair) or its `pricing` differs from the stored one — then the promotion is cleared. Rows absent from the new table lose theirs.+`PUT /models` also invalidates the Project's cached Session runtimes (same effective-value semantics as a vault update): no hot swap into a run already in flight, but the next Task on any Session of the Project re-resumes and reads the new `api_key` / `base_url`. It additionally publishes a `credentials_updated` event to the Project's open Session channels (see Streaming below), and the models response carries `updatedAt` (the config file's mtime) — the Web App compares it against the last auth failure to decide whether an auth-dead composer should stay disabled.+#### Penguin Go key authorization++All routes are owner-only. The browser receives a local flow id and authorization URL, never the device secret, delivered API key, or other platform response fields. PenguinHarness validates the platform catalog server-side, writes the delivered key across existing `penguin-go` entries, and creates locally missing models from the platform metadata. Existing models refresh their platform list price and client protocol; endpoints and other Project-owned configuration are not overwritten, and models are never deleted. Once the Project model table is written, the platform's discounts replace the group's stored promotions in `web.db`; they are never persisted in `.project_config.toml`.++| Method | Path | Description |+| --- | --- | --- |+| POST | /api/projects/:projectId/platform-auth/start | Start a one-time authorization flow; its platform deadline is capped locally at ten minutes |+| POST | /api/projects/:projectId/platform-auth/sync | Fetch the platform catalog with the stored key, add locally missing models, and refresh existing platform-owned metadata; returns `added` / `updated` counts, or `platform_reauthorization_required` when that key is invalid |+| GET | /api/projects/:projectId/platform-auth/:flowId/status | Poll Penguin Go server-side, write the delivered key to the group, and add platform models |+| POST | /api/projects/:projectId/platform-auth/:flowId/retry | Retry only the local atomic write after an apply failure; does not request the single-use delivery again |+| POST | /api/projects/:projectId/platform-auth/:flowId/cancel | Cancel the local flow; the platform-side pending record expires by its TTL |++A completed write invalidates cached Project runtimes and publishes `credentials_updated`. A non-empty platform catalog can create the group when it is absent; `apply_failed` means the validated delivery could not be applied to local configuration, and its retry route repeats only that local write.+#### Provider key mintingOwner-only, except the redirect receiver `GET /callback`, which answers without a session and can do nothing but hand the code it was redirected with to the flow — see below. A provider group that publishes an authorization flow in the built-in catalog can mint a **new** API key for the user in the browser, instead of the user copying one out of a console.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 8dcd0bbd..2246a924 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -152,7 +152,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \| POST | /api/version/update | **仅管理员。**启动在线更新任务——在服务器上后台运行 `penguin update --yes`——已有任务在跑则并入;应答与 GET 完全一致。已结束的任务可以再次启动(即重试) || POST | /api/version/restart | **仅管理员。**请求进程在优雅关闭后以托管进程约定的重启退出码退出,由 `penguin server \| penguin web` 在已安装的版本上重新拉起:`{restarting: true}`;没有托管进程时为 `{restarting: false, reason: "no_supervisor"}` |-`update-check` 是服务端唯一的对外网络请求,并且严格失败兜底:查询失败仍返回 200,只是设置 `error`(`network` / `rate_limited` / `bad_response`)且 `latestVersion` 为 null;结果在内存中缓存(成功 1 小时、失败 10 分钟);设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭该查询(返回 `disabled: true`,不发起任何网络请求)。更新的 `status` 为 `updated`(需重启服务才能运行新版本)、`failed` 或 `unsupported` —— 后者包括服务不是通过 `penguin server|web` 启动(`reason: "not_launched_via_cli"`),以及 CLI 自身拒绝执行(源码运行、无法识别的安装方式、Windows);`output` 携带 CLI 输出的末尾片段。+`update-check` 是服务端唯一自动发起的对外网络请求,并且严格失败兜底:查询失败仍返回 200,只是设置 `error`(`network` / `rate_limited` / `bad_response`)且 `latestVersion` 为 null;结果在内存中缓存(成功 1 小时、失败 10 分钟);设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭该查询(返回 `disabled: true`,不发起任何网络请求)。Owner 主动发起的供应商 Key 授权会另外产生对外请求。更新的 `status` 为 `updated`(需重启服务才能运行新版本)、`failed` 或 `unsupported` —— 后者包括服务不是通过 `penguin server|web` 启动(`reason: "not_launched_via_cli"`),以及 CLI 自身拒绝执行(源码运行、无法识别的安装方式、Windows);`output` 携带 CLI 输出的末尾片段。### Project 与成员@@ -171,8 +171,8 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \| 方法 | 路径 | 说明 || --- | --- | --- |-| GET | /api/projects/:projectId/models | 模型列表(api_key 掩码显示) |-| PUT | /api/projects/:projectId/models | 全表替换,条目以 `(provider, modelId)` 为键 |+| GET | /api/projects/:projectId/models | 模型列表(api_key 掩码显示);有促销的行以 `discount` 携带其折扣 |+| PUT | /api/projects/:projectId/models | 全表替换,条目以 `(provider, modelId)` 为键;条目的 `discount` 写入或清除其促销折扣(见下文) || POST | /api/projects/:projectId/models/test | 连通性测试:`{provider, modelId, …}` → `{ok, latencyMs?, message?}` || POST | /api/projects/:projectId/models/detect | 自定义 base URL 的协议自动检测:按 `openai-responses` → `ant-messages` → `openai-chat` 顺序探测,先用整理后的 URL(整段端点路径会先被剥掉),再用它增删 `/v1` 后的形式,返回第一个被提供的协议与实际应答的 base URL:`{baseUrl, apiKey?, …}` → `{detected?, baseUrl?, probes}` || POST | /api/projects/:projectId/models/list | 新增分组导入所用的端点模型列表:按检测出的协议列出端点服务的全部模型 id:`{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}` |@@ -180,8 +180,24 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \所有涉及模型的接口都要求完整的 `(provider, modelId)` 二元组,不做任何推断:只带一半的请求一律 400,绝不会退化为一次查找。模型引用本身可省略的场景(创建 Session、定时任务)省略的是整对,两半都不给即选用 Project 默认模型。+行上的 `pricing` 恒为牌价。促销折扣是从牌价中扣除的比例,取值在 0 与 1 之间(不含两端),不写入 `.project_config.toml`,而由服务端按行存于 `web.db`、在计算成本时扣除。`PUT /models` 时,条目带 `discount` 即按其写入:数字写入,`null` 清除,其他取值在写入任何内容之前即返回 400。省略 `discount` 的条目保留已存折扣,但若条目改名(`renamedFrom` 指向另一对引用)或 `pricing` 与已存价格不同,则一并清除;新表中不再出现的行,折扣随之删除。+`PUT /models` 同时会使该 Project 已缓存的 Session 运行时失效(与 vault 更新同一套生效语义):进行中的运行不做热替换,但该 Project 下任何 Session 的下一个 Task 都会重新装载并读到新的 `api_key` / `base_url`。它还会向该 Project 已打开的 Session 通道发布 `credentials_updated` 事件(见下文「流式推送」),且模型响应携带 `updatedAt`(配置文件 mtime)——Web App 用它与最近一次鉴权失败的时间比较,决定鉴权失败的输入框是否继续禁用。+#### Penguin Go Key 授权++以下路由全部仅限 Owner。浏览器只会得到本地 flow id 与授权 URL,不会得到设备密钥、中转站交付的 API Key 或其他平台响应字段。PenguinHarness 在服务端校验平台模型清单,把交付的 Key 写入 `penguin-go` 既有条目,并按平台元数据创建本地缺失模型;已有模型会刷新平台牌价和客户端协议,端点及其他由 Project 管理的配置不会被覆盖,模型也不会被删除。Project 模型表写入后,平台返回的折扣会整体替换该分组存于 `web.db` 的促销折扣,从不写入 `.project_config.toml`。++| 方法 | 路径 | 说明 |+| --- | --- | --- |+| POST | /api/projects/:projectId/platform-auth/start | 开启一次性授权流程;按平台截止时间过期,本地最长保留十分钟 |+| POST | /api/projects/:projectId/platform-auth/sync | 使用已保存的 Key 获取平台模型清单,新增本地缺失模型并刷新已有模型的平台元数据;响应以 `added` / `updated` 返回数量,Key 无效时返回 `platform_reauthorization_required` |+| GET | /api/projects/:projectId/platform-auth/:flowId/status | 由服务端轮询中转站,把已交付 Key 写入模型组并新增平台模型 |+| POST | /api/projects/:projectId/platform-auth/:flowId/retry | 写入失败时仅重试本地原子写,不重复请求一次性交付 |+| POST | /api/projects/:projectId/platform-auth/:flowId/cancel | 取消本地流程;中转站的 pending 记录按自身 TTL 过期 |++成功写入后会使该 Project 的缓存运行时失效,并发布 `credentials_updated`。只要平台返回非空模型清单,分组不存在时也可以直接创建;`apply_failed` 表示通过校验的交付内容未能写入本地配置,重试接口只会再次执行这一步本地写入。+#### 授权新建 API key仅限 Owner,但供应商跳回的 `GET /callback` 例外——它无需会话即可应答,且只能把跳回时带来的授权码存到流程上,详见下文。若某个供应商分组在内置目录中声明了授权流程,用户可以在浏览器里授权并**新建**一个 API key,不必再去控制台复制。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 38481cba..685e0793 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -519,6 +519,8 @@ export interface ModelInfo {*/fastMode?: boolean;pricing?: ModelPricingDto;+ /** Running promotion for this row — a fraction in (0, 1) off `pricing`, which is the list price — read from web.db. Absent when the row has none. */+ discount?: number;/** Environment variable name to fall back to when api_key is empty (e.g. ANTHROPIC_API_KEY); unset if no known fallback. */envKey?: string;/**@@ -577,6 +579,12 @@ export interface ModelUpdateEntry {/** Per-model fast mode: only `true` is persisted; omitted or `false` clears the annotation (absent = off). */fastMode?: boolean;pricing?: ModelPricingDto;+ /**+ * Promotion to store for this row, a fraction in (0, 1) off `pricing`; `null` clears it. Omitted+ * keeps the stored promotion — unless this entry renames the row or changes its pricing, which+ * clears it.+ */+ discount?: number | null;/** Providing it overwrites and updates createdAt; omitting it keeps the existing value. */apiKey?: string;/** When true, clears the stored api_key. */@@ -848,6 +856,37 @@ export interface ModelOAuthCodeResponse {error?: ModelOAuthErrorCode;}+// ---------------------------------------------------------------------------+// Penguin Go key authorization (/api/projects/:p/platform-auth, owner)+// ---------------------------------------------------------------------------++export interface PlatformAuthStartResponse {+ flowId: string;+ authorizeUrl: string;+ expiresAt: string;+}++export type PlatformAuthFlowErrorCode =+ | "unreachable"+ | "upstream_failed"+ | "invalid_key"+ | "expired"+ | "locked"+ | "already_delivered"+ | "apply_failed";++export interface PlatformAuthFlowStatusResponse {+ status: "pending" | "applying" | "completed" | "cancelled" | "apply_failed" | "error";+ error?: PlatformAuthFlowErrorCode;+ applied?: number;+}++/** Result of refreshing Penguin Go's catalog with the Project's stored platform key. */+export interface PlatformModelSyncResponse extends ModelsResponse {+ added: number;+ updated: number;+}+// ---------------------------------------------------------------------------// New-chat defaults (the `[default_chat]` block of .project_config.toml)// ---------------------------------------------------------------------------diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex a404410d..42a37ae9 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -39,6 +39,8 @@ export interface ServerConfig {* derived per request instead.*/previewOrigin: string | null;+ /** Trusted Penguin Go origin; never supplied by a browser request. */+ penguinGoOrigin: 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@@ -146,7 +148,35 @@ function normalizePreviewOrigin(raw: string | undefined): string | null {return url.origin;}-/** Parses server config from environment variables (PORT / HOST / PENGUIN_HOME / PENGUIN_WEB_DIST / PENGUIN_WEB_DB / PENGUIN_PREVIEW_ORIGIN / PENGUIN_SEED_ADMIN_PASSWORD / PENGUIN_DESKTOP_TOKEN / PENGUIN_PORT_FILE / PENGUIN_TRUST_PROXY / PENGUIN_CLI_ENTRY). */+/** HTTPS in production; plain HTTP is accepted only for an explicit loopback integration. */+export function normalizePenguinGoOrigin(raw: string | undefined): string {+ const value = raw?.trim() || "https://token.penguin.ooo";+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ throw new Error(`Invalid PENGUIN_GO_ORIGIN=${value} (expected an absolute HTTP(S) origin)`);+ }+ if (+ url.username !== "" ||+ url.password !== "" ||+ url.pathname !== "/" ||+ url.search !== "" ||+ url.hash !== ""+ ) {+ throw new Error(+ `Invalid PENGUIN_GO_ORIGIN=${value} (paths, credentials, query and fragment are not allowed)`,+ );+ }+ const loopback =+ url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {+ throw new Error(`Invalid PENGUIN_GO_ORIGIN=${value} (HTTPS required except for loopback HTTP)`);+ }+ 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). */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@@ -169,6 +199,7 @@ export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): ServedbPath: env.PENGUIN_WEB_DB ?? path.join(root, "web.db"),webDist: env.PENGUIN_WEB_DIST ?? defaultWebDist(),previewOrigin: normalizePreviewOrigin(env.PENGUIN_PREVIEW_ORIGIN),+ penguinGoOrigin: normalizePenguinGoOrigin(env.PENGUIN_GO_ORIGIN),// 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.tsindex 29f83f96..565aa2f1 100644--- a/packages/server/src/db/migrations.ts+++ b/packages/server/src/db/migrations.ts@@ -432,6 +432,34 @@ export const MIGRATIONS: readonly Migration[] = [`);},},+ {+ version: 9,+ name: "model-promotions",+ // Additive: one new table, nothing existing touched. A predecessor build never reads it+ // and prices every row at the number in its Project file, so a rollback survives it.+ swapSafe: true,+ up(db) {+ // Frozen copy of the DDL as of the model-promotions 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_promotions ( -- NOT a cache rebuildable from files: the only record of a Project row's running promotion (.project_config.toml keeps the list price), written by preset seeding at Project creation, "sync presets" and Penguin Go authorization / sync, and read by cost; lost rows price usage at list until the next sync writes them back+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,+ provider TEXT NOT NULL,+ model_id TEXT NOT NULL,+ discount REAL NOT NULL CHECK (discount > 0 AND discount < 1),+ updated_at TEXT NOT NULL,+ PRIMARY KEY (project_id, provider, model_id)+ );+ `);+ },+ // LOSES every stored promotion: no file holds a copy of the fractions, so usage is priced+ // at the Project files' list prices until the next "sync presets" or Penguin Go sync+ // writes them back.+ down(db) {+ db.exec("DROP TABLE IF EXISTS model_promotions");+ },+ },];/** The highest version this build knows how to reach. */diff --git a/packages/server/src/db/repos/model-promotions.ts b/packages/server/src/db/repos/model-promotions.tsnew file mode 100644index 00000000..c7be44f3--- /dev/null+++ b/packages/server/src/db/repos/model-promotions.ts@@ -0,0 +1,81 @@+/**+ * Per-Project model promotions: the fraction off a row's list price its seller is running.+ *+ * Not a cache. `.project_config.toml` keeps only the list price, so these rows are the one+ * record of each promotion: preset seeding, "sync presets" and Penguin Go authorization / sync+ * write them, cost reads them, and a row lost here prices that model at list until one of+ * those writers runs again. Both replace methods swap their whole set in one transaction, so+ * a reader never sees half of one.+ */+import { Component, Use } from "@prismshadow/penguin-core/kernel";+import type { Db } from "../../hmr/capabilities.js";+import type { ModelPromotion, ModelPromotions } from "../../mechanisms/projects.js";++@Component()+export class ModelPromotionsRepo implements ModelPromotions {+ @Use() private readonly db!: Db;++ get(projectId: string, provider: string, modelId: string): number | undefined {+ const r = this.db+ .prepare(+ "SELECT discount FROM model_promotions WHERE project_id = ? AND provider = ? AND model_id = ?",+ )+ .get(projectId, provider, modelId);+ return r ? (r.discount as number) : undefined;+ }++ list(projectId: string): ModelPromotion[] {+ return this.db+ .prepare("SELECT provider, model_id, discount FROM model_promotions WHERE project_id = ?")+ .all(projectId)+ .map((r) => ({+ provider: r.provider as string,+ modelId: r.model_id as string,+ discount: r.discount as number,+ }));+ }++ replaceAll(projectId: string, rows: readonly ModelPromotion[]): void {+ this.replace(projectId, undefined, rows);+ }++ replaceProvider(projectId: string, provider: string, rows: readonly ModelPromotion[]): void {+ this.replace(projectId, provider, rows);+ }++ /** Deletes the Project's rows (one group's, when `provider` is given) and inserts `rows`, atomically. */+ private replace(+ projectId: string,+ provider: string | undefined,+ rows: readonly ModelPromotion[],+ ): void {+ this.db.exec("BEGIN IMMEDIATE");+ try {+ if (provider === undefined) {+ this.db.prepare("DELETE FROM model_promotions WHERE project_id = ?").run(projectId);+ } else {+ this.db+ .prepare("DELETE FROM model_promotions WHERE project_id = ? AND provider = ?")+ .run(projectId, provider);+ }+ const insert = this.db.prepare(+ `INSERT INTO model_promotions (project_id, provider, model_id, discount, updated_at)+ VALUES (?, ?, ?, ?, ?)`,+ );+ const updatedAt = new Date().toISOString();+ for (const row of rows) {+ // A group's replace must not reach into another group's rows it never deleted.+ if (provider !== undefined && row.provider !== provider) {+ throw new Error(+ `A ${provider} promotion replace was given a ${row.provider} row: ${row.modelId}.`,+ );+ }+ insert.run(projectId, row.provider, row.modelId, row.discount, updatedAt);+ }+ this.db.exec("COMMIT");+ } catch (error) {+ this.db.exec("ROLLBACK");+ throw error;+ }+ }+}diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.tsindex 303fd9b2..5339ceb4 100644--- a/packages/server/src/db/schema.ts+++ b/packages/server/src/db/schema.ts@@ -12,6 +12,16 @@* idx_usage_session_ts): CREATE INDEX IF NOT EXISTS never rebuilds an existing index either.*/+export const MODEL_PROMOTIONS_SQL = `+CREATE TABLE IF NOT EXISTS model_promotions ( -- NOT a cache rebuildable from files: the only record of a Project row's running promotion (.project_config.toml keeps the list price), written by preset seeding at Project creation, "sync presets" and Penguin Go authorization / sync, and read by cost; lost rows price usage at list until the next sync writes them back+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,+ provider TEXT NOT NULL,+ model_id TEXT NOT NULL,+ discount REAL NOT NULL CHECK (discount > 0 AND discount < 1), -- fraction off the row's list price: billed = list × (1 − discount)+ updated_at TEXT NOT NULL,+ PRIMARY KEY (project_id, provider, model_id)+);`;+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}$@@ -48,6 +58,7 @@ CREATE TABLE IF NOT EXISTS project_members ( -- member grants only; owners arecreated_at TEXT NOT NULL,PRIMARY KEY (project_id, user_id));+${MODEL_PROMOTIONS_SQL}CREATE TABLE IF NOT EXISTS agents ( -- index only; name/description live in system_config.yamlproject_id TEXT NOT NULL,agent_id TEXT NOT NULL,diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.tsindex 581e2c79..999f52a7 100644--- a/packages/server/src/hmr/capabilities.ts+++ b/packages/server/src/hmr/capabilities.ts@@ -114,6 +114,7 @@ export const HMR_INTERFACES: HmrInterfaces = {"portFile","trustProxy","supervised",+ "penguinGoOrigin",],db: ["prepare", "exec", "close"],channels: ["get", "peek", "broadcast", "dispose", "setActivityProbe"],diff --git a/packages/server/src/http/errors.ts b/packages/server/src/http/errors.tsindex 983614fc..24f4579a 100644--- a/packages/server/src/http/errors.ts+++ b/packages/server/src/http/errors.ts@@ -14,6 +14,7 @@ export class HttpError extends Error {readonly status: number,readonly code: string,message: string,+ readonly retryAfterSeconds?: number,) {super(message);this.name = "HttpError";@@ -47,6 +48,9 @@ export function modelCredentialMissing(modelId: string): HttpError {/** app.onError handler: maps HttpError through as-is; everything else is logged and converged to 500. */export function handleError(err: Error, c: Context): Response {if (err instanceof HttpError) {+ if (err.retryAfterSeconds !== undefined) {+ c.header("Retry-After", String(err.retryAfterSeconds));+ }return c.json(errorBody(err.code, err.message), err.status as 400);}// Unknown error: print the stack for diagnosis, but never expose details externally.diff --git a/packages/server/src/http/routes/models.ts b/packages/server/src/http/routes/models.tsindex fe39d327..89695222 100644--- a/packages/server/src/http/routes/models.ts+++ b/packages/server/src/http/routes/models.ts@@ -166,6 +166,13 @@ function parseModelsUpdate(body: Record<string, unknown>): ModelsUpdateRequest {output: p.output as number,};}+ // The promotion stored for this row (null clears it); the service checks the range.+ if (m.discount !== undefined) {+ if (m.discount !== null && typeof m.discount !== "number") {+ throw badRequest(`models[${i}].discount must be null or a number above 0 and below 1.`);+ }+ entry.discount = m.discount;+ }if (m.apiKey !== undefined) {if (typeof m.apiKey !== "string" || m.apiKey.length === 0) {throw badRequest(`models[${i}].apiKey must be a non-empty string.`);diff --git a/packages/server/src/http/routes/platform-auth.ts b/packages/server/src/http/routes/platform-auth.tsnew file mode 100644index 00000000..6243f710--- /dev/null+++ b/packages/server/src/http/routes/platform-auth.ts@@ -0,0 +1,105 @@+/** Project-owner routes for authorizing a Penguin Go key. */+import { Hono } from "hono";+import type {+ PlatformAuthFlowStatusResponse,+ PlatformAuthStartResponse,+ PlatformModelSyncResponse,+} from "../../api/types.js";+import type { AppEnv } from "../../auth/middleware.js";+import type { PlatformAuth } from "../../services/platform-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 PlatformAuthRouteDeps extends ModelsRouteDeps {+ platformAuth: PlatformAuth;+}++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,+ "platform_auth_flow_not_found",+ "This login has expired or does not exist.",+ );+ }+ return value;+}++function owner(deps: PlatformAuthRouteDeps, userId: string, projectId: string): void {+ deps.access.requireProjectOwner(userId, projectId);+}++function publishIfChanged(deps: PlatformAuthRouteDeps, projectId: string, changed: boolean): void {+ if (changed) modelConfigChanged(deps, projectId);+}++export function platformAuthRoutes(deps: PlatformAuthRouteDeps): 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.platformAuth.start({+ projectId,+ userId: c.var.user.userId,+ })) satisfies PlatformAuthStartResponse,+ 201,+ );+ });++ app.post("/sync", async (c) => {+ const projectId = requireValidId(c, "projectId");+ owner(deps, c.var.user.userId, projectId);+ const synced = await deps.platformAuth.sync(projectId);+ publishIfChanged(deps, projectId, synced.added > 0 || synced.updated > 0);+ return c.json({+ ...(await deps.projectConfigService.getModels(projectId)),+ added: synced.added,+ updated: synced.updated,+ } satisfies PlatformModelSyncResponse);+ });++ app.get("/:flowId/status", async (c) => {+ const projectId = requireValidId(c, "projectId");+ owner(deps, c.var.user.userId, projectId);+ const result = await deps.platformAuth.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 PlatformAuthFlowStatusResponse);+ });++ app.post("/:flowId/retry", async (c) => {+ const projectId = requireValidId(c, "projectId");+ owner(deps, c.var.user.userId, projectId);+ const result = await deps.platformAuth.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 PlatformAuthFlowStatusResponse);+ });++ app.post("/:flowId/cancel", (c) => {+ const projectId = requireValidId(c, "projectId");+ owner(deps, c.var.user.userId, projectId);+ deps.platformAuth.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.tsindex 8f9c5518..ef2f1dad 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -117,11 +117,13 @@ import { agentConfigRoutes } from "./agent-config.js";import { vaultRoutes } from "./vault.js";import { modelsRoutes } from "./models.js";import { modelOAuthCallbackRoutes, modelOAuthRoutes } from "./model-oauth.js";+import { platformAuthRoutes } from "./platform-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 { Schedules, SessionIndex, SessionOrigins } from "../../mechanisms/sessions.js";import type { ErrorLog, UsageQueries } from "../../mechanisms/observability.js";import type { TraceIndex, Traces } from "../../mechanisms/traces.js";@@ -1590,6 +1592,12 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {auth: "user",order: 110,},+ {+ id: "session-api.platform-auth",+ prefix: "/api/projects/:projectId/platform-auth",+ auth: "user",+ order: 115,+ },{id: "session-api.chat-defaults",prefix: "/api/projects/:projectId/chat-defaults",@@ -1654,6 +1662,7 @@ export class SessionApiRoutes {@Use() private readonly access!: Access;@Use() private readonly projectConfig!: ProjectConfigStore;@Use() private readonly modelOAuth!: ModelOAuth;+ @Use() private readonly platformAuth!: PlatformAuth;@Use() private readonly traceIndex!: TraceIndex;@Use() private readonly traces!: Traces;@Use() private readonly workspaceFiles!: WorkspaceFiles;@@ -1668,6 +1677,7 @@ export class SessionApiRoutes {@Bind("session-api.model-oauth-callback") modelOauthCallbackRoutes!: Hono<AppEnv>;@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.chat-defaults") chatDefaultsRoutes!: Hono<AppEnv>;@Bind("session-api.command-policy") commandPolicyRoutes!: Hono<AppEnv>;@Bind("session-api.agents") agentsRoutes!: Hono<AppEnv>;@@ -1714,16 +1724,18 @@ export class SessionApiRoutes {projectConfigService,sessionsRepo,};- this.modelOauthCallbackRoutes = modelOAuthCallbackRoutes(modelOAuthDeps);- this.modelsRoutes = modelsRoutes({+ const modelDeps = {channels,manager,machines: this.machines,projectConfigService,access,sessionsRepo,- });+ };+ this.modelOauthCallbackRoutes = modelOAuthCallbackRoutes(modelOAuthDeps);+ this.modelsRoutes = modelsRoutes(modelDeps);this.modelOauthRoutes = modelOAuthRoutes(modelOAuthDeps);+ this.platformAuthRoutes = platformAuthRoutes({ ...modelDeps, platformAuth: this.platformAuth });this.chatDefaultsRoutes = chatDefaultsRoutes({agentConfigService,projectConfigService,diff --git a/packages/server/src/mechanisms/projects.ts b/packages/server/src/mechanisms/projects.tsindex 6e9edd86..67437381 100644--- a/packages/server/src/mechanisms/projects.ts+++ b/packages/server/src/mechanisms/projects.ts@@ -32,6 +32,10 @@ import type {ProjectConfig,} from "@prismshadow/penguin-core";import type { TieredRates } from "../services/usage-service.js";+import type {+ PlatformModelApplyResult,+ PlatformModelCatalog,+} from "../services/platform-auth-types.js";import type {ModelOAuthErrorCode,ModelOAuthMode,@@ -99,7 +103,8 @@ export abstract class ProjectConfigStore extends Interface<{loadConfig(projectId: string): Promise<ProjectConfig>;writeRaw(projectId: string, data: RawTable): Promise<void>;writeInitialConfig(projectId: string, name: string): Promise<void>;- ensurePresetModels(projectId: string): Promise<void>;+ ensurePresetModels(projectId: string): Promise<boolean>;+ seedPresetPromotions(projectId: string): Promise<void>;getName(projectId: string): Promise<string | undefined>;setName(projectId: string, name: string): Promise<void>;getDefaultModelRef(projectId: string): Promise<ModelRef | undefined>;@@ -140,9 +145,33 @@ 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>;+ getGroupApiKey(projectId: string, provider: string): Promise<string | undefined>;+ mergePlatformModels(+ projectId: string,+ provider: string,+ catalog: PlatformModelCatalog,+ apiKey: string,+ applyKeyToExisting: boolean,+ ): Promise<PlatformModelApplyResult>;completeOnce(projectId: string, prompt: string): Promise<UtilityCompletion>;}>() {}+export interface ModelPromotion {+ provider: string;+ modelId: string;+ discount: number;+}++/** Per-Project model promotions (web.db `model_promotions`). */+export abstract class ModelPromotions extends Interface<{+ get(projectId: string, provider: string, modelId: string): number | undefined;+ list(projectId: string): ModelPromotion[];+ /** Replaces every promotion of the Project, in one transaction. */+ replaceAll(projectId: string, rows: readonly ModelPromotion[]): void;+ /** Replaces the promotions of one provider group, in one transaction. */+ replaceProvider(projectId: string, provider: string, rows: readonly ModelPromotion[]): 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.tsindex 068b0f42..a2387d07 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -67,6 +67,7 @@ import { ServerSettingsRepo } from "./db/repos/server-settings.js";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 { MembersRepo } from "./db/repos/members.js";import { AgentsRepo } from "./db/repos/agents.js";import { UsageRepo } from "./db/repos/usage.js";@@ -81,6 +82,7 @@ import { UsageRecorder } from "./runtime/usage-recorder.js";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 { TraceIndexService } from "./services/trace-index.js";import { TraceService } from "./services/trace-service.js";import { WorkspaceFilesService } from "./services/workspace-files-service.js";@@ -250,12 +252,14 @@ export class IdentityModule {}@Module({children: [ProjectsRepo,+ ModelPromotionsRepo,MembersRepo,AgentsRepo,ProjectAccess,ProjectService,ProjectConfigService,ModelOAuthService,+ PlatformAuthProvider,ProjectsRoutes,ProjectAdminRoutes,],@@ -267,6 +271,7 @@ export class IdentityModule {}ProjectLifecycle,ProjectConfigStore,ModelOAuth,+ PlatformAuth,InitialProjectProvisioner,],})diff --git a/packages/server/src/services/platform-auth-service.ts b/packages/server/src/services/platform-auth-service.tsnew file mode 100644index 00000000..f8b42cb1--- /dev/null+++ b/packages/server/src/services/platform-auth-service.ts@@ -0,0 +1,619 @@+/**+ * Project-scoped Penguin Go key authorization.+ *+ * The Web App presents this like any other provider's "authorize a key" action. Penguin Go's+ * wire protocol is different from OAuth/PKCE, though: the server registers a device secret,+ * polls the one-time delivery, validates its API key and model catalog, then adds newly+ * advertised models while writing the key across the provider group. Account and balance+ * metadata remain outside PenguinHarness.+ */+import { randomBytes } from "node:crypto";+import { Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";+import { PENGUIN_GO_PROVIDER_ID } from "@prismshadow/penguin-core/model-catalog";+import { HttpError } from "../http/errors.js";+import { Config } from "../hmr/capabilities.js";+import type { ProjectConfigStore } from "../mechanisms/projects.js";+import type { PlatformAuthFlowStatusResponse } from "../api/types.js";+import {+ PLATFORM_CLIENT_ID,+ type PlatformCatalogPricing,+ type PlatformModelApplyResult,+ type PlatformModelCatalog,+} from "./platform-auth-types.js";++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_API_KEY_LENGTH = 1024;+const MAX_CATALOG_MODELS = 512;+const MAX_MODEL_ID_LENGTH = 256;+const MAX_DISPLAY_NAME_LENGTH = 256;+const MAX_ENDPOINT_LENGTH = 2048;+const DEFAULT_RETRY_AFTER_MS = 1_000;+const MAX_RETRY_AFTER_MS = 60_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?: PlatformAuthFlowStatusResponse["error"];+ applied?: number;+ apiKey?: string;+ catalog?: PlatformModelCatalog;+ polling?: Promise<void>;+ retryPollAt?: number;+ changed?: boolean;+}++export type PlatformAuthStatusResult = PlatformAuthFlowStatusResponse & { changed?: true };++interface PlatformAuthDeps {+ origin: string;+ getKey: (projectId: string) => Promise<string | undefined>;+ applyCatalog: (+ projectId: string,+ catalog: PlatformModelCatalog,+ apiKey: string,+ applyKeyToExisting: boolean,+ ) => Promise<PlatformModelApplyResult>;+ 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("Platform response is too large.");+ throw new Error("Platform 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 platform returned an invalid ${label}.`);+ }+ return value;+}++function platformEndpoint(value: unknown): string {+ const raw = requiredString(value, MAX_ENDPOINT_LENGTH, "endpoint");+ const parsed = new URL(raw);+ if (+ (parsed.protocol !== "http:" && parsed.protocol !== "https:") ||+ parsed.username ||+ parsed.password+ ) {+ throw new Error("The platform returned an invalid endpoint.");+ }+ return raw.replace(/\/+$/, "");+}++function platformPrice(value: unknown, label: string): number {+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {+ throw new Error(`The platform returned an invalid ${label} price.`);+ }+ return value;+}++function platformPricing(value: unknown, label: string): PlatformCatalogPricing {+ const pricing = asRecord(value);+ if (pricing.unit !== "usd_per_mtok") {+ throw new Error(`The platform returned an unsupported ${label} pricing unit.`);+ }+ return {+ unit: "usd_per_mtok",+ cacheRead: platformPrice(pricing.cacheRead, `${label} cache read`),+ cacheWrite: platformPrice(pricing.cacheWrite, `${label} cache write`),+ output: platformPrice(pricing.output, `${label} output`),+ };+}++/**+ * The promotion a platform model carries, if any: its list price and the fraction off it. The+ * wire sends both or neither, and the billed `pricing` must be that list price less the fraction.+ */+function platformPromotion(+ model: Record<string, unknown>,+ billed: PlatformCatalogPricing,+): { listPricing: PlatformCatalogPricing; discount: number } | undefined {+ const hasListPricing = model.listPricing !== undefined;+ const hasDiscount = model.discount !== undefined;+ if (hasListPricing !== hasDiscount) {+ throw new Error("The platform returned incomplete discount metadata.");+ }+ if (!hasListPricing) return undefined;+ if (+ typeof model.discount !== "number" ||+ !Number.isFinite(model.discount) ||+ model.discount <= 0 ||+ model.discount >= 1+ ) {+ throw new Error("The platform returned an invalid discount.");+ }+ const discount = model.discount;+ const listPricing = platformPricing(model.listPricing, "list");+ const close = (actual: number, list: number): boolean =>+ Math.abs(actual - list * (1 - discount)) <= 1e-9 * Math.max(1, Math.abs(actual));+ if (+ !close(billed.cacheRead, listPricing.cacheRead) ||+ !close(billed.cacheWrite, listPricing.cacheWrite) ||+ !close(billed.output, listPricing.output)+ ) {+ throw new Error("The platform returned inconsistent discount metadata.");+ }+ return { listPricing, discount };+}++function platformCatalog(value: unknown, requireEnvelope: boolean): PlatformModelCatalog {+ const body = asRecord(value);+ if (requireEnvelope && body.schemaVersion !== 1) {+ throw new Error("The platform returned an unsupported model catalog.");+ }+ if (requireEnvelope) requiredString(body.catalogVersion, 128, "catalog version");+ const endpoints = asRecord(body.endpoints);+ const endpointByName = {+ openai: platformEndpoint(endpoints.openai),+ google: platformEndpoint(endpoints.google),+ } as const;+ if (!Array.isArray(body.models) || body.models.length > MAX_CATALOG_MODELS) {+ throw new Error("The platform returned an invalid model catalog.");+ }+ const seen = new Set<string>();+ const models = body.models.map((value) => {+ const model = asRecord(value);+ const modelId = requiredString(model.modelId, MAX_MODEL_ID_LENGTH, "model id");+ if (seen.has(modelId)) throw new Error("The platform returned duplicate model ids.");+ seen.add(modelId);+ const displayName = requiredString(+ model.displayName,+ MAX_DISPLAY_NAME_LENGTH,+ "model display name",+ );+ const contextWindow = model.contextWindow;+ if (!Number.isSafeInteger(contextWindow) || Number(contextWindow) <= 0) {+ throw new Error("The platform returned an invalid context window.");+ }+ const maxOutputTokens = model.maxOutputTokens;+ if (+ maxOutputTokens !== undefined &&+ (!Number.isSafeInteger(maxOutputTokens) || Number(maxOutputTokens) <= 0)+ ) {+ throw new Error("The platform returned an invalid maximum output length.");+ }+ if (typeof model.supportsVision !== "boolean") {+ throw new Error("The platform returned an invalid vision capability.");+ }+ const billed = platformPricing(model.pricing, "effective");+ const promotion = platformPromotion(model, billed);+ const route = asRecord(model.recommendedRoute);+ const provider = model.provider;+ const googleRoute =+ provider === "google" &&+ route.protocol === "google-generative-language" &&+ route.endpoint === "google";+ const deepSeekRoute =+ provider === "deepseek" &&+ route.protocol === "deepseek-responses" &&+ route.endpoint === "openai";+ if (!googleRoute && !deepSeekRoute) {+ throw new Error("The platform returned an unsupported model route.");+ }+ return {+ modelId,+ displayName,+ contextWindow: Number(contextWindow),+ supportsVision: model.supportsVision,+ // A Project stores the list price; the promotion travels apart, as the fraction.+ pricing: promotion?.listPricing ?? billed,+ ...(promotion !== undefined ? { discount: promotion.discount } : {}),+ baseUrl: endpointByName[googleRoute ? "google" : "openai"],+ clientType: googleRoute ? ("gemini-3.8" as const) : ("deepseek-v4" as const),+ };+ });+ return { models };+}++/** Validates the one-time authorization payload and extracts only connection data. */+export function platformConnection(value: unknown): {+ apiKey: string;+ catalog: PlatformModelCatalog;+} {+ const body = asRecord(value);+ const client = asRecord(body.client);+ if (client.id !== PLATFORM_CLIENT_ID) throw new Error("The platform returned another client.");+ const connection = asRecord(body.connection);+ return {+ apiKey: requiredString(connection.apiKey, MAX_API_KEY_LENGTH, "API key"),+ catalog: platformCatalog(connection, false),+ };+}++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 PlatformAuthService {+ private readonly flows = new Map<string, Flow>();+ private readonly fetchImpl: typeof fetch;+ private readonly now: () => number;++ constructor(private readonly deps: PlatformAuthDeps) {+ this.fetchImpl = deps.fetchImpl ?? ((...args) => fetch(...args));+ this.now = deps.now ?? (() => Date.now());+ }++ private url(path: string): string {+ return `${this.deps.origin}${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 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("/api/auth/desktop/start", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ code, deviceSecret, client: { id: PLATFORM_CLIENT_ID } }),+ });+ } catch {+ throw new HttpError(502, "platform_unreachable", "Penguin Go 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,+ "platform_rate_limited",+ "Penguin Go is receiving too many authorization requests. Try again shortly.",+ retryAfter,+ );+ }+ if (response.status !== 201) {+ throw new HttpError(502, "platform_start_failed", "Penguin Go refused the key flow.");+ }+ let body: Record<string, unknown>;+ try {+ body = asRecord(await readJsonBounded(response));+ } catch {+ throw new HttpError(502, "platform_start_failed", "Penguin Go 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, "platform_start_failed", "Penguin Go returned an invalid expiry.");+ }+ this.evictOldest(input.userId, input.projectId);+ const authorizeUrl = `${this.deps.origin}/desktop/authorize?code=${encodeURIComponent(code)}`;+ 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<PlatformAuthStatusResult> {+ const flow = this.requireFlow(input);+ if (+ flow.status === "pending" &&+ (flow.retryPollAt === undefined || flow.retryPollAt <= this.now())+ ) {+ flow.polling ??= this.pollPlatform(flow).finally(() => {+ flow.polling = undefined;+ });+ await flow.polling;+ }+ return this.publicFlow(flow);+ }++ async retryApply(input: {+ flowId: string;+ projectId: string;+ userId: string;+ }): Promise<PlatformAuthStatusResult> {+ const flow = this.requireFlow(input);+ if (flow.status !== "apply_failed" || flow.apiKey === undefined || flow.catalog === undefined) {+ throw new HttpError(409, "platform_auth_not_retryable", "This key cannot be applied again.");+ }+ await this.apply(flow);+ return this.publicFlow(flow);+ }++ /** Refreshes the platform catalog with the Project's existing key, without a browser login. */+ async sync(projectId: string): Promise<PlatformModelApplyResult> {+ const apiKey = await this.deps.getKey(projectId);+ if (apiKey === undefined) {+ throw new HttpError(+ 409,+ "platform_reauthorization_required",+ "Penguin Go authorization is required.",+ );+ }+ let response: Response;+ try {+ response = await this.request("/api/client/models", {+ method: "GET",+ headers: { authorization: `Bearer ${apiKey}` },+ });+ } catch {+ throw new HttpError(502, "platform_unreachable", "Penguin Go could not be reached.");+ }+ if (response.status === 401 || response.status === 403) {+ throw new HttpError(+ 409,+ "platform_reauthorization_required",+ "The Penguin Go key is no longer valid. Authorize it again.",+ );+ }+ if (!response.ok) {+ throw new HttpError(502, "platform_sync_failed", "Penguin Go refused model sync.");+ }+ let catalog: PlatformModelCatalog;+ try {+ catalog = platformCatalog(await readJsonBounded(response), true);+ } catch {+ throw new HttpError(+ 502,+ "platform_sync_failed",+ "Penguin Go returned an invalid model catalog.",+ );+ }+ return this.deps.applyCatalog(projectId, catalog, apiKey, false);+ }++ 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,+ "platform_auth_flow_used",+ "This key flow can no longer be cancelled.",+ );+ }+ flow.status = "cancelled";+ flow.code = null;+ flow.deviceSecret = null;+ flow.apiKey = undefined;+ flow.catalog = undefined;+ }++ private async pollPlatform(flow: Flow): Promise<void> {+ if (!this.isPending(flow) || flow.code === null || flow.deviceSecret === null) return;+ let response: Response;+ try {+ response = await this.request("/api/auth/desktop/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 === "claimed") {+ try {+ const connection = platformConnection(body);+ flow.apiKey = connection.apiKey;+ flow.catalog = connection.catalog;+ } catch {+ flow.status = "error";+ flow.error = "invalid_key";+ flow.code = null;+ flow.deviceSecret = null;+ return;+ }+ 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.apiKey === undefined || flow.catalog === undefined) return;+ flow.status = "applying";+ flow.error = undefined;+ try {+ const result = await this.deps.applyCatalog(flow.projectId, flow.catalog, flow.apiKey, true);+ if (result.applied === 0) throw new Error("The Penguin Go catalog is empty.");+ flow.applied = result.applied;+ flow.apiKey = undefined;+ flow.catalog = undefined;+ flow.status = "completed";+ flow.changed = true;+ } catch {+ flow.status = "apply_failed";+ flow.error = "apply_failed";+ }+ }++ private publicFlow(flow: Flow): PlatformAuthStatusResult {+ 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,+ "platform_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 key authorization capability consumed by Project model routes. */+export abstract class PlatformAuth extends Interface<+ Pick<PlatformAuthService, "start" | "status" | "retryApply" | "sync" | "cancel">+>() {}++/** Keep in-flight flows on the current platform App, like ModelOAuthService. */+@Module()+export class PlatformAuthProvider {+ @Use() private readonly config!: Config;+ @Use() private readonly projectConfig!: ProjectConfigStore;+ @Provide() auth!: PlatformAuth;++ setup() {+ this.auth = new PlatformAuthService({+ origin: this.config.penguinGoOrigin,+ getKey: (projectId) => this.projectConfig.getGroupApiKey(projectId, PENGUIN_GO_PROVIDER_ID),+ applyCatalog: (projectId, catalog, apiKey, applyKeyToExisting) =>+ this.projectConfig.mergePlatformModels(+ projectId,+ PENGUIN_GO_PROVIDER_ID,+ catalog,+ apiKey,+ applyKeyToExisting,+ ),+ });+ }+}diff --git a/packages/server/src/services/platform-auth-types.ts b/packages/server/src/services/platform-auth-types.tsnew file mode 100644index 00000000..59eae094--- /dev/null+++ b/packages/server/src/services/platform-auth-types.ts@@ -0,0 +1,39 @@+/** Stable identifiers for Penguin Go's key-authorization flow. */++export const PLATFORM_CLIENT_ID = "penguin-harness";++export interface PlatformCatalogPricing {+ unit: "usd_per_mtok";+ cacheRead: number;+ cacheWrite: number;+ output: number;+}++/** A platform model normalized into the fields Penguin persists for a newly discovered row. */+export interface PlatformCatalogModel {+ modelId: string;+ displayName: string;+ contextWindow: number;+ supportsVision: boolean;+ /**+ * List price, which is what a Project stores: the platform's `listPricing` when it runs a+ * promotion on the model, its billed `pricing` otherwise.+ */+ pricing: PlatformCatalogPricing;+ /** Fraction off `pricing` the platform is running (0.5 = half price); absent when none. */+ discount?: number;+ baseUrl: string;+ clientType: "gemini-3.8" | "deepseek-v4";+}++/** Validated snapshot returned by Penguin Go's client-model catalog. */+export interface PlatformModelCatalog {+ models: PlatformCatalogModel[];+}++/** Catalog merge result. `updated` counts existing rows whose list price, client type or promotion changed. */+export interface PlatformModelApplyResult {+ added: number;+ updated: number;+ applied: number;+}diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.tsindex 9db1546b..aec2521a 100644--- a/packages/server/src/services/project-config-service.ts+++ b/packages/server/src/services/project-config-service.ts@@ -38,14 +38,16 @@ import {GenerativeModel,canonicalClientType,listEndpointModels as coreListEndpointModels,+ PENGUIN_GO_PROVIDER_ID,catalogEntryFor,defaultProjectConfig,imageUrlMessage,metaMaxTokens,+ presetPromotions,projectConfigFromTable,projectConfigPath,renderProjectConfigToml,- resolveModelEnv,+ resolveProviderModelEnv,userText,} from "@prismshadow/penguin-core";import { providerInfo } from "@prismshadow/penguin-core/model-catalog";@@ -78,6 +80,11 @@ import type {} from "../api/types.js";import { badRequest } from "../http/validate.js";import { cacheable } from "../internal/mtime-gate.js";+import type {+ PlatformCatalogPricing,+ PlatformModelApplyResult,+ PlatformModelCatalog,+} from "./platform-auth-types.js";import { detectModelProtocol } from "./protocol-detect.js";import {VISION_PROBE_IMAGE,@@ -90,7 +97,11 @@ import {import type { PricingRates, TieredRates } from "./usage-service.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Config, Paths } from "../hmr/capabilities.js";-import type { ProjectConfigStore } from "../mechanisms/projects.js";+import type {+ ModelPromotion,+ ModelPromotions,+ ProjectConfigStore,+} from "../mechanisms/projects.js";export type RawTable = Record<string, unknown>;@@ -159,6 +170,90 @@ function optNum(v: unknown): number | undefined {return typeof v === "number" && Number.isFinite(v) ? v : undefined;}+function platformPricingTable(pricing: PlatformCatalogPricing): RawTable {+ return {+ unit: pricing.unit,+ cache_read: pricing.cacheRead,+ cache_write: pricing.cacheWrite,+ output: pricing.output,+ };+}++function platformPricingMatches(value: unknown, pricing: PlatformCatalogPricing): boolean {+ const stored = asTable(value);+ return (+ stored.unit === pricing.unit &&+ stored.cache_read === pricing.cacheRead &&+ stored.cache_write === pricing.cacheWrite &&+ stored.output === pricing.output+ );+}++/**+ * A stored `pricing` table as the three buckets, or undefined when it holds none: one present+ * bucket is a price, and a missing one reads as 0.+ */+function pricingDtoOf(value: unknown): ModelPricingDto | undefined {+ const pricing = asTable(value);+ const cacheRead = optNum(pricing.cache_read);+ const cacheWrite = optNum(pricing.cache_write);+ const output = optNum(pricing.output);+ if (cacheRead === undefined && cacheWrite === undefined && output === undefined) {+ return undefined;+ }+ return { cacheRead: cacheRead ?? 0, cacheWrite: cacheWrite ?? 0, output: output ?? 0 };+}++/** The same three numbers, or both absent. */+function samePricing(a: ModelPricingDto | undefined, b: ModelPricingDto | undefined): boolean {+ if (a === undefined || b === undefined) return a === b;+ return a.cacheRead === b.cacheRead && a.cacheWrite === b.cacheWrite && a.output === b.output;+}++/** A promotion's fraction off every bucket, rounded to six decimals the way `tieredRates` rounds. */+function promotedRates(rates: PricingRates, discount: number): PricingRates {+ const off = (v: number): number => Math.round(v * (1 - discount) * 1e6) / 1e6;+ return {+ cacheRead: off(rates.cacheRead),+ cacheWrite: off(rates.cacheWrite),+ output: off(rates.output),+ };+}++function modelEnvironmentApiKey(+ provider: string,+ modelId: string,+ clientType: string | undefined,+): string | undefined {+ const envKey = resolveProviderModelEnv(provider, modelId, clientType)?.envKey;+ return envKey ? process.env[envKey]?.trim() || undefined : undefined;+}++function probeApiKey(input: {+ provider: string;+ modelId: string;+ clientType: string | undefined;+ requestKey: string | undefined;+ savedKey: string | undefined;+ clearSavedKey: boolean | undefined;+}): string | undefined {+ return (+ input.requestKey ??+ (input.clearSavedKey ? undefined : input.savedKey) ??+ modelEnvironmentApiKey(input.provider, input.modelId, input.clientType)+ );+}++function assertRelayConnection(+ provider: string,+ apiKey: string | undefined,+ baseUrl: string | undefined,+): void {+ if (provider !== PENGUIN_GO_PROVIDER_ID) return;+ if (apiKey === undefined) throw new Error("Missing API key for Penguin Go.");+ if (!baseUrl?.trim()) throw new Error("Missing API base URL for Penguin Go.");+}+/*** Both tiers of a price read from a Project's config.*@@ -370,6 +465,8 @@ export class ProjectConfigService implements ProjectConfigStore {private readonly cache = new Map<string, { mtimeMs: number; table: RawTable }>();@Use() private readonly paths!: Paths;+ /** Optional for narrow service tests; the production Projects module always provides it. */+ @Use() private readonly promotions?: ModelPromotions;private get root(): string {return this.paths.root;}@@ -488,11 +585,12 @@ export class ProjectConfigService implements ProjectConfigStore {* **Only backfills when there are no models at all**: a Project that already has* models configured (via the CLI or edited by the user) is left as-is, and its* other fields (name, etc.) are preserved too — existing config is never- * overwritten.+ * overwritten. Returns whether it wrote the presets, which is when their promotions+ * are to be seeded too (seedPresetPromotions).*/- async ensurePresetModels(projectId: string): Promise<void> {+ async ensurePresetModels(projectId: string): Promise<boolean> {const raw = await this.readRaw(projectId);- if (asArray(raw.models).length > 0) return;+ if (asArray(raw.models).length > 0) return false;const preset = defaultProjectConfig();await this.writeRaw(projectId, {...raw,@@ -500,6 +598,17 @@ export class ProjectConfigService implements ProjectConfigStore {...(preset.default_model !== undefined ? { default_model: preset.default_model } : {}),models: preset.models,});+ return true;+ }++ /**+ * Stores the built-in catalog's flat promotions for a Project just seeded with the preset+ * models: the file carries their list prices, and these fractions are the rest of what the+ * presets bill. The rows reference the Project's `projects` row (foreign keys are enforced),+ * so this runs once that row exists.+ */+ async seedPresetPromotions(projectId: string): Promise<void> {+ this.promotions?.replaceAll(projectId, presetPromotions());}/** Project display name (the toml's name; returns undefined if unset, the frontend falls back to displaying the id). */@@ -662,7 +771,11 @@ export class ProjectConfigService implements ProjectConfigStore {return this.getPlugins(projectId);}- /** Pricing lookup for usage-recorder: the current pricing for this paired reference (undefined if none -> cost is NULL). */+ /**+ * Pricing lookup for usage-recorder: the current pricing for this paired reference (undefined+ * if none -> cost is NULL). The file holds the list price; a stored promotion takes its+ * fraction off both tiers, so a scheduled row on a promotion bills the two factors multiplied.+ */async getPricing(projectId: string,provider: string,@@ -670,15 +783,15 @@ export class ProjectConfigService implements ProjectConfigStore {): Promise<TieredRates | undefined> {const raw = await this.readRaw(projectId);const entry = asArray(raw.models).find((m) => entryMatches(m, provider, modelId));- const pricing = entry ? asTable(entry.pricing) : {};- const cacheRead = optNum(pricing.cache_read);- const cacheWrite = optNum(pricing.cache_write);- const output = optNum(pricing.output);- if (cacheRead === undefined && cacheWrite === undefined && output === undefined) {- return undefined;- }- const rates = { cacheRead: cacheRead ?? 0, cacheWrite: cacheWrite ?? 0, output: output ?? 0 };- return tieredRates(provider, modelId, rates);+ const rates = pricingDtoOf(entry?.pricing);+ if (rates === undefined) return undefined;+ const tiered = tieredRates(provider, modelId, rates);+ const discount = this.promotions?.get(projectId, provider, modelId);+ if (discount === undefined) return tiered;+ return {+ peak: promotedRates(tiered.peak, discount),+ offPeak: promotedRates(tiered.offPeak, discount),+ };}/**@@ -718,12 +831,19 @@ export class ProjectConfigService implements ProjectConfigStore {const raw = await this.readRaw(projectId);// Probeable before the entry exists, so a custom model can be checked while adding it.const entry = asArray(raw.models).find((m) => entryMatches(m, req.provider, req.modelId)) ?? {};- const savedKey = optStr(entry.api_key);- const apiKey = req.clearApiKey ? undefined : (req.apiKey ?? savedKey);const savedBaseUrl = optStr(entry.base_url);const baseUrl = req.baseUrl === null ? undefined : (req.baseUrl ?? savedBaseUrl);const clientType = canonicalClientType(req.clientType ?? optStr(entry.client_type));+ const apiKey = probeApiKey({+ provider: req.provider,+ modelId: req.modelId,+ clientType,+ requestKey: req.apiKey,+ savedKey: optStr(entry.api_key),+ clearSavedKey: req.clearApiKey,+ });try {+ assertRelayConnection(req.provider, apiKey, baseUrl);// Inside the try for the same reason as testModel: the SDK throws on a missing// credential during construction, and that must read as "probe failed", not a 500.const llm = new GenerativeModel({@@ -815,13 +935,19 @@ export class ProjectConfigService implements ProjectConfigStore {// Testable even if the model isn't in the config yet (validate before saving when adding a custom model): in that case all parameters come from the request body.const entry = asArray(raw.models).find((m) => entryMatches(m, req.provider, req.modelId)) ?? {};// Always tests against the **current form draft**: checking "clear" means the saved key is not fallen back to; an explicit null base URL is treated as cleared.- const savedKey = optStr(entry.api_key);- const apiKey = req.clearApiKey ? undefined : (req.apiKey ?? savedKey);const savedBaseUrl = optStr(entry.base_url);const baseUrl = req.baseUrl === null ? undefined : (req.baseUrl ?? savedBaseUrl);// The pre-0.4.2 "openai" spelling (request or stored entry) is normalized to the// canonical "openai-chat" (deprecated upstream alias; see canonicalClientType).const clientType = canonicalClientType(req.clientType ?? optStr(entry.client_type));+ const apiKey = probeApiKey({+ provider: req.provider,+ modelId: req.modelId,+ clientType,+ requestKey: req.apiKey,+ savedKey: optStr(entry.api_key),+ clearSavedKey: req.clearApiKey,+ });// Fast mode follows the form draft like baseUrl (the frontend always sends the current// toggle), falling back to the stored annotation: the probe then exercises exactly the// serving tier sessions would use, so a model rejecting fast_mode fails the test with@@ -830,6 +956,7 @@ export class ProjectConfigService implements ProjectConfigStore {const startedAt = Date.now();try {+ assertRelayConnection(req.provider, apiKey, baseUrl);// Construction must be inside the try block: the underlying provider SDK can// throw during **client construction** itself when a credential is missing// (models on the OpenAI protocol need apiKey/OPENAI_API_KEY) — the whole point@@ -913,14 +1040,26 @@ export class ProjectConfigService implements ProjectConfigStore {req: ModelProtocolDetectRequest,): Promise<ModelProtocolDetectResponse> {let apiKey = req.apiKey;+ let savedClientType: string | undefined;if (apiKey === undefined && !req.clearApiKey && req.provider && req.modelId) {const raw = await this.readRaw(projectId);const entry = asArray(raw.models).find((m) =>entryMatches(m, req.provider as string, req.modelId as string),);apiKey = entry !== undefined ? optStr(entry.api_key) : undefined;+ savedClientType = entry === undefined ? undefined : optStr(entry.client_type);+ }+ const relayRequest = req.provider === PENGUIN_GO_PROVIDER_ID;+ if (apiKey === undefined && relayRequest && req.provider && req.modelId) {+ apiKey = modelEnvironmentApiKey(req.provider, req.modelId, savedClientType);}- return detectModelProtocol({ baseUrl: req.baseUrl, ...(apiKey ? { apiKey } : {}) });+ return detectModelProtocol({+ baseUrl: req.baseUrl,+ ...(apiKey ? { apiKey } : {}),+ // Without a relay key, anonymous probing is still safe and can identify a route from+ // its 401. An empty env prevents the lower-level detector from substituting a vendor key.+ ...(relayRequest ? { env: {} } : {}),+ });}/**@@ -974,29 +1113,27 @@ export class ProjectConfigService implements ProjectConfigStore {* the catalog are treated as custom models: envKey only has a fallback for the* openai protocol). vision follows the TOML annotation when present, otherwise* falls back to the catalog annotation (if neither exists, the field is omitted =- * supported by default).+ * supported by default). `pricing` is the file's list price, and a row with a stored+ * promotion reports its fraction as `discount`.*/async getModels(projectId: string): Promise<ModelsResponse> {const raw = await this.readRaw(projectId);const defaultRef = optRef(raw.default_model);const visionRef = optRef(raw.vision_model);+ const discounts = new Map(+ (this.promotions?.list(projectId) ?? []).map((p) => [+ refKey(p.provider, p.modelId),+ p.discount,+ ]),+ );const models: ModelInfo[] = asArray(raw.models)// An entry is valid only if both provider and model_id are strings (an entry in the old concatenated format lacks provider and is ignored)..filter((m) => typeof m.provider === "string" && typeof m.model_id === "string").map((m) => {const provider = m.provider as string;const modelId = m.model_id as string;- const pricing = asTable(m.pricing);- const pricingDto: ModelPricingDto | undefined =- optNum(pricing.cache_read) !== undefined ||- optNum(pricing.cache_write) !== undefined ||- optNum(pricing.output) !== undefined- ? {- cacheRead: optNum(pricing.cache_read) ?? 0,- cacheWrite: optNum(pricing.cache_write) ?? 0,- output: optNum(pricing.output) ?? 0,- }- : undefined;+ const pricingDto = pricingDtoOf(m.pricing);+ const discount = discounts.get(refKey(provider, modelId));// Normalized on read: entries stored before AgentHub 0.4.2's openai -> openai-chat// rename report the canonical spelling without a disk rewrite (the next models PUT// persists it).@@ -1007,7 +1144,7 @@ export class ProjectConfigService implements ProjectConfigStore {// protocol reads OPENAI_*, independent of the group), otherwise it's// auto-routed to a provider client based on model_id; an id that can't be// routed has no fallback (no envKey, and AgentHub will reject that id).- const envKey = resolveModelEnv(modelId, clientType)?.envKey;+ const envKey = resolveProviderModelEnv(provider, modelId, clientType)?.envKey;const vision = typeof m.vision === "boolean" ? m.vision : cat?.supportsVision;// Output cap: TOML annotation only (user-owned; the built-in catalog never presets it).const maxTokens = optNum(m.max_tokens);@@ -1055,6 +1192,7 @@ export class ProjectConfigService implements ProjectConfigStore {...(envKey ? { envKey } : {}),...(envKeyMasked !== undefined ? { envKeyMasked } : {}),...(pricingDto ? { pricing: pricingDto } : {}),+ ...(discount !== undefined ? { discount } : {}),...(apiKey !== undefined || credBaseUrl !== undefined? {credential: {@@ -1089,8 +1227,20 @@ export class ProjectConfigService implements ProjectConfigStore {* the upstream id changes) is migrated as a pair via `renamedFrom`: credential and* unknown fields migrate along with the base entry, and default/vision pointers* follow. Other extension fields in the toml (name, etc.) are preserved.+ *+ * Promotions (web.db) follow the new table once the file is written: a declared+ * `discount` is stored (null clears it); an omitted one keeps the stored promotion unless+ * the entry renames the row or changes its pricing; a row left out of the table takes its+ * promotion with it. A `discount` outside (0, 1) rejects the request before any write.*/async updateModels(projectId: string, req: ModelsUpdateRequest): Promise<ModelsResponse> {+ req.models.forEach((entry, i) => {+ const { discount } = entry;+ if (discount === undefined || discount === null) return;+ if (!(Number.isFinite(discount) && discount > 0 && discount < 1)) {+ throw badRequest(`models[${i}].discount must be null or a number above 0 and below 1.`);+ }+ });const raw = await this.readRaw(projectId);const prevModels = asArray(raw.models);@@ -1098,6 +1248,13 @@ export class ProjectConfigService implements ProjectConfigStore {const nextModels: RawTable[] = [];// 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.+ const promotionPlan: Array<{+ provider: string;+ modelId: string;+ declared: number | null | undefined;+ keep: boolean;+ }> = [];for (const entry of req.models) {const key = refKey(entry.provider, entry.modelId);if (seen.has(key)) {@@ -1106,14 +1263,16 @@ export class ProjectConfigService implements ProjectConfigStore {);}seen.add(key);- if (+ const renamedFrom =entry.renamedFrom !== undefined &&!(entry.renamedFrom.provider === entry.provider &&entry.renamedFrom.modelId === entry.modelId)- ) {- renamed.set(refKey(entry.renamedFrom.provider, entry.renamedFrom.modelId), {+ ? entry.renamedFrom+ : undefined;+ if (renamedFrom !== undefined) {+ renamed.set(refKey(renamedFrom.provider, renamedFrom.modelId), {provider: entry.provider,modelId: entry.modelId,});@@ -1125,6 +1284,17 @@ export class ProjectConfigService implements ProjectConfigStore {// means removed).const prevRef = entry.renamedFrom ?? { provider: entry.provider, modelId: entry.modelId };const prev = prevModels.find((m) => entryMatches(m, prevRef.provider, prevRef.modelId)) ?? {};+ // An omitted promotion survives only on the row it was taken off, at the price it was+ // taken off: a renamed row is another row, and a changed price is not that price.+ promotionPlan.push({+ provider: entry.provider,+ modelId: entry.modelId,+ declared: entry.discount,+ keep:+ entry.discount === undefined &&+ renamedFrom === undefined &&+ samePricing(entry.pricing, pricingDtoOf(prev.pricing)),+ });const next: RawTable = { ...prev, provider: entry.provider, model_id: entry.modelId };delete next.context_window;delete next.client_type;@@ -1173,7 +1343,6 @@ export class ProjectConfigService implements ProjectConfigStore {output: entry.pricing.output,};}-// credential is inlined on the entry; added/removed on top of the old value per the request (migrates automatically with the base entry when the key changes).if (entry.clearApiKey) {delete next.api_key;@@ -1250,6 +1419,18 @@ export class ProjectConfigService implements ProjectConfigStore {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 });+ }+ // 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);}@@ -1274,6 +1455,111 @@ export class ProjectConfigService implements ProjectConfigStore {await this.writeRaw(projectId, { ...raw, models: nextModels });return applied;}++ /** Returns one persisted group key without exposing it through an HTTP response. */+ async getGroupApiKey(projectId: string, provider: string): Promise<string | undefined> {+ const raw = await this.readRaw(projectId);+ for (const model of asArray(raw.models)) {+ if (model.provider !== provider) continue;+ const apiKey = optStr(model.api_key);+ if (apiKey !== undefined) return apiKey;+ }+ return undefined;+ }++ /**+ * Adds newly advertised models and refreshes platform-owned routing and list price on+ * existing rows, then replaces this group's promotions (web.db) with the platform's. Project+ * TOML stays in the same shape as every other model group, list price included. Other+ * annotations remain Project-owned and are never overwritten. Authorization additionally+ * applies the freshly delivered key to the whole group.+ */+ async mergePlatformModels(+ projectId: string,+ provider: string,+ catalog: PlatformModelCatalog,+ apiKey: string,+ applyKeyToExisting: boolean,+ ): Promise<PlatformModelApplyResult> {+ const raw = await this.readRaw(projectId);+ const current = asArray(raw.models);+ const catalogById = new Map(catalog.models.map((model) => [model.modelId, model]));+ const storedPromotions = new Map(+ (this.promotions?.list(projectId) ?? [])+ .filter((promotion) => promotion.provider === provider)+ .map((promotion) => [promotion.modelId, promotion.discount]),+ );+ const known = new Set<string>();+ const createdAt = new Date().toISOString();+ let added = 0;+ let updated = 0;+ let applied = 0;+ let configChanged = false;+ const nextModels = current.map((model): RawTable => {+ if (model.provider !== provider || typeof model.model_id !== "string") return model;+ const modelId = String(model.model_id);+ known.add(modelId);+ const catalogModel = catalogById.get(modelId);+ const remotePricing = catalogModel?.pricing;+ const pricingChanged =+ remotePricing !== undefined && !platformPricingMatches(model.pricing, remotePricing);+ const clientTypeChanged =+ catalogModel !== undefined && model.client_type !== catalogModel.clientType;+ // A row the platform no longer lists loses its promotion below, which is a change too.+ const promotionChanged =+ this.promotions !== undefined && storedPromotions.get(modelId) !== catalogModel?.discount;+ if (pricingChanged || clientTypeChanged || promotionChanged) updated += 1;+ if (applyKeyToExisting) applied += 1;+ if (!pricingChanged && !clientTypeChanged && !applyKeyToExisting) return model;+ configChanged = true;+ return {+ ...model,+ ...(pricingChanged && remotePricing !== undefined+ ? { pricing: platformPricingTable(remotePricing) }+ : {}),+ ...(clientTypeChanged && catalogModel !== undefined+ ? { client_type: catalogModel.clientType }+ : {}),+ ...(applyKeyToExisting ? { api_key: apiKey, created_at: createdAt } : {}),+ };+ });++ for (const model of catalog.models) {+ if (known.has(model.modelId)) continue;+ known.add(model.modelId);+ added += 1;+ applied += 1;+ configChanged = true;+ nextModels.push({+ provider,+ model_id: model.modelId,+ display_name: model.displayName,+ context_window: model.contextWindow,+ vision: model.supportsVision,+ pricing: platformPricingTable(model.pricing),+ client_type: model.clientType,+ base_url: model.baseUrl,+ api_key: apiKey,+ created_at: createdAt,+ });+ }++ if (configChanged) {+ await this.writeRaw(projectId, { ...raw, models: nextModels });+ }+ // After the file write, so a promotion never lands for a row the file failed to take; a+ // failure here leaves the group's previous promotions until the next authorization or Sync.+ this.promotions?.replaceProvider(+ projectId,+ provider,+ catalog.models.flatMap((model) =>+ model.discount !== undefined && known.has(model.modelId)+ ? [{ provider, modelId: model.modelId, discount: model.discount }]+ : [],+ ),+ );+ return { added, updated, applied };+ }}/**diff --git a/packages/server/src/services/project-service.ts b/packages/server/src/services/project-service.tsindex 2e1a97b2..64500dfb 100644--- a/packages/server/src/services/project-service.ts+++ b/packages/server/src/services/project-service.ts@@ -154,6 +154,9 @@ export class ProjectService implements ProjectLifecycle {try {await fs.mkdir(projectDir(this.root, projectId), { recursive: true });await this.projectConfig.writeInitialConfig(projectId, displayName);+ // The presets' promotions live in web.db, keyed to the row inserted above (and removed+ // with it by the rollback below).+ await this.projectConfig.seedPresetPromotions(projectId);await this.provisionBuiltinAgents(projectId);} catch (err) {this.projects.delete(projectId);@@ -190,12 +193,15 @@ export class ProjectService implements ProjectLifecycle {// models and the default model are backfilled instead (only when there are no// models at all; a default_project already configured via the CLI is left// as-is).- await this.projectConfig.ensurePresetModels(projectId);+ const seeded = await this.projectConfig.ensurePresetModels(projectId);this.projects.insert({projectId,ownerUserId: user.userId,createdAt: new Date().toISOString(),});+ // Presets written just now bring their promotions, once the row they reference exists; a+ // Project that kept its own models keeps its own pricing.+ if (seeded) await this.projectConfig.seedPresetPromotions(projectId);}/**@@ -259,7 +265,7 @@ export class ProjectService implements ProjectLifecycle {new Promise<void>((resolve) => setTimeout(resolve, ABORT_SETTLE_TIMEOUT_MS).unref?.()),]);}- this.projects.delete(projectId); // project_members and machine_project cascade-deleted+ this.projects.delete(projectId); // project_members, machine_project and model_promotions cascade-deletedthis.agents.deleteByProject(projectId);this.sessions.deleteByProject(projectId);this.usage.deleteByProject(projectId);diff --git a/packages/server/test/config.test.ts b/packages/server/test/config.test.tsindex 3f48a81f..bc4b2b6e 100644--- a/packages/server/test/config.test.ts+++ b/packages/server/test/config.test.ts@@ -89,3 +89,26 @@ describe("resolveServerConfig: PENGUIN_CLI_ENTRY parsing", () => {expect(blank === null || blank.endsWith(`${path.sep}penguin.js`)).toBe(true);});});++describe("resolveServerConfig: PENGUIN_GO_ORIGIN parsing", () => {+ it("defaults to the production HTTPS origin and accepts loopback HTTP for integration", () => {+ expect(resolveServerConfig({ ...base }).penguinGoOrigin).toBe("https://token.penguin.ooo");+ expect(+ resolveServerConfig({ ...base, PENGUIN_GO_ORIGIN: " http://127.0.0.1:3000 " })+ .penguinGoOrigin,+ ).toBe("http://127.0.0.1:3000");+ });++ it("rejects non-origin input and non-loopback plaintext HTTP", () => {+ for (const bad of [+ "http://token.penguin.ooo",+ "https://token.penguin.ooo/path",+ "https://user:[email protected]",+ "https://token.penguin.ooo?next=x",+ ]) {+ expect(() => resolveServerConfig({ ...base, PENGUIN_GO_ORIGIN: bad }), bad).toThrow(+ /Invalid PENGUIN_GO_ORIGIN/,+ );+ }+ });+});diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.tsindex a905d420..5e54cd60 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_promotions");dropCompanyModeTables(db);db.exec("DROP TABLE messaging_bindings");db.exec("DROP INDEX IF EXISTS idx_auth_sessions_expires");@@ -109,6 +110,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_promotions");db.exec(PRE_CHANNEL_CHAT_DDL);// SCHEMA_SQL declares the CURRENT shape; migration 8's queue came after 6.db.exec("DROP TABLE IF EXISTS org_desk_notices");@@ -121,14 +123,25 @@ 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_promotions");db.exec("PRAGMA user_version = 7");return db;}+/** A database stamped at migration 8: desk notices exist, but the promotions table does not. */+function open8(): DatabaseSync {+ const db = new sqlite.DatabaseSync(":memory:");+ db.exec(SCHEMA_SQL);+ db.exec("DROP TABLE IF EXISTS model_promotions");+ db.exec("PRAGMA user_version = 8");+ 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_promotions");dropCompanyModeTables(db);db.exec(GOAL_STATE_DDL);// SCHEMA_SQL declares the CURRENT shape, and a 0.2.9 database has no machines tables —@@ -148,6 +161,7 @@ function open029(): DatabaseSync {function openPreProfile(): DatabaseSync {const db = new sqlite.DatabaseSync(":memory:");db.exec(SCHEMA_SQL);+ 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// profile's, so a database at 4 has none of their tables.@@ -526,6 +540,37 @@ 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 = () =>+ db+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'model_promotions'")+ .get();+ try {+ expect(migrate(db).applied).toEqual(["model-promotions"]);+ expect(schemaVersion(db)).toBe(9);+ expect(tableExists()).toEqual({ "1": 1 });++ rollbackTo(db, 8);+ expect(schemaVersion(db)).toBe(8);+ expect(tableExists()).toBeUndefined();+ } finally {+ db.close();+ }+ });++ it("is safe to create while a pushed platform boots", () => {+ const db = open8();+ try {+ expect(migrate(db, { swapPath: true }).applied).toEqual(["model-promotions"]);+ expect(schemaVersion(db)).toBe(9);+ } finally {+ db.close();+ }+ });+});+describe("0.2.4 → current", () => {/** The whole point: an older runtime's database becomes what a current build creates. */it("brings a 0.2.4 database to the shape a fresh one is created with", () => {diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex ed96e7a1..8b74a03c 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -107,6 +107,7 @@ export function testConfig(root: string): ServerConfig {port: 7364,dbPath: ":memory:",previewOrigin: null,+ penguinGoOrigin: "https://token.penguin.ooo",// 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.tsindex 285419c1..9ecd521f 100644--- a/packages/server/test/models.test.ts+++ b/packages/server/test/models.test.ts@@ -15,13 +15,15 @@ import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import {MODEL_CATALOG,+ PENGUIN_GO_BASE_URL,catalogEntryFor,- effectivePricing,+ presetPromotions,userText,} from "@prismshadow/penguin-core";import type {ModelsResponse,ModelTestResponse,+ ModelVisionDetectResponse,ProjectCreateResponse,SessionCreateResponse,} from "../src/api/types.js";@@ -133,36 +135,45 @@ describe("models preset & catalog enrichment", () => {expect(mimo.credential?.baseUrl).toBe("https://openrouter.ai/api/v1");expect(mimo.credential?.apiKeyMasked).toBeUndefined();- // A catalog row on a promotion is preset at the rate the seller BILLS, not at the list- // price the catalog records. The cost center prices only against what is written into- // the Project, so anything else here would report a cost nobody was charged.+ // A catalog row on a promotion is preset at its LIST price like every other row, and the+ // promotion is seeded beside it in web.db: the rows reporting a discount are exactly the+ // catalog's flat promotions.const promoted = catalogEntryFor("tokendance", "glm-5.3-flash")!;- const billed = effectivePricing(promoted)!;- expect(pick(body, "tokendance", "glm-5.3-flash").pricing).toEqual({- cacheRead: billed.cache_read,- cacheWrite: billed.cache_write,- output: billed.output,- });- expect(billed.output).toBeLessThan(promoted.pricing!.output);- // An undiscounted row is preset at its list price, unchanged.+ expect(pick(body, "tokendance", "glm-5.3-flash")).toMatchObject({+ pricing: {+ cacheRead: promoted.pricing!.cache_read,+ cacheWrite: promoted.pricing!.cache_write,+ output: promoted.pricing!.output,+ },+ discount: promoted.discount,+ });+ expect(+ body.models+ .filter((m) => m.discount !== undefined)+ .map((m) => ({ provider: m.provider, modelId: m.modelId, discount: m.discount })),+ ).toEqual(presetPromotions());+ // An undiscounted row is preset at its list price, unchanged, and reports no discount.const plain = catalogEntryFor("tokendance", "hy4-preview")!;expect(pick(body, "tokendance", "hy4-preview").pricing).toEqual({cacheRead: plain.pricing!.cache_read,cacheWrite: plain.pricing!.cache_write,output: plain.pricing!.output,});+ expect(pick(body, "tokendance", "hy4-preview")).not.toHaveProperty("discount");});- it("masks the env fallback for first-party official entries only, and never leaks the value", async () => {+ it("masks allowed direct and relay env fallbacks, never gateway fallbacks, and never leaks a value", async () => {const saved = {anthropic: process.env.ANTHROPIC_API_KEY,deepseek: process.env.DEEPSEEK_API_KEY,openai: process.env.OPENAI_API_KEY,+ penguin: process.env.PENGUIN_GO_API_KEY,};const anthropicValue = "sk-ant-test-secret-value-123456";const openaiValue = "sk-openai-test-secret-value-789";process.env.ANTHROPIC_API_KEY = anthropicValue;process.env.OPENAI_API_KEY = openaiValue;+ process.env.PENGUIN_GO_API_KEY = "sk-penguin-test-secret-value-456";// Empty counts as absent — it would not authenticate either.process.env.DEEPSEEK_API_KEY = "";try {@@ -185,6 +196,19 @@ describe("models preset & catalog enrichment", () => {baseUrl: "https://openrouter.ai/api/v1",},{ provider: "custom", modelId: "my-model", clientType: "openai" },+ // Both protocols in the relay group resolve the same provider-scoped key.+ {+ provider: "penguin-go",+ modelId: "gemini-3.8-flash",+ clientType: "gemini-3.8",+ baseUrl: PENGUIN_GO_BASE_URL,+ },+ {+ provider: "penguin-go",+ modelId: "deepseek-flash",+ clientType: "deepseek-v4",+ baseUrl: PENGUIN_GO_BASE_URL,+ },],});expect(put.status).toBe(200);@@ -204,11 +228,17 @@ describe("models preset & catalog enrichment", () => {expect(gateway.envKey).toBe("OPENAI_API_KEY");expect(gateway.envKeyMasked).toBeUndefined();expect(pick(body, "custom", "my-model").envKeyMasked).toBeUndefined();+ const penguinMasked = "sk-p…-456";+ expect(pick(body, "penguin-go", "gemini-3.8-flash").envKey).toBe("PENGUIN_GO_API_KEY");+ expect(pick(body, "penguin-go", "gemini-3.8-flash").envKeyMasked).toBe(penguinMasked);+ expect(pick(body, "penguin-go", "deepseek-flash").envKey).toBe("PENGUIN_GO_API_KEY");+ expect(pick(body, "penguin-go", "deepseek-flash").envKeyMasked).toBe(penguinMasked);} finally {for (const [key, value] of [["ANTHROPIC_API_KEY", saved.anthropic],["DEEPSEEK_API_KEY", saved.deepseek],["OPENAI_API_KEY", saved.openai],+ ["PENGUIN_GO_API_KEY", saved.penguin],] as const) {if (value === undefined) delete process.env[key];else process.env[key] = value;@@ -450,6 +480,10 @@ describe("default_project presets", () => {modelId: "deepseek-flash",});expect(body.models.map(pairKey)).toEqual(catalogPairs);+ // Presets backfilled here bring their promotions too, seeded once the Project row exists.+ expect(body.models.filter((m) => m.discount !== undefined)).toHaveLength(+ presetPromotions().length,+ );// The point of presets is "works out of the box": creating a Session should succeed without passing a model ref.const created = await api.post(@@ -640,6 +674,112 @@ describe("model-reference rekeying and the connectivity test", () => {});});+ it("a stored promotion takes its fraction off the list price on disk, multiplied with a scheduled row's off-peak tier", async () => {+ const svc = t.deps.projectConfigService;+ const off = (v: number, fraction: number): number => Math.round(v * (1 - fraction) * 1e6) / 1e6;+ // Seeded with the Project: TokenDance's glm-5.3-flash is on 10% off.+ const list = catalogEntryFor("tokendance", "glm-5.3-flash")!.pricing!;+ const promoted = {+ cacheRead: off(list.cache_read, 0.1),+ cacheWrite: off(list.cache_write, 0.1),+ output: off(list.output, 0.1),+ };+ expect(await svc.getPricing(projectId, "tokendance", "glm-5.3-flash")).toEqual({+ peak: promoted,+ offPeak: promoted,+ });++ // A scheduled row still at the catalog's peak price, with a promotion of its own: peak bills+ // the promotion alone, off-peak the half-price tier with the promotion taken off it too.+ const peak = catalogEntryFor("deepseek", "deepseek-v4-flash")!.pricing!;+ await svc.updateModels(projectId, {+ models: [+ {+ provider: "deepseek",+ modelId: "deepseek-v4-flash",+ pricing: {+ cacheRead: peak.cache_read,+ cacheWrite: peak.cache_write,+ output: peak.output,+ },+ discount: 0.2,+ },+ ],+ });+ const rates = (await svc.getPricing(projectId, "deepseek", "deepseek-v4-flash"))!;+ expect(rates.peak.output).toBe(off(peak.output, 0.2));+ expect(rates.offPeak.output).toBe(off(off(peak.output, 0.5), 0.2));+ });++ it("PUT discount: a declared one is stored and null clears it; an omitted one survives only on an unrenamed row at an unchanged price", async () => {+ const price = { cacheRead: 0.1, cacheWrite: 1, output: 4 };+ const row = (modelId: string, extra: Record<string, unknown> = {}) => ({+ provider: "custom",+ modelId,+ pricing: price,+ ...extra,+ });+ const stored = () =>+ t.deps.db+ .prepare(+ "SELECT model_id, discount FROM model_promotions WHERE project_id = ? ORDER BY model_id",+ )+ .all(projectId);++ const declared = await api.put(url(), {+ models: ["kept", "repriced", "renamed", "cleared", "dropped"].map((id) =>+ row(id, { discount: 0.2 }),+ ),+ });+ expect(declared.status).toBe(200);+ expect(+ ((await declared.json()) as ModelsResponse).models.map((m) => [m.modelId, m.discount]),+ ).toEqual([+ ["kept", 0.2],+ ["repriced", 0.2],+ ["renamed", 0.2],+ ["cleared", 0.2],+ ["dropped", 0.2],+ ]);++ const next = await api.put(url(), {+ models: [+ row("kept"),+ row("repriced", { pricing: { ...price, output: 5 } }),+ row("renamed-to", { renamedFrom: { provider: "custom", modelId: "renamed" } }),+ row("cleared", { discount: null }),+ ],+ });+ expect(next.status).toBe(200);+ expect(+ ((await next.json()) as ModelsResponse).models.map((m) => [m.modelId, m.discount]),+ ).toEqual([+ ["kept", 0.2],+ ["repriced", undefined],+ ["renamed-to", undefined],+ ["cleared", undefined],+ ]);+ // The dropped row's promotion went with it rather than lingering unseen.+ expect(stored()).toEqual([{ model_id: "kept", discount: 0.2 }]);++ // Out of range or not a number: 400 before anything is written, so neither the file nor+ // the table moves — not even for the valid row beside it, whose new price would otherwise+ // have cleared its promotion.+ const cfgFile = path.join(t.root, projectId, ".project_config.toml");+ const before = await readFile(cfgFile, "utf8");+ for (const bad of [0, 1, -0.2, 1.5, "0.2"]) {+ const res = await api.put(url(), {+ models: [+ row("kept", { pricing: { ...price, output: 9 } }),+ row("other", { discount: bad }),+ ],+ });+ expect(res.status, String(bad)).toBe(400);+ }+ expect(await readFile(cfgFile, "utf8")).toBe(before);+ expect(stored()).toEqual([{ model_id: "kept", discount: 0.2 }]);+ });+it("an absent display name inherits the catalog's; only an empty one clears it", async () => {// Two different requests, and reading them as one is how a client that simply has no name// for a model — one built from the catalog, which stores no name of its own — destroys the@@ -844,6 +984,57 @@ describe("model-reference rekeying and the connectivity test", () => {}});+ it("Penguin Go probes never substitute vendor environment keys", async () => {+ const saved = {+ gemini: process.env.GEMINI_API_KEY,+ openai: process.env.OPENAI_API_KEY,+ penguin: process.env.PENGUIN_GO_API_KEY,+ };+ process.env.GEMINI_API_KEY = "vendor-gemini-must-not-cross";+ process.env.OPENAI_API_KEY = "vendor-openai-must-not-cross";+ delete process.env.PENGUIN_GO_API_KEY;+ try {+ for (const modelId of ["gemini-3.8-flash", "deepseek-flash"]) {+ const tested = await api.post(testUrl(), { provider: "penguin-go", modelId });+ expect(tested.status).toBe(200);+ expect((await tested.json()) as ModelTestResponse).toMatchObject({+ ok: false,+ message: "Missing API key for Penguin Go.",+ });++ const vision = await api.post(`${url()}/detect-vision`, {+ provider: "penguin-go",+ modelId,+ });+ expect(vision.status).toBe(200);+ expect((await vision.json()) as ModelVisionDetectResponse).toMatchObject({+ outcome: "failed",+ message: "Missing API key for Penguin Go.",+ });+ }++ process.env.PENGUIN_GO_API_KEY = "penguin-go-key-without-endpoint";+ const noEndpoint = await api.post(testUrl(), {+ provider: "penguin-go",+ modelId: "gemini-3.8-flash",+ baseUrl: null,+ });+ expect((await noEndpoint.json()) as ModelTestResponse).toMatchObject({+ ok: false,+ message: "Missing API base URL for Penguin Go.",+ });+ } finally {+ for (const [key, value] of [+ ["GEMINI_API_KEY", saved.gemini],+ ["OPENAI_API_KEY", saved.openai],+ ["PENGUIN_GO_API_KEY", saved.penguin],+ ] as const) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });+it("connectivity test: clearApiKey does not fall back to the stored key (the current draft is what gets tested)", async () => {// A key is already saved, but the test request carries clearApiKey — the server must **not** use// the saved key. Clear the env var so "don't use the saved key" == no credential at all, so construction synchronously throws missing-credential (no network request, deterministic).diff --git a/packages/server/test/platform-auth.test.ts b/packages/server/test/platform-auth.test.tsnew file mode 100644index 00000000..17c2e19f--- /dev/null+++ b/packages/server/test/platform-auth.test.ts@@ -0,0 +1,567 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type {+ ModelsResponse,+ PlatformAuthFlowStatusResponse,+ PlatformAuthStartResponse,+ PlatformModelSyncResponse,+ ProjectCreateResponse,+} from "../src/api/types.js";+import { PlatformAuthService, platformConnection } from "../src/services/platform-auth-service.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++function json(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}++const deliveryBody = {+ status: "claimed",+ client: { id: "penguin-harness", displayName: "PenguinHarness" },+ user: { id: 7, username: "penguin-go-user", displayName: "Penguin Go User", avatarUrl: null },+ apiKey: "ignored-top-level-key",+ connection: {+ apiKey: "sk-penguin-go-secret-0001",+ endpoints: {+ openai: "https://token.penguin.ooo/api",+ google: "https://token.penguin.ooo/api",+ anthropic: "https://token.penguin.ooo/api/anthropic",+ },+ models: [+ {+ provider: "google",+ modelId: "gemini-3.8-flash",+ displayName: "Gemini 3.8 Flash",+ contextWindow: 1_048_576,+ maxOutputTokens: 65_536,+ supportsVision: true,+ pricing: {+ unit: "usd_per_mtok",+ cacheRead: 0,+ cacheWrite: 0.625,+ output: 5,+ },+ listPricing: {+ unit: "usd_per_mtok",+ cacheRead: 0,+ cacheWrite: 1.25,+ output: 10,+ },+ discount: 0.5,+ recommendedRoute: {+ protocol: "google-generative-language",+ endpoint: "google",+ },+ },+ {+ provider: "deepseek",+ modelId: "deepseek-future",+ displayName: "DeepSeek Future",+ contextWindow: 1_000_000,+ maxOutputTokens: 65_536,+ supportsVision: false,+ pricing: {+ unit: "usd_per_mtok",+ cacheRead: 0.03,+ cacheWrite: 0.15,+ output: 0.6,+ },+ recommendedRoute: {+ protocol: "deepseek-responses",+ endpoint: "openai",+ },+ },+ ],+ },+};++const syncCatalog = (models: unknown[] = deliveryBody.connection.models) => ({+ schemaVersion: 1,+ catalogVersion: "a".repeat(64),+ endpoints: deliveryBody.connection.endpoints,+ models,+});++describe("Penguin Go key delivery validation", () => {+ it("accepts only the expected client and connection API key", () => {+ const connection = platformConnection(deliveryBody);+ expect(connection).toMatchObject({+ apiKey: "sk-penguin-go-secret-0001",+ catalog: {+ models: [+ {+ modelId: "gemini-3.8-flash",+ clientType: "gemini-3.8",+ // A promoted model normalizes to its list price, which is what a Project stores,+ // and the fraction off it; the billed price is only checked against the two.+ pricing: {+ unit: "usd_per_mtok",+ cacheRead: 0,+ cacheWrite: 1.25,+ output: 10,+ },+ discount: 0.5,+ },+ {+ modelId: "deepseek-future",+ clientType: "deepseek-v4",+ pricing: { unit: "usd_per_mtok", cacheRead: 0.03, cacheWrite: 0.15, output: 0.6 },+ },+ ],+ },+ });+ expect(connection.catalog.models[0]).not.toHaveProperty("listPricing");+ expect(connection.catalog.models[1]).not.toHaveProperty("discount");+ expect(() => platformConnection({ ...deliveryBody, client: { id: "another-client" } })).toThrow(+ "another client",+ );+ expect(() =>+ platformConnection({+ ...deliveryBody,+ connection: { ...deliveryBody.connection, apiKey: "" },+ }),+ ).toThrow("invalid API key");+ expect(() =>+ platformConnection({+ ...deliveryBody,+ connection: {+ ...deliveryBody.connection,+ models: [{ ...deliveryBody.connection.models[0], maxOutputTokens: 0 }],+ },+ }),+ ).toThrow("maximum output length");+ expect(() =>+ platformConnection({+ ...deliveryBody,+ connection: {+ ...deliveryBody.connection,+ models: [+ {+ ...deliveryBody.connection.models[0]!,+ pricing: {+ ...deliveryBody.connection.models[0]!.pricing,+ output: -1,+ },+ },+ ],+ },+ }),+ ).toThrow("invalid effective output price");+ expect(() =>+ platformConnection({+ ...deliveryBody,+ connection: {+ ...deliveryBody.connection,+ models: [+ {+ ...deliveryBody.connection.models[0]!,+ pricing: {+ ...deliveryBody.connection.models[0]!.pricing,+ unit: "cny_per_mtok",+ },+ },+ ],+ },+ }),+ ).toThrow("unsupported effective pricing unit");+ });+});++describe("Penguin Go key authorization routes", () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let member: ReturnType<typeof apiClient>;+ let projectId: string;+ let pollCount: number;+ let currentCatalogModels: unknown[];++ beforeEach(async () => {+ t = await createTestApp();+ const ownerUser = await provisionUser(t.app, "penguin_api_owner");+ owner = apiClient(t.app, ownerUser.cookie);+ const memberUser = await provisionUser(t.app, "penguin_api_member");+ member = apiClient(t.app, memberUser.cookie);+ projectId = (+ (await (+ await owner.post("/api/projects", {+ projectId: "penguin_api_owner-project",+ name: "Penguin Go Project",+ })+ ).json()) as ProjectCreateResponse+ ).project.projectId;+ expect(+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "penguin_api_member" }))+ .status,+ ).toBe(201);++ pollCount = 0;+ currentCatalogModels = [...deliveryBody.connection.models];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);+ if (url.pathname === "/api/auth/desktop/start") {+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;+ expect(body.client).toEqual({ id: "penguin-harness" });+ expect(String(body.code)).toMatch(/^[A-Za-z0-9_-]{43}$/);+ expect(String(body.deviceSecret)).toMatch(/^[A-Za-z0-9_-]{43}$/);+ return json(201, { expiresAt: new Date(Date.now() + 10 * 60_000).toISOString() });+ }+ if (url.pathname === "/api/auth/desktop/poll") {+ pollCount += 1;+ return pollCount === 1+ ? json(200, { status: "pending", expiresInSeconds: 500 })+ : json(200, deliveryBody);+ }+ if (url.pathname === "/api/client/models") {+ expect(new Headers(init?.headers).get("authorization")).toBe(+ "Bearer sk-penguin-go-secret-0001",+ );+ return json(200, syncCatalog(currentCatalogModels));+ }+ throw new Error(`Unexpected platform request: ${url.pathname}`);+ }),+ );+ });++ afterEach(async () => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ await t.cleanup();+ });++ it("writes the delivered key to the prebuilt group and exposes no account state", async () => {+ const base = `/api/projects/${projectId}/platform-auth`;+ const initial = (await (+ await owner.get(`/api/projects/${projectId}/models`)+ ).json()) as ModelsResponse;+ const initialPenguinGoModels = initial.models.filter(+ (model) => model.provider === "penguin-go",+ );+ expect(initialPenguinGoModels.map((model) => model.modelId)).toEqual([+ "gemini-3.8-flash",+ "gemini-3.7-flash",+ "gemini-3.6-flash",+ "gemini-3.5-flash",+ "gemini-3.5-flash-lite",+ "gemini-3.1-flash-lite",+ "gemini-3.1-pro-preview",+ "deepseek-flash",+ "deepseek-v4-pro",+ ]);+ expect(+ initialPenguinGoModels.every(+ (model) => model.credential?.baseUrl === "https://token.penguin.ooo/api",+ ),+ ).toBe(true);+ expect(+ initialPenguinGoModels.every((model) => model.credential?.apiKeyMasked === undefined),+ ).toBe(true);+ expect((await member.post(`${base}/start`, {})).status).toBe(403);+ const unauthorizedSync = await owner.post(`${base}/sync`, {});+ expect(unauthorizedSync.status).toBe(409);+ expect(await unauthorizedSync.json()).toMatchObject({+ error: { code: "platform_reauthorization_required" },+ });++ const startResponse = await owner.post(`${base}/start`, {});+ expect(startResponse.status).toBe(201);+ const started = (await startResponse.json()) as PlatformAuthStartResponse;+ expect(started.authorizeUrl).toMatch(+ /^https:\/\/token\.penguin\.ooo\/desktop\/authorize\?code=/,+ );+ expect(JSON.stringify(started)).not.toContain("deviceSecret");++ const pending = (await (+ await owner.get(`${base}/${started.flowId}/status`)+ ).json()) as PlatformAuthFlowStatusResponse;+ expect(pending).toEqual({ status: "pending" });++ const done = (await (+ await owner.get(`${base}/${started.flowId}/status`)+ ).json()) as PlatformAuthFlowStatusResponse;+ expect(done).toEqual({ status: "completed", applied: 10 });+ expect(JSON.stringify(done)).not.toContain("sk-penguin");++ const models = (await (+ await owner.get(`/api/projects/${projectId}/models`)+ ).json()) as ModelsResponse;+ const penguinGoModels = models.models.filter((model) => model.provider === "penguin-go");+ expect(penguinGoModels).toHaveLength(10);+ const deepseekFuture = penguinGoModels.find((model) => model.modelId === "deepseek-future");+ expect(deepseekFuture).toMatchObject({+ displayName: "DeepSeek Future",+ contextWindow: 1_000_000,+ clientType: "deepseek-v4",+ vision: false,+ pricing: { cacheRead: 0.03, cacheWrite: 0.15, output: 0.6 },+ credential: { baseUrl: "https://token.penguin.ooo/api" },+ });+ expect(deepseekFuture).not.toHaveProperty("maxTokens");+ expect(deepseekFuture).not.toHaveProperty("discount");+ // The promoted model: the file takes the platform's LIST price, and the fraction is stored+ // beside it in web.db.+ const gemini = penguinGoModels.find((model) => model.modelId === "gemini-3.8-flash");+ expect(gemini).toMatchObject({+ clientType: "gemini-3.8",+ pricing: { cacheRead: 0, cacheWrite: 1.25, output: 10 },+ discount: 0.5,+ });+ expect(gemini).not.toHaveProperty("listPricing");+ const stored = (await t.deps.projectConfigService.readRaw(projectId)).models as Record<+ string,+ unknown+ >[];+ const storedGemini = stored.find(+ (model) => model.provider === "penguin-go" && model.model_id === "gemini-3.8-flash",+ );+ expect(storedGemini).toMatchObject({+ pricing: { unit: "usd_per_mtok", cache_read: 0, cache_write: 1.25, output: 10 },+ });+ expect(storedGemini).not.toHaveProperty("discount");+ const promotionOf = (modelId: string) =>+ t.deps.db+ .prepare(+ "SELECT discount FROM model_promotions WHERE project_id = ? AND provider = ? AND model_id = ?",+ )+ .get(projectId, "penguin-go", modelId);+ expect(promotionOf("gemini-3.8-flash")).toEqual({ discount: 0.5 });+ expect(penguinGoModels.every((model) => model.credential?.apiKeyMasked !== undefined)).toBe(+ true,+ );+ expect(+ penguinGoModels.every(+ (model) => model.credential?.baseUrl === "https://token.penguin.ooo/api",+ ),+ ).toBe(true);+ expect(JSON.stringify(models)).not.toContain("sk-penguin-go-secret-0001");++ const synced = (await (+ await owner.post(`${base}/sync`, {})+ ).json()) as PlatformModelSyncResponse;+ expect(synced).toMatchObject({ added: 0, updated: 0 });+ expect(synced.updatedAt).toBe(models.updatedAt);+ expect(synced.models.filter((model) => model.provider === "penguin-go")).toHaveLength(10);++ const patchGemini = (patch: Record<string, unknown>) => {+ currentCatalogModels = currentCatalogModels.map((model) =>+ (model as { modelId?: unknown }).modelId === "gemini-3.8-flash"+ ? { ...(model as Record<string, unknown>), ...patch }+ : model,+ );+ };+ patchGemini({+ pricing: { unit: "usd_per_mtok", cacheRead: 0, cacheWrite: 0.75, output: 6 },+ listPricing: { unit: "usd_per_mtok", cacheRead: 0, cacheWrite: 1.5, output: 12 },+ });+ const repriced = (await (+ await owner.post(`${base}/sync`, {})+ ).json()) as PlatformModelSyncResponse;+ expect(repriced).toMatchObject({ added: 0, updated: 1 });+ expect(repriced.models.find((model) => model.modelId === "gemini-3.8-flash")).toMatchObject({+ pricing: { cacheRead: 0, cacheWrite: 1.5, output: 12 },+ discount: 0.5,+ });++ // Same list price, deeper promotion: an update all the same, landing in web.db alone —+ // the file is not rewritten and keeps the list price.+ patchGemini({+ pricing: { unit: "usd_per_mtok", cacheRead: 0, cacheWrite: 1.125, output: 9 },+ discount: 0.25,+ });+ const promotionOnly = (await (+ await owner.post(`${base}/sync`, {})+ ).json()) as PlatformModelSyncResponse;+ expect(promotionOnly).toMatchObject({ added: 0, updated: 1 });+ expect(promotionOnly.updatedAt).toBe(repriced.updatedAt);+ expect(+ promotionOnly.models.find((model) => model.modelId === "gemini-3.8-flash"),+ ).toMatchObject({+ pricing: { cacheRead: 0, cacheWrite: 1.5, output: 12 },+ discount: 0.25,+ });+ expect(promotionOf("gemini-3.8-flash")).toEqual({ discount: 0.25 });++ currentCatalogModels.push({+ provider: "google",+ modelId: "gemini-future",+ displayName: "Gemini Future",+ contextWindow: 1_048_576,+ maxOutputTokens: 65_536,+ supportsVision: true,+ pricing: {+ unit: "usd_per_mtok",+ cacheRead: 0.05,+ cacheWrite: 0.25,+ output: 1,+ },+ listPricing: {+ unit: "usd_per_mtok",+ cacheRead: 0.1,+ cacheWrite: 0.5,+ output: 2,+ },+ discount: 0.5,+ recommendedRoute: {+ protocol: "google-generative-language",+ endpoint: "google",+ },+ });+ const added = (await (+ await owner.post(`${base}/sync`, {})+ ).json()) as PlatformModelSyncResponse;+ expect(added).toMatchObject({ added: 1, updated: 0 });+ expect(added.models.find((model) => model.modelId === "gemini-future")).toMatchObject({+ displayName: "Gemini Future",+ contextWindow: 1_048_576,+ clientType: "gemini-3.8",+ vision: true,+ pricing: { cacheRead: 0.1, cacheWrite: 0.5, output: 2 },+ discount: 0.5,+ credential: {+ apiKeyMasked: "sk-p…0001",+ baseUrl: "https://token.penguin.ooo/api",+ },+ });+ expect(added.models.find((model) => model.modelId === "gemini-future")).not.toHaveProperty(+ "maxTokens",+ );+ expect((await owner.get(base)).status).toBe(404);+ expect((await owner.post(`${base}/refresh`, {})).status).toBe(404);+ expect((await owner.post(`${base}/logout`, {})).status).toBe(404);+ });++ it("preserves the platform start backoff as HTTP 429 with Retry-After", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => json(429, { error: "rate_limited", retryAfterSeconds: 7 })),+ );++ const response = await owner.post(`/api/projects/${projectId}/platform-auth/start`, {});+ expect(response.status).toBe(429);+ expect(response.headers.get("retry-after")).toBe("7");+ expect(await response.json()).toMatchObject({ error: { code: "platform_rate_limited" } });+ });+});++describe("single-delivery local retry", () => {+ it("requires reauthorization when the stored platform key is rejected", async () => {+ const applyCatalog = vi.fn();+ const service = new PlatformAuthService({+ origin: "https://token.penguin.ooo",+ getKey: async () => "revoked-key",+ applyCatalog,+ fetchImpl: async () => json(401, { error: "Invalid API key" }),+ });++ await expect(service.sync("p1")).rejects.toMatchObject({+ status: 409,+ code: "platform_reauthorization_required",+ });+ expect(applyCatalog).not.toHaveBeenCalled();+ });++ it("reuses the key after a failed write without polling the platform again", async () => {+ let applies = 0;+ let polls = 0;+ const service = new PlatformAuthService({+ origin: "https://token.penguin.ooo",+ getKey: async () => undefined,+ applyCatalog: async () => {+ applies += 1;+ if (applies === 1) throw new Error("disk busy");+ return { added: 0, updated: 0, applied: 5 };+ },+ fetchImpl: async (input, init) => {+ const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);+ if (url.pathname.endsWith("/start")) {+ return json(201, { expiresAt: new Date(Date.now() + 60_000).toISOString() });+ }+ expect(init?.redirect).toBe("manual");+ polls += 1;+ return json(200, deliveryBody);+ },+ });+ const started = await service.start({ projectId: "p1", userId: "u1" });+ expect(+ await service.status({ flowId: started.flowId, projectId: "p1", userId: "u1" }),+ ).toMatchObject({ status: "apply_failed", error: "apply_failed" });+ expect(+ await service.retryApply({ flowId: started.flowId, projectId: "p1", userId: "u1" }),+ ).toMatchObject({ status: "completed", applied: 5, changed: true });+ expect(polls).toBe(1);+ expect(applies).toBe(2);+ });++ it("keeps a rate-limited poll pending and retries after the platform backoff", async () => {+ let now = 1_000;+ let polls = 0;+ const service = new PlatformAuthService({+ origin: "https://token.penguin.ooo",+ now: () => now,+ getKey: async () => undefined,+ applyCatalog: async () => ({ added: 0, updated: 0, applied: 5 }),+ fetchImpl: async (input) => {+ const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);+ if (url.pathname.endsWith("/start")) {+ return json(201, { expiresAt: new Date(now + 60_000).toISOString() });+ }+ polls += 1;+ return polls === 1+ ? json(429, { error: "rate_limited", retryAfterSeconds: 2 })+ : json(200, deliveryBody);+ },+ });+ const started = await service.start({ projectId: "p1", userId: "u1" });++ expect(await service.status({ flowId: started.flowId, projectId: "p1", userId: "u1" })).toEqual(+ { status: "pending" },+ );+ now += 1_999;+ expect(await service.status({ flowId: started.flowId, projectId: "p1", userId: "u1" })).toEqual(+ { status: "pending" },+ );+ expect(polls).toBe(1);++ now += 1;+ expect(+ await service.status({ flowId: started.flowId, projectId: "p1", userId: "u1" }),+ ).toMatchObject({ status: "completed", applied: 5, changed: true });+ expect(polls).toBe(2);+ });++ it("does not apply a claimed key when the user cancels while polling", async () => {+ let releasePoll!: (response: Response) => void;+ let markPollStarted!: () => void;+ const pollStarted = new Promise<void>((resolve) => {+ markPollStarted = resolve;+ });+ const applyCatalog = vi.fn(async () => ({ added: 0, updated: 0, applied: 5 }));+ const service = new PlatformAuthService({+ origin: "https://token.penguin.ooo",+ getKey: async () => undefined,+ applyCatalog,+ fetchImpl: async (input) => {+ const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);+ if (url.pathname.endsWith("/start")) {+ return json(201, { expiresAt: new Date(Date.now() + 60_000).toISOString() });+ }+ markPollStarted();+ return new Promise<Response>((resolve) => {+ releasePoll = resolve;+ });+ },+ });+ const started = await service.start({ projectId: "p1", userId: "u1" });+ const status = service.status({ flowId: started.flowId, projectId: "p1", userId: "u1" });+ await pollStarted;++ service.cancel({ flowId: started.flowId, projectId: "p1", userId: "u1" });+ releasePoll(json(200, deliveryBody));++ await expect(status).resolves.toEqual({ status: "cancelled" });+ expect(applyCatalog).not.toHaveBeenCalled();+ });+});diff --git a/packages/server/test/protocol-detect.test.ts b/packages/server/test/protocol-detect.test.tsindex 866fb2d2..ada6a0c7 100644--- a/packages/server/test/protocol-detect.test.ts+++ b/packages/server/test/protocol-detect.test.ts@@ -692,4 +692,41 @@ describe("POST /api/projects/:p/models/detect", () => {await new Promise<void>((resolve) => server.close(() => resolve()));}});++ it("a Penguin Go probe never sends vendor environment keys to the relay endpoint", async () => {+ const seen: Array<{ path: string; auth?: string; xApiKey?: string }> = [];+ const server = antOnlyServer(seen);+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const port = (server.address() as AddressInfo).port;+ const saved = {+ anthropic: process.env.ANTHROPIC_API_KEY,+ openai: process.env.OPENAI_API_KEY,+ penguin: process.env.PENGUIN_GO_API_KEY,+ };+ process.env.ANTHROPIC_API_KEY = "vendor-anthropic-must-not-cross";+ process.env.OPENAI_API_KEY = "vendor-openai-must-not-cross";+ delete process.env.PENGUIN_GO_API_KEY;+ try {+ const response = await api.post(detectUrl(), {+ baseUrl: `http://127.0.0.1:${port}`,+ provider: "penguin-go",+ modelId: "deepseek-flash",+ });+ expect(response.status).toBe(200);+ expect(((await response.json()) as ModelProtocolDetectResponse).detected).toBe(+ "ant-messages",+ );+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.every((request) => request.auth === undefined)).toBe(true);+ expect(seen.every((request) => request.xApiKey === undefined)).toBe(true);+ } finally {+ if (saved.anthropic === undefined) delete process.env.ANTHROPIC_API_KEY;+ else process.env.ANTHROPIC_API_KEY = saved.anthropic;+ if (saved.openai === undefined) delete process.env.OPENAI_API_KEY;+ else process.env.OPENAI_API_KEY = saved.openai;+ if (saved.penguin === undefined) delete process.env.PENGUIN_GO_API_KEY;+ else process.env.PENGUIN_GO_API_KEY = saved.penguin;+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });});diff --git a/packages/web/src/api/client.ts b/packages/web/src/api/client.tsindex b406702e..638b040e 100644--- a/packages/web/src/api/client.ts+++ b/packages/web/src/api/client.ts@@ -13,12 +13,14 @@ import { S } from "../lib/strings";export class ApiError extends Error {readonly status: number;readonly code: string;+ readonly retryAfterSeconds?: number;- constructor(status: number, code: string, message: string) {+ constructor(status: number, code: string, message: string, retryAfterSeconds?: number) {super(message);this.name = "ApiError";this.status = status;this.code = code;+ this.retryAfterSeconds = retryAfterSeconds;}}@@ -102,7 +104,10 @@ export async function apiFetchWithMeta<T>(// Non-JSON error body: fall back to the default message.}if (response.status === 401 && !isAuthEndpoint(path)) onUnauthorized?.();- throw new ApiError(response.status, code, message);+ const retryAfter = response.headers.get("retry-after");+ const retryAfterSeconds =+ retryAfter !== null && /^\d+$/.test(retryAfter) ? Number(retryAfter) : undefined;+ throw new ApiError(response.status, code, message, retryAfterSeconds);}const headerDate = Date.parse(response.headers.get("date") ?? "");diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 10dfbf00..56696e28 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -71,6 +71,9 @@ import type {ModelOAuthStartRequest,ModelOAuthStartResponse,ModelOAuthStatusResponse,+ PlatformAuthFlowStatusResponse,+ PlatformAuthStartResponse,+ PlatformModelSyncResponse,ModelProtocolDetectRequest,ModelProtocolDetectResponse,ModelsResponse,@@ -403,6 +406,37 @@ 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: {} },+ );++export const syncPlatformModels = (projectId: string) =>+ apiFetch<PlatformModelSyncResponse>(+ `/api/projects/${encodeURIComponent(projectId)}/platform-auth/sync`,+ { method: "POST", body: {} },+ );+// Vault environment variables (Agent-level) -------------------------------------------------------export const getVault = (projectId: string, agentId: string) =>diff --git a/packages/web/src/components/ui/provider-logo.tsx b/packages/web/src/components/ui/provider-logo.tsxindex 239075da..66b433e7 100644--- a/packages/web/src/components/ui/provider-logo.tsx+++ b/packages/web/src/components/ui/provider-logo.tsx@@ -119,6 +119,22 @@ const GLYPHS: Record<string, Glyph> = {</>),},+ "penguin-go": {+ // The app's Penguin emblem with its white rounded-square background and gradients+ // removed. Every remaining brand shape inherits currentColor, matching the other+ // preset-provider marks while the original full-colour app logo stays untouched.+ viewBox: "139 129 954 954",+ path: (+ <>+ <path d="M475 558v3c-1 0-3 1-4 1-16 4-31 9-47 14-1 0-2 1-4 1-76 26-179 67-217 143-7 15-9 29-4 45 2 5 4 10 8 14s4 4 4 6c1 1 3 1 4 2s2 1 3 2c9 6 18 10 29 14 4 1 4 1 8 3v2c-23 4-48-1-67-14-12-9-19-19-22-34-2-28 8-50 27-71 1-2 3-4 5-6s4-4 5-6l3-3h2c1-1 1-3 2-4 20-19 44-35 69-48 1-1 3-2 4-2 14-8 29-15 44-21l9-3c36-15 74-26 112-34 1 0 2 0 3-1 17-3 17-3 24-3m571 110c-7 13-22 25-33 35l-3 3c-7 6-15 12-23 18-1 1-2 2-3 2-71 54-153 93-236 122-1 0-2 1-3 1-31 11-63 20-95 27-1 0-1 0-4 1-65 14-132 17-198 8 0-1-1-1-1-2 4-1 7-2 11-2 141-16 278-54 423-118 1 0 2-1 3-1 26-12 51-24 75-38 1 0 1 0 5-3 14-8 27-16 40-24 1-1 2-1 4-2 11-8 21-16 32-24 4-3 4-3 6-3" />+ <path d="M532 329c35 18 68 41 97 68l9 6 12 12c3 3 6 6 10 9 3 3 6 5 8 8 36 34 36 34 56 42l-3-3-17-17c1-5 2-8 5-13 0-1 0-1 2-4 1-2 1-4 2-5 1-2 2-3 2-5 13-26 25-51 45-72 0-1 0-1 2-3 24-26 60-37 94-39 20-1 39 1 58 6 19 6 39 8 58 2-1 6-3 10-7 14-3 2-6 4-9 5 1 1 2 1 3 2 16 11 26 24 30 44 3 18 3 18 0 24h3c50-4 50-4 71 10 2 2 2 2 3 7-5 5-10 6-16 8-31 9-53 23-72 49-1 1-2 2-3 4-24 33-41 70-57 108-17 42-39 80-68 114-1 1-1 2-2 2-10 12-22 24-34 34-2 1-4 3-6 5-12 10-24 18-37 26-1 1-3 2-4 3-73 47-165 69-251 56-21-3-38 2-58 8-1 0-1 0-4 1-2 1-3 1-4 2-2 0-3 0-4 1-6 2-8 7-11 13-4 7-8 14-13 20l-3 3c-9 11-19 23-34 26-6 0-7 0-11-4-2-3-1-6-1-10v-3c-1 1-3 2-4 3-7 4-12 6-20 5-4-2-5-3-6-7 0-8 3-13 8-18h-3c-4-1-4-1-6-3-2-4-2-5-1-9 17-29 46-44 77-53-17-3-37-6-53 2-2 2-4 5-6 7-4 6-9 11-14 16l-3 3c-12 12-27 25-45 29-5 0-6 0-10-4-2-2-2-2-2-6 1-5 2-7 4-11-10 3-10 3-13 4-5 1-8 1-13 0-4-4-4-4-5-8 1-7 6-11 11-16-2-1-3-1-5-2l-2-2c1-11 11-18 19-25 18-16 40-27 63-35 5-2 9-4 13-8l4-4c-2 0-3-1-5-1-18-4-34-10-50-21v-3h3c33-3 64-17 86-42 3-3 6-7 8-11 3-3 6-7 10-10 2-3 4-5 6-8 6-7 13-14 19-21 2-1 3-2 4-3 7-7 14-14 22-20 2-2 4-4 6-5 32-27 68-49 104-69l3 3c9 7 20 10 32 12-2-1-3-2-5-3-24-15-41-37-55-62 0-1 0-1-3-5-5-8-9-16-14-25-15-27-32-52-51-76-1-1-2-3-3-4-6-8-13-15-19-23-4-4-8-9-12-14-1-1-2-2-3-4-12-15-12-15-12-23 1-4 1-4 3-6 25-15 74 11 97 22m288 38-3 3c-16 14-26 35-27 56 0 15 1 27 8 40 1 1 1 2 2 3 10 18 25 29 44 38 2 0 3 1 5 1v2l-3 1c-43 10-81 41-108 76-2 2-4 5-6 7-4 5-8 11-12 16-5 7-11 14-17 21-2 3-5 7-8 10-47 58-107 90-180 104-30 6-56 19-81 38-2 2-4 3-6 4-2 2-3 3-5 4 3 3 9 4 13 6 7 2 14 4 21 7 27 10 54 17 83 20h4c80 7 163-20 228-65 1-1 2-2 4-3 25-17 50-37 69-61 2-2 3-5 5-7 28-32 46-71 62-109 17-40 36-78 63-112-3-2-6-3-10-4-15-4-26-12-37-23 1-2 2-3 3-5 7-10 9-21 7-33-4-19-12-32-29-43-29-16-64-13-89 8" />+ <path d="M985 405h3c0 2 1 4 1 6h4c49-5 49-5 67 7 4 4 4 4 6 7-1 2-1 3-2 5-1 0-2 1-4 1-3 1-6 2-10 3l-9 3c-19 6-35 15-49 30l-3 3-5 5-6 6c-3-1-5-3-8-4 1-5 2-7 6-11l-12-3c0-1-1-3-1-4 1-1 1-2 2-3 3-5 5-9 6-14 1-2 1-3 2-5 2-6 2-6 2-8l3-3c1-3 1-5 2-8 1-5 2-8 5-13" />+ <path d="M308 782c1 0 1 1 2 1v4c1 1 3 1 4 2v2c2 0 3-1 5-1l2 2c8 8 15 11 26 11 3 1 7 3 10 4h5l3 1c-2 8-8 14-14 20-2 3-3 5-5 7-13 14-31 31-51 32-5 0-5 0-9-3-2-6 0-11 3-17q-4.5 0-9 3c-5 2-10 2-15 1-3-1-3-1-6-4-1-5 0-8 3-12 2-3 4-5 7-8l-6-3c0-2-1-4-1-6 10-12 21-23 35-31h3v-2c3-1 5-2 8-3" />+ <path d="M393 824c1 1 2 1 3 2h4c6 1 7 3 11 6 3 1 7 2 10 3 1 1 2 1 4 2 3 1 3 1 8 2 6 1 7 2 10 7l-1 3h-2c-1 2-1 3-2 5-9 19-25 45-45 53-6 2-10 4-16 2-4-4-4-5-4-10 0-2 1-4 1-6-1 0-2 1-3 1-1 1-2 2-3 2-1 1-3 2-4 2-5 3-9 3-15 3-3-2-5-3-6-7 0-7 3-13 8-18-1 0-3-1-4-1-4-1-4-1-6-3-1-5 0-7 2-11 1-2 2-3 3-4s1-2 2-3l8-8c0-1 0-1 3-3 23-22 23-22 34-19" />+ <path d="M880 387c10 6 19 13 23 25 1 7 1 12-2 18-4 5-8 8-15 8-8 0-11-2-16-7-4-9-3-17 0-25 2-4 2-4 6-8h2c-4-6-10-8-17-10h-15c2-4 2-4 5-6 10-3 20 1 29 5m-3 16c-2 2-2 2-2 6s0 4 4 8c5-3 5-3 6-6 0-3 0-3-3-8Z" />+ </>+ ),+ },"qwen-token-plan": QWEN_GLYPH,"qwen-pay-as-you-go": QWEN_GLYPH,minimax: {diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 3f401b8d..c82b5fba 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -104,7 +104,7 @@ import { buildInputHistory } from "./input-history";import { buildOutline } from "./outline-model";import { GoalStatusBanner } from "./goal-banner";import { handoffMessage, modelSwitchMessage } from "./agent-handoff";-import { hasConfiguredKey, sameModelRef } from "../models/model-grouping";+import { hasConfiguredKey, promotedPricing, sameModelRef } from "../models/model-grouping";import { providerInfo } from "@prismshadow/penguin-core/model-catalog";import { WorkspaceBrowser } from "./workspace-browser";import { ChatMemoryView } from "./memory-view";@@ -1548,8 +1548,11 @@ export function ChatPage() {);// Real-time cost for this turn: converts the Task's bucketed usage using the session Model's- // (paired reference) current pricing; null if no pricing is configured.- const modelPricing = models?.models.find((m) => sameModelRef(m, activeModelRef))?.pricing;+ // (paired reference) current pricing; null if no pricing is configured. That pricing is the+ // list price, so a promotion the models response reports for the Model comes off it here, as+ // it does on the recorded cost.+ const activeModel = models?.models.find((m) => sameModelRef(m, activeModelRef));+ const modelPricing = promotedPricing(activeModel?.pricing, activeModel?.discount);const ctx: StreamRenderContext = {pendingApprovals: stream.pendingApprovals,onApprove,diff --git a/packages/web/src/features/models/catalog-sync.ts b/packages/web/src/features/models/catalog-sync.tsindex 44eaeef0..480df29d 100644--- a/packages/web/src/features/models/catalog-sync.ts+++ b/packages/web/src/features/models/catalog-sync.ts@@ -2,16 +2,25 @@* One-click sync of the Project model table with the built-in catalog ("sync presets" next* to the search box): union semantics — catalog entries not configured locally are added;* entries present on both sides are reset to the catalog's fields (context window, pricing,- * protocol, base URL, vision — the catalog wins wherever the two differ, including removing- * pricing the catalog doesn't carry); locally added models (including user-defined groups)- * are kept untouched. Credentials are never touched: merged rows carry no apiKey input (the- * PUT keeps the stored key) and existing rows keep their credential display state.+ * protocol, base URL, vision, and the promotion — the catalog wins wherever the two differ).+ * Missing catalog pricing removes local pricing, and a missing catalog promotion removes the+ * stored one. Locally added models (including user-defined groups) are kept untouched.+ * Credentials are never touched: merged rows carry no apiKey input (the PUT keeps the stored+ * key) and existing rows keep their credential display state.*+ * The price a sync writes is the catalog's list price; the promotion running on it is stored by+ * the server outside the config file, which is why it travels as a declaration rather than as a+ * field — see {@link catalogPromotion}, which also covers the Penguin Go group it leaves alone.* The display name is the one catalog field that is filled but never overwritten — see* {@link displayNameFill}.*/-import { catalogEntryFor, presetModelEntries } from "@prismshadow/penguin-core/model-catalog";+import {+ PENGUIN_GO_PROVIDER_ID,+ catalogEntryFor,+ presetModelEntries,+} from "@prismshadow/penguin-core/model-catalog";import type { ModelsResponse } from "@prismshadow/penguin-server/api";+import { fractionOff } from "./model-grouping";import type { RowState } from "./models-page";type PresetEntry = ReturnType<typeof presetModelEntries>[number];@@ -24,13 +33,20 @@ type CatalogFields = ReturnType<typeof presetFields>;/** The catalog-owned fields of a row, in RowState's string-typed form (mirrors toRow). */function presetFields(p: PresetEntry) {+ const pricing = p.pricing+ ? {+ cacheRead: String(p.pricing.cache_read),+ cacheWrite: String(p.pricing.cache_write),+ output: String(p.pricing.output),+ }+ : undefined;return {vision: p.vision !== false,contextWindow: p.context_window !== undefined ? String(p.context_window) : "",clientType: p.client_type ?? "",- cacheRead: p.pricing ? String(p.pricing.cache_read) : "",- cacheWrite: p.pricing ? String(p.pricing.cache_write) : "",- output: p.pricing ? String(p.pricing.output) : "",+ cacheRead: pricing?.cacheRead ?? "",+ cacheWrite: pricing?.cacheWrite ?? "",+ output: pricing?.output ?? "",baseUrl: p.base_url ?? "",};}@@ -56,9 +72,50 @@ function displayNameFill(p: PresetEntry, current: string | undefined): string |return catalogEntryFor(p.provider, p.model_id)?.displayName;}+/** A promotion as the catalog declares it for one row: `undefined` is "none". */+type CatalogPromotion = { discount: number | undefined };++/**+ * The promotion a sync declares for a preset row, or `null` for a row whose promotion is not the+ * catalog's to declare.+ *+ * The catalog owns it on the same terms as the price it runs on: its flat `discount` when that+ * is a fraction in (0, 1), and no promotion otherwise (`discount: undefined`, sent as `null` so+ * a promotion that has ended is cleared). Like the display name it is looked up in the catalog,+ * because the persisted entry shape carries no promotion.+ *+ * Merged rows declare it whether or not anything about them changed. A row whose price the merge+ * rewrites has to: the server keeps a stored promotion only through saves that leave the row's+ * price alone. On every other row it restates the catalog's value, so what the save stores+ * follows the catalog rather than whatever promotion the page last loaded.+ *+ * Penguin Go rows get `null`: that group's promotions arrive with the platform's own catalog, on+ * authorization and on the group's Sync, so this sync never compares them and never changes+ * them. A merge that rewrites such a row's price still has to restate the promotion it already+ * has, or the server would drop it along with the old price (see syncRowsWithCatalog).+ */+function catalogPromotion(p: PresetEntry): CatalogPromotion | null {+ if (p.provider === PENGUIN_GO_PROVIDER_ID) return null;+ return { discount: fractionOff(catalogEntryFor(p.provider, p.model_id)?.discount) };+}++/** Whether `current` differs from the catalog's promotion (never, on a row it is not the catalog's). */+function promotionDiffers(+ promotion: CatalogPromotion | null,+ current: number | undefined,+): boolean {+ return promotion !== null && current !== promotion.discount;+}++/** The fields that make a row declare `promotion` on save (see rowToEntry). */+function declared(promotion: CatalogPromotion): Pick<RowState, "discount" | "discountDeclared"> {+ return { discount: promotion.discount, discountDeclared: true };+}+/** A brand-new row for a catalog entry not configured locally (original: null -> added on PUT). */function presetToRow(p: PresetEntry): RowState {const displayName = displayNameFill(p, undefined);+ const promotion = catalogPromotion(p);return {provider: p.provider,modelId: p.model_id,@@ -69,6 +126,7 @@ function presetToRow(p: PresetEntry): RowState {// Deliberately outside presetFields, which the catalog owns outright — on an existing row// the same lookup is fill-only (see displayNameFill)....(displayName !== undefined ? { displayName } : {}),+ ...(promotion !== null ? declared(promotion) : {}),// The output cap and fast mode are user-owned, not catalog-owned (deliberately outside// presetFields, so a sync never clobbers them on existing rows): fresh rows inherit the// Agent setting / default to off.@@ -85,7 +143,9 @@ function presetToRow(p: PresetEntry): RowState {* `models-page.tsx`'s `toRow` the catalog owns — deliberately, so the badge below can read a* model table the page has not loaded into row state. `test/catalog-sync.test.ts` pins the two* together: whatever `toRow` does to a DTO, this must do to the same DTO, or the badge and the- * sync button would disagree about whether anything is out of date.+ * sync button would disagree about whether anything is out of date. The promotion is the one+ * catalog-owned value compared outside these fields, and both sides read it verbatim: `toRow`+ * copies `discount` straight off the DTO.*/function savedFields(m: ModelDto): CatalogFields {return {@@ -114,10 +174,10 @@ export interface CatalogDelta {** The same union `syncRowsWithCatalog` applies, so the two cannot disagree about whether there* is anything to do: catalog entries the table does not carry are additions, entries it does- * carry whose catalog-owned fields differ — or whose display name is blank — are updates, and- * locally added models are invisible to both. `refs` is what a dismissal is stamped against, so- * a later catalog release touching a different model raises the badge again (see- * `lib/todo-badges.ts`).+ * carry whose catalog-owned fields differ — a promotion-only difference included, outside the+ * Penguin Go group — or whose display name is blank are updates, and locally added models are+ * invisible to both. `refs` is what a dismissal is stamped against, so a later catalog release+ * touching a different model raises the badge again (see `lib/todo-badges.ts`).*/export function catalogDelta(models: readonly ModelDto[],@@ -138,6 +198,7 @@ export function catalogDelta(// carrying rows with no name would hold a badge the button answers "already up to date".if (displayNameFill(p, entry.displayName) !== undefined ||+ promotionDiffers(catalogPromotion(p), entry.discount) ||(Object.keys(target) as (keyof CatalogFields)[]).some((k) => fields[k] !== target[k])) {delta.updated += 1;@@ -152,6 +213,11 @@ export function catalogDelta(* credential state, and list position (fields are updated in place); catalog-only entries* are appended in catalog order. Returns the merged rows plus added/updated counts for the* success toast (updated counts only rows the merge actually rewrote).+ *+ * Every preset row outside the Penguin Go group leaves the merge declaring its catalog+ * promotion, rewritten or not (see catalogPromotion), so such a row is a new object even when+ * nothing about it changed: `updated` is the count of changes, not object identity. A Penguin Go+ * row the merge rewrites declares the promotion it already has.*/export function syncRowsWithCatalog(rows: RowState[],@@ -172,12 +238,23 @@ export function syncRowsWithCatalog(const row = next[i]!;const fields = presetFields(p);const fill = displayNameFill(p, row.displayName);+ const promotion = catalogPromotion(p);const changed =fill !== undefined ||+ promotionDiffers(promotion, row.discount) ||(Object.keys(fields) as (keyof typeof fields)[]).some((k) => row[k] !== fields[k]);- if (changed) {- next[i] = { ...row, ...fields, ...(fill !== undefined ? { displayName: fill } : {}) };- updated += 1;+ if (changed) updated += 1;+ if (changed || promotion !== null) {+ next[i] = {+ ...row,+ ...fields,+ ...(fill !== undefined ? { displayName: fill } : {}),+ // Only a rewritten row reaches here without a catalog promotion: a Penguin Go row,+ // which keeps the platform's promotion it already has.+ ...(promotion !== null+ ? declared(promotion)+ : { discount: row.discount, discountDeclared: true }),+ };}}return { rows: next, added, updated };diff --git a/packages/web/src/features/models/model-grouping.ts b/packages/web/src/features/models/model-grouping.tsindex 77bc38bb..6872d52f 100644--- a/packages/web/src/features/models/model-grouping.ts+++ b/packages/web/src/features/models/model-grouping.ts@@ -19,7 +19,6 @@import {MODEL_PROVIDERS,catalogEntryFor,- effectivePricing,offPeakAt,} from "@prismshadow/penguin-core/model-catalog";import type { ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";@@ -47,6 +46,12 @@ export interface ModelRowLike {/** Upstream model id (i.e. the stored model_id). */modelId: string;displayName?: string;+ /**+ * The row's running promotion, as the models endpoint reports it: a fraction off the stored+ * price, which is the list price (0.5 = half price). The server keeps it apart from the config+ * file and applies it when it prices usage. Absent when the row has none.+ */+ discount?: number;}/** Synthesized vendor info for a user-defined group: OpenAI protocol semantics (env fallback OPENAI_*), no external links or gateway endpoint. */@@ -190,18 +195,32 @@ export interface PricingBucketsLike {/** The discount decoration for one model card, and the price it makes the row cost right now. */export interface DiscountedPrice {- /** Whole-percent rate off list, as the badge shows it (50 for a half-price row). */+ /**+ * Whole-percent saving off the list price, as the badge shows it (50 for a half-price row). A+ * promotion and a live off-peak tier combine into one figure: 20% off, then half of the rest,+ * is 60.+ */percent: number;/*** What the seller bills for this row right now, in USD per million tokens — the figure the- * card prints. For a flat promotion this is the stored price, already discounted at sync- * time; for a scheduled one the stored price is the peak price and this is the reduced rate.+ * card prints: the stored list price less the running promotion and, while the off-peak tier+ * is live, less its rate as well.+ */+ billed: BucketPrices;+ /**+ * True when the saving is the time-of-day tier alone, so the badge can explain when it+ * applies. A row that also runs a promotion is explained as the promotion.*/- billed: { cacheRead: number; cacheWrite: number; output: number };- /** True when the rate is a time-of-day one, so the badge can explain when it applies. */scheduled: boolean;}+/** The three price buckets in USD per million tokens, in the numeric shape the DTO carries. */+export interface BucketPrices {+ cacheRead: number;+ cacheWrite: number;+ output: number;+}+/** One bucket as a finite number, or undefined for an unpriced ("" / absent) field. */function bucketValue(v: number | string | undefined): number | undefined {if (typeof v === "number") return Number.isFinite(v) ? v : undefined;@@ -211,54 +230,78 @@ function bucketValue(v: number | string | undefined): number | undefined {}/**- * The discount decoration for one model row, or undefined for a row that carries none.+ * `value` as a fraction off a price, or undefined when it is not one. Only (0, 1) says anything:+ * a badge built from a value outside that range reads as `-0%`, as `-100%` beside a "Free" tag,+ * or as `--20%`.+ */+export function fractionOff(value: number | undefined): number | undefined {+ return value !== undefined && value > 0 && value < 1 ? value : undefined;+}++/**+ * A price as the row's running promotion bills it: every bucket less `discount`, or `pricing`+ * itself when there is no promotion. Stored prices are list prices, so anything estimating what+ * usage costs from them has to take off the promotion the server takes off when it records that+ * cost. A time-of-day tier is not applied here.+ */+export function promotedPricing(+ pricing: BucketPrices | undefined,+ discount: number | undefined,+): BucketPrices | undefined {+ const promotion = fractionOff(discount);+ if (pricing === undefined || promotion === undefined) return pricing;+ return {+ cacheRead: pricing.cacheRead * (1 - promotion),+ cacheWrite: pricing.cacheWrite * (1 - promotion),+ output: pricing.output * (1 - promotion),+ };+}++/**+ * The discount decoration for one model row, or undefined for a row billed at its stored price.*- * A row qualifies only when its (provider, modelId) names a catalog entry on a promotion AND- * its stored price is still exactly the price that entry expects to be stored. Prices are- * editable, and a hand-typed number has nothing to do with the seller's list price — marking it- * would invent a saving the user is not getting. The same guard covers a Project that has not- * run "sync presets" yet: its rows still hold whatever price they were created with.+ * The stored price is always the list price, and two things can take something off it:*- * Which price that is differs by promotion kind, and the difference is the point:+ * - A **promotion** is the row's `discount`, which the server keeps apart from the config file:+ * presets are seeded and synced with the catalog's, a platform sync writes the platform's, and+ * a save that changes the row's price clears it. Keeping it true to the price stored beside+ * it is the server's job, so it is taken as given here.+ * - An **off-peak tier** comes from the catalog entry's schedule. It changes twice a day, so+ * nothing stores it: the reduction is applied here, against `now`, and inside the peak windows+ * the row is simply at list price. It applies only while the stored price is still exactly the+ * catalog's peak price. Prices are editable, and a hand-typed number has nothing to do with the+ * seller's peak price — halving it would invent a saving the user is not getting.*- * - A **flat** promotion is a single rate the seller bills until it lapses, so `sync presets`- * bakes it in and the stored number is already the discounted one.- * - A **scheduled** one changes twice a day. Baking it in would put a number on disk that meant- * something different an hour later, and would make re-syncing rewrite prices by the clock —- * so the peak price is stored and the reduction is applied here, against `now`. Inside the- * peak windows the row is simply at list price and carries no mark at all.+ * When both apply, the two reductions multiply.*/export function discountedPrice(row: ModelRowLike & PricingBucketsLike,now: Date = new Date(),): DiscountedPrice | undefined {+ const cacheRead = bucketValue(row.cacheRead);+ const cacheWrite = bucketValue(row.cacheWrite);+ const output = bucketValue(row.output);+ // An unpriced row has no price to take anything off.+ if (cacheRead === undefined || cacheWrite === undefined || output === undefined) return undefined;+ const promotion = fractionOff(row.discount) ?? 0;const entry = catalogEntryFor(row.provider, row.modelId);- if (entry?.pricing === undefined) return undefined;- const schedule = entry.offPeakDiscount;- const rate = schedule?.rate ?? entry.discount;- // A fraction off, so only (0, 1) says anything: `effectivePricing` already ignores 0, and a- // badge built from a value outside that range reads as `-0%`, `-100%` beside a "Free" tag, or- // `--20%`. A stray 0 is the plausible one — the field's own doc says a lapsed promotion is one- // field to delete, and deleting a digit is the near miss.- if (rate === undefined || rate <= 0 || rate >= 1) return undefined;- const expected = schedule !== undefined ? entry.pricing : effectivePricing(entry);- if (expected === undefined) return undefined;- const same =- bucketValue(row.cacheRead) === expected.cache_read &&- bucketValue(row.cacheWrite) === expected.cache_write &&- bucketValue(row.output) === expected.output;- if (!same) return undefined;- if (schedule !== undefined && !offPeakAt(schedule, now)) return undefined;- const billed = effectivePricing(entry, now);- if (billed === undefined) return undefined;+ const schedule = entry?.offPeakDiscount;+ const peak = entry?.pricing;+ const tier =+ schedule !== undefined &&+ peak !== undefined &&+ cacheRead === peak.cache_read &&+ cacheWrite === peak.cache_write &&+ output === peak.output &&+ offPeakAt(schedule, now)+ ? (fractionOff(schedule.rate) ?? 0)+ : 0;+ if (promotion === 0 && tier === 0) return undefined;+ const off = (v: number): number => Math.round(v * (1 - promotion) * (1 - tier) * 1e6) / 1e6;return {- percent: Math.round(rate * 100),- billed: {- cacheRead: billed.cache_read,- cacheWrite: billed.cache_write,- output: billed.output,- },- scheduled: schedule !== undefined,+ percent: Math.round((promotion + tier - promotion * tier) * 100),+ billed: { cacheRead: off(cacheRead), cacheWrite: off(cacheWrite), output: off(output) },+ scheduled: tier > 0 && promotion === 0,};}diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex e1ce09a4..c63fbf08 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -50,8 +50,10 @@ import type {ModelVisionDetectRequest,} from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";+import { ApiError } from "../../api/client";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";+import { ICON_SIZE } from "../../lib/icon-scale";import { useDocumentTitle } from "../../lib/use-document-title";import { useProject } from "../../state/project";import { useAuth } from "../../state/auth";@@ -77,18 +79,21 @@ import { EmptyState } from "../../components/ui/empty-state";import { formatDateTime, humanizeTokens } from "../../lib/format";import {MODEL_PROVIDERS,+ PENGUIN_GO_BASE_URL,+ PENGUIN_GO_PROVIDER_ID,canonicalClientType,catalogEntryFor,fastModeProtocol,modelHomepageUrl,providerClientType,providerInfo,- resolveModelEnv,+ resolveProviderModelEnv,} from "@prismshadow/penguin-core/model-catalog";import type { FastModeProtocol, ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";import {allGroupKeys,discountedPrice,+ fractionOff,groupModelRows,hasConfiguredKey,isFreeModel,@@ -132,6 +137,7 @@ 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";/** 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: "¥" };@@ -182,6 +188,8 @@ const KEY_ICON ="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4";/** Arrow entering a door: authorize with the provider and come back with a key. */const SIGN_IN_ICON = "M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4M10 17l5-5-5-5M15 12H3";+/** Rotate clockwise: refresh an already-authorized platform catalog. */+const SYNC_ICON = "M23 4v6h-6M20.49 15a9 9 0 1 1-2.12-9.36L23 10";/** Speed-test glyphs (24x24 line paths): gauge for the group action, clock = TTFT, zap = TPS. */const GAUGE_ICON = "M12 14l3.5-3.5M20.49 17A10 10 0 1 0 3.5 17";@@ -313,9 +321,22 @@ export interface RowState {* their preset pin. Never persisted empty for a custom-like entry — see protocolForPersist.*/clientType: string;+ /** Price buckets in USD per million tokens: the list price, any promotion kept in `discount`. */cacheRead: string;cacheWrite: string;output: string;+ /**+ * The running promotion the server reports for this row: a fraction off the list price above+ * (0.5 = half price), stored outside the config file and applied when usage is priced. Absent+ * when the row has none.+ */+ discount?: number;+ /**+ * Set only by the "sync presets" merge: the row states its catalog promotion on save —+ * `discount`, or none to clear one — instead of leaving the server to keep or clear what it+ * has stored (see rowToEntry and catalog-sync.ts).+ */+ discountDeclared?: boolean;/** Current base_url input; compared against originalBaseUrl to decide omit/override/clear (null). */baseUrl: string;originalBaseUrl: string;@@ -460,10 +481,10 @@ export function modelLabelOf(displayName: string | undefined, modelId: string):** Loading rounds the stored USD to four decimals so it is typeable (`usdToInput`), so* re-encoding an untouched field would commit that rounding as the new price: a silent edit of- * a number nobody changed. Small, but not nothing — a catalog row billed at CNY 0.05 per- * million lands on $0.0071 instead of $0.00714285…, enough to move a promoted row off the- * figure its seller bills and drop the discount mark that says so. Editing the field is what- * makes the typed value authoritative.+ * a number nobody changed. Small, but not nothing — a catalog row listed at CNY 0.05 per+ * million lands on $0.0071 instead of $0.00714285…, which is a price change: the save would+ * cancel the row's promotion, and a scheduled row would leave the catalog's peak price and+ * lose its off-peak mark. Editing the field is what makes the typed value authoritative.*/export function priceToSubmit(formValue: string,@@ -503,6 +524,7 @@ export function toRow(m: ModelsResponse["models"][number]): RowState {if (m.envKey !== undefined) row.envKey = m.envKey;if (m.envKeyMasked !== undefined) row.envKeyMasked = m.envKeyMasked;if (m.credential) row.credential = m.credential;+ if (m.discount !== undefined) row.discount = m.discount;return row;}@@ -614,6 +636,10 @@ export function rowToEntry(row: RowState): ModelUpdateEntry {) {entry.pricing = { cacheRead: cr, cacheWrite: cwr, output: out };}+ // Promotion: sent only when the preset sync declared one (a number stores it, null clears it).+ // Every other save omits it and leaves the stored promotion to the server, which keeps it+ // unless this entry renames the row or changes its price.+ if (row.discountDeclared) entry.discount = row.discount ?? null;if (row.apiKeyInput.trim()) entry.apiKey = row.apiKeyInput.trim();if (row.clearApiKey) entry.clearApiKey = true;const baseUrl = row.baseUrl.trim();@@ -860,6 +886,28 @@ export function ModelsPage() {refreshProjectTodos(projectId);};+ const syncPlatformModels = async () => {+ if (!projectId) return;+ setBusy(true);+ try {+ const res = await api.syncPlatformModels(projectId);+ setRows(res.models.map(toRow));+ setDefaultModel(res.defaultModel);+ setVisionModel(res.visionModel);+ if (res.added === 0 && res.updated === 0) toastInfo(S.models.syncUpToDate);+ else toastSuccess(S.models.syncDone(res.added, res.updated));+ } catch (error) {+ if (error instanceof ApiError && error.code === "platform_reauthorization_required") {+ keyLanded.current = false;+ setOauthFor(PENGUIN_GO_PROVIDER_ID);+ } else {+ toastError(apiErrorText(error));+ }+ } finally {+ setBusy(false);+ }+ };+/*** Group speed test: one real request per model, strictly sequential (concurrent probes* trip provider rate limits), each result written to the card as it lands. The@@ -999,7 +1047,7 @@ export function ModelsPage() {);},// dragleave also fires when the pointer merely crosses onto one of the header's OWN- // children — the collapse button spans most of the row, and up to five actions+ // children — the collapse button spans most of the row, and up to six actions// follow it — so clearing unconditionally strobes the indicator. relatedTarget is// where the drag is going: still inside means nothing changed.onDragLeave: (e: ReactDragEvent) => {@@ -1125,13 +1173,16 @@ export function ModelsPage() {{groups.map((group) => {const open = isGroupExpanded(expanded, group.provider.id, searching);const drag = groupDragProps(group.provider.id);+ const platformAuthorized =+ group.provider.id === PENGUIN_GO_PROVIDER_ID &&+ group.rows.some((row) => Boolean(row.credential?.apiKeyMasked));return (// The drop indicator is drawn against the WHOLE group, so "below" reads as// after this group and its model cards rather than between the header and// its own first card. It needs this wrapper to live in: the section clips// its children (overflow-hidden carries the expand/collapse transition).// Absolutely positioned, so it costs no layout width and cannot push the- // header's up-to-five actions out of a narrow page.+ // header's up-to-six actions out of a narrow page.<div key={group.provider.id} className="relative">{drag.dropEdge !== null && (<div@@ -1205,6 +1256,23 @@ export function ModelsPage() {</span>)}</button>+ {isOwner && platformAuthorized && (+ // A stored Penguin Go key enables catalog refresh, but authorization remains+ // a separate action so the owner can replace it with another account.+ // Sync leads the group actions and sits immediately before Add model.+ <Button+ size="sm"+ variant="ghost"+ className="shrink-0"+ disabled={busy}+ aria-label={`${S.models.platformSync} ${group.provider.label}`}+ title={S.models.platformSync}+ onClick={() => void syncPlatformModels()}+ >+ <GlyphIcon d={SYNC_ICON} size={ICON_SIZE.groupHeaderAction} />+ <span className="hidden @3xl:inline">{S.models.platformSync}</span>+ </Button>+ )}{isOwner && (// Add-model entry point: present on every group header (including// custom), new models belong to that group. Narrow rows never hide a@@ -1219,29 +1287,30 @@ export function ModelsPage() {title={S.models.addToGroup}onClick={() => setAddingTo(group.provider.id)}>- <GlyphIcon d={PLUS_ICON} size={13} />+ <GlyphIcon d={PLUS_ICON} size={ICON_SIZE.groupHeaderAction} /><span className="hidden @3xl:inline">{S.models.addToGroup}</span></Button>)}- {isOwner && group.provider.oauth && (- // Authorize-a-key action: rendered off the group's own catalog- // descriptor, so a provider gains this button by publishing a flow- // rather than by being named here. Same narrow-row rule as its- // neighbours — the label goes, the icon and its names stay. It leads the- // manual key action: where a group can mint a key, that is the shorter path.- <Button- size="sm"- variant="ghost"- className="shrink-0"- disabled={busy}- aria-label={`${S.models.oauthKey} ${group.provider.label}`}- title={S.models.oauthKey}- onClick={() => setOauthFor(group.provider.id)}- >- <GlyphIcon d={SIGN_IN_ICON} size={13} />- <span className="hidden @3xl:inline">{S.models.oauthKey}</span>- </Button>- )}+ {isOwner &&+ (group.provider.oauth || group.provider.id === PENGUIN_GO_PROVIDER_ID) && (+ // Authorize-a-key action: rendered off the group's own catalog+ // descriptor, so a provider gains this button by publishing a flow+ // rather than by being named here. Same narrow-row rule as its+ // neighbours — the label goes, the icon and its names stay. It leads the+ // manual key action: where a group can mint a key, that is the shorter path.+ <Button+ size="sm"+ variant="ghost"+ className="shrink-0"+ disabled={busy}+ aria-label={`${S.models.oauthKey} ${group.provider.label}`}+ title={S.models.oauthKey}+ onClick={() => setOauthFor(group.provider.id)}+ >+ <GlyphIcon d={SIGN_IN_ICON} size={ICON_SIZE.groupHeaderAction} />+ <span className="hidden @3xl:inline">{S.models.oauthKey}</span>+ </Button>+ )}{isOwner && group.provider.id !== "custom" && (// Bulk key action: icon-only while this row is narrow, labeled from// @3xl up. The button itself never disappears — aria-label + title@@ -1255,7 +1324,7 @@ export function ModelsPage() {title={S.models.groupApiKey}onClick={() => setGroupKeyFor(group.provider.id)}>- <GlyphIcon d={KEY_ICON} size={13} />+ <GlyphIcon d={KEY_ICON} size={ICON_SIZE.groupHeaderAction} /><span className="hidden @3xl:inline">{S.models.groupApiKey}</span></Button>)}@@ -1273,7 +1342,7 @@ export function ModelsPage() {}onClick={() => setSpeedFor(group.provider.id)}>- <GlyphIcon d={GAUGE_ICON} size={13} />+ <GlyphIcon d={GAUGE_ICON} size={ICON_SIZE.groupHeaderAction} />{/* Compact rows keep this accessible action icon-only. */}<span className="hidden @3xl:inline">{speedRunning === group.provider.id@@ -1295,7 +1364,7 @@ export function ModelsPage() {title={S.models.deleteGroup}onClick={() => setDeleteGroupFor(group.provider.id)}>- <GlyphIcon d={TRASH_ICON} size={13} />+ <GlyphIcon d={TRASH_ICON} size={ICON_SIZE.groupHeaderAction} /><span className="hidden @3xl:inline">{S.models.deleteGroup}</span></Button>)}@@ -1418,30 +1487,48 @@ export function ModelsPage() {opens a NEW authorization, which is how a completed authorization ended up offeringitself again. `count` is only read while the flow is still running, so a reload'smomentary absence of rows reads as zero and is never seen. */}- {projectId && oauthFor !== null && (- <ModelOAuthDialog- projectId={projectId}- provider={MODEL_PROVIDERS.find((p) => p.id === oauthFor) ?? userProviderInfo(oauthFor)}- count={rows?.filter((r) => r.provider === oauthFor).length ?? 0}- onClose={() => {- setOauthFor(null);- // The reload waits for the dismissal rather than racing the open dialog: the key- // was written server-side, so the table in hand is stale in exactly one place, and- // reloading brings the masked key back. Gated on a key having landed, because- // `load` also drops this Project's speed results — measurements that cost real API- // quota and live only in page memory — and a cancelled flow changed nothing.- if (keyLanded.current) void load();- keyLanded.current = false;- }}- onApplied={() => {- // The dialog stays open and reports the outcome itself (its `done` phase), because- // the authorization ran in another tab and a toast would be announced to a window- // nobody is looking at. All this seam does is record that the dismissal has a- // reload to do.- keyLanded.current = true;- }}- />- )}+ {projectId &&+ oauthFor !== null &&+ (oauthFor === PENGUIN_GO_PROVIDER_ID ? (+ <PlatformKeyAuthDialog+ projectId={projectId}+ providerLabel={+ MODEL_PROVIDERS.find((provider) => provider.id === oauthFor)?.label ?? oauthFor+ }+ count={rows?.filter((row) => row.provider === oauthFor).length ?? 0}+ onClose={() => {+ setOauthFor(null);+ if (keyLanded.current) void load();+ keyLanded.current = false;+ }}+ onApplied={() => {+ keyLanded.current = true;+ }}+ />+ ) : (+ <ModelOAuthDialog+ projectId={projectId}+ provider={MODEL_PROVIDERS.find((p) => p.id === oauthFor) ?? userProviderInfo(oauthFor)}+ count={rows?.filter((r) => r.provider === oauthFor).length ?? 0}+ onClose={() => {+ setOauthFor(null);+ // The reload waits for the dismissal rather than racing the open dialog: the key+ // was written server-side, so the table in hand is stale in exactly one place, and+ // reloading brings the masked key back. Gated on a key having landed, because+ // `load` also drops this Project's speed results — measurements that cost real API+ // quota and live only in page memory — and a cancelled flow changed nothing.+ if (keyLanded.current) void load();+ keyLanded.current = false;+ }}+ onApplied={() => {+ // The dialog stays open and reports the outcome itself (its `done` phase), because+ // the authorization ran in another tab and a toast would be announced to a window+ // nobody is looking at. All this seam does is record that the dismissal has a+ // reload to do.+ keyLanded.current = true;+ }}+ />+ ))}{rows && deleteGroupFor !== null && (<ConfirmModal@@ -1987,17 +2074,18 @@ function ModelCard({}) {const priced = row.cacheRead || row.cacheWrite || row.output;/**- * A promoted catalog row. `discountedPrice` returns nothing once the price has been edited- * away from the catalog's, and nothing for a row on a time-of-day schedule while it is inside- * its peak windows — at peak it is simply at list price, which is what is stored.+ * What is taken off this row's list price right now: its running promotion, its live+ * off-peak tier, or both. `discountedPrice` returns nothing for a row with neither — no+ * promotion, and a schedule that is inside its peak windows or on a price edited away from+ * the catalog's peak price.*- * `hourTick` is in the dependency list for that second case: a scheduled row's price changes- * on the hour with nobody touching the page, and a card left open would otherwise keep- * printing a rate that stopped applying.+ * `hourTick` is in the dependency list for the schedule: a scheduled row's price changes on+ * the hour with nobody touching the page, and a card left open would otherwise keep printing+ * a rate that stopped applying.*/const discount = useMemo(() => discountedPrice(row), [row, hourTick]);- // The buckets to print: what the seller bills right now. They differ from the stored numbers- // only for a scheduled discount, whose stored price is the peak one.+ // The buckets to print: what the seller bills right now. The stored numbers are the list+ // price, so they differ whenever a discount applies.const shownPrice = discount? {cacheRead: String(discount.billed.cacheRead),@@ -2314,7 +2402,8 @@ function ModelDialog({cacheRead: "",cacheWrite: "",output: "",- baseUrl: info?.gatewayBaseUrl ?? "",+ baseUrl:+ addProvider === PENGUIN_GO_PROVIDER_ID ? PENGUIN_GO_BASE_URL : (info?.gatewayBaseUrl ?? ""),originalBaseUrl: "",apiKeyInput: "",clearApiKey: false,@@ -2364,6 +2453,8 @@ function ModelDialog({const [tokenUnitRef, tokenUnitWidth] = useAffixWidth();const isNew = row === null;const preset = row !== null && isPreset(row);+ /** The loaded row's running promotion, explained under the price fields. */+ const promotion = fractionOff(row?.discount);// Read from the live form, not the saved row, so editing the upstream id, the protocol or// the base URL updates the answer as it is typed.@@ -2605,12 +2696,13 @@ function ModelDialog({// inferred — required for custom / user-defined groups and entries with an explicit// openai protocol (gateway groups already have it pre-filled); optional for entries// auto-routed within a first-party vendor group (the client has its own official- // default endpoint). Shared by validation and the label's required "*" mark.+ // default endpoint). The Penguin Go relay is also required: its shared key must never+ // fall through to a vendor default. Shared by validation and the label's required "*" mark.const openAiLike =form.clientType.trim().toLowerCase().includes("openai") ||form.provider === "custom" ||providerInfo(form.provider) === undefined;- const baseUrlRequired = !preset && openAiLike;+ const baseUrlRequired = form.provider === PENGUIN_GO_PROVIDER_ID || (!preset && openAiLike);// Custom-like groups (custom + user-defined) pick among AgentHub's generic protocol// clients: the base URL field's suffix becomes the protocol picker there, unless the// entry carries a legacy vendor-pinned client_type — that keeps the read-only note below@@ -2681,15 +2773,30 @@ function ModelDialog({return null;}setFieldErrors({});+ const cacheRead = priceToSubmit(form.cacheRead, row?.cacheRead, currency);+ const cacheWrite = priceToSubmit(form.cacheWrite, row?.cacheWrite, currency);+ const output = priceToSubmit(form.output, row?.output, currency);+ // The server cancels the promotion of a row saved with a new price or identity. A promotion+ // the preset sync declared (still on the row when that sync's save failed) would restate it+ // instead, so the declaration goes, and with it the promotion the card would otherwise keep+ // showing until the save lands.+ const cancelsPromotion =+ row !== null &&+ (cacheRead !== row.cacheRead ||+ cacheWrite !== row.cacheWrite ||+ output !== row.output ||+ form.provider !== row.provider ||+ modelId !== row.modelId);return {...form,modelId,// Custom models with an empty context window fall back to the default value (preset models left empty just mean "unknown", not auto-filled).contextWindow:!preset && !contextWindow ? String(CUSTOM_CONTEXT_DEFAULT) : form.contextWindow,- cacheRead: priceToSubmit(form.cacheRead, row?.cacheRead, currency),- cacheWrite: priceToSubmit(form.cacheWrite, row?.cacheWrite, currency),- output: priceToSubmit(form.output, row?.output, currency),+ cacheRead,+ cacheWrite,+ output,+ ...(cancelsPromotion ? { discount: undefined, discountDeclared: undefined } : {}),};};@@ -2735,15 +2842,16 @@ function ModelDialog({// and self-defined groups have no link).const dialogProvider = providerInfo(form.provider);// env fallback resolves live from the current form (uses the same- // resolveModelEnv as the server's getModels): explicit client_type takes- // priority, otherwise auto-route by model_id; no fallback if it can't be routed.+ // the same provider-aware resolver as the server's getModels): the Penguin Go relay+ // keeps its own key while ordinary groups follow client routing.//// Custom and user-defined groups opt out of the model_id half (per maintainer): typing// `claude-sonnet-5` into a custom group must not quietly imply the Anthropic client and// its ANTHROPIC_* key. Those groups default to the compatible client, which is also what// gets persisted when nothing is picked or detected — so keying the hint off it is what// the entry will actually read after saving.- const liveEnvKey = resolveModelEnv(+ const liveEnvKey = resolveProviderModelEnv(+ form.provider,form.modelId.trim(),envHintClientType(form.provider, form.clientType),)?.envKey;@@ -3359,6 +3467,14 @@ function ModelDialog({</label>))}</div>+ {/* The fields hold the list price, not the promotional price the card prints: the+ promotion is stored apart and taken off when usage is priced. It is said here, in+ view while the prices are typed, because typing a different price cancels it. */}+ {promotion !== undefined && (+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {S.models.promotionPriceHint(Math.round(promotion * 100))}+ </p>+ )}{/* 5) Identity: model id (renamable) + display name and group (side by side) */}{!isNew && identityFields}diff --git a/packages/web/src/features/models/platform-key-auth-dialog.tsx b/packages/web/src/features/models/platform-key-auth-dialog.tsxnew file mode 100644index 00000000..2bee23c7--- /dev/null+++ b/packages/web/src/features/models/platform-key-auth-dialog.tsx@@ -0,0 +1,265 @@+import { useEffect, useRef, useState } from "react";+import type {+ PlatformAuthFlowErrorCode,+ PlatformAuthFlowStatusResponse,+ PlatformAuthStartResponse,+} from "@prismshadow/penguin-server/api";+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";+import { S } from "../../lib/strings";++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;+}++/**+ * 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.+ */+export function PlatformKeyAuthDialog({+ projectId,+ providerLabel,+ count,+ onClose,+ onApplied,+}: {+ projectId: string;+ providerLabel: string;+ count: number;+ onClose: () => void;+ onApplied: (applied: number) => void;+}) {+ const [phase, setPhase] = useState<Phase>("ready");+ const [flow, setFlow] = useState<PlatformAuthStartResponse | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [applied, setApplied] = useState(0);+ const [retrySeconds, setRetrySeconds] = useState(0);+ const [retryableApply, setRetryableApply] = useState(false);+ const completedRef = useRef(false);+ const startGenerationRef = useRef(0);+ const onAppliedRef = useRef(onApplied);+ onAppliedRef.current = onApplied;++ useEffect(+ () => () => {+ startGenerationRef.current += 1;+ },+ [],+ );++ useEffect(() => {+ if (retrySeconds <= 0) return;+ const timer = window.setTimeout(+ () => setRetrySeconds((seconds) => Math.max(0, seconds - 1)),+ 1_000,+ );+ return () => window.clearTimeout(timer);+ }, [retrySeconds]);++ useEffect(() => {+ if ((phase !== "waiting" && phase !== "applying") || flow === null) return;+ let stopped = false;+ let timer: number | undefined;+ const tick = async (): Promise<void> => {+ try {+ const next = await api.getPlatformAuthFlow(projectId, flow.flowId);+ if (stopped) return;+ if (next.status === "pending") {+ timer = window.setTimeout(() => void tick(), POLL_MS);+ return;+ }+ if (next.status === "applying") {+ setPhase("applying");+ timer = window.setTimeout(() => void tick(), POLL_MS);+ return;+ }+ if (next.status === "completed") {+ const nextApplied = next.applied ?? count;+ setApplied(nextApplied);+ setPhase("done");+ if (!completedRef.current) {+ completedRef.current = true;+ onAppliedRef.current(nextApplied);+ }+ return;+ }+ const canRetryApply = next.status === "apply_failed";+ setError(flowError(next.error));+ setRetryableApply(canRetryApply);+ if (!canRetryApply) setFlow(null);+ setPhase("failed");+ } catch (cause) {+ if (stopped) return;+ setError(apiErrorText(cause));+ setRetryableApply(false);+ if (cause instanceof ApiError && cause.code === "platform_auth_flow_not_found") {+ setFlow(null);+ }+ setPhase("failed");+ }+ };+ void tick();+ return () => {+ stopped = true;+ if (timer !== undefined) window.clearTimeout(timer);+ };+ }, [count, flow, phase, projectId]);++ const close = (): void => {+ startGenerationRef.current += 1;+ if (flow !== null && phase !== "done") {+ void api.cancelPlatformAuth(projectId, flow.flowId).catch(() => {});+ }+ onClose();+ };++ const beginAuthorization = async (): Promise<void> => {+ if (phase === "starting" || retrySeconds > 0) return;+ if (flow !== null) {+ void api.cancelPlatformAuth(projectId, flow.flowId).catch(() => {});+ }+ completedRef.current = false;+ setFlow(null);+ setError(null);+ setRetryableApply(false);+ setPhase("starting");+ const generation = ++startGenerationRef.current;++ // Open synchronously from the click so browsers do not treat the eventual navigation as+ // an unsolicited popup while the server creates the one-time authorization request.+ const authorizationTab = window.open("about:blank", "_blank");+ if (authorizationTab !== null) authorizationTab.opener = null;+ try {+ const started = await api.startPlatformAuth(projectId);+ if (generation !== startGenerationRef.current) {+ authorizationTab?.close();+ void api.cancelPlatformAuth(projectId, started.flowId).catch(() => {});+ return;+ }+ setFlow(started);+ if (authorizationTab === null) {+ // Popup blockers can still intervene. Keep the created request and let the next+ // explicit click open its URL without consuming another platform start quota.+ setPhase("ready");+ return;+ }+ authorizationTab.location.replace(started.authorizeUrl);+ setPhase("waiting");+ } catch (cause) {+ authorizationTab?.close();+ if (generation !== startGenerationRef.current) return;+ setError(apiErrorText(cause));+ if (cause instanceof ApiError && cause.retryAfterSeconds !== undefined) {+ setRetrySeconds(cause.retryAfterSeconds);+ }+ setPhase("failed");+ }+ };++ const retryApply = async (): Promise<void> => {+ if (flow === null) return;+ setError(null);+ setPhase("applying");+ try {+ const next: PlatformAuthFlowStatusResponse = await api.retryPlatformAuthApply(+ projectId,+ flow.flowId,+ );+ if (next.status !== "completed") {+ setError(flowError(next.error));+ setRetryableApply(next.status === "apply_failed");+ setPhase("failed");+ return;+ }+ const nextApplied = next.applied ?? count;+ setApplied(nextApplied);+ setPhase("done");+ if (!completedRef.current) {+ completedRef.current = true;+ onAppliedRef.current(nextApplied);+ }+ } catch (cause) {+ setError(apiErrorText(cause));+ setRetryableApply(true);+ setPhase("failed");+ }+ };++ const primary =+ phase === "failed" && retryableApply ? (+ <Button size="sm" variant="primary" onClick={() => void retryApply()}>+ {S.models.oauthRetry}+ </Button>+ ) : (+ <Button+ size="sm"+ variant="primary"+ disabled={+ phase === "starting" || phase === "waiting" || phase === "applying" || retrySeconds > 0+ }+ onClick={() => {+ if (flow !== null) {+ window.open(flow.authorizeUrl, "_blank", "noopener,noreferrer");+ setPhase("waiting");+ return;+ }+ void beginAuthorization();+ }}+ >+ {phase === "failed"+ ? retrySeconds > 0+ ? `${S.models.oauthRetry} (${retrySeconds}s)`+ : S.models.oauthRetry+ : S.models.oauthAuthorize}+ </Button>+ );++ return (+ <Modal+ open+ title={S.models.oauthTitle(providerLabel)}+ onClose={close}+ footer={+ phase === "done" ? (+ <Button size="sm" onClick={close}>+ {S.common.close}+ </Button>+ ) : (+ <>+ <Button size="sm" onClick={close}>+ {S.common.cancel}+ </Button>+ {primary}+ </>+ )+ }+ >+ <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)}+ </p>+ {(phase === "starting" || phase === "waiting" || phase === "applying") && (+ <p className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">+ <span className="inline-block h-2.5 w-2.5 shrink-0 animate-spin rounded-full border border-current border-t-transparent" />+ {phase === "starting"+ ? S.models.platformKeyStarting+ : phase === "applying"+ ? S.models.platformKeyApplying+ : S.models.oauthWaiting}+ </p>+ )}+ {error !== null && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}+ </div>+ </Modal>+ );+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e1b57046..0e45c969 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1011,6 +1011,7 @@ export const en: Strings = {"- Never read or edit .project_config.toml; configuration goes through penguin commands only.",`- Finish with \`penguin config model list --project-id ${projectId} --root <data root>\` and show me the result.`,].join("\n"),+ platformSync: "Sync",homepage: "Model page",speedTest: "Speed test",speedTestTitle: "Speed test",@@ -1106,6 +1107,8 @@ export const en: Strings = {priceCacheRead: "Cache read price",priceCacheWrite: "Cache write price",priceOutput: "Output price",+ promotionPriceHint: (pct: number): string =>+ `These are list prices. A running promotion takes ${pct}% off them; changing a price cancels it`,currency: "Currency",currencyUsd: "USD $",currencyCny: "CNY ¥",@@ -1159,6 +1162,22 @@ export const en: Strings = {apply_failed:"A key was created but could not be saved. Authorize again, then delete the unused key in the provider's console.",},+ platformKeyIntro: (n: number): string =>+ `Authorization automatically obtains a Penguin Go API key and writes it to all ${n} preset models in this group, replacing their current key.`,+ platformKeyAppliedBody: (n: number): string =>+ `Authorized. The Penguin Go API key is set on ${n} model${n === 1 ? "" : "s"} and ready to use.`,+ platformKeyStarting: "Starting authorization…",+ platformKeyApplying: "Authorization completed. Writing the key to the model group…",+ platformKeyErrors: {+ unreachable: "Penguin Go could not be reached. Check the network and start again.",+ upstream_failed: "Penguin Go could not complete authorization. Start again.",+ invalid_key: "Penguin Go returned no usable API key. 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 key 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",@@ -4191,6 +4210,8 @@ Scenarios:task_in_progress: "This Session already has a task running.",compacting: "This Session is compacting its context and is not accepting new input.",shutting_down: "The server is shutting down. Please try again shortly.",+ platform_rate_limited:+ "Too many platform authorization requests. Try again when the countdown ends.",// The three "cannot compact" reasons each have their own server code, so each keeps its// own explanation here — collapsing them into one sentence would tell a user who just// compacted that they have never spoken.diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 83ca9ec4..d98db907 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -998,6 +998,7 @@ export const zh = {"- 不要读取或改动 .project_config.toml,配置只经 penguin 命令。",`- 最后运行 \`penguin config model list --project-id ${projectId} --root <数据根目录>\` 把结果列给我。`,].join("\n"),+ platformSync: "同步",homepage: "模型主页",speedTest: "测速",speedTestTitle: "分组测速",@@ -1109,6 +1110,9 @@ export const zh = {priceCacheRead: "缓存命中价格",priceCacheWrite: "缓存未命中价格",priceOutput: "输出价格",+ /** Line under the model dialog's price fields on a row with a running promotion: the fields hold the list price, and changing it cancels the promotion. */+ promotionPriceHint: (pct: number): string =>+ `此处为牌价,当前促销在此基础上省 ${pct}%;修改价格会取消促销`,currency: "币种",currencyUsd: "美元 $",currencyCny: "人民币 ¥",@@ -1161,6 +1165,21 @@ export const zh = {unreachable: "连不上供应商,请检查网络后重新开始。",apply_failed: "key 已创建但未能保存。请重新授权,并到供应商控制台删掉那个没用上的 key。",},+ platformKeyIntro: (n: number): string =>+ `授权后会自动获取一个 Penguin Go API key,并写入该分组下全部 ${n} 个预置模型,覆盖它们当前的 key。`,+ platformKeyAppliedBody: (n: number): string =>+ `已完成授权:Penguin Go API key 已配置到 ${n} 个模型上,可以直接使用了。`,+ platformKeyStarting: "正在创建授权请求…",+ platformKeyApplying: "授权已完成,正在写入模型组…",+ platformKeyErrors: {+ unreachable: "无法连接 Penguin Go,请检查网络后重新开始。",+ upstream_failed: "Penguin Go 未能完成授权,请重新开始。",+ invalid_key: "Penguin Go 未返回可用的 API key,请重新开始。",+ expired: "授权已过期,请重新开始。",+ locked: "授权已锁定,请重新开始。",+ already_delivered: "该授权结果已经交付,请重新开始。",+ apply_failed: "API key 已取得,但未能写入模型组。可以直接重试,无需再次授权。",+ },// Providers with separate domestic / international endpoints: note on the default// endpoint used when left blank via env var (the other side's key needs an explicit// base URL). Written to match AgentHub's actual behavior; rendered wherever the env fallback hint appears.@@ -4149,6 +4168,7 @@ Benchmark:task_in_progress: "该 Session 已有任务在运行。",compacting: "该 Session 正在压缩上下文,暂不接受新的输入。",shutting_down: "服务正在关闭,请稍后重试。",+ platform_rate_limited: "平台授权请求过于频繁,请等待倒计时结束后重试。",// The three "cannot compact" reasons each have their own server code, so each keeps its// own explanation here — collapsing them into one sentence would tell a user who just// compacted that they have never spoken.diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex 7cbdbe6f..2bf5ecb8 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -152,7 +152,7 @@}}-/* ---------- Animations (EmaPowerbank style: 160-280ms ease, slight entrance offset + subtle scale) ---------- */+/* ---------- Animations (160-280ms ease, slight entrance offset + subtle scale) ---------- */@keyframes rise-in {from {diff --git a/packages/web/test/api-error-text.test.ts b/packages/web/test/api-error-text.test.tsindex 071d0a21..197b80e7 100644--- a/packages/web/test/api-error-text.test.ts+++ b/packages/web/test/api-error-text.test.ts@@ -7,8 +7,8 @@* meets, and pin that the three "cannot compact" reasons stay three distinct explanations* rather than collapsing into one.*/-import { afterEach, describe, expect, it } from "vitest";-import { ApiError } from "../src/api/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiError, apiFetch } from "../src/api/client";import { apiErrorText } from "../src/lib/api-error";import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";import { en as EN } from "../src/lib/strings-en";@@ -17,7 +17,10 @@ import { en as EN } from "../src/lib/strings-en";const serverError = (code: string): ApiError =>new ApiError(409, code, "RAW ENGLISH SERVER MESSAGE");-afterEach(() => setActiveStrings(ZH));+afterEach(() => {+ setActiveStrings(ZH);+ vi.unstubAllGlobals();+});describe("apiErrorText", () => {it("localizes each compaction refusal separately in both locales", () => {@@ -49,6 +52,7 @@ describe("apiErrorText", () => {"memory_file_not_found","memory_scope_not_found","trace_not_found",+ "platform_rate_limited","internal",];for (const code of reachable) {@@ -79,4 +83,26 @@ describe("apiErrorText", () => {setActiveStrings(ZH);expect(apiErrorText(new Error("boom"))).toBe(S.common.unknownError);});++ it("keeps a numeric Retry-After header on the ApiError", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(+ async () =>+ new Response(+ JSON.stringify({ error: { code: "platform_rate_limited", message: "slow down" } }),+ {+ status: 429,+ headers: { "content-type": "application/json", "retry-after": "7" },+ },+ ),+ ),+ );++ await expect(apiFetch("/api/platform-rate-limit-test")).rejects.toMatchObject({+ status: 429,+ code: "platform_rate_limited",+ retryAfterSeconds: 7,+ });+ });});diff --git a/packages/web/test/catalog-sync.test.ts b/packages/web/test/catalog-sync.test.tsindex 0bde7ca1..a14a0f1b 100644--- a/packages/web/test/catalog-sync.test.ts+++ b/packages/web/test/catalog-sync.test.ts@@ -1,20 +1,24 @@/*** catalog-sync.ts unit tests: the "sync presets" merge — union of the local model table and- * the built-in catalog, catalog winning on differing preset entries, local additions and- * credentials untouched, the display name filled but never overwritten — plus `catalogDelta`,- * the same question asked of a saved table so the Models nav badge can answer it before the- * page has loaded any rows.+ * the built-in catalog, catalog winning on differing preset entries (their promotion included,+ * outside the Penguin Go group), local additions and credentials untouched, the display name+ * filled but never overwritten — plus `catalogDelta`, the same question asked of a saved table+ * so the Models nav badge can answer it before the page has loaded any rows.** The last block is the one that matters most: the badge and the button must never disagree* about whether there is anything to do, so every case above is replayed through both.*/import { describe, expect, it } from "vitest";-import { catalogEntryFor } from "@prismshadow/penguin-core/model-catalog";+import {+ PENGUIN_GO_PROVIDER_ID,+ catalogEntryFor,+ presetModelEntries,+} from "@prismshadow/penguin-core/model-catalog";import type { ModelsResponse } from "@prismshadow/penguin-server/api";import { catalogDelta, syncRowsWithCatalog } from "../src/features/models/catalog-sync";import { presetUpdateTodo } from "../src/lib/todo-badges";import { noticeCounts } from "../src/lib/bulk-update";-import { toRow } from "../src/features/models/models-page";+import { rowToEntry, toRow } from "../src/features/models/models-page";import type { RowState } from "../src/features/models/models-page";type ModelDto = ModelsResponse["models"][number];@@ -102,6 +106,23 @@ const PRESET: PresetEntry[] = [},];+/**+ * A shipped preset row the catalog runs a flat promotion on, found rather than named: promotions+ * start and end with catalog releases, and the cases below are about what a sync does with one.+ */+const PROMOTED: PresetEntry = presetModelEntries().find((p) => {+ const discount = catalogEntryFor(p.provider, p.model_id)?.discount;+ return (+ p.provider !== PENGUIN_GO_PROVIDER_ID && discount !== undefined && discount > 0 && discount < 1+ );+})!;+const PROMOTED_DISCOUNT = catalogEntryFor(PROMOTED.provider, PROMOTED.model_id)!.discount!;++/** A shipped Penguin Go preset row: that group's promotions are the platform's, not the catalog's. */+const PENGUIN_GO: PresetEntry = presetModelEntries().find(+ (p) => p.provider === PENGUIN_GO_PROVIDER_ID,+)!;+describe("syncRowsWithCatalog", () => {it("adds catalog entries missing locally (gateway base URL preset, original null -> new on PUT)", () => {const { rows, added, updated } = syncRowsWithCatalog([], PRESET);@@ -155,11 +176,13 @@ describe("syncRowsWithCatalog", () => {expect(row.credential).toEqual({ hasApiKey: true });});- it("leaves up-to-date rows untouched (same object, updated not counted)", () => {+ it("leaves up-to-date rows unchanged (updated not counted), declaring their catalog promotion", () => {const upToDate = inSyncRow();const { rows, updated } = syncRowsWithCatalog([upToDate], PRESET);expect(updated).toBe(0);- expect(rows[0]).toBe(upToDate);+ // The catalog runs no promotion on this row, so the declaration is "none".+ expect(rows[0]).toEqual({ ...upToDate, discountDeclared: true });+ expect(rows[0]!.discount).toBeUndefined();});it("fills a blank display name from the catalog, and never overwrites one already there", () => {@@ -177,7 +200,7 @@ describe("syncRowsWithCatalog", () => {const renamed = inSyncRow({ displayName: "My DeepSeek" });const kept = syncRowsWithCatalog([renamed], PRESET);expect(kept.updated).toBe(0);- expect(kept.rows[0]).toBe(renamed);+ expect(kept.rows[0]).toEqual({ ...renamed, discountDeclared: true });});it("preserves a user-set max output tokens through a preset sync (user-owned, not catalog-owned)", () => {@@ -221,6 +244,43 @@ describe("syncRowsWithCatalog", () => {expect([row.cacheRead, row.cacheWrite, row.output]).toEqual(["", "", ""]);});+ it("restores Penguin Go's complete preset pricing when the saved row is stale", () => {+ const preset = presetModelEntries().find(+ (entry) => entry.provider === "penguin-go" && entry.model_id === "gemini-3.8-flash",+ )!;+ const local = makeRow({+ provider: preset.provider,+ modelId: preset.model_id,+ displayName: catalogName(preset.provider, preset.model_id),+ vision: preset.vision !== false,+ contextWindow: String(preset.context_window),+ clientType: preset.client_type ?? "",+ baseUrl: preset.base_url ?? "",+ originalBaseUrl: preset.base_url ?? "",+ cacheRead: "0.1",+ cacheWrite: "0.2",+ output: "0.3",+ });+ const merged = syncRowsWithCatalog([local], [preset]);+ expect(merged.updated).toBe(1);+ expect([merged.rows[0]!.cacheRead, merged.rows[0]!.cacheWrite, merged.rows[0]!.output]).toEqual(+ [+ String(preset.pricing!.cache_read),+ String(preset.pricing!.cache_write),+ String(preset.pricing!.output),+ ],+ );++ const dto = inSyncDto(preset, {+ pricing: { cacheRead: 0.1, cacheWrite: 0.2, output: 0.3 },+ });+ expect(catalogDelta([dto], [preset])).toEqual({+ added: 0,+ updated: 1,+ refs: ["penguin-go/gemini-3.8-flash"],+ });+ });+it("syncs against the real built-in catalog by default", () => {const { rows, added, updated } = syncRowsWithCatalog([]);expect(added).toBeGreaterThan(30);@@ -229,6 +289,52 @@ describe("syncRowsWithCatalog", () => {expect(rows.every((r) => r.apiKeyInput === "" && !r.clearApiKey)).toBe(true);// Every catalog entry is named, so no row added from it may go out nameless.expect(rows.every((r) => (r.displayName ?? "") !== "")).toBe(true);+ // Every added row declares its catalog promotion, except the Penguin Go group's.+ expect(+ rows.every((r) => (r.discountDeclared === true) === (r.provider !== PENGUIN_GO_PROVIDER_ID)),+ ).toBe(true);+ });++ it("declares the catalog's promotion on preset rows, and a promotion-only difference is an update", () => {+ const added = syncRowsWithCatalog([], [PROMOTED]);+ expect(added.rows[0]).toMatchObject({ discount: PROMOTED_DISCOUNT, discountDeclared: true });++ // In line with the catalog on every field but the promotion, which the server never stored.+ const unpromoted = toRow(inSyncDto(PROMOTED));+ const merged = syncRowsWithCatalog([unpromoted], [PROMOTED]);+ expect(merged.updated).toBe(1);+ expect(merged.rows[0]).toMatchObject({ discount: PROMOTED_DISCOUNT, discountDeclared: true });+ expect(rowToEntry(merged.rows[0]!).discount).toBe(PROMOTED_DISCOUNT);++ // A promotion the catalog no longer runs is declared cleared.+ const lapsed = syncRowsWithCatalog([inSyncRow({ discount: 0.3 })], PRESET);+ expect(lapsed.updated).toBe(1);+ expect(lapsed.rows[0]!.discount).toBeUndefined();+ expect(rowToEntry(lapsed.rows[0]!).discount).toBeNull();++ const current = syncRowsWithCatalog(+ [toRow(inSyncDto(PROMOTED, { discount: PROMOTED_DISCOUNT }))],+ [PROMOTED],+ );+ expect(current.updated).toBe(0);+ expect(current.rows[0]!.discountDeclared).toBe(true);+ });++ it("never compares a Penguin Go row's promotion, and keeps it through a rewrite", () => {+ // The platform's promotion on a row the catalog prices without one: nothing to do.+ const synced = toRow(inSyncDto(PENGUIN_GO, { discount: 0.5 }));+ const untouched = syncRowsWithCatalog([synced], [PENGUIN_GO]);+ expect(untouched.updated).toBe(0);+ expect(untouched.rows[0]).toBe(synced);++ // A row whose price the merge rewrites restates the platform's promotion, which the server+ // would otherwise drop with the old price.+ const stale = toRow(+ inSyncDto(PENGUIN_GO, { discount: 0.5, pricing: { cacheRead: 1, cacheWrite: 2, output: 3 } }),+ );+ const rewritten = syncRowsWithCatalog([stale], [PENGUIN_GO]);+ expect(rewritten.updated).toBe(1);+ expect(rowToEntry(rewritten.rows[0]!).discount).toBe(0.5);});});@@ -316,12 +422,24 @@ describe("catalogDelta", () => {expect(catalogDelta([local], PRESET).refs).not.toContain("custom/my-own");});+ it("counts a promotion-only difference as an update, outside the Penguin Go group", () => {+ expect(catalogDelta([inSyncDto(PROMOTED)], [PROMOTED]).updated).toBe(1);+ expect(+ catalogDelta([inSyncDto(PROMOTED, { discount: PROMOTED_DISCOUNT })], [PROMOTED]).updated,+ ).toBe(0);+ expect(catalogDelta([inSyncDto(PRESET[0]!, { discount: 0.3 })], PRESET).refs).toContain(+ "deepseek/deepseek-v4-pro",+ );+ expect(catalogDelta([inSyncDto(PENGUIN_GO, { discount: 0.5 })], [PENGUIN_GO]).updated).toBe(0);+ });+/*** The badge reads a saved table; the button reads row state. They are two conversions of the* same data, so this pins them together: whatever `toRow` does to a DTO, `catalogDelta` must* read the same way, or a dot would lead to a button answering "already up to date".*/it("agrees with the sync merge on every table shape, against the real catalog", () => {+ const presets = [...PRESET, PROMOTED, PENGUIN_GO];const tables: ModelDto[][] = [[],[makeDto({ provider: "deepseek", modelId: "deepseek-v4-pro" })],@@ -339,10 +457,15 @@ describe("catalogDelta", () => {[inSyncDto(PRESET[0]!)],[inSyncDto(PRESET[0]!, { displayName: "" })],[inSyncDto(PRESET[0]!, { displayName: "My DeepSeek" })],+ // The promotion: missing, current, lapsed, and the Penguin Go group's own.+ [inSyncDto(PROMOTED)],+ [inSyncDto(PROMOTED, { discount: PROMOTED_DISCOUNT })],+ [inSyncDto(PRESET[0]!, { discount: 0.3 })],+ [inSyncDto(PENGUIN_GO, { discount: 0.5 })],];for (const table of tables) {- const merged = syncRowsWithCatalog(table.map(toRow), PRESET);- const delta = catalogDelta(table, PRESET);+ const merged = syncRowsWithCatalog(table.map(toRow), presets);+ const delta = catalogDelta(table, presets);expect([delta.added, delta.updated], JSON.stringify(table)).toEqual([merged.added,merged.updated,diff --git a/packages/web/test/model-grouping.test.ts b/packages/web/test/model-grouping.test.tsindex 0abf1286..13c71bef 100644--- a/packages/web/test/model-grouping.test.ts+++ b/packages/web/test/model-grouping.test.ts@@ -13,6 +13,7 @@*/import { describe, expect, it } from "vitest";import {+ MODEL_CATALOG,MODEL_PROVIDERS,catalogEntryFor,effectivePricing,@@ -24,6 +25,7 @@ import {isFreeModel,matchesQuery,orderModelsLikeLibrary,+ promotedPricing,visibleChatModels,} from "../src/features/models/model-grouping";import type { ModelCredentialRowLike, ModelRowLike } from "../src/features/models/model-grouping";@@ -81,11 +83,13 @@ describe("groupModelRows", () => {expect(groups[4]!.provider.envKey).toBe("OPENAI_API_KEY");expect(groups[4]!.rows.map((r) => r.modelId)).toEqual(["weird-model"]);// Group order matches MODEL_PROVIDERS, whose sequence is hand-curated (gateways and- // first-party vendors interleaved): TokenDance first as the recommended group, DeepSeek- // next as the default model's provider, custom last. This is the page's DEFAULT — the+ // first-party vendors interleaved): the managed Penguin Go group first when present,+ // then TokenDance+ // and DeepSeek, with custom last. This is the page's DEFAULT — the// stored per-Project order applied below overrides it.expect(MODEL_PROVIDERS.map((p) => p.id)).toEqual(["tokendance",+ "penguin-go","deepseek","openrouter","fireworks",@@ -339,43 +343,73 @@ describe("isFreeModel", () => {});describe("discountedPrice", () => {/**- * A row carrying exactly what "sync presets" would write for a catalog entry: the discounted- * price for a flat promotion, the peak price for a scheduled one (which is never baked in).+ * A row carrying what the catalog hands a Project: its list price (the peak one for a scheduled+ * entry) and no promotion. The promotion is the server's to report, so each case adds its own.*/- const syncedRow = (provider: string, modelId: string) => {- const entry = catalogEntryFor(provider, modelId)!;- const billed = (entry.offPeakDiscount !== undefined ? entry.pricing : effectivePricing(entry))!;+ const presetRow = (provider: string, modelId: string) => {+ const pricing = catalogEntryFor(provider, modelId)!.pricing!;return {provider,modelId,- cacheRead: String(billed.cache_read),- cacheWrite: String(billed.cache_write),- output: String(billed.output),+ cacheRead: String(pricing.cache_read),+ cacheWrite: String(pricing.cache_write),+ output: String(pricing.output),};};- it("a synced row on a flat promotion reports the rate, and bills at the stored price", () => {- const row = syncedRow("tokendance", "glm-5.3-flash");- const found = discountedPrice(row)!;- expect(found.percent).toBe(10);- expect(found.scheduled).toBe(false);- // A flat promotion is baked in at sync time, so what is billed is what is stored.- expect(found.billed).toEqual({- cacheRead: Number(row.cacheRead),- cacheWrite: Number(row.cacheWrite),- output: Number(row.output),- });- // And it really is below the catalog's list price.- const entry = catalogEntryFor("tokendance", "glm-5.3-flash")!;- expect(entry.pricing!.cache_write).toBeGreaterThan(found.billed.cacheWrite);- });-// Beijing is UTC+8, so 01:00Z is 09:00 there. 2026-08-31 is a Monday.const PEAK = new Date("2026-08-31T01:30:00Z");const OFF_PEAK = new Date("2026-08-31T05:00:00Z");+ it("a promotion takes its rate off the stored list price, on any row", () => {+ // Off the catalog on purpose: the promotion is the row's own, as a platform sync reports it+ // for a model the built-in catalog has never heard of.+ const row = {+ provider: "penguin-go",+ modelId: "gemini-future",+ cacheRead: "0.1",+ cacheWrite: "0.5",+ output: "2",+ discount: 0.5,+ };+ expect(discountedPrice(row)).toEqual({+ percent: 50,+ billed: { cacheRead: 0.05, cacheWrite: 0.25, output: 1 },+ scheduled: false,+ });+ // No price check of its own: the server clears a promotion whose price a save changes.+ expect(discountedPrice({ ...row, output: "4" })?.billed.output).toBe(2);+ });++ it("reads the promotion off the row, never off the catalog entry", () => {+ const promoted = MODEL_CATALOG.find(+ (e) =>+ e.pricing !== undefined &&+ e.offPeakDiscount === undefined &&+ e.discount !== undefined &&+ e.discount > 0 &&+ e.discount < 1,+ )!;+ const row = presetRow(promoted.provider, promoted.modelId);+ expect(discountedPrice(row)).toBeUndefined();+ expect(discountedPrice({ ...row, discount: promoted.discount })?.percent).toBe(+ Math.round(promoted.discount! * 100),+ );+ // A file still holding the promotional price itself, with nothing reported beside it, is+ // billed at that number and says nothing about a saving.+ const effective = effectivePricing(promoted)!;+ expect(+ discountedPrice({+ ...row,+ cacheRead: String(effective.cache_read),+ cacheWrite: String(effective.cache_write),+ output: String(effective.output),+ }),+ ).toBeUndefined();+ });+it("a scheduled row is marked and halved off-peak, and left at list price at peak", () => {- const row = syncedRow("deepseek", "deepseek-v4-flash");+ const row = presetRow("deepseek", "deepseek-v4-flash");const entry = catalogEntryFor("deepseek", "deepseek-v4-flash")!;const off = discountedPrice(row, OFF_PEAK)!;@@ -387,15 +421,52 @@ describe("discountedPrice", () => {expect(discountedPrice(row, PEAK)).toBeUndefined();});- it("a scheduled row whose price was edited is never halved, at either hour", () => {- const row = { ...syncedRow("deepseek", "deepseek-v4-pro"), output: "1.234" };+ it("a promotion on a scheduled row multiplies with the live off-peak tier", () => {+ const row = { ...presetRow("deepseek", "deepseek-flash"), discount: 0.2 };+ const output = catalogEntryFor("deepseek", "deepseek-flash")!.pricing!.output;++ // 20% off, then half of the rest: 60% off, explained as the promotion.+ const off = discountedPrice(row, OFF_PEAK)!;+ expect(off.percent).toBe(60);+ expect(off.scheduled).toBe(false);+ expect(off.billed.output).toBeCloseTo(output * 0.8 * 0.5, 5);++ const peak = discountedPrice(row, PEAK)!;+ expect(peak.percent).toBe(20);+ expect(peak.billed.output).toBeCloseTo(output * 0.8, 5);+ });++ it("a scheduled row whose price was edited is never halved, though a promotion still applies", () => {+ const row = { ...presetRow("deepseek", "deepseek-v4-pro"), output: "1.234" };expect(discountedPrice(row, OFF_PEAK)).toBeUndefined();expect(discountedPrice(row, PEAK)).toBeUndefined();+ expect(discountedPrice({ ...row, discount: 0.2 }, OFF_PEAK)).toEqual({+ percent: 20,+ billed: expect.objectContaining({ output: 0.9872 }),+ scheduled: false,+ });+ });++ it("ignores a discount outside (0, 1)", () => {+ const priced = {+ provider: "custom",+ modelId: "my-proxy",+ cacheRead: "1",+ cacheWrite: "2",+ output: "3",+ };+ const scheduled = presetRow("deepseek", "deepseek-v4-flash");+ for (const discount of [0, 1, -0.2, 1.5, Number.NaN]) {+ expect(discountedPrice({ ...priced, discount })).toBeUndefined();+ // Only the tier is left to report.+ expect(discountedPrice({ ...scheduled, discount }, OFF_PEAK)).toMatchObject({+ percent: 50,+ scheduled: true,+ });+ }});- it("undiscounted catalog rows, off-catalog rows and unpriced rows report nothing", () => {- expect(discountedPrice(syncedRow("tokendance", "qwen3.8-flash"))).toBeUndefined();- expect(discountedPrice(syncedRow("tokendance", "hy4-preview"))).toBeUndefined();+ it("rows with nothing to take off, and unpriced rows, report nothing", () => {expect(discountedPrice({provider: "custom",@@ -405,7 +476,10 @@ describe("discountedPrice", () => {output: "3",}),).toBeUndefined();- expect(discountedPrice({ provider: "tokendance", modelId: "kimi-k3" })).toBeUndefined();+ // A promotion needs a price to come off.+ expect(+ discountedPrice({ provider: "tokendance", modelId: "kimi-k3", discount: 0.2 }),+ ).toBeUndefined();expect(discountedPrice({provider: "tokendance",@@ -413,38 +487,33 @@ describe("discountedPrice", () => {cacheRead: "",cacheWrite: "",output: "",+ discount: 0.2,}),).toBeUndefined();});- it("an edited price drops the decoration: a hand-typed number is not a discount off list", () => {- const row = syncedRow("tokendance", "kimi-k3");- expect(discountedPrice(row)).toBeDefined();- expect(discountedPrice({ ...row, output: "9.99" })).toBeUndefined();- // A row still holding the LIST price (a Project that has not synced presets) is not- // being billed the promotional rate, so it gets no badge either.- const entry = catalogEntryFor("tokendance", "kimi-k3")!;- expect(- discountedPrice({- ...row,- cacheRead: String(entry.pricing!.cache_read),- cacheWrite: String(entry.pricing!.cache_write),- output: String(entry.pricing!.output),- }),- ).toBeUndefined();+ it("accepts the DTO's numeric buckets as well as the edit form's strings", () => {+ const strings = {+ provider: "custom",+ modelId: "my-proxy",+ cacheRead: "1",+ cacheWrite: "2",+ output: "3",+ discount: 0.1,+ };+ expect(discountedPrice(strings)?.percent).toBe(10);+ expect(discountedPrice({ ...strings, cacheRead: 1, cacheWrite: 2, output: 3 })?.billed).toEqual(+ { cacheRead: 0.9, cacheWrite: 1.8, output: 2.7 },+ );});+});- it("accepts the DTO's numeric buckets as well as the edit form's strings", () => {- const row = syncedRow("tokendance", "qwen3.8-max");- expect(discountedPrice(row)?.percent).toBe(10);- expect(- discountedPrice({- provider: row.provider,- modelId: row.modelId,- cacheRead: Number(row.cacheRead),- cacheWrite: Number(row.cacheWrite),- output: Number(row.output),- })?.percent,- ).toBe(10);+describe("promotedPricing", () => {+ it("takes a running promotion off every bucket, and leaves a price without one as it is", () => {+ const list = { cacheRead: 0.5, cacheWrite: 2, output: 8 };+ expect(promotedPricing(list, 0.25)).toEqual({ cacheRead: 0.375, cacheWrite: 1.5, output: 6 });+ expect(promotedPricing(list, undefined)).toBe(list);+ expect(promotedPricing(list, 1)).toBe(list);+ expect(promotedPricing(undefined, 0.25)).toBeUndefined();});});diff --git a/packages/web/test/protocol-detect.test.ts b/packages/web/test/protocol-detect.test.tsindex 27df393c..ef7e8ee4 100644--- a/packages/web/test/protocol-detect.test.ts+++ b/packages/web/test/protocol-detect.test.ts@@ -240,6 +240,17 @@ describe("rowToEntry (the persistence funnel)", () => {it("omits clientType for a vendor group so AgentHub keeps inferring it", () => {expect(rowToEntry(row({ provider: "openai", modelId: "gpt-5.6" })).clientType).toBeUndefined();});++ it("sends a promotion only when the preset sync declared one", () => {+ // A promotion the page merely loaded is left to the server, which keeps it unless the entry+ // renames the row or changes its price.+ expect(rowToEntry(row({ provider: "penguin-go", discount: 0.5 }))).not.toHaveProperty(+ "discount",+ );+ expect(rowToEntry(row({ discount: 0.2, discountDeclared: true })).discount).toBe(0.2);+ // Declared with no promotion: an explicit clear.+ expect(rowToEntry(row({ discountDeclared: true })).discount).toBeNull();+ });});describe("detection copy", () => {