Skip to content

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

fix: a keyless model entry borrows an environment variable only for the vendor's own endpoint (#794)

Yaowei Zheng75f472b7e930
diff --git a/changelog/unreleased/2026-09-18-gateway-no-env-keys.md b/changelog/unreleased/2026-09-18-gateway-no-env-keys.md
new file mode 100644
index 00000000..74ccac3a
--- /dev/null
+++ b/changelog/unreleased/2026-09-18-gateway-no-env-keys.md
@@ -0,0 +1,82 @@
+# A keyless model entry borrows an environment variable only for the vendor's own endpoint
+
+- **Date:** 2026-09-18
+- **Type:** fix
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#794](https://github.com/Prism-Shadow/penguin-harness/pull/794)
+- **Breaking:** yes — a model entry with no `api_key` whose `base_url` is not the vendor's own official endpoint (every gateway preset — TokenDance, OpenRouter, Fireworks AI, SiliconFlow, Qwen Pay-As-You-Go, Qwen Token Plan; `custom`, `vllm` and user-created rows with their own endpoint; a vendor row re-pointed at a proxy or at `bedrock://`) no longer reads `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / `GEMINI_API_KEY` (or any vendor variable) from the server environment; Sessions, the connection test, the group speed test, the vision probe, protocol detection and the endpoint listing refuse it instead
+
+[中文版](2026-09-18-gateway-no-env-keys.zh.md)
+
+AgentHub's clients read a vendor's environment variable whenever they are handed no key, whatever
+base URL they were pointed at. A keyless row in a gateway group therefore sent the user's own OpenAI
+or Anthropic key to the gateway: one group speed test on a mixed-protocol gateway made 27 requests,
+7 carrying the Anthropic key and 20 the OpenAI key, and the model dialog's key field, once any
+Anthropic row had shown the variable was set, told a gateway row to "leave empty to use the
+ANTHROPIC_API_KEY env var". PenguinHarness now decides itself whether a keyless entry may lean on
+the environment, before any client exists, and the rule is about the **destination**, not the
+group's name: environment keys are for official endpoints only.
+
+## Details
+
+- Core's `modelEnvFallback` is the one rule; every client the harness builds applies it —
+ Session creation and resume, the vision describer, the connectivity and speed probes, the
+ vision probe and the utility completion through `resolveModelCredential`, the endpoint
+ listing and protocol detection (a protocol and a URL, no entry yet) through
+ `endpointEnvApiKey`. A keyless entry is allowed the routed client's variable when it has no base URL (the
+ client's default endpoint is the vendor's own, or the `*_BASE_URL` the user set beside the key),
+ or when its base URL is one of that vendor's own official endpoints (the catalog pins the
+ DeepSeek and MiniMax rows this way). Anything else is refused with "Model
+ `<provider>/<id>` has no API key … set the API key on the model entry", which the server files
+ under `model_credential_missing` like the SDKs' own missing-credential errors.
+- Where the fallback is allowed the client is still handed no key and reads the variable itself,
+ exactly as before — a vendor row loses nothing, including a Bedrock `ANTHROPIC_BASE_URL` with no
+ `ANTHROPIC_API_KEY`. The Penguin Go relay's provider-scoped `PENGUIN_GO_API_KEY`, which no
+ AgentHub client knows, is read by the harness and passed explicitly for every row of that group;
+ unset, the row is refused rather than left to the client's vendor variable. That closes the same
+ hole for Sessions on keyless relay rows, which the probes had already guarded.
+- The models API reports `envKey` only for entries the rule allows a fallback, and the masked
+ `envKeyMasked` preview only where the fallback may be presented as covering the entry (core's
+ `modelEnvPreviewKey`: a row whose own base URL is a vendor endpoint, or a keyless row in a
+ vendor group or Penguin Go) — the eight vLLM presets and a custom row saved without a base URL
+ do fall back, but are no longer shown as "key configured", which would have put a self-hosted
+ model id in front of api.openai.com. The dialog's hint reads the same function, from the row as
+ drafted — group, id, protocol and base URL — and hides the stored mask once the draft resolves
+ to another variable; the group-level "Set key" dialog names a variable only for vendor groups
+ and Penguin Go; the import dialog's key field says the endpoint's key is required.
+- Two leaks one layer down are **not** fixed here and are tracked as an AgentHub follow-up (they
+ reach the harness through the next AgentHub release and bump): the DeepSeek, GLM and Kimi
+ clients hand the OpenAI SDK an undefined key when their own variable is unset, and the SDK
+ fills it from `OPENAI_API_KEY`; and the Anthropic client lets its SDK attach the environment's
+ `ANTHROPIC_AUTH_TOKEN` (and, on Bedrock, `ANTHROPIC_API_KEY`) even beside a row's own key.
+- The `agent-development` plugin's `penguin-sdk` skill states the rule (plugin `2026.09.30.1`).
+- Protocol detection and the add-group listing lend a bare endpoint the protocol's variable on
+ the same terms: the vendor's own URL only. A gateway or a private
+ server is probed anonymously (a protocol-shaped 401 still identifies the route), and a listing
+ with no usable key is refused before a client exists.
+- The `custom` group's Atria Dawn Preview preset, which used to read `ANTHROPIC_API_KEY`, now
+ needs its own key like every other custom row.
+
+## Compatibility
+
+What stops working: a Session, connection test, speed test, vision probe, protocol detection or
+model import on an entry that has no `api_key` and points anywhere other than the vendor's own
+endpoint — every gateway group row, every `custom`, `vllm` or user-created row with its own base URL,
+and a vendor row re-pointed at a proxy — now fails with "has no API key" where it used to run on
+`OPENAI_API_KEY`, `ANTHROPIC_API_KEY` or `GEMINI_API_KEY` from the server environment. A self-hosted
+server that accepts any bearer token is affected too: `OPENAI_API_KEY=dummy` in the environment no
+longer covers it. A keyless Anthropic row with `base_url = "bedrock://<region>"` (AWS credential
+chain) is refused as well, with a message that says so: until AgentHub stops letting its Bedrock
+client attach `ANTHROPIC_API_KEY`, either set the entry's AWS key (`access,secret`) or leave the
+row's base URL empty and export `ANTHROPIC_BASE_URL=bedrock://<region>` instead — a row with no base
+URL still follows AgentHub's own pairing.
+
+What to do: put the key on the row — **Model settings → API key**, the group header's **Set key**,
+or `penguin config model add … --api-key <key>`. A self-hosted or custom server that used to run on
+`OPENAI_API_KEY` + `OPENAI_BASE_URL` in the environment while the row carried its own base URL is
+exactly this case: environment keys are for official endpoints only, so that key goes on the row.
+A row with **no** base URL is untouched and still follows AgentHub's own env pairing (`*_API_KEY`
+with `*_BASE_URL`). Nothing on disk changes shape and no migration runs; entries that already carry
+a key are untouched.
+
+There is no compatibility code, so there is no `backward-compatibility` entry for this batch.
diff --git a/changelog/unreleased/2026-09-18-gateway-no-env-keys.zh.md b/changelog/unreleased/2026-09-18-gateway-no-env-keys.zh.md
new file mode 100644
index 00000000..fc41b02e
--- /dev/null
+++ b/changelog/unreleased/2026-09-18-gateway-no-env-keys.zh.md
@@ -0,0 +1,65 @@
+# 没有 key 的模型条目只在发往厂商自己的端点时才借用环境变量
+
+- **Date:** 2026-09-18
+- **Type:** fix
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#794](https://github.com/Prism-Shadow/penguin-harness/pull/794)
+- **Breaking:** yes — 没有 `api_key` 且 `base_url` 不是厂商官方端点的模型条目(全部网关预置——TokenDance、OpenRouter、Fireworks AI、SiliconFlow、Qwen Pay-As-You-Go、Qwen Token Plan;带自己端点的 `custom`、`vllm` 与自建分组条目;改指到代理或 `bedrock://` 的厂商条目)不再从服务端环境读取 `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / `GEMINI_API_KEY`(或任何厂商变量);会话、连通性测试、分组测速、视觉探测、协议检测与端点导入一律拒绝
+
+[English](2026-09-18-gateway-no-env-keys.md)
+
+AgentHub 的客户端只要没拿到 key,就会读取厂商的环境变量,无论被指向哪个 base URL。网关分组里没有
+key 的条目因此把用户自己的 OpenAI 或 Anthropic key 发给了网关:对一个混合协议网关做一次分组测速会发出
+27 个请求,其中 7 个带着 Anthropic key、20 个带着 OpenAI key;而只要任何一条 Anthropic 条目证明过该变量
+已设置,模型弹窗的 key 输入框就会对网关条目提示「留空则使用环境变量 ANTHROPIC_API_KEY」。现在由
+PenguinHarness 自己在构建任何客户端之前判定没有 key 的条目能否倚赖环境变量,判据是**目的地**而不是
+分组名:环境变量里的 key 只用于官方端点。
+
+## 细节
+
+- core 的 `modelEnvFallback` 是唯一的规则,harness 构建的每个客户端都套用它——会话创建与恢复、视觉代读、
+ 连通性与测速探测、视觉探测、工具性补全经 `resolveModelCredential`,端点列举与协议检测(只有协议与 URL、
+ 尚无条目)经 `endpointEnvApiKey`。没有 key 的条目在以下情形被允许使用其
+ 客户端的变量:没有 base URL(客户端缺省端点即厂商自己的端点,或用户在 key 旁一并设置的
+ `*_BASE_URL`);base URL 是该厂商自己的官方端点之一(目录里 DeepSeek 与 MiniMax 条目即这样钉住)。其余
+ 一律拒绝,报「Model
+ `<provider>/<id>` has no API key … set the API key on the model entry」,服务端将其与 SDK 自身的凭据缺失
+ 错误一样归入 `model_credential_missing`。
+- 允许回退时客户端依旧拿不到 key、自己读取变量,与此前完全一致——厂商条目没有任何损失,包括没有
+ `ANTHROPIC_API_KEY` 的 Bedrock `ANTHROPIC_BASE_URL`。Penguin Go 中转专属的 `PENGUIN_GO_API_KEY` 没有
+ 任何 AgentHub 客户端认识,由 harness 读取并显式传给该分组的每一条;未设置时拒绝,而不是交给客户端去读
+ 厂商变量。这同时补上了没有 key 的中转条目在会话里的同一漏洞(探测路径此前已有守卫)。
+- 模型接口只对规则允许回退的条目报告 `envKey`,而掩码预览 `envKeyMasked` 只在可以把回退呈现为「已覆盖
+ 该条目」时才报告(core 的 `modelEnvPreviewKey`:自带 base URL 且为厂商端点的行,或厂商分组 / Penguin Go
+ 里没有 key 的行)——八个 vLLM 预置与没有 base URL 的 custom 行虽会回退,但不再显示为「已配置 key」,
+ 否则等于把自托管模型 id 摆到 api.openai.com 面前。弹窗提示读同一函数、按草稿中的行——分组、id、协议与
+ base URL——实时解析,草稿解析到别的变量时隐去已存掩码;分组级「手动设置密钥」弹窗只为厂商分组与
+ Penguin Go 点名变量;导入弹窗的 key 输入框改为说明该端点的 key 必填。
+- 下一层的两处泄漏**不在此处修**,作为 AgentHub 后续项跟进(随下一个 AgentHub 版本与 bump 到达 harness):
+ DeepSeek、GLM、Kimi 客户端在自家变量未设置时把 undefined 的 key 交给 OpenAI SDK,SDK 从
+ `OPENAI_API_KEY` 补上;Anthropic 客户端让其 SDK 附带环境里的 `ANTHROPIC_AUTH_TOKEN`(Bedrock 上还有
+ `ANTHROPIC_API_KEY`),即使行上已有自己的 key。
+- `agent-development` 插件的 `penguin-sdk` Skill 写明该规则(插件 `2026.09.30.1`)。
+- 协议检测与新增分组的端点列举按同一口径把协议变量借给裸端点:只借给厂商自己的 URL。网关或私有服务器
+ 一律匿名探测(协议格式的 401 照样能识别路由),没有可用 key 的列举在构建客户端之前即被拒绝。
+- `custom` 分组的预置模型 Atria Dawn Preview 此前读取 `ANTHROPIC_API_KEY`,现在与其他 custom 条目一样
+ 需要自己的 key。
+
+## 兼容性
+
+不再可用的情形:对一个没有 `api_key`、且指向厂商自身端点之外任何地址的条目发起会话、连通性测试、
+测速、视觉探测、协议检测或模型导入——所有网关分组的条目、所有带自己 base URL 的 `custom`、`vllm` 或自建
+分组条目、以及被改指到代理的厂商条目——现在以「has no API key」失败,而此前它们靠服务端环境里的
+`OPENAI_API_KEY`、`ANTHROPIC_API_KEY` 或 `GEMINI_API_KEY` 运行。接受任意 bearer token 的自托管服务器同样
+受影响:环境里的 `OPENAI_API_KEY=dummy` 不再覆盖它。`base_url = "bedrock://<region>"`(AWS 凭据链)且没有
+key 的 Anthropic 条目同样被拒绝,并给出专门的提示:在 AgentHub 不再让其 Bedrock 客户端附带
+`ANTHROPIC_API_KEY` 之前,要么给条目写 AWS key(`access,secret`),要么把条目的 base URL 留空、改在环境里
+设置 `ANTHROPIC_BASE_URL=bedrock://<region>`——没有 base URL 的条目仍按 AgentHub 自己的配对工作。
+
+需要做的事:把 key 放到条目上——**模型配置 → API key**、组头的**手动设置密钥**,或 `penguin config
+model add … --api-key <key>`。此前靠环境里的 `OPENAI_API_KEY` + `OPENAI_BASE_URL` 运行、而条目又自带
+base URL 的自托管或自定义服务器正是这种情形:环境变量里的 key 只用于官方端点,这把 key 要写到条目上。
+**没有** base URL 的条目不受影响,仍按 AgentHub 自己的环境配对(`*_API_KEY` 与 `*_BASE_URL`)工作。磁盘
+上的数据形态不变、不运行任何迁移;已带 key 的条目不受影响。
+
+本批次没有兼容代码,因此不设 `backward-compatibility` 条目。
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index ee813473..e539ff57 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -31,6 +31,7 @@ import {
listInstalledHooks,
projectDir,
resolveSessionMemory,
+ resolveModelCredential,
resolveModelRef,
sessionScratchpadDir,
systemConfigPath,
@@ -227,7 +228,13 @@ export interface CreateSessionOptions {
* own config.
*/
thinkingLevel?: ThinkingLevelName | null;
- /** Explicit credentials; if unspecified, falls back to credentials in the Project config, then to AgentHub reading environment variables. */
+ /**
+ * Explicit credentials; if unspecified, falls back to the credentials in the Project config,
+ * then — only when the entry's requests go to the vendor's own endpoint (no base URL, or a
+ * vendor endpoint) — to the vendor's environment variable, read by AgentHub. A keyless entry
+ * pointed anywhere else (a gateway, a self-hosted server) is refused with a
+ * ModelCredentialError; see resolveModelCredential.
+ */
apiKey?: string;
baseUrl?: string;
/** Internal use: this Session's depth in the subagent spawn chain (0 at the top level), used to cap spawn depth. */
@@ -239,7 +246,7 @@ export interface CreateSessionOptions {
export interface ResumeSessionOptions {
/** Id of the Session to resume. */
sessionId: string;
- /** Explicit credentials; if unspecified, falls back to credentials in the Project config, then to AgentHub reading environment variables. */
+ /** Explicit credentials; if unspecified, falls back to the Project config, then to the vendor's environment variable on the same terms as CreateSessionOptions.apiKey. */
apiKey?: string;
baseUrl?: string;
}
@@ -357,6 +364,26 @@ function resolveCompaction(
};
}
+/**
+ * The credential a Session's (or a describer's) client is built with for a model entry: the
+ * explicit override, else the entry's inline fields, else — only where resolveModelCredential
+ * allows it — nothing, so the routed client reads its own environment variable. A keyless
+ * entry whose endpoint is not the vendor's own throws its ModelCredentialError here, which
+ * hosts file with the SDKs' missing-credential errors (the server's `isMissingCredential`).
+ */
+function entryCredential(
+ entry: ModelEntry,
+ opts: { apiKey?: string | undefined; baseUrl?: string | undefined },
+): { apiKey?: string; baseUrl?: string } {
+ return resolveModelCredential({
+ provider: entry.provider,
+ modelId: entry.model_id,
+ clientType: entry.client_type,
+ baseUrl: opts.baseUrl ?? entry.base_url,
+ apiKey: opts.apiKey ?? entry.api_key,
+ });
+}
+
/**
* Output cap for meta requests (title generation / vision describing): these carry their own
* small hardcoded budget, tightened further by the entry's per-model `max_tokens` when that is
@@ -620,11 +647,11 @@ export class Agent {
`Model is not in the Project config: ${formatModelRef(ref)}. Use \`penguin config model list\` to see the configured models, or \`penguin config model add\` to add one.`,
);
}
- // Credentials are inlined on the model entry (single config file); an
- // explicit argument takes priority, falling back to AgentHub reading env vars
- // when both are absent.
- const apiKey = opts.apiKey ?? modelEntry.api_key;
- const baseUrl = opts.baseUrl ?? modelEntry.base_url;
+ // Credentials are inlined on the model entry (single config file); an explicit
+ // argument takes priority. With neither, the entry may lean on the environment only
+ // where the rule in resolveModelCredential allows (the vendor's own endpoint): a keyless
+ // row pointed elsewhere is refused here, before any client exists.
+ const { apiKey, baseUrl } = entryCredential(modelEntry, opts);
// An explicit Workspace must already exist as a directory: if it
// doesn't, throw rather than auto-create (to avoid a typo silently working in
@@ -735,8 +762,9 @@ export class Agent {
`The original Session's Model is not in the Project config: ${formatModelRef(ref)}. Use \`penguin config model add\` to configure it again before resuming.`,
);
}
- const apiKey = opts.apiKey ?? modelEntry.api_key;
- const baseUrl = opts.baseUrl ?? modelEntry.base_url;
+ // Same credential rule as createSession (see entryCredential): a key deleted since the
+ // Session was created surfaces here, at resume.
+ const { apiKey, baseUrl } = entryCredential(modelEntry, opts);
// No level at resume: the host re-applies its stored value (Session.thinkingLevel) when it holds one,
// and contexts opened without a pin read the Agent config's chain (the same chain
@@ -1139,10 +1167,13 @@ export class Agent {
visionDescriber = {
// The model attribution in the tool output matches the request's source: both are the entry's upstream model_id.
modelId: visionEntry.model_id,
+ // Resolved on each call rather than once here: the same credential rule as the
+ // session model (a keyless entry pointed away from its vendor is refused), and a
+ // refusal is a failed read_file, not a failed Session.
createLLM: () =>
new GenerativeModel({
modelId: visionEntry.model_id,
- ...(visionEntry.api_key !== undefined ? { apiKey: visionEntry.api_key } : {}),
+ ...entryCredential(visionEntry, {}),
...(this.assembly?.resolveModelApiKey
? {
resolveApiKey: () =>
@@ -1155,7 +1186,6 @@ export class Agent {
}),
}
: {}),
- ...(visionEntry.base_url !== undefined ? { baseUrl: visionEntry.base_url } : {}),
...(visionEntry.client_type !== undefined
? { clientType: visionEntry.client_type }
: {}),
diff --git a/packages/core/src/llm/list-models.ts b/packages/core/src/llm/list-models.ts
index 0cf83f79..a49e8449 100644
--- a/packages/core/src/llm/list-models.ts
+++ b/packages/core/src/llm/list-models.ts
@@ -9,35 +9,63 @@
* down to that client's own models, and a client with no models endpoint rejects with its
* `UnsupportedOperationError` (recognizable by `err.name`).
*
- * Credential semantics mirror the connectivity test: an omitted `apiKey` lets the wrapped
- * SDK read the protocol's own environment variable (`OPENAI_API_KEY` / `ANTHROPIC_API_KEY`),
- * and a missing credential surfaces as the SDK's own construction/request error — callers
+ * Credential semantics mirror the connectivity test: an omitted `apiKey` falls back to the
+ * protocol's environment variable (`OPENAI_API_KEY` / `ANTHROPIC_API_KEY`) **only when the
+ * base URL is that vendor's own endpoint** (see endpointEnvApiKey) — the wrapped SDK would
+ * otherwise read the variable itself and send the
+ * user's vendor key to whatever endpoint was typed, so with no usable key the listing is
+ * refused before a client exists. Other failures surface as the SDK's own errors — callers
* collapse errors into their outcome shape, nothing is caught here.
*/
import { AutoLLMClient } from "@prismshadow/agenthub";
+import {
+ ModelCredentialError,
+ endpointEnvApiKey,
+ modelEnvFallback,
+} from "../state/model-catalog.js";
/** One endpoint listing request: which protocol to speak, and the credential/URL to speak it with. */
export interface ListEndpointModelsOptions {
/** AgentHub client type to route through (the add-group flow passes a detected generic protocol). */
clientType: string;
- /** Plaintext API key; omitted = the SDK's environment fallback for the protocol. */
+ /** Plaintext API key; omitted = the environment fallback for the protocol, where the endpoint allows one. */
apiKey?: string;
/** Endpoint base URL; omitted = the vendor default of the routed client. */
baseUrl?: string;
+ /** Environment the fallback reads; defaults to `process.env` (injectable for tests). */
+ env?: Readonly<Record<string, string | undefined>>;
}
/**
* Lists the model ids the endpoint serves, in the order the endpoint returned them.
* Throws whatever AgentHub or the wrapped SDK throws (unsupported operation, auth,
- * network); bounding the call in time is the caller's concern.
+ * network), or a ModelCredentialError when there is no key and the endpoint may not use
+ * the environment's; bounding the call in time is the caller's concern.
*/
export async function listEndpointModels(options: ListEndpointModelsOptions): Promise<string[]> {
+ const apiKey =
+ options.apiKey || endpointEnvApiKey(options.clientType, options.baseUrl, options.env);
+ if (apiKey === undefined) {
+ // Two different situations, two messages: the vendor's own endpoint with its variable
+ // simply unset, and an endpoint the environment is not lent to at all.
+ const allowed = modelEnvFallback({
+ provider: "custom",
+ modelId: "",
+ clientType: options.clientType,
+ baseUrl: options.baseUrl,
+ });
+ throw new ModelCredentialError(
+ allowed !== undefined
+ ? `No API key for ${options.baseUrl ?? "the endpoint"}: ${allowed.envKey} is not set in the server environment. Enter the API key, or set the variable.`
+ : `No API key for ${options.baseUrl ?? "the endpoint"}. The environment lends a key only to a vendor's own endpoint: enter the endpoint's API key.`,
+ );
+ }
const client = new AutoLLMClient({
// AutoLLMClient routes by clientType when given one; model is its fallback routing key
// and must still be a string, so the client type doubles as it.
model: options.clientType,
clientType: options.clientType,
- ...(options.apiKey ? { apiKey: options.apiKey } : {}),
+ apiKey,
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
});
return client.listModels();
diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.ts
index ca313466..0922ee86 100644
--- a/packages/core/src/state/model-catalog.ts
+++ b/packages/core/src/state/model-catalog.ts
@@ -122,7 +122,12 @@ export interface ModelProviderInfo {
id: string;
/** Display name (brand name, shared by Chinese and English UI). */
label: string;
- /** API key env var name (AgentHub reads this automatically when credential is blank). */
+ /**
+ * API key env var name: the pair AgentHub's client for this group's rows reads when handed no
+ * key. Whether a keyless row may actually lean on it is decided per entry by
+ * modelEnvFallback — a gateway group records OPENAI_* because that is what its generic
+ * client reads, and precisely for that reason its rows never get the fallback.
+ */
envKey: string;
/** base URL env var name. */
envBaseUrlKey: string;
@@ -272,10 +277,12 @@ export const MODELSCOPE_PROVIDER_ID = "modelscope";
* Qwen Pay-As-You-Go and Qwen Token Plan — reach their models through one of AgentHub's generic
* OpenAI-protocol clients (`openai-responses` for OpenRouter, `openai-chat` for the rest).
* Those clients read **OPENAI_API_KEY / OPENAI_BASE_URL** when the credential is blank, not
- * the gateway's own variable names, so every such gateway group records the OPENAI_* pair and the
- * env fallback hint the frontend shows is accurate either way. ModelScope also records the
- * OPENAI_* pair because its group credential is an api-inference access token even when a row's
- * protocol is model-specific.
+ * the gateway's own variable names, so every such gateway group records the OPENAI_* pair as the
+ * fact it is — and that is exactly why a keyless gateway row is refused the fallback (see
+ * modelEnvFallback): the variable holds the user's OpenAI key, and a gateway is not OpenAI.
+ * ModelScope also records the OPENAI_* pair because its group credential is an api-inference
+ * access token even when a row's protocol is model-specific; its rows are refused the fallback
+ * on the same terms.
*/
export const MODEL_PROVIDERS: ModelProviderInfo[] = [
{
@@ -2648,7 +2655,9 @@ export function resolveModelEnv(modelId: string, clientType?: string): ModelEnvI
* AgentHub client selected by model id / protocol. Aggregate groups are deliberately different:
* Penguin Go's Google and DeepSeek routes share one relay credential, and ModelScope's Qwen and
* DeepSeek routes share one api-inference token, so the provider-scoped variable must win over
- * the selected protocol everywhere the harness resolves a key.
+ * the selected protocol everywhere the harness resolves a key. Whether a keyless row may use
+ * that variable is modelEnvFallback's decision: ModelScope's is OPENAI_*, a vendor variable, so
+ * its rows get no fallback.
*/
export function resolveProviderModelEnv(
provider: string,
@@ -2664,6 +2673,244 @@ export function resolveProviderModelEnv(
return resolveModelEnv(modelId, clientType);
}
+/**
+ * The endpoints AgentHub's vendor clients talk to when handed no base URL, per credential
+ * variable: the OpenAI and Anthropic SDK defaults, Google's Generative Language host, the
+ * defaults the vendor-specific clients (deepseek_v4, glm5_3, kimi_k3, minimax_m3) carry, plus
+ * the second official host where a vendor runs two (Z.AI's mainland bigmodel.cn, Moonshot's
+ * international .ai, MiniMax's mainland minimaxi.com). A key taken from the environment is
+ * sent only to one of these — see modelEnvFallback.
+ */
+export const VENDOR_ENDPOINTS: Readonly<Record<string, readonly string[]>> = {
+ OPENAI_API_KEY: ["https://api.openai.com/v1"],
+ ANTHROPIC_API_KEY: ["https://api.anthropic.com"],
+ GEMINI_API_KEY: ["https://generativelanguage.googleapis.com"],
+ DEEPSEEK_API_KEY: [DEEPSEEK_BASE_URL],
+ ZAI_API_KEY: ["https://api.z.ai/api/paas/v4", "https://open.bigmodel.cn/api/paas/v4"],
+ MOONSHOT_API_KEY: ["https://api.moonshot.cn/v1", "https://api.moonshot.ai/v1"],
+ MINIMAX_API_KEY: [MINIMAX_BASE_URL, "https://api.minimaxi.com/v1"],
+};
+
+/**
+ * Endpoint equality for the credential rule: scheme and host compared case-insensitively
+ * (with the port), the path without trailing slashes; a value that does not parse as a URL
+ * matches nothing.
+ */
+export function sameEndpoint(a: string, b: string): boolean {
+ const norm = (value: string): string | undefined => {
+ try {
+ const u = new URL(value.trim());
+ return `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/, "")}`;
+ } catch {
+ return undefined;
+ }
+ };
+ const na = norm(a);
+ return na !== undefined && na === norm(b);
+}
+
+/** What the credential rule reads off a model entry: the paired reference, the pinned protocol and the endpoint. */
+export interface ModelCredentialShape {
+ provider: string;
+ modelId: string;
+ /** Pinned AgentHub client type; blank or absent = auto-routed by model id. */
+ clientType?: string | undefined;
+ /** Inline base URL; blank or absent = the routed client's default endpoint (or its `*_BASE_URL` variable). */
+ baseUrl?: string | undefined;
+}
+
+/** The environment pair a keyless entry may fall back to, and who reads it. */
+export interface ModelEnvFallback extends ModelEnvInfo {
+ /**
+ * `true`: AgentHub's routed client reads this pair itself, so the harness hands it no key
+ * and the client's own environment lookup — and its own error when the variable is unset —
+ * apply unchanged. `false`: a provider-scoped pair no AgentHub client knows (the Penguin Go
+ * relay's); the harness reads it and passes the value explicitly, refusing when it is unset.
+ */
+ readByClient: boolean;
+}
+
+/**
+ * The environment fallback a keyless model entry is allowed, or `undefined` when it gets
+ * none and must carry its own key.
+ *
+ * AgentHub's clients read a vendor variable (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, …)
+ * whenever they are handed no key, whatever base URL they were pointed at — so a keyless row
+ * in a gateway group would send the user's own OpenAI or Anthropic key to the gateway. The
+ * rule here is about the **destination**, not the group's label: environment keys are for
+ * official endpoints only.
+ *
+ * - No base URL on the entry: the routed client talks to its own default endpoint, or to the
+ * `*_BASE_URL` the user set beside the key — that pairing is AgentHub's own and is left to
+ * it entirely; the client reads the pair itself.
+ * - A base URL that is one of that vendor's own official endpoints (VENDOR_ENDPOINTS; the
+ * catalog pins the DeepSeek and MiniMax rows this way) — allowed.
+ * - Anything else — every gateway group's preset endpoint, custom / user-defined / vLLM rows
+ * with their own endpoints, a vendor row re-pointed at a proxy — refused. A row's own base
+ * URL equal to the `*_BASE_URL` variable's value earns no exception either (per the user:
+ * environment keys are for official endpoints only): put the key on the row.
+ * - A group with a provider-scoped pair (Penguin Go, whose key no AgentHub client reads) is
+ * allowed that pair for every one of its rows, regardless of base URL; the harness reads it.
+ * A group pair that is itself a vendor variable (ModelScope records OPENAI_*) is not
+ * provider-scoped: its rows follow the destination rule like any other gateway's.
+ *
+ * Pure, so the server and the models page answer the same question for the preview, the
+ * dialog hint and the refusal.
+ */
+export function modelEnvFallback(entry: ModelCredentialShape): ModelEnvFallback | undefined {
+ const clientType = entry.clientType?.trim() || undefined;
+ const clientPair = resolveModelEnv(entry.modelId, clientType);
+ const groupPair = resolveProviderModelEnv(entry.provider, entry.modelId, clientType);
+ // VENDOR_ENDPOINTS keys every variable an AgentHub client reads (each pair resolveModelEnv
+ // can name), so a group pair outside it is one only the harness knows.
+ if (
+ groupPair !== undefined &&
+ groupPair.envKey !== clientPair?.envKey &&
+ !Object.hasOwn(VENDOR_ENDPOINTS, groupPair.envKey)
+ ) {
+ return { ...groupPair, readByClient: false };
+ }
+ if (clientPair === undefined) return undefined;
+ const baseUrl = entry.baseUrl?.trim();
+ if (!baseUrl) return { ...clientPair, readByClient: true };
+ if ((VENDOR_ENDPOINTS[clientPair.envKey] ?? []).some((own) => sameEndpoint(own, baseUrl))) {
+ return { ...clientPair, readByClient: true };
+ }
+ return undefined;
+}
+
+/**
+ * The variable a keyless entry added to this group with the group's defaults falls back to,
+ * or `undefined` when such an entry gets none: gateways (a preset base URL), the pinned
+ * self-hosted group (vLLM), custom and user-defined groups all point away from the vendors'
+ * own endpoints. The group-level key dialog's hint and the group header read this.
+ */
+export function providerEnvFallbackKey(providerId: string): string | undefined {
+ const info = providerInfo(providerId);
+ if (
+ info === undefined ||
+ info.id === "custom" ||
+ info.gatewayBaseUrl !== undefined ||
+ info.clientType !== undefined
+ ) {
+ return undefined;
+ }
+ return info.envKey;
+}
+
+/**
+ * A model entry that cannot be given to an AgentHub client as configured: no key, and no
+ * environment variable it may use; or a relay row with no endpoint for its relay key. The
+ * message names the model and what to do, and says "API key" so hosts that classify
+ * credential errors by message (the server's `isMissingCredential`) file it with the SDKs'
+ * own missing-credential errors.
+ */
+export class ModelCredentialError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "ModelCredentialError";
+ }
+}
+
+/** What a client is constructed with: an explicit key, or none when the routed client may read its own variable. */
+export interface ResolvedModelCredential {
+ apiKey?: string;
+ baseUrl?: string;
+}
+
+/**
+ * The credential an AgentHub client is built with for a **model entry**, applying
+ * modelEnvFallback's rule (the one function every path shares): Session creation and resume,
+ * the vision describer, the connectivity / speed / vision probes and the utility completion
+ * go through here; the endpoint listing and protocol detection, which have a protocol and a
+ * URL but no entry, apply the same rule through endpointEnvApiKey.
+ *
+ * - An inline key (the entry's, or an explicit override) is used as given.
+ * - No key, fallback allowed and read by the client: no key is handed over, the client reads
+ * the pair itself — byte-for-byte what happened before this rule existed, including the
+ * SDK's own error when the variable is unset too (an entry with no base URL under a Bedrock
+ * `ANTHROPIC_BASE_URL` and no `ANTHROPIC_API_KEY` stays valid).
+ * - No key, fallback allowed but provider-scoped: the variable's value is passed explicitly,
+ * and an unset variable is refused here rather than letting the client read a vendor's.
+ * - No key, no fallback: refused with a ModelCredentialError before any client exists.
+ * - A provider-scoped group's row (Penguin Go) is also refused without a base URL, whatever
+ * the key's source: the relay key must not travel to the vendor's default endpoint.
+ */
+export function resolveModelCredential(
+ entry: ModelCredentialShape & { apiKey?: string | undefined },
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): ResolvedModelCredential {
+ const ref = `${entry.provider}/${entry.modelId}`;
+ const baseUrl = entry.baseUrl || undefined;
+ const apiKey = entry.apiKey || undefined;
+ const fallback = modelEnvFallback(entry);
+ if (fallback !== undefined && !fallback.readByClient && !baseUrl?.trim()) {
+ throw new ModelCredentialError(
+ `Model ${ref} has no base URL. Its API key belongs to the ${providerInfo(entry.provider)?.label ?? entry.provider} endpoint and cannot be sent to the vendor's default endpoint: set the base URL on the model entry.`,
+ );
+ }
+ if (apiKey !== undefined) return { apiKey, ...(baseUrl !== undefined ? { baseUrl } : {}) };
+ if (fallback === undefined) {
+ // A Bedrock region on the entry is not "not the vendor's": it is AWS, whose usual
+ // credential is the default provider chain rather than a key. Until AgentHub stops
+ // letting its Bedrock client attach ANTHROPIC_API_KEY, a keyless row here is refused,
+ // and the message says what still works.
+ if (baseUrl?.trim().toLowerCase().startsWith("bedrock://")) {
+ throw new ModelCredentialError(
+ `Model ${ref} has no API key. A Bedrock endpoint set on the model entry cannot fall back to the environment yet: set the entry's AWS key (access,secret), or leave its base URL empty and set ANTHROPIC_BASE_URL=${baseUrl.trim()} in the server environment.`,
+ );
+ }
+ throw new ModelCredentialError(
+ `Model ${ref} has no API key. Its endpoint is not the vendor's own, so no environment variable is used for it: set the API key on the model entry.`,
+ );
+ }
+ if (fallback.readByClient) return baseUrl !== undefined ? { baseUrl } : {};
+ const value = env[fallback.envKey]?.trim();
+ if (!value) {
+ throw new ModelCredentialError(
+ `Model ${ref} has no API key: set one on the model entry, or set ${fallback.envKey} in the server environment.`,
+ );
+ }
+ return { apiKey: value, ...(baseUrl !== undefined ? { baseUrl } : {}) };
+}
+
+/**
+ * The key the environment lends a bare endpoint spoken to on a generic protocol client —
+ * the add-group listing and the protocol probes, which have a base URL and a protocol but no
+ * entry yet. Same rule as modelEnvFallback: only a vendor's own endpoint gets the vendor's
+ * key; a gateway or a private server gets none.
+ */
+export function endpointEnvApiKey(
+ clientType: string,
+ baseUrl: string | undefined,
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): string | undefined {
+ const fallback = modelEnvFallback({ provider: "custom", modelId: "", clientType, baseUrl });
+ if (fallback === undefined) return undefined;
+ return env[fallback.envKey]?.trim() || undefined;
+}
+
+/**
+ * The variable the UI may present as covering a keyless entry — the masked preview on the
+ * card, the dialog's "leave empty to use …" hint — or `undefined` when nothing should be
+ * promised. Narrower than modelEnvFallback on purpose: a row with no base URL in a group whose
+ * defaults point away from the vendor (the vLLM presets, a custom row saved without an
+ * endpoint) does fall back to OPENAI_API_KEY under the rule, but presenting that as "key
+ * configured" would encourage exactly the misconfiguration that sends the OpenAI key and a
+ * self-hosted model id to api.openai.com. The preview therefore needs the row to name a vendor
+ * endpoint itself, or to sit in a group whose defaults are the vendor's (providerEnvFallbackKey).
+ * The server's `GET /models` preview and the web dialog's hint both read this, so the two
+ * cannot disagree.
+ */
+export function modelEnvPreviewKey(entry: ModelCredentialShape): string | undefined {
+ const fallback = modelEnvFallback(entry);
+ if (fallback === undefined) return undefined;
+ if (entry.baseUrl?.trim() || providerEnvFallbackKey(entry.provider) !== undefined) {
+ return fallback.envKey;
+ }
+ return undefined;
+}
+
/**
* 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
diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.ts
index e29723fe..2e57d13a 100644
--- a/packages/core/test/agent.test.ts
+++ b/packages/core/test/agent.test.ts
@@ -25,6 +25,7 @@ import {
systemConfigPath,
} from "../src/state/paths.js";
import {
+ MODEL_CATALOG,
addModel,
createAgent,
DEFAULT_AGENT_ID,
@@ -1232,3 +1233,53 @@ describe("Agent model contexts are assembled from the Agent State on disk, at ev
}
});
});
+
+describe("Agent.createSession credential rule (a keyless gateway row never borrows a vendor key)", () => {
+ it("refuses a keyless gateway preset before any client exists, even with OPENAI_API_KEY set", async () => {
+ // stubProviderKeys has set OPENAI_API_KEY and friends: the pre-rule behaviour was to hand
+ // AgentHub no key and let its generic client read the variable — sending the user's
+ // OpenAI key to the gateway. The preset carries the gateway's base URL and no key.
+ const preset = MODEL_CATALOG.find((m) => m.provider === "openrouter" && m.retired !== true)!;
+ expect(process.env.OPENAI_API_KEY).toBeDefined();
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-gateway-keyless");
+ await fs.mkdir(ws, { recursive: true });
+ await expect(
+ agent.createSession({ workspaceDir: ws, provider: preset.provider, modelId: preset.modelId }),
+ ).rejects.toThrow(/has no API key/);
+ // No Session, so nothing to dispose; the same row with its own key is a normal Session
+ // (an Agent reads the Project config when it is created, so a fresh one sees the key).
+ await addModel(tmpRoot, DEFAULT_PROJECT_ID, {
+ provider: preset.provider,
+ model_id: preset.modelId,
+ api_key: "sk-gateway-own-key",
+ });
+ const keyed = await createAgent();
+ const session = await keyed.createSession({
+ workspaceDir: ws,
+ provider: preset.provider,
+ modelId: preset.modelId,
+ });
+ try {
+ expect(session.provider).toBe(preset.provider);
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("still lets a keyless vendor preset lean on the vendor's own variable", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-vendor-keyless");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({
+ workspaceDir: ws,
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ });
+ try {
+ expect(session.modelId).toBe("claude-sonnet-4-6");
+ } finally {
+ session.dispose();
+ }
+ });
+});
diff --git a/packages/core/test/list-endpoint-models.test.ts b/packages/core/test/list-endpoint-models.test.ts
index 5f964d69..6a763574 100644
--- a/packages/core/test/list-endpoint-models.test.ts
+++ b/packages/core/test/list-endpoint-models.test.ts
@@ -1,7 +1,9 @@
/**
* listEndpointModels: the thin AgentHub wrapper — routes by the given client type,
- * forwards credential/base URL only when present, and returns the listing verbatim
- * (order preserved, no dedup: presentation policy belongs to callers).
+ * resolves the credential itself (the environment lends a key only to the vendor's own
+ * endpoint and refuses the listing otherwise, before any client exists), forwards the base
+ * URL only when present, and returns the listing verbatim (order preserved, no dedup:
+ * presentation policy belongs to callers).
*/
import { describe, expect, it, vi } from "vitest";
@@ -46,10 +48,41 @@ describe("listEndpointModels", () => {
]);
});
- it("omits absent credential and base URL so the SDK's environment fallback applies", async () => {
+ it("lends the protocol's environment key to the vendor's own endpoint (no base URL = the vendor default)", async () => {
captured.options.length = 0;
- await listEndpointModels({ clientType: "ant-messages" });
- expect(captured.options).toEqual([{ model: "ant-messages", clientType: "ant-messages" }]);
+ await listEndpointModels({
+ clientType: "ant-messages",
+ env: { ANTHROPIC_API_KEY: " sk-env-1 " },
+ });
+ expect(captured.options).toEqual([
+ { model: "ant-messages", clientType: "ant-messages", apiKey: "sk-env-1" },
+ ]);
+ });
+
+ it("refuses a keyless listing of a foreign endpoint before a client exists, whatever the environment holds", async () => {
+ captured.options.length = 0;
+ await expect(
+ listEndpointModels({
+ clientType: "openai-chat",
+ baseUrl: "https://gw.example/v1",
+ env: { OPENAI_API_KEY: "sk-env-2" },
+ }),
+ ).rejects.toMatchObject({
+ name: "ModelCredentialError",
+ message: expect.stringContaining("enter the endpoint's API key"),
+ });
+ expect(captured.options).toEqual([]);
+ });
+
+ it("names the unset variable when the vendor's own endpoint has no key to lend", async () => {
+ captured.options.length = 0;
+ await expect(listEndpointModels({ clientType: "ant-messages", env: {} })).rejects.toMatchObject(
+ {
+ name: "ModelCredentialError",
+ message: expect.stringContaining("ANTHROPIC_API_KEY is not set"),
+ },
+ );
+ expect(captured.options).toEqual([]);
});
it("propagates AgentHub errors unchanged (callers collapse them into their outcome shape)", async () => {
@@ -57,9 +90,9 @@ describe("listEndpointModels", () => {
name: "UnsupportedOperationError",
});
try {
- await expect(listEndpointModels({ clientType: "claude-5" })).rejects.toMatchObject({
- name: "UnsupportedOperationError",
- });
+ await expect(
+ listEndpointModels({ clientType: "claude-5", apiKey: "sk-list-3" }),
+ ).rejects.toMatchObject({ name: "UnsupportedOperationError" });
} finally {
captured.fail = undefined;
}
diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.ts
index c7237839..f0730aae 100644
--- a/packages/core/test/model-catalog.test.ts
+++ b/packages/core/test/model-catalog.test.ts
@@ -3,6 +3,7 @@
* three-bucket pricing, lookups, and preset entry generation.
*/
import { describe, expect, it } from "vitest";
+import { listEndpointModels } from "../src/llm/list-models.js";
import {
APP_URL,
MODEL_CATALOG,
@@ -25,6 +26,14 @@ import {
isVendorGroup,
resolveModelEnv,
resolveProviderModelEnv,
+ ModelCredentialError,
+ PENGUIN_GO_BASE_URL,
+ endpointEnvApiKey,
+ modelEnvFallback,
+ modelEnvPreviewKey,
+ providerEnvFallbackKey,
+ resolveModelCredential,
+ sameEndpoint,
unroutableVendorModel,
} from "../src/state/index.js";
@@ -1879,3 +1888,287 @@ describe("off-peak schedules", () => {
}
});
});
+
+describe("modelEnvFallback / resolveModelCredential (a vendor key from the environment goes only to the vendor)", () => {
+ const VENDOR_ENV = {
+ OPENAI_API_KEY: "sk-openai-env",
+ ANTHROPIC_API_KEY: "sk-anthropic-env",
+ GEMINI_API_KEY: "sk-gemini-env",
+ DEEPSEEK_API_KEY: "sk-deepseek-env",
+ };
+ const shapeOf = (m: (typeof MODEL_CATALOG)[number]) => ({
+ provider: m.provider,
+ modelId: m.modelId,
+ clientType: m.clientType,
+ baseUrl: m.baseUrl,
+ });
+
+ it("refuses every keyless row of every gateway group, whatever vendor variables are set", () => {
+ const gateways = MODEL_PROVIDERS.filter((p) => p.gatewayBaseUrl !== undefined).map((p) => p.id);
+ expect(gateways).toContain("tokendance");
+ expect(gateways).toContain("openrouter");
+ const rows = MODEL_CATALOG.filter((m) => gateways.includes(m.provider));
+ expect(rows.length).toBeGreaterThan(20);
+ for (const m of rows) {
+ expect(modelEnvFallback(shapeOf(m)), `${m.provider}/${m.modelId}`).toBeUndefined();
+ expect(
+ () => resolveModelCredential(shapeOf(m), VENDOR_ENV),
+ `${m.provider}/${m.modelId}`,
+ ).toThrow(ModelCredentialError);
+ }
+ // The message says "API key", which is what hosts classify a missing credential by.
+ expect(() =>
+ resolveModelCredential(shapeOf(catalogEntryFor("tokendance", "glm-5.3")!), VENDOR_ENV),
+ ).toThrow(/has no API key/);
+ });
+
+ it("leaves a first-party vendor row on its client's own variable, handing the client no key", () => {
+ // No base URL: the client's default endpoint is the vendor's own.
+ const sonnet = shapeOf(catalogEntryFor("anthropic", "claude-sonnet-4-6")!);
+ expect(modelEnvFallback(sonnet)).toEqual({
+ envKey: "ANTHROPIC_API_KEY",
+ envBaseUrlKey: "ANTHROPIC_BASE_URL",
+ readByClient: true,
+ });
+ expect(resolveModelCredential(sonnet, VENDOR_ENV)).toEqual({});
+ // A pinned vendor endpoint (the catalog's DeepSeek / MiniMax rows) is the vendor's own too.
+ const flash = shapeOf(catalogEntryFor("deepseek", "deepseek-flash")!);
+ expect(flash.baseUrl).toBe("https://api.deepseek.com");
+ expect(modelEnvFallback(flash)?.envKey).toBe("DEEPSEEK_API_KEY");
+ expect(resolveModelCredential(flash, VENDOR_ENV)).toEqual({
+ baseUrl: "https://api.deepseek.com",
+ });
+ // The variable being unset is the client's business, not ours: still handed nothing
+ // (a Bedrock ANTHROPIC_BASE_URL with no ANTHROPIC_API_KEY stays valid).
+ expect(resolveModelCredential(sonnet, {})).toEqual({});
+ // An inline key always wins, on any row.
+ expect(resolveModelCredential({ ...sonnet, apiKey: "sk-inline" }, VENDOR_ENV)).toEqual({
+ apiKey: "sk-inline",
+ });
+ expect(
+ resolveModelCredential(
+ { ...shapeOf(catalogEntryFor("openrouter", "openai/gpt-5.5")!), apiKey: "sk-or" },
+ VENDOR_ENV,
+ ),
+ ).toMatchObject({ apiKey: "sk-or" });
+ });
+
+ it("reads the Penguin Go relay's own variable itself and never a vendor's", () => {
+ const relayRows = MODEL_CATALOG.filter((m) => m.provider === "penguin-go");
+ expect(relayRows.length).toBeGreaterThan(0);
+ for (const m of relayRows) {
+ expect(modelEnvFallback(shapeOf(m)), m.modelId).toEqual({
+ envKey: "PENGUIN_GO_API_KEY",
+ envBaseUrlKey: "PENGUIN_GO_BASE_URL",
+ readByClient: false,
+ });
+ // Vendor variables set, relay variable unset: refused, not GEMINI_API_KEY.
+ expect(() => resolveModelCredential(shapeOf(m), VENDOR_ENV), m.modelId).toThrow(
+ /PENGUIN_GO_API_KEY/,
+ );
+ expect(
+ resolveModelCredential(shapeOf(m), { ...VENDOR_ENV, PENGUIN_GO_API_KEY: " pg-key " }),
+ m.modelId,
+ ).toEqual({ apiKey: "pg-key", baseUrl: PENGUIN_GO_BASE_URL });
+ }
+ // The relay key belongs to the relay endpoint: a row with no base URL is refused even
+ // with a key, so the key cannot travel to the vendor's default endpoint.
+ expect(() =>
+ resolveModelCredential(
+ {
+ provider: "penguin-go",
+ modelId: "gemini-3.8-flash",
+ clientType: "gemini-3.8",
+ apiKey: "pg",
+ },
+ VENDOR_ENV,
+ ),
+ ).toThrow(/has no base URL/);
+ });
+
+ it("judges custom, vLLM and user-defined rows by their endpoint, not their group", () => {
+ // A private server: refused.
+ const local = {
+ provider: "custom",
+ modelId: "local-model",
+ clientType: "openai-chat",
+ baseUrl: "http://127.0.0.1:8000/v1",
+ };
+ expect(modelEnvFallback(local)).toBeUndefined();
+ expect(() => resolveModelCredential(local, VENDOR_ENV)).toThrow(ModelCredentialError);
+ const vllm = shapeOf(MODEL_CATALOG.find((m) => m.provider === "vllm")!);
+ expect(modelEnvFallback({ ...vllm, baseUrl: "http://gpu-box:8000/v1" })).toBeUndefined();
+ // The vendor's own endpoint typed into a custom row: the OpenAI key goes to OpenAI.
+ expect(modelEnvFallback({ ...local, baseUrl: "https://api.openai.com/v1/" })?.envKey).toBe(
+ "OPENAI_API_KEY",
+ );
+ // OPENAI_BASE_URL naming the very same server earns no exception (environment keys are
+ // for official endpoints only): the key goes on the row.
+ const paired = { ...VENDOR_ENV, OPENAI_BASE_URL: "http://127.0.0.1:8000/v1/" };
+ expect(() => resolveModelCredential(local, paired)).toThrow(ModelCredentialError);
+ // A user-defined group with no base URL auto-routes to the vendor: allowed, like before.
+ expect(modelEnvFallback({ provider: "myproxy", modelId: "claude-sonnet-4-6" })?.envKey).toBe(
+ "ANTHROPIC_API_KEY",
+ );
+ // A vendor row re-pointed at a proxy: refused.
+ expect(
+ modelEnvFallback({
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ baseUrl: "https://proxy.example/anthropic",
+ }),
+ ).toBeUndefined();
+ // An id nothing routes has no client and so no variable.
+ expect(modelEnvFallback({ provider: "custom", modelId: "opaque" })).toBeUndefined();
+ });
+
+ it("endpointEnvApiKey lends a bare endpoint the protocol's key on the same terms", () => {
+ expect(
+ endpointEnvApiKey("openai-chat", "https://gw.example.com/v1", VENDOR_ENV),
+ ).toBeUndefined();
+ expect(endpointEnvApiKey("ant-messages", "https://gw.example.com", VENDOR_ENV)).toBeUndefined();
+ expect(endpointEnvApiKey("openai-chat", "https://api.openai.com/v1", VENDOR_ENV)).toBe(
+ "sk-openai-env",
+ );
+ expect(endpointEnvApiKey("ant-messages", "https://api.anthropic.com/", VENDOR_ENV)).toBe(
+ "sk-anthropic-env",
+ );
+ expect(endpointEnvApiKey("openai-responses", undefined, VENDOR_ENV)).toBe("sk-openai-env");
+ // Not even when OPENAI_BASE_URL names that very URL.
+ expect(
+ endpointEnvApiKey("openai-chat", "https://gw.example.com/v1", {
+ ...VENDOR_ENV,
+ OPENAI_BASE_URL: "https://gw.example.com/v1",
+ }),
+ ).toBeUndefined();
+ expect(
+ endpointEnvApiKey("openai-chat", "https://api.openai.com/v1", { OPENAI_API_KEY: " " }),
+ ).toBeUndefined();
+ });
+
+ it("providerEnvFallbackKey names the group-level fallback only for first-party groups", () => {
+ expect(providerEnvFallbackKey("anthropic")).toBe("ANTHROPIC_API_KEY");
+ expect(providerEnvFallbackKey("deepseek")).toBe("DEEPSEEK_API_KEY");
+ expect(providerEnvFallbackKey("penguin-go")).toBe("PENGUIN_GO_API_KEY");
+ for (const id of [
+ "tokendance",
+ "openrouter",
+ "fireworks",
+ "siliconflow",
+ "qwen-token-plan",
+ "vllm",
+ "custom",
+ "my-group",
+ ]) {
+ expect(providerEnvFallbackKey(id), id).toBeUndefined();
+ }
+ });
+
+ it("sameEndpoint ignores case in the host and trailing slashes, and nothing else", () => {
+ expect(sameEndpoint("https://API.OpenAI.com/v1/", "https://api.openai.com/v1")).toBe(true);
+ expect(sameEndpoint("https://api.openai.com/v1", "https://api.openai.com/v2")).toBe(false);
+ expect(sameEndpoint("https://api.openai.com/v1", "https://api.openai.com")).toBe(false);
+ expect(sameEndpoint("http://host:8000/v1", "http://host:8001/v1")).toBe(false);
+ expect(sameEndpoint("not a url", "not a url")).toBe(false);
+ // The cases that make this a security check — a string-prefix "simplification" would pass
+ // each of them, and each would carry the OpenAI key somewhere else.
+ const openai = "https://api.openai.com/v1";
+ expect(sameEndpoint(openai, "https://api.openai.com.evil.example/v1")).toBe(false);
+ expect(sameEndpoint(openai, "https://[email protected]/v1")).toBe(false);
+ expect(sameEndpoint(openai, "http://api.openai.com/v1")).toBe(false);
+ for (const lookalike of [
+ "https://api.openai.com.evil.example/v1",
+ "https://[email protected]/v1",
+ "http://api.openai.com/v1",
+ ]) {
+ expect(
+ modelEnvFallback({
+ provider: "custom",
+ modelId: "x",
+ clientType: "openai-chat",
+ baseUrl: lookalike,
+ }),
+ lookalike,
+ ).toBeUndefined();
+ }
+ });
+
+ it("refuses a keyless Bedrock row with a message that names the way out, not 'not the vendor's own'", () => {
+ expect(() =>
+ resolveModelCredential(
+ { provider: "anthropic", modelId: "claude-sonnet-5", baseUrl: "bedrock://us-east-1" },
+ { ANTHROPIC_API_KEY: "sk-ant" },
+ ),
+ ).toThrow(/Bedrock endpoint.*ANTHROPIC_BASE_URL=bedrock:\/\/us-east-1/);
+ // Rule 1 keeps Bedrock reachable: no base URL on the row, the region in the environment.
+ expect(
+ resolveModelCredential(
+ { provider: "anthropic", modelId: "claude-sonnet-5" },
+ { ANTHROPIC_BASE_URL: "bedrock://us-east-1" },
+ ),
+ ).toEqual({});
+ });
+
+ it("modelEnvPreviewKey presents a fallback as covering the row only where that is not a misconfiguration", () => {
+ // The eight vLLM presets ship with no base URL: they fall back under the rule, but must not
+ // read as "key configured" — that would run a self-hosted id against api.openai.com.
+ for (const m of MODEL_CATALOG.filter((v) => v.provider === "vllm")) {
+ const shape = { provider: m.provider, modelId: m.modelId, clientType: m.clientType };
+ expect(modelEnvFallback(shape)?.envKey, m.modelId).toBe("OPENAI_API_KEY");
+ expect(modelEnvPreviewKey(shape), m.modelId).toBeUndefined();
+ }
+ // A custom row saved without a base URL: same.
+ expect(
+ modelEnvPreviewKey({ provider: "custom", modelId: "m", clientType: "openai-chat" }),
+ ).toBeUndefined();
+ // A custom row that names the vendor's endpoint itself: previewed.
+ expect(
+ modelEnvPreviewKey({
+ provider: "custom",
+ modelId: "m",
+ clientType: "openai-chat",
+ baseUrl: "https://api.openai.com/v1",
+ }),
+ ).toBe("OPENAI_API_KEY");
+ // Vendor groups and the relay: previewed, as on main.
+ expect(modelEnvPreviewKey({ provider: "anthropic", modelId: "claude-sonnet-4-6" })).toBe(
+ "ANTHROPIC_API_KEY",
+ );
+ expect(modelEnvPreviewKey(shapeOf(catalogEntryFor("deepseek", "deepseek-flash")!))).toBe(
+ "DEEPSEEK_API_KEY",
+ );
+ expect(modelEnvPreviewKey(shapeOf(catalogEntryFor("penguin-go", "gemini-3.8-flash")!))).toBe(
+ "PENGUIN_GO_API_KEY",
+ );
+ // Refused rows are never previewed.
+ expect(modelEnvPreviewKey(shapeOf(catalogEntryFor("tokendance", "glm-5.3")!))).toBeUndefined();
+ expect(
+ modelEnvPreviewKey({
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ baseUrl: "https://proxy.example/anthropic",
+ }),
+ ).toBeUndefined();
+ });
+});
+
+describe("listEndpointModels credential gate (the add-group import)", () => {
+ it("refuses a keyless listing of a gateway or private endpoint before any client exists, whatever the environment holds", async () => {
+ const env = { OPENAI_API_KEY: "sk-openai-env", ANTHROPIC_API_KEY: "sk-anthropic-env" };
+ await expect(
+ listEndpointModels({ clientType: "openai-chat", baseUrl: "https://gw.example.com/v1", env }),
+ ).rejects.toThrow(ModelCredentialError);
+ await expect(
+ listEndpointModels({ clientType: "ant-messages", baseUrl: "http://127.0.0.1:8000", env }),
+ ).rejects.toThrow(/enter the endpoint's API key/);
+ // With the SDK's own variable unset and the endpoint the vendor's own, the refusal is ours
+ // too (no client is constructed to read an unset variable and throw its own error).
+ await expect(
+ listEndpointModels({
+ clientType: "openai-chat",
+ baseUrl: "https://api.openai.com/v1",
+ env: {},
+ }),
+ ).rejects.toThrow(ModelCredentialError);
+ });
+});
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index a289860c..bb462720 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -66,7 +66,7 @@ An unparseable value stops the server at startup instead of falling back silentl
### Provider credential variables
-When 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 inline `base_url`.
+When a model entry has no inline `api_key`, it falls back to the provider's environment variable **only when its requests go to that provider's official endpoint**: the entry has no `base_url`, or its `base_url` is the vendor's own endpoint. A `*_BASE_URL` value is used only when the entry does not inline `base_url`; an entry with its own `base_url` is never covered by the environment, even when `OPENAI_BASE_URL` names the same server. Every other entry — the gateway groups' preset endpoints, custom, vLLM and user-created groups with their own endpoints — needs its own `api_key`, and PenguinHarness refuses to build a client for it otherwise; see [Set API keys](/models#set-api-keys).
| Provider | API key | Base URL |
| --- | --- | --- |
@@ -79,7 +79,7 @@ When a model entry has no inline `api_key`, AgentHub falls back to the provider'
| zhipu | `ZAI_API_KEY` | `ZAI_BASE_URL` |
| moonshot | `MOONSHOT_API_KEY` | `MOONSHOT_BASE_URL` |
-The openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, vllm and custom groups speak an OpenAI-compatible protocol, hence the shared `OPENAI_*` variables. ModelScope also shares `OPENAI_*` because its group credential is an api-inference token, even when a preset row pins a model-specific protocol. The Penguin Go relay keeps a pair of its own, so the app never offers a vendor credential for it. The direct MiniMax M3 Responses client uses `MINIMAX_*`, and the built-in MiniMax preset already pins the official endpoint. For provider groups and the built-in model catalog, see [Models & Providers](/models).
+The openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-token-plan, vllm and custom groups speak an OpenAI-compatible protocol, hence the shared `OPENAI_*` variables — which, by the rule above, their rows do not fall back to: the variable holds your OpenAI key, and a gateway is not OpenAI. ModelScope also shares `OPENAI_*` because its group credential is an api-inference token, even when a preset row pins a model-specific protocol; its rows do not fall back to it either. The Penguin Go relay keeps a pair of its own, so the app never offers a vendor credential for it. The direct MiniMax M3 Responses client uses `MINIMAX_*`, and the built-in MiniMax preset already pins the official endpoint. For provider groups and the built-in model catalog, see [Models & Providers](/models).
## Project config
@@ -108,7 +108,7 @@ The openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-tok
| `max_tokens` | number | The agent's `model.max_tokens` | Per-model max output Tokens; overrides the agent's `model.max_tokens` when set |
| `fast_mode` | boolean | Off | Per-model fast mode (the provider's premium faster serving tier) |
| `pricing` | table | — | Three price buckets, `cache_read` / `cache_write` / `output`, in USD per million Tokens (`unit = "usd_per_mtok"`). Always the list price |
-| `api_key` | string | The provider's environment variable | Inline credential |
+| `api_key` | string | The provider's environment variable, for the vendor's own endpoint only | Inline credential |
| `base_url` | string | Preset for some catalog entries | Custom base URL |
| `created_at` | string | — | When `api_key` was written (ISO 8601); a display field maintained by the interface layer |
@@ -118,7 +118,7 @@ Field notes:
- `fast_mode`: only `true` is persisted. It is offered only for models whose AgentHub client can serve it, and the others reject requests that carry it. See [Models](/models#fast-mode).
- `pricing`: the figure here is the list price. A running promotion is not written to this file: the server keeps it in `web.db` and takes it off when it computes cost. See [Prices and promotions](/models#prices-and-promotions).
- `base_url`: the built-in catalog presets it for gateways and for the direct rows that pin a client, MiniMax M3 and DeepSeek `deepseek-flash`.
-- `api_key`: when empty, AgentHub falls back to the provider's environment variable.
+- `api_key`: when empty, the entry falls back to the provider's environment variable only when its endpoint is the vendor's own (see [Provider credential variables](#provider-credential-variables)); a gateway, custom or vLLM entry needs its own key.
```toml
default_model = { provider = "deepseek", model_id = "deepseek-flash" }
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index 830e8e4d..3ae110fd 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -66,7 +66,7 @@ Agent 运行的每条命令,PATH 的第一位都是本安装自带的 `penguin
### 供应商凭证变量
-模型条目没有内联 `api_key` 时,AgentHub 会回退到供应商的环境变量。`*_BASE_URL` 的值只在条目没有内联 `base_url` 时才会使用。
+模型条目没有内联 `api_key` 时,**只在请求确实发往该供应商的官方端点时**回退到供应商的环境变量:条目没有 `base_url`,或 `base_url` 是厂商自己的端点。`*_BASE_URL` 的值只在条目没有内联 `base_url` 时才会使用;自带 `base_url` 的条目一律不由环境变量覆盖,即使 `OPENAI_BASE_URL` 指向同一台服务器也不例外。其余条目——网关分组预置的端点、带自己端点的 custom、vLLM 与自建分组——必须有自己的 `api_key`,否则 PenguinHarness 拒绝为它构建客户端;见[设置 API key](/models#设置-api-key)。
| 供应商 | API key | Base URL |
| --- | --- | --- |
@@ -79,7 +79,7 @@ Agent 运行的每条命令,PATH 的第一位都是本安装自带的 `penguin
| zhipu | `ZAI_API_KEY` | `ZAI_BASE_URL` |
| moonshot | `MOONSHOT_API_KEY` | `MOONSHOT_BASE_URL` |
-openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、vllm 和 custom 这几组供应商使用 OpenAI 兼容协议,因此共用 `OPENAI_*` 变量。ModelScope 也共用 `OPENAI_*`,因为它的分组凭据是 api-inference token,即使某条预置固定了模型专属协议也是如此。Penguin Go 中转分组单独使用一对自己的变量,应用因此不会为它推荐任何厂商凭证。MiniMax M3 的直连 Responses 客户端使用 `MINIMAX_*`,内置的 MiniMax 预设也已经固定为官方端点。供应商分组和内置模型目录见[模型与供应商](/models)。
+openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-token-plan、vllm 和 custom 这几组供应商使用 OpenAI 兼容协议,因此共用 `OPENAI_*` 变量——按上面的规则,它们的条目并不会回退到这对变量:变量里存的是你的 OpenAI key,而网关不是 OpenAI。ModelScope 也共用 `OPENAI_*`,因为它的分组凭据是 api-inference token,即使某条预置固定了模型专属协议也是如此;它的条目同样不会回退到这对变量。Penguin Go 中转分组单独使用一对自己的变量,应用因此不会为它推荐任何厂商凭证。MiniMax M3 的直连 Responses 客户端使用 `MINIMAX_*`,内置的 MiniMax 预设也已经固定为官方端点。供应商分组和内置模型目录见[模型与供应商](/models)。
## Project 配置
@@ -108,7 +108,7 @@ openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-to
| `max_tokens` | 数字 | Agent 的 `model.max_tokens` | 单个模型的最大输出 Token;设置后覆盖 Agent 的 `model.max_tokens` |
| `fast_mode` | 布尔 | 关闭 | 单个模型的快速模式(供应商收取溢价的快速服务档位) |
| `pricing` | 表 | — | 三档价格 `cache_read` / `cache_write` / `output`,以美元每百万 Token 计价(`unit = "usd_per_mtok"`)。这里记的始终是牌价 |
-| `api_key` | 字符串 | 供应商的环境变量 | 内联凭证 |
+| `api_key` | 字符串 | 供应商的环境变量,仅限厂商自己的端点 | 内联凭证 |
| `base_url` | 字符串 | 部分模型目录条目有预设 | 自定义 base URL |
| `created_at` | 字符串 | — | `api_key` 的写入时间(ISO 8601);由界面层维护的展示字段 |
@@ -118,7 +118,7 @@ openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-to
- `fast_mode`:只持久化 `true`。只有 AgentHub 客户端能支持快速模式的模型才会提供这个选项,其他模型会拒绝携带它的请求。见[模型](/models#快速模式)。
- `pricing`:这里记的是牌价。正在进行的促销不写入这个文件:服务端把它保存在 `web.db` 里,计算成本时再从牌价中扣除。见[价格与促销](/models#价格与促销)。
- `base_url`:内置模型目录为网关以及固定客户端的直连条目预设了这个字段,即 MiniMax M3 和 DeepSeek 的 `deepseek-flash`。
-- `api_key`:为空时,AgentHub 回退到供应商的环境变量。
+- `api_key`:为空时,只在条目的端点是厂商自己的地址时回退到供应商的环境变量(见[供应商凭证变量](#供应商凭证变量));网关、custom 与 vLLM 条目需要自己的 key。
```toml
default_model = { provider = "deepseek", model_id = "deepseek-flash" }
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index b6716dc8..75386c54 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -62,7 +62,7 @@ The group appears in the list once its first model is saved.
**Import models** fills a new group with every model an OpenAI-compatible or Anthropic-compatible endpoint lists.
1. Select **Import models**.
-2. In **API key**, enter the key. Leave it empty to use the protocol's `OPENAI_*` or `ANTHROPIC_*` environment variables.
+2. In **API key**, enter the endpoint's key. The server's `OPENAI_*` / `ANTHROPIC_*` variables are not used for an endpoint that is not the vendor's own (see [Set API keys](#set-api-keys)), so a listing without a key is refused.
3. In **Custom base URL**, enter the endpoint's base URL.
4. Select **Detect** at the top-right of the field, or pick the protocol from the menu at the right edge of the field. See [Detect a custom model's protocol](#detect-a-custom-models-protocol).
5. Select **Import all models**. PenguinHarness asks the endpoint for its model list and saves every model into the new group, in the endpoint's order.
@@ -88,7 +88,7 @@ All of the group's models and their API keys are removed. Built-in groups cannot
2. In **Model ID**, enter the model id exactly as the provider's API expects it, for example `gpt-5.5`. **Get model IDs** opens the provider's model list.
3. Optional: in **Display name**, enter a display name. An empty display name shows the model id.
4. Fill in the credentials and endpoint:
- - **API key**: leave it empty to use the provider's environment variable. The field names the variable when it is set on the server.
+ - **API key**: in a vendor group, leave it empty to use the provider's environment variable; the field names the variable when it is set on the server. In a gateway group, in **Custom** and in groups you created, the key is required — no environment variable is used for an endpoint that is not the vendor's own.
- **Custom base URL**: required in **Custom** and in groups you created. In gateway groups it is filled in for you.
5. Optional: fill in the limits and prices:
- **Context window**: the model's context window in Tokens. For a model that is not in the built-in catalog, an empty field saves as 1000000.
@@ -163,8 +163,8 @@ Detection never blocks a save. If you select **Confirm** while the protocol is s
- Probes are minimal invalid requests with `{}` bodies. They cost no Tokens and need no valid model id: an error in the protocol's own shape proves the route exists, a `404` or `405` means the path is not served, and HTML or gateway noise counts for nothing.
- The probed URLs and auth headers are exactly what the AgentHub client uses after saving: `Authorization: Bearer` for the OpenAI protocols, and `x-api-key` plus `Authorization: Bearer` and `anthropic-version` for `ant-messages`. A detected protocol is one that will really work.
-- The server picks the probe credential in three steps: the API key typed in the dialog, else the key already stored for the entry, else the environment variable of the protocol that probe speaks (`ANTHROPIC_API_KEY` for `ant-messages`, `OPENAI_API_KEY` for the two OpenAI protocols). The choice is made per probe, because the protocol is what is being determined. None of these values reach the browser or the response.
-- Detection works with no credential at all, since a protocol-shaped `401` identifies the route. An authenticated probe is still far more likely to get that answer than the generic `401` or gateway HTML an anonymous request often gets.
+- The server picks the probe credential in three steps: the API key typed in the dialog, else the key already stored for the entry, else the environment variable of the protocol that probe speaks (`ANTHROPIC_API_KEY` for `ant-messages`, `OPENAI_API_KEY` for the two OpenAI protocols) — but only when the probed URL is that vendor's own endpoint. The choice is made per probe, because the protocol is what is being determined. None of these values reach the browser or the response.
+- Detection works with no credential at all, since a protocol-shaped `401` identifies the route. A gateway or a private server is therefore probed anonymously: your vendor key is never sent to a URL you typed.
- Nothing is inferred from the model id in these groups. Typing `claude-sonnet-5` into a custom group does not select the Anthropic client or its `ANTHROPIC_*` key: custom groups fall back to `openai-chat`, and the API key hint follows that. Vendor and gateway groups are not affected; their ids are known to the catalog, so they route by id or by the group's preset.
- Entries created before detection existed keep `client_type = "openai"`, which is still an alias of `openai-chat`. They are rewritten only when you pick a protocol or a detection applies. An older, non-standard protocol value is shown read-only: "Protocol: {t} (kept as configured; not editable)".
- Detection is available as `POST /api/projects/:id/models/detect` (owner only); see [Server API](/server-api).
@@ -180,7 +180,7 @@ Detection never blocks a save. If you select **Confirm** while the protocol is s
> [!NOTE]
> Unlike protocol detection, this probe is a real, billed request: an image request cannot be made free the way the protocol probes are. It runs only when you select **Detect**, never on its own and never on save.
-The credential comes from the same chain as the connection test: the key typed in the dialog, else the stored key, else the protocol's environment variable, all resolved on the server. **Vision support** appears only for models that are not in the built-in catalog; catalog models already declare whether they accept images.
+The credential comes from the same chain as the connection test: the key typed in the dialog, else the stored key, else the environment variable where the endpoint is allowed one (see [Set API keys](#set-api-keys)), all resolved on the server. **Vision support** appears only for models that are not in the built-in catalog; catalog models already declare whether they accept images.
## Set API keys
@@ -188,7 +188,7 @@ Each model carries its own API key, or none.
- **One model.** In **Model settings**, enter the key in **API key**. Once saved, the key is shown masked; leave the field empty to keep it, or select **Clear stored API key** to remove it.
- **A whole group.** On a group's header, select **Set key** and enter the key. It applies to every model in the group.
-- **No key.** A model without a key uses the provider's environment variable on the server; see [Built-in provider groups](#built-in-provider-groups). The card and the dialog show when a key is read from an environment variable.
+- **No key.** A model without a key uses the provider's environment variable on the server **only when its requests go to that provider's official endpoint**: the entry has no base URL (AgentHub's own `*_API_KEY` / `*_BASE_URL` pairing then applies), or its base URL is the vendor's own endpoint. A row with its own base URL is never covered by the environment, not even when `OPENAI_BASE_URL` names the same server. Gateway groups (TokenDance, OpenRouter, Fireworks AI, SiliconFlow, the Qwen gateways, ModelScope), **Custom**, **vLLM** and groups you created point at other endpoints, so their models need their own key: a Session, a connection test or a group speed test on a keyless row there fails with "has no API key" instead of borrowing `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`. The Penguin Go group is the exception that proves the rule — its rows fall back to its own `PENGUIN_GO_API_KEY`, never to a vendor's variable. The card and the dialog show when a key is read from an environment variable; see [Built-in provider groups](#built-in-provider-groups).
A key you type is stored in the hidden Project config file, which has mode 0600. The Web App always masks it.
@@ -359,7 +359,7 @@ A local inference server can join a Project in two ways.
### Add the model to the vLLM group
-Add the model to the **vLLM** group. The protocol is fixed to `openai-chat-vllm-adapter`, and the group has no preset base URL, so set **Custom base URL** to your server.
+Add the model to the **vLLM** group. The protocol is fixed to `openai-chat-vllm-adapter`, and the group has no preset base URL, so set **Custom base URL** to your server. Set **API key** too: the server's key, or any placeholder if it checks none. A row with its own base URL is never covered by the server's `OPENAI_API_KEY`, so a keyless row is refused.
The group ships eight preset models at a price of 0:
@@ -381,6 +381,7 @@ Add a `custom` model with:
- `client_type = "openai-chat"`
- `base_url` pointing at the server, for example `http://127.0.0.1:8000/v1`
- the served model name as `model_id`
+- `api_key`: the server's key, or any placeholder if it checks none — the environment's `OPENAI_API_KEY` does not cover a server of your own
Protocol detection settles on `openai-chat` for such servers, and the base URL field's suffix menu selects it by hand.
@@ -398,7 +399,7 @@ The per-request output limit and the compaction threshold both follow this windo
## Built-in provider groups
-The table below lists the built-in groups and the environment variables their models fall back to when an entry has no key. The catalog source is `packages/core/src/state/model-catalog.ts`. Each group also has a `_BASE_URL` variant, for example `ANTHROPIC_BASE_URL`. The **Models** page lists the groups in this order, followed by the groups you create.
+The table below lists the built-in groups and the environment variables their models fall back to when an entry has no key. The catalog source is `packages/core/src/state/model-catalog.ts`. Each group also has a `_BASE_URL` variant, for example `ANTHROPIC_BASE_URL`. The **Models** page lists the groups in this order, followed by the groups you create. A gateway group's rows carry the gateway's endpoint, so **they never fall back**: the variable in their row is the one their protocol client reads, and exactly because it holds your vendor key it is not sent to the gateway (see [Set API keys](#set-api-keys)).
| Provider | API key env var | Notes |
| --- | --- | --- |
@@ -418,9 +419,9 @@ The table below lists the built-in groups and the environment variables their mo
| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan subscription gateway, preset base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`; pricing from each model page's official list price (the preview model has only a quota-multiplier promo, no list price) |
| modelscope | `OPENAI_API_KEY` | ModelScope's OpenAI-compatible api-inference gateway, preset base URL `https://api-inference.modelscope.cn/v1`; ids are the upstream repo names (`deepseek-ai/DeepSeek-V4.1-Flash`, `Qwen/Qwen3.8-27B`); the group's header authorizes a token for you through an authorization bridge, or takes one you set by hand. See [The ModelScope group](#the-modelscope-group) |
| vllm | `OPENAI_API_KEY` | Self-hosted vLLM servers: protocol fixed to `openai-chat-vllm-adapter`, no preset base URL, eight preset models priced at 0 (see [Connect a local or self-hosted endpoint](#connect-a-local-or-self-hosted-endpoint)) |
-| custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint; ships one preset, Atria Dawn Preview (Anthropic Messages API at `api.atria-asi.ai`, credential from `ANTHROPIC_API_KEY` when the entry has none, 256K window, priced at $0 until the vendor publishes prices) |
+| custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint; ships one preset, Atria Dawn Preview (Anthropic Messages API at `api.atria-asi.ai`, needs its own key, 256K window, priced at $0 until the vendor publishes prices) |
-The OpenAI-compatible gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan) go through AgentHub's generic OpenAI-protocol clients, so with blank credentials they read `OPENAI_API_KEY`, not a gateway-specific variable. ModelScope also uses the `OPENAI_*` credential variables because its credential is an api-inference token, but its preset rows can pin a model-specific protocol.
+The OpenAI-compatible gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan) go through AgentHub's generic OpenAI-protocol clients, whose variable is `OPENAI_API_KEY`; a keyless row there is refused rather than sent your OpenAI key. The same holds for custom, vLLM and user-created groups unless the row's base URL is the vendor's own endpoint. ModelScope also uses the `OPENAI_*` credential variables because its credential is an api-inference token, but its preset rows can pin a model-specific protocol; a keyless ModelScope row is refused the same way.
- The OpenRouter group uses the Responses client (`client_type = "openai-responses"`) for its presets and for any model you add to it, because OpenRouter serves the Responses API at that same base URL for every model it resells.
- The other gateway presets use the Chat Completions client (`client_type = "openai-chat"`).
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index 1ba78448..a6999bc4 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -62,7 +62,7 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择
**导入模型**会把一个 OpenAI 兼容或 Anthropic 兼容端点列出的所有模型填进新分组。
1. 点击**导入模型**。
-2. 在 **API key** 里输入密钥。留空则使用协议的 `OPENAI_*` 或 `ANTHROPIC_*` 环境变量。
+2. 在 **API key** 里输入该端点的密钥。端点不是厂商自己的地址时,服务端的 `OPENAI_*` / `ANTHROPIC_*` 变量不会被使用(见[设置 API key](#设置-api-key)),不填 key 的导入会被拒绝。
3. 在**自定义 base URL** 里输入端点的 base URL。
4. 点击字段右上角的**检测协议**,或者在字段最右侧的菜单里选择协议。见[检测自定义模型的协议](#检测自定义模型的协议)。
5. 点击**批量导入模型**。PenguinHarness 会向端点请求模型列表,然后按端点返回的顺序把所有模型保存到新分组。
@@ -88,7 +88,7 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择
2. 在**模型 ID** 里输入模型 id,必须与供应商 API 要求的完全一致,例如 `gpt-5.5`。**获取模型 id** 会打开供应商的模型列表。
3. 可选:在**模型名称**里输入显示名。显示名为空时直接显示模型 id。
4. 填写凭证和端点:
- - **API key**:留空则使用供应商的环境变量。如果服务端设置了这个变量,输入框会显示变量名。
+ - **API key**:在厂商分组里留空则使用供应商的环境变量,服务端设置了这个变量时输入框会显示变量名。在网关分组、**Custom** 分组和你创建的分组里 key 必填——端点不是厂商自己的地址时,不会使用任何环境变量。
- **自定义 base URL**:在 **Custom** 分组和你创建的分组里必填。网关分组会自动填好。
5. 可选:填写限制和价格:
- **上下文窗口**:模型的上下文窗口大小,单位是 Token。模型不在内置模型目录里时,留空会保存为 1000000。
@@ -163,8 +163,8 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择
- 探测请求是请求体为 `{}` 的最小无效请求,不消耗 Token,也不需要有效的模型 id:返回的错误若符合协议自身的格式,就证明路由存在;返回 `404` 或 `405`,说明路径没有提供服务;HTML 或网关杂讯一律不算数。
- 探测用的 URL 和认证头,与保存后 AgentHub 客户端实际使用的完全一致:OpenAI 系协议用 `Authorization: Bearer`,`ant-messages` 用 `x-api-key` 加 `Authorization: Bearer` 和 `anthropic-version`。所以检测出的协议一定真实可用。
-- 服务端按三步选取探测凭据:优先用弹窗里填写的 API key,其次用这个条目已保存的 key,最后用探测目标协议对应的环境变量(`ant-messages` 用 `ANTHROPIC_API_KEY`,两个 OpenAI 协议用 `OPENAI_API_KEY`)。每发一次探测都会重新选择,因为此刻要确定的就是协议。这些值不会传到浏览器,也不会出现在响应里。
-- 完全没有凭据也能检测,因为协议格式的 `401` 同样能识别路由。不过相比匿名请求经常得到的笼统 `401` 或网关 HTML,带凭据的探测得到这个明确答案的可能性大得多。
+- 服务端按三步选取探测凭据:优先用弹窗里填写的 API key,其次用这个条目已保存的 key,最后用探测目标协议对应的环境变量(`ant-messages` 用 `ANTHROPIC_API_KEY`,两个 OpenAI 协议用 `OPENAI_API_KEY`)——但只在被探测的 URL 是该厂商自己的端点时才会使用。每发一次探测都会重新选择,因为此刻要确定的就是协议。这些值不会传到浏览器,也不会出现在响应里。
+- 完全没有凭据也能检测,因为协议格式的 `401` 同样能识别路由。因此网关或私有服务器一律匿名探测:你的厂商 key 不会发往你输入的 URL。
- 在这些分组里,不会从模型 id 推断任何东西。在自定义分组里输入 `claude-sonnet-5`,不会因此选用 Anthropic 客户端或它的 `ANTHROPIC_*` key:自定义分组一律回退到 `openai-chat`,API key 提示也照此显示。供应商分组和网关分组不受影响;模型目录认识它们的 id,所以按 id 或按分组的预置来路由。
- 在检测功能出现之前创建的条目,保留 `client_type = "openai"`,它至今仍是 `openai-chat` 的别名。只有手动选择协议、或某次检测生效时,才会改写这个值。旧的非标准协议值以只读方式显示:「协议:{t}(沿用原配置,不可修改)」。
- 检测也可以通过 `POST /api/projects/:id/models/detect` 调用(仅 owner 可用),参见 [Server API](/server-api)。
@@ -180,7 +180,7 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择
> [!NOTE]
> 和协议检测不同,这一探测是真实、计费的请求:图片请求无法像协议探测那样做到免费。它只在你点击**检测**时执行,绝不会自动运行,也不会在保存时运行。
-凭据来源和连通性测试是同一条链路:先用弹窗里填写的 key,其次用已保存的 key,最后用协议对应的环境变量,全部在服务端解析。**支持视觉**只对不在内置模型目录里的模型显示;目录里的模型本身就声明了是否接受图片。
+凭据来源和连通性测试是同一条链路:先用弹窗里填写的 key,其次用已保存的 key,最后在端点允许的范围内用环境变量(见[设置 API key](#设置-api-key)),全部在服务端解析。**支持视觉**只对不在内置模型目录里的模型显示;目录里的模型本身就声明了是否接受图片。
## 设置 API key
@@ -188,7 +188,7 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择
- **单个模型。** 在**模型配置**里,把 key 填入 **API key**。保存后 key 会打码显示;输入框留空即保留原 key,点击**清除已存 API key** 可删除它。
- **整个分组。** 在分组标题栏上点击**手动设置密钥**并输入 key,组内所有模型都会使用它。
-- **不配 key。** 没配 key 的模型使用服务端上供应商的环境变量;参见[内置供应商分组](#内置供应商分组)。key 来自环境变量时,卡片和弹窗都会显示这一点。
+- **不配 key。** 没配 key 的模型**只在请求确实发往该供应商的官方端点时**使用服务端上供应商的环境变量:条目没有 base URL(此时按 AgentHub 自己的 `*_API_KEY` / `*_BASE_URL` 配对),或 base URL 是厂商自己的端点。自带 base URL 的条目一律不由环境变量覆盖,即使 `OPENAI_BASE_URL` 指向同一台服务器也不例外。网关分组(TokenDance、OpenRouter、Fireworks AI、SiliconFlow、两个 Qwen 网关、ModelScope)、**Custom**、**vLLM** 和你创建的分组指向别的端点,其中的模型必须配自己的 key:在这些分组里对没有 key 的模型发起会话、连通性测试或分组测速,会以「has no API key」失败,而不是借用 `OPENAI_API_KEY` 或 `ANTHROPIC_API_KEY`。Penguin Go 分组是唯一的例外,它回退到自己的 `PENGUIN_GO_API_KEY`,从不使用厂商变量。key 来自环境变量时,卡片和弹窗都会显示这一点;参见[内置供应商分组](#内置供应商分组)。
你填写的 key 存在 Project 的隐藏配置文件里,文件权限为 0600。Web App 里它始终打码显示。
@@ -358,7 +358,7 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr
### 把模型添加到 vLLM 分组
-把模型添加到 **vLLM** 分组。协议固定为 `openai-chat-vllm-adapter`,分组没有预置 base URL,所以要把**自定义 base URL** 设置为你的服务器地址。
+把模型添加到 **vLLM** 分组。协议固定为 `openai-chat-vllm-adapter`,分组没有预置 base URL,所以要把**自定义 base URL** 设置为你的服务器地址。同时填上 **API key**:服务器的 key,服务器不校验 key 时随便填一个占位值也行。自带 base URL 的条目不会由服务端的 `OPENAI_API_KEY` 覆盖,没有 key 的条目会被拒绝。
分组自带八个预置模型,价格均为 0:
@@ -380,6 +380,7 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr
- `client_type = "openai-chat"`
- `base_url` 指向服务器,例如 `http://127.0.0.1:8000/v1`
- `model_id` 填服务器实际提供的模型名称
+- `api_key`:服务器的 key,服务器不校验 key 时填任意占位值——环境里的 `OPENAI_API_KEY` 不覆盖你自己的服务器
对这类服务器,协议检测会判定为 `openai-chat`;也可以通过 base URL 字段的后缀菜单手动选定。
@@ -397,7 +398,7 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr
## 内置供应商分组
-下表列出了各个内置分组,以及条目没有 key 时模型回退使用的环境变量。模型目录的源码位于 `packages/core/src/state/model-catalog.ts`。每个分组还有一个 `_BASE_URL` 变体,例如 `ANTHROPIC_BASE_URL`。**模型库**页面按这个顺序列出分组,你创建的分组排在后面。
+下表列出了各个内置分组,以及条目没有 key 时模型回退使用的环境变量。模型目录的源码位于 `packages/core/src/state/model-catalog.ts`。每个分组还有一个 `_BASE_URL` 变体,例如 `ANTHROPIC_BASE_URL`。**模型库**页面按这个顺序列出分组,你创建的分组排在后面。网关分组的条目带着网关自己的端点,因此**从不回退**:表里的变量是它们的协议客户端读取的那一个,而正因为它存的是你的厂商 key,它不会被发往网关(见[设置 API key](#设置-api-key))。
| 供应商 | API key 环境变量 | 说明 |
| --- | --- | --- |
@@ -417,9 +418,9 @@ PenguinHarness 升级可能改变内置的预置模型目录。一旦发生,Pr
| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan 订阅网关,预置 base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`;价格取自各模型页面的官方牌价(预览模型只有配额倍率优惠,没有牌价) |
| modelscope | `OPENAI_API_KEY` | 魔搭的 OpenAI 兼容 api-inference 网关,预置 base URL `https://api-inference.modelscope.cn/v1`;id 就是上游仓库名(如 `deepseek-ai/DeepSeek-V4.1-Flash`、`Qwen/Qwen3.8-27B`);分组标题栏可以经授权中转层为你自动授权一把 token,也可以手动设置。见 [ModelScope 分组](#modelscope-分组) |
| vllm | `OPENAI_API_KEY` | 自托管 vLLM 服务器:协议固定为 `openai-chat-vllm-adapter`,无预置 base URL,八个预置模型价格均为 0(见[连接本地或自托管端点](#连接本地或自托管端点)) |
-| custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点;自带一个预置模型 Atria Dawn Preview(Anthropic Messages API,地址 `api.atria-asi.ai`,条目没有凭据时使用 `ANTHROPIC_API_KEY`,上下文窗口 256K,供应商公布价格之前定价 $0) |
+| custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点;自带一个预置模型 Atria Dawn Preview(Anthropic Messages API,地址 `api.atria-asi.ai`,需要自己的 key,上下文窗口 256K,供应商公布价格之前定价 $0) |
-OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan)走的是 AgentHub 通用的 OpenAI 协议客户端,凭据留空时读取 `OPENAI_API_KEY`,而不是某个网关专属的变量。ModelScope 也使用 `OPENAI_*` 凭据变量,因为它的凭据是 api-inference token,但它的预置条目可以逐条固定模型专属协议。
+OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan)走的是 AgentHub 通用的 OpenAI 协议客户端,对应变量是 `OPENAI_API_KEY`;其中没有 key 的条目会被拒绝,而不是把你的 OpenAI key 发过去。custom、vLLM 和自建分组同样如此,除非条目的 base URL 就是厂商自己的端点。ModelScope 也使用 `OPENAI_*` 凭据变量,因为它的凭据是 api-inference token,但它的预置条目可以逐条固定模型专属协议;没有 key 的 ModelScope 条目同样会被拒绝。
- OpenRouter 分组的预置模型,以及你添加到该分组的任何模型,都使用 Responses 客户端(`client_type = "openai-responses"`),因为 OpenRouter 在同一个 base URL 上为它转售的每一个模型提供 Responses API。
- 其他网关的预置模型使用 Chat Completions 客户端(`client_type = "openai-chat"`)。
diff --git a/packages/docs/content/quickstart-cli.en.md b/packages/docs/content/quickstart-cli.en.md
index 2be82692..d94f24c7 100644
--- a/packages/docs/content/quickstart-cli.en.md
+++ b/packages/docs/content/quickstart-cli.en.md
@@ -48,7 +48,7 @@ penguin config model add --provider deepseek --model-id deepseek-flash --api-key
You can also add models later on the **Models** page of the Web App.
- A model is always named by a `(provider, model_id)` pair, so `--provider` and `--model-id` are both required. PenguinHarness never infers the provider from the model id. See [Models & Providers](/models) for the built-in groups.
-- The API key can also come from an environment variable. When a model entry has no inline `api_key`, AgentHub (the LLM gateway library) reads variables such as `DEEPSEEK_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and `GEMINI_API_KEY`. A `.env` file in the working directory is loaded automatically.
+- The API key can also come from an environment variable, for the vendor's own endpoint. When a model entry has no inline `api_key` and no `base_url` of its own (or one that is the vendor's official endpoint), AgentHub (the LLM gateway library) reads variables such as `DEEPSEEK_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and `GEMINI_API_KEY`. An entry pointed at a gateway or a server of your own needs `--api-key`. A `.env` file in the working directory is loaded automatically.
## Start the Web App
diff --git a/packages/docs/content/quickstart-cli.zh.md b/packages/docs/content/quickstart-cli.zh.md
index 3350affa..0a960ae3 100644
--- a/packages/docs/content/quickstart-cli.zh.md
+++ b/packages/docs/content/quickstart-cli.zh.md
@@ -48,7 +48,7 @@ penguin config model add --provider deepseek --model-id deepseek-flash --api-key
之后也可以在 Web App 的**模型库**页面添加模型。
- 模型始终以 `(provider, model_id)` 二元组引用,因此 `--provider` 与 `--model-id` 都必填。PenguinHarness 不会根据模型 id 推断供应商。内置分组见[模型与 Provider](/models)。
-- API Key 也可以来自环境变量。模型条目没有内联 `api_key` 时,LLM 网关库 AgentHub 会读取 `DEEPSEEK_API_KEY`、`ANTHROPIC_API_KEY`、`OPENAI_API_KEY`、`GEMINI_API_KEY` 等变量。工作目录下的 `.env` 文件会自动加载。
+- API Key 也可以来自环境变量,但仅限厂商自己的端点。模型条目没有内联 `api_key`、且没有自己的 `base_url`(或 `base_url` 就是厂商官方端点)时,LLM 网关库 AgentHub 会读取 `DEEPSEEK_API_KEY`、`ANTHROPIC_API_KEY`、`OPENAI_API_KEY`、`GEMINI_API_KEY` 等变量。指向网关或自己服务器的条目需要 `--api-key`。工作目录下的 `.env` 文件会自动加载。
## 启动 Web App
diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.md
index 565e6c03..bd5222ea 100644
--- a/packages/docs/content/quickstart-desktop.en.md
+++ b/packages/docs/content/quickstart-desktop.en.md
@@ -50,7 +50,7 @@ A model is always referenced as a `(provider, model_id)` pair: the provider is n
API keys already exported in your shell profile (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, …) work without entering them again. On macOS and Linux, when you launch the app from the Dock or the desktop, it imports the login shell's environment, filling in only the variables the launch itself did not set. The agent shell's `PATH` benefits the same way. Set `PENGUIN_NO_LOGIN_SHELL_ENV` to turn this off.
-For an official provider's model with no stored key, the **Models** page shows the detected variable's value masked, just as it shows a stored key: on the model's card, and in the model's dialog, which marks the key as **Read from environment variable**. Gateway and custom groups are not matched against these variables.
+For an official provider's model with no stored key, the **Models** page shows the detected variable's value masked, just as it shows a stored key: on the model's card, and in the model's dialog, which marks the key as **Read from environment variable**. Gateway groups, and custom or vLLM rows with a base URL of their own, are not matched against these variables — a model there needs its own key.
## Run your first Task
diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.md
index fbee51ea..b6a44d48 100644
--- a/packages/docs/content/quickstart-desktop.zh.md
+++ b/packages/docs/content/quickstart-desktop.zh.md
@@ -50,7 +50,7 @@ PenguinHarness 不内置任何模型凭据。为要使用的模型配置 API Key
已经在 shell 配置文件里 export 的 API Key(`ANTHROPIC_API_KEY`、`OPENAI_API_KEY` 等)不用再填一遍。在 macOS 和 Linux 上从 Dock 或桌面启动应用时,应用会导入登录 shell 的环境变量,只补上启动时没有设置的变量。Agent shell 的 `PATH` 也因此受益。设置 `PENGUIN_NO_LOGIN_SHELL_ENV` 可以关闭这项导入。
-官方供应商的模型没有保存 Key 时,**模型库**页面会以掩码显示检测到的环境变量值,和显示已保存的 Key 一样:模型卡片上显示,模型详情弹窗里也显示,并标注为**读取自环境变量**。网关分组和自定义分组不会匹配这些变量。
+官方供应商的模型没有保存 Key 时,**模型库**页面会以掩码显示检测到的环境变量值,和显示已保存的 Key 一样:模型卡片上显示,模型详情弹窗里也显示,并标注为**读取自环境变量**。网关分组,以及自带 base URL 的 custom / vLLM 条目,不会匹配这些变量——那里的模型需要自己的 key。
## 跑通第一个 Task
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index b29058be..d5c30e52 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -523,14 +523,21 @@ export interface ModelInfo {
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. */
+ /**
+ * Environment variable name the entry falls back to when api_key is empty (e.g.
+ * ANTHROPIC_API_KEY); unset when it gets no fallback — an id nothing routes, or an entry
+ * whose base URL is not the vendor's own official endpoint (a gateway preset, a custom /
+ * vLLM / user-created row with its own endpoint, a vendor row re-pointed at a proxy).
+ */
envKey?: string;
/**
* Masked preview (same rule as `credential.apiKeyMasked`) of the value the server process
- * currently holds for `envKey` — the plaintext is never serialized. Reported only for
- * first-party official entries (vendor group, catalog shape unmodified); gateway, custom
- * and user-defined groups never carry it. Absent = the variable is unset or empty, or the
- * entry is not first-party.
+ * currently holds for `envKey` — the plaintext is never serialized. Reported only where the
+ * fallback may be presented as covering the entry (core's modelEnvPreviewKey): a row whose
+ * own base URL is a vendor endpoint, or a keyless row in a vendor group or Penguin Go. Gateway
+ * rows never carry it, and neither do custom / vLLM / user-defined rows with no base URL,
+ * although those do fall back. Absent = the variable is unset or empty, or the entry is not
+ * previewable.
*/
envKeyMasked?: string;
credential?: CredentialInfo;
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index a7639f23..b13cf117 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -39,7 +39,6 @@ import {
canonicalClientType,
listEndpointModels as coreListEndpointModels,
MODELSCOPE_PROVIDER_ID,
- PENGUIN_GO_PROVIDER_ID,
catalogEntryFor,
defaultProjectConfig,
imageUrlMessage,
@@ -48,10 +47,12 @@ import {
projectConfigFromTable,
projectConfigPath,
renderProjectConfigToml,
- resolveProviderModelEnv,
+ modelEnvFallback,
+ modelEnvPreviewKey,
+ resolveModelCredential,
userText,
} from "@prismshadow/penguin-core";
-import { providerInfo, unroutableVendorModel } from "@prismshadow/penguin-core/model-catalog";
+import { unroutableVendorModel } from "@prismshadow/penguin-core/model-catalog";
import type {
PluginTables,
CommandPolicyRule,
@@ -121,48 +122,6 @@ export function maskApiKey(key: string): string {
return `${key.slice(0, 4)}…${key.slice(-4)}`;
}
-/**
- * Whether a model's env fallback is *first-party*: the entry points at the provider's own
- * official endpoint, so consulting the vendor variable (ANTHROPIC_API_KEY, …) is the intended
- * configuration and its value may be previewed masked. Excluded — no detection, no preview:
- *
- * - gateway groups and any group pinning a protocol, e.g. OpenRouter or vLLM (both reach a
- * generic OpenAI-protocol client whose fallback is OPENAI_API_KEY, the *official OpenAI*
- * variable; steering it to a reseller or to the user's own server is exactly the
- * misconfiguration the preview must not encourage), and the custom group;
- * - user-defined groups (not in MODEL_PROVIDERS at all);
- * - any entry re-pointed away from the official shape: a catalog preset whose client_type or
- * base_url differs from the catalog's own values, or an off-catalog vendor-group entry that
- * pins either (a bare auto-routed id targets the vendor's first-party client and stays in).
- *
- * `envKey` itself is still reported for every routable entry — this gate governs only the
- * presence preview.
- */
-export function envFallbackFirstParty(entry: {
- provider: string;
- modelId: string;
- clientType: string | undefined;
- baseUrl: string | undefined;
-}): boolean {
- const group = providerInfo(entry.provider);
- if (
- group === undefined ||
- group.id === "custom" ||
- group.gatewayBaseUrl !== undefined ||
- group.clientType !== undefined
- ) {
- return false;
- }
- const cat = catalogEntryFor(entry.provider, entry.modelId);
- if (cat !== undefined) {
- return (
- canonicalClientType(entry.clientType) === canonicalClientType(cat.clientType) &&
- entry.baseUrl === cat.baseUrl
- );
- }
- return entry.clientType === undefined && entry.baseUrl === undefined;
-}
-
function asTable(v: unknown): RawTable {
return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as RawTable) : {};
}
@@ -225,40 +184,6 @@ function promotedRates(rates: PricingRates, discount: number): PricingRates {
};
}
-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.
*
@@ -418,13 +343,20 @@ export function utilityCompletionConfig(
modelId: string,
entry: Record<string, unknown>,
): GenerativeModelConfig {
- const apiKey = optStr(entry.api_key);
- const baseUrl = optStr(entry.base_url);
const clientType = canonicalClientType(optStr(entry.client_type));
+ // The same credential rule as every other client the harness builds (see core's
+ // resolveModelCredential): a keyless entry pointed away from its vendor throws here, which
+ // completeOnce reports as the failure it is.
+ const credential = resolveModelCredential({
+ provider: optStr(entry.provider) ?? "",
+ modelId,
+ clientType,
+ baseUrl: optStr(entry.base_url),
+ apiKey: optStr(entry.api_key),
+ });
return {
modelId,
- ...(apiKey ? { apiKey } : {}),
- ...(baseUrl ? { baseUrl } : {}),
+ ...credential,
...(clientType ? { clientType } : {}),
tools: [],
thinkingLevel: "none",
@@ -871,9 +803,8 @@ export class ProjectConfigService implements ProjectConfigStore {
* one costs real money, unlike the protocol probes).
*
* Credential resolution is the connectivity test's, verbatim — the request's key, else
- * the stored one, unless "clear" is checked. The environment layer needs no code here:
- * omitting apiKey lets AgentHub read the protocol's own variable, which is the same
- * chain protocol detection spells out by hand because it bypasses the SDK. Nothing
+ * the stored one, unless "clear" is checked, else the environment where core's
+ * resolveModelCredential allows it (the vendor's own endpoint; never a gateway's). Nothing
* secret is returned; the failure message is the provider's own text, truncated.
*/
async detectVision(
@@ -886,28 +817,27 @@ export class ProjectConfigService implements ProjectConfigStore {
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,
- });
+ const draftKey = req.clearApiKey ? undefined : (req.apiKey ?? optStr(entry.api_key));
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.
+ // Inside the try for the same reason as testModel: both the credential rule's refusal
+ // and the SDK's own missing-credential throw at construction must read as "probe
+ // failed", not a 500.
+ const credential = resolveModelCredential({
+ provider: req.provider,
+ modelId: req.modelId,
+ clientType,
+ baseUrl,
+ apiKey: draftKey,
+ });
const llm = new GenerativeModel({
modelId: req.modelId,
- ...(apiKey ? { apiKey } : {}),
+ ...credential,
...this.requestApiKeyResolver(
projectId,
req.provider,
req.modelId,
req.apiKey === undefined && req.clearApiKey !== true,
),
- ...(baseUrl ? { baseUrl } : {}),
...(clientType ? { clientType } : {}),
tools: [],
// The lowest real level, not "none": several reasoning endpoints reject a request
@@ -1001,14 +931,7 @@ export class ProjectConfigService implements ProjectConfigStore {
// 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,
- });
+ const draftKey = req.clearApiKey ? undefined : (req.apiKey ?? optStr(entry.api_key));
// 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
@@ -1017,23 +940,29 @@ 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
- // of a connectivity test is to collapse that kind of failure into
- // `{ ok:false }`; if construction were outside the try, a missing-key test
- // would bubble up as a 500.
+ // Credential resolution and construction must both be inside the try block: core's
+ // credential rule refuses a keyless entry pointed away from its vendor (a gateway row
+ // never borrows OPENAI_API_KEY / ANTHROPIC_API_KEY from the server environment — the
+ // group speed test runs through here too), and the provider SDK can throw during
+ // **client construction** itself when a credential is missing. The whole point of a
+ // connectivity test is to collapse that kind of failure into `{ ok:false }`; outside
+ // the try, a missing-key test would bubble up as a 500.
+ const credential = resolveModelCredential({
+ provider: req.provider,
+ modelId: req.modelId,
+ clientType,
+ baseUrl,
+ apiKey: draftKey,
+ });
const llm = new GenerativeModel({
modelId: req.modelId,
- ...(apiKey ? { apiKey } : {}),
+ ...credential,
...this.requestApiKeyResolver(
projectId,
req.provider,
req.modelId,
req.apiKey === undefined && req.clearApiKey !== true,
),
- ...(baseUrl ? { baseUrl } : {}),
...(clientType ? { clientType } : {}),
...(fastMode ? { fastMode: true } : {}),
tools: [],
@@ -1094,10 +1023,12 @@ export class ProjectConfigService implements ProjectConfigStore {
* 1. the request body's key (what the user just typed in the dialog);
* 2. otherwise, when the optional paired reference names a stored entry and "clear"
* isn't checked, that entry's saved key (the frontend only ever sees the mask);
- * 3. otherwise the environment variable for whichever protocol each probe speaks,
- * resolved inside detectModelProtocol because the protocol is the thing being
- * determined (ANTHROPIC_API_KEY for ant-messages, OPENAI_API_KEY for the two
- * OpenAI protocols).
+ * 3. otherwise the environment: a provider-scoped variable (the Penguin Go relay's
+ * PENGUIN_GO_API_KEY) resolved here for the group's rows, and otherwise the variable
+ * of whichever protocol each probe speaks, resolved inside detectModelProtocol
+ * because the protocol is the thing being determined — and only for a URL that is
+ * the vendor's own (see core's endpointEnvApiKey), never for a gateway or a private
+ * server.
* Layers 2 and 3 are read server-side only and never travel back to the browser.
* Detection still runs with no credential at all: a protocol-shaped 401/403 proves the
* route. Never throws on probe failures — every outcome is reported per probe.
@@ -1116,24 +1047,31 @@ export class ProjectConfigService implements ProjectConfigStore {
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);
+ if (apiKey === undefined && req.provider && req.modelId) {
+ // A provider-scoped pair (the relay's) is the harness's to read, for any URL in that
+ // group; a vendor pair is left to the per-probe rule in detectModelProtocol. Without a
+ // relay key, anonymous probing is still safe and can identify a route from its 401.
+ const fallback = modelEnvFallback({
+ provider: req.provider,
+ modelId: req.modelId,
+ clientType: savedClientType,
+ });
+ if (fallback !== undefined && !fallback.readByClient) {
+ apiKey = process.env[fallback.envKey]?.trim() || undefined;
+ }
}
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: {} } : {}),
});
}
/**
* Endpoint model listing for the add-group import (see EndpointModelListRequest). All
* parameters come from the request — a group being created has no stored entry to fall
- * back to; an omitted key follows the same environment chain as the connectivity test
- * (the wrapped SDK reads the protocol's own variable). Never throws: SDK construction
+ * back to; an omitted key is lent the protocol's environment variable only when the URL is
+ * that vendor's own (core's endpointEnvApiKey), and refused otherwise. Never throws: SDK
+ * construction
* and request failures collapse into `{ ok:false, message }`, an AgentHub
* UnsupportedOperationError additionally sets `unsupported` so the dialog can point at
* the manual path, and a listing that outlives LIST_MODELS_TIMEOUT_MS is reported as
@@ -1206,12 +1144,14 @@ export class ProjectConfigService implements ProjectConfigStore {
// persists it).
const clientType = canonicalClientType(optStr(m.client_type));
const cat = catalogEntryFor(provider, modelId);
- // The env fallback is reported as-is: follows the same rule as
- // AgentHub routing — an explicit client_type takes priority (the openai
- // 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 = resolveProviderModelEnv(provider, modelId, clientType)?.envKey;
+ const credBaseUrl = optStr(m.base_url);
+ // The env fallback the entry is actually allowed (core's modelEnvFallback): the
+ // variable AgentHub's routed client reads — an explicit client_type takes priority,
+ // otherwise the id auto-routes — but only while the entry's endpoint is the vendor's
+ // own. A gateway, custom or vLLM row with its own endpoint gets no envKey at all:
+ // reporting a name there would promise a fallback the harness refuses.
+ const fallback = modelEnvFallback({ provider, modelId, clientType, baseUrl: credBaseUrl });
+ const envKey = fallback?.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);
@@ -1228,18 +1168,22 @@ export class ProjectConfigService implements ProjectConfigStore {
m.display_name === "" ? "" : (optStr(m.display_name) ?? cat?.displayName);
// credential is inlined on the entry: a credential block is emitted if either api_key or base_url is present.
const apiKey = optStr(m.api_key);
- const credBaseUrl = optStr(m.base_url);
const createdAt = optStr(m.created_at);
- // Masked env-fallback preview, first-party entries only (see envFallbackFirstParty):
- // presence is implied by the field, the plaintext never leaves the server, and an
- // empty variable counts as absent — it would not authenticate either. Read from this
- // process's env, which on the desktop already includes the imported login-shell
+ // Masked env-fallback preview, for the entries the UI may present as covered (core's
+ // modelEnvPreviewKey — the dialog's hint reads the same function): a row on a vendor
+ // endpoint, or a keyless row in a group whose defaults are the vendor's. A vLLM preset
+ // or a custom row with no base URL does fall back under the rule, but is not shown as
+ // configured. Presence is implied by the field, the plaintext never leaves the server,
+ // and an empty variable counts as absent — it would not authenticate either. Read from
+ // this process's env, which on the desktop already includes the imported login-shell
// variables.
- const envValue =
- envKey !== undefined &&
- envFallbackFirstParty({ provider, modelId, clientType, baseUrl: credBaseUrl })
- ? (process.env[envKey] ?? "")
- : "";
+ const previewKey = modelEnvPreviewKey({
+ provider,
+ modelId,
+ clientType,
+ baseUrl: credBaseUrl,
+ });
+ const envValue = previewKey !== undefined ? (process.env[previewKey] ?? "") : "";
const envKeyMasked = envValue !== "" ? maskApiKey(envValue) : undefined;
const info: ModelInfo = {
provider,
diff --git a/packages/server/src/services/protocol-detect.ts b/packages/server/src/services/protocol-detect.ts
index 55bd7bcd..3b98e45b 100644
--- a/packages/server/src/services/protocol-detect.ts
+++ b/packages/server/src/services/protocol-detect.ts
@@ -46,12 +46,13 @@
* Credential resolution is layered: the caller passes the key typed in the dialog or the
* entry's stored one, and when there is neither, each probe falls back to the environment
* variable for the protocol IT speaks (`ANTHROPIC_API_KEY` for `ant-messages`,
- * `OPENAI_API_KEY` for the two OpenAI protocols — see envApiKeyForProtocol). Detection
- * still works with no credential at all, but an authenticated probe is far more likely to
- * draw a protocol-shaped error than the generic 401 or gateway HTML an anonymous request
- * often gets, so the fallback materially improves accuracy.
+ * `OPENAI_API_KEY` for the two OpenAI protocols — see envApiKeyForProtocol) — but only when
+ * the probed base URL is that vendor's own endpoint. A gateway or a private server gets an
+ * anonymous probe: detection still
+ * works with no credential at all (a protocol-shaped 401 identifies the route), and sending
+ * the user's vendor key to a URL they typed is exactly what the rule forbids.
*/
-import { resolveModelEnv } from "@prismshadow/penguin-core";
+import { endpointEnvApiKey } from "@prismshadow/penguin-core";
import type {
ModelProtocolDetectResponse,
ModelProtocolProbeDto,
@@ -102,25 +103,25 @@ export const PROTOCOL_PROBES: readonly ProbeSpec[] = [
];
/**
- * Environment-variable fallback for a probe's credential, resolved PER PROTOCOL.
+ * Environment-variable fallback for a probe's credential, resolved PER PROTOCOL and PER URL.
*
* Which env var backs a request depends on the protocol being spoken, and detection is
* precisely the case where the protocol is not yet known — so the resolution happens once
* per probe rather than once per detection: `ant-messages` reads `ANTHROPIC_API_KEY`,
- * `openai-responses` / `openai-chat` read `OPENAI_API_KEY`. `resolveModelEnv` is the same
- * mapping the rest of the app uses (an explicit client type wins over the model id there),
- * so this cannot drift from what the saved model will actually read.
+ * `openai-responses` / `openai-chat` read `OPENAI_API_KEY`. Core's endpointEnvApiKey is the
+ * same rule the saved model is held to (see modelEnvFallback), so this cannot drift from
+ * what the entry will actually be allowed to read: the variable is lent only to the
+ * vendor's own endpoint.
*
* Server-side only: the value is placed in a request header and never returned to the
* browser, echoed in a result, or logged.
*/
export function envApiKeyForProtocol(
clientType: ProtocolClientType,
+ baseUrl: string,
env: NodeJS.ProcessEnv = process.env,
): string | undefined {
- const envKey = resolveModelEnv("", clientType)?.envKey;
- if (!envKey) return undefined;
- return env[envKey]?.trim() || undefined;
+ return endpointEnvApiKey(clientType, baseUrl, env);
}
/** Whether a string is an absolute http(s) URL (the only base URLs worth probing). */
@@ -341,10 +342,10 @@ export async function detectModelProtocol(options: {
baseUrl: string;
/**
* Explicit credential (the key typed in the dialog, or the entry's stored key). When
- * absent, each probe falls back to the environment variable for the protocol it speaks
- * — see envApiKeyForProtocol. An authenticated probe is what makes the difference
- * between a protocol-shaped error (which identifies the route) and the generic 401 or
- * gateway HTML that an anonymous request often draws instead.
+ * absent, each probe falls back to the environment variable for the protocol it speaks,
+ * where the probed URL is allowed one — see envApiKeyForProtocol. An authenticated probe
+ * is what makes the difference between a protocol-shaped error (which identifies the
+ * route) and the generic 401 or gateway HTML that an anonymous request often draws.
*/
apiKey?: string;
/** Injection point for tests; defaults to global fetch (which routes through the admin proxy settings, see net/proxy.ts). */
@@ -358,7 +359,7 @@ export async function detectModelProtocol(options: {
const probes: ModelProtocolProbeDto[] = [];
for (const baseUrl of candidateBaseUrls(options.baseUrl)) {
for (const spec of PROTOCOL_PROBES) {
- const apiKey = options.apiKey ?? envApiKeyForProtocol(spec.clientType, options.env);
+ const apiKey = options.apiKey ?? envApiKeyForProtocol(spec.clientType, baseUrl, options.env);
const probe = await runProbe(spec, baseUrl, apiKey, fetchImpl, timeoutMs);
probes.push(probe);
if (probe.outcome === "served") return { detected: spec.clientType, baseUrl, probes };
diff --git a/packages/server/test/models-list.test.ts b/packages/server/test/models-list.test.ts
index 3ac01def..1ec7dbb8 100644
--- a/packages/server/test/models-list.test.ts
+++ b/packages/server/test/models-list.test.ts
@@ -39,7 +39,7 @@ describe("ProjectConfigService.listEndpointModels", () => {
]);
});
- it("omits an absent key so the SDK's environment fallback applies", async () => {
+ it("omits an absent key; whether the environment may lend one is core's listing's decision (see its tests)", async () => {
const calls: Record<string, unknown>[] = [];
await service.listEndpointModels(
{ baseUrl: req.baseUrl, clientType: "ant-messages" },
diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.ts
index 22dd48c5..1d7bb70f 100644
--- a/packages/server/test/models.test.ts
+++ b/packages/server/test/models.test.ts
@@ -170,7 +170,7 @@ describe("models preset & catalog enrichment", () => {
expect(pick(body, "tokendance", "hy4-preview")).not.toHaveProperty("discount");
});
- it("masks allowed direct and relay env fallbacks, never gateway fallbacks, and never leaks a value", async () => {
+ it("reports and masks the env fallback only where the entry is allowed one (the vendor's own endpoint, or the relay's own variable), and never leaks a value", async () => {
const saved = {
anthropic: process.env.ANTHROPIC_API_KEY,
deepseek: process.env.DEEPSEEK_API_KEY,
@@ -194,16 +194,30 @@ describe("models preset & catalog enrichment", () => {
{ provider: "deepseek", modelId: "deepseek-v4-pro" },
// Off-catalog id in a vendor group, pure auto-route: still first-party.
{ provider: "anthropic", modelId: "claude-sonnet-4-6-preview" },
- // Vendor group re-pointed at a generic protocol: not first-party.
+ // Vendor group on a generic protocol with no base URL: the OpenAI client talks to
+ // api.openai.com, so the OpenAI key may back it — whatever the group is called.
{ provider: "anthropic", modelId: "claude-via-gateway", clientType: "openai" },
- // Gateway and custom groups never carry a preview, even with OPENAI_API_KEY set.
+ // A gateway row carries the gateway's endpoint: no fallback at all, so no envKey
+ // and no preview, even with OPENAI_API_KEY set.
{
provider: "openrouter",
modelId: "xiaomi/mimo-v2.5",
clientType: "openai-chat",
baseUrl: "https://openrouter.ai/api/v1",
},
+ // Custom rows are judged by their endpoint: none → the vendor's own (a fallback, but
+ // not a preview — see modelEnvPreviewKey); a private server → nothing.
{ provider: "custom", modelId: "my-model", clientType: "openai" },
+ {
+ provider: "custom",
+ modelId: "my-local",
+ clientType: "openai",
+ baseUrl: "http://127.0.0.1:8000/v1",
+ },
+ // A vLLM preset as seeded: no base URL, the vLLM adapter pinned. It falls back to
+ // OPENAI_API_KEY under the rule, but showing the mask would list a self-hosted id in
+ // the chat picker as configured and send the OpenAI key to api.openai.com.
+ { provider: "vllm", modelId: "Qwen/Qwen3.8-27B", clientType: "openai-chat-vllm-adapter" },
// Both protocols in the relay group resolve the same provider-scoped key.
{
provider: "penguin-go",
@@ -229,13 +243,20 @@ describe("models preset & catalog enrichment", () => {
expect(pick(body, "anthropic", "claude-sonnet-4-6").envKeyMasked).toBe(masked);
expect(pick(body, "anthropic", "claude-sonnet-4-6-preview").envKeyMasked).toBe(masked);
expect(pick(body, "deepseek", "deepseek-v4-pro").envKeyMasked).toBeUndefined();
+ const openaiMasked = `${openaiValue.slice(0, 4)}…${openaiValue.slice(-4)}`;
const rePointed = pick(body, "anthropic", "claude-via-gateway");
expect(rePointed.envKey).toBe("OPENAI_API_KEY");
- expect(rePointed.envKeyMasked).toBeUndefined();
+ expect(rePointed.envKeyMasked).toBe(openaiMasked);
const gateway = pick(body, "openrouter", "xiaomi/mimo-v2.5");
- expect(gateway.envKey).toBe("OPENAI_API_KEY");
+ expect(gateway.envKey).toBeUndefined();
expect(gateway.envKeyMasked).toBeUndefined();
+ expect(pick(body, "custom", "my-model").envKey).toBe("OPENAI_API_KEY");
expect(pick(body, "custom", "my-model").envKeyMasked).toBeUndefined();
+ expect(pick(body, "custom", "my-local").envKey).toBeUndefined();
+ expect(pick(body, "custom", "my-local").envKeyMasked).toBeUndefined();
+ const vllm = pick(body, "vllm", "Qwen/Qwen3.8-27B");
+ expect(vllm.envKey).toBe("OPENAI_API_KEY");
+ expect(vllm.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);
@@ -406,8 +427,8 @@ describe("models preset & catalog enrichment", () => {
const body = (await (await api.get(url())).json()) as ModelsResponse;
const legacy = pick(body, "custom", "legacy-openai-model");
expect(legacy.clientType).toBe("openai-chat");
- // The env fallback resolves like any openai-chat entry.
- expect(legacy.envKey).toBe("OPENAI_API_KEY");
+ // Its own endpoint, so no environment fallback is reported for it.
+ expect(legacy.envKey).toBeUndefined();
});
it("a configured model that has since been dropped from the built-in catalog still loads, keeps its data, and stays usable", async () => {
@@ -454,7 +475,8 @@ describe("models preset & catalog enrichment", () => {
expect(orphan.pricing).toEqual({ cacheRead: 0, cacheWrite: 0, output: 0 });
expect(orphan.vision).toBe(false);
expect(orphan.clientType).toBe("openai-chat");
- expect(orphan.envKey).toBe("OPENAI_API_KEY");
+ // It still carries the gateway's endpoint, so it gets no environment fallback.
+ expect(orphan.envKey).toBeUndefined();
// The credential survives, masked; the base URL is still inlined on the entry.
expect(orphan.credential?.baseUrl).toBe("https://openrouter.ai/api/v1");
expect(orphan.credential?.apiKeyMasked).toBeTruthy();
@@ -535,6 +557,9 @@ describe("models preset & catalog enrichment", () => {
expect(pick(body, "moonshot", "kimi-k2.6").credential?.apiKeyMasked).toBe("sk-o…1111");
expect(pick(body, "moonshot", "kimi-k2.6").envKey).toBe("MOONSHOT_API_KEY");
expect(pick(body, "siliconflow", "kimi-k2.6").credential?.apiKeyMasked).toBe("sk-g…2222");
+ // Saved without the gateway's base URL, this row's client talks to api.openai.com — so
+ // the OpenAI variable honestly is its fallback (the preset, which carries the gateway
+ // endpoint, gets none; see the env-fallback test above).
expect(pick(body, "siliconflow", "kimi-k2.6").envKey).toBe("OPENAI_API_KEY");
// Round-trips through disk unchanged.
@@ -1133,6 +1158,71 @@ describe("model-reference rekeying and the connectivity test", () => {
}
});
+ it("the connectivity test and the group speed test refuse a keyless gateway row without touching the environment", async () => {
+ // The #786 review's finding: a keyless gateway row handed AgentHub no key, and its
+ // generic client read OPENAI_API_KEY / ANTHROPIC_API_KEY itself — one speed test on a
+ // gateway group sent the user's vendor keys to the gateway once per model. Both paths run
+ // through testModel; both must refuse before any request leaves the process.
+ const saved = { openai: process.env.OPENAI_API_KEY, anthropic: process.env.ANTHROPIC_API_KEY };
+ process.env.OPENAI_API_KEY = "vendor-openai-must-not-cross";
+ process.env.ANTHROPIC_API_KEY = "vendor-anthropic-must-not-cross";
+ const realFetch = globalThis.fetch;
+ let requests = 0;
+ globalThis.fetch = (async () => {
+ requests += 1;
+ throw new Error("no request may leave the process for a refused probe");
+ }) as typeof fetch;
+ try {
+ // A gateway preset: the group's endpoint, no key. Both OpenAI-protocol gateways and the
+ // Messages-protocol custom preset (Atria — the path that carried the Anthropic key in the
+ // #786 finding) are refused, and the refusal is the harness's own sentence, never the
+ // SDK's text with a vendor variable in it.
+ for (const [provider, modelId] of [
+ ["tokendance", "glm-5.3"],
+ ["openrouter", "openai/gpt-5.5"],
+ ["custom", "Atria-Dawn-Preview"],
+ ] as const) {
+ expect(catalogEntryFor(provider, modelId)).toBeDefined();
+ for (const speed of [false, true]) {
+ const res = await api.post(testUrl(), { provider, modelId, speed });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as ModelTestResponse;
+ expect(body.ok).toBe(false);
+ expect(body.message).toMatch(/has no API key/);
+ expect(body.message).toMatch(/set the API key on the model entry/);
+ expect(body.message).not.toMatch(/OPENAI_API_KEY|ANTHROPIC_API_KEY|must-not-cross/);
+ }
+ }
+ // A not-yet-saved custom row pointed at a private server: same refusal.
+ const draft = await api.post(testUrl(), {
+ provider: "custom",
+ modelId: "draft-model",
+ clientType: "openai-chat",
+ baseUrl: "http://127.0.0.1:9/v1",
+ });
+ expect(((await draft.json()) as ModelTestResponse).message).toMatch(/has no API key/);
+ // The vision probe shares the rule.
+ const vision = await api.post(`${url()}/detect-vision`, {
+ provider: "tokendance",
+ modelId: "glm-5.3",
+ });
+ expect((await vision.json()) as ModelVisionDetectResponse).toMatchObject({
+ outcome: "failed",
+ message: expect.stringMatching(/has no API key/) as string,
+ });
+ expect(requests).toBe(0);
+ } finally {
+ globalThis.fetch = realFetch;
+ for (const [key, value] of [
+ ["OPENAI_API_KEY", saved.openai],
+ ["ANTHROPIC_API_KEY", saved.anthropic],
+ ] as const) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ }
+ });
+
it("Penguin Go probes never substitute vendor environment keys", async () => {
const saved = {
gemini: process.env.GEMINI_API_KEY,
@@ -1148,7 +1238,7 @@ describe("model-reference rekeying and the connectivity test", () => {
expect(tested.status).toBe(200);
expect((await tested.json()) as ModelTestResponse).toMatchObject({
ok: false,
- message: "Missing API key for Penguin Go.",
+ message: expect.stringMatching(/has no API key.*PENGUIN_GO_API_KEY/) as string,
});
const vision = await api.post(`${url()}/detect-vision`, {
@@ -1158,7 +1248,7 @@ describe("model-reference rekeying and the connectivity test", () => {
expect(vision.status).toBe(200);
expect((await vision.json()) as ModelVisionDetectResponse).toMatchObject({
outcome: "failed",
- message: "Missing API key for Penguin Go.",
+ message: expect.stringMatching(/has no API key.*PENGUIN_GO_API_KEY/) as string,
});
}
@@ -1170,7 +1260,7 @@ describe("model-reference rekeying and the connectivity test", () => {
});
expect((await noEndpoint.json()) as ModelTestResponse).toMatchObject({
ok: false,
- message: "Missing API base URL for Penguin Go.",
+ message: expect.stringMatching(/has no base URL/) as string,
});
} finally {
for (const [key, value] of [
diff --git a/packages/server/test/protocol-detect.test.ts b/packages/server/test/protocol-detect.test.ts
index ada6a0c7..eddfac9c 100644
--- a/packages/server/test/protocol-detect.test.ts
+++ b/packages/server/test/protocol-detect.test.ts
@@ -457,28 +457,68 @@ describe("detectModelProtocol (order and stop-at-first)", () => {
// ---------------------------------------------------------------------------
describe("envApiKeyForProtocol", () => {
- it("maps each protocol to the variable its AgentHub client actually reads", () => {
+ const OPENAI = "https://api.openai.com/v1";
+ const ANTHROPIC = "https://api.anthropic.com";
+
+ it("maps each protocol to the variable its AgentHub client actually reads, for the vendor's own endpoint", () => {
const env = { OPENAI_API_KEY: "sk-openai", ANTHROPIC_API_KEY: "sk-anthropic" };
- expect(envApiKeyForProtocol("openai-responses", env)).toBe("sk-openai");
- expect(envApiKeyForProtocol("openai-chat", env)).toBe("sk-openai");
+ expect(envApiKeyForProtocol("openai-responses", OPENAI, env)).toBe("sk-openai");
+ expect(envApiKeyForProtocol("openai-chat", OPENAI, env)).toBe("sk-openai");
// The whole point of resolving per protocol: this one is NOT an OPENAI_* reader.
- expect(envApiKeyForProtocol("ant-messages", env)).toBe("sk-anthropic");
+ expect(envApiKeyForProtocol("ant-messages", ANTHROPIC, env)).toBe("sk-anthropic");
+ });
+
+ it("lends nothing to a URL that is not the vendor's own, even one OPENAI_BASE_URL names", () => {
+ const env = { OPENAI_API_KEY: "sk-openai", ANTHROPIC_API_KEY: "sk-anthropic" };
+ // A gateway, a private server: the user's vendor key must not be sent there.
+ expect(envApiKeyForProtocol("openai-chat", "https://gw.example.com/v1", env)).toBeUndefined();
+ expect(envApiKeyForProtocol("ant-messages", "http://127.0.0.1:8000", env)).toBeUndefined();
+ // Environment keys are for official endpoints only: naming the URL in OPENAI_BASE_URL
+ // does not make it one.
+ expect(
+ envApiKeyForProtocol("openai-chat", "https://gw.example.com/v1", {
+ ...env,
+ OPENAI_BASE_URL: "https://gw.example.com/v1/",
+ }),
+ ).toBeUndefined();
});
it("treats unset and blank as absent", () => {
- expect(envApiKeyForProtocol("openai-chat", {})).toBeUndefined();
- expect(envApiKeyForProtocol("openai-chat", { OPENAI_API_KEY: " " })).toBeUndefined();
- expect(envApiKeyForProtocol("ant-messages", { OPENAI_API_KEY: "sk-openai" })).toBeUndefined();
+ expect(envApiKeyForProtocol("openai-chat", OPENAI, {})).toBeUndefined();
+ expect(envApiKeyForProtocol("openai-chat", OPENAI, { OPENAI_API_KEY: " " })).toBeUndefined();
+ expect(
+ envApiKeyForProtocol("ant-messages", ANTHROPIC, { OPENAI_API_KEY: "sk-openai" }),
+ ).toBeUndefined();
});
});
describe("detectModelProtocol env fallback", () => {
const BASE = "https://gw.example.com/v1";
- it("authenticates each probe from the env var for the protocol THAT probe speaks", async () => {
+ it("probes a URL that is not a vendor's own anonymously, whatever vendor keys are set", async () => {
const seen: SeenCall[] = [];
await detectModelProtocol({
baseUrl: BASE,
+ // OPENAI_BASE_URL naming the URL changes nothing: environment keys are for official
+ // endpoints only.
+ env: {
+ OPENAI_API_KEY: "sk-openai",
+ OPENAI_BASE_URL: BASE,
+ ANTHROPIC_API_KEY: "sk-anthropic",
+ },
+ fetchImpl: fakeFetch({}, seen), // every path 404s, so both candidates run all three probes
+ });
+ expect(seen).toHaveLength(6);
+ for (const call of seen) {
+ expect(call.headers.authorization).toBeUndefined();
+ expect(call.headers["x-api-key"]).toBeUndefined();
+ }
+ });
+
+ it("authenticates each probe of a vendor's own URL from the env var for the protocol THAT probe speaks", async () => {
+ const seen: SeenCall[] = [];
+ await detectModelProtocol({
+ baseUrl: "https://api.openai.com/v1",
env: { OPENAI_API_KEY: "sk-openai", ANTHROPIC_API_KEY: "sk-anthropic" },
fetchImpl: fakeFetch({}, seen), // every path 404s, so both candidates run all three probes
});
@@ -486,9 +526,14 @@ describe("detectModelProtocol env fallback", () => {
const [responses, messages, chat] = seen as [SeenCall, SeenCall, SeenCall];
expect(responses.headers.authorization).toBe("Bearer sk-openai");
expect(chat.headers.authorization).toBe("Bearer sk-openai");
- // ant-messages carries the Anthropic key through both header conventions.
- expect(messages.headers.authorization).toBe("Bearer sk-anthropic");
- expect(messages.headers["x-api-key"]).toBe("sk-anthropic");
+ // OpenAI's host is not Anthropic's endpoint: the Messages probe stays anonymous there.
+ expect(messages.headers.authorization).toBeUndefined();
+ expect(messages.headers["x-api-key"]).toBeUndefined();
+ // The neighbouring /v1-less candidate is not the official endpoint either.
+ const [responses2, messages2, chat2] = seen.slice(3) as [SeenCall, SeenCall, SeenCall];
+ expect(responses2.headers.authorization).toBeUndefined();
+ expect(messages2.headers["x-api-key"]).toBeUndefined();
+ expect(chat2.headers.authorization).toBeUndefined();
// Whatever the source, the credential never reaches a URL.
for (const call of seen) {
expect(call.url).not.toContain("sk-openai");
@@ -511,7 +556,7 @@ describe("detectModelProtocol env fallback", () => {
it("falls back per protocol, so a half-configured environment still authenticates its own probe", async () => {
const seen: SeenCall[] = [];
await detectModelProtocol({
- baseUrl: BASE,
+ baseUrl: "https://api.anthropic.com",
env: { ANTHROPIC_API_KEY: "sk-anthropic" },
fetchImpl: fakeFetch({}, seen),
});
@@ -523,7 +568,7 @@ describe("detectModelProtocol env fallback", () => {
it("never echoes an env-sourced key into the reported probes", async () => {
const res = await detectModelProtocol({
- baseUrl: BASE,
+ baseUrl: "https://api.openai.com/v1",
env: { OPENAI_API_KEY: "sk-openai", ANTHROPIC_API_KEY: "sk-anthropic" },
fetchImpl: fakeFetch({ "/v1/responses": { status: 401, body: OPENAI_ERROR } }),
});
@@ -614,7 +659,7 @@ describe("POST /api/projects/:p/models/detect", () => {
}
});
- it("the paired reference falls back to the stored key (probe before the frontend ever sees a plaintext key); clearApiKey suppresses that fallback and leaves only the env var", async () => {
+ it("the paired reference falls back to the stored key (probe before the frontend ever sees a plaintext key); clearApiKey suppresses that fallback, and a private URL is not lent the env var", 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));
@@ -644,14 +689,16 @@ describe("POST /api/projects/:p/models/detect", () => {
expect(messagesProbe?.xApiKey).toBe("sk-stored-secret");
// clearApiKey drops the STORED key. What backs the probe then is whatever the saved
- // model itself would run on, i.e. the protocol's env var — so this asserts both
- // halves, with the environment pinned (the real one must never reach a probe, and
- // the suite must not depend on what the developer exports).
+ // model itself would run on — and a private server is allowed no env var — so this
+ // asserts both halves, with the environment pinned (the real one must never reach a
+ // probe, and the suite must not depend on what the developer exports).
const savedAnthropic = process.env.ANTHROPIC_API_KEY;
const savedOpenai = process.env.OPENAI_API_KEY;
+ const savedAnthropicBase = process.env.ANTHROPIC_BASE_URL;
try {
delete process.env.ANTHROPIC_API_KEY;
delete process.env.OPENAI_API_KEY;
+ delete process.env.ANTHROPIC_BASE_URL;
seen.length = 0;
const cleared = await api.post(detectUrl(), {
baseUrl: `http://127.0.0.1:${port}`,
@@ -668,25 +715,33 @@ describe("POST /api/projects/:p/models/detect", () => {
expect(keyless?.xApiKey).toBeUndefined();
expect(keyless?.auth).toBeUndefined();
- // Same request with the env var present: the stored key stays suppressed, and the
- // environment — not "sk-stored-secret" — is what authenticates the probe.
+ // Same request with the env var present — and even with ANTHROPIC_BASE_URL naming
+ // this very server: the stored key stays suppressed, and the local server is not
+ // Anthropic's endpoint, so the Anthropic key is NOT lent to it and the probe stays
+ // anonymous. Environment keys are for official endpoints only.
process.env.ANTHROPIC_API_KEY = "sk-env-anthropic";
+ process.env.ANTHROPIC_BASE_URL = `http://127.0.0.1:${port}`;
seen.length = 0;
- const viaEnv = await api.post(detectUrl(), {
+ const withheld = await api.post(detectUrl(), {
baseUrl: `http://127.0.0.1:${port}`,
provider: "custom",
modelId: "stored-key-model",
clearApiKey: true,
});
- expect(viaEnv.status).toBe(200);
- const envProbe = seen.find((c) => c.path === "/v1/messages");
- expect(envProbe?.xApiKey).toBe("sk-env-anthropic");
- expect(envProbe?.auth).toBe("Bearer sk-env-anthropic");
+ expect(withheld.status).toBe(200);
+ expect(((await withheld.json()) as ModelProtocolDetectResponse).detected).toBe(
+ "ant-messages",
+ );
+ const withheldProbe = seen.find((c) => c.path === "/v1/messages");
+ expect(withheldProbe?.xApiKey).toBeUndefined();
+ expect(withheldProbe?.auth).toBeUndefined();
} finally {
if (savedAnthropic === undefined) delete process.env.ANTHROPIC_API_KEY;
else process.env.ANTHROPIC_API_KEY = savedAnthropic;
if (savedOpenai === undefined) delete process.env.OPENAI_API_KEY;
else process.env.OPENAI_API_KEY = savedOpenai;
+ if (savedAnthropicBase === undefined) delete process.env.ANTHROPIC_BASE_URL;
+ else process.env.ANTHROPIC_BASE_URL = savedAnthropicBase;
}
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
diff --git a/packages/server/test/utility-completion.test.ts b/packages/server/test/utility-completion.test.ts
index 11803b77..19f6f724 100644
--- a/packages/server/test/utility-completion.test.ts
+++ b/packages/server/test/utility-completion.test.ts
@@ -46,6 +46,7 @@ describe("utilityCompletionConfig", () => {
it("still honours a per-model cap pinned below the budget, and the entry's protocol", () => {
const config = utilityCompletionConfig("m-bench", {
+ api_key: "sk-1",
max_tokens: 128,
base_url: "https://example.test/v1",
// The pre-0.4.2 spelling is normalized like everywhere else.
@@ -56,8 +57,22 @@ describe("utilityCompletionConfig", () => {
expect(config.clientType).toBe("openai-chat");
});
+ it("refuses a keyless entry whose endpoint is not the vendor's own (core's credential rule)", () => {
+ // completeOnce reports this as a failure; the environment's OPENAI_API_KEY is never
+ // borrowed for a third-party endpoint.
+ expect(() =>
+ utilityCompletionConfig("m-bench", {
+ provider: "custom",
+ base_url: "https://example.test/v1",
+ client_type: "openai",
+ }),
+ ).toThrow(/has no API key/);
+ });
+
it("never tightens to an uncapped entry's -1", () => {
- expect(utilityCompletionConfig("m-bench", { max_tokens: -1 }).maxTokens).toBe(300);
+ expect(utilityCompletionConfig("m-bench", { api_key: "sk-1", max_tokens: -1 }).maxTokens).toBe(
+ 300,
+ );
});
});
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index fed90443..1dfee787 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -86,8 +86,8 @@ import {
isVendorGroup,
modelHomepageUrl,
providerClientType,
+ providerEnvFallbackKey,
providerInfo,
- resolveProviderModelEnv,
unroutableVendorModel,
} from "@prismshadow/penguin-core/model-catalog";
import type {
@@ -117,7 +117,7 @@ import {
DEFAULT_CUSTOM_CLIENT_TYPE,
detectableBaseUrl,
displayWidthCh,
- envHintClientType,
+ envHintKeyFor,
isCustomLikeGroup,
isGenericProtocolClientType,
needsProtocolDetectOnSave,
@@ -2944,20 +2944,12 @@ function ModelDialog({
// the model id and API key labels in both the add and edit dialogs; custom
// and self-defined groups have no link).
const dialogProvider = providerInfo(form.provider);
- // env fallback resolves live from the current form (uses the same
- // 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 = resolveProviderModelEnv(
- form.provider,
- form.modelId.trim(),
- envHintClientType(form.provider, form.clientType),
- )?.envKey;
+ // The variable a blank key may be PRESENTED as covered by, for the entry as drafted (core's
+ // modelEnvPreviewKey, which the server's masked preview reads too): undefined for every row
+ // whose endpoint is not the vendor's own — a gateway's preset base URL, a custom or vLLM
+ // server, a vendor row re-pointed at a proxy — and for a keyless vLLM / custom row with no
+ // base URL. The hint and the stored-mask block below follow this.
+ const liveEnvKey = envHintKeyFor(form.provider, form.modelId, form.clientType, form.baseUrl);
// The protocol this group pins on every entry, user-added ones included (OpenRouter,
// vLLM); undefined for every group that leaves the protocol to auto-routing, a gateway
// preset, or detection.
@@ -3338,13 +3330,18 @@ function ModelDialog({
rule): the created-at position says where the key comes from instead, and there is
no clear control — an environment variable cannot be cleared from here. Typing a new
key hides this like the stored block; once saved, the stored key takes priority and
- the display switches to the stored form. */}
- {!form.credential?.apiKeyMasked && form.envKeyMasked !== undefined && !form.apiKeyInput && (
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
- <span className="font-mono">{form.envKeyMasked}</span>
- <span className="text-gray-400">{S.models.readFromEnv}</span>
- </div>
- )}
+ the display switches to the stored form. The mask is the SAVED row's: once the draft
+ resolves to another variable or to none (a proxy base URL typed over a vendor row),
+ it is hidden rather than left promising a key the draft will not have. */}
+ {!form.credential?.apiKeyMasked &&
+ form.envKeyMasked !== undefined &&
+ liveEnvKey === form.envKey &&
+ !form.apiKeyInput && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
+ <span className="font-mono">{form.envKeyMasked}</span>
+ <span className="text-gray-400">{S.models.readFromEnv}</span>
+ </div>
+ )}
{/* 2) base URL (required for custom / user-defined groups and explicit openai protocol — see
baseUrlRequired). The in-field suffix at the right edge shows the protocol path the
@@ -3782,6 +3779,7 @@ function GroupKeyDialog({
onSubmit: (apiKey: string) => void;
}) {
const [key, setKey] = useState("");
+ const groupEnvKey = providerEnvFallbackKey(provider.id);
return (
<Modal
open
@@ -3814,11 +3812,14 @@ function GroupKeyDialog({
className="font-mono"
autoComplete="off"
autoFocus
- // Only promise the variable when the server reported a value for it: the group's
- // variable name is always known, which says nothing about whether it is set.
+ // Only promise the variable when this group's rows may fall back to it at all
+ // (providerEnvFallbackKey: never a gateway, custom, vLLM or user-defined group —
+ // the OpenAI key an Anthropic row proved set is not this gateway's key) AND the
+ // server reported a value for it: the group's variable name is always known,
+ // which says nothing about whether it is set.
placeholder={
- detectedEnvKeys.has(provider.envKey)
- ? S.models.apiKeyEnvHint(provider.envKey)
+ groupEnvKey !== undefined && detectedEnvKeys.has(groupEnvKey)
+ ? S.models.apiKeyEnvHint(groupEnvKey)
: undefined
}
/>
diff --git a/packages/web/src/features/models/protocol-types.ts b/packages/web/src/features/models/protocol-types.ts
index 372f860b..6df749b7 100644
--- a/packages/web/src/features/models/protocol-types.ts
+++ b/packages/web/src/features/models/protocol-types.ts
@@ -6,7 +6,11 @@
* The probing itself is server-side (packages/server/src/services/protocol-detect.ts); these
* only decide what the dialog shows and what is worth sending there.
*/
-import { providerClientType, providerInfo } from "@prismshadow/penguin-core/model-catalog";
+import {
+ modelEnvPreviewKey,
+ providerClientType,
+ providerInfo,
+} from "@prismshadow/penguin-core/model-catalog";
/**
* AgentHub's generic protocol client types, in detection order (custom / user-defined
@@ -160,6 +164,31 @@ export function envHintClientType(provider: string, clientType: string): string
);
}
+/**
+ * The variable the dialog's API-key field may promise for the entry as drafted, or undefined
+ * when nothing should be promised: core's modelEnvPreviewKey — the same function the server's
+ * GET /models preview reads, so the hint and the card's "read from environment variable" can
+ * never disagree — over the form's group, id, protocol (resolved as envHintClientType does)
+ * and base URL. A gateway row carries its preset endpoint, so it resolves to nothing — the
+ * hint that used to read "leave empty to use OPENAI_API_KEY" on a TokenDance or OpenRouter row
+ * was promising the user's OpenAI key to a third party; a vLLM preset or a custom row with no
+ * base URL resolves to nothing either, so the field never suggests running a self-hosted id
+ * against api.openai.com.
+ */
+export function envHintKeyFor(
+ provider: string,
+ modelId: string,
+ clientType: string,
+ baseUrl: string,
+): string | undefined {
+ return modelEnvPreviewKey({
+ provider,
+ modelId: modelId.trim(),
+ clientType: envHintClientType(provider, clientType),
+ baseUrl,
+ });
+}
+
/*
* Failure classification used to live here, splitting "unreachable" from "the endpoint
* answered but serves none of the three". Removed deliberately (per maintainer): the
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index fc970381..47d5d9ec 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1255,7 +1255,7 @@ export const en: Strings = {
groupModeImport: "Import models",
groupImportAll: "Import all models",
groupImportNeedUrl: "Fill in a valid base URL first (http/https)",
- groupImportKeyHint: "Leave empty to read the protocol's OPENAI_* / ANTHROPIC_* env vars",
+ groupImportKeyHint: "The endpoint's API key (required unless the URL is the vendor's own)",
groupImportListing: "Fetching model list…",
groupImportSaving: (n: number): string => `Importing ${n} models…`,
groupImportUnsupported: "This protocol cannot list models — add them manually",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 4137ae53..20ef9f38 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1286,7 +1286,7 @@ export const zh = {
groupModeImport: "导入模型",
groupImportAll: "批量导入模型",
groupImportNeedUrl: "请先填写有效的 base URL(http/https)",
- groupImportKeyHint: "留空按协议读取 OPENAI_* / ANTHROPIC_* 环境变量",
+ groupImportKeyHint: "该端点的 API key(URL 不是厂商官方地址时必填)",
groupImportListing: "正在获取模型列表…",
groupImportSaving: (n: number): string => `正在导入 ${n} 个模型…`,
groupImportUnsupported: "该协议不支持列出模型,请手动添加",
diff --git a/packages/web/test/protocol-detect.test.ts b/packages/web/test/protocol-detect.test.ts
index ef7e8ee4..ed8aafe3 100644
--- a/packages/web/test/protocol-detect.test.ts
+++ b/packages/web/test/protocol-detect.test.ts
@@ -7,7 +7,11 @@
* composes.
*/
import { describe, expect, it } from "vitest";
-import { resolveModelEnv } from "@prismshadow/penguin-core/model-catalog";
+import {
+ MODEL_CATALOG,
+ modelEnvPreviewKey,
+ resolveModelEnv,
+} from "@prismshadow/penguin-core/model-catalog";
import { zh as ZH } from "../src/lib/strings";
import { en as EN } from "../src/lib/strings-en";
import { clientTypeAfterProviderChange, rowToEntry } from "../src/features/models/models-page";
@@ -17,6 +21,7 @@ import {
detectableBaseUrl,
displayWidthCh,
envHintClientType,
+ envHintKeyFor,
isCustomLikeGroup,
isGenericProtocolClientType,
needsProtocolDetectOnSave,
@@ -180,6 +185,96 @@ describe("envHintClientType (custom groups never infer a client from the model i
});
});
+describe("envHintKeyFor (the API-key field promises a variable only where the entry may fall back to it)", () => {
+ it("names nothing for a gateway row: its preset endpoint is not the vendor's, so the vendor key is not its key", () => {
+ // The #786 finding: once an Anthropic row had proved OPENAI_API_KEY / ANTHROPIC_API_KEY
+ // set, a TokenDance or OpenCode Go row read "leave empty to use the ... env var".
+ expect(
+ envHintKeyFor("tokendance", "glm-5.3", "openai-chat", "https://tokendance.space/gateway/v1"),
+ ).toBeUndefined();
+ expect(
+ envHintKeyFor(
+ "openrouter",
+ "openai/gpt-5.5",
+ "openai-responses",
+ "https://openrouter.ai/api/v1",
+ ),
+ ).toBeUndefined();
+ expect(
+ envHintKeyFor("custom", "claude-sonnet-5", "ant-messages", "https://gw.example.com"),
+ ).toBeUndefined();
+ expect(envHintKeyFor("vllm", "Qwen/Qwen3.8-27B", "", "http://gpu-box:8000/v1")).toBeUndefined();
+ expect(
+ envHintKeyFor("my-group", "some-model", "", "https://gw.example.com/v1"),
+ ).toBeUndefined();
+ });
+
+ it("names the vendor's variable for a first-party row, and the relay's own for Penguin Go", () => {
+ expect(envHintKeyFor("anthropic", "claude-sonnet-4-6", "", "")).toBe("ANTHROPIC_API_KEY");
+ expect(envHintKeyFor("google", "gemini-3.1-pro", "", "")).toBe("GEMINI_API_KEY");
+ expect(
+ envHintKeyFor("deepseek", "deepseek-flash", "deepseek-v4", "https://api.deepseek.com"),
+ ).toBe("DEEPSEEK_API_KEY");
+ // A custom row pointed at the vendor's own endpoint gets the vendor's key: it goes to the vendor.
+ expect(envHintKeyFor("custom", "gpt-5.6", "openai-chat", "https://api.openai.com/v1")).toBe(
+ "OPENAI_API_KEY",
+ );
+ expect(
+ envHintKeyFor(
+ "penguin-go",
+ "gemini-3.8-flash",
+ "gemini-3.8",
+ "https://token.penguin.ooo/api",
+ ),
+ ).toBe("PENGUIN_GO_API_KEY");
+ });
+
+ it("follows the base URL as it is edited: re-pointing a vendor row at a proxy drops the hint", () => {
+ expect(
+ envHintKeyFor("anthropic", "claude-sonnet-4-6", "", "https://proxy.example/anthropic"),
+ ).toBeUndefined();
+ expect(envHintKeyFor("anthropic", "claude-sonnet-4-6", "", "https://api.anthropic.com/")).toBe(
+ "ANTHROPIC_API_KEY",
+ );
+ });
+
+ it("promises nothing for a keyless vLLM preset or custom row with no base URL, and agrees with the server's preview rule", () => {
+ // The vLLM presets ship with no base URL; the server refuses them a masked preview for the
+ // same reason the field must not read "leave empty to use OPENAI_API_KEY": a self-hosted
+ // id would be run against api.openai.com. Both sides read core's modelEnvPreviewKey.
+ const cases: Array<[string, string, string, string]> = [
+ ...MODEL_CATALOG.filter((m) => m.provider === "vllm").map(
+ (m): [string, string, string, string] => [
+ m.provider,
+ m.modelId,
+ m.clientType ?? "",
+ m.baseUrl ?? "",
+ ],
+ ),
+ ["custom", "local-model", "openai-chat", ""],
+ ["custom", "gpt-5.6", "openai-chat", "https://api.openai.com/v1"],
+ ["anthropic", "claude-sonnet-4-6", "", ""],
+ ["anthropic", "claude-sonnet-4-6", "", "https://proxy.example/anthropic"],
+ ["tokendance", "glm-5.3", "openai-chat", "https://tokendance.space/gateway/v1"],
+ ["penguin-go", "gemini-3.8-flash", "gemini-3.8", "https://token.penguin.ooo/api"],
+ ];
+ for (const [provider, modelId, clientType, baseUrl] of cases) {
+ expect(envHintKeyFor(provider, modelId, clientType, baseUrl), `${provider}/${modelId}`).toBe(
+ modelEnvPreviewKey({
+ provider,
+ modelId,
+ clientType: envHintClientType(provider, clientType),
+ baseUrl,
+ }),
+ );
+ }
+ for (const m of MODEL_CATALOG.filter((v) => v.provider === "vllm")) {
+ expect(envHintKeyFor("vllm", m.modelId, "", ""), m.modelId).toBeUndefined();
+ }
+ expect(envHintKeyFor("custom", "local-model", "openai-chat", "")).toBeUndefined();
+ });
+});
+
describe("protocolForPersist (an empty protocol must never reach the config)", () => {
it("falls back to openai-chat for a custom-like entry that still has none", () => {
// AutoLLMClient THROWS on an unmatched client type, so persisting "" would save a
diff --git a/plugins/agent-development/plugin.json b/plugins/agent-development/plugin.json
index 59bcd1c2..6559449f 100644
--- a/plugins/agent-development/plugin.json
+++ b/plugins/agent-development/plugin.json
@@ -3,6 +3,6 @@
"description_zh": "基于 PenguinHarness 的智能体开发:用 SDK 构建应用、经统一的 LLM API 调用任意模型、管理模型与密钥、编排智能体/会话/成本/定时任务。",
"short_description": "SDK, unified LLM API, config and orchestration.",
"short_description_zh": "SDK、统一 LLM API、配置与编排。",
- "version": "2026.09.20.2",
+ "version": "2026.09.30.1",
"category": "ai-app-development"
}
diff --git a/plugins/agent-development/skills/penguin-sdk/SKILL.md b/plugins/agent-development/skills/penguin-sdk/SKILL.md
index db401f68..f4c807b5 100644
--- a/plugins/agent-development/skills/penguin-sdk/SKILL.md
+++ b/plugins/agent-development/skills/penguin-sdk/SKILL.md
@@ -52,7 +52,7 @@ If the package is not on your npm registry (it is developed in the PenguinHarnes
Configure a model for the app's data root, in this order — stop at the first that works:
1. `penguin config model add --root <data_dir> --provider <group> --model-id <id> --api-key <key> [--base-url <url>] [--client-type openai-chat] --set-default` — prefer `--client-type openai-chat --base-url <endpoint>` (works with any OpenAI Chat Completions compatible endpoint; exact ids in the agenthub-models skill). `--provider` is required: a model is always the `(provider, model_id)` pair and the group is never inferred from the id (`custom` for an endpoint outside the built-in groups).
-2. Environment variables cover the **credential only** (`DEEPSEEK_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, …) — model selection still comes from the project config, whose preset default is `deepseek-flash`. Env-only setup therefore works out of the box only with `DEEPSEEK_API_KEY`; for another vendor either run the CLI command above or pass a configured `{ provider, modelId }` pair to `createSession`.
+2. Environment variables cover the **credential only** (`DEEPSEEK_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, …), and only for an entry whose requests go to the **vendor's own endpoint** (no `--base-url`, or the vendor's official one) — an entry with a `--base-url` of its own (a gateway, a self-hosted server) needs `--api-key`, or `createSession` refuses it. Model selection still comes from the project config, whose preset default is `deepseek-flash`. Env-only setup therefore works out of the box only with `DEEPSEEK_API_KEY`; for another vendor either run the CLI command above or pass a configured `{ provider, modelId }` pair to `createSession`.
Keep model API keys **project-local**: configure them with the penguin CLI into the app's own data root under the working directory, so the project stays self-contained and movable. When building an AI app, **always pass `--root <data_dir>` pointing at the app's data directory inside the current working directory** (the same path you give `createAgent({ root })`, e.g. `./penguin_data`) — never run `penguin config ...` without `--root`, or it writes to the global `~/.penguin/data` instead of the project. Never read, copy or fall back to model keys stored in the user's global `~/.penguin` directory — that config belongs to the person running Penguin, not to the app you are building.