refactor(web): 按有序凭据来源执行 Search/Fetch 认证

This commit is contained in:
yudshj committed 2026-11-05 12:06:14 +08:00
1 parent 483dfc223f
commit 6bcf6ee314
23 files changed
+626 -577

No files matched your search

@@ -18,8 +18,8 @@
en: 9d68ffca5c8be681
zh: 36bb661f98de0ebb
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/credential-resolution:
en: 7ebcfe94ab4dbff5
zh: 0e58c91daff60547
en: 15f6fb26c8605260
zh: 93467641a8ff0aad
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections:
en: 5fcd3319fbceed1d
zh: 20771646b9c36fa6
@@ -30,7 +30,7 @@ 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 token is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the active `@deepseek-ai/dsh-llm-deepseek-account` Loader entry at the entry root that the model provider directory lists, with `/v1/tools`; without that entry, the origin of that route's default base URL is used. An HTTP 401 invalidates that token. With `auto` billing on the `deepseek-account` route, the operation sends the account token when that entry exists and a token is released. Every other `auto` operation, including one in an account conversation without a sign-in or a token, sends the key under the `apiKeyEnv` of the active `@deepseek-ai/dsh-llm-deepseek-api-key` entry for `deepseek-official`, resolved with that package's own resolver (including `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that entry, `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 entry whose settings its resolver rejects is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` without reading a credential or sending the request, so a broken gateway setting never redirects requests to the official endpoint.
The account token is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the active `@deepseek-ai/dsh-llm-deepseek-account` Loader entry at the entry root that the model provider directory lists, with `/v1/tools`; without that entry, the origin of that route's default base URL is used. An HTTP 401 invalidates that token. With `auto` billing on the `deepseek-account` route, the operation sends the account token when that entry exists and a token is released. Every other `auto` operation, including one in an account conversation without a sign-in or a token, sends the key under the `apiKeyEnv` of the active `@deepseek-ai/dsh-llm-deepseek-api-key` entry for `deepseek-official`, resolved with that package's own resolver (including `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that entry, `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 entry whose settings its resolver rejects 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.
@@ -30,7 +30,7 @@ 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-ai/dsh-llm-deepseek-account` Loader 条目的 origin 加 `/v1/tools` 下的请求端点给出的令牌;没有该条目时使用该路由默认基础地址的 origin。HTTP 401 会作废该令牌。`auto` 计费在 `deepseek-account` 路由上,若存在该条目且取得令牌,操作发送账号令牌。其他所有 `auto` 操作,包括账号会话中没有登录或没有令牌的操作,都把 `deepseek-official` 的活动 `@deepseek-ai/dsh-llm-deepseek-api-key` 条目的 `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-ai/dsh-llm-deepseek-account` Loader 条目的 origin 加 `/v1/tools` 下的请求端点给出的令牌;没有该条目时使用该路由默认基础地址的 origin。HTTP 401 会作废该令牌。`auto` 计费在 `deepseek-account` 路由上,若存在该条目且取得令牌,操作发送账号令牌。其他所有 `auto` 操作,包括账号会话中没有登录或没有令牌的操作,都把 `deepseek-official` 的活动 `@deepseek-ai/dsh-llm-deepseek-api-key` 条目的 `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` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。
在 YAML 中设置了非空 `searchBaseURL` 或 `searchApiKeyEnv`(Fetch 为 `fetchBaseURL` 或 `fetchApiKeyEnv`)的能力,则无论计费方式如何,始终把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为官方基础地址),从不发送账号令牌,因此内网或第三方端点只收到为它选择的密钥。每个能力有自己的字段,因为一个部署可以由不同网关提供搜索和抓取。这些字段只能在 YAML 中设置,空值视为未设置。schema 之外字段的已保存值,包括 `baseURL`、`apiKeyEnv` 和 `apiKey`,可以加载而不产生 schema 错误,且不生效。
+1 -1
View File
@@ -4699,7 +4699,7 @@ export interface Config {
- `inject`: `web`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/web/web-deepseek-api/src/index.ts:62`](../packages/web/web-deepseek-api/src/index.ts)
- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts)
```ts config-catalog
/**
+1 -1
View File
@@ -4701,7 +4701,7 @@ export interface Config {
- `inject`: `web`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/web/web-deepseek-api/src/index.ts:62`](../packages/web/web-deepseek-api/src/index.ts)
- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts)
```ts config-catalog
/**
@@ -3,14 +3,14 @@
# 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.1/web-search-billing/guide.md
/:
en: 06cd61d28600c5f1
zh: 4956df9d055a3ee0
en: d5f047c8126e2039
zh: 921852a96d5fdaf2
/deepseek-web-search-and-fetch-choose-their-credential-by-billing:
en: 5b4ad8a6553f2017
zh: 33d0dbee4bbadad8
/deepseek-web-search-and-fetch-choose-their-credential-by-billing/change:
en: d22ed11c422be0e4
zh: 0fed8534bd1c6923
en: c479258a05c03e30
zh: 9479ed43eebd03c2
/deepseek-web-search-and-fetch-choose-their-credential-by-billing/migration:
en: 2253ee5ecba49a94
zh: eeabad2fee18a978
en: f02650a1b0730ecf
zh: e6ddb011af754005
@@ -1,6 +1,6 @@
---
kind: upgrade-guide
description: "DeepSeek web search and fetch bill the signed-in DeepSeek account when a conversation on another model provider has no DeepSeek API key; new searchBilling and fetchBilling settings choose the credential."
description: "DeepSeek Search and Fetch add per-capability billing and replace provider authentication fields with ordered credential sources."
---
# DeepSeek web search and fetch choose their credential by billing
@@ -9,11 +9,15 @@ English | [中文](guide.zh.md)
## Change
Previously, the DeepSeek Search API and Fetch API (`web-deepseek-api`) sent the DeepSeek account token only in conversations on the `deepseek-account` model provider; every other operation sent the DeepSeek API key, and without a key it failed and the model did not see `web_search` or `web_fetch`. Now each capability has a billing setting, `searchBilling` and `fetchBilling`, with the values `auto` (the default), `account`, and `api-key`. With `auto`, conversations on `deepseek-account` and `deepseek-official` behave as before, but a conversation on another model provider, or an operation outside a conversation, that has no DeepSeek API key now bills the signed-in DeepSeek account instead of failing. `account` always sends only the account token, and `api-key` always sends only the API key. Settings with `searchBaseURL`, `searchApiKeyEnv`, `fetchBaseURL`, or `fetchApiKeyEnv` ignore billing and are unchanged. Signed-in users without a DeepSeek API key who chat on other model providers are affected; users with a key, or without a sign-in, see no change.
The DeepSeek Search and Fetch APIs (`web-deepseek-api`) previously used the signed-in account only in `deepseek-account` conversations; other conversations required an API key. New `searchBilling` and `fetchBilling` settings accept `auto` (default), `account`, or `api-key`. With `auto`, DeepSeek model routes behave as before; other conversations and operations outside a Session now use the signed-in account when no key exists. `account` uses only the account; `api-key` only the key. Non-empty `*BaseURL` or `*ApiKeyEnv` settings still take precedence. Other providers, including local HTTP fetch, are unaffected.
In TypeScript, `DeepSeekSearchApiOptions` and `DeepSeekFetchApiOptions` lose their top-level `baseURL`. Their `auth` becomes `{ sources, missingCredentialMessage? }`. Each account or API-key source carries its own address; list order replaces the implicit account-first order. Direct provider constructors must migrate.
With an `AbortSignal`, credential-read errors now retain the original `Error` as `cause` and its name in the diagnostic without an extra `Error:` wrapper. A resolver throwing a DOMException named `AbortError` now yields `WEB_ABORTED`, not `WEB_PROVIDER_ERROR`, even when that signal is not aborted. The no-signal path already behaves this way.
## Migration
1. To keep the earlier behavior, which never bills the account outside account conversations, set both capabilities to `api-key`: in **Plugins > Built-in plugin settings > Web search and fetch**, choose **DeepSeek API key** in each **Billing** menu, or set the keys on the `web-deepseek-api` row:
1. To disable the new account fallback, set both capabilities to `api-key` on the `web-deepseek-api` row, or choose **DeepSeek API key** under **Plugins > Built-in plugin settings > Web search and fetch** when each DeepSeek API is selected:
```yaml
- name: '@deepseek-ai/dsh-web-deepseek-api'
@@ -22,5 +26,16 @@ Previously, the DeepSeek Search API and Fetch API (`web-deepseek-api`) sent the
fetchBilling: api-key
```
This also stops account billing in conversations on `deepseek-account`.
2. Confirm: in a conversation on another model provider without a DeepSeek API key, the model no longer offers `web_search` or `web_fetch`, and with a key a search succeeds.
This also disables account billing in account conversations; it does not fully restore the old route-dependent behavior.
2. Migrate direct `DeepSeekSearchApiProvider` and `DeepSeekFetchApiProvider` constructors. The table describes TypeScript options, not YAML settings:
| Old option | Replacement |
|---|---|
| `baseURL: base`, `auth.apiKey: key` | `auth.sources: [{ kind: 'api-key', baseURL: base, key }]` |
| `auth.resolveApiKey`, `auth.apiKeyEnv` | An API-key source with `key: { ref, configured, resolve }`. Keep the reference (`DEEPSEEK_API_KEY` when omitted); `configured()` checks presence without reading the value, and `resolve()` reads it. |
| `auth.account` | `{ kind: 'account', ...account }`; preserve its address and callbacks. Place it before the Key source to retain account-first behavior. |
| `auth.missingKeyMessage` | `auth.missingCredentialMessage` |
| `auth.invalidRoute` | `{ kind: 'misconfigured', message }` at the position of the invalid source; it fails only when reached. |
3. Update error handling to recognize resolver `AbortError` as cancellation. Do not depend on the extra error wrapper or its diagnostic prefix.
4. Confirm migrated constructors type-check. With the DeepSeek APIs selected and `api-key` billing, missing keys withhold their tools; configured keys allow requests. Local HTTP fetch remains unaffected.
@@ -1,6 +1,6 @@
---
kind: upgrade-guide
description: "在其他模型提供方上的会话没有 DeepSeek API 密钥时,DeepSeek 网页搜索与获取改为由已登录的 DeepSeek 账号计费;新增的 searchBilling 与 fetchBilling 设置选择所用凭据。"
description: "DeepSeek Search 与 Fetch 新增按能力选择的计费方式,并将提供方认证字段替换为有序凭据来源。"
---
# DeepSeek 网页搜索与获取按计费方式选择凭据
@@ -9,11 +9,15 @@ description: "在其他模型提供方上的会话没有 DeepSeek API 密钥时
## 变更
过去,DeepSeek Search API 与 Fetch API(`web-deepseek-api`)只在 `deepseek-account` 模型提供方上的会话中发送 DeepSeek 账号令牌;其他所有操作都发送 DeepSeek API 密钥,没有密钥时操作失败,模型也看不到 `web_search` 或 `web_fetch`。现在每个能力都有一个计费方式设置 `searchBilling` 和 `fetchBilling`,取值为 `auto`(默认)、`account` 和 `api-key`。在 `auto` 下,`deepseek-account` 和 `deepseek-official` 上的会话行为不变,但在其他模型提供方上的会话或会话之外的操作没有 DeepSeek API 密钥时,现在改由已登录的 DeepSeek 账号计费,而不再失败。`account` 始终只发送账号令牌,`api-key` 始终只发送 API 密钥。设置了 `searchBaseURL`、`searchApiKeyEnv`、`fetchBaseURL` 或 `fetchApiKeyEnv` 的配置忽略计费方式,行为不变。受影响的是在其他模型提供方上对话、已登录但没有 DeepSeek API 密钥的用户;有密钥或未登录的用户不受影响。
DeepSeek Search 与 Fetch API(`web-deepseek-api`)过去只在 `deepseek-account` 会话中使用已登录账号;其他会话需要 API 密钥。新增的 `searchBilling` 与 `fetchBilling` 设置接受 `auto`(默认)、`account` 或 `api-key`。在 `auto` 下,DeepSeek 模型路由的行为不变;其他会话与会话之外的操作在没有密钥时改用已登录账号。`account` 只使用账号,`api-key` 只使用密钥。非空的 `*BaseURL` 或 `*ApiKeyEnv` 设置仍然优先。其他提供方(包括本地 HTTP 抓取)不受影响。
在 TypeScript 中,`DeepSeekSearchApiOptions` 与 `DeepSeekFetchApiOptions` 移除了顶层 `baseURL`。其 `auth` 改为 `{ sources, missingCredentialMessage? }`。每个账号或 API 密钥来源携带自己的地址;列表顺序替代隐式的账号优先顺序。直接调用提供方构造函数的代码需要迁移。
传入 `AbortSignal` 时,凭据读取错误现在保留原始 `Error` 作为 `cause`,诊断也保留其名称,不再额外包装一层 `Error:`。解析函数抛出名为 `AbortError` 的 DOMException 时,即使该 signal 未取消,现在也返回 `WEB_ABORTED`,而非 `WEB_PROVIDER_ERROR`。未传 signal 的路径原本就采用此行为。
## 迁移
1. 要保持原有行为,即在账号会话之外从不由账号计费,就把两个能力都设为 `api-key`:在**插件 > 内置插件配置 > 网页搜索与获取**中,在每个**计费方式**下拉框选择 **DeepSeek API Key**,或在 `web-deepseek-api` 行设置这两个键:
1. 要禁用新增的账号回退,在 `web-deepseek-api` 行把两个能力都设为 `api-key`;也可以在**插件 > 内置插件配置 > 网页搜索与获取**中,选中相应的 DeepSeek API 后选择 **DeepSeek API Key**:
```yaml
- name: '@deepseek-ai/dsh-web-deepseek-api'
@@ -22,5 +26,16 @@ description: "在其他模型提供方上的会话没有 DeepSeek API 密钥时
fetchBilling: api-key
```
这样在 `deepseek-account` 上的会话也不再由账号计费。
2. 确认:在其他模型提供方上、没有 DeepSeek API 密钥的会话中,模型不再提供 `web_search` 或 `web_fetch`;配置密钥后搜索成功。
这也会禁用账号会话中的账号计费,并不能完全恢复原来按路由选择的行为。
2. 迁移直接调用 `DeepSeekSearchApiProvider` 与 `DeepSeekFetchApiProvider` 构造函数的代码。下表描述 TypeScript 选项,而非 YAML 设置:
| 原选项 | 替换方式 |
|---|---|
| `baseURL: base`、`auth.apiKey: key` | `auth.sources: [{ kind: 'api-key', baseURL: base, key }]` |
| `auth.resolveApiKey`、`auth.apiKeyEnv` | API 密钥来源的 `key: { ref, configured, resolve }`。保留原引用(省略时为 `DEEPSEEK_API_KEY`);`configured()` 只检查是否存在,不读取值,`resolve()` 读取值。 |
| `auth.account` | `{ kind: 'account', ...account }`;保留其地址和回调。放在 Key 来源之前可保留账号优先行为。 |
| `auth.missingKeyMessage` | `auth.missingCredentialMessage` |
| `auth.invalidRoute` | 在无效来源的位置放置 `{ kind: 'misconfigured', message }`;只有轮到该项才失败。 |
3. 更新错误处理,将解析函数的 `AbortError` 识别为取消。不要依赖额外的错误包装层或其诊断前缀。
4. 确认迁移后的构造代码通过类型检查。选中 DeepSeek API 并使用 `api-key` 计费时,缺少密钥会隐藏相应工具;配置密钥后可以发请求。本地 HTTP 抓取不受影响。
@@ -108,7 +108,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo
| `@deepseek-ai/dsh-client-ui-settings-session-log` | no | General settings control for Session-log upload with DeepSeek API requests |
| `@deepseek-ai/dsh-client-ui-settings-shell` | no | Settings page of the shell executor on the dsh web client's Plugins page: the command timeout and the per-stream output cap of the shell namespace |
| `@deepseek-ai/dsh-client-ui-settings-subagent` | no | Settings page of Subagent delegation on the dsh web client's Plugins page: recursion depth, parallel capacity, and the models agents may choose for subagents |
| `@deepseek-ai/dsh-client-ui-settings-web-search` | no | Settings page for web search and fetch on the dsh web client's Plugins page: the Search and Fetch provider menus, the DeepSeek Search API result count, and legacy Messages search settings |
| `@deepseek-ai/dsh-client-ui-settings-web-search` | no | Settings page for web search and fetch on the dsh web client's Plugins page: the Search and Fetch provider menus, the DeepSeek Search API result count, DeepSeek Search and Fetch API billing, and legacy Messages search settings |
| `@deepseek-ai/dsh-client-ui-shortcuts` | no | Keyboard shortcut reference, recording, and local preference editing |
| `@deepseek-ai/dsh-client-ui-sidebar` | no | Sidebar plugin: session multi-level tree, search, grouping, state dots |
| `@deepseek-ai/dsh-client-ui-sidebar-browser` | no | Sandboxed Web browser tabs for the right Sidebar |
@@ -18,14 +18,14 @@
en: c8f55fe5fc093808
zh: 816d07f508d0f016
/deepseek-ai-dsh-web-deepseek-api/use-this-package/authentication:
en: 7265220e7a007c96
zh: 8da1fdbae168afc6
en: b25cbe2a7894c03e
zh: db47f20dffe77a30
/deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures:
en: 7dbb34d960c1344c
zh: 51a1459415857ab5
/deepseek-ai-dsh-web-deepseek-api/understand-the-implementation:
en: 0ef6417e1e784c65
zh: 8c1fc4e955e2ed52
en: 71549e32f0a69c81
zh: 9cafbeb60bdf0114
/deepseek-ai-dsh-web-deepseek-api/model-experience:
en: 215e7ba838619b7b
zh: a311da3843709f90
+3 -3
View File
@@ -59,9 +59,9 @@ 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 token.** The operation sends the token that `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. The endpoint is under the origin of the active Loader entry of `@deepseek-ai/dsh-llm-deepseek-account` at the entry root that the model provider directory lists for `deepseek-account`; without that entry, it is under the origin of that route's default base URL (`https://api.deepseek.com`, or the `DEEPSEEK_BASE_URL` origin). No sign-in, no account service, or an empty token means no token. A failed account-token read fails the operation without trying another credential. An active entry whose settings the route's own resolver rejects fails the operation before any credential is read when the operation needs the token.
- **Account token.** The operation sends the token that `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. The endpoint is under the origin of the active Loader entry of `@deepseek-ai/dsh-llm-deepseek-account` at the entry root that the model provider directory lists for `deepseek-account`; without that entry, it is under the origin of that route's default base URL (`https://api.deepseek.com`, or the `DEEPSEEK_BASE_URL` origin). No sign-in, no account service, or an empty token means no token. A failed account-token read fails the operation without trying another credential. An active entry whose settings the route's own resolver rejects fails the operation before that account token is read when the operation reaches this source.
- **API key.** The operation sends the key under the `apiKeyEnv` of the active `@deepseek-ai/dsh-llm-deepseek-api-key` entry the directory lists for `deepseek-official` (`DEEPSEEK_API_KEY` by default) as `Authorization: Bearer` to that route's origin, resolving its options as the route does. Without that entry, or with an inactive one, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. An active entry whose settings the route's own resolver rejects 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 token, and without one the API key; without the account route entry, 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 configured key the account token; a mounted account route entry whose settings do not resolve leaves only the API key.
- **`auto` billing** follows the conversation. On the `deepseek-account` route it sends the account token, and without one the API key; without the account route entry, 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 token; without a key, a mounted account route entry whose settings do not resolve fails the operation.
- **`account` billing** sends only the account token 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.
@@ -84,7 +84,7 @@ An unparseable own base URL makes that capability's provider unavailable; and a
<details>
<summary>Implementation internals — click to expand</summary>
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 active model route entries into its endpoint and credential. 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) owns credential resolution, the choice between the account endpoint and the API-key endpoint, 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 turns one capability's settings snapshot, the conversation's route, and the active model route entries 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.
See the [web subsystem](../../../docs/subsystems/web.md) for service types and [tool-web](../tool-web/README.md) for bounded model output.
+3 -3
View File
@@ -59,9 +59,9 @@ 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` 列出的、入口根部活动的 `@deepseek-ai/dsh-llm-deepseek-account` Loader 条目的 origin 下;没有该条目时,位于该路由默认基础地址的 origin(`https://api.deepseek.com`,或 `DEEPSEEK_BASE_URL` 的 origin)下。没有登录、没有账号服务或令牌为空都算没有令牌。账号令牌读取失败时操作失败,不再尝试其他凭据。条目活动但其设置被该路由自身的解析器拒绝时,需要令牌的操作在读取任何凭据前失败。
- **账号令牌。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点给出的令牌;2026-10-16 公网 Search 与 Fetch 路由已接受该令牌。端点位于模型提供方目录为 `deepseek-account` 列出的、入口根部活动的 `@deepseek-ai/dsh-llm-deepseek-account` Loader 条目的 origin 下;没有该条目时,位于该路由默认基础地址的 origin(`https://api.deepseek.com`,或 `DEEPSEEK_BASE_URL` 的 origin)下。没有登录、没有账号服务或令牌为空都算没有令牌。账号令牌读取失败时操作失败,不再尝试其他凭据。条目活动但其设置被该路由自身的解析器拒绝时,操作在轮到该来源时失败,不读取该账号令牌。
- **API 密钥。** 操作以 `Authorization: Bearer` 把目录为 `deepseek-official` 列出的活动 `@deepseek-ai/dsh-llm-deepseek-api-key` 条目的 `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 密钥,没有配置密钥时发送账号令牌;已挂载但设置无法解析的账号路由条目使其只剩 API 密钥。
- **`auto` 计费**跟随会话。在 `deepseek-account` 路由上先发送账号令牌,没有令牌时发送 API 密钥;没有账号路由条目时只发送 API 密钥。在 `deepseek-official` 路由上只发送 API 密钥。在其他路由上或会话之外先发送 API 密钥,没有密钥时发送账号令牌;没有密钥且已挂载的账号路由条目设置无法解析时,操作失败。
- **`account` 计费**在任何路由上只发送账号令牌,**`api-key` 计费**只发送 API 密钥;两者都不回退到另一种凭据。
没有凭据时,操作失败,诊断信息按计费方式点名缺少的登录或模型页面与密钥引用,以及网页搜索与获取设置页上的 `*Billing` 字段。
@@ -84,7 +84,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的
<details>
<summary>实现细节 — 点击展开</summary>
[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由和活动的模型路由条目转换为其端点和凭据。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)负责凭据解析、在账号端点与 API 密钥端点之间选择、取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。
[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由和活动的模型路由条目转换为该操作的有序凭据,每个凭据都绑定其发往的 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` 会话事件。工具调用和结果仍按常规记录到会话。
服务类型见 [Web 子系统](../../../docs/subsystems/web.zh.md),受限的模型输出见 [tool-web](../tool-web/README.zh.md)。
+3 -5
View File
@@ -14,9 +14,7 @@ export const DEEPSEEK_FETCH_API_PROVIDER_ID = 'deepseek-fetch-api'
/** Authentication and endpoint settings snapshotted for one fetch. */
export interface DeepSeekFetchApiOptions {
/** API base the API key is sent to, including its path prefix; `/fetch` is appended. An account token goes to its own base. */
baseURL: string
/** Authentication sources of the fetch. */
/** Ordered authentication sources of the fetch; `/fetch` is appended to the base of the source sent. */
auth: DeepSeekWebAuth
/** Settings that endpoint failures of the fetch name. */
guidance: DeepSeekWebGuidance
@@ -46,13 +44,13 @@ export class DeepSeekFetchApiProvider implements WebFetchProvider {
available(): boolean {
const options = this.resolveOptions()
return hasDeepSeekWebCredential(options.auth) && URL.canParse(options.baseURL)
return hasDeepSeekWebCredential(options.auth)
&& options.auth.sources.every(source => source.kind === 'misconfigured' || URL.canParse(source.baseURL))
}
fetch(request: WebFetchRequest, signal?: AbortSignal): Promise<WebFetchResult> {
const options = this.resolveOptions()
return dispatchDeepSeekWeb(options.auth, {
baseURL: options.baseURL,
path: '/fetch',
body: { url: request.url },
decode: (payload): WebFetchResult => {
+102 -239
View File
@@ -37,7 +37,9 @@ import { DeepSeekFetchApiProvider } from './fetch.ts'
import {
DEEPSEEK_DEFAULT_COUNT, DEEPSEEK_SEARCH_REQUESTS_PER_SECOND, DEEPSEEK_WEB_API_BASE_URL, DeepSeekSearchApiProvider,
} from './search.ts'
import type { DeepSeekWebAuth, DeepSeekWebGuidance } from './transport.ts'
import {
isDeepSeekWebAuthReady, type DeepSeekWebAuth, type DeepSeekWebAuthSource, type DeepSeekWebGuidance,
} from './transport.ts'
export { DEEPSEEK_FETCH_API_PROVIDER_ID, DeepSeekFetchApiProvider } from './fetch.ts'
export type { DeepSeekFetchApiOptions } from './fetch.ts'
@@ -121,29 +123,6 @@ type RouteName = keyof typeof ROUTE_PACKAGES
*/
type Rule = 'account-conversation' | 'official-conversation' | 'other-conversation' | 'account' | 'api-key'
/** One credential an operation can send, or the failure of the route it needs for it. */
type Step =
/** The account token, sent to {@link baseURL}. */
| { source: 'account'; baseURL: string }
/** The API key under {@link key}, sent to {@link baseURL}. */
| { source: 'api-key'; baseURL: string; key: CredentialRef }
/** The route this credential needs is mounted, and its resolver rejects its settings with {@link reason}. */
| { source: 'account' | 'api-key'; invalid: string }
/** Endpoint and credential resolved for one operation or readiness check of one capability. */
type Plan = { capability: Capability } & (
/** The capability's own endpoint and key; never the account token. */
| { kind: 'custom'; baseURL: string; key: CredentialRef }
/** The credentials {@link rule} selects, tried in order; the operation sends the first one available. */
| { kind: 'billing'; rule: Rule; steps: readonly [Step, ...Step[]] }
)
/** A mounted, active model route whose settings its own resolver rejects. */
interface InvalidRoute {
/** Resolver failure message. */
invalid: string
}
/** Path prefix of the Search and Fetch APIs under a DeepSeek origin. */
const TOOLS_PATH = '/v1/tools'
@@ -162,11 +141,11 @@ const ROUTE_PACKAGES = {
[ACCOUNT_PROVIDER]: '@deepseek-ai/dsh-llm-deepseek-account',
} as const
/** Display and configuration names of each capability. */
/** Display names, configuration prefix, and operation path of each capability. */
const CAPABILITY = {
search: { subject: 'Search', prefix: 'search' },
fetch: { subject: 'Fetch', prefix: 'fetch' },
} as const satisfies Record<Capability, { subject: DeepSeekWebGuidance['subject']; prefix: string }>
search: { subject: 'Search', prefix: 'search', path: '/search' },
fetch: { subject: 'Fetch', prefix: 'fetch', path: '/fetch' },
} as const satisfies Record<Capability, { subject: DeepSeekWebGuidance['subject']; prefix: string; path: '/search' | '/fetch' }>
/**
* Read the text of the latest human prompt, the question that triggered the
@@ -183,7 +162,7 @@ function latestUserQuestion(session: Session | undefined): string | undefined {
/**
* Register the Search API and Fetch API providers over one live settings section. Each operation reads one settings
* snapshot and the route of the initiating Session's latest model request; each `ready()` call reads one settings
* snapshot and the route of the model request being prepared. Both resolve the same plan.
* snapshot and the route of the model request being prepared. Both resolve the same ordered credentials.
* @param ctx - plugin context owning both registrations.
* @param config - live settings, read once per operation.
*/
@@ -191,23 +170,21 @@ export function apply(ctx: Context, config: Config): void {
const own = (capability: Capability) => capability === 'search'
? { baseURL: config.searchBaseURL.get(), ref: config.searchApiKeyEnv.get(), billing: config.searchBilling.get() }
: { baseURL: config.fetchBaseURL.get(), ref: config.fetchApiKeyEnv.get(), billing: config.fetchBilling.get() }
const plan = (capability: Capability, llmProvider: string | undefined) =>
resolvePlan(ctx, capability, own(capability), llmProvider)
const target = (capability: Capability) => {
const resolved = plan(capability, ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider)
return { baseURL: planBaseURL(resolved), auth: planAuth(ctx, resolved), guidance: planGuidance(resolved) }
}
const target = (capability: Capability, llmProvider: string | undefined) =>
resolveTarget(ctx, capability, own(capability), llmProvider)
const current = (capability: Capability) =>
target(capability, ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider)
const ready = (capability: Capability) => (llmProvider: string | undefined): Promise<boolean> =>
planReady(ctx, plan(capability, llmProvider))
isDeepSeekWebAuthReady(target(capability, llmProvider).auth, CAPABILITY[capability].path)
const searchApi = new DeepSeekSearchApiProvider(() => ({
...target('search'),
...current('search'),
count: config.count.get(),
requestsPerSecond: config.searchRequestsPerSecond.get(),
...config.sendOriginalQuestion.get() ? {
originalQuestion: () => latestUserQuestion(ctx.get('agents')?.currentInitiator()?.session),
} : {},
}))
const fetchApi = new DeepSeekFetchApiProvider(() => target('fetch'))
const fetchApi = new DeepSeekFetchApiProvider(() => current('fetch'))
ctx.web.registerSearchProvider({
id: searchApi.id,
description: searchApi.description,
@@ -225,187 +202,132 @@ export function apply(ctx: Context, config: Config): void {
}
/**
* Resolve the endpoint and credential of one capability without reading credential values. Route endpoints use the
* origin of the route's resolved Messages base URL with `/v1/tools`.
* @param ctx - context with the model and loader services.
* Resolve the ordered credentials and endpoint guidance of one capability without reading credential values. Route
* endpoints use the origin of the route's resolved Messages base URL with `/v1/tools`.
* @param ctx - context with the model, loader, credential, and account services.
* @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.
* @param llmProvider - provider route of the model request the operation serves.
* @returns the plan.
* @returns the authentication sources and the settings endpoint failures name.
*/
function resolvePlan(
function resolveTarget(
ctx: Context, capability: Capability,
own: { baseURL: string | undefined; ref: string | undefined; billing: Billing }, llmProvider: string | undefined,
): Plan {
): { auth: DeepSeekWebAuth; guidance: DeepSeekWebGuidance } {
const { subject, prefix } = 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) {
return {
capability, kind: 'custom', baseURL: ownBaseURL ?? DEEPSEEK_WEB_API_BASE_URL,
key: ownRef === undefined ? DEEPSEEK_API_KEY : credentialRef(ownRef),
}
const ref = ownRef === undefined ? DEEPSEEK_API_KEY : credentialRef(ownRef)
const json = JSON.stringify(ref)
return { guidance: guidance(true), auth: {
sources: [apiKeySource(ctx, ownBaseURL ?? DEEPSEEK_WEB_API_BASE_URL, ref)],
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'
return { capability, kind: 'billing', rule, steps: ruleSteps(ctx, rule) }
const sources = ruleSources(ctx, capability, rule)
const [ref = DEEPSEEK_API_KEY] = sources.flatMap(row => row.kind === 'api-key' && typeof row.key !== 'string' ? [row.key.ref] : [])
return { guidance: guidance(false), auth: { sources, missingCredentialMessage: missingMessage(capability, rule, ref) } }
}
/**
* The credentials one rule tries, in order.
* @param ctx - context with the model and loader services.
* @param ctx - context with the model, loader, credential, and account services.
* @param capability - the capability whose diagnostics misconfigured sources name.
* @param rule - the rule.
* @returns the steps; the account step is absent in an account conversation without a mounted account route.
* @returns the sources; the account source is absent in an account conversation without a mounted account route.
*/
function ruleSteps(ctx: Context, rule: Rule): [Step, ...Step[]] {
function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeekWebAuthSource[] {
const accountConfig = routeConfig(ctx, ACCOUNT_PROVIDER) as AccountRouteConfig | undefined
switch (rule) {
case 'account-conversation': {
const account = accountStep(ctx, false)
return account === undefined ? [apiKeyStep(ctx)] : [account, apiKeyStep(ctx)]
}
case 'account-conversation': return accountConfig === undefined
? [officialSource(ctx, capability)] : [accountSource(ctx, capability, accountConfig), officialSource(ctx, capability)]
case 'official-conversation':
case 'api-key': return [apiKeyStep(ctx)]
case 'other-conversation': return [apiKeyStep(ctx), accountStep(ctx, true)]
case 'account': return [accountStep(ctx, true)]
case 'api-key': return [officialSource(ctx, capability)]
case 'other-conversation': return [officialSource(ctx, capability), accountSource(ctx, capability, accountConfig)]
case 'account': return [accountSource(ctx, capability, accountConfig)]
/* v8 ignore next -- the switch is exhaustive. */
default: return assertNever(rule)
}
}
/** The API-key step: the DeepSeek API-key route's key and origin, or `DEEPSEEK_API_KEY` and the official base without it. */
function apiKeyStep(ctx: Context): Step {
const official = officialRoute(ctx)
if (official === undefined) return { source: 'api-key', baseURL: DEEPSEEK_WEB_API_BASE_URL, key: DEEPSEEK_API_KEY }
if ('invalid' in official) return { source: 'api-key', invalid: official.invalid }
return { source: 'api-key', baseURL: toolsBase(official.baseURL), key: official.apiKeyEnv }
/**
* The API key of the active 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 resolver rejects its settings.
*/
function officialSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource {
const config = routeConfig(ctx, OFFICIAL_PROVIDER) as OfficialRouteConfig | undefined
if (config === undefined) return apiKeySource(ctx, DEEPSEEK_WEB_API_BASE_URL, DEEPSEEK_API_KEY)
let resolved: { baseURL: string; apiKeyEnv: CredentialRef }
try { resolved = resolveOfficialOptions(plainOfficialOptions(config), launchEnvironmentOf(ctx)) }
catch (error: unknown) { return misconfigured(capability, OFFICIAL_PROVIDER, error) }
return apiKeySource(ctx, toolsBase(resolved.baseURL), resolved.apiKeyEnv)
}
/**
* The account step: the account route's origin, or without that route the origin of its default base URL.
* @param ctx - context with the model, loader, and launch-environment services.
* @param unmountedDefault - whether a missing account route uses its default base URL rather than omitting the step.
* @returns the step, or undefined without the route when {@link unmountedDefault} is false.
* The account token sent to the origin of the account route, or without that route to the origin of its default base
* URL, including `DEEPSEEK_BASE_URL`. The account service releases the token only for destinations it allows.
* @param config - the active account route's settings, or undefined for the defaults.
* @returns the source, or a misconfigured source when the route's resolver rejects its settings.
*/
function accountStep(ctx: Context, unmountedDefault: true): Step
function accountStep(ctx: Context, unmountedDefault: boolean): Step | undefined
function accountStep(ctx: Context, unmountedDefault: boolean): Step | undefined {
const account = accountRoute(ctx) ?? (unmountedDefault ? defaultAccountRoute(ctx) : undefined)
if (account === undefined) return undefined
if ('invalid' in account) return { source: 'account', invalid: account.invalid }
return { source: 'account', baseURL: toolsBase(account.baseURL) }
}
/** Whether a step's route resolved. */
function resolvedStep(step: Step): step is Exclude<Step, { invalid: string }> {
return !('invalid' in step)
}
/** The base an operation's API key goes to; a plan without one names a base no credential is sent to. */
function planBaseURL(plan: Plan): string {
if (plan.kind === 'custom') return plan.baseURL
const step = plan.steps.filter(resolvedStep).find(row => row.source === 'api-key') ?? plan.steps.find(resolvedStep)
return step?.baseURL ?? DEEPSEEK_WEB_API_BASE_URL
}
/**
* Build the authentication sources of one planned operation without reading secret values.
* @param ctx - context with the account, credential, and launch-environment services.
* @param plan - the operation's plan.
* @returns the sources the transport resolves.
*/
function planAuth(ctx: Context, plan: Plan): DeepSeekWebAuth {
if (plan.kind === 'custom') {
return {
resolveApiKey: () => resolveDeepSeekApiKey(ctx, plan.key), apiKeyEnv: plan.key, missingKeyMessage: missingKeyMessage(plan),
}
}
const [first, second] = plan.steps
if (!resolvedStep(first)) {
// Fails before any credential is read; the resolver only keeps the transport from reporting no credential source.
return {
/* v8 ignore next -- the transport fails at the account stage before it resolves a key. */
resolveApiKey: () => Promise.resolve(undefined),
invalidRoute: { stage: 'account', message: invalidRouteMessage(plan.capability, stepRoute(first), first.invalid) },
}
}
const account = plan.steps.filter(resolvedStep).find(row => row.source === 'account')
const apiKey = plan.steps.filter(resolvedStep).find(row => row.source === 'api-key')
const keyRef = apiKey?.source === 'api-key' ? apiKey.key : undefined
// With the key first, the account releases no token while a key is configured, so the transport sends the key.
const keyFirst = first.source === 'api-key' && keyRef !== undefined
function accountSource(ctx: Context, capability: Capability, config: AccountRouteConfig | undefined): DeepSeekWebAuthSource {
let baseURL: string
try {
baseURL = resolveAccountOptions(config === undefined ? {} : plainAccountOptions(config), launchEnvironmentOf(ctx)).protocol.baseURL
} catch (error: unknown) { return misconfigured(capability, ACCOUNT_PROVIDER, error) }
return {
...account === undefined ? {} : {
account: {
baseURL: account.baseURL,
resolveToken: keyFirst
? async (endpoint: string) => await deepSeekApiKeyConfigured(ctx, keyRef)
? undefined : await resolveDeepSeekAccountToken(ctx, endpoint)
: (endpoint: string) => resolveDeepSeekAccountToken(ctx, endpoint),
rejectToken: (token: string) => rejectDeepSeekAccountToken(ctx, token),
},
},
...keyRef === undefined ? {} : { resolveApiKey: () => resolveDeepSeekApiKey(ctx, keyRef), apiKeyEnv: keyRef },
missingKeyMessage: missingKeyMessage(plan),
...second !== undefined && !resolvedStep(second) && second.source === 'api-key' ? {
invalidRoute: { stage: 'api-key', message: invalidRouteMessage(plan.capability, stepRoute(second), second.invalid) },
} : {},
kind: 'account', baseURL: toolsBase(baseURL),
resolveToken: endpoint => resolveDeepSeekAccountToken(ctx, endpoint),
rejectToken: token => rejectDeepSeekAccountToken(ctx, token),
}
}
/** The model route a step's credential depends on. */
function stepRoute(step: Step): RouteName {
return step.source === 'account' ? ACCOUNT_PROVIDER : OFFICIAL_PROVIDER
/** The key under `ref`, read through the shared DeepSeek credential helpers, sent to `baseURL`. */
function apiKeySource(ctx: Context, baseURL: string, ref: CredentialRef): DeepSeekWebAuthSource {
return { kind: 'api-key', baseURL, key: {
ref, configured: () => deepSeekApiKeyConfigured(ctx, ref), resolve: () => resolveDeepSeekApiKey(ctx, ref),
} }
}
/**
* Whether an operation planned as `plan` has a credential, checked in the order {@link planAuth} resolves them. A
* failed read, or a needed route whose settings do not resolve, answers false, because the operation fails on the same
* step. Only presence is checked: the key's value
* is not read and the endpoint is not contacted, so a wrong key still counts as configured.
* @param ctx - context with the account, credential, and launch-environment services.
* @param plan - the operation's plan.
* @returns whether the operation has a credential to send.
* 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 error - the route resolver's failure.
* @returns the source whose diagnostic names the route and both recoveries.
*/
async function planReady(ctx: Context, plan: Plan): Promise<boolean> {
const steps: readonly Step[] = plan.kind === 'custom'
? [{ source: 'api-key', baseURL: plan.baseURL, key: plan.key }] : plan.steps
for (const step of steps) {
if (!resolvedStep(step)) return false
if (step.source === 'account') {
let token: string | undefined
try { token = await resolveDeepSeekAccountToken(ctx, step.baseURL) }
catch (_unreadableGrant) { return false /* The operation fails on this read before it tries another credential. */ }
if (token !== undefined && token.length > 0) return true
continue
}
try { if (await deepSeekApiKeyConfigured(ctx, step.key)) return true }
catch (_unreadableStore) { return false /* A store that cannot be read fails the operation on this step too. */ }
}
return false
function misconfigured(capability: Capability, route: RouteName, error: unknown): DeepSeekWebAuthSource {
const { subject, prefix } = CAPABILITY[capability]
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'
return { kind: 'misconfigured', message: `DeepSeek ${subject} API sends ${credential} to the origin of the ${provider}, and`
+ ` that provider's settings do not resolve: ${errorMessage(error)}. ${subject} did not send the request. Guide the user`
+ ' to correct that provider\'s settings on the Models page or in the deployment configuration, or to set'
+ ` ${name}.${prefix}BaseURL and ${name}.${prefix}ApiKeyEnv so ${subject} uses its own endpoint.` }
}
/** Settings named by endpoint failures of one planned operation. */
function planGuidance(plan: Plan): DeepSeekWebGuidance {
const { subject, prefix } = CAPABILITY[plan.capability]
return {
subject, plugin: name, custom: plan.kind === 'custom', baseURLField: `${prefix}BaseURL`, apiKeyEnvField: `${prefix}ApiKeyEnv`,
}
}
/** Model-facing diagnostic for an operation that has no credential to send. */
function missingKeyMessage(plan: Plan): string {
const { subject, prefix } = CAPABILITY[plan.capability]
if (plan.kind === 'custom') {
const ref = JSON.stringify(plan.key)
return `DeepSeek ${subject} API sends the API key under ${ref} to its own endpoint, and no key is configured for ${ref}.`
+ ` Guide the user to export ${ref} in the launching environment, or to correct ${name}.${prefix}ApiKeyEnv.`
}
const key = plan.steps.find(step => step.source === 'api-key' && resolvedStep(step))
const ref = JSON.stringify(key !== undefined && 'key' in key ? key.key : DEEPSEEK_API_KEY)
/**
* Model-facing diagnostic for an operation billed by `rule` that has no credential to send.
* @param capability - the capability that stops.
* @param rule - the rule that ordered its credentials.
* @param keyRef - the reference of the API key the rule tries, or `DEEPSEEK_API_KEY` when it tries none.
* @returns the diagnostic naming the missing credentials and their recoveries.
*/
function missingMessage(capability: Capability, rule: Rule, keyRef: CredentialRef): string {
const { subject, prefix } = CAPABILITY[capability]
const ref = JSON.stringify(keyRef)
const addKey = `add the DeepSeek API key on the Models page or export ${ref} in the launching environment`
const billing = `${name}.${prefix}Billing`
const settings = 'on the Web search and fetch settings page'
switch (plan.rule) {
switch (rule) {
case 'account-conversation':
return `DeepSeek ${subject} API uses the DeepSeek account sign-in of this conversation, then the DeepSeek API key, and`
+ ` neither is available: no signed-in DeepSeek account is available, and no key is configured for ${ref}. Guide the`
@@ -414,17 +336,10 @@ function missingKeyMessage(plan: Plan): string {
return `DeepSeek ${subject} API uses the DeepSeek API key, as this conversation's model provider does, and no key is`
+ ` configured for ${ref}. Guide the user to ${addKey}, or to sign in to DeepSeek and set ${billing} to "account"`
+ ` ${settings}.`
case 'other-conversation': {
const account = plan.steps.find(step => step.source === 'account')
const accountState = account !== undefined && !resolvedStep(account)
? `the settings of the DeepSeek account model provider do not resolve: ${account.invalid}`
: 'no signed-in DeepSeek account is available'
const accountRecovery = account !== undefined && !resolvedStep(account)
? 'to correct the DeepSeek account model provider\'s settings on the Models page or in the deployment configuration'
: 'to sign in to DeepSeek'
case 'other-conversation':
return `DeepSeek ${subject} API uses the DeepSeek API key, then the DeepSeek account sign-in, and neither is available:`
+ ` no key is configured for ${ref}, and ${accountState}. Guide the user to ${addKey}, or ${accountRecovery}.`
}
+ ` no key is configured for ${ref}, and no signed-in DeepSeek account is available. Guide the user to ${addKey}, or`
+ ' to sign in to DeepSeek.'
case 'account':
return `DeepSeek ${subject} API bills only the signed-in DeepSeek account, and no signed-in DeepSeek account is`
+ ` available. ${subject} did not send the request. Guide the user to sign in to DeepSeek, or to set ${billing} to`
@@ -433,62 +348,10 @@ function missingKeyMessage(plan: Plan): string {
return `DeepSeek ${subject} API bills only the DeepSeek API key, and no key is configured for ${ref}. Guide the user to`
+ ` ${addKey}, or to set ${billing} to "account" or "auto" ${settings}.`
/* v8 ignore next -- the switch is exhaustive. */
default: return assertNever(plan.rule)
default: return assertNever(rule)
}
}
/**
* Model-facing diagnostic for an operation that would use a mounted model route whose settings do not resolve.
* @param capability - the capability that stopped.
* @param route - the route whose settings failed.
* @param reason - the route resolver's failure message.
* @returns the diagnostic naming the route and both recoveries.
*/
function invalidRouteMessage(capability: Capability, route: RouteName, reason: string): string {
const { subject, prefix } = CAPABILITY[capability]
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'
return `DeepSeek ${subject} API sends ${credential} to the origin of the ${provider}, and that provider's settings do not`
+ ` resolve: ${reason}. ${subject} did not send the request. Guide the user to correct that provider's settings on the`
+ ` Models page or in the deployment configuration, or to set ${name}.${prefix}BaseURL and ${name}.${prefix}ApiKeyEnv`
+ ` so ${subject} uses its own endpoint.`
}
/**
* Read the active DeepSeek API-key model route.
* @returns its Messages base URL and credential reference, the resolver failure when its settings do not resolve, or
* undefined when none is mounted and active.
*/
function officialRoute(ctx: Context): { baseURL: string; apiKeyEnv: CredentialRef } | InvalidRoute | undefined {
const config = routeConfig(ctx, OFFICIAL_PROVIDER) as OfficialRouteConfig | undefined
if (config === undefined) return undefined
try {
const resolved = resolveOfficialOptions(plainOfficialOptions(config), launchEnvironmentOf(ctx))
return { baseURL: resolved.baseURL, apiKeyEnv: resolved.apiKeyEnv }
} catch (error: unknown) { return { invalid: errorMessage(error) } }
}
/**
* Read the active DeepSeek account model route.
* @returns its Messages base URL, the resolver failure when its settings do not resolve, or undefined when none is
* mounted and active.
*/
function accountRoute(ctx: Context): { baseURL: string } | InvalidRoute | undefined {
const config = routeConfig(ctx, ACCOUNT_PROVIDER) as AccountRouteConfig | undefined
if (config === undefined) return undefined
try { return { baseURL: resolveAccountOptions(plainAccountOptions(config), launchEnvironmentOf(ctx)).protocol.baseURL } }
catch (error: unknown) { return { invalid: errorMessage(error) } }
}
/**
* Resolve the account route's default settings, as an entry without settings would, including `DEEPSEEK_BASE_URL`.
* @returns its Messages base URL, or the resolver failure.
*/
function defaultAccountRoute(ctx: Context): { baseURL: string } | InvalidRoute {
try { return { baseURL: resolveAccountOptions({}, launchEnvironmentOf(ctx)).protocol.baseURL } }
catch (error: unknown) { return { invalid: errorMessage(error) } }
}
/** The message of a thrown value. */
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
+3 -5
View File
@@ -26,9 +26,7 @@ const ORIGINAL_QUESTION_MAX_CHARS = 128
/** Authentication, endpoint, and result settings snapshotted for one search. */
export interface DeepSeekSearchApiOptions {
/** API base the API key is sent to, including its path prefix; `/search` is appended. An account token goes to its own base. */
baseURL: string
/** Authentication sources of the search. */
/** Ordered authentication sources of the search; `/search` is appended to the base of the source sent. */
auth: DeepSeekWebAuth
/** Settings that endpoint failures of the search name. */
guidance: DeepSeekWebGuidance
@@ -93,7 +91,8 @@ export class DeepSeekSearchApiProvider implements WebSearchProvider {
available(): boolean {
const options = this.resolveOptions()
return hasDeepSeekWebCredential(options.auth) && URL.canParse(options.baseURL)
return hasDeepSeekWebCredential(options.auth)
&& options.auth.sources.every(source => source.kind === 'misconfigured' || URL.canParse(source.baseURL))
&& isPositiveInteger(options.count) && isPositiveInteger(options.requestsPerSecond)
}
@@ -101,7 +100,6 @@ export class DeepSeekSearchApiProvider implements WebSearchProvider {
const options = this.resolveOptions()
const question = boundedQuestion(options.originalQuestion?.())
return dispatchDeepSeekWeb(options.auth, {
baseURL: options.baseURL,
path: '/search',
body: {
query: request.query,
+138 -85
View File
@@ -9,42 +9,59 @@ import { WebError } from '@deepseek-ai/dsh-web'
const USER_AGENT = 'deepseek-harness/0.0.1'
/** Account token tried before the API key of an operation. */
interface DeepSeekWebAccountAuth {
/** API base the token is sent to, including its path prefix. */
baseURL: string
/** Resolve the token the account releases for a dispatch endpoint; undefined or empty selects the API key. */
resolveToken: (endpoint: string) => Promise<string | undefined>
/** Invalidate the exact token rejected by HTTP 401; failures must not replace the request error. */
rejectToken: (token: string) => Promise<void>
/**
* API key of one {@link DeepSeekWebAuthSource}: a literal value, where an empty string means no key, or a credential
* reference read once per use without retention.
*/
export type DeepSeekWebApiKey = string | {
/** Credential reference the key is stored under. */
ref: CredentialRef
/** Report key presence without reading or validating its value; store failures reject. */
configured: () => Promise<boolean>
/** Read and validate the key; undefined or empty means no key, and store or format failures reject. */
resolve: () => Promise<string | undefined>
}
/** Authentication values resolved once for an operation. */
/**
* 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`.
*/
export type DeepSeekWebAuthSource =
/** The account token released for the dispatch endpoint, sent as `x-dsh-auth-token`. */
| {
kind: 'account'
/** API base the token is sent to, including its path prefix. */
baseURL: string
/** Read the token released for a dispatch endpoint; undefined or empty means no token, and read failures reject. */
resolveToken: (endpoint: string) => Promise<string | undefined>
/** Invalidate the exact token rejected by HTTP 401; failures must not replace the request error. */
rejectToken: (token: string) => Promise<void>
}
/** 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
}
/** A credential whose settings do not resolve; reaching it fails the operation with `WEB_PROVIDER_MISCONFIGURED`. */
| {
kind: 'misconfigured'
/** Model-facing diagnostic naming the settings and their recoveries. */
message: string
}
/**
* Credentials of one operation in the order the caller chose. The operation reads them in order and sends one request
* with the first that is present; a later source is not read once an earlier one is present, fails to read, or is
* misconfigured. Request failures never move to another source.
*/
export interface DeepSeekWebAuth {
/** Account token sent to its own base when released; otherwise the API key is sent to the request's base. */
account?: DeepSeekWebAccountAuth
/** Literal API key; takes precedence over the credential resolver. */
apiKey?: string
/** Resolve the current API key without retaining it. */
resolveApiKey?: () => Promise<string | undefined>
/** Credential reference named by missing-key diagnostics. */
apiKeyEnv?: CredentialRef
/** Model-facing diagnostic thrown when no API key resolves; the generic one names {@link apiKeyEnv}. */
missingKeyMessage?: string
/**
* A mounted model route the operation depends on and whose settings do not resolve. The operation fails with
* `WEB_PROVIDER_MISCONFIGURED` and {@link DeepSeekWebInvalidRoute.message} at the stage that would use the route,
* before resolving its credential or sending anything.
*/
invalidRoute?: DeepSeekWebInvalidRoute
}
/** A model route whose settings do not resolve, and the stage of an operation that needs it. */
interface DeepSeekWebInvalidRoute {
/** `account` fails before the account token is read; `api-key` fails where the API key would be resolved. */
stage: 'account' | 'api-key'
/** Model-facing diagnostic naming the route and its recoveries. */
message: string
/** Candidate credentials, first preferred. */
sources: readonly DeepSeekWebAuthSource[]
/** Model-facing `WEB_PROVIDER_CREDENTIAL_MISSING` diagnostic; omitted uses a generic missing-credential message. */
missingCredentialMessage?: string
}
/** User-owned endpoint settings named by dispatch failures. */
@@ -63,9 +80,7 @@ export interface DeepSeekWebGuidance {
/** One fully resolved web API request. */
interface DeepSeekWebRequest<T> {
/** API base the API key is sent to, including its path prefix. */
baseURL: string
/** Operation path appended to the base of the credential sent, such as `/search`. */
/** Operation path appended to the base of the source sent, such as `/search`. */
path: string
/** JSON request body. */
body: object
@@ -84,12 +99,50 @@ interface DeepSeekWebRequest<T> {
}
/**
* Check whether an authentication source exists; does not resolve credentials.
* Check synchronously whether an operation has a source to try, without reading credentials.
* @param auth - Sources for the operation.
* @returns Whether a literal key or resolver is present.
* @returns Whether any source is an account, a credential reference, a non-empty literal key, or a misconfigured source
* the operation reports.
*/
export function hasDeepSeekWebCredential(auth: DeepSeekWebAuth): boolean {
return (auth.apiKey?.length ?? 0) > 0 || auth.resolveApiKey !== undefined || auth.account !== undefined
return auth.sources.some(source => source.kind !== 'api-key' || typeof source.key !== 'string' || source.key.length > 0)
}
/**
* Check whether an operation would find a credential, reading the sources in the order {@link dispatchDeepSeekWeb}
* does. An account source reads its token 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.
* @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<boolean> {
for (const source of auth.sources) {
switch (source.kind) {
case 'misconfigured': return false
case 'account': {
let token: string | undefined
try { token = await source.resolveToken(joinPath(source.baseURL, path)) }
catch (_unreadableGrant) { return false /* The operation fails on this read before it tries another source. */ }
if (token !== undefined && token.length > 0) return true
break
}
case 'api-key': {
const { key } = source
if (typeof key === 'string') {
if (key.length > 0) return true
break
}
try { if (await 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)
}
}
return false
}
/** Narrow a remote JSON object.
@@ -111,7 +164,7 @@ export function invalidResponse(): WebError {
interface SearchAuth {
/** `account` for a DeepSeek account token, `api-key` for an API key. */
readonly kind: 'account' | 'api-key'
/** Absolute dispatch URL under the base of the credential. */
/** Absolute dispatch URL under the base of the source. */
readonly endpoint: string
/** Headers carrying the credential. */
readonly headers: Readonly<Record<string, string>>
@@ -119,9 +172,9 @@ interface SearchAuth {
readonly reject?: () => Promise<void>
}
/** Dispatch one operation using a single settings and credential snapshot.
* @param options - Authentication sources for this operation.
* @param request - Resolved endpoint, JSON payload, and response decoder.
/** 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 signal - Caller cancellation signal.
* @returns The validated provider result.
*/
@@ -247,36 +300,47 @@ function searchEndpointError(
/**
* Resolve one operation's authentication headers without retaining a credential on the provider.
* @param options - the caller's snapshot, so the credential and the endpoint it is sent to come from one section.
* @param request - the resolved request; its path under the account base scopes the account token.
* @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.
* @param signal - abort signal for the surrounding operation.
* @returns the account-token header and account endpoint when a token resolves, otherwise the API-key headers and the
* request's endpoint, tagged by credential kind.
* @returns the headers and endpoint of the first present source, tagged by credential kind.
* @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(
options: DeepSeekWebAuth, request: DeepSeekWebRequest<unknown>, signal?: AbortSignal,
auth: DeepSeekWebAuth, request: DeepSeekWebRequest<unknown>, signal?: AbortSignal,
): Promise<SearchAuth> {
const { account, invalidRoute } = options
if (invalidRoute?.stage === 'account') throw routeMisconfigured(invalidRoute)
if (account !== undefined) {
const endpoint = joinPath(account.baseURL, request.path)
const token = await resolveCredential(() => account.resolveToken(endpoint), signal)
if (token !== undefined && token.length > 0) return {
kind: 'account', endpoint, headers: { 'x-dsh-auth-token': token },
reject: async () => { await account.rejectToken(token) },
throwIfSearchAborted(signal)
for (const source of auth.sources) {
throwIfSearchAborted(signal)
switch (source.kind) {
case 'misconfigured': throw new WebError(source.message, 'WEB_PROVIDER_MISCONFIGURED')
case 'account': {
const endpoint = joinPath(source.baseURL, request.path)
const token = await resolveCredential(() => source.resolveToken(endpoint), signal)
if (token !== undefined && token.length > 0) return {
kind: 'account', endpoint, headers: { 'x-dsh-auth-token': token },
reject: async () => { await source.rejectToken(token) },
}
break
}
case 'api-key': {
const { key } = source
const apiKey = typeof key === 'string' ? key : await resolveCredential(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 (invalidRoute?.stage === 'api-key') throw routeMisconfigured(invalidRoute)
const apiKey = await resolveApiKey(options, signal)
return { kind: 'api-key', endpoint: joinPath(request.baseURL, request.path), headers: {
...request.apiKeyHeaders?.(apiKey),
'authorization': `Bearer ${apiKey}`,
} }
}
/** The failure of an operation that would use a model route whose settings do not resolve. */
function routeMisconfigured(route: DeepSeekWebInvalidRoute): WebError {
return new WebError(route.message, 'WEB_PROVIDER_MISCONFIGURED')
throw new WebError(
auth.missingCredentialMessage ?? 'DeepSeek web access has no credential to send',
'WEB_PROVIDER_CREDENTIAL_MISSING',
)
}
/** Append an operation path to an API base, without doubling a trailing slash. */
@@ -284,25 +348,14 @@ function joinPath(baseURL: string, path: string): string {
return `${baseURL.replace(/\/+$/u, '')}${path}`
}
/* jscpd:ignore-start */
/**
* 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 operation.
* @returns the resolved key.
*/
async function resolveApiKey(options: DeepSeekWebAuth, signal?: AbortSignal): Promise<string> {
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
throw new WebError(
options.missingKeyMessage ?? `DeepSeek web access has no API key for "${options.apiKeyEnv ?? 'DEEPSEEK_API_KEY'}"`,
'WEB_PROVIDER_CREDENTIAL_MISSING',
)
/* 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
* already-cancelled search never starts the resolver.
@@ -345,7 +398,7 @@ function abortable<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
},
(error: unknown) => {
signal.removeEventListener('abort', onAbort)
reject(new Error(String(error).replace(/^Error: /u, ''), { cause: error }))
reject(error instanceof Error ? error : new Error(String(error), { cause: error }))
},
)
})
@@ -139,7 +139,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route',
expect(await ready(ctx, operation, 'deepseek-account')).toBe(true)
await operate(ctx, operation, 'deepseek-account')
expect(sent()).toEqual([{ endpoint: `${ACCOUNT}/${operation}`, authorization: null, token: 'account-token' }])
expect(asked).toEqual([ACCOUNT, `${ACCOUNT}/${operation}`])
expect(asked).toEqual([`${ACCOUNT}/${operation}`, `${ACCOUNT}/${operation}`])
})
it('derives the account endpoint from DEEPSEEK_BASE_URL', async () => {
@@ -282,7 +282,7 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => {
expect(await ready(ctx, operation, route)).toBe(true)
await operate(ctx, operation, route)
expect(sent()).toEqual([{ endpoint: `${ACCOUNT}/${operation}`, authorization: null, token: 'account-token' }])
expect(asked).toEqual([ACCOUNT, `${ACCOUNT}/${operation}`])
expect(asked).toEqual([`${ACCOUNT}/${operation}`, `${ACCOUNT}/${operation}`])
})
it('sends the account token to the default account origin without the account route', async () => {
@@ -316,7 +316,7 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => {
}
})
it('sends the key while the mounted account route settings do not resolve, and fails without the key', async () => {
it('sends the key while the mounted account route settings do not resolve, and is misconfigured without the key', async () => {
const subject = operation === 'search' ? 'Search' : 'Fetch'
const routes = [officialRoute(), accountRoute({ thinking: 'disabled', reasoningEffort: 'high' })]
const withKey = await mount({ routes, account: signedIn(), environment: { DEEPSEEK_API_KEY: 'chat-key' } })
@@ -327,12 +327,12 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => {
const withoutKey = await mount({ routes, account: signedIn(asked) })
expect(await ready(withoutKey.ctx, operation, 'moonshotai')).toBe(false)
await expect(operate(withoutKey.ctx, operation, 'moonshotai')).rejects.toMatchObject({
code: 'WEB_PROVIDER_CREDENTIAL_MISSING',
message: `DeepSeek ${subject} API uses the DeepSeek API key, then the DeepSeek account sign-in, and neither is available:`
+ ' no key is configured for "DEEPSEEK_API_KEY", and the settings of the DeepSeek account model provider do not'
+ ' resolve: llm-deepseek: only reasoningEffort "off" can be configured when thinking is disabled. Guide the user to'
+ ' add the DeepSeek API key on the Models page or export "DEEPSEEK_API_KEY" in the launching environment, or to'
+ ' correct the DeepSeek account model provider\'s settings on the Models page or in the deployment configuration.',
code: 'WEB_PROVIDER_MISCONFIGURED',
message: `DeepSeek ${subject} API sends the DeepSeek account sign-in to the origin of the DeepSeek account model`
+ ' provider, and that provider\'s settings do not resolve: llm-deepseek: only reasoningEffort "off" can be configured'
+ ` when thinking is disabled. ${subject} did not send the request. Guide the user to correct that provider's settings`
+ ' on the Models page or in the deployment configuration, or to set'
+ ` web-deepseek-api.${operation}BaseURL and web-deepseek-api.${operation}ApiKeyEnv so ${subject} uses its own endpoint.`,
})
expect(withoutKey.sent()).toEqual([])
expect(asked).toEqual([])
@@ -341,7 +341,8 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => {
it('fails without asking the account when the credential store cannot be read', async () => {
const asked: string[] = []
const { ctx, sent } = await mount({
routes: bothRoutes, account: signedIn(asked), credentials: { describe: () => Promise.reject(new Error('store locked')) },
routes: bothRoutes, account: signedIn(asked),
credentials: { describe: () => Promise.reject(new Error('store locked')), resolve: () => Promise.reject(new Error('store locked')) },
})
expect(await ready(ctx, operation, 'moonshotai')).toBe(false)
await expect(operate(ctx, operation, 'moonshotai')).rejects.toMatchObject({
@@ -455,7 +456,7 @@ describe.each(OPERATIONS)('%s billed to the signed-in DeepSeek account', (operat
expect(await ready(ctx, operation, route)).toBe(true)
await operate(ctx, operation, route)
expect(sent()).toEqual([{ endpoint: `${ACCOUNT}/${operation}`, authorization: null, token: 'account-token' }])
expect(asked).toEqual([ACCOUNT, `${ACCOUNT}/${operation}`])
expect(asked).toEqual([`${ACCOUNT}/${operation}`, `${ACCOUNT}/${operation}`])
})
it('sends the token to the default account origin without the account route', async () => {
@@ -35,7 +35,7 @@ async function observe(run: () => Promise<unknown>): Promise<string[]> {
import { DeepSeekSearchApiProvider } from '../src/search.ts'
describe('deepseek search api egress', () => {
it('goes through the proxy', async () => {
const p = new DeepSeekSearchApiProvider(() => ({ auth: { apiKey: 'probe' }, baseURL: 'http://dsk-probe.invalid/api/v1/tools', count: 10, requestsPerSecond: 5, guidance: customGuidance('search') }))
const p = new DeepSeekSearchApiProvider(() => ({ auth: { sources: [{ kind: 'api-key', baseURL: 'http://dsk-probe.invalid/api/v1/tools', key: 'probe' }] }, count: 10, requestsPerSecond: 5, guidance: customGuidance('search') }))
expect(await observe(() => p.search({ query: 'probe' }))).toEqual(['REQ http://dsk-probe.invalid/api/v1/tools/search'])
})
})
@@ -6,7 +6,9 @@ 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'
const fetchProvider = (options: DeepSeekFetchApiOptions) => new DeepSeekFetchApiProvider(() => options)
const options = { auth: { apiKey: 'ds-key' }, baseURL: 'https://api.deepseek.test/api/v1/tools', guidance: customGuidance('fetch') }
const BASE = 'https://api.deepseek.test/api/v1/tools'
const auth = (key: string, baseURL = BASE): DeepSeekFetchApiOptions['auth'] => ({ sources: [{ kind: 'api-key', baseURL, 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 })
}
@@ -16,7 +18,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, baseURL: `${options.baseURL}/` })
const provider = fetchProvider({ ...options, auth: auth('ds-key', `${BASE}/`) })
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,
})
@@ -55,8 +57,8 @@ describe('DeepSeek Fetch API', () => {
})
it('is available only with a credential source and a parseable base', () => {
expect(fetchProvider(options).available()).toBe(true)
expect(fetchProvider({ ...options, auth: { apiKey: '' } }).available()).toBe(false)
expect(fetchProvider({ ...options, baseURL: 'not a url' }).available()).toBe(false)
expect(fetchProvider({ ...options, auth: auth('') }).available()).toBe(false)
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' })))
@@ -64,7 +66,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' } }]))
const fiber = await ctx.plugin(webApiPlugin, { fetchBaseURL: options.baseURL })
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()
await expect(ctx.web.fetch({ url: 'https://example.com' })).rejects.toMatchObject({ code: 'WEB_PROVIDER_CONFIGURED_MISSING' })
@@ -47,14 +47,25 @@ 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({ apiKey: TEST_API_KEY }, {
baseURL: redirectOrigin, path: `/${status}`, body: { query: TEST_QUERY }, decode: value => value,
await expect(dispatchDeepSeekWeb({ sources: [{ kind: 'api-key', baseURL: redirectOrigin, key: TEST_API_KEY }] }, {
path: `/${status}`, body: { query: TEST_QUERY }, decode: value => value,
apiKeyHeaders: key => ({ 'x-api-key': key }),
guidance: customGuidance('search'),
})).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' })
expect(targetRequests).toHaveLength(0)
})
it('rejects a redirect of an account-token request before contacting Location', async () => {
targetRequests.length = 0
await expect(dispatchDeepSeekWeb({ sources: [{
kind: 'account', baseURL: redirectOrigin, resolveToken: async () => 'redirect-test-token', rejectToken: async () => {},
}] }, {
path: '/307', body: { query: TEST_QUERY }, decode: value => value,
guidance: customGuidance('search'),
})).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' })
expect(targetRequests).toHaveLength(0)
})
it('shows default 307 following forwards the custom credential and POST body', async () => {
targetRequests.length = 0
const body = JSON.stringify({ query: TEST_QUERY })
@@ -19,9 +19,11 @@ import { customGuidance } from './guidance.ts'
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 }] })
const options = {
auth: { apiKey: 'ds-key' },
baseURL: 'https://api.deepseek.test/api/v1/tools',
auth: auth('ds-key'),
count: 10,
requestsPerSecond: 5,
guidance: customGuidance('search'),
@@ -73,7 +75,7 @@ describe('mapSearchResponse', () => {
describe('DeepSeekSearchApiProvider availability', () => {
it('is unavailable without a key', () => {
expect(searchProvider({ ...options, auth: { apiKey: '' } }).available()).toBe(false)
expect(searchProvider({ ...options, auth: auth('') }).available()).toBe(false)
})
it('is available with a key', () => {
@@ -81,11 +83,15 @@ describe('DeepSeekSearchApiProvider availability', () => {
})
it('is available with only an account token resolver', () => {
expect(searchProvider({ ...options, auth: { account: { baseURL: options.baseURL, resolveToken: async () => 'account-token', rejectToken: async () => {} } } }).available()).toBe(true)
expect(searchProvider({ ...options, auth: { sources: [{ kind: 'account', baseURL: BASE, resolveToken: async () => 'account-token', rejectToken: async () => {} }] } }).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, baseURL: 'not a url' }).available()).toBe(false)
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) => {
@@ -1,26 +1,40 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { credentialRef } from '@deepseek-ai/dsh-credentials'
import { WebError } from '@deepseek-ai/dsh-web'
import { customGuidance } from './guidance.ts'
import { dispatchDeepSeekWeb, type DeepSeekWebAuth } from '../src/transport.ts'
const options = { apiKey: 'ds-key', baseURL: 'https://api.deepseek.test/v1/tools' }
import {
dispatchDeepSeekWeb, hasDeepSeekWebCredential, isDeepSeekWebAuthReady,
type DeepSeekWebApiKey, type DeepSeekWebAuthSource,
} from '../src/transport.ts'
const API_BASE = 'https://api.deepseek.test/v1/tools'
const ACCOUNT_BASE = 'https://account.deepseek.test/v1/tools'
/** Sources of one search; the account fields, when given, form the account credential on {@link ACCOUNT_BASE}. */
type SearchSources = Omit<DeepSeekWebAuth, 'account'> & {
baseURL: string
recordRequest?: (endpoint: string) => void
resolveAccountToken?: (endpoint: string) => Promise<string | undefined>
rejectAccountToken?: (token: string) => Promise<void>
/** An API-key source on {@link API_BASE}. */
function keySource(key: DeepSeekWebApiKey = 'ds-key'): DeepSeekWebAuthSource {
return { kind: 'api-key', baseURL: API_BASE, key }
}
function searchProvider({ baseURL, recordRequest, resolveAccountToken, rejectAccountToken, ...auth }: SearchSources) {
const account = resolveAccountToken === undefined ? {} : {
account: { baseURL: ACCOUNT_BASE, resolveToken: resolveAccountToken, rejectToken: rejectAccountToken ?? (async () => {}) },
}
return { search: (body: { query: string }, signal?: AbortSignal) => dispatchDeepSeekWeb({ ...auth, ...account }, {
baseURL, path: '/search', body, decode: value => value,
/** A referenced key whose presence check and read are the given functions. */
function keyRef(resolve: () => Promise<string | undefined>, configured: () => Promise<boolean> = async () => true): DeepSeekWebApiKey {
return { ref: credentialRef('TEST_KEY'), configured, resolve }
}
/** An account source on {@link ACCOUNT_BASE}. */
function accountSource(
resolveToken: (endpoint: string) => Promise<string | undefined>, rejectToken: (token: string) => Promise<void> = async () => {},
): DeepSeekWebAuthSource {
return { kind: 'account', baseURL: ACCOUNT_BASE, resolveToken, rejectToken }
}
const misconfigured: DeepSeekWebAuthSource = { kind: 'misconfigured', message: 'route settings do not resolve' }
/** Search once with the given sources, in order. */
function search(
sources: readonly DeepSeekWebAuthSource[], signal?: AbortSignal,
extra: { recordRequest?: (endpoint: string) => void; missingCredentialMessage?: string } = {},
) {
const { recordRequest, missingCredentialMessage } = extra
return dispatchDeepSeekWeb({ sources, ...missingCredentialMessage === undefined ? {} : { missingCredentialMessage } }, {
path: '/search', body: { query: 'q' }, decode: value => value,
...recordRequest === undefined ? {} : { recordRequest },
apiKeyHeaders: key => ({ 'x-api-key': key }),
guidance: customGuidance('search'),
}, signal) }
}, signal)
}
function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, ...init })
@@ -29,65 +43,170 @@ async function rejectedWebError(operation: Promise<unknown>): Promise<WebError>
try { await operation } catch (error) { if (error instanceof WebError) return error; throw error }
throw new Error('expected request to reject')
}
/** Stub fetch and read back the endpoint and headers of each call. */
function captureFetch(response: () => Response = () => jsonResponse({})) {
// The provider always passes the endpoint as a string.
const fetchMock = vi.fn(async (_input: string, _init?: RequestInit) => response())
vi.stubGlobal('fetch', fetchMock)
return {
fetchMock,
sent: () => fetchMock.mock.calls.map(([url, init]) => ({ url, headers: (init?.headers ?? {}) as Record<string, string> })),
}
}
afterEach(() => vi.unstubAllGlobals())
describe('DeepSeek web account authentication', () => {
/** Stub fetch and read back the endpoint and headers of its first call. */
function captureFetch() {
// The provider always passes the endpoint as a string.
const fetchMock = vi.fn(async (_input: string, _init?: RequestInit) => jsonResponse({}))
vi.stubGlobal('fetch', fetchMock)
return {
fetchMock,
first: () => {
const [url, init] = fetchMock.mock.calls[0] ?? []
return { url: url ?? '', headers: (init?.headers ?? {}) as Record<string, string> }
},
}
}
it('sends only the account token to the account endpoint it was released for, ahead of a configured key', async () => {
const { first } = captureFetch()
const resolveAccountToken = vi.fn(async (_endpoint: string) => 'account-token')
const resolveApiKey = vi.fn(async () => 'resolved-key')
await searchProvider({ ...options, resolveAccountToken, resolveApiKey }).search({ query: 'q' })
const { url, headers } = first()
expect(url).toBe(`${ACCOUNT_BASE}/search`)
expect(resolveAccountToken).toHaveBeenCalledExactlyOnceWith(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')
describe('DeepSeek web credential order', () => {
it('sends only the account token to its own base when the account comes first, without reading the key', async () => {
const { sent } = captureFetch()
const resolveToken = vi.fn(async (_endpoint: string) => 'account-token')
const resolve = vi.fn(async () => 'resolved-key')
await search([accountSource(resolveToken), keySource(keyRef(resolve))])
const [request] = sent()
expect(sent()).toHaveLength(1)
expect(request?.url).toBe(`${ACCOUNT_BASE}/search`)
expect(resolveToken).toHaveBeenCalledExactlyOnceWith(request?.url)
expect(resolve).not.toHaveBeenCalled()
expect(request?.headers['x-dsh-auth-token']).toBe('account-token')
expect(request?.headers).not.toHaveProperty('x-api-key')
expect(request?.headers).not.toHaveProperty('authorization')
})
it.each([undefined, ''])('falls back to the API key on the API-key endpoint when the account resolves %j', async (token) => {
const { first } = captureFetch()
await searchProvider({ ...options, resolveAccountToken: async () => token }).search({ query: 'q' })
const { url, headers } = first()
expect(url).toBe(`${options.baseURL}/search`)
expect(headers['x-api-key']).toBe('ds-key')
expect(headers).not.toHaveProperty('x-dsh-auth-token')
it('sends only the key to its own base when the key comes first, without reading the account', async () => {
const { sent } = captureFetch()
const resolveToken = vi.fn(async () => 'account-token')
const resolve = vi.fn(async () => 'resolved-key')
const configured = vi.fn(async () => true)
await search([keySource(keyRef(resolve, configured)), accountSource(resolveToken)])
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).not.toHaveProperty('x-dsh-auth-token')
expect(resolve).toHaveBeenCalledOnce()
expect(configured).not.toHaveBeenCalled()
expect(resolveToken).not.toHaveBeenCalled()
})
it('maps an account resolver rejection to WEB_PROVIDER_ERROR without dispatching', async () => {
it.each([undefined, ''])('sends the account token when the referenced key first in order resolves %j', async (key) => {
const { sent } = captureFetch()
await search([keySource(keyRef(async () => key)), 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]])
})
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.each<[string, readonly DeepSeekWebAuthSource[]]>([
['no sources', []],
['an empty literal key', [keySource('')]],
['a missing referenced 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(searchProvider({
...options,
resolveAccountToken: () => Promise.reject(new Error('account storage failed')),
}).search({ query: 'q' }))
await expect(search(sources, undefined, { missingCredentialMessage: 'no credential for this search' }))
.rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING', message: 'no credential for this search' })
expect(fetchMock).not.toHaveBeenCalled()
})
it('names no credential without a caller diagnostic', async () => {
captureFetch()
await expect(search([])).rejects.toMatchObject({
code: 'WEB_PROVIDER_CREDENTIAL_MISSING', message: 'DeepSeek web access has no credential to send',
})
})
it('sends an earlier present source without reaching a misconfigured one', async () => {
const { sent } = captureFetch()
await search([accountSource(async () => 'account-token'), misconfigured])
expect(sent().map(row => row.url)).toEqual([`${ACCOUNT_BASE}/search`])
})
it.each<[string, readonly DeepSeekWebAuthSource[]]>([
['first', [misconfigured, keySource()]],
['after an absent account token', [accountSource(async () => undefined), misconfigured, keySource()]],
])('fails with WEB_PROVIDER_MISCONFIGURED when a misconfigured source is reached %s', async (_label, sources) => {
const { fetchMock } = captureFetch()
await expect(search(sources)).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED', message: 'route settings do not resolve' })
expect(fetchMock).not.toHaveBeenCalled()
})
it('maps an account read failure to WEB_PROVIDER_ERROR without reading the next source', async () => {
const { fetchMock } = captureFetch()
const resolve = vi.fn(async () => 'resolved-key')
await expect(search([accountSource(() => Promise.reject(new Error('account storage failed'))), keySource(keyRef(resolve))]))
.rejects.toThrow(expect.objectContaining({
code: 'WEB_PROVIDER_ERROR',
message: 'DeepSeek web credential resolution failed: Error: account storage failed',
}))
expect(resolve).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
it.each([undefined, new AbortController().signal])('keeps a key read failure as the cause without reading the account (signal %#)', async (signal) => {
const { fetchMock } = captureFetch()
const failure = new WebError('malformed key', 'WEB_PROVIDER_MISCONFIGURED')
const resolveToken = vi.fn(async () => 'account-token')
const error = await rejectedWebError(search([keySource(keyRef(() => Promise.reject(failure))), accountSource(resolveToken)], signal))
expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message: `DeepSeek web credential resolution failed: ${String(failure)}` })
expect(error.cause).toBe(failure)
expect(resolveToken).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
})
describe('DeepSeek web credential availability and readiness', () => {
it.each<[boolean, readonly DeepSeekWebAuthSource[]]>([
[false, []],
[false, [keySource('')]],
[true, [keySource()]],
[true, [keySource(keyRef(async () => undefined))]],
[true, [accountSource(async () => undefined)]],
[true, [misconfigured]],
])('reports a source to try as %s without reading credentials', (expected, sources) => {
expect(hasDeepSeekWebCredential({ sources })).toBe(expected)
})
it('checks a referenced key for presence without reading it, and asks the account for the operation 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(configured).toHaveBeenCalledOnce()
expect(resolve).not.toHaveBeenCalled()
expect(resolveToken).toHaveBeenCalledExactlyOnceWith(`${ACCOUNT_BASE}/fetch`)
expect(fetchMock).not.toHaveBeenCalled()
})
it.each<[string, readonly DeepSeekWebAuthSource[], boolean]>([
['no sources', [], false],
['an empty literal key', [keySource('')], false],
['a literal key', [keySource()], true],
['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)
})
it.each<[string, DeepSeekWebAuthSource]>([
['a misconfigured source', misconfigured],
['an unreadable account grant', accountSource(() => Promise.reject(new Error('grant unreadable')))],
['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(resolveToken).not.toHaveBeenCalled()
})
})
describe('DeepSeek web account authentication', () => {
it('replaces endpoint guidance with sign-in guidance when DeepSeek rejects the account token', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'invalid token' } }, { status: 401 })))
const error = await rejectedWebError(searchProvider({
...options,
resolveAccountToken: async () => 'account-token',
}).search({ query: 'q' }))
const error = await rejectedWebError(search([accountSource(async () => 'account-token')]))
expect(error).toMatchObject({
code: 'WEB_PROVIDER_ERROR',
message: 'DeepSeek API error (HTTP 401): invalid token\n\n'
@@ -97,23 +216,37 @@ describe('DeepSeek web account authentication', () => {
})
it.each([false, true])('invalidates the sent account token on 401 and preserves the HTTP error when removal fails: %s', async (fails) => {
const rejectAccountToken = vi.fn(async (_token: string) => { if (fails) throw new Error('storage failed') })
const rejectToken = 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, resolveAccountToken: async () => 'sent-token', rejectAccountToken,
}).search({ query: 'q' }))
const error = await rejectedWebError(search([accountSource(async () => 'sent-token', rejectToken)]))
expect(error.code).toBe('WEB_PROVIDER_ERROR')
expect(error.message).toContain('HTTP 401')
expect(rejectAccountToken).toHaveBeenCalledExactlyOnceWith('sent-token')
expect(rejectToken).toHaveBeenCalledExactlyOnceWith('sent-token')
})
it.each([[401, undefined], [403, 'account-token']] as const)('does not invalidate a token for status %s and token %s', async (status, token) => {
const rejectAccountToken = vi.fn(async () => {})
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status })))
await expect(searchProvider({
...options, resolveAccountToken: async () => token, rejectAccountToken,
}).search({ query: 'q' })).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' })
expect(rejectAccountToken).not.toHaveBeenCalled()
it('sends one request and tries no later source when the account token is rejected', async () => {
const { fetchMock } = captureFetch(() => jsonResponse({}, { status: 401 }))
const resolve = vi.fn(async () => 'resolved-key')
await expect(search([accountSource(async () => 'sent-token'), keySource(keyRef(resolve))])).rejects.toThrow('HTTP 401')
expect(fetchMock).toHaveBeenCalledOnce()
expect(resolve).not.toHaveBeenCalled()
})
it.each([401, 429])('sends one request and tries no later source when the key gets HTTP %i', async (status) => {
const { fetchMock } = captureFetch(() => jsonResponse({}, { status }))
const resolveToken = vi.fn(async () => 'account-token')
const rejectToken = vi.fn(async () => {})
await expect(search([keySource(), accountSource(resolveToken, rejectToken)])).rejects.toThrow(`HTTP ${status}`)
expect(fetchMock).toHaveBeenCalledOnce()
expect(resolveToken).not.toHaveBeenCalled()
expect(rejectToken).not.toHaveBeenCalled()
})
it('does not invalidate a token for status 403', async () => {
const rejectToken = vi.fn(async () => {})
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 403 })))
await expect(search([accountSource(async () => 'account-token', rejectToken)])).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' })
expect(rejectToken).not.toHaveBeenCalled()
})
it('retains the HTTP failure when account invalidation cancels the requesting Session', async () => {
@@ -126,10 +259,9 @@ describe('DeepSeek web account authentication', () => {
return body
})
vi.stubGlobal('fetch', vi.fn(async () => response))
const error = await rejectedWebError(searchProvider({
...options, resolveAccountToken: async () => 'sent-token',
rejectAccountToken: async () => { controller.abort(new Error('signed out')) },
}).search({ query: 'q' }, controller.signal))
const error = await rejectedWebError(search(
[accountSource(async () => 'sent-token', async () => { controller.abort(new Error('signed out')) })], controller.signal,
))
expect(error.code).toBe('WEB_PROVIDER_ERROR')
expect(error.message).toContain('HTTP 401')
expect(controller.signal.aborted).toBe(true)
@@ -143,12 +275,10 @@ describe('DeepSeek web account authentication', () => {
throw new DOMException('The operation was aborted.', 'AbortError')
})
vi.stubGlobal('fetch', vi.fn(async () => response))
const rejectAccountToken = vi.fn(async (_token: string) => {})
const error = await rejectedWebError(searchProvider({
...options, resolveAccountToken: async () => 'sent-token', rejectAccountToken,
}).search({ query: 'q' }, controller.signal))
const rejectToken = vi.fn(async (_token: string) => {})
const error = await rejectedWebError(search([accountSource(async () => 'sent-token', rejectToken)], controller.signal))
expect(error.code).toBe('WEB_ABORTED')
expect(rejectAccountToken).toHaveBeenCalledExactlyOnceWith('sent-token')
expect(rejectToken).toHaveBeenCalledExactlyOnceWith('sent-token')
})
it('reports cancellation during an API-key 401 body read without invalidating a token', async () => {
@@ -159,29 +289,21 @@ describe('DeepSeek web account authentication', () => {
throw new DOMException('The operation was aborted.', 'AbortError')
})
vi.stubGlobal('fetch', vi.fn(async () => response))
const rejectAccountToken = vi.fn(async (_token: string) => {})
const error = await rejectedWebError(searchProvider({
...options, resolveAccountToken: async () => undefined, rejectAccountToken,
}).search({ query: 'q' }, controller.signal))
const rejectToken = vi.fn(async (_token: string) => {})
const error = await rejectedWebError(search([accountSource(async () => undefined, rejectToken), keySource()], controller.signal))
expect(error.code).toBe('WEB_ABORTED')
expect(rejectAccountToken).not.toHaveBeenCalled()
expect(rejectToken).not.toHaveBeenCalled()
})
it('keeps endpoint guidance for other account-authenticated HTTP failures', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 503 })))
const error = await rejectedWebError(searchProvider({
...options,
resolveAccountToken: async () => 'account-token',
}).search({ query: 'q' }))
const error = await rejectedWebError(search([accountSource(async () => 'account-token')]))
expect(error.message).toContain('If that endpoint is not intended')
})
it('maps a synchronous resolver throw to WEB_PROVIDER_ERROR', async () => {
const { fetchMock } = captureFetch()
await expect(searchProvider({
...options,
resolveAccountToken: () => { throw new Error('account service threw') },
}).search({ query: 'q' }))
await expect(search([accountSource(() => { throw new Error('account service threw') })]))
.rejects.toThrow(expect.objectContaining({
code: 'WEB_PROVIDER_ERROR',
message: 'DeepSeek web credential resolution failed: Error: account service threw',
@@ -189,137 +311,102 @@ describe('DeepSeek web 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')
const controller = new AbortController()
controller.abort(new Error('caller stopped'))
await expect(searchProvider({ ...options, apiKey: '', resolveAccountToken, resolveApiKey })
.search({ query: 'q' }, controller.signal))
it('reports cancellation before a missing credential when no source exists', async () => {
const { fetchMock } = captureFetch()
await expect(search([], AbortSignal.abort(new Error('caller stopped'))))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(resolveAccountToken).not.toHaveBeenCalled()
expect(resolveApiKey).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
it('starts neither resolver for a pre-aborted call', async () => {
const resolveToken = vi.fn(async () => 'account-token')
const resolve = vi.fn(async () => 'resolved-key')
await expect(search([accountSource(resolveToken), keySource(keyRef(resolve))], AbortSignal.abort(new Error('caller stopped'))))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(resolveToken).not.toHaveBeenCalled()
expect(resolve).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: '',
resolveAccountToken: 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()
const resolve = vi.fn(() => Promise.reject(new Error('must not run')))
await expect(search([
accountSource(async () => { controller.abort(new Error('caller stopped')); return undefined }), keySource(keyRef(resolve)),
], controller.signal)).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(resolve).not.toHaveBeenCalled()
})
it('aborts while the account resolver remains pending', async () => {
const { fetchMock } = captureFetch()
const controller = new AbortController()
const search = searchProvider({
...options,
resolveAccountToken: () => new Promise<string>(() => {}),
}).search({ query: 'q' }, controller.signal)
const pending = search([accountSource(() => new Promise<string>(() => {}))], controller.signal)
controller.abort(new Error('deadline'))
await expect(search).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
await expect(pending).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(fetchMock).not.toHaveBeenCalled()
})
})
describe('DeepSeek web cancellation and failures', () => {
it('does not start credential resolution or dispatch for a pre-aborted call', async () => {
const resolveApiKey = vi.fn(async () => 'late-key')
const resolve = vi.fn(async () => 'late-key')
const recordRequest = vi.fn()
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const controller = new AbortController()
controller.abort(new Error('caller stopped'))
await expect(searchProvider({
...options,
apiKey: '',
resolveApiKey,
recordRequest,
}).search({ query: 'q' }, controller.signal))
const { fetchMock } = captureFetch()
await expect(search([keySource(keyRef(resolve))], AbortSignal.abort(new Error('caller stopped')), { recordRequest }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(resolveApiKey).not.toHaveBeenCalled()
expect(resolve).not.toHaveBeenCalled()
expect(recordRequest).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
it('aborts while an uncooperative credential resolver remains pending', async () => {
const resolveApiKey = vi.fn(() => new Promise<string>(() => {}))
const resolve = vi.fn(() => new Promise<string>(() => {}))
const recordRequest = vi.fn()
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const { fetchMock } = captureFetch()
const controller = new AbortController()
const search = searchProvider({
...options,
apiKey: '',
resolveApiKey,
recordRequest,
}).search({ query: 'q' }, controller.signal)
const pending = search([keySource(keyRef(resolve))], controller.signal, { recordRequest })
controller.abort(new Error('deadline'))
await expect(search).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(resolveApiKey).toHaveBeenCalledOnce()
await expect(pending).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(resolve).toHaveBeenCalledOnce()
expect(recordRequest).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
it('resolves credentials under an active cancellation signal', async () => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse({ truncated: false }))
vi.stubGlobal('fetch', fetchMock)
const controller = new AbortController()
await expect(searchProvider({
...options,
apiKey: '',
resolveApiKey: async () => 'resolved-key',
}).search({ query: 'q' }, controller.signal)).resolves.toMatchObject({ truncated: false })
const [, init] = fetchMock.mock.calls[0]!
expect((init?.headers as Record<string, string>)['x-api-key']).toBe('resolved-key')
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')
})
it('maps a credential resolver rejection under an active signal to WEB_PROVIDER_ERROR', async () => {
const controller = new AbortController()
await expect(searchProvider({
...options,
apiKey: '',
resolveApiKey: () => Promise.reject(new Error('credential backend failed')),
}).search({ query: 'q' }, controller.signal))
await expect(search([keySource(keyRef(() => Promise.reject(new Error('credential backend failed'))))], new AbortController().signal))
.rejects.toThrow(expect.objectContaining({
code: 'WEB_PROVIDER_ERROR',
message: 'DeepSeek web credential resolution failed: Error: credential backend failed',
}))
})
it('uses the default credential reference when no resolver is configured', async () => {
await expect(searchProvider({ ...options, apiKey: '' }).search({ query: 'q' }))
.rejects.toThrow('DeepSeek web access has no API key for "DEEPSEEK_API_KEY"')
it('maps a non-Error credential rejection under an active signal to WEB_PROVIDER_ERROR with the value as its cause', async () => {
// oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the non-Error arm is the case under test.
const rejectString = () => Promise.reject('backend down')
const error = await rejectedWebError(search([keySource(keyRef(rejectString))], new AbortController().signal))
expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message: 'DeepSeek web credential resolution failed: Error: backend down' })
expect(error.cause).toMatchObject({ cause: 'backend down' })
})
it('observes cancellation triggered synchronously by credential resolution', async () => {
const controller = new AbortController()
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
await expect(searchProvider({
...options,
apiKey: '',
resolveApiKey: () => {
controller.abort(new Error('resolver cancelled caller'))
return Promise.resolve('unused-key')
},
}).search({ query: 'q' }, controller.signal))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
const { fetchMock } = captureFetch()
await expect(search([keySource(keyRef(() => {
controller.abort(new Error('resolver cancelled caller'))
return Promise.resolve('unused-key')
}))], controller.signal)).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
expect(fetchMock).not.toHaveBeenCalled()
})
it('maps an HTTP error to WEB_PROVIDER_ERROR with the provider message', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'rate limited' } }, { status: 429 })))
await expect(searchProvider(options).search({ query: 'q' }))
await expect(search([keySource()]))
.rejects.toThrow(expect.objectContaining({
code: 'WEB_PROVIDER_ERROR',
message: 'DeepSeek API error (HTTP 429): rate limited\n\n'
@@ -333,25 +420,25 @@ describe('DeepSeek web cancellation and failures', () => {
it('handles a string-form error body', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'bad request' }, { status: 400 })))
const error = await rejectedWebError(searchProvider(options).search({ query: 'q' }))
const error = await rejectedWebError(search([keySource()]))
expect(error.message).toContain('DeepSeek API error (HTTP 400): bad request')
})
it('keeps a status-line message when the error body is not JSON', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('upstream error', { status: 503 })))
const error = await rejectedWebError(searchProvider(options).search({ query: 'q' }))
const error = await rejectedWebError(search([keySource()]))
expect(error.message).toContain('DeepSeek API error (HTTP 503)')
})
it('keeps the status-line message when the JSON error body carries no detail', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 500 })))
const error = await rejectedWebError(searchProvider(options).search({ query: 'q' }))
const error = await rejectedWebError(search([keySource()]))
expect(error.message).toContain('DeepSeek API error (HTTP 500)')
})
it('maps an abort to WEB_ABORTED', async () => {
vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new DOMException('aborted', 'AbortError'))))
await expect(searchProvider(options).search({ query: 'q' }))
await expect(search([keySource()]))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
})
@@ -361,14 +448,14 @@ describe('DeepSeek web cancellation and failures', () => {
await new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => { reject(new Error('custom abort reason')) }, { once: true })
})))
const search = searchProvider(options).search({ query: 'q' }, controller.signal)
const pending = search([keySource()], controller.signal)
controller.abort(new Error('timeout reason'))
await expect(search).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
await expect(pending).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
})
it('maps an unparseable success body to WEB_PROVIDER_ERROR', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('not json', { status: 200 })))
await expect(searchProvider(options).search({ query: 'q' }))
await expect(search([keySource()]))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
})
@@ -376,7 +463,7 @@ describe('DeepSeek web cancellation and failures', () => {
const body = new Response('', { status: 200 })
vi.spyOn(body, 'json').mockRejectedValue(new DOMException('aborted', 'AbortError'))
vi.stubGlobal('fetch', vi.fn(async () => body))
await expect(searchProvider(options).search({ query: 'q' }))
await expect(search([keySource()]))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
})
@@ -384,15 +471,14 @@ describe('DeepSeek web cancellation and failures', () => {
const body = new Response('', { status: 500 })
vi.spyOn(body, 'json').mockRejectedValue(new DOMException('aborted', 'AbortError'))
vi.stubGlobal('fetch', vi.fn(async () => body))
await expect(searchProvider(options).search({ query: 'q' }))
await expect(search([keySource()]))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
})
it('maps a network failure to WEB_PROVIDER_ERROR', async () => {
vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new TypeError('connection refused'))))
const error = await rejectedWebError(searchProvider(options).search({ query: 'q' }))
const error = await rejectedWebError(search([keySource()]))
expect(error.code).toBe('WEB_PROVIDER_ERROR')
expect(error.message).toContain('The web request used endpoint "https://api.deepseek.test/v1/tools/search".')
})
})
@@ -5,11 +5,12 @@ import { customGuidance } from './guidance.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: apiKey ?? '' }] } as const
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: { apiKey: apiKey! }, baseURL, count: 10, requestsPerSecond: 5, guidance: customGuidance('search') }))
const provider = new DeepSeekSearchApiProvider(() => ({ auth, 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)
@@ -17,7 +18,7 @@ maybe('DeepSeek Search and Fetch real API', () => {
}, 40_000)
it('returns Markdown from the Fetch API', async () => {
const provider = new DeepSeekFetchApiProvider(() => ({ auth: { apiKey: apiKey! }, baseURL, guidance: customGuidance('fetch') }))
const provider = new DeepSeekFetchApiProvider(() => ({ auth, 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)