diff --git a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.i18n.yaml
index bbbf53a526..0be791a222 100644
--- a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.i18n.yaml
@@ -9,8 +9,8 @@
en: 6228c81e4965b688
zh: 04b702be0cfbf195
/agent-note-credential-boundaries-whole-snapshot-requests-and-atomic-route-registration/decision:
- en: 052787311a4e6edc
- zh: 963eed632ea198de
+ en: 3ecf963f99b8e9ae
+ zh: 84fa0bed2316ce94
/agent-note-credential-boundaries-whole-snapshot-requests-and-atomic-route-registration/alternatives-considered:
en: 90c5883b247f7301
zh: 6d2a660d8653f805
diff --git a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.md b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.md
index 03ea573307..f153f3afd4 100644
--- a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.md
+++ b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.md
@@ -18,7 +18,7 @@ Two request-path defects sat beside them. DeepSeek resolved connection and crede
**The stored credential has no boundary against the model, and the READMEs say so.** `0600` under a `0700` directory stops other OS users; the model's bash and filesystem tools run as that same user, and the shipped default confines nothing. What the harness does hold to is narrower and stated as exactly that: no surface hoists the document into `process.env`, and the model is never handed a resolved path to it, so reaching the value takes a deliberate read of a path it was not given. An OS-keychain provider — a store the model's processes cannot read at all — is recorded as the real answer rather than implied by a partial one.
-**One request, one generation.** DeepSeek's resolved snapshot carries the credential reference beside the endpoint, and `resolveApiKey` receives that snapshot instead of re-reading configuration. A rejected generation now contributes nothing at all. pi-ai defers to provider-native discovery only for a profile naming no credential; a configured reference that misses fails with `MISSING_CREDENTIAL` naming the route and the reference. The boot-time credential probe is deleted: it could run before the credentials service mounted and reported every failure as a missing key, while the first request already gives the accurate error.
+**One request, one generation.** DeepSeek's resolved snapshot carries the credential reference beside the endpoint, and the API-key route's `resolveAuth` hands that snapshot's endpoint and reference to `ctx.deepseekAuth` instead of re-reading configuration. A rejected generation now contributes nothing at all. pi-ai defers to provider-native discovery only for a profile naming no credential; a configured reference that misses fails with `MISSING_CREDENTIAL` naming the route and the reference. The boot-time credential probe is deleted: it could run before the credentials service mounted and reported every failure as a missing key, while the first request already gives the accurate error.
**Route replacement is a registry operation, not a caller sequence.** `registerAdapter` returns a handle carrying `replace(providers)`: the candidate set is validated in full first (conflicts, names, provider metadata), then swapped in one synchronous section. A refused replacement leaves the previous routes registered and serving, and the caller's facts cache only advances after the registry actually holds the new set, so reverting to a working configuration re-applies. pi-ai's registration facts are sorted by provider, so a settings document that merely reorders its keys is no longer a route change.
diff --git a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.zh.md b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.zh.md
index 9f822b8bee..52a592660d 100644
--- a/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.zh.md
+++ b/.agents/notes/implemented/architecture/2026-07-30-credential-boundaries-and-atomic-registration.zh.md
@@ -22,7 +22,7 @@ Status: implemented
**存下的凭据对模型没有边界,而 README 就是这么写的。**`0700` 目录下的 `0600` 挡得住其他 OS 用户;模型的 bash 与文件系统工具正是以同一用户身份运行,而已交付的默认配置不提供任何约束。harness 真正守住的边界更窄,文档也严格按这一范围表述:没有任何一个面会把该文档提升进 `process.env`,模型也从不会拿到它的解析后路径,因此要拿到这个值,需要刻意去读一条并未交给它的路径。OS 钥匙串(keychain)提供方——一个模型的进程根本读不到的存储——被记录为真正的答案,而不是靠一个残缺的方案去暗示它。
-**一次请求,一代设置。**DeepSeek 解析出的快照在端点旁一并携带凭据引用,`resolveApiKey` 接收这份快照,而不再重新读取配置。被拒绝的那一代如今完全不再贡献任何东西。只有当一个 profile 完全没有点名凭据时,pi-ai 才交给提供方原生的发现流程;配置了引用却解析不到,就以 `MISSING_CREDENTIAL` 失败,并点名该路由与该引用。启动时的凭据探测被删除:它可能在凭据服务挂载之前就运行,并把每一种失败都报成密钥缺失,而第一次请求本就会给出准确的错误。
+**一次请求,一代设置。**DeepSeek 解析出的快照在端点旁一并携带凭据引用,API 密钥路由的 `resolveAuth` 把这份快照的端点和引用交给 `ctx.deepseekAuth`,而不再重新读取配置。被拒绝的那一代如今完全不再贡献任何东西。只有当一个 profile 完全没有点名凭据时,pi-ai 才交给提供方原生的发现流程;配置了引用却解析不到,就以 `MISSING_CREDENTIAL` 失败,并点名该路由与该引用。启动时的凭据探测被删除:它可能在凭据服务挂载之前就运行,并把每一种失败都报成密钥缺失,而第一次请求本就会给出准确的错误。
**路由替换是注册表的操作,不是调用方的一串步骤。**`registerAdapter` 返回一个携带 `replace(providers)` 的句柄:候选集合先被完整校验(冲突、名称、提供方元数据),再在一个同步区段内完成替换。被拒绝的替换会让先前的路由保持注册并继续服务,而调用方的事实缓存只有在注册表确实持有新集合之后才会推进,因此改回可用配置时会重新生效。pi-ai 的注册事实按提供方排序,因此仅仅调换键顺序的设置文档不再算作路由变更。
diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml
index 75d406fe23..e877a2ccc2 100644
--- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml
@@ -9,8 +9,8 @@
en: 8d4d00e33af763b2
zh: 61977c82d66ae9bf
/agent-note-account-provider-and-active-request-cancellation/decision:
- en: 6f5463ecf88c1435
- zh: 7c9e46f90c8ccffb
+ en: 383ef40d2ec7b6f1
+ zh: 2e9482475015b1ff
/agent-note-account-provider-and-active-request-cancellation/alternatives-considered:
en: 7ed93136cf11074a
zh: 1ee997e271e919ad
diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md
index 8ea62952ed..bb2f639601 100644
--- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md
+++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md
@@ -14,7 +14,7 @@ Selecting credentials from login state changes the billing identity of an existi
Account cancellation reads each running Agent’s latest `Session.requestContext()` instead of maintaining another provider field. This logged value remains through tools and retries and follows the next bound request. Idle Agents are excluded. During a new turn’s first preparation it can still name the previous turn’s account route, so sign-out can also interrupt an API-key turn that has not bound its new request yet. A missing account credential rejects a first request without a previous context before transport.
-Successful local sign-out publishes an account event. The account route plugin installs a listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. It registers the same predicate with the account service as the running-task report behind sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. Requests this listener cannot reach end through the withdrawal signal of their credential, which the [route credential decision](2026-11-10-llm-route-credential-seam.md) owns.
+Successful local sign-out publishes an account event. The account route plugin installs a listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. It registers the same predicate with the account service as the running-task report behind sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. Requests this listener cannot reach end through the withdrawal signal of their credential, which the [DeepSeek request authentication decision](2026-11-10-deepseek-request-authentication.md) owns.
## Alternatives considered
diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md
index 2fc0872a4b..1cfd3c435b 100644
--- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md
+++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md
@@ -14,7 +14,7 @@ Status: implemented
账号取消读取运行中 Agent 最近的 `Session.requestContext()`,不维护额外提供方字段。该已记录值在工具和重试阶段保留,随下一次绑定请求更新;空闲 Agent 不计入。新轮次首次准备期间,它仍可能指向上一轮的账号路由,因此退登也可能打断尚未绑定新请求的 API key 轮次。没有历史上下文的首请求若缺少账号凭据,会在传输前失败。
-本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的撤回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。
+本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的撤回信号结束,这一信号由 [DeepSeek 请求鉴权决策](2026-11-10-deepseek-request-authentication.zh.md)负责。
## Alternatives considered
diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml
index 24af686ace..6bcaf5bb56 100644
--- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml
@@ -9,8 +9,8 @@
en: 32ba2b2b42e8deb5
zh: 6a6532561f81b8e2
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/decision:
- en: 023c6db0af5f9424
- zh: 7bdf40c49e381ee3
+ en: 9bf594047ad5c864
+ zh: 366263d56f8a4fbf
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered:
en: 6da221f6b821ea44
zh: b15774011abed7ed
diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md
index 72b06f6f77..cbf8b2a4d9 100644
--- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md
+++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md
@@ -13,7 +13,7 @@ English | [中文](2026-09-27-web-search-offered-by-provider-readiness.zh.md)
Each role of the web capability seam owns one part of a per-step check:
- **Service Definition.** `WebSearchProvider` and `WebFetchProvider` have an optional `ready(llmProvider)` that answers whether an operation made for a model request on that chat route has a credential to send. It checks configuration only and makes no network calls. `ctx.web.searchReady(llmProvider?)` and `ctx.web.fetchReady(llmProvider?)` resolve the provider with the same rules as `search()` and `fetch()` and return its answer. A provider without `ready()` counts as ready, and a selection failure answers true because the operation reports that failure as a structured `WebError`.
-- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.providerCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section.
+- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, in a conversation on the account route, whether `ctx.deepseekAuth` has the account sign-in configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, the account sign-in configured for the endpoint under that route's origin counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); `ctx.deepseekAuth` performs these checks, a key's through the reference helpers of `dsh-credentials`. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section.
- **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` with [step activation conditions](../../../../packages/core/tools/README.md#conditional-tools) that ask `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route of the step's model selection. The agent loop resolves conditions before it assembles the step, so the declared tools, the `tool:web_search` and `tool:web_fetch` prompt sections, PTC program bindings, and dispatch all read the same admitted set.
The route decides only whether the account token is checked before the API key, which happens on the `deepseek-account` route; an API key counts on every route, so a conversation on another provider's model is offered the DeepSeek web tools whenever a DeepSeek key is configured. A Search or Fetch API capability with its own YAML fields ignores the route and is ready exactly when its own key is configured.
diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md
index 0712cacc50..29e5b96e2e 100644
--- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md
+++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md
@@ -13,7 +13,7 @@ Status: implemented
web 能力 seam 的每个角色各负责逐步骤检查的一部分:
- **Service Definition。** `WebSearchProvider` 与 `WebFetchProvider` 有一个可选的 `ready(llmProvider)`,回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。它只检查配置,不发起网络调用。`ctx.web.searchReady(llmProvider?)` 与 `ctx.web.fetchReady(llmProvider?)` 按与 `search()`、`fetch()` 相同的规则解析提供方并返回其回答。没有 `ready()` 的提供方视为就绪;选择失败时回答 true,因为对应操作会把该失败报告为结构化 `WebError`。
-- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.providerCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。
+- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在账号路由上的会话里检查 `ctx.deepseekAuth` 是否已为其 Messages 端点配置账号登录凭据,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,为该路由 origin 之下的端点配置的账号登录凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `ctx.deepseekAuth` 执行,其中密钥的检查经由 `dsh-credentials` 的引用函数。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。
- **Consumer。** `dsh-tool-web` 注册 `web_search` 与 `web_fetch` 时各带一个[步骤激活条件](../../../../packages/core/tools/README.zh.md#conditional-tools),以该步骤模型选择的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`。agent loop 在组装该步骤之前解析各条件,因此声明的工具、`tool:web_search` 与 `tool:web_fetch` 提示词段落、PTC 程序绑定与派发都读取同一个准入集合。
路由只决定是否先检查账号 token 再检查 API 密钥,这发生在 `deepseek-account` 路由上;API 密钥在每条路由上都算数,因此只要配置了 DeepSeek 密钥,使用其他提供方模型的对话也会获得 DeepSeek Web 工具。在 YAML 中设置了单独字段的 Search 或 Fetch API 能力不看路由,恰在其自身密钥已配置时就绪。
diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml
index 9c22957426..5c0fef0e12 100644
--- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml
@@ -18,8 +18,8 @@
en: 9d68ffca5c8be681
zh: 36bb661f98de0ebb
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/credential-resolution:
- en: aa5522b172d2c580
- zh: 04561ffe78d69ff4
+ en: dca56d7ced4e5294
+ zh: e984a7fddac3228f
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections:
en: 5fcd3319fbceed1d
zh: 20771646b9c36fa6
diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md
index 3d11c29843..9c903db910 100644
--- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md
+++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md
@@ -30,11 +30,11 @@ The Search and Fetch APIs read one `web-deepseek-api` namespace, and each resolv
Each of Search and Fetch has a billing setting, `web-deepseek-api.searchBilling` or `fetchBilling`, which the settings page edits as a **Billing** menu under the selected API. The default, `auto`, follows the DeepSeek credential of the conversation; `account` sends only the signed-in account's token and `api-key` only the API key, without falling back to the other. The conversation's route is the `provider` of the initiating Session's latest request context, which account sign-out also reads; `ready()` uses the route of the model request being prepared, so readiness and execution resolve the same plan.
-The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.providerCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint.
+The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route connects to `ctx.deepseekAuth`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key of the mounted `deepseek-official` route, read under that route's `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two mounted DeepSeek routes, which includes either DeepSeek route id while its plugin is not mounted, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the mounted `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint.
A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`fetchBaseURL` or `fetchApiKeyEnv` for Fetch) instead, whatever its billing, always sends the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) to its `*BaseURL` (the official base when unset) and never the account token, so an intranet or third-party endpoint receives only the key chosen for it. Each capability has its own fields because a deployment can serve search and fetch from different gateways. These fields are YAML-only, and an empty value counts as unset. Stored values of fields outside the schema, including `baseURL`, `apiKeyEnv`, and `apiKey`, load without schema errors and have no effect.
-The DeepSeek model routes publish the credential they send through `ctx.llm.providerCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key.
+`ctx.deepseekAuth` orders and releases these credentials ([DeepSeek request authentication](2026-11-10-deepseek-request-authentication.md)): each DeepSeek model route connects the deployment its settings name, the API-key route with its key reference under `apiKeyEnv`, and the account sign-in is the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs ask that service instead of reading provider configuration, and it reads route keys, `DEEPSEEK_API_KEY`, and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose authorization offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key.
### Defaults and stored selections
diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md
index cb3c0e67c0..ae7f79c9cb 100644
--- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md
+++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md
@@ -30,11 +30,11 @@ Search 与 Fetch API 读取同一个 `web-deepseek-api` namespace,并各自解
Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling` 或 `fetchBilling`,设置页在选中的 API 下方以**计费方式**下拉框编辑它。默认值 `auto` 跟随会话的 DeepSeek 凭据;`account` 只发送已登录账号的令牌,`api-key` 只发送 API 密钥,都不回退到另一种凭据。会话的路由是发起会话最近一次请求上下文的 `provider`,账号退出登录读取的也是它;`ready()` 使用正在准备的模型请求的路由,因此就绪判断与执行解析出相同的方案。
-账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由通过 `ctx.llm.providerCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。
+账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由向 `ctx.deepseekAuth` 登记的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由的密钥(按该路由的 `apiKeyEnv` 读取,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个已挂载的 DeepSeek 路由之外的路由上(包括这两个路由 id 之一而其插件未挂载的情况)或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在已挂载的 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。
在 YAML 中设置了非空 `searchBaseURL` 或 `searchApiKeyEnv`(Fetch 为 `fetchBaseURL` 或 `fetchApiKeyEnv`)的能力,则无论计费方式如何,始终把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为官方基础地址),从不发送账号令牌,因此内网或第三方端点只收到为它选择的密钥。每个能力有自己的字段,因为一个部署可以由不同网关提供搜索和抓取。这些字段只能在 YAML 中设置,空值视为未设置。schema 之外字段的已保存值,包括 `baseURL`、`apiKeyEnv` 和 `apiKey`,可以加载而不产生 schema 错误,且不生效。
-DeepSeek 模型路由通过 `ctx.llm.providerCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。
+这些凭据由 `ctx.deepseekAuth` 排序并释放([DeepSeek 请求鉴权](2026-11-10-deepseek-request-authentication.zh.md)):每条 DeepSeek 模型路由登记其设置所指的部署,API 密钥路由同时登记其 `apiKeyEnv` 下的密钥引用,账号登录凭据则是 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 向该服务索取凭据而不读取提供方配置,该服务通过 `dsh-credentials` 的引用函数读取路由密钥、`DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。
### 默认值与已保存的选择
diff --git a/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.i18n.yaml
new file mode 100644
index 0000000000..c0667c2eef
--- /dev/null
+++ b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.i18n.yaml
@@ -0,0 +1,19 @@
+# Bilingual-pair consistency record for 2026-11-10-deepseek-request-authentication.md (docs/i18n/README.md): per heading
+# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
+# After editing either side, bring the other along and re-record with:
+# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md
+/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer:
+ en: 0ede9c11789e5fd7
+ zh: c3e552dfe6216df0
+/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/problem:
+ en: 1470ef8f922d447a
+ zh: ccd66a1b897c88e2
+/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/decision:
+ en: 316f5dc600e50f33
+ zh: f52cacf521e94159
+/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/alternatives-considered:
+ en: 3a4f69542b4a91b2
+ zh: 1eb4edce81a858d6
+/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/consequences:
+ en: 88174cd0c4fca1ee
+ zh: ae56350b8198a0b0
diff --git a/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md
new file mode 100644
index 0000000000..38eec99134
--- /dev/null
+++ b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md
@@ -0,0 +1,73 @@
+# Agent Note: DeepSeek request authentication - one service releases the API key or the account sign-in to every DeepSeek consumer
+
+Status: implemented
+
+English | [中文](2026-11-10-deepseek-request-authentication.zh.md)
+
+## Problem
+
+DeepSeek APIs accept two kinds of credential, an API key and the account sign-in, and each API accepts one or both: the Messages, Files, and model-listing requests of each model route carry one kind, Search and Fetch accept both, and DeepSeek adds account authentication to its other APIs one at a time. No package owned the choice between the two kinds. `@deepseek-ai/dsh-llm-deepseek`, the protocol transport, exported helpers that read `ctx.credentials`, the launch environment, and `ctx.deepseekAccount`, so the transport depended on both credential services although it only sends the headers a route gives it. The two route plugins resolved their credentials through those helpers and threw their own missing-credential failures from inside `resolveAuth`. The Search and Fetch API providers re-derived each route's base URL and key reference from the Loader entry of the route package with that package's own config resolver, ordered the two credentials by their billing setting, and rendered the request headers; Messages search hard-coded the account route id and applied an order of its own. Both web packages therefore depended on `llm-deepseek`, on both route plugins, and on the Loader, and a consumer of another DeepSeek API would have repeated the selection, the deployment binding, the header rendering, and the invalidation. The account service, which sits below every consumer, owned Agent cancellation after sign-out and lived in the `credentials/` group beside the credential store it only uses. A change to how one route authenticates touched the transport, both web providers, and their tests.
+
+## Decision
+
+`@deepseek-ai/dsh-deepseek-auth`, in the `packages/account/` group, provides `ctx.deepseekAuth`. The package holds the Service Definition and the Service Provider of DeepSeek request authentication, and every plugin that calls a DeepSeek API is a Consumer. A consumer describes one request: the credential kinds its API `accepts`, the `billing` its settings choose, the model `route` of the conversation, and a `destination`, either a path under the chosen kind's deployment or one absolute URL. `candidates(request)` returns the kinds in billing order, each bound to the endpoint its credential is sent to, and reads no credential. `authorize(request, signal)` releases the first kind that has a credential as a `DeepSeekAuthorization`: the `kind`, the `endpoint`, the request `headers`, the key `reference` for diagnostics, and for the account sign-in a `reject()` for HTTP 401 and a `revoked` signal that aborts when the account signs out. An authorization carries no bare credential value: a consumer names the headers an API key is sent in through `apiKeyHeaders`, and the account service chooses the header of the sign-in.
+
+The service owns the billing order. `api-key` and `account` billing try that kind only. `auto` follows the conversation: on the route a plugin connected for the account sign-in, the sign-in and then the API key; on the route a plugin connected for the API key, the API key; on any other route, or outside a conversation, the API key and then the sign-in. The service names no route id: each model route plugin passes the provider route it registers when it connects, and `routeKind(route)` answers the kind connected under that id. A conversation recorded on `deepseek-account` or `deepseek-official` whose plugin is not mounted is ordered as any other route. A kind outside `accepts` is never a candidate.
+
+Each kind has one deployment at a time. A model route plugin connects its provider route and the deployment its settings name with `connect(kind, route, connection)` inside `ctx.effect()`, and the service calls `connection` for each request. Without a connection the API key is `DEEPSEEK_API_KEY` at `https://api.deepseek.com`, and the sign-in goes to the origin `DEEPSEEK_BASE_URL` names, the official API by default. A credential is released only for a destination under the origin of its kind's deployment that embeds no credentials. A request can carry its own connection of a kind in `connections`, which replaces the connected or default one: a model route passes the configuration generation it captured for one model request, and a consumer with its own endpoint and key passes those. A kind whose connection does not resolve stays among the candidates as an unresolved entry, and `authorize()` stops there with `UNRESOLVED_CONNECTION` and does not try a later kind.
+
+The API key is read through `resolveCredentialRef` and `credentialRefConfigured` of `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one. `dsh-credentials` also owns `normalizeApiKey`, the Host definition of a key that an HTTP header can carry, which answers the trimmed key or the reason a key cannot be used and words no diagnostic. The service words the diagnostic of an unusable key and reports it as `DeepSeekAuthError` with code `INVALID_CREDENTIAL`, `llm-pi-ai` words its own and reports it as `LlmError`, and `@deepseek-ai/dsh-llm` holds neither a credential interface nor a key check. The account sign-in is what `ctx.deepseekAccount.resolveRequestCredential(endpoint)` releases; it is absent in a composition without the account service.
+
+`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the request headers, an optional `revoked` signal, and an optional failure callback, or `undefined`; `missingCredential(connection, provider)` names the failure of a request without a credential, `MISSING_CREDENTIAL` by default. The transport runs each model request and its file operations under the `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers.
+
+The route plugins are consumers that also connect their deployment, and both require the service. `llm-deepseek-api-key` connects, under its route id, its base URL, its `apiKeyEnv` reference, and its settings namespace as the owner that key diagnostics name; it asks for the key in `x-api-key` with `accepts: ['api-key']` and reports an unusable key as its own `INVALID_CREDENTIAL`. `llm-deepseek-account` connects its base URL under its route id, asks with `accepts: ['account']`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. A request in flight at sign-out ends with its authorization's `revoked` signal and fails as `ACCOUNT_SIGN_IN_REQUIRED`, and its failure callback cancels the same Agents, so a request that outlives the plugin still ends its turn with the signed-out cause.
+
+`@deepseek-ai/dsh-deepseek-account` releases request credentials to the authentication service. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the account service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The account service inspects no Agents and depends on neither `dsh-agent`, `dsh-llm`, nor the authentication service. The package lives in the `packages/account/` group under its unchanged name.
+
+The web providers declare what their APIs accept. `web-deepseek-api` asks for candidates with `accepts: ['account', 'api-key']`, the capability's billing, the conversation's route, and the path `/v1/tools/search` or `/v1/tools/fetch`; a capability with its own `*BaseURL` or `*ApiKeyEnv` asks with `accepts: ['api-key']` and its own connection, so only that key goes to that endpoint. `web-search-deepseek` passes its search endpoint as an absolute destination and its referenced key as its own connection. In a conversation on the connected account route it asks with `auto` billing, so the sign-in comes first when the search endpoint is under the origin of the account deployment; every other search asks with `api-key` billing. A literal `apiKey` is the provider's own credential: beside it the provider asks only for the sign-in, and sends the literal key when the service releases none. `web-deepseek-api` words its missing-credential and unresolved-settings failures from the candidates. Both web consumers contain a failed `reject()` so the HTTP rejection stays the reported error, run their request under the authorization's `revoked` signal, and report a request that signal ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, the Loader, or the account service, and neither reads a credential through `dsh-llm`: `web-search-deepseek` does not depend on it, and `web-deepseek-api` imports only the message text helper `extractTextContent` from it.
+
+## Alternatives considered
+
+**Publishing each route's credential through the model service.** `LlmAdapter.providerCredential(provider)` on `dsh-llm` would answer a route's credential kind, its base URL, and a grant for one endpoint, and consumers would read `ctx.llm.providerCredential('deepseek-official')` and `providerCredential('deepseek-account')`. A lookup keyed by model route leaves every consumer to order the two credentials by billing, to render its own headers from a bare value, and to fall back by itself when a route is not mounted. An API outside the model protocol, such as the speech and document APIs under `/v1/tools/`, has no route to ask and no place to declare the kinds it accepts. The model service would carry a credential interface with one publisher, the DeepSeek adapter, and two web consumers.
+
+**A shared library over that publication instead of a service.** The model routes authenticate through the same operation as every other consumer, and a library that reads what the routes publish cannot serve the routes themselves.
+
+**Checking keys through `dsh-llm`, through a copy in the service, or through a validator each consumer passes.** A service shared by every DeepSeek consumer must not depend on the model service, which is one consumer's dependency. A second Host copy of the rule would be kept in step with the first and with the browser's copy by comments only. A validator parameter would make each consumer that accepts a key pass one, and the web packages would keep their `dsh-llm` dependency for it. The check lives in `dsh-credentials`, the layer that reads the key, and each caller words its own failure for the reason the check returns.
+
+**The diagnostic text of an unusable key in `dsh-credentials`.** One function there would give the service and `llm-pi-ai` the same words. The text tells the user to set the reference on the Models page, so the package that stores credentials would name a page of its consumers. Each of the two callers words the text, and the credential store names no consumer.
+
+**`dsh-llm` importing the key check from `dsh-credentials`.** Nothing in the model service reads a key. Its only caller of the check was `llm-pi-ai`, which already depends on `dsh-credentials`, so the model service exports no key check and gains no dependency.
+
+**A `deepseek-api-key` package beside `deepseek-account`.** `deepseek-account` is the account product feature: browser sign-in, the stored grant, profile, balance, notifications, and the Platform session, of which releasing a request credential is a small part. The API key has no such feature. It is a named string in the generic credential store, and its DeepSeek-specific logic is the key source inside the service. A package becomes worthwhile when DeepSeek-specific key behavior appears, such as a balance per key, server-side validation, or several keys.
+
+**Merging the two model route plugins, or their route ids.** They are two model providers with different settings and catalog sources, the `ACCOUNT_*` failure mapping, and the sign-out policy over running tasks. The route id is the durable record of how a conversation is billed: Session logs carry it, and sign-out cancellation and `auto` billing read it.
+
+**A fixed table of the two DeepSeek route ids in the service.** `routeKind()` would answer for `deepseek-account` and `deepseek-official` whichever plugins are mounted, and a conversation recorded on the account route would try only the API key while the account route plugin is not mounted. The table would put the route ids of two consumers into the service those consumers depend on. Each route plugin passes its own id when it connects, and a route id whose plugin is not mounted is ordered as any other route.
+
+**Route plugins that work without the service.** An optional service would leave compositions and tests that mount a route by hand unchanged, but each route would keep a credential path that bypasses the service.
+
+**One billing order for every consumer.** Messages search outside an account conversation never tries the sign-in. Giving it the general order would change which credential existing conversations send, so the rule stays.
+
+**A credential fingerprint in the authorization.** Consumers only send requests, so they need headers; cache scoping by credential is the adapter's own concern, which the listing cache meets by hashing the headers it sends.
+
+**A `credentials-env` provider instead of reference helpers.** A provider that reads the environment would change which composition is authoritative for every consumer; the helpers keep the launch-environment fallback local to the consumers that need it, so such a provider remains an independent option.
+
+**The account service's inference origin for the sign-in without a connected account route.** Routing that default through `DEEPSEEK_BASE_URL` keeps the keyless billing snapshot and every documented deployment unchanged; the account service still refuses every origin but its own.
+
+**Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own.
+
+**Keeping the route plugin's sign-out listener until its tasks end.** Unloading the route then waits for a running turn: disabling the plugin blocks, and every other settings write queues behind that reload, for as long as the turn runs.
+
+**Cancelling the route's tasks when the route unloads.** A configuration reload or a plugin update would stop turns that no sign-out touched.
+
+**Returning the sign-out policy to the account service.** The service would again inspect Agents and know route ids, the dependencies this decision removes.
+
+**Keeping the route's listener or report registered after its plugin unloads.** A registration that outlives the plugin that made it breaks the rule that registrations are effects of their owner, and leaves code of an unloaded plugin running in another scope for as long as the task runs.
+
+## Consequences
+
+A consumer of another DeepSeek API declares the kinds that API accepts; it reads no credential, renders no header, and holds no fallback. When an API gains a kind, its consumer widens `accepts`. A new credential kind is a source in the service and a member of `DeepSeekAuthKind`. The transport, the model service, the web providers, and the account service do not depend on one another for credentials, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. The `llm-deepseek` credential helpers and the route plugins' config exports do not exist; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.md) lists the replacements.
+
+Every composition that mounts a DeepSeek model route or a DeepSeek web provider mounts the service; without it those plugins wait and register nothing. The `base` and `sdk-minimal` bundles carry its row, and the SDK server mounts it with its fallback route when the composition has none. One deployment per kind means a second `connect()` of a kind throws `DUPLICATE_CONNECTION`. `auto` billing recognizes a route only while the plugin that registers it is connected: a conversation recorded on `deepseek-account` or `deepseek-official` whose plugin is not mounted, and a DeepSeek model reached through another provider plugin, are ordered as any other route, so their Search and Fetch operations send the API key and, without a key, the account sign-in. A route's configuration failure reaches consumers as an unresolved candidate: the Search and Fetch APIs report it as `WEB_PROVIDER_MISCONFIGURED`, Messages search as `WEB_PROVIDER_ERROR`, and neither tries a later credential. An unusable key reaches a web tool's result under the error name `DeepSeekAuthError`.
+
+A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns.
diff --git a/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.zh.md b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.zh.md
new file mode 100644
index 0000000000..4f50ab93de
--- /dev/null
+++ b/.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.zh.md
@@ -0,0 +1,73 @@
+# Agent Note: DeepSeek request authentication - one service releases the API key or the account sign-in to every DeepSeek consumer
+
+Status: implemented
+
+[English](2026-11-10-deepseek-request-authentication.md) | 中文
+
+## 问题
+
+DeepSeek 的 API 接受两种凭据:API 密钥和账号登录。每个 API 接受其中一种或两种:每条模型路由的 Messages、Files 和模型列表请求只带一种,Search 与 Fetch 两种都接受,DeepSeek 还在逐个为其他 API 增加账号鉴权。在两种凭据之间做选择这件事没有所有者。协议传输层 `@deepseek-ai/dsh-llm-deepseek` 导出读取 `ctx.credentials`、启动环境和 `ctx.deepseekAccount` 的辅助函数,因此尽管传输层只发送路由交给它的请求头,它仍依赖两个凭据服务。两个路由插件通过这些函数解析凭据,并在 `resolveAuth` 内部抛出各自的凭据缺失错误。Search 与 Fetch API 提供方用路由包自己的配置解析函数,从路由包的 Loader 条目重新推导每条路由的基础地址和密钥引用,按自己的计费设置排定两种凭据的顺序,并自己组装请求头;Messages 搜索则硬编码账号路由 id,并使用自己的一套顺序。因此两个 Web 包都依赖 `llm-deepseek`、两个路由插件和 Loader,而其他 DeepSeek API 的消费方还得把选择凭据、绑定部署、组装请求头和作废凭据再做一遍。位于所有消费方之下的账号服务拥有退登后的 Agent 取消逻辑,并和它仅仅使用的凭据库一起放在 `credentials/` 组。改变一条路由的鉴权方式要同时触及传输层、两个 Web 提供方及其测试。
+
+## 决策
+
+位于 `packages/account/` 组的 `@deepseek-ai/dsh-deepseek-auth` 提供 `ctx.deepseekAuth`。该包同时承担 DeepSeek 请求鉴权的 Service Definition 和 Service Provider,每个调用 DeepSeek API 的插件都是 Consumer。消费方描述一次请求:它的 API 接受的凭据种类 `accepts`、其设置选择的计费方式 `billing`、会话的模型路由 `route`,以及目的地 `destination`,即所选种类的部署之下的一个路径,或一个绝对 URL。`candidates(request)` 按计费顺序返回各个种类,每个种类都绑定到其凭据发往的端点,且不读取任何凭据。`authorize(request, signal)` 把第一个持有凭据的种类释放为 `DeepSeekAuthorization`:`kind`、`endpoint`、请求 `headers`、供诊断使用的密钥 `reference`,账号登录还带有用于 HTTP 401 的 `reject()` 和在账号退登时中止的 `revoked` 信号。授权不携带裸的凭据值:消费方通过 `apiKeyHeaders` 指定 API 密钥放进哪些请求头,账号登录的请求头由账号服务决定。
+
+计费顺序由该服务拥有。`api-key` 与 `account` 计费只尝试对应的那一种。`auto` 跟随会话:在某个插件为账号登录登记的路由上先尝试账号登录、再尝试 API 密钥;在某个插件为 API 密钥登记的路由上只尝试 API 密钥;在其他路由上或不在会话中时,先尝试 API 密钥、再尝试账号登录。该服务自身不写任何路由 id:每个模型路由插件在登记时传入它注册的提供方路由,`routeKind(route)` 回答在该 id 下登记的种类。记录在 `deepseek-account` 或 `deepseek-official` 上的会话,在对应插件未挂载时按其他路由处理。不在 `accepts` 中的种类永远不会成为候选。
+
+每个种类同一时间只有一个部署。模型路由插件在 `ctx.effect()` 内用 `connect(kind, route, connection)` 登记自己的提供方路由及其设置所指的部署,服务为每个请求调用 `connection`。没有登记时,API 密钥是发往 `https://api.deepseek.com` 的 `DEEPSEEK_API_KEY`,账号登录发往 `DEEPSEEK_BASE_URL` 所指的 origin,默认为官方 API。凭据只释放给其种类的部署 origin 之下且不内嵌凭据的目的地。请求可以在 `connections` 里携带某一种类自己的连接,它取代已登记的或默认的连接:模型路由传入它为一次模型请求捕获的那一代配置,拥有自己端点和密钥的消费方传入这两项。连接无法解析的种类作为未解析条目留在候选中,`authorize()` 在此以 `UNRESOLVED_CONNECTION` 停止,不再尝试后面的种类。
+
+API 密钥通过 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境。`dsh-credentials` 还拥有 `normalizeApiKey`,即 Host 端对“能放进 HTTP 请求头的密钥”的定义:它回答去掉首尾空白后的密钥,或密钥不可用的原因,不生成任何诊断文案。该服务为不可用的密钥写出诊断文案,并将其报告为代码 `INVALID_CREDENTIAL` 的 `DeepSeekAuthError`,`llm-pi-ai` 写出自己的文案并报告为 `LlmError`,`@deepseek-ai/dsh-llm` 既不带凭据接口也不带密钥检查。账号登录就是 `ctx.deepseekAccount.resolveRequestCredential(endpoint)` 释放的凭据;组合中没有账号服务时不存在这种凭据。
+
+`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回请求头、可选的 `revoked` 信号和可选的失败回调,或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。传输层让每次模型请求及其文件操作受 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。
+
+路由插件是同时登记自身部署的消费方,二者都要求该服务已挂载。`llm-deepseek-api-key` 在自己的路由 id 下登记其基础地址、`apiKeyEnv` 引用,以及作为密钥诊断所指属主的设置命名空间;它以 `accepts: ['api-key']` 索取放在 `x-api-key` 里的密钥,并把不可用的密钥报告为自己的 `INVALID_CREDENTIAL`。`llm-deepseek-account` 在自己的路由 id 下登记其基础地址,以 `accepts: ['account']` 索取凭据,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。退登时在途的请求随其授权的 `revoked` 信号结束,以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;它的失败回调会取消同一批 Agent,因此比插件存活更久的请求仍会以退登原因结束其回合。
+
+`@deepseek-ai/dsh-deepseek-account` 向鉴权服务释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、`reject()` 和 `revoked` 信号;`reject()` 仅在已存储的授权记录仍一致时删除它并隔离存储失败,`revoked` 由账号服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。账号服务不检查任何 Agent,也不依赖 `dsh-agent`、`dsh-llm` 或鉴权服务。包以不变的名字位于 `packages/account/` 组。
+
+Web 提供方声明各自的 API 接受什么。`web-deepseek-api` 以 `accepts: ['account', 'api-key']`、该能力的计费设置、会话的路由,以及路径 `/v1/tools/search` 或 `/v1/tools/fetch` 索取候选;设置了自己的 `*BaseURL` 或 `*ApiKeyEnv` 的能力以 `accepts: ['api-key']` 和自己的连接索取,因此发往该端点的只有那把密钥。`web-search-deepseek` 把搜索端点作为绝对目的地传入,把它引用的密钥作为自己的连接传入。在已登记的账号路由上的会话里,它以 `auto` 计费索取,因此当搜索端点位于账号部署的 origin 之下时先尝试账号登录;其他搜索都以 `api-key` 计费索取。字面 `apiKey` 是该提供方自己的凭据:有它时提供方只索取账号登录,服务不释放任何凭据时发送字面密钥。`web-deepseek-api` 依据候选来措辞凭据缺失和设置无法解析的失败。两个 Web 消费方都隔离失败的 `reject()` 以保证报告的是 HTTP 拒绝,都让请求受授权的 `revoked` 信号约束,并把被该信号结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不依赖 `llm-deepseek`、路由插件、Loader 或账号服务,也都不经 `dsh-llm` 读取凭据:`web-search-deepseek` 不依赖它,`web-deepseek-api` 只从它导入消息文本辅助函数 `extractTextContent`。
+
+## 考虑过的替代方案
+
+**通过模型服务发布每条路由的凭据。** `dsh-llm` 上的 `LlmAdapter.providerCredential(provider)` 回答一条路由的凭据种类、基础地址和面向某个端点的授权,消费方读取 `ctx.llm.providerCredential('deepseek-official')` 和 `providerCredential('deepseek-account')`。按模型路由查询意味着每个消费方都要自己按计费排定两种凭据的顺序、自己用裸值组装请求头,并在路由未挂载时自己回退。模型协议之外的 API,例如 `/v1/tools/` 下的语音和文档 API,既没有可以询问的路由,也没有地方声明它接受哪些种类。模型服务还要带上一个凭据接口,而它只有 DeepSeek 适配器一个发布方和两个 Web 消费方。
+
+**在上述发布之上用公共库代替服务。** 模型路由与其他消费方通过同一个操作鉴权,而读取路由所发布内容的库无法反过来为路由本身服务。
+
+**通过 `dsh-llm` 检查密钥、在服务里保留一份副本,或由每个消费方传入校验函数。** 所有 DeepSeek 消费方共用的服务不能依赖模型服务,后者只是其中一类消费方的依赖。Host 端的第二份规则只能靠注释与第一份以及浏览器端的那份保持一致。校验函数参数会让每个接受密钥的消费方都传一个,两个 Web 包也要为此继续依赖 `dsh-llm`。检查放在读取密钥的那一层 `dsh-credentials`,每个调用方依据检查返回的原因写出自己的失败。
+
+**把不可用密钥的诊断文案放在 `dsh-credentials`。** 那里的一个函数能让该服务和 `llm-pi-ai` 使用同样的措辞。但文案要告诉用户在 Models 页面设置该引用,存储凭据的包就会写出其消费方的页面。两个调用方各自写出文案,凭据存储不写任何消费方的名字。
+
+**让 `dsh-llm` 从 `dsh-credentials` 导入密钥检查。** 模型服务里没有任何代码读取密钥。该检查在其中唯一的调用方是 `llm-pi-ai`,而它已经依赖 `dsh-credentials`,因此模型服务不导出密钥检查,也不新增依赖。
+
+**在 `deepseek-account` 旁边设一个 `deepseek-api-key` 包。** `deepseek-account` 是账号这项产品功能:浏览器登录、已存储的授权、资料、余额、通知和 Platform 会话,释放请求凭据只占其中一小部分。API 密钥没有这样的功能。它是通用凭据库里一个有名字的字符串,它的 DeepSeek 专属逻辑就是服务内部的密钥来源。等到出现 DeepSeek 专属的密钥行为,例如按密钥查余额、向服务端校验或多把密钥,才值得拆出一个包。
+
+**合并两个模型路由插件,或合并它们的路由 id。** 它们是两个模型提供方,设置和目录来源不同,还各有 `ACCOUNT_*` 失败映射和针对运行中任务的退登策略。路由 id 是一段会话如何计费的持久记录:会话日志携带它,退登取消和 `auto` 计费读取它。
+
+**在服务里放一张含两个 DeepSeek 路由 id 的固定表。** 无论挂载了哪些插件,`routeKind()` 都会为 `deepseek-account` 和 `deepseek-official` 作答,记录在账号路由上的会话在账号路由插件未挂载时只尝试 API 密钥。这张表会把两个消费方的路由 id 写进它们所依赖的服务。每个路由插件在登记时传入自己的 id,插件未挂载的路由 id 按其他路由处理。
+
+**让路由插件在没有该服务时也能工作。** 把服务做成可选依赖可以让手工挂载路由的组合和测试保持不变,但每条路由都要保留一条绕过该服务的取凭据路径。
+
+**让所有消费方使用同一套计费顺序。** Messages 搜索在账号会话之外从不尝试账号登录。让它采用通用顺序会改变现有会话发送的凭据,因此这条规则保留。
+
+**在授权中加入凭据指纹。** 消费方只负责发送请求,因此只需要请求头;按凭据划分缓存作用域是适配器自己的事,列表缓存通过哈希它发送的请求头即可满足。
+
+**用 `credentials-env` 提供方代替引用函数。** 读取环境的提供方会改变每个消费方眼中哪个组合具有权威性;引用函数把启动环境后备保留在需要它的消费方本地,使这样的提供方仍是独立的选项。
+
+**没有登记账号路由时,账号登录使用账号服务的推理 origin。** 让该默认值经由 `DEEPSEEK_BASE_URL` 可保持无密钥计费快照和所有已记录部署不变;账号服务仍拒绝除自身 origin 以外的一切来源。
+
+**把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。
+
+**让路由插件的退登监听保留到其任务结束。** 这样卸载路由要等待运行中的回合:停用插件会被阻塞,其他设置写入也排在这次重载之后,直到回合结束。
+
+**路由卸载时取消其任务。** 配置重载或插件更新会停掉与退登无关的回合。
+
+**把退登策略放回账号服务。** 账号服务将重新检查 Agent 并认识路由 id,而这正是本决策去掉的依赖。
+
+**插件卸载后仍保留路由的监听或报告注册。** 比注册它的插件存活更久的注册违反“注册是其所有者的 effect”这一规则,并让已卸载插件的代码在任务运行期间留在其他作用域里。
+
+## 后果
+
+其他 DeepSeek API 的消费方只声明该 API 接受的种类;它不读取凭据、不组装请求头,也不保留回退逻辑。某个 API 新增一种凭据时,它的消费方扩充 `accepts`。新增凭据种类意味着在服务里加一个来源,并为 `DeepSeekAuthKind` 加一个成员。传输层、模型服务、Web 提供方和账号服务在凭据上互不依赖,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。`llm-deepseek` 的凭据辅助函数和路由插件的配置导出不复存在;[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.zh.md)列出了替代方案。
+
+凡是挂载 DeepSeek 模型路由或 DeepSeek Web 提供方的组合都要挂载该服务;没有它时这些插件一直等待,不注册任何东西。`base` 和 `sdk-minimal` 两个组合包带有它的条目,SDK 服务端在组合里没有它时随后备路由一起挂载它。每个种类一个部署意味着对同一种类第二次 `connect()` 会抛出 `DUPLICATE_CONNECTION`。`auto` 计费只在注册某条路由的插件已登记时才认它:记录在 `deepseek-account` 或 `deepseek-official` 上而对应插件未挂载的会话,以及经由其他提供方插件访问的 DeepSeek 模型,都按其他路由处理,因此它们的 Search 与 Fetch 操作发送 API 密钥,没有密钥时发送账号登录。路由的配置失败以未解析候选的形式到达消费方:Search 与 Fetch API 将其报告为 `WEB_PROVIDER_MISCONFIGURED`,Messages 搜索报告为 `WEB_PROVIDER_ERROR`,二者都不再尝试后面的凭据。不可用的密钥在 Web 工具的结果里以错误名 `DeepSeekAuthError` 出现。
+
+退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。
diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml
deleted file mode 100644
index a5d7ec13b7..0000000000
--- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml
+++ /dev/null
@@ -1,19 +0,0 @@
-# Bilingual-pair consistency record for 2026-11-10-llm-route-credential-seam.md (docs/i18n/README.md): per heading
-# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
-# After editing either side, bring the other along and re-record with:
-# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md
-/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse:
- en: d11883f28d5cdd99
- zh: 860795ae4d93c317
-/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/problem:
- en: 9665e1879893fe76
- zh: 9da30ad0be6fc38d
-/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision:
- en: aaa2d2c7202408d4
- zh: 134987da042fd07b
-/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered:
- en: d6b2de393add9887
- zh: b5351f9a49387bd6
-/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences:
- en: df942606f0d31fa5
- zh: cb1f21dd7f60ab7f
diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md
deleted file mode 100644
index c0544bdcfb..0000000000
--- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse
-
-Status: implemented
-
-English | [中文](2026-11-10-llm-route-credential-seam.zh.md)
-
-## Problem
-
-Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/dsh-llm-deepseek`, the protocol transport, exported helpers that read `ctx.credentials`, the launch environment, and `ctx.deepseekAccount`, so the transport depended on both credential services although it only sends the headers a route gives it. The two route plugins resolved their credentials through those helpers and threw their own missing-credential failures from inside `resolveAuth`. The Search and Fetch API providers re-derived each route's base URL and key reference from the Loader entry of the route package with that package's own config resolver, and Messages search hard-coded the account route id, so both web packages depended on `llm-deepseek`, on both route plugins, and on the Loader. The account service, which sits below every consumer, owned Agent cancellation after sign-out and lived in the `credentials/` group beside the credential store it only uses. A change to how one route authenticates touched the transport, both web providers, and their tests.
-
-## Decision
-
-`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.providerCredential(provider)` publishes a `ProviderCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `ProviderCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request.
-
-`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The transport runs each model request and its file operations under the grant's `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers.
-
-The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. A request in flight at sign-out ends with its grant's `revoked` signal and fails as `ACCOUNT_SIGN_IN_REQUIRED`, and its failure callback cancels the same Agents, so a request that outlives the plugin still ends its turn with the signed-out cause.
-
-`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name.
-
-The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.providerCredential('deepseek-official')` and `providerCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service.
-
-## Alternatives considered
-
-**A `deepseek-auth` package holding the credential seam.** The seam needs a Service Definition only, no Cordis service, and that one Definition role belongs beside `LlmAdapter`; a package for an interface adds a dependency without an owner of behavior.
-
-**A credential fingerprint in the published credential.** Consumers only send requests, so they need headers and a value; cache scoping by credential is the adapter's own concern, which the listing cache meets by hashing the headers it sends.
-
-**A `credentials-env` provider instead of reference helpers.** A provider that reads the environment would change which composition is authoritative for every consumer; the helpers keep the launch-environment fallback local to the consumers that need it, so such a provider remains an independent option.
-
-**The account service's inference origin for the web fallback without the account route.** Routing that fallback through `DEEPSEEK_BASE_URL` keeps the keyless billing snapshot and every documented deployment unchanged; the account service still refuses every origin but its own.
-
-**Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own.
-
-**Keeping the route plugin's sign-out listener until its tasks end.** Unloading the route then waits for a running turn: disabling the plugin blocks, and every other settings write queues behind that reload, for as long as the turn runs.
-
-**Cancelling the route's tasks when the route unloads.** A configuration reload or a plugin update would stop turns that no sign-out touched.
-
-**Returning the sign-out policy to the account service.** The service would again inspect Agents and know route ids, the dependencies this decision removes.
-
-**Keeping the route's listener or report registered after its plugin unloads.** A registration that outlives the plugin that made it breaks the rule that registrations are effects of their owner, and leaves code of an unloaded plugin running in another scope for as long as the task runs.
-
-## Consequences
-
-Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `providerCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`.
-
-A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns.
diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md
deleted file mode 100644
index 2282d44a68..0000000000
--- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse
-
-Status: implemented
-
-[English](2026-11-10-llm-route-credential-seam.md) | 中文
-
-## 问题
-
-多个包共用同一份 DeepSeek 凭据,却没有所有者。协议传输层 `@deepseek-ai/dsh-llm-deepseek` 导出读取 `ctx.credentials`、启动环境和 `ctx.deepseekAccount` 的辅助函数,因此尽管传输层只发送路由交给它的请求头,它仍依赖两个凭据服务。两个路由插件通过这些函数解析凭据,并在 `resolveAuth` 内部抛出各自的凭据缺失错误。Search 与 Fetch API 提供方用路由包自己的配置解析函数,从路由包的 Loader 条目重新推导每条路由的基础地址和密钥引用,Messages 搜索则硬编码账号路由 id,因此两个 Web 包都依赖 `llm-deepseek`、两个路由插件和 Loader。位于所有消费方之下的账号服务拥有退登后的 Agent 取消逻辑,并和它仅仅使用的凭据库一起放在 `credentials/` 组。改变一条路由的鉴权方式要同时触及传输层、两个 Web 提供方及其测试。
-
-## 决策
-
-`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.providerCredential(provider)` 发布一个 `ProviderCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `ProviderCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。
-
-`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。
-
-路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。退登时在途的请求随其授权的 `revoked` 信号结束,以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;它的失败回调会取消同一批 Agent,因此比插件存活更久的请求仍会以退登原因结束其回合。
-
-`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token、`reject()` 和 `revoked` 信号;`reject()` 仅在授权仍一致时删除它并隔离存储失败,`revoked` 由服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。
-
-Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.providerCredential('deepseek-official')` 和 `providerCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。
-
-## 考虑过的替代方案
-
-**用一个 `deepseek-auth` 包承载凭据 seam。** 该 seam 只需要 Service Definition,不需要 Cordis 服务,而这一个 Definition 角色应与 `LlmAdapter` 放在一起;为一个接口建包只会增加一个没有行为所有者的依赖。
-
-**在发布的凭据中加入凭据指纹。** 消费方只负责发送请求,因此只需要请求头和值;按凭据划分缓存作用域是适配器自己的事,列表缓存通过哈希它发送的请求头即可满足。
-
-**用 `credentials-env` 提供方代替引用函数。** 读取环境的提供方会改变每个消费方眼中哪个组合具有权威性;引用函数把启动环境后备保留在需要它的消费方本地,使这样的提供方仍是独立的选项。
-
-**没有账号路由时的 Web 后备使用账号服务的推理 origin。** 让该后备经由 `DEEPSEEK_BASE_URL` 可保持无密钥计费快照和所有已记录部署不变;账号服务仍拒绝除自身 origin 以外的一切来源。
-
-**把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。
-
-**让路由插件的退登监听保留到其任务结束。** 这样卸载路由要等待运行中的回合:停用插件会被阻塞,其他设置写入也排在这次重载之后,直到回合结束。
-
-**路由卸载时取消其任务。** 配置重载或插件更新会停掉与退登无关的回合。
-
-**把退登策略放回账号服务。** 账号服务将重新检查 Agent 并认识路由 id,而这正是本决策去掉的依赖。
-
-**插件卸载后仍保留路由的监听或报告注册。** 比注册它的插件存活更久的注册违反“注册是其所有者的 effect”这一规则,并让已卸载插件的代码在任务运行期间留在其他作用域里。
-
-## 后果
-
-新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `providerCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。
-
-退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。
diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml
index 4493a15e53..0780e32ff0 100644
--- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml
+++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml
@@ -27,8 +27,8 @@
en: 0dcc97d8105fab60
zh: d80d40ae3a0c601d
/agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered:
- en: 021a4b08ad534b36
- zh: e98e1f65e50a568b
+ en: e377ad3c0327300e
+ zh: 4b9f7f83f464e657
/agent-note-direct-deepseek-search-and-fetch-apis/consequences:
en: 7ec21c5b1124e5f8
zh: af769dbdb4face9f
diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md
index f6ed9ab69f..6b535ace4f 100644
--- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md
+++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md
@@ -52,7 +52,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request
**Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider.
-**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.providerCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent.
+**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credentials instead come from one service, `ctx.deepseekAuth`, which releases the request headers of the API key or the account sign-in; Messages search and the Search/Fetch API transports remain independent.
**Split Search and Fetch into separate packages.** The guide serves both APIs from one base with one credential; separate packages would duplicate settings that address one deployment. Independent selection does not require separate packages, because each API registers its own provider id. Each operation lives in its own module, so either API can change without the other.
diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md
index fb88219a08..622195c6b6 100644
--- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md
+++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md
@@ -52,7 +52,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek
**把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。
-**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.providerCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。
+**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据改为来自同一个服务 `ctx.deepseekAuth`,它释放 API 密钥或账号登录凭据的请求头;Messages 搜索与 Search/Fetch API 传输层保持独立。
**把 Search 和 Fetch 拆成两个包。** 指南从同一基础地址、以同一份凭据提供两个 API;拆成两个包会让指向同一部署的设置重复出现。分别选择不需要拆包,因为每个 API 注册自己的提供方 id。每种操作位于独立模块,任一 API 都可以单独修改。
diff --git a/apps/cli/composition.md b/apps/cli/composition.md
index 1fa22d5a13..2bdf06a2c7 100644
--- a/apps/cli/composition.md
+++ b/apps/cli/composition.md
@@ -56,6 +56,8 @@ flowchart LR
cfg --> plugin_dsh_base_authorization
plugin_dsh_base_deepseek_account["deepseek-account
@deepseek-ai/dsh-deepseek-account"]
cfg --> plugin_dsh_base_deepseek_account
+ plugin_dsh_base_deepseek_auth["deepseek-auth
@deepseek-ai/dsh-deepseek-auth"]
+ cfg --> plugin_dsh_base_deepseek_auth
plugin_dsh_base_credentials["credentials
@deepseek-ai/dsh-credentials-local"]
cfg --> plugin_dsh_base_credentials
plugin_dsh_base_llm_pi_ai["llm-pi-ai
@deepseek-ai/dsh-llm-pi-ai"]
@@ -234,6 +236,7 @@ flowchart LR
| `settings` | `@deepseek-ai/dsh-settings` |
| `authorization` | `@deepseek-ai/dsh-authorization` |
| `deepseek-account` | `@deepseek-ai/dsh-deepseek-account` |
+| `deepseek-auth` | `@deepseek-ai/dsh-deepseek-auth` |
| `credentials` | `@deepseek-ai/dsh-credentials-local` |
| `llm-pi-ai` | `@deepseek-ai/dsh-llm-pi-ai` |
| `session-persistence-jsonl` | `@deepseek-ai/dsh-session-persistence-jsonl` |
diff --git a/apps/cli/package.json b/apps/cli/package.json
index 4762b5311a..0c5c178a22 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -177,7 +177,8 @@
"@types/ws": "8.18.1",
"ajv": "^8.20.0",
"execa": "^10.0.1",
- "ws": "8.21.3"
+ "ws": "8.21.3",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"exports": {
"./profile-boot": {
diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts
index 6150f1b30f..29f1217c4c 100644
--- a/apps/cli/tests/built-bin.e2e.ts
+++ b/apps/cli/tests/built-bin.e2e.ts
@@ -1263,6 +1263,7 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)',
['deepseek-llm-api-extensions', '@deepseek-ai/dsh-deepseek-llm-api-extensions'],
['session-log-deepseek', '@deepseek-ai/dsh-session-log-deepseek'],
['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'],
+ ['deepseek-auth', '@deepseek-ai/dsh-deepseek-auth'],
['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek-api-key'],
['sandbox', '@deepseek-ai/dsh-sandbox-local'],
['filesystem', '@deepseek-ai/dsh-fs-local'],
diff --git a/apps/cli/tests/profiles/headless/tests/harness.ts b/apps/cli/tests/profiles/headless/tests/harness.ts
index 43164c9d7b..c354102286 100644
--- a/apps/cli/tests/profiles/headless/tests/harness.ts
+++ b/apps/cli/tests/profiles/headless/tests/harness.ts
@@ -9,6 +9,7 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import TokenMeter from '@deepseek-ai/dsh-token-meter'
import ToolResultPruner from '@deepseek-ai/dsh-compaction-tool-result-pruner'
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
@@ -70,6 +71,7 @@ export async function codingHarness(workdir: string, options: CodingHarnessOptio
systemPrompt: { personaPrefix: options.personaPrefix ?? '' },
})
await ctx.plugin(AgentLoop, { agents: [] })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
...options.modelContextWindow === undefined && options.modelMaxTokens === undefined ? {} : {
models: [{
diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts
index e8efb9463f..f71cf9b768 100644
--- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts
+++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts
@@ -20,6 +20,7 @@ import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env'
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
import Sandbox from '@deepseek-ai/dsh-sandbox-local'
import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
@@ -63,6 +64,7 @@ async function ptcModeHarness(cwd: string): Promise {
tools: { mode: 'ptc' },
})
await harness.plugin(AgentLoop, { agents: [] })
+ await harness.plugin(DeepSeekAuth)
await harness.plugin(LlmDeepSeek)
if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime)
await harness.plugin(BashEnvPlugin)
@@ -83,6 +85,7 @@ async function workspacePtcModeHarness(): Promise {
await harness.plugin(ToolFs)
await harness.plugin(AgentInstructions, { maxBytes: 65536 })
await harness.plugin(AgentLoop, { agents: [] })
+ await harness.plugin(DeepSeekAuth)
await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] })
await mountRuntime(harness)
return harness
diff --git a/apps/web/tests/cot-translation-paid.e2e.ts b/apps/web/tests/cot-translation-paid.e2e.ts
index 1e08265e12..8d5bf22b6d 100644
--- a/apps/web/tests/cot-translation-paid.e2e.ts
+++ b/apps/web/tests/cot-translation-paid.e2e.ts
@@ -143,7 +143,7 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr
if (account === undefined) throw new Error('Shipped native Account service is absent')
// Only credential acquisition is nondeterministic; the Loader-owned native route and wire remain real.
const credential = {
- headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token',
+ headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' },
revoked: new AbortController().signal, reject: () => Promise.resolve(),
}
const auth = vi.spyOn(account, 'resolveRequestCredential').mockImplementation(async (url: string) =>
diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml
index 2b69c0bcf4..9e71aa6ce7 100644
--- a/docs/capability-seams.i18n.yaml
+++ b/docs/capability-seams.i18n.yaml
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
- en: 9a698ae22b619a5d
- zh: bd82134864167e76
+ en: b2a1901a1e5d3b7e
+ zh: b738c6da26e253eb
diff --git a/docs/capability-seams.md b/docs/capability-seams.md
index 9427f6c000..c450667b64 100644
--- a/docs/capability-seams.md
+++ b/docs/capability-seams.md
@@ -94,8 +94,6 @@ flowchart LR
pkg_llm_replay["llm-replay"]
pkg_agent_loop["agent-loop"]
pkg_compaction_basic["compaction-basic"]
- pkg_web_deepseek_api["web-deepseek-api"]
- pkg_web_search_deepseek["web-search-deepseek"]
pkg_session_log_deepseek["session-log-deepseek"]
svc_sessionLogDeepSeek["ctx.sessionLogDeepSeek
Session-log upload policy"]
pkg_deepseek_llm_api_extensions["deepseek-llm-api-extensions"]
@@ -153,10 +151,14 @@ flowchart LR
pkg_credentials["credentials"]
svc_credentials["ctx.credentials
Credential seam"]
pkg_credentials_local["credentials-local"]
- pkg_llm_deepseek_api_key["llm-deepseek-api-key"]
+ pkg_deepseek_auth["deepseek-auth"]
pkg_deepseek_account["deepseek-account"]
svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"]
pkg_llm_deepseek_account["llm-deepseek-account"]
+ svc_deepseekAuth["ctx.deepseekAuth
DeepSeek request authentication"]
+ pkg_llm_deepseek_api_key["llm-deepseek-api-key"]
+ pkg_web_deepseek_api["web-deepseek-api"]
+ pkg_web_search_deepseek["web-search-deepseek"]
pkg_authorization["authorization"]
svc_authorization["ctx.authorization
Authorization flow registry"]
pkg_client_product_analytics["client-product-analytics"]
@@ -378,6 +380,7 @@ flowchart LR
pkg_cua --> svc_cuaAccess
pkg_cua --> svc_cuaPrograms
pkg_deepseek_account --> svc_deepseekAccount
+ pkg_deepseek_auth --> svc_deepseekAuth
pkg_deepseek_chat_import --> svc_deepseekChatImport
pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions
pkg_experimental_api_speech_to_text --> svc_speechController
@@ -536,14 +539,16 @@ flowchart LR
svc_connection_authentication --> pkg_client_connection
svc_cordisInspect --> pkg_tool_cordis
svc_credentials --> pkg_api_settings_controller
- svc_credentials --> pkg_llm_deepseek_api_key
+ svc_credentials --> pkg_deepseek_auth
svc_credentials --> pkg_llm_pi_ai
- svc_credentials --> pkg_web_deepseek_api
- svc_credentials --> pkg_web_search_deepseek
svc_cuaAccess --> pkg_cua
svc_cuaPrograms --> pkg_cua_mcp
+ svc_deepseekAccount --> pkg_deepseek_auth
svc_deepseekAccount --> pkg_llm_deepseek_account
- svc_deepseekAccount --> pkg_web_deepseek_api
+ svc_deepseekAuth --> pkg_llm_deepseek_account
+ svc_deepseekAuth --> pkg_llm_deepseek_api_key
+ svc_deepseekAuth --> pkg_web_deepseek_api
+ svc_deepseekAuth --> pkg_web_search_deepseek
svc_deepseekLlmApiExtensions --> pkg_llm_deepseek
svc_directoryPicker --> pkg_api_workspace_controller
svc_dynamicCordisRunner --> pkg_tool_cordis
@@ -562,8 +567,6 @@ flowchart LR
svc_jobs --> pkg_tool_terminal
svc_llm --> pkg_agent_loop
svc_llm --> pkg_compaction_basic
- svc_llm --> pkg_web_deepseek_api
- svc_llm --> pkg_web_search_deepseek
svc_lsp --> pkg_tool_lsp
svc_mcpResources --> pkg_mcp_resources
svc_officeKit --> pkg_client_ui_sidebar_documentpreview
@@ -708,7 +711,7 @@ flowchart LR
| `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-office`](../packages/document/tool-office) | - | Authorized Office bytes are rendered as PDFs or images, converted, or recalculated on the Host using the declared native target engine, or Node WASM when no native target is declared. |
| `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The host commits accepted images before session events; provider adapters resolve authorized durable references into provider-native content. |
| `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | Owns streaming intake, durable storage, and staged receipt lifetime; the Session controller binds receipts to accepted submissions. |
-| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | Adapters register provider implementations; the loop and compaction call the provider-neutral stream service, and the DeepSeek web providers read the credential a route publishes. |
+| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic) | - | Adapters register provider implementations; the loop and compaction call the provider-neutral stream service. |
| `ctx.sessionLogDeepSeek` | `core` | [`session-log-deepseek`](../packages/session/session-log-deepseek) | - | - | - | Plugins register caller-owned exclusions before the canonical Session-log request contribution is prepared; unmatched requests use normal upload eligibility. |
| `ctx.deepseekLlmApiExtensions` | `seam` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | [`session-log-deepseek`](../packages/session/session-log-deepseek), [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Plugins prepare independent top-level fields; the official adapter merges them and commits their delivery state after HTTP acceptance. |
| `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Owns isolated per-session replay folds; pressure consumers share immutable revisioned measurements. |
@@ -734,8 +737,9 @@ flowchart LR
| `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. |
| `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. |
| `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session. |
-| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. |
-| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/account/deepseek-account) | - | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`web-deepseek-api`](../packages/web/web-deepseek-api) | - | The Host owns browser authorization and local credentials and releases per-request credentials to the account model route and the web providers; UI consumers receive state without tokens. |
+| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`deepseek-auth`](../packages/account/deepseek-auth), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. |
+| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/account/deepseek-account) | - | [`deepseek-auth`](../packages/account/deepseek-auth), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | - | The Host owns browser authorization and local credentials and releases per-request credentials to DeepSeek request authentication; the account model route registers its running-task report, and UI consumers receive state without tokens. |
+| `ctx.deepseekAuth` | `service` | [`deepseek-auth`](../packages/account/deepseek-auth) | - | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | Every DeepSeek API consumer names the credential kinds its API accepts; the service orders the API key and the account sign-in by billing, binds each to its deployment, and releases request headers. |
| `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol. |
| `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | Accepts selected Desktop events, enriches available login identity, and observes live compaction under the live Host collection policy. |
| `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | Product analytics and Session feedback adapters create independent reporting channels through one injected service. |
diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md
index 5e9c81a60b..7857577842 100644
--- a/docs/capability-seams.zh.md
+++ b/docs/capability-seams.zh.md
@@ -96,8 +96,6 @@ flowchart LR
pkg_llm_replay["llm-replay"]
pkg_agent_loop["agent-loop"]
pkg_compaction_basic["compaction-basic"]
- pkg_web_deepseek_api["web-deepseek-api"]
- pkg_web_search_deepseek["web-search-deepseek"]
pkg_session_log_deepseek["session-log-deepseek"]
svc_sessionLogDeepSeek["ctx.sessionLogDeepSeek
Session-log upload policy"]
pkg_deepseek_llm_api_extensions["deepseek-llm-api-extensions"]
@@ -155,10 +153,14 @@ flowchart LR
pkg_credentials["credentials"]
svc_credentials["ctx.credentials
Credential seam"]
pkg_credentials_local["credentials-local"]
- pkg_llm_deepseek_api_key["llm-deepseek-api-key"]
+ pkg_deepseek_auth["deepseek-auth"]
pkg_deepseek_account["deepseek-account"]
svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"]
pkg_llm_deepseek_account["llm-deepseek-account"]
+ svc_deepseekAuth["ctx.deepseekAuth
DeepSeek request authentication"]
+ pkg_llm_deepseek_api_key["llm-deepseek-api-key"]
+ pkg_web_deepseek_api["web-deepseek-api"]
+ pkg_web_search_deepseek["web-search-deepseek"]
pkg_authorization["authorization"]
svc_authorization["ctx.authorization
Authorization flow registry"]
pkg_client_product_analytics["client-product-analytics"]
@@ -380,6 +382,7 @@ flowchart LR
pkg_cua --> svc_cuaAccess
pkg_cua --> svc_cuaPrograms
pkg_deepseek_account --> svc_deepseekAccount
+ pkg_deepseek_auth --> svc_deepseekAuth
pkg_deepseek_chat_import --> svc_deepseekChatImport
pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions
pkg_experimental_api_speech_to_text --> svc_speechController
@@ -538,14 +541,16 @@ flowchart LR
svc_connection_authentication --> pkg_client_connection
svc_cordisInspect --> pkg_tool_cordis
svc_credentials --> pkg_api_settings_controller
- svc_credentials --> pkg_llm_deepseek_api_key
+ svc_credentials --> pkg_deepseek_auth
svc_credentials --> pkg_llm_pi_ai
- svc_credentials --> pkg_web_deepseek_api
- svc_credentials --> pkg_web_search_deepseek
svc_cuaAccess --> pkg_cua
svc_cuaPrograms --> pkg_cua_mcp
+ svc_deepseekAccount --> pkg_deepseek_auth
svc_deepseekAccount --> pkg_llm_deepseek_account
- svc_deepseekAccount --> pkg_web_deepseek_api
+ svc_deepseekAuth --> pkg_llm_deepseek_account
+ svc_deepseekAuth --> pkg_llm_deepseek_api_key
+ svc_deepseekAuth --> pkg_web_deepseek_api
+ svc_deepseekAuth --> pkg_web_search_deepseek
svc_deepseekLlmApiExtensions --> pkg_llm_deepseek
svc_directoryPicker --> pkg_api_workspace_controller
svc_dynamicCordisRunner --> pkg_tool_cordis
@@ -564,8 +569,6 @@ flowchart LR
svc_jobs --> pkg_tool_terminal
svc_llm --> pkg_agent_loop
svc_llm --> pkg_compaction_basic
- svc_llm --> pkg_web_deepseek_api
- svc_llm --> pkg_web_search_deepseek
svc_lsp --> pkg_tool_lsp
svc_mcpResources --> pkg_mcp_resources
svc_officeKit --> pkg_client_ui_sidebar_documentpreview
@@ -710,7 +713,7 @@ flowchart LR
| `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-office`](../packages/document/tool-office) | - | 已授权的 Office 字节在宿主上使用已声明的原生目标引擎渲染为 PDF 或图片、转换或重算;未声明原生目标时使用 Node WASM。 |
| `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 宿主会在会话事件之前提交已接受的图片;提供方适配器将已授权的持久引用解析为提供方原生内容。 |
| `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | 负责流式接收、持久存储和暂存回执生命周期;Session Controller 将回执绑定到已接受的提交。 |
-| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | 适配器注册提供方实现;agent loop(智能体循环)与压缩功能调用与提供方无关的流式服务,DeepSeek Web 提供方读取路由发布的凭据。 |
+| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic) | - | 适配器注册提供方实现;agent loop(智能体循环)与压缩功能调用提供方无关的流服务。 |
| `ctx.sessionLogDeepSeek` | `core` | [`session-log-deepseek`](../packages/session/session-log-deepseek) | - | - | - | 插件在准备权威 Session 日志请求贡献前注册归调用方所有的排除条件;没有条件匹配的请求应用普通上传资格判断。 |
| `ctx.deepseekLlmApiExtensions` | `seam` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | [`session-log-deepseek`](../packages/session/session-log-deepseek), [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 插件准备彼此独立的顶层字段;官方适配器会合并这些字段,并在 HTTP 接受后提交其交付状态。 |
| `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 拥有按会话隔离的回放折叠区;压力消费方共享不可变且带修订版本的测量结果。 |
@@ -736,8 +739,9 @@ flowchart LR
| `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. |
| `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. |
| `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | 拥有默认关闭的设置命名空间;Agent 作用域的委派工具会在组合新顶层 Session 时读取它。 |
-| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 |
-| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/account/deepseek-account) | - | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`web-deepseek-api`](../packages/web/web-deepseek-api) | - | Host 负责浏览器授权和本地凭证,并向账号模型路由和 Web 提供方释放按请求的凭据;UI 使用方只接收不含 token 的状态。 |
+| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`deepseek-auth`](../packages/account/deepseek-auth), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 |
+| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/account/deepseek-account) | - | [`deepseek-auth`](../packages/account/deepseek-auth), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | - | Host 负责浏览器授权和本地凭证,并向 DeepSeek 请求鉴权释放按请求的凭据;账号模型路由注册其运行中任务报告,UI 使用方只接收不含 token 的状态。 |
+| `ctx.deepseekAuth` | `service` | [`deepseek-auth`](../packages/account/deepseek-auth) | - | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | 每个 DeepSeek API 消费方给出其 API 接受的凭据种类;服务按计费方式排定 API 密钥与账号登录的顺序,把每一种绑定到其部署,并释放请求头。 |
| `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | flow 由知道如何取得某份凭据的插件注册,并以其写入的记录为键;seam 拥有这段对话与"每个键同时只跑一次尝试"的生命周期,而非协议本身。 |
| `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | 根据 Host 动态采集策略接收指定桌面事件、补充可用登录身份并监听实时压缩。 |
| `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | 产品埋点和 Session 反馈适配器通过同一个注入服务创建独立上报通道。 |
diff --git a/docs/config-catalog.md b/docs/config-catalog.md
index bd1605158e..d257ee3301 100644
--- a/docs/config-catalog.md
+++ b/docs/config-catalog.md
@@ -2049,7 +2049,7 @@ export interface Config {
## `@deepseek-ai/dsh-llm-deepseek-account`
-- `inject`: `llm`
+- `inject`: `llm` · `deepseekAuth`
- `refs`: [`ModelListingConfig`](../packages/llm/llm-deepseek/src/index.ts) · [`ModelOverride`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:15`](../packages/llm/llm-deepseek-account/src/config.ts)
@@ -2067,7 +2067,7 @@ export interface Config extends Omit, ModelListingConf
## `@deepseek-ai/dsh-llm-deepseek-api-key`
-- `inject`: `llm`
+- `inject`: `llm` · `deepseekAuth`
- `refs`: [`ModelListingConfig`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/llm/llm-deepseek-api-key/src/config.ts:18`](../packages/llm/llm-deepseek-api-key/src/config.ts)
@@ -5026,9 +5026,9 @@ export interface Config {
## `@deepseek-ai/dsh-web-deepseek-api`
-- `inject`: `web`
+- `inject`: `web` · `deepseekAuth`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
-- `source`: [`packages/web/web-deepseek-api/src/index.ts:57`](../packages/web/web-deepseek-api/src/index.ts)
+- `source`: [`packages/web/web-deepseek-api/src/index.ts:55`](../packages/web/web-deepseek-api/src/index.ts)
```ts config-catalog
/**
@@ -5104,9 +5104,9 @@ export interface Config {
## `@deepseek-ai/dsh-web-search-deepseek`
-- `inject`: `web`
+- `inject`: `web` · `deepseekAuth`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
-- `source`: [`packages/web/web-search-deepseek/src/index.ts:53`](../packages/web/web-search-deepseek/src/index.ts)
+- `source`: [`packages/web/web-search-deepseek/src/index.ts:51`](../packages/web/web-search-deepseek/src/index.ts)
```ts config-catalog
/** Plugin config (all optional — `apply` fills env-var and constant defaults). */
@@ -5309,6 +5309,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
| `@deepseek-ai/dsh-cordis-client-runner` | — | [`packages/extensions/cordis-client-runner/src/index.ts`](../packages/extensions/cordis-client-runner/src/index.ts) |
| `@deepseek-ai/dsh-creation-recommendations` | `tools` · `pluginManager` · `agents` · `subagents` · `profileContext` · `skills` · `actionCards` | [`packages/experimental/creation-recommendations/src/index.ts`](../packages/experimental/creation-recommendations/src/index.ts) |
| `@deepseek-ai/dsh-cua` | — | [`packages/experimental/cua/src/index.ts`](../packages/experimental/cua/src/index.ts) |
+| `@deepseek-ai/dsh-deepseek-auth` | — | [`packages/account/deepseek-auth/src/index.ts`](../packages/account/deepseek-auth/src/index.ts) |
| `@deepseek-ai/dsh-deepseek-llm-api-extensions` | — | [`packages/llm/deepseek-llm-api-extensions/src/index.ts`](../packages/llm/deepseek-llm-api-extensions/src/index.ts) |
| `@deepseek-ai/dsh-deliverable-file-references` | `systemPrompt` | [`packages/deliverables/deliverable-file-references/src/index.ts`](../packages/deliverables/deliverable-file-references/src/index.ts) |
| `@deepseek-ai/dsh-experimental-auto-review` | `approval` · `llm` · `permissionPresets` · `sessions` · `tools` · `workingDirectory` | [`packages/experimental/auto-review/src/index.ts`](../packages/experimental/auto-review/src/index.ts) |
diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md
index 291a06ff71..632ec37e4a 100644
--- a/docs/config-catalog.zh.md
+++ b/docs/config-catalog.zh.md
@@ -2051,7 +2051,7 @@ export interface Config {
## `@deepseek-ai/dsh-llm-deepseek-account`
-- `inject`: `llm`
+- `inject`: `llm` · `deepseekAuth`
- `refs`: [`ModelListingConfig`](../packages/llm/llm-deepseek/src/index.ts) · [`ModelOverride`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/llm/llm-deepseek-account/src/config.ts:15`](../packages/llm/llm-deepseek-account/src/config.ts)
@@ -2069,7 +2069,7 @@ export interface Config extends Omit, ModelListingConf
## `@deepseek-ai/dsh-llm-deepseek-api-key`
-- `inject`: `llm`
+- `inject`: `llm` · `deepseekAuth`
- `refs`: [`ModelListingConfig`](../packages/llm/llm-deepseek/src/index.ts) · [`ProtocolConfig`](../packages/llm/llm-deepseek/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/llm/llm-deepseek-api-key/src/config.ts:18`](../packages/llm/llm-deepseek-api-key/src/config.ts)
@@ -5028,9 +5028,9 @@ export interface Config {
## `@deepseek-ai/dsh-web-deepseek-api`
-- `inject`: `web`
+- `inject`: `web` · `deepseekAuth`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
-- `source`: [`packages/web/web-deepseek-api/src/index.ts:57`](../packages/web/web-deepseek-api/src/index.ts)
+- `source`: [`packages/web/web-deepseek-api/src/index.ts:55`](../packages/web/web-deepseek-api/src/index.ts)
```ts config-catalog
/**
@@ -5106,9 +5106,9 @@ export interface Config {
## `@deepseek-ai/dsh-web-search-deepseek`
-- `inject`: `web`
+- `inject`: `web` · `deepseekAuth`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
-- `source`: [`packages/web/web-search-deepseek/src/index.ts:53`](../packages/web/web-search-deepseek/src/index.ts)
+- `source`: [`packages/web/web-search-deepseek/src/index.ts:51`](../packages/web/web-search-deepseek/src/index.ts)
```ts config-catalog
/** Plugin config (all optional — `apply` fills env-var and constant defaults). */
@@ -5311,6 +5311,7 @@ export interface Config {
| `@deepseek-ai/dsh-cordis-client-runner` | — | [`packages/extensions/cordis-client-runner/src/index.ts`](../packages/extensions/cordis-client-runner/src/index.ts) |
| `@deepseek-ai/dsh-creation-recommendations` | `tools` · `pluginManager` · `agents` · `subagents` · `profileContext` · `skills` · `actionCards` | [`packages/experimental/creation-recommendations/src/index.ts`](../packages/experimental/creation-recommendations/src/index.ts) |
| `@deepseek-ai/dsh-cua` | — | [`packages/experimental/cua/src/index.ts`](../packages/experimental/cua/src/index.ts) |
+| `@deepseek-ai/dsh-deepseek-auth` | — | [`packages/account/deepseek-auth/src/index.ts`](../packages/account/deepseek-auth/src/index.ts) |
| `@deepseek-ai/dsh-deepseek-llm-api-extensions` | — | [`packages/llm/deepseek-llm-api-extensions/src/index.ts`](../packages/llm/deepseek-llm-api-extensions/src/index.ts) |
| `@deepseek-ai/dsh-deliverable-file-references` | `systemPrompt` | [`packages/deliverables/deliverable-file-references/src/index.ts`](../packages/deliverables/deliverable-file-references/src/index.ts) |
| `@deepseek-ai/dsh-experimental-auto-review` | `approval` · `llm` · `permissionPresets` · `sessions` · `tools` · `workingDirectory` | [`packages/experimental/auto-review/src/index.ts`](../packages/experimental/auto-review/src/index.ts) |
diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md
index 737e716f5c..a078588a2d 100644
--- a/docs/event-producer-consumer.md
+++ b/docs/event-producer-consumer.md
@@ -57,10 +57,10 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:115`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
-| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
+| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:115`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
| `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` |
| `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` |
-| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:81`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
+| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:78`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - |
| `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` |
| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md
index df8ae55841..75a9e45e63 100644
--- a/docs/event-producer-consumer.zh.md
+++ b/docs/event-producer-consumer.zh.md
@@ -59,10 +59,10 @@
| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:115`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
-| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
+| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:115`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
| `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` |
| `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` |
-| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:81`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
+| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:78`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - |
| `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` |
| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
diff --git a/docs/module-graph.md b/docs/module-graph.md
index cde25ac1a6..6e39b017e6 100644
--- a/docs/module-graph.md
+++ b/docs/module-graph.md
@@ -119,6 +119,7 @@ flowchart TD
end
subgraph group_account["packages/account"]
pkg_deepseek_account["deepseek-account"]
+ pkg_deepseek_auth["deepseek-auth"]
end
subgraph group_api["packages/api"]
pkg_api_gateway["api-gateway"]
@@ -666,6 +667,10 @@ flowchart TD
pkg_skill_filesystem --> pkg_fs
pkg_skill_filesystem --> pkg_home_paths
pkg_skill_filesystem --> pkg_skill
+ pkg_deepseek_auth --> pkg_credentials
+ pkg_deepseek_auth --> pkg_deepseek_account
+ pkg_deepseek_auth --> pkg_error
+ pkg_deepseek_auth --> pkg_launch_environment
pkg_api_workspace_controller --> pkg_api_gateway
pkg_api_workspace_controller --> pkg_client_connection
pkg_api_workspace_controller --> pkg_host_directory_picker
@@ -694,10 +699,12 @@ flowchart TD
pkg_pwsh_local --> pkg_timeout
pkg_llm_deepseek_account --> pkg_agent
pkg_llm_deepseek_account --> pkg_deepseek_account
+ pkg_llm_deepseek_account --> pkg_deepseek_auth
pkg_llm_deepseek_account --> pkg_launch_environment
pkg_llm_deepseek_account --> pkg_llm
pkg_llm_deepseek_account --> pkg_llm_deepseek
pkg_llm_deepseek_api_key --> pkg_credentials
+ pkg_llm_deepseek_api_key --> pkg_deepseek_auth
pkg_llm_deepseek_api_key --> pkg_launch_environment
pkg_llm_deepseek_api_key --> pkg_llm
pkg_llm_deepseek_api_key --> pkg_llm_deepseek
@@ -716,15 +723,14 @@ flowchart TD
pkg_goal --> pkg_typert_protocol
pkg_web_deepseek_api --> pkg_agent
pkg_web_deepseek_api --> pkg_credentials
- pkg_web_deepseek_api --> pkg_deepseek_account
- pkg_web_deepseek_api --> pkg_launch_environment
+ pkg_web_deepseek_api --> pkg_deepseek_auth
pkg_web_deepseek_api --> pkg_llm
pkg_web_deepseek_api --> pkg_session
pkg_web_deepseek_api --> pkg_web
pkg_web_search_deepseek --> pkg_agent
pkg_web_search_deepseek --> pkg_credentials
+ pkg_web_search_deepseek --> pkg_deepseek_auth
pkg_web_search_deepseek --> pkg_launch_environment
- pkg_web_search_deepseek --> pkg_llm
pkg_web_search_deepseek --> pkg_session
pkg_web_search_deepseek --> pkg_web
pkg_file_reference --> pkg_agent
@@ -1574,6 +1580,7 @@ flowchart TD
pkg_sdk_jsonrpc_server --> pkg_agent
pkg_sdk_jsonrpc_server --> pkg_attachment
pkg_sdk_jsonrpc_server --> pkg_commands
+ pkg_sdk_jsonrpc_server --> pkg_deepseek_auth
pkg_sdk_jsonrpc_server --> pkg_goal
pkg_sdk_jsonrpc_server --> pkg_llm
pkg_sdk_jsonrpc_server --> pkg_llm_deepseek_api_key
@@ -1818,6 +1825,7 @@ flowchart TD
| [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs) |
| [`fs-observation-policy`](../packages/fs/fs-observation-policy) | `fs` | [`fs`](../packages/fs/fs) |
| [`skill-filesystem`](../packages/skill/skill-filesystem) | `skill` | [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`skill`](../packages/skill/skill) |
+| [`deepseek-auth`](../packages/account/deepseek-auth) | `account` | [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`error`](../packages/util/error), [`launch-environment`](../packages/util/launch-environment) |
| [`api-workspace-controller`](../packages/api/workspace-controller) | `api` | [`api-gateway`](../packages/api/gateway), [`client-connection`](../packages/client/connection), [`host-directory-picker`](../packages/host/directory-picker), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol), [`workspace`](../packages/workspace/workspace) |
| [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`typert-protocol`](../packages/typert/protocol) |
| [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | `experimental` | [`experimental-translator`](../packages/experimental/translator) |
@@ -1826,13 +1834,13 @@ flowchart TD
| [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`bash-local`](../packages/shell/bash-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
-| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) |
-| [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) |
+| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/account/deepseek-account), [`deepseek-auth`](../packages/account/deepseek-auth), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) |
+| [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) |
| [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`timeout`](../packages/util/timeout) |
| [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) |
| [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) |
-| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) |
-| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) |
+| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) |
+| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) |
| [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) |
| [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) |
@@ -1976,5 +1984,5 @@ flowchart TD
| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-session-status`](../packages/client/ui-session-status), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) |
| [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) |
| [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
-| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
+| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`deepseek-auth`](../packages/account/deepseek-auth), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md
index e5585ac8d8..91eed3700e 100644
--- a/docs/module-graph.zh.md
+++ b/docs/module-graph.zh.md
@@ -121,6 +121,7 @@ flowchart TD
end
subgraph group_account["packages/account"]
pkg_deepseek_account["deepseek-account"]
+ pkg_deepseek_auth["deepseek-auth"]
end
subgraph group_api["packages/api"]
pkg_api_gateway["api-gateway"]
@@ -668,6 +669,10 @@ flowchart TD
pkg_skill_filesystem --> pkg_fs
pkg_skill_filesystem --> pkg_home_paths
pkg_skill_filesystem --> pkg_skill
+ pkg_deepseek_auth --> pkg_credentials
+ pkg_deepseek_auth --> pkg_deepseek_account
+ pkg_deepseek_auth --> pkg_error
+ pkg_deepseek_auth --> pkg_launch_environment
pkg_api_workspace_controller --> pkg_api_gateway
pkg_api_workspace_controller --> pkg_client_connection
pkg_api_workspace_controller --> pkg_host_directory_picker
@@ -696,10 +701,12 @@ flowchart TD
pkg_pwsh_local --> pkg_timeout
pkg_llm_deepseek_account --> pkg_agent
pkg_llm_deepseek_account --> pkg_deepseek_account
+ pkg_llm_deepseek_account --> pkg_deepseek_auth
pkg_llm_deepseek_account --> pkg_launch_environment
pkg_llm_deepseek_account --> pkg_llm
pkg_llm_deepseek_account --> pkg_llm_deepseek
pkg_llm_deepseek_api_key --> pkg_credentials
+ pkg_llm_deepseek_api_key --> pkg_deepseek_auth
pkg_llm_deepseek_api_key --> pkg_launch_environment
pkg_llm_deepseek_api_key --> pkg_llm
pkg_llm_deepseek_api_key --> pkg_llm_deepseek
@@ -718,15 +725,14 @@ flowchart TD
pkg_goal --> pkg_typert_protocol
pkg_web_deepseek_api --> pkg_agent
pkg_web_deepseek_api --> pkg_credentials
- pkg_web_deepseek_api --> pkg_deepseek_account
- pkg_web_deepseek_api --> pkg_launch_environment
+ pkg_web_deepseek_api --> pkg_deepseek_auth
pkg_web_deepseek_api --> pkg_llm
pkg_web_deepseek_api --> pkg_session
pkg_web_deepseek_api --> pkg_web
pkg_web_search_deepseek --> pkg_agent
pkg_web_search_deepseek --> pkg_credentials
+ pkg_web_search_deepseek --> pkg_deepseek_auth
pkg_web_search_deepseek --> pkg_launch_environment
- pkg_web_search_deepseek --> pkg_llm
pkg_web_search_deepseek --> pkg_session
pkg_web_search_deepseek --> pkg_web
pkg_file_reference --> pkg_agent
@@ -1576,6 +1582,7 @@ flowchart TD
pkg_sdk_jsonrpc_server --> pkg_agent
pkg_sdk_jsonrpc_server --> pkg_attachment
pkg_sdk_jsonrpc_server --> pkg_commands
+ pkg_sdk_jsonrpc_server --> pkg_deepseek_auth
pkg_sdk_jsonrpc_server --> pkg_goal
pkg_sdk_jsonrpc_server --> pkg_llm
pkg_sdk_jsonrpc_server --> pkg_llm_deepseek_api_key
@@ -1820,6 +1827,7 @@ flowchart TD
| [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs) |
| [`fs-observation-policy`](../packages/fs/fs-observation-policy) | `fs` | [`fs`](../packages/fs/fs) |
| [`skill-filesystem`](../packages/skill/skill-filesystem) | `skill` | [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`skill`](../packages/skill/skill) |
+| [`deepseek-auth`](../packages/account/deepseek-auth) | `account` | [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`error`](../packages/util/error), [`launch-environment`](../packages/util/launch-environment) |
| [`api-workspace-controller`](../packages/api/workspace-controller) | `api` | [`api-gateway`](../packages/api/gateway), [`client-connection`](../packages/client/connection), [`host-directory-picker`](../packages/host/directory-picker), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol), [`workspace`](../packages/workspace/workspace) |
| [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`typert-protocol`](../packages/typert/protocol) |
| [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | `experimental` | [`experimental-translator`](../packages/experimental/translator) |
@@ -1828,13 +1836,13 @@ flowchart TD
| [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`bash-local`](../packages/shell/bash-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
-| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) |
-| [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) |
+| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/account/deepseek-account), [`deepseek-auth`](../packages/account/deepseek-auth), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) |
+| [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) |
| [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`timeout`](../packages/util/timeout) |
| [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) |
| [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) |
-| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) |
-| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) |
+| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) |
+| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-auth`](../packages/account/deepseek-auth), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) |
| [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) |
| [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) |
@@ -1978,5 +1986,5 @@ flowchart TD
| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-session-status`](../packages/client/ui-session-status), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) |
| [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) |
| [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
-| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
+| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`deepseek-auth`](../packages/account/deepseek-auth), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml
index f05bc29ab8..5354786369 100644
--- a/docs/persistence-catalog.i18n.yaml
+++ b/docs/persistence-catalog.i18n.yaml
@@ -558,8 +558,8 @@
en: 028791baa24a6a0a
zh: 028791baa24a6a0a
/session-persistence-event-catalog/resolved-persistence-types/in-history:
- en: b952affc9dc40743
- zh: dd5d0872283e3762
+ en: ad2f023eedbc2a7e
+ zh: 2124b8dedfbf8383
/session-persistence-event-catalog/resolved-persistence-types/in-progress:
en: 61de2b0c9de8c15b
zh: 61de2b0c9de8c15b
@@ -1197,8 +1197,8 @@
en: 8d2873c634bf6405
zh: 91e92b5730462cf0
/session-persistence-event-catalog/resolved-persistence-types/replayenvelope:
- en: 293da0eae99bdbe8
- zh: 244c9cfd281b9451
+ en: 34cbedee7bc95921
+ zh: f7deeddb8d60152a
/session-persistence-event-catalog/resolved-persistence-types/requestcontext:
en: 544039047a28b6bb
zh: c691f0bb1e23db08
@@ -1248,8 +1248,8 @@
en: 29df35a8cc984e75
zh: 321b4e8bb0ad0850
/session-persistence-event-catalog/resolved-persistence-types/streamchunk:
- en: 71d48d17e3763774
- zh: 8cb0f1d92afa3236
+ en: 747e384b3176e0cb
+ zh: defbff408ea7c97c
/session-persistence-event-catalog/resolved-persistence-types/subagentcatalogevent:
en: 8a56ae8e701509b3
zh: caef4f0223f65470
@@ -1317,8 +1317,8 @@
en: 49fcbb63c824347e
zh: 187486d676edfe0e
/session-persistence-event-catalog/resolved-persistence-types/toolschema:
- en: d9e99600cd0c02c3
- zh: 9885b7337c349b41
+ en: afa1e3fd9ccdd95b
+ zh: 7af667e3ebac25e8
/session-persistence-event-catalog/resolved-persistence-types/toolschema~2:
en: 12c14727bb7834e2
zh: b0f3c877873c36db
@@ -2013,11 +2013,11 @@
en: bb507524bcc39c53
zh: 8314898562437473
/session-persistence-event-catalog/resolved-persistence-types/type-block-end:
- en: 13224de3736d2d48
- zh: 6bf99a32b41f7165
+ en: 7513d6a33f4ad113
+ zh: 652201059a3de858
/session-persistence-event-catalog/resolved-persistence-types/type-block-start:
- en: 598ec19ec3abf6ed
- zh: 84efc0177a9fd177
+ en: 56230efa41e79869
+ zh: 9ca4b8990a28d4d9
/session-persistence-event-catalog/resolved-persistence-types/type-chunk:
en: 4b0ed1fe2caa26fb
zh: 8fffdc4f8c3deb79
@@ -2058,8 +2058,8 @@
en: 14e4b48d856bcf57
zh: 72ba176535dc7f3f
/session-persistence-event-catalog/resolved-persistence-types/type-finish:
- en: e1b5a95753e1984b
- zh: 3a04bd831ff9f12d
+ en: 30f8f49d0755dc2d
+ zh: d8553c9590a0e9bf
/session-persistence-event-catalog/resolved-persistence-types/type-goal-change:
en: aad2516b62d3ee83
zh: e7204c4dc4e8e408
@@ -2097,8 +2097,8 @@
en: 4bf62582902829c5
zh: c9da9d11402ee1c4
/session-persistence-event-catalog/resolved-persistence-types/type-reasoning-delta:
- en: a2952ab46acfed9d
- zh: b4e68befe87800dd
+ en: a3f08ffda3526201
+ zh: e599517be130ff99
/session-persistence-event-catalog/resolved-persistence-types/type-request-context:
en: f8addb1a01da9ca1
zh: 4ef11ebddd302c05
@@ -2160,8 +2160,8 @@
en: 28bab22053eabff2
zh: 54c0e424fcb99c05
/session-persistence-event-catalog/resolved-persistence-types/type-text-delta:
- en: 9856f0f63d3b413c
- zh: c3bae6ac9e949696
+ en: 5f30a603fab07135
+ zh: 3b7e2076351a1473
/session-persistence-event-catalog/resolved-persistence-types/type-todo-write:
en: 2fa7ba77598a95b4
zh: 50972b51d77e9155
@@ -2169,8 +2169,8 @@
en: 45ff4145d9e2c7d4
zh: 36a346ff729c4b84
/session-persistence-event-catalog/resolved-persistence-types/type-tool-call-delta:
- en: 7c45dcb12f5fedb5
- zh: eea8f79e052f2bf0
+ en: 0e907728f330a8c7
+ zh: d9d1400d4c468ab2
/session-persistence-event-catalog/resolved-persistence-types/type-tool-workflow-agent-end:
en: 8eb5e1eb95722bc7
zh: 8dd5980029600648
@@ -2202,8 +2202,8 @@
en: 1b045de96172be4b
zh: 8a15c6f35b576b37
/session-persistence-event-catalog/resolved-persistence-types/type-usage:
- en: 2b86abaff8e6aaa8
- zh: 4afeeb9af04b72f0
+ en: 0ce623d4c59f5a2f
+ zh: 2d830e6e1badb1ba
/session-persistence-event-catalog/resolved-persistence-types/type-user-message:
en: 6e4884da342f291a
zh: 454973316ff24910
diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md
index 835ced1d80..24902ce41c 100644
--- a/docs/persistence-catalog.md
+++ b/docs/persistence-catalog.md
@@ -2017,7 +2017,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8`
SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5`
-Sources: [`packages/llm/llm/src/types.ts:528`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:440`](../packages/llm/llm/src/types.ts)
`"in-history"`
@@ -4572,7 +4572,7 @@ Sources: [`packages/llm/llm/src/types.ts:75`](../packages/llm/llm/src/types.ts)
SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555`
-Sources: [`packages/llm/llm/src/types.ts:562`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -4886,7 +4886,7 @@ Sources: [`packages/skill/skill/src/index.ts:149`](../packages/skill/skill/src/i
SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180`
-Sources: [`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:496`](../packages/llm/llm/src/types.ts)
One of:
@@ -5315,7 +5315,7 @@ Sources: [`packages/llm/llm/src/message.ts:172`](../packages/llm/llm/src/message
SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2`
-Sources: [`packages/llm/llm/src/types.ts:605`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:517`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8336,7 +8336,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625`
SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d`
-Sources: [`packages/llm/llm/src/types.ts:589`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:501`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8350,7 +8350,7 @@ Sources: [`packages/llm/llm/src/types.ts:589`](../packages/llm/llm/src/types.ts)
SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90`
-Sources: [`packages/llm/llm/src/types.ts:585`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:497`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8568,7 +8568,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8`
SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1`
-Sources: [`packages/llm/llm/src/types.ts:591`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:503`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8774,7 +8774,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:27`](../packages/llm/llm/src
SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095`
-Sources: [`packages/llm/llm/src/types.ts:587`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:499`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -9110,7 +9110,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:20`](../packages/llm/llm/src
SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65`
-Sources: [`packages/llm/llm/src/types.ts:586`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:498`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -9158,7 +9158,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:34`](../packages/llm/llm/src
SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a`
-Sources: [`packages/llm/llm/src/types.ts:588`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:500`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -9336,7 +9336,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8`
SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515`
-Sources: [`packages/llm/llm/src/types.ts:590`](../packages/llm/llm/src/types.ts)
+Sources: [`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md
index 6f4b1e7762..2a2c00d6a6 100644
--- a/docs/persistence-catalog.zh.md
+++ b/docs/persistence-catalog.zh.md
@@ -2019,7 +2019,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8`
SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5`
-来源:[`packages/llm/llm/src/types.ts:528`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:440`](../packages/llm/llm/src/types.ts)
`"in-history"`
@@ -4574,7 +4574,7 @@ SHA-256: `814d9434e1ddf9078612b3b34322f26e9363b469213335007f7e9ba7fee9464e`
SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555`
-来源:[`packages/llm/llm/src/types.ts:562`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -4888,7 +4888,7 @@ SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db`
SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180`
-来源:[`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:496`](../packages/llm/llm/src/types.ts)
以下类型之一:
@@ -5317,7 +5317,7 @@ SHA-256: `4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731`
SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2`
-来源:[`packages/llm/llm/src/types.ts:605`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:517`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8338,7 +8338,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625`
SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d`
-来源:[`packages/llm/llm/src/types.ts:589`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:501`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8352,7 +8352,7 @@ SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d`
SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90`
-来源:[`packages/llm/llm/src/types.ts:585`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:497`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8570,7 +8570,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8`
SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1`
-来源:[`packages/llm/llm/src/types.ts:591`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:503`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8776,7 +8776,7 @@ SHA-256: `71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd`
SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095`
-来源:[`packages/llm/llm/src/types.ts:587`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:499`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -9112,7 +9112,7 @@ SHA-256: `e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33`
SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65`
-来源:[`packages/llm/llm/src/types.ts:586`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:498`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -9160,7 +9160,7 @@ SHA-256: `3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6`
SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a`
-来源:[`packages/llm/llm/src/types.ts:588`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:500`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -9338,7 +9338,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8`
SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515`
-来源:[`packages/llm/llm/src/types.ts:590`](../packages/llm/llm/src/types.ts)
+来源:[`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json
index 46e8095609..3a30d2d9d8 100644
--- a/docs/persistence-schema.json
+++ b/docs/persistence-schema.json
@@ -89,7 +89,7 @@
{"digest":"0a8a062bc9c3c0d97fd97742262f2ea53dd32297f834e81114870d38ac3dc6da","names":[],"sources":[]},
{"digest":"0a92c5bdfa06c2e2615b777728f3aa95f408d43b9012e7b754568311251db623","names":[],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:29"]},
{"digest":"0aa62ab51b36c0e64b134bd03ba8725d758744180a1a447da49beaad194f219f","names":[],"sources":[]},
- {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:562"]},
+ {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:474"]},
{"digest":"0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:161"]},
{"digest":"0af3ecfb8c60d416fc40a7cc4fb2c4851a8e46608b2b38ab9e510670c971aa1f","names":[],"sources":[]},
{"digest":"0b6d718c693fdf7f06dcccb0bcbbabe78cc63514eafc62d6b2a3899735279d6f","names":["packages/goal/goal/src/types.ts#GoalRef"],"sources":["packages/goal/goal/src/types.ts:20"]},
@@ -182,7 +182,7 @@
{"digest":"297fbd8067d7815adae02b89790ec6ff5fb7c2cb0d0eb026e1746c24ec857761","names":[],"sources":[]},
{"digest":"2aad1179f957631477b582e57cd8f538cb82618fc3fb816bde1171154235b065","names":[],"sources":[]},
{"digest":"2ab12a0e345658f9342816d773fe610f049982bcad82631f43b9205abe43e5ee","names":[],"sources":[]},
- {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:587"]},
+ {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:499"]},
{"digest":"2aed07493b1c65b6d00de5586da1e743cf501684b9ad43a1765fb4007d4ea456","names":[],"sources":[]},
{"digest":"2c4c21f19f426a58f2dac914e34313aa43f8408972de857a486d1f086d5adb6c","names":[],"sources":[]},
{"digest":"2c64d4bc7264fd3f8bed47e96ab8a593bce05a1e4e1c436dcd244a3b7e0c2a9d","names":[],"sources":[]},
@@ -224,7 +224,7 @@
{"digest":"3bc287e765d58dc3a22672a0495a6cfd561220dd38fbaecef80aa95b96caed79","names":[],"sources":[]},
{"digest":"3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f","names":["packages/core/session/src/types.ts#OptionalSessionSeq"],"sources":["packages/core/session/src/types.ts:66"]},
{"digest":"3bdb8dc6989655b0d4ec361edafb8e2629bc263e1ea591819414fdafc1a413b3","names":[],"sources":[]},
- {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:585"]},
+ {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:497"]},
{"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]},
{"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]},
{"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]},
@@ -249,7 +249,7 @@
{"digest":"45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448","names":[],"sources":["packages/interaction/user-approval/src/types.ts:44"]},
{"digest":"477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028","names":[],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:25"]},
{"digest":"47e5d84f1a93450a78c7f3954b43990d0f629af7c034a56313e5deb63e772c1b","names":[],"sources":[]},
- {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:584"]},
+ {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:496"]},
{"digest":"487b65c37bfedb8b72088c4107a0a90a6249701f6b26745f6d98f9b8a22b07c7","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:43"]},
{"digest":"48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3","names":[],"sources":[]},
{"digest":"48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb","names":[],"sources":[]},
@@ -326,7 +326,7 @@
{"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]},
{"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:34"]},
{"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:36"]},
- {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:605"]},
+ {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:517"]},
{"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:149"]},
{"digest":"67d5f73ceae82f5265258142ad6cf172de2c1fef93ba551b7f0454e0a93bffe0","names":["packages/llm/llm/src/call-config.ts#LlmCallConfig"],"sources":["packages/llm/llm/src/call-config.ts:30"]},
{"digest":"68141cbe3994a5ffcd064c07c75996538437fd9dbf77ce8a2927e89ec577fabe","names":[],"sources":[]},
@@ -413,7 +413,7 @@
{"digest":"871bfd6f7bb91061246768d3377f3fd58d6b8ea7c31f44c714ae7ab215650d62","names":[],"sources":[]},
{"digest":"87b1a33564b9a4d63b00988a524c12259243953aebb9c9a05127d87b27464df9","names":[],"sources":[]},
{"digest":"88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa","names":[],"sources":[]},
- {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:588"]},
+ {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:500"]},
{"digest":"8a046b52331959aa3394680d6acbe09b8a5447c6b61375f263445bfcef19b7f1","names":[],"sources":[]},
{"digest":"8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0","names":[],"sources":[]},
{"digest":"8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad","names":[],"sources":["packages/interaction/permission-presets/src/index.ts:61"]},
@@ -441,7 +441,7 @@
{"digest":"93cbbc5a7fd0b1aa1ff1b9a6bb5ec52b073f48e5a5200365c45c0cd54059e1b9","names":[],"sources":["packages/interaction/user-approval/src/types.ts:55"]},
{"digest":"93d38436347f67c9022aacbc4472e283d722bcab8eb73fc376aaf7b6a6b9fb35","names":[],"sources":[]},
{"digest":"94c56aeb1564ad735eb773d88636b40761d063efa1610f1308004d32923f5378","names":[],"sources":[]},
- {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:586"]},
+ {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:498"]},
{"digest":"95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd","names":[],"sources":[]},
{"digest":"95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60","names":[],"sources":[]},
{"digest":"9645cf93769a6dfb227bd400bd6cb9fa7bab9140f4a851e4ae92514ade6e3114","names":[],"sources":[]},
@@ -475,7 +475,7 @@
{"digest":"a15a19ef63cf5d1b711db1d249821dab0cedcd3a9ad09137b47352c93841fd20","names":[],"sources":[]},
{"digest":"a16e567c8cd2c55cf1e911aed3c200c4e1f6febb1459ff2a9e7adf159afb68cb","names":[],"sources":[]},
{"digest":"a2066bd52f61218ba15b758def2641cc6a8bd3d4a594a488ee4c65be356d7e39","names":[],"sources":[]},
- {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:591"]},
+ {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:503"]},
{"digest":"a2be0f0cb59f0d4a06557d45847d1938aced238baa77a6da416e590b8b958553","names":[],"sources":[]},
{"digest":"a3a259a1aa5401af786ce08c4a8419681d3000d73467991b5fc563389bc4ebd2","names":[],"sources":[]},
{"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]},
@@ -597,7 +597,7 @@
{"digest":"d215701afb7aafbfd63205a6bbb8803aed60810bd613e2dbbc43071c38b6c568","names":[],"sources":["packages/experimental/timeline/src/reminders.ts:14"]},
{"digest":"d28765f87d6b6ab408e0b2f3e7e297791b004b806d8e302c49903ebae815feb2","names":[],"sources":[]},
{"digest":"d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41","names":[],"sources":[]},
- {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:589"]},
+ {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:501"]},
{"digest":"d4c799e3d51cae1040362ba4968efc484739e14416c9c1df20c2f108b4ef2eb5","names":[],"sources":[]},
{"digest":"d4e4d575abeb4b72d616dc65c17ac0eaa943cc135609395044c38d5afcb10e31","names":[],"sources":[]},
{"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9","names":[],"sources":[]},
@@ -671,11 +671,11 @@
{"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:238"]},
{"digest":"f1996af2602e6f62b5ab179ca5c4af00d8753938b74cc6ef102de09e99e74a7e","names":[],"sources":[]},
{"digest":"f19bee84bf3d20904553cdcd57465232bc1c2a194f54c4d195292ba0487223a6","names":["packages/attachment/attachment/src/types.ts#FileAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:39"]},
- {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:590"]},
+ {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:502"]},
{"digest":"f230c0b583e23b25ee0a61dbe4c05e95c1e2ae44b27939501eb9e03696f0c278","names":[],"sources":[]},
{"digest":"f29d63336e8266d80dd7baeab219436db86341304f6be1cd0edb36f5134c4a47","names":[],"sources":[]},
{"digest":"f2da0f27c1e6add59982c37b15e4a4912c5b33466859cce3b13d503600e24aef","names":["packages/llm/llm/src/types.ts#FileBlock"],"sources":["packages/llm/llm/src/types.ts:105"]},
- {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:528"]},
+ {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:440"]},
{"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]},
{"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]},
{"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]},
diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml
index 665e916b45..92f8f08fd9 100644
--- a/docs/subsystems/account.i18n.yaml
+++ b/docs/subsystems/account.i18n.yaml
@@ -6,8 +6,8 @@
en: 2302e2999588bac3
zh: 5e0ac058b50036dc
/deepseek-account/request-credentials:
- en: c5fb32307f841c66
- zh: 8ed40c0c99884301
+ en: a5d0001547d8341f
+ zh: 0c553f214b9ce6ea
/deepseek-account/embedded-platform-credentials:
en: 9a651d70acbe83a6
zh: 4624b0299f5fdd8e
diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md
index d064016326..22073c8ad6 100644
--- a/docs/subsystems/account.md
+++ b/docs/subsystems/account.md
@@ -8,7 +8,7 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun
## Request credentials
-`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. The `deepseek-account` model route publishes this credential through `ctx.llm.providerCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released.
+`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token` and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. Consumers do not call it themselves: [`ctx.deepseekAuth`](../../packages/account/deepseek-auth/README.md) asks for the credential on behalf of the `deepseek-account` model route and the DeepSeek web providers, for a destination under the origin of that route's base URL or, without that route, of `DEEPSEEK_BASE_URL`. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released.
Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`; a request that outlives the plugin ends through its credential's `revoked` signal, and the plugin's failure callback for that request cancels the work.
@@ -167,6 +167,53 @@ watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterab
Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts)
+
+
+### `ctx.deepseekAuth` — `DeepSeekAuth`
+
+`ctx.deepseekAuth`: the two DeepSeek credential kinds behind one request-authorization operation.
+
+```ts cordis-catalog
+/**
+ * Connect the deployment a model route plugin's settings name for one kind. Call it from within `ctx.effect()`.
+ * @param kind - the kind the plugin's route bills.
+ * @param route - provider route the plugin registers; {@link routeKind} answers `kind` for it while connected.
+ * @param connection - reads the plugin's current settings; a throw marks the kind unresolved for that operation.
+ * @returns the disposer removing the connection.
+ * @throws {DeepSeekAuthError} code `DUPLICATE_CONNECTION` when the kind is already connected.
+ */
+connect(kind: DeepSeekAuthKind, route: string, connection: () => DeepSeekAuthConnection): () => void
+
+/**
+ * The kind that bills a conversation on one model route.
+ * @param route - provider route of a model request; undefined names none.
+ * @returns the kind connected under that route, or undefined for a route no plugin connected.
+ */
+routeKind(route: string | undefined): DeepSeekAuthKind | undefined
+
+/**
+ * The kinds one request can authenticate with, in the order its billing tries them, each bound to its destination.
+ * Nothing is read from a credential store.
+ * @param request - the request.
+ * @returns candidates and unresolved kinds, first preferred; empty when the destination accepts no kind the
+ * billing allows or no allowed kind serves an absolute destination.
+ */
+candidates(request: DeepSeekAuthRequest): (DeepSeekAuthCandidate | DeepSeekAuthUnresolved)[]
+
+/**
+ * Release the credential of the first candidate that has one. A later candidate is not read once an earlier one
+ * has a credential, fails to read, or does not resolve.
+ * @param request - the request.
+ * @param signal - cancellation for the lookups.
+ * @returns the authorization, or undefined when no candidate has a credential.
+ * @throws {DeepSeekAuthError} code `UNRESOLVED_CONNECTION` at an unresolved kind, `INVALID_CREDENTIAL` for an
+ * unusable API key; store failures propagate.
+ */
+async authorize(request: DeepSeekAuthRequest, signal?: AbortSignal): Promise
+```
+
+Source: [`packages/account/deepseek-auth/src/index.ts`](../../packages/account/deepseek-auth/src/index.ts)
+
### `deepseek-account/*` events
diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md
index ccbdbd0510..fc54815c18 100644
--- a/docs/subsystems/account.zh.md
+++ b/docs/subsystems/account.zh.md
@@ -8,7 +8,7 @@
## 请求凭据
-`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.providerCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。
+`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。消费方不直接调用它:[`ctx.deepseekAuth`](../../packages/account/deepseek-auth/README.zh.md) 代 `deepseek-account` 模型路由和 DeepSeek Web 提供方索取这份凭据,目标地址位于该路由基础地址的 origin 之下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 的 origin 之下。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。
按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责;比插件存活更久的请求通过其凭据的 `revoked` 信号结束,插件为该请求提供的失败回调随后取消这些工作。
@@ -167,6 +167,53 @@ watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterab
Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts)
+
+
+### `ctx.deepseekAuth` — `DeepSeekAuth`
+
+`ctx.deepseekAuth`: the two DeepSeek credential kinds behind one request-authorization operation.
+
+```ts cordis-catalog
+/**
+ * Connect the deployment a model route plugin's settings name for one kind. Call it from within `ctx.effect()`.
+ * @param kind - the kind the plugin's route bills.
+ * @param route - provider route the plugin registers; {@link routeKind} answers `kind` for it while connected.
+ * @param connection - reads the plugin's current settings; a throw marks the kind unresolved for that operation.
+ * @returns the disposer removing the connection.
+ * @throws {DeepSeekAuthError} code `DUPLICATE_CONNECTION` when the kind is already connected.
+ */
+connect(kind: DeepSeekAuthKind, route: string, connection: () => DeepSeekAuthConnection): () => void
+
+/**
+ * The kind that bills a conversation on one model route.
+ * @param route - provider route of a model request; undefined names none.
+ * @returns the kind connected under that route, or undefined for a route no plugin connected.
+ */
+routeKind(route: string | undefined): DeepSeekAuthKind | undefined
+
+/**
+ * The kinds one request can authenticate with, in the order its billing tries them, each bound to its destination.
+ * Nothing is read from a credential store.
+ * @param request - the request.
+ * @returns candidates and unresolved kinds, first preferred; empty when the destination accepts no kind the
+ * billing allows or no allowed kind serves an absolute destination.
+ */
+candidates(request: DeepSeekAuthRequest): (DeepSeekAuthCandidate | DeepSeekAuthUnresolved)[]
+
+/**
+ * Release the credential of the first candidate that has one. A later candidate is not read once an earlier one
+ * has a credential, fails to read, or does not resolve.
+ * @param request - the request.
+ * @param signal - cancellation for the lookups.
+ * @returns the authorization, or undefined when no candidate has a credential.
+ * @throws {DeepSeekAuthError} code `UNRESOLVED_CONNECTION` at an unresolved kind, `INVALID_CREDENTIAL` for an
+ * unusable API key; store failures propagate.
+ */
+async authorize(request: DeepSeekAuthRequest, signal?: AbortSignal): Promise
+```
+
+Source: [`packages/account/deepseek-auth/src/index.ts`](../../packages/account/deepseek-auth/src/index.ts)
+
### `deepseek-account/*` events
diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml
index dbb124b198..49f34b6799 100644
--- a/docs/subsystems/llm-streaming.i18n.yaml
+++ b/docs/subsystems/llm-streaming.i18n.yaml
@@ -36,8 +36,8 @@
en: 58dec2259b0b1c6f
zh: fc99fe965acaabf3
/llm-streaming/the-model-request:
- en: 61d4131601adbc32
- zh: b83156c875d29b89
+ en: 834d3d8d6b5871ab
+ zh: 393889ec6075f622
/llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header:
en: b0eb4620c6953646
zh: fabf51c7245a4855
@@ -48,5 +48,5 @@
en: 8c140f9c5a799f01
zh: f66b895594247e92
/llm-streaming/service-and-provider-contracts:
- en: 81b4ede66c5e906d
- zh: 2ad0ddb1a32e3167
+ en: 8dc79d4cc82824c2
+ zh: 3ebabd3a117ad717
diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md
index 1e93b92f64..078f4f4700 100644
--- a/docs/subsystems/llm-streaming.md
+++ b/docs/subsystems/llm-streaming.md
@@ -527,86 +527,6 @@ interface LlmNativeAuth {
}
```
-A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.providerCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. A grant whose owner can withdraw the credential while requests carry it, as an account sign-out does, has a `revoked` signal: the consumer runs each request it authenticates under that signal and reports a request the signal ended as its own failure, not as the caller's cancellation.
-
-```ts type-equiv
-/**
- * One credential released for one destination. Host-only: it carries the
- * secret, so it never crosses a Remote boundary and never enters a log.
- */
-interface ProviderCredentialGrant {
- /**
- * Request headers carrying the credential as the route's own protocol
- * expects it, such as `x-api-key` for an API key. Consumers speaking that
- * protocol send them unchanged.
- */
- readonly headers: Readonly>
- /**
- * The bare credential value, for destinations whose protocol renders it
- * differently from {@link headers}, such as `Authorization: Bearer`.
- */
- readonly value: string
- /**
- * Invalidate this exact credential after the destination rejected it with
- * HTTP 401 so no later request resends it. Absent for kinds without
- * invalidation. The owner contains storage failures: the caller reports the
- * destination's rejection, never a failure of this call.
- * @returns settlement after the invalidation attempt.
- */
- reject?(): Promise
- /**
- * Aborts when the owner withdraws this credential while requests carrying it
- * may be in flight, as an account sign-out does. A consumer ends each request
- * it authenticated with this grant and reports that end as its own failure,
- * not as the caller's cancellation. Absent for kinds that are never withdrawn.
- */
- readonly revoked?: AbortSignal
-}
-```
-
-```ts type-equiv
-/**
- * The credential one registered provider route currently sends, answered by
- * the route's owning adapter so that consumers read no provider configuration
- * and choose no header names. `ctx.llm.providerCredential()` resolves a new value
- * per call from one configuration generation; a caller keeps it for one
- * operation only.
- */
-interface ProviderCredential {
- /** Kind of credential the route sends. */
- readonly kind: LlmCredentialKind
- /**
- * The route's current request base URL as its configuration resolves it,
- * environment fallbacks included: the destination this credential is meant
- * for. Consumers derive sibling endpoints of the same deployment from it.
- */
- readonly baseURL: string
- /**
- * Credential reference the route resolves, for diagnostics that tell the user
- * where to configure the credential; absent for kinds without a stored
- * reference, such as sign-in grants.
- */
- readonly reference?: string
- /**
- * Whether {@link resolve} would release a credential for `endpoint`, checked
- * without validating the credential or contacting the destination; the owner
- * may read its store to answer. Store failures reject.
- * @param endpoint - absolute URL the credential would be sent to.
- * @returns whether a credential is configured for that destination.
- */
- configured(endpoint: string): Promise
- /**
- * Release the credential for `endpoint`, or `undefined` when none is
- * configured or the destination may not receive it. The caller chooses the
- * failure it reports for `undefined`. Store and format failures reject.
- * @param endpoint - absolute URL the credential will be sent to.
- * @param signal - cancellation for the lookup.
- * @returns the released credential, or `undefined`.
- */
- resolve(endpoint: string, signal?: AbortSignal): Promise
-}
-```
-
A catalog entry may carry a provider-authored `badge` that selectors show beside the model name. It is display data: `resolveModelInfo` omits it, and no model request carries it.
```ts type-equiv
@@ -950,8 +870,6 @@ The [wire reference](../deepseek-llm-api-wire-extensions.md) defines the exact r
`LlmAdapter` is the provider contract: subclass, implement `stream()`, and register one adapter instance with `ctx.llm.registerAdapter(providers, adapter)`. `GenerateOptions.provider` selects the registered adapter; `GenerateOptions.model` is passed to that adapter and need not be registered at lifecycle start. Duplicate provider routes fail atomically. Optional `providerRetryPolicy()` is captured per route with normal defaults, while `providerInfo()` and asynchronous `listModels()` feed `LlmRuntime.listProviders()` / `listModels()` with detached selector metadata. That catalog is advisory rather than a request whitelist: the adapter remains authoritative and may accept unlisted model ids. One asynchronous `resolveModel()` query returns exact model identity plus optional correctness-sensitive context capacity, an adapter-configured `defaultMaxTokens`, and ordered model-owned reasoning ids with an optional deployment default; absent fields mean unavailable metadata or provider-owned behavior, not invalid catalog membership. The resolver receives optional cancellation and must settle promptly after abort. `LlmRuntime.resolveModelInfo()` validates and detaches the aggregate. At the final adapter boundary, `resolveCallConfig()` materializes the output default only when `maxTokens` is absent and validates and materializes reasoning, so direct calls cannot bypass either configured behavior; direct dispatch captures one registration before awaiting that resolution. The agent loop instead uses `prepareCall()` to keep the same registration across model resolution, durable header logging, and dispatch, retain detached context metadata from that exact lookup, and report which config fields the adapter defaulted. Adapter lookup happens at the terminal continuation of the `llm/stream` waterfall, so a listener may short-circuit the call or route a mutable one-shot request before lookup. AgentLoop observes a request attempt once the outer waterfall returns a stream handle; that limited boundary does not prove a lazy terminal adapter was constructed or began provider I/O. The `block-start` / `block-end` `index` correlation and the assembler together mean an adapter only has to emit well-formed chunks — block reassembly is not each adapter's problem. [architecture.md](../architecture.md#turn-flow) shows where `ctx.llm.stream()` and the `llm/stream` waterfall sit in one turn.
-Optional `providerCredential()` publishes the credential a route currently sends, with the route's base URL, its kind, and an optional credential reference. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter: an unregistered route answers `undefined`, because callers ask about routes a conversation named earlier, and a registered route whose configuration does not resolve propagates the adapter's failure. The DeepSeek web providers read it to call the deployment of the conversation's route with that route's credential, so no consumer reads another plugin's configuration or chooses its header names.
-
```ts type-equiv
/** One model call whose config and adapter registration were resolved together. */
interface PreparedLlmCall {
@@ -1019,16 +937,6 @@ declare abstract class LlmAdapter {
* @returns the same target used by request serialization, before provider-internal processing.
*/
imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;
- /**
- * Describe the credential one owned route currently sends, for consumers that
- * call the same deployment outside the model request path, such as web
- * providers that share a route's credential and endpoint. The default
- * publishes none. Implementations answer from one configuration generation
- * per call and may throw when that configuration does not resolve.
- * @param _provider - a route passed to `registerAdapter()` for this instance.
- * @returns the route's current credential, or `undefined` when the route publishes none.
- */
- providerCredential(_provider: string): ProviderCredential | undefined;
/**
* List models this adapter can currently advertise for one owned provider.
* Core routing accepts unlisted model ids; catalog-driven entry points such
@@ -1209,17 +1117,6 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u
*/
imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget
-/**
- * Resolve the credential one registered route currently sends, through its
- * owning adapter. An unregistered route answers `undefined` rather than
- * throwing because callers ask about routes a conversation named earlier,
- * which may no longer be mounted; a registered route whose configuration
- * does not resolve propagates the adapter's failure.
- * @param provider - provider route whose credential is wanted.
- * @returns the route's credential, or `undefined` when the route is unregistered or publishes none.
- */
-providerCredential(provider: string): ProviderCredential | undefined
-
/**
* Resolve the exact text one durable file occurrence contributes to every
* provider request in the current execution environment.
diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md
index 2e8707f13a..dcebebf666 100644
--- a/docs/subsystems/llm-streaming.zh.md
+++ b/docs/subsystems/llm-streaming.zh.md
@@ -533,86 +533,6 @@ interface LlmNativeAuth {
}
```
-路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.providerCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时撤回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。
-
-```ts type-equiv
-/**
- * One credential released for one destination. Host-only: it carries the
- * secret, so it never crosses a Remote boundary and never enters a log.
- */
-interface ProviderCredentialGrant {
- /**
- * Request headers carrying the credential as the route's own protocol
- * expects it, such as `x-api-key` for an API key. Consumers speaking that
- * protocol send them unchanged.
- */
- readonly headers: Readonly>
- /**
- * The bare credential value, for destinations whose protocol renders it
- * differently from {@link headers}, such as `Authorization: Bearer`.
- */
- readonly value: string
- /**
- * Invalidate this exact credential after the destination rejected it with
- * HTTP 401 so no later request resends it. Absent for kinds without
- * invalidation. The owner contains storage failures: the caller reports the
- * destination's rejection, never a failure of this call.
- * @returns settlement after the invalidation attempt.
- */
- reject?(): Promise
- /**
- * Aborts when the owner withdraws this credential while requests carrying it
- * may be in flight, as an account sign-out does. A consumer ends each request
- * it authenticated with this grant and reports that end as its own failure,
- * not as the caller's cancellation. Absent for kinds that are never withdrawn.
- */
- readonly revoked?: AbortSignal
-}
-```
-
-```ts type-equiv
-/**
- * The credential one registered provider route currently sends, answered by
- * the route's owning adapter so that consumers read no provider configuration
- * and choose no header names. `ctx.llm.providerCredential()` resolves a new value
- * per call from one configuration generation; a caller keeps it for one
- * operation only.
- */
-interface ProviderCredential {
- /** Kind of credential the route sends. */
- readonly kind: LlmCredentialKind
- /**
- * The route's current request base URL as its configuration resolves it,
- * environment fallbacks included: the destination this credential is meant
- * for. Consumers derive sibling endpoints of the same deployment from it.
- */
- readonly baseURL: string
- /**
- * Credential reference the route resolves, for diagnostics that tell the user
- * where to configure the credential; absent for kinds without a stored
- * reference, such as sign-in grants.
- */
- readonly reference?: string
- /**
- * Whether {@link resolve} would release a credential for `endpoint`, checked
- * without validating the credential or contacting the destination; the owner
- * may read its store to answer. Store failures reject.
- * @param endpoint - absolute URL the credential would be sent to.
- * @returns whether a credential is configured for that destination.
- */
- configured(endpoint: string): Promise
- /**
- * Release the credential for `endpoint`, or `undefined` when none is
- * configured or the destination may not receive it. The caller chooses the
- * failure it reports for `undefined`. Store and format failures reject.
- * @param endpoint - absolute URL the credential will be sent to.
- * @param signal - cancellation for the lookup.
- * @returns the released credential, or `undefined`.
- */
- resolve(endpoint: string, signal?: AbortSignal): Promise
-}
-```
-
目录条目可以携带提供方编写的 `badge`,供选择器显示在模型名称旁。它只是展示数据:`resolveModelInfo` 不返回它,模型请求也不携带它。
```ts type-equiv
@@ -956,8 +876,6 @@ interface LlmCallConfigAdapterDefaults {
`LlmAdapter` 是提供方约定:创建子类、实现 `stream()`,再用 `ctx.llm.registerAdapter(providers, adapter)` 注册一个适配器实例。`GenerateOptions.provider` 选择已注册适配器;`GenerateOptions.model` 会传给该适配器,无需在生命周期启动时注册。重复提供方路由会原子失败。可选的 `providerRetryPolicy()` 会按路由捕获并填入 normal 默认值,`providerInfo()` 与异步 `listModels()` 方法则为 `LlmRuntime.listProviders()` / `listModels()` 提供分离的 selector 元数据。该目录仅供参考,不是请求白名单:适配器仍是权威,并可接受未列出的模型 id。单次异步 `resolveModel()` 查询返回确切模型身份,以及可选的对正确性敏感的上下文容量、适配器配置的 `defaultMaxTokens`、由模型持有的有序推理强度 ID 和可选的部署默认值;字段缺失表示元数据不可用或保留提供方持有的行为,而不表示目录成员关系无效。解析器会接收可选的取消信号,并且必须在信号中止后迅速完成结算。`LlmRuntime.resolveModelInfo()` 会校验聚合结果并返回分离值。在最终适配器边界,`resolveCallConfig()` 仅在 `maxTokens` 缺失时填入输出默认值,并校验和填入推理强度,因此直接调用也无法绕过任何一项已配置行为;直接分派会在等待解析前捕获一项适配器注册。agent loop 则使用 `prepareCall()`,使模型解析、请求头持久记录和分派全程使用同一项注册,保留来自同一次查询的分离上下文元数据,并报告适配器填入的配置字段。适配器查找发生在 `llm/stream` waterfall 的终端 continuation,因此 listener 可以在查找前短路调用,或路由一个可变的一次性请求。AgentLoop 在外层 waterfall 返回流句柄时观察到一次请求尝试;这个有限边界不能证明惰性终端适配器已构造完成或开始提供方 I/O。`block-start` / `block-end` 的 `index` 关联与 assembler 共同意味着适配器只需 emit 格式正确的分片——块重组不是每个适配器各自的问题。`ctx.llm.stream()` 与 `llm/stream` waterfall 在一个轮次中的位置见 [architecture.md](../architecture.zh.md#turn-flow)。
-可选的 `providerCredential()` 发布路由当前发送的凭据,连同路由的基础地址、凭据种类和可选的凭据引用。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器:未注册的路由回答 `undefined`,因为调用方询问的是会话早先命名的路由;已注册但配置无法解析的路由则传播适配器的失败。DeepSeek Web 提供方据此用会话路由的凭据调用同一部署,因此没有消费方需要读取其他插件的配置或自行选择请求头名称。
-
```ts type-equiv
/** One model call whose config and adapter registration were resolved together. */
interface PreparedLlmCall {
@@ -1025,16 +943,6 @@ declare abstract class LlmAdapter {
* @returns the same target used by request serialization, before provider-internal processing.
*/
imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;
- /**
- * Describe the credential one owned route currently sends, for consumers that
- * call the same deployment outside the model request path, such as web
- * providers that share a route's credential and endpoint. The default
- * publishes none. Implementations answer from one configuration generation
- * per call and may throw when that configuration does not resolve.
- * @param _provider - a route passed to `registerAdapter()` for this instance.
- * @returns the route's current credential, or `undefined` when the route publishes none.
- */
- providerCredential(_provider: string): ProviderCredential | undefined;
/**
* List models this adapter can currently advertise for one owned provider.
* Core routing accepts unlisted model ids; catalog-driven entry points such
@@ -1215,17 +1123,6 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u
*/
imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget
-/**
- * Resolve the credential one registered route currently sends, through its
- * owning adapter. An unregistered route answers `undefined` rather than
- * throwing because callers ask about routes a conversation named earlier,
- * which may no longer be mounted; a registered route whose configuration
- * does not resolve propagates the adapter's failure.
- * @param provider - provider route whose credential is wanted.
- * @returns the route's credential, or `undefined` when the route is unregistered or publishes none.
- */
-providerCredential(provider: string): ProviderCredential | undefined
-
/**
* Resolve the exact text one durable file occurrence contributes to every
* provider request in the current execution environment.
diff --git a/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.i18n.yaml
new file mode 100644
index 0000000000..f5e885f737
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.i18n.yaml
@@ -0,0 +1,16 @@
+# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
+# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
+# After editing either side, bring the other along and re-record with:
+# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.md
+/:
+ en: 56911e8190557ac2
+ zh: 199a530cada9ef1b
+/deepseek-consumers-authenticate-through-ctx-deepseekauth:
+ en: 0edf2a8ee3bc6aff
+ zh: 3af58b98573eb8f9
+/deepseek-consumers-authenticate-through-ctx-deepseekauth/change:
+ en: 157466403a04468e
+ zh: 5e361579bf85311a
+/deepseek-consumers-authenticate-through-ctx-deepseekauth/migration:
+ en: 5080b12103295b1a
+ zh: f6f681e22a7c2a18
diff --git a/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.md
new file mode 100644
index 0000000000..97a7318e07
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.md
@@ -0,0 +1,34 @@
+---
+kind: upgrade-guide
+description: "DeepSeek model routes and web providers require the new dsh-deepseek-auth plugin; the llm-deepseek credential helpers, the dsh-llm API key check, the route plugins' config exports, and account Agent inspection are removed."
+---
+
+# DeepSeek consumers authenticate through ctx.deepseekAuth
+
+English | [中文](guide.zh.md)
+
+## Change
+
+`@deepseek-ai/dsh-deepseek-auth` provides `ctx.deepseekAuth`, which releases the API key or the account sign-in for one DeepSeek request. `@deepseek-ai/dsh-llm-deepseek-api-key`, `@deepseek-ai/dsh-llm-deepseek-account`, `@deepseek-ai/dsh-web-deepseek-api`, and `@deepseek-ai/dsh-web-search-deepseek` declare it as a peer dependency and start only in a composition that mounts it. The `base` and `sdk-minimal` bundles mount it.
+
+`@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, `DeepSeekRequestAuth` gains an optional `revoked` signal, and the new `missingCredential` option names the missing-credential failure. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional.
+
+`@deepseek-ai/dsh-llm` no longer exports `normalizeApiKey` and `assertUsableApiKey`. `@deepseek-ai/dsh-credentials` exports `normalizeApiKey(raw)`, `resolveCredentialRef(ctx, ref)`, and `credentialRefConfigured(ctx, ref)`.
+
+`@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report.
+
+`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. A sign-out aborts released credentials' `revoked` signal, ending in-flight account requests: model requests outside a turn fail with `ACCOUNT_SIGN_IN_REQUIRED`, Search and Fetch with `WEB_PROVIDER_ERROR`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name.
+
+Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. With `auto` billing, a `deepseek-account` or `deepseek-official` conversation whose route plugin is not mounted tries the API key, then the account credential. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken`, `rejectAccountToken`, and `resolveApiKey` with `authorize(endpoint, signal)`.
+
+## Migration
+
+1. Add `- name: '@deepseek-ai/dsh-deepseek-auth'` to every composition that mounts one of the four plugins without the `base` or `sdk-minimal` bundle. Code that mounts them through `ctx.plugin()` mounts the package's default export first.
+2. Replace the removed `llm-deepseek` helpers with `ctx.deepseekAuth.authorize({ consumer, accepts, destination })`: send the returned `headers`, call `reject()` after HTTP 401 when present, and end the request when `revoked` aborts. `candidates()` answers presence checks.
+3. Replace `assertUsableApiKey` with `normalizeApiKey` from `@deepseek-ai/dsh-credentials`, and throw your own error for its `reason`.
+4. In custom `DeepSeekAdapter` or `registerDeepSeekProvider` consumers, return `undefined` from `resolveAuth` when no credential exists and supply `missingCredential` for a route-specific failure. Pass credential headers, not a token, to `createModelListingCache`.
+5. Replace imports of the route plugins' config exports with the plugins' own `Config`.
+6. Make `deepseekAccount` stand-ins implement `resolveRequestCredential`, returning a `revoked` signal; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead.
+7. Update workspace references to `packages/account/deepseek-account`; the npm package name, Remote namespace, and configuration keys are unchanged.
+8. Replace `resolveAccountToken`, `rejectAccountToken`, and `resolveApiKey` in `DeepSeekSearchProviderOptions` with `authorize`.
+9. Type-check the callers, then send one DeepSeek model request and one web search in each changed composition.
diff --git a/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.zh.md
new file mode 100644
index 0000000000..4fc85b64c2
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.zh.md
@@ -0,0 +1,34 @@
+---
+kind: upgrade-guide
+description: "DeepSeek 模型路由和 Web 提供方要求挂载新的 dsh-deepseek-auth 插件;移除 llm-deepseek 的凭据辅助函数、dsh-llm 的 API 密钥检查、路由插件的配置导出和账号服务对 Agent 的检查。"
+---
+
+# DeepSeek 消费方通过 ctx.deepseekAuth 鉴权
+
+[English](guide.md) | 中文
+
+## 变更
+
+`@deepseek-ai/dsh-deepseek-auth` 提供 `ctx.deepseekAuth`,为一次 DeepSeek 请求释放 API 密钥或账号登录凭据。`@deepseek-ai/dsh-llm-deepseek-api-key`、`@deepseek-ai/dsh-llm-deepseek-account`、`@deepseek-ai/dsh-web-deepseek-api` 和 `@deepseek-ai/dsh-web-search-deepseek` 把它声明为对等依赖(peer dependency),并且只在挂载了它的组合中启动。`base` 与 `sdk-minimal` 两个组合包挂载它。
+
+`@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,`DeepSeekRequestAuth` 新增可选的 `revoked` 信号,新增的 `missingCredential` 选项命名凭据缺失的失败。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。
+
+`@deepseek-ai/dsh-llm` 不再导出 `normalizeApiKey` 和 `assertUsableApiKey`。`@deepseek-ai/dsh-credentials` 导出 `normalizeApiKey(raw)`、`resolveCredentialRef(ctx, ref)` 和 `credentialRefConfigured(ctx, ref)`。
+
+`@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。
+
+`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。退登会中止已释放凭据的 `revoked` 信号,从而结束在途的账号请求:回合之外的模型请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,Search 与 Fetch 以 `WEB_PROVIDER_ERROR` 失败。该包移除 `dsh-agent` 与 `dsh-llm` 对等依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。
+
+没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。在 `auto` 计费下,`deepseek-account` 或 `deepseek-official` 上的会话在其路由插件未挂载时先尝试 API 密钥,再尝试账号凭据。`DeepSeekSearchProviderOptions` 用 `authorize(endpoint, signal)` 替换 `resolveAccountToken`、`rejectAccountToken` 与 `resolveApiKey`。
+
+## 迁移
+
+1. 凡是不经 `base` 或 `sdk-minimal` 组合包而挂载上述四个插件之一的组合,都加入 `- name: '@deepseek-ai/dsh-deepseek-auth'`。用 `ctx.plugin()` 挂载它们的代码先挂载该包的默认导出。
+2. 用 `ctx.deepseekAuth.authorize({ consumer, accepts, destination })` 替换被移除的 `llm-deepseek` 辅助函数:发送返回的 `headers`,存在 `reject()` 时在 HTTP 401 之后调用它,并在 `revoked` 中止时结束请求。存在性检查使用 `candidates()`。
+3. 用 `@deepseek-ai/dsh-credentials` 的 `normalizeApiKey` 替换 `assertUsableApiKey`,并依据它的 `reason` 抛出自己的错误。
+4. 在自定义的 `DeepSeekAdapter` 或 `registerDeepSeekProvider` 消费方中,没有凭据时让 `resolveAuth` 返回 `undefined`,并为路由专属的失败提供 `missingCredential`。向 `createModelListingCache` 传递凭据请求头而不是 token。
+5. 用路由插件自身的 `Config` 替换对其配置导出的导入。
+6. 让 `deepseekAccount` 替身实现 `resolveRequestCredential` 并返回 `revoked` 信号;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。
+7. 把工作区引用更新为 `packages/account/deepseek-account`;npm 包名、Remote 命名空间和配置键均不变。
+8. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken`、`rejectAccountToken` 与 `resolveApiKey` 替换为 `authorize`。
+9. 对调用方做类型检查,然后在每个改动过的组合里各发起一次 DeepSeek 模型请求和一次 Web 搜索。
diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml
deleted file mode 100644
index ce61c10cdf..0000000000
--- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
-# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
-# After editing either side, bring the other along and re-record with:
-# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md
-/:
- en: 56fc7afd90f0fcde
- zh: 0b441fc159f25bcf
-/deepseek-routes-publish-the-credential-web-consumers-reuse:
- en: b5392bcd81f69488
- zh: 68cd945f2dde46af
-/deepseek-routes-publish-the-credential-web-consumers-reuse/change:
- en: 7568433b72e2633b
- zh: dcd4c6deb72da3a4
-/deepseek-routes-publish-the-credential-web-consumers-reuse/migration:
- en: 0632d7c9ffce1675
- zh: a8b4d67f469eaee7
diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md
deleted file mode 100644
index 7b4b539fb7..0000000000
--- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-kind: upgrade-guide
-description: "DeepSeek model routes publish their credential through ctx.llm.providerCredential(); the llm-deepseek credential helpers, the route plugins' config exports, and account Agent inspection are removed."
----
-
-# DeepSeek routes publish the credential web consumers reuse
-
-English | [中文](guide.zh.md)
-
-## Change
-
-`LlmAdapter.providerCredential(provider)` and `LlmRuntime.providerCredential(provider)` publish a route's current credential as a `ProviderCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `ProviderCredentialGrant` with protocol headers, the bare value, an optional `reject()`, and an optional `revoked` withdrawal signal.
-
-`@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional.
-
-`@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report.
-
-`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. A sign-out aborts released credentials' `revoked` signal, ending in-flight account requests: model requests outside a turn fail with `ACCOUNT_SIGN_IN_REQUIRED`, Search and Fetch with `WEB_PROVIDER_ERROR`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`.
-
-`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.providerCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`.
-
-## Migration
-
-1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.providerCredential(provider)`, and run each request under the grant's `revoked` signal.
-2. In custom `DeepSeekAdapter` or `registerDeepSeekProvider` consumers, return `undefined` from `resolveAuth` when no credential exists, add `value` to every `DeepSeekRequestAuth`, supply `missingCredential` for a route-specific failure, and declare `credential` to publish the route's credential. Pass credential headers, not a token, to `createModelListingCache`.
-3. Replace imports of the route plugins' config exports with the plugins' own `Config`, and read a route's endpoint from its published credential instead of its resolver.
-4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`, returning a `revoked` signal; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead.
-5. Update workspace references to `packages/account/deepseek-account`; the npm package name, Remote namespace, and configuration keys are unchanged.
-6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `ProviderCredentialGrant`.
diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md
deleted file mode 100644
index 6e6705bfeb..0000000000
--- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-kind: upgrade-guide
-description: "DeepSeek 模型路由通过 ctx.llm.providerCredential() 发布自己的凭据;移除 llm-deepseek 的凭据辅助函数、路由插件的配置导出和账号服务对 Agent 的检查。"
----
-
-# DeepSeek 路由发布 Web 消费方复用的凭据
-
-[English](guide.md) | 中文
-
-## 变更
-
-`LlmAdapter.providerCredential(provider)` 与 `LlmRuntime.providerCredential(provider)` 把路由当前的凭据发布为 `ProviderCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `ProviderCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 撤回信号。
-
-`@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。
-
-`@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。
-
-`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。退登会中止已释放凭据的 `revoked` 信号,从而结束在途的账号请求:回合之外的模型请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,Search 与 Fetch 以 `WEB_PROVIDER_ERROR` 失败。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。
-
-`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.providerCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。
-
-## 迁移
-
-1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.providerCredential(provider)`,并让每个请求受授权的 `revoked` 信号约束。
-2. 在自定义的 `DeepSeekAdapter` 或 `registerDeepSeekProvider` 消费方中,没有凭据时让 `resolveAuth` 返回 `undefined`,为每个 `DeepSeekRequestAuth` 加上 `value`,为路由专属的失败提供 `missingCredential`,并声明 `credential` 以发布路由凭据。向 `createModelListingCache` 传递凭据请求头而不是 token。
-3. 用路由插件自身的 `Config` 替换对其配置导出的导入,并从路由发布的凭据而非其解析函数读取端点。
-4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential` 并返回 `revoked` 信号;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。
-5. 把工作区引用更新为 `packages/account/deepseek-account`;npm 包名、Remote 命名空间和配置键均不变。
-6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `ProviderCredentialGrant` 的 `resolveAccountCredential`。
diff --git a/packages/account/README.i18n.yaml b/packages/account/README.i18n.yaml
index ae0a4268ed..3ffd85c88a 100644
--- a/packages/account/README.i18n.yaml
+++ b/packages/account/README.i18n.yaml
@@ -3,20 +3,20 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/account/README.md
/:
- en: c603fc9f9990181e
- zh: fc045770018269cd
+ en: 65f89da052a7067f
+ zh: e7d32dd098a0005e
/account-deepseek-account:
en: 15e52f323c5ffdba
zh: e32a4d077fd5ef98
/account-deepseek-account/summary:
- en: b75f72f3404fcd85
- zh: c24435d70528c5a4
+ en: 21dd20608c62012a
+ zh: 2d9954d43ca0e0b7
/account-deepseek-account/table-of-contents:
en: 1eb35b015a6c423f
zh: a8a3dceee2c9e943
/account-deepseek-account/packages:
- en: 4f342c1e06b8c9e2
- zh: f36f298ef3bd1be2
+ en: 29fa6562bc33791c
+ zh: 8df0763eba581702
/account-deepseek-account/related-documentation:
en: 6667d1a41ac182d1
zh: 065a196972782a34
diff --git a/packages/account/README.md b/packages/account/README.md
index 278ac10749..96e1181ea0 100644
--- a/packages/account/README.md
+++ b/packages/account/README.md
@@ -1,5 +1,5 @@
---
-description: "Package map for the DeepSeek account family: browser sign-in, the stored account grant, and the Host-only request credentials released to the account model route and the DeepSeek web providers."
+description: "Package map for the DeepSeek account family: browser sign-in, the stored account grant, and the request authentication that chooses between the account sign-in and the API key for every DeepSeek API request."
kind: "package-group"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
-The `account/` group signs the user in to DeepSeek through the system browser and keeps the account grant in the local credential store that [`credentials/`](../credentials/README.md) owns. Host consumers never read the token: the `deepseek-account` model route and the DeepSeek web providers ask `ctx.deepseekAccount` for the credential of one request destination and receive its request headers, the bare value, and an invalidation for an HTTP 401. Clients receive account state through the `account` Remote namespace without credentials.
+The `account/` group signs the user in to DeepSeek through the system browser and keeps the account grant in the local credential store that [`credentials/`](../credentials/README.md) owns. Host consumers never read the token: `ctx.deepseekAuth` asks `ctx.deepseekAccount` for the credential of one request destination and hands the DeepSeek model routes and web providers its request headers, an invalidation for an HTTP 401, and a signal that aborts at sign-out. The same service releases the API key for consumers the key bills. Clients receive account state through the `account` Remote namespace without credentials.
## Table of Contents
@@ -22,11 +22,12 @@ The `account/` group signs the user in to DeepSeek through the system browser an
## Packages
-One package provides the account feature; its README covers day-to-day use, and the subsystem reference owns the exhaustive contracts.
+Two packages provide the account feature and DeepSeek request authentication; their READMEs cover day-to-day use, and the subsystem reference owns the exhaustive contracts.
| Package | Role | ctx key |
|---|---|---|
| [`deepseek-account/`](deepseek-account/README.md) | Browser sign-in, the stored grant, Platform profile, balance, and notification reads, and Host-only request credentials for allowed destinations | `ctx.deepseekAccount` |
+| [`deepseek-auth/`](deepseek-auth/README.md) | Request authentication for every DeepSeek API consumer: orders the API key and the account sign-in by billing, binds each to its deployment, and releases request headers | `ctx.deepseekAuth` |
-----
diff --git a/packages/account/README.zh.md b/packages/account/README.zh.md
index 1bc1a0a936..ebb259e72d 100644
--- a/packages/account/README.zh.md
+++ b/packages/account/README.zh.md
@@ -1,5 +1,5 @@
---
-description: "DeepSeek 账号能力族的包映射:浏览器登录、已存账号授权,以及向账号模型路由和 DeepSeek Web 提供方释放的仅限 Host 的请求凭据。"
+description: "DeepSeek 账号能力族的包映射:浏览器登录、已存账号授权,以及为每个 DeepSeek API 请求在账号登录与 API 密钥之间选择的请求鉴权。"
kind: "package-group"
---
@@ -9,7 +9,7 @@ kind: "package-group"
## 概述
-`account/` 组通过系统浏览器让用户登录 DeepSeek,并把账号授权保存在 [`credentials/`](../credentials/README.zh.md) 拥有的本地凭据库中。Host 消费方从不读取 token:`deepseek-account` 模型路由和 DeepSeek Web 提供方向 `ctx.deepseekAccount` 索取某个请求目标的凭据,取得其请求头、裸值以及用于 HTTP 401 的失效操作。客户端通过不携带凭据的 `account` Remote 命名空间获得账号状态。
+`account/` 组通过系统浏览器让用户登录 DeepSeek,并把账号授权保存在 [`credentials/`](../credentials/README.zh.md) 拥有的本地凭据库中。Host 消费方从不读取 token:`ctx.deepseekAuth` 向 `ctx.deepseekAccount` 索取某个请求目标的凭据,并把其请求头、用于 HTTP 401 的失效操作以及退出登录时中止的信号交给 DeepSeek 模型路由和 Web 提供方。同一个服务也为由 API 密钥计费的消费方释放密钥。客户端通过不携带凭据的 `account` Remote 命名空间获得账号状态。
## 目录
@@ -22,11 +22,12 @@ kind: "package-group"
## 包
-一个包提供账号功能;它的 README 覆盖日常使用,全部约定以子系统参考为准。
+两个包提供账号功能和 DeepSeek 请求鉴权;它们的 README 覆盖日常使用,全部约定以子系统参考为准。
| 包 | 角色 | ctx 键 |
|---|---|---|
| [`deepseek-account/`](deepseek-account/README.zh.md) | 浏览器登录、已存授权、Platform 资料、余额与通知读取,以及面向允许目标的仅限 Host 的请求凭据 | `ctx.deepseekAccount` |
+| [`deepseek-auth/`](deepseek-auth/README.zh.md) | 面向所有 DeepSeek API 消费方的请求鉴权:按计费方式排定 API 密钥与账号登录的顺序,把每一种绑定到其部署,并释放请求头 | `ctx.deepseekAuth` |
-----
diff --git a/packages/account/deepseek-account/README.i18n.yaml b/packages/account/deepseek-account/README.i18n.yaml
index a102b05ce6..b743611eca 100644
--- a/packages/account/deepseek-account/README.i18n.yaml
+++ b/packages/account/deepseek-account/README.i18n.yaml
@@ -6,8 +6,8 @@
en: 9dbb9bc3960a11fe
zh: ed58987926489d3e
/deepseek-ai-dsh-deepseek-account:
- en: cc98cb1949c9fe0f
- zh: bbb0b8fa319b9abc
+ en: 3943a528cd7abc81
+ zh: 00dfb3ac0eb520b7
/deepseek-ai-dsh-deepseek-account/summary:
en: 28bcca957bf6abf4
zh: 4a3fc8a59f2925bc
diff --git a/packages/account/deepseek-account/README.md b/packages/account/deepseek-account/README.md
index 00de347b8f..5874a8644f 100644
--- a/packages/account/deepseek-account/README.md
+++ b/packages/account/deepseek-account/README.md
@@ -13,7 +13,7 @@ getPlatformSession exports the stored grant only when its issuer matches platfor
`desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin.
-Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures, and a `revoked` signal; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. The account model route and the DeepSeek web providers use it instead of composing headers themselves, and end the request that carries the token when `revoked` aborts.
+Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures, and a `revoked` signal; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. [`ctx.deepseekAuth`](../deepseek-auth/README.md) calls it for the account model route and the DeepSeek web providers, which end the request that carries the token when `revoked` aborts.
## Summary
diff --git a/packages/account/deepseek-account/README.zh.md b/packages/account/deepseek-account/README.zh.md
index f8b0869126..93dede1137 100644
--- a/packages/account/deepseek-account/README.zh.md
+++ b/packages/account/deepseek-account/README.zh.md
@@ -13,7 +13,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导
`desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。
-资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token、`reject()` 和 `revoked` 信号的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头,并在 `revoked` 中止时结束携带该 token 的请求。
+资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、`reject()` 和 `revoked` 信号的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。[`ctx.deepseekAuth`](../deepseek-auth/README.zh.md) 代账号模型路由和 DeepSeek Web 提供方调用它,后两者在 `revoked` 中止时结束携带该 token 的请求。
## 概述
diff --git a/packages/account/deepseek-account/src/index.ts b/packages/account/deepseek-account/src/index.ts
index 54e724a933..de9d559ce1 100644
--- a/packages/account/deepseek-account/src/index.ts
+++ b/packages/account/deepseek-account/src/index.ts
@@ -488,7 +488,6 @@ export class DeepSeekAccount extends TypertRemoteService {
const { ctx } = this
return {
headers: { [ACCOUNT_TOKEN_HEADER]: token },
- value: token,
revoked,
reject: async () => {
try { await ctx.get('deepseekAccount')?.rejectToken(token) }
diff --git a/packages/account/deepseek-account/src/types.ts b/packages/account/deepseek-account/src/types.ts
index eac08b8a4a..a9c8344441 100644
--- a/packages/account/deepseek-account/src/types.ts
+++ b/packages/account/deepseek-account/src/types.ts
@@ -118,8 +118,6 @@ declare module '@deepseek-ai/cordis' {
export interface AccountRequestCredential {
/** Request headers carrying the account token. */
readonly headers: Readonly>
- /** The bare token. */
- readonly value: string
/**
* Remove the stored token after the destination rejected it, unless a newer
* sign-in replaced it. The removal runs on the account service mounted when
diff --git a/packages/account/deepseek-account/tests/account-stub.ts b/packages/account/deepseek-account/tests/account-stub.ts
index 3f0459dcc8..378b944a7c 100644
--- a/packages/account/deepseek-account/tests/account-stub.ts
+++ b/packages/account/deepseek-account/tests/account-stub.ts
@@ -13,8 +13,8 @@ export interface AccountStubOptions {
}
/**
- * An account service releasing request credentials as the real one does: the token header, the bare token, the
- * sign-out signal, and an invalidation that reports no failure.
+ * An account service releasing request credentials as the real one does: the token header, the sign-out signal,
+ * and an invalidation that reports no failure.
* @param options - token policy, rejection observer, and sign-out signal.
* @returns the stand-in, typed as the service for `ctx.provide`.
*/
@@ -26,7 +26,6 @@ export function accountStub(options: AccountStubOptions): DeepSeekAccount {
if (token === undefined || token.length === 0) return undefined
return {
headers: { [ACCOUNT_TOKEN_HEADER]: token },
- value: token,
revoked: signedOut,
reject: async () => {
try { await options.reject?.(token) }
diff --git a/packages/account/deepseek-account/tests/account.spec.ts b/packages/account/deepseek-account/tests/account.spec.ts
index b352a8773e..76405b1ab7 100644
--- a/packages/account/deepseek-account/tests/account.spec.ts
+++ b/packages/account/deepseek-account/tests/account.spec.ts
@@ -369,7 +369,8 @@ it('allows real account credentials only on the exact official HTTPS origin', as
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({
kind: 'grant', payload: { version: 1, issuer: 'https://platform.deepseek.com', token: 'test-account-token' },
}))
- expect((await f.account.resolveRequestCredential('https://api.deepseek.com/v1'))?.value).toBe('test-account-token')
+ expect((await f.account.resolveRequestCredential('https://api.deepseek.com/v1'))?.headers)
+ .toEqual({ 'x-dsh-auth-token': 'test-account-token' })
for (const url of ['http://api.deepseek.com', 'https://api.deepseek.com.evil.test', 'https://api.deepseek.com:8443', 'https://user@api.deepseek.com']) {
expect(await f.account.resolveRequestCredential(url)).toBeUndefined()
}
@@ -385,7 +386,7 @@ it('releases the request credential for an allowed destination and removes the r
const endpoint = 'http://inference.example.test:8094/v1/tools/search'
expect(await f.account.resolveRequestCredential('https://api.deepseek.com/v1/tools/search')).toBeUndefined()
const credential = await f.account.resolveRequestCredential(endpoint)
- expect(credential).toMatchObject({ headers: { 'x-dsh-auth-token': 'test-account-token' }, value: 'test-account-token' })
+ expect(credential).toMatchObject({ headers: { 'x-dsh-auth-token': 'test-account-token' } })
await credential!.reject()
expect((await f.account.getState()).status).toBe('signed-out')
expect(await f.account.resolveRequestCredential(endpoint)).toBeUndefined()
@@ -609,7 +610,7 @@ it('releases a withdrawn credential when sign-out completes while its token is b
await f.account.signOut(clientMetadata())
release.resolve(undefined)
// The token was read before the sign-out removed it, so the credential must not authenticate a request.
- expect(await pending).toMatchObject({ value: 'test-platform-grant', revoked: { aborted: true } })
+ expect(await pending).toMatchObject({ headers: { 'x-dsh-auth-token': 'test-platform-grant' }, revoked: { aborted: true } })
} finally { read.mockRestore() }
})
@@ -1020,7 +1021,8 @@ it('sends a development grant only to its configured inference origin', async ()
await f.wait('waiting-browser')
await fetch(f.callback(), { redirect: 'manual' })
await f.wait('succeeded')
- expect((await f.account.resolveRequestCredential('http://inference.example.test:8094/api'))?.value).toBe('test-account-token')
+ expect((await f.account.resolveRequestCredential('http://inference.example.test:8094/api'))?.headers)
+ .toEqual({ 'x-dsh-auth-token': 'test-account-token' })
for (const url of ['https://api.deepseek.com', 'http://inference.example.test:8095/api',
'https://inference.example.test:8094/api', 'http://user@inference.example.test:8094/api']) {
expect(await f.account.resolveRequestCredential(url)).toBeUndefined()
diff --git a/packages/account/deepseek-auth/README.i18n.yaml b/packages/account/deepseek-auth/README.i18n.yaml
new file mode 100644
index 0000000000..298add1e63
--- /dev/null
+++ b/packages/account/deepseek-auth/README.i18n.yaml
@@ -0,0 +1,58 @@
+# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
+# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
+# After editing either side, bring the other along and re-record with:
+# pnpm run verify-translation-pairing --write packages/account/deepseek-auth/README.md
+/:
+ en: 72aa9af5bb4b9d47
+ zh: 0474d8db22dbf845
+/deepseek-ai-dsh-deepseek-auth:
+ en: 819d59b8b22bf985
+ zh: 3f919581e5639cca
+/deepseek-ai-dsh-deepseek-auth/summary:
+ en: 27b451d236a03881
+ zh: 2eb02aed4c4ab1b3
+/deepseek-ai-dsh-deepseek-auth/table-of-contents:
+ en: d152484eb41ac6b4
+ zh: 09388d293f9be9cb
+/deepseek-ai-dsh-deepseek-auth/use-this-package:
+ en: 475c8fce4a8aa18f
+ zh: c5a2b3c20dc3ee53
+/deepseek-ai-dsh-deepseek-auth/use-this-package/when-to-use-it:
+ en: 5ae5865ce8e74ca9
+ zh: f35aa7f2742a1e76
+/deepseek-ai-dsh-deepseek-auth/use-this-package/authorizing-a-request:
+ en: 02b641a20536ed3e
+ zh: cf704140423f4091
+/deepseek-ai-dsh-deepseek-auth/use-this-package/where-each-kind-s-credential-and-deployment-come-from:
+ en: b909920465406991
+ zh: babec6024f3741a0
+/deepseek-ai-dsh-deepseek-auth/use-this-package/what-can-go-wrong:
+ en: 6b4a01982c7a435b
+ zh: 188c13fea190a619
+/deepseek-ai-dsh-deepseek-auth/understand-the-implementation:
+ en: 6133f3219e92d614
+ zh: d4f47c8fe96bbb83
+/deepseek-ai-dsh-deepseek-auth/understand-the-implementation/design-philosophy:
+ en: 781040be419e91c6
+ zh: fd7cfff0a180a6ca
+/deepseek-ai-dsh-deepseek-auth/understand-the-implementation/source-map:
+ en: 28159a33fcde18a3
+ zh: 8e29411be0a9efe7
+/deepseek-ai-dsh-deepseek-auth/understand-the-implementation/lifecycle:
+ en: 410428e4e26f97ee
+ zh: b0fff475dfebe3ad
+/deepseek-ai-dsh-deepseek-auth/further-exploration:
+ en: 4d9c163447511873
+ zh: 39cd847064374250
+/deepseek-ai-dsh-deepseek-auth/model-experience:
+ en: fe5289b96181fa86
+ zh: 186fd56ec8423081
+/deepseek-ai-dsh-deepseek-auth/model-experience/kv-cache-effect:
+ en: 8d28a9884785f30c
+ zh: b1c45c04e1a543d7
+/deepseek-ai-dsh-deepseek-auth/known-limitations-and-deferred-work:
+ en: d2fd57e36ce7b03a
+ zh: f105c8dbd169db9e
+/deepseek-ai-dsh-deepseek-auth/known-limitations-and-deferred-work/dev-note:
+ en: e3eca6e1556f695c
+ zh: 7234e0729568e2e9
diff --git a/packages/account/deepseek-auth/README.md b/packages/account/deepseek-auth/README.md
new file mode 100644
index 0000000000..47351cb2b7
--- /dev/null
+++ b/packages/account/deepseek-auth/README.md
@@ -0,0 +1,179 @@
+---
+description: "DeepSeek request authentication for plugins that call a DeepSeek API: one service chooses between the API key and the account sign-in, binds the credential to its deployment, and releases the request headers."
+kind: "package-reference"
+---
+
+# @deepseek-ai/dsh-deepseek-auth
+
+English | [中文](README.zh.md)
+
+## Summary
+
+`dsh-deepseek-auth` authenticates requests to DeepSeek APIs through `ctx.deepseekAuth`. A consumer names the credential kinds its API accepts, the API key, the account sign-in, or both, and the billing its settings choose. The service orders the kinds, binds each to the deployment its credential belongs to, and releases the headers of the first kind that has a credential. The DeepSeek model routes, the Search and Fetch APIs, and Messages search use it. It stores nothing: keys come from the credential store or the launch environment, and the sign-in from the account service.
+
+## Table of Contents
+
+- [Use this package](#use-this-package)
+- [Understand the implementation](#understand-the-implementation)
+- [Further Exploration](#further-exploration)
+- [Model Experience](#model-experience)
+- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
+- [Dev Note](#dev-note)
+
+-----
+
+
+## Use this package
+
+A plugin that calls a DeepSeek API asks this service for the credential of one request. The plugin sends the request itself and words its own failures.
+
+### When to use it
+
+Use it for every request a Host plugin sends to a DeepSeek deployment. Mount it in every composition that mounts a DeepSeek model route or a DeepSeek web provider; those plugins require it. It needs no configuration. It reads the credentials service and the account service when they are mounted and works without either.
+
+### Authorizing a request
+
+```ts
+import type { Context } from '@deepseek-ai/cordis'
+import type {} from '@deepseek-ai/dsh-deepseek-auth'
+
+declare const ctx: Context
+declare const route: string | undefined // provider route of the conversation's latest model request
+declare const signal: AbortSignal
+
+const authorization = await ctx.deepseekAuth.authorize({
+ consumer: 'my-plugin',
+ accepts: ['account', 'api-key'],
+ billing: 'auto',
+ route,
+ destination: { path: '/v1/tools/search' },
+}, signal)
+if (authorization === undefined) throw new Error('no DeepSeek credential is configured')
+await fetch(authorization.endpoint, { method: 'POST', headers: authorization.headers, signal })
+```
+
+`accepts` lists the kinds the destination API accepts; a kind outside it is never tried. When an API starts to accept another kind, its consumer adds that kind to `accepts`, and nothing else changes. `billing` is `api-key`, `account`, or `auto`, which follows the model route of the conversation:
+
+| `billing` | Conversation's model route | Kinds tried, in order |
+|---|---|---|
+| `api-key` | any | API key |
+| `account` | any | account sign-in |
+| `auto` | the route connected for the account sign-in, `deepseek-account` | account sign-in, then API key |
+| `auto` | the route connected for the API key, `deepseek-official` | API key |
+| `auto` | any other route, or no conversation | API key, then account sign-in |
+
+A route belongs to the first two `auto` rows only while the plugin that registers it is mounted and has connected it. A conversation recorded on `deepseek-account` or `deepseek-official` whose plugin is not mounted follows the last row.
+
+`destination` is a path appended to the origin of the chosen kind's deployment, or one absolute `url`. A kind serves an absolute URL only when the URL is under the origin of that kind's deployment and embeds no credentials, so a key is never sent to another origin.
+
+An authorization carries the `kind`, the `endpoint`, and the request `headers`. An API key is sent as `Authorization: Bearer` unless `apiKeyHeaders` names `x-api-key` or both; the account sign-in is sent in the header the account service chooses. `reject()`, present for the account sign-in, invalidates the credential after the destination answered HTTP 401. `revoked`, also present for the account sign-in, aborts when the account signs out: the consumer ends the request it authenticated and reports that end as its own failure, not as the caller's cancellation.
+
+`candidates(request)` returns the same kinds in the same order without reading a credential. Each candidate answers `configured()` for readiness checks and `resolve(signal)` for the credential, and names its `endpoint` and, for an API key, its `reference` for diagnostics. `routeKind(route)` names the kind a mounted model route plugin connected under that route id, and `undefined` for every other route.
+
+### Where each kind's credential and deployment come from
+
+| Kind | With its model route mounted | Without it |
+|---|---|---|
+| API key | The key reference and base URL of the `deepseek-official` route's settings, which the Models page edits | `DEEPSEEK_API_KEY`, sent to `https://api.deepseek.com` |
+| Account sign-in | The account service's credential, sent to the origin of the `deepseek-account` route's base URL | The account service's credential, sent to the origin `DEEPSEEK_BASE_URL` names, the official API by default |
+
+A model route plugin connects the provider route it registers and its settings from within `ctx.effect()`:
+
+```ts
+import type { Context } from '@deepseek-ai/cordis'
+import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import type {} from '@deepseek-ai/dsh-deepseek-auth'
+
+declare const ctx: Context
+declare const settings: () => { baseURL: string; apiKeyEnv: string }
+
+ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => {
+ const { baseURL, apiKeyEnv } = settings()
+ return { baseURL, reference: credentialRef(apiKeyEnv), owner: 'llm-deepseek' }
+}))
+```
+
+The service calls the function for each request, so a settings change reaches the next request. While the connection exists, `auto` billing orders a conversation on that route by the connected kind. A request can carry its own connection of a kind in `connections`, which replaces the connected or default one: a model route passes the configuration generation it captured for one model request, and a consumer with its own endpoint and key passes those.
+
+A key is read through the credentials service when one is mounted and through the launch environment otherwise, as [`dsh-credentials`](../../credentials/credentials/README.md) defines for references.
+
+### What can go wrong
+
+- `authorize()` returns `undefined` when no candidate has a credential. The consumer words the failure; `candidates()` supplies the kinds and the key reference to name.
+- An API key that is blank or holds characters no HTTP header can carry fails with `DeepSeekAuthError` code `INVALID_CREDENTIAL`. The message names the owner and the reference to fix and never the key.
+- A kind whose connection does not resolve, because the route's settings throw, a base URL does not parse, or `DEEPSEEK_BASE_URL` is no HTTP(S) URL, appears in `candidates()` as an unresolved entry. `authorize()` stops there with code `UNRESOLVED_CONNECTION` and does not try a later kind.
+- A second `connect()` of one kind throws `DUPLICATE_CONNECTION`.
+- Credential store failures propagate.
+
+-----
+
+
+## Understand the implementation
+
+
+Implementation internals — click to expand
+
+This section explains the design decisions behind the service; the observable behavior is covered in [Use this package](#use-this-package).
+
+### Design philosophy
+
+- **Consumers declare what their API accepts; the service chooses.** DeepSeek adds account authentication to its APIs one at a time. A consumer's `accepts` list is the only place that records what one API accepts, so widening it is the whole change when an API gains a kind.
+- **A credential is bound to its deployment.** Each kind has one deployment at a time, and a credential is released only for destinations under that deployment's origin.
+- **The model routes are consumers.** The route plugins connect their settings and ask for authorization like every other consumer, so the transport and the model service hold no credential interface.
+- **The service depends on no consumer.** It reads the credential store and the account service and names no model route: each route plugin passes its own route id when it connects, and `auto` billing compares the conversation's route with the connected ids.
+
+### Source map
+
+| File | Role |
+|---|---|
+| [`src/index.ts`](src/index.ts) | The service: connections, billing order, destination binding, the API-key and account sources, `DeepSeekAuthError` |
+| [`src/types.ts`](src/types.ts) | Request, connection, candidate, and authorization types |
+
+### Lifecycle
+
+The service holds only the connections model route plugins registered; each disposer removes one. Nothing else is retained between requests: every `candidates()` call reads the connected settings again, and every `resolve()` reads the credential again.
+
+
+
+-----
+
+
+## Further Exploration
+
+- [Account package map](../README.md) — the account service and this service.
+- [DeepSeek account subsystem](../../../docs/subsystems/account.md) — the account sign-in and the request credentials this service releases.
+- [Credential-reference seam](../../credentials/credentials/README.md) — how a key reference is read and checked.
+- [DeepSeek request authentication](../../../.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md) — the decision and its rejected alternatives.
+
+-----
+
+
+## Model Experience
+
+None, as the service releases request headers to Host plugins and contributes nothing to a model request's content. Its consumers word the failures a model reads.
+
+#### KV Cache effect
+
+No invalidation; no credential enters a request prefix.
+
+## Known Limitations and Deferred Work
+
+
+
+These limits define when this package is a poor fit or needs special care. They are current package constraints, not a task backlog.
+
+- **One deployment per kind** — a second `deepseek-official` style route with its own key and endpoint cannot connect; a consumer that needs another key passes its own connection in the request.
+- **A route counts as a DeepSeek route only while its plugin is connected** — a conversation recorded on `deepseek-account` or `deepseek-official` follows the order of other routes, API key and then account sign-in, while that plugin is not mounted, and so does a DeepSeek model reached through another provider plugin.
+- **No credential validation** — `configured()` reports presence only, so a wrong key counts as configured until the destination rejects it.
+
+
+### Dev Note
+
+
+Working context for maintainers — click to expand
+
+This Dev Note is working context for maintainers: open questions and undecided directions. It is explicitly non-authoritative — shipped behavior, limits, and accepted rationale live in the sections above, the package code, and the linked Agent Note.
+
+The speech and document APIs under `/v1/tools/` accept only the API key today. Their consumers declare `accepts: ['api-key']` and add `account` when the server accepts the account sign-in.
+
+
diff --git a/packages/account/deepseek-auth/README.zh.md b/packages/account/deepseek-auth/README.zh.md
new file mode 100644
index 0000000000..46b601da85
--- /dev/null
+++ b/packages/account/deepseek-auth/README.zh.md
@@ -0,0 +1,179 @@
+---
+description: "面向调用 DeepSeek API 的插件的 DeepSeek 请求鉴权:一个服务在 API 密钥与账号登录之间选择,把凭据绑定到它所属的部署,并释放请求头。"
+kind: "package-reference"
+---
+
+# @deepseek-ai/dsh-deepseek-auth
+
+[English](README.md) | 中文
+
+## 概述
+
+`dsh-deepseek-auth` 通过 `ctx.deepseekAuth` 为发往 DeepSeek API 的请求鉴权。消费方给出其 API 接受的凭据种类(API 密钥、账号登录,或两者)以及其设置选择的计费方式。服务排定种类的顺序,把每一种绑定到其凭据所属的部署,并释放第一个持有凭据的种类的请求头。DeepSeek 模型路由、Search 与 Fetch API、Messages 搜索都使用它。它不存储任何东西:密钥来自凭据存储或启动环境,登录凭据来自账号服务。
+
+## 目录
+
+- [使用本包](#use-this-package)
+- [理解实现](#understand-the-implementation)
+- [进一步探索](#further-exploration)
+- [模型体验](#model-experience)
+- [已知限制与延期工作](#known-limitations-and-deferred-work)
+- [开发备注](#dev-note)
+
+-----
+
+
+## 使用本包
+
+调用 DeepSeek API 的插件向本服务索取一次请求的凭据。请求由插件自己发送,失败的措辞也由插件自己决定。
+
+### 何时使用
+
+Host 插件发往 DeepSeek 部署的每一个请求都使用它。凡是挂载了 DeepSeek 模型路由或 DeepSeek Web 提供方的组合都要挂载它,这些插件依赖它。它不需要配置。凭据服务和账号服务已挂载时它会读取它们,两者都没有时也能工作。
+
+### 为请求鉴权
+
+```ts
+import type { Context } from '@deepseek-ai/cordis'
+import type {} from '@deepseek-ai/dsh-deepseek-auth'
+
+declare const ctx: Context
+declare const route: string | undefined // provider route of the conversation's latest model request
+declare const signal: AbortSignal
+
+const authorization = await ctx.deepseekAuth.authorize({
+ consumer: 'my-plugin',
+ accepts: ['account', 'api-key'],
+ billing: 'auto',
+ route,
+ destination: { path: '/v1/tools/search' },
+}, signal)
+if (authorization === undefined) throw new Error('no DeepSeek credential is configured')
+await fetch(authorization.endpoint, { method: 'POST', headers: authorization.headers, signal })
+```
+
+`accepts` 列出目标 API 接受的种类,不在其中的种类不会被尝试。某个 API 开始接受另一种凭据时,它的消费方把该种类加入 `accepts`,其余不变。`billing` 取 `api-key`、`account` 或 `auto`,`auto` 跟随会话的模型路由:
+
+| `billing` | 会话的模型路由 | 依次尝试的种类 |
+|---|---|---|
+| `api-key` | 任意 | API 密钥 |
+| `account` | 任意 | 账号登录 |
+| `auto` | 为账号登录登记的路由,即 `deepseek-account` | 账号登录,然后 API 密钥 |
+| `auto` | 为 API 密钥登记的路由,即 `deepseek-official` | API 密钥 |
+| `auto` | 其他任何路由,或不在会话中 | API 密钥,然后账号登录 |
+
+只有注册某条路由的插件已挂载并登记了它,该路由才属于前两行 `auto`。记录在 `deepseek-account` 或 `deepseek-official` 上的会话,在对应插件未挂载时按最后一行处理。
+
+`destination` 是拼接到所选种类部署 origin 之后的路径,或一个绝对 `url`。只有当绝对 URL 位于某种类部署的 origin 之下且不内嵌凭据时,该种类才为它服务,因此密钥不会被发往其他 origin。
+
+一次授权携带 `kind`、`endpoint` 和请求 `headers`。API 密钥以 `Authorization: Bearer` 发送,除非 `apiKeyHeaders` 指定 `x-api-key` 或两者;账号登录凭据放在账号服务选定的请求头里。`reject()` 只在账号登录时存在,用于在目标返回 HTTP 401 后作废该凭据。`revoked` 同样只在账号登录时存在,账号退出登录时中止:消费方结束它鉴权的请求,并把这次结束报告为自身的失败,而不是调用方的取消。
+
+`candidates(request)` 以相同顺序返回相同的种类,但不读取凭据。每个候选用 `configured()` 回答就绪检查,用 `resolve(signal)` 给出凭据,并给出 `endpoint`,API 密钥还给出供诊断使用的 `reference`。`routeKind(route)` 给出已挂载的模型路由插件在该路由 id 下登记的种类,其他路由一律为 `undefined`。
+
+### 每种凭据及其部署的来源
+
+| 种类 | 其模型路由已挂载 | 未挂载 |
+|---|---|---|
+| API 密钥 | `deepseek-official` 路由设置里的密钥引用和 base URL,即 Models 页面编辑的那份 | `DEEPSEEK_API_KEY`,发往 `https://api.deepseek.com` |
+| 账号登录 | 账号服务的凭据,发往 `deepseek-account` 路由 base URL 的 origin | 账号服务的凭据,发往 `DEEPSEEK_BASE_URL` 所指的 origin,默认为官方 API |
+
+模型路由插件在 `ctx.effect()` 内登记它注册的提供方路由和自己的设置:
+
+```ts
+import type { Context } from '@deepseek-ai/cordis'
+import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import type {} from '@deepseek-ai/dsh-deepseek-auth'
+
+declare const ctx: Context
+declare const settings: () => { baseURL: string; apiKeyEnv: string }
+
+ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => {
+ const { baseURL, apiKeyEnv } = settings()
+ return { baseURL, reference: credentialRef(apiKeyEnv), owner: 'llm-deepseek' }
+}))
+```
+
+服务对每个请求调用这个函数,所以设置的改动在下一个请求生效。连接存在期间,`auto` 计费按所登记的种类排定该路由上会话的顺序。请求可以在 `connections` 里携带某一种类自己的连接,它取代已登记的或默认的连接:模型路由传入它为一次模型请求捕获的那一代配置,拥有自己端点和密钥的消费方传入这两项。
+
+密钥在凭据服务已挂载时经由它读取,否则经由启动环境读取,规则由 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 为引用定义。
+
+### 可能出错的地方
+
+- 没有候选持有凭据时,`authorize()` 返回 `undefined`。失败的措辞由消费方决定;`candidates()` 提供要指出的种类和密钥引用。
+- 空白的或含有 HTTP 请求头无法携带的字符的 API 密钥,以 `DeepSeekAuthError`(代码 `INVALID_CREDENTIAL`)失败。消息指出属主和要修正的引用,不包含密钥。
+- 连接无法解析的种类(路由设置抛出、base URL 无法解析,或 `DEEPSEEK_BASE_URL` 不是 HTTP(S) URL)在 `candidates()` 中表现为未解析条目。`authorize()` 在此以代码 `UNRESOLVED_CONNECTION` 停止,不再尝试后面的种类。
+- 对同一种类第二次 `connect()` 抛出 `DUPLICATE_CONNECTION`。
+- 凭据存储的失败向上传播。
+
+-----
+
+
+## 理解实现
+
+
+实现细节——点击展开
+
+本节解释服务背后的设计决策;可观察的行为见[使用本包](#use-this-package)。
+
+### 设计理念
+
+- **消费方声明其 API 接受什么,服务负责选择。** DeepSeek 逐个为它的 API 增加账号鉴权。消费方的 `accepts` 列表是记录某个 API 接受什么的唯一位置,所以 API 新增一种凭据时,扩充这个列表就是全部改动。
+- **凭据绑定到它的部署。** 每个种类同一时间只有一个部署,凭据只释放给该部署 origin 之下的目标。
+- **模型路由也是消费方。** 路由插件登记自己的设置,并和其他消费方一样索取授权,因此传输层和模型服务不带任何凭据接口。
+- **服务不依赖任何消费方。** 它读取凭据存储和账号服务,自身不写任何模型路由的名字:每个路由插件在登记时传入自己的路由 id,`auto` 计费把会话的路由与已登记的 id 比较。
+
+### 源码地图
+
+| 文件 | 职责 |
+|---|---|
+| [`src/index.ts`](src/index.ts) | 服务本体:连接、计费顺序、目标绑定、API 密钥来源与账号来源、`DeepSeekAuthError` |
+| [`src/types.ts`](src/types.ts) | 请求、连接、候选与授权的类型 |
+
+### 生命周期
+
+服务只保存模型路由插件登记的连接,每个 disposer 移除一个。请求之间不保留其他任何东西:每次 `candidates()` 调用都重新读取已登记的设置,每次 `resolve()` 都重新读取凭据。
+
+
+
+-----
+
+
+## 进一步探索
+
+- [账号包映射](../README.zh.md)——账号服务与本服务。
+- [DeepSeek 账号子系统](../../../docs/subsystems/account.zh.md)——账号登录以及本服务释放的请求凭据。
+- [凭据引用 seam](../../credentials/credentials/README.zh.md)——密钥引用如何读取与检查。
+- [DeepSeek 请求鉴权](../../../.agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.zh.md)——决策及被否决的替代方案。
+
+-----
+
+
+## 模型体验
+
+无,因为本服务向 Host 插件释放请求头,不向模型请求的内容贡献任何东西。模型读到的失败文案由它的消费方措辞。
+
+#### KV Cache 影响
+
+不失效;没有凭据进入请求前缀。
+
+## 已知限制与延期工作
+
+
+
+这些限制说明本包在何时不适用或需要特别注意。它们是当前的包约束,不是任务积压。
+
+- **每个种类一个部署**——第二条带有自己密钥和端点的 `deepseek-official` 式路由无法登记;需要另一把密钥的消费方在请求里传入自己的连接。
+- **路由只在其插件已登记时才算 DeepSeek 路由**——记录在 `deepseek-account` 或 `deepseek-official` 上的会话,在对应插件未挂载时按其他路由的顺序处理(先 API 密钥,后账号登录);经由其他提供方插件访问的 DeepSeek 模型也是如此。
+- **不校验凭据**——`configured()` 只报告是否存在,所以错误的密钥在目标拒绝它之前都算已配置。
+
+
+### 开发备注
+
+
+维护者的工作上下文——点击展开
+
+本开发备注是维护者的工作上下文:未决问题和尚未确定的方向。它明确不具权威性——已交付的行为、限制和已接受的理由见上文各节、包代码和链接的 Agent Note。
+
+`/v1/tools/` 下的语音和文档 API 目前只接受 API 密钥。它们的消费方声明 `accepts: ['api-key']`,待服务端接受账号登录后再加入 `account`。
+
+
diff --git a/packages/account/deepseek-auth/locale/de.json b/packages/account/deepseek-auth/locale/de.json
new file mode 100644
index 0000000000..f200c66d81
--- /dev/null
+++ b/packages/account/deepseek-auth/locale/de.json
@@ -0,0 +1,6 @@
+{
+ "meta": {
+ "title": "DeepSeek-Anfrageauthentifizierung",
+ "description": "Wählt für jede Anfrage an DeepSeek den API-Schlüssel oder die Kontoanmeldung aus und stellt die Anfrage-Header bereit."
+ }
+}
diff --git a/packages/account/deepseek-auth/locale/en.json b/packages/account/deepseek-auth/locale/en.json
new file mode 100644
index 0000000000..83575d3add
--- /dev/null
+++ b/packages/account/deepseek-auth/locale/en.json
@@ -0,0 +1,5 @@
+{
+ "meta": {
+ "title": "DeepSeek request authentication"
+ }
+}
diff --git a/packages/account/deepseek-auth/locale/es.json b/packages/account/deepseek-auth/locale/es.json
new file mode 100644
index 0000000000..121319486a
--- /dev/null
+++ b/packages/account/deepseek-auth/locale/es.json
@@ -0,0 +1,6 @@
+{
+ "meta": {
+ "title": "Autenticación de solicitudes de DeepSeek",
+ "description": "Elige la clave de API o el inicio de sesión de la cuenta para cada solicitud a DeepSeek y proporciona los encabezados de la solicitud."
+ }
+}
diff --git a/packages/account/deepseek-auth/locale/fr.json b/packages/account/deepseek-auth/locale/fr.json
new file mode 100644
index 0000000000..c394c678b5
--- /dev/null
+++ b/packages/account/deepseek-auth/locale/fr.json
@@ -0,0 +1,6 @@
+{
+ "meta": {
+ "title": "Authentification des requêtes DeepSeek",
+ "description": "Choisit la clé API ou la connexion au compte pour chaque requête envoyée à DeepSeek et fournit les en-têtes de la requête."
+ }
+}
diff --git a/packages/account/deepseek-auth/locale/ja.json b/packages/account/deepseek-auth/locale/ja.json
new file mode 100644
index 0000000000..dec87782e2
--- /dev/null
+++ b/packages/account/deepseek-auth/locale/ja.json
@@ -0,0 +1,6 @@
+{
+ "meta": {
+ "title": "DeepSeek リクエスト認証",
+ "description": "DeepSeek へのリクエストごとに API キーまたはアカウントログインを選び、リクエストヘッダーを提供します。"
+ }
+}
diff --git a/packages/account/deepseek-auth/locale/pt.json b/packages/account/deepseek-auth/locale/pt.json
new file mode 100644
index 0000000000..05f54d9796
--- /dev/null
+++ b/packages/account/deepseek-auth/locale/pt.json
@@ -0,0 +1,6 @@
+{
+ "meta": {
+ "title": "Autenticação de solicitações DeepSeek",
+ "description": "Escolhe a chave de API ou o login da conta para cada solicitação ao DeepSeek e fornece os cabeçalhos da solicitação."
+ }
+}
diff --git a/packages/account/deepseek-auth/locale/ru.json b/packages/account/deepseek-auth/locale/ru.json
new file mode 100644
index 0000000000..440f8c5283
--- /dev/null
+++ b/packages/account/deepseek-auth/locale/ru.json
@@ -0,0 +1,6 @@
+{
+ "meta": {
+ "title": "Аутентификация запросов DeepSeek",
+ "description": "Выбирает ключ API или вход в учётную запись для каждого запроса к DeepSeek и предоставляет заголовки запроса."
+ }
+}
diff --git a/packages/account/deepseek-auth/locale/zh.json b/packages/account/deepseek-auth/locale/zh.json
new file mode 100644
index 0000000000..f56f4de411
--- /dev/null
+++ b/packages/account/deepseek-auth/locale/zh.json
@@ -0,0 +1,6 @@
+{
+ "meta": {
+ "title": "DeepSeek 请求鉴权",
+ "description": "为发往 DeepSeek 的每个请求选择 API 密钥或账号登录,并提供请求头。"
+ }
+}
diff --git a/packages/account/deepseek-auth/package.json b/packages/account/deepseek-auth/package.json
new file mode 100644
index 0000000000..db3ef2e785
--- /dev/null
+++ b/packages/account/deepseek-auth/package.json
@@ -0,0 +1,58 @@
+{
+ "name": "@deepseek-ai/dsh-deepseek-auth",
+ "description": "DeepSeek request authentication (ctx.deepseekAuth): choose between the API key and the account sign-in for one DeepSeek API request and release its headers",
+ "version": "0.2.2-rc.3",
+ "publishConfig": {
+ "access": "public"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
+ "directory": "packages/account/deepseek-auth"
+ },
+ "type": "module",
+ "main": "lib/index.js",
+ "types": "lib/types/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./lib/types/index.d.ts",
+ "default": "./lib/index.js"
+ },
+ "./types": {
+ "types": "./lib/types/types.d.ts",
+ "default": "./lib/types/types.js"
+ },
+ "./src/*": "./src/*",
+ "./package.json": "./package.json",
+ "./locale/*.json": "./locale/*.json"
+ },
+ "files": [
+ "locale/*.json",
+ "lib/index.js",
+ "lib/types/**/*.js",
+ "lib/types/**/*.d.ts",
+ "lib/types/**/*.d.ts.map",
+ "lib/**/*.js.map",
+ "src"
+ ],
+ "license": "MIT",
+ "peerDependencies": {
+ "@deepseek-ai/cordis": "workspace:~",
+ "@deepseek-ai/dsh-credentials": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-account": "workspace:*",
+ "@deepseek-ai/dsh-error": "workspace:*",
+ "@deepseek-ai/dsh-launch-environment": "workspace:*"
+ },
+ "peerDependenciesMeta": {
+ "@deepseek-ai/dsh-deepseek-account": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "@deepseek-ai/cordis": "workspace:~",
+ "@deepseek-ai/dsh-credentials": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-account": "workspace:*",
+ "@deepseek-ai/dsh-error": "workspace:*",
+ "@deepseek-ai/dsh-launch-environment": "workspace:*"
+ }
+}
diff --git a/packages/account/deepseek-auth/src/index.ts b/packages/account/deepseek-auth/src/index.ts
new file mode 100644
index 0000000000..ba2a4d6aa5
--- /dev/null
+++ b/packages/account/deepseek-auth/src/index.ts
@@ -0,0 +1,257 @@
+/**
+ * DeepSeek request authentication (`ctx.deepseekAuth`). DeepSeek APIs accept two kinds of credential, the API key and
+ * the account sign-in, and each API accepts one or both. A consumer names the kinds its API accepts and the billing
+ * its settings choose; this service orders the kinds, binds each to the deployment its credential belongs to, and
+ * releases the request headers of the first kind that has a credential. Model route plugins connect the deployment
+ * their settings name; without a connection the API key is `DEEPSEEK_API_KEY` at the official API and the account
+ * sign-in goes to the deployment `DEEPSEEK_BASE_URL` names.
+ *
+ * ```ts
+ * const authorization = await ctx.deepseekAuth.authorize({
+ * consumer: name, accepts: ['account', 'api-key'], billing: 'auto', route, destination: { path: '/v1/tools/search' },
+ * }, signal)
+ * ```
+ *
+ * @module @deepseek-ai/dsh-deepseek-auth
+ */
+import { Context, Service } from '@deepseek-ai/cordis'
+import { credentialRef, credentialRefConfigured, normalizeApiKey, resolveCredentialRef } from '@deepseek-ai/dsh-credentials'
+import type { ApiKeyRejection } from '@deepseek-ai/dsh-credentials'
+import type {} from '@deepseek-ai/dsh-deepseek-account'
+import { HarnessError } from '@deepseek-ai/dsh-error'
+import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
+import type {
+ DeepSeekAuthCandidate, DeepSeekAuthConnection, DeepSeekAuthKind, DeepSeekAuthRequest, DeepSeekAuthUnresolved,
+ DeepSeekAuthorization,
+} from './types.ts'
+
+export type * from './types.ts'
+
+declare module '@deepseek-ai/cordis' {
+ interface Context { deepseekAuth: DeepSeekAuth }
+}
+
+/** Base URL of the official DeepSeek API, where `DEEPSEEK_API_KEY` is sent without a connected API-key route. */
+const OFFICIAL_BASE_URL = 'https://api.deepseek.com'
+
+/** Credential reference of the official DeepSeek API key. */
+const DEEPSEEK_API_KEY = credentialRef('DEEPSEEK_API_KEY')
+
+/**
+ * Launch-environment variable naming the DeepSeek deployment the model routes default to. Without a connected account
+ * route, its origin receives the account sign-in.
+ */
+const DEEPSEEK_BASE_URL_ENV = 'DEEPSEEK_BASE_URL'
+
+/** Failure codes of {@link DeepSeekAuthError}. */
+export type DeepSeekAuthErrorCode =
+ /** A second connection of one kind; one model route plugin owns each kind's deployment. */
+ | 'DUPLICATE_CONNECTION'
+ /** The configured API key is blank or cannot travel in an HTTP header. */
+ | 'INVALID_CREDENTIAL'
+ /** The connection of the kind an operation reached does not resolve. */
+ | 'UNRESOLVED_CONNECTION'
+
+/** A DeepSeek authentication failure; `message` never contains a credential. */
+export class DeepSeekAuthError extends HarnessError {
+ declare readonly code: DeepSeekAuthErrorCode
+
+ /**
+ * @param message - what failed and what to change.
+ * @param code - the failure class.
+ * @param options - the underlying failure.
+ */
+ constructor(message: string, code: DeepSeekAuthErrorCode, options?: ErrorOptions) {
+ super(message, code, options)
+ // Consumers quote this name in their own diagnostics, so it does not follow a bundler's class renaming.
+ this.name = 'DeepSeekAuthError'
+ }
+}
+
+/**
+ * The diagnostic for a configured API key that cannot be sent. The key never enters the text: `reference` names where to
+ * fix it. The Models page is named as the writer it usually is, not as the only one, because the same value can arrive
+ * from a hand-edited `.env` or a shell export in a composition that mounts no credentials service.
+ * @param reason - why the key cannot be sent.
+ * @param owner - settings namespace or plugin name prefixed to the text.
+ * @param reference - the credential reference the key was read under.
+ * @returns the message of the `INVALID_CREDENTIAL` failure.
+ */
+function unusableKey(reason: ApiKeyRejection, owner: string, reference: string): string {
+ const defect: Record = {
+ empty: `is blank; set ${reference} to the raw key (the web Models page writes it) or export it in the launching`
+ + ' environment',
+ illegalCharacters: `contains characters no HTTP header can carry; set ${reference} to the raw key alone (the web Models`
+ + ' page writes it)',
+ }
+ return `${owner}: the API key resolved from ${reference} ${defect[reason]}`
+}
+
+/** Marks a failure of the launch-environment deployment, apart from a failure of a connected route's settings. */
+class DeploymentError extends Error {
+ /** @param cause - why the variable's value is no deployment URL. */
+ constructor(cause: unknown) { super('unresolved deployment', { cause }) }
+}
+
+/** `ctx.deepseekAuth`: the two DeepSeek credential kinds behind one request-authorization operation. */
+export class DeepSeekAuth extends Service {
+ private readonly connections = new Map DeepSeekAuthConnection }>()
+
+ /** @param ctx - Host context; the credentials service and the account service are read when mounted. */
+ constructor(ctx: Context) {
+ super(ctx, 'deepseekAuth')
+ }
+
+ /**
+ * Connect the deployment a model route plugin's settings name for one kind. Call it from within `ctx.effect()`.
+ * @param kind - the kind the plugin's route bills.
+ * @param route - provider route the plugin registers; {@link routeKind} answers `kind` for it while connected.
+ * @param connection - reads the plugin's current settings; a throw marks the kind unresolved for that operation.
+ * @returns the disposer removing the connection.
+ * @throws {DeepSeekAuthError} code `DUPLICATE_CONNECTION` when the kind is already connected.
+ */
+ connect(kind: DeepSeekAuthKind, route: string, connection: () => DeepSeekAuthConnection): () => void {
+ if (this.connections.has(kind)) {
+ throw new DeepSeekAuthError(`deepseek-auth: the ${kind} deployment is already connected`, 'DUPLICATE_CONNECTION')
+ }
+ this.connections.set(kind, { route, connection })
+ return () => { this.connections.delete(kind) }
+ }
+
+ /**
+ * The kind that bills a conversation on one model route.
+ * @param route - provider route of a model request; undefined names none.
+ * @returns the kind connected under that route, or undefined for a route no plugin connected.
+ */
+ routeKind(route: string | undefined): DeepSeekAuthKind | undefined {
+ for (const [kind, connected] of this.connections) {
+ if (connected.route === route) return kind
+ }
+ return undefined
+ }
+
+ /**
+ * The kinds one request can authenticate with, in the order its billing tries them, each bound to its destination.
+ * Nothing is read from a credential store.
+ * @param request - the request.
+ * @returns candidates and unresolved kinds, first preferred; empty when the destination accepts no kind the
+ * billing allows or no allowed kind serves an absolute destination.
+ */
+ candidates(request: DeepSeekAuthRequest): (DeepSeekAuthCandidate | DeepSeekAuthUnresolved)[] {
+ return this.order(request).filter(kind => request.accepts.includes(kind)).flatMap(kind => this.candidate(kind, request))
+ }
+
+ /**
+ * Release the credential of the first candidate that has one. A later candidate is not read once an earlier one
+ * has a credential, fails to read, or does not resolve.
+ * @param request - the request.
+ * @param signal - cancellation for the lookups.
+ * @returns the authorization, or undefined when no candidate has a credential.
+ * @throws {DeepSeekAuthError} code `UNRESOLVED_CONNECTION` at an unresolved kind, `INVALID_CREDENTIAL` for an
+ * unusable API key; store failures propagate.
+ */
+ async authorize(request: DeepSeekAuthRequest, signal?: AbortSignal): Promise {
+ for (const candidate of this.candidates(request)) {
+ if ('unresolved' in candidate) {
+ throw new DeepSeekAuthError(
+ `deepseek-auth: the ${candidate.kind} ${candidate.unresolved} does not resolve: ${String(candidate.error)}`,
+ 'UNRESOLVED_CONNECTION', { cause: candidate.error },
+ )
+ }
+ const authorization = await candidate.resolve(signal)
+ if (authorization !== undefined) return authorization
+ }
+ return undefined
+ }
+
+ /** The kinds the billing tries, in order, before the destination's accepted kinds narrow them. */
+ private order(request: DeepSeekAuthRequest): DeepSeekAuthKind[] {
+ const billing = request.billing ?? 'auto'
+ if (billing !== 'auto') return [billing]
+ switch (this.routeKind(request.route)) {
+ // A conversation on the account route falls back to the API key.
+ case 'account': return ['account', 'api-key']
+ case 'api-key': return ['api-key']
+ // Every route no plugin connected, whatever its id, and an operation outside a conversation.
+ default: return ['api-key', 'account']
+ }
+ }
+
+ /** Bind one kind to the request's destination; empty when the kind does not serve an absolute destination. */
+ private candidate(kind: DeepSeekAuthKind, request: DeepSeekAuthRequest): (DeepSeekAuthCandidate | DeepSeekAuthUnresolved)[] {
+ let connection: DeepSeekAuthConnection
+ try { connection = request.connections?.[kind] ?? this.connections.get(kind)?.connection() ?? this.unconnected(kind) }
+ catch (error: unknown) {
+ const unresolved = error instanceof DeploymentError ? 'deployment' : 'connection'
+ return [{ kind, unresolved, error: error instanceof DeploymentError ? error.cause : error }]
+ }
+ let endpoint: string
+ try {
+ const deployment = new URL(connection.baseURL)
+ if ('path' in request.destination) endpoint = `${deployment.origin}${request.destination.path}`
+ else {
+ const destination = new URL(request.destination.url)
+ if (destination.origin !== deployment.origin || destination.username !== '' || destination.password !== '') return []
+ endpoint = request.destination.url
+ }
+ } catch (error: unknown) { return [{ kind, unresolved: 'connection', error }] }
+ return [kind === 'api-key' ? this.apiKey(connection, endpoint, request) : this.account(endpoint)]
+ }
+
+ /** The connection of a kind no model route plugin connected. */
+ private unconnected(kind: DeepSeekAuthKind): DeepSeekAuthConnection {
+ if (kind === 'api-key') return { baseURL: OFFICIAL_BASE_URL }
+ const configured = launchEnvironmentOf(this.ctx).get(DEEPSEEK_BASE_URL_ENV)?.value
+ if (configured === undefined || configured.length === 0) return { baseURL: OFFICIAL_BASE_URL }
+ try {
+ const url = new URL(configured)
+ if (!/^https?:$/u.test(url.protocol) || url.username.length > 0 || url.password.length > 0) {
+ throw new Error(`${DEEPSEEK_BASE_URL_ENV} must be an HTTP(S) URL without credentials`)
+ }
+ } catch (error: unknown) { throw new DeploymentError(error) }
+ return { baseURL: configured }
+ }
+
+ /** The API key read under the connection's reference, sent in the headers the request names. */
+ private apiKey(connection: DeepSeekAuthConnection, endpoint: string, request: DeepSeekAuthRequest): DeepSeekAuthCandidate {
+ const { ctx } = this
+ const reference = connection.reference ?? DEEPSEEK_API_KEY
+ const owner = connection.owner ?? request.consumer
+ return {
+ kind: 'api-key', endpoint, reference,
+ configured: () => credentialRefConfigured(ctx, reference),
+ resolve: async (signal) => {
+ signal?.throwIfAborted()
+ const raw = await resolveCredentialRef(ctx, reference)
+ if (raw === undefined) return undefined
+ const checked = normalizeApiKey(raw)
+ if (!checked.ok) throw new DeepSeekAuthError(unusableKey(checked.reason, owner, reference), 'INVALID_CREDENTIAL')
+ const headers: Record = {}
+ for (const header of request.apiKeyHeaders ?? ['authorization']) {
+ headers[header] = header === 'authorization' ? `Bearer ${checked.value}` : checked.value
+ }
+ return { kind: 'api-key', endpoint, reference, headers }
+ },
+ }
+ }
+
+ /** The account sign-in the account service releases for the endpoint; absent without that service. */
+ private account(endpoint: string): DeepSeekAuthCandidate {
+ const { ctx } = this
+ return {
+ kind: 'account', endpoint,
+ configured: async () => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined,
+ resolve: async (signal) => {
+ signal?.throwIfAborted()
+ const credential = await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)
+ if (credential === undefined) return undefined
+ return {
+ kind: 'account', endpoint, headers: credential.headers, revoked: credential.revoked,
+ reject: () => credential.reject(),
+ }
+ },
+ }
+ }
+}
+
+export default DeepSeekAuth
diff --git a/packages/account/deepseek-auth/src/types.ts b/packages/account/deepseek-auth/src/types.ts
new file mode 100644
index 0000000000..e057976336
--- /dev/null
+++ b/packages/account/deepseek-auth/src/types.ts
@@ -0,0 +1,115 @@
+/**
+ * Types of DeepSeek request authentication. Host-only: an authorization carries a secret, so none of these values
+ * crosses a Remote boundary or enters a log.
+ * @module @deepseek-ai/dsh-deepseek-auth/types
+ */
+import type { CredentialRef } from '@deepseek-ai/dsh-credentials'
+
+/** A way to authenticate a DeepSeek API request: the API key, or the account sign-in. */
+export type DeepSeekAuthKind = 'api-key' | 'account'
+
+/** Which credential pays for an operation: one kind only, or `auto`, which follows the conversation's model route. */
+export type DeepSeekAuthBilling = 'auto' | DeepSeekAuthKind
+
+/** Request header an API key is sent in: `authorization` as `Bearer `, `x-api-key` as the bare key. */
+export type DeepSeekApiKeyHeader = 'authorization' | 'x-api-key'
+
+/** The deployment the credential of one kind belongs to and, for the API key, where the key is read. */
+export interface DeepSeekAuthConnection {
+ /** Base URL of the deployment; the credential is sent only to destinations under its origin. */
+ readonly baseURL: string
+ /** API key only: the credential reference the key is read under; `DEEPSEEK_API_KEY` when omitted. */
+ readonly reference?: CredentialRef
+ /**
+ * API key only: the settings namespace or package name prefixed to the diagnostic of an unusable key; the
+ * request's `consumer` when omitted.
+ */
+ readonly owner?: string
+}
+
+/**
+ * Where one request goes: a path appended to the origin of the chosen kind's deployment, or one absolute URL, which a
+ * kind serves only when the URL is under the origin of that kind's deployment and embeds no credentials.
+ */
+export type DeepSeekAuthDestination = { readonly path: string } | { readonly url: string }
+
+/** One DeepSeek API request that needs authentication. */
+export interface DeepSeekAuthRequest {
+ /** Name of the requesting plugin, prefixed to the diagnostic of an unusable key whose connection names no owner. */
+ readonly consumer: string
+ /** Kinds the destination API accepts; a kind outside this list is never a candidate. */
+ readonly accepts: readonly DeepSeekAuthKind[]
+ /** Which credential pays; `auto` when omitted. */
+ readonly billing?: DeepSeekAuthBilling
+ /** Provider route of the model request this operation serves; only `auto` billing reads it. */
+ readonly route?: string | undefined
+ /** Where the request goes. */
+ readonly destination: DeepSeekAuthDestination
+ /**
+ * The caller's own connection of a kind, used in place of the connected or default one: the configuration
+ * generation a model route captured for one request, or a consumer's own endpoint and key.
+ */
+ readonly connections?: Readonly>>
+ /** Headers an API key is sent in; `authorization` when omitted. The account sign-in chooses its own header. */
+ readonly apiKeyHeaders?: readonly DeepSeekApiKeyHeader[]
+}
+
+/** The credential of one kind released for one request, ready to send. */
+export interface DeepSeekAuthorization {
+ /** Kind of the credential. */
+ readonly kind: DeepSeekAuthKind
+ /** Absolute URL the request is sent to. */
+ readonly endpoint: string
+ /** Request headers carrying the credential. */
+ readonly headers: Readonly>
+ /** API key only: the reference the key was read under, for diagnostics that tell the user where to configure it. */
+ readonly reference?: CredentialRef
+ /**
+ * Invalidate this exact credential after the destination rejected it with HTTP 401, so no later request resends
+ * it. Absent for kinds without invalidation. The owner contains storage failures: the caller reports the
+ * destination's rejection, never a failure of this call.
+ * @returns settlement after the invalidation attempt.
+ */
+ reject?(): Promise
+ /**
+ * Aborts when the owner withdraws the credential while requests may carry it, as an account sign-out does. A
+ * consumer ends each request it authenticated with this authorization and reports that end as its own failure,
+ * not as the caller's cancellation. Absent for kinds that are never withdrawn.
+ */
+ readonly revoked?: AbortSignal
+}
+
+/** One kind a request can authenticate with, in the order the billing chose. Nothing is read until asked. */
+export interface DeepSeekAuthCandidate {
+ /** Kind of the credential. */
+ readonly kind: DeepSeekAuthKind
+ /** Absolute URL a request authenticated with this kind is sent to. */
+ readonly endpoint: string
+ /** API key only: the reference the key is read under. */
+ readonly reference?: CredentialRef
+ /**
+ * Whether {@link resolve} would release a credential, checked without validating it or contacting the
+ * destination. Store failures reject.
+ * @returns whether a credential of this kind is configured for the endpoint.
+ */
+ configured(): Promise
+ /**
+ * Release the credential, or `undefined` when none is configured. Store failures and an unusable key reject.
+ * @param signal - cancellation for the lookup.
+ * @returns the authorization, or `undefined`.
+ */
+ resolve(signal?: AbortSignal): Promise
+}
+
+/** A kind the billing chose whose connection does not resolve; an operation that reaches it stops there. */
+export interface DeepSeekAuthUnresolved {
+ /** Kind of the credential. */
+ readonly kind: DeepSeekAuthKind
+ /**
+ * What did not resolve: the `connection` a model route plugin connected or the caller supplied, or the `deployment`
+ * the launch environment names for the account sign-in without a connected account route.
+ */
+ readonly unresolved: 'connection' | 'deployment'
+ /** The failure. */
+ readonly error: unknown
+}
diff --git a/packages/account/deepseek-auth/tests/authorize.spec.ts b/packages/account/deepseek-auth/tests/authorize.spec.ts
new file mode 100644
index 0000000000..4c79233eea
--- /dev/null
+++ b/packages/account/deepseek-auth/tests/authorize.spec.ts
@@ -0,0 +1,137 @@
+/** Reading and releasing the credential of each kind, and choosing the first kind that has one. */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import { DeepSeekAuthError } from '@deepseek-ai/dsh-deepseek-auth'
+import { accountStub } from '../../deepseek-account/tests/account-stub.ts'
+import { candidate, disposeMounted, mount, request } from './harness.ts'
+
+afterEach(disposeMounted)
+
+const SEARCH = 'https://api.deepseek.com/v1/tools/search'
+const key = request({ billing: 'api-key' })
+const signIn = request({ billing: 'account' })
+
+describe('the API key', () => {
+ it('is read under DEEPSEEK_API_KEY and sent as a bearer token by default', async () => {
+ const ctx = await mount({ stored: { DEEPSEEK_API_KEY: ' sk-stored ' } })
+ const [entry] = ctx.deepseekAuth.candidates(key)
+ expect(await candidate(entry).configured()).toBe(true)
+ expect(await ctx.deepseekAuth.authorize(key)).toEqual({
+ kind: 'api-key', endpoint: SEARCH, reference: 'DEEPSEEK_API_KEY', headers: { authorization: 'Bearer sk-stored' },
+ })
+ })
+
+ it.each([
+ [['x-api-key'], { 'x-api-key': 'sk-stored' }],
+ [['x-api-key', 'authorization'], { 'x-api-key': 'sk-stored', 'authorization': 'Bearer sk-stored' }],
+ ] as const)('is sent in the headers the request names: %j', async (apiKeyHeaders, headers) => {
+ const ctx = await mount({ stored: { DEEPSEEK_API_KEY: 'sk-stored' } })
+ expect((await ctx.deepseekAuth.authorize({ ...key, apiKeyHeaders }))?.headers).toEqual(headers)
+ })
+
+ it('is read under the reference of its connection', async () => {
+ const ctx = await mount({ stored: { DEEPSEEK_API_KEY: 'sk-default', ROUTE_KEY: 'sk-route' } })
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => ({ baseURL: 'https://route.deepseek.test', reference: credentialRef('ROUTE_KEY') })))
+ expect(await ctx.deepseekAuth.authorize(key)).toMatchObject({ reference: 'ROUTE_KEY', headers: { authorization: 'Bearer sk-route' } })
+ })
+
+ it('is read from the launch environment only without a credentials service', async () => {
+ const ambient = await mount({ environment: { DEEPSEEK_API_KEY: 'sk-ambient' } })
+ expect((await ambient.deepseekAuth.authorize(key))?.headers).toEqual({ authorization: 'Bearer sk-ambient' })
+ const authoritative = await mount({ environment: { DEEPSEEK_API_KEY: 'sk-ambient' }, stored: {} })
+ expect(await candidate(authoritative.deepseekAuth.candidates(key)[0]).configured()).toBe(false)
+ expect(await authoritative.deepseekAuth.authorize(key)).toBeUndefined()
+ })
+
+ it.each([
+ [
+ ' ', undefined,
+ 'web-test: the API key resolved from DEEPSEEK_API_KEY is blank; set DEEPSEEK_API_KEY to the raw key'
+ + ' (the web Models page writes it) or export it in the launching environment',
+ ],
+ [
+ 'sk-你好', 'llm-deepseek',
+ 'llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry;'
+ + ' set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)',
+ ],
+ ])('refuses the unusable key %j, naming its owner and reference and never the key', async (value, owner, message) => {
+ const ctx = await mount({ stored: { DEEPSEEK_API_KEY: value } })
+ const connections = { 'api-key': { baseURL: 'https://api.deepseek.com', ...owner === undefined ? {} : { owner } } }
+ const failure = await ctx.deepseekAuth.authorize({ ...key, connections }).catch((error: unknown) => error)
+ expect(failure).toBeInstanceOf(DeepSeekAuthError)
+ expect(failure).toMatchObject({ code: 'INVALID_CREDENTIAL', message })
+ })
+
+ it('starts no read for a cancelled lookup', async () => {
+ const ctx = await mount({ stored: { DEEPSEEK_API_KEY: 'sk-stored' } })
+ const reason = new Error('cancelled')
+ await expect(ctx.deepseekAuth.authorize(key, AbortSignal.abort(reason))).rejects.toBe(reason)
+ })
+})
+
+describe('the account sign-in', () => {
+ it('is absent without the account service', async () => {
+ const ctx = await mount()
+ expect(await candidate(ctx.deepseekAuth.candidates(signIn)[0]).configured()).toBe(false)
+ expect(await ctx.deepseekAuth.authorize(signIn)).toBeUndefined()
+ })
+
+ it('is what the account service releases for the endpoint, with its invalidation and its sign-out signal', async () => {
+ const rejected = vi.fn()
+ const signedOut = new AbortController()
+ const asked: string[] = []
+ const account = accountStub({ token: (url) => { asked.push(url); return 'account-token' }, reject: rejected, signedOut: signedOut.signal })
+ const ctx = await mount({ account })
+ expect(await candidate(ctx.deepseekAuth.candidates(signIn)[0]).configured()).toBe(true)
+ const authorization = await ctx.deepseekAuth.authorize(signIn)
+ expect(authorization).toMatchObject({ kind: 'account', endpoint: SEARCH, headers: { 'x-dsh-auth-token': 'account-token' } })
+ expect(authorization?.revoked).toBe(signedOut.signal)
+ expect(asked).toEqual([SEARCH, SEARCH])
+ await authorization?.reject?.()
+ expect(rejected).toHaveBeenCalledExactlyOnceWith('account-token')
+ })
+
+ it('is absent while the account releases nothing for the endpoint, and starts no read for a cancelled lookup', async () => {
+ const token = vi.fn(() => undefined)
+ const ctx = await mount({ account: accountStub({ token }) })
+ expect(await ctx.deepseekAuth.authorize(signIn)).toBeUndefined()
+ token.mockClear()
+ const reason = new Error('cancelled')
+ await expect(ctx.deepseekAuth.authorize(signIn, AbortSignal.abort(reason))).rejects.toBe(reason)
+ expect(token).not.toHaveBeenCalled()
+ })
+})
+
+describe('authorize', () => {
+ it('releases the first kind that has a credential and does not read a later one', async () => {
+ const token = vi.fn(() => 'account-token')
+ const ctx = await mount({ stored: { DEEPSEEK_API_KEY: 'sk-stored' }, account: accountStub({ token }) })
+ expect(await ctx.deepseekAuth.authorize(request())).toMatchObject({ kind: 'api-key' })
+ expect(token).not.toHaveBeenCalled()
+ })
+
+ it('moves to the next kind when the first has no credential, and releases nothing when none has', async () => {
+ const withAccount = await mount({ stored: {}, account: accountStub({ token: () => 'account-token' }) })
+ expect(await withAccount.deepseekAuth.authorize(request())).toMatchObject({ kind: 'account' })
+ const empty = await mount({ stored: {} })
+ expect(await empty.deepseekAuth.authorize(request())).toBeUndefined()
+ })
+
+ it('stops at an unresolved kind without reading a later one', async () => {
+ const token = vi.fn(() => 'account-token')
+ const ctx = await mount({ account: accountStub({ token }) })
+ const failure = new Error('settings do not resolve')
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => { throw failure }))
+ const stopped = await ctx.deepseekAuth.authorize(request()).catch((error: unknown) => error)
+ expect(stopped).toMatchObject({ code: 'UNRESOLVED_CONNECTION', cause: failure })
+ expect((stopped as Error).message).toContain('the api-key connection does not resolve: Error: settings do not resolve')
+ expect(token).not.toHaveBeenCalled()
+ })
+
+ it('propagates a credential store failure', async () => {
+ const ctx = await mount()
+ const failure = new Error('store unreadable')
+ ctx.provide('credentials', { resolve: () => Promise.reject(failure) } as never)
+ await expect(ctx.deepseekAuth.authorize(key)).rejects.toBe(failure)
+ })
+})
diff --git a/packages/account/deepseek-auth/tests/candidates.spec.ts b/packages/account/deepseek-auth/tests/candidates.spec.ts
new file mode 100644
index 0000000000..8ba3d8c63d
--- /dev/null
+++ b/packages/account/deepseek-auth/tests/candidates.spec.ts
@@ -0,0 +1,115 @@
+/** Which kinds a request can authenticate with, in which order, and where each one is sent. */
+import { afterEach, describe, expect, it } from 'vitest'
+import { DeepSeekAuthError } from '@deepseek-ai/dsh-deepseek-auth'
+import { disposeMounted, mount, request, summary } from './harness.ts'
+
+const OFFICIAL = 'https://api.deepseek.com/v1/tools/search'
+const ROUTE = 'https://route.deepseek.test/anthropic'
+const ACCOUNT = 'https://account.deepseek.test/anthropic'
+
+afterEach(disposeMounted)
+
+describe('billing order', () => {
+ it.each([
+ ['api-key', undefined, ['api-key']],
+ ['api-key', 'deepseek-account', ['api-key']],
+ ['account', 'deepseek-official', ['account']],
+ ['auto', 'deepseek-official', ['api-key']],
+ ['auto', 'deepseek-account', ['account', 'api-key']],
+ ['auto', 'moonshotai', ['api-key', 'account']],
+ ['auto', undefined, ['api-key', 'account']],
+ [undefined, undefined, ['api-key', 'account']],
+ ] as const)('tries %j billing on route %j as %j while both DeepSeek model routes are connected', async (billing, route, kinds) => {
+ const ctx = await mount()
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => ({ baseURL: ROUTE })))
+ ctx.effect(() => ctx.deepseekAuth.connect('account', 'deepseek-account', () => ({ baseURL: ACCOUNT })))
+ const entries = ctx.deepseekAuth.candidates(request({ ...billing === undefined ? {} : { billing }, route }))
+ expect(entries.map(entry => entry.kind)).toEqual(kinds)
+ })
+
+ it('tries the sign-in first in a conversation on the connected account route, then the API key', async () => {
+ const ctx = await mount()
+ ctx.effect(() => ctx.deepseekAuth.connect('account', 'deepseek-account', () => ({ baseURL: ACCOUNT })))
+ expect(summary(ctx.deepseekAuth.candidates(request({ route: 'deepseek-account' })))).toEqual([
+ 'account https://account.deepseek.test/v1/tools/search', `api-key ${OFFICIAL}`,
+ ])
+ })
+
+ it.each(['deepseek-account', 'deepseek-official'])('orders a conversation on route %j as on any other route while no plugin connected that route', async (route) => {
+ const ctx = await mount()
+ expect(summary(ctx.deepseekAuth.candidates(request({ route })))).toEqual([`api-key ${OFFICIAL}`, `account ${OFFICIAL}`])
+ })
+
+ it('never offers a kind the destination does not accept', async () => {
+ const ctx = await mount()
+ expect(summary(ctx.deepseekAuth.candidates(request({ accepts: ['api-key'], destination: { path: '/v1/tools/asr' } }))))
+ .toEqual(['api-key https://api.deepseek.com/v1/tools/asr'])
+ expect(ctx.deepseekAuth.candidates(request({ accepts: ['api-key'], billing: 'account' }))).toEqual([])
+ })
+
+ it('names the kind a route bills by the id its plugin connected, for as long as that plugin stays mounted', async () => {
+ const ctx = await mount()
+ const kinds = () => ['gateway', 'deepseek-account', 'deepseek-official', undefined].map(route => ctx.deepseekAuth.routeKind(route))
+ expect(kinds()).toEqual([undefined, undefined, undefined, undefined])
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'gateway', () => ({ baseURL: ROUTE })))
+ const account = await ctx.plugin({ name: 'account-route', inject: ['deepseekAuth'], apply: (scope: typeof ctx) => {
+ scope.effect(() => scope.deepseekAuth.connect('account', 'deepseek-account', () => ({ baseURL: ACCOUNT })))
+ } })
+ expect(kinds()).toEqual(['api-key', 'account', undefined, undefined])
+ await account.dispose()
+ expect(kinds()).toEqual(['api-key', undefined, undefined, undefined])
+ })
+})
+
+describe('connections', () => {
+ it('sends each kind to the origin of the deployment its model route plugin connected', async () => {
+ const ctx = await mount()
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => ({ baseURL: ROUTE })))
+ ctx.effect(() => ctx.deepseekAuth.connect('account', 'deepseek-account', () => ({ baseURL: ACCOUNT })))
+ expect(summary(ctx.deepseekAuth.candidates(request()))).toEqual([
+ 'api-key https://route.deepseek.test/v1/tools/search', 'account https://account.deepseek.test/v1/tools/search',
+ ])
+ })
+
+ it('reads the connected settings for each request', async () => {
+ const ctx = await mount()
+ let baseURL = ROUTE
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => ({ baseURL })))
+ baseURL = 'https://next.deepseek.test/anthropic'
+ expect(summary(ctx.deepseekAuth.candidates(request({ billing: 'api-key' })))).toEqual(['api-key https://next.deepseek.test/v1/tools/search'])
+ })
+
+ it('removes a connection with the plugin that made it', async () => {
+ const ctx = await mount()
+ const plugin = await ctx.plugin({ name: 'route', inject: ['deepseekAuth'], apply: (scope: typeof ctx) => {
+ scope.effect(() => scope.deepseekAuth.connect('api-key', 'deepseek-official', () => ({ baseURL: ROUTE })))
+ } })
+ expect(summary(ctx.deepseekAuth.candidates(request({ billing: 'api-key' })))).toEqual(['api-key https://route.deepseek.test/v1/tools/search'])
+ await plugin.dispose()
+ expect(summary(ctx.deepseekAuth.candidates(request({ billing: 'api-key' })))).toEqual([`api-key ${OFFICIAL}`])
+ })
+
+ it('refuses a second connection of one kind', async () => {
+ const ctx = await mount()
+ ctx.effect(() => ctx.deepseekAuth.connect('account', 'deepseek-account', () => ({ baseURL: ACCOUNT })))
+ expect(() => ctx.deepseekAuth.connect('account', 'another-account-route', () => ({ baseURL: ROUTE })))
+ .toThrow(expect.objectContaining({ constructor: DeepSeekAuthError, code: 'DUPLICATE_CONNECTION' }))
+ })
+
+ it('prefers the connection a request carries over the connected one', async () => {
+ const ctx = await mount()
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => ({ baseURL: ROUTE })))
+ const own = { 'api-key': { baseURL: 'https://own.deepseek.test/api/v1/tools' } }
+ expect(summary(ctx.deepseekAuth.candidates(request({ billing: 'api-key', connections: own })))).toEqual(['api-key https://own.deepseek.test/v1/tools/search'])
+ })
+
+ it('marks a kind unresolved when its connected settings do not resolve or name no URL', async () => {
+ const ctx = await mount()
+ const failure = new Error('settings do not resolve')
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => { throw failure }))
+ ctx.effect(() => ctx.deepseekAuth.connect('account', 'deepseek-account', () => ({ baseURL: 'not a url' })))
+ const [key, account] = ctx.deepseekAuth.candidates(request())
+ expect(key).toEqual({ kind: 'api-key', unresolved: 'connection', error: failure })
+ expect(account).toMatchObject({ kind: 'account', unresolved: 'connection' })
+ })
+})
diff --git a/packages/account/deepseek-auth/tests/destinations.spec.ts b/packages/account/deepseek-auth/tests/destinations.spec.ts
new file mode 100644
index 0000000000..d326b64721
--- /dev/null
+++ b/packages/account/deepseek-auth/tests/destinations.spec.ts
@@ -0,0 +1,57 @@
+/** Where a credential may be sent: absolute destinations, and the deployment of a kind no model route connected. */
+import { afterEach, describe, expect, it } from 'vitest'
+import { disposeMounted, mount, request, summary } from './harness.ts'
+
+afterEach(disposeMounted)
+
+describe('absolute destinations', () => {
+ const ROUTE = 'https://route.deepseek.test/anthropic'
+
+ it('offers a kind for a URL under the origin of its deployment', async () => {
+ const ctx = await mount()
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => ({ baseURL: ROUTE })))
+ const url = 'https://route.deepseek.test/anthropic/v1/models'
+ expect(summary(ctx.deepseekAuth.candidates(request({ billing: 'api-key', destination: { url } })))).toEqual([`api-key ${url}`])
+ })
+
+ it.each([
+ 'https://other.deepseek.test/anthropic/v1/models',
+ 'http://route.deepseek.test/anthropic/v1/models',
+ 'https://user:secret@route.deepseek.test/anthropic/v1/models',
+ ])('offers no kind for %s, which is outside the deployment or embeds credentials', async (url) => {
+ const ctx = await mount()
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', 'deepseek-official', () => ({ baseURL: ROUTE })))
+ expect(ctx.deepseekAuth.candidates(request({ billing: 'api-key', destination: { url } }))).toEqual([])
+ })
+
+ it('marks a kind unresolved for a destination that is no URL', async () => {
+ const ctx = await mount()
+ expect(ctx.deepseekAuth.candidates(request({ billing: 'api-key', destination: { url: 'not a url' } })))
+ .toMatchObject([{ kind: 'api-key', unresolved: 'connection' }])
+ })
+})
+
+describe('the account deployment without a connected account route', () => {
+ it.each([[{}], [{ DEEPSEEK_BASE_URL: '' }]])('is the official API for environment %j', async (environment) => {
+ const ctx = await mount({ environment })
+ expect(summary(ctx.deepseekAuth.candidates(request({ billing: 'account' })))).toEqual(['account https://api.deepseek.com/v1/tools/search'])
+ })
+
+ it('is the origin DEEPSEEK_BASE_URL names', async () => {
+ const ctx = await mount({ environment: { DEEPSEEK_BASE_URL: 'https://gateway.deepseek.test/anthropic' } })
+ expect(summary(ctx.deepseekAuth.candidates(request({ billing: 'account' })))).toEqual(['account https://gateway.deepseek.test/v1/tools/search'])
+ })
+
+ it.each(['not a url', 'ftp://gateway.deepseek.test', 'https://user:secret@gateway.deepseek.test'])(
+ 'is unresolved for DEEPSEEK_BASE_URL=%s, naming the deployment', async (value) => {
+ const ctx = await mount({ environment: { DEEPSEEK_BASE_URL: value } })
+ const [entry] = ctx.deepseekAuth.candidates(request({ billing: 'account' }))
+ expect(entry).toMatchObject({ kind: 'account', unresolved: 'deployment' })
+ expect(entry).toHaveProperty('error', expect.any(Error))
+ })
+
+ it('does not move the API key, which stays at the official API', async () => {
+ const ctx = await mount({ environment: { DEEPSEEK_BASE_URL: 'https://gateway.deepseek.test/anthropic' } })
+ expect(summary(ctx.deepseekAuth.candidates(request({ billing: 'api-key' })))).toEqual(['api-key https://api.deepseek.com/v1/tools/search'])
+ })
+})
diff --git a/packages/account/deepseek-auth/tests/harness.ts b/packages/account/deepseek-auth/tests/harness.ts
new file mode 100644
index 0000000000..4bfb3e509b
--- /dev/null
+++ b/packages/account/deepseek-auth/tests/harness.ts
@@ -0,0 +1,59 @@
+/** A context with the DeepSeek authentication service over stand-in credential planes. */
+import { Context } from '@deepseek-ai/cordis'
+import DeepSeekAuth, { type DeepSeekAuthCandidate, type DeepSeekAuthRequest, type DeepSeekAuthUnresolved } from '@deepseek-ai/dsh-deepseek-auth'
+import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account'
+import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
+
+/** Credential planes of one test context. */
+export interface Planes {
+ /** Launch-environment variables. */
+ environment?: Record
+ /** Values of the mounted credentials service by reference; omitted mounts no service. */
+ stored?: Record
+ /** Account service stand-in. */
+ account?: DeepSeekAccount
+}
+
+const mounted: Context[] = []
+
+/** Dispose every context {@link mount} created. */
+export async function disposeMounted(): Promise {
+ await Promise.all(mounted.splice(0).map(ctx => ctx.fiber.dispose()))
+}
+
+/**
+ * Mount the service.
+ * @param planes - the credential planes it reads.
+ * @returns the context.
+ */
+export async function mount(planes: Planes = {}): Promise {
+ const ctx = new Context()
+ mounted.push(ctx)
+ ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: planes.environment ?? {} }]))
+ const { stored } = planes
+ if (stored !== undefined) {
+ ctx.provide('credentials', {
+ resolve: (ref: string) => Promise.resolve(stored[ref] === undefined ? undefined : { value: stored[ref] }),
+ describe: (ref: string) => Promise.resolve({ configured: (stored[ref]?.length ?? 0) > 0 }),
+ } as never)
+ }
+ if (planes.account !== undefined) ctx.provide('deepseekAccount', planes.account)
+ await ctx.plugin(DeepSeekAuth)
+ return ctx
+}
+
+/** A request to the Search API accepting both kinds, with overrides. */
+export function request(overrides: Partial = {}): DeepSeekAuthRequest {
+ return { consumer: 'web-test', accepts: ['account', 'api-key'], destination: { path: '/v1/tools/search' }, ...overrides }
+}
+
+/** Each entry as `kind endpoint`, or `kind !unresolved` for an unresolved kind. */
+export function summary(entries: readonly (DeepSeekAuthCandidate | DeepSeekAuthUnresolved)[]): string[] {
+ return entries.map(entry => 'unresolved' in entry ? `${entry.kind} !${entry.unresolved}` : `${entry.kind} ${entry.endpoint}`)
+}
+
+/** Narrow an entry to a candidate, failing the test for an unresolved kind. */
+export function candidate(entry: DeepSeekAuthCandidate | DeepSeekAuthUnresolved | undefined): DeepSeekAuthCandidate {
+ if (entry === undefined || 'unresolved' in entry) throw new Error('expected a candidate')
+ return entry
+}
diff --git a/packages/account/deepseek-auth/tsconfig.json b/packages/account/deepseek-auth/tsconfig.json
new file mode 100644
index 0000000000..8b9ed8e7bc
--- /dev/null
+++ b/packages/account/deepseek-auth/tsconfig.json
@@ -0,0 +1,30 @@
+{
+ "extends": "../../../tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "include": [
+ "src"
+ ],
+ "references": [
+ {
+ "path": "../../../vendor/cosmokit"
+ },
+ {
+ "path": "../../../vendor/cordis"
+ },
+ {
+ "path": "../../credentials/credentials"
+ },
+ {
+ "path": "../deepseek-account"
+ },
+ {
+ "path": "../../util/error"
+ },
+ {
+ "path": "../../util/launch-environment"
+ }
+ ]
+}
diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml
index 18286618f9..16c67aa2ab 100644
--- a/packages/bundle/base/cordis.patch.yml
+++ b/packages/bundle/base/cordis.patch.yml
@@ -122,6 +122,10 @@
config:
desktopPlatform: !!js "ctx.get('profileContext')?.name === 'desktop' && ['darwin', 'win32'].includes(process.platform) ? process.platform : null"
+ # DeepSeek model routes and web providers ask this service for the API key or the account sign-in of each request.
+ - id: deepseek-auth
+ name: '@deepseek-ai/dsh-deepseek-auth'
+
- id: credentials
name: '@deepseek-ai/dsh-credentials-local'
diff --git a/packages/bundle/base/package.json b/packages/bundle/base/package.json
index 044e4044a7..bafe989e6f 100644
--- a/packages/bundle/base/package.json
+++ b/packages/bundle/base/package.json
@@ -58,6 +58,7 @@
"@deepseek-ai/dsh-config-editor": "workspace:*",
"@deepseek-ai/dsh-credentials-local": "workspace:*",
"@deepseek-ai/dsh-deepseek-account": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*",
"@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*",
"@deepseek-ai/dsh-fs-local": "workspace:*",
"@deepseek-ai/dsh-fs-observation-policy": "workspace:*",
diff --git a/packages/bundle/sdk-minimal/cordis.patch.yml b/packages/bundle/sdk-minimal/cordis.patch.yml
index e46eed1e0f..60d835440c 100644
--- a/packages/bundle/sdk-minimal/cordis.patch.yml
+++ b/packages/bundle/sdk-minimal/cordis.patch.yml
@@ -23,6 +23,9 @@
- id: plugin-package-inventory-deepseek
name: '@deepseek-ai/dsh-plugin-package-inventory-deepseek'
+ - id: deepseek-auth
+ name: '@deepseek-ai/dsh-deepseek-auth'
+
- id: llm-deepseek
name: '@deepseek-ai/dsh-llm-deepseek-api-key'
config:
diff --git a/packages/bundle/sdk-minimal/package.json b/packages/bundle/sdk-minimal/package.json
index cfbe112af6..344e4dca14 100644
--- a/packages/bundle/sdk-minimal/package.json
+++ b/packages/bundle/sdk-minimal/package.json
@@ -72,7 +72,8 @@
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-working-directory": "workspace:*",
"@deepseek-ai/dsh-tool-working-directory": "workspace:*",
- "@deepseek-ai/dsh-fs-local": "workspace:*"
+ "@deepseek-ai/dsh-fs-local": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~"
diff --git a/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts b/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts
index 3357798d2e..710474034e 100644
--- a/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts
+++ b/packages/bundle/sdk-minimal/tests/sdk-minimal.spec.ts
@@ -27,6 +27,7 @@ describe('dsh-sdk-minimal bundle', () => {
['deepseek-llm-api-extensions', '@deepseek-ai/dsh-deepseek-llm-api-extensions'],
['session-log-deepseek', '@deepseek-ai/dsh-session-log-deepseek'],
['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'],
+ ['deepseek-auth', '@deepseek-ai/dsh-deepseek-auth'],
['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek-api-key'],
['sandbox', '@deepseek-ai/dsh-sandbox-local'],
['filesystem', '@deepseek-ai/dsh-fs-local'],
diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml
index 0b4439bdbe..995a27a637 100644
--- a/packages/client/ui-settings-models/README.i18n.yaml
+++ b/packages/client/ui-settings-models/README.i18n.yaml
@@ -36,8 +36,8 @@
en: a87afbec5e339b36
zh: 6348c81af7e650e1
/deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation/validation:
- en: d469e496518d44c5
- zh: e71938ef7502a20c
+ en: 7ebb4f43b619d8dd
+ zh: 3cdb6dd893cb8c8e
/deepseek-ai-dsh-client-ui-settings-models/understand-the-implementation/concurrency-and-credentials:
en: 6e04c00818f014cd
zh: 2d57f8d8944e67ed
diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md
index ec7675d6c6..3f4a5a2c4b 100644
--- a/packages/client/ui-settings-models/README.md
+++ b/packages/client/ui-settings-models/README.md
@@ -93,7 +93,7 @@ The page never holds a full settings section: it holds only the REDACTED descrip
### Validation
-A typed API key is judged on its own field: after trimming, it must be non-empty and every character must be printable ASCII (`[\x21-\x7E]`), which is exactly what an HTTP header value can carry — the twin of `normalizeApiKey` in `@deepseek-ai/dsh-llm`, mirrored here because the source-plane split forbids importing it. A value matching a pasted `NAME=value` environment line or wrapped in matching quotes is refused as the same format failure. Empty ids, duplicate ids, empty explicit names, and unreadable, non-positive, or fractional capacities fail before any write. The retry fields come from the `retryPolicy` schema the namespace publishes: each union branch is a mode, number fields become inputs whose integer step, minimum, and maximum are checked from the schema, string lists become the code picker, nested objects become folds, and fields of other types are not shown. The labels, hints, messages, and code names are copy owned by this page; an unlabelled field shows its schema key. The two rules `resolveRetryPolicy` in `@deepseek-ai/dsh-llm` enforces beyond any field bound, an initial delay at most the maximum delay and no repeated code, are mirrored for the same reason, because `llm-deepseek` only logs a warning for a live policy it refuses. The card writes the policy field by field, so an unchanged inherited field stays inherited. DeepSeek's `models` is one replace-by-value array: the editor shows inherited effective rows until the first model edit materializes the complete array in the user layer, while reset unsets that override.
+A typed API key is judged on its own field: after trimming, it must be non-empty and every character must be printable ASCII (`[\x21-\x7E]`), which is exactly what an HTTP header value can carry — the twin of `normalizeApiKey` in `@deepseek-ai/dsh-credentials`, mirrored here because the source-plane split forbids importing it. A value matching a pasted `NAME=value` environment line or wrapped in matching quotes is refused as the same format failure. Empty ids, duplicate ids, empty explicit names, and unreadable, non-positive, or fractional capacities fail before any write. The retry fields come from the `retryPolicy` schema the namespace publishes: each union branch is a mode, number fields become inputs whose integer step, minimum, and maximum are checked from the schema, string lists become the code picker, nested objects become folds, and fields of other types are not shown. The labels, hints, messages, and code names are copy owned by this page; an unlabelled field shows its schema key. The two rules `resolveRetryPolicy` in `@deepseek-ai/dsh-llm` enforces beyond any field bound, an initial delay at most the maximum delay and no repeated code, are mirrored for the same reason, because `llm-deepseek` only logs a warning for a live policy it refuses. The card writes the policy field by field, so an unchanged inherited field stays inherited. DeepSeek's `models` is one replace-by-value array: the editor shows inherited effective rows until the first model edit materializes the complete array in the user layer, while reset unsets that override.
### Concurrency and credentials
diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md
index 244e1c0e05..d82c299e5c 100644
--- a/packages/client/ui-settings-models/README.zh.md
+++ b/packages/client/ui-settings-models/README.zh.md
@@ -93,7 +93,7 @@ Models 页面包含 **DeepSeek 账号**(`deepseek-account`,英文为 **DeepS
### 校验
-键入的 API 密钥按其自身字段判定:去除首尾空白后必须非空,且每个字符都必须是可打印 ASCII(`[\x21-\x7E]`),这正是 HTTP 头值能够携带的字符集——与 `@deepseek-ai/dsh-llm` 中的 `normalizeApiKey` 互为镜像,此处复刻是因为源平面拆分禁止导入它。与粘贴的 `NAME=value` 环境行一致或包裹在匹配引号内的值,会作为同样的格式失败被拒绝。空 id、重复 id、空显式名称以及不可读、非正数或小数的容量都会在任何写入之前失败。重试字段来自命名空间发布的 `retryPolicy` schema:每个 union 分支是一种模式,数字字段成为输入框,其整数步长、最小值和最大值按 schema 检查,字符串列表成为错误码勾选列表,嵌套对象成为折叠区,其他类型的字段不显示。标签、提示、错误消息和错误码名称是本页面拥有的文案;没有标签的字段显示其 schema 键名。`@deepseek-ai/dsh-llm` 中 `resolveRetryPolicy` 在字段上限之外还强制执行两条规则:初始延迟不大于最大延迟、错误码不重复,出于同样原因在此复刻,因为 `llm-deepseek` 对它拒绝的实时策略只记录警告。卡片按字段写入策略,因此未修改的继承字段保持继承。DeepSeek 的 `models` 是一个按值整体替换的数组:编辑器先显示继承的有效行,直到第一次模型编辑把完整数组物化进用户层,重置则取消该覆盖。
+键入的 API 密钥按其自身字段判定:去除首尾空白后必须非空,且每个字符都必须是可打印 ASCII(`[\x21-\x7E]`),这正是 HTTP 头值能够携带的字符集——与 `@deepseek-ai/dsh-credentials` 中的 `normalizeApiKey` 互为镜像,此处复刻是因为源平面拆分禁止导入它。与粘贴的 `NAME=value` 环境行一致或包裹在匹配引号内的值,会作为同样的格式失败被拒绝。空 id、重复 id、空显式名称以及不可读、非正数或小数的容量都会在任何写入之前失败。重试字段来自命名空间发布的 `retryPolicy` schema:每个 union 分支是一种模式,数字字段成为输入框,其整数步长、最小值和最大值按 schema 检查,字符串列表成为错误码勾选列表,嵌套对象成为折叠区,其他类型的字段不显示。标签、提示、错误消息和错误码名称是本页面拥有的文案;没有标签的字段显示其 schema 键名。`@deepseek-ai/dsh-llm` 中 `resolveRetryPolicy` 在字段上限之外还强制执行两条规则:初始延迟不大于最大延迟、错误码不重复,出于同样原因在此复刻,因为 `llm-deepseek` 对它拒绝的实时策略只记录警告。卡片按字段写入策略,因此未修改的继承字段保持继承。DeepSeek 的 `models` 是一个按值整体替换的数组:编辑器先显示继承的有效行,直到第一次模型编辑把完整数组物化进用户层,重置则取消该覆盖。
### 并发与凭据
diff --git a/packages/client/ui-settings-models/src/client/apiKey.ts b/packages/client/ui-settings-models/src/client/apiKey.ts
index 353488a0b5..64c7daa08c 100644
--- a/packages/client/ui-settings-models/src/client/apiKey.ts
+++ b/packages/client/ui-settings-models/src/client/apiKey.ts
@@ -4,7 +4,7 @@
*/
/**
- * Twin of `normalizeApiKey` in `@deepseek-ai/dsh-llm`: printable ASCII, space
+ * Twin of `normalizeApiKey` in `@deepseek-ai/dsh-credentials`: printable ASCII, space
* excluded. Client packages reference only client packages, so the charset
* rule is mirrored here rather than imported; keep the two in step, as
* `validateDeepSeekModels` is kept in step with the host's `catalogModel`.
diff --git a/packages/context/agent-instructions/package.json b/packages/context/agent-instructions/package.json
index 3716038104..8b4cdba701 100644
--- a/packages/context/agent-instructions/package.json
+++ b/packages/context/agent-instructions/package.json
@@ -65,6 +65,7 @@
"@deepseek-ai/dsh-tool-fs": "workspace:*",
"@deepseek-ai/dsh-tool-testkit": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
- "@deepseek-ai/dsh-working-directory": "workspace:*"
+ "@deepseek-ai/dsh-working-directory": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/context/agent-instructions/tests/agent-instructions.e2e.ts b/packages/context/agent-instructions/tests/agent-instructions.e2e.ts
index 1dbf99c634..dbe66298e8 100644
--- a/packages/context/agent-instructions/tests/agent-instructions.e2e.ts
+++ b/packages/context/agent-instructions/tests/agent-instructions.e2e.ts
@@ -9,6 +9,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session'
import type { Agent } from '@deepseek-ai/dsh-agent'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import * as AgentInstructions from '@deepseek-ai/dsh-agent-instructions'
import { candidateScopeKey } from '../src/render.ts'
import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
@@ -47,6 +48,7 @@ async function harness(): Promise<{ ctx: Context; agent: Agent }> {
vi.stubEnv('DSH_AGENTS_HOME', join(workdir, 'absent-agents'))
await ctx.plugin(AgentInstructions, { maxBytes: 65536 })
await ctx.plugin(AgentLoop, { agents: [] })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] })
const handle = await ctx.agents.create({
sessionId: brandString('workspace-context-e2e-session'),
diff --git a/packages/core/agent-loop/package.json b/packages/core/agent-loop/package.json
index 5a6e0449d3..89d6e9214a 100644
--- a/packages/core/agent-loop/package.json
+++ b/packages/core/agent-loop/package.json
@@ -62,6 +62,7 @@
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
"@deepseek-ai/dsh-tool-executor-ptc": "workspace:*",
"@deepseek-ai/dsh-tool-testkit": "workspace:*",
- "@deepseek-ai/dsh-tools": "workspace:*"
+ "@deepseek-ai/dsh-tools": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/core/agent-loop/tests/request-cache.e2e.ts b/packages/core/agent-loop/tests/request-cache.e2e.ts
index f25d878bbd..ea61666c64 100644
--- a/packages/core/agent-loop/tests/request-cache.e2e.ts
+++ b/packages/core/agent-loop/tests/request-cache.e2e.ts
@@ -12,6 +12,7 @@ import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { brandString } from '@deepseek-ai/dsh-brand'
/**
@@ -51,6 +52,7 @@ async function loopHarness(): Promise {
await created.plugin(NativeToolExecutor)
await created.plugin(AgentRegistry)
await created.plugin(AgentLoop, { agents: [] })
+ await created.plugin(DeepSeekAuth)
await created.plugin(LlmDeepSeek)
created.tools.register(defineContentToolFixture({
name: 'lookup',
diff --git a/packages/credentials/credentials/README.i18n.yaml b/packages/credentials/credentials/README.i18n.yaml
index 1489c975f1..10f63ea8bd 100644
--- a/packages/credentials/credentials/README.i18n.yaml
+++ b/packages/credentials/credentials/README.i18n.yaml
@@ -24,8 +24,8 @@
en: 8f3500119608f91b
zh: 147fdb5389affbc0
/deepseek-ai-dsh-credentials/use-this-package/storing-checking-and-removing-keys:
- en: 9f6cf31d0fd281ac
- zh: b20ac60e6cdd7527
+ en: 729ea87c65c4f12b
+ zh: e6356492854a4487
/deepseek-ai-dsh-credentials/use-this-package/storing-updating-and-removing-records:
en: 300c3f1f13abdca4
zh: ec7a6486ac88889c
@@ -48,8 +48,8 @@
en: 1d56a35fe82e78f3
zh: 1fffc3e104c36805
/deepseek-ai-dsh-credentials/understand-the-implementation/source-map:
- en: f7c85d12a7179da0
- zh: 347ac9e9f89005aa
+ en: 74759a13b7790d41
+ zh: 4819aa4cac80b611
/deepseek-ai-dsh-credentials/understand-the-implementation/client-safe-types:
en: b955d1b41f0ad904
zh: 3f49a25e157d3672
diff --git a/packages/credentials/credentials/README.md b/packages/credentials/credentials/README.md
index 845629e9e8..7f88a7dc81 100644
--- a/packages/credentials/credentials/README.md
+++ b/packages/credentials/credentials/README.md
@@ -60,7 +60,7 @@ await ctx.credentials.unset(ref) // no-op when absent; an
Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. Providers may disclose a masked stored-value preview through the optional `masked` field; the full value stays on the Host.
-Consumers that must also work in compositions without a credentials service, such as the DeepSeek model and web providers, read references through `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`: a mounted service is authoritative, including when it holds no value, and only its absence makes them read the launch environment, where an empty value is absent. Store failures propagate, and callers validate the value's format.
+Consumers that must also work in compositions without a credentials service, such as DeepSeek request authentication, read references through `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`: a mounted service is authoritative, including when it holds no value, and only its absence makes them read the launch environment, where an empty value is absent. Store failures propagate. Callers validate the value's format with `normalizeApiKey(raw)`, which trims the value and rejects a blank one or one with characters no HTTP header can carry, and word their own error for the `reason` it returns; this package words no diagnostic.
### Storing, updating, and removing records
@@ -133,6 +133,7 @@ One doctrine and four consequences:
| File | Role |
|---|---|
| [`src/index.ts`](src/index.ts) | Service Definition: the `credentialRef`/`credentialKey` brands, `ResolvedCredential`/`CredentialRecordInfo`, the abstract provider over both key spaces, contained fan-out |
+| [`src/api-key.ts`](src/api-key.ts) | The well-formedness check of a resolved API key and the diagnostic that names where to fix it |
| [`src/types.ts`](src/types.ts) | Client-safe type surface: the `CredentialRef` and `CredentialKey` brands, the stored-record union, the `CredentialInfo` reference view, the `credentials/reference-updated` and `credentials/record-updated` declarations |
### Client-safe types
diff --git a/packages/credentials/credentials/README.zh.md b/packages/credentials/credentials/README.zh.md
index bc03f641d7..979afec31b 100644
--- a/packages/credentials/credentials/README.zh.md
+++ b/packages/credentials/credentials/README.zh.md
@@ -60,7 +60,7 @@ await ctx.credentials.unset(ref) // no-op when absent; an
用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。提供方可通过可选的 `masked` 字段报告已保存值的脱敏预览;完整值留在 Host。
-必须在没有凭据服务的组合中也能工作的消费方(如 DeepSeek 模型与 Web 提供方)通过 `resolveCredentialRef(ctx, ref)` 和 `credentialRefConfigured(ctx, ref)` 读取引用:已挂载的服务具有权威性,包括它不持有值的情况;只有服务缺席时才读取启动环境,其中空值视为不存在。存储失败向上传播,值的格式由调用方校验。
+必须在没有凭据服务的组合中也能工作的消费方(如 DeepSeek 请求鉴权)通过 `resolveCredentialRef(ctx, ref)` 和 `credentialRefConfigured(ctx, ref)` 读取引用:已挂载的服务具有权威性,包括它不持有值的情况;只有服务缺席时才读取启动环境,其中空值视为不存在。存储失败向上传播。值的格式由调用方用 `normalizeApiKey(raw)` 校验:它去掉首尾空白,并拒绝空值和含有 HTTP 请求头无法携带的字符的值;调用方再依据它返回的 `reason` 写出自己的错误;本包不生成诊断文案。
### 存储、更新与移除记录
@@ -133,6 +133,7 @@ apiKeyEnv: DEEPSEEK_API_KEY
| 文件 | 职责 |
|---|---|
| [`src/index.ts`](src/index.ts) | Service Definition:`credentialRef`/`credentialKey` 品牌、`ResolvedCredential`/`CredentialRecordInfo`、覆盖两个键空间的抽象提供方、带失败隔离的扇出 |
+| [`src/api-key.ts`](src/api-key.ts) | 已解析 API 密钥的格式判断,以及指出修正位置的诊断文案 |
| [`src/types.ts`](src/types.ts) | 客户端安全类型面:`CredentialRef` 与 `CredentialKey` 品牌、存储记录联合类型、`CredentialInfo` 引用视图、`credentials/reference-updated` 与 `credentials/record-updated` 事件声明 |
### 客户端安全类型
diff --git a/packages/llm/llm/src/api-key.ts b/packages/credentials/credentials/src/api-key.ts
similarity index 87%
rename from packages/llm/llm/src/api-key.ts
rename to packages/credentials/credentials/src/api-key.ts
index 85d0b1ed60..0b316f56a3 100644
--- a/packages/llm/llm/src/api-key.ts
+++ b/packages/credentials/credentials/src/api-key.ts
@@ -1,7 +1,8 @@
/**
- * The one definition of a well-formed provider API key, shared by every
- * adapter that puts one in an HTTP header.
- * @module @deepseek-ai/dsh-llm/api-key
+ * The one definition of a well-formed API key, shared by every consumer that
+ * puts a resolved key in an HTTP header. A consumer words its own diagnostic
+ * for a key that is not.
+ * @module @deepseek-ai/dsh-credentials/api-key
*/
/**
diff --git a/packages/credentials/credentials/src/index.ts b/packages/credentials/credentials/src/index.ts
index 6190b7bc2a..de2c71663e 100644
--- a/packages/credentials/credentials/src/index.ts
+++ b/packages/credentials/credentials/src/index.ts
@@ -16,6 +16,7 @@ import type { CredentialInfo, CredentialKey, CredentialRecord, CredentialRef } f
export type {
ApiKeyRecord, CredentialInfo, CredentialKey, CredentialRecord, CredentialRef, GrantRecord,
} from './types.ts'
+export * from './api-key.ts'
const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
diff --git a/packages/credentials/credentials/tests/api-key.spec.ts b/packages/credentials/credentials/tests/api-key.spec.ts
new file mode 100644
index 0000000000..51e82e8904
--- /dev/null
+++ b/packages/credentials/credentials/tests/api-key.spec.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest'
+import { normalizeApiKey } from '@deepseek-ai/dsh-credentials'
+
+describe('normalizeApiKey', () => {
+ it('accepts a printable-ASCII key unchanged', () => {
+ expect(normalizeApiKey('sk-0123456789abcdef')).toEqual({ ok: true, value: 'sk-0123456789abcdef' })
+ })
+
+ it('trims surrounding whitespace before judging', () => {
+ expect(normalizeApiKey(' sk-abc\t\n')).toEqual({ ok: true, value: 'sk-abc' })
+ })
+
+ it.each([
+ ['an empty string', ''],
+ ['spaces only', ' '],
+ ['a tab only', '\t'],
+ ])('rejects %s as empty', (_label, raw) => {
+ expect(normalizeApiKey(raw)).toEqual({ ok: false, reason: 'empty' })
+ })
+
+ it.each([
+ ['an emoji', 'sk-\u{1F600}abc'],
+ ['CJK text', 'sk-你好'],
+ ['full-width punctuation', 'sk-abc,'],
+ ['an interior space', 'sk-abc def'],
+ ['a C0 control character', 'sk-abc\x01'],
+ ['a latin-1 character', 'sk-café'],
+ ])('rejects %s as illegal characters', (_label, raw) => {
+ expect(normalizeApiKey(raw)).toEqual({ ok: false, reason: 'illegalCharacters' })
+ })
+
+ it('accepts the printable-ASCII boundary characters', () => {
+ expect(normalizeApiKey('!~')).toEqual({ ok: true, value: '!~' })
+ })
+})
diff --git a/packages/experimental/auto-review/package.json b/packages/experimental/auto-review/package.json
index 96d2d57fbc..22b27b44c8 100644
--- a/packages/experimental/auto-review/package.json
+++ b/packages/experimental/auto-review/package.json
@@ -80,7 +80,8 @@
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-user-approval": "workspace:*",
"@deepseek-ai/cordis": "workspace:~",
- "@deepseek-ai/dsh-working-directory": "workspace:*"
+ "@deepseek-ai/dsh-working-directory": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"publishConfig": {
"access": "public"
diff --git a/packages/experimental/auto-review/tests/auto-review.e2e.ts b/packages/experimental/auto-review/tests/auto-review.e2e.ts
index 0e2b81c040..5c5eddd6a4 100644
--- a/packages/experimental/auto-review/tests/auto-review.e2e.ts
+++ b/packages/experimental/auto-review/tests/auto-review.e2e.ts
@@ -17,6 +17,7 @@ import {
type StreamChunk,
} from '@deepseek-ai/dsh-llm'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import PermissionPresetService, { AUTO_PRESET } from '@deepseek-ai/dsh-permission-presets'
import SandboxProvider, { type ConfinedArgv, type SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy'
@@ -135,6 +136,7 @@ async function mount(ctx: Context, workspace: string, dshHome: string): Promise<
systemPrompt: {}, tools: { mode: 'native' },
})
// No reasoning or output-budget override: use each shipped model's defaults.
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { retryPolicy: { mode: 'normal', maxRetries: 0 } })
await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: workspace })
await ctx.plugin(UnusedSandbox)
diff --git a/packages/experimental/translator/package.json b/packages/experimental/translator/package.json
index b30925db07..a8d936b5f0 100644
--- a/packages/experimental/translator/package.json
+++ b/packages/experimental/translator/package.json
@@ -70,6 +70,7 @@
"@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*",
"@deepseek-ai/dsh-session-log-deepseek": "workspace:*",
"@deepseek-ai/dsh-session-projection": "workspace:*",
- "@deepseek-ai/dsh-session-query-sqlite": "workspace:*"
+ "@deepseek-ai/dsh-session-query-sqlite": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/experimental/translator/tests/deepseek.e2e.ts b/packages/experimental/translator/tests/deepseek.e2e.ts
index 817de245f8..7e7d81a1e3 100644
--- a/packages/experimental/translator/tests/deepseek.e2e.ts
+++ b/packages/experimental/translator/tests/deepseek.e2e.ts
@@ -5,6 +5,7 @@ import LlmRuntime from '@deepseek-ai/dsh-llm'
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -25,12 +26,14 @@ it.skipIf(!enabled)('translates a small independent billed query with exact Flas
{ id: 'llm', name: '@deepseek-ai/dsh-llm' },
{ id: 'sessions', name: '@deepseek-ai/dsh-session' },
{ id: 'storage', name: '@deepseek-ai/dsh-session-persistence-jsonl', config: { root: join(root, 'sessions'), compression: 'none' } },
+ { id: 'deepseek-auth', name: '@deepseek-ai/dsh-deepseek-auth' },
{ id: 'official-live-owner', name: '@deepseek-ai/dsh-llm-deepseek-api-key' },
{ id: 'translator', name: '@deepseek-ai/dsh-experimental-translator', config: { deepseekMaxOutputTokens: 128 } },
]))
const modules = new Map([
['@deepseek-ai/dsh-llm', LlmRuntime], ['@deepseek-ai/dsh-session', SessionStore],
['@deepseek-ai/dsh-session-persistence-jsonl', JsonlPersistence],
+ ['@deepseek-ai/dsh-deepseek-auth', DeepSeekAuth],
['@deepseek-ai/dsh-llm-deepseek-api-key', Official], ['@deepseek-ai/dsh-experimental-translator', Translator],
])
const ctx = await boot('paid-translation-live', configPath, [], (host) => {
diff --git a/packages/experimental/translator/tests/paid-fixture.ts b/packages/experimental/translator/tests/paid-fixture.ts
index 9dbc1c44a4..f410fda87f 100644
--- a/packages/experimental/translator/tests/paid-fixture.ts
+++ b/packages/experimental/translator/tests/paid-fixture.ts
@@ -7,6 +7,7 @@ import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import SqliteSessionQuery from '@deepseek-ai/dsh-session-query-sqlite'
import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import * as Account from '@deepseek-ai/dsh-llm-deepseek-account'
import DeepSeekLlmApiExtensionRegistry from '@deepseek-ai/dsh-deepseek-llm-api-extensions'
import * as SessionLogDeepSeek from '@deepseek-ai/dsh-session-log-deepseek'
@@ -131,6 +132,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options:
{ id: 'llm', name: '@deepseek-ai/dsh-llm' },
{ id: 'session', name: '@deepseek-ai/dsh-session' },
{ id: 'storage', name: '@deepseek-ai/dsh-session-persistence-jsonl', config: { root: storedRoot, compression: 'none' } },
+ { id: 'deepseek-auth', name: '@deepseek-ai/dsh-deepseek-auth' },
{ id: 'official-custom-id', name: options.officialName ?? '@deepseek-ai/dsh-llm-deepseek-api-key', disabled: !withNativeOwners, config: {
baseURL, apiKeyEnv: 'PAID_TRANSLATION_FIXTURE_KEY', models: options.officialModels ?? [{ id: 'deepseek-flash', name: 'Flash version-independent name' }],
} },
@@ -149,6 +151,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options:
const modules = new Map([
['@deepseek-ai/dsh-llm', LlmRuntime], ['@deepseek-ai/dsh-session', SessionStore],
['@deepseek-ai/dsh-session-persistence-jsonl', JsonlPersistence], ['@deepseek-ai/dsh-session-query-sqlite', SqliteSessionQuery],
+ ['@deepseek-ai/dsh-deepseek-auth', DeepSeekAuth],
['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry],
[options.officialName ?? '@deepseek-ai/dsh-llm-deepseek-api-key', Official],
['@deepseek-ai/dsh-llm-deepseek-account', Account], ['@deepseek-ai/dsh-experimental-translator', Translator],
diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts
index 2f275bfdae..88c8af94b0 100644
--- a/packages/extensions/tool-cordis/src/api-catalog.ts
+++ b/packages/extensions/tool-cordis/src/api-catalog.ts
@@ -1158,6 +1158,39 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
],
},
+ {
+ key: 'deepseekAuth',
+ summary: '`ctx.deepseekAuth`: the two DeepSeek credential kinds behind one request-authorization operation.',
+ description: '`ctx.deepseekAuth`: the two DeepSeek credential kinds behind one request-authorization operation.',
+ methods: [
+ {
+ signature: 'connect(kind: DeepSeekAuthKind, route: string, connection: () => DeepSeekAuthConnection): () => void',
+ description: 'Connect the deployment a model route plugin\'s settings name for one kind. Call it from within `ctx.effect()`.',
+ parameters: [{ name: 'kind', description: 'the kind the plugin\'s route bills.' }, { name: 'route', description: 'provider route the plugin registers; {@link routeKind} answers `kind` for it while connected.' }, { name: 'connection', description: 'reads the plugin\'s current settings; a throw marks the kind unresolved for that operation.' }],
+ returns: 'the disposer removing the connection.',
+ throws: ['{DeepSeekAuthError} code `DUPLICATE_CONNECTION` when the kind is already connected.'],
+ },
+ {
+ signature: 'routeKind(route: string | undefined): DeepSeekAuthKind | undefined',
+ description: 'The kind that bills a conversation on one model route.',
+ parameters: [{ name: 'route', description: 'provider route of a model request; undefined names none.' }],
+ returns: 'the kind connected under that route, or undefined for a route no plugin connected.',
+ },
+ {
+ signature: 'candidates(request: DeepSeekAuthRequest): (DeepSeekAuthCandidate | DeepSeekAuthUnresolved)[]',
+ description: 'The kinds one request can authenticate with, in the order its billing tries them, each bound to its destination. Nothing is read from a credential store.',
+ parameters: [{ name: 'request', description: 'the request.' }],
+ returns: 'candidates and unresolved kinds, first preferred; empty when the destination accepts no kind the billing allows or no allowed kind serves an absolute destination.',
+ },
+ {
+ signature: 'async authorize(request: DeepSeekAuthRequest, signal?: AbortSignal): Promise',
+ description: 'Release the credential of the first candidate that has one. A later candidate is not read once an earlier one has a credential, fails to read, or does not resolve.',
+ parameters: [{ name: 'request', description: 'the request.' }, { name: 'signal', description: 'cancellation for the lookups.' }],
+ returns: 'the authorization, or undefined when no candidate has a credential.',
+ throws: ['{DeepSeekAuthError} code `UNRESOLVED_CONNECTION` at an unresolved kind, `INVALID_CREDENTIAL` for an unusable API key; store failures propagate.'],
+ },
+ ],
+ },
{
key: 'deepseekChatImport',
summary: 'Serves the owner-only export upload route and the limits the browser checks first.',
@@ -2281,12 +2314,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
parameters: [{ name: 'provider', description: 'registered provider route.' }, { name: 'model', description: 'exact model id.' }, { name: 'image', description: 'normalized image reference.' }],
returns: 'dimensions and byte target used by the adapter\'s request serializer.',
},
- {
- signature: 'providerCredential(provider: string): ProviderCredential | undefined',
- description: 'Resolve the credential one registered route currently sends, through its owning adapter. An unregistered route answers `undefined` rather than throwing because callers ask about routes a conversation named earlier, which may no longer be mounted; a registered route whose configuration does not resolve propagates the adapter\'s failure.',
- parameters: [{ name: 'provider', description: 'provider route whose credential is wanted.' }],
- returns: 'the route\'s credential, or `undefined` when the route is unregistered or publishes none.',
- },
{
signature: 'fileRequestText(ref: FileAttachmentRef): string',
description: 'Resolve the exact text one durable file occurrence contributes to every provider request in the current execution environment.',
@@ -5989,7 +6016,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'AccountRequestCredential',
- declaration: 'export interface AccountRequestCredential {\n readonly headers: Readonly>;\n readonly value: string;\n reject(): Promise;\n readonly revoked: AbortSignal;\n}',
+ declaration: 'export interface AccountRequestCredential {\n readonly headers: Readonly>;\n reject(): Promise;\n readonly revoked: AbortSignal;\n}',
},
{
name: 'AccountUpdate',
@@ -6855,6 +6882,42 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'DailyScheduleRecord',
declaration: 'export interface DailyScheduleRecord {\n readonly id: ScheduleId;\n readonly kind: \'daily\';\n readonly title: string;\n readonly prompt: string;\n readonly time: string;\n readonly timeZone: string;\n readonly scheduledAt: string;\n}',
},
+ {
+ name: 'DeepSeekApiKeyHeader',
+ declaration: 'export type DeepSeekApiKeyHeader = \'authorization\' | \'x-api-key\';',
+ },
+ {
+ name: 'DeepSeekAuthBilling',
+ declaration: 'export type DeepSeekAuthBilling = \'auto\' | DeepSeekAuthKind;',
+ },
+ {
+ name: 'DeepSeekAuthCandidate',
+ declaration: 'export interface DeepSeekAuthCandidate {\n readonly kind: DeepSeekAuthKind;\n readonly endpoint: string;\n readonly reference?: CredentialRef;\n configured(): Promise;\n resolve(signal?: AbortSignal): Promise;\n}',
+ },
+ {
+ name: 'DeepSeekAuthConnection',
+ declaration: 'export interface DeepSeekAuthConnection {\n readonly baseURL: string;\n readonly reference?: CredentialRef;\n readonly owner?: string;\n}',
+ },
+ {
+ name: 'DeepSeekAuthDestination',
+ declaration: 'export type DeepSeekAuthDestination = {\n readonly path: string;\n} | {\n readonly url: string;\n};',
+ },
+ {
+ name: 'DeepSeekAuthKind',
+ declaration: 'export type DeepSeekAuthKind = \'api-key\' | \'account\';',
+ },
+ {
+ name: 'DeepSeekAuthorization',
+ declaration: 'export interface DeepSeekAuthorization {\n readonly kind: DeepSeekAuthKind;\n readonly endpoint: string;\n readonly headers: Readonly>;\n readonly reference?: CredentialRef;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}',
+ },
+ {
+ name: 'DeepSeekAuthRequest',
+ declaration: 'export interface DeepSeekAuthRequest {\n readonly consumer: string;\n readonly accepts: readonly DeepSeekAuthKind[];\n readonly billing?: DeepSeekAuthBilling;\n readonly route?: string | undefined;\n readonly destination: DeepSeekAuthDestination;\n readonly connections?: Readonly>>;\n readonly apiKeyHeaders?: readonly DeepSeekApiKeyHeader[];\n}',
+ },
+ {
+ name: 'DeepSeekAuthUnresolved',
+ declaration: 'export interface DeepSeekAuthUnresolved {\n readonly kind: DeepSeekAuthKind;\n readonly unresolved: \'connection\' | \'deployment\';\n readonly error: unknown;\n}',
+ },
{
name: 'DeepSeekLlmApiExtensionMap',
declaration: 'export interface DeepSeekLlmApiExtensionMap {\n}',
@@ -7765,7 +7828,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'LlmAdapter',
- declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n providerCredential(_provider: string): ProviderCredential | undefined;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}',
+ declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}',
},
{
name: 'LlmAttemptId',
@@ -7787,14 +7850,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'LlmConfigurableProvider',
declaration: 'export interface LlmConfigurableProvider {\n provider: string;\n displayName: string;\n settingsNs: string;\n settingsPath: readonly string[];\n declared?: boolean;\n defaultBaseURL?: string;\n baseURLEnv?: readonly string[];\n nativeAuth?: LlmNativeAuth;\n error?: string;\n}',
},
- {
- name: 'LlmCredentialKind',
- declaration: 'export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap];',
- },
- {
- name: 'LlmCredentialKindMap',
- declaration: 'export interface LlmCredentialKindMap {\n \'api-key\': \'api-key\';\n account: \'account\';\n}',
- },
{
name: 'LlmDiscoveredModel',
declaration: 'export interface LlmDiscoveredModel {\n id: string;\n name?: string;\n contextWindow?: number;\n maxTokens?: number;\n inputModalities?: readonly ModelModality[];\n}',
@@ -7861,7 +7916,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'LlmRuntime',
- declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n providerCredential(provider: string): ProviderCredential | undefined;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, /* …truncated — full shape in source */',
+ declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, signal?: AbortSignal): Promise;\n async prepareCall(conf /* …truncated — full shape in source */',
},
{
name: 'LocalAtInput',
@@ -8675,14 +8730,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'PromptSubmitResult',
declaration: 'export type PromptSubmitResult = {\n text: string;\n context?: readonly string[];\n drop?: undefined;\n} | {\n drop: string;\n text?: undefined;\n context?: undefined;\n};',
},
- {
- name: 'ProviderCredential',
- declaration: 'export interface ProviderCredential {\n readonly kind: LlmCredentialKind;\n readonly baseURL: string;\n readonly reference?: string;\n configured(endpoint: string): Promise;\n resolve(endpoint: string, signal?: AbortSignal): Promise;\n}',
- },
- {
- name: 'ProviderCredentialGrant',
- declaration: 'export interface ProviderCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}',
- },
{
name: 'ProviderRequestId',
declaration: 'export type ProviderRequestId = Branded<\'ProviderRequestId\'>;',
diff --git a/packages/fs/tool-fs/package.json b/packages/fs/tool-fs/package.json
index d2273cd228..7a7fbda77b 100644
--- a/packages/fs/tool-fs/package.json
+++ b/packages/fs/tool-fs/package.json
@@ -79,6 +79,7 @@
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-ptc-runtime": "workspace:*",
"@deepseek-ai/dsh-fs-sandbox": "workspace:*",
- "@deepseek-ai/dsh-working-directory": "workspace:*"
+ "@deepseek-ai/dsh-working-directory": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/fs/tool-fs/tests/harness.ts b/packages/fs/tool-fs/tests/harness.ts
index d525a5dbdb..2213d68f0c 100644
--- a/packages/fs/tool-fs/tests/harness.ts
+++ b/packages/fs/tool-fs/tests/harness.ts
@@ -7,6 +7,7 @@ import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
import * as FsPolicy from '@deepseek-ai/dsh-fs-observation-policy'
import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
/**
* Build the real fs-tool stack for with-key e2e tests. Agents have no session
@@ -17,6 +18,7 @@ export async function fsHarness(fsCwd: string, persona = ''): Promise {
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx, { systemPrompt: { personaPrefix: persona } })
await ctx.plugin(AgentLoop, { agents: [] })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek)
await ctx.plugin(LocalFileSystem, { cwd: fsCwd })
await ctx.plugin(WorkingDirectory, { defaultDirectory: fsCwd })
diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml
index ab9e5e1b82..937fede492 100644
--- a/packages/llm/llm-deepseek-account/README.i18n.yaml
+++ b/packages/llm/llm-deepseek-account/README.i18n.yaml
@@ -9,17 +9,17 @@
en: 8fa1148e0ee9d351
zh: 634ec9d79d5ffbf0
/deepseek-ai-dsh-llm-deepseek-account/summary:
- en: 47201804733ec769
- zh: 3c6751b16a45759f
+ en: 1a65ab875bc8e6d8
+ zh: 2eadeb1d5f7e5591
/deepseek-ai-dsh-llm-deepseek-account/table-of-contents:
en: 23386452a66b2fbd
zh: 4cf93c4bf17b3da2
/deepseek-ai-dsh-llm-deepseek-account/use-this-package:
- en: a6a05e40662f10ed
- zh: eb19e4706ab10515
+ en: 5fcd547146a46e0c
+ zh: 516ba55c0a60b91a
/deepseek-ai-dsh-llm-deepseek-account/understand-the-implementation:
- en: d8253a04dce699e1
- zh: 264f36b1b96d0241
+ en: e5f7aaa2c2598df2
+ zh: 5769395c8dd8355a
/deepseek-ai-dsh-llm-deepseek-account/further-exploration:
en: 30a69b9c66d89580
zh: fcc026a6373c1bee
diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md
index 283b36d3eb..244a63e434 100644
--- a/packages/llm/llm-deepseek-account/README.md
+++ b/packages/llm/llm-deepseek-account/README.md
@@ -11,7 +11,7 @@ English | [中文](README.zh.md)
Register authentication, the account model listing, and model gating for `deepseek-account`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, the account catalog, and model admission.
-Authentication resolution returns the request credential the account service releases for the destination, carrying `x-dsh-auth-token`, with a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route publishes the account credential through `ctx.llm.providerCredential('deepseek-account')` with its base URL, so the DeepSeek web providers send it to the same deployment.
+Authentication resolution asks [`ctx.deepseekAuth`](../../account/deepseek-auth/README.md) for the account sign-in the account service releases for the destination, carrying `x-dsh-auth-token`, and adds a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route connects its route id and base URL to that service, so the DeepSeek web providers send the account sign-in to the same deployment.
## Table of Contents
@@ -25,7 +25,7 @@ Authentication resolution returns the request credential the account service rel
## Use this package
-Only `deepseekAccount.resolveRequestCredential(url)` supplies the credential; the account service validates the destination. Signed-out or ineligible requests fail with `ACCOUNT_SIGN_IN_REQUIRED` and discovery returns an empty catalog. The route never falls back to an API key. Other credential lookup errors propagate.
+Only the account sign-in supplies the credential: `ctx.deepseekAuth` asks `deepseekAccount.resolveRequestCredential(url)`, and the account service validates the destination. Signed-out or ineligible requests fail with `ACCOUNT_SIGN_IN_REQUIRED` and discovery returns an empty catalog. The route never falls back to an API key. Other credential lookup errors propagate. The plugin starts only in a composition that mounts `@deepseek-ai/dsh-deepseek-auth`; the `base` bundle mounts it.
The route's catalog comes from the account's `GET /models` listing at the origin of the Messages `baseURL` (`https://api.deepseek.com/models` for the official endpoint); the listing endpoint is not configurable. Listing requests carry the account token in `x-dsh-auth-token` and the harness `User-Agent`, and reject redirects.
@@ -63,7 +63,7 @@ The settings namespace is the Cordis entry id, or the plugin name without an ent
## Understand the implementation
-Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request; a model request in flight keeps its credential and failure callback until it ends, so both can run after disposal. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the credential headers.
+Account credential lookup and invalidation go through `ctx.deepseekAuth`, which asks the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request; a model request in flight keeps its credential and failure callback until it ends, so both can run after disposal. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the credential headers.
A failed request the shared transport classifies as `QUOTA` is rewritten to `ACCOUNT_QUOTA` before it leaves this provider, covering an HTTP 402 response and an in-band SSE error alike. The shared transport and the `deepseek-official` route keep `QUOTA`, so the account route's top-up action never appears for an API-key or third-party failure.
diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md
index 04b6256544..83b427ca50 100644
--- a/packages/llm/llm-deepseek-account/README.zh.md
+++ b/packages/llm/llm-deepseek-account/README.zh.md
@@ -11,7 +11,7 @@ kind: "package-reference"
为 `deepseek-account` 注册鉴权、账号模型列表和模型门控。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包负责凭据解析、账号目录和模型准入。
-鉴权解析返回账号服务为目标地址释放的请求凭据,携带 `x-dsh-auth-token`,并附带使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由通过 `ctx.llm.providerCredential('deepseek-account')` 连同其基础地址发布账号凭据,使 DeepSeek Web 提供方把它发往同一部署。
+鉴权解析向 [`ctx.deepseekAuth`](../../account/deepseek-auth/README.zh.md) 索取账号服务为目标地址释放的账号登录凭据,携带 `x-dsh-auth-token`,并附加使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由把自己的路由 id 和基础地址登记到该服务,使 DeepSeek Web 提供方把账号登录凭据发往同一部署。
## 目录
@@ -25,7 +25,7 @@ kind: "package-reference"
## 使用此包
-账号凭据仅由 `deepseekAccount.resolveRequestCredential(url)` 提供,目标地址必须通过账号服务的来源校验。未登录或目标不允许账号鉴权时,请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,目录为空;不会回退到 API key。其他凭据查询错误继续向调用者报告。
+凭据只来自账号登录:`ctx.deepseekAuth` 调用 `deepseekAccount.resolveRequestCredential(url)`,目标地址必须通过账号服务的来源校验。未登录或目标不允许账号鉴权时,请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,目录为空;不会回退到 API key。其他凭据查询错误继续向调用者报告。本插件只在挂载了 `@deepseek-ai/dsh-deepseek-auth` 的组合中启动;`base` 组合包挂载它。
路由的目录来自账号的 `GET /models` 列表,地址为 Messages `baseURL` 的 origin 加 `/models`(官方端点即 `https://api.deepseek.com/models`),不可配置。列表请求用 `x-dsh-auth-token` 携带账号 token,带上 harness 的 `User-Agent`,并拒绝重定向。
@@ -63,7 +63,7 @@ kind: "package-reference"
## 理解实现
-账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求;在途的模型请求会把它的凭据和失败回调保留到请求结束,因此二者可能在释放之后执行。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和凭据请求头的 SHA-256 为键。
+账号凭据的读取与作废经由 `ctx.deepseekAuth`,后者调用账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求;在途的模型请求会把它的凭据和失败回调保留到请求结束,因此二者可能在释放之后执行。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和凭据请求头的 SHA-256 为键。
共享传输判定为 `QUOTA` 的失败请求离开本提供方前会被改写为 `ACCOUNT_QUOTA`,HTTP 402 响应与流内 SSE 错误都适用。共享传输与 `deepseek-official` 路由保留 `QUOTA`,因此账号路由的充值操作不会出现在 API Key 或第三方失败上。
diff --git a/packages/llm/llm-deepseek-account/package.json b/packages/llm/llm-deepseek-account/package.json
index 48333500d9..b903651587 100644
--- a/packages/llm/llm-deepseek-account/package.json
+++ b/packages/llm/llm-deepseek-account/package.json
@@ -42,7 +42,8 @@
"@deepseek-ai/dsh-launch-environment": "workspace:*",
"@deepseek-ai/dsh-deepseek-account": "workspace:*",
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
- "@deepseek-ai/dsh-agent": "workspace:*"
+ "@deepseek-ai/dsh-agent": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/dsh-brand": "workspace:*",
@@ -54,7 +55,8 @@
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
"@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*",
"@deepseek-ai/dsh-timeout": "workspace:*",
- "@deepseek-ai/dsh-agent": "workspace:*"
+ "@deepseek-ai/dsh-agent": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"peerDependenciesMeta": {
"@deepseek-ai/dsh-deepseek-account": {
diff --git a/packages/llm/llm-deepseek-account/src/index.ts b/packages/llm/llm-deepseek-account/src/index.ts
index d9ea06b2db..9547775bc6 100644
--- a/packages/llm/llm-deepseek-account/src/index.ts
+++ b/packages/llm/llm-deepseek-account/src/index.ts
@@ -2,7 +2,7 @@
import type {} from '@deepseek-ai/cordis-plugin-loader'
import type { Context } from '@deepseek-ai/cordis'
import { ACCOUNT_QUOTA_EXCEEDED_CODE, APP_IDENTITY, LlmError, QUOTA_EXCEEDED_CODE } from '@deepseek-ai/dsh-llm'
-import type { AccountRequestCredential } from '@deepseek-ai/dsh-deepseek-account'
+import type { DeepSeekAuthorization } from '@deepseek-ai/dsh-deepseek-auth'
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
import {
catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveAdapterOptions, resolveListedCatalog,
@@ -13,7 +13,7 @@ import { Config, plainAccountOptions, resolveAccountOptions } from './config.ts'
export { Config } from './config.ts'
export const name = 'llm-deepseek-account'
-export const inject = ['llm']
+export const inject = ['llm', 'deepseekAuth']
const PROVIDER = 'deepseek-account'
/** Console tag of listing diagnostics; product profiles mount no console exporter for `ctx.logger`. */
@@ -28,37 +28,44 @@ export function apply(ctx: Context, config: Config): void {
const environment = launchEnvironmentOf(ctx)
const settings = () => resolveAccountOptions(plainAccountOptions(config), environment)
settings()
+ // Every other DeepSeek consumer billed by the account sends the sign-in to this route's deployment.
+ ctx.effect(() => ctx.deepseekAuth.connect('account', PROVIDER, () => ({ baseURL: settings().protocol.baseURL })), 'llm-deepseek-account: account deployment')
const supported = resolveAdapterOptions({}).models
- /** The account credential released for one destination; absent without an allowed signed-in account or without the account service. */
- const requestCredential = async (endpoint: string): Promise =>
- await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)
+ /**
+ * The account sign-in `ctx.deepseekAuth` releases for one destination under the deployment at `baseURL`; absent
+ * without an allowed signed-in account or without the account service.
+ */
+ const requestCredential = (baseURL: string, endpoint: string): Promise =>
+ ctx.deepseekAuth.authorize({
+ consumer: name, accepts: ['account'], billing: 'account', destination: { url: endpoint }, connections: { account: { baseURL } },
+ })
/** The failure of a request whose account signed out before it finished: the code a request made after the sign-out fails with. */
const signedOutMidRequest = (cause: unknown) => new LlmError(
'The DeepSeek account signed out before this request finished. Sign in to DeepSeek to use the account provider.',
'ACCOUNT_SIGN_IN_REQUIRED',
{ cause },
)
- const resolveAuth = async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => {
- const credential = await requestCredential(endpoint)
+ const resolveAuth = async (connection: ResolvedDeepSeekOptions, endpoint: string): Promise => {
+ const credential = await requestCredential(connection.baseURL, endpoint)
if (credential === undefined) return undefined
return {
...credential,
onRequestError: async (error) => {
try {
// A sign-out ends the requests that carry its token, so it is the failure of any request that fails after it.
- if (credential.revoked.aborted) return signedOutMidRequest(error)
+ if (credential.revoked?.aborted === true) return signedOutMidRequest(error)
if (!(error instanceof LlmError)) return error
if (error.code === QUOTA_EXCEEDED_CODE) {
return new LlmError(error.message, ACCOUNT_QUOTA_EXCEEDED_CODE, { ...error.failure, cause: error })
}
if (error.failure.status !== 401) return error
const rejected = new LlmError(error.message, 'ACCOUNT_TOKEN_INVALID', { ...error.failure, cause: error })
- await credential.reject()
+ await credential.reject?.()
return rejected
} finally {
// A request can outlive this plugin and the sign-out listener it mounts. Once the credential it carried is
// signed out, by the user or by the rejection above, the request ends this route's tasks itself.
- if (credential.revoked.aborted) cancelAccountTasks(ctx, PROVIDER)
+ if (credential.revoked?.aborted === true) cancelAccountTasks(ctx, PROVIDER)
}
},
}
@@ -69,7 +76,7 @@ export function apply(ctx: Context, config: Config): void {
)
const catalog = createModelListingCache(ctx, name, PROVIDER, {
settings: () => settings().catalog,
- credential: async url => (await requestCredential(url))?.headers,
+ credential: async url => (await requestCredential(settings().protocol.baseURL, url))?.headers,
})
let loggedListing: ModelListing | undefined
/** Resolve the catalog, reporting each listing's hidden entries and dropped badges once. */
@@ -107,10 +114,6 @@ export function apply(ctx: Context, config: Config): void {
connect: async signal => connectionOf(await catalog.view(settings().catalog, signal)),
resolveAuth,
missingCredential,
- credential: {
- kind: 'account',
- configured: async (_connection, endpoint) => (await requestCredential(endpoint)) !== undefined,
- },
admit: (connection, model) => { refuseListedModel(model, connection.catalog.refusals.get(model)) },
discoverModels: async (provider) => {
const view = await catalog.view(settings().catalog)
diff --git a/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts b/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts
index 81870b249c..a17b24bb39 100644
--- a/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts
+++ b/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts
@@ -5,6 +5,7 @@ import { accountStub } from '../../../account/deepseek-account/tests/account-stu
import * as ApiKey from '@deepseek-ai/dsh-llm-deepseek-api-key'
import { afterEach, expect, it, vi } from 'vitest'
import * as Account from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
const contexts: Context[] = []
afterEach(async () => {
@@ -34,6 +35,7 @@ async function routeFor(token: string | undefined, provider: 'deepseek-account'
contexts.push(ctx)
await ctx.plugin(LlmRuntime)
ctx.provide('deepseekAccount', accountStub({ token: () => token }))
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(provider === 'deepseek-account' ? Account : ApiKey)
return ctx
}
@@ -69,6 +71,7 @@ it('still expires the stored credential on an account-route 401', async () => {
await ctx.plugin(LlmRuntime)
const rejectToken = vi.fn(async (_token: string): Promise => {})
ctx.provide('deepseekAccount', accountStub({ token: () => 'account-token', reject: rejectToken }))
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Account)
vi.spyOn(globalThis, 'fetch').mockImplementation(messagesOnly(() => new Response('Unauthorized', { status: 401 })))
await expect(finishOf(ctx, 'deepseek-account')).resolves.toMatchObject({
diff --git a/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts b/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts
index 07f773d8dd..6cf50935ca 100644
--- a/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts
+++ b/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts
@@ -4,6 +4,7 @@ import { BlockAssembler, LlmRuntime } from '@deepseek-ai/dsh-llm'
import { afterEach, expect, it, vi } from 'vitest'
import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts'
import * as Account from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
const contexts: Context[] = []
afterEach(async () => {
@@ -42,6 +43,7 @@ async function route(options: { reject?: (token: string) => void; agents?: boole
accountStub({ token: () => 'account-token', signedOut: signedOut.signal, ...reject === undefined ? {} : { reject } }),
{ registerRunningTaskReport: () => () => {} },
))
+ await ctx.plugin(DeepSeekAuth)
const plugin = ctx.plugin(Account)
await plugin
return { ctx, signedOut, cancelAccountTask, cancelApiKeyTask, plugin }
diff --git a/packages/llm/llm-deepseek-account/tests/provider.spec.ts b/packages/llm/llm-deepseek-account/tests/provider.spec.ts
index ac9ab397f4..7803cade06 100644
--- a/packages/llm/llm-deepseek-account/tests/provider.spec.ts
+++ b/packages/llm/llm-deepseek-account/tests/provider.spec.ts
@@ -8,6 +8,7 @@ import LlmRuntime, { type ReasoningEffortId } from '@deepseek-ai/dsh-llm'
import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts'
import * as ApiKey from '@deepseek-ai/dsh-llm-deepseek-api-key'
import * as Account from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
const MESSAGES = { output_modalities: ['text'], api_capabilities: { anthropic_messages: {} } }
const FLASH = {
@@ -60,6 +61,7 @@ it('keeps discovery and disposal independent across the two credential routes',
const server = await listing(json({ data: [FLASH, PRO] }))
let token: string | undefined = 'fixture-account-token'
const ctx = await host(server.origin, () => token)
+ await ctx.plugin(DeepSeekAuth)
const account = ctx.plugin(Account, { baseURL: server.baseURL })
await account
const official = ctx.plugin(ApiKey, { models: [{ id: 'api-key-model', name: 'API-key model' }] })
@@ -86,6 +88,7 @@ it('keeps discovery and disposal independent across the two credential routes',
it('resolves listed capabilities with this build\'s model knowledge', async () => {
const server = await listing(json({ data: [FLASH, PRO] }))
const ctx = await host(server.origin)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Account, { baseURL: server.baseURL })
await expect(ctx.llm.resolveModelInfo('deepseek-account', 'deepseek-flash')).resolves.toMatchObject({
name: 'DeepSeek-V4.1-Flash', context: { contextWindow: 1_048_576 }, defaultMaxTokens: 256_000,
@@ -101,6 +104,7 @@ it('advertises the badges its listing declares', async () => {
const badge = { text: { en: 'New', zh: '新' }, tone: 'success' }
const server = await listing(json({ data: [{ ...FLASH, client_metadata: { 'deepseek-harness': { badge } } }, PRO] }))
const ctx = await host(server.origin)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Account, { baseURL: server.baseURL })
expect((await ctx.llm.listModels('deepseek-account')).map(row => [row.id, row.badge])).toEqual([
['deepseek-flash', badge], ['deepseek-v4-pro', undefined],
@@ -121,6 +125,7 @@ it('publishes an account badge removal after the default idle refresh interval',
})
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
try {
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Account, { baseURL: server.baseURL })
expect((await ctx.llm.listModels('deepseek-account'))[0]?.badge?.text).toBe('New')
badge = undefined
@@ -139,6 +144,7 @@ it('falls back to the bundled catalog when the listing fails', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const server = await listing((_request, response) => { response.writeHead(503).end('down') })
const ctx = await host(server.origin)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Account, { baseURL: server.baseURL })
expect((await ctx.llm.listModels('deepseek-account')).map(row => row.id)).toEqual(['deepseek-flash', 'deepseek-v4-pro'])
expect(warn).toHaveBeenCalledExactlyOnceWith('[llm-deepseek-account]', expect.stringContaining('using the bundled catalog') as string)
@@ -156,6 +162,7 @@ it('hides and refuses listed models this build cannot serve before any inference
{ id: 'deepseek-v4-pro' },
] }))
const ctx = await host(server.origin)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Account, { baseURL: server.baseURL })
expect((await ctx.llm.listModels('deepseek-account')).map(row => row.id)).toEqual(['deepseek-flash', 'deepseek-v5-open'])
await expect(ctx.llm.prepareCall({ provider: 'deepseek-account', model: 'deepseek-v5' })).rejects.toMatchObject({ code: 'MODEL_UNSUPPORTED' })
@@ -175,6 +182,7 @@ it('applies model overrides and reports stale ones on the provider directory unt
json({ data: rows })(request, response)
})
const ctx = await host(server.origin, () => token)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Account, { baseURL: server.baseURL, modelOverrides: { 'deepseek-flash': { contextWindow: 524_288 }, 'deepseek-v5': { contextWindow: 9 } } })
await ctx.llm.listModels('deepseek-account')
await expect(ctx.llm.resolveModelInfo('deepseek-account', 'deepseek-flash')).resolves.toMatchObject({ context: { contextWindow: 524_288 } })
@@ -189,6 +197,7 @@ it('applies model overrides and reports stale ones on the provider directory unt
it('rejects the retired models setting at load', async () => {
const ctx = await host('http://127.0.0.1:1')
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(Account, { models: [] })).rejects.toThrow(/models is no longer configurable/)
expect(ctx.llm.listProviders()).toEqual([])
})
@@ -197,6 +206,7 @@ it('aborts an in-flight listing request when the plugin is disposed', async () =
const held = Promise.withResolvers()
const server = await listing((request) => { held.resolve(request) })
const ctx = await host(server.origin)
+ await ctx.plugin(DeepSeekAuth)
const account = ctx.plugin(Account, { baseURL: server.baseURL })
await account
const pending = ctx.llm.listModels('deepseek-account')
@@ -207,33 +217,21 @@ it('aborts an in-flight listing request when the plugin is disposed', async () =
await expect(pending).resolves.toEqual(expect.any(Array))
})
-it('publishes the account credential for its consumers, asking the account for each endpoint', async () => {
+it('connects its route id and deployment, so other DeepSeek consumers send the account sign-in to its origin', async () => {
const asked: string[] = []
- let token: string | undefined = 'fixture-account-token'
const ctx = new Context()
contexts.push(ctx)
await ctx.plugin(LlmRuntime)
- ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return token } }))
- await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' })
- const credential = ctx.llm.providerCredential('deepseek-account')
- expect(credential).toMatchObject({ kind: 'account', baseURL: 'https://account.deepseek.test/anthropic' })
- expect(credential).not.toHaveProperty('reference')
- const endpoint = 'https://account.deepseek.test/v1/tools/search'
- await expect(credential!.configured(endpoint)).resolves.toBe(true)
- await expect(credential!.resolve(endpoint)).resolves.toMatchObject({ headers: { 'x-dsh-auth-token': 'fixture-account-token' }, value: 'fixture-account-token' })
- token = undefined
- await expect(credential!.configured(endpoint)).resolves.toBe(false)
- await expect(credential!.resolve(endpoint)).resolves.toBeUndefined()
- expect(asked).toEqual([endpoint, endpoint, endpoint, endpoint])
- expect(ctx.llm.providerCredential('deepseek-official')).toBeUndefined()
-})
-
-it('publishes a credential nobody holds without the account service', async () => {
- const ctx = new Context()
- contexts.push(ctx)
- await ctx.plugin(LlmRuntime)
- await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' })
- const credential = ctx.llm.providerCredential('deepseek-account')!
- await expect(credential.configured('https://account.deepseek.test/v1/tools/search')).resolves.toBe(false)
- await expect(credential.resolve('https://account.deepseek.test/v1/tools/search')).resolves.toBeUndefined()
+ ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return 'fixture-account-token' } }))
+ await ctx.plugin(DeepSeekAuth)
+ const search = { consumer: 'web-test', accepts: ['account'], billing: 'account', destination: { path: '/v1/tools/search' } } as const
+ const route = await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' })
+ expect(ctx.deepseekAuth.routeKind('deepseek-account')).toBe('account')
+ expect(await ctx.deepseekAuth.authorize(search)).toMatchObject({
+ kind: 'account', endpoint: 'https://account.deepseek.test/v1/tools/search', headers: { 'x-dsh-auth-token': 'fixture-account-token' },
+ })
+ await route.dispose()
+ expect(ctx.deepseekAuth.routeKind('deepseek-account')).toBeUndefined()
+ expect(await ctx.deepseekAuth.authorize(search)).toMatchObject({ endpoint: 'https://api.deepseek.com/v1/tools/search' })
+ expect(asked).toEqual(['https://account.deepseek.test/v1/tools/search', 'https://api.deepseek.com/v1/tools/search'])
})
diff --git a/packages/llm/llm-deepseek-account/tsconfig.json b/packages/llm/llm-deepseek-account/tsconfig.json
index 725d721c73..819cf572c5 100644
--- a/packages/llm/llm-deepseek-account/tsconfig.json
+++ b/packages/llm/llm-deepseek-account/tsconfig.json
@@ -34,6 +34,9 @@
},
{
"path": "../../core/agent"
+ },
+ {
+ "path": "../../account/deepseek-auth"
}
]
}
diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml
index 6b0f0744ae..ac19d15e20 100644
--- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml
+++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml
@@ -9,17 +9,17 @@
en: b6871195e386cc64
zh: 742b05a3ca80883c
/deepseek-ai-dsh-llm-deepseek-api-key/summary:
- en: 25f6f430c8ce1a6b
- zh: b221bef9390771e7
+ en: 3e86ef7b396d1ae2
+ zh: ce99f1095d90d0a7
/deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents:
en: 23386452a66b2fbd
zh: 4cf93c4bf17b3da2
/deepseek-ai-dsh-llm-deepseek-api-key/use-this-package:
- en: f342f3bba7246464
- zh: 8073e5bf0c760fc6
+ en: 382b0489976b8642
+ zh: 9bbff6c681a9ed86
/deepseek-ai-dsh-llm-deepseek-api-key/understand-the-implementation:
- en: 2fe0f32c15603cd9
- zh: 984ce05b82e8e679
+ en: c12e159cb4d8b31c
+ zh: 20fc6c969391c3d8
/deepseek-ai-dsh-llm-deepseek-api-key/further-exploration:
en: 347659458510940c
zh: ccfb03e18b356a39
diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md
index c0010921d9..05090e772c 100644
--- a/packages/llm/llm-deepseek-api-key/README.md
+++ b/packages/llm/llm-deepseek-api-key/README.md
@@ -11,7 +11,7 @@ English | [中文](README.zh.md)
Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission.
-Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.providerCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL.
+Authentication resolution asks [`ctx.deepseekAuth`](../../account/deepseek-auth/README.md) for the validated API key in `x-api-key` for Messages, Files, and listing requests. The route connects its route id, base URL, and `apiKeyEnv` reference to that service, so the DeepSeek web providers send the same key as a bearer token to the same deployment. The key is released only for destinations under the origin of that base URL.
## Table of Contents
@@ -25,7 +25,7 @@ Authentication resolution returns the validated API key in `x-api-key` for Messa
## Use this package
-`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. It reads the key through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): when the credentials service exists, its precedence applies, and only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`, whose diagnostic names this plugin's settings namespace and the credential reference. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call.
+`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. `ctx.deepseekAuth` reads the key through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): when the credentials service exists, its precedence applies, and only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`, whose diagnostic names this plugin's settings namespace and the credential reference. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. The plugin starts only in a composition that mounts `@deepseek-ai/dsh-deepseek-auth`; the `base` and `sdk-minimal` bundles mount it.
```yaml
- id: llm-deepseek
@@ -35,7 +35,7 @@ Authentication resolution returns the validated API key in `x-api-key` for Messa
apiKeyEnv: DEEPSEEK_API_KEY
```
-The endpoint and credential reference come from one configuration resolution. In-flight requests retain that snapshot; subsequent updates affect subsequent calls. Account login state cannot change this route’s credential. For a destination at another origin, or a URL that embeds credentials, the published credential's `configured()` answers false and its `resolve()` releases nothing, and neither reads the credential store.
+The endpoint and credential reference come from one configuration resolution. In-flight requests retain that snapshot; subsequent updates affect subsequent calls. Account login state cannot change this route’s credential. For a destination at another origin, or a URL that embeds credentials, `ctx.deepseekAuth` releases no key and does not read the credential store.
`models` is an independently configurable catalog for this provider; defaults and protocol capabilities come from the shared transport. While `models` equals the built-in catalog and the Messages origin is the official API, `https://api.deepseek.com`, the route serves the official `GET https://api.deepseek.com/models` listing instead. Listing requests carry the API key in `x-api-key` and the harness `User-Agent`, and reject redirects; without an API key the route requests nothing. Any other endpoint, including one named by `baseURL` or `$DEEPSEEK_BASE_URL`, serves `models` and requests no listing. Discovery does not probe inference endpoints.
@@ -55,7 +55,7 @@ The settings namespace is the Cordis entry id, or the plugin name without an ent
## Understand the implementation
-API-key lookup calls `resolveCredentialRef` and `credentialRefConfigured` from `dsh-credentials` and validates the value with `assertUsableApiKey` from `dsh-llm`; the shared transport reads no credential. Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the listed catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport; the cache lives in memory and is keyed by endpoint and a SHA-256 of the key, so another key loads its own listing. A `loader/volatile-update` listener discards the cached listing whenever the route starts or stops following it.
+API-key lookup goes through `ctx.deepseekAuth`, which reads the key under the route's `apiKeyEnv` reference and checks that it can travel in an HTTP header; this plugin reports an unusable key as `INVALID_CREDENTIAL`, and the shared transport reads no credential. Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the listed catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport; the cache lives in memory and is keyed by endpoint and a SHA-256 of the key, so another key loads its own listing. A `loader/volatile-update` listener discards the cached listing whenever the route starts or stops following it.
## Further Exploration
diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md
index 59b5229f04..17a245402a 100644
--- a/packages/llm/llm-deepseek-api-key/README.zh.md
+++ b/packages/llm/llm-deepseek-api-key/README.zh.md
@@ -11,7 +11,7 @@ kind: "package-reference"
为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。
-鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.providerCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥。
+鉴权解析向 [`ctx.deepseekAuth`](../../account/deepseek-auth/README.zh.md) 索取验证后的 API key,放入 `x-api-key`,供 Messages、Files 和列表请求使用。路由把自己的路由 id、基础地址和 `apiKeyEnv` 引用登记到该服务,使 DeepSeek Web 提供方以 Bearer 令牌把同一密钥发往同一部署。密钥只对该基础地址所在 origin 下的目的地释放。
## 目录
@@ -25,7 +25,7 @@ kind: "package-reference"
## 使用此包
-`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败,其诊断点名本插件的设置命名空间与凭据引用。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。
+`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。密钥由 `ctx.deepseekAuth` 通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败,其诊断点名本插件的设置命名空间与凭据引用。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。本插件只在挂载了 `@deepseek-ai/dsh-deepseek-auth` 的组合中启动;`base` 与 `sdk-minimal` 两个组合包挂载它。
```yaml
- id: llm-deepseek
@@ -35,7 +35,7 @@ kind: "package-reference"
apiKeyEnv: DEEPSEEK_API_KEY
```
-端点和凭据引用来自同一次配置解析;进行中的请求保留该快照,后续配置更新仅影响后续请求。账号登录态不影响该路由使用的凭据。对其他 origin 的目的地或内嵌凭据的 URL,发布的凭据的 `configured()` 回答 false,`resolve()` 不释放任何内容,二者都不读取凭据存储。
+端点和凭据引用来自同一次配置解析;进行中的请求保留该快照,后续配置更新仅影响后续请求。账号登录态不影响该路由使用的凭据。对其他 origin 的目的地或内嵌凭据的 URL,`ctx.deepseekAuth` 不释放密钥,也不读取凭据存储。
`models` 是该 provider 独立的可配置目录;默认值和协议能力来自共享传输包。当 `models` 等于内置目录、且 Messages 的 origin 是官方 API `https://api.deepseek.com` 时,路由改为提供官方 `GET https://api.deepseek.com/models` 列表。列表请求用 `x-api-key` 携带 API key,带上 harness 的 `User-Agent`,并拒绝重定向;没有 API key 时不发任何请求。其他端点,包括由 `baseURL` 或 `$DEEPSEEK_BASE_URL` 指定的端点,提供 `models`,不请求列表。目录判断不探测推理端点。
@@ -55,7 +55,7 @@ kind: "package-reference"
## 理解实现
-API key 读取调用 `dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured`,并用 `dsh-llm` 的 `assertUsableApiKey` 校验值;共享传输层不读取任何凭据。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入列表目录和门控。列表请求、缓存和目录解析来自共享传输包;缓存只在内存中,以端点和 API key 的 SHA-256 为键,因此换一个 key 会加载它自己的列表。一个 `loader/volatile-update` 监听器在路由开始或停止使用列表时丢弃缓存的列表。
+API key 的读取经由 `ctx.deepseekAuth`:它按路由的 `apiKeyEnv` 引用读取密钥,并检查密钥能否放进 HTTP 请求头;本插件把不可用的密钥报告为 `INVALID_CREDENTIAL`,共享传输层不读取任何凭据。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入列表目录和门控。列表请求、缓存和目录解析来自共享传输包;缓存只在内存中,以端点和 API key 的 SHA-256 为键,因此换一个 key 会加载它自己的列表。一个 `loader/volatile-update` 监听器在路由开始或停止使用列表时丢弃缓存的列表。
## 进一步探索
diff --git a/packages/llm/llm-deepseek-api-key/package.json b/packages/llm/llm-deepseek-api-key/package.json
index e93842548c..0c3c627e66 100644
--- a/packages/llm/llm-deepseek-api-key/package.json
+++ b/packages/llm/llm-deepseek-api-key/package.json
@@ -37,7 +37,8 @@
"@deepseek-ai/dsh-llm-deepseek": "workspace:*",
"@deepseek-ai/dsh-launch-environment": "workspace:*",
"@deepseek-ai/dsh-credentials": "workspace:*",
- "@deepseek-ai/cordis-plugin-loader": "workspace:~"
+ "@deepseek-ai/cordis-plugin-loader": "workspace:~",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
@@ -45,7 +46,8 @@
"@deepseek-ai/dsh-llm-deepseek": "workspace:*",
"@deepseek-ai/dsh-launch-environment": "workspace:*",
"@deepseek-ai/dsh-credentials": "workspace:*",
- "@deepseek-ai/cordis-plugin-loader": "workspace:~"
+ "@deepseek-ai/cordis-plugin-loader": "workspace:~",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"peerDependenciesMeta": {
"@deepseek-ai/cordis-plugin-loader": {
diff --git a/packages/llm/llm-deepseek-api-key/src/index.ts b/packages/llm/llm-deepseek-api-key/src/index.ts
index a35e6aebaa..cb2e2c8ff9 100644
--- a/packages/llm/llm-deepseek-api-key/src/index.ts
+++ b/packages/llm/llm-deepseek-api-key/src/index.ts
@@ -1,9 +1,9 @@
/** API-key authentication, credential-gated discovery, and the official model listing for the official DeepSeek route. */
import type { Context } from '@deepseek-ai/cordis'
-import { APP_IDENTITY, assertUsableApiKey, LlmError } from '@deepseek-ai/dsh-llm'
+import { APP_IDENTITY, INVALID_CREDENTIAL_CODE, LlmError } from '@deepseek-ai/dsh-llm'
import type { LlmModelBadge } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/cordis-plugin-loader'
-import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials'
+import { DeepSeekAuthError } from '@deepseek-ai/dsh-deepseek-auth'
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
import {
catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveListedCatalog,
@@ -15,7 +15,7 @@ import type { ResolvedDeepSeekOptions } from './config.ts'
export { Config } from './config.ts'
export type { Options, ResolvedDeepSeekOptions } from './config.ts'
export const name = 'llm-deepseek-api-key'
-export const inject = ['llm']
+export const inject = ['llm', 'deepseekAuth']
const PROVIDER = 'deepseek-official'
/** Console tag of listing diagnostics; product profiles mount no console exporter for `ctx.logger`. */
@@ -36,24 +36,29 @@ export function apply(ctx: Context, config: Config): void {
const settingsNs = ctx.fiber.entry?.options.id ?? name
const options = () => resolveAdapterOptions(plainOptions(config), launchEnvironmentOf(ctx))
options()
- /** The validated API key, or `undefined` when none is configured; store and format failures propagate. */
- const resolveApiKey = async (connection: ResolvedDeepSeekOptions): Promise => {
- const value = await resolveCredentialRef(ctx, connection.apiKeyEnv)
- return value === undefined ? undefined : assertUsableApiKey(value, settingsNs, connection.apiKeyEnv)
- }
+ // Every other DeepSeek consumer billed by the API key sends this route's key to this route's deployment.
+ ctx.effect(() => ctx.deepseekAuth.connect('api-key', PROVIDER, () => {
+ const connection = options()
+ return { baseURL: connection.baseURL, reference: connection.apiKeyEnv, owner: settingsNs }
+ }), 'llm-deepseek-api-key: API-key deployment')
/**
- * Whether `endpoint` belongs to the deployment this route sends its key to: the origin of the route's base URL,
- * without credentials embedded in the URL.
+ * The key `ctx.deepseekAuth` releases for `endpoint` from one configuration generation, in the header Messages
+ * expects; `undefined` when none is configured or `endpoint` is outside the route's deployment. An unusable key fails
+ * as this route's `INVALID_CREDENTIAL`; store failures propagate.
*/
- const servedByRoute = (connection: ResolvedDeepSeekOptions, endpoint: string): boolean => {
- const destination = new URL(endpoint)
- return destination.origin === new URL(connection.baseURL).origin && destination.username === '' && destination.password === ''
- }
const resolveAuth = async (connection: ResolvedDeepSeekOptions, endpoint: string): Promise => {
- // The store is read only for a destination this route serves, as the presence check below.
- if (!servedByRoute(connection, endpoint)) return undefined
- const key = await resolveApiKey(connection)
- return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key }
+ try {
+ return await ctx.deepseekAuth.authorize({
+ consumer: settingsNs, accepts: ['api-key'], billing: 'api-key', destination: { url: endpoint },
+ connections: { 'api-key': { baseURL: connection.baseURL, reference: connection.apiKeyEnv } },
+ apiKeyHeaders: ['x-api-key'],
+ })
+ } catch (error) {
+ if (error instanceof DeepSeekAuthError && error.code === 'INVALID_CREDENTIAL') {
+ throw new LlmError(error.message, INVALID_CREDENTIAL_CODE, { cause: error })
+ }
+ throw error
+ }
}
const missingCredential = (connection: ResolvedDeepSeekOptions) => new LlmError(
`llm-deepseek: no API key for provider route "${PROVIDER}"; store ${connection.apiKeyEnv} through the credentials`
@@ -105,17 +110,11 @@ export function apply(ctx: Context, config: Config): void {
},
resolveAuth,
missingCredential,
- credential: {
- kind: 'api-key',
- reference: connection => connection.apiKeyEnv,
- configured: async (connection, endpoint) =>
- servedByRoute(connection, endpoint) && await credentialRefConfigured(ctx, connection.apiKeyEnv),
- },
admit: (connection, model) => { refuseListedModel(model, connection.refusals.get(model)) },
discoverModels: async (provider) => {
const connection = options()
if (connection.listing === undefined) {
- if (await resolveApiKey(connection) === undefined) return []
+ if (await resolveAuth(connection, connection.baseURL) === undefined) return []
return connection.models.map(model => catalogModelInfo(provider, model))
}
const view = await listings.view(connection.listing)
diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts
index 5f1cb8035f..9ee1222553 100644
--- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts
+++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts
@@ -3,12 +3,14 @@ import { Context } from '@deepseek-ai/cordis'
import LlmRuntime from '@deepseek-ai/dsh-llm'
import { expect, it, vi } from 'vitest'
import * as ApiKey from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
it.each([undefined, ''])('hides models without an API key: %j', async (key) => {
vi.stubEnv('DEEPSEEK_API_KEY', key)
const ctx = new Context()
try {
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, {})
expect(await ctx.llm.listModels('deepseek-official')).toEqual([])
} finally {
@@ -22,6 +24,7 @@ it('advertises configured models with an API key', async () => {
const ctx = new Context()
try {
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, { models: [{ id: 'configured-model' }] })
expect(await ctx.llm.listModels('deepseek-official')).toEqual([
expect.objectContaining({ provider: 'deepseek-official', id: 'configured-model' }),
@@ -37,6 +40,7 @@ it('reports malformed credentials during discovery under the settings namespace
const ctx = new Context()
try {
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, {})
const [directory] = ctx.llm.listConfigurableProviders()
expect(directory?.settingsNs).toBe('llm-deepseek-api-key')
@@ -54,6 +58,7 @@ it('names the Loader entry id in credential diagnostics, as product profiles mou
const ctx = new Context()
try {
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin({
name: ApiKey.name, inject: ApiKey.inject, Config: ApiKey.Config,
apply: (inner: Context, config: ApiKey.Config) => {
@@ -72,52 +77,39 @@ it('names the Loader entry id in credential diagnostics, as product profiles mou
}
})
-it('publishes the route API key for its consumers from the credential planes it reads itself', async () => {
- vi.stubEnv('DEEPSEEK_API_KEY', 'fixture-api-key')
+it('connects its route id, key reference and deployment, so other DeepSeek consumers send its key to its origin', async () => {
+ vi.stubEnv('DEEPSEEK_API_KEY', 'default-key')
+ vi.stubEnv('ROUTE_KEY', 'fixture-api-key')
const ctx = new Context()
try {
await ctx.plugin(LlmRuntime)
- await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' })
- const credential = ctx.llm.providerCredential('deepseek-official')
- expect(credential).toMatchObject({ kind: 'api-key', baseURL: 'https://route.deepseek.test/anthropic', reference: 'DEEPSEEK_API_KEY' })
- const endpoint = 'https://route.deepseek.test/v1/tools/search'
- await expect(credential!.configured(endpoint)).resolves.toBe(true)
- await expect(credential!.resolve(endpoint)).resolves.toEqual({ headers: { 'x-api-key': 'fixture-api-key' }, value: 'fixture-api-key' })
- vi.stubEnv('DEEPSEEK_API_KEY', '')
- await expect(credential!.configured(endpoint)).resolves.toBe(false)
- await expect(credential!.resolve(endpoint)).resolves.toBeUndefined()
- vi.stubEnv('DEEPSEEK_API_KEY', 'invalid\nheader')
- await expect(credential!.configured(endpoint)).resolves.toBe(true)
- await expect(credential!.resolve(endpoint)).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' })
+ await ctx.plugin(DeepSeekAuth)
+ const search = { consumer: 'web-test', accepts: ['api-key'], billing: 'api-key', destination: { path: '/v1/tools/search' } } as const
+ const route = await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic', apiKeyEnv: 'ROUTE_KEY' })
+ expect(ctx.deepseekAuth.routeKind('deepseek-official')).toBe('api-key')
+ expect(await ctx.deepseekAuth.authorize(search)).toEqual({
+ kind: 'api-key', endpoint: 'https://route.deepseek.test/v1/tools/search', reference: 'ROUTE_KEY', headers: { authorization: 'Bearer fixture-api-key' },
+ })
+ vi.stubEnv('ROUTE_KEY', 'invalid\nheader')
+ await expect(ctx.deepseekAuth.authorize(search)).rejects.toThrow('llm-deepseek-api-key: the API key resolved from ROUTE_KEY contains characters')
+ await route.dispose()
+ expect(ctx.deepseekAuth.routeKind('deepseek-official')).toBeUndefined()
+ expect(await ctx.deepseekAuth.authorize(search)).toMatchObject({ endpoint: 'https://api.deepseek.com/v1/tools/search', reference: 'DEEPSEEK_API_KEY' })
} finally {
await ctx.fiber.dispose()
vi.unstubAllEnvs()
}
})
-it.each([
- 'https://other-origin.example/v1/tools/search',
- 'http://route.deepseek.test/v1/tools/search',
- 'https://route.deepseek.test:8443/v1/tools/search',
- 'https://user@route.deepseek.test/v1/tools/search',
- 'https://:secret@route.deepseek.test/v1/tools/search',
-])('releases no key for %s, a destination outside the origin of its base URL, without reading the credential store', async (endpoint) => {
- const resolve = vi.fn(async () => ({ value: 'stored-key' }))
- const describe = vi.fn(async () => ({ configured: true }))
+it('fails a model listing whose credential store cannot be read with the store\'s failure', async () => {
+ const failure = new Error('credential store unreadable')
const ctx = new Context()
try {
- ctx.provide('credentials', { resolve, describe } as never)
+ ctx.provide('credentials', { resolve: () => Promise.reject(failure) } as never)
await ctx.plugin(LlmRuntime)
- await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' })
- const credential = ctx.llm.providerCredential('deepseek-official')
- await expect(credential!.configured(endpoint)).resolves.toBe(false)
- await expect(credential!.resolve(endpoint)).resolves.toBeUndefined()
- expect(resolve).not.toHaveBeenCalled()
- expect(describe).not.toHaveBeenCalled()
- // The same store answers for a destination under the route's origin.
- const served = 'https://route.deepseek.test/v1/tools/search'
- await expect(credential!.configured(served)).resolves.toBe(true)
- await expect(credential!.resolve(served)).resolves.toEqual({ headers: { 'x-api-key': 'stored-key' }, value: 'stored-key' })
+ await ctx.plugin(DeepSeekAuth)
+ await ctx.plugin(ApiKey, { models: [{ id: 'configured-model' }] })
+ await expect(ctx.llm.listModels('deepseek-official')).rejects.toBe(failure)
} finally {
await ctx.fiber.dispose()
}
diff --git a/packages/llm/llm-deepseek-api-key/tests/listing.spec.ts b/packages/llm/llm-deepseek-api-key/tests/listing.spec.ts
index 94d6bbe09b..e1dd4b8030 100644
--- a/packages/llm/llm-deepseek-api-key/tests/listing.spec.ts
+++ b/packages/llm/llm-deepseek-api-key/tests/listing.spec.ts
@@ -4,6 +4,7 @@ import { Context } from '@deepseek-ai/cordis'
import LlmRuntime from '@deepseek-ai/dsh-llm'
import { liveConfig } from '../../../settings/settings/tests/live-config.ts'
import * as ApiKey from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
const LISTING_URL = 'https://api.deepseek.com/models'
const MESSAGES = { output_modalities: ['text'], api_capabilities: { anthropic_messages: {} } }
@@ -51,6 +52,7 @@ const ids = async (ctx: Context) => (await ctx.llm.listModels('deepseek-official
it('follows the official listing while the catalog is the built-in one', async () => {
const requests = officialListing(listing(FLASH, { ...PRO, id: 'deepseek-v5', ...requires('0.0.1') }, PRO))
const { ctx, diagnostics } = await host()
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, {})
expect(await ids(ctx)).toEqual(['deepseek-flash', 'deepseek-v5', 'deepseek-v4-pro'])
await expect(ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-flash')).resolves.toMatchObject({
@@ -64,12 +66,14 @@ it('advertises listed badges only while it follows the listing', async () => {
const badge = { text: '1017', tone: 'info' }
officialListing(listing({ ...FLASH, client_metadata: { 'deepseek-harness': { badge } } }, PRO))
const { ctx } = await host()
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, {})
const listed = await ctx.llm.listModels('deepseek-official')
expect(listed.map(model => [model.id, model.badge])).toEqual([['deepseek-flash', badge], ['deepseek-v4-pro', undefined]])
await expect(ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-flash')).resolves.not.toHaveProperty('badge')
const other = await host()
+ await other.ctx.plugin(DeepSeekAuth)
await other.ctx.plugin(ApiKey, { baseURL: 'http://127.0.0.1:9/anthropic' })
expect((await other.ctx.llm.listModels('deepseek-official')).some(model => model.badge !== undefined)).toBe(false)
})
@@ -77,6 +81,7 @@ it('advertises listed badges only while it follows the listing', async () => {
it('keeps a customized catalog without requesting the listing', async () => {
const requests = officialListing(listing(FLASH))
const { ctx } = await host()
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, { models: [{ id: 'custom', name: 'Custom' }] })
expect(await ids(ctx)).toEqual(['custom'])
await expect(ctx.llm.resolveModelInfo('deepseek-official', 'custom')).resolves.toMatchObject({ name: 'Custom' })
@@ -86,6 +91,7 @@ it('keeps a customized catalog without requesting the listing', async () => {
it('serves the built-in catalog on another endpoint without requesting a listing', async () => {
const requests = officialListing(listing(FLASH))
const { ctx } = await host()
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, { baseURL: 'http://127.0.0.1:9/anthropic' })
expect(await ids(ctx)).toEqual(BUILT_IN)
expect(requests).toEqual([])
@@ -94,6 +100,7 @@ it('serves the built-in catalog on another endpoint without requesting a listing
it('falls back to the built-in catalog when the listing fails', async () => {
officialListing(() => new Response('down', { status: 503 }))
const { ctx, warn } = await host()
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, {})
expect(await ids(ctx)).toEqual(BUILT_IN)
expect(warn).toHaveBeenCalledExactlyOnceWith('[llm-deepseek-api-key]', expect.stringContaining('using the bundled catalog') as string)
@@ -104,6 +111,7 @@ it('refuses listed models this build cannot serve before any inference request',
FLASH, { ...PRO, id: 'deepseek-v5' }, { ...PRO, id: 'deepseek-v5-next', ...requires('99.0.0-alpha.1') }, { id: 'deepseek-v4-pro' },
))
const { ctx, warn } = await host()
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, {})
expect(await ids(ctx)).toEqual(['deepseek-flash'])
await expect(ctx.llm.prepareCall({ provider: 'deepseek-official', model: 'deepseek-v4-pro' })).rejects.toMatchObject({ code: 'MODEL_UNSUPPORTED' })
@@ -118,6 +126,7 @@ it("leaves a malformed replacement key to the request instead of refusing by the
const requests = officialListing(listing(FLASH, PRO, { ...PRO, id: 'deepseek-v5-next', ...requires('99.0.0-alpha.1') }))
const { ctx } = await host()
vi.stubEnv('MALFORMED_DEEPSEEK_API_KEY', 'invalid\nheader')
+ await ctx.plugin(DeepSeekAuth)
const live = await liveConfig(ctx, ApiKey, {})
await expect(ctx.llm.prepareCall({ provider: 'deepseek-official', model: 'deepseek-v5-next' })).rejects.toMatchObject({ code: 'CLIENT_UPGRADE_REQUIRED' })
await live.update({ apiKeyEnv: 'MALFORMED_DEEPSEEK_API_KEY' })
@@ -134,6 +143,7 @@ it('lets a caller abandon the first listing wait', async () => {
}, { once: true })
}))
const { ctx } = await host()
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, {})
const caller = new AbortController()
const pending = ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-flash', caller.signal)
@@ -145,6 +155,7 @@ it('lets a caller abandon the first listing wait', async () => {
it.each([[{}], [{ models: [{ id: 'custom' }] }]])('hides the route without a key and requests nothing for %j', async (config) => {
const requests = officialListing(listing(FLASH))
const { ctx } = await host('')
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, config)
expect(await ids(ctx)).toEqual([])
expect(requests).toEqual([])
@@ -153,6 +164,7 @@ it.each([[{}], [{ models: [{ id: 'custom' }] }]])('hides the route without a key
it('reloads the listing once when the catalog returns to the built-in one', async () => {
const requests = officialListing((_request, index) => (index === 0 ? listing(FLASH, PRO) : listing(FLASH, PRO, { ...PRO, id: 'deepseek-v5', ...requires('0.0.1') }))())
const { ctx } = await host()
+ await ctx.plugin(DeepSeekAuth)
const live = await liveConfig(ctx, ApiKey, {})
expect(await ids(ctx)).toEqual(BUILT_IN)
await live.update({ models: [{ id: 'custom' }] })
@@ -166,6 +178,7 @@ it('reloads the listing once when the catalog returns to the built-in one', asyn
it('keeps following the listing across an update the adapter rejects', async () => {
const requests = officialListing(listing(FLASH, PRO))
const { ctx } = await host()
+ await ctx.plugin(DeepSeekAuth)
const live = await liveConfig(ctx, ApiKey, {})
expect(await ids(ctx)).toEqual(BUILT_IN)
await live.update({ thinking: 'disabled', reasoningEffort: 'high' })
@@ -180,6 +193,7 @@ it.each([undefined, null])('notifies an idle client when a badge is replaced and
let badge: { text: string; tone: string } | null | undefined = { text: 'New', tone: 'info' }
officialListing(() => listing({ ...FLASH, client_metadata: { 'deepseek-harness': { badge } } })())
const { ctx } = await host()
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(ApiKey, {})
const changed = vi.fn()
ctx.on('llm/models-updated', changed)
diff --git a/packages/llm/llm-deepseek-api-key/tsconfig.json b/packages/llm/llm-deepseek-api-key/tsconfig.json
index 7556e5085a..e0b6177eea 100644
--- a/packages/llm/llm-deepseek-api-key/tsconfig.json
+++ b/packages/llm/llm-deepseek-api-key/tsconfig.json
@@ -28,6 +28,9 @@
},
{
"path": "../../../vendor/schemastery"
+ },
+ {
+ "path": "../../account/deepseek-auth"
}
]
}
diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml
index c929a5cfcc..db79ecedb1 100644
--- a/packages/llm/llm-deepseek/README.i18n.yaml
+++ b/packages/llm/llm-deepseek/README.i18n.yaml
@@ -9,8 +9,8 @@
en: e66a018af9e2de3c
zh: d7188003d01964bb
/deepseek-ai-dsh-llm-deepseek/summary:
- en: dc3675dcd430459e
- zh: 4abf101572e2e595
+ en: c76085f3ddeaa1e4
+ zh: 40bde51391cd9d10
/deepseek-ai-dsh-llm-deepseek/table-of-contents:
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
@@ -27,8 +27,8 @@
en: 2a634ead5b47fe97
zh: 46f199ee79a8c5dc
/deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials:
- en: 22d74c69c0aa9234
- zh: d70eaf90c93a76d1
+ en: 5f8cda73f2c10260
+ zh: 2a507d9ee8b9c67a
/deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images:
en: f20f2cfbb38e4ba9
zh: c527b91c8b747886
diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md
index 96223b73bc..d781753171 100644
--- a/packages/llm/llm-deepseek/README.md
+++ b/packages/llm/llm-deepseek/README.md
@@ -11,7 +11,7 @@ English | [中文](README.zh.md)
Provide the shared DeepSeek Messages transport, request configuration, and model capabilities. Compose [API-key](../llm-deepseek-api-key/README.md) or [account](../llm-deepseek-account/README.md) plugins for authentication, model discovery, and provider registration. Valid settings changes affect subsequent calls while in-flight calls retain their configuration. This package can run beside the [pi-ai adapter](../llm-pi-ai/README.md).
-`resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: its headers, its bare value, and an optional failure callback, or `undefined` when none is configured. Messages and Files send those headers without selecting a credential mode. Upload reuse is isolated by endpoint and a hash of the authentication headers; raw credentials are not persisted.
+`resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: its headers, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. Messages and Files send those headers without selecting a credential mode. Upload reuse is isolated by endpoint and a hash of the authentication headers; raw credentials are not persisted.
## Table of Contents
@@ -94,7 +94,7 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r
Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account route owns HTTP 401 classification and the account service the credential invalidation; the transport passes failures to the credential's callback.
-Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.providerCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither.
+Provider plugins supply credentials through two adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. The plugins take both the API key and the account sign-in from [`ctx.deepseekAuth`](../../account/deepseek-auth/README.md); this transport reads no credential.
### Streaming with thinking and images
diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md
index 84772f3fcd..5d897f62d2 100644
--- a/packages/llm/llm-deepseek/README.zh.md
+++ b/packages/llm/llm-deepseek/README.zh.md
@@ -11,7 +11,7 @@ kind: "package-reference"
提供共享的 DeepSeek Messages 传输、请求配置和模型能力。组合 [API key](../llm-deepseek-api-key/README.zh.md) 或[账号](../llm-deepseek-account/README.zh.md)插件以提供鉴权、模型发现与 provider 注册。有效的设置更改在后续请求生效,进行中的请求保留原配置。本包可与 [pi-ai 适配器](../llm-pi-ai/README.zh.md)并用。
-`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:请求头、裸凭据值以及可选的失败回调;未配置时返回 `undefined`。Messages 和 Files 直接使用这些请求头,不判断凭据类型。上传复用按端点和鉴权请求头的哈希隔离,不持久化原始凭据。
+`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:请求头、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。Messages 和 Files 直接使用这些请求头,不判断凭据类型。上传复用按端点和鉴权请求头的哈希隔离,不持久化原始凭据。
## 目录
@@ -94,7 +94,7 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 `
Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。
-提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.providerCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。
+提供方插件通过两个适配器钩子提供凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。插件的 API Key 和账号登录凭据都取自 [`ctx.deepseekAuth`](../../account/deepseek-auth/README.zh.md);本传输层不读取任何凭据。
### 带 thinking 与图片的流式调用
diff --git a/packages/llm/llm-deepseek/package.json b/packages/llm/llm-deepseek/package.json
index 6d8f9c545e..86bd938196 100644
--- a/packages/llm/llm-deepseek/package.json
+++ b/packages/llm/llm-deepseek/package.json
@@ -82,7 +82,8 @@
"@deepseek-ai/dsh-credentials-local": "workspace:*",
"@deepseek-ai/dsh-settings": "workspace:*",
"@deepseek-ai/dsh-deepseek-account": "workspace:*",
- "@types/semver": "^7.8.0"
+ "@types/semver": "^7.8.0",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"peerDependenciesMeta": {
"@deepseek-ai/cordis-plugin-loader": {
diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts
index 5f625e687d..0803bde860 100644
--- a/packages/llm/llm-deepseek/src/adapter.ts
+++ b/packages/llm/llm-deepseek/src/adapter.ts
@@ -1,7 +1,7 @@
/** Direct Messages transport with one cancellable lifecycle per model request. */
import { attributionHeaders, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm'
-import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, ProviderCredential, StreamChunk } from '@deepseek-ai/dsh-llm'
+import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, StreamChunk } from '@deepseek-ai/dsh-llm'
import type { DeepSeekLlmApiExtensionRequest, DeepSeekLlmApiJson } from '@deepseek-ai/dsh-deepseek-llm-api-extensions'
import { idleWatchdog, timeoutOf } from '@deepseek-ai/dsh-timeout'
import { modelInfo } from './model-info.ts'
@@ -47,31 +47,6 @@ export class DeepSeekAdapter extends LlmAdapt
if (entry === undefined) throw new LlmError(`DeepSeek model "${model}" has no declared image projection`, 'UNKNOWN_MODEL')
return resolveRequestImageTarget(entry, image)
}
- override providerCredential(_provider: string): ProviderCredential | undefined {
- const publication = this.dependencies.credential
- if (publication === undefined) return undefined
- // One configuration generation serves the whole published object, as it does one model request.
- const connection = this.dependencies.options()
- const reference = publication.reference?.(connection)
- return {
- kind: publication.kind,
- baseURL: connection.baseURL,
- ...reference === undefined ? {} : { reference },
- configured: endpoint => publication.configured(connection, endpoint),
- resolve: async (endpoint, signal) => {
- signal?.throwIfAborted()
- const auth = await this.dependencies.resolveAuth(connection, endpoint)
- if (auth === undefined) return undefined
- // The adapter's failure classification stays behind the seam.
- const reject = auth.reject?.bind(auth)
- return {
- headers: auth.headers, value: auth.value,
- ...reject === undefined ? {} : { reject },
- ...auth.revoked === undefined ? {} : { revoked: auth.revoked },
- }
- },
- }
- }
override async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise {
const connection = await this.connection(signal)
this.dependencies.admit?.(connection, model)
diff --git a/packages/llm/llm-deepseek/src/host.ts b/packages/llm/llm-deepseek/src/host.ts
index 202d9c2bef..0b87c549f0 100644
--- a/packages/llm/llm-deepseek/src/host.ts
+++ b/packages/llm/llm-deepseek/src/host.ts
@@ -45,7 +45,7 @@ export function createModelListingCache(
*/
export function registerDeepSeekProvider(
ctx: Context, provider: string, dependencies: Pick,
- 'options' | 'resolveAuth' | 'missingCredential' | 'credential' | 'providerName' | 'discoverModels' | 'connect' | 'admit'>): void {
+ 'options' | 'resolveAuth' | 'missingCredential' | 'providerName' | 'discoverModels' | 'connect' | 'admit'>): void {
ctx.inject(['settings'], (child) => { child.effect(() => child.settings.configure({ auto: false }, ctx.fiber)) })
let userId: AnonymousUserId | undefined
// These conditions repeat on every request of a route; log each first occurrence only.
diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts
index 8bd83450b4..1c7ab36255 100644
--- a/packages/llm/llm-deepseek/src/index.ts
+++ b/packages/llm/llm-deepseek/src/index.ts
@@ -15,7 +15,7 @@ export {
DEFAULT_STREAM_IDLE_TIMEOUT_MS,
} from './defaults.ts'
export { DeepSeekAdapter } from './adapter.ts'
-export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions, DeepSeekProviderCredentialOptions } from './types.ts'
+export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions } from './types.ts'
export {
DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET,
DEFAULT_MAX_IMAGES_PER_REQUEST,
diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts
index 0e483b92a4..0efced1afe 100644
--- a/packages/llm/llm-deepseek/src/types.ts
+++ b/packages/llm/llm-deepseek/src/types.ts
@@ -1,6 +1,6 @@
/** Model catalog and request-local dependencies for DeepSeek Messages. */
import type {
- ImageAttachmentAccess, LlmCredentialKind, LlmError, LlmModelInfo, ModelModality, ProviderCredentialGrant, ResolvedRetryPolicy,
+ ImageAttachmentAccess, LlmError, LlmModelInfo, ModelModality, ResolvedRetryPolicy,
SystemPromptUpdate, ToolUpdate,
} from '@deepseek-ai/dsh-llm'
import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
@@ -85,12 +85,18 @@ export interface DeepSeekConnectionOptions {
}
/**
- * Authentication released for one request and its file operations: the route
- * credential grant the provider plugin builds, plus the request-failure
- * classification bound to that credential. The grant's `revoked` signal ends
- * the request and its file operations as the caller's cancellation does.
+ * Authentication the provider plugin releases for one request and its file operations, with the request-failure
+ * classification bound to that credential.
*/
-export interface DeepSeekRequestAuth extends ProviderCredentialGrant {
+export interface DeepSeekRequestAuth {
+ /** Request headers carrying the credential. */
+ readonly headers: Readonly>
+ /**
+ * Aborts when the owner withdraws the credential while the request may carry it, as an account sign-out does. It
+ * ends the request and its file operations as the caller's cancellation does. Absent for credentials that are
+ * never withdrawn.
+ */
+ readonly revoked?: AbortSignal
/**
* Classify a failure using the captured credential; callback failure preserves the original error. The end a
* withdrawn credential causes arrives here too, for the provider plugin to name.
@@ -98,20 +104,6 @@ export interface DeepSeekRequestAuth extends ProviderCredentialGrant {
onRequestError?: (error: unknown) => Promise
}
-/**
- * What `providerCredential()` publishes about the route's credential beside the
- * request-path hooks, so consumers outside the model request path share the
- * route's credential without reading its configuration.
- */
-export interface DeepSeekProviderCredentialOptions {
- /** Kind of credential the route sends. */
- kind: LlmCredentialKind
- /** Credential reference the route resolves, named by diagnostics; omission publishes none. */
- reference?: (connection: Connection) => string | undefined
- /** Report whether a credential exists for `endpoint` without reading its value. */
- configured: (connection: Connection, endpoint: string) => Promise
-}
-
/** Constructor options for {@link DeepSeekAdapter}: the operation-local resolution hooks the plugin owns. */
export interface DeepSeekAdapterOptions {
/** Report unusable native Messages replay metadata without exposing content or signatures. */
@@ -137,8 +129,7 @@ export interface DeepSeekAdapterOptions Promise
/**
@@ -146,11 +137,6 @@ export interface DeepSeekAdapterOptions LlmError
- /**
- * Publish the route's credential through `providerCredential()`, whose `resolve` forwards the headers, value,
- * rejection, and withdrawal signal of {@link resolveAuth} without its failure classification; omission publishes none.
- */
- credential?: DeepSeekProviderCredentialOptions
/** Resolve the harness-home anonymous id shared with telemetry and feedback. */
resolveUserId: () => AnonymousUserId
/** Resolve the current durable attachment service; absence rejects image input. */
diff --git a/packages/llm/llm-deepseek/tests/account-routing.spec.ts b/packages/llm/llm-deepseek/tests/account-routing.spec.ts
index 7f58c4104e..e99290ef96 100644
--- a/packages/llm/llm-deepseek/tests/account-routing.spec.ts
+++ b/packages/llm/llm-deepseek/tests/account-routing.spec.ts
@@ -14,6 +14,7 @@ import ToolRuntime from '@deepseek-ai/dsh-tools'
import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit'
import * as DeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
import * as AccountProvider from '@deepseek-ai/dsh-llm-deepseek-account'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { assemble } from './assemble.ts'
const contexts: Context[] = []
@@ -39,6 +40,7 @@ async function harness() {
await ctx.plugin(plugin)
}
await ctx.plugin(AgentLoop, { agents: [] })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(DeepSeek, {})
await ctx.plugin(AccountProvider, {})
return ctx
@@ -58,6 +60,7 @@ it('never falls back to an API key while signed out', async () => {
const ctx = new Context()
contexts.push(ctx)
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(DeepSeek, {})
await ctx.plugin(AccountProvider, {})
const fetch = vi.spyOn(globalThis, 'fetch')
@@ -187,6 +190,7 @@ it('never borrows an account token for a missing API key', async () => {
const resolveToken = vi.fn(async (_url: string) => 'fixture-account-token')
ctx.provide('deepseekAccount', accountStub({ token: url => resolveToken(url) }))
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(DeepSeek, {})
await ctx.plugin(AccountProvider, {})
const fetch = vi.spyOn(globalThis, 'fetch')
diff --git a/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts b/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts
index 469cd3be6d..441cee0a4c 100644
--- a/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts
+++ b/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts
@@ -22,6 +22,7 @@ import LocalCredentials from '@deepseek-ai/dsh-credentials-local'
import DeepSeekAccount, { type AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account'
import LlmRuntime, { type StreamChunk } from '@deepseek-ai/dsh-llm'
import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
@@ -115,6 +116,7 @@ async function boot(origin: string) {
['@deepseek-ai/dsh-deepseek-account', { module: DeepSeekAccount, config: {
platformOrigin: origin, inferenceOrigin: origin, allowLoopbackHttp: true, logoutRetryDelayMs: 1,
} }],
+ ['@deepseek-ai/dsh-deepseek-auth', { module: DeepSeekAuth }],
['@deepseek-ai/dsh-llm-deepseek-account', { module: AccountRoute, config: { baseURL: `${origin}/anthropic` } }],
])
await writeFile(join(home, 'cordis.yml'), JSON.stringify(
diff --git a/packages/llm/llm-deepseek/tests/adapter.e2e.ts b/packages/llm/llm-deepseek/tests/adapter.e2e.ts
index a59fadfa3e..96573561d7 100644
--- a/packages/llm/llm-deepseek/tests/adapter.e2e.ts
+++ b/packages/llm/llm-deepseek/tests/adapter.e2e.ts
@@ -23,6 +23,7 @@ import * as PluginPackageInventoryDeepSeek from '@deepseek-ai/dsh-plugin-package
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
import * as SessionLogDeepSeek from '@deepseek-ai/dsh-session-log-deepseek'
import * as Messages from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { DeepSeekFilesClient } from '../src/files-api.ts'
import { MESSAGES_FILES_BETA } from '../src/messages-api.ts'
import { assemble, options, user, sourceModuleLoader } from './helpers.ts'
@@ -41,6 +42,7 @@ async function boot(models?: Messages.Options['models'], baseURL = Protocol.PUBL
const ctx = new Context()
cleanups.push(() => ctx.fiber.dispose())
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Messages, {
baseURL,
maxTokens: 4096,
diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts
index 7665bed167..2cace62e65 100644
--- a/packages/llm/llm-deepseek/tests/adapter.spec.ts
+++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts
@@ -31,6 +31,7 @@ import { DeepSeekFileStore } from '../src/file-store.ts'
import { resolveAdapterOptions } from '../src/config.ts'
import * as Messages from '@deepseek-ai/dsh-llm-deepseek-api-key'
import * as AccountProvider from '@deepseek-ai/dsh-llm-deepseek-account'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { adapter, assemble, chunks, MODEL, options, prepareExtensions, server, sse, textEvents, user, sourceModuleLoader } from './helpers.ts'
const cleanup: (() => Promise)[] = []
@@ -199,7 +200,7 @@ describe('direct Messages HTTP', () => {
const files = new DeepSeekFileStore()
const llm = new DeepSeekAdapter({
options: () => resolveAdapterOptions({ baseURL: source.url }),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId,
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }), resolveUserId: () => 'test-user' as AnonymousUserId,
resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files,
prepareExtensions: prepare,
})
@@ -216,7 +217,7 @@ describe('direct Messages HTTP', () => {
const first = await endpoint(), second = await endpoint()
let config = resolveAdapterOptions({ baseURL: first.url, maxTokens: 10, models: [{ id: MODEL, systemPromptUpdate: 'in-history' }] })
const files = new DeepSeekFileStore()
- const llm = new DeepSeekAdapter({ options: () => config, resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': snapshot.maxTokens === 10 ? 'first' : 'second' }, value: snapshot.maxTokens === 10 ? 'first' : 'second' }), resolveUserId: () => 'user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions })
+ const llm = new DeepSeekAdapter({ options: () => config, resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': snapshot.maxTokens === 10 ? 'first' : 'second' } }), resolveUserId: () => 'user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions })
const prepared = await llm.prepareCall('deepseek-official', MODEL)
config = resolveAdapterOptions({ baseURL: second.url, maxTokens: 20 })
expect(prepared.model.systemPromptUpdate).toBe('in-history')
@@ -249,7 +250,7 @@ describe('direct Messages HTTP', () => {
const withdrawn = new AbortController()
const onRequestError = vi.fn(async (error: unknown) => new LlmError('credential withdrawn', 'ACCOUNT_SIGN_IN_REQUIRED', { cause: error }))
const stream = adapter({ baseURL: http.url }, {
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', revoked: withdrawn.signal, onRequestError }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, revoked: withdrawn.signal, onRequestError }),
}).stream(options())[Symbol.asyncIterator]()
expect((await stream.next()).value).toMatchObject({ type: 'block-start' })
expect((await stream.next()).value).toMatchObject({ type: 'text-delta' })
@@ -263,7 +264,7 @@ describe('direct Messages HTTP', () => {
it('reports a withdrawal the provider does not name as a transport failure, without contacting the provider', async () => {
const http = await endpoint()
const llm = adapter({ baseURL: http.url }, {
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', revoked: AbortSignal.abort() }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, revoked: AbortSignal.abort() }),
})
await expect(chunks(llm.stream(options()))).rejects.toMatchObject({ code: 'TRANSPORT' })
expect(http.requests).toEqual([])
@@ -306,7 +307,7 @@ describe('direct Messages HTTP', () => {
vi.stubGlobal('fetch', async () => new Response('Unauthorized', { status: 401 }))
const llm = new DeepSeekAdapter({
options: () => resolveAdapterOptions({}),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key',
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' },
onRequestError: async () => { throw new Error('credential storage unavailable') },
}),
resolveUserId: () => 'fixture-user' as import('@deepseek-ai/dsh-anonymous-user-id').AnonymousUserId,
@@ -349,6 +350,7 @@ describe('Cordis provider composition', () => {
const { ctx, home } = await context()
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(Messages, { baseURL: http.url })
const model = 'deepseek-flash'
const price = () => ctx.llm.imageRequestPricing('deepseek-official', model)!
@@ -380,7 +382,7 @@ describe('Cordis provider composition', () => {
ctx.loader.builtins.include = Include
const modules = new Map([
['@deepseek-ai/dsh-llm', LlmRuntime], ['@deepseek-ai/dsh-llm-deepseek-api-key', Messages], ['@deepseek-ai/dsh-llm-deepseek-account', AccountProvider],
- ['@deepseek-ai/dsh-credentials-local', LocalCredentials],
+ ['@deepseek-ai/dsh-credentials-local', LocalCredentials], ['@deepseek-ai/dsh-deepseek-auth', DeepSeekAuth],
['@deepseek-ai/dsh-agent', AgentRegistry], ['@deepseek-ai/dsh-agent-loop', AgentLoop],
['@deepseek-ai/dsh-session', SessionStore], ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry],
['@deepseek-ai/dsh-system-prompt', SystemPrompt], ['@deepseek-ai/dsh-tools', ToolRuntime],
@@ -646,6 +648,7 @@ describe('Cordis provider composition', () => {
vi.stubEnv('DEEPSEEK_BASE_URL', http.url)
vi.stubEnv('DEEPSEEK_API_KEY', 'env-key')
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
const fiber = ctx.plugin(Messages)
await fiber
await chunks(ctx.llm.stream(options()))
@@ -673,6 +676,7 @@ it.each([
// The stand-in releases the credential by exact destination; the real service owns origin validation in its own suite.
ctx.provide('deepseekAccount', accountStub({ token: url => url === 'https://api.deepseek.com' ? 'account-token' : undefined }))
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(expected === 'account-token' ? AccountProvider : Messages, { baseURL })
const request = vi.fn((_input, init) => {
const headers = new Headers(init?.headers)
diff --git a/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts b/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts
index c6bb3eacfa..9614bd15fe 100644
--- a/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts
+++ b/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts
@@ -19,6 +19,7 @@ import { credentialRef } from '@deepseek-ai/dsh-credentials'
import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local'
import { liveConfig } from '../../../settings/settings/tests/live-config.ts'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
import { assemble } from './assemble.ts'
import { closeMockServers, mockServer, textEvents } from './mock-server.ts'
@@ -130,6 +131,7 @@ async function boot(dir: string, config: object): Promise {
await ctx.plugin(LlmRuntime)
await ctx.plugin(StaticAttachmentStore)
await ctx.plugin(LocalCredentialProvider, { path: join(dir, '.credentials.yaml'), watch: false })
+ await ctx.plugin(DeepSeekAuth)
configurations.set(ctx, await liveConfig(ctx, LlmDeepSeek, config))
return { ctx }
}
diff --git a/packages/llm/llm-deepseek/tests/egress.spec.ts b/packages/llm/llm-deepseek/tests/egress.spec.ts
index 03b04f8550..2ad503a181 100644
--- a/packages/llm/llm-deepseek/tests/egress.spec.ts
+++ b/packages/llm/llm-deepseek/tests/egress.spec.ts
@@ -39,6 +39,7 @@ import { Context } from '@deepseek-ai/cordis'
import LlmRuntime from '@deepseek-ai/dsh-llm'
import DeepSeekLlmApiExtensionRegistry from '@deepseek-ai/dsh-deepseek-llm-api-extensions'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
let home: string
beforeAll(() => {
@@ -56,6 +57,7 @@ async function streamOnce(): Promise {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
await ctx.plugin(DeepSeekLlmApiExtensionRegistry)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: 'http://deepseek-probe.invalid/v1', models: [{ id: 'm' }] })
for await (const _chunk of ctx.llm.stream({ provider: 'deepseek-official', model: 'm', messages: [] })) {
// The endpoint never answers; the proxy record is the assertion.
diff --git a/packages/llm/llm-deepseek/tests/extensions.spec.ts b/packages/llm/llm-deepseek/tests/extensions.spec.ts
index c9acacbb31..0c145f5e83 100644
--- a/packages/llm/llm-deepseek/tests/extensions.spec.ts
+++ b/packages/llm/llm-deepseek/tests/extensions.spec.ts
@@ -9,6 +9,7 @@ import DeepSeekLlmApiExtensionRegistry from '@deepseek-ai/dsh-deepseek-llm-api-e
import type { DeepSeekLlmApiExtensionRequest } from '@deepseek-ai/dsh-deepseek-llm-api-extensions'
import type { SessionId } from '@deepseek-ai/dsh-session'
import * as DeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { adapter, assemble, options, sse, textEvents } from './helpers.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
@@ -35,6 +36,7 @@ async function boot() {
cleanup.push(() => ctx.fiber.dispose())
await ctx.plugin(LlmRuntime)
await ctx.plugin(DeepSeekLlmApiExtensionRegistry)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(DeepSeek, { baseURL: 'https://messages.example.test/root' })
return ctx
}
diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts
index 2b0959b1b3..48f1caa3f3 100644
--- a/packages/llm/llm-deepseek/tests/files.spec.ts
+++ b/packages/llm/llm-deepseek/tests/files.spec.ts
@@ -40,7 +40,7 @@ function harness(config: Config = {}, revoked?: AbortSignal) {
const prepare = vi.fn(prepareExtensions)
const adapter = new DeepSeekAdapter({
options: () => resolveAdapterOptions(Object.assign({ baseURL: 'https://gateway.example/custom' }, config)),
- resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', ...revoked === undefined ? {} : { revoked } }),
+ resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' }, ...revoked === undefined ? {} : { revoked } }),
resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments,
resolveImageAccess: () => ({ readonlyPath: '/workspace/image.png' }), resolveFiles: () => files, prepareExtensions: prepare,
})
diff --git a/packages/llm/llm-deepseek/tests/fixtures/cordis.yml b/packages/llm/llm-deepseek/tests/fixtures/cordis.yml
index 2136dd7ae0..85f25c195e 100644
--- a/packages/llm/llm-deepseek/tests/fixtures/cordis.yml
+++ b/packages/llm/llm-deepseek/tests/fixtures/cordis.yml
@@ -12,6 +12,7 @@
config:
path: {{credentials}}
watch: false
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-llm-deepseek-api-key'
config:
apiKeyEnv: DEEPSEEK_API_KEY
diff --git a/packages/llm/llm-deepseek/tests/helpers.ts b/packages/llm/llm-deepseek/tests/helpers.ts
index 08af4080c5..77beea8f04 100644
--- a/packages/llm/llm-deepseek/tests/helpers.ts
+++ b/packages/llm/llm-deepseek/tests/helpers.ts
@@ -45,7 +45,7 @@ export async function assemble(stream: AsyncIterable, model = MODEL
}
export function adapter(config: Config = {}, dependencies: Partial = {}) {
const files = new DeepSeekFileStore()
- return new DeepSeekAdapter({ options: () => resolveAdapterOptions(config), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions, ...dependencies })
+ return new DeepSeekAdapter({ options: () => resolveAdapterOptions(config), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions, ...dependencies })
}
/**
* Loopback Messages endpoint recording each model request.
diff --git a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts
index 80de499748..1109b0289c 100644
--- a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts
+++ b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts
@@ -20,6 +20,7 @@ import DeepSeekLlmApiExtensionRegistry from '@deepseek-ai/dsh-deepseek-llm-api-e
import * as SessionLogDeepSeek from '@deepseek-ai/dsh-session-log-deepseek'
import * as DeepSeekPluginPackageInventory from '@deepseek-ai/dsh-plugin-package-inventory-deepseek'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { assemble } from './assemble.ts'
import { closeMockServers, mockServer, textEvents } from './mock-server.ts'
import { sourceModuleLoader } from './helpers.ts'
@@ -100,6 +101,7 @@ async function loadComposition(
' debounceMs: 10',
]
: [],
+ "- name: '@deepseek-ai/dsh-deepseek-auth'",
'- id: llm-deepseek',
" name: '@deepseek-ai/dsh-llm-deepseek-api-key'",
' config:',
@@ -123,6 +125,7 @@ async function loadComposition(
['@deepseek-ai/dsh-session-log-deepseek', SessionLogDeepSeek],
['@deepseek-ai/dsh-plugin-package-inventory-deepseek', DeepSeekPluginPackageInventory],
['@deepseek-ai/dsh-credentials-local', LocalCredentialProvider],
+ ['@deepseek-ai/dsh-deepseek-auth', DeepSeekAuth],
['@deepseek-ai/dsh-llm-deepseek-api-key', LlmDeepSeek],
])
// The custom importer bypasses Node resolution; mirror the package manifests
diff --git a/packages/llm/llm-deepseek/tests/official-route-turn.spec.ts b/packages/llm/llm-deepseek/tests/official-route-turn.spec.ts
index 964e956288..5321fdd602 100644
--- a/packages/llm/llm-deepseek/tests/official-route-turn.spec.ts
+++ b/packages/llm/llm-deepseek/tests/official-route-turn.spec.ts
@@ -10,6 +10,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRuntime from '@deepseek-ai/dsh-tools'
import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
import * as DeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { brandString } from '@deepseek-ai/dsh-brand'
const contexts: Context[] = []
@@ -29,6 +30,7 @@ it('records the prompt and fails the request when the official endpoint has a ma
}
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(AgentLoop, { agents: [] })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(DeepSeek, {})
const agent = await ctx.agentLoop.create(brandString('malformed-official-key'), { provider: 'deepseek-official', model: 'deepseek-flash' })
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }))
diff --git a/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts b/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts
index 778cd5564b..808fc85b1b 100644
--- a/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts
+++ b/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts
@@ -23,7 +23,7 @@ async function route(hooks: Pick) {
inject: ['llm'],
apply: (child: Context) => {
registerDeepSeekProvider(child, 'fixture-route', {
- options: () => endpoint(), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key' }), ...hooks,
+ options: () => endpoint(), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' } }), ...hooks,
})
},
})
@@ -59,7 +59,7 @@ it('refuses a model before a prepared call exists', async () => {
it('refuses a model on a direct adapter stream', () => {
const adapter = new DeepSeekAdapter({
options: () => endpoint(),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' } }),
resolveUserId: () => 'fixture-user' as AnonymousUserId,
prepareExtensions,
admit: () => { throw new LlmError('blocked by fixture', 'MODEL_UNSUPPORTED') },
diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts
index 9c74f6ef14..8766cf50f9 100644
--- a/packages/llm/llm-deepseek/tests/route-credential.spec.ts
+++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts
@@ -1,39 +1,14 @@
-/** The adapter publishes a route credential only for providers that declare one, and refuses requests without a credential. */
+/** The adapter refuses a request whose provider releases no credential, with the provider's diagnostic when it names one. */
import { afterEach, expect, it, vi } from 'vitest'
-import { Context } from '@deepseek-ai/cordis'
-import LlmRuntime, { LlmError } from '@deepseek-ai/dsh-llm'
+import { LlmError } from '@deepseek-ai/dsh-llm'
import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id'
-import { DeepSeekAdapter, registerDeepSeekProvider, resolveAdapterOptions } from '../src/index.ts'
-import type { DeepSeekAdapterOptions, DeepSeekRequestAuth, ResolvedDeepSeekOptions } from '../src/index.ts'
+import { DeepSeekAdapter, resolveAdapterOptions } from '../src/index.ts'
+import type { DeepSeekAdapterOptions } from '../src/index.ts'
import { chunks, options as request, prepareExtensions } from './helpers.ts'
-const contexts: Context[] = []
-afterEach(async () => {
- for (const ctx of contexts.splice(0)) await ctx.fiber.dispose()
- vi.unstubAllGlobals()
-})
+afterEach(() => { vi.unstubAllGlobals() })
-const BASE_URL = 'https://route.deepseek.test/anthropic'
-const ALLOWED = 'https://route.deepseek.test/v1/tools/search'
-const OTHER = 'https://route.deepseek.test/v1/tools/fetch'
-const connection = () => resolveAdapterOptions({ baseURL: BASE_URL })
-
-type Hooks = Partial>
-
-/** Mount the runtime and one fixture route whose credential hooks are `hooks`. */
-async function route(hooks: Hooks): Promise {
- const ctx = new Context()
- contexts.push(ctx)
- await ctx.plugin(LlmRuntime)
- await ctx.plugin({
- name: 'fixture-route',
- inject: ['llm'],
- apply: (child: Context) => {
- registerDeepSeekProvider(child, 'fixture-route', { options: connection, resolveAuth: () => Promise.resolve(undefined), ...hooks })
- },
- })
- return ctx
-}
+const connection = () => resolveAdapterOptions({ baseURL: 'https://route.deepseek.test/anthropic' })
/** A direct adapter without a credential, failing requests through `missingCredential` when given. */
function adapterWithout(missingCredential?: DeepSeekAdapterOptions['missingCredential']): DeepSeekAdapter {
@@ -46,46 +21,6 @@ function adapterWithout(missingCredential?: DeepSeekAdapterOptions['missingCrede
})
}
-it('publishes no credential for a provider that declares none', async () => {
- const ctx = await route({})
- expect(ctx.llm.providerCredential('fixture-route')).toBeUndefined()
-})
-
-it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => {
- const reject = vi.fn(() => Promise.resolve())
- const revoked = new AbortController().signal
- const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise =>
- endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, revoked, onRequestError: error => Promise.resolve(error) } : undefined)
- const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED)
- const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } })
- const credential = ctx.llm.providerCredential('fixture-route')
- expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' })
- await expect(credential!.configured(ALLOWED)).resolves.toBe(true)
- await expect(credential!.configured(OTHER)).resolves.toBe(false)
- // The grant carries the seam's fields only; the adapter's failure classification stays behind it.
- const grant = await credential!.resolve(ALLOWED)
- expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject', 'revoked'])
- expect(grant).toMatchObject({ headers: { 'x-fixture': 'k' }, value: 'k' })
- expect(grant!.revoked).toBe(revoked)
- await grant!.reject!()
- expect(reject).toHaveBeenCalledTimes(1)
- await expect(credential!.resolve(OTHER)).resolves.toBeUndefined()
- await expect(credential!.resolve(ALLOWED, AbortSignal.abort(new Error('caller left')))).rejects.toThrow('caller left')
- expect(resolveAuth).toHaveBeenCalledTimes(2)
- expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL])
-})
-
-it('omits the reference of a credential kind without one and the rejection and withdrawal of a grant without them', async () => {
- const ctx = await route({
- resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }),
- credential: { kind: 'account', configured: () => Promise.resolve(false) },
- })
- const credential = ctx.llm.providerCredential('fixture-route')
- expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL })
- expect(credential).not.toHaveProperty('reference')
- await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' })
-})
-
it('fails a request without a credential before any network I/O, with the default diagnostic', async () => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
diff --git a/packages/llm/llm-deepseek/tests/runtime.e2e.ts b/packages/llm/llm-deepseek/tests/runtime.e2e.ts
index b86d9b1eff..588f8989c2 100644
--- a/packages/llm/llm-deepseek/tests/runtime.e2e.ts
+++ b/packages/llm/llm-deepseek/tests/runtime.e2e.ts
@@ -30,6 +30,7 @@ import * as PluginPackageInventoryDeepSeek from '@deepseek-ai/dsh-plugin-package
import * as SessionLogDeepSeek from '@deepseek-ai/dsh-session-log-deepseek'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
import type { Options as Config } from '@deepseek-ai/dsh-llm-deepseek'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import type { WireRequest } from '../src/wire-types.ts'
import { assemble, type AssembledResult } from './assemble.ts'
@@ -113,6 +114,7 @@ async function harness(model: string, config: Partial = {}) {
contexts.push(ctx)
await ctx.plugin(LlmRuntime)
await ctx.plugin(E2eAttachmentStore)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
baseURL: Protocol.PUBLIC_BASE_URL,
...model === VISION ? { models: [{ id: VISION, inputModalities: ['text', 'image'] }] } : {},
@@ -158,6 +160,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('llm-deepseek e2e (real API)', ()
contexts.push(ctx)
await ctx.plugin(LlmRuntime)
await ctx.plugin(LocalAttachments)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: Protocol.PUBLIC_BASE_URL, maxTokens: 4096 })
const model = 'deepseek-flash'
await expect(ctx.llm.resolveModelInfo('deepseek-official', model)).resolves.toMatchObject({
@@ -238,6 +241,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('llm-deepseek e2e (real API)', ()
await ctx.plugin(DeepSeekLlmApiExtensionRegistry)
await ctx.plugin(SessionLogDeepSeek, { enabled: true })
await ctx.plugin(PluginPackageInventoryDeepSeek)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: Protocol.PUBLIC_BASE_URL, thinking: 'disabled' })
const session = ctx.sessions.create(brandString('real-extension-fields'))
session.append('turn/start', { turn: 1 })
@@ -268,6 +272,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('llm-deepseek e2e (real API)', ()
contexts.push(ctx)
await ctx.plugin(LlmRuntime)
await ctx.plugin(LocalCredentialProvider, { path: join(dir, '.credentials.yaml'), watch: false })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: Protocol.PUBLIC_BASE_URL })
const result = await assemble(ctx, {
diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts
index 03664fd783..61890886bf 100644
--- a/packages/llm/llm-deepseek/tests/runtime.spec.ts
+++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts
@@ -25,6 +25,7 @@ import DeepSeekLlmApiExtensionRegistry from '@deepseek-ai/dsh-deepseek-llm-api-e
import type { PreparedDeepSeekLlmApiExtensions } from '@deepseek-ai/dsh-deepseek-llm-api-extensions'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
import { DeepSeekAdapter, resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepseek'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
import { providerError } from '../src/transport.ts'
import { resolveRequestImageTarget } from '../src/request-pricing.ts'
@@ -61,6 +62,7 @@ async function harness(baseURL: string, config: object = {}) {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
await ctx.plugin(DeepSeekLlmApiExtensionRegistry)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL, ...config })
return ctx
}
@@ -79,7 +81,7 @@ function adapterOf(
const { apiKey, ...rest } = config
return new DeepSeekAdapter({
options: () => resolveAdapterOptions({ ...rest }),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': apiKey ?? 'k' }, value: apiKey ?? 'k' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': apiKey ?? 'k' } }),
resolveUserId: () => TEST_USER_ID,
resolveAttachments: () => attachments,
...files === undefined ? {} : { resolveFiles: () => files },
@@ -209,7 +211,7 @@ describe('request image target', () => {
const attachments = {} as AttachmentStore
const adapter = new DeepSeekAdapter({
options: () => resolveAdapterOptions({ models: [{ id: 'vision', inputModalities: ['text', 'image'] }] }),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }),
resolveUserId: () => TEST_USER_ID,
resolveAttachments: () => attachments,
resolveImageAccess: (store, ref) => (store === attachments && ref === imageRef
@@ -232,7 +234,7 @@ describe('DeepSeekAdapter against a mock server', () => {
}))
const adapter = new DeepSeekAdapter({
options: () => resolveAdapterOptions({ baseURL: server.url }),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }),
resolveUserId: () => TEST_USER_ID,
prepareExtensions: prepareExtensions as never,
})
@@ -247,7 +249,7 @@ describe('DeepSeekAdapter against a mock server', () => {
const server = await mockServer([])
const base = {
options: () => resolveAdapterOptions({ baseURL: server.url }),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }),
resolveUserId: () => TEST_USER_ID,
}
const failed = new DeepSeekAdapter({
@@ -276,7 +278,7 @@ describe('DeepSeekAdapter against a mock server', () => {
let signalSeen: AbortSignal | undefined
const adapter = new DeepSeekAdapter({
options: () => resolveAdapterOptions({ baseURL: server.url }),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }),
resolveUserId: () => TEST_USER_ID,
prepareExtensions: ((request: { signal: AbortSignal }) => {
signalSeen = request.signal
@@ -341,7 +343,7 @@ describe('DeepSeekAdapter against a mock server', () => {
const accept = vi.fn()
const adapter = new DeepSeekAdapter({
options: () => resolveAdapterOptions({ baseURL: server.url }),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }),
resolveUserId: () => TEST_USER_ID,
prepareExtensions: () => Promise.resolve({ fields: { dsh_test: 1 }, accept: async () => { accept() } }) as never,
})
@@ -359,7 +361,7 @@ describe('DeepSeekAdapter against a mock server', () => {
const unaccepted = vi.fn()
const base = {
options: () => resolveAdapterOptions({ baseURL: server.url }),
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }),
resolveUserId: () => TEST_USER_ID,
prepareExtensions: () => Promise.resolve({
fields: { dsh_test: 1 },
@@ -1166,7 +1168,7 @@ describe('DeepSeekAdapter against a mock server', () => {
'rejects image input for text-only model %s before credentials, image reads, or fetch',
async (model) => {
const server = await mockServer([])
- const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }))
+ const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' } }))
const attachments = attachmentStoreOf(ref => Promise.resolve(requestImage(ref)))
const resolveAttachments = vi.fn(() => attachments.store)
const adapter = new DeepSeekAdapter({
@@ -1193,7 +1195,7 @@ describe('DeepSeekAdapter against a mock server', () => {
it('rejects vision input without an attachment provider before credentials or fetch', async () => {
const server = await mockServer([])
- const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }))
+ const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' } }))
const adapter = new DeepSeekAdapter({
options: () => resolveAdapterOptions({
baseURL: server.url,
@@ -1777,6 +1779,7 @@ describe('plugin registration and config', () => {
const server = await mockServer([])
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
const fiber = await ctx.plugin(LlmDeepSeek, {
baseURL: server.url,
})
@@ -1795,6 +1798,7 @@ describe('plugin registration and config', () => {
it('registers retryPolicy from the provider config', async () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
retryPolicy: {
@@ -1815,6 +1819,7 @@ describe('plugin registration and config', () => {
vi.stubEnv('DEEPSEEK_API_KEY', 'catalog-fixture-key')
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: 'http://127.0.0.1:1' })
expect(ctx.llm.listProviders()).toEqual([{ id: 'deepseek-official', name: 'DeepSeek' }])
await expect(ctx.llm.listModels('deepseek-official')).resolves.toEqual([
@@ -1851,6 +1856,7 @@ describe('plugin registration and config', () => {
it('keeps deepseek-v4-pro available with its V4 capabilities', async () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: 'http://127.0.0.1:1' })
const info = await ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-v4-pro')
expect(info).toMatchObject({
@@ -1865,6 +1871,7 @@ describe('plugin registration and config', () => {
it.each(['off', 'low', 'max'] as const)('uses the configured %s reasoning default', async (effort) => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
reasoningEffort: effort,
@@ -1886,6 +1893,7 @@ describe('plugin registration and config', () => {
it('accepts off as the default when thinking is deployment-disabled', async () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
thinking: 'disabled',
@@ -1909,6 +1917,7 @@ describe('plugin registration and config', () => {
async (reasoningEffort) => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
thinking: 'disabled',
@@ -1944,6 +1953,7 @@ describe('plugin registration and config', () => {
vi.stubEnv('DEEPSEEK_API_KEY', 'catalog-fixture-key')
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
LlmDeepSeek.apply(ctx, LlmDeepSeek.Config({ baseURL: 'http://127.0.0.1:1' }))
await expect(ctx.llm.listModels('deepseek-official')).resolves.toEqual([
{ provider: 'deepseek-official', id: 'deepseek-flash', name: 'DeepSeek-V4.1-Flash', inputModalities: ['text', 'image'] },
@@ -1962,6 +1972,7 @@ describe('plugin registration and config', () => {
vi.stubEnv('DEEPSEEK_API_KEY', 'catalog-fixture-key')
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
models: [
@@ -1997,6 +2008,7 @@ describe('plugin registration and config', () => {
it('uses exact model capacity before the adapter-wide default', async () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
defaultContextWindow: 256_000,
@@ -2017,6 +2029,7 @@ describe('plugin registration and config', () => {
it('allows an explicit empty model catalog', async () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
models: [],
@@ -2041,6 +2054,7 @@ describe('plugin registration and config', () => {
it.each(invalidModels)('rejects invalid advisory model config', async (models, message) => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(Reflect.apply(ctx.plugin.bind(ctx), undefined, [LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1', models: [...models],
}])).rejects.toThrow(message)
@@ -2065,6 +2079,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
models: [legacyModel],
@@ -2146,6 +2161,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
defaultContextWindow,
@@ -2162,6 +2178,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
maxTokens,
@@ -2221,6 +2238,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
maxRequestFilesBytes,
@@ -2237,6 +2255,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
maxInlineRequestImageBytes,
@@ -2250,6 +2269,7 @@ describe('plugin registration and config', () => {
vi.stubEnv('DEEPSEEK_BASE_URL', 'http://127.0.0.1:1')
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {})
expect(ctx.llm.listProviders()).toEqual([{ id: 'deepseek-official', name: 'DeepSeek' }])
})
@@ -2258,6 +2278,7 @@ describe('plugin registration and config', () => {
vi.stubEnv('DEEPSEEK_API_KEY', '')
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: 'http://127.0.0.1:1' })
expect(ctx.llm.listProviders()).toEqual([{ id: 'deepseek-official', name: 'DeepSeek' }])
await expect(ctx.llm.listModels('deepseek-official')).resolves.toEqual([])
@@ -2280,6 +2301,7 @@ describe('plugin registration and config', () => {
const server = await mockServer([{ kind: 'sse', events: textEvents }])
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: server.url })
await assemble(ctx, { model: 'deepseek-v4-flash', messages: [] })
expect(server.headers[0]?.['x-api-key']).toBe('ambient-key')
@@ -2289,6 +2311,7 @@ describe('plugin registration and config', () => {
vi.stubEnv('DEEPSEEK_API_KEY', '')
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { baseURL: 'http://127.0.0.1:1' })
const result = await assemble(ctx, { model: 'deepseek-v4-flash', messages: [] })
expect(result.finish).toMatchObject({ kind: 'error', failure: { code: 'MISSING_CREDENTIAL' } })
@@ -2309,6 +2332,7 @@ describe('plugin registration and config', () => {
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {})
await assemble(ctx,{ model: 'deepseek-v4-flash', messages: [] })
expect(server.requests).toHaveLength(1)
@@ -2339,6 +2363,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
// Registration succeeds; no call is made (would hit api.deepseek.com).
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {})
expect(ctx.llm.listProviders()).toEqual([{ id: 'deepseek-official', name: 'DeepSeek' }])
})
@@ -2353,7 +2378,7 @@ describe('plugin registration and config', () => {
it('resolves connection facts and the credential exactly once per stream call', async () => {
const server = await mockServer([{ kind: 'sse', events: textEvents }])
const options = vi.fn(() => resolveAdapterOptions({ baseURL: server.url }))
- const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'per-request-key' }, value: 'per-request-key' }))
+ const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'per-request-key' } }))
const resolveUserId = vi.fn(() => TEST_USER_ID)
const adapter = new DeepSeekAdapter({ options, resolveAuth, resolveUserId, prepareExtensions: noExtensions })
@@ -2373,6 +2398,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
streamIdleTimeoutMs: 0,
@@ -2391,6 +2417,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
filesApiTimeoutMs: 0,
@@ -2407,6 +2434,7 @@ describe('plugin registration and config', () => {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(LlmDeepSeek, {
baseURL: 'http://127.0.0.1:1',
retryPolicy: { mode: 'normal', maxRetries: -1 },
diff --git a/packages/llm/llm-pi-ai/package.json b/packages/llm/llm-pi-ai/package.json
index c4e9d3a510..688a040be8 100644
--- a/packages/llm/llm-pi-ai/package.json
+++ b/packages/llm/llm-pi-ai/package.json
@@ -65,7 +65,8 @@
"@deepseek-ai/dsh-settings": "workspace:*",
"@deepseek-ai/dsh-timeout": "workspace:*",
"@deepseek-ai/dsh-tool-testkit": "workspace:*",
- "@deepseek-ai/dsh-tools": "workspace:*"
+ "@deepseek-ai/dsh-tools": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"peerDependenciesMeta": {
"@deepseek-ai/cordis-plugin-loader": {
diff --git a/packages/llm/llm-pi-ai/src/discovery.ts b/packages/llm/llm-pi-ai/src/discovery.ts
index 020861bc94..428b0b7802 100644
--- a/packages/llm/llm-pi-ai/src/discovery.ts
+++ b/packages/llm/llm-pi-ai/src/discovery.ts
@@ -23,7 +23,8 @@
* @module dsh-llm-pi-ai/discovery
*/
-import { INVALID_CREDENTIAL_CODE, LlmError, normalizeApiKey } from '@deepseek-ai/dsh-llm'
+import { normalizeApiKey } from '@deepseek-ai/dsh-credentials'
+import { INVALID_CREDENTIAL_CODE, LlmError } from '@deepseek-ai/dsh-llm'
import type { LlmDiscoveredModel, LlmModelDiscoveryOperation } from '@deepseek-ai/dsh-llm'
import { attributionHeaders } from '@deepseek-ai/dsh-llm'
import { catalogModels } from './catalog.ts'
diff --git a/packages/llm/llm-pi-ai/src/index.ts b/packages/llm/llm-pi-ai/src/index.ts
index 5a3dffeeaa..36f0b3ce05 100644
--- a/packages/llm/llm-pi-ai/src/index.ts
+++ b/packages/llm/llm-pi-ai/src/index.ts
@@ -60,7 +60,9 @@ import type {} from '@deepseek-ai/cordis-plugin-loader'
import type { Context } from '@deepseek-ai/cordis'
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
-import { assertUsableApiKey, LlmError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm'
+import { normalizeApiKey } from '@deepseek-ai/dsh-credentials'
+import type { ApiKeyRejection } from '@deepseek-ai/dsh-credentials'
+import { INVALID_CREDENTIAL_CODE, LlmError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm'
import type { AdapterRegistrationHandle, DirectoryRegistrationHandle, LlmConfigurableProvider } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/dsh-fs'
import { deepEqualJson } from '@deepseek-ai/dsh-util-values'
@@ -221,7 +223,20 @@ export function apply(ctx: Context, config: Config): void {
? (await credentials.resolve(ref))?.value
// Without the seam the environment is the whole credential plane.
: launchEnvironmentOf(ctx).get(ref)?.value
- if (hit !== undefined && hit.length > 0) return assertUsableApiKey(hit, 'llm-pi-ai', ref)
+ if (hit !== undefined && hit.length > 0) {
+ // A stored key picks up surrounding whitespace, which is trimmed. Any other defect fails here, where the
+ // reference to fix can be named, instead of inside `fetch`.
+ const checked = normalizeApiKey(hit)
+ if (checked.ok) return checked.value
+ // The key never enters the text. The Models page is named as its usual writer; a hand-edited `.env` or a shell
+ // export can supply the same value.
+ const defect: Record = {
+ empty: `is blank; set ${ref} to the raw key (the web Models page writes it) or export it in the launching environment`,
+ illegalCharacters: 'contains characters no HTTP header can carry;'
+ + ` set ${ref} to the raw key alone (the web Models page writes it)`,
+ }
+ throw new LlmError(`llm-pi-ai: the API key resolved from ${ref} ${defect[checked.reason]}`, INVALID_CREDENTIAL_CODE)
+ }
throw new LlmError(
`llm-pi-ai: no credential for provider route "${provider}"; its profile resolves ${ref}, which is not`
+ ` set — store ${ref} through the credentials service (the web Models page writes it) or export it,`
diff --git a/packages/llm/llm-pi-ai/tests/adapter.e2e.ts b/packages/llm/llm-pi-ai/tests/adapter.e2e.ts
index b7787a55d8..a142afe383 100644
--- a/packages/llm/llm-pi-ai/tests/adapter.e2e.ts
+++ b/packages/llm/llm-pi-ai/tests/adapter.e2e.ts
@@ -6,6 +6,7 @@ import type { Message, ToolSchema } from '@deepseek-ai/dsh-llm'
import * as LlmPiAi from '@deepseek-ai/dsh-llm-pi-ai'
import type { PiAiProviderProfile } from '@deepseek-ai/dsh-llm-pi-ai'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { assemble, type AssembledResult } from './assemble.ts'
/**
@@ -150,6 +151,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('llm-pi-ai e2e (real API)', () =>
const deepseekCtx = new Context()
contexts.push(deepseekCtx)
await deepseekCtx.plugin(LlmRuntime)
+ await deepseekCtx.plugin(DeepSeekAuth)
await deepseekCtx.plugin(LlmDeepSeek, { thinking: 'disabled' })
const piCtx = await harness(FLASH)
diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts
index 6d342f2675..b0785b5f3e 100644
--- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts
+++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts
@@ -984,6 +984,28 @@ describe('provider profile lifecycle', () => {
expect(server.requests).toHaveLength(0)
})
+ it.each([
+ [' ', 'is blank; set PI_CUSTOM_REF_KEY to the raw key (the web Models page writes it) or export it in the launching environment'],
+ ['sk-\u{1F600}supersecret', 'contains characters no HTTP header can carry; set PI_CUSTOM_REF_KEY to the raw key alone (the web Models page writes it)'],
+ ])('refuses the unusable key %j behind apiKeyEnv before any request, naming the reference and never the key', async (value, detail) => {
+ vi.stubEnv('PI_CUSTOM_REF_KEY', value)
+ const server = await mockServer([{ events: textEvents }])
+ const ctx = await harness(server.url, { apiKey: undefined, apiKeyEnv: 'PI_CUSTOM_REF_KEY' })
+ const result = await assemble(ctx, { model: 'deepseek-flash', messages: [] })
+ expect(result.finish).toEqual({
+ kind: 'error', failure: { message: `llm-pi-ai: the API key resolved from PI_CUSTOM_REF_KEY ${detail}`, code: 'INVALID_CREDENTIAL' },
+ })
+ expect(server.requests).toHaveLength(0)
+ })
+
+ it('trims whitespace around the key behind apiKeyEnv', async () => {
+ vi.stubEnv('PI_CUSTOM_REF_KEY', ' custom-ref-key\t\n')
+ const server = await mockServer([{ events: textEvents }])
+ const ctx = await harness(server.url, { apiKey: undefined, apiKeyEnv: 'PI_CUSTOM_REF_KEY' })
+ await assemble(ctx, { model: 'deepseek-flash', messages: [] })
+ expect(server.headers[0]?.authorization).toBe('Bearer custom-ref-key')
+ })
+
it('validates empty, underspecified, legacy-shaped, and explicitly blank profiles', () => {
expect(DEFAULT_MAX_REQUEST_IMAGE_BYTES).toBe(20 * 1024 * 1024)
// Empty and omitted dicts are the dormant zero-route posture, not errors.
diff --git a/packages/llm/llm-pi-ai/tests/protocol-roundtrip.spec.ts b/packages/llm/llm-pi-ai/tests/protocol-roundtrip.spec.ts
index 82644ab561..994878cefa 100644
--- a/packages/llm/llm-pi-ai/tests/protocol-roundtrip.spec.ts
+++ b/packages/llm/llm-pi-ai/tests/protocol-roundtrip.spec.ts
@@ -5,6 +5,7 @@ import LlmRuntime, { createToolResultMessage, createUserMessage } from '@deepsee
import type { Message } from '@deepseek-ai/dsh-llm'
import * as LlmPiAi from '@deepseek-ai/dsh-llm-pi-ai'
import * as DeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { assemble } from './assemble.ts'
import { anthropicFrame, closeMockServers, mockServer } from './mock-server.ts'
@@ -131,6 +132,7 @@ describe('protocol history round trips', () => {
'route-b': { api: b, baseURL: target.url, apiKeyEnv: 'PROTOCOL_ROUNDTRIP_KEY', cacheRetention: 'none', models: [{ id: 'model' }] },
},
} })
+ await ctx.plugin(DeepSeekAuth)
if (b === 'deepseek-messages') await ctx.plugin(DeepSeek, {
baseURL: target.url, apiKeyEnv: 'PROTOCOL_ROUNDTRIP_KEY', models: [{ id: 'model' }], thinking: 'disabled',
})
diff --git a/packages/llm/llm-retry/package.json b/packages/llm/llm-retry/package.json
index 427a7e977a..115fefe8b3 100644
--- a/packages/llm/llm-retry/package.json
+++ b/packages/llm/llm-retry/package.json
@@ -66,6 +66,7 @@
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
"@deepseek-ai/dsh-tool-testkit": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
- "@deepseek-ai/cordis": "workspace:~"
+ "@deepseek-ai/cordis": "workspace:~",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/llm/llm-retry/tests/transport-recovery.spec.ts b/packages/llm/llm-retry/tests/transport-recovery.spec.ts
index 4e4d673d80..849a2a87e3 100644
--- a/packages/llm/llm-retry/tests/transport-recovery.spec.ts
+++ b/packages/llm/llm-retry/tests/transport-recovery.spec.ts
@@ -12,6 +12,7 @@ import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server'
import type { SessionId } from '@deepseek-ai/dsh-session'
import type { SessionEvent } from '@deepseek-ai/dsh-session'
import * as Retry from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { brandString } from '@deepseek-ai/dsh-brand'
let context: Context | undefined
@@ -54,6 +55,7 @@ async function harness(
vi.stubEnv('DEEPSEEK_API_KEY', 'mock-key')
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, {
baseURL,
streamIdleTimeoutMs: options.streamIdleTimeoutMs ?? 1_000,
diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml
index ee9b1d0bd5..17fca7f409 100644
--- a/packages/llm/llm/README.i18n.yaml
+++ b/packages/llm/llm/README.i18n.yaml
@@ -21,8 +21,8 @@
en: c3ecb5a1421f27db
zh: 4bbd3c0e513845e1
/deepseek-ai-dsh-llm/use-this-package/minimal-composition:
- en: cf221d60fb42a278
- zh: 0ea17503495d386b
+ en: 3774971ae87ad549
+ zh: db7d1b49d45cce6b
/deepseek-ai-dsh-llm/use-this-package/what-you-can-do:
en: cb9f0c6ee3203ab3
zh: 8513340a40192513
@@ -36,8 +36,8 @@
en: 12d0444c18a397c7
zh: 9d4a5468b4bb7fcd
/deepseek-ai-dsh-llm/understand-the-implementation/source-map:
- en: 8ec1ca8903e09bc0
- zh: 77c7bc3413cbab1c
+ en: fbdadaf319e03d9c
+ zh: edec7c5ef22b37ac
/deepseek-ai-dsh-llm/understand-the-implementation/main-flow:
en: c95d4947745e39bb
zh: ec37b969f27629e2
diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md
index 1419acbe3b..ddc03932e7 100644
--- a/packages/llm/llm/README.md
+++ b/packages/llm/llm/README.md
@@ -37,10 +37,11 @@ Choose this package whenever a plugin or composition needs to call a model: it i
### Minimal composition
-Mount the service and at least one adapter, then select the provider by name in every request:
+Mount the service and at least one adapter, then select the provider by name in every request. The DeepSeek route below also requires [`dsh-deepseek-auth`](../../account/deepseek-auth/README.md), which releases its API key:
```yaml
- name: '@deepseek-ai/dsh-llm'
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-llm-deepseek-api-key'
config:
apiKeyEnv: DEEPSEEK_API_KEY
@@ -124,7 +125,6 @@ The service is built on one separation: **the logical contract is provider-neutr
| [`src/retry-policy.ts`](src/retry-policy.ts) | Provider-owned retry policy resolution (normal and always modes) |
| [`src/error.ts`](src/error.ts) | `HarnessError`/`LlmError` taxonomy and provider-neutral failure codes |
| [`src/content.ts`](src/content.ts) | Shared file and image helpers: content walks, file projection, image offload accounting, and offloaded-image projection |
-| [`src/api-key.ts`](src/api-key.ts) | Credential format check shared by every adapter |
| [`src/adapter-failure.ts`](src/adapter-failure.ts) | Failure normalization into terminal finish chunks |
### Main flow
diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md
index 777d877ff0..2a1bf8bfbf 100644
--- a/packages/llm/llm/README.zh.md
+++ b/packages/llm/llm/README.zh.md
@@ -37,10 +37,11 @@ kind: "package-reference"
### 最小组合
-挂载服务与至少一个适配器,然后在每个请求中按名称选择提供方:
+挂载服务与至少一个适配器,然后在每个请求中按名称选择提供方。下面的 DeepSeek 路由还要求挂载 [`dsh-deepseek-auth`](../../account/deepseek-auth/README.zh.md),由它释放 API 密钥:
```yaml
- name: '@deepseek-ai/dsh-llm'
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-llm-deepseek-api-key'
config:
apiKeyEnv: DEEPSEEK_API_KEY
@@ -124,7 +125,6 @@ const configure = (maxTokens: number): ConfigureCall =>
| [`src/retry-policy.ts`](src/retry-policy.ts) | 提供方自有重试策略解析(normal 与 always 模式) |
| [`src/error.ts`](src/error.ts) | `HarnessError`/`LlmError` 分类体系与提供方无关失败 code |
| [`src/content.ts`](src/content.ts) | 共享文件与图片辅助函数:内容遍历、文件投影、图片卸载计数与已卸载图片投影 |
-| [`src/api-key.ts`](src/api-key.ts) | 每个适配器共享的凭据格式校验 |
| [`src/adapter-failure.ts`](src/adapter-failure.ts) | 把失败归一化为终止 finish 分片 |
### 主流程
diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts
index d354188c30..24b06101b4 100644
--- a/packages/llm/llm/src/index.ts
+++ b/packages/llm/llm/src/index.ts
@@ -22,7 +22,6 @@ import type {
LlmResolvedModelInfo,
LlmProviderInfo,
ModelModality,
- ProviderCredential,
StreamChunk,
SystemPromptUpdate,
ToolSchema,
@@ -34,10 +33,9 @@ import type { ResolvedRetryPolicy } from './retry-policy.ts'
import type { ProviderRequestId } from './brand.ts'
import { callConfigEquals } from './call-config.ts'
import type { ConfigureCall, LlmCallConfig, LlmCallConfigAdapterDefaults } from './call-config.ts'
-import { HarnessError, INVALID_CREDENTIAL_CODE } from './error.ts'
+import { HarnessError } from './error.ts'
import type { BuiltinLlmFailureCode } from './error.ts'
import { normalizeLlmFailure } from './adapter-failure.ts'
-import { normalizeApiKey } from './api-key.ts'
import {
contentHasFile, contentHasImage, fileHandleText, projectFilesToText, projectImagesForTextModel, projectToolUpdates,
} from './content.ts'
@@ -46,7 +44,6 @@ import type { FileAttachmentRef, ImageAttachmentRef, ImageRequestTarget } from '
export * from './attribution.ts'
export * from './brand.ts'
export * from './error.ts'
-export * from './api-key.ts'
export type * from './types.ts'
export * from './content.ts'
export * from './assistant-stream.ts'
@@ -150,41 +147,6 @@ export class LlmError extends HarnessError {
}
}
-/**
- * Accept one supplied credential, or refuse it as unusable.
- *
- * A stored key arrives from the credentials seam, a `.env` line, or a shell
- * export, all of which pick up surrounding whitespace, so trimming is silent.
- * Anything else fails here rather than inside `fetch`, whose ByteString
- * refusal names a UTF-16 code point instead of the setting to change. The key
- * never enters the message: `ref` names where to fix it, and echoing any part
- * of a secret into a log or a UI is the failure this diagnosis avoids.
- *
- * Lives beside {@link LlmError} rather than in `./api-key.ts` so the predicate
- * module stays dependency-free; both adapters share this one diagnosis instead
- * of keeping near-identical local copies.
- * @param raw - the credential exactly as supplied.
- * @param pkg - the refusing plugin's settings namespace or package name, prefixed to the diagnostic.
- * @param ref - the credential reference the value resolved through.
- * @returns the trimmed, usable key.
- */
-export function assertUsableApiKey(raw: string, pkg: string, ref: string): string {
- const checked = normalizeApiKey(raw)
- if (checked.ok) return checked.value
- // The Models page is named as the writer it usually is, not as the only one:
- // the same value can arrive from a hand-edited .env or a shell export in a
- // composition that mounts no credentials seam at all, where directing the
- // user to a page that deployment does not serve would be a dead end.
- throw new LlmError(
- checked.reason === 'empty'
- ? `${pkg}: the API key resolved from ${ref} is blank; set ${ref} to the raw key`
- + ' (the web Models page writes it) or export it in the launching environment'
- : `${pkg}: the API key resolved from ${ref} contains characters no HTTP header can carry;`
- + ` set ${ref} to the raw key alone (the web Models page writes it)`,
- INVALID_CREDENTIAL_CODE,
- )
-}
-
/** One model call whose config and adapter registration were resolved together. */
export interface PreparedLlmCall {
/** Detached, deep-frozen config with any adapter-owned default materialized. */
@@ -269,19 +231,6 @@ export abstract class LlmAdapter {
return { width: image.width, height: image.height, maxBytes: image.bytes }
}
- /**
- * Describe the credential one owned route currently sends, for consumers that
- * call the same deployment outside the model request path, such as web
- * providers that share a route's credential and endpoint. The default
- * publishes none. Implementations answer from one configuration generation
- * per call and may throw when that configuration does not resolve.
- * @param _provider - a route passed to `registerAdapter()` for this instance.
- * @returns the route's current credential, or `undefined` when the route publishes none.
- */
- providerCredential(_provider: string): ProviderCredential | undefined {
- return undefined
- }
-
/**
* List models this adapter can currently advertise for one owned provider.
* Core routing accepts unlisted model ids; catalog-driven entry points such
@@ -726,19 +675,6 @@ export class LlmRuntime extends TypertRemoteService {
return this.registration(provider).adapter.imageRequestTarget(provider, model, image)
}
- /**
- * Resolve the credential one registered route currently sends, through its
- * owning adapter. An unregistered route answers `undefined` rather than
- * throwing because callers ask about routes a conversation named earlier,
- * which may no longer be mounted; a registered route whose configuration
- * does not resolve propagates the adapter's failure.
- * @param provider - provider route whose credential is wanted.
- * @returns the route's credential, or `undefined` when the route is unregistered or publishes none.
- */
- providerCredential(provider: string): ProviderCredential | undefined {
- return this.adapters.get(provider)?.adapter.providerCredential(provider)
- }
-
/**
* Resolve the exact text one durable file occurrence contributes to every
* provider request in the current execution environment.
diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts
index fdc7320c40..dae3c7c4ac 100644
--- a/packages/llm/llm/src/types.ts
+++ b/packages/llm/llm/src/types.ts
@@ -292,94 +292,6 @@ export interface LlmNativeAuth {
oauth: boolean
}
-/**
- * Merge-extensible vocabulary of the credential kinds a provider route sends.
- * `api-key` is a provider key read from a credential reference or the launch
- * environment; `account` is a grant obtained by signing in. An adapter that
- * sends another kind declares it here.
- */
-export interface LlmCredentialKindMap {
- 'api-key': 'api-key'
- account: 'account'
-}
-
-/** Any declared credential kind. */
-export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap]
-
-/**
- * One credential released for one destination. Host-only: it carries the
- * secret, so it never crosses a Remote boundary and never enters a log.
- */
-export interface ProviderCredentialGrant {
- /**
- * Request headers carrying the credential as the route's own protocol
- * expects it, such as `x-api-key` for an API key. Consumers speaking that
- * protocol send them unchanged.
- */
- readonly headers: Readonly>
- /**
- * The bare credential value, for destinations whose protocol renders it
- * differently from {@link headers}, such as `Authorization: Bearer`.
- */
- readonly value: string
- /**
- * Invalidate this exact credential after the destination rejected it with
- * HTTP 401 so no later request resends it. Absent for kinds without
- * invalidation. The owner contains storage failures: the caller reports the
- * destination's rejection, never a failure of this call.
- * @returns settlement after the invalidation attempt.
- */
- reject?(): Promise
- /**
- * Aborts when the owner withdraws this credential while requests carrying it
- * may be in flight, as an account sign-out does. A consumer ends each request
- * it authenticated with this grant and reports that end as its own failure,
- * not as the caller's cancellation. Absent for kinds that are never withdrawn.
- */
- readonly revoked?: AbortSignal
-}
-
-/**
- * The credential one registered provider route currently sends, answered by
- * the route's owning adapter so that consumers read no provider configuration
- * and choose no header names. `ctx.llm.providerCredential()` resolves a new value
- * per call from one configuration generation; a caller keeps it for one
- * operation only.
- */
-export interface ProviderCredential {
- /** Kind of credential the route sends. */
- readonly kind: LlmCredentialKind
- /**
- * The route's current request base URL as its configuration resolves it,
- * environment fallbacks included: the destination this credential is meant
- * for. Consumers derive sibling endpoints of the same deployment from it.
- */
- readonly baseURL: string
- /**
- * Credential reference the route resolves, for diagnostics that tell the user
- * where to configure the credential; absent for kinds without a stored
- * reference, such as sign-in grants.
- */
- readonly reference?: string
- /**
- * Whether {@link resolve} would release a credential for `endpoint`, checked
- * without validating the credential or contacting the destination; the owner
- * may read its store to answer. Store failures reject.
- * @param endpoint - absolute URL the credential would be sent to.
- * @returns whether a credential is configured for that destination.
- */
- configured(endpoint: string): Promise
- /**
- * Release the credential for `endpoint`, or `undefined` when none is
- * configured or the destination may not receive it. The caller chooses the
- * failure it reports for `undefined`. Store and format failures reject.
- * @param endpoint - absolute URL the credential will be sent to.
- * @param signal - cancellation for the lookup.
- * @returns the released credential, or `undefined`.
- */
- resolve(endpoint: string, signal?: AbortSignal): Promise
-}
-
/**
* One interrogation of a provider endpoint that configuration has not stored
* yet. Configuration surfaces send the draft a user is still editing, so the
diff --git a/packages/llm/llm/tests/api-key.spec.ts b/packages/llm/llm/tests/api-key.spec.ts
deleted file mode 100644
index 783b054b9b..0000000000
--- a/packages/llm/llm/tests/api-key.spec.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { assertUsableApiKey, INVALID_CREDENTIAL_CODE, normalizeApiKey } from '@deepseek-ai/dsh-llm'
-
-describe('normalizeApiKey', () => {
- it('accepts a printable-ASCII key unchanged', () => {
- expect(normalizeApiKey('sk-0123456789abcdef')).toEqual({ ok: true, value: 'sk-0123456789abcdef' })
- })
-
- it('trims surrounding whitespace before judging', () => {
- expect(normalizeApiKey(' sk-abc\t\n')).toEqual({ ok: true, value: 'sk-abc' })
- })
-
- it.each([
- ['an empty string', ''],
- ['spaces only', ' '],
- ['a tab only', '\t'],
- ])('rejects %s as empty', (_label, raw) => {
- expect(normalizeApiKey(raw)).toEqual({ ok: false, reason: 'empty' })
- })
-
- it.each([
- ['an emoji', 'sk-\u{1F600}abc'],
- ['CJK text', 'sk-你好'],
- ['full-width punctuation', 'sk-abc,'],
- ['an interior space', 'sk-abc def'],
- ['a C0 control character', 'sk-abc\x01'],
- ['a latin-1 character', 'sk-café'],
- ])('rejects %s as illegal characters', (_label, raw) => {
- expect(normalizeApiKey(raw)).toEqual({ ok: false, reason: 'illegalCharacters' })
- })
-
- it('accepts the printable-ASCII boundary characters', () => {
- expect(normalizeApiKey('!~')).toEqual({ ok: true, value: '!~' })
- })
-
- it('publishes a code distinct from a missing credential', () => {
- expect(INVALID_CREDENTIAL_CODE).toBe('INVALID_CREDENTIAL')
- })
-})
-
-describe('assertUsableApiKey', () => {
- it('returns the trimmed key when it is usable', () => {
- expect(assertUsableApiKey(' sk-abc ', 'llm-deepseek', 'DEEPSEEK_API_KEY')).toBe('sk-abc')
- })
-
- it('refuses a blank stored credential, naming the reference', () => {
- expect(() => assertUsableApiKey(' ', 'llm-deepseek', 'DEEPSEEK_API_KEY'))
- .toThrow(/llm-deepseek: the API key resolved from DEEPSEEK_API_KEY is blank/)
- })
-
- it('refuses an unusable stored credential with the invalid-credential code', () => {
- try {
- assertUsableApiKey('sk-\u{1F600}', 'llm-pi-ai', 'ACME_API_KEY')
- expect.fail('an illegal key must throw')
- } catch (error) {
- expect((error as { code: string }).code).toBe(INVALID_CREDENTIAL_CODE)
- expect((error as Error).message).toContain('llm-pi-ai')
- expect((error as Error).message).toContain('ACME_API_KEY')
- }
- })
-
- it('never echoes the key it refuses', () => {
- try {
- assertUsableApiKey('sk-\u{1F600}supersecret', 'llm-deepseek', 'DEEPSEEK_API_KEY')
- expect.fail('an illegal key must throw')
- } catch (error) {
- expect((error as Error).message).not.toContain('supersecret')
- }
- })
-})
diff --git a/packages/llm/llm/tests/topology.spec.ts b/packages/llm/llm/tests/topology.spec.ts
index 3a9735fbef..98b1be4920 100644
--- a/packages/llm/llm/tests/topology.spec.ts
+++ b/packages/llm/llm/tests/topology.spec.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import LlmRuntime, { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm'
-import type { GenerateOptions, LlmConfigurableProvider, ProviderCredential, StreamChunk } from '@deepseek-ai/dsh-llm'
+import type { GenerateOptions, LlmConfigurableProvider, StreamChunk } from '@deepseek-ai/dsh-llm'
class NoopAdapter extends LlmAdapter {
@@ -339,25 +339,3 @@ describe('imageRequestPricing resolution', () => {
expect(ctx.llm.imageRequestPricing('a', 'vision')).toBeUndefined()
})
})
-
-describe('providerCredential resolution', () => {
- it('forwards to the owning adapter and answers undefined everywhere else', async () => {
- const ctx = await setup()
- const credential: ProviderCredential = {
- kind: 'api-key', baseURL: 'https://a.example/v1',
- configured: () => Promise.resolve(true),
- resolve: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }),
- }
- class CredentialAdapter extends NoopAdapter {
- override providerCredential(provider: string) { return provider === 'a' ? credential : undefined }
- }
- const dispose = ctx.llm.registerAdapter(['a', 'b'], new CredentialAdapter())
- ctx.llm.registerAdapter(['plain'], new NoopAdapter())
- expect(ctx.llm.providerCredential('a')).toBe(credential)
- expect(ctx.llm.providerCredential('b')).toBeUndefined()
- expect(ctx.llm.providerCredential('plain')).toBeUndefined()
- expect(ctx.llm.providerCredential('missing')).toBeUndefined()
- dispose()
- expect(ctx.llm.providerCredential('a')).toBeUndefined()
- })
-})
diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md
index ac0dd083a8..06fc5ac9ba 100644
--- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md
+++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md
@@ -9,6 +9,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo
| Package | Config | Description |
|---|---|---|
| `@deepseek-ai/dsh-deepseek-account` | yes | Sign in to DeepSeek and manage account credentials and notifications |
+| `@deepseek-ai/dsh-deepseek-auth` | no | DeepSeek request authentication (ctx.deepseekAuth): choose between the API key and the account sign-in for one DeepSeek API request and release its headers |
## acp
diff --git a/packages/sdk/server/package.json b/packages/sdk/server/package.json
index 48ecea878d..b26498b684 100644
--- a/packages/sdk/server/package.json
+++ b/packages/sdk/server/package.json
@@ -51,7 +51,8 @@
"@deepseek-ai/dsh-subagent": "workspace:*",
"@deepseek-ai/dsh-user-approval": "workspace:*",
"@deepseek-ai/dsh-user-questions": "workspace:*",
- "@deepseek-ai/dsh-working-directory": "workspace:*"
+ "@deepseek-ai/dsh-working-directory": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
@@ -84,6 +85,7 @@
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-user-approval": "workspace:*",
"@deepseek-ai/dsh-user-questions": "workspace:*",
- "@deepseek-ai/dsh-working-directory": "workspace:*"
+ "@deepseek-ai/dsh-working-directory": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/sdk/server/src/server.ts b/packages/sdk/server/src/server.ts
index 731ae2da16..ce5043fee8 100644
--- a/packages/sdk/server/src/server.ts
+++ b/packages/sdk/server/src/server.ts
@@ -23,6 +23,7 @@ import type {} from '@deepseek-ai/dsh-permission-presets'
import type {} from '@deepseek-ai/dsh-schedule'
import type { SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
import type {
ApprovalRequestParams,
@@ -94,6 +95,7 @@ export class HarnessSdkJsonRpcServer {
private reasoningEffort: ReasoningEffortId | undefined
private maxTokens: number | undefined
private llmFiber: { dispose(): Promise } | undefined
+ private authFiber: { dispose(): Promise } | undefined
private readonly sessions = new Map()
private readonly sessionCreations = new Map>()
private readonly commandTasks = new Set>()
@@ -233,7 +235,17 @@ export class HarnessSdkJsonRpcServer {
: brandString(params.reasoningEffort)
if (!this.hasAdapterFor(provider)) {
if (provider !== 'deepseek-official') throw new Error(`no adapter registered for provider "${provider}"`)
- this.llmFiber = await this.ctx.plugin(LlmDeepSeek)
+ // The route requires the DeepSeek authentication service; a composition without one gets it with the fallback route.
+ if (this.ctx.get('deepseekAuth') === undefined) this.authFiber = await this.ctx.plugin(DeepSeekAuth)
+ try {
+ this.llmFiber = await this.ctx.plugin(LlmDeepSeek)
+ } catch (error: unknown) {
+ // Without the route nothing here uses the authentication service this call mounted.
+ const mounted = this.authFiber
+ this.authFiber = undefined
+ await mounted?.dispose()
+ throw error
+ }
}
// Adapter presence was read from this service above; a successful fallback mount also requires it.
const llm = this.ctx.get('llm') as LlmRuntime
@@ -484,9 +496,13 @@ export class HarnessSdkJsonRpcServer {
const teardownResults = await Promise.allSettled([
this.goalLifetime.dispose(),
...records.map(rec => Promise.resolve().then(() => rec.handle.dispose())),
- ...(this.llmFiber === undefined ? [] : [Promise.resolve().then(() => this.llmFiber?.dispose())]),
+ ...(this.llmFiber === undefined ? [] : [Promise.resolve().then(async () => {
+ // The route requires the authentication service, so the route goes first; its failure does not keep the service.
+ try { await this.llmFiber?.dispose() } finally { await this.authFiber?.dispose() }
+ })]),
])
this.llmFiber = undefined
+ this.authFiber = undefined
failures.push(...teardownResults
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
.map(result => result.reason as unknown))
diff --git a/packages/sdk/server/tests/server.spec.ts b/packages/sdk/server/tests/server.spec.ts
index feabf16163..3f8faa036f 100644
--- a/packages/sdk/server/tests/server.spec.ts
+++ b/packages/sdk/server/tests/server.spec.ts
@@ -24,6 +24,7 @@ import { brandString } from '@deepseek-ai/dsh-brand'
import SubagentRuntime, { type SubagentRunId, type SubagentStartRequest, type SubagentRun, type SubagentResult, type SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent'
import type { JsonRpcTransportPeer } from '@deepseek-ai/dsh-sdk-protocol'
import { HarnessSdkJsonRpcServer } from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
class FakeTransport implements JsonRpcTransportPeer {
notifications: { method: string; params?: Record }[] = []
@@ -1050,6 +1051,7 @@ describe('HarnessSdkJsonRpcServer', () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-existing-llm-'))
const ctx = await makeHarness(storageDir)
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { models: [{ id: 'preinstalled-model' }] })
try {
const server = new HarnessSdkJsonRpcServer(ctx, new FakeTransport())
@@ -1067,10 +1069,84 @@ describe('HarnessSdkJsonRpcServer', () => {
}
})
+ it.each([
+ ['a composition without DeepSeek authentication', false],
+ ['a composition that mounts DeepSeek authentication', true],
+ ] as const)('mounts the official route for %s and removes at shutdown only what it mounted', async (_composition, mounted) => {
+ const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-fallback-auth-'))
+ const ctx = await makeHarness(storageDir)
+ vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
+ // A loopback endpoint keeps the fallback-mounted official route off the network; no request is sent.
+ vi.stubEnv('DEEPSEEK_BASE_URL', 'http://127.0.0.1:9/anthropic')
+ if (mounted) await ctx.plugin(DeepSeekAuth)
+ const officialRoute = (): boolean => ctx.get('llm')?.listProviders().some(provider => provider.id === 'deepseek-official') ?? false
+ // Reported as a boolean: a failed assertion must not print the service and its context.
+ const authentication = (): boolean => ctx.get('deepseekAuth') !== undefined
+ try {
+ const server = new HarnessSdkJsonRpcServer(ctx, new FakeTransport())
+ await server.initialize({ cwd: storageDir, provider: 'deepseek-official', model: 'deepseek-v4-flash' })
+ expect([officialRoute(), authentication()]).toEqual([true, true])
+ await server.shutdown()
+ expect([officialRoute(), authentication()]).toEqual([false, mounted])
+ } finally {
+ await ctx.fiber.dispose()
+ await rm(storageDir, { recursive: true, force: true })
+ }
+ })
+
+ it.each([
+ ['a composition without DeepSeek authentication', false],
+ ['a composition that mounts DeepSeek authentication', true],
+ ] as const)('leaves %s as it was when the fallback route does not mount', async (_composition, mounted) => {
+ const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-fallback-failed-'))
+ const ctx = await makeHarness(storageDir)
+ vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
+ // The official route rejects a base URL that is no HTTP(S) root while it mounts.
+ vi.stubEnv('DEEPSEEK_BASE_URL', 'ftp://deepseek.test/anthropic')
+ if (mounted) await ctx.plugin(DeepSeekAuth)
+ const authentication = (): boolean => ctx.get('deepseekAuth') !== undefined
+ try {
+ const server = new HarnessSdkJsonRpcServer(ctx, new FakeTransport())
+ await expect(server.initialize({ cwd: storageDir, provider: 'deepseek-official', model: 'deepseek-v4-flash' }))
+ .rejects.toThrow('Messages baseURL must be an HTTP(S) root')
+ expect(authentication()).toBe(mounted)
+ await server.shutdown()
+ expect(authentication()).toBe(mounted)
+ } finally {
+ await ctx.fiber.dispose()
+ await rm(storageDir, { recursive: true, force: true })
+ }
+ })
+
+ it('removes the DeepSeek authentication it mounted when the fallback route fails to dispose', async () => {
+ const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-fallback-dispose-'))
+ const ctx = await makeHarness(storageDir)
+ vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
+ vi.stubEnv('DEEPSEEK_BASE_URL', 'http://127.0.0.1:9/anthropic')
+ try {
+ const server = new HarnessSdkJsonRpcServer(ctx, new FakeTransport())
+ await server.initialize({ cwd: storageDir, provider: 'deepseek-official', model: 'deepseek-v4-flash' })
+ const [route] = ctx.registry.get(LlmDeepSeek)?.fibers ?? []
+ if (route === undefined) throw new Error('expected the fallback route fiber')
+ const rawDispose = route.dispose
+ const failure = new Error('route teardown failed')
+ vi.spyOn(route, 'dispose').mockImplementation(async () => {
+ await rawDispose()
+ throw failure
+ })
+ await expect(server.shutdown()).rejects.toBe(failure)
+ expect(ctx.get('deepseekAuth') !== undefined).toBe(false)
+ } finally {
+ await ctx.fiber.dispose()
+ await rm(storageDir, { recursive: true, force: true })
+ }
+ })
+
it('rejects a missing non-DeepSeek provider when an LLM service already exists', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-new-llm-'))
const ctx = await makeHarness(storageDir)
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek)
try {
const server = new HarnessSdkJsonRpcServer(ctx, new FakeTransport())
diff --git a/packages/sdk/server/tsconfig.json b/packages/sdk/server/tsconfig.json
index 48e2fd7b56..fec572da5c 100644
--- a/packages/sdk/server/tsconfig.json
+++ b/packages/sdk/server/tsconfig.json
@@ -55,6 +55,9 @@
},
{
"path": "../../interaction/permission-presets"
+ },
+ {
+ "path": "../../account/deepseek-auth"
}
]
}
diff --git a/packages/session/session-log-deepseek/package.json b/packages/session/session-log-deepseek/package.json
index 99fcfa48d1..d1cd9f69e7 100644
--- a/packages/session/session-log-deepseek/package.json
+++ b/packages/session/session-log-deepseek/package.json
@@ -58,6 +58,7 @@
"@deepseek-ai/dsh-llm-mock-server": "workspace:*",
"@deepseek-ai/dsh-message-feedback": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
- "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*"
+ "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/session/session-log-deepseek/tests/feedback-composition.spec.ts b/packages/session/session-log-deepseek/tests/feedback-composition.spec.ts
index 3ecf031750..9cc874c353 100644
--- a/packages/session/session-log-deepseek/tests/feedback-composition.spec.ts
+++ b/packages/session/session-log-deepseek/tests/feedback-composition.spec.ts
@@ -12,6 +12,7 @@ import MessageFeedback from '@deepseek-ai/dsh-message-feedback'
import { recordFeedback } from '@deepseek-ai/dsh-command-feedback'
import LlmRuntime, { createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import DeepSeekLlmApiExtensions from '@deepseek-ai/dsh-deepseek-llm-api-extensions'
import { startMockLlmServer, type MockLlmServer, type MockLlmServerOptions } from '@deepseek-ai/dsh-llm-mock-server'
import * as SessionLogDeepSeek from '../src/index.ts'
@@ -45,6 +46,7 @@ async function boot(
['@deepseek-ai/dsh-session-persistence-jsonl', JsonlSessionPersistence],
['@deepseek-ai/dsh-message-feedback', MessageFeedback],
['@deepseek-ai/dsh-llm', LlmRuntime],
+ ['@deepseek-ai/dsh-deepseek-auth', DeepSeekAuth],
['@deepseek-ai/dsh-llm-deepseek-api-key', LlmDeepSeek],
['@deepseek-ai/dsh-deepseek-llm-api-extensions', DeepSeekLlmApiExtensions],
['@deepseek-ai/dsh-session-log-deepseek', SessionLogDeepSeek],
diff --git a/packages/session/session-title-first-prompt-llm/package.json b/packages/session/session-title-first-prompt-llm/package.json
index 9cf4757885..376e8177c1 100644
--- a/packages/session/session-title-first-prompt-llm/package.json
+++ b/packages/session/session-title-first-prompt-llm/package.json
@@ -54,6 +54,7 @@
"@deepseek-ai/dsh-session-title-llm": "workspace:*",
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-session-projection": "workspace:*",
- "@deepseek-ai/dsh-agent-loop": "workspace:*"
+ "@deepseek-ai/dsh-agent-loop": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/session/session-title-first-prompt-llm/tests/provider.e2e.ts b/packages/session/session-title-first-prompt-llm/tests/provider.e2e.ts
index 79c8274206..69178ebbe6 100644
--- a/packages/session/session-title-first-prompt-llm/tests/provider.e2e.ts
+++ b/packages/session/session-title-first-prompt-llm/tests/provider.e2e.ts
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import LlmRuntime from '@deepseek-ai/dsh-llm'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
import SessionTitleService from '@deepseek-ai/dsh-session-title'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
@@ -21,6 +22,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('first-prompt title provider with
const ctx = new Context()
contexts.push(ctx)
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek, { thinking: 'disabled' })
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
diff --git a/packages/subagent/subagent-spawn-in-process/package.json b/packages/subagent/subagent-spawn-in-process/package.json
index 4d9d31a7d2..3ccdc0b5c9 100644
--- a/packages/subagent/subagent-spawn-in-process/package.json
+++ b/packages/subagent/subagent-spawn-in-process/package.json
@@ -55,6 +55,7 @@
"@deepseek-ai/dsh-tool-subagent": "workspace:*",
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-session-projection": "workspace:*",
- "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*"
+ "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/subagent/subagent-spawn-in-process/tests/harness.ts b/packages/subagent/subagent-spawn-in-process/tests/harness.ts
index 6bc59cb6b4..9cf05abb09 100644
--- a/packages/subagent/subagent-spawn-in-process/tests/harness.ts
+++ b/packages/subagent/subagent-spawn-in-process/tests/harness.ts
@@ -12,6 +12,7 @@ import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
import SubagentRuntime from '@deepseek-ai/dsh-subagent'
import * as Spawn from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
/**
@@ -32,6 +33,7 @@ export async function spawnHarness(workdir: string): Promise {
systemPrompt: { personaPrefix: 'You are a coding agent. Report only when the requested work is done.' },
})
await ctx.plugin(AgentLoop, { agents: [] })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(LlmDeepSeek)
await ctx.plugin(LocalSubprocessRuntime)
await ctx.plugin(BashEnvPlugin)
diff --git a/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts b/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts
index 38672325df..5c980cf5e3 100644
--- a/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts
+++ b/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts
@@ -39,7 +39,7 @@ it('continues the parent through default Messages after a reasoning-bearing cont
const connection = resolveAdapterOptions({ baseURL: http.url })
const adapter = new DeepSeekAdapter({
options: () => connection,
- resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }),
+ resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }),
resolveUserId: () => '00000000-0000-4000-8000-000000000001' as AnonymousUserId,
prepareExtensions: () => Promise.resolve({ fields: {}, accept: () => Promise.resolve() }),
})
diff --git a/packages/web/tool-web/README.i18n.yaml b/packages/web/tool-web/README.i18n.yaml
index e1f06e2cb0..25584657f7 100644
--- a/packages/web/tool-web/README.i18n.yaml
+++ b/packages/web/tool-web/README.i18n.yaml
@@ -21,8 +21,8 @@
en: b476ed2e08c158e1
zh: 17ddc6ee8123cbb4
/deepseek-ai-dsh-tool-web/use-this-package/minimal-configuration:
- en: 64f406c13623a5e4
- zh: 79df236295b8c577
+ en: 7121bd6b2fad3a28
+ zh: 33405ef1923671d5
/deepseek-ai-dsh-tool-web/use-this-package/using-web-search:
en: 6bc6e7c3bdb13862
zh: e4fc9b4921467368
diff --git a/packages/web/tool-web/README.md b/packages/web/tool-web/README.md
index f736e51640..2a74ddd12d 100644
--- a/packages/web/tool-web/README.md
+++ b/packages/web/tool-web/README.md
@@ -33,10 +33,11 @@ Choose this package when the model should discover current information or read a
### Minimal configuration
-Load the web service, at least one backend, and this package; both tools register by default.
+Load the web service, at least one backend, and this package; both tools register by default. The DeepSeek backend below requires [`dsh-deepseek-auth`](../../account/deepseek-auth/README.md) for its credentials.
```yaml
- name: '@deepseek-ai/dsh-web'
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-web-deepseek-api'
- name: '@deepseek-ai/dsh-tool-web'
```
diff --git a/packages/web/tool-web/README.zh.md b/packages/web/tool-web/README.zh.md
index af2451d76f..1081d311d0 100644
--- a/packages/web/tool-web/README.zh.md
+++ b/packages/web/tool-web/README.zh.md
@@ -33,10 +33,11 @@ kind: "package-reference"
### 最小配置
-加载 web 服务、至少一个后端与本包;两个工具默认都会注册。
+加载 web 服务、至少一个后端与本包;两个工具默认都会注册。下面的 DeepSeek 后端要求挂载 [`dsh-deepseek-auth`](../../account/deepseek-auth/README.zh.md) 以取得凭据。
```yaml
- name: '@deepseek-ai/dsh-web'
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-web-deepseek-api'
- name: '@deepseek-ai/dsh-tool-web'
```
diff --git a/packages/web/tool-web/package.json b/packages/web/tool-web/package.json
index 0a3371ad87..ba070f56a8 100644
--- a/packages/web/tool-web/package.json
+++ b/packages/web/tool-web/package.json
@@ -64,6 +64,7 @@
"@types/turndown": "^5.0.6",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-token-meter": "workspace:*",
- "@deepseek-ai/dsh-launch-environment": "workspace:*"
+ "@deepseek-ai/dsh-launch-environment": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/web/tool-web/tests/integration.spec.ts b/packages/web/tool-web/tests/integration.spec.ts
index 49896f0a3a..4ecd5a01c2 100644
--- a/packages/web/tool-web/tests/integration.spec.ts
+++ b/packages/web/tool-web/tests/integration.spec.ts
@@ -15,6 +15,7 @@ import { Context } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { brandString } from '@deepseek-ai/dsh-brand'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
import { createScope } from '@deepseek-ai/dsh-scope'
import type { SessionId } from '@deepseek-ai/dsh-session'
@@ -55,6 +56,7 @@ beforeEach(async () => {
})
await ctx.plugin(WebFetchLocal, {})
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: { DEEPSEEK_API_KEY: 'search-key' } }]))
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(WebDeepSeekApi, { searchBaseURL: SEARCH_API_BASE, sendOriginalQuestion: false })
// The shipped deployment shape: the tool-call budget is declared by tool-web
// config (default 30s, attached as ToolDefinition.timeoutMs) and enforced by
diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml
index d2e5ca1950..64d9982d75 100644
--- a/packages/web/web-deepseek-api/README.i18n.yaml
+++ b/packages/web/web-deepseek-api/README.i18n.yaml
@@ -15,17 +15,17 @@
en: 76368b6b1da79c80
zh: 1e8f931a56b7d34d
/deepseek-ai-dsh-web-deepseek-api/use-this-package:
- en: 673ba23a4e608cf2
- zh: 042afa607aaf4335
+ en: 7a5307c0b8c8b7d4
+ zh: 124bb95be87aab88
/deepseek-ai-dsh-web-deepseek-api/use-this-package/authentication:
- en: ba52a11cc1840ca6
- zh: d8f238abb1b309c8
+ en: a54cbc8b38f54bc1
+ zh: d5e219a1439a8ff7
/deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures:
- en: e7a5d332ebababe7
- zh: 6ea098d53d4e9616
+ en: cb00c9329a964bbb
+ zh: 06eb9fcb23bc92e0
/deepseek-ai-dsh-web-deepseek-api/understand-the-implementation:
- en: ab3a0eaeee8747cf
- zh: 449aeb4bce7d7707
+ en: c13e3136583eefd0
+ zh: c397d8edf093ebb1
/deepseek-ai-dsh-web-deepseek-api/model-experience:
en: 215e7ba838619b7b
zh: a311da3843709f90
@@ -54,8 +54,8 @@
en: 14f9af39f3be4fac
zh: 3c7139fba0f17862
/deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work:
- en: c52fd4fda604976e
- zh: 5cc3fad3d756362a
+ en: f2e7c5945900e148
+ zh: eb76055ae634f6db
/deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work/dev-note:
en: 0a1253c6f7b5e8b9
zh: 9f56528562c7c914
diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md
index bb141166c7..e34ed7ebe3 100644
--- a/packages/web/web-deepseek-api/README.md
+++ b/packages/web/web-deepseek-api/README.md
@@ -24,13 +24,14 @@ Search and fetch the web through the DeepSeek Search and Fetch APIs: one direct
## Use this package
-Mount the plugin alongside `dsh-web` and select its providers. Shipped profiles mount it and select its Search API (`deepseek-search-api`) for search and local HTTP fetch for fetch. In **Plugins > Built-in plugin settings > Web search and fetch**, choosing **DeepSeek Search API** in the **Search** menu selects `deepseek-search-api` and choosing **DeepSeek Fetch API** in the **Fetch** menu selects `deepseek-fetch-api`; each menu is saved independently, and choosing another entry restores another provider. While a menu selects one of these providers, its **Billing** menu below writes `searchBilling` or `fetchBilling`: **Automatic**, **Signed-in DeepSeek account**, or **DeepSeek API key**. A saved selection applies to the next operation.
+Mount the plugin alongside `dsh-web` and [`dsh-deepseek-auth`](../../account/deepseek-auth/README.md), which releases its credentials, and select its providers. Shipped profiles mount it and select its Search API (`deepseek-search-api`) for search and local HTTP fetch for fetch. In **Plugins > Built-in plugin settings > Web search and fetch**, choosing **DeepSeek Search API** in the **Search** menu selects `deepseek-search-api` and choosing **DeepSeek Fetch API** in the **Fetch** menu selects `deepseek-fetch-api`; each menu is saved independently, and choosing another entry restores another provider. While a menu selects one of these providers, its **Billing** menu below writes `searchBilling` or `fetchBilling`: **Automatic**, **Signed-in DeepSeek account**, or **DeepSeek API key**. A saved selection applies to the next operation.
```yaml
- name: '@deepseek-ai/dsh-web'
config:
searchProvider: deepseek-search-api
fetchProvider: deepseek-fetch-api
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-web-deepseek-api'
config:
searchBaseURL: https://search.example.test/api/v1/tools
@@ -59,22 +60,22 @@ Run the real API tests with `DEEPSEEK_API_KEY` and `DEEPSEEK_SEARCH_API_TEST_BAS
Search and Fetch each resolve their endpoint and credential from one settings snapshot per operation, so a saved setting, a model-provider change, a sign-in, or a stored key applies to the next operation. The conversation's route is the `provider` of the initiating Session's latest request context; `ready()` uses the route of the model request being prepared.
- **Own settings.** A capability with a non-empty `*BaseURL` or `*ApiKeyEnv` sends only the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) as `Authorization: Bearer` to its `*BaseURL` (`https://api.deepseek.com/v1/tools` when unset) on every route, and never the account token. Without the key, the operation fails with a diagnostic that names the reference and the `*ApiKeyEnv` field.
-- **Account credential.** The operation sends the credential `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. With the `deepseek-account` model route mounted, the endpoint is under the origin of the base URL that route publishes through `ctx.llm.providerCredential`; without that route, it is under the origin `DEEPSEEK_BASE_URL` names, `https://api.deepseek.com` by default. No sign-in or no account service means no credential. A failed credential read fails the operation without trying another credential. A mounted route whose settings do not resolve, or a `DEEPSEEK_BASE_URL` that is not an HTTP(S) URL without credentials, fails the operation before the credential is read when the operation reaches this source.
-- **API key.** With the `deepseek-official` model route mounted, the operation sends the key that route publishes through `ctx.llm.providerCredential`, read under the route's `apiKeyEnv` (`DEEPSEEK_API_KEY` by default), as `Authorization: Bearer` to the origin of the route's base URL. Without that route, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. A mounted route whose settings do not resolve fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`.
-- **`auto` billing** follows the conversation. On the `deepseek-account` route it sends the account credential, and without one the API key; without the account route, only the API key. On the `deepseek-official` route it sends only the API key. On any other route or outside a Session it sends the API key, and without a key the account credential; without a key, a mounted account route whose settings do not resolve fails the operation.
+- **Account credential.** The operation sends the credential `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. With the `deepseek-account` model route mounted, the endpoint is under the origin of that route's base URL; without that route, it is under the origin `DEEPSEEK_BASE_URL` names, `https://api.deepseek.com` by default. No sign-in or no account service means no credential. A failed credential read fails the operation without trying another credential. A mounted route whose settings do not resolve, or a `DEEPSEEK_BASE_URL` that is not an HTTP(S) URL without credentials, fails the operation before the credential is read when the operation reaches this source.
+- **API key.** With the `deepseek-official` model route mounted, the operation sends that route's key, read under the route's `apiKeyEnv` (`DEEPSEEK_API_KEY` by default), as `Authorization: Bearer` to the origin of the route's base URL. Without that route, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. A mounted route whose settings do not resolve fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`.
+- **`auto` billing** follows the conversation. On the mounted `deepseek-account` route it sends the account credential, and without one the API key. On the mounted `deepseek-official` route it sends only the API key. On any other route, on either of those route ids while its plugin is not mounted, or outside a Session it sends the API key, and without a key the account credential; without a key, a mounted account route whose settings do not resolve fails the operation.
- **`account` billing** sends only the account credential on every route, and **`api-key` billing** only the API key; neither falls back to the other credential.
Without a credential, the operation fails with a diagnostic for its billing that names the missing sign-in or the Models page and the key reference, and the `*Billing` field on the Web search and fetch settings page.
-Keys the operation reads itself, `DEEPSEEK_API_KEY` without the API-key route and the own `*ApiKeyEnv`, go through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): `ctx.credentials` is authoritative, with launch-environment lookup only when that service is absent. Route keys and own keys receive the same whitespace normalization and format validation as model requests; malformed keys fail before dispatch.
+`ctx.deepseekAuth` reads every key, the API-key route's, `DEEPSEEK_API_KEY` without that route, and the own `*ApiKeyEnv`, through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): `ctx.credentials` is authoritative, with launch-environment lookup only when that service is absent. Every key receives the same whitespace normalization and format validation as model requests; malformed keys fail before dispatch.
-Each provider's `ready()` answers whether its next operation for that route has a credential, in the order its billing resolves them: a route credential its route reports configured for the endpoint, an account credential the account service releases for the endpoint, or a key that `ctx.credentials.describe` reports configured (without that service, the launch environment must carry it). A failed credential or credential-store read, or a needed route whose settings do not resolve, answers false. While these providers are selected, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and `web_fetch` with their prompt guidance from each request for which they answer false. Only presence is checked: a wrong key counts as ready and fails each call.
+Each provider's `ready()` answers whether its next operation for that route has a credential, in the order its billing resolves them: an account credential the account service releases for the endpoint, or a key that `ctx.credentials.describe` reports configured (without that service, the launch environment must carry it). A failed credential or credential-store read, or a needed route whose settings do not resolve, answers false. While these providers are selected, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and `web_fetch` with their prompt guidance from each request for which they answer false. Only presence is checked: a wrong key counts as ready and fails each call.
### Results and failures
The Search API receives `query`, `count` (the configured count, or the request's smaller `maxResults`), `need_content: false`, and, unless `sendOriginalQuestion` is off, `ori_question`: the text of the initiating Session's latest human prompt with whitespace collapsed and cut to 128 characters. A search outside a Session or without such a prompt omits it. The provider maps `results[].snippet` as the display excerpt and `results[].summary` as the model-facing excerpt, and maps nullable `date` to optional `publishedAt`; `dsh-tool-web` caps each summary. An empty results array is successful. Fetch sends `url` and returns the original Markdown as a text body with HTTP status 200, because the API answers with an error status when the target yields no usable content. Its URL is the requested URL: the API reports no final redirected URL.
-An unparseable own base URL makes that capability's provider unavailable; and a `count` outside 1 to 50 makes Search unavailable. A missing credential fails with `WEB_PROVIDER_CREDENTIAL_MISSING`; a needed model route whose settings do not resolve fails with `WEB_PROVIDER_MISCONFIGURED`, naming the resolver failure, the Models page, and the capability's `*BaseURL` and `*ApiKeyEnv`; cancellation uses `WEB_ABORTED`; transport, HTTP, and malformed response failures use `WEB_PROVIDER_ERROR`. A request ends when the credential it carries is withdrawn, as an account sign-out does through the grant's `revoked` signal: it fails with `WEB_PROVIDER_ERROR` and guidance to sign in again, or for another credential kind to check that credential on the Models page, unless the caller cancelled as well, which stays `WEB_ABORTED`. Redirects are rejected before contacting their target. Non-success Fetch API statuses are retrieval failures, not target-page statuses. Account-authenticated HTTP 401 responses invalidate only the token sent by that request and provide sign-in guidance; a newer sign-in is preserved, and credential-removal failure does not replace the HTTP error. API-key failures and HTTP 403 never invalidate an account token; other dispatch failures identify the endpoint and say where it came from: for a route endpoint they guide the user to that provider's base URL on the Models page or to the capability's `*BaseURL` and `*ApiKeyEnv`, and for own settings to correcting or removing those fields. No automatic retry or provider fallback occurs.
+An own base URL that does not parse or that embeds credentials makes that capability's provider unavailable; and a `count` outside 1 to 50 makes Search unavailable. A missing credential fails with `WEB_PROVIDER_CREDENTIAL_MISSING`; a needed model route whose settings do not resolve fails with `WEB_PROVIDER_MISCONFIGURED`, naming the resolver failure, the Models page, and the capability's `*BaseURL` and `*ApiKeyEnv`; cancellation uses `WEB_ABORTED`; transport, HTTP, and malformed response failures use `WEB_PROVIDER_ERROR`. A request ends when the credential it carries is withdrawn, as an account sign-out does through the authorization's `revoked` signal: it fails with `WEB_PROVIDER_ERROR` and guidance to sign in again, or for another credential kind to check that credential on the Models page, unless the caller cancelled as well, which stays `WEB_ABORTED`. Redirects are rejected before contacting their target. Non-success Fetch API statuses are retrieval failures, not target-page statuses. Account-authenticated HTTP 401 responses invalidate only the token sent by that request and provide sign-in guidance; a newer sign-in is preserved, and credential-removal failure does not replace the HTTP error. API-key failures and HTTP 403 never invalidate an account token; other dispatch failures identify the endpoint and say where it came from: for a route endpoint they guide the user to that provider's base URL on the Models page or to the capability's `*BaseURL` and `*ApiKeyEnv`, and for own settings to correcting or removing those fields. No automatic retry or provider fallback occurs.
-----
@@ -84,7 +85,7 @@ An unparseable own base URL makes that capability's provider unavailable; and a
Implementation internals — click to expand
-The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the credentials the mounted DeepSeek model routes publish through `ctx.llm.providerCredential` into the operation's ordered credentials, each bound to the API base it is sent to. The [Search provider](src/search.ts) validates response JSON before returning service results; the [Fetch provider](src/fetch.ts) validates the Markdown body. The [transport](src/transport.ts) reads those credentials in order, sends one request with the first present one, and owns cancellation, redirect rejection, and failure guidance; a recording hook runs before dispatch and prevents it by throwing. Search and Fetch API calls emit no auxiliary request event. The [Messages search provider](../web-search-deepseek/README.md) owns its `web/deepseek-search-llm-request` Session event declaration and recording. Tool calls and results retain their normal Session logging.
+The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and asks [`ctx.deepseekAuth`](../../account/deepseek-auth/README.md) with one capability's settings snapshot and the conversation's route for the operation's ordered credentials, each bound to the endpoint it is sent to. The plugin words the failures of a missing credential and of settings that do not resolve. The [Search provider](src/search.ts) validates response JSON before returning service results; the [Fetch provider](src/fetch.ts) validates the Markdown body. The [transport](src/transport.ts) reads those credentials in order, sends one request with the headers of the first present one, and owns cancellation, redirect rejection, and failure guidance; a recording hook runs before dispatch and prevents it by throwing. Search and Fetch API calls emit no auxiliary request event. The [Messages search provider](../web-search-deepseek/README.md) owns its `web/deepseek-search-llm-request` Session event declaration and recording. Tool calls and results retain their normal Session logging.
See the [web subsystem](../../../docs/subsystems/web.md) for service types and [tool-web](../tool-web/README.md) for bounded model output.
@@ -132,7 +133,7 @@ A returning or removed web tool changes the declared tools as [`dsh-tool-web`](.
- API query and URL constraints are enforced by the remote service. An unresolvable Fetch target returned HTTP 500 rather than the documented 404 on 2026-10-16, and its failure carries the same endpoint guidance as an endpoint failure. Fetch exposes neither the target status nor the final redirect URL, so results report HTTP 200 and the requested URL; the provider discards the API's page title.
- `available()` cannot query asynchronous credential stores; `ready()` does, so model steps withhold the tools when the store lacks the key. A direct `ctx.web.search()` or `ctx.web.fetch()` call can still fail with a missing-credential error.
- Search pacing limits send times within one plugin instance. Other processes and clients on the same account share the account-wide 5 QPS limit without coordination, and network jitter can still bunch arrivals; an HTTP 429 fails that search, and `dsh-tool-web` then fails the whole multi-query call. Fetch is not paced, so parallel `web_fetch` calls can exceed the Fetch limit.
-- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.providerCredential`. An adapter that publishes no credential, such as a test replay adapter, or a credential of the other kind (an account credential as `deepseek-official`, an API key as `deepseek-account`) counts as no route: its conversations use `DEEPSEEK_API_KEY` and the official base, and `account` billing asks the account service as it does without the account route.
+- Route endpoints, credentials, and the `auto` order follow what the `llm-deepseek-api-key` and `llm-deepseek-account` plugins connect to `ctx.deepseekAuth`. Another adapter registered as `deepseek-official` or `deepseek-account`, such as a test replay adapter, counts as no DeepSeek route: under `auto` billing its conversations send `DEEPSEEK_API_KEY` to the official base and, without a key, the account credential, and `account` billing asks the account service as it does without the account route.
### Dev Note
diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md
index bcc91f5444..1065f6975a 100644
--- a/packages/web/web-deepseek-api/README.zh.md
+++ b/packages/web/web-deepseek-api/README.zh.md
@@ -24,13 +24,14 @@ kind: "package-reference"
## 使用此包
-将插件与 `dsh-web` 一起挂载,并选择它的提供方。内置配置挂载此插件,为搜索选择它的 Search API(`deepseek-search-api`),为抓取选择本地 HTTP 抓取。在**插件 > 内置插件配置 > 网页搜索与获取**中,在**搜索**下拉框选择 **DeepSeek Search API** 会选中 `deepseek-search-api`,在**获取**下拉框选择 **DeepSeek Fetch API** 会选中 `deepseek-fetch-api`;两个下拉框分别保存,选择其他条目即改用其他提供方。下拉框选中这两个提供方之一时,其下方的**计费方式**下拉框写入 `searchBilling` 或 `fetchBilling`:**自动**、**已登录的 DeepSeek 账号**或 **DeepSeek API Key**。保存的选择从下一次操作开始生效。
+将插件与 `dsh-web` 以及为它释放凭据的 [`dsh-deepseek-auth`](../../account/deepseek-auth/README.zh.md) 一起挂载,并选择它的提供方。内置配置挂载此插件,为搜索选择它的 Search API(`deepseek-search-api`),为抓取选择本地 HTTP 抓取。在**插件 > 内置插件配置 > 网页搜索与获取**中,在**搜索**下拉框选择 **DeepSeek Search API** 会选中 `deepseek-search-api`,在**获取**下拉框选择 **DeepSeek Fetch API** 会选中 `deepseek-fetch-api`;两个下拉框分别保存,选择其他条目即改用其他提供方。下拉框选中这两个提供方之一时,其下方的**计费方式**下拉框写入 `searchBilling` 或 `fetchBilling`:**自动**、**已登录的 DeepSeek 账号**或 **DeepSeek API Key**。保存的选择从下一次操作开始生效。
```yaml
- name: '@deepseek-ai/dsh-web'
config:
searchProvider: deepseek-search-api
fetchProvider: deepseek-fetch-api
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-web-deepseek-api'
config:
searchBaseURL: https://search.example.test/api/v1/tools
@@ -59,22 +60,22 @@ kind: "package-reference"
Search 与 Fetch 每次操作各自从同一份设置快照解析端点和凭据,因此保存的设置、模型提供方变更、登录或存入的密钥从下一次操作开始生效。会话的路由是发起会话最近一次请求上下文的 `provider`;`ready()` 使用正在准备的模型请求的路由。
- **单独配置。** 设置了非空 `*BaseURL` 或 `*ApiKeyEnv` 的能力在任何路由上都只以 `Authorization: Bearer` 把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为 `https://api.deepseek.com/v1/tools`),从不发送账号令牌。没有该密钥时,操作失败,诊断信息点名该引用和 `*ApiKeyEnv` 字段。
-- **账号凭据。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点释放的凭据;2026-10-16 公网 Search 与 Fetch 路由已接受该凭据。挂载了 `deepseek-account` 模型路由时,端点位于该路由通过 `ctx.llm.providerCredential` 发布的基础地址的 origin 下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 所指 origin 下,默认 `https://api.deepseek.com`。没有登录或没有账号服务都算没有凭据。凭据读取失败时操作失败,不再尝试其他凭据。已挂载路由的设置无法解析,或 `DEEPSEEK_BASE_URL` 不是不含凭据的 HTTP(S) URL 时,操作在轮到该来源时于读取凭据前失败。
-- **API 密钥。** 挂载了 `deepseek-official` 模型路由时,操作以 `Authorization: Bearer` 把该路由通过 `ctx.llm.providerCredential` 发布的密钥(按路由的 `apiKeyEnv` 读取,默认 `DEEPSEEK_API_KEY`)发往该路由基础地址的 origin。没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。已挂载路由的设置无法解析时,每个需要该密钥的操作都在读取密钥前失败,绝不改用官方端点或 `DEEPSEEK_API_KEY`。
-- **`auto` 计费**跟随会话。在 `deepseek-account` 路由上先发送账号凭据,没有凭据时发送 API 密钥;没有账号路由时只发送 API 密钥。在 `deepseek-official` 路由上只发送 API 密钥。在其他路由上或会话之外先发送 API 密钥,没有密钥时发送账号凭据;没有密钥且已挂载的账号路由设置无法解析时,操作失败。
+- **账号凭据。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点释放的凭据;2026-10-16 公网 Search 与 Fetch 路由已接受该凭据。挂载了 `deepseek-account` 模型路由时,端点位于该路由基础地址的 origin 下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 所指 origin 下,默认 `https://api.deepseek.com`。没有登录或没有账号服务都算没有凭据。凭据读取失败时操作失败,不再尝试其他凭据。已挂载路由的设置无法解析,或 `DEEPSEEK_BASE_URL` 不是不含凭据的 HTTP(S) URL 时,操作在轮到该来源时于读取凭据前失败。
+- **API 密钥。** 挂载了 `deepseek-official` 模型路由时,操作以 `Authorization: Bearer` 把该路由的密钥(按路由的 `apiKeyEnv` 读取,默认 `DEEPSEEK_API_KEY`)发往该路由基础地址的 origin。没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。已挂载路由的设置无法解析时,每个需要该密钥的操作都在读取密钥前失败,绝不改用官方端点或 `DEEPSEEK_API_KEY`。
+- **`auto` 计费**跟随会话。在已挂载的 `deepseek-account` 路由上先发送账号凭据,没有凭据时发送 API 密钥。在已挂载的 `deepseek-official` 路由上只发送 API 密钥。在其他路由上、在这两个路由 id 之一而其插件未挂载时,或在会话之外,先发送 API 密钥,没有密钥时发送账号凭据;没有密钥且已挂载的账号路由设置无法解析时,操作失败。
- **`account` 计费**在任何路由上只发送账号凭据,**`api-key` 计费**只发送 API 密钥;两者都不回退到另一种凭据。
没有凭据时,操作失败,诊断信息按计费方式点名缺少的登录或模型页面与密钥引用,以及网页搜索与获取设置页上的 `*Billing` 字段。
-操作自行读取的密钥——没有 API 密钥路由时的 `DEEPSEEK_API_KEY` 和单独配置的 `*ApiKeyEnv`——通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:`ctx.credentials` 具有权威性,仅在该服务缺席时读取启动环境。路由密钥与单独配置的密钥均接受与模型请求相同的首尾空白规范化和格式校验;格式错误在发送请求前失败。
+`ctx.deepseekAuth` 读取每一把密钥——API 密钥路由的密钥、没有该路由时的 `DEEPSEEK_API_KEY` 和单独配置的 `*ApiKeyEnv`——都通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数:`ctx.credentials` 具有权威性,仅在该服务缺席时读取启动环境。每把密钥均接受与模型请求相同的首尾空白规范化和格式校验;格式错误在发送请求前失败。
-每个提供者的 `ready()` 按其计费方式的解析顺序回答其在该路由上的下一次操作是否有凭据:路由报告为该端点已配置的路由凭据、账号服务为该端点释放的账号凭据,或 `ctx.credentials.describe` 报告已配置的密钥(没有该服务时,启动环境必须包含它)。凭据或凭据存储读取失败,或所需路由的设置无法解析时,回答 false。这两个提供者被选中时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它们回答 false 的每个请求中撤下 `web_search` 与 `web_fetch` 及其提示词指引。只检查是否存在:错误的密钥仍算就绪,并使每次调用失败。
+每个提供者的 `ready()` 按其计费方式的解析顺序回答其在该路由上的下一次操作是否有凭据:账号服务为该端点释放的账号凭据,或 `ctx.credentials.describe` 报告已配置的密钥(没有该服务时,启动环境必须包含它)。凭据或凭据存储读取失败,或所需路由的设置无法解析时,回答 false。这两个提供者被选中时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它们回答 false 的每个请求中撤下 `web_search` 与 `web_fetch` 及其提示词指引。只检查是否存在:错误的密钥仍算就绪,并使每次调用失败。
### 结果与失败
Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 `maxResults`)、`need_content: false`,以及在 `sendOriginalQuestion` 未关闭时的 `ori_question`:发起会话中最近一条用户提示的文本,空白折叠后截取至 128 个字符。在会话之外或没有此类提示的搜索不发送该字段。提供者将 `results[].snippet` 映射为展示用摘录,将 `results[].summary` 映射为面向模型的摘录,并将可为 null 的 `date` 映射为可选的 `publishedAt`;`dsh-tool-web` 限制每条摘要的长度。空结果数组表示成功。Fetch 发送 `url`,以文本正文返回原始 Markdown,并报告 HTTP 状态 200,因为目标没有可用内容时 API 会返回错误状态。返回 URL 为请求 URL:API 不报告重定向后的最终 URL。
-单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。请求携带的凭据被撤回时(例如账号退登通过授权的 `revoked` 信号撤回),请求随即结束:以 `WEB_PROVIDER_ERROR` 失败并提供重新登录的指引,其他种类的凭据则指引用户在模型页面检查该凭据;调用方同时取消时仍为 `WEB_ABORTED`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。
+单独配置的基础地址无法解析或内嵌凭据时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。请求携带的凭据被撤回时(例如账号退登通过授权的 `revoked` 信号撤回),请求随即结束:以 `WEB_PROVIDER_ERROR` 失败并提供重新登录的指引,其他种类的凭据则指引用户在模型页面检查该凭据;调用方同时取消时仍为 `WEB_ABORTED`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。
-----
@@ -84,7 +85,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的
实现细节 — 点击展开
-[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由,以及已挂载的 DeepSeek 模型路由通过 `ctx.llm.providerCredential` 发布的凭据转换为该操作的有序凭据,每个凭据都绑定其发往的 API 基础地址。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)按顺序读取这些凭据,用第一个存在的凭据发送一次请求,并负责取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。
+[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并带着一个能力的设置快照和会话的路由向 [`ctx.deepseekAuth`](../../account/deepseek-auth/README.zh.md) 索取该操作的有序凭据,每个凭据都绑定其发往的端点。缺少凭据和设置无法解析这两类失败的措辞由插件负责。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)按顺序读取这些凭据,用第一个存在的凭据的请求头发送一次请求,并负责取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。
服务类型见 [Web 子系统](../../../docs/subsystems/web.zh.md),受限的模型输出见 [tool-web](../tool-web/README.zh.md)。
@@ -132,7 +133,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的
- 查询和 URL 约束由远端服务执行。2026-10-16 抓取无法解析的目标域名时返回 HTTP 500,而非文档所述的 404,其失败信息与端点失败附带相同的端点指引。Fetch 既不暴露目标状态,也不暴露最终重定向 URL,因此结果报告 HTTP 200 和请求 URL;提供者丢弃 API 返回的页面标题。
- `available()` 无法查询异步凭据存储;`ready()` 可以,因此凭据存储缺少密钥时,模型步骤会撤下这两个工具。直接调用 `ctx.web.search()` 或 `ctx.web.fetch()` 仍可能因凭据缺失失败。
- Search 限速只约束单个插件实例内的发送时间。同一账号下的其他进程和客户端共享账号级 5 QPS 限制,彼此不协调,网络抖动也可能使请求集中到达;HTTP 429 会使该次搜索失败,随后 `dsh-tool-web` 会使整个多查询调用失败。Fetch 不限速,因此并行的 `web_fetch` 调用可能超过 Fetch 限制。
-- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.providerCredential` 发布的内容。不发布凭据的适配器(例如测试回放适配器),或发布另一种凭据的适配器(以 `deepseek-official` 发布账号凭据,或以 `deepseek-account` 发布 API 密钥),都视为没有路由:其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址,`account` 计费则像没有账号路由时一样询问账号服务。
+- 路由端点、凭据与 `auto` 顺序只认 `llm-deepseek-api-key` 和 `llm-deepseek-account` 插件登记到 `ctx.deepseekAuth` 的内容。以 `deepseek-official` 或 `deepseek-account` 注册的其他适配器(例如测试回放适配器)不算 DeepSeek 路由:在 `auto` 计费下,其会话把 `DEEPSEEK_API_KEY` 发往官方基础地址,没有密钥时发送账号凭据;`account` 计费则像没有账号路由时一样询问账号服务。
### 开发备注
diff --git a/packages/web/web-deepseek-api/package.json b/packages/web/web-deepseek-api/package.json
index adbaddf25d..a6169a0f37 100644
--- a/packages/web/web-deepseek-api/package.json
+++ b/packages/web/web-deepseek-api/package.json
@@ -35,11 +35,10 @@
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-agent": "workspace:*",
"@deepseek-ai/dsh-credentials": "workspace:*",
- "@deepseek-ai/dsh-deepseek-account": "workspace:*",
- "@deepseek-ai/dsh-launch-environment": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
- "@deepseek-ai/dsh-web": "workspace:*"
+ "@deepseek-ai/dsh-web": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"dependencies": {
"@deepseek-ai/schemastery": "workspace:~"
@@ -59,11 +58,7 @@
"@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
"@deepseek-ai/dsh-session-projection": "workspace:*",
- "@deepseek-ai/dsh-web": "workspace:*"
- },
- "peerDependenciesMeta": {
- "@deepseek-ai/dsh-deepseek-account": {
- "optional": true
- }
+ "@deepseek-ai/dsh-web": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/web/web-deepseek-api/src/fetch.ts b/packages/web/web-deepseek-api/src/fetch.ts
index 17286454dc..52cd9ab0ea 100644
--- a/packages/web/web-deepseek-api/src/fetch.ts
+++ b/packages/web/web-deepseek-api/src/fetch.ts
@@ -14,7 +14,7 @@ export const DEEPSEEK_FETCH_API_PROVIDER_ID = 'deepseek-fetch-api'
/** Authentication and endpoint settings snapshotted for one fetch. */
export interface DeepSeekFetchApiOptions {
- /** Ordered authentication sources of the fetch; `/fetch` is appended to the base of the source sent. */
+ /** Ordered authentication sources of the fetch, each bound to the Fetch endpoint its credential is sent to. */
auth: DeepSeekWebAuth
/** Settings that endpoint failures of the fetch name. */
guidance: DeepSeekWebGuidance
@@ -43,15 +43,12 @@ export class DeepSeekFetchApiProvider implements WebFetchProvider {
constructor(private readonly resolveOptions: () => DeepSeekFetchApiOptions) {}
available(): boolean {
- const options = this.resolveOptions()
- return hasDeepSeekWebCredential(options.auth)
- && options.auth.sources.every(source => source.kind === 'misconfigured' || URL.canParse(source.baseURL))
+ return hasDeepSeekWebCredential(this.resolveOptions().auth)
}
fetch(request: WebFetchRequest, signal?: AbortSignal): Promise {
const options = this.resolveOptions()
return dispatchDeepSeekWeb(options.auth, {
- path: '/fetch',
body: { url: request.url },
decode: (payload): WebFetchResult => {
if (!isRecord(payload) || typeof payload.content !== 'string') throw invalidResponse()
diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts
index 53da7fdbdf..bf949f217f 100644
--- a/packages/web/web-deepseek-api/src/index.ts
+++ b/packages/web/web-deepseek-api/src/index.ts
@@ -2,16 +2,16 @@
* Register the DeepSeek Search and Fetch APIs in `ctx.web` as `deepseek-search-api` and `deepseek-fetch-api`. Each
* operation is one direct API request without an auxiliary model request. `web.searchProvider` and `web.fetchProvider`
* select them. Each capability's billing setting chooses its credential. `auto` follows the conversation: a Session
- * whose latest model request used the `deepseek-account` route sends the account credential to that route's origin and
- * otherwise the API key; one on the `deepseek-official` route sends the API key; any other operation sends the API key
- * and, without a key, the signed-in account's credential. `account` sends only the account credential and `api-key`
- * only the API key. Each mounted DeepSeek model route publishes its credential and base URL through
- * `ctx.llm.providerCredential()`: the API key is that of the `deepseek-official` route, sent to its origin, or
- * `DEEPSEEK_API_KEY` sent to the official base without that route; the account credential is that of the
- * `deepseek-account` route, sent to its origin, or outside an account conversation without that route the signed-in
- * account's credential sent to the origin `DEEPSEEK_BASE_URL` names, by default the official one. An operation that
- * needs a mounted route whose settings do not resolve fails instead of changing its endpoint or credential. A capability
- * with its own `*BaseURL` or `*ApiKeyEnv` uses only that endpoint and key instead, whatever its billing
+ * whose latest model request used the mounted `deepseek-account` route sends the account credential to that route's
+ * origin and otherwise the API key; one on the mounted `deepseek-official` route sends the API key; any other
+ * operation, including one on either route id while its plugin is not mounted, sends the API key and, without a key,
+ * the signed-in account's credential. `account` sends only the account credential and `api-key` only the API key.
+ * `ctx.deepseekAuth` orders the two kinds and binds each to its deployment: the API key is that of the mounted
+ * `deepseek-official` route, sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base without that route;
+ * the account credential is sent to the origin of the mounted `deepseek-account` route, or without that route to the
+ * origin `DEEPSEEK_BASE_URL` names, by default the official one. An operation that needs a mounted route whose
+ * settings do not resolve fails instead of changing its endpoint or credential. A capability with its own `*BaseURL`
+ * or `*ApiKeyEnv` uses only that endpoint and key instead, whatever its billing
* ([rationale](../../../../.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md#credential-resolution)).
* Both providers report themselves not ready when their next operation would have no credential.
* @module @deepseek-ai/dsh-web-deepseek-api
@@ -19,10 +19,8 @@
import type { Context, Volatile } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type {} from '@deepseek-ai/dsh-agent'
-import { credentialRef, credentialRefConfigured, resolveCredentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials'
-import type {} from '@deepseek-ai/dsh-deepseek-account'
-import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
-import { assertUsableApiKey, type LlmCredentialKind } from '@deepseek-ai/dsh-llm'
+import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import type { DeepSeekAuthCandidate, DeepSeekAuthKind, DeepSeekAuthUnresolved } from '@deepseek-ai/dsh-deepseek-auth'
import { extractTextContent } from '@deepseek-ai/dsh-llm/message'
import type { Session } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-web'
@@ -45,8 +43,8 @@ export type { DeepSeekSearchApiOptions } from './search.ts'
/** Cordis plugin name used by loader diagnostics. */
export const name = 'web-deepseek-api'
-/** The web seam both providers register into. */
-export const inject = ['web']
+/** The web seam both providers register into, and the DeepSeek authentication their operations ask for credentials. */
+export const inject = ['web', 'deepseekAuth']
/**
* Settings read by the next search or fetch without re-registering either provider. A non-empty `*BaseURL` or
@@ -119,23 +117,12 @@ const TOOLS_PATH = '/v1/tools'
/** Credential reference of the official DeepSeek API key. */
const DEEPSEEK_API_KEY = credentialRef('DEEPSEEK_API_KEY')
-/** Provider id of the DeepSeek account route. */
-const ACCOUNT_PROVIDER = 'deepseek-account'
-
-/** Provider id of the DeepSeek API-key route. */
-const OFFICIAL_PROVIDER = 'deepseek-official'
-
-/** Model route whose published credential an operation can send. */
-type RouteName = typeof ACCOUNT_PROVIDER | typeof OFFICIAL_PROVIDER
-
-/**
- * Credential kind each DeepSeek model route publishes. Billing chooses between the two kinds by route id, so an
- * adapter registered under one of these ids that publishes the other kind is not that route.
- */
-const ROUTE_CREDENTIAL_KIND = {
- [ACCOUNT_PROVIDER]: 'account',
- [OFFICIAL_PROVIDER]: 'api-key',
-} as const satisfies Record
+/** Rule of an `auto` billing by the credential kind that bills the conversation's model route. */
+const CONVERSATION_RULE = {
+ 'account': 'account-conversation',
+ 'api-key': 'official-conversation',
+ 'other': 'other-conversation',
+} as const satisfies Record
/**
* Launch-environment variable naming the DeepSeek deployment the model routes default to. Without the account route,
@@ -177,7 +164,7 @@ export function apply(ctx: Context, config: Config): void {
const current = (capability: Capability) =>
target(capability, ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider)
const ready = (capability: Capability) => (llmProvider: string | undefined): Promise =>
- isDeepSeekWebAuthReady(target(capability, llmProvider).auth, CAPABILITY[capability].path)
+ isDeepSeekWebAuthReady(target(capability, llmProvider).auth)
const searchApi = new DeepSeekSearchApiProvider(() => ({
...current('search'),
count: config.count.get(),
@@ -204,9 +191,10 @@ export function apply(ctx: Context, config: Config): void {
}
/**
- * Resolve the ordered credentials and endpoint guidance of one capability without reading credential values. Route
- * endpoints use the origin of the route's published base URL with `/v1/tools`.
- * @param ctx - context with the model, credential, and account services.
+ * Resolve the ordered credentials and endpoint guidance of one capability without reading credential values.
+ * `ctx.deepseekAuth` orders the credential kinds and binds each to the capability's path under the origin of its
+ * deployment.
+ * @param ctx - context with the DeepSeek authentication service.
* @param capability - the capability being resolved.
* @param own - the capability's own base URL and credential reference, where empty values count as unset, and its
* billing.
@@ -217,133 +205,66 @@ function resolveTarget(
ctx: Context, capability: Capability,
own: { baseURL: string | undefined; ref: string | undefined; billing: Billing }, llmProvider: string | undefined,
): { auth: DeepSeekWebAuth; guidance: DeepSeekWebGuidance } {
- const { subject, prefix } = CAPABILITY[capability]
+ const { subject, prefix, path } = CAPABILITY[capability]
const guidance = (custom: boolean): DeepSeekWebGuidance =>
({ subject, plugin: name, custom, baseURLField: `${prefix}BaseURL`, apiKeyEnvField: `${prefix}ApiKeyEnv` })
const ownBaseURL = nonEmpty(own.baseURL), ownRef = nonEmpty(own.ref)
if (ownBaseURL !== undefined || ownRef !== undefined) {
- const ref = ownRef === undefined ? DEEPSEEK_API_KEY : credentialRef(ownRef)
- const json = JSON.stringify(ref)
+ const reference = ownRef === undefined ? DEEPSEEK_API_KEY : credentialRef(ownRef)
+ const baseURL = ownBaseURL ?? DEEPSEEK_WEB_API_BASE_URL
+ const json = JSON.stringify(reference)
+ // A base URL that does not parse, or that embeds credentials, leaves no source, so the provider is unavailable.
+ const sources = ctx.deepseekAuth.candidates({
+ consumer: name, accepts: ['api-key'], billing: 'api-key',
+ destination: { url: `${baseURL.replace(/\/+$/u, '')}${path}` }, connections: { 'api-key': { baseURL, reference } },
+ }).filter(isCandidate)
return { guidance: guidance(true), auth: {
- sources: [apiKeySource(ctx, ownBaseURL ?? DEEPSEEK_WEB_API_BASE_URL, ref)],
+ sources,
missingCredentialMessage: `DeepSeek ${subject} API sends the API key under ${json} to its own endpoint, and no key is`
+ ` configured for ${json}. Guide the user to export ${json} in the launching environment, or to correct`
+ ` ${name}.${prefix}ApiKeyEnv.`,
} }
}
- const rule: Rule = own.billing !== 'auto' ? own.billing
- : llmProvider === ACCOUNT_PROVIDER ? 'account-conversation'
- : llmProvider === OFFICIAL_PROVIDER ? 'official-conversation' : 'other-conversation'
- const sources = ruleSources(ctx, capability, rule)
- const ref: string = sources.flatMap(keyReference)[0] ?? DEEPSEEK_API_KEY
- return { guidance: guidance(false), auth: { sources, missingCredentialMessage: missingMessage(capability, rule, ref) } }
-}
-
-/**
- * The credentials one rule tries, in order.
- * @param ctx - context with the model, credential, and account services.
- * @param capability - the capability whose diagnostics misconfigured sources name.
- * @param rule - the rule.
- * @returns the sources; the account source is absent in an account conversation without a mounted account route.
- */
-function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeekWebAuthSource[] {
- switch (rule) {
- case 'account-conversation': {
- const account = routeSource(ctx, capability, ACCOUNT_PROVIDER)
- return account === undefined ? [officialSource(ctx, capability)] : [account, officialSource(ctx, capability)]
- }
- case 'official-conversation':
- case 'api-key': return [officialSource(ctx, capability)]
- case 'other-conversation': return [officialSource(ctx, capability), accountSource(ctx, capability)]
- case 'account': return [accountSource(ctx, capability)]
- /* v8 ignore next -- the switch is exhaustive. */
- default: return assertNever(rule)
- }
-}
-
-/**
- * The credential a mounted model route publishes, sent to the Search and Fetch APIs under the origin of the route's
- * base URL.
- * @param ctx - context with the optional model service.
- * @param capability - the capability whose diagnostics a misconfigured source names.
- * @param provider - the route.
- * @returns the source; undefined when no mounted route publishes a credential of that route's kind as `provider`; a
- * misconfigured source when the route's settings do not resolve or its published base URL does not parse.
- */
-function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined {
- try {
- const credential = ctx.get('llm')?.providerCredential(provider)
- if (credential === undefined || credential.kind !== ROUTE_CREDENTIAL_KIND[provider]) return undefined
- return { kind: 'route', baseURL: toolsBase(credential.baseURL), credential }
- } catch (error: unknown) {
- return misconfigured(capability, provider, error)
- }
-}
-
-/**
- * The API key of the DeepSeek API-key route sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base
- * without that route.
- * @returns the source, or a misconfigured source when the route's settings do not resolve.
- */
-function officialSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource {
- return routeSource(ctx, capability, OFFICIAL_PROVIDER) ?? apiKeySource(ctx, DEEPSEEK_WEB_API_BASE_URL, DEEPSEEK_API_KEY)
-}
-
-/**
- * The account credential of the DeepSeek account route sent to its origin, or without that route the signed-in
- * account's credential sent to the origin `DEEPSEEK_BASE_URL` names, by default the official one. The account service
- * releases its credential only for destinations it allows.
- * @returns the source, or a misconfigured source when the route's settings or `DEEPSEEK_BASE_URL` do not resolve.
- */
-function accountSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource {
- const route = routeSource(ctx, capability, ACCOUNT_PROVIDER)
- if (route !== undefined) return route
- const configured = nonEmpty(launchEnvironmentOf(ctx).get(DEEPSEEK_BASE_URL_ENV)?.value)
- let baseURL = DEEPSEEK_WEB_API_BASE_URL
- if (configured !== undefined) {
- try { baseURL = toolsBase(deploymentURL(configured)) }
- catch (error: unknown) { return misconfiguredDeployment(capability, error) }
- }
- return { kind: 'route', baseURL, credential: {
- kind: 'account',
- configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined,
- resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined),
+ const candidates = ctx.deepseekAuth.candidates({
+ consumer: name, accepts: ['account', 'api-key'], billing: own.billing, route: llmProvider,
+ destination: { path: `${TOOLS_PATH}${path}` },
+ })
+ const rule: Rule = own.billing !== 'auto' ? own.billing : CONVERSATION_RULE[ctx.deepseekAuth.routeKind(llmProvider) ?? 'other']
+ const ref: string = candidates.filter(isCandidate).find(candidate => candidate.reference !== undefined)?.reference ?? DEEPSEEK_API_KEY
+ return { guidance: guidance(false), auth: {
+ sources: candidates.map(candidate => isCandidate(candidate) ? candidate : unresolved(capability, candidate)),
+ missingCredentialMessage: missingMessage(capability, rule, ref),
} }
}
-/** The key under `ref`, read from the credentials service or the launch environment, sent to `baseURL`. */
-function apiKeySource(ctx: Context, baseURL: string, ref: CredentialRef): DeepSeekWebAuthSource {
- return { kind: 'api-key', baseURL, key: {
- ref,
- configured: () => credentialRefConfigured(ctx, ref),
- resolve: async () => {
- const value = await resolveCredentialRef(ctx, ref)
- return value === undefined ? undefined : assertUsableApiKey(value, name, ref)
- },
- } }
+/** Whether `ctx.deepseekAuth` bound a credential kind to its endpoint, as opposed to a kind whose settings do not resolve. */
+function isCandidate(candidate: DeepSeekAuthCandidate | DeepSeekAuthUnresolved): candidate is DeepSeekAuthCandidate {
+ return !('unresolved' in candidate)
}
-/** The credential reference an API-key source names in missing-credential diagnostics. */
-function keyReference(source: DeepSeekWebAuthSource): string[] {
- switch (source.kind) {
- case 'api-key': return [source.key.ref]
- case 'route': return source.credential.kind === 'api-key' && source.credential.reference !== undefined ? [source.credential.reference] : []
- case 'misconfigured': return []
- /* v8 ignore next -- the switch is exhaustive. */
- default: return assertNever(source)
- }
+/**
+ * The source of a credential kind whose model route settings, or whose deployment in `DEEPSEEK_BASE_URL`, do not
+ * resolve.
+ * @param capability - the capability that stops.
+ * @param candidate - the kind and its failure.
+ * @returns the source whose diagnostic names what failed and both recoveries.
+ */
+function unresolved(capability: Capability, candidate: DeepSeekAuthUnresolved): DeepSeekWebAuthSource {
+ return candidate.unresolved === 'deployment'
+ ? misconfiguredDeployment(capability, candidate.error)
+ : misconfigured(capability, candidate.kind, candidate.error)
}
/**
* The source of a credential whose model route settings do not resolve.
* @param capability - the capability that stops.
- * @param route - the route whose settings failed.
+ * @param kind - the credential kind whose route settings failed.
* @param error - the route's failure.
* @returns the source whose diagnostic names the route and both recoveries.
*/
-function misconfigured(capability: Capability, route: RouteName, error: unknown): DeepSeekWebAuthSource {
- const provider = route === ACCOUNT_PROVIDER ? 'DeepSeek account model provider' : 'DeepSeek API-key model provider'
- const credential = route === ACCOUNT_PROVIDER ? 'the DeepSeek account sign-in' : 'that provider\'s API key'
+function misconfigured(capability: Capability, kind: DeepSeekAuthKind, error: unknown): DeepSeekWebAuthSource {
+ const provider = kind === 'account' ? 'DeepSeek account model provider' : 'DeepSeek API-key model provider'
+ const credential = kind === 'account' ? 'the DeepSeek account sign-in' : 'that provider\'s API key'
return unresolvedSource(capability, `${credential} to the origin of the ${provider}, and that provider's settings do not resolve`,
error, 'correct that provider\'s settings on the Models page or in the deployment configuration')
}
@@ -410,25 +331,6 @@ function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
-/**
- * Accept a deployment base URL that may receive the account credential: HTTP(S) without embedded credentials.
- * @param value - the configured URL.
- * @returns the value.
- * @throws {Error} when the value is not such a URL.
- */
-function deploymentURL(value: string): string {
- const url = new URL(value)
- if (!/^https?:$/u.test(url.protocol) || url.username.length > 0 || url.password.length > 0) {
- throw new Error(`${DEEPSEEK_BASE_URL_ENV} must be an HTTP(S) URL without credentials`)
- }
- return value
-}
-
-/** The Search and Fetch API base under the origin of a Messages base URL. */
-function toolsBase(messagesBaseURL: string): string {
- return `${new URL(messagesBaseURL).origin}${TOOLS_PATH}`
-}
-
/** A string with content, or undefined for an absent or empty value. */
function nonEmpty(value: string | undefined): string | undefined {
return value !== undefined && value.length > 0 ? value : undefined
diff --git a/packages/web/web-deepseek-api/src/search.ts b/packages/web/web-deepseek-api/src/search.ts
index 5ba5d69ae7..5db1687d1c 100644
--- a/packages/web/web-deepseek-api/src/search.ts
+++ b/packages/web/web-deepseek-api/src/search.ts
@@ -26,7 +26,7 @@ const ORIGINAL_QUESTION_MAX_CHARS = 128
/** Authentication, endpoint, and result settings snapshotted for one search. */
export interface DeepSeekSearchApiOptions {
- /** Ordered authentication sources of the search; `/search` is appended to the base of the source sent. */
+ /** Ordered authentication sources of the search, each bound to the Search endpoint its credential is sent to. */
auth: DeepSeekWebAuth
/** Settings that endpoint failures of the search name. */
guidance: DeepSeekWebGuidance
@@ -92,7 +92,6 @@ export class DeepSeekSearchApiProvider implements WebSearchProvider {
available(): boolean {
const options = this.resolveOptions()
return hasDeepSeekWebCredential(options.auth)
- && options.auth.sources.every(source => source.kind === 'misconfigured' || URL.canParse(source.baseURL))
&& isPositiveInteger(options.count) && isPositiveInteger(options.requestsPerSecond)
}
@@ -100,7 +99,6 @@ export class DeepSeekSearchApiProvider implements WebSearchProvider {
const options = this.resolveOptions()
const question = boundedQuestion(options.originalQuestion?.())
return dispatchDeepSeekWeb(options.auth, {
- path: '/search',
body: {
query: request.query,
count: Math.min(options.count, request.maxResults ?? options.count),
diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts
index 7405c1c0da..0f37ff1e14 100644
--- a/packages/web/web-deepseek-api/src/transport.ts
+++ b/packages/web/web-deepseek-api/src/transport.ts
@@ -4,46 +4,18 @@
* ([rationale](../../../../.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md)).
* @module @deepseek-ai/dsh-web-deepseek-api/transport
*/
-import type { CredentialRef } from '@deepseek-ai/dsh-credentials'
-import type { LlmCredentialKind, ProviderCredential } from '@deepseek-ai/dsh-llm'
+import type { DeepSeekAuthCandidate, DeepSeekAuthKind, DeepSeekAuthorization } from '@deepseek-ai/dsh-deepseek-auth'
import { WebError } from '@deepseek-ai/dsh-web'
const USER_AGENT = 'deepseek-harness/0.0.1'
-/** API key of one {@link DeepSeekWebAuthSource}: a credential reference read once per use without retention. */
-export interface DeepSeekWebApiKey {
- /** Credential reference the key is stored under. */
- ref: CredentialRef
- /** Report key presence without reading or validating its value; store failures reject. */
- configured: () => Promise
- /** Read and validate the key; undefined or empty means no key, and store or format failures reject. */
- resolve: () => Promise
-}
-
-/**
- * One credential an operation can send, bound to the API base it is sent to. The operation appends its path, such as
- * `/search`, to `baseURL`.
- */
+/** One credential an operation can send, bound to the endpoint it is sent to. */
export type DeepSeekWebAuthSource =
/**
- * A credential released per use for the dispatch endpoint, as a DeepSeek model route publishes it. An API key is
- * sent as `Authorization: Bearer`; any other kind is sent through the headers of its grant.
+ * A credential kind `ctx.deepseekAuth` bound to the operation's endpoint. It answers presence and releases the
+ * request headers per use; read failures reject.
*/
- | {
- kind: 'route'
- /** API base the credential is sent to, including its path prefix. */
- baseURL: string
- /** The credential's owner: it answers presence and releases a grant for an endpoint, and read failures reject. */
- credential: Omit
- }
- /** An API key, sent as `Authorization: Bearer`. */
- | {
- kind: 'api-key'
- /** API base the key is sent to, including its path prefix. */
- baseURL: string
- /** The key to send. */
- key: DeepSeekWebApiKey
- }
+ | DeepSeekAuthCandidate
/** A credential whose settings do not resolve; reaching it fails the operation with `WEB_PROVIDER_MISCONFIGURED`. */
| {
kind: 'misconfigured'
@@ -79,14 +51,10 @@ export interface DeepSeekWebGuidance {
/** One fully resolved web API request. */
interface DeepSeekWebRequest {
- /** Operation path appended to the base of the source sent, such as `/search`. */
- path: string
/** JSON request body. */
body: object
/** Protocol headers without credentials. */
headers?: Readonly>
- /** Additional headers sent beside an API key; other credential kinds send only their grant's headers. */
- apiKeyHeaders?: (key: string) => Readonly>
/** Validate and project the response. */
decode: (payload: unknown) => T
/** Endpoint recovery settings. */
@@ -100,7 +68,7 @@ interface DeepSeekWebRequest {
/**
* Check synchronously whether an operation has a source to try, without reading credentials.
* @param auth - Sources for the operation.
- * @returns Whether any source exists: a route credential, a credential reference, or a misconfigured source the
+ * @returns Whether any source exists: a credential kind bound to the endpoint, or a misconfigured source the
* operation reports.
*/
export function hasDeepSeekWebCredential(auth: DeepSeekWebAuth): boolean {
@@ -109,31 +77,17 @@ export function hasDeepSeekWebCredential(auth: DeepSeekWebAuth): boolean {
/**
* Check whether an operation would find a credential, reading the sources in the order {@link dispatchDeepSeekWeb}
- * does. A route source asks its credential whether one is configured for the operation's endpoint; a referenced key is
- * only checked for presence, so a malformed or wrong key counts as ready. A misconfigured source or a failed read
- * answers false without reading later sources, because the operation fails there too. Nothing is sent and nothing is
- * retained.
+ * does. Each source is only asked whether a credential is configured, so a malformed or wrong key counts as ready. A
+ * misconfigured source or a failed read answers false without reading later sources, because the operation fails there
+ * too. Nothing is sent and nothing is retained.
* @param auth - Sources for the operation.
- * @param path - Operation path appended to each source's base.
* @returns Whether a source before any misconfigured or unreadable one is present.
*/
-export async function isDeepSeekWebAuthReady(auth: DeepSeekWebAuth, path: '/search' | '/fetch'): Promise {
+export async function isDeepSeekWebAuthReady(auth: DeepSeekWebAuth): Promise {
for (const source of auth.sources) {
- switch (source.kind) {
- case 'misconfigured': return false
- case 'route': {
- try { if (await source.credential.configured(joinPath(source.baseURL, path))) return true }
- catch (_unreadableCredential) { return false /* The operation fails on this read before it tries another source. */ }
- break
- }
- case 'api-key': {
- try { if (await source.key.configured()) return true }
- catch (_unreadableStore) { return false /* The operation fails on this read before it tries another source. */ }
- break
- }
- /* v8 ignore next -- the switch is exhaustive. */
- default: return assertNever(source)
- }
+ if (source.kind === 'misconfigured') return false
+ try { if (await source.configured()) return true }
+ catch (_unreadableCredential) { return false /* The operation fails on this read before it tries another source. */ }
}
return false
}
@@ -153,23 +107,9 @@ export function invalidResponse(): WebError {
return new WebError('DeepSeek returned an invalid response body', 'WEB_PROVIDER_ERROR')
}
-/** Authentication headers and endpoint for one operation, tagged by the kind of credential that produced them. */
-interface SearchAuth {
- /** Kind of the credential sent; an API-key source sends `api-key`. */
- readonly kind: LlmCredentialKind
- /** Absolute dispatch URL under the base of the source. */
- readonly endpoint: string
- /** Headers carrying the credential. */
- readonly headers: Readonly>
- /** Request-bound invalidation of the sent credential, present when its grant offers one; the dispatch contains its failure. */
- readonly reject?: () => Promise
- /** Withdrawal of the sent credential, present when its grant offers one; it ends the request. */
- readonly revoked?: AbortSignal
-}
-
/** Dispatch one operation using a single settings and credential snapshot: one request, with the first present source.
* @param options - Ordered authentication sources for this operation.
- * @param request - Operation path, JSON payload, and response decoder.
+ * @param request - JSON payload and response decoder.
* @param signal - Caller cancellation signal.
* @returns The validated provider result.
*/
@@ -177,7 +117,7 @@ export async function dispatchDeepSeekWeb(
options: DeepSeekWebAuth, request: DeepSeekWebRequest, signal?: AbortSignal,
): Promise {
const { body, decode, recordRequest, guidance } = request
- const auth = await authHeaders(options, request, signal)
+ const auth = await authorize(options, signal)
const { endpoint } = auth
await request.waitToSend?.(signal)
throwIfSearchAborted(signal)
@@ -270,7 +210,7 @@ export async function dispatchDeepSeekWeb(
/**
* The signal one request runs under: the caller's cancellation and the withdrawal of the credential it carries.
* @param signal - caller cancellation, when the caller supplies one.
- * @param revoked - withdrawal of the sent credential, when its grant offers one.
+ * @param revoked - withdrawal of the sent credential, when its authorization offers one.
* @returns the composed signal, or undefined when neither exists.
*/
function requestSignal(signal: AbortSignal | undefined, revoked: AbortSignal | undefined): AbortSignal | undefined {
@@ -285,7 +225,7 @@ function requestSignal(signal: AbortSignal | undefined, revoked: AbortSignal | u
* @param cause - what the interrupted fetch or body read threw.
* @returns the provider failure, with sign-in guidance for an account credential.
*/
-function credentialWithdrawnError(kind: LlmCredentialKind, cause: unknown): WebError {
+function credentialWithdrawnError(kind: DeepSeekAuthKind, cause: unknown): WebError {
return new WebError(
kind === 'account'
? 'The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again;'
@@ -335,46 +275,20 @@ function searchEndpointError(
}
/**
- * Resolve one operation's authentication headers without retaining a credential on the provider.
- * @param auth - the caller's ordered sources, each binding its credential to the base it is sent to.
- * @param request - the resolved request; its path under the source's base is the endpoint.
+ * Release the credential of the first present source without retaining it on the provider.
+ * @param auth - the caller's ordered sources, each bound to the endpoint its credential is sent to.
* @param signal - abort signal for the surrounding operation.
- * @returns the headers and endpoint of the first present source, tagged by credential kind.
+ * @returns the authorization of the first present source.
* @throws {@link WebError} `WEB_PROVIDER_MISCONFIGURED` at a misconfigured source, `WEB_PROVIDER_ERROR` when a read
* fails, `WEB_ABORTED` on cancellation, and `WEB_PROVIDER_CREDENTIAL_MISSING` when no source is present.
*/
-async function authHeaders(
- auth: DeepSeekWebAuth, request: DeepSeekWebRequest, signal?: AbortSignal,
-): Promise {
+async function authorize(auth: DeepSeekWebAuth, signal?: AbortSignal): Promise {
throwIfSearchAborted(signal)
for (const source of auth.sources) {
throwIfSearchAborted(signal)
- switch (source.kind) {
- case 'misconfigured': throw new WebError(source.message, 'WEB_PROVIDER_MISCONFIGURED')
- case 'route': {
- const endpoint = joinPath(source.baseURL, request.path)
- const grant = await resolveCredential(() => source.credential.resolve(endpoint, signal), signal)
- if (grant === undefined) break
- const { kind } = source.credential
- const invalidate = grant.reject?.bind(grant)
- return {
- kind, endpoint,
- headers: kind === 'api-key' ? { ...request.apiKeyHeaders?.(grant.value), authorization: `Bearer ${grant.value}` } : grant.headers,
- ...invalidate === undefined ? {} : { reject: invalidate },
- ...grant.revoked === undefined ? {} : { revoked: grant.revoked },
- }
- }
- case 'api-key': {
- const apiKey = await resolveCredential(source.key.resolve, signal)
- if (apiKey !== undefined && apiKey.length > 0) return { kind: 'api-key', endpoint: joinPath(source.baseURL, request.path), headers: {
- ...request.apiKeyHeaders?.(apiKey),
- 'authorization': `Bearer ${apiKey}`,
- } }
- break
- }
- /* v8 ignore next -- the switch is exhaustive. */
- default: return assertNever(source)
- }
+ if (source.kind === 'misconfigured') throw new WebError(source.message, 'WEB_PROVIDER_MISCONFIGURED')
+ const authorization = await resolveCredential(() => source.resolve(signal), signal)
+ if (authorization !== undefined) return authorization
}
throw new WebError(
auth.missingCredentialMessage ?? 'DeepSeek web access has no credential to send',
@@ -382,18 +296,6 @@ async function authHeaders(
)
}
-/** Append an operation path to an API base, without doubling a trailing slash. */
-function joinPath(baseURL: string, path: string): string {
- return `${baseURL.replace(/\/+$/u, '')}${path}`
-}
-
-/* v8 ignore start -- reached only by a value outside a closed union, which the compiler rejects. */
-/** Reject an unhandled member of a closed union. */
-function assertNever(value: never): never {
- throw new Error(`web-deepseek-api: unexpected credential source ${JSON.stringify(value)}`)
-}
-/* v8 ignore stop */
-
/* jscpd:ignore-start */
/**
* Run one credential resolver under the search's cancellation signal. An
@@ -424,7 +326,12 @@ async function resolveCredential(resolve: () => Promise, signal?: AbortSig
*/
function abortable(operation: Promise, signal?: AbortSignal): Promise {
if (signal === undefined) return operation
- if (signal.aborted) return Promise.reject(searchAborted(signal))
+ if (signal.aborted) {
+ // The operation began before this check and can still reject: a credential read that cancels its caller, then
+ // fails. Observing it keeps that rejection from being unhandled.
+ void operation.catch(() => {})
+ return Promise.reject(searchAborted(signal))
+ }
return new Promise((resolve, reject) => {
const onAbort = (): void => { reject(searchAborted(signal)) }
signal.addEventListener('abort', onAbort, { once: true })
diff --git a/packages/web/web-deepseek-api/tests/composition.spec.ts b/packages/web/web-deepseek-api/tests/composition.spec.ts
index 123d645bc7..3463ecb6d4 100644
--- a/packages/web/web-deepseek-api/tests/composition.spec.ts
+++ b/packages/web/web-deepseek-api/tests/composition.spec.ts
@@ -14,6 +14,7 @@ import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environ
import LlmRuntime from '@deepseek-ai/dsh-llm'
import * as Account from '@deepseek-ai/dsh-llm-deepseek-account'
import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import WebRuntime from '@deepseek-ai/dsh-web'
import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api'
import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts'
@@ -27,6 +28,7 @@ afterEach(async () => {
const MODULES = new Map([
['@deepseek-ai/dsh-llm', LlmRuntime],
+ ['@deepseek-ai/dsh-deepseek-auth', DeepSeekAuth],
['@deepseek-ai/dsh-llm-deepseek-api-key', Official],
['@deepseek-ai/dsh-llm-deepseek-account', Account],
['@deepseek-ai/dsh-web', WebRuntime],
@@ -69,6 +71,7 @@ async function bootComposition(
const configPath = join(root, 'cordis.yml')
await writeFile(configPath, JSON.stringify([
{ id: 'llm', name: '@deepseek-ai/dsh-llm' },
+ { id: 'deepseek-auth', name: '@deepseek-ai/dsh-deepseek-auth' },
{ id: 'llm-deepseek', name: '@deepseek-ai/dsh-llm-deepseek-api-key' },
{ id: 'llm-deepseek-account', name: '@deepseek-ai/dsh-llm-deepseek-account' },
{ id: 'web', name: '@deepseek-ai/dsh-web', config: { searchProvider: 'deepseek-search-api', fetchProvider: 'deepseek-fetch-api' } },
diff --git a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts
index 04082d58e6..a787cd1945 100644
--- a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts
+++ b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts
@@ -8,6 +8,7 @@ import { Context } from '@deepseek-ai/cordis'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts'
import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
@@ -37,7 +38,7 @@ interface Setup {
config?: Record
/** Launch-environment variables. */
environment?: Record
- /** Model routes the provider directory lists. */
+ /** Model routes connected to the authentication service. */
routes?: readonly RouteRow[]
/** Account service stand-in. */
account?: DeepSeekAccount
@@ -70,6 +71,7 @@ async function mount(setup: Setup): Promise<{ ctx: Context; sent: () => Sent[] }
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: setup.environment ?? {} }]))
if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account)
if (setup.credentials !== undefined) ctx.provide('credentials', setup.credentials as never)
+ await ctx.plugin(DeepSeekAuth)
if (setup.routes !== undefined) provideRoutes(ctx, setup.routes)
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
@@ -290,6 +292,24 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => {
expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: null, token: 'account-token' }])
})
+ it.each(['deepseek-account', 'deepseek-official'])('orders route %s as any other route while no plugin connected it', async (route) => {
+ const asked: string[] = []
+ const withKey = await mount({ account: signedIn(asked), environment: { DEEPSEEK_API_KEY: 'chat-key' } })
+ expect(await ready(withKey.ctx, operation, route)).toBe(true)
+ await operate(withKey.ctx, operation, route)
+ expect(withKey.sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: 'Bearer chat-key', token: null }])
+ expect(asked).toEqual([])
+ const signedInOnly = await mount({ account: signedIn() })
+ expect(await ready(signedInOnly.ctx, operation, route)).toBe(true)
+ await operate(signedInOnly.ctx, operation, route)
+ expect(signedInOnly.sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: null, token: 'account-token' }])
+ const neither = await mount({ account: signedOut() })
+ expect(await ready(neither.ctx, operation, route)).toBe(false)
+ const failure = operate(neither.ctx, operation, route)
+ await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING' })
+ await expect(failure).rejects.toThrow('uses the DeepSeek API key, then the DeepSeek account sign-in, and neither is available')
+ })
+
it('is not ready and names both recoveries without a key and a sign-in', async () => {
const subject = operation === 'search' ? 'Search' : 'Fetch'
for (const account of [signedOut(), undefined]) {
@@ -356,7 +376,7 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => {
it.each<[string, readonly RouteRow[] | undefined]>([
['no model service is mounted', undefined],
['no route registers deepseek-official', [accountRoute()]],
- ['the registered deepseek-official adapter publishes no credential', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, withoutCredential: true }]],
+ ['the registered deepseek-official adapter connects no deployment', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, withoutConnection: true }]],
])('sends DEEPSEEK_API_KEY to the official base when %s', async (_label, routes) => {
const { ctx, sent } = await mount({
...routes === undefined ? {} : { routes },
@@ -604,6 +624,7 @@ describe.each(OPERATIONS)('%s with its own endpoint settings', (operation) => {
['only a base URL', { [baseURL]: OWN }, { endpoint: `${OWN}/${operation}`, authorization: 'Bearer chat-key', token: null }],
['only a key reference', { [apiKeyEnv]: 'OWN_KEY' }, { endpoint: `${OFFICIAL}/${operation}`, authorization: 'Bearer own-key', token: null }],
['both', { [baseURL]: OWN, [apiKeyEnv]: 'OWN_KEY' }, { endpoint: `${OWN}/${operation}`, authorization: 'Bearer own-key', token: null }],
+ ['a base URL with trailing slashes', { [baseURL]: `${OWN}//` }, { endpoint: `${OWN}/${operation}`, authorization: 'Bearer chat-key', token: null }],
])('uses %s on every conversation route and never the account token', async (_label, config, expected) => {
const asked: string[] = []
const { ctx, sent } = await mount({
@@ -639,57 +660,13 @@ describe.each(OPERATIONS)('%s with its own endpoint settings', (operation) => {
expect(sent()).toEqual([{ endpoint: `${ACCOUNT}/${operation}`, authorization: null, token: 'account-token' }])
})
- it('reports an unparseable base URL as an unavailable provider', async () => {
- const { ctx, sent } = await mount({ config: { [baseURL]: 'not a url' }, environment: { DEEPSEEK_API_KEY: 'chat-key' } })
+ it.each(['not a url', 'https://user:secret@own.deepseek.test/api/v1/tools'])('reports the base URL %s, which does not parse or embeds credentials, as an unavailable provider', async (value) => {
+ const { ctx, sent } = await mount({ config: { [baseURL]: value }, environment: { DEEPSEEK_API_KEY: 'chat-key' } })
await expect(operate(ctx, operation)).rejects.toMatchObject({ code: 'WEB_PROVIDER_CONFIGURED_UNAVAILABLE' })
expect(sent()).toEqual([])
})
})
-describe.each(OPERATIONS)('%s beside an adapter that publishes the other credential kind under a DeepSeek route id', (operation) => {
- const accountUnderOfficial: RouteRow = { provider: 'deepseek-official', publishes: 'account', config: { baseURL: 'https://route.deepseek.test/anthropic' } }
- const keyUnderAccount: RouteRow = { provider: 'deepseek-account', publishes: 'api-key', config: { baseURL: 'https://account.deepseek.test/anthropic' } }
-
- it.each(['api-key', 'auto'])('sends DEEPSEEK_API_KEY to the official base under %s billing, never the account credential published as the API-key route', async (billing) => {
- const asked: string[] = []
- const { ctx, sent } = await mount({
- config: { [`${operation}Billing`]: billing }, routes: [accountUnderOfficial], account: signedIn(asked),
- environment: { DEEPSEEK_API_KEY: 'chat-key' },
- })
- expect(await ready(ctx, operation, 'deepseek-official')).toBe(true)
- await operate(ctx, operation, 'deepseek-official')
- expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: 'Bearer chat-key', token: null }])
- expect(asked).toEqual([])
- })
-
- it('is not ready under API-key billing without a key, and never sends that account credential', async () => {
- const asked: string[] = []
- const { ctx, sent } = await mount({ config: { [`${operation}Billing`]: 'api-key' }, routes: [accountUnderOfficial], account: signedIn(asked) })
- expect(await ready(ctx, operation, 'deepseek-official')).toBe(false)
- await expect(operate(ctx, operation, 'deepseek-official')).rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING' })
- expect(sent()).toEqual([])
- expect(asked).toEqual([])
- })
-
- it('sends the signed-in account token to the default account origin under account billing, never the API key published as the account route', async () => {
- const { ctx, sent } = await mount({
- config: { [`${operation}Billing`]: 'account' }, routes: [keyUnderAccount], account: signedIn(),
- environment: { DEEPSEEK_API_KEY: 'chat-key' },
- })
- expect(await ready(ctx, operation, 'deepseek-account')).toBe(true)
- await operate(ctx, operation, 'deepseek-account')
- expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: null, token: 'account-token' }])
- })
-
- it('treats a conversation on that account route id as one without an account route under automatic billing', async () => {
- const { ctx, sent } = await mount({ routes: [keyUnderAccount], account: signedIn(), environment: { DEEPSEEK_API_KEY: 'chat-key' } })
- expect(await ready(ctx, operation, 'deepseek-account')).toBe(true)
- await operate(ctx, operation, 'deepseek-account')
- // The key goes to the official base, not to the base URL that adapter publishes.
- expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: 'Bearer chat-key', token: null }])
- })
-})
-
describe('independent capabilities', () => {
it('resolves Search from its own settings while Fetch follows the conversation', async () => {
const { ctx, sent } = await mount({
@@ -722,7 +699,7 @@ describe('independent capabilities', () => {
})
})
-describe('route credential failures', () => {
+describe('model route settings failures', () => {
it('reports a thrown non-Error value as its string', async () => {
const { ctx, sent } = await mount({
routes: [{ provider: 'deepseek-official', throws: 'route resolver unavailable' }], environment: { DEEPSEEK_API_KEY: 'chat-key' },
@@ -733,9 +710,9 @@ describe('route credential failures', () => {
expect(sent()).toEqual([])
})
- it('reports a route publishing an unparsable base URL as misconfigured, before readiness and without sending', async () => {
+ it('reports a route whose base URL does not parse as misconfigured, before readiness and without sending', async () => {
const { ctx, sent } = await mount({
- routes: [{ provider: 'deepseek-official', publishedBaseURL: 'not a url' }], environment: { DEEPSEEK_API_KEY: 'chat-key' },
+ routes: [{ provider: 'deepseek-official', connectedBaseURL: 'not a url' }], environment: { DEEPSEEK_API_KEY: 'chat-key' },
})
expect(await ready(ctx, 'search', 'deepseek-official')).toBe(false)
const failure = operate(ctx, 'search', 'deepseek-official')
diff --git a/packages/web/web-deepseek-api/tests/credentials.spec.ts b/packages/web/web-deepseek-api/tests/credentials.spec.ts
index 4fcae996e9..a4a6dd42ac 100644
--- a/packages/web/web-deepseek-api/tests/credentials.spec.ts
+++ b/packages/web/web-deepseek-api/tests/credentials.spec.ts
@@ -5,6 +5,7 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local'
import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import WebRuntime from '@deepseek-ai/dsh-web'
@@ -28,6 +29,7 @@ function captureAuthorization(): () => (string | null)[] {
async function mount(ctx: Context, config: Record, environment: Record): Promise {
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: environment }]))
await ctx.plugin(WebRuntime, { searchProvider: 'deepseek-search-api' })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(webApiPlugin, config)
}
@@ -79,6 +81,19 @@ describe('web-deepseek-api API-key resolution', () => {
} finally { await ctx.fiber.dispose() }
})
+ it('names the reference of an unusable key, and never the key', async () => {
+ captureAuthorization()
+ const ctx = new Context()
+ try {
+ ctx.provide('credentials', { resolve: async () => ({ value: '非法密钥' }), describe: async () => ({ configured: true }) } as never)
+ await mount(ctx, {}, {})
+ await expect(ctx.web.search({ query: 'q' })).rejects.toThrow(
+ 'DeepSeek web credential resolution failed: DeepSeekAuthError: web-deepseek-api: the API key resolved from DEEPSEEK_API_KEY'
+ + ' contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)',
+ )
+ } finally { await ctx.fiber.dispose() }
+ })
+
it.each(['', 'bad key', '非法密钥'])('rejects malformed stored key %j before dispatch', async (value) => {
const authorization = captureAuthorization()
const ctx = new Context()
diff --git a/packages/web/web-deepseek-api/tests/egress.spec.ts b/packages/web/web-deepseek-api/tests/egress.spec.ts
index cbe81aac8c..c2518d66ab 100644
--- a/packages/web/web-deepseek-api/tests/egress.spec.ts
+++ b/packages/web/web-deepseek-api/tests/egress.spec.ts
@@ -1,9 +1,9 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
-import { credentialRef } from '@deepseek-ai/dsh-credentials'
import { installProxyFromEnvironment } from '@deepseek-ai/dsh-http-proxy'
import { customGuidance } from './guidance.ts'
+import { keyCandidate } from './sources.ts'
let seen: string[] = []
let proxy: Server
@@ -36,7 +36,7 @@ async function observe(run: () => Promise): Promise {
import { DeepSeekSearchApiProvider } from '../src/search.ts'
describe('deepseek search api egress', () => {
it('goes through the proxy', async () => {
- const p = new DeepSeekSearchApiProvider(() => ({ auth: { sources: [{ kind: 'api-key', baseURL: 'http://dsk-probe.invalid/api/v1/tools', key: { ref: credentialRef('PROBE_KEY'), configured: async () => true, resolve: async () => 'probe' } }] }, count: 10, requestsPerSecond: 5, guidance: customGuidance('search') }))
+ const p = new DeepSeekSearchApiProvider(() => ({ auth: { sources: [keyCandidate('http://dsk-probe.invalid/api/v1/tools/search', 'probe', 'PROBE_KEY')] }, count: 10, requestsPerSecond: 5, guidance: customGuidance('search') }))
expect(await observe(() => p.search({ query: 'probe' }))).toEqual(['REQ http://dsk-probe.invalid/api/v1/tools/search'])
})
})
diff --git a/packages/web/web-deepseek-api/tests/fetch.spec.ts b/packages/web/web-deepseek-api/tests/fetch.spec.ts
index 31ef9f6e14..d36338aeec 100644
--- a/packages/web/web-deepseek-api/tests/fetch.spec.ts
+++ b/packages/web/web-deepseek-api/tests/fetch.spec.ts
@@ -1,15 +1,15 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
-import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import WebRuntime from '@deepseek-ai/dsh-web'
import { DeepSeekFetchApiProvider, type DeepSeekFetchApiOptions } from '@deepseek-ai/dsh-web-deepseek-api'
import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api'
import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { customGuidance } from './guidance.ts'
+import { keyCandidate } from './sources.ts'
const fetchProvider = (options: DeepSeekFetchApiOptions) => new DeepSeekFetchApiProvider(() => options)
const BASE = 'https://api.deepseek.test/api/v1/tools'
-const auth = (key: string, baseURL = BASE): DeepSeekFetchApiOptions['auth'] =>
- ({ sources: [{ kind: 'api-key', baseURL, key: { ref: credentialRef('TEST_KEY'), configured: async () => key.length > 0, resolve: async () => key.length > 0 ? key : undefined } }] })
+const auth = (key: string): DeepSeekFetchApiOptions['auth'] => ({ sources: [keyCandidate(`${BASE}/fetch`, key)] })
const options = { auth: auth('ds-key'), guidance: customGuidance('fetch') }
function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, ...init })
@@ -20,7 +20,7 @@ describe('DeepSeek Fetch API', () => {
it('posts the URL and returns the Markdown as a retrieved page', async () => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse({ title: 'Example', content: '# Article\n\nBody' }))
vi.stubGlobal('fetch', fetchMock)
- const provider = fetchProvider({ ...options, auth: auth('ds-key', `${BASE}/`) })
+ const provider = fetchProvider(options)
expect(await provider.fetch({ url: 'https://example.com/article' })).toEqual({
url: 'https://example.com/article', statusCode: 200, body: { kind: 'text', content: '# Article\n\nBody' }, truncated: false,
})
@@ -57,11 +57,10 @@ describe('DeepSeek Fetch API', () => {
+ 'Only the user should choose or change the endpoint.',
})
})
- it('is available only with a credential source and a parseable base', () => {
+ it('is available only with a credential source', () => {
expect(fetchProvider(options).available()).toBe(true)
expect(fetchProvider({ ...options, auth: { sources: [] } }).available()).toBe(false)
expect(fetchProvider({ ...options, auth: auth('') }).available()).toBe(true)
- expect(fetchProvider({ ...options, auth: auth('ds-key', 'not a url') }).available()).toBe(false)
})
it('unregisters both providers with its plugin fiber', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ title: '', content: 'body' })))
@@ -69,6 +68,7 @@ describe('DeepSeek Fetch API', () => {
try {
await ctx.plugin(WebRuntime, { searchProvider: 'deepseek-search-api', fetchProvider: 'deepseek-fetch-api' })
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: { DEEPSEEK_API_KEY: 'ds-key' } }]))
+ await ctx.plugin(DeepSeekAuth)
const fiber = await ctx.plugin(webApiPlugin, { fetchBaseURL: BASE })
await expect(ctx.web.fetch({ url: 'https://example.com' })).resolves.toMatchObject({ body: { content: 'body' } })
await fiber.dispose()
diff --git a/packages/web/web-deepseek-api/tests/redirect.spec.ts b/packages/web/web-deepseek-api/tests/redirect.spec.ts
index f1985a350e..73b565c05f 100644
--- a/packages/web/web-deepseek-api/tests/redirect.spec.ts
+++ b/packages/web/web-deepseek-api/tests/redirect.spec.ts
@@ -6,8 +6,8 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { createServer, type IncomingMessage, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
-import { credentialRef } from '@deepseek-ai/dsh-credentials'
import { customGuidance } from './guidance.ts'
+import { keyCandidate } from './sources.ts'
import { dispatchDeepSeekWeb } from '../src/transport.ts'
const TEST_API_KEY = 'redirect-test-key'
@@ -48,9 +48,8 @@ afterAll(async () => {
describe('dispatchDeepSeekWeb redirect policy', () => {
it.each([301, 302, 303, 307, 308])('rejects HTTP %i before contacting Location', async (status) => {
targetRequests.length = 0
- await expect(dispatchDeepSeekWeb({ sources: [{ kind: 'api-key', baseURL: redirectOrigin, key: { ref: credentialRef('TEST_API_KEY'), configured: async () => true, resolve: async () => TEST_API_KEY } }] }, {
- path: `/${status}`, body: { query: TEST_QUERY }, decode: value => value,
- apiKeyHeaders: key => ({ 'x-api-key': key }),
+ await expect(dispatchDeepSeekWeb({ sources: [keyCandidate(`${redirectOrigin}/${status}`, TEST_API_KEY, 'TEST_API_KEY')] }, {
+ body: { query: TEST_QUERY }, decode: value => value,
guidance: customGuidance('search'),
})).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' })
expect(targetRequests).toHaveLength(0)
@@ -58,11 +57,12 @@ describe('dispatchDeepSeekWeb redirect policy', () => {
it('rejects a redirect of an account-token request before contacting Location', async () => {
targetRequests.length = 0
- const grant = { headers: { 'x-dsh-auth-token': 'redirect-test-token' }, value: 'redirect-test-token' }
+ const endpoint = `${redirectOrigin}/307`
+ const authorization = { kind: 'account', endpoint, headers: { 'x-dsh-auth-token': 'redirect-test-token' } } as const
await expect(dispatchDeepSeekWeb({ sources: [{
- kind: 'route', baseURL: redirectOrigin, credential: { kind: 'account', configured: async () => true, resolve: async () => grant },
+ kind: 'account', endpoint, configured: async () => true, resolve: async () => authorization,
}] }, {
- path: '/307', body: { query: TEST_QUERY }, decode: value => value,
+ body: { query: TEST_QUERY }, decode: value => value,
guidance: customGuidance('search'),
})).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' })
expect(targetRequests).toHaveLength(0)
diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts
index 29f0f426c9..026a656947 100644
--- a/packages/web/web-deepseek-api/tests/routes.ts
+++ b/packages/web/web-deepseek-api/tests/routes.ts
@@ -1,13 +1,11 @@
/**
- * A stand-in model service publishing DeepSeek route credentials the way the route plugins do. It reimplements their
- * publication over the plugins' config resolvers, so `composition.spec.ts`, which boots the real route plugins through
+ * Connect DeepSeek model route settings to `ctx.deepseekAuth` the way the route plugins do. It reimplements their
+ * connection over the plugins' config resolvers, so `composition.spec.ts`, which boots the real route plugins through
* the Loader, is what covers the production path.
*/
import type { Context } from '@deepseek-ai/cordis'
-import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials'
-import type {} from '@deepseek-ai/dsh-deepseek-account'
+import type {} from '@deepseek-ai/dsh-deepseek-auth'
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
-import type { ProviderCredential } from '@deepseek-ai/dsh-llm'
import { Config as AccountConfig } from '@deepseek-ai/dsh-llm-deepseek-account'
import { plainAccountOptions, resolveAccountOptions } from '@deepseek-ai/dsh-llm-deepseek-account/src/config.ts'
import { Config as OfficialConfig } from '@deepseek-ai/dsh-llm-deepseek-api-key'
@@ -17,53 +15,33 @@ import { plainOptions, resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepse
export interface RouteRow {
/** Provider id the route registers. */
provider: 'deepseek-official' | 'deepseek-account'
- /** Route plugin config; the route package's own resolver turns it into the published base URL and key reference. */
+ /** Route plugin config; the route package's own resolver turns it into the connected base URL and key reference. */
config?: Record
- /** Publish no credential, as an adapter another package registers under this id does. Defaults to false. */
- withoutCredential?: boolean
- /** Value `providerCredential()` throws instead of publishing. */
+ /** Connect no deployment, as an adapter another package registers under this id does. Defaults to false. */
+ withoutConnection?: boolean
+ /** Value the route's settings throw instead of resolving. */
throws?: unknown
- /** Base URL published in place of the resolved one, as a route publishing an unparsable base would. */
- publishedBaseURL?: string
- /** Credential kind published under this id, as another adapter registered under it can; defaults to the route's own kind. */
- publishes?: 'api-key' | 'account'
-}
-
-/** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */
-function credentialOf(ctx: Context, route: RouteRow): ProviderCredential {
- const environment = launchEnvironmentOf(ctx)
- if ((route.publishes ?? (route.provider === 'deepseek-official' ? 'api-key' : 'account')) === 'api-key') {
- const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment)
- const ref = resolved.apiKeyEnv
- return {
- kind: 'api-key', baseURL: route.publishedBaseURL ?? resolved.baseURL, reference: ref,
- configured: () => credentialRefConfigured(ctx, ref),
- resolve: async () => {
- const key = await resolveCredentialRef(ctx, ref)
- return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key }
- },
- }
- }
- const resolved = resolveAccountOptions(plainAccountOptions(AccountConfig(route.config ?? {})), environment)
- return {
- kind: 'account', baseURL: route.publishedBaseURL ?? resolved.protocol.baseURL,
- configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined,
- resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined),
- }
+ /** Base URL connected in place of the resolved one, as route settings naming an unparsable base would. */
+ connectedBaseURL?: string
}
/**
- * Provide an `llm` stand-in whose `providerCredential()` answers for `routes`.
- * @param ctx - the root context.
+ * Connect `routes` to the mounted `ctx.deepseekAuth`, each resolving its config per request as the route plugin does.
+ * @param ctx - the root context, with the authentication service mounted.
* @param routes - route rows, one per provider id.
*/
export function provideRoutes(ctx: Context, routes: readonly RouteRow[]): void {
- ctx.provide('llm', {
- providerCredential: (provider: string): ProviderCredential | undefined => {
- const route = routes.find(row => row.provider === provider)
- if (route === undefined || route.withoutCredential === true) return undefined
+ for (const route of routes) {
+ if (route.withoutConnection === true) continue
+ ctx.effect(() => ctx.deepseekAuth.connect(route.provider === 'deepseek-official' ? 'api-key' : 'account', route.provider, () => {
if (route.throws !== undefined) throw route.throws
- return credentialOf(ctx, route)
- },
- } as never)
+ const environment = launchEnvironmentOf(ctx)
+ if (route.provider === 'deepseek-official') {
+ const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment)
+ return { baseURL: route.connectedBaseURL ?? resolved.baseURL, reference: resolved.apiKeyEnv, owner: 'llm-deepseek' }
+ }
+ const resolved = resolveAccountOptions(plainAccountOptions(AccountConfig(route.config ?? {})), environment)
+ return { baseURL: route.connectedBaseURL ?? resolved.protocol.baseURL }
+ }))
+ }
}
diff --git a/packages/web/web-deepseek-api/tests/search.spec.ts b/packages/web/web-deepseek-api/tests/search.spec.ts
index 17d3eccfa7..49860a0793 100644
--- a/packages/web/web-deepseek-api/tests/search.spec.ts
+++ b/packages/web/web-deepseek-api/tests/search.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
-import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { Session } from '@deepseek-ai/dsh-session'
@@ -15,14 +15,14 @@ import {
import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api'
import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { customGuidance } from './guidance.ts'
+import { keyCandidate } from './sources.ts'
/** Construct the provider over a fixed options value; production passes a live thunk. */
const searchProvider = (options: DeepSeekSearchApiOptions): DeepSeekSearchApiProvider =>
new DeepSeekSearchApiProvider(() => options)
const BASE = 'https://api.deepseek.test/api/v1/tools'
-const auth = (key: string, baseURL = BASE): DeepSeekSearchApiOptions['auth'] =>
- ({ sources: [{ kind: 'api-key', baseURL, key: { ref: credentialRef('TEST_KEY'), configured: async () => key.length > 0, resolve: async () => key.length > 0 ? key : undefined } }] })
+const auth = (key: string): DeepSeekSearchApiOptions['auth'] => ({ sources: [keyCandidate(`${BASE}/search`, key)] })
const options = {
auth: auth('ds-key'),
@@ -76,7 +76,7 @@ describe('mapSearchResponse', () => {
})
describe('DeepSeekSearchApiProvider availability', () => {
- it('is unavailable without a source, and available with a referenced key whose presence only ready() reads', () => {
+ it('is unavailable without a source, and available with a key whose presence only ready() reads', () => {
expect(searchProvider({ ...options, auth: { sources: [] } }).available()).toBe(false)
expect(searchProvider({ ...options, auth: auth('') }).available()).toBe(true)
})
@@ -85,19 +85,15 @@ describe('DeepSeekSearchApiProvider availability', () => {
expect(searchProvider(options).available()).toBe(true)
})
- it('is available with only a route credential', () => {
- const credential = { kind: 'account', configured: async () => true, resolve: async () => undefined } as const
- expect(searchProvider({ ...options, auth: { sources: [{ kind: 'route', baseURL: BASE, credential }] } }).available()).toBe(true)
+ it('is available with only an account credential', () => {
+ const account = { kind: 'account', endpoint: `${BASE}/search`, configured: async () => true, resolve: async () => undefined } as const
+ expect(searchProvider({ ...options, auth: { sources: [account] } }).available()).toBe(true)
})
it('is available with only a misconfigured source, which the search reports', () => {
expect(searchProvider({ ...options, auth: { sources: [{ kind: 'misconfigured', message: 'route settings do not resolve' }] } }).available()).toBe(true)
})
- it('is misconfigured when the base URL is unparseable', () => {
- expect(searchProvider({ ...options, auth: auth('ds-key', 'not a url') }).available()).toBe(false)
- })
-
it.each([0, 1.5])('is unavailable with invalid count %j', (count) => {
expect(searchProvider({ ...options, count }).available()).toBe(false)
})
@@ -222,6 +218,7 @@ describe('Search API triggering question', () => {
await ctx.plugin(AgentRegistry)
await ctx.plugin(WebRuntime, { searchProvider: 'deepseek-search-api' })
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: { DEEPSEEK_API_KEY: 'ds-key' } }]))
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(webApiPlugin, config)
const messages = [
userMessage('m1', { kind: 'user' }, [{ type: 'text', text: 'Earlier question' }]),
@@ -256,6 +253,7 @@ describe('Search API configuration and failures', () => {
try {
await ctx.plugin(WebRuntime, { searchProvider: 'deepseek-search-api' })
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: { DEEPSEEK_API_KEY: 'ds-key' } }]))
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(webApiPlugin, {})
await ctx.web.search({ query: 'q' })
expect(fetchMock.mock.calls[0]?.[0]).toBe(`${DEEPSEEK_WEB_API_BASE_URL}/search`)
@@ -270,6 +268,7 @@ describe('Search API configuration and failures', () => {
try {
await ctx.plugin(WebRuntime, { searchProvider: 'deepseek-search-api' })
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: { DEEPSEEK_API_KEY: 'ds-key' } }]))
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(webApiPlugin, { searchBaseURL: 'not a url' })
await expect(ctx.web.search({ query: 'q' })).rejects.toMatchObject({ code: 'WEB_PROVIDER_CONFIGURED_UNAVAILABLE' })
expect(fetchMock).not.toHaveBeenCalled()
diff --git a/packages/web/web-deepseek-api/tests/sources.ts b/packages/web/web-deepseek-api/tests/sources.ts
new file mode 100644
index 0000000000..b3810a8412
--- /dev/null
+++ b/packages/web/web-deepseek-api/tests/sources.ts
@@ -0,0 +1,20 @@
+/** Credential sources for provider tests that construct a provider or a request directly. */
+import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import type { DeepSeekAuthCandidate } from '@deepseek-ai/dsh-deepseek-auth'
+
+/**
+ * An API-key candidate bound to `endpoint`, as `ctx.deepseekAuth` binds one: it releases `key` as a bearer token and
+ * releases nothing for an empty key.
+ * @param endpoint - absolute URL the operation dispatches to.
+ * @param key - the key; empty means none is configured.
+ * @param reference - the credential reference the candidate names.
+ * @returns the candidate.
+ */
+export function keyCandidate(endpoint: string, key: string, reference = 'TEST_KEY'): DeepSeekAuthCandidate {
+ const ref = credentialRef(reference)
+ return {
+ kind: 'api-key', endpoint, reference: ref,
+ configured: async () => key.length > 0,
+ resolve: async () => key.length > 0 ? { kind: 'api-key', endpoint, reference: ref, headers: { authorization: `Bearer ${key}` } } : undefined,
+ }
+}
diff --git a/packages/web/web-deepseek-api/tests/transport.spec.ts b/packages/web/web-deepseek-api/tests/transport.spec.ts
index 554d1f7671..84bc9e7b0a 100644
--- a/packages/web/web-deepseek-api/tests/transport.spec.ts
+++ b/packages/web/web-deepseek-api/tests/transport.spec.ts
@@ -1,50 +1,59 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import type { DeepSeekAuthCandidate } from '@deepseek-ai/dsh-deepseek-auth'
import { WebError } from '@deepseek-ai/dsh-web'
import { customGuidance } from './guidance.ts'
import {
- dispatchDeepSeekWeb, hasDeepSeekWebCredential, isDeepSeekWebAuthReady,
- type DeepSeekWebApiKey, type DeepSeekWebAuthSource,
+ dispatchDeepSeekWeb, hasDeepSeekWebCredential, isDeepSeekWebAuthReady, type DeepSeekWebAuthSource,
} from '../src/transport.ts'
const API_BASE = 'https://api.deepseek.test/v1/tools'
const ACCOUNT_BASE = 'https://account.deepseek.test/v1/tools'
-/** An API-key source on {@link API_BASE}. */
-function keySource(key: DeepSeekWebApiKey = keyRef(async () => 'ds-key')): DeepSeekWebAuthSource {
- return { kind: 'api-key', baseURL: API_BASE, key }
+const KEY_REF = credentialRef('TEST_KEY')
+/** The presence check and the read of one referenced key. */
+interface KeyRead {
+ configured: () => Promise
+ resolve: () => Promise
}
/** A referenced key whose presence check and read are the given functions. */
-function keyRef(resolve: () => Promise, configured: () => Promise = async () => true): DeepSeekWebApiKey {
- return { ref: credentialRef('TEST_KEY'), configured, resolve }
+function keyRef(resolve: () => Promise, configured: () => Promise = async () => true): KeyRead {
+ return { configured, resolve }
}
/**
- * A route source on {@link ACCOUNT_BASE} whose account credential releases `resolveToken(endpoint)` as the token header;
- * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failure rejects the grant's
- * invalidation, as an owner that does not contain its storage failures does. `revoked` is the sign-out signal the
- * grant carries, when given.
+ * An API-key candidate bound to the Search endpoint under {@link API_BASE}, as `ctx.deepseekAuth` binds one: it
+ * releases the read key as a bearer token and releases nothing without a key. `revoked` is the withdrawal signal the
+ * authorization carries, when given.
+ */
+function keySource(key: KeyRead = keyRef(async () => 'ds-key'), revoked?: AbortSignal): DeepSeekAuthCandidate {
+ const endpoint = `${API_BASE}/search`
+ return {
+ kind: 'api-key', endpoint, reference: KEY_REF, configured: key.configured,
+ resolve: async () => {
+ const value = await key.resolve()
+ if (value === undefined) return undefined
+ return { kind: 'api-key', endpoint, reference: KEY_REF, headers: { authorization: `Bearer ${value}` }, ...revoked === undefined ? {} : { revoked } }
+ },
+ }
+}
+/**
+ * An account candidate bound to the Search endpoint under {@link ACCOUNT_BASE}, releasing `resolveToken(endpoint)` as
+ * the token header; an empty token releases nothing. `rejectToken` observes each invalidated token, and its failure
+ * rejects the invalidation, as an owner that does not contain its storage failures does. `revoked` is the sign-out
+ * signal the authorization carries, when given.
*/
function accountSource(
resolveToken: (endpoint: string) => Promise, rejectToken: (token: string) => Promise = async () => {},
revoked?: AbortSignal,
-): DeepSeekWebAuthSource {
- const grant = async (endpoint: string) => {
+): DeepSeekAuthCandidate {
+ const endpoint = `${ACCOUNT_BASE}/search`
+ const release = async () => {
const token = await resolveToken(endpoint)
if (token === undefined || token.length === 0) return undefined
- return { headers: { 'x-dsh-auth-token': token }, value: token, reject: () => rejectToken(token), ...revoked === undefined ? {} : { revoked } }
+ return {
+ kind: 'account' as const, endpoint, headers: { 'x-dsh-auth-token': token }, reject: () => rejectToken(token),
+ ...revoked === undefined ? {} : { revoked },
+ }
}
- return { kind: 'route', baseURL: ACCOUNT_BASE, credential: {
- kind: 'account', configured: async endpoint => (await grant(endpoint)) !== undefined, resolve: grant,
- } }
-}
-/**
- * A route source on {@link API_BASE} whose API-key credential releases `key`, sent as a bearer token, with the
- * withdrawal signal `revoked` when given.
- */
-function keyRouteSource(key: string | undefined, reference = 'ROUTE_KEY', revoked?: AbortSignal): DeepSeekWebAuthSource {
- return { kind: 'route', baseURL: API_BASE, credential: {
- kind: 'api-key', reference,
- configured: async () => key !== undefined,
- resolve: async () => key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key, ...revoked === undefined ? {} : { revoked } },
- } }
+ return { kind: 'account', endpoint, configured: async () => (await release()) !== undefined, resolve: release }
}
const misconfigured: DeepSeekWebAuthSource = { kind: 'misconfigured', message: 'route settings do not resolve' }
/** Search once with the given sources, in order. */
@@ -54,9 +63,8 @@ function search(
) {
const { recordRequest, missingCredentialMessage } = extra
return dispatchDeepSeekWeb({ sources, ...missingCredentialMessage === undefined ? {} : { missingCredentialMessage } }, {
- path: '/search', body: { query: 'q' }, decode: value => value,
+ body: { query: 'q' }, decode: value => value,
...recordRequest === undefined ? {} : { recordRequest },
- apiKeyHeaders: key => ({ 'x-api-key': key }),
guidance: customGuidance('search'),
}, signal)
}
@@ -104,16 +112,16 @@ describe('DeepSeek web credential order', () => {
const [request] = sent()
expect(sent()).toHaveLength(1)
expect(request?.url).toBe(`${API_BASE}/search`)
- expect(request?.headers).toMatchObject({ 'authorization': 'Bearer resolved-key', 'x-api-key': 'resolved-key' })
+ expect(request?.headers).toMatchObject({ authorization: 'Bearer resolved-key' })
expect(request?.headers).not.toHaveProperty('x-dsh-auth-token')
expect(resolve).toHaveBeenCalledOnce()
expect(configured).not.toHaveBeenCalled()
expect(resolveToken).not.toHaveBeenCalled()
})
- it.each([undefined, ''])('sends the account token when the referenced key first in order resolves %j', async (key) => {
+ it('sends the account token when the key first in order is absent', async () => {
const { sent } = captureFetch()
- await search([keySource(keyRef(async () => key)), accountSource(async () => 'account-token')])
+ await search([keySource(keyRef(async () => undefined)), accountSource(async () => 'account-token')])
expect(sent().map(row => [row.url, row.headers['x-dsh-auth-token'], row.headers.authorization]))
.toEqual([[`${ACCOUNT_BASE}/search`, 'account-token', undefined]])
})
@@ -121,29 +129,13 @@ describe('DeepSeek web credential order', () => {
it.each([undefined, ''])('sends the key to its own base when the account first in order resolves %j', async (token) => {
const { sent } = captureFetch()
await search([accountSource(async () => token), keySource()])
- expect(sent().map(row => [row.url, row.headers['x-api-key'], row.headers['x-dsh-auth-token']]))
- .toEqual([[`${API_BASE}/search`, 'ds-key', undefined]])
- })
-
- it('sends a route API key as a bearer token with the request\'s API-key headers, never the route\'s own headers', async () => {
- const { sent } = captureFetch()
- await search([keyRouteSource('route-key')])
- const [request] = sent()
- expect(request?.url).toBe(`${API_BASE}/search`)
- expect(request?.headers).toMatchObject({ 'authorization': 'Bearer route-key', 'x-api-key': 'route-key' })
- expect(request?.headers).not.toHaveProperty('x-dsh-auth-token')
- })
-
- it('moves past a route whose API key is absent', async () => {
- const { sent } = captureFetch()
- await search([keyRouteSource(undefined), accountSource(async () => 'account-token')])
- expect(sent().map(row => [row.url, row.headers['x-dsh-auth-token']])).toEqual([[`${ACCOUNT_BASE}/search`, 'account-token']])
+ expect(sent().map(row => [row.url, row.headers.authorization, row.headers['x-dsh-auth-token']]))
+ .toEqual([[`${API_BASE}/search`, 'Bearer ds-key', undefined]])
})
it.each<[string, readonly DeepSeekWebAuthSource[]]>([
['no sources', []],
- ['a referenced key that resolves empty', [keySource(keyRef(async () => ''))]],
- ['a missing referenced key and no account token', [keySource(keyRef(async () => undefined)), accountSource(async () => undefined)]],
+ ['a missing key and no account token', [keySource(keyRef(async () => undefined)), accountSource(async () => undefined)]],
])('fails with the caller diagnostic and sends nothing for %s', async (_label, sources) => {
const { fetchMock } = captureFetch()
await expect(search(sources, undefined, { missingCredentialMessage: 'no credential for this search' }))
@@ -209,15 +201,15 @@ describe('DeepSeek web credential availability and readiness', () => {
expect(hasDeepSeekWebCredential({ sources })).toBe(expected)
})
- it('checks a referenced key for presence without reading it, and asks the account for the operation endpoint', async () => {
+ it('checks a key for presence without reading it, and asks the account for its endpoint', async () => {
const { fetchMock } = captureFetch()
const resolve = vi.fn(async () => 'resolved-key')
const configured = vi.fn(async () => false)
const resolveToken = vi.fn(async (_endpoint: string) => 'account-token')
- expect(await isDeepSeekWebAuthReady({ sources: [keySource(keyRef(resolve, configured)), accountSource(resolveToken)] }, '/fetch')).toBe(true)
+ expect(await isDeepSeekWebAuthReady({ sources: [keySource(keyRef(resolve, configured)), accountSource(resolveToken)] })).toBe(true)
expect(configured).toHaveBeenCalledOnce()
expect(resolve).not.toHaveBeenCalled()
- expect(resolveToken).toHaveBeenCalledExactlyOnceWith(`${ACCOUNT_BASE}/fetch`)
+ expect(resolveToken).toHaveBeenCalledExactlyOnceWith(`${ACCOUNT_BASE}/search`)
expect(fetchMock).not.toHaveBeenCalled()
})
@@ -228,7 +220,7 @@ describe('DeepSeek web credential availability and readiness', () => {
['a configured key before the account', [keySource(keyRef(async () => undefined)), accountSource(async () => undefined)], true],
['neither credential', [accountSource(async () => ''), keySource(keyRef(async () => undefined, async () => false))], false],
])('answers for %s', async (_label, sources, expected) => {
- expect(await isDeepSeekWebAuthReady({ sources }, '/search')).toBe(expected)
+ expect(await isDeepSeekWebAuthReady({ sources })).toBe(expected)
})
it.each<[string, DeepSeekWebAuthSource]>([
@@ -237,7 +229,7 @@ describe('DeepSeek web credential availability and readiness', () => {
['an unreadable credential store', keySource(keyRef(async () => 'key', () => Promise.reject(new Error('store locked'))))],
])('answers false at %s without reading later sources', async (_label, source) => {
const resolveToken = vi.fn(async () => 'account-token')
- expect(await isDeepSeekWebAuthReady({ sources: [source, accountSource(resolveToken)] }, '/search')).toBe(false)
+ expect(await isDeepSeekWebAuthReady({ sources: [source, accountSource(resolveToken)] })).toBe(false)
expect(resolveToken).not.toHaveBeenCalled()
})
})
@@ -288,9 +280,9 @@ describe('DeepSeek web account authentication', () => {
expect(rejectToken).not.toHaveBeenCalled()
})
- it('keeps endpoint guidance for a 401 on a route API key, which has no invalidation', async () => {
+ it('keeps endpoint guidance for a 401 on an API key, which has no invalidation', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'invalid key' }, { status: 401 })))
- const error = await rejectedWebError(search([keyRouteSource('route-key')]))
+ const error = await rejectedWebError(search([keySource()]))
expect(error.message).toContain('DeepSeek API error (HTTP 401): invalid key')
expect(error.message).toContain('If that endpoint is not intended')
expect(error.message).not.toContain('sign in')
@@ -383,6 +375,17 @@ describe('DeepSeek web account authentication', () => {
expect(resolve).not.toHaveBeenCalled()
})
+ it('reports the cancellation when a credential read cancels its caller and then fails', async () => {
+ const { fetchMock } = captureFetch()
+ const controller = new AbortController()
+ const source = accountSource(() => {
+ controller.abort(new Error('caller stopped'))
+ return Promise.reject(new Error('read failed after the cancellation'))
+ })
+ await expect(search([source], controller.signal)).rejects.toMatchObject({ code: 'WEB_ABORTED' })
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
it('aborts while the account resolver remains pending', async () => {
const { fetchMock } = captureFetch()
const controller = new AbortController()
@@ -414,7 +417,7 @@ describe('DeepSeek web credential withdrawal', () => {
it.each<[string, (revoked: AbortSignal) => DeepSeekWebAuthSource, string]>([
['an account sign-out', revoked => accountSource(async () => 'account-token', undefined, revoked), ACCOUNT_SIGNED_OUT],
- ['the withdrawal of a route key', revoked => keyRouteSource('route-key', 'ROUTE_KEY', revoked), KEY_WITHDRAWN],
+ ['the withdrawal of a key', revoked => keySource(undefined, revoked), KEY_WITHDRAWN],
])('ends an open request at %s and reports the withdrawal instead of a cancellation', async (_label, source, message) => {
for (const signal of [undefined, new AbortController().signal]) {
const withdrawn = new AbortController()
@@ -490,7 +493,7 @@ describe('DeepSeek web cancellation and failures', () => {
const { sent } = captureFetch(() => jsonResponse({ truncated: false }))
await expect(search([keySource(keyRef(async () => 'resolved-key'))], new AbortController().signal))
.resolves.toMatchObject({ truncated: false })
- expect(sent()[0]?.headers['x-api-key']).toBe('resolved-key')
+ expect(sent()[0]?.headers.authorization).toBe('Bearer resolved-key')
})
it('maps a credential resolver rejection under an active signal to WEB_PROVIDER_ERROR', async () => {
diff --git a/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts b/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts
index 84d2cfc65e..38285f5c23 100644
--- a/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts
+++ b/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts
@@ -1,20 +1,17 @@
import { describe, expect, it } from 'vitest'
-import { credentialRef } from '@deepseek-ai/dsh-credentials'
import { DeepSeekFetchApiProvider, DeepSeekSearchApiProvider } from '@deepseek-ai/dsh-web-deepseek-api'
import { customGuidance } from './guidance.ts'
+import { keyCandidate } from './sources.ts'
/** Real Search and Fetch API probes; the base names the deployment the key authenticates. */
const apiKey = process.env.DEEPSEEK_API_KEY
const baseURL = process.env.DEEPSEEK_SEARCH_API_TEST_BASE_URL ?? ''
-const auth = { sources: [{
- kind: 'api-key', baseURL,
- key: { ref: credentialRef('DEEPSEEK_API_KEY'), configured: async () => apiKey !== undefined, resolve: async () => apiKey },
-}] } as const
+const auth = (path: '/search' | '/fetch') => ({ sources: [keyCandidate(`${baseURL}${path}`, apiKey ?? '', 'DEEPSEEK_API_KEY')] })
const maybe = apiKey !== undefined && apiKey.length > 0 && baseURL.length > 0 ? describe : describe.skip
maybe('DeepSeek Search and Fetch real API', () => {
it('returns citeable sources from the Search API', async () => {
- const provider = new DeepSeekSearchApiProvider(() => ({ auth, count: 10, requestsPerSecond: 5, guidance: customGuidance('search') }))
+ const provider = new DeepSeekSearchApiProvider(() => ({ auth: auth('/search'), count: 10, requestsPerSecond: 5, guidance: customGuidance('search') }))
const result = await provider.search({ query: 'DeepSeek', maxResults: 3 }, AbortSignal.timeout(30_000))
expect(result.sources.length).toBeGreaterThan(0)
expect(result.sources.length).toBeLessThanOrEqual(3)
@@ -22,7 +19,7 @@ maybe('DeepSeek Search and Fetch real API', () => {
}, 40_000)
it('returns Markdown from the Fetch API', async () => {
- const provider = new DeepSeekFetchApiProvider(() => ({ auth, guidance: customGuidance('fetch') }))
+ const provider = new DeepSeekFetchApiProvider(() => ({ auth: auth('/fetch'), guidance: customGuidance('fetch') }))
const result = await provider.fetch({ url: 'https://example.com' }, AbortSignal.timeout(30_000))
expect(result.body.kind).toBe('text')
expect(result.body.content.length).toBeGreaterThan(0)
diff --git a/packages/web/web-deepseek-api/tsconfig.json b/packages/web/web-deepseek-api/tsconfig.json
index 01466b7c23..4b8ab7ff39 100644
--- a/packages/web/web-deepseek-api/tsconfig.json
+++ b/packages/web/web-deepseek-api/tsconfig.json
@@ -8,9 +8,6 @@
"src"
],
"references": [
- {
- "path": "../../util/launch-environment"
- },
{
"path": "../../../vendor/cosmokit"
},
@@ -32,14 +29,14 @@
{
"path": "../../credentials/credentials"
},
- {
- "path": "../../account/deepseek-account"
- },
{
"path": "../../util/http-proxy"
},
{
"path": "../../llm/llm"
+ },
+ {
+ "path": "../../account/deepseek-auth"
}
]
}
diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml
index a9907cc6f9..a46294f8c1 100644
--- a/packages/web/web-search-deepseek/README.i18n.yaml
+++ b/packages/web/web-search-deepseek/README.i18n.yaml
@@ -15,17 +15,17 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-web-search-deepseek/use-this-package:
- en: e0d352d6402d9d3b
- zh: a449234557ef8bd6
+ en: ad3fa6a3820c138a
+ zh: 98ecae8075955c8b
/deepseek-ai-dsh-web-search-deepseek/use-this-package/when-to-choose-it:
en: 0187c8af8d2d98c5
zh: 1c9607b3a662bcaa
/deepseek-ai-dsh-web-search-deepseek/use-this-package/minimal-configuration:
- en: 3ed88edabdf63c8d
- zh: c66176c8a7c9a434
+ en: b336edf5f1a6f43f
+ zh: 215cd616bcd91874
/deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication:
- en: bea7705262c58779
- zh: a8c166024477b311
+ en: f5af5bfdd5d26c66
+ zh: 840c9cff505a08ac
/deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns:
en: e30442c90365357b
zh: 9c9e2f1182963a8a
@@ -39,14 +39,14 @@
en: 9842c69ad3636bb3
zh: 3cdc3f816cbdd0cb
/deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/design-philosophy:
- en: 9ebf133e28acbd3a
- zh: 440399ab6a4f5540
+ en: e4ad49ef66f73a8e
+ zh: 13bbf09a8bc9f396
/deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/source-map:
en: 6488e1c85646339f
zh: 2b5ca1c6b5939a8c
/deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/request-flow:
- en: f5f0e602ec250162
- zh: 5854cc89c0806644
+ en: 77119c7dc83d870a
+ zh: 1853a414bfd91f84
/deepseek-ai-dsh-web-search-deepseek/further-exploration:
en: 3a650478cf33d792
zh: ab4247c4c31f4a90
diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md
index 503822edf5..67531280b9 100644
--- a/packages/web/web-search-deepseek/README.md
+++ b/packages/web/web-search-deepseek/README.md
@@ -25,7 +25,7 @@ With `dsh-web-search-deepseek`, the harness searches the web through DeepSeek's
## Use this package
-Mount the provider in a composition that already loads the web service; it registers as the `deepseek-official` search provider, so `ctx.web.search()` resolves it automatically when it is the only usable search backend — or pin it with `searchProvider: deepseek-official`.
+Mount the provider in a composition that already loads the web service and [`dsh-deepseek-auth`](../../account/deepseek-auth/README.md), which releases its credentials; it registers as the `deepseek-official` search provider, so `ctx.web.search()` resolves it automatically when it is the only usable search backend — or pin it with `searchProvider: deepseek-official`.
### When to choose it
@@ -33,10 +33,11 @@ Choose this backend when a deployment wants DeepSeek's native server-side web se
### Minimal configuration
-Load the web service and the provider; the key resolves from `ctx.credentials` when that service is mounted, otherwise from the process environment. The auxiliary search call has its own endpoint setting and uses the Anthropic-compatible base `https://api.deepseek.com/anthropic/v1`, with `/messages` appended. It reads `$DEEPSEEK_SEARCH_BASE_URL`, independently of the conversation adapter’s `$DEEPSEEK_BASE_URL`; the `dsh` launcher accepts both variables from the launching environment or `$DSH_HOME/.env`, never from a project `.env` ([app-boot](../../boot/app-boot/README.md)).
+Load the web service, DeepSeek authentication, and the provider; the key resolves from `ctx.credentials` when that service is mounted, otherwise from the process environment. The auxiliary search call has its own endpoint setting and uses the Anthropic-compatible base `https://api.deepseek.com/anthropic/v1`, with `/messages` appended. It reads `$DEEPSEEK_SEARCH_BASE_URL`, independently of the conversation adapter’s `$DEEPSEEK_BASE_URL`; the `dsh` launcher accepts both variables from the launching environment or `$DSH_HOME/.env`, never from a project `.env` ([app-boot](../../boot/app-boot/README.md)).
```yaml
- name: '@deepseek-ai/dsh-web'
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-web-search-deepseek'
config:
apiKeyEnv: DEEPSEEK_API_KEY
@@ -58,11 +59,11 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a
### Authentication
-A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.providerCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. An account-authenticated search in flight when the account signs out ends through the credential's `revoked` signal and fails as `WEB_PROVIDER_ERROR` with sign-in guidance.
+A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names the `deepseek-account` model route, the search endpoint has the origin of that route's base URL, and `ctx.deepseekAuth` releases the account sign-in for the search endpoint. The sign-in is asked for only at that origin, so it is never sent to the search endpoint of another deployment. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. An account-authenticated search in flight when the account signs out ends through the credential's `revoked` signal and fails as `WEB_PROVIDER_ERROR` with sign-in guidance.
-The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential for the origin of the configured search endpoint that reports itself configured for that endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or whose published base URL does not parse, or a failed account-credential or credential-store read, answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs.
+The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: on the `deepseek-account` route the account sign-in is configured for the search endpoint, which requires that endpoint to be under the origin of that route's base URL, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve, or a failed account-credential or credential-store read, answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs.
-Referenced keys go through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md) and receive the same whitespace normalization and format validation as model requests. A malformed referenced key fails before dispatch; readiness remains a presence-only check.
+`ctx.deepseekAuth` reads referenced keys through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md) and applies the same whitespace normalization and format validation as model requests. A malformed referenced key fails before dispatch; readiness remains a presence-only check.
### What a search returns
@@ -91,7 +92,7 @@ This section explains the design decisions behind the provider; the observable b
The provider is built on two commitments:
- **Structured blocks only.** DeepSeek runs the search server-side and returns structured `web_search_tool_result` blocks; the provider parses those blocks and never scrapes URLs out of model prose. In strict mode, a response with no such block throws `WEB_PROVIDER_ERROR` instead of degrading.
-- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on a route that publishes an account credential for the search endpoint's origin uses that credential, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart.
+- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on the account route, whose deployment has the search endpoint's origin, uses the account sign-in, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the key is read from the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart.
### Source map
@@ -103,9 +104,9 @@ The provider is built on two commitments:
### Request flow
-Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.providerCredential` when it publishes one for the search endpoint's origin, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back.
+Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks [`ctx.deepseekAuth`](../../account/deepseek-auth/README.md) for the credential of the search endpoint, the account sign-in in a conversation on the account route and otherwise the referenced key read through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back.
-Readiness captures the same options but reads no API key value: on a route publishing an account credential for the search endpoint's origin it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured.
+Readiness captures the same options but reads no API key value: it asks each candidate `ctx.deepseekAuth` returns for the search, in order, whether its credential is configured, in a conversation on the account route first the account sign-in for the search endpoint and then the key reference through `ctx.credentials.describe()` (or the environment). A literal key always counts as configured.
diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md
index a8196222d3..d108c7099e 100644
--- a/packages/web/web-search-deepseek/README.zh.md
+++ b/packages/web/web-search-deepseek/README.zh.md
@@ -25,7 +25,7 @@ kind: "package-reference"
## 使用本包
-在已加载 web 服务的组合中挂载本提供方;它以 `deepseek-official` 搜索提供方身份注册,因此当它是唯一可用的搜索后端时,`ctx.web.search()` 会自动解析到它——也可以用 `searchProvider: deepseek-official` 固定。
+在已加载 web 服务和为它释放凭据的 [`dsh-deepseek-auth`](../../account/deepseek-auth/README.zh.md) 的组合中挂载本提供方;它以 `deepseek-official` 搜索提供方身份注册,因此当它是唯一可用的搜索后端时,`ctx.web.search()` 会自动解析到它——也可以用 `searchProvider: deepseek-official` 固定。
### 何时选择
@@ -33,10 +33,11 @@ kind: "package-reference"
### 最小配置
-加载 web 服务与本提供方;密钥在已挂载 `ctx.credentials` 服务时从其解析,否则从进程环境解析。辅助搜索调用有独立的端点设置,使用 Anthropic 兼容基址 `https://api.deepseek.com/anthropic/v1`,并追加 `/messages`。它读取 `$DEEPSEEK_SEARCH_BASE_URL`,与会话适配器的 `$DEEPSEEK_BASE_URL` 相互独立;`dsh` 启动器从启动环境或 `$DSH_HOME/.env` 接受这两个变量,绝不从项目 `.env` 接受([app-boot](../../boot/app-boot/README.zh.md))。
+加载 web 服务、DeepSeek 鉴权服务与本提供方;密钥在已挂载 `ctx.credentials` 服务时从其解析,否则从进程环境解析。辅助搜索调用有独立的端点设置,使用 Anthropic 兼容基址 `https://api.deepseek.com/anthropic/v1`,并追加 `/messages`。它读取 `$DEEPSEEK_SEARCH_BASE_URL`,与会话适配器的 `$DEEPSEEK_BASE_URL` 相互独立;`dsh` 启动器从启动环境或 `$DSH_HOME/.env` 接受这两个变量,绝不从项目 `.env` 接受([app-boot](../../boot/app-boot/README.zh.md))。
```yaml
- name: '@deepseek-ai/dsh-web'
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-web-search-deepseek'
config:
apiKeyEnv: DEEPSEEK_API_KEY
@@ -58,11 +59,11 @@ kind: "package-reference"
### 鉴权
-当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.providerCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。账号退登时仍在途的账号鉴权搜索会通过凭据的 `revoked` 信号结束,并以 `WEB_PROVIDER_ERROR` 失败,附带登录指引。
+当发起会话最近的 `request/context` 事件指明 `deepseek-account` 模型路由,搜索端点与该路由的基础地址同源,且 `ctx.deepseekAuth` 为搜索端点释放了账号登录凭据时,搜索使用 DeepSeek 账号鉴权。只有同源时才会索取该凭据,因此它不会发往其他部署的搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。账号退登时仍在途的账号鉴权搜索会通过凭据的 `revoked` 信号结束,并以 `WEB_PROVIDER_ERROR` 失败,附带登录指引。
-提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由为配置的搜索端点所在 origin 发布了账号凭据且该凭据报告自身已为该端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析或其发布的基础地址无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。
+提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:在 `deepseek-account` 路由上账号登录凭据已为搜索端点配置(这要求该端点位于该路由基础地址的 origin 之下),或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。
-引用密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取,接受与模型请求相同的首尾空白规范化和格式校验。引用密钥格式错误会在发送请求前失败;就绪判断仍只检查是否存在。
+引用密钥由 `ctx.deepseekAuth` 通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取,接受与模型请求相同的首尾空白规范化和格式校验。引用密钥格式错误会在发送请求前失败;就绪判断仍只检查是否存在。
### 搜索返回什么
@@ -91,7 +92,7 @@ kind: "package-reference"
本提供方建立在两项承诺之上:
- **只取结构化块。** DeepSeek 在服务端执行搜索并返回结构化的 `web_search_tool_result` 块;提供方解析这些块,绝不从模型文本中抓取 URL。严格模式下,没有此类块的响应会抛出 `WEB_PROVIDER_ERROR`,而非降级。
-- **会话凭据,逐次解析。** 提供方不新增密钥:发起会话的路由为搜索端点所在 origin 发布账号凭据时,搜索使用该凭据,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。
+- **会话凭据,逐次解析。** 提供方不新增密钥:发起会话位于账号路由且该路由的部署与搜索端点同源时,搜索使用账号登录凭据,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。
### 源码地图
@@ -103,9 +104,9 @@ kind: "package-reference"
### 请求流程
-每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.providerCredential` 为搜索端点所在 origin 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。
+每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后向 [`ctx.deepseekAuth`](../../account/deepseek-auth/README.zh.md) 索取搜索端点的凭据:账号路由上的会话取账号登录凭据,否则取经由 `ctx.credentials`(或环境)读取的引用密钥,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。
-就绪判断捕获相同的选项,但不读取 API 密钥的值:路由为搜索端点所在 origin 发布账号凭据时,先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。
+就绪判断捕获相同的选项,但不读取 API 密钥的值:它依次询问 `ctx.deepseekAuth` 为这次搜索返回的每个候选其凭据是否已配置,在账号路由上的会话里先是面向搜索端点的账号登录凭据,然后经由 `ctx.credentials.describe()`(或环境)询问密钥引用。字面密钥总是算作已配置。
diff --git a/packages/web/web-search-deepseek/package.json b/packages/web/web-search-deepseek/package.json
index 169945f9bc..85549ca977 100644
--- a/packages/web/web-search-deepseek/package.json
+++ b/packages/web/web-search-deepseek/package.json
@@ -36,9 +36,9 @@
"@deepseek-ai/dsh-agent": "workspace:*",
"@deepseek-ai/dsh-credentials": "workspace:*",
"@deepseek-ai/dsh-launch-environment": "workspace:*",
- "@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
- "@deepseek-ai/dsh-web": "workspace:*"
+ "@deepseek-ai/dsh-web": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
},
"dependencies": {
"@deepseek-ai/schemastery": "workspace:~"
@@ -55,6 +55,7 @@
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-llm-deepseek-account": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
- "@deepseek-ai/dsh-web": "workspace:*"
+ "@deepseek-ai/dsh-web": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts
index b63dd86263..7e88cb90e4 100644
--- a/packages/web/web-search-deepseek/src/index.ts
+++ b/packages/web/web-search-deepseek/src/index.ts
@@ -1,9 +1,9 @@
/**
* Register a DeepSeek-backed provider in `ctx.web`. It calls the Anthropic-compatible Messages API
- * with native `web_search_20250305`. A search initiated by a Session whose latest model request used
- * a route that publishes an account credential through `ctx.llm.providerCredential()` authenticates with
- * that credential when the search endpoint has the origin of that route's base URL and the
- * credential's owner allows the endpoint; every other search reuses `DEEPSEEK_API_KEY`. The provider
+ * with native `web_search_20250305`. `ctx.deepseekAuth` releases its credential: a search initiated by
+ * a Session whose latest model request used the DeepSeek account route authenticates with the account
+ * sign-in when the search endpoint has the origin of that route's base URL and the account service
+ * allows the endpoint; every other search reuses `DEEPSEEK_API_KEY`. The provider
* does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own endpoint configuration. The
* provider reports itself not ready for a model request whose search would have no credential.
* @module @deepseek-ai/dsh-web-search-deepseek
@@ -13,11 +13,9 @@ import type { Volatile } from '@deepseek-ai/cordis'
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type {} from '@deepseek-ai/dsh-agent'
-import { credentialRef, credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials'
-import type { CredentialRef } from '@deepseek-ai/dsh-credentials'
+import { credentialRef } from '@deepseek-ai/dsh-credentials'
+import type { DeepSeekAuthRequest } from '@deepseek-ai/dsh-deepseek-auth'
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
-import { assertUsableApiKey } from '@deepseek-ai/dsh-llm'
-import type { ProviderCredential } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-web'
import {
@@ -44,8 +42,8 @@ export type { DeepSeekSearchLlmRequest, DeepSeekSearchProviderOptions } from './
/** Cordis plugin name used by loader diagnostics. */
export const name = 'web-search-deepseek'
-/** The web seam this provider registers into. */
-export const inject = ['web']
+/** The web seam this provider registers into, and the DeepSeek authentication its searches ask for credentials. */
+export const inject = ['web', 'deepseekAuth']
const DEFAULT_API_KEY_ENV = 'DEEPSEEK_API_KEY'
@@ -89,57 +87,62 @@ const SEARCH_BASE_URL_ENV = 'DEEPSEEK_SEARCH_BASE_URL'
/** Settings namespace carrying this provider's endpoint, model, and key reference. */
export const WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE = 'web-search-deepseek'
-/** Options for one search, with the key reference the readiness check reads. */
-type SearchOptions = DeepSeekSearchProviderOptions & { readonly apiKeyEnv: CredentialRef }
-
-/**
- * The account credential the model route `route` publishes for the deployment that serves `endpoint`. A route's
- * account credential is sent only to the origin of that route's base URL, whatever destinations its owner would
- * release it for.
- * @param ctx - plugin context supplying the optional model service.
- * @param route - provider route of a model request; undefined names none.
- * @param endpoint - absolute URL the search dispatches to.
- * @returns the route's account credential, or undefined for another kind, another origin, no credential, or no route.
- * @throws when the route's settings do not resolve, or its published base URL or `endpoint` does not parse.
- */
-function accountCredentialOf(ctx: Context, route: string | undefined, endpoint: string): ProviderCredential | undefined {
- const credential = route === undefined ? undefined : ctx.get('llm')?.providerCredential(route)
- if (credential?.kind !== 'account') return undefined
- return new URL(credential.baseURL).origin === new URL(endpoint).origin ? credential : undefined
+/** Options for one search, with what the search asks `ctx.deepseekAuth`. */
+type SearchOptions = DeepSeekSearchProviderOptions & {
+ /**
+ * The request a search to `endpoint` makes for a model request on `route`, or `undefined` when the literal key is
+ * the only credential it can send.
+ */
+ readonly authRequest: (route: string | undefined, endpoint: string) => DeepSeekAuthRequest | undefined
}
/**
* Project one resolved section into the options the provider serves its next
* search with. Environment fallbacks stay here rather than in the provider:
* every value it reads is already fully defaulted.
- * @param ctx - plugin context supplying the credential, model, and environment planes.
+ * @param ctx - plugin context supplying the DeepSeek authentication, the Agent registry, and the environment.
* @param config - the currently authoritative section.
* @returns options for one search.
*/
function resolveOptions(
ctx: Context, config: { [K in keyof Config]: ReturnType },
): SearchOptions {
- const apiKeyEnv = credentialRef(config.apiKeyEnv)
+ const reference = credentialRef(config.apiKeyEnv)
const literalApiKey = config.apiKey !== undefined && config.apiKey.length > 0
? config.apiKey
: undefined
+ const baseURL = config.baseURL
+ ?? launchEnvironmentOf(ctx).get(SEARCH_BASE_URL_ENV)?.value
+ ?? DEEPSEEK_DEFAULT_BASE_URL
+ const authRequest = (route: string | undefined, endpoint: string): DeepSeekAuthRequest | undefined => {
+ // The account sign-in pays only for a conversation on the account route, and only through that route.
+ const accountConversation = ctx.deepseekAuth.routeKind(route) === 'account'
+ if (literalApiKey !== undefined && !accountConversation) return undefined
+ return {
+ consumer: name,
+ // A literal key is this provider's own credential, so beside it only the account sign-in is asked for.
+ accepts: literalApiKey === undefined ? ['account', 'api-key'] : ['account'],
+ billing: accountConversation ? 'auto' : 'api-key',
+ route,
+ destination: { url: endpoint },
+ // The referenced key is this provider's own too: it goes to the search endpoint, whatever the API-key route uses.
+ connections: { 'api-key': { baseURL, reference } },
+ // Official DeepSeek expects `x-api-key`; an Anthropic-compatible proxy may expect `Authorization: Bearer`.
+ apiKeyHeaders: ['x-api-key', 'authorization'],
+ }
+ }
return {
...literalApiKey === undefined ? {} : { apiKey: literalApiKey },
- resolveAccountCredential: async (endpoint) => {
+ authRequest,
+ authorize: async (endpoint, signal) => {
// The latest request context names the route that served the model
// request which called this search, as account sign-out reads it.
const route = ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider
- const credential = accountCredentialOf(ctx, route, endpoint)
- return credential === undefined ? undefined : await credential.resolve(endpoint)
+ const request = authRequest(route, endpoint)
+ return request === undefined ? undefined : await ctx.deepseekAuth.authorize(request, signal)
},
- resolveApiKey: async () => {
- const value = await resolveCredentialRef(ctx, apiKeyEnv)
- return value === undefined ? undefined : assertUsableApiKey(value, name, apiKeyEnv)
- },
- apiKeyEnv,
- baseURL: config.baseURL
- ?? launchEnvironmentOf(ctx).get(SEARCH_BASE_URL_ENV)?.value
- ?? DEEPSEEK_DEFAULT_BASE_URL,
+ apiKeyEnv: reference,
+ baseURL,
model: config.model,
apiVersion: config.apiVersion,
maxTokens: config.maxTokens,
@@ -155,31 +158,27 @@ function resolveOptions(
/**
* Whether the search a model request on `route` would make has a credential, checked in the order
- * the search resolves them: the account credential the route publishes for the origin of the search
- * endpoint first, then the API key. A route whose settings do not resolve or whose published base URL
- * does not parse, or a failed read, answers false, because the search fails there
- * instead of trying the next credential. Only presence is checked: the API key's value is not read
- * and the endpoint is not contacted, so a wrong key or an endpoint without native search still
- * counts as configured.
- * @param ctx - plugin context supplying the model, credential, and environment planes.
+ * the search resolves them: on the account route the account sign-in, when the search endpoint has the
+ * origin of that route's base URL, then the API key. A route whose settings do not resolve, or a failed
+ * read, answers false, because the search fails there instead of trying the next credential. Only
+ * presence is checked: the API key's value is not read and the endpoint is not contacted, so a wrong
+ * key or an endpoint without native search still counts as configured.
+ * @param ctx - plugin context supplying the DeepSeek authentication.
* @param options - options the next search would use.
* @param route - provider route of the model request being assembled.
- * @returns whether the account credential or an API key is available to that search.
+ * @returns whether the account sign-in or an API key is available to that search.
*/
async function searchConfigured(
ctx: Context, options: SearchOptions, route: string | undefined,
): Promise {
- const endpoint = `${options.baseURL}/messages`
- let account: ProviderCredential | undefined
- try { account = accountCredentialOf(ctx, route, endpoint) }
- catch (_unresolvedRoute) { return false /* The search fails on this route before it reads any credential. */ }
- if (account !== undefined) {
- try { if (await account.configured(endpoint)) return true }
- catch (_unreadableGrant) { return false /* The search fails on this read before it tries the API key. */ }
+ const request = options.authRequest(route, `${options.baseURL}/messages`)
+ for (const candidate of request === undefined ? [] : ctx.deepseekAuth.candidates(request)) {
+ // The search stops at a route whose settings do not resolve before it reads any credential.
+ if ('unresolved' in candidate) return false
+ try { if (await candidate.configured()) return true }
+ catch (_unreadableCredential) { return false /* The search fails on this read before it tries the next credential. */ }
}
- if (options.apiKey !== undefined) return true
- try { return await credentialRefConfigured(ctx, options.apiKeyEnv) }
- catch (_unreadableStore) { return false /* A store that cannot be read supplies no key to the search either. */ }
+ return options.apiKey !== undefined
}
/**
diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts
index bff545d5cf..8bf8be3185 100644
--- a/packages/web/web-search-deepseek/src/provider.ts
+++ b/packages/web/web-search-deepseek/src/provider.ts
@@ -14,7 +14,7 @@ import type {
WebSearchSource,
} from '@deepseek-ai/dsh-web'
import type { CredentialRef } from '@deepseek-ai/dsh-credentials'
-import type { ProviderCredentialGrant } from '@deepseek-ai/dsh-llm'
+import type { DeepSeekAuthorization } from '@deepseek-ai/dsh-deepseek-auth'
import type {} from '@deepseek-ai/dsh-session'
import type {
AnthropicError,
@@ -94,17 +94,16 @@ declare module '@deepseek-ai/dsh-session/types' {
/** Resolved provider options (the plugin's `apply` supplies credential and constant defaults). */
export interface DeepSeekSearchProviderOptions {
/**
- * Resolve the DeepSeek account credential for one search endpoint. A credential takes
- * precedence over every API key and is sent only through the headers of its grant, which
- * also invalidates it after HTTP 401; a failure of that invalidation is contained, and the
- * search reports the HTTP rejection. The grant's `revoked` signal ends the search when the
- * account signs out. `undefined` selects API-key authentication.
+ * Release the credential `ctx.deepseekAuth` binds to one search endpoint: the account sign-in in a
+ * conversation the account bills, otherwise the referenced API key. A released credential takes
+ * precedence over the literal {@link apiKey} and is sent only through its headers. An account
+ * sign-in is invalidated through `reject` after HTTP 401; a failure of that invalidation is
+ * contained, and the search reports the HTTP rejection. Its `revoked` signal ends the search when
+ * the account signs out. `undefined` selects the literal key.
*/
- resolveAccountCredential?: (endpoint: string) => Promise
- /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */
+ authorize?: (endpoint: string, signal?: AbortSignal) => Promise
+ /** Literal DeepSeek API key, sent when {@link authorize} releases no credential. */
apiKey?: string
- /** Resolve the current DeepSeek API key for one search operation. */
- resolveApiKey?: () => Promise
/** Credential reference named by missing-credential diagnostics. */
apiKeyEnv?: CredentialRef
/** Endpoint base; `/messages` is appended. */
@@ -188,17 +187,11 @@ export function mapAnthropicResponse(response: AnthropicResponse): WebSearchResu
return { sources, truncated: false }
}
-/** Authentication headers for one search, tagged by the credential that produced them. */
-interface SearchAuth {
- /** `account` for a DeepSeek account credential, `api-key` for an API key. */
- readonly kind: 'account' | 'api-key'
- /** Headers carrying the credential. */
- readonly headers: Readonly>
- /** Request-bound invalidation, present when the sent account credential offers one. */
- readonly reject?: () => Promise
- /** Sign-out of the sent account credential, present when its grant offers one; it ends the request. */
- readonly revoked?: AbortSignal
-}
+/**
+ * The credential one search sends, tagged by its kind: the fields the search reads of an authorization
+ * `ctx.deepseekAuth` releases. `reject` invalidates a sent account sign-in, and `revoked` ends the request at sign-out.
+ */
+type SearchAuth = Pick
/**
* The DeepSeek-backed search provider. HTTP redirects fail as `WEB_PROVIDER_ERROR`;
@@ -229,8 +222,8 @@ export class DeepSeekSearchProvider implements WebSearchProvider {
available(): boolean {
const options = this.resolveOptions()
- return ((options.apiKey?.length ?? 0) > 0 || options.resolveApiKey !== undefined || options.resolveAccountCredential !== undefined)
- && URL.canParse(options.baseURL)
+ return ((options.apiKey?.length ?? 0) > 0 || options.authorize !== undefined)
+ && dispatchable(options.baseURL)
&& isPositiveInteger(options.maxTokens)
&& isPositiveInteger(options.maxUses)
}
@@ -337,45 +330,24 @@ export class DeepSeekSearchProvider implements WebSearchProvider {
}
/**
- * Resolve one operation's authentication headers without retaining a credential on the provider.
+ * Resolve one operation's credential without retaining it on the provider.
* @param options - the caller's snapshot, so the credential and the endpoint it is sent to come from one section.
* @param endpoint - the Messages endpoint this operation dispatches to.
* @param signal - abort signal for the surrounding search.
- * @returns the account credential's headers when one resolves, otherwise the API-key headers, tagged by credential kind.
+ * @returns the released credential when one resolves, otherwise the literal key in both API-key headers.
*/
private async authHeaders(
options: DeepSeekSearchProviderOptions, endpoint: string, signal?: AbortSignal,
): Promise {
- const { resolveAccountCredential } = options
- const credential = resolveAccountCredential === undefined
+ const { authorize, apiKey } = options
+ const released = authorize === undefined
? undefined
- : await resolveCredential(() => resolveAccountCredential(endpoint), signal)
- if (credential !== undefined) {
- const invalidate = credential.reject?.bind(credential)
- return {
- kind: 'account', headers: credential.headers,
- ...invalidate === undefined ? {} : { reject: invalidate },
- ...credential.revoked === undefined ? {} : { revoked: credential.revoked },
- }
- }
- const apiKey = await this.apiKey(options, signal)
+ : await resolveCredential(() => authorize(endpoint, signal), signal)
+ if (released !== undefined) return released
+ throwIfSearchAborted(signal)
// Official DeepSeek expects `x-api-key`; an Anthropic-compatible proxy
// may expect `Authorization: Bearer` — send both so either resolves.
- return { kind: 'api-key', headers: { 'x-api-key': apiKey, 'authorization': `Bearer ${apiKey}` } }
- }
-
- /**
- * Resolve one operation's API key without retaining it on the provider.
- * @param options - the caller's snapshot, so the key and the endpoint it is sent to come from one section.
- * @param signal - abort signal for the surrounding search.
- * @returns the resolved key.
- */
- private async apiKey(options: DeepSeekSearchProviderOptions, signal?: AbortSignal): Promise {
- throwIfSearchAborted(signal)
- if (options.apiKey !== undefined && options.apiKey.length > 0) return options.apiKey
- const { resolveApiKey } = options
- const resolved = resolveApiKey === undefined ? undefined : await resolveCredential(resolveApiKey, signal)
- if (resolved !== undefined && resolved.length > 0) return resolved
+ if (apiKey !== undefined && apiKey.length > 0) return { kind: 'api-key', headers: { 'x-api-key': apiKey, 'authorization': `Bearer ${apiKey}` } }
const ref = options.apiKeyEnv ?? 'DEEPSEEK_API_KEY'
throw new WebError(
`DeepSeek search has no API key for "${ref}"; store it through the credentials service`
@@ -412,7 +384,7 @@ async function resolveCredential(resolve: () => Promise, signal?: AbortSig
/**
* The signal one search runs under: the caller's cancellation and the sign-out of the account credential it carries.
* @param signal - caller cancellation, when the caller supplies one.
- * @param revoked - sign-out of the sent account credential, when its grant offers one.
+ * @param revoked - sign-out of the sent account credential, when its authorization offers one.
* @returns the composed signal, or undefined when neither exists.
*/
function requestSignal(signal: AbortSignal | undefined, revoked: AbortSignal | undefined): AbortSignal | undefined {
@@ -464,7 +436,12 @@ function searchEndpointError(endpoint: string, message: string, cause?: unknown)
*/
function abortable(operation: Promise, signal?: AbortSignal): Promise {
if (signal === undefined) return operation
- if (signal.aborted) return Promise.reject(searchAborted(signal))
+ if (signal.aborted) {
+ // The operation began before this check and can still reject: a credential read that cancels its caller, then
+ // fails on that cancellation. Observing it keeps that rejection from being unhandled.
+ void operation.catch(() => {})
+ return Promise.reject(searchAborted(signal))
+ }
return new Promise((resolve, reject) => {
const onAbort = (): void => { reject(searchAborted(signal)) }
signal.addEventListener('abort', onAbort, { once: true })
@@ -498,6 +475,13 @@ function isAbortError(error: unknown): boolean {
return error instanceof DOMException && error.name === 'AbortError'
}
+/** True for a base URL a search can be sent to: it parses and embeds no credentials, which `fetch` refuses to send. */
+function dispatchable(baseURL: string): boolean {
+ if (!URL.canParse(baseURL)) return false
+ const { username, password } = new URL(baseURL)
+ return username === '' && password === ''
+}
+
/** True for DeepSeek request limits that can be sent to the Messages API. */
function isPositiveInteger(value: number): boolean {
return Number.isInteger(value) && value > 0
diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts
index 3af5b9666e..39671251da 100644
--- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts
+++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts
@@ -12,8 +12,8 @@ import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local'
import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment'
import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account'
import LlmRuntime from '@deepseek-ai/dsh-llm'
-import type { ProviderCredential, ProviderCredentialGrant } from '@deepseek-ai/dsh-llm'
import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
import WebRuntime, { WebError, type WebSearchResult } from '@deepseek-ai/dsh-web'
import {
@@ -32,25 +32,39 @@ import { brandString } from '@deepseek-ai/dsh-brand'
const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchProvider =>
new DeepSeekSearchProvider(() => options)
+/** The provider's credential resolver. */
+type Authorize = NonNullable
+
/**
- * The account credential resolver a route publishes over `token`, with `reject` observing each invalidated token;
- * a throwing observer rejects the grant's invalidation, as an owner that does not contain its storage failures does.
- * `revoked` is the sign-out signal the grant carries, when given.
+ * A resolver releasing the account sign-in over `token`, as `ctx.deepseekAuth` releases one, with `reject` observing
+ * each invalidated token; a throwing observer rejects the invalidation, as an owner that does not contain its storage
+ * failures does. `revoked` is the sign-out signal the authorization carries, when given.
*/
function accountCredential(
token: (endpoint: string) => Promise, reject?: (token: string) => Promise, revoked?: AbortSignal,
-): (endpoint: string) => Promise {
+): Authorize {
return async (endpoint) => {
const value = await token(endpoint)
if (value === undefined || value.length === 0) return undefined
return {
- headers: { 'x-dsh-auth-token': value }, value,
+ kind: 'account', headers: { 'x-dsh-auth-token': value },
...reject === undefined ? {} : { reject: () => reject(value) },
...revoked === undefined ? {} : { revoked },
}
}
}
+/**
+ * A resolver releasing the referenced API key that `key` reads, in both API-key headers as `ctx.deepseekAuth` releases
+ * it for this provider; no key releases nothing.
+ */
+function keyCredential(key: () => Promise): Authorize {
+ return async () => {
+ const value = await key()
+ return value === undefined ? undefined : { kind: 'api-key', headers: { 'x-api-key': value, 'authorization': `Bearer ${value}` } }
+ }
+}
+
/** Return the provider's rejected WebError, or propagate an unexpected outcome. */
async function rejectedWebError(operation: Promise): Promise {
try {
@@ -202,13 +216,14 @@ describe('DeepSeekSearchProvider availability', () => {
expect(searchProvider(options).available()).toBe(true)
})
- it('is available with only an account token resolver', () => {
- expect(searchProvider({ ...options, apiKey: '', resolveAccountCredential: accountCredential(async () => 'account-token') }).available()).toBe(true)
+ it('is available with only a credential resolver', () => {
+ expect(searchProvider({ ...options, apiKey: '', authorize: accountCredential(async () => 'account-token') }).available()).toBe(true)
})
- it('is misconfigured when the base URL is unparseable', () => {
- expect(searchProvider({ ...options, baseURL: 'not a url' }).available()).toBe(false)
- })
+ it.each(['not a url', 'https://user@api.deepseek.test/anthropic/v1', 'https://:secret@api.deepseek.test/anthropic/v1'])(
+ 'is misconfigured when the base URL is %s, which does not parse or embeds credentials', (baseURL) => {
+ expect(searchProvider({ ...options, baseURL }).available()).toBe(false)
+ })
it('is misconfigured when request limits are not positive integers', () => {
expect(searchProvider({ ...options, maxTokens: 0 }).available()).toBe(false)
@@ -225,6 +240,7 @@ describe('DeepSeekSearchProvider request mapping', () => {
try {
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: { DEEPSEEK_API_KEY: value } }]))
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(deepseekPlugin)
await expect(ctx.web.search({ query: 'q' })).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' })
expect(fetchMock).not.toHaveBeenCalled()
@@ -285,22 +301,20 @@ describe('DeepSeekSearchProvider account authentication', () => {
}
}
- it('sends only the account token for the dispatched endpoint, ahead of a configured key', async () => {
+ it('sends only the released account token for the dispatched endpoint, ahead of the literal key', async () => {
const { first } = captureFetch()
const resolveAccountToken = vi.fn(async (_endpoint: string) => 'account-token')
- const resolveApiKey = vi.fn(async () => 'resolved-key')
- await searchProvider({ ...options, resolveAccountCredential: accountCredential(resolveAccountToken), resolveApiKey }).search({ query: 'q' })
+ await searchProvider({ ...options, authorize: accountCredential(resolveAccountToken) }).search({ query: 'q' })
const { url, headers } = first()
expect(resolveAccountToken).toHaveBeenCalledWith(url)
- expect(resolveApiKey).not.toHaveBeenCalled()
expect(headers['x-dsh-auth-token']).toBe('account-token')
expect(headers).not.toHaveProperty('x-api-key')
expect(headers).not.toHaveProperty('authorization')
})
- it.each([undefined, ''])('falls back to the API key when the account resolves %j', async (token) => {
+ it.each([undefined, ''])('sends the literal key when the account resolves %j and no credential is released', async (token) => {
const { first } = captureFetch()
- await searchProvider({ ...options, resolveAccountCredential: accountCredential(async () => token) }).search({ query: 'q' })
+ await searchProvider({ ...options, authorize: accountCredential(async () => token) }).search({ query: 'q' })
const { headers } = first()
expect(headers['x-api-key']).toBe('ds-key')
expect(headers).not.toHaveProperty('x-dsh-auth-token')
@@ -310,7 +324,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
const { fetchMock } = captureFetch()
await expect(searchProvider({
...options,
- resolveAccountCredential: accountCredential(() => Promise.reject(new Error('account storage failed'))),
+ authorize: accountCredential(() => Promise.reject(new Error('account storage failed'))),
}).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({
code: 'WEB_PROVIDER_ERROR',
@@ -323,7 +337,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'invalid token' } }, { status: 401 })))
const error = await rejectedWebError(searchProvider({
...options,
- resolveAccountCredential: accountCredential(async () => 'account-token'),
+ authorize: accountCredential(async () => 'account-token'),
}).search({ query: 'q' }))
expect(error).toMatchObject({
code: 'WEB_PROVIDER_ERROR',
@@ -337,7 +351,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
const rejectAccountToken = vi.fn(async (_token: string) => { if (fails) throw new Error('storage failed') })
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'invalid token' }, { status: 401 })))
const error = await rejectedWebError(searchProvider({
- ...options, resolveAccountCredential: accountCredential(async () => 'sent-token', rejectAccountToken),
+ ...options, authorize: accountCredential(async () => 'sent-token', rejectAccountToken),
}).search({ query: 'q' }))
expect(error.code).toBe('WEB_PROVIDER_ERROR')
expect(error.message).toBe('DeepSeek API error (HTTP 401): invalid token\n\n'
@@ -350,7 +364,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
const rejectAccountToken = vi.fn(async (_token: string) => {})
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status })))
const error = await rejectedWebError(searchProvider({
- ...options, resolveAccountCredential: accountCredential(async () => token, rejectAccountToken),
+ ...options, authorize: accountCredential(async () => token, rejectAccountToken),
}).search({ query: 'q' }))
expect(error.code).toBe('WEB_PROVIDER_ERROR')
expect(rejectAccountToken).not.toHaveBeenCalled()
@@ -366,7 +380,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
vi.stubGlobal('fetch', vi.fn(async () => response))
const rejectAccountToken = vi.fn(async (_token: string) => {})
const error = await rejectedWebError(searchProvider({
- ...options, resolveAccountCredential: accountCredential(async () => 'sent-token', rejectAccountToken),
+ ...options, authorize: accountCredential(async () => 'sent-token', rejectAccountToken),
}).search({ query: 'q' }, controller.signal))
expect(error.code).toBe('WEB_ABORTED')
expect(rejectAccountToken).toHaveBeenCalledExactlyOnceWith('sent-token')
@@ -376,7 +390,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
+ ' again; the search endpoint does not need changing.'
/** A provider authenticating with an account credential whose sign-out signal is `revoked`. */
const signedIn = (revoked: AbortSignal): DeepSeekSearchProvider =>
- searchProvider({ ...options, resolveAccountCredential: accountCredential(async () => 'account-token', undefined, revoked) })
+ searchProvider({ ...options, authorize: accountCredential(async () => 'account-token', undefined, revoked) })
it('ends an open search when the account signs out and reports sign-in guidance instead of a cancellation', async () => {
for (const signal of [undefined, new AbortController().signal]) {
@@ -428,7 +442,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 503 })))
const error = await rejectedWebError(searchProvider({
...options,
- resolveAccountCredential: accountCredential(async () => 'account-token'),
+ authorize: accountCredential(async () => 'account-token'),
}).search({ query: 'q' }))
expect(error.message).toContain('Search endpoint configuration is separate from chat.')
})
@@ -437,7 +451,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
const { fetchMock } = captureFetch()
await expect(searchProvider({
...options,
- resolveAccountCredential: accountCredential(() => { throw new Error('account service threw') }),
+ authorize: accountCredential(() => { throw new Error('account service threw') }),
}).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({
code: 'WEB_PROVIDER_ERROR',
@@ -446,32 +460,18 @@ describe('DeepSeekSearchProvider account authentication', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
- it('starts neither resolver for a pre-aborted call', async () => {
- const resolveAccountToken = vi.fn(async () => 'account-token')
- const resolveApiKey = vi.fn(async () => 'resolved-key')
+ it('does not send the literal key after cancellation during credential resolution', async () => {
+ const { fetchMock } = captureFetch()
const controller = new AbortController()
- controller.abort(new Error('caller stopped'))
- await expect(searchProvider({ ...options, apiKey: '', resolveAccountCredential: accountCredential(resolveAccountToken), resolveApiKey })
- .search({ query: 'q' }, controller.signal))
- .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
- expect(resolveAccountToken).not.toHaveBeenCalled()
- expect(resolveApiKey).not.toHaveBeenCalled()
- })
-
- it('does not start API-key resolution after cancellation during account resolution', async () => {
- const controller = new AbortController()
- const resolveApiKey = vi.fn(() => Promise.reject(new Error('must not run')))
await expect(searchProvider({
...options,
- apiKey: '',
- resolveAccountCredential: accountCredential(async () => {
+ authorize: accountCredential(async () => {
controller.abort(new Error('caller stopped'))
return undefined
}),
- resolveApiKey,
}).search({ query: 'q' }, controller.signal))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
- expect(resolveApiKey).not.toHaveBeenCalled()
+ expect(fetchMock).not.toHaveBeenCalled()
})
it('aborts while the account resolver remains pending', async () => {
@@ -479,7 +479,7 @@ describe('DeepSeekSearchProvider account authentication', () => {
const controller = new AbortController()
const search = searchProvider({
...options,
- resolveAccountCredential: accountCredential(() => new Promise(() => {})),
+ authorize: accountCredential(() => new Promise(() => {})),
}).search({ query: 'q' }, controller.signal)
controller.abort(new Error('deadline'))
await expect(search).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
@@ -501,7 +501,7 @@ describe('DeepSeekSearchProvider settings changes mid-search', () => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse()))
vi.stubGlobal('fetch', fetchMock)
- const provider = new DeepSeekSearchProvider(() => ({ ...current, resolveApiKey }))
+ const provider = new DeepSeekSearchProvider(() => ({ ...current, authorize: keyCredential(resolveApiKey) }))
const search = provider.search({ query: 'q' })
await vi.waitFor(() => { expect(typeof commitSettings).toBe('function') })
commitSettings()
@@ -527,7 +527,7 @@ describe('DeepSeekSearchProvider error handling', () => {
await expect(searchProvider({
...options,
apiKey: '',
- resolveApiKey,
+ authorize: keyCredential(resolveApiKey),
recordRequest,
}).search({ query: 'q' }, controller.signal))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
@@ -545,7 +545,7 @@ describe('DeepSeekSearchProvider error handling', () => {
const search = searchProvider({
...options,
apiKey: '',
- resolveApiKey,
+ authorize: keyCredential(resolveApiKey),
recordRequest,
}).search({ query: 'q' }, controller.signal)
controller.abort(new Error('deadline'))
@@ -562,7 +562,7 @@ describe('DeepSeekSearchProvider error handling', () => {
await expect(searchProvider({
...options,
apiKey: '',
- resolveApiKey: async () => 'resolved-key',
+ authorize: keyCredential(async () => 'resolved-key'),
}).search({ query: 'q' }, controller.signal)).resolves.toMatchObject({ truncated: false })
const [, init = {}] = fetchMock.mock.calls[0]!
expect((init.headers as Record)['x-api-key']).toBe('resolved-key')
@@ -573,7 +573,7 @@ describe('DeepSeekSearchProvider error handling', () => {
await expect(searchProvider({
...options,
apiKey: '',
- resolveApiKey: () => Promise.reject(new Error('credential backend failed')),
+ authorize: keyCredential(() => Promise.reject(new Error('credential backend failed'))),
}).search({ query: 'q' }, controller.signal))
.rejects.toThrow(expect.objectContaining({
code: 'WEB_PROVIDER_ERROR',
@@ -593,10 +593,10 @@ describe('DeepSeekSearchProvider error handling', () => {
await expect(searchProvider({
...options,
apiKey: '',
- resolveApiKey: () => {
+ authorize: keyCredential(() => {
controller.abort(new Error('resolver cancelled caller'))
return Promise.resolve('unused-key')
- },
+ }),
}).search({ query: 'q' }, controller.signal))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(fetchMock).not.toHaveBeenCalled()
@@ -699,6 +699,7 @@ describe('web-search-deepseek plugin registration', () => {
vi.stubGlobal('fetch', vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())))
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(DeepSeekAuth)
const fiber = await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' })
await expect(ctx.web.search({ query: 'q' })).resolves.toMatchObject({ truncated: false })
await fiber.dispose()
@@ -709,6 +710,7 @@ describe('web-search-deepseek plugin registration', () => {
it('rejects maxTokens: 0 at plugin construction', async () => {
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(deepseekPlugin, { apiKey: 'ds-key', maxTokens: 0 }))
.rejects.toThrow(/maxTokens expected number >= 1/)
})
@@ -716,6 +718,7 @@ describe('web-search-deepseek plugin registration', () => {
it('rejects maxUses: 0 at plugin construction', async () => {
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(deepseekPlugin, { apiKey: 'ds-key', maxUses: 0 }))
.rejects.toThrow(/maxUses expected number >= 1/)
})
@@ -723,6 +726,7 @@ describe('web-search-deepseek plugin registration', () => {
it('rejects a fractional maxUses at plugin construction', async () => {
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(DeepSeekAuth)
await expect(ctx.plugin(deepseekPlugin, { apiKey: 'ds-key', maxUses: 1.5 }))
.rejects.toThrow(/maxUses expected number multiple of 1/)
})
@@ -732,13 +736,13 @@ describe('web-search-deepseek plugin registration', () => {
})
it('survives the real Loader unwrapExports path keeping name/inject/Config', () => {
- // A default export would make `unwrapExports` collapse the namespace and drop `inject: ['web']`.
+ // A default export would make `unwrapExports` collapse the namespace and drop `inject`.
// Drive the real Loader path because hand-built namespace mounting cannot expose that failure.
const loader = Object.create(Loader.prototype) as Loader
const unwrapped = loader.unwrapExports(deepseekPlugin) as Record
expect(unwrapped).toBe(deepseekPlugin)
expect(unwrapped.name).toBe('web-search-deepseek')
- expect(unwrapped.inject).toEqual(['web'])
+ expect(unwrapped.inject).toEqual(['web', 'deepseekAuth'])
expect(typeof unwrapped.apply).toBe('function')
})
@@ -749,6 +753,7 @@ describe('web-search-deepseek plugin registration', () => {
const loader = Object.create(Loader.prototype) as Loader
const unwrapped = loader.unwrapExports(deepseekPlugin) as Parameters[0]
// A collapsed export shape (dropped inject) would throw "without inject" here.
+ await ctx.plugin(DeepSeekAuth)
const fiber = await ctx.plugin(unwrapped, { apiKey: 'ds-key' })
await expect(ctx.web.search({ query: 'q' })).resolves.toMatchObject({ truncated: false })
await fiber.dispose()
@@ -762,6 +767,7 @@ describe('web-search-deepseek plugin registration', () => {
vi.stubGlobal('fetch', fetchMock)
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(DeepSeekAuth)
deepseekPlugin.apply(ctx, deepseekPlugin.Config({}))
await ctx.web.search({ query: 'q' })
const [url, init = {}] = fetchMock.mock.calls[0]!
@@ -785,6 +791,7 @@ describe('web-search-deepseek plugin registration', () => {
try {
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
await ctx.plugin(LocalCredentialProvider, { path: join(dir, '.credentials.yaml'), watch: false })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(deepseekPlugin, { baseURL: 'https://api.deepseek.test/anthropic/v1' })
await expect(ctx.web.search({ query: 'missing' }))
@@ -812,6 +819,7 @@ describe('web-search-deepseek plugin registration', () => {
try {
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(deepseekPlugin, {})
let caught: unknown
try {
@@ -834,7 +842,7 @@ describe('web-search-deepseek account route selection', () => {
* initiator whose latest request context names `provider`.
* @param provider - route recorded by the initiating Session's request context; undefined runs the
* search without an initiator while a Session on the account route exists.
- * @param routeBaseURL - base URL of the mounted account route, whose origin its credential is published for.
+ * @param routeBaseURL - base URL of the mounted account route, whose origin receives the account sign-in.
* @returns the headers the search sent and the URLs the account was asked about.
*/
async function searchAs(
@@ -850,6 +858,7 @@ describe('web-search-deepseek account route selection', () => {
await ctx.plugin(AgentRegistry)
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(AccountRoute, { baseURL: routeBaseURL })
ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return 'account-token' } }))
await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' })
@@ -873,7 +882,7 @@ describe('web-search-deepseek account route selection', () => {
expect(headers).not.toHaveProperty('x-api-key')
})
- it('sends the API key when the account route publishes its credential for another origin, without asking the account', async () => {
+ it('sends the API key when the account route serves another origin, without asking the account', async () => {
// The stand-in account releases its token for every destination, so only the origin comparison withholds it.
const { headers, asked } = await searchAs('deepseek-account', 'https://other-deployment.test/anthropic')
expect(asked).toEqual([])
@@ -895,6 +904,7 @@ describe('web-search-deepseek account route selection', () => {
await ctx.plugin(AgentRegistry)
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(AccountRoute, { baseURL: ACCOUNT_ROUTE_BASE })
ctx.provide('deepseekAccount', accountStub({ token: () => current, reject: rejectToken }))
await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' })
@@ -910,7 +920,36 @@ describe('web-search-deepseek account route selection', () => {
}
})
- it.each(['deepseek-official', undefined])('keeps API-key authentication for route %j, whose published credential is no account', async (provider) => {
+ it('does not read the API key after the caller cancels during the account read', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ const controller = new AbortController()
+ const readKey = vi.fn(async () => ({ value: 'stored-key' }))
+ const ctx = new Context()
+ try {
+ await ctx.plugin(SessionStore)
+ await ctx.plugin(SessionProjectionRegistry)
+ await ctx.plugin(AgentRegistry)
+ await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
+ await ctx.plugin(AccountRoute, { baseURL: ACCOUNT_ROUTE_BASE })
+ ctx.provide('credentials', { resolve: readKey } as never)
+ ctx.provide('deepseekAccount', accountStub({ token: () => { controller.abort(new Error('caller stopped')); return undefined } }))
+ await ctx.plugin(deepseekPlugin)
+ const session = ctx.sessions.create(brandString('web-search-account-cancelled'))
+ session.append('turn/start', { turn: 1 })
+ session.append('request/context', { provider: 'deepseek-account', model: 'deepseek-v4-flash' })
+ const search = ctx.agents.withInitiator({ session } as Agent, () => ctx.web.search({ query: 'q' }, controller.signal))
+ await expect(search).rejects.toMatchObject({ code: 'WEB_ABORTED' })
+ expect(readKey).not.toHaveBeenCalled()
+ expect(fetchMock).not.toHaveBeenCalled()
+ } finally {
+ await ctx.fiber.dispose()
+ }
+ })
+
+ it.each(['deepseek-official', undefined])('keeps API-key authentication for route %j, which the account does not bill', async (provider) => {
const { headers, asked } = await searchAs(provider)
expect(asked).toEqual([])
expect(headers['x-api-key']).toBe('ds-key')
@@ -953,8 +992,8 @@ describe('web-search-deepseek search readiness', () => {
}
/**
- * Mount the web seam with the DeepSeek provider selected for search, beside the account model route whose
- * published credential the account route answers with.
+ * Mount the web seam with the DeepSeek provider selected for search, beside the DeepSeek authentication service and
+ * the account model route that connects the account deployment.
* @param setup - provider config, account double, and credential store.
* @returns the composed context.
*/
@@ -963,6 +1002,7 @@ describe('web-search-deepseek search readiness', () => {
mounted.push(ctx)
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
await ctx.plugin(LlmRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(AccountRoute, { baseURL: ACCOUNT_ROUTE_BASE })
if (setup.credentialsDir !== undefined) {
await ctx.plugin(LocalCredentialProvider, { path: join(setup.credentialsDir, '.credentials.yaml'), watch: false })
@@ -1070,19 +1110,18 @@ describe('web-search-deepseek search readiness', () => {
}
})
- it.each<[string, () => ProviderCredential, string]>([
+ it.each<[string, () => { baseURL: string }, string]>([
['settings do not resolve', () => { throw new Error('route settings do not resolve') }, 'route settings do not resolve'],
- ['published base URL does not parse', () => ({
- kind: 'account', baseURL: 'not a url', configured: () => Promise.resolve(true),
- resolve: () => Promise.resolve({ headers: { 'x-dsh-auth-token': 'account-token' }, value: 'account-token' }),
- }), 'Invalid URL'],
- ])('is not ready and fails the search when the initiating route\'s %s, despite a literal key', async (_fault, providerCredential, diagnostic) => {
+ ['base URL does not parse', () => ({ baseURL: 'not a url' }), 'Invalid URL'],
+ ])('is not ready and fails the search when the initiating route\'s %s, despite a literal key', async (_fault, accountRoute, diagnostic) => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse()))
vi.stubGlobal('fetch', fetchMock)
const ctx = new Context()
mounted.push(ctx)
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
- ctx.provide('llm', { providerCredential } as never)
+ await ctx.plugin(DeepSeekAuth)
+ // The account route plugin connects its settings this way; here they fail as broken route settings do.
+ ctx.effect(() => ctx.deepseekAuth.connect('account', 'deepseek-account', accountRoute))
await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' })
expect(await ctx.web.searchReady('deepseek-account')).toBe(false)
expect(await ctx.web.searchReady(undefined)).toBe(true)
@@ -1139,6 +1178,7 @@ describe('web-search-deepseek on any model route', () => {
await ctx.plugin(SessionProjectionRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID })
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(deepseekPlugin, config)
const session = ctx.sessions.create(brandString(`web-search-route-${route}`))
session.append('turn/start', { turn: 1 })
diff --git a/packages/web/web-search-deepseek/tests/settings.spec.ts b/packages/web/web-search-deepseek/tests/settings.spec.ts
index 26a9b21deb..eaf6e64c0b 100644
--- a/packages/web/web-search-deepseek/tests/settings.spec.ts
+++ b/packages/web/web-search-deepseek/tests/settings.spec.ts
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { liveConfig } from '../../../settings/settings/tests/live-config.ts'
import WebRuntime from '@deepseek-ai/dsh-web'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import * as deepseekPlugin from '@deepseek-ai/dsh-web-search-deepseek'
function jsonResponse(body: unknown): Response {
@@ -27,6 +28,7 @@ const ONE_RESULT = {
async function boot() {
const ctx = new Context()
await ctx.plugin(WebRuntime, {})
+ await ctx.plugin(DeepSeekAuth)
const live = await liveConfig(ctx, deepseekPlugin, { apiKey: 'ds-key', baseURL: 'https://search.entry.test/v1' })
return { ctx, live }
diff --git a/packages/web/web-search-deepseek/tsconfig.json b/packages/web/web-search-deepseek/tsconfig.json
index bb371f359c..b3a38ca330 100644
--- a/packages/web/web-search-deepseek/tsconfig.json
+++ b/packages/web/web-search-deepseek/tsconfig.json
@@ -36,7 +36,7 @@
"path": "../../util/http-proxy"
},
{
- "path": "../../llm/llm"
+ "path": "../../account/deepseek-auth"
}
]
}
diff --git a/packages/web/web/README.i18n.yaml b/packages/web/web/README.i18n.yaml
index 3e5a420ab2..58cecaa07c 100644
--- a/packages/web/web/README.i18n.yaml
+++ b/packages/web/web/README.i18n.yaml
@@ -21,8 +21,8 @@
en: 557a8a3f2dfebae4
zh: 3c85382484e4b717
/deepseek-ai-dsh-web/use-this-package/minimal-configuration:
- en: cb5267c425eef938
- zh: 26c3c04ee28c8c01
+ en: bbaef93914250552
+ zh: b594f4bb0b8f5a8d
/deepseek-ai-dsh-web/use-this-package/searching-and-fetching:
en: 713944abf68263cd
zh: c428cb53b8708e99
diff --git a/packages/web/web/README.md b/packages/web/web/README.md
index ace53aad16..f86af0941e 100644
--- a/packages/web/web/README.md
+++ b/packages/web/web/README.md
@@ -33,12 +33,13 @@ Choose the service when a plugin or tool must search or fetch without hard-codin
### Minimal configuration
-Load the service and let a single mounted backend auto-select, or pin a provider id with `searchProvider`/`fetchProvider`. The environment variables `$DSH_WEB_SEARCH_PROVIDER` and `$DSH_WEB_FETCH_PROVIDER` feed the same fields and are not a separate priority chain. Both backends below register a fetch provider, so the example pins `fetchProvider: http`.
+Load the service and let a single mounted backend auto-select, or pin a provider id with `searchProvider`/`fetchProvider`. The environment variables `$DSH_WEB_SEARCH_PROVIDER` and `$DSH_WEB_FETCH_PROVIDER` feed the same fields and are not a separate priority chain. Both backends below register a fetch provider, so the example pins `fetchProvider: http`. The DeepSeek backend requires [`dsh-deepseek-auth`](../../account/deepseek-auth/README.md) for its credentials.
```yaml
- name: '@deepseek-ai/dsh-web'
config:
fetchProvider: http
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-web-deepseek-api'
- name: '@deepseek-ai/dsh-web-fetch-http'
```
diff --git a/packages/web/web/README.zh.md b/packages/web/web/README.zh.md
index c1aca29ce9..6196cdce54 100644
--- a/packages/web/web/README.zh.md
+++ b/packages/web/web/README.zh.md
@@ -33,12 +33,13 @@ kind: "package-reference"
### 最小配置
-加载服务并让唯一挂载的后端自动选择,或用 `searchProvider`/`fetchProvider` 固定提供方 id。环境变量 `$DSH_WEB_SEARCH_PROVIDER` 与 `$DSH_WEB_FETCH_PROVIDER` 提供相同字段,不是另一条优先级链。下面两个后端都注册了抓取提供方,因此示例固定 `fetchProvider: http`。
+加载服务并让唯一挂载的后端自动选择,或用 `searchProvider`/`fetchProvider` 固定提供方 id。环境变量 `$DSH_WEB_SEARCH_PROVIDER` 与 `$DSH_WEB_FETCH_PROVIDER` 提供相同字段,不是另一条优先级链。下面两个后端都注册了抓取提供方,因此示例固定 `fetchProvider: http`。其中的 DeepSeek 后端要求挂载 [`dsh-deepseek-auth`](../../account/deepseek-auth/README.zh.md) 以取得凭据。
```yaml
- name: '@deepseek-ai/dsh-web'
config:
fetchProvider: http
+- name: '@deepseek-ai/dsh-deepseek-auth'
- name: '@deepseek-ai/dsh-web-deepseek-api'
- name: '@deepseek-ai/dsh-web-fetch-http'
```
diff --git a/packages/workflow/workflow-ptc/package.json b/packages/workflow/workflow-ptc/package.json
index 8303a8919c..1002b1452a 100644
--- a/packages/workflow/workflow-ptc/package.json
+++ b/packages/workflow/workflow-ptc/package.json
@@ -74,6 +74,7 @@
"@deepseek-ai/dsh-subprocess-local": "workspace:*",
"@deepseek-ai/dsh-sandbox-local": "workspace:*",
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*",
- "@deepseek-ai/dsh-working-directory": "workspace:*"
+ "@deepseek-ai/dsh-working-directory": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*"
}
}
diff --git a/packages/workflow/workflow-ptc/tests/workflow-ptc.e2e.ts b/packages/workflow/workflow-ptc/tests/workflow-ptc.e2e.ts
index c20b15ba80..ab982e8eec 100644
--- a/packages/workflow/workflow-ptc/tests/workflow-ptc.e2e.ts
+++ b/packages/workflow/workflow-ptc/tests/workflow-ptc.e2e.ts
@@ -8,6 +8,7 @@ import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
import SubagentRuntime from '@deepseek-ai/dsh-subagent'
import * as Spawn from '@deepseek-ai/dsh-subagent-spawn-in-process'
import PtcWorkflowEngine from '../src/index.ts'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import { mountPtcRuntime } from './setup.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
@@ -23,6 +24,7 @@ async function harness(): Promise {
await mountAgentLoopTestDependencies(built, { workingDirectory: true })
await mountPtcRuntime(built)
await built.plugin(AgentLoop, { agents: [] })
+ await built.plugin(DeepSeekAuth)
await built.plugin(LlmDeepSeek)
await built.plugin(SubagentRuntime)
await built.plugin(Spawn, { providerName: 'spawn' })
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4fbc412176..4a09ab92d3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -610,6 +610,9 @@ importers:
'@deepseek-ai/dsh-credentials-local':
specifier: workspace:*
version: link:../../packages/credentials/credentials-local
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../packages/account/deepseek-auth
'@deepseek-ai/dsh-deepseek-llm-api-extensions':
specifier: workspace:*
version: link:../../packages/llm/deepseek-llm-api-extensions
@@ -1377,6 +1380,24 @@ importers:
specifier: workspace:*
version: link:../../util/values
+ packages/account/deepseek-auth:
+ devDependencies:
+ '@deepseek-ai/cordis':
+ specifier: workspace:~
+ version: link:../../../vendor/cordis
+ '@deepseek-ai/dsh-credentials':
+ specifier: workspace:*
+ version: link:../../credentials/credentials
+ '@deepseek-ai/dsh-deepseek-account':
+ specifier: workspace:*
+ version: link:../deepseek-account
+ '@deepseek-ai/dsh-error':
+ specifier: workspace:*
+ version: link:../../util/error
+ '@deepseek-ai/dsh-launch-environment':
+ specifier: workspace:*
+ version: link:../../util/launch-environment
+
packages/acp/acp:
dependencies:
'@agentclientprotocol/sdk':
@@ -2581,6 +2602,9 @@ importers:
'@deepseek-ai/dsh-deepseek-account':
specifier: workspace:*
version: link:../../account/deepseek-account
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-deepseek-llm-api-extensions':
specifier: workspace:*
version: link:../../llm/deepseek-llm-api-extensions
@@ -2965,6 +2989,9 @@ importers:
'@deepseek-ai/dsh-compaction-image-offload':
specifier: workspace:*
version: link:../../compaction/compaction-image-offload
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-deepseek-llm-api-extensions':
specifier: workspace:*
version: link:../../llm/deepseek-llm-api-extensions
@@ -7997,6 +8024,9 @@ importers:
'@deepseek-ai/dsh-brand':
specifier: workspace:*
version: link:../../util/brand
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-fs':
specifier: workspace:*
version: link:../../fs/fs
@@ -8404,6 +8434,9 @@ importers:
'@deepseek-ai/dsh-agent':
specifier: workspace:*
version: link:../agent
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-llm':
specifier: workspace:*
version: link:../../llm/llm
@@ -9042,6 +9075,9 @@ importers:
'@deepseek-ai/dsh-compaction':
specifier: workspace:*
version: link:../../compaction/compaction
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-fs-local':
specifier: workspace:*
version: link:../../fs/fs-local
@@ -12668,6 +12704,9 @@ importers:
'@deepseek-ai/dsh-deepseek-account':
specifier: workspace:*
version: link:../../account/deepseek-account
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-deepseek-llm-api-extensions':
specifier: workspace:*
version: link:../../llm/deepseek-llm-api-extensions
@@ -13415,6 +13454,9 @@ importers:
'@deepseek-ai/dsh-attachment':
specifier: workspace:*
version: link:../../attachment/attachment
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-error':
specifier: workspace:*
version: link:../../util/error
@@ -14519,6 +14561,9 @@ importers:
'@deepseek-ai/dsh-deepseek-account':
specifier: workspace:*
version: link:../../account/deepseek-account
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-deepseek-llm-api-extensions':
specifier: workspace:*
version: link:../deepseek-llm-api-extensions
@@ -14601,6 +14646,9 @@ importers:
'@deepseek-ai/dsh-deepseek-account':
specifier: workspace:*
version: link:../../account/deepseek-account
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-launch-environment':
specifier: workspace:*
version: link:../../util/launch-environment
@@ -14632,6 +14680,9 @@ importers:
'@deepseek-ai/dsh-credentials':
specifier: workspace:*
version: link:../../credentials/credentials
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-launch-environment':
specifier: workspace:*
version: link:../../util/launch-environment
@@ -14675,6 +14726,9 @@ importers:
'@deepseek-ai/dsh-credentials':
specifier: workspace:*
version: link:../../credentials/credentials
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-fs':
specifier: workspace:*
version: link:../../fs/fs
@@ -14739,6 +14793,9 @@ importers:
'@deepseek-ai/dsh-agent-loop-testkit':
specifier: workspace:*
version: link:../../test-support/agent-loop-testkit
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-llm':
specifier: workspace:*
version: link:../llm
@@ -15758,6 +15815,9 @@ importers:
'@deepseek-ai/dsh-compaction-basic':
specifier: workspace:*
version: link:../../compaction/compaction-basic
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-goal':
specifier: workspace:*
version: link:../../goal/goal
@@ -16248,6 +16308,9 @@ importers:
'@deepseek-ai/dsh-command-feedback':
specifier: workspace:*
version: link:../../feedback/command-feedback
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-deepseek-llm-api-extensions':
specifier: workspace:*
version: link:../../llm/deepseek-llm-api-extensions
@@ -16602,6 +16665,9 @@ importers:
'@deepseek-ai/dsh-agent-loop':
specifier: workspace:*
version: link:../../core/agent-loop
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-llm':
specifier: workspace:*
version: link:../../llm/llm
@@ -18321,6 +18387,9 @@ importers:
'@deepseek-ai/dsh-brand':
specifier: workspace:*
version: link:../../util/brand
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-llm':
specifier: workspace:*
version: link:../../llm/llm
@@ -19478,6 +19547,9 @@ importers:
'@deepseek-ai/dsh-brand':
specifier: workspace:*
version: link:../../util/brand
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-launch-environment':
specifier: workspace:*
version: link:../../util/launch-environment
@@ -19573,6 +19645,9 @@ importers:
'@deepseek-ai/dsh-deepseek-account':
specifier: workspace:*
version: link:../../account/deepseek-account
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:*
version: link:../../util/http-proxy
@@ -19644,6 +19719,9 @@ importers:
'@deepseek-ai/dsh-deepseek-account':
specifier: workspace:*
version: link:../../account/deepseek-account
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-http-proxy':
specifier: workspace:*
version: link:../../util/http-proxy
@@ -19763,6 +19841,9 @@ importers:
'@deepseek-ai/dsh-agent-loop-testkit':
specifier: workspace:*
version: link:../../test-support/agent-loop-testkit
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../account/deepseek-auth
'@deepseek-ai/dsh-fs':
specifier: workspace:*
version: link:../../fs/fs
@@ -19977,6 +20058,9 @@ importers:
'@deepseek-ai/dsh-deepseek-account':
specifier: workspace:*
version: link:../../packages/account/deepseek-account
+ '@deepseek-ai/dsh-deepseek-auth':
+ specifier: workspace:*
+ version: link:../../packages/account/deepseek-auth
'@deepseek-ai/dsh-deepseek-llm-api-extensions':
specifier: workspace:*
version: link:../../packages/llm/deepseek-llm-api-extensions
diff --git a/python/sdk-runtime/package.json b/python/sdk-runtime/package.json
index bf94634746..4a8bf0e61d 100644
--- a/python/sdk-runtime/package.json
+++ b/python/sdk-runtime/package.json
@@ -45,6 +45,7 @@
"@deepseek-ai/dsh-cordis-host-runner": "workspace:*",
"@deepseek-ai/dsh-credentials": "workspace:*",
"@deepseek-ai/dsh-deepseek-account": "workspace:*",
+ "@deepseek-ai/dsh-deepseek-auth": "workspace:*",
"@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-file-reference": "workspace:*",
diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts
index 546a326ac2..af11b181e5 100644
--- a/scripts/gen-cordis-catalog.ts
+++ b/scripts/gen-cordis-catalog.ts
@@ -92,6 +92,7 @@ export const SERVICE_PAGE: Record = {
cordisInspect: 'extensions.md',
authorization: 'credentials.md',
deepseekAccount: 'account.md',
+ deepseekAuth: 'account.md',
credentials: 'credentials.md',
credentialsController: 'credentials.md',
settingsController: 'settings.md',
@@ -497,7 +498,6 @@ export const LINK_MAP: Readonly> = {
LlmResolvedModelInfo: 'llm-streaming.md',
LlmFailure: 'llm-streaming.md',
LlmImageRequestPricing: 'llm-streaming.md',
- ProviderCredential: 'llm-streaming.md',
LlmModelInfo: 'llm-streaming.md',
LlmProviderInfo: 'llm-streaming.md',
LlmConfigurableProvider: 'llm-streaming.md',
@@ -934,6 +934,15 @@ export const LINK_MAP: Readonly> = {
AccountUserId: 'account.md',
PlatformSession: 'account.md',
SignInAttemptId: 'account.md',
+ DeepSeekApiKeyHeader: 'account.md',
+ DeepSeekAuthBilling: 'account.md',
+ DeepSeekAuthCandidate: 'account.md',
+ DeepSeekAuthConnection: 'account.md',
+ DeepSeekAuthDestination: 'account.md',
+ DeepSeekAuthKind: 'account.md',
+ DeepSeekAuthRequest: 'account.md',
+ DeepSeekAuthUnresolved: 'account.md',
+ DeepSeekAuthorization: 'account.md',
AuthorizationPrompt: 'credentials.md',
AuthorizationRequest: 'credentials.md',
AuthorizationSession: 'credentials.md',
diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts
index ee39f0e039..5b9d25f473 100644
--- a/scripts/gen-doc-graphs.ts
+++ b/scripts/gen-doc-graphs.ts
@@ -324,8 +324,8 @@ const SERVICE_ROLES: ServiceRole[] = [
title: 'LLM adapter registry',
mode: 'seam',
implementations: ['llm-deepseek', 'llm-pi-ai', 'llm-replay'],
- consumers: ['agent-loop', 'compaction-basic', 'web-deepseek-api', 'web-search-deepseek'],
- note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service, and the DeepSeek web providers read the credential a route publishes.',
+ consumers: ['agent-loop', 'compaction-basic'],
+ note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.',
},
{
key: 'sessionLogDeepSeek',
@@ -522,7 +522,7 @@ const SERVICE_ROLES: ServiceRole[] = [
title: 'Credential seam',
mode: 'seam',
implementations: ['credentials-local'],
- consumers: ['api-settings-controller', 'llm-deepseek-api-key', 'llm-pi-ai', 'web-deepseek-api', 'web-search-deepseek'],
+ consumers: ['api-settings-controller', 'deepseek-auth', 'llm-pi-ai'],
note: 'Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage.',
},
{
@@ -531,8 +531,17 @@ const SERVICE_ROLES: ServiceRole[] = [
title: 'DeepSeek account',
mode: 'service',
implementations: [],
- consumers: ['llm-deepseek-account', 'web-deepseek-api'],
- note: 'The Host owns browser authorization and local credentials and releases per-request credentials to the account model route and the web providers; UI consumers receive state without tokens.',
+ consumers: ['deepseek-auth', 'llm-deepseek-account'],
+ note: 'The Host owns browser authorization and local credentials and releases per-request credentials to DeepSeek request authentication; the account model route registers its running-task report, and UI consumers receive state without tokens.',
+ },
+ {
+ key: 'deepseekAuth',
+ pkg: 'deepseek-auth',
+ title: 'DeepSeek request authentication',
+ mode: 'service',
+ implementations: [],
+ consumers: ['llm-deepseek-account', 'llm-deepseek-api-key', 'web-deepseek-api', 'web-search-deepseek'],
+ note: 'Every DeepSeek API consumer names the credential kinds its API accepts; the service orders the API key and the account sign-in by billing, binds each to its deployment, and releases request headers.',
},
{
key: 'authorization',
diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts
index b8a9c958c7..a65863932c 100644
--- a/scripts/gen-tool-catalog.ts
+++ b/scripts/gen-tool-catalog.ts
@@ -39,6 +39,7 @@ import type { ImageAttachmentLimits, ImageAttachmentRef, SaveImageAttachment, St
import UserQuestionService from '@deepseek-ai/dsh-user-questions'
import PlanModeController from '@deepseek-ai/dsh-plan-mode'
import WebRuntime from '@deepseek-ai/dsh-web'
+import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import * as WebDeepSeekApi from '@deepseek-ai/dsh-web-deepseek-api'
import * as WebFetchLocal from '@deepseek-ai/dsh-web-fetch-http'
import SubagentRuntime from '@deepseek-ai/dsh-subagent'
@@ -762,8 +763,10 @@ const TOOL_PACKAGES: ToolPackage[] = [
writes: ['tool/call', 'tool/result'],
async mount(ctx) {
// Mount search and fetch providers so both tools register. Their schemas
- // do not depend on provider identity or availability.
+ // do not depend on provider identity or availability. The DeepSeek
+ // provider starts only beside the authentication service.
await ctx.plugin(WebRuntime)
+ await ctx.plugin(DeepSeekAuth)
await ctx.plugin(WebDeepSeekApi)
await ctx.plugin(WebFetchLocal)
await ctx.plugin(ToolWeb)
diff --git a/scripts/plugin-entry-existing-exports.ts b/scripts/plugin-entry-existing-exports.ts
index 15f2878f72..ec0b258596 100644
--- a/scripts/plugin-entry-existing-exports.ts
+++ b/scripts/plugin-entry-existing-exports.ts
@@ -89,13 +89,13 @@ export const EXISTING_PLUGIN_ENTRY_EXPORTS = {
'CONTEXT_SUMMARY_MAX_CHARS', 'CONTEXT_WINDOW_EXCEEDED_CODE', 'EMPTY_RESPONSE_CODE', 'IMAGE_OFFLOAD_REQUIRED_CODE',
'INVALID_CREDENTIAL_CODE', 'LLM_FAILURE_CODES', 'LlmAdapter', 'LlmAttemptId', 'MessageId', 'ProviderRequestId',
'QUOTA_EXCEEDED_CODE', 'RETRY_CODE_CHOICES', 'ReasoningEffortId', 'RetryPolicySchema', 'ToolCallId',
- 'assembleAssistantStream', 'assertUsableApiKey', 'assistantStreamChunks', 'assistantStreamFirstTokenTime',
+ 'assembleAssistantStream', 'assistantStreamChunks', 'assistantStreamFirstTokenTime',
'assistantStreamHasVisibleContent', 'assistantStreamHasVisibleText', 'attributionHeaders', 'boundContextSummary',
'callConfigEquals', 'chunkHasVisibleText', 'contentHasFile', 'contentHasImage', 'createAssistantMessage',
'createDeveloperMessage', 'createMessage', 'createSystemMessage', 'createToolResultMessage', 'createUserMessage',
'errorChain', 'expandAssistantStream', 'fileHandleText', 'freezeMessage', 'isAgentLoopRequest',
'isContextWindowExceededError', 'isHarnessError', 'isQuotaExceededError', 'isTokenDelta', 'isVisibleChunk',
- 'joinAssistantStreamText', 'lastAssistantStreamChunk', 'markAgentLoopRequest', 'normalizeApiKey',
+ 'joinAssistantStreamText', 'lastAssistantStreamChunk', 'markAgentLoopRequest',
'offloadedImageText', 'projectFilesToText', 'projectImagesForTextModel', 'projectOffloadedImages',
'projectToolUpdates', 'requestImageHandleText', 'requiredImageOffload', 'resolveImageAttachmentAccess',
'resolveRetryPolicy', 'runFirstTokenTime', 'runFirstVisibleTime', 'textOnlyImageText', 'userAgent',
diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json
index d515279af7..05227e60b8 100644
--- a/scripts/type-equiv.manifest.json
+++ b/scripts/type-equiv.manifest.json
@@ -1848,16 +1848,6 @@
"symbol": "LlmNativeAuth",
"source": "packages/llm/llm/src/types.ts"
},
- {
- "doc": "docs/subsystems/llm-streaming.md",
- "symbol": "ProviderCredentialGrant",
- "source": "packages/llm/llm/src/types.ts"
- },
- {
- "doc": "docs/subsystems/llm-streaming.md",
- "symbol": "ProviderCredential",
- "source": "packages/llm/llm/src/types.ts"
- },
{
"doc": "docs/subsystems/permission-presets.md",
"symbol": "Config",
diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts
index b22a1cea60..6816992ff0 100644
--- a/scripts/verify-package-readme-model-experience.ts
+++ b/scripts/verify-package-readme-model-experience.ts
@@ -94,6 +94,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = {
'packages/computer-use/computer-use': { kind: 'none', reason: 'The registry only reserves provider names; providers own all model-facing tools and guidance.' },
'packages/document/office-kit': { kind: 'indirect', reason: 'The provider returns rendered and converted bytes; the Office tools own their model-visible results.' },
+ 'packages/account/deepseek-auth': { kind: 'none', reason: 'Request authentication releases HTTP headers to Host plugins and registers no model context or tools.' },
'packages/account/deepseek-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' },
'packages/client/ui-settings-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' },
'packages/client/ui-account-notifications': { kind: 'none', reason: 'Account notification presentation and polling add no model input or Session events.' },
diff --git a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs
index 760695f765..5c5861132a 100644
--- a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs
+++ b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs
@@ -37,7 +37,7 @@ export async function apply(ctx, config) {
const signedOut = new AbortController()
ctx.provide('deepseekAccount', {
resolveRequestCredential: async endpoint => endpoint.startsWith('https://api.deepseek.com/')
- ? { headers: { 'x-dsh-auth-token': ACCOUNT_TOKEN }, value: ACCOUNT_TOKEN, revoked: signedOut.signal, reject: async () => {} }
+ ? { headers: { 'x-dsh-auth-token': ACCOUNT_TOKEN }, revoked: signedOut.signal, reject: async () => {} }
: undefined,
})
let restoreFetch = () => {}
diff --git a/tsconfig.base.json b/tsconfig.base.json
index 81d372e5d6..25774a0a52 100644
--- a/tsconfig.base.json
+++ b/tsconfig.base.json
@@ -483,6 +483,7 @@
"@deepseek-ai/dsh-credentials-local": ["./packages/credentials/credentials-local/src"],
"@deepseek-ai/dsh-cua-bundle": ["./packages/experimental/cua-bundle/src"],
"@deepseek-ai/dsh-cua-mcp": ["./packages/experimental/cua-mcp/src"],
+ "@deepseek-ai/dsh-deepseek-auth": ["./packages/account/deepseek-auth/src"],
"@deepseek-ai/dsh-deepseek-chat-import": ["./packages/experimental/deepseek-chat-import/src"],
"@deepseek-ai/dsh-deepseek-llm-api-extensions": ["./packages/llm/deepseek-llm-api-extensions/src"],
"@deepseek-ai/dsh-deliverable-file-references": ["./packages/deliverables/deliverable-file-references/src"],
diff --git a/tsconfig.host.json b/tsconfig.host.json
index 788e3642a4..61eaffea03 100644
--- a/tsconfig.host.json
+++ b/tsconfig.host.json
@@ -351,6 +351,7 @@
{ "path": "./packages/document/tool-office" },
{ "path": "./packages/account/deepseek-account" },
+ { "path": "./packages/account/deepseek-auth" },
{ "path": "./packages/client/ui-deliverables/tsconfig.host.json" },
{ "path": "./vendor/cosmokit" },
{ "path": "./vendor/schemastery" },