From d42563e4ba83cb1adefe5b14952434040810d0aa Mon Sep 17 00:00:00 2001 From: LegGasai Date: Tue, 10 Nov 2026 19:59:14 +0800 Subject: [PATCH 01/16] refactor(llm): publish DeepSeek route credentials through ctx.llm `LlmAdapter.routeCredential(provider)` publishes the credential a route currently sends: kind, resolved base URL, optional reference, a value-free presence check, and per-endpoint grants carrying protocol headers, the bare value, and an optional 401 invalidation. `LlmRuntime.routeCredential()` forwards to the owning adapter. `dsh-llm-deepseek` reads no credential: `resolveAuth(connection, endpoint)` returns a grant or `undefined`, `missingCredential` names the failure, and `credential` declares the publication. The route plugins own their credentials through the new `dsh-credentials` reference helpers and the account service's `resolveRequestCredential()`; the account route also owns sign-out cancellation and registers a running-task report. The account service inspects no Agents, drops its `dsh-agent` and `dsh-llm` peers, and moves to `packages/account/`. The web providers consume route publications and drop their dependencies on `dsh-llm-deepseek`, the route plugins, and the Loader. Documented in the Agent Note and the `llm-route-credential` upgrade guide. --- ...ch-offered-by-provider-readiness.i18n.yaml | 4 +- ...eb-search-offered-by-provider-readiness.md | 2 +- ...search-offered-by-provider-readiness.zh.md | 2 +- ...026-10-29-web-provider-selection.i18n.yaml | 4 +- .../2026-10-29-web-provider-selection.md | 4 +- .../2026-10-29-web-provider-selection.zh.md | 4 +- ...-11-10-llm-route-credential-seam.i18n.yaml | 19 ++ .../2026-11-10-llm-route-credential-seam.md | 37 +++ ...2026-11-10-llm-route-credential-seam.zh.md | 37 +++ ...-10-15-deepseek-search-fetch-api.i18n.yaml | 4 +- .../2026-10-15-deepseek-search-fetch-api.md | 2 +- ...2026-10-15-deepseek-search-fetch-api.zh.md | 2 +- ...dis-cleanup-dependency-lifetimes.i18n.yaml | 4 +- ...-09-cordis-cleanup-dependency-lifetimes.md | 2 +- ...-cordis-cleanup-dependency-lifetimes.zh.md | 2 +- AGENTS.md | 1 + apps/desktop-host/tsconfig.json | 2 +- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/tsconfig.client.json | 2 +- apps/desktop/tsconfig.host.json | 2 +- docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 21 +- docs/capability-seams.zh.md | 21 +- docs/config-catalog.md | 6 +- docs/config-catalog.zh.md | 6 +- docs/event-producer-consumer.md | 12 +- docs/event-producer-consumer.zh.md | 12 +- docs/module-graph.md | 92 ++++--- docs/module-graph.zh.md | 92 ++++--- docs/persistence-catalog.i18n.yaml | 72 +++--- docs/persistence-catalog.md | 36 +-- docs/persistence-catalog.zh.md | 36 +-- docs/persistence-schema.json | 34 +-- docs/subsystems/README.i18n.yaml | 4 +- docs/subsystems/README.md | 1 + docs/subsystems/README.zh.md | 1 + docs/subsystems/account.i18n.yaml | 16 ++ docs/subsystems/account.md | 234 ++++++++++++++++++ docs/subsystems/account.zh.md | 234 ++++++++++++++++++ docs/subsystems/credentials.i18n.yaml | 10 +- docs/subsystems/credentials.md | 197 +-------------- docs/subsystems/credentials.zh.md | 197 +-------------- docs/subsystems/llm-streaming.i18n.yaml | 8 +- docs/subsystems/llm-streaming.md | 96 +++++++ docs/subsystems/llm-streaming.zh.md | 96 +++++++ .../llm-route-credential/guide.i18n.yaml | 16 ++ .../v0.2.2-rc.1/llm-route-credential/guide.md | 29 +++ .../llm-route-credential/guide.zh.md | 29 +++ packages/README.i18n.yaml | 4 +- packages/README.md | 7 +- packages/README.zh.md | 7 +- packages/account/README.i18n.yaml | 25 ++ packages/account/README.md | 51 ++++ packages/account/README.zh.md | 51 ++++ .../deepseek-account/README.i18n.yaml | 10 +- .../deepseek-account/README.md | 6 +- .../deepseek-account/README.zh.md | 6 +- .../deepseek-account/locale/de.json | 0 .../deepseek-account/locale/en.json | 0 .../deepseek-account/locale/es.json | 0 .../deepseek-account/locale/fr.json | 0 .../deepseek-account/locale/ja.json | 0 .../deepseek-account/locale/pt.json | 0 .../deepseek-account/locale/ru.json | 0 .../deepseek-account/locale/zh.json | 0 .../deepseek-account/package.json | 11 +- .../deepseek-account/src/client-metadata.ts | 0 .../deepseek-account/src/details.ts | 0 .../deepseek-account/src/index.ts | 43 +++- .../deepseek-account/src/logout.ts | 0 .../deepseek-account/src/notifications.ts | 0 .../deepseek-account/src/protocol.ts | 13 +- .../deepseek-account/src/types.ts | 18 ++ .../deepseek-account/tests/account-stub.ts | 35 +++ .../deepseek-account/tests/account.spec.ts | 29 +++ .../tests/authorization-response.spec.ts | 0 .../tests/client-headers.spec.ts | 0 .../deepseek-account/tests/details.spec.ts | 0 .../tests/diagnostics.spec.ts | 0 .../tests/expected/web-exchange-failure.txt | 0 .../deepseek-account/tests/logout.spec.ts | 0 .../tests/notifications.spec.ts | 0 .../deepseek-account/tests/origins.spec.ts | 0 .../deepseek-account/tests/remote.spec.ts | 19 +- .../deepseek-account/tsconfig.json | 9 +- packages/api/remotes/tsconfig.client.json | 2 +- packages/api/remotes/tsconfig.host.json | 2 +- .../product-analytics/tsconfig.host.json | 2 +- .../ui-account-notifications/tsconfig.json | 2 +- .../client/ui-settings-account/tsconfig.json | 2 +- .../credentials/authorization/package.json | 8 +- .../credentials/authorization/src/index.ts | 2 +- .../credentials/authorization/tsconfig.json | 2 +- .../credentials/credentials/README.i18n.yaml | 4 +- packages/credentials/credentials/README.md | 2 + packages/credentials/credentials/README.zh.md | 2 + packages/credentials/credentials/package.json | 6 +- packages/credentials/credentials/src/index.ts | 33 +++ .../tests/reference-fallback.spec.ts | 50 ++++ .../credentials/credentials/tsconfig.json | 3 + .../deepseek-account/src/account-tasks.ts | 35 --- .../translator/tests/paid-fixture.ts | 6 +- .../extensions/tool-cordis/src/api-catalog.ts | 44 +++- .../llm/llm-deepseek-account/README.i18n.yaml | 12 +- packages/llm/llm-deepseek-account/README.md | 8 +- .../llm/llm-deepseek-account/README.zh.md | 8 +- .../llm/llm-deepseek-account/package.json | 9 +- .../llm-deepseek-account/src/account-tasks.ts | 40 +++ .../llm/llm-deepseek-account/src/index.ts | 36 ++- .../tests/account-quota.spec.ts | 12 +- .../tests/account-tasks.spec.ts | 13 +- .../tests/provider.spec.ts | 37 ++- .../llm/llm-deepseek-account/tsconfig.json | 5 +- .../llm/llm-deepseek-api-key/README.i18n.yaml | 12 +- packages/llm/llm-deepseek-api-key/README.md | 6 +- .../llm/llm-deepseek-api-key/README.zh.md | 6 +- .../llm/llm-deepseek-api-key/src/index.ts | 51 ++-- .../tests/discovery.spec.ts | 23 ++ packages/llm/llm-deepseek/README.i18n.yaml | 4 +- packages/llm/llm-deepseek/README.md | 6 +- packages/llm/llm-deepseek/README.zh.md | 6 +- packages/llm/llm-deepseek/src/adapter.ts | 27 +- packages/llm/llm-deepseek/src/auth-headers.ts | 12 + packages/llm/llm-deepseek/src/credential.ts | 58 ----- packages/llm/llm-deepseek/src/file-store.ts | 6 +- packages/llm/llm-deepseek/src/host.ts | 8 +- packages/llm/llm-deepseek/src/index.ts | 3 +- .../llm/llm-deepseek/src/listing-cache.ts | 25 +- packages/llm/llm-deepseek/src/types.ts | 45 +++- .../tests/account-routing.spec.ts | 12 +- .../llm/llm-deepseek/tests/adapter.spec.ts | 45 ++-- .../llm/llm-deepseek/tests/credential.spec.ts | 71 ------ packages/llm/llm-deepseek/tests/files.spec.ts | 2 +- packages/llm/llm-deepseek/tests/helpers.ts | 2 +- .../llm-deepseek/tests/listing-cache.spec.ts | 19 +- .../llm-deepseek/tests/prepared-call.spec.ts | 5 +- .../llm-deepseek/tests/provider-hooks.spec.ts | 4 +- .../tests/route-credential.spec.ts | 92 +++++++ .../llm/llm-deepseek/tests/runtime.spec.ts | 20 +- packages/llm/llm-deepseek/tsconfig.json | 2 +- packages/llm/llm/src/index.ts | 27 ++ packages/llm/llm/src/types.ts | 81 ++++++ packages/llm/llm/tests/topology.spec.ts | 24 +- .../skills/dsh-doc/references/packages.md | 7 +- .../continuation-messages-adapter.spec.ts | 2 +- .../web/web-deepseek-api/README.i18n.yaml | 12 +- packages/web/web-deepseek-api/README.md | 16 +- packages/web/web-deepseek-api/README.zh.md | 16 +- packages/web/web-deepseek-api/package.json | 26 +- packages/web/web-deepseek-api/src/index.ts | 210 +++++++++------- .../web/web-deepseek-api/src/transport.ts | 99 ++++---- .../tests/composition.spec.ts | 4 +- .../tests/credential-resolution.spec.ts | 95 +++---- .../web/web-deepseek-api/tests/egress.spec.ts | 3 +- .../web/web-deepseek-api/tests/fetch.spec.ts | 7 +- .../web-deepseek-api/tests/redirect.spec.ts | 6 +- packages/web/web-deepseek-api/tests/routes.ts | 73 +++--- .../web/web-deepseek-api/tests/search.spec.ts | 14 +- .../web-deepseek-api/tests/transport.spec.ts | 60 ++++- .../tests/web-deepseek-api.e2e.ts | 6 +- packages/web/web-deepseek-api/tsconfig.json | 12 +- .../web/web-search-deepseek/README.i18n.yaml | 12 +- packages/web/web-search-deepseek/README.md | 12 +- packages/web/web-search-deepseek/README.zh.md | 12 +- packages/web/web-search-deepseek/package.json | 21 +- packages/web/web-search-deepseek/src/index.ts | 74 +++--- .../web/web-search-deepseek/src/provider.ts | 42 ++-- .../tests/deepseek.spec.ts | 113 ++++++--- .../web/web-search-deepseek/tsconfig.json | 5 +- packages/web/web/package.json | 10 +- packages/web/web/src/types.ts | 2 +- packages/web/web/tsconfig.json | 2 +- pnpm-lock.yaml | 121 +++++---- scripts/gen-cordis-catalog.ts | 30 +-- scripts/gen-doc-graphs.ts | 10 +- scripts/plugin-entry-existing-exports.ts | 2 - scripts/type-equiv.manifest.json | 10 + .../verify-package-readme-model-experience.ts | 2 +- .../web-search-billing-fixture.mjs | 5 +- tsconfig.base.json | 6 +- tsconfig.host.json | 2 +- 183 files changed, 2775 insertions(+), 1577 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md create mode 100644 .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md create mode 100644 docs/subsystems/account.i18n.yaml create mode 100644 docs/subsystems/account.md create mode 100644 docs/subsystems/account.zh.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md create mode 100644 packages/account/README.i18n.yaml create mode 100644 packages/account/README.md create mode 100644 packages/account/README.zh.md rename packages/{credentials => account}/deepseek-account/README.i18n.yaml (86%) rename packages/{credentials => account}/deepseek-account/README.md (96%) rename packages/{credentials => account}/deepseek-account/README.zh.md (96%) rename packages/{credentials => account}/deepseek-account/locale/de.json (100%) rename packages/{credentials => account}/deepseek-account/locale/en.json (100%) rename packages/{credentials => account}/deepseek-account/locale/es.json (100%) rename packages/{credentials => account}/deepseek-account/locale/fr.json (100%) rename packages/{credentials => account}/deepseek-account/locale/ja.json (100%) rename packages/{credentials => account}/deepseek-account/locale/pt.json (100%) rename packages/{credentials => account}/deepseek-account/locale/ru.json (100%) rename packages/{credentials => account}/deepseek-account/locale/zh.json (100%) rename packages/{credentials => account}/deepseek-account/package.json (87%) rename packages/{credentials => account}/deepseek-account/src/client-metadata.ts (100%) rename packages/{credentials => account}/deepseek-account/src/details.ts (100%) rename packages/{credentials => account}/deepseek-account/src/index.ts (95%) rename packages/{credentials => account}/deepseek-account/src/logout.ts (100%) rename packages/{credentials => account}/deepseek-account/src/notifications.ts (100%) rename packages/{credentials => account}/deepseek-account/src/protocol.ts (95%) rename packages/{credentials => account}/deepseek-account/src/types.ts (89%) create mode 100644 packages/account/deepseek-account/tests/account-stub.ts rename packages/{credentials => account}/deepseek-account/tests/account.spec.ts (97%) rename packages/{credentials => account}/deepseek-account/tests/authorization-response.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/client-headers.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/details.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/diagnostics.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/expected/web-exchange-failure.txt (100%) rename packages/{credentials => account}/deepseek-account/tests/logout.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/notifications.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/origins.spec.ts (100%) rename packages/{credentials => account}/deepseek-account/tests/remote.spec.ts (84%) rename packages/{credentials => account}/deepseek-account/tsconfig.json (78%) create mode 100644 packages/credentials/credentials/tests/reference-fallback.spec.ts delete mode 100644 packages/credentials/deepseek-account/src/account-tasks.ts create mode 100644 packages/llm/llm-deepseek-account/src/account-tasks.ts rename packages/{credentials/deepseek-account => llm/llm-deepseek-account}/tests/account-tasks.spec.ts (78%) create mode 100644 packages/llm/llm-deepseek/src/auth-headers.ts delete mode 100644 packages/llm/llm-deepseek/src/credential.ts delete mode 100644 packages/llm/llm-deepseek/tests/credential.spec.ts create mode 100644 packages/llm/llm-deepseek/tests/route-credential.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml index badb03541e..8344fd2eb2 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml @@ -9,8 +9,8 @@ en: 32ba2b2b42e8deb5 zh: 6a6532561f81b8e2 /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/decision: - en: 08a54b37e157da29 - zh: 65f633055d9df242 + en: 8513348797d8b8c3 + zh: 13d4066e07db0fb9 /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered: en: 6da221f6b821ea44 zh: b15774011abed7ed diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md index 2399e3f1fc..ed8c3c2803 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md @@ -13,7 +13,7 @@ English | [中文](2026-09-27-web-search-offered-by-provider-readiness.zh.md) Each role of the web capability seam owns one part of a per-step check: - **Service Definition.** `WebSearchProvider` and `WebFetchProvider` have an optional `ready(llmProvider)` that answers whether an operation made for a model request on that chat route has a credential to send. It checks configuration only and makes no network calls. `ctx.web.searchReady(llmProvider?)` and `ctx.web.fetchReady(llmProvider?)` resolve the provider with the same rules as `search()` and `fetch()` and return its answer. A provider without `ready()` counts as ready, and a selection failure answers true because the operation reports that failure as a structured `WebError`. -- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on the `deepseek-account` route, whether `ctx.deepseekAccount.resolveToken()` returns a token for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, a token for that route's `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the [shared credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts) perform these presence checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section. +- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.routeCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section. - **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` with [step activation conditions](../../../../packages/core/tools/README.md#conditional-tools) that ask `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route of the step's model selection. The agent loop resolves conditions before it assembles the step, so the declared tools, the `tool:web_search` and `tool:web_fetch` prompt sections, PTC program bindings, and dispatch all read the same admitted set. The route decides only whether the account token is checked before the API key, which happens on the `deepseek-account` route; an API key counts on every route, so a conversation on another provider's model is offered the DeepSeek web tools whenever a DeepSeek key is configured. A Search or Fetch API capability with its own YAML fields ignores the route and is ready exactly when its own key is configured. diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md index 61f8acb6f8..96277e8532 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md @@ -13,7 +13,7 @@ Status: implemented web 能力 seam 的每个角色各负责逐步骤检查的一部分: - **Service Definition。** `WebSearchProvider` 与 `WebFetchProvider` 有一个可选的 `ready(llmProvider)`,回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。它只检查配置,不发起网络调用。`ctx.web.searchReady(llmProvider?)` 与 `ctx.web.fetchReady(llmProvider?)` 按与 `search()`、`fetch()` 相同的规则解析提供方并返回其回答。没有 `ready()` 的提供方视为就绪;选择失败时回答 true,因为对应操作会把该失败报告为结构化 `WebError`。 -- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `deepseek-account` 路由上检查 `ctx.deepseekAccount.resolveToken()` 是否为其 Messages 端点返回 token,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由 `/v1/tools` 基础地址的 token 算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由[共享凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。 +- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.routeCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。 - **Consumer。** `dsh-tool-web` 注册 `web_search` 与 `web_fetch` 时各带一个[步骤激活条件](../../../../packages/core/tools/README.zh.md#conditional-tools),以该步骤模型选择的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`。agent loop 在组装该步骤之前解析各条件,因此声明的工具、`tool:web_search` 与 `tool:web_fetch` 提示词段落、PTC 程序绑定与派发都读取同一个准入集合。 路由只决定是否先检查账号 token 再检查 API 密钥,这发生在 `deepseek-account` 路由上;API 密钥在每条路由上都算数,因此只要配置了 DeepSeek 密钥,使用其他提供方模型的对话也会获得 DeepSeek Web 工具。在 YAML 中设置了单独字段的 Search 或 Fetch API 能力不看路由,恰在其自身密钥已配置时就绪。 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml index 9ad135dbed..4c0e201093 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml @@ -18,8 +18,8 @@ en: 9d68ffca5c8be681 zh: 36bb661f98de0ebb /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/credential-resolution: - en: 15f6fb26c8605260 - zh: 93467641a8ff0aad + en: 6650000bd819e2ce + zh: 9e141db8bc3f51f8 /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections: en: 5fcd3319fbceed1d zh: 20771646b9c36fa6 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md index 82bfa34cfb..42aca3fdbc 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md @@ -30,11 +30,11 @@ The Search and Fetch APIs read one `web-deepseek-api` namespace, and each resolv Each of Search and Fetch has a billing setting, `web-deepseek-api.searchBilling` or `fetchBilling`, which the settings page edits as a **Billing** menu under the selected API. The default, `auto`, follows the DeepSeek credential of the conversation; `account` sends only the signed-in account's token and `api-key` only the API key, without falling back to the other. The conversation's route is the `provider` of the initiating Session's latest request context, which account sign-out also reads; `ready()` uses the route of the model request being prepared, so readiness and execution resolve the same plan. -The account 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. +The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.routeCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint. A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`fetchBaseURL` or `fetchApiKeyEnv` for Fetch) instead, whatever its billing, always sends the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) to its `*BaseURL` (the official base when unset) and never the account token, so an intranet or third-party endpoint receives only the key chosen for it. Each capability has its own fields because a deployment can serve search and fetch from different gateways. These fields are YAML-only, and an empty value counts as unset. Stored values of fields outside the schema, including `baseURL`, `apiKeyEnv`, and `apiKey`, load without schema errors and have no effect. -The [credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts) of `@deepseek-ai/dsh-llm-deepseek` read and validate API keys, check key presence, and release account tokens for the DeepSeek model routes, Messages search, and the Search and Fetch APIs, so every DeepSeek request reads the credential store the same way; the account model route, Messages search, and the Search and Fetch APIs also invalidate the token that an HTTP 401 rejects. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key. +The DeepSeek model routes publish the credential they send through `ctx.llm.routeCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key. ### Defaults and stored selections diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md index f995d39d19..58bb904d33 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md @@ -30,11 +30,11 @@ Search 与 Fetch API 读取同一个 `web-deepseek-api` namespace,并各自解 Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling` 或 `fetchBilling`,设置页在选中的 API 下方以**计费方式**下拉框编辑它。默认值 `auto` 跟随会话的 DeepSeek 凭据;`account` 只发送已登录账号的令牌,`api-key` 只发送 API 密钥,都不回退到另一种凭据。会话的路由是发起会话最近一次请求上下文的 `provider`,账号退出登录读取的也是它;`ready()` 使用正在准备的模型请求的路由,因此就绪判断与执行解析出相同的方案。 -账号令牌是 `ctx.deepseekAccount` 为模型提供方目录列出的入口根部活动 `@deepseek-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-account` 路由通过 `ctx.llm.routeCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。 在 YAML 中设置了非空 `searchBaseURL` 或 `searchApiKeyEnv`(Fetch 为 `fetchBaseURL` 或 `fetchApiKeyEnv`)的能力,则无论计费方式如何,始终把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为官方基础地址),从不发送账号令牌,因此内网或第三方端点只收到为它选择的密钥。每个能力有自己的字段,因为一个部署可以由不同网关提供搜索和抓取。这些字段只能在 YAML 中设置,空值视为未设置。schema 之外字段的已保存值,包括 `baseURL`、`apiKeyEnv` 和 `apiKey`,可以加载而不产生 schema 错误,且不生效。 -`@deepseek-ai/dsh-llm-deepseek` 的[凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)为 DeepSeek 模型路由、Messages 搜索以及 Search 与 Fetch API 读取并校验 API 密钥、检查密钥是否存在、取得账号令牌,因此每个 DeepSeek 请求都以同一方式读取凭据库;账号模型路由、Messages 搜索以及 Search 与 Fetch API 还会作废被 HTTP 401 拒绝的令牌。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 +DeepSeek 模型路由通过 `ctx.llm.routeCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 ### 默认值与已保存的选择 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml new file mode 100644 index 0000000000..2d080f2a52 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-10-llm-route-credential-seam.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse: + en: d11883f28d5cdd99 + zh: 860795ae4d93c317 +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/problem: + en: 9665e1879893fe76 + zh: 9da30ad0be6fc38d +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: + en: d7f7ef9ed3038ef7 + zh: c003e6b3338d1f3e +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: + en: 8177946a6bfa1a6d + zh: f523f9057b4b47c5 +/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: + en: e558492c672907dc + zh: 3748557528dc3055 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md new file mode 100644 index 0000000000..9e73be3c88 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -0,0 +1,37 @@ +# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse + +Status: implemented + +English | [中文](2026-11-10-llm-route-credential-seam.zh.md) + +## Problem + +Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/dsh-llm-deepseek`, the protocol transport, exported helpers that read `ctx.credentials`, the launch environment, and `ctx.deepseekAccount`, so the transport depended on both credential services although it only sends the headers a route gives it. The two route plugins resolved their credentials through those helpers and threw their own missing-credential failures from inside `resolveAuth`. The Search and Fetch API providers re-derived each route's base URL and key reference from the Loader entry of the route package with that package's own config resolver, and Messages search hard-coded the account route id, so both web packages depended on `llm-deepseek`, on both route plugins, and on the Loader. The account service, which sits below every consumer, owned Agent cancellation after sign-out and lived in the `credentials/` group beside the credential store it only uses. A change to how one route authenticates touched the transport, both web providers, and their tests. + +## Decision + +`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that read no value, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, and an optional `reject()` for HTTP 401. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. + +`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The listing cache scopes by endpoint and a hash of the credential headers. + +The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. + +`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. + +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account`, and the reference helpers otherwise. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. + +## Alternatives considered + +**A `deepseek-auth` package holding the credential seam.** The seam needs a Service Definition only, no Cordis service, and that one Definition role belongs beside `LlmAdapter`; a package for an interface adds a dependency without an owner of behavior. + +**A credential fingerprint in the published credential.** Consumers only send requests, so they need headers and a value; cache scoping by credential is the adapter's own concern, which the listing cache meets by hashing the headers it sends. + +**A `credentials-env` provider instead of reference helpers.** A provider that reads the environment would change which composition is authoritative for every consumer; the helpers keep the launch-environment fallback local to the consumers that need it, so such a provider remains an independent option. + +**The account service's inference origin for the web fallback without the account route.** Routing that fallback through `DEEPSEEK_BASE_URL` keeps the keyless billing snapshot and every documented deployment unchanged; the account service still refuses every origin but its own. + +**Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own. + +## Consequences + +Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md new file mode 100644 index 0000000000..663d216dff --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -0,0 +1,37 @@ +# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse + +Status: implemented + +[English](2026-11-10-llm-route-credential-seam.md) | 中文 + +## 问题 + +多个包共用同一份 DeepSeek 凭据,却没有所有者。协议传输层 `@deepseek-ai/dsh-llm-deepseek` 导出读取 `ctx.credentials`、启动环境和 `ctx.deepseekAccount` 的辅助函数,因此尽管传输层只发送路由交给它的请求头,它仍依赖两个凭据服务。两个路由插件通过这些函数解析凭据,并在 `resolveAuth` 内部抛出各自的凭据缺失错误。Search 与 Fetch API 提供方用路由包自己的配置解析函数,从路由包的 Loader 条目重新推导每条路由的基础地址和密钥引用,Messages 搜索则硬编码账号路由 id,因此两个 Web 包都依赖 `llm-deepseek`、两个路由插件和 Loader。位于所有消费方之下的账号服务拥有退登后的 Agent 取消逻辑,并和它仅仅使用的凭据库一起放在 `credentials/` 组。改变一条路由的鉴权方式要同时触及传输层、两个 Web 提供方及其测试。 + +## 决策 + +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不读取值的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`,以及可选的 HTTP 401 `reject()`。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 + +`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。列表缓存以端点和凭据请求头的哈希划分作用域。 + +路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。 + +`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 + +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类时使用其账号凭据,否则使用引用函数。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 + +## 考虑过的替代方案 + +**用一个 `deepseek-auth` 包承载凭据 seam。** 该 seam 只需要 Service Definition,不需要 Cordis 服务,而这一个 Definition 角色应与 `LlmAdapter` 放在一起;为一个接口建包只会增加一个没有行为所有者的依赖。 + +**在发布的凭据中加入凭据指纹。** 消费方只负责发送请求,因此只需要请求头和值;按凭据划分缓存作用域是适配器自己的事,列表缓存通过哈希它发送的请求头即可满足。 + +**用 `credentials-env` 提供方代替引用函数。** 读取环境的提供方会改变每个消费方眼中哪个组合具有权威性;引用函数把启动环境后备保留在需要它的消费方本地,使这样的提供方仍是独立的选项。 + +**没有账号路由时的 Web 后备使用账号服务的推理 origin。** 让该后备经由 `DEEPSEEK_BASE_URL` 可保持无密钥计费快照和所有已记录部署不变;账号服务仍拒绝除自身 origin 以外的一切来源。 + +**把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。 + +## 后果 + +新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml index 98c3a9541a..d683eb8924 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml @@ -27,8 +27,8 @@ en: 0dcc97d8105fab60 zh: d80d40ae3a0c601d /agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered: - en: 907e0b8424943d43 - zh: f45e583e7cb4eb63 + en: 88708dc170d3e77b + zh: e04536e494769d9c /agent-note-direct-deepseek-search-and-fetch-apis/consequences: en: 7ec21c5b1124e5f8 zh: af769dbdb4face9f diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md index ee8b912b2e..18c1946887 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md @@ -52,7 +52,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request **Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider. -**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the shared [`llm-deepseek` credential helpers](../../../../packages/llm/llm-deepseek/src/credential.ts); Messages search and the Search/Fetch API transports remain independent. +**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.routeCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent. **Split Search and Fetch into separate packages.** The guide serves both APIs from one base with one credential; separate packages would duplicate settings that address one deployment. Independent selection does not require separate packages, because each API registers its own provider id. Each operation lives in its own module, so either API can change without the other. diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md index c7493c8e23..324fcd1d0c 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md @@ -52,7 +52,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek **把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。 -**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为通过共享的 [`llm-deepseek` 凭据函数](../../../../packages/llm/llm-deepseek/src/credential.ts)获取;Messages 搜索与 Search/Fetch API 传输层保持独立。 +**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.routeCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。 **把 Search 和 Fetch 拆成两个包。** 指南从同一基础地址、以同一份凭据提供两个 API;拆成两个包会让指向同一部署的设置重复出现。分别选择不需要拆包,因为每个 API 注册自己的提供方 id。每种操作位于独立模块,任一 API 都可以单独修改。 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml index db6139954a..9346ae7076 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml @@ -21,8 +21,8 @@ en: 8a9578bbc700c0bf zh: 8ee46e5ef1cf3972 /agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/authorization-loses-required-observation-or-an-accepted-credential-write: - en: c6b0d746185d0d3b - zh: a228633ecdf42800 + en: 0532e871788d6ef7 + zh: 75131f43216bd05f /agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/ssh-disables-cleanup-requests-before-dependent-process-cleanup-finishes: en: 85fb2b564bc40230 zh: 97c3e794124f8044 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md index cb7ad564cd..86111905d8 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md @@ -36,7 +36,7 @@ A focused in-memory experiment using the actual Cordis and storage-domain implem ### Authorization loses required observation or an accepted credential write -**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts). +**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/account/deepseek-account/src/index.ts). **Successful write, false failure.** Pause a credential write, dispose the account consumer, then complete the write and emit its update. The observer can auto-unsubscribe alongside the account's drain; Authorization then rejects with `NOT_COMMITTED` despite successful storage. Keep observation owned by the operation until its result settles, or acknowledge successful `session.commit` directly while giving legacy direct-write observation an explicit lifetime. A focused experiment using actual Cordis and Authorization with a deferred in-memory credential provider reproduced `NOT_COMMITTED` after the provider write succeeded; the complete browser sign-in path is source-traced. diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md index fd5a6c3f45..8b779d84cc 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md @@ -36,7 +36,7 @@ Status: proposed ### Authorization 丢失必需的提交观察或已接受的凭据写入 -**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts)。 +**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/account/deepseek-account/src/index.ts)。 **写入成功,却报告失败。** 暂停凭据写入,释放账号消费者,再完成写入并发出更新。观察器可以与账号的排空并发自动退订;随后 Authorization 即使存储成功也会以 `NOT_COMMITTED` 拒绝。应让操作拥有观察器直到结果确定,或直接确认成功的 `session.commit`,同时给旧式直接写入观察明确的生命周期。使用实际 Cordis 与 Authorization、配合延迟的内存凭据 provider 的实验,复现了 provider 写入成功后返回 `NOT_COMMITTED`;完整浏览器登录路径由源码追踪确认。 diff --git a/AGENTS.md b/AGENTS.md index f189147619..6353b6a7dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,7 @@ packages/ @deepseek-ai/dsh- workspaces at packages/// identity/ anonymous identity settings/ user settings credentials/ credentials/authorization + account/ DeepSeek account acp/ automation-only ACP interaction/ human interaction boot/ application boot diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index c30951a3a4..9664d632b8 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -26,7 +26,7 @@ "path": "../../packages/host/webserver" }, { - "path": "../../packages/credentials/deepseek-account" + "path": "../../packages/account/deepseek-account" }, { "path": "../../packages/boot/plugin-manager" diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 7b4f37e1ad..9ef268ef5c 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -15,8 +15,8 @@ en: 127ea90553cb6af7 zh: 7b1c5aec8558c684 /deepseek-harness-desktop/application-overview: - en: 37d36f8d57214336 - zh: ceb50c0fa866eb24 + en: fba8dc2cecbe0350 + zh: 61092170a17906ad /deepseek-harness-desktop/terminal-command: en: 5f2d25a1d8472647 zh: 2acb5c5d7d1917e2 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index ffe4f5b520..0fc6a891ab 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -49,7 +49,7 @@ Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/depend Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar. -Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection. +Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/account/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection. A server-expired account credential returns to Welcome when no official API key is configured; an available API key keeps the workspace open. Explicit sign-out follows the same rule. Both Welcome and the workspace display the localized expiry notice. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index a6c2493fbc..e5d1a3d89c 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -49,7 +49,7 @@ Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一 Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。 -Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。 +Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/account/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。 账号凭据被服务端判定失效后,未配置官方 API key 时返回 Welcome;有可用 API key 时保持工作区打开。主动退出登录遵循相同规则。Welcome 和工作区均显示本地化的登录失效提示。 diff --git a/apps/desktop/tsconfig.client.json b/apps/desktop/tsconfig.client.json index eb17ebe087..7e24cdcda3 100644 --- a/apps/desktop/tsconfig.client.json +++ b/apps/desktop/tsconfig.client.json @@ -14,7 +14,7 @@ "path": "../../packages/client/ui-primitives" }, { - "path": "../../packages/credentials/deepseek-account" + "path": "../../packages/account/deepseek-account" }, { "path": "../../packages/client/product-analytics/tsconfig.client.json" diff --git a/apps/desktop/tsconfig.host.json b/apps/desktop/tsconfig.host.json index 2701caf5a6..92ec693165 100644 --- a/apps/desktop/tsconfig.host.json +++ b/apps/desktop/tsconfig.host.json @@ -18,7 +18,7 @@ "path": "../../packages/util/home-paths" }, { - "path": "../../packages/credentials/deepseek-account" + "path": "../../packages/account/deepseek-account" }, { "path": "../../packages/api/gateway/tsconfig.host.json" diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 77f025f1e9..040ac417df 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: b76743a3ff14d2f4 - zh: 82431aa3ded14a89 + en: 6fc86dc663906645 + zh: b1833a4bd578896a diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 145a4f5317..d52b5b4727 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -85,6 +85,8 @@ flowchart LR pkg_llm_replay["llm-replay"] pkg_agent_loop["agent-loop"] pkg_compaction_basic["compaction-basic"] + pkg_web_deepseek_api["web-deepseek-api"] + pkg_web_search_deepseek["web-search-deepseek"] pkg_session_log_deepseek["session-log-deepseek"] svc_sessionLogDeepSeek["ctx.sessionLogDeepSeek
Session-log upload policy"] pkg_deepseek_llm_api_extensions["deepseek-llm-api-extensions"] @@ -140,8 +142,10 @@ flowchart LR pkg_credentials["credentials"] svc_credentials["ctx.credentials
Credential seam"] pkg_credentials_local["credentials-local"] + pkg_llm_deepseek_api_key["llm-deepseek-api-key"] pkg_deepseek_account["deepseek-account"] svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"] + pkg_llm_deepseek_account["llm-deepseek-account"] pkg_authorization["authorization"] svc_authorization["ctx.authorization
Authorization flow registry"] pkg_client_product_analytics["client-product-analytics"] @@ -282,8 +286,6 @@ flowchart LR pkg_tool_jobs["tool-jobs"] pkg_web["web"] svc_web["ctx.web
Web access provider registry"] - pkg_web_search_deepseek["web-search-deepseek"] - pkg_web_deepseek_api["web-deepseek-api"] pkg_web_fetch_http["web-fetch-http"] pkg_spill["spill"] svc_spillStore["ctx.spillStore
Spill storage seam"] @@ -512,10 +514,13 @@ flowchart LR svc_connection --> pkg_host_frontend_static svc_cordisInspect --> pkg_tool_cordis svc_credentials --> pkg_api_settings_controller - svc_credentials --> pkg_llm_deepseek + svc_credentials --> pkg_llm_deepseek_api_key svc_credentials --> pkg_llm_pi_ai + svc_credentials --> pkg_web_deepseek_api + svc_credentials --> pkg_web_search_deepseek svc_cuaAccess --> pkg_cua - svc_deepseekAccount --> pkg_llm_deepseek + svc_deepseekAccount --> pkg_llm_deepseek_account + svc_deepseekAccount --> pkg_web_deepseek_api svc_deepseekLlmApiExtensions --> pkg_llm_deepseek svc_directoryPicker --> pkg_api_workspace_controller svc_dynamicCordisRunner --> pkg_tool_cordis @@ -534,6 +539,8 @@ flowchart LR svc_jobs --> pkg_tool_terminal svc_llm --> pkg_agent_loop svc_llm --> pkg_compaction_basic + svc_llm --> pkg_web_deepseek_api + svc_llm --> pkg_web_search_deepseek svc_lsp --> pkg_tool_lsp svc_mcpResources --> pkg_mcp_resources svc_officeKit --> pkg_client_ui_sidebar_documentpreview @@ -674,7 +681,7 @@ flowchart LR | `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-office`](../packages/document/tool-office) | - | Authorized Office bytes are rendered as PDFs or images, converted, or recalculated on the Host using the declared native target engine, or Node WASM when no native target is declared. | | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The host commits accepted images before session events; provider adapters resolve authorized durable references into provider-native content. | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | Owns streaming intake, durable storage, and staged receipt lifetime; the Session controller binds receipts to accepted submissions. | -| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic) | - | Adapters register provider implementations; the loop and compaction call the provider-neutral stream service. | +| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | Adapters register provider implementations; the loop and compaction call the provider-neutral stream service, and the DeepSeek web providers read the credential a route publishes. | | `ctx.sessionLogDeepSeek` | `core` | [`session-log-deepseek`](../packages/session/session-log-deepseek) | - | - | - | Plugins register caller-owned exclusions before the canonical Session-log request contribution is prepared; unmatched requests use normal upload eligibility. | | `ctx.deepseekLlmApiExtensions` | `seam` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | [`session-log-deepseek`](../packages/session/session-log-deepseek), [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Plugins prepare independent top-level fields; the official adapter merges them and commits their delivery state after HTTP acceptance. | | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Owns isolated per-session replay folds; pressure consumers share immutable revisioned measurements. | @@ -699,8 +706,8 @@ flowchart LR | `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. | | `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. | | `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session. | -| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. | -| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/credentials/deepseek-account) | - | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The Host owns browser authorization and local credentials; UI consumers receive state without tokens. | +| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. | +| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/account/deepseek-account) | - | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`web-deepseek-api`](../packages/web/web-deepseek-api) | - | The Host owns browser authorization and local credentials and releases per-request credentials to the account model route and the web providers; UI consumers receive state without tokens. | | `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol. | | `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | Accepts selected Desktop events, enriches available login identity, and observes live compaction under the live Host collection policy. | | `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | Product analytics and Session feedback adapters create independent reporting channels through one injected service. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 5effa1f8c4..bfc8a1df8c 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -87,6 +87,8 @@ flowchart LR pkg_llm_replay["llm-replay"] pkg_agent_loop["agent-loop"] pkg_compaction_basic["compaction-basic"] + pkg_web_deepseek_api["web-deepseek-api"] + pkg_web_search_deepseek["web-search-deepseek"] pkg_session_log_deepseek["session-log-deepseek"] svc_sessionLogDeepSeek["ctx.sessionLogDeepSeek
Session-log upload policy"] pkg_deepseek_llm_api_extensions["deepseek-llm-api-extensions"] @@ -142,8 +144,10 @@ flowchart LR pkg_credentials["credentials"] svc_credentials["ctx.credentials
Credential seam"] pkg_credentials_local["credentials-local"] + pkg_llm_deepseek_api_key["llm-deepseek-api-key"] pkg_deepseek_account["deepseek-account"] svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"] + pkg_llm_deepseek_account["llm-deepseek-account"] pkg_authorization["authorization"] svc_authorization["ctx.authorization
Authorization flow registry"] pkg_client_product_analytics["client-product-analytics"] @@ -284,8 +288,6 @@ flowchart LR pkg_tool_jobs["tool-jobs"] pkg_web["web"] svc_web["ctx.web
Web access provider registry"] - pkg_web_search_deepseek["web-search-deepseek"] - pkg_web_deepseek_api["web-deepseek-api"] pkg_web_fetch_http["web-fetch-http"] pkg_spill["spill"] svc_spillStore["ctx.spillStore
Spill storage seam"] @@ -514,10 +516,13 @@ flowchart LR svc_connection --> pkg_host_frontend_static svc_cordisInspect --> pkg_tool_cordis svc_credentials --> pkg_api_settings_controller - svc_credentials --> pkg_llm_deepseek + svc_credentials --> pkg_llm_deepseek_api_key svc_credentials --> pkg_llm_pi_ai + svc_credentials --> pkg_web_deepseek_api + svc_credentials --> pkg_web_search_deepseek svc_cuaAccess --> pkg_cua - svc_deepseekAccount --> pkg_llm_deepseek + svc_deepseekAccount --> pkg_llm_deepseek_account + svc_deepseekAccount --> pkg_web_deepseek_api svc_deepseekLlmApiExtensions --> pkg_llm_deepseek svc_directoryPicker --> pkg_api_workspace_controller svc_dynamicCordisRunner --> pkg_tool_cordis @@ -536,6 +541,8 @@ flowchart LR svc_jobs --> pkg_tool_terminal svc_llm --> pkg_agent_loop svc_llm --> pkg_compaction_basic + svc_llm --> pkg_web_deepseek_api + svc_llm --> pkg_web_search_deepseek svc_lsp --> pkg_tool_lsp svc_mcpResources --> pkg_mcp_resources svc_officeKit --> pkg_client_ui_sidebar_documentpreview @@ -676,7 +683,7 @@ flowchart LR | `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-office`](../packages/document/tool-office) | - | 已授权的 Office 字节在宿主上使用已声明的原生目标引擎渲染为 PDF 或图片、转换或重算;未声明原生目标时使用 Node WASM。 | | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 宿主会在会话事件之前提交已接受的图片;提供方适配器将已授权的持久引用解析为提供方原生内容。 | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | 负责流式接收、持久存储和暂存回执生命周期;Session Controller 将回执绑定到已接受的提交。 | -| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic) | - | 适配器注册提供方实现;agent loop(智能体循环)与压缩功能调用提供方无关的流服务。 | +| `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | 适配器注册提供方实现;agent loop(智能体循环)与压缩功能调用与提供方无关的流式服务,DeepSeek Web 提供方读取路由发布的凭据。 | | `ctx.sessionLogDeepSeek` | `core` | [`session-log-deepseek`](../packages/session/session-log-deepseek) | - | - | - | 插件在准备权威 Session 日志请求贡献前注册归调用方所有的排除条件;没有条件匹配的请求应用普通上传资格判断。 | | `ctx.deepseekLlmApiExtensions` | `seam` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | [`session-log-deepseek`](../packages/session/session-log-deepseek), [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 插件准备彼此独立的顶层字段;官方适配器会合并这些字段,并在 HTTP 接受后提交其交付状态。 | | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 拥有按会话隔离的回放折叠区;压力消费方共享不可变且带修订版本的测量结果。 | @@ -701,8 +708,8 @@ flowchart LR | `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. | | `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. | | `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | 拥有默认关闭的设置命名空间;Agent 作用域的委派工具会在组合新顶层 Session 时读取它。 | -| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 | -| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/credentials/deepseek-account) | - | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Host 负责浏览器授权和本地凭证;UI 使用方只接收不含 token 的状态。 | +| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`web-deepseek-api`](../packages/web/web-deepseek-api), [`web-search-deepseek`](../packages/web/web-search-deepseek) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 | +| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/account/deepseek-account) | - | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`web-deepseek-api`](../packages/web/web-deepseek-api) | - | Host 负责浏览器授权和本地凭证,并向账号模型路由和 Web 提供方释放按请求的凭据;UI 使用方只接收不含 token 的状态。 | | `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | flow 由知道如何取得某份凭据的插件注册,并以其写入的记录为键;seam 拥有这段对话与"每个键同时只跑一次尝试"的生命周期,而非协议本身。 | | `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | 根据 Host 动态采集策略接收指定桌面事件、补充可用登录身份并监听实时压缩。 | | `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | 产品埋点和 Session 反馈适配器通过同一个注入服务创建独立上报通道。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 41bd0207f3..e60acb4e73 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -892,7 +892,7 @@ export interface Config { ## `@deepseek-ai/dsh-deepseek-account` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts) +- `source`: [`packages/account/deepseek-account/src/index.ts:39`](../packages/account/deepseek-account/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ @@ -4851,7 +4851,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:56`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** @@ -4929,7 +4929,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-search-deepseek/src/index.ts:54`](../packages/web/web-search-deepseek/src/index.ts) +- `source`: [`packages/web/web-search-deepseek/src/index.ts:53`](../packages/web/web-search-deepseek/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `apply` fills env-var and constant defaults). */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index a3bb192363..5abff53155 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -894,7 +894,7 @@ export interface Config { ## `@deepseek-ai/dsh-deepseek-account` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts) +- `source`: [`packages/account/deepseek-account/src/index.ts:39`](../packages/account/deepseek-account/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ @@ -4853,7 +4853,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:56`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** @@ -4931,7 +4931,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-search-deepseek/src/index.ts:54`](../packages/web/web-search-deepseek/src/index.ts) +- `source`: [`packages/web/web-search-deepseek/src/index.ts:53`](../packages/web/web-search-deepseek/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `apply` fills env-var and constant defaults). */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 1d80e1cfe7..c9c6deebc2 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -15,7 +15,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | @@ -40,11 +40,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/account/deepseek-account), `remotes` | | `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:88`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | -| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:110`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | -| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:106`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | -| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | +| `deepseek-account/model-sign-in-required` | `emit` | [`packages/account/deepseek-account/src/types.ts:110`](../packages/account/deepseek-account/src/types.ts) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) (`emit`) | `remotes` | +| `deepseek-account/session-expired` | `emit` | [`packages/account/deepseek-account/src/types.ts:106`](../packages/account/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`deepseek-account`](../packages/account/deepseek-account), `remotes` | +| `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | @@ -59,7 +59,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:77`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 9245fa8fab..0e89f97f00 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -17,7 +17,7 @@ | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | @@ -42,11 +42,11 @@ | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/account/deepseek-account), `remotes` | | `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:88`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | -| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:110`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | -| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:106`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | -| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | +| `deepseek-account/model-sign-in-required` | `emit` | [`packages/account/deepseek-account/src/types.ts:110`](../packages/account/deepseek-account/src/types.ts) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) (`emit`) | `remotes` | +| `deepseek-account/session-expired` | `emit` | [`packages/account/deepseek-account/src/types.ts:106`](../packages/account/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`deepseek-account`](../packages/account/deepseek-account), `remotes` | +| `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | @@ -61,7 +61,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:77`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/module-graph.md b/docs/module-graph.md index f7b3d5563c..bdbe8d7067 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -115,6 +115,9 @@ flowchart TD subgraph group_acp["packages/acp"] pkg_acp["acp"] end + subgraph group_account["packages/account"] + pkg_deepseek_account["deepseek-account"] + end subgraph group_api["packages/api"] pkg_api_gateway["api-gateway"] pkg_api_job_controller["api-job-controller"] @@ -245,7 +248,6 @@ flowchart TD pkg_authorization["authorization"] pkg_credentials["credentials"] pkg_credentials_local["credentials-local"] - pkg_deepseek_account["deepseek-account"] end subgraph group_deliverables["packages/deliverables"] pkg_deliverable_file_references["deliverable-file-references"] @@ -488,6 +490,7 @@ flowchart TD end pkg_llm --> pkg_error pkg_session --> pkg_scope + pkg_web --> pkg_error pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand pkg_attachment --> pkg_error @@ -496,10 +499,7 @@ flowchart TD pkg_browser_use --> pkg_brand pkg_client_connection --> pkg_scope pkg_computer_use --> pkg_brand - pkg_credentials_local --> pkg_atomic_write - pkg_credentials_local --> pkg_credentials - pkg_credentials_local --> pkg_home_paths - pkg_credentials_local --> pkg_launch_environment + pkg_credentials --> pkg_launch_environment pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths @@ -516,7 +516,8 @@ flowchart TD pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm pkg_skill --> pkg_scope - pkg_web --> pkg_llm + pkg_web_fetch_http --> pkg_timeout + pkg_web_fetch_http --> pkg_web pkg_spill --> pkg_brand pkg_spill --> pkg_llm pkg_spill --> pkg_session @@ -526,7 +527,11 @@ flowchart TD pkg_hmr --> pkg_app_boot pkg_hmr --> pkg_cmdline pkg_authorization --> pkg_credentials - pkg_authorization --> pkg_llm + pkg_authorization --> pkg_error + pkg_credentials_local --> pkg_atomic_write + pkg_credentials_local --> pkg_credentials + pkg_credentials_local --> pkg_home_paths + pkg_credentials_local --> pkg_launch_environment pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_subprocess @@ -564,11 +569,15 @@ flowchart TD pkg_fs --> pkg_llm pkg_fs --> pkg_sandbox pkg_skill_office --> pkg_skill - pkg_web_fetch_http --> pkg_timeout - pkg_web_fetch_http --> pkg_web pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence + pkg_deepseek_account --> pkg_authorization + pkg_deepseek_account --> pkg_brand + pkg_deepseek_account --> pkg_credentials + pkg_deepseek_account --> pkg_host_webserver + pkg_deepseek_account --> pkg_typert_protocol + pkg_deepseek_account --> pkg_util_values pkg_config_editor --> pkg_app_boot pkg_config_editor --> pkg_hmr pkg_deliverable_file_references --> pkg_system_prompt @@ -667,6 +676,11 @@ flowchart TD pkg_pwsh_local --> pkg_shell pkg_pwsh_local --> pkg_subprocess pkg_pwsh_local --> pkg_timeout + pkg_llm_deepseek_account --> pkg_agent + pkg_llm_deepseek_account --> pkg_deepseek_account + pkg_llm_deepseek_account --> pkg_launch_environment + pkg_llm_deepseek_account --> pkg_llm + pkg_llm_deepseek_account --> pkg_llm_deepseek pkg_llm_deepseek_api_key --> pkg_credentials pkg_llm_deepseek_api_key --> pkg_launch_environment pkg_llm_deepseek_api_key --> pkg_llm @@ -686,6 +700,19 @@ flowchart TD pkg_goal --> pkg_session pkg_goal --> pkg_session_projection pkg_goal --> pkg_typert_protocol + pkg_web_deepseek_api --> pkg_agent + pkg_web_deepseek_api --> pkg_credentials + pkg_web_deepseek_api --> pkg_deepseek_account + pkg_web_deepseek_api --> pkg_launch_environment + pkg_web_deepseek_api --> pkg_llm + pkg_web_deepseek_api --> pkg_session + pkg_web_deepseek_api --> pkg_web + pkg_web_search_deepseek --> pkg_agent + pkg_web_search_deepseek --> pkg_credentials + pkg_web_search_deepseek --> pkg_launch_environment + pkg_web_search_deepseek --> pkg_llm + pkg_web_search_deepseek --> pkg_session + pkg_web_search_deepseek --> pkg_web pkg_file_reference --> pkg_agent pkg_harness_dev_context --> pkg_agent pkg_harness_dev_context --> pkg_session @@ -700,14 +727,6 @@ flowchart TD pkg_tmux_context --> pkg_session pkg_tmux_context --> pkg_session_projection pkg_tmux_context --> pkg_shell - pkg_deepseek_account --> pkg_agent - pkg_deepseek_account --> pkg_authorization - pkg_deepseek_account --> pkg_brand - pkg_deepseek_account --> pkg_credentials - pkg_deepseek_account --> pkg_host_webserver - pkg_deepseek_account --> pkg_llm - pkg_deepseek_account --> pkg_typert_protocol - pkg_deepseek_account --> pkg_util_values pkg_commands --> pkg_agent pkg_commands --> pkg_attachment pkg_commands --> pkg_brand @@ -763,10 +782,6 @@ flowchart TD pkg_workflow --> pkg_brand pkg_workflow --> pkg_llm pkg_workflow --> pkg_session - pkg_llm_deepseek_account --> pkg_deepseek_account - pkg_llm_deepseek_account --> pkg_launch_environment - pkg_llm_deepseek_account --> pkg_llm - pkg_llm_deepseek_account --> pkg_llm_deepseek pkg_tools --> pkg_agent pkg_tools --> pkg_llm pkg_tools --> pkg_scope @@ -780,13 +795,6 @@ flowchart TD pkg_fs_sandbox --> pkg_fs_local pkg_fs_sandbox --> pkg_sandbox pkg_fs_sandbox --> pkg_sandbox_policy - pkg_web_search_deepseek --> pkg_agent - pkg_web_search_deepseek --> pkg_credentials - pkg_web_search_deepseek --> pkg_deepseek_account - pkg_web_search_deepseek --> pkg_launch_environment - pkg_web_search_deepseek --> pkg_llm_deepseek - pkg_web_search_deepseek --> pkg_session - pkg_web_search_deepseek --> pkg_web pkg_compaction --> pkg_brand pkg_compaction --> pkg_commands pkg_compaction --> pkg_llm @@ -900,16 +908,6 @@ flowchart TD pkg_tool_web --> pkg_system_prompt pkg_tool_web --> pkg_tools pkg_tool_web --> pkg_web - pkg_web_deepseek_api --> pkg_agent - pkg_web_deepseek_api --> pkg_credentials - pkg_web_deepseek_api --> pkg_deepseek_account - pkg_web_deepseek_api --> pkg_launch_environment - pkg_web_deepseek_api --> pkg_llm - pkg_web_deepseek_api --> pkg_llm_deepseek - pkg_web_deepseek_api --> pkg_llm_deepseek_account - pkg_web_deepseek_api --> pkg_llm_deepseek_api_key - pkg_web_deepseek_api --> pkg_session - pkg_web_deepseek_api --> pkg_web pkg_tool_todo --> pkg_agent pkg_tool_todo --> pkg_session pkg_tool_todo --> pkg_session_projection @@ -1654,7 +1652,6 @@ flowchart TD | [`client-ui-workflow-run`](../packages/client/ui-workflow-run) | `client` | — | | [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | — | | [`client-web`](../packages/client/web) | `client` | — | -| [`credentials`](../packages/credentials/credentials) | `credentials` | — | | [`office-kit`](../packages/document/office-kit) | `document` | — | | [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | `experimental` | — | | [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | @@ -1700,13 +1697,14 @@ flowchart TD | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | +| [`web`](../packages/web/web) | `web` | [`error`](../packages/util/error) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | | [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | -| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | +| [`credentials`](../packages/credentials/credentials) | `credentials` | [`launch-environment`](../packages/util/launch-environment) | | [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | @@ -1719,12 +1717,13 @@ flowchart TD | [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | +| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) | | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | | [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | -| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | +| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error) | +| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | @@ -1742,9 +1741,9 @@ flowchart TD | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | -| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | +| [`deepseek-account`](../packages/account/deepseek-account) | `account` | [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | | [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | `experimental` | [`settings`](../packages/settings/settings) | @@ -1776,15 +1775,17 @@ flowchart TD | [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`bash-local`](../packages/shell/bash-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`timeout`](../packages/util/timeout) | | [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | +| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | +| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | | [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | -| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`llm`](../packages/llm/llm), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | @@ -1796,11 +1797,9 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | -| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | @@ -1822,7 +1821,6 @@ flowchart TD | [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`tools`](../packages/core/tools) | | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | -| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | | [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 340164d5a3..319d57e90c 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -117,6 +117,9 @@ flowchart TD subgraph group_acp["packages/acp"] pkg_acp["acp"] end + subgraph group_account["packages/account"] + pkg_deepseek_account["deepseek-account"] + end subgraph group_api["packages/api"] pkg_api_gateway["api-gateway"] pkg_api_job_controller["api-job-controller"] @@ -247,7 +250,6 @@ flowchart TD pkg_authorization["authorization"] pkg_credentials["credentials"] pkg_credentials_local["credentials-local"] - pkg_deepseek_account["deepseek-account"] end subgraph group_deliverables["packages/deliverables"] pkg_deliverable_file_references["deliverable-file-references"] @@ -490,6 +492,7 @@ flowchart TD end pkg_llm --> pkg_error pkg_session --> pkg_scope + pkg_web --> pkg_error pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand pkg_attachment --> pkg_error @@ -498,10 +501,7 @@ flowchart TD pkg_browser_use --> pkg_brand pkg_client_connection --> pkg_scope pkg_computer_use --> pkg_brand - pkg_credentials_local --> pkg_atomic_write - pkg_credentials_local --> pkg_credentials - pkg_credentials_local --> pkg_home_paths - pkg_credentials_local --> pkg_launch_environment + pkg_credentials --> pkg_launch_environment pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths @@ -518,7 +518,8 @@ flowchart TD pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm pkg_skill --> pkg_scope - pkg_web --> pkg_llm + pkg_web_fetch_http --> pkg_timeout + pkg_web_fetch_http --> pkg_web pkg_spill --> pkg_brand pkg_spill --> pkg_llm pkg_spill --> pkg_session @@ -528,7 +529,11 @@ flowchart TD pkg_hmr --> pkg_app_boot pkg_hmr --> pkg_cmdline pkg_authorization --> pkg_credentials - pkg_authorization --> pkg_llm + pkg_authorization --> pkg_error + pkg_credentials_local --> pkg_atomic_write + pkg_credentials_local --> pkg_credentials + pkg_credentials_local --> pkg_home_paths + pkg_credentials_local --> pkg_launch_environment pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_subprocess @@ -566,11 +571,15 @@ flowchart TD pkg_fs --> pkg_llm pkg_fs --> pkg_sandbox pkg_skill_office --> pkg_skill - pkg_web_fetch_http --> pkg_timeout - pkg_web_fetch_http --> pkg_web pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence + pkg_deepseek_account --> pkg_authorization + pkg_deepseek_account --> pkg_brand + pkg_deepseek_account --> pkg_credentials + pkg_deepseek_account --> pkg_host_webserver + pkg_deepseek_account --> pkg_typert_protocol + pkg_deepseek_account --> pkg_util_values pkg_config_editor --> pkg_app_boot pkg_config_editor --> pkg_hmr pkg_deliverable_file_references --> pkg_system_prompt @@ -669,6 +678,11 @@ flowchart TD pkg_pwsh_local --> pkg_shell pkg_pwsh_local --> pkg_subprocess pkg_pwsh_local --> pkg_timeout + pkg_llm_deepseek_account --> pkg_agent + pkg_llm_deepseek_account --> pkg_deepseek_account + pkg_llm_deepseek_account --> pkg_launch_environment + pkg_llm_deepseek_account --> pkg_llm + pkg_llm_deepseek_account --> pkg_llm_deepseek pkg_llm_deepseek_api_key --> pkg_credentials pkg_llm_deepseek_api_key --> pkg_launch_environment pkg_llm_deepseek_api_key --> pkg_llm @@ -688,6 +702,19 @@ flowchart TD pkg_goal --> pkg_session pkg_goal --> pkg_session_projection pkg_goal --> pkg_typert_protocol + pkg_web_deepseek_api --> pkg_agent + pkg_web_deepseek_api --> pkg_credentials + pkg_web_deepseek_api --> pkg_deepseek_account + pkg_web_deepseek_api --> pkg_launch_environment + pkg_web_deepseek_api --> pkg_llm + pkg_web_deepseek_api --> pkg_session + pkg_web_deepseek_api --> pkg_web + pkg_web_search_deepseek --> pkg_agent + pkg_web_search_deepseek --> pkg_credentials + pkg_web_search_deepseek --> pkg_launch_environment + pkg_web_search_deepseek --> pkg_llm + pkg_web_search_deepseek --> pkg_session + pkg_web_search_deepseek --> pkg_web pkg_file_reference --> pkg_agent pkg_harness_dev_context --> pkg_agent pkg_harness_dev_context --> pkg_session @@ -702,14 +729,6 @@ flowchart TD pkg_tmux_context --> pkg_session pkg_tmux_context --> pkg_session_projection pkg_tmux_context --> pkg_shell - pkg_deepseek_account --> pkg_agent - pkg_deepseek_account --> pkg_authorization - pkg_deepseek_account --> pkg_brand - pkg_deepseek_account --> pkg_credentials - pkg_deepseek_account --> pkg_host_webserver - pkg_deepseek_account --> pkg_llm - pkg_deepseek_account --> pkg_typert_protocol - pkg_deepseek_account --> pkg_util_values pkg_commands --> pkg_agent pkg_commands --> pkg_attachment pkg_commands --> pkg_brand @@ -765,10 +784,6 @@ flowchart TD pkg_workflow --> pkg_brand pkg_workflow --> pkg_llm pkg_workflow --> pkg_session - pkg_llm_deepseek_account --> pkg_deepseek_account - pkg_llm_deepseek_account --> pkg_launch_environment - pkg_llm_deepseek_account --> pkg_llm - pkg_llm_deepseek_account --> pkg_llm_deepseek pkg_tools --> pkg_agent pkg_tools --> pkg_llm pkg_tools --> pkg_scope @@ -782,13 +797,6 @@ flowchart TD pkg_fs_sandbox --> pkg_fs_local pkg_fs_sandbox --> pkg_sandbox pkg_fs_sandbox --> pkg_sandbox_policy - pkg_web_search_deepseek --> pkg_agent - pkg_web_search_deepseek --> pkg_credentials - pkg_web_search_deepseek --> pkg_deepseek_account - pkg_web_search_deepseek --> pkg_launch_environment - pkg_web_search_deepseek --> pkg_llm_deepseek - pkg_web_search_deepseek --> pkg_session - pkg_web_search_deepseek --> pkg_web pkg_compaction --> pkg_brand pkg_compaction --> pkg_commands pkg_compaction --> pkg_llm @@ -902,16 +910,6 @@ flowchart TD pkg_tool_web --> pkg_system_prompt pkg_tool_web --> pkg_tools pkg_tool_web --> pkg_web - pkg_web_deepseek_api --> pkg_agent - pkg_web_deepseek_api --> pkg_credentials - pkg_web_deepseek_api --> pkg_deepseek_account - pkg_web_deepseek_api --> pkg_launch_environment - pkg_web_deepseek_api --> pkg_llm - pkg_web_deepseek_api --> pkg_llm_deepseek - pkg_web_deepseek_api --> pkg_llm_deepseek_account - pkg_web_deepseek_api --> pkg_llm_deepseek_api_key - pkg_web_deepseek_api --> pkg_session - pkg_web_deepseek_api --> pkg_web pkg_tool_todo --> pkg_agent pkg_tool_todo --> pkg_session pkg_tool_todo --> pkg_session_projection @@ -1656,7 +1654,6 @@ flowchart TD | [`client-ui-workflow-run`](../packages/client/ui-workflow-run) | `client` | — | | [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | — | | [`client-web`](../packages/client/web) | `client` | — | -| [`credentials`](../packages/credentials/credentials) | `credentials` | — | | [`office-kit`](../packages/document/office-kit) | `document` | — | | [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | `experimental` | — | | [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | @@ -1702,13 +1699,14 @@ flowchart TD | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | +| [`web`](../packages/web/web) | `web` | [`error`](../packages/util/error) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | | [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | -| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | +| [`credentials`](../packages/credentials/credentials) | `credentials` | [`launch-environment`](../packages/util/launch-environment) | | [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | @@ -1721,12 +1719,13 @@ flowchart TD | [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | +| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) | | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | | [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | -| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | +| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error) | +| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | @@ -1744,9 +1743,9 @@ flowchart TD | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | -| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | +| [`deepseek-account`](../packages/account/deepseek-account) | `account` | [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | | [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | `experimental` | [`settings`](../packages/settings/settings) | @@ -1778,15 +1777,17 @@ flowchart TD | [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`bash-local`](../packages/shell/bash-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`timeout`](../packages/util/timeout) | | [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | +| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | +| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | | [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | -| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`llm`](../packages/llm/llm), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | @@ -1798,11 +1799,9 @@ flowchart TD | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | -| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | @@ -1824,7 +1823,6 @@ flowchart TD | [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`tools`](../packages/core/tools) | | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | -| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | | [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index f2294edff6..e7a2915d50 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -294,8 +294,8 @@ en: d278748103cf1640 zh: d278748103cf1640 /session-persistence-event-catalog/events/web/web-deepseek-search-llm-request-log-only: - en: a3e7718f295ba130 - zh: e6435b44b42f0784 + en: 52d1a5b0a68ac0a4 + zh: 1df3a7a0da7f5fa0 /session-persistence-event-catalog/events/working-directory: en: e8dd0cebbb930eb7 zh: e8dd0cebbb930eb7 @@ -558,8 +558,8 @@ en: 028791baa24a6a0a zh: 028791baa24a6a0a /session-persistence-event-catalog/resolved-persistence-types/in-history: - en: ad2f023eedbc2a7e - zh: 2124b8dedfbf8383 + en: eef7993dfeef3c9d + zh: 36f6a03a24688113 /session-persistence-event-catalog/resolved-persistence-types/in-progress: en: 61de2b0c9de8c15b zh: 61de2b0c9de8c15b @@ -1026,8 +1026,8 @@ en: a6a2e38fdd6d127a zh: 1fe82356d89f5769 /session-persistence-event-catalog/resolved-persistence-types/deepseeksearchllmrequest: - en: 8cc704c4048167a7 - zh: d27823620065ad25 + en: ee82cea3594af41c + zh: c8e879993414b727 /session-persistence-event-catalog/resolved-persistence-types/developermessage: en: b91fd6f924b6d84e zh: c74abb179c889ed6 @@ -1194,8 +1194,8 @@ en: 8d2873c634bf6405 zh: 91e92b5730462cf0 /session-persistence-event-catalog/resolved-persistence-types/replayenvelope: - en: 34cbedee7bc95921 - zh: f7deeddb8d60152a + en: c0559f92b5275c58 + zh: 50616ae676eeee4c /session-persistence-event-catalog/resolved-persistence-types/requestcontext: en: 544039047a28b6bb zh: c691f0bb1e23db08 @@ -1245,8 +1245,8 @@ en: ecc15ebadb77afdf zh: 97ac27d6a4175f6f /session-persistence-event-catalog/resolved-persistence-types/streamchunk: - en: 747e384b3176e0cb - zh: defbff408ea7c97c + en: 1585ce86ccaaca53 + zh: b3073eb80e23a11f /session-persistence-event-catalog/resolved-persistence-types/subagentcatalogevent: en: 8a56ae8e701509b3 zh: caef4f0223f65470 @@ -1284,8 +1284,8 @@ en: b6bd8e9986773217 zh: ed177c2f090964af /session-persistence-event-catalog/resolved-persistence-types/textblock: - en: 7ad0f4915397b511 - zh: bcaa8bd449927989 + en: e820b2d216671243 + zh: a569cf66b82c57d7 /session-persistence-event-catalog/resolved-persistence-types/todoitem: en: ee24f9407df530ac zh: 310bedf3ac730d77 @@ -1314,8 +1314,8 @@ en: 2258683c3cfa4ce3 zh: 5663aa76c911761b /session-persistence-event-catalog/resolved-persistence-types/toolschema: - en: afa1e3fd9ccdd95b - zh: 7af667e3ebac25e8 + en: a1613c3dc1fd1b54 + zh: eb4590c068e2699c /session-persistence-event-catalog/resolved-persistence-types/toolschema~2: en: 12c14727bb7834e2 zh: b0f3c877873c36db @@ -1932,8 +1932,8 @@ en: b28ca6b37f5a338d zh: 4c4f2f05721b8b62 /session-persistence-event-catalog/resolved-persistence-types/max-tokens-messages-model-thinking: - en: 3216b23c131d0070 - zh: 73ca171c6014f16e + en: efe43158304eaf7b + zh: 7a4b0d7f1a9f1c65 /session-persistence-event-catalog/resolved-persistence-types/member-teamid-version: en: 33c28b8c72b73604 zh: 8b606ec7196176c8 @@ -1959,8 +1959,8 @@ en: b8d80b4b1e6441ad zh: d5c52e1bfe560297 /session-persistence-event-catalog/resolved-persistence-types/role-user: - en: 04b34b8ffe7e7764 - zh: a792d5371516fd9d + en: d05bb42138160fbd + zh: 9a17d062eefa48a3 /session-persistence-event-catalog/resolved-persistence-types/sessionformatversion-sessionid-throughseq: en: 8063597183ef767f zh: b064698c54089f07 @@ -2007,11 +2007,11 @@ en: bb507524bcc39c53 zh: 8314898562437473 /session-persistence-event-catalog/resolved-persistence-types/type-block-end: - en: 7513d6a33f4ad113 - zh: 652201059a3de858 + en: c65956b2e4936b98 + zh: 04a10188520dd9e2 /session-persistence-event-catalog/resolved-persistence-types/type-block-start: - en: 56230efa41e79869 - zh: 9ca4b8990a28d4d9 + en: 10eec3e1fa456886 + zh: a62e18e8e00a5f18 /session-persistence-event-catalog/resolved-persistence-types/type-chunk: en: 2186ede3e9917aea zh: 0cfef64045dce95b @@ -2040,8 +2040,8 @@ en: 6b632a8f70a45496 zh: ad6c793e41731fd7 /session-persistence-event-catalog/resolved-persistence-types/type-disabled: - en: 585627a50ece4e5f - zh: 157837aee3da0ac3 + en: 04db8a26a3befdd4 + zh: 8b24a37ac00bac8a /session-persistence-event-catalog/resolved-persistence-types/type-feedback-message-delete: en: 204561e2311db97e zh: 77264396bd5e25c4 @@ -2052,8 +2052,8 @@ en: 14e4b48d856bcf57 zh: 72ba176535dc7f3f /session-persistence-event-catalog/resolved-persistence-types/type-finish: - en: 30f8f49d0755dc2d - zh: d8553c9590a0e9bf + en: df64e36d97f48908 + zh: 86cf679e6b3fdb85 /session-persistence-event-catalog/resolved-persistence-types/type-goal-change: en: aad2516b62d3ee83 zh: e7204c4dc4e8e408 @@ -2091,8 +2091,8 @@ en: 34e5591d75322649 zh: a216839f305c9796 /session-persistence-event-catalog/resolved-persistence-types/type-reasoning-delta: - en: a3f08ffda3526201 - zh: e599517be130ff99 + en: bcafe0c539f6a5e2 + zh: 3be968698a8985bc /session-persistence-event-catalog/resolved-persistence-types/type-request-context: en: f8addb1a01da9ca1 zh: 4ef11ebddd302c05 @@ -2154,8 +2154,8 @@ en: 1484738718de5312 zh: 3e6fbe9c64068225 /session-persistence-event-catalog/resolved-persistence-types/type-text-delta: - en: 5f30a603fab07135 - zh: 3b7e2076351a1473 + en: 908a84e2ee82a7cc + zh: 5d8994c209e864a0 /session-persistence-event-catalog/resolved-persistence-types/type-todo-write: en: 2fa7ba77598a95b4 zh: 50972b51d77e9155 @@ -2163,8 +2163,8 @@ en: 32f732b97739e4d2 zh: f288e48e356969c0 /session-persistence-event-catalog/resolved-persistence-types/type-tool-call-delta: - en: 0e907728f330a8c7 - zh: d9d1400d4c468ab2 + en: 9663efae6bd28efb + zh: d8765a82a6b537a5 /session-persistence-event-catalog/resolved-persistence-types/type-tool-workflow-agent-end: en: 8eb5e1eb95722bc7 zh: 8dd5980029600648 @@ -2196,8 +2196,8 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: 5c4bf682faecace1 - zh: e2014c3dc10bae79 + en: 20d2e379fc64c866 + zh: b2d35dba5d3006af /session-persistence-event-catalog/resolved-persistence-types/type-user-message: en: fd9f5dacef8c0ce8 zh: 79eab747b55dfaac @@ -2205,8 +2205,8 @@ en: 99c8837344178a47 zh: bf746f5678346596 /session-persistence-event-catalog/resolved-persistence-types/type-web-search-20250305: - en: e0071555851c7cee - zh: 1f368baf78a7d689 + en: 557e9462b176c4a3 + zh: 4dddcab9de61639f /session-persistence-event-catalog/resolved-persistence-types/type-working-directory-change: en: 2fcb09b83898ee18 zh: 44c7f987f0bf3588 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 33d9aa4395..30e9eaf416 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -1313,7 +1313,7 @@ Source: [`packages/core/session/src/types.ts:315`](../packages/core/session/src/ 'web/deepseek-search-llm-request': DeepSeekSearchLlmRequest ``` -Source: [`packages/web/web-search-deepseek/src/provider.ts:89`](../packages/web/web-search-deepseek/src/provider.ts) +Source: [`packages/web/web-search-deepseek/src/provider.ts:90`](../packages/web/web-search-deepseek/src/provider.ts) ### `working-directory/*` @@ -2018,7 +2018,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -Sources: [`packages/llm/llm/src/types.ts:440`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:521`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -3418,7 +3418,7 @@ Sources: [`packages/subagent/subagent/src/descriptor.ts:72`](../packages/subagen SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -4564,7 +4564,7 @@ Sources: [`packages/llm/llm/src/types.ts:75`](../packages/llm/llm/src/types.ts) SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -Sources: [`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:555`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4878,7 +4878,7 @@ Sources: [`packages/skill/skill/src/index.ts:146`](../packages/skill/skill/src/i SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -Sources: [`packages/llm/llm/src/types.ts:496`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:577`](../packages/llm/llm/src/types.ts) One of: @@ -5135,7 +5135,7 @@ One of: SHA-256: `4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c` -Sources: [`packages/llm/llm/src/types.ts:69`](../packages/llm/llm/src/types.ts) · [`packages/web/web-search-deepseek/src/provider.ts:66`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/llm/llm/src/types.ts:69`](../packages/llm/llm/src/types.ts) · [`packages/web/web-search-deepseek/src/provider.ts:67`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -5307,7 +5307,7 @@ Sources: [`packages/llm/llm/src/message.ts:173`](../packages/llm/llm/src/message SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -Sources: [`packages/llm/llm/src/types.ts:517`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:598`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7961,7 +7961,7 @@ Sources: [`packages/session/working-directory/src/index.ts:48`](../packages/sess SHA-256: `9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:61`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:62`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -8085,7 +8085,7 @@ Sources: [`packages/core/session/src/types.ts:303`](../packages/core/session/src SHA-256: `9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:64`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:65`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -8316,7 +8316,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -Sources: [`packages/llm/llm/src/types.ts:501`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8330,7 +8330,7 @@ Sources: [`packages/llm/llm/src/types.ts:501`](../packages/llm/llm/src/types.ts) SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -Sources: [`packages/llm/llm/src/types.ts:497`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:578`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8488,7 +8488,7 @@ SHA-256: `510826cf4e1f9220d75c1efd90b349dd9a77fc5ba15d19e16f87e85a48db5f99` SHA-256: `37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:82`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:83`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| @@ -8548,7 +8548,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -Sources: [`packages/llm/llm/src/types.ts:503`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8754,7 +8754,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:28`](../packages/llm/llm/src SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -Sources: [`packages/llm/llm/src/types.ts:499`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:580`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9090,7 +9090,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:21`](../packages/llm/llm/src SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -Sources: [`packages/llm/llm/src/types.ts:498`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:579`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9138,7 +9138,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:35`](../packages/llm/llm/src SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -Sources: [`packages/llm/llm/src/types.ts:500`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:581`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9316,7 +9316,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -Sources: [`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:583`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9363,7 +9363,7 @@ SHA-256: `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` SHA-256: `2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3` -Sources: [`packages/web/web-search-deepseek/src/provider.ts:71`](../packages/web/web-search-deepseek/src/provider.ts) +Sources: [`packages/web/web-search-deepseek/src/provider.ts:72`](../packages/web/web-search-deepseek/src/provider.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 5047ebc659..7604079d8d 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -1315,7 +1315,7 @@ export type SessionEvent = { 'web/deepseek-search-llm-request': DeepSeekSearchLlmRequest ``` -来源:[`packages/web/web-search-deepseek/src/provider.ts:89`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:90`](../packages/web/web-search-deepseek/src/provider.ts) ### `working-directory/*` @@ -2020,7 +2020,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -来源:[`packages/llm/llm/src/types.ts:440`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:521`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -3420,7 +3420,7 @@ SHA-256: `6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f` SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` -来源:[`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4566,7 +4566,7 @@ SHA-256: `814d9434e1ddf9078612b3b34322f26e9363b469213335007f7e9ba7fee9464e` SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -来源:[`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:555`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4880,7 +4880,7 @@ SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db` SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -来源:[`packages/llm/llm/src/types.ts:496`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:577`](../packages/llm/llm/src/types.ts) 以下类型之一: @@ -5137,7 +5137,7 @@ SHA-256: `b2d2a01e51341a3bfec809198952c8c830a7899f4cb6ecd3c1dc0b5d9a2af943` SHA-256: `4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c` -来源:[`packages/llm/llm/src/types.ts:69`](../packages/llm/llm/src/types.ts) · [`packages/web/web-search-deepseek/src/provider.ts:66`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/llm/llm/src/types.ts:69`](../packages/llm/llm/src/types.ts) · [`packages/web/web-search-deepseek/src/provider.ts:67`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5309,7 +5309,7 @@ SHA-256: `4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731` SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -来源:[`packages/llm/llm/src/types.ts:517`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:598`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7963,7 +7963,7 @@ SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5` SHA-256: `9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee` -来源:[`packages/web/web-search-deepseek/src/provider.ts:61`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:62`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8087,7 +8087,7 @@ SHA-256: `e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654` SHA-256: `9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5` -来源:[`packages/web/web-search-deepseek/src/provider.ts:64`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:65`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8318,7 +8318,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -来源:[`packages/llm/llm/src/types.ts:501`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8332,7 +8332,7 @@ SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -来源:[`packages/llm/llm/src/types.ts:497`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:578`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8490,7 +8490,7 @@ SHA-256: `510826cf4e1f9220d75c1efd90b349dd9a77fc5ba15d19e16f87e85a48db5f99` SHA-256: `37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1` -来源:[`packages/web/web-search-deepseek/src/provider.ts:82`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:83`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8550,7 +8550,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -来源:[`packages/llm/llm/src/types.ts:503`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8756,7 +8756,7 @@ SHA-256: `71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd` SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -来源:[`packages/llm/llm/src/types.ts:499`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:580`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9092,7 +9092,7 @@ SHA-256: `e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33` SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -来源:[`packages/llm/llm/src/types.ts:498`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:579`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9140,7 +9140,7 @@ SHA-256: `3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6` SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -来源:[`packages/llm/llm/src/types.ts:500`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:581`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9318,7 +9318,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -来源:[`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:583`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9365,7 +9365,7 @@ SHA-256: `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` SHA-256: `2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3` -来源:[`packages/web/web-search-deepseek/src/provider.ts:71`](../packages/web/web-search-deepseek/src/provider.ts) +来源:[`packages/web/web-search-deepseek/src/provider.ts:72`](../packages/web/web-search-deepseek/src/provider.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index a2832eb98c..7594740854 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -88,7 +88,7 @@ {"digest":"0a8a062bc9c3c0d97fd97742262f2ea53dd32297f834e81114870d38ac3dc6da","names":[],"sources":[]}, {"digest":"0a92c5bdfa06c2e2615b777728f3aa95f408d43b9012e7b754568311251db623","names":[],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:29"]}, {"digest":"0aa62ab51b36c0e64b134bd03ba8725d758744180a1a447da49beaad194f219f","names":[],"sources":[]}, - {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:474"]}, + {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:555"]}, {"digest":"0af3ecfb8c60d416fc40a7cc4fb2c4851a8e46608b2b38ab9e510670c971aa1f","names":[],"sources":[]}, {"digest":"0b6d718c693fdf7f06dcccb0bcbbabe78cc63514eafc62d6b2a3899735279d6f","names":["packages/goal/goal/src/types.ts#GoalRef"],"sources":["packages/goal/goal/src/types.ts:20"]}, {"digest":"0b9b8facbe2c19773b3fb0ecc824ccbcc603d41b8f18069faa3807d449572fce","names":[],"sources":[]}, @@ -180,11 +180,11 @@ {"digest":"297fbd8067d7815adae02b89790ec6ff5fb7c2cb0d0eb026e1746c24ec857761","names":[],"sources":[]}, {"digest":"2aad1179f957631477b582e57cd8f538cb82618fc3fb816bde1171154235b065","names":[],"sources":[]}, {"digest":"2ab12a0e345658f9342816d773fe610f049982bcad82631f43b9205abe43e5ee","names":[],"sources":[]}, - {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:499"]}, + {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:580"]}, {"digest":"2aed07493b1c65b6d00de5586da1e743cf501684b9ad43a1765fb4007d4ea456","names":[],"sources":[]}, {"digest":"2c4c21f19f426a58f2dac914e34313aa43f8408972de857a486d1f086d5adb6c","names":[],"sources":[]}, {"digest":"2c64d4bc7264fd3f8bed47e96ab8a593bce05a1e4e1c436dcd244a3b7e0c2a9d","names":[],"sources":[]}, - {"digest":"2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:71"]}, + {"digest":"2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:72"]}, {"digest":"2da725e554cd89301d829ed9dc45a572c3cd1b93b5e91d0d71f007976d8a0863","names":[],"sources":[]}, {"digest":"2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f","names":["packages/schedule/schedule/src/types.ts#ScheduleChange"],"sources":["packages/schedule/schedule/src/types.ts:232"]}, {"digest":"2e4debca12f2c449f96dc6574f3fbf2fb346193443114a241d01a236362ec48c","names":[],"sources":[]}, @@ -208,7 +208,7 @@ {"digest":"374fdd68aee5ff844e378c0cbdd961d247a0f22e4ade0bb03d800cd2a46a2b8b","names":[],"sources":["packages/llm/llm-retry/src/types.ts:30"]}, {"digest":"378f90f9f6022a0991928a1eaf7991094ea1920fe89a9248358a1da106e1a970","names":[],"sources":[]}, {"digest":"37cbc9cf06d494cfe5c67f078af1605eacb8e4c2c853e9e26455b73de0ee7ccf","names":[],"sources":[]}, - {"digest":"37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:82"]}, + {"digest":"37ff65426bcf130f045d3a59ef2a4648eb170cd30280cbd024108a2e9b4401d1","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:83"]}, {"digest":"383cf73ae4748e5beb281ae74857ba1ffb92ae01075b9fbf51af78b666007a8f","names":[],"sources":[]}, {"digest":"3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:35"]}, {"digest":"390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackRating"],"sources":["packages/feedback/message-feedback/src/types.ts:17"]}, @@ -220,7 +220,7 @@ {"digest":"3bca25b2baa6b22be9b577621a7603497f40870ed88a8dac4383d37dc2bb6e18","names":[],"sources":[]}, {"digest":"3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f","names":["packages/core/session/src/types.ts#OptionalSessionSeq"],"sources":["packages/core/session/src/types.ts:66"]}, {"digest":"3bdb8dc6989655b0d4ec361edafb8e2629bc263e1ea591819414fdafc1a413b3","names":[],"sources":[]}, - {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:497"]}, + {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:578"]}, {"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]}, {"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]}, {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, @@ -245,7 +245,7 @@ {"digest":"45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448","names":[],"sources":["packages/interaction/user-approval/src/types.ts:44"]}, {"digest":"477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028","names":[],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:25"]}, {"digest":"47e5d84f1a93450a78c7f3954b43990d0f629af7c034a56313e5deb63e772c1b","names":[],"sources":[]}, - {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:496"]}, + {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:577"]}, {"digest":"487b65c37bfedb8b72088c4107a0a90a6249701f6b26745f6d98f9b8a22b07c7","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:44"]}, {"digest":"48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3","names":[],"sources":[]}, {"digest":"48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb","names":[],"sources":[]}, @@ -263,7 +263,7 @@ {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, - {"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:69","packages/web/web-search-deepseek/src/provider.ts:66"]}, + {"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:69","packages/web/web-search-deepseek/src/provider.ts:67"]}, {"digest":"4edec1b770e8ec4ce1220bf42edc5ac46713a1b48d4caa778dcfc98bad1f28a3","names":[],"sources":[]}, {"digest":"4f507598cf476214aa7646ce7841a7064a9dcb05d0a1eaaefaf79c2b738f160f","names":[],"sources":[]}, {"digest":"4f91f187baeabef5c7950c4780d31bbe39f3345dff591a6cf26ac7e135ac1cf4","names":[],"sources":["packages/context/session-reference/src/types.ts:18"]}, @@ -323,7 +323,7 @@ {"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]}, {"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:35"]}, {"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:35"]}, - {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:517"]}, + {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:598"]}, {"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:146"]}, {"digest":"67d5f73ceae82f5265258142ad6cf172de2c1fef93ba551b7f0454e0a93bffe0","names":["packages/llm/llm/src/call-config.ts#LlmCallConfig"],"sources":["packages/llm/llm/src/call-config.ts:31"]}, {"digest":"68141cbe3994a5ffcd064c07c75996538437fd9dbf77ce8a2927e89ec577fabe","names":[],"sources":[]}, @@ -411,7 +411,7 @@ {"digest":"871bfd6f7bb91061246768d3377f3fd58d6b8ea7c31f44c714ae7ab215650d62","names":[],"sources":[]}, {"digest":"87b1a33564b9a4d63b00988a524c12259243953aebb9c9a05127d87b27464df9","names":[],"sources":[]}, {"digest":"88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa","names":[],"sources":[]}, - {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:500"]}, + {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:581"]}, {"digest":"8a046b52331959aa3394680d6acbe09b8a5447c6b61375f263445bfcef19b7f1","names":[],"sources":[]}, {"digest":"8a54d228b1b7d8453e4304d32723d489f28b4b33b221f335342146926ad94fc6","names":[],"sources":[]}, {"digest":"8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0","names":[],"sources":[]}, @@ -440,7 +440,7 @@ {"digest":"93cbbc5a7fd0b1aa1ff1b9a6bb5ec52b073f48e5a5200365c45c0cd54059e1b9","names":[],"sources":["packages/interaction/user-approval/src/types.ts:55"]}, {"digest":"93d38436347f67c9022aacbc4472e283d722bcab8eb73fc376aaf7b6a6b9fb35","names":[],"sources":[]}, {"digest":"94c56aeb1564ad735eb773d88636b40761d063efa1610f1308004d32923f5378","names":[],"sources":[]}, - {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:498"]}, + {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:579"]}, {"digest":"95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd","names":[],"sources":[]}, {"digest":"95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60","names":[],"sources":[]}, {"digest":"9645cf93769a6dfb227bd400bd6cb9fa7bab9140f4a851e4ae92514ade6e3114","names":[],"sources":[]}, @@ -452,13 +452,13 @@ {"digest":"998f22585a5d73ec005365e203f07fc3b3a029e82323fdda3fd7f13b0a9639d0","names":[],"sources":[]}, {"digest":"99e7e7d7fed55ae6a3a648b35192f16ab1248ddcb0179a0e275128ac1487d7c7","names":[],"sources":[]}, {"digest":"99f0e98184709ad10f27bfdeaafb4457d9d2b413f402331764798cdb7d3cbe4d","names":[],"sources":[]}, - {"digest":"9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:64"]}, + {"digest":"9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:65"]}, {"digest":"9a410ddf56792b2b7cd4a224a2e54dc4dee30a8e8e6b1c2b9a1d19992b217adc","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowAgentStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:20"]}, {"digest":"9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7","names":["packages/core/session/src/types.ts#EpochHeader"],"sources":["packages/core/session/src/types.ts:246"]}, {"digest":"9ac52f0f84fec2eb9f71c2937e497d759db5ca0da4836d93a679d113684141f2","names":[],"sources":[]}, {"digest":"9acbe713f3f641921dd3333b240aa72e176d795327c24e8d9db9b68b16771b49","names":[],"sources":[]}, {"digest":"9b4fd974c124c83743efe030ba4e1250e087505f3f74588716a521fb8d453267","names":[],"sources":[]}, - {"digest":"9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:61"]}, + {"digest":"9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:62"]}, {"digest":"9d80129e13edfb6feb03ed327e6085c6ef60b97ad074244b2f5fd4667424a6a4","names":[],"sources":[]}, {"digest":"9e07693fd7cd9babe0688c22c986e4d519ae1c0e40eeea13b2dc583bed2abc86","names":[],"sources":[]}, {"digest":"9e2c06d8653585b33d72d5c1a80da79c8a24a88c284409bca15cc0f0ead5ebfb","names":[],"sources":[]}, @@ -474,7 +474,7 @@ {"digest":"a15a19ef63cf5d1b711db1d249821dab0cedcd3a9ad09137b47352c93841fd20","names":[],"sources":[]}, {"digest":"a16e567c8cd2c55cf1e911aed3c200c4e1f6febb1459ff2a9e7adf159afb68cb","names":[],"sources":[]}, {"digest":"a2066bd52f61218ba15b758def2641cc6a8bd3d4a594a488ee4c65be356d7e39","names":[],"sources":[]}, - {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:503"]}, + {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:584"]}, {"digest":"a2be0f0cb59f0d4a06557d45847d1938aced238baa77a6da416e590b8b958553","names":[],"sources":[]}, {"digest":"a3a259a1aa5401af786ce08c4a8419681d3000d73467991b5fc563389bc4ebd2","names":[],"sources":[]}, {"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]}, @@ -502,7 +502,7 @@ {"digest":"aae343bc3d663c83f2e8b5e1c7eea5d509dc7a5361bc8bd8b5ac3bb8d3b1ed56","names":[],"sources":[]}, {"digest":"ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7","names":[],"sources":["packages/core/session/src/types.ts:220","packages/llm/llm/src/types.ts:166"]}, {"digest":"aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba","names":[],"sources":[]}, - {"digest":"abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c","names":["packages/web/web-search-deepseek/src/provider.ts#DeepSeekSearchLlmRequest"],"sources":["packages/web/web-search-deepseek/src/provider.ts:55"]}, + {"digest":"abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c","names":["packages/web/web-search-deepseek/src/provider.ts#DeepSeekSearchLlmRequest"],"sources":["packages/web/web-search-deepseek/src/provider.ts:56"]}, {"digest":"ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585","names":[],"sources":["packages/core/session/src/types.ts:398"]}, {"digest":"ad22a5ca5bbaab2e1440779cd3648e85ddfc6f73b5207394eda699555cf31430","names":[],"sources":[]}, {"digest":"ad3b56aa2fc1ad4250e7399295d34a8eae592e1907e85852e2291b2e498a30bc","names":[],"sources":[]}, @@ -596,7 +596,7 @@ {"digest":"d0fbb0ca1bbba059830826f33f801da1aced35a2504376d61e020bdfec8d50c0","names":[],"sources":[]}, {"digest":"d28765f87d6b6ab408e0b2f3e7e297791b004b806d8e302c49903ebae815feb2","names":[],"sources":[]}, {"digest":"d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41","names":[],"sources":[]}, - {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:501"]}, + {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:582"]}, {"digest":"d4c799e3d51cae1040362ba4968efc484739e14416c9c1df20c2f108b4ef2eb5","names":[],"sources":[]}, {"digest":"d4e4d575abeb4b72d616dc65c17ac0eaa943cc135609395044c38d5afcb10e31","names":[],"sources":[]}, {"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9","names":[],"sources":[]}, @@ -670,11 +670,11 @@ {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:238"]}, {"digest":"f1996af2602e6f62b5ab179ca5c4af00d8753938b74cc6ef102de09e99e74a7e","names":[],"sources":[]}, {"digest":"f19bee84bf3d20904553cdcd57465232bc1c2a194f54c4d195292ba0487223a6","names":["packages/attachment/attachment/src/types.ts#FileAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:39"]}, - {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:502"]}, + {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:583"]}, {"digest":"f230c0b583e23b25ee0a61dbe4c05e95c1e2ae44b27939501eb9e03696f0c278","names":[],"sources":[]}, {"digest":"f29d63336e8266d80dd7baeab219436db86341304f6be1cd0edb36f5134c4a47","names":[],"sources":[]}, {"digest":"f2da0f27c1e6add59982c37b15e4a4912c5b33466859cce3b13d503600e24aef","names":["packages/llm/llm/src/types.ts#FileBlock"],"sources":["packages/llm/llm/src/types.ts:105"]}, - {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:440"]}, + {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:521"]}, {"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]}, {"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]}, {"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]}, diff --git a/docs/subsystems/README.i18n.yaml b/docs/subsystems/README.i18n.yaml index 6501690aa5..213de39754 100644 --- a/docs/subsystems/README.i18n.yaml +++ b/docs/subsystems/README.i18n.yaml @@ -3,5 +3,5 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/README.md /subsystems: - en: 1a570deda3572868 - zh: 4d256f68b7e39701 + en: 8e833255afdc9a87 + zh: 89c2af912ed35a49 diff --git a/docs/subsystems/README.md b/docs/subsystems/README.md index bea5c3f895..77dad38082 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -24,6 +24,7 @@ One page per subsystem of the DeepSeek Harness: what it is, the data structures | [persistence.md](persistence.md) | the durability seam: `SessionPersistence`, the JSONL provider, `session/flush`, crash recovery, `SessionHeader` | | [settings.md](settings.md) | the user-settings seam: `SettingsNamespace` registration, layered resolution (defaults → composition `base` → user document), owner scopes, hot commits | | [credentials.md](credentials.md) | the credential seam: `CredentialRef` references (never values) in configuration, per-operation resolution, UI-safe `CredentialInfo`, provider source layers | +| [account.md](account.md) | the DeepSeek account: browser sign-in state, the stored grant, Host-only request credentials for the account model route and the web providers, and the Platform session projection | | [session-query.md](session-query.md) | logical records, bounded exact-event reads, relationship traces, semantic filters/documents, and full-text result pages | | [feedback.md](feedback.md) | lifecycle-bound per-message feedback records, optimistic versions, sidecar persistence, and the Host Remote contract | | [session-title.md](session-title.md) | durable title snapshots, cited source-message seqs, and the asynchronous provider contract | diff --git a/docs/subsystems/README.zh.md b/docs/subsystems/README.zh.md index 4c714de6a0..db3ba392a0 100644 --- a/docs/subsystems/README.zh.md +++ b/docs/subsystems/README.zh.md @@ -24,6 +24,7 @@ | [persistence.md](persistence.zh.md) | 持久性 seam:`SessionPersistence`、JSONL 提供方、`session/flush`、崩溃恢复、`SessionHeader` | | [settings.md](settings.zh.md) | 用户设置 seam:`SettingsNamespace` 注册、分层解析(默认值 → 组合 `base` → 用户文档)、owner scope、热提交 | | [credentials.md](credentials.zh.md) | 凭据 seam:配置中的 `CredentialRef` 引用(绝不含值)、按操作解析、对 UI 安全的 `CredentialInfo`、提供方来源层 | +| [account.md](account.zh.md) | DeepSeek 账号:浏览器登录状态、已存授权、供账号模型路由与 Web 提供方使用的仅限 Host 的请求凭据,以及 Platform 会话投影 | | [session-query.md](session-query.zh.md) | 逻辑记录、有界精确事件读取、关系追踪、语义筛选器/文档与全文检索结果页 | | [feedback.md](feedback.zh.md) | 绑定生命周期的逐消息反馈记录、乐观版本、伴随记录持久化与 Host Remote 约定 | | [session-title.md](session-title.zh.md) | 持久标题快照、被引用的来源消息 seq 与异步提供方约定 | diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml new file mode 100644 index 0000000000..90e4efdb1c --- /dev/null +++ b/docs/subsystems/account.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for account.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/subsystems/account.md +/deepseek-account: + en: 2302e2999588bac3 + zh: 5e0ac058b50036dc +/deepseek-account/request-credentials: + en: 76f2eb1df1948c8a + zh: 70f698243f8e3ae8 +/deepseek-account/embedded-platform-credentials: + en: 9a651d70acbe83a6 + zh: 4624b0299f5fdd8e +/deepseek-account/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit: + en: b2c8c533124a121c + zh: c2a5c227b5a01146 diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md new file mode 100644 index 0000000000..0706d14f80 --- /dev/null +++ b/docs/subsystems/account.md @@ -0,0 +1,234 @@ +# DeepSeek Account + +English | [中文](account.zh.md) + +The account service of [dsh-deepseek-account](../../packages/account/deepseek-account) signs the user in through the system browser, stores the resulting grant as a credential record of the [credential seam](credentials.md), and releases per-request account credentials to Host consumers. Consumers name the destination of one request and receive the headers that request carries; they never read the stored token, choose its header, or decide which origin may receive it. Clients observe account state through the `account` Remote namespace, which carries no credential. + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + +## Request credentials + +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `resolveToken(url)` returns the bare token under the same policy for consumers that compose their own request, and `rejectToken(token)` is the invalidation `reject()` performs. + +Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`. + +## Embedded Platform credentials + +PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account Remote API, AccountView, and AccountDetails. + +AccountDetails.balance projects recharge wallets in value and promotional wallets in bonusWallets, with independent currency and decimal balance strings. Failed queries contain no wallet arrays. + +Notification queries return an AccountNotificationBatch with the server's nextPollAfterSeconds and its notifications in server order. Each AccountNotification carries an opaque id, createdAt, a nullable displayUntil, localized title and body, ordered actions, and optional JSON data, never credentials. getNotificationContent reads one notification by id, including consumed ones, and reportNotificationEvent reports displayed, cta_clicked, or dismissed for it. Notification operations use the initiating UI language through x-client-locale, without a language query parameter. + + + + + +## Cordis API + +Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + + +### `ctx.deepseekAccount` — `DeepSeekAccount` + +Account login, credentials, and client-safe Remote operations. + +```ts cordis-catalog +/** + * Read stored-account presence and the latest login attempt. + * @returns a snapshot without credentials or PKCE secrets. + */ +@Remote async getState(): Promise + +/** + * Query Platform profile independently of wallet balances. + * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch + * consumers, so they re-read getPlatformSession; repeated IDs stay silent. + * @param client - identity of the requesting UI for this call. + * @returns profile outcome, or null if signed out or the grant changed during the query. + */ +@Remote async getProfile(client: AccountClientMetadata): Promise + +/** + * Query Platform recharge and bonus wallet balances independently of profile data. + * @param client - identity of the requesting UI for this call. + * @returns balance outcome, or null if signed out or the grant changed during the query. + */ +@Remote getBalance(client: AccountClientMetadata): Promise + +/** + * Query unconsumed account notifications in server order without reading profile data. + * @param client - identity of the requesting UI for this call; its language selects the server-authored message. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. + */ +@Remote async getNotifications(client: AccountClientMetadata): Promise + +/** + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. + */ +@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise + +/** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ +@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise + +/** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ +async rejectToken(token: string): Promise + +/** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ +async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + +/** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ +async getPlatformSession(): Promise + +/** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ +async resolveToken(url: string): Promise + +/** + * Release the account credential for one request to `url` as the request + * carries it, together with its invalidation. Host-only. + * @param url - actual request destination or API base URL. + * @returns the request credential, or undefined for other origins or a signed-out account. + */ +async resolveRequestCredential(url: string): Promise + +/** + * Join an active attempt or start browser authorization. + * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. + * @param callbackOrigin - browser-accessible loopback HTTP origin, including any SSH local port. + * @param loginSource - initiating UI, used to return from a failed exchange. + * @returns the initial snapshot without waiting for browser approval. + */ +@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise + +/** + * Cancel only the named attempt; committing attempts settle before returning. + * @param attemptId - attempt identity from this Host. + * @returns state after cancellation or an already-started commit. + */ +@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise + +/** + * Remove the local grant while retaining API keys; the provider revokes it in the background. + * @param client - identity of the requesting UI, captured for the background revocation retries. + * @returns the signed-out state after local removal; remote failures never restore the grant. + */ +@Remote signOut(client: AccountClientMetadata): Promise + +/** + * Register a report of running work that signing out would interrupt. The + * plugin billing the account to a model route registers one from within + * `ctx.effect()`; without any report nothing is known to be running. + * @param report - answers whether such work is running now. + * @returns the disposer removing the report. + */ +registerRunningTaskReport(report: () => boolean): () => void + +/** + * Inspect running work before sign-out. + * @returns whether a registered report says a running task uses the account; false without reports. + */ +@Remote hasRunningAccountTasks(): boolean + +/** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ +@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> + +/** + * Subscribe to ordered updates including a complete initial snapshot. + * @param signal - subscription lifetime; ending it never cancels login. + * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. + */ +watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable + +/** + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. + */ +@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable +``` + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + + + +### `deepseek-account/*` events + + + +#### `deepseek-account/model-sign-in-required` — emit + +An account model request requires the user to sign in. + +```ts cordis-catalog +/** An account model request requires the user to sign in. + * @mode emit + */ +'deepseek-account/model-sign-in-required'(): void +``` + +Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/account/deepseek-account/src/types.ts) + + + +#### `deepseek-account/session-expired` — emit + +Server rejection removed the current account credential; this notification is not replayed. + +```ts cordis-catalog +/** Server rejection removed the current account credential; this notification is not replayed. + * @mode emit + */ +'deepseek-account/session-expired'(): void +``` + +Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/account/deepseek-account/src/types.ts) + + + +#### `deepseek-account/signed-out` — emit + +Local grant removal has completed. + +```ts cordis-catalog +/** Local grant removal has completed. + * @mode emit + */ +'deepseek-account/signed-out'(): void +``` + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + + +The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken, resolveRequestCredential, registerRunningTaskReport, and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/account/deepseek-account/README.md). + +`AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries. diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md new file mode 100644 index 0000000000..45d5d03973 --- /dev/null +++ b/docs/subsystems/account.zh.md @@ -0,0 +1,234 @@ +# DeepSeek 账号 + +[English](account.md) | 中文 + +[dsh-deepseek-account](../../packages/account/deepseek-account) 的账号服务通过系统浏览器完成登录,把得到的授权作为[凭据 seam](credentials.zh.md) 的一条凭据记录保存,并向 Host 消费方释放按请求的账号凭据。消费方只说明一次请求的目标地址并取得该请求所携带的请求头;它们既不读取已存 token,也不选择其请求头,也不决定哪个来源可以接收它。客户端通过不携带凭据的 `account` Remote 命名空间观察账号状态。 + +来源:[`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + +## 请求凭据 + +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`resolveToken(url)` 在同一策略下为自行组装请求的消费方返回裸 token,`rejectToken(token)` 则是 `reject()` 执行的失效操作。 + +按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责。 + +## 内嵌 Platform 凭证 + +PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号 Remote API、AccountView 和 AccountDetails 均不包含此快照。 + +AccountDetails.balance 将充值钱包投影为 value、赠送钱包投影为 bonusWallets,分别保留币种和十进制余额字符串。查询失败不包含钱包数组。 + +通知查询返回 AccountNotificationBatch,包含服务端的 nextPollAfterSeconds 和按服务端顺序排列的通知。每条 AccountNotification 携带不透明 id、createdAt、可为 null 的 displayUntil、本地化的 title 与 body、有序 actions 以及可选的 JSON data,绝不包含凭证。getNotificationContent 按 id 读取一条通知,包括已消费的通知;reportNotificationEvent 为其上报 displayed、cta_clicked 或 dismissed。通知操作通过 x-client-locale 传递发起界面的语言,不使用语言查询参数。 + + + + + +## Cordis API + +Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + + +### `ctx.deepseekAccount` — `DeepSeekAccount` + +Account login, credentials, and client-safe Remote operations. + +```ts cordis-catalog +/** + * Read stored-account presence and the latest login attempt. + * @returns a snapshot without credentials or PKCE secrets. + */ +@Remote async getState(): Promise + +/** + * Query Platform profile independently of wallet balances. + * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch + * consumers, so they re-read getPlatformSession; repeated IDs stay silent. + * @param client - identity of the requesting UI for this call. + * @returns profile outcome, or null if signed out or the grant changed during the query. + */ +@Remote async getProfile(client: AccountClientMetadata): Promise + +/** + * Query Platform recharge and bonus wallet balances independently of profile data. + * @param client - identity of the requesting UI for this call. + * @returns balance outcome, or null if signed out or the grant changed during the query. + */ +@Remote getBalance(client: AccountClientMetadata): Promise + +/** + * Query unconsumed account notifications in server order without reading profile data. + * @param client - identity of the requesting UI for this call; its language selects the server-authored message. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. + */ +@Remote async getNotifications(client: AccountClientMetadata): Promise + +/** + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. + */ +@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise + +/** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ +@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise + +/** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ +async rejectToken(token: string): Promise + +/** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ +async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + +/** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ +async getPlatformSession(): Promise + +/** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ +async resolveToken(url: string): Promise + +/** + * Release the account credential for one request to `url` as the request + * carries it, together with its invalidation. Host-only. + * @param url - actual request destination or API base URL. + * @returns the request credential, or undefined for other origins or a signed-out account. + */ +async resolveRequestCredential(url: string): Promise + +/** + * Join an active attempt or start browser authorization. + * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. + * @param callbackOrigin - browser-accessible loopback HTTP origin, including any SSH local port. + * @param loginSource - initiating UI, used to return from a failed exchange. + * @returns the initial snapshot without waiting for browser approval. + */ +@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise + +/** + * Cancel only the named attempt; committing attempts settle before returning. + * @param attemptId - attempt identity from this Host. + * @returns state after cancellation or an already-started commit. + */ +@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise + +/** + * Remove the local grant while retaining API keys; the provider revokes it in the background. + * @param client - identity of the requesting UI, captured for the background revocation retries. + * @returns the signed-out state after local removal; remote failures never restore the grant. + */ +@Remote signOut(client: AccountClientMetadata): Promise + +/** + * Register a report of running work that signing out would interrupt. The + * plugin billing the account to a model route registers one from within + * `ctx.effect()`; without any report nothing is known to be running. + * @param report - answers whether such work is running now. + * @returns the disposer removing the report. + */ +registerRunningTaskReport(report: () => boolean): () => void + +/** + * Inspect running work before sign-out. + * @returns whether a registered report says a running task uses the account; false without reports. + */ +@Remote hasRunningAccountTasks(): boolean + +/** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ +@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> + +/** + * Subscribe to ordered updates including a complete initial snapshot. + * @param signal - subscription lifetime; ending it never cancels login. + * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. + */ +watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable + +/** + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. + */ +@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable +``` + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + + + +### `deepseek-account/*` events + + + +#### `deepseek-account/model-sign-in-required` — emit + +An account model request requires the user to sign in. + +```ts cordis-catalog +/** An account model request requires the user to sign in. + * @mode emit + */ +'deepseek-account/model-sign-in-required'(): void +``` + +Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/account/deepseek-account/src/types.ts) + + + +#### `deepseek-account/session-expired` — emit + +Server rejection removed the current account credential; this notification is not replayed. + +```ts cordis-catalog +/** Server rejection removed the current account credential; this notification is not replayed. + * @mode emit + */ +'deepseek-account/session-expired'(): void +``` + +Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/account/deepseek-account/src/types.ts) + + + +#### `deepseek-account/signed-out` — emit + +Local grant removal has completed. + +```ts cordis-catalog +/** Local grant removal has completed. + * @mode emit + */ +'deepseek-account/signed-out'(): void +``` + +Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) + + +账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken、resolveRequestCredential、registerRunningTaskReport 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/account/deepseek-account/README.zh.md)。 + +`AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。 diff --git a/docs/subsystems/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index 174bd14fc4..a2d00f31df 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/credentials.md /user-credentials: - en: 4589c745baf092c7 - zh: 3a782e6a06825201 + en: cdf4cba4b28c4d9b + zh: ca46998bc56d30e6 /user-credentials/identity: en: 0083032b9d19467d zh: 15d7a7520bac094e @@ -17,9 +17,3 @@ /user-credentials/change-commits: en: 464315a953330eb2 zh: d9815591f3abc2cb -/user-credentials/embedded-platform-credentials: - en: 6f80d44cdec8e05a - zh: 658e5e4958f9baa6 -/user-credentials/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit: - en: 664f0f89d89ac686 - zh: 178263324ad76307 diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 444b2b8a52..31d2fbccfd 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -6,6 +6,8 @@ The credential seam of [dsh-credentials](../../packages/credentials/credentials) Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credentials/credentials/src/index.ts) +The DeepSeek account grant is one such record; its sign-in, request credentials, and Platform session are documented in [account.md](account.md). + ## Identity A reference names one credential as a POSIX-style environment-variable name. The brand prevents callers from mixing credential references with other strings passed between packages or processes; construction validates the shell-identifier syntax. @@ -55,14 +57,6 @@ interface CredentialInfo { `credentials/reference-updated (ref)` fires after a committed change to a provider-managed source — a `set`, an `unset`, or an external edit observed in storage. Ambient process-environment changes are not observable and never emit. Consumers do not need the event (they re-resolve per operation); it exists for configuration surfaces refreshing a "configured" badge. -## Embedded Platform credentials - -PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account Remote API, AccountView, and AccountDetails. - -AccountDetails.balance projects recharge wallets in value and promotional wallets in bonusWallets, with independent currency and decimal balance strings. Failed queries contain no wallet arrays. - -Bonus notification queries return an AccountBonusBatch with the current Platform account id and eligible orders in server order. AccountBonusNotification retains the server message and expiry without projecting credentials. Acknowledgment carries the expected account id and order id; the Host refuses it after an account change. Both notification operations use the initiating UI language through x-client-locale, without a language query parameter. - @@ -262,140 +256,6 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts) - - -### `ctx.deepseekAccount` — `DeepSeekAccount` - -Account login, credentials, and client-safe Remote operations. - -```ts cordis-catalog -/** - * Read stored-account presence and the latest login attempt. - * @returns a snapshot without credentials or PKCE secrets. - */ -@Remote async getState(): Promise - -/** - * Query Platform profile independently of wallet balances. - * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch - * consumers, so they re-read getPlatformSession; repeated IDs stay silent. - * @param client - identity of the requesting UI for this call. - * @returns profile outcome, or null if signed out or the grant changed during the query. - */ -@Remote async getProfile(client: AccountClientMetadata): Promise - -/** - * Query Platform recharge and bonus wallet balances independently of profile data. - * @param client - identity of the requesting UI for this call. - * @returns balance outcome, or null if signed out or the grant changed during the query. - */ -@Remote getBalance(client: AccountClientMetadata): Promise - -/** - * Query unconsumed account notifications in server order without reading profile data. - * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. - */ -@Remote async getNotifications(client: AccountClientMetadata): Promise - -/** - * Query localized content of a notification, including one already consumed. - * @param id - notification whose content is requested. - * @param client - identity of the requesting UI; its language selects the localized content. - * @returns content without changing consumption, or null if signed out or the grant changed. - */ -@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise - -/** - * Report a notification interaction; the backend decides consumption. - * @param id - notification the user interacted with. - * @param event - displayed frame, non-dismiss action click, or explicit dismissal. - * @param client - identity of the requesting UI for this call. - * @returns true once the server accepts the event; false if signed out or credentials changed during the call. - */ -@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise - -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -async rejectToken(token: string): Promise - -/** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ -async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> - -/** - * Read credentials for the configured embedded-page origin, bound to their account environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ -async getPlatformSession(): Promise - -/** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. - */ -async resolveToken(url: string): Promise - -/** - * Join an active attempt or start browser authorization. - * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. - * @param callbackOrigin - browser-accessible loopback HTTP origin, including any SSH local port. - * @param loginSource - initiating UI, used to return from a failed exchange. - * @returns the initial snapshot without waiting for browser approval. - */ -@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise - -/** - * Cancel only the named attempt; committing attempts settle before returning. - * @param attemptId - attempt identity from this Host. - * @returns state after cancellation or an already-started commit. - */ -@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise - -/** - * Remove the local grant while retaining API keys; the provider revokes it in the background. - * @param client - identity of the requesting UI, captured for the background revocation retries. - * @returns the signed-out state after local removal; remote failures never restore the grant. - */ -@Remote signOut(client: AccountClientMetadata): Promise - -/** - * Inspect running work before sign-out. - * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. - */ -@Remote hasRunningAccountTasks(): boolean - -/** - * Subscribe to live credential expiry without replay. - * @param signal - subscription lifetime; provider disposal also ends it. - * @returns expiry notifications emitted during the subscription. - */ -@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> - -/** - * Subscribe to ordered updates including a complete initial snapshot. - * @param signal - subscription lifetime; ending it never cancels login. - * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. - */ -watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable - -/** - * Stream account state without the Host-only identity subscription option. - * @param signal - subscription lifetime. - * @returns initial state, login progress, and credential-change updates. - */ -@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable -``` - -Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) - ### `authorization/*` events @@ -466,57 +326,4 @@ Committed change to a provider-managed credential source: a `set`, an `unset`, o ``` Source: [`packages/credentials/credentials/src/types.ts`](../../packages/credentials/credentials/src/types.ts) - - - -### `deepseek-account/*` events - - - -#### `deepseek-account/model-sign-in-required` — emit - -An account model request requires the user to sign in. - -```ts cordis-catalog -/** An account model request requires the user to sign in. - * @mode emit - */ -'deepseek-account/model-sign-in-required'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/types.ts`](../../packages/credentials/deepseek-account/src/types.ts) - - - -#### `deepseek-account/session-expired` — emit - -Server rejection removed the current account credential; this notification is not replayed. - -```ts cordis-catalog -/** Server rejection removed the current account credential; this notification is not replayed. - * @mode emit - */ -'deepseek-account/session-expired'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/types.ts`](../../packages/credentials/deepseek-account/src/types.ts) - - - -#### `deepseek-account/signed-out` — emit - -Local grant removal has completed. - -```ts cordis-catalog -/** Local grant removal has completed. - * @mode emit - */ -'deepseek-account/signed-out'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) - -The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/credentials/deepseek-account/README.md). - -`AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries. diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index ce9fbdadd5..1aeb209dfb 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -6,6 +6,8 @@ 来源:[`packages/credentials/credentials/src/index.ts`](../../packages/credentials/credentials/src/index.ts) +DeepSeek 账号授权是其中一条记录;其登录、请求凭据和 Platform 会话见 [account.zh.md](account.zh.md)。 + ## 标识 引用以 POSIX 风格环境变量名命名一条凭据。brand 防止调用方将凭据引用与在包或进程之间传递的其他字符串混用;构造时校验 shell 标识符语法。 @@ -55,14 +57,6 @@ interface CredentialInfo { `credentials/reference-updated (ref)` 在提供方管理的来源发生已提交变更后发出——`set`、`unset` 或在存储中观察到的外部编辑。进程环境自身的变化不可观测,永不发出事件。消费方不需要该事件(它们按操作重新解析);它服务于配置界面刷新「已配置」徽标。 -## 内嵌 Platform 凭证 - -PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号 Remote API、AccountView 和 AccountDetails 均不包含此快照。 - -AccountDetails.balance 将充值钱包投影为 value、赠送钱包投影为 bonusWallets,分别保留币种和十进制余额字符串。查询失败不包含钱包数组。 - -赠金通知查询返回 AccountBonusBatch,包含当前 Platform 账号 id 和按服务端顺序排列的可通知订单。AccountBonusNotification 保留服务端消息与到期时间,不投影凭证。确认请求携带预期账号 id 和订单 id;账号变化后 Host 拒绝该请求。两项通知操作都通过 x-client-locale 传递发起界面的语言,不使用语言查询参数。 - @@ -262,140 +256,6 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts) - - -### `ctx.deepseekAccount` — `DeepSeekAccount` - -Account login, credentials, and client-safe Remote operations. - -```ts cordis-catalog -/** - * Read stored-account presence and the latest login attempt. - * @returns a snapshot without credentials or PKCE secrets. - */ -@Remote async getState(): Promise - -/** - * Query Platform profile independently of wallet balances. - * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch - * consumers, so they re-read getPlatformSession; repeated IDs stay silent. - * @param client - identity of the requesting UI for this call. - * @returns profile outcome, or null if signed out or the grant changed during the query. - */ -@Remote async getProfile(client: AccountClientMetadata): Promise - -/** - * Query Platform recharge and bonus wallet balances independently of profile data. - * @param client - identity of the requesting UI for this call. - * @returns balance outcome, or null if signed out or the grant changed during the query. - */ -@Remote getBalance(client: AccountClientMetadata): Promise - -/** - * Query unconsumed account notifications in server order without reading profile data. - * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. - */ -@Remote async getNotifications(client: AccountClientMetadata): Promise - -/** - * Query localized content of a notification, including one already consumed. - * @param id - notification whose content is requested. - * @param client - identity of the requesting UI; its language selects the localized content. - * @returns content without changing consumption, or null if signed out or the grant changed. - */ -@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise - -/** - * Report a notification interaction; the backend decides consumption. - * @param id - notification the user interacted with. - * @param event - displayed frame, non-dismiss action click, or explicit dismissal. - * @param client - identity of the requesting UI for this call. - * @returns true once the server accepts the event; false if signed out or credentials changed during the call. - */ -@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise - -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -async rejectToken(token: string): Promise - -/** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ -async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> - -/** - * Read credentials for the configured embedded-page origin, bound to their account environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ -async getPlatformSession(): Promise - -/** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. - */ -async resolveToken(url: string): Promise - -/** - * Join an active attempt or start browser authorization. - * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. - * @param callbackOrigin - browser-accessible loopback HTTP origin, including any SSH local port. - * @param loginSource - initiating UI, used to return from a failed exchange. - * @returns the initial snapshot without waiting for browser approval. - */ -@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise - -/** - * Cancel only the named attempt; committing attempts settle before returning. - * @param attemptId - attempt identity from this Host. - * @returns state after cancellation or an already-started commit. - */ -@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise - -/** - * Remove the local grant while retaining API keys; the provider revokes it in the background. - * @param client - identity of the requesting UI, captured for the background revocation retries. - * @returns the signed-out state after local removal; remote failures never restore the grant. - */ -@Remote signOut(client: AccountClientMetadata): Promise - -/** - * Inspect running work before sign-out. - * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. - */ -@Remote hasRunningAccountTasks(): boolean - -/** - * Subscribe to live credential expiry without replay. - * @param signal - subscription lifetime; provider disposal also ends it. - * @returns expiry notifications emitted during the subscription. - */ -@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> - -/** - * Subscribe to ordered updates including a complete initial snapshot. - * @param signal - subscription lifetime; ending it never cancels login. - * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. - */ -watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable - -/** - * Stream account state without the Host-only identity subscription option. - * @param signal - subscription lifetime. - * @returns initial state, login progress, and credential-change updates. - */ -@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable -``` - -Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) - ### `authorization/*` events @@ -466,57 +326,4 @@ Committed change to a provider-managed credential source: a `set`, an `unset`, o ``` Source: [`packages/credentials/credentials/src/types.ts`](../../packages/credentials/credentials/src/types.ts) - - - -### `deepseek-account/*` events - - - -#### `deepseek-account/model-sign-in-required` — emit - -An account model request requires the user to sign in. - -```ts cordis-catalog -/** An account model request requires the user to sign in. - * @mode emit - */ -'deepseek-account/model-sign-in-required'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/types.ts`](../../packages/credentials/deepseek-account/src/types.ts) - - - -#### `deepseek-account/session-expired` — emit - -Server rejection removed the current account credential; this notification is not replayed. - -```ts cordis-catalog -/** Server rejection removed the current account credential; this notification is not replayed. - * @mode emit - */ -'deepseek-account/session-expired'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/types.ts`](../../packages/credentials/deepseek-account/src/types.ts) - - - -#### `deepseek-account/signed-out` — emit - -Local grant removal has completed. - -```ts cordis-catalog -/** Local grant removal has completed. - * @mode emit - */ -'deepseek-account/signed-out'(): void -``` - -Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) - -账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/credentials/deepseek-account/README.zh.md)。 - -`AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。 diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index 59d8d46494..6f5c92fbc5 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -36,8 +36,8 @@ en: 58dec2259b0b1c6f zh: fc99fe965acaabf3 /llm-streaming/the-model-request: - en: 834d3d8d6b5871ab - zh: 393889ec6075f622 + en: 1962ba10f5515278 + zh: 9fa56ed8f54136aa /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 @@ -48,5 +48,5 @@ en: 8c140f9c5a799f01 zh: f66b895594247e92 /llm-streaming/service-and-provider-contracts: - en: 8dc79d4cc82824c2 - zh: 3ebabd3a117ad717 + en: 4d210152ca139cb0 + zh: d131e11d95666342 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 565da04ff2..e94dbef6dc 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -525,6 +525,79 @@ interface LlmNativeAuth { } ``` +A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.routeCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. + +```ts type-equiv +/** + * One credential released for one destination. Host-only: it carries the + * secret, so it never crosses a Remote boundary and never enters a log. + */ +interface RouteCredentialGrant { + /** + * Request headers carrying the credential as the route's own protocol + * expects it, such as `x-api-key` for an API key. Consumers speaking that + * protocol send them unchanged. + */ + readonly headers: Readonly> + /** + * The bare credential value, for destinations whose protocol renders it + * differently from {@link headers}, such as `Authorization: Bearer`. + */ + readonly value: string + /** + * Invalidate this exact credential after the destination rejected it with + * HTTP 401 so no later request resends it. Absent for kinds without + * invalidation. The owner contains storage failures: the caller reports the + * destination's rejection, never a failure of this call. + * @returns settlement after the invalidation attempt. + */ + reject?(): Promise +} +``` + +```ts type-equiv +/** + * The credential one registered provider route currently sends, answered by + * the route's owning adapter so that consumers read no provider configuration + * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * per call from one configuration generation; a caller keeps it for one + * operation only. + */ +interface RouteCredential { + /** Kind of credential the route sends. */ + readonly kind: LlmCredentialKind + /** + * The route's current request base URL as its configuration resolves it, + * environment fallbacks included: the destination this credential is meant + * for. Consumers derive sibling endpoints of the same deployment from it. + */ + readonly baseURL: string + /** + * Credential reference the route resolves, for diagnostics that tell the user + * where to configure the credential; absent for kinds without a stored + * reference, such as sign-in grants. + */ + readonly reference?: string + /** + * Whether {@link resolve} would release a credential for `endpoint`, checked + * without reading the credential's value, validating it, or contacting the + * destination. Store failures reject. + * @param endpoint - absolute URL the credential would be sent to. + * @returns whether a credential is configured for that destination. + */ + configured(endpoint: string): Promise + /** + * Release the credential for `endpoint`, or `undefined` when none is + * configured or the destination may not receive it. The caller chooses the + * failure it reports for `undefined`. Store and format failures reject. + * @param endpoint - absolute URL the credential will be sent to. + * @param signal - cancellation for the lookup. + * @returns the released credential, or `undefined`. + */ + resolve(endpoint: string, signal?: AbortSignal): Promise +} +``` + A catalog entry may carry a provider-authored `badge` that selectors show beside the model name. It is display data: `resolveModelInfo` omits it, and no model request carries it. ```ts type-equiv @@ -868,6 +941,8 @@ The [wire reference](../deepseek-llm-api-wire-extensions.md) defines the exact r `LlmAdapter` is the provider contract: subclass, implement `stream()`, and register one adapter instance with `ctx.llm.registerAdapter(providers, adapter)`. `GenerateOptions.provider` selects the registered adapter; `GenerateOptions.model` is passed to that adapter and need not be registered at lifecycle start. Duplicate provider routes fail atomically. Optional `providerRetryPolicy()` is captured per route with normal defaults, while `providerInfo()` and asynchronous `listModels()` feed `LlmRuntime.listProviders()` / `listModels()` with detached selector metadata. That catalog is advisory rather than a request whitelist: the adapter remains authoritative and may accept unlisted model ids. One asynchronous `resolveModel()` query returns exact model identity plus optional correctness-sensitive context capacity, an adapter-configured `defaultMaxTokens`, and ordered model-owned reasoning ids with an optional deployment default; absent fields mean unavailable metadata or provider-owned behavior, not invalid catalog membership. The resolver receives optional cancellation and must settle promptly after abort. `LlmRuntime.resolveModelInfo()` validates and detaches the aggregate. At the final adapter boundary, `resolveCallConfig()` materializes the output default only when `maxTokens` is absent and validates and materializes reasoning, so direct calls cannot bypass either configured behavior; direct dispatch captures one registration before awaiting that resolution. The agent loop instead uses `prepareCall()` to keep the same registration across model resolution, durable header logging, and dispatch, retain detached context metadata from that exact lookup, and report which config fields the adapter defaulted. Adapter lookup happens at the terminal continuation of the `llm/stream` waterfall, so a listener may short-circuit the call or route a mutable one-shot request before lookup. AgentLoop observes a request attempt once the outer waterfall returns a stream handle; that limited boundary does not prove a lazy terminal adapter was constructed or began provider I/O. The `block-start` / `block-end` `index` correlation and the assembler together mean an adapter only has to emit well-formed chunks — block reassembly is not each adapter's problem. [architecture.md](../architecture.md#turn-flow) shows where `ctx.llm.stream()` and the `llm/stream` waterfall sit in one turn. +Optional `routeCredential()` publishes the credential a route currently sends, with the route's base URL, its kind, and an optional credential reference. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter: an unregistered route answers `undefined`, because callers ask about routes a conversation named earlier, and a registered route whose configuration does not resolve propagates the adapter's failure. The DeepSeek web providers read it to call the deployment of the conversation's route with that route's credential, so no consumer reads another plugin's configuration or chooses its header names. + ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ interface PreparedLlmCall { @@ -935,6 +1010,16 @@ declare abstract class LlmAdapter { * @returns the same target used by request serialization, before provider-internal processing. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; + /** + * Describe the credential one owned route currently sends, for consumers that + * call the same deployment outside the model request path, such as web + * providers that share a route's credential and endpoint. The default + * publishes none. Implementations answer from one configuration generation + * per call and may throw when that configuration does not resolve. + * @param _provider - a route passed to `registerAdapter()` for this instance. + * @returns the route's current credential, or `undefined` when the route publishes none. + */ + routeCredential(_provider: string): RouteCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1115,6 +1200,17 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget +/** + * Resolve the credential one registered route currently sends, through its + * owning adapter. An unregistered route answers `undefined` rather than + * throwing because callers ask about routes a conversation named earlier, + * which may no longer be mounted; a registered route whose configuration + * does not resolve propagates the adapter's failure. + * @param provider - provider route whose credential is wanted. + * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + */ +routeCredential(provider: string): RouteCredential | undefined + /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 2f360b8f8f..36bc2aad2d 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -531,6 +531,79 @@ interface LlmNativeAuth { } ``` +路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。 + +```ts type-equiv +/** + * One credential released for one destination. Host-only: it carries the + * secret, so it never crosses a Remote boundary and never enters a log. + */ +interface RouteCredentialGrant { + /** + * Request headers carrying the credential as the route's own protocol + * expects it, such as `x-api-key` for an API key. Consumers speaking that + * protocol send them unchanged. + */ + readonly headers: Readonly> + /** + * The bare credential value, for destinations whose protocol renders it + * differently from {@link headers}, such as `Authorization: Bearer`. + */ + readonly value: string + /** + * Invalidate this exact credential after the destination rejected it with + * HTTP 401 so no later request resends it. Absent for kinds without + * invalidation. The owner contains storage failures: the caller reports the + * destination's rejection, never a failure of this call. + * @returns settlement after the invalidation attempt. + */ + reject?(): Promise +} +``` + +```ts type-equiv +/** + * The credential one registered provider route currently sends, answered by + * the route's owning adapter so that consumers read no provider configuration + * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * per call from one configuration generation; a caller keeps it for one + * operation only. + */ +interface RouteCredential { + /** Kind of credential the route sends. */ + readonly kind: LlmCredentialKind + /** + * The route's current request base URL as its configuration resolves it, + * environment fallbacks included: the destination this credential is meant + * for. Consumers derive sibling endpoints of the same deployment from it. + */ + readonly baseURL: string + /** + * Credential reference the route resolves, for diagnostics that tell the user + * where to configure the credential; absent for kinds without a stored + * reference, such as sign-in grants. + */ + readonly reference?: string + /** + * Whether {@link resolve} would release a credential for `endpoint`, checked + * without reading the credential's value, validating it, or contacting the + * destination. Store failures reject. + * @param endpoint - absolute URL the credential would be sent to. + * @returns whether a credential is configured for that destination. + */ + configured(endpoint: string): Promise + /** + * Release the credential for `endpoint`, or `undefined` when none is + * configured or the destination may not receive it. The caller chooses the + * failure it reports for `undefined`. Store and format failures reject. + * @param endpoint - absolute URL the credential will be sent to. + * @param signal - cancellation for the lookup. + * @returns the released credential, or `undefined`. + */ + resolve(endpoint: string, signal?: AbortSignal): Promise +} +``` + 目录条目可以携带提供方编写的 `badge`,供选择器显示在模型名称旁。它只是展示数据:`resolveModelInfo` 不返回它,模型请求也不携带它。 ```ts type-equiv @@ -874,6 +947,8 @@ interface LlmCallConfigAdapterDefaults { `LlmAdapter` 是提供方约定:创建子类、实现 `stream()`,再用 `ctx.llm.registerAdapter(providers, adapter)` 注册一个适配器实例。`GenerateOptions.provider` 选择已注册适配器;`GenerateOptions.model` 会传给该适配器,无需在生命周期启动时注册。重复提供方路由会原子失败。可选的 `providerRetryPolicy()` 会按路由捕获并填入 normal 默认值,`providerInfo()` 与异步 `listModels()` 方法则为 `LlmRuntime.listProviders()` / `listModels()` 提供分离的 selector 元数据。该目录仅供参考,不是请求白名单:适配器仍是权威,并可接受未列出的模型 id。单次异步 `resolveModel()` 查询返回确切模型身份,以及可选的对正确性敏感的上下文容量、适配器配置的 `defaultMaxTokens`、由模型持有的有序推理强度 ID 和可选的部署默认值;字段缺失表示元数据不可用或保留提供方持有的行为,而不表示目录成员关系无效。解析器会接收可选的取消信号,并且必须在信号中止后迅速完成结算。`LlmRuntime.resolveModelInfo()` 会校验聚合结果并返回分离值。在最终适配器边界,`resolveCallConfig()` 仅在 `maxTokens` 缺失时填入输出默认值,并校验和填入推理强度,因此直接调用也无法绕过任何一项已配置行为;直接分派会在等待解析前捕获一项适配器注册。agent loop 则使用 `prepareCall()`,使模型解析、请求头持久记录和分派全程使用同一项注册,保留来自同一次查询的分离上下文元数据,并报告适配器填入的配置字段。适配器查找发生在 `llm/stream` waterfall 的终端 continuation,因此 listener 可以在查找前短路调用,或路由一个可变的一次性请求。AgentLoop 在外层 waterfall 返回流句柄时观察到一次请求尝试;这个有限边界不能证明惰性终端适配器已构造完成或开始提供方 I/O。`block-start` / `block-end` 的 `index` 关联与 assembler 共同意味着适配器只需 emit 格式正确的分片——块重组不是每个适配器各自的问题。`ctx.llm.stream()` 与 `llm/stream` waterfall 在一个轮次中的位置见 [architecture.md](../architecture.zh.md#turn-flow)。 +可选的 `routeCredential()` 发布路由当前发送的凭据,连同路由的基础地址、凭据种类和可选的凭据引用。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器:未注册的路由回答 `undefined`,因为调用方询问的是会话早先命名的路由;已注册但配置无法解析的路由则传播适配器的失败。DeepSeek Web 提供方据此用会话路由的凭据调用同一部署,因此没有消费方需要读取其他插件的配置或自行选择请求头名称。 + ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ interface PreparedLlmCall { @@ -941,6 +1016,16 @@ declare abstract class LlmAdapter { * @returns the same target used by request serialization, before provider-internal processing. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; + /** + * Describe the credential one owned route currently sends, for consumers that + * call the same deployment outside the model request path, such as web + * providers that share a route's credential and endpoint. The default + * publishes none. Implementations answer from one configuration generation + * per call and may throw when that configuration does not resolve. + * @param _provider - a route passed to `registerAdapter()` for this instance. + * @returns the route's current credential, or `undefined` when the route publishes none. + */ + routeCredential(_provider: string): RouteCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1121,6 +1206,17 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget +/** + * Resolve the credential one registered route currently sends, through its + * owning adapter. An unregistered route answers `undefined` rather than + * throwing because callers ask about routes a conversation named earlier, + * which may no longer be mounted; a registered route whose configuration + * does not resolve propagates the adapter's failure. + * @param provider - provider route whose credential is wanted. + * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + */ +routeCredential(provider: string): RouteCredential | undefined + /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml new file mode 100644 index 0000000000..752379e39f --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md +/: + en: f0cf30e5430471e8 + zh: 2e6e871797dfdd6b +/deepseek-routes-publish-the-credential-web-consumers-reuse: + en: d7412a58aadc57a0 + zh: 82243a8cd8563083 +/deepseek-routes-publish-the-credential-web-consumers-reuse/change: + en: 7a63f24e07fb3d33 + zh: 99c64684a589088e +/deepseek-routes-publish-the-credential-web-consumers-reuse/migration: + en: 64ac045c8d9a1336 + zh: 4712f6eacd85a151 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md new file mode 100644 index 0000000000..2ec50f9a98 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "DeepSeek model routes publish their credential through ctx.llm.routeCredential(); the llm-deepseek credential helpers, the route plugins' config exports, and account Agent inspection are removed." +--- + +# DeepSeek routes publish the credential web consumers reuse + +English | [中文](guide.zh.md) + +## Change + +`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a value-free `configured(endpoint)` check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`. + +`@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional. + +`@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report. + +`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)`; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. + +`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id without a published credential counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. + +## Migration + +1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.routeCredential(provider)`. +2. In custom `DeepSeekAdapter` or `registerDeepSeekProvider` consumers, return `undefined` from `resolveAuth` when no credential exists, add `value` to every `DeepSeekRequestAuth`, supply `missingCredential` for a route-specific failure, and declare `credential` to publish the route's credential. Pass credential headers, not a token, to `createModelListingCache`. +3. Replace imports of the route plugins' config exports with the plugins' own `Config`, and read a route's endpoint from its published credential instead of its resolver. +4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead. +5. Update workspace references to `packages/account/deepseek-account`; the npm package name, Remote namespace, and configuration keys are unchanged. +6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `RouteCredentialGrant`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md new file mode 100644 index 0000000000..187434d603 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己的凭据;移除 llm-deepseek 的凭据辅助函数、路由插件的配置导出和账号服务对 Agent 的检查。" +--- + +# DeepSeek 路由发布 Web 消费方复用的凭据 + +[English](guide.md) | 中文 + +## 变更 + +`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、不读取值的 `configured(endpoint)` 检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。 + +`@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 + +`@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。 + +`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 + +`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 + +## 迁移 + +1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.routeCredential(provider)`。 +2. 在自定义的 `DeepSeekAdapter` 或 `registerDeepSeekProvider` 消费方中,没有凭据时让 `resolveAuth` 返回 `undefined`,为每个 `DeepSeekRequestAuth` 加上 `value`,为路由专属的失败提供 `missingCredential`,并声明 `credential` 以发布路由凭据。向 `createModelListingCache` 传递凭据请求头而不是 token。 +3. 用路由插件自身的 `Config` 替换对其配置导出的导入,并从路由发布的凭据而非其解析函数读取端点。 +4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential`;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。 +5. 把工作区引用更新为 `packages/account/deepseek-account`;npm 包名、Remote 命名空间和配置键均不变。 +6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `RouteCredentialGrant` 的 `resolveAccountCredential`。 diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 686f5672c1..81357d69c5 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -15,8 +15,8 @@ en: ffc55792d6e922e1 zh: 83bd759638857e2d /packages/package-groups: - en: 704e948001e25580 - zh: dcfbb1b483d2a95a + en: 2f76ab75d2b0b872 + zh: 7e6ce5f883d805c9 /packages/release-expectations: en: 236081c1659b25ab zh: 809110adf003802e diff --git a/packages/README.md b/packages/README.md index 431eadfc37..a8c0dbc993 100644 --- a/packages/README.md +++ b/packages/README.md @@ -57,7 +57,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`experimental/`](experimental/README.md) | Capabilities under evaluation; [status and support policy](experimental/README.md#status) | | [`workflow/`](workflow/README.md) | Workflow seam, PTC process engine, and the model-facing `workflow` tool | | [`web/`](web/README.md) | Web capability family: seam, search/fetch providers, model-facing web tools | -| [`document/`](document/README.md) | Shared Host Office rendering, conversion, and recalculation, the Office tools, and Kit engine resolution | +| [`document/`](document/README.md) | Host Office rendering, conversion, and recalculation, the Office tools, and Kit engine resolution | | [`attachment/`](attachment/README.md) | Durable attachment identity, validation, local content-addressed storage | | [`spill/`](spill/README.md) | Spill capability family: storage seam, local impl, tool-result spill policy | | [`todo/`](todo/README.md) | The model-facing `todo_write` tool | @@ -70,7 +70,8 @@ Every package lives in exactly one group; new packages join existing groups, and | [`session/`](session/README.md) | Durable session data plane: persistence seam + backends, projection seam, log-backed titles, session reporting | | [`session-query/`](session-query/README.md) | Session retrieval family: logical corpus, bounded reads, lineage, semantic filtering, SQLite full-text search | | [`settings/`](settings/README.md) | User-settings seam + file-backed provider | -| [`credentials/`](credentials/README.md) | Credential-reference and credential-record seam + env-over-`.env` provider + authorization flows that ask a human | +| [`credentials/`](credentials/README.md) | Credential reference and record seam, env-over-`.env` provider, and authorization flows that ask a human | +| [`account/`](account/README.md) | DeepSeek account sign-in and Host-only request credentials | | [`storage/`](storage/README.md) | Non-session storage hub + backends + domain form | | [`workspace/`](workspace/README.md) | Workspace entity | | [`sdk/`](sdk/README.md) | Out-of-process SDK: JSON-RPC protocol and TypeScript client/server | @@ -80,7 +81,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`host/`](host/README.md) | Web GUI host services, directory picking, application launch, plugin inventory, and product telemetry | | [`client/`](client/README.md) | Web-GUI browser half: shell, wire, object services, slots, `ui-*` plugins | | [`test-support/`](test-support/README.md) | Test infrastructure (testkits, replay, Loader smokes) | -| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups (`Branded`, home/path helpers, timeout, retention, official bundle lists) | +| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups | ----- diff --git a/packages/README.zh.md b/packages/README.zh.md index 5855d9c3fd..fda5527ba1 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -57,7 +57,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`experimental/`](experimental/README.zh.md) | 仍在评估中的能力;[状态与支持策略](experimental/README.zh.md#status) | | [`workflow/`](workflow/README.zh.md) | 工作流 seam、PTC 进程引擎、面向模型的 `workflow` 工具 | | [`web/`](web/README.zh.md) | Web 能力系列:seam、搜索/获取提供方、面向模型的 Web 工具 | -| [`document/`](document/README.zh.md) | 共享宿主 Office 渲染、转换与重算、Office 工具与 Kit 引擎解析 | +| [`document/`](document/README.zh.md) | 宿主 Office 渲染、转换与重算、Office 工具与 Kit 引擎解析 | | [`attachment/`](attachment/README.zh.md) | 持久附件标识、校验、本地内容寻址存储 | | [`spill/`](spill/README.zh.md) | spill 能力系列:存储 seam、本地实现、工具结果 spill 策略 | | [`todo/`](todo/README.zh.md) | 面向模型的 `todo_write` 工具 | @@ -70,7 +70,8 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`session/`](session/README.zh.md) | 持久会话数据平面:持久化 seam + 后端、投影 seam、基于日志的标题、会话上报 | | [`session-query/`](session-query/README.zh.md) | 会话检索系列:逻辑语料库、有界读取、血缘、语义过滤、SQLite 全文搜索 | | [`settings/`](settings/README.zh.md) | 用户设置 seam + 基于文件的提供方 | -| [`credentials/`](credentials/README.zh.md) | 凭据引用与凭据记录 seam + 环境变量优先于 `.env` 的提供方 + 需要向人询问的授权流程 | +| [`credentials/`](credentials/README.zh.md) | 凭据引用与记录 seam、环境变量优先于 `.env` 的提供方,以及需要向人询问的授权流程 | +| [`account/`](account/README.zh.md) | DeepSeek 账号登录与仅限 Host 的请求凭据 | | [`storage/`](storage/README.zh.md) | 非会话存储中枢 + 后端 + 领域形式 | | [`workspace/`](workspace/README.zh.md) | Workspace 实体 | | [`sdk/`](sdk/README.zh.md) | 进程外 SDK:JSON-RPC 协议与 TypeScript 客户端/服务器 | @@ -80,7 +81,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`host/`](host/README.zh.md) | Web GUI 宿主服务、目录选择、应用启动、插件清单和产品遥测 | | [`client/`](client/README.zh.md) | web GUI 浏览器半侧:shell、协议层、对象服务、slot、`ui-*` 插件 | | [`test-support/`](test-support/README.zh.md) | 测试基础设施(testkit、回放、Loader 冒烟测试) | -| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表(`Branded`、home/路径辅助函数、超时、留存、官方组合包列表) | +| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表 | ----- diff --git a/packages/account/README.i18n.yaml b/packages/account/README.i18n.yaml new file mode 100644 index 0000000000..ae0a4268ed --- /dev/null +++ b/packages/account/README.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/account/README.md +/: + en: c603fc9f9990181e + zh: fc045770018269cd +/account-deepseek-account: + en: 15e52f323c5ffdba + zh: e32a4d077fd5ef98 +/account-deepseek-account/summary: + en: b75f72f3404fcd85 + zh: c24435d70528c5a4 +/account-deepseek-account/table-of-contents: + en: 1eb35b015a6c423f + zh: a8a3dceee2c9e943 +/account-deepseek-account/packages: + en: 4f342c1e06b8c9e2 + zh: f36f298ef3bd1be2 +/account-deepseek-account/related-documentation: + en: 6667d1a41ac182d1 + zh: 065a196972782a34 +/account-deepseek-account/dev-note: + en: 5de1d6304e00c58f + zh: 8d8225361cfa29e5 diff --git a/packages/account/README.md b/packages/account/README.md new file mode 100644 index 0000000000..278ac10749 --- /dev/null +++ b/packages/account/README.md @@ -0,0 +1,51 @@ +--- +description: "Package map for the DeepSeek account family: browser sign-in, the stored account grant, and the Host-only request credentials released to the account model route and the DeepSeek web providers." +kind: "package-group" +--- + +# account/ — DeepSeek account + +English | [中文](README.zh.md) + +## Summary + +The `account/` group signs the user in to DeepSeek through the system browser and keeps the account grant in the local credential store that [`credentials/`](../credentials/README.md) owns. Host consumers never read the token: the `deepseek-account` model route and the DeepSeek web providers ask `ctx.deepseekAccount` for the credential of one request destination and receive its request headers, the bare value, and an invalidation for an HTTP 401. Clients receive account state through the `account` Remote namespace without credentials. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +One package provides the account feature; its README covers day-to-day use, and the subsystem reference owns the exhaustive contracts. + +| Package | Role | ctx key | +|---|---|---| +| [`deepseek-account/`](deepseek-account/README.md) | Browser sign-in, the stored grant, Platform profile, balance, and notification reads, and Host-only request credentials for allowed destinations | `ctx.deepseekAccount` | + +----- + + +## Related documentation + +Start with the subsystem reference for the account contracts, then the credential store the grant lives in. + +- [Account subsystem reference](../../docs/subsystems/account.md) — sign-in state, request credentials, the Platform session projection, and the generated Cordis surface. +- [Credentials subsystem reference](../../docs/subsystems/credentials.md) — the credential records the grant is stored in. +- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-deepseek-account) — every accepted field of the account service. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/account/README.zh.md b/packages/account/README.zh.md new file mode 100644 index 0000000000..1bc1a0a936 --- /dev/null +++ b/packages/account/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "DeepSeek 账号能力族的包映射:浏览器登录、已存账号授权,以及向账号模型路由和 DeepSeek Web 提供方释放的仅限 Host 的请求凭据。" +kind: "package-group" +--- + +# account/:DeepSeek 账号 + +[English](README.md) | 中文 + +## 概述 + +`account/` 组通过系统浏览器让用户登录 DeepSeek,并把账号授权保存在 [`credentials/`](../credentials/README.zh.md) 拥有的本地凭据库中。Host 消费方从不读取 token:`deepseek-account` 模型路由和 DeepSeek Web 提供方向 `ctx.deepseekAccount` 索取某个请求目标的凭据,取得其请求头、裸值以及用于 HTTP 401 的失效操作。客户端通过不携带凭据的 `account` Remote 命名空间获得账号状态。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +一个包提供账号功能;它的 README 覆盖日常使用,全部约定以子系统参考为准。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`deepseek-account/`](deepseek-account/README.zh.md) | 浏览器登录、已存授权、Platform 资料、余额与通知读取,以及面向允许目标的仅限 Host 的请求凭据 | `ctx.deepseekAccount` | + +----- + + +## 相关文档 + +先从子系统参考了解账号约定,再看授权所在的凭据库。 + +- [账号子系统参考](../../docs/subsystems/account.zh.md)——登录状态、请求凭据、Platform 会话投影与生成的 Cordis 接口面。 +- [凭据子系统参考](../../docs/subsystems/credentials.zh.md)——保存授权的凭据记录。 +- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 +- [生成配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-deepseek-account)——账号服务的每个受支持字段。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/credentials/deepseek-account/README.i18n.yaml b/packages/account/deepseek-account/README.i18n.yaml similarity index 86% rename from packages/credentials/deepseek-account/README.i18n.yaml rename to packages/account/deepseek-account/README.i18n.yaml index 7c8e7b9d6f..95ce3a191b 100644 --- a/packages/credentials/deepseek-account/README.i18n.yaml +++ b/packages/account/deepseek-account/README.i18n.yaml @@ -1,13 +1,13 @@ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/credentials/deepseek-account/README.md +# pnpm run verify-translation-pairing --write packages/account/deepseek-account/README.md /: en: 9dbb9bc3960a11fe zh: ed58987926489d3e /deepseek-ai-dsh-deepseek-account: - en: 78e86576b7f38038 - zh: 7ec9f58f21ce00bf + en: 06fe55f319bd1b2c + zh: 9559b712e50bbc73 /deepseek-ai-dsh-deepseek-account/summary: en: 28bcca957bf6abf4 zh: 4a3fc8a59f2925bc @@ -15,8 +15,8 @@ en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: a334962d65816a50 - zh: 28f66b089476123a + en: 02b899ac5ad80227 + zh: 0cb4d6984ae6ed62 /deepseek-ai-dsh-deepseek-account/understand-the-implementation: en: 76d2da2dab100ac3 zh: 2c9404f27915daab diff --git a/packages/credentials/deepseek-account/README.md b/packages/account/deepseek-account/README.md similarity index 96% rename from packages/credentials/deepseek-account/README.md rename to packages/account/deepseek-account/README.md index 28e3b20afe..34d87bf729 100644 --- a/packages/credentials/deepseek-account/README.md +++ b/packages/account/deepseek-account/README.md @@ -13,7 +13,7 @@ getPlatformSession exports the stored grant only when its issuer matches platfor `desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. -Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. +Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that performs that removal after an HTTP 401 while containing storage failures; the account model route and the DeepSeek web providers use it instead of composing headers themselves. ## Summary @@ -36,9 +36,9 @@ The service exposes its client-safe operations through the `account` Remote name `DeepSeekAccount` is the concrete service owning login, credentials, and Remote operations. The `/types` entry exposes types without loading the service implementation. `watch` returns complete state tagged as `snapshot` or `credentials-changed`; Host-only `watch(signal, true)` also receives profile-identity changes, while Remote subscriptions omit that option. -The `/client-metadata` entry provides pure Platform header and cookie helpers for Host consumers. The configuration schema is `DeepSeekAccount.Config`; the plugin entry exports no helper functions. Mounting the service installs account-task cancellation. +The `/client-metadata` entry provides pure Platform header and cookie helpers for Host consumers. The configuration schema is `DeepSeekAccount.Config`; the plugin entry exports no helper functions. -The `agents` service is optional. `hasRunningAccountTasks()` returns false when it is absent; when present, it checks running tasks for the account provider. +`hasRunningAccountTasks()` answers through the reports model routes register with `registerRunningTaskReport()` inside `ctx.effect()`; without a report, nothing is known to be running. The `llm-deepseek-account` route registers one and owns cancelling its running Agents after sign-out. The profile projection maps `id_profile.picture` to `avatarUrl`, using null when no picture is configured. diff --git a/packages/credentials/deepseek-account/README.zh.md b/packages/account/deepseek-account/README.zh.md similarity index 96% rename from packages/credentials/deepseek-account/README.zh.md rename to packages/account/deepseek-account/README.zh.md index 628fd2ed61..88b4801909 100644 --- a/packages/credentials/deepseek-account/README.zh.md +++ b/packages/account/deepseek-account/README.zh.md @@ -13,7 +13,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 `desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 -资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。 +资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后执行上述清除并隔离存储失败。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。 ## 概述 @@ -36,9 +36,9 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 `DeepSeekAccount` 是具体服务,拥有登录、凭证和 Remote 操作。`/types` 提供不加载服务实现的类型出口。`watch` 返回完整状态与 `snapshot` 或 `credentials-changed` 类型;仅 Host 的 `watch(signal, true)` 还接收资料身份变化,Remote 订阅不启用该选项。 -`/client-metadata` 为 Host 使用方提供纯函数形式的 Platform 请求头和 Cookie 辅助函数。配置 schema 为 `DeepSeekAccount.Config`;插件入口不导出辅助函数。挂载服务时会安装账号任务取消逻辑。 +`/client-metadata` 为 Host 使用方提供纯函数形式的 Platform 请求头和 Cookie 辅助函数。配置 schema 为 `DeepSeekAccount.Config`;插件入口不导出辅助函数。 -`agents` 服务为可选依赖。未提供时,`hasRunningAccountTasks()` 返回 false;提供时,检查使用账号服务的运行中任务。 +`hasRunningAccountTasks()` 通过模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport()` 注册的报告作答;没有报告时视为没有运行中的工作。`llm-deepseek-account` 路由注册一份报告,并负责在退登后取消其运行中的 Agent。 账号资料投影将 `id_profile.picture` 映射为 `avatarUrl`,没有配置头像时返回 null。 diff --git a/packages/credentials/deepseek-account/locale/de.json b/packages/account/deepseek-account/locale/de.json similarity index 100% rename from packages/credentials/deepseek-account/locale/de.json rename to packages/account/deepseek-account/locale/de.json diff --git a/packages/credentials/deepseek-account/locale/en.json b/packages/account/deepseek-account/locale/en.json similarity index 100% rename from packages/credentials/deepseek-account/locale/en.json rename to packages/account/deepseek-account/locale/en.json diff --git a/packages/credentials/deepseek-account/locale/es.json b/packages/account/deepseek-account/locale/es.json similarity index 100% rename from packages/credentials/deepseek-account/locale/es.json rename to packages/account/deepseek-account/locale/es.json diff --git a/packages/credentials/deepseek-account/locale/fr.json b/packages/account/deepseek-account/locale/fr.json similarity index 100% rename from packages/credentials/deepseek-account/locale/fr.json rename to packages/account/deepseek-account/locale/fr.json diff --git a/packages/credentials/deepseek-account/locale/ja.json b/packages/account/deepseek-account/locale/ja.json similarity index 100% rename from packages/credentials/deepseek-account/locale/ja.json rename to packages/account/deepseek-account/locale/ja.json diff --git a/packages/credentials/deepseek-account/locale/pt.json b/packages/account/deepseek-account/locale/pt.json similarity index 100% rename from packages/credentials/deepseek-account/locale/pt.json rename to packages/account/deepseek-account/locale/pt.json diff --git a/packages/credentials/deepseek-account/locale/ru.json b/packages/account/deepseek-account/locale/ru.json similarity index 100% rename from packages/credentials/deepseek-account/locale/ru.json rename to packages/account/deepseek-account/locale/ru.json diff --git a/packages/credentials/deepseek-account/locale/zh.json b/packages/account/deepseek-account/locale/zh.json similarity index 100% rename from packages/credentials/deepseek-account/locale/zh.json rename to packages/account/deepseek-account/locale/zh.json diff --git a/packages/credentials/deepseek-account/package.json b/packages/account/deepseek-account/package.json similarity index 87% rename from packages/credentials/deepseek-account/package.json rename to packages/account/deepseek-account/package.json index 088b4e8106..15cf18c2de 100644 --- a/packages/credentials/deepseek-account/package.json +++ b/packages/account/deepseek-account/package.json @@ -8,7 +8,7 @@ "repository": { "type": "git", "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/credentials/deepseek-account" + "directory": "packages/account/deepseek-account" }, "type": "module", "main": "lib/index.js", @@ -56,8 +56,6 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", - "@deepseek-ai/dsh-agent": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/dsh-authorization": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", @@ -67,19 +65,12 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", - "@deepseek-ai/dsh-agent": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/dsh-authorization": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, - "peerDependenciesMeta": { - "@deepseek-ai/dsh-agent": { - "optional": true - } - }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", "zod": "4.6.6" diff --git a/packages/credentials/deepseek-account/src/client-metadata.ts b/packages/account/deepseek-account/src/client-metadata.ts similarity index 100% rename from packages/credentials/deepseek-account/src/client-metadata.ts rename to packages/account/deepseek-account/src/client-metadata.ts diff --git a/packages/credentials/deepseek-account/src/details.ts b/packages/account/deepseek-account/src/details.ts similarity index 100% rename from packages/credentials/deepseek-account/src/details.ts rename to packages/account/deepseek-account/src/details.ts diff --git a/packages/credentials/deepseek-account/src/index.ts b/packages/account/deepseek-account/src/index.ts similarity index 95% rename from packages/credentials/deepseek-account/src/index.ts rename to packages/account/deepseek-account/src/index.ts index 8dddec9074..739907057e 100644 --- a/packages/credentials/deepseek-account/src/index.ts +++ b/packages/account/deepseek-account/src/index.ts @@ -8,15 +8,14 @@ import { Context, Service } from '@deepseek-ai/cordis' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import Schema from '@deepseek-ai/schemastery' import { z } from 'zod' -import { installAccountTaskCancellation, isRunningAccountTask } from './account-tasks.ts' import { mergePlatformCookies, platformClientHeaders, platformWireLocale } from './client-metadata.ts' -import { type AccountNotification, type AccountNotificationBatch, type AccountNotificationEvent, type AccountNotificationId, type AccountClientMetadata, type AccountDetails, type AccountUserId, type AccountView, type AccountUpdate, type PlatformSession, type SignInAttemptId, type SignInAttemptView } from './types.ts' +import { type AccountNotification, type AccountNotificationBatch, type AccountNotificationEvent, type AccountNotificationId, type AccountClientMetadata, type AccountDetails, type AccountRequestCredential, type AccountUserId, type AccountView, type AccountUpdate, type PlatformSession, type SignInAttemptId, type SignInAttemptView } from './types.ts' import { credentialKey } from '@deepseek-ai/dsh-credentials' import type { AuthorizationSession } from '@deepseek-ai/dsh-authorization' import { profile, readAccountDetail } from './details.ts' import { readNotificationContent, readNotifications, sendNotificationEvent } from './notifications.ts' import { revokeAccount, type LogoutRetryPolicy } from './logout.ts' -import { AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformOrigin, browserUrl, requestPlatform, initialization, exchange, loginOrigin } from './protocol.ts' +import { ACCOUNT_TOKEN_HEADER, AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformOrigin, browserUrl, requestPlatform, initialization, exchange, loginOrigin } from './protocol.ts' export type * from './types.ts' @@ -122,6 +121,7 @@ export class DeepSeekAccount extends TypertRemoteService { private readonly revocations = new Set>() private attempt: Attempt | undefined private readonly listeners = new Set<(kind: 'snapshot' | 'credentials-changed' | 'identity') => void>() + private readonly runningTaskReports = new Set<() => boolean>() /** * Latest ready profile read and the grant token it was read with. Binding the token keeps a * cached identity from answering for a credential that has since changed. @@ -134,7 +134,6 @@ export class DeepSeekAccount extends TypertRemoteService { /** @param ctx - Host with authorization and credentials services. @param config - deployment options. */ constructor(ctx: Context, config: Config = {}) { super(ctx, 'deepseekAccount', { namespace: 'account' }) - installAccountTaskCancellation(ctx) const resolved = Config(config) this.embeddedPageDist = resolved.embeddedPageDist this.origin = platformOrigin(resolved.platformOrigin, resolved.allowLoopbackHttp, 'platformOrigin') @@ -469,6 +468,25 @@ export class DeepSeekAccount extends TypertRemoteService { return result.data.token } + /** + * Release the account credential for one request to `url` as the request + * carries it, together with its invalidation. Host-only. + * @param url - actual request destination or API base URL. + * @returns the request credential, or undefined for other origins or a signed-out account. + */ + async resolveRequestCredential(url: string): Promise { + const token = await this.resolveToken(url) + if (token === undefined) return undefined + return { + headers: { [ACCOUNT_TOKEN_HEADER]: token }, + value: token, + reject: async () => { + try { await this.rejectToken(token) } + catch (_credentialRemovalFailed) { /* The destination's rejection is the failure to report; the next rejection retries. */ } + }, + } + } + /** * Join an active attempt or start browser authorization. * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. @@ -570,13 +588,26 @@ export class DeepSeekAccount extends TypertRemoteService { return this.removing } + /** + * Register a report of running work that signing out would interrupt. The + * plugin billing the account to a model route registers one from within + * `ctx.effect()`; without any report nothing is known to be running. + * @param report - answers whether such work is running now. + * @returns the disposer removing the report. + */ + registerRunningTaskReport(report: () => boolean): () => void { + this.runningTaskReports.add(report) + return () => { this.runningTaskReports.delete(report) } + } + /** * Inspect running work before sign-out. - * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. + * @returns whether a registered report says a running task uses the account; false without reports. */ @Remote hasRunningAccountTasks(): boolean { - return this.ctx.get('agents')?.list().some(isRunningAccountTask) ?? false + for (const report of this.runningTaskReports) if (report()) return true + return false } /** diff --git a/packages/credentials/deepseek-account/src/logout.ts b/packages/account/deepseek-account/src/logout.ts similarity index 100% rename from packages/credentials/deepseek-account/src/logout.ts rename to packages/account/deepseek-account/src/logout.ts diff --git a/packages/credentials/deepseek-account/src/notifications.ts b/packages/account/deepseek-account/src/notifications.ts similarity index 100% rename from packages/credentials/deepseek-account/src/notifications.ts rename to packages/account/deepseek-account/src/notifications.ts diff --git a/packages/credentials/deepseek-account/src/protocol.ts b/packages/account/deepseek-account/src/protocol.ts similarity index 95% rename from packages/credentials/deepseek-account/src/protocol.ts rename to packages/account/deepseek-account/src/protocol.ts index b7a6a234a6..2a0160e65e 100644 --- a/packages/credentials/deepseek-account/src/protocol.ts +++ b/packages/account/deepseek-account/src/protocol.ts @@ -66,7 +66,7 @@ export function platformHeaders(values: Record): Record() for (const [name, value] of Object.entries(values)) { const key = name.toLowerCase() - if (['authorization', 'x-dsh-auth-token', 'host', 'content-length', 'transfer-encoding', 'connection', 'content-type'].includes(key) + if (['authorization', ACCOUNT_TOKEN_HEADER, 'host', 'content-length', 'transfer-encoding', 'connection', 'content-type'].includes(key) || names.has(key)) throw new Error('account: requestHeaders contains a reserved or duplicate header') names.add(key) try { headers.set(name, value) } @@ -161,9 +161,12 @@ export function requestNotificationEvent(origin: string, token: string, id: Acco }, signal) } +/** Request header carrying the account token on every request the token authenticates. */ +export const ACCOUNT_TOKEN_HEADER = 'x-dsh-auth-token' + // The grant is provider-owned; deployment requestHeaders cannot override it or the client identity. function accountHeaders(headers: Record, token: string): Record { - return { ...headers, 'x-dsh-auth-token': token } + return { ...headers, [ACCOUNT_TOKEN_HEADER]: token } } /** @@ -177,7 +180,7 @@ function accountHeaders(headers: Record, token: string): Record< export async function logoutAccount(origin: string, token: string, signal: AbortSignal, headers: Record): Promise { await platformRequest(`${origin}/auth-api/v0/users/logout`, { - method: 'POST', headers: { ...headers, 'x-dsh-auth-token': token }, + method: 'POST', headers: { ...headers, [ACCOUNT_TOKEN_HEADER]: token }, }, signal) } @@ -196,7 +199,7 @@ async function platformRequest(url: string, init: RequestInit, signal: AbortSign if (!callerCancelled(signal)) console.error('[deepseek-account] request failed', { path, errorCode: 'no-response', aborted: signal.aborted }) throw new PlatformAuthError('no-response') } - if (response.status === 401 && new Headers(init.headers).has('x-dsh-auth-token')) { + if (response.status === 401 && new Headers(init.headers).has(ACCOUNT_TOKEN_HEADER)) { if (!callerCancelled(signal)) console.error('[deepseek-account] request failed', { path, status: response.status, errorCode: 'expired' }) await response.body?.cancel() throw new AccountUnauthorizedError() @@ -228,7 +231,7 @@ async function platformRequest(url: string, init: RequestInit, signal: AbortSign const responseCodes = z.object({ code: z.number().int(), data: z.object({ biz_code: z.number().int() }).optional() }).safeParse(payload) if (responseCodes.success) codes = responseCodes.data const authorization = z.object({ code: z.literal(40003) }).safeParse(payload) - if (authorization.success && new Headers(init.headers).has('x-dsh-auth-token')) { + if (authorization.success && new Headers(init.headers).has(ACCOUNT_TOKEN_HEADER)) { throw new AccountUnauthorizedError() } stage = 'envelope' diff --git a/packages/credentials/deepseek-account/src/types.ts b/packages/account/deepseek-account/src/types.ts similarity index 89% rename from packages/credentials/deepseek-account/src/types.ts rename to packages/account/deepseek-account/src/types.ts index 5ccd36303b..9a0f23c772 100644 --- a/packages/credentials/deepseek-account/src/types.ts +++ b/packages/account/deepseek-account/src/types.ts @@ -111,6 +111,24 @@ declare module '@deepseek-ai/cordis' { } } +/** + * The account credential released for one request destination, as the request + * carries it. Host-only: it holds the token and never crosses the Remote. + */ +export interface AccountRequestCredential { + /** Request headers carrying the account token. */ + readonly headers: Readonly> + /** The bare token. */ + readonly value: string + /** + * Remove the stored token after the destination rejected it, unless a newer + * sign-in replaced it. Storage failures are contained: the caller reports + * the destination's rejection, and the next rejection retries the removal. + * @returns settlement after the removal attempt. + */ + reject(): Promise +} + /** Host-only credentials for an embedded Platform document; never expose through account RPC. */ export interface PlatformSession { readonly origin: string diff --git a/packages/account/deepseek-account/tests/account-stub.ts b/packages/account/deepseek-account/tests/account-stub.ts new file mode 100644 index 0000000000..a04352bbac --- /dev/null +++ b/packages/account/deepseek-account/tests/account-stub.ts @@ -0,0 +1,35 @@ +/** `deepseekAccount` stand-ins for consumers of the account's request credential. */ +import type { DeepSeekAccount } from '../src/index.ts' +import { ACCOUNT_TOKEN_HEADER } from '../src/protocol.ts' + +/** Token policy and rejection observer of one stand-in. */ +export interface AccountStubOptions { + /** The token released for a destination; undefined or empty releases nothing, and a throw fails the read. */ + readonly token: (url: string) => string | undefined | Promise + /** Observes each rejected token; a throw is contained, as the service contains storage failures. */ + readonly reject?: (token: string) => void | Promise +} + +/** + * An account service releasing request credentials as the real one does: the token header, the bare token, and an + * invalidation that reports no failure. + * @param options - token policy and rejection observer. + * @returns the stand-in, typed as the service for `ctx.provide`. + */ +export function accountStub(options: AccountStubOptions): DeepSeekAccount { + const stub: Pick = { + async resolveRequestCredential(url) { + const token = await options.token(url) + if (token === undefined || token.length === 0) return undefined + return { + headers: { [ACCOUNT_TOKEN_HEADER]: token }, + value: token, + reject: async () => { + try { await options.reject?.(token) } + catch (_storageFailure) { /* The destination's rejection is the failure to report, as in the service. */ } + }, + } + }, + } + return stub as DeepSeekAccount +} diff --git a/packages/credentials/deepseek-account/tests/account.spec.ts b/packages/account/deepseek-account/tests/account.spec.ts similarity index 97% rename from packages/credentials/deepseek-account/tests/account.spec.ts rename to packages/account/deepseek-account/tests/account.spec.ts index 267616dab3..a5a1662868 100644 --- a/packages/credentials/deepseek-account/tests/account.spec.ts +++ b/packages/account/deepseek-account/tests/account.spec.ts @@ -306,6 +306,35 @@ it('allows real account credentials only on the exact official HTTPS origin', as } }) +it('releases the request credential for an allowed destination and removes the rejected token through it', async () => { + const f = await fixture(undefined, {}, false, {}, 'http://inference.example.test:8094') + f.exchangeResponse({ token: 'test-account-token' }) + await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'desktop') + await f.wait('waiting-browser') + await fetch(f.callback(), { redirect: 'manual' }) + await f.wait('succeeded') + const endpoint = 'http://inference.example.test:8094/v1/tools/search' + expect(await f.account.resolveRequestCredential('https://api.deepseek.com/v1/tools/search')).toBeUndefined() + const credential = await f.account.resolveRequestCredential(endpoint) + expect(credential).toMatchObject({ headers: { 'x-dsh-auth-token': 'test-account-token' }, value: 'test-account-token' }) + await credential!.reject() + expect((await f.account.getState()).status).toBe('signed-out') + expect(await f.account.resolveRequestCredential(endpoint)).toBeUndefined() +}) + +it('contains a storage failure while removing a rejected token', async () => { + const f = await fixture(undefined, {}, false, {}, 'http://inference.example.test:8094') + f.exchangeResponse({ token: 'test-account-token' }) + await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'desktop') + await f.wait('waiting-browser') + await fetch(f.callback(), { redirect: 'manual' }) + await f.wait('succeeded') + const credential = await f.account.resolveRequestCredential('http://inference.example.test:8094/v1/tools/search') + await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'api-key', key: 'wrong-kind' })) + await expect(credential!.reject()).resolves.toBeUndefined() + await expect(f.account.rejectToken('test-account-token')).rejects.toThrow('account: storage') +}) + it('restricts platform destinations to the configured origin and route', () => { expect(() => platformOrigin('http://localhost:8081', false, 'platformOrigin')).toThrow() expect(platformOrigin('http://localhost:8081', true, 'platformOrigin')).toBe('http://localhost:8081') diff --git a/packages/credentials/deepseek-account/tests/authorization-response.spec.ts b/packages/account/deepseek-account/tests/authorization-response.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/authorization-response.spec.ts rename to packages/account/deepseek-account/tests/authorization-response.spec.ts diff --git a/packages/credentials/deepseek-account/tests/client-headers.spec.ts b/packages/account/deepseek-account/tests/client-headers.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/client-headers.spec.ts rename to packages/account/deepseek-account/tests/client-headers.spec.ts diff --git a/packages/credentials/deepseek-account/tests/details.spec.ts b/packages/account/deepseek-account/tests/details.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/details.spec.ts rename to packages/account/deepseek-account/tests/details.spec.ts diff --git a/packages/credentials/deepseek-account/tests/diagnostics.spec.ts b/packages/account/deepseek-account/tests/diagnostics.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/diagnostics.spec.ts rename to packages/account/deepseek-account/tests/diagnostics.spec.ts diff --git a/packages/credentials/deepseek-account/tests/expected/web-exchange-failure.txt b/packages/account/deepseek-account/tests/expected/web-exchange-failure.txt similarity index 100% rename from packages/credentials/deepseek-account/tests/expected/web-exchange-failure.txt rename to packages/account/deepseek-account/tests/expected/web-exchange-failure.txt diff --git a/packages/credentials/deepseek-account/tests/logout.spec.ts b/packages/account/deepseek-account/tests/logout.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/logout.spec.ts rename to packages/account/deepseek-account/tests/logout.spec.ts diff --git a/packages/credentials/deepseek-account/tests/notifications.spec.ts b/packages/account/deepseek-account/tests/notifications.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/notifications.spec.ts rename to packages/account/deepseek-account/tests/notifications.spec.ts diff --git a/packages/credentials/deepseek-account/tests/origins.spec.ts b/packages/account/deepseek-account/tests/origins.spec.ts similarity index 100% rename from packages/credentials/deepseek-account/tests/origins.spec.ts rename to packages/account/deepseek-account/tests/origins.spec.ts diff --git a/packages/credentials/deepseek-account/tests/remote.spec.ts b/packages/account/deepseek-account/tests/remote.spec.ts similarity index 84% rename from packages/credentials/deepseek-account/tests/remote.spec.ts rename to packages/account/deepseek-account/tests/remote.spec.ts index e33fc547da..7e1e162044 100644 --- a/packages/credentials/deepseek-account/tests/remote.spec.ts +++ b/packages/account/deepseek-account/tests/remote.spec.ts @@ -3,7 +3,6 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' -import type { Agent } from '@deepseek-ai/dsh-agent' import AuthorizationService from '@deepseek-ai/dsh-authorization' import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' import { credentialKey } from '@deepseek-ai/dsh-credentials' @@ -70,18 +69,16 @@ it('delivers expiry only to current subscribers and stops on disconnect or provi expect(await reopened).toEqual({ done: true, value: undefined }) }) -it('reports running account requests and excludes absent, idle, and other-provider tasks', async () => { - const { ctx, account } = await fixture() +it('reports running account work through registered reports and forgets disposed ones', async () => { + const { account } = await fixture() expect(account.hasRunningAccountTasks()).toBe(false) - const active: Array> = [] - const task = (status: Agent['status'], provider?: string): Pick => ({ - status, session: { requestContext: () => provider === undefined ? undefined : { provider, model: 'model' } } as Agent['session'], - }) - ctx.provide('agents', { list: () => active } as Context['agents']) - active.push(task('running'), task('running', 'deepseek-official'), task('idle', 'deepseek-account')) + let running = false + const idle = account.registerRunningTaskReport(() => false) + const dispose = account.registerRunningTaskReport(() => running) expect(account.hasRunningAccountTasks()).toBe(false) - active.push(task('running', 'deepseek-account')) + running = true expect(account.hasRunningAccountTasks()).toBe(true) - active.pop() + dispose() expect(account.hasRunningAccountTasks()).toBe(false) + idle() }) diff --git a/packages/credentials/deepseek-account/tsconfig.json b/packages/account/deepseek-account/tsconfig.json similarity index 78% rename from packages/credentials/deepseek-account/tsconfig.json rename to packages/account/deepseek-account/tsconfig.json index e4add1d675..2c0bd9becb 100644 --- a/packages/credentials/deepseek-account/tsconfig.json +++ b/packages/account/deepseek-account/tsconfig.json @@ -18,16 +18,13 @@ "path": "../../util/brand" }, { - "path": "../../core/agent" + "path": "../../util/values" }, { - "path": "../../llm/llm" + "path": "../../credentials/authorization" }, { - "path": "../authorization" - }, - { - "path": "../credentials" + "path": "../../credentials/credentials" }, { "path": "../../../vendor/schemastery" diff --git a/packages/api/remotes/tsconfig.client.json b/packages/api/remotes/tsconfig.client.json index 2e82590c7a..bc8fc4f34d 100644 --- a/packages/api/remotes/tsconfig.client.json +++ b/packages/api/remotes/tsconfig.client.json @@ -113,7 +113,7 @@ "path": "../../document/office-kit" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../web/web" diff --git a/packages/api/remotes/tsconfig.host.json b/packages/api/remotes/tsconfig.host.json index 33a538658d..c05d497e60 100644 --- a/packages/api/remotes/tsconfig.host.json +++ b/packages/api/remotes/tsconfig.host.json @@ -90,7 +90,7 @@ "path": "../../host/plugin-inventory" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../web/web" diff --git a/packages/client/product-analytics/tsconfig.host.json b/packages/client/product-analytics/tsconfig.host.json index b4b4e831ab..e2d3803bd6 100644 --- a/packages/client/product-analytics/tsconfig.host.json +++ b/packages/client/product-analytics/tsconfig.host.json @@ -28,7 +28,7 @@ "path": "../../credentials/credentials" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../host/webserver" diff --git a/packages/client/ui-account-notifications/tsconfig.json b/packages/client/ui-account-notifications/tsconfig.json index 3d18f2dc37..6c2da05873 100644 --- a/packages/client/ui-account-notifications/tsconfig.json +++ b/packages/client/ui-account-notifications/tsconfig.json @@ -30,7 +30,7 @@ "path": "../ui-settings-account" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../host/webserver" diff --git a/packages/client/ui-settings-account/tsconfig.json b/packages/client/ui-settings-account/tsconfig.json index ac170f07db..d425a8cdea 100644 --- a/packages/client/ui-settings-account/tsconfig.json +++ b/packages/client/ui-settings-account/tsconfig.json @@ -36,7 +36,7 @@ "path": "../ui-theme/tsconfig.client.json" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../ui-settings-models" diff --git a/packages/credentials/authorization/package.json b/packages/credentials/authorization/package.json index 8a9da04f8f..a3a4b26d5d 100644 --- a/packages/credentials/authorization/package.json +++ b/packages/credentials/authorization/package.json @@ -37,13 +37,13 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/credentials/authorization/src/index.ts b/packages/credentials/authorization/src/index.ts index f54e04896a..418c301543 100644 --- a/packages/credentials/authorization/src/index.ts +++ b/packages/credentials/authorization/src/index.ts @@ -28,7 +28,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import type { CredentialKey, CredentialRecord } from '@deepseek-ai/dsh-credentials' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { AuthorizationEntry, AuthorizationMethod, AuthorizationNotice, AuthorizationOutcome, AuthorizationPrompt, diff --git a/packages/credentials/authorization/tsconfig.json b/packages/credentials/authorization/tsconfig.json index 414fd879c6..ec432a59c7 100644 --- a/packages/credentials/authorization/tsconfig.json +++ b/packages/credentials/authorization/tsconfig.json @@ -18,7 +18,7 @@ "path": "../credentials" }, { - "path": "../../llm/llm" + "path": "../../util/error" } ] } diff --git a/packages/credentials/credentials/README.i18n.yaml b/packages/credentials/credentials/README.i18n.yaml index 2b850ee561..1489c975f1 100644 --- a/packages/credentials/credentials/README.i18n.yaml +++ b/packages/credentials/credentials/README.i18n.yaml @@ -24,8 +24,8 @@ en: 8f3500119608f91b zh: 147fdb5389affbc0 /deepseek-ai-dsh-credentials/use-this-package/storing-checking-and-removing-keys: - en: 68096f3f256353ed - zh: 673608f5d5e66d66 + en: 9f6cf31d0fd281ac + zh: b20ac60e6cdd7527 /deepseek-ai-dsh-credentials/use-this-package/storing-updating-and-removing-records: en: 300c3f1f13abdca4 zh: ec7a6486ac88889c diff --git a/packages/credentials/credentials/README.md b/packages/credentials/credentials/README.md index 26e324c30b..845629e9e8 100644 --- a/packages/credentials/credentials/README.md +++ b/packages/credentials/credentials/README.md @@ -60,6 +60,8 @@ await ctx.credentials.unset(ref) // no-op when absent; an Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. Providers may disclose a masked stored-value preview through the optional `masked` field; the full value stays on the Host. +Consumers that must also work in compositions without a credentials service, such as the DeepSeek model and web providers, read references through `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`: a mounted service is authoritative, including when it holds no value, and only its absence makes them read the launch environment, where an empty value is absent. Store failures propagate, and callers validate the value's format. + ### Storing, updating, and removing records A plugin addresses each record by `/` — its own registered name plus an id it chooses, such as a provider route key — and reads, modifies, or removes what it holds: diff --git a/packages/credentials/credentials/README.zh.md b/packages/credentials/credentials/README.zh.md index 7aa8fc9d9e..bc03f641d7 100644 --- a/packages/credentials/credentials/README.zh.md +++ b/packages/credentials/credentials/README.zh.md @@ -60,6 +60,8 @@ await ctx.credentials.unset(ref) // no-op when absent; an 用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。提供方可通过可选的 `masked` 字段报告已保存值的脱敏预览;完整值留在 Host。 +必须在没有凭据服务的组合中也能工作的消费方(如 DeepSeek 模型与 Web 提供方)通过 `resolveCredentialRef(ctx, ref)` 和 `credentialRefConfigured(ctx, ref)` 读取引用:已挂载的服务具有权威性,包括它不持有值的情况;只有服务缺席时才读取启动环境,其中空值视为不存在。存储失败向上传播,值的格式由调用方校验。 + ### 存储、更新与移除记录 插件按 `/` 寻址每条记录——自身注册名加一个自选 id,例如提供方路由键——并读取、修改或移除它所持有的内容: diff --git a/packages/credentials/credentials/package.json b/packages/credentials/credentials/package.json index 4589152305..6c847e9587 100644 --- a/packages/credentials/credentials/package.json +++ b/packages/credentials/credentials/package.json @@ -35,10 +35,12 @@ ], "license": "MIT", "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-launch-environment": "workspace:*" }, "devDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-launch-environment": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*" diff --git a/packages/credentials/credentials/src/index.ts b/packages/credentials/credentials/src/index.ts index 8f6054a327..6190b7bc2a 100644 --- a/packages/credentials/credentials/src/index.ts +++ b/packages/credentials/credentials/src/index.ts @@ -10,6 +10,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' +import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import type { CredentialInfo, CredentialKey, CredentialRecord, CredentialRef } from './types.ts' export type { @@ -151,6 +152,38 @@ declare module '@deepseek-ai/cordis' { } } +/** + * Read one reference's current value through the mounted credentials service, + * or through the launch environment when the composition mounts no service. A + * mounted service is authoritative, including when it holds no value: the + * environment is read only when there is no service to ask, which is how + * one-shot compositions without the store authenticate from their launching + * shell. Empty values are absent. Store failures propagate; callers validate + * the value's format. + * @param ctx - context providing the optional credentials service and the launch environment. + * @param ref - the reference to read. + * @returns the value, or `undefined` while unconfigured. + */ +export async function resolveCredentialRef(ctx: Context, ref: CredentialRef): Promise { + const credentials = ctx.get('credentials') + if (credentials !== undefined) return (await credentials.resolve(ref))?.value + const ambient = launchEnvironmentOf(ctx).get(ref)?.value + return ambient === undefined || ambient.length === 0 ? undefined : ambient +} + +/** + * Report whether a reference is configured without reading its value, through + * the same source {@link resolveCredentialRef} reads. Store failures propagate. + * @param ctx - context providing the optional credentials service and the launch environment. + * @param ref - the reference to inspect. + * @returns whether the authoritative source holds a value for the reference. + */ +export async function credentialRefConfigured(ctx: Context, ref: CredentialRef): Promise { + const credentials = ctx.get('credentials') + if (credentials !== undefined) return (await credentials.describe(ref)).configured + return (launchEnvironmentOf(ctx).get(ref)?.value.length ?? 0) > 0 +} + /** * Abstract credential service over two key spaces that answer two questions. * diff --git a/packages/credentials/credentials/tests/reference-fallback.spec.ts b/packages/credentials/credentials/tests/reference-fallback.spec.ts new file mode 100644 index 0000000000..3bfc12d435 --- /dev/null +++ b/packages/credentials/credentials/tests/reference-fallback.spec.ts @@ -0,0 +1,50 @@ +/** Reference reads fall back to the launch environment only when no credentials service is mounted. */ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, vi } from 'vitest' +import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' +import { credentialRef, credentialRefConfigured, resolveCredentialRef } from '../src/index.ts' +import { MemoryCredentials } from './memory.ts' + +const ref = credentialRef('TEST_PROVIDER_KEY') + +function context(value?: string): Context { + const ctx = new Context() + ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([ + { source: 'process', values: value === undefined ? {} : { [ref]: value } }, + ])) + return ctx +} + +describe('reference reads without a credentials service', () => { + it.each([undefined, '', 'ambient-key'])('read the launch environment, treating empty as absent: %j', async (value) => { + const ctx = context(value) + try { + await expect(resolveCredentialRef(ctx, ref)).resolves.toBe(value ? value : undefined) + await expect(credentialRefConfigured(ctx, ref)).resolves.toBe(Boolean(value)) + } finally { await ctx.fiber.dispose() } + }) +}) + +describe('reference reads with a credentials service', () => { + it('treat the service as authoritative, including its absence of a value', async () => { + const ctx = context('ambient-key') + const resolve = vi.fn(async () => undefined) + const describeRef = vi.fn(async () => ({ configured: false, writable: true })) + ctx.provide('credentials', { resolve, describe: describeRef } as never) + try { + await expect(credentialRefConfigured(ctx, ref)).resolves.toBe(false) + expect(resolve).not.toHaveBeenCalled() + await expect(resolveCredentialRef(ctx, ref)).resolves.toBeUndefined() + expect(resolve).toHaveBeenCalledExactlyOnceWith(ref) + } finally { await ctx.fiber.dispose() } + }) + + it('return the stored value verbatim on every read', async () => { + const ctx = context('ambient-key') + await ctx.plugin(MemoryCredentials, { [ref]: ' stored-key ' }) + try { + await expect(resolveCredentialRef(ctx, ref)).resolves.toBe(' stored-key ') + await expect(credentialRefConfigured(ctx, ref)).resolves.toBe(true) + } finally { await ctx.fiber.dispose() } + }) +}) diff --git a/packages/credentials/credentials/tsconfig.json b/packages/credentials/credentials/tsconfig.json index 342f636170..e984ba2b9d 100644 --- a/packages/credentials/credentials/tsconfig.json +++ b/packages/credentials/credentials/tsconfig.json @@ -16,6 +16,9 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../util/launch-environment" } ] } diff --git a/packages/credentials/deepseek-account/src/account-tasks.ts b/packages/credentials/deepseek-account/src/account-tasks.ts deleted file mode 100644 index 6325571dd5..0000000000 --- a/packages/credentials/deepseek-account/src/account-tasks.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** Account sign-out policy over the latest logged request route. */ -import type { Context } from '@deepseek-ai/cordis' -import { LlmError } from '@deepseek-ai/dsh-llm' -import type { Agent } from '@deepseek-ai/dsh-agent' -import type {} from './index.ts' - -/** - * Identify running work whose latest bound request used the account route. - * @param agent - live Agent with its durable request context. - * @returns whether account sign-out should interrupt this task. - */ -export function isRunningAccountTask(agent: Pick): boolean { - return agent.status === 'running' && agent.session.requestContext()?.provider === 'deepseek-account' -} - -/** - * Cancel signed-out account tasks and publish sign-in guidance for rejected requests. - * @param ctx - account provider lifetime; Agents may attach later. - */ -export function installAccountTaskCancellation(ctx: Context): void { - ctx.inject(['agents'], (scope) => { - scope.on('agent/error', ({ error }) => { - if (error instanceof LlmError && error.code === 'ACCOUNT_SIGN_IN_REQUIRED') { - scope.emit('deepseek-account/model-sign-in-required') - } - }) - scope.on('deepseek-account/signed-out', () => { - for (const agent of scope.agents.list()) { - if (isRunningAccountTask(agent)) { - agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }) - } - } - }) - }) -} diff --git a/packages/experimental/translator/tests/paid-fixture.ts b/packages/experimental/translator/tests/paid-fixture.ts index 82d45d3a5d..bb2235c338 100644 --- a/packages/experimental/translator/tests/paid-fixture.ts +++ b/packages/experimental/translator/tests/paid-fixture.ts @@ -7,7 +7,6 @@ import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SqliteSessionQuery from '@deepseek-ai/dsh-session-query-sqlite' import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as Account from '@deepseek-ai/dsh-llm-deepseek-account' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' import DeepSeekLlmApiExtensionRegistry from '@deepseek-ai/dsh-deepseek-llm-api-extensions' import * as SessionLogDeepSeek from '@deepseek-ai/dsh-session-log-deepseek' import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' @@ -17,6 +16,7 @@ import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import Translator, { type Config } from '../src/index.ts' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' /** Provider-visible request, without credential values. */ export interface NativeRequest { @@ -170,9 +170,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options: describe: async () => ({ configured, writable: true }), resolve: async () => configured ? { value: 'fixture-native-key', source: 'fixture' } : undefined, } as never) - host.provide('deepseekAccount', { - resolveToken: async (_baseURL: string): Promise => signedIn ? 'fixture-account-token' : undefined, - } as DeepSeekAccount) + host.provide('deepseekAccount', accountStub({ token: () => signedIn ? 'fixture-account-token' : undefined })) }) let ctx = await start(), session: Session | undefined cleanups.push(async () => { await ctx.fiber.dispose() }) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index d0397ec2f8..ba605d4539 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1041,6 +1041,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], returns: 'stored token, or undefined for other origins or a signed-out account.', }, + { + signature: 'async resolveRequestCredential(url: string): Promise', + description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation. Host-only.', + parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], + returns: 'the request credential, or undefined for other origins or a signed-out account.', + }, { signature: '@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: \'web\' | \'desktop\'): Promise', description: 'Join an active attempt or start browser authorization.', @@ -1059,11 +1065,17 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'client', description: 'identity of the requesting UI, captured for the background revocation retries.' }], returns: 'the signed-out state after local removal; remote failures never restore the grant.', }, + { + signature: 'registerRunningTaskReport(report: () => boolean): () => void', + description: 'Register a report of running work that signing out would interrupt. The plugin billing the account to a model route registers one from within `ctx.effect()`; without any report nothing is known to be running.', + parameters: [{ name: 'report', description: 'answers whether such work is running now.' }], + returns: 'the disposer removing the report.', + }, { signature: '@Remote hasRunningAccountTasks(): boolean', description: 'Inspect running work before sign-out.', parameters: [], - returns: 'whether a running task\'s latest request uses the account route; false when the optional agents service is absent.', + returns: 'whether a registered report says a running task uses the account; false without reports.', }, { signature: '@Remote({ mode: \'stream\' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<\'session-expired\'>', @@ -2154,6 +2166,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'provider', description: 'registered provider route.' }, { name: 'model', description: 'exact model id.' }, { name: 'image', description: 'normalized image reference.' }], returns: 'dimensions and byte target used by the adapter\'s request serializer.', }, + { + signature: 'routeCredential(provider: string): RouteCredential | undefined', + description: 'Resolve the credential one registered route currently sends, through its owning adapter. An unregistered route answers `undefined` rather than throwing because callers ask about routes a conversation named earlier, which may no longer be mounted; a registered route whose configuration does not resolve propagates the adapter\'s failure.', + parameters: [{ name: 'provider', description: 'provider route whose credential is wanted.' }], + returns: 'the route credential, or `undefined` when the route is unregistered or publishes none.', + }, { signature: 'fileRequestText(ref: FileAttachmentRef): string', description: 'Resolve the exact text one durable file occurrence contributes to every provider request in the current execution environment.', @@ -5761,6 +5779,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AccountProfile', declaration: 'export interface AccountProfile {\n readonly id: AccountUserId | null;\n readonly name: string | null;\n readonly contact: string | null;\n readonly avatarUrl?: string | null;\n}', }, + { + name: 'AccountRequestCredential', + declaration: 'export interface AccountRequestCredential {\n readonly headers: Readonly>;\n readonly value: string;\n reject(): Promise;\n}', + }, { name: 'AccountUpdate', declaration: 'export interface AccountUpdate {\n readonly type: \'snapshot\' | \'credentials-changed\';\n readonly state: AccountView;\n}', @@ -7375,7 +7397,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmAdapter', - declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', + declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n routeCredential(_provider: string): RouteCredential | undefined;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', }, { name: 'LlmAttemptId', @@ -7397,6 +7419,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'LlmConfigurableProvider', declaration: 'export interface LlmConfigurableProvider {\n provider: string;\n displayName: string;\n settingsNs: string;\n settingsPath: readonly string[];\n declared?: boolean;\n defaultBaseURL?: string;\n baseURLEnv?: readonly string[];\n nativeAuth?: LlmNativeAuth;\n error?: string;\n}', }, + { + name: 'LlmCredentialKind', + declaration: 'export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap];', + }, + { + name: 'LlmCredentialKindMap', + declaration: 'export interface LlmCredentialKindMap {\n \'api-key\': \'api-key\';\n account: \'account\';\n}', + }, { name: 'LlmDiscoveredModel', declaration: 'export interface LlmDiscoveredModel {\n id: string;\n name?: string;\n contextWindow?: number;\n maxTokens?: number;\n inputModalities?: readonly ModelModality[];\n}', @@ -7463,7 +7493,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmRuntime', - declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, signal?: AbortSignal): Promise;\n async prepareCall(conf /* …truncated — full shape in source */', + declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n routeCredential(provider: string): RouteCredential | undefined;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, signa /* …truncated — full shape in source */', }, { name: 'LocalAtInput', @@ -8557,6 +8587,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ReviewVerdict', declaration: 'export type ReviewVerdict = \'approved\' | \'changes-requested\' | \'commented\' | \'dismissed\';', }, + { + name: 'RouteCredential', + declaration: 'export interface RouteCredential {\n readonly kind: LlmCredentialKind;\n readonly baseURL: string;\n readonly reference?: string;\n configured(endpoint: string): Promise;\n resolve(endpoint: string, signal?: AbortSignal): Promise;\n}', + }, + { + name: 'RouteCredentialGrant', + declaration: 'export interface RouteCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n}', + }, { name: 'RpcId', declaration: 'export type RpcId = Branded<\'rpc-id\'>;', diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index ade47b1cf3..b2cab10d84 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -9,17 +9,17 @@ en: 8fa1148e0ee9d351 zh: 634ec9d79d5ffbf0 /deepseek-ai-dsh-llm-deepseek-account/summary: - en: b80e34cdfb51009d - zh: eda44bcc181793d8 + en: 90635454957391b0 + zh: 815bf79ba6056c3c /deepseek-ai-dsh-llm-deepseek-account/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-account/use-this-package: - en: b1a9453e08198023 - zh: 630e7f566ad4d9db + en: 3d952599a9b0bf85 + zh: 231c0331a7d217e3 /deepseek-ai-dsh-llm-deepseek-account/understand-the-implementation: - en: 06629c312d0cb860 - zh: f33b2773b0ab1d25 + en: ee65c14a90dfa0dd + zh: 91778b3e940da7f7 /deepseek-ai-dsh-llm-deepseek-account/further-exploration: en: 30a69b9c66d89580 zh: fcc026a6373c1bee diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index d6397a8c5f..9b5ee9f706 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, the account model listing, and model gating for `deepseek-account`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, the account catalog, and model admission. -Authentication resolution returns `x-dsh-auth-token` and a failure callback capturing the same token. HTTP 401 classification and rejection stay in this provider; a rejected older request cannot clear a replacement login. +Authentication resolution returns the request credential the account service releases for the destination, carrying `x-dsh-auth-token`, with a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route publishes the account credential through `ctx.llm.routeCredential('deepseek-account')` with its base URL, so the DeepSeek web providers send it to the same deployment. ## Table of Contents @@ -25,7 +25,7 @@ Authentication resolution returns `x-dsh-auth-token` and a failure callback capt ## Use this package -Only `deepseekAccount.resolveToken(url)` supplies the token; the account service validates the destination. Signed-out or ineligible requests fail with `ACCOUNT_SIGN_IN_REQUIRED` and discovery returns an empty catalog. The route never falls back to an API key. Other credential lookup errors propagate. +Only `deepseekAccount.resolveRequestCredential(url)` supplies the credential; the account service validates the destination. Signed-out or ineligible requests fail with `ACCOUNT_SIGN_IN_REQUIRED` and discovery returns an empty catalog. The route never falls back to an API key. Other credential lookup errors propagate. The route's catalog comes from the account's `GET /models` listing at the origin of the Messages `baseURL` (`https://api.deepseek.com/models` for the official endpoint); the listing endpoint is not configurable. Listing requests carry the account token in `x-dsh-auth-token` and the harness `User-Agent`, and reject redirects. @@ -56,14 +56,14 @@ An offered model shows the badge its listing entry declares under `client_metada | `modelsMaxAgeMs` | `600,000` | Automatic refresh interval after first use, also used after failure; `0` refreshes on access only | | `modelOverrides` | `{}` | Field overrides by model id | -An account request HTTP 401 maps to `ACCOUNT_TOKEN_INVALID` independently of the response body. The account service removes the credential only if it still matches the request token. HTTP 403 and other failures do not clear the login. The account module owns task cancellation after sign-out; this plugin does not inspect Agents. +An account request HTTP 401 maps to `ACCOUNT_TOKEN_INVALID` independently of the response body. The account service removes the credential only if it still matches the request token. HTTP 403 and other failures do not clear the login. After `deepseek-account/signed-out`, this plugin cancels running Agents whose latest bound request used this route, keeping their inboxes; it publishes `deepseek-account/model-sign-in-required` for a request that fails with `ACCOUNT_SIGN_IN_REQUIRED`, and registers a running-task report with the account service so its sign-out confirmation knows about that work. The settings namespace is the Cordis entry id, or the plugin name without an entry. Product profiles retain the official entry id `llm-deepseek` and use `llm-deepseek-account` for the account route. ## Understand the implementation -Account-token lookup and invalidation use the [shared credential helpers](../llm-deepseek/src/credential.ts); this plugin retains HTTP error classification. Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the token. +Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the token. A failed request the shared transport classifies as `QUOTA` is rewritten to `ACCOUNT_QUOTA` before it leaves this provider, covering an HTTP 402 response and an in-band SSE error alike. The shared transport and the `deepseek-official` route keep `QUOTA`, so the account route's top-up action never appears for an API-key or third-party failure. diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index a2407afbda..2f6958d366 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-account` 注册鉴权、账号模型列表和模型门控。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包负责凭据解析、账号目录和模型准入。 -鉴权解析返回 `x-dsh-auth-token` 和捕获同一 token 的失败回调。HTTP 401 的分类和凭据失效处理由此提供方负责;被拒绝的旧请求不能清除替换后的登录。 +鉴权解析返回账号服务为目标地址释放的请求凭据,携带 `x-dsh-auth-token`,并附带使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由通过 `ctx.llm.routeCredential('deepseek-account')` 连同其基础地址发布账号凭据,使 DeepSeek Web 提供方把它发往同一部署。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用此包 -账号 token 仅由 `deepseekAccount.resolveToken(url)` 提供,目标地址必须通过账号服务的来源校验。未登录或目标不允许账号鉴权时,请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,目录为空;不会回退到 API key。其他凭据查询错误继续向调用者报告。 +账号凭据仅由 `deepseekAccount.resolveRequestCredential(url)` 提供,目标地址必须通过账号服务的来源校验。未登录或目标不允许账号鉴权时,请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,目录为空;不会回退到 API key。其他凭据查询错误继续向调用者报告。 路由的目录来自账号的 `GET /models` 列表,地址为 Messages `baseURL` 的 origin 加 `/models`(官方端点即 `https://api.deepseek.com/models`),不可配置。列表请求用 `x-dsh-auth-token` 携带账号 token,带上 harness 的 `User-Agent`,并拒绝重定向。 @@ -56,14 +56,14 @@ kind: "package-reference" | `modelsMaxAgeMs` | `600,000` | 首次使用后的自动刷新间隔,失败后也按此间隔重试;`0` 表示只在访问时刷新 | | `modelOverrides` | `{}` | 按模型 id 的字段覆盖 | -账号请求的 HTTP 401 与响应正文无关:映射为 `ACCOUNT_TOKEN_INVALID`,并要求账号服务仅在当前 token 仍与请求所用 token 相同时清除凭据。403 和其他错误不会触发清除。账号模块负责退登后打断任务,本插件不遍历 Agent。 +账号请求的 HTTP 401 与响应正文无关:映射为 `ACCOUNT_TOKEN_INVALID`,并要求账号服务仅在当前 token 仍与请求所用 token 相同时清除凭据。403 和其他错误不会触发清除。`deepseek-account/signed-out` 之后,本插件取消最近一次绑定请求使用本路由的运行中 Agent 并保留其收件箱;请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败时发布 `deepseek-account/model-sign-in-required`,并向账号服务注册运行中任务报告,供其退登确认了解这些工作。 设置命名空间采用 Cordis entry id,没有 entry 时采用插件名。产品保留 official 的 `llm-deepseek` entry id,账号使用 `llm-deepseek-account`。 ## 理解实现 -账号 token 读取与作废使用[共享凭据函数](../llm-deepseek/src/credential.ts);本插件保留 HTTP 错误分类。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和 token 的 SHA-256 为键。 +账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和 token 的 SHA-256 为键。 共享传输判定为 `QUOTA` 的失败请求离开本提供方前会被改写为 `ACCOUNT_QUOTA`,HTTP 402 响应与流内 SSE 错误都适用。共享传输与 `deepseek-official` 路由保留 `QUOTA`,因此账号路由的充值操作不会出现在 API Key 或第三方失败上。 diff --git a/packages/llm/llm-deepseek-account/package.json b/packages/llm/llm-deepseek-account/package.json index 96895b0c3d..3a3765d94c 100644 --- a/packages/llm/llm-deepseek-account/package.json +++ b/packages/llm/llm-deepseek-account/package.json @@ -41,7 +41,8 @@ "@deepseek-ai/dsh-llm-deepseek": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/cordis-plugin-loader": "workspace:~" + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -51,7 +52,8 @@ "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", - "@deepseek-ai/dsh-timeout": "workspace:*" + "@deepseek-ai/dsh-timeout": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-deepseek-account": { @@ -59,6 +61,9 @@ }, "@deepseek-ai/cordis-plugin-loader": { "optional": true + }, + "@deepseek-ai/dsh-agent": { + "optional": true } } } diff --git a/packages/llm/llm-deepseek-account/src/account-tasks.ts b/packages/llm/llm-deepseek-account/src/account-tasks.ts new file mode 100644 index 0000000000..00843ce2be --- /dev/null +++ b/packages/llm/llm-deepseek-account/src/account-tasks.ts @@ -0,0 +1,40 @@ +/** Account sign-out policy over the latest logged request route of each running Agent. */ +import type { Context } from '@deepseek-ai/cordis' +import { LlmError } from '@deepseek-ai/dsh-llm' +import type { Agent } from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-deepseek-account' + +/** Whether a running Agent's latest bound request used the account route `provider`. */ +function isRunningAccountTask(agent: Pick, provider: string): boolean { + return agent.status === 'running' && agent.session.requestContext()?.provider === provider +} + +/** + * Cancel signed-out account tasks, publish sign-in guidance for rejected + * requests, and report running account work to the account service's + * sign-out confirmation. Each listener attaches once the service it needs is + * mounted and detaches with this plugin. + * @param ctx - account route plugin lifetime; Agents and the account service may attach later. + * @param provider - the account route id this plugin registers. + */ +export function installAccountTaskCancellation(ctx: Context, provider: string): void { + ctx.inject(['agents'], (scope) => { + scope.on('agent/error', ({ error }) => { + if (error instanceof LlmError && error.code === 'ACCOUNT_SIGN_IN_REQUIRED') { + scope.emit('deepseek-account/model-sign-in-required') + } + }) + scope.on('deepseek-account/signed-out', () => { + for (const agent of scope.agents.list()) { + if (isRunningAccountTask(agent, provider)) { + agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }) + } + } + }) + scope.inject(['deepseekAccount'], (reporting) => { + reporting.effect(() => reporting.deepseekAccount.registerRunningTaskReport( + () => reporting.agents.list().some(agent => isRunningAccountTask(agent, provider)), + ), 'llm-deepseek-account: running task report') + }) + }) +} diff --git a/packages/llm/llm-deepseek-account/src/index.ts b/packages/llm/llm-deepseek-account/src/index.ts index bda73bceda..e4d77e1e6e 100644 --- a/packages/llm/llm-deepseek-account/src/index.ts +++ b/packages/llm/llm-deepseek-account/src/index.ts @@ -2,22 +2,20 @@ import type {} from '@deepseek-ai/cordis-plugin-loader' import type { Context } from '@deepseek-ai/cordis' import { ACCOUNT_QUOTA_EXCEEDED_CODE, APP_IDENTITY, LlmError, QUOTA_EXCEEDED_CODE } from '@deepseek-ai/dsh-llm' -import type {} from '@deepseek-ai/dsh-deepseek-account' +import type { AccountRequestCredential } from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { - catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, requestModelListing, resolveAdapterOptions, - resolveListedCatalog, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, + catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveAdapterOptions, resolveListedCatalog, } from '@deepseek-ai/dsh-llm-deepseek' import type { DeepSeekRequestAuth, ListedCatalog, ListingView, ModelListing, ResolvedDeepSeekOptions } from '@deepseek-ai/dsh-llm-deepseek' +import { installAccountTaskCancellation } from './account-tasks.ts' import { Config, plainAccountOptions, resolveAccountOptions } from './config.ts' -export { Config, plainAccountOptions, resolveAccountOptions } from './config.ts' +export { Config } from './config.ts' export const name = 'llm-deepseek-account' export const inject = ['llm'] const PROVIDER = 'deepseek-account' -/** Header carrying the account token on Messages, Files, and model-listing requests. */ -const TOKEN_HEADER = 'x-dsh-auth-token' /** Console tag of listing diagnostics; product profiles mount no console exporter for `ctx.logger`. */ const LOG_TAG = '[llm-deepseek-account]' @@ -31,11 +29,14 @@ export function apply(ctx: Context, config: Config): void { const settings = () => resolveAccountOptions(plainAccountOptions(config), environment) settings() const supported = resolveAdapterOptions({}).models - const resolveAuth = async (connection: ResolvedDeepSeekOptions): Promise => { - const token = await resolveDeepSeekAccountToken(ctx, connection.baseURL) - if (token === undefined) throw new LlmError('Sign in to DeepSeek to use the account provider. The request destination must allow account authentication.', 'ACCOUNT_SIGN_IN_REQUIRED') + /** The account credential released for one destination; absent without an allowed signed-in account or without the account service. */ + const requestCredential = async (endpoint: string): Promise => + await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) + const resolveAuth = async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { + const credential = await requestCredential(endpoint) + if (credential === undefined) return undefined return { - headers: { [TOKEN_HEADER]: token }, + ...credential, onRequestError: async (error) => { if (!(error instanceof LlmError)) return error if (error.code === QUOTA_EXCEEDED_CODE) { @@ -43,15 +44,18 @@ export function apply(ctx: Context, config: Config): void { } if (error.failure.status !== 401) return error const rejected = new LlmError(error.message, 'ACCOUNT_TOKEN_INVALID', { ...error.failure, cause: error }) - await rejectDeepSeekAccountToken(ctx, token) + await credential.reject() return rejected }, } } + const missingCredential = () => new LlmError( + 'Sign in to DeepSeek to use the account provider. The request destination must allow account authentication.', + 'ACCOUNT_SIGN_IN_REQUIRED', + ) const catalog = createModelListingCache(ctx, name, PROVIDER, { settings: () => settings().catalog, - credential: url => resolveDeepSeekAccountToken(ctx, url), - load: (url, token, signal) => requestModelListing(url, { [TOKEN_HEADER]: token }, signal), + credential: async url => (await requestCredential(url))?.headers, }) let loggedListing: ModelListing | undefined /** Resolve the catalog, reporting each listing's hidden entries and dropped badges once. */ @@ -88,6 +92,11 @@ export function apply(ctx: Context, config: Config): void { options: () => connectionOf(catalog.current()), connect: async signal => connectionOf(await catalog.view(settings().catalog, signal)), resolveAuth, + missingCredential, + credential: { + kind: 'account', + configured: async (_connection, endpoint) => (await requestCredential(endpoint)) !== undefined, + }, admit: (connection, model) => { refuseListedModel(model, connection.catalog.refusals.get(model)) }, discoverModels: async (provider) => { const view = await catalog.view(settings().catalog) @@ -96,4 +105,5 @@ export function apply(ctx: Context, config: Config): void { return offered.map(model => catalogModelInfo(provider, model, badges.get(model.id))) }, }) + installAccountTaskCancellation(ctx, PROVIDER) } diff --git a/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts b/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts index 41bd00a4c0..81870b249c 100644 --- a/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/account-quota.spec.ts @@ -1,7 +1,7 @@ /** Account-route quota classification stays separate from API-key and third-party quota. */ import { Context } from '@deepseek-ai/cordis' import { BlockAssembler, LlmRuntime } from '@deepseek-ai/dsh-llm' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import * as ApiKey from '@deepseek-ai/dsh-llm-deepseek-api-key' import { afterEach, expect, it, vi } from 'vitest' import * as Account from '../src/index.ts' @@ -33,10 +33,7 @@ async function routeFor(token: string | undefined, provider: 'deepseek-account' const ctx = new Context() contexts.push(ctx) await ctx.plugin(LlmRuntime) - ctx.provide('deepseekAccount', { - resolveToken: async (_baseURL: string): Promise => token, - rejectToken: async (_token: string): Promise => {}, - } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => token })) await ctx.plugin(provider === 'deepseek-account' ? Account : ApiKey) return ctx } @@ -71,10 +68,7 @@ it('still expires the stored credential on an account-route 401', async () => { contexts.push(ctx) await ctx.plugin(LlmRuntime) const rejectToken = vi.fn(async (_token: string): Promise => {}) - ctx.provide('deepseekAccount', { - resolveToken: async (_baseURL: string): Promise => 'account-token', - rejectToken: (token: string): Promise => rejectToken(token), - } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'account-token', reject: rejectToken })) await ctx.plugin(Account) vi.spyOn(globalThis, 'fetch').mockImplementation(messagesOnly(() => new Response('Unauthorized', { status: 401 }))) await expect(finishOf(ctx, 'deepseek-account')).resolves.toMatchObject({ diff --git a/packages/credentials/deepseek-account/tests/account-tasks.spec.ts b/packages/llm/llm-deepseek-account/tests/account-tasks.spec.ts similarity index 78% rename from packages/credentials/deepseek-account/tests/account-tasks.spec.ts rename to packages/llm/llm-deepseek-account/tests/account-tasks.spec.ts index 14b9653b33..220f39cf37 100644 --- a/packages/credentials/deepseek-account/tests/account-tasks.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/account-tasks.spec.ts @@ -1,4 +1,4 @@ -/** Account cancellation follows logged routes and the owning plugin lifetime. */ +/** Account cancellation and running-task reports follow logged routes and the owning plugin lifetime. */ import { Context } from '@deepseek-ai/cordis' import { LlmError } from '@deepseek-ai/dsh-llm' import { expect, it, vi } from 'vitest' @@ -16,9 +16,17 @@ it('cancels running account tasks with their inboxes retained and detaches with { status: 'running', session: { requestContext: () => undefined }, cancel: cancelOther }, ] ctx.provide('agents', { list: () => tasks } as never) - const owner = ctx.plugin((scope) => { installAccountTaskCancellation(scope) }) + const reports = new Set<() => boolean>() + ctx.provide('deepseekAccount', { + registerRunningTaskReport: (report: () => boolean) => { reports.add(report); return () => { reports.delete(report) } }, + } as never) + const owner = ctx.plugin((scope) => { installAccountTaskCancellation(scope, 'deepseek-account') }) try { await owner.await() + expect([...reports].map(report => report())).toEqual([true]) + tasks[0]!.status = 'idle' + expect([...reports].map(report => report())).toEqual([false]) + tasks[0]!.status = 'running' ctx.emit('deepseek-account/signed-out') expect(cancelAccount).toHaveBeenCalledExactlyOnceWith( { kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }, @@ -34,6 +42,7 @@ it('cancels running account tasks with their inboxes retained and detaches with report(new LlmError('Sign in required', 'ACCOUNT_SIGN_IN_REQUIRED')) expect(notice).toHaveBeenCalledTimes(1) await owner.dispose() + expect(reports.size).toBe(0) report(new LlmError('Sign in required', 'ACCOUNT_SIGN_IN_REQUIRED')) expect(notice).toHaveBeenCalledTimes(1) ctx.emit('deepseek-account/signed-out') diff --git a/packages/llm/llm-deepseek-account/tests/provider.spec.ts b/packages/llm/llm-deepseek-account/tests/provider.spec.ts index 2ad19db785..5f4139eb91 100644 --- a/packages/llm/llm-deepseek-account/tests/provider.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/provider.spec.ts @@ -4,7 +4,7 @@ import type { IncomingMessage, Server, ServerResponse } from 'node:http' import { afterEach, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { ReasoningEffortId } from '@deepseek-ai/dsh-llm' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import * as ApiKey from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as Account from '../src/index.ts' @@ -50,9 +50,7 @@ async function host(origin: string, token: () => string | undefined = () => 'fix const ctx = new Context() contexts.push(ctx) await ctx.plugin(LlmRuntime) - ctx.provide('deepseekAccount', { - resolveToken: (url: string) => Promise.resolve(new URL(url).origin === origin ? token() : undefined), - } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: url => new URL(url).origin === origin ? token() : undefined })) return ctx } @@ -207,3 +205,34 @@ it('aborts an in-flight listing request when the plugin is disposed', async () = await closed await expect(pending).resolves.toEqual(expect.any(Array)) }) + +it('publishes the account credential for its consumers, asking the account for each endpoint', async () => { + const asked: string[] = [] + let token: string | undefined = 'fixture-account-token' + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return token } })) + await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) + const credential = ctx.llm.routeCredential('deepseek-account') + expect(credential).toMatchObject({ kind: 'account', baseURL: 'https://account.deepseek.test/anthropic' }) + expect(credential).not.toHaveProperty('reference') + const endpoint = 'https://account.deepseek.test/v1/tools/search' + await expect(credential!.configured(endpoint)).resolves.toBe(true) + await expect(credential!.resolve(endpoint)).resolves.toMatchObject({ headers: { 'x-dsh-auth-token': 'fixture-account-token' }, value: 'fixture-account-token' }) + token = undefined + await expect(credential!.configured(endpoint)).resolves.toBe(false) + await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() + expect(asked).toEqual([endpoint, endpoint, endpoint, endpoint]) + expect(ctx.llm.routeCredential('deepseek-official')).toBeUndefined() +}) + +it('publishes a credential nobody holds without the account service', async () => { + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) + const credential = ctx.llm.routeCredential('deepseek-account')! + await expect(credential.configured('https://account.deepseek.test/v1/tools/search')).resolves.toBe(false) + await expect(credential.resolve('https://account.deepseek.test/v1/tools/search')).resolves.toBeUndefined() +}) diff --git a/packages/llm/llm-deepseek-account/tsconfig.json b/packages/llm/llm-deepseek-account/tsconfig.json index 73803a4a6e..725d721c73 100644 --- a/packages/llm/llm-deepseek-account/tsconfig.json +++ b/packages/llm/llm-deepseek-account/tsconfig.json @@ -21,7 +21,7 @@ "path": "../../util/launch-environment" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../../vendor/loader" @@ -31,6 +31,9 @@ }, { "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/agent" } ] } diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index dfb3bd13e8..68ac287b92 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,17 +9,17 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: f937052cf8ff4812 - zh: 899d61f5021136d6 + en: 69c60bbfb6aafb7a + zh: 1afe49ea9cdc3cd5 /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-api-key/use-this-package: - en: 007427bed9bd469b - zh: 5089b5781746357f + en: 77aeaaf77e17245f + zh: 5b621a9a4aeea7d9 /deepseek-ai-dsh-llm-deepseek-api-key/understand-the-implementation: - en: 1b9584855817eddb - zh: feb2c883ca355d31 + en: 2fe0f32c15603cd9 + zh: 984ce05b82e8e679 /deepseek-ai-dsh-llm-deepseek-api-key/further-exploration: en: 347659458510940c zh: ccfb03e18b356a39 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index aa6665824c..e646cb1ef2 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for both Messages and Files requests. +Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. ## Table of Contents @@ -25,7 +25,7 @@ Authentication resolution returns the validated API key in `x-api-key` for both ## Use this package -`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. When the credentials service exists, its precedence applies; only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. +`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. It reads the key through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): when the credentials service exists, its precedence applies, and only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. ```yaml - id: llm-deepseek @@ -55,7 +55,7 @@ The settings namespace is the Cordis entry id, or the plugin name without an ent ## Understand the implementation -API-key lookup calls `resolveDeepSeekApiKey` from the [shared credential module](../llm-deepseek/src/credential.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the listed catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport; the cache lives in memory and is keyed by endpoint and a SHA-256 of the key, so another key loads its own listing. A `loader/volatile-update` listener discards the cached listing whenever the route starts or stops following it. +API-key lookup calls `resolveCredentialRef` and `credentialRefConfigured` from `dsh-credentials` and validates the value with `assertUsableApiKey` from `dsh-llm`; the shared transport reads no credential. Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the listed catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport; the cache lives in memory and is keyed by endpoint and a SHA-256 of the key, so another key loads its own listing. A `loader/volatile-update` listener discards the cached listing whenever the route starts or stops following it. ## Further Exploration diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index 33ca8db1fa..b26da9ab8b 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages 和 Files 请求共同使用。 +鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用此包 -`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。 +`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。 ```yaml - id: llm-deepseek @@ -55,7 +55,7 @@ kind: "package-reference" ## 理解实现 -API key 读取调用[共享凭据模块](../llm-deepseek/src/credential.ts)的 `resolveDeepSeekApiKey`。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入列表目录和门控。列表请求、缓存和目录解析来自共享传输包;缓存只在内存中,以端点和 API key 的 SHA-256 为键,因此换一个 key 会加载它自己的列表。一个 `loader/volatile-update` 监听器在路由开始或停止使用列表时丢弃缓存的列表。 +API key 读取调用 `dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured`,并用 `dsh-llm` 的 `assertUsableApiKey` 校验值;共享传输层不读取任何凭据。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入列表目录和门控。列表请求、缓存和目录解析来自共享传输包;缓存只在内存中,以端点和 API key 的 SHA-256 为键,因此换一个 key 会加载它自己的列表。一个 `loader/volatile-update` 监听器在路由开始或停止使用列表时丢弃缓存的列表。 ## 进一步探索 diff --git a/packages/llm/llm-deepseek-api-key/src/index.ts b/packages/llm/llm-deepseek-api-key/src/index.ts index ac0f4753c5..9fa4f2a996 100644 --- a/packages/llm/llm-deepseek-api-key/src/index.ts +++ b/packages/llm/llm-deepseek-api-key/src/index.ts @@ -1,18 +1,18 @@ /** API-key authentication, credential-gated discovery, and the official model listing for the official DeepSeek route. */ import type { Context } from '@deepseek-ai/cordis' -import { APP_IDENTITY, LlmError } from '@deepseek-ai/dsh-llm' +import { APP_IDENTITY, assertUsableApiKey, LlmError } from '@deepseek-ai/dsh-llm' import type { LlmModelBadge } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/cordis-plugin-loader' +import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { - catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, requestModelListing, resolveListedCatalog, - resolveDeepSeekApiKey, + catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveListedCatalog, } from '@deepseek-ai/dsh-llm-deepseek' -import type { CatalogRefusal, DeepSeekCatalogModel, ListingView, ModelListing } from '@deepseek-ai/dsh-llm-deepseek' +import type { CatalogRefusal, DeepSeekCatalogModel, DeepSeekRequestAuth, ListingView, ModelListing } from '@deepseek-ai/dsh-llm-deepseek' import { Config, plainOptions, resolveAdapterOptions } from './config.ts' import type { ResolvedDeepSeekOptions } from './config.ts' -export { Config, plainOptions, resolveAdapterOptions } from './config.ts' +export { Config } from './config.ts' export type { Options, ResolvedDeepSeekOptions } from './config.ts' export const name = 'llm-deepseek-api-key' export const inject = ['llm'] @@ -34,28 +34,23 @@ interface OfficialConnection extends ResolvedDeepSeekOptions { export function apply(ctx: Context, config: Config): void { const options = () => resolveAdapterOptions(plainOptions(config), launchEnvironmentOf(ctx)) options() - const resolveApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { - const ref = connection.apiKeyEnv - const key = await resolveDeepSeekApiKey(ctx, ref) - if (key !== undefined) return key - throw new LlmError( - `llm-deepseek: no API key for provider route "${PROVIDER}"; store ${ref} through the credentials` - + ` service (the web Models page writes it), or export ${ref} in the launching environment`, - 'MISSING_CREDENTIAL', - ) + /** The validated API key, or `undefined` when none is configured; store and format failures propagate. */ + const resolveApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { + const value = await resolveCredentialRef(ctx, connection.apiKeyEnv) + return value === undefined ? undefined : assertUsableApiKey(value, 'llm-deepseek', connection.apiKeyEnv) } - /** The API key, or `undefined` when none is configured; other credential failures propagate. */ - const presentApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { - try { return await resolveApiKey(connection) } - catch (error) { - if (error instanceof LlmError && error.code === 'MISSING_CREDENTIAL') return undefined - throw error - } + const resolveAuth = async (connection: ResolvedDeepSeekOptions): Promise => { + const key = await resolveApiKey(connection) + return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key } } + const missingCredential = (connection: ResolvedDeepSeekOptions) => new LlmError( + `llm-deepseek: no API key for provider route "${PROVIDER}"; store ${connection.apiKeyEnv} through the credentials` + + ` service (the web Models page writes it), or export ${connection.apiKeyEnv} in the launching environment`, + 'MISSING_CREDENTIAL', + ) const listings = createModelListingCache(ctx, name, PROVIDER, { settings: () => options().listing, - credential: async () => presentApiKey(options()), - load: (url, apiKey, signal) => requestModelListing(url, { 'x-api-key': apiKey }, signal), + credential: async () => (await resolveAuth(options()))?.headers, }) let reportedListing: ModelListing | undefined /** Resolve the catalog, reporting each listing's hidden entries and dropped badges once. */ @@ -96,12 +91,18 @@ export function apply(ctx: Context, config: Config): void { } return connectionOf(connection, view) }, - resolveAuth: async connection => ({ headers: { 'x-api-key': await resolveApiKey(connection) } }), + resolveAuth, + missingCredential, + credential: { + kind: 'api-key', + reference: connection => connection.apiKeyEnv, + configured: connection => credentialRefConfigured(ctx, connection.apiKeyEnv), + }, admit: (connection, model) => { refuseListedModel(model, connection.refusals.get(model)) }, discoverModels: async (provider) => { const connection = options() if (connection.listing === undefined) { - if (await presentApiKey(connection) === undefined) return [] + if (await resolveApiKey(connection) === undefined) return [] return connection.models.map(model => catalogModelInfo(provider, model)) } const view = await listings.view(connection.listing) diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index 27f55f005b..528d332e2d 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -44,3 +44,26 @@ it('reports malformed credentials during discovery', async () => { vi.unstubAllEnvs() } }) + +it('publishes the route API key for its consumers from the credential planes it reads itself', async () => { + vi.stubEnv('DEEPSEEK_API_KEY', 'fixture-api-key') + const ctx = new Context() + try { + await ctx.plugin(LlmRuntime) + await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) + const credential = ctx.llm.routeCredential('deepseek-official') + expect(credential).toMatchObject({ kind: 'api-key', baseURL: 'https://route.deepseek.test/anthropic', reference: 'DEEPSEEK_API_KEY' }) + const endpoint = 'https://route.deepseek.test/v1/tools/search' + await expect(credential!.configured(endpoint)).resolves.toBe(true) + await expect(credential!.resolve(endpoint)).resolves.toEqual({ headers: { 'x-api-key': 'fixture-api-key' }, value: 'fixture-api-key' }) + vi.stubEnv('DEEPSEEK_API_KEY', '') + await expect(credential!.configured(endpoint)).resolves.toBe(false) + await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() + vi.stubEnv('DEEPSEEK_API_KEY', 'invalid\nheader') + await expect(credential!.configured(endpoint)).resolves.toBe(true) + await expect(credential!.resolve(endpoint)).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) + } finally { + await ctx.fiber.dispose() + vi.unstubAllEnvs() + } +}) diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 18c1efe0dc..68db96e254 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: - en: d3f232309f4963ef - zh: 2e0ccd028de26f3e + en: 98b9a8d297095e32 + zh: b8f8eb46038214cb /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: 81bf213499f015ba zh: e9107ef322213e56 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 3c25fee26e..5333f68e3c 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -87,11 +87,11 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r ### Account credentials -`deepseek-official` resolves only its configured API-key reference. `deepseek-account` resolves only the stored grant from the [account service](../../credentials/deepseek-account/README.md), whose allowed `inferenceOrigin` defaults to `https://api.deepseek.com`. Neither route falls back to the other. Signing out removes the account grant and preserves API keys. +`deepseek-official` resolves only its configured API-key reference. `deepseek-account` resolves only the stored grant from the [account service](../../account/deepseek-account/README.md), whose allowed `inferenceOrigin` defaults to `https://api.deepseek.com`. Neither route falls back to the other. Signing out removes the account grant and preserves API keys. -Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account service owns HTTP 401 classification and credential invalidation; the transport passes failures to its callback. +Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account route owns HTTP 401 classification and the account service the credential invalidation; the transport passes failures to the credential's callback. -The [shared credential helpers](src/credential.ts) serve model routes and web providers without choosing request headers. `resolveDeepSeekApiKey(ctx, ref)` returns a normalized, validated key or `undefined`; an installed credentials service is authoritative, and only its absence enables launch-environment lookup. Store and key-format failures propagate. `deepSeekApiKeyConfigured(ctx, ref)` checks presence without reading stored key values. Account helpers delegate allowed-destination resolution and exact-token invalidation to the account service; invalidation contains storage failures so the original request error remains visible. +Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, and an optional failure callback, or `undefined` when none is configured. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.routeCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. ### Streaming with thinking and images diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 3d1b6beeb4..8a83625697 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -87,11 +87,11 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` ### 账号凭据 -`deepseek-official` 仅解析配置的 API Key 引用。`deepseek-account` 仅解析[账号服务](../../credentials/deepseek-account/README.zh.md)保存的授权,其允许的 `inferenceOrigin` 默认为 `https://api.deepseek.com`。两条路由均不回退到另一凭证。退出登录删除账号授权,保留 API Key。 +`deepseek-official` 仅解析配置的 API Key 引用。`deepseek-account` 仅解析[账号服务](../../account/deepseek-account/README.zh.md)保存的授权,其允许的 `inferenceOrigin` 默认为 `https://api.deepseek.com`。两条路由均不回退到另一凭证。退出登录删除账号授权,保留 API Key。 -Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号服务负责 HTTP 401 分类和凭据失效处理;传输层将错误交给其回调。 +Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -[共享凭据函数](src/credential.ts)为模型路由和 Web 提供方获取凭据,不决定请求头。`resolveDeepSeekApiKey(ctx, ref)` 返回规范化并校验后的密钥或 `undefined`;已安装的凭据服务具有权威性,仅在该服务缺席时读取启动环境。存储与密钥格式错误向上传播。`deepSeekApiKeyConfigured(ctx, ref)` 检查是否存在,不读取已存密钥值。账号函数将目标地址许可检查和精确 token 作废交给账号服务;作废时隔离存储失败,保留原请求错误。 +提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值以及可选的失败回调;未配置时返回 `undefined`。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 ### 带 thinking 与图片的流式调用 diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index a6129f26fd..0020cf5cde 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -1,7 +1,7 @@ /** Direct Messages transport with one cancellable lifecycle per model request. */ import { attributionHeaders, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, RouteCredential, StreamChunk } from '@deepseek-ai/dsh-llm' import type { DeepSeekLlmApiExtensionRequest, DeepSeekLlmApiJson } from '@deepseek-ai/dsh-deepseek-llm-api-extensions' import { idleWatchdog, timeoutOf } from '@deepseek-ai/dsh-timeout' import { modelInfo } from './model-info.ts' @@ -47,6 +47,23 @@ export class DeepSeekAdapter extends LlmAdapt if (entry === undefined) throw new LlmError(`DeepSeek model "${model}" has no declared image projection`, 'UNKNOWN_MODEL') return resolveRequestImageTarget(entry, image) } + override routeCredential(_provider: string): RouteCredential | undefined { + const publication = this.dependencies.credential + if (publication === undefined) return undefined + // One configuration generation serves the whole published object, as it does one model request. + const connection = this.dependencies.options() + const reference = publication.reference?.(connection) + return { + kind: publication.kind, + baseURL: connection.baseURL, + ...reference === undefined ? {} : { reference }, + configured: endpoint => publication.configured(connection, endpoint), + resolve: async (endpoint, signal) => { + signal?.throwIfAborted() + return await this.dependencies.resolveAuth(connection, endpoint) + }, + } + } override async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise { const connection = await this.connection(signal) this.dependencies.admit?.(connection, model) @@ -62,6 +79,11 @@ export class DeepSeekAdapter extends LlmAdapt return this.dependencies.connect?.(signal) ?? Promise.resolve(this.dependencies.options()) } + private missingCredential(connection: C, provider: string): LlmError { + return this.dependencies.missingCredential?.(connection, provider) + ?? new LlmError(`llm-deepseek: no credential for provider route "${provider}"`, 'MISSING_CREDENTIAL') + } + private async * generate(options: GenerateOptions, connection: C): AsyncGenerator { const consumer = new AbortController() const signal = options.signal === undefined ? consumer.signal : AbortSignal.any([consumer.signal, options.signal]) @@ -95,7 +117,8 @@ export class DeepSeekAdapter extends LlmAdapt const { messages, versions } = await prepareImages( options.messages, connection, options.model, this.dependencies.resolveAttachments?.(), this.imageAccess, signal, ) - const auth = await this.dependencies.resolveAuth(connection) + const auth = await this.dependencies.resolveAuth(connection, connection.baseURL) + if (auth === undefined) throw this.missingCredential(connection, options.provider) try { const files = new RequestFiles(this.files, { baseURL: connection.baseURL, headers: auth.headers, diff --git a/packages/llm/llm-deepseek/src/auth-headers.ts b/packages/llm/llm-deepseek/src/auth-headers.ts new file mode 100644 index 0000000000..e267691e81 --- /dev/null +++ b/packages/llm/llm-deepseek/src/auth-headers.ts @@ -0,0 +1,12 @@ +/** Deterministic serialization of credential headers for credential-scoped caches. @module dsh-llm-deepseek/auth-headers */ + +/** + * Serialize credential headers so caches scoped by credential digest the same + * credential to the same value whatever the header order. The result is hash + * input only: never persist or log it. + * @param headers - credential headers of one request. + * @returns a stable string representation of the headers. + */ +export function serializeAuthHeaders(headers: Readonly>): string { + return JSON.stringify(Object.entries(headers).sort(([left], [right]) => left.localeCompare(right))) +} diff --git a/packages/llm/llm-deepseek/src/credential.ts b/packages/llm/llm-deepseek/src/credential.ts deleted file mode 100644 index 0edcbb1107..0000000000 --- a/packages/llm/llm-deepseek/src/credential.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** Credential values shared by DeepSeek model and web providers; callers own protocol headers and missing-key errors. */ -import type { Context } from '@deepseek-ai/cordis' -import type { CredentialRef } from '@deepseek-ai/dsh-credentials' -import type {} from '@deepseek-ai/dsh-deepseek-account' -import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' - -/** - * Read and validate one API key. An installed credentials service is authoritative, including absence; - * only deployments without that service read the launch environment. Store and format failures propagate. - * @param ctx - context providing the credential and launch-environment services. - * @param ref - credential reference to resolve. - * @returns the validated key, or undefined when no key is configured. - */ -export async function resolveDeepSeekApiKey(ctx: Context, ref: CredentialRef): Promise { - const credentials = ctx.get('credentials') - if (credentials !== undefined) { - const hit = await credentials.resolve(ref) - return hit === undefined ? undefined : assertUsableApiKey(hit.value, 'llm-deepseek', ref) - } - const ambient = launchEnvironmentOf(ctx).get(ref) - return ambient === undefined || ambient.value.length === 0 ? undefined : assertUsableApiKey(ambient.value, 'llm-deepseek', ref) -} - -/** - * Check key presence without resolving a credential-store value or validating its format. Store failures propagate. - * @param ctx - context providing the credential and launch-environment services. - * @param ref - credential reference to inspect. - * @returns whether the authoritative credential source reports a configured key. - */ -export async function deepSeekApiKeyConfigured(ctx: Context, ref: CredentialRef): Promise { - const credentials = ctx.get('credentials') - return credentials === undefined - ? (launchEnvironmentOf(ctx).get(ref)?.value.length ?? 0) > 0 - : (await credentials.describe(ref)).configured -} - -/** - * Read an account token only for a destination allowed by the account service. Credential-store failures propagate. - * @param ctx - context providing the optional account service. - * @param endpoint - destination that would receive the token. - * @returns the token, or undefined without an allowed signed-in account. - */ -export async function resolveDeepSeekAccountToken(ctx: Context, endpoint: string): Promise { - return await ctx.get('deepseekAccount')?.resolveToken(endpoint) -} - -/** - * Invalidate the account token rejected by a request, without clearing a newer sign-in. Removal failure is contained - * so callers can report the original request failure; the account service owns in-memory invalidation and persistence. - * @param ctx - context providing the optional account service. - * @param token - exact token sent by the rejected request. - * @returns settlement after the invalidation attempt. - */ -export async function rejectDeepSeekAccountToken(ctx: Context, token: string): Promise { - try { await ctx.get('deepseekAccount')?.rejectToken(token) } - catch (_credentialRemovalFailed) { /* Storage failure cannot replace the request failure. */ } -} diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index da6f87654a..f89603c83c 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -6,6 +6,7 @@ import { DeepSeekFilesClient, isFilesQuotaError } from './files-api.ts' import type { DeepSeekFileId } from './file-id.ts' import { messagesApiRoot } from './messages-api.ts' import { deepSeekFileScope, DeepSeekUploadIndex } from './upload-index.ts' +import { serializeAuthHeaders } from './auth-headers.ts' import type { DeepSeekUploadRecord } from './upload-index.ts' /** Shared Files-store limit for each request image, including file-id references. */ @@ -47,10 +48,7 @@ interface SharedUpload { /** The Files resource's parent URL identifies the upload namespace. */ function fileScope(connection: DeepSeekFileConnection) { - return deepSeekFileScope( - messagesApiRoot(connection.baseURL), - JSON.stringify(Object.entries(connection.headers).sort(([left], [right]) => left.localeCompare(right))), - ) + return deepSeekFileScope(messagesApiRoot(connection.baseURL), serializeAuthHeaders(connection.headers)) } function abortReason(signal: AbortSignal): Error { diff --git a/packages/llm/llm-deepseek/src/host.ts b/packages/llm/llm-deepseek/src/host.ts index c9e89cad8e..202d9c2bef 100644 --- a/packages/llm/llm-deepseek/src/host.ts +++ b/packages/llm/llm-deepseek/src/host.ts @@ -8,6 +8,7 @@ import { getOrCreateAnonymousUserId, type AnonymousUserId } from '@deepseek-ai/d import { deepEqualJson } from '@deepseek-ai/dsh-util-values' import { DeepSeekAdapter } from './adapter.ts' import type { DeepSeekAdapterOptions, DeepSeekConnectionOptions } from './types.ts' +import { requestModelListing } from './listing.ts' import { ModelListingCache, type ListingCacheDependencies } from './listing-cache.ts' /** @@ -15,16 +16,17 @@ import { ModelListingCache, type ListingCacheDependencies } from './listing-cach * @param ctx - provider plugin lifetime. * @param owner - plugin name used in diagnostics. * @param provider - route whose catalog changes. - * @param dependencies - current configuration, credentials, and listing transport. + * @param dependencies - current configuration and credential headers; `load` defaults to the official `/models` request. * @returns the cache, disposed with the provider after its active work settles. */ export function createModelListingCache( ctx: Context, owner: string, provider: string, - dependencies: Pick, + dependencies: Pick & Partial>, ): ModelListingCache { const tag = `[${owner}]` const cache = new ModelListingCache({ ...dependencies, + load: dependencies.load ?? requestModelListing, now: () => Date.now(), // ACP reserves stdout for protocol messages, including during successful catalog loads. info: (message) => { console.error(tag, message) }, @@ -43,7 +45,7 @@ export function createModelListingCache( */ export function registerDeepSeekProvider( ctx: Context, provider: string, dependencies: Pick, - 'options' | 'resolveAuth' | 'providerName' | 'discoverModels' | 'connect' | 'admit'>): void { + 'options' | 'resolveAuth' | 'missingCredential' | 'credential' | 'providerName' | 'discoverModels' | 'connect' | 'admit'>): void { ctx.inject(['settings'], (child) => { child.effect(() => child.settings.configure({ auto: false }, ctx.fiber)) }) let userId: AnonymousUserId | undefined // These conditions repeat on every request of a route; log each first occurrence only. diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts index c3ca109a93..0474969f60 100644 --- a/packages/llm/llm-deepseek/src/index.ts +++ b/packages/llm/llm-deepseek/src/index.ts @@ -1,5 +1,4 @@ /** DeepSeek Messages transport, request configuration, and model capabilities. */ -export { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey } from './credential.ts' export { catalogModelFields, deepSeekConfigFields, Config, isBuiltInCatalog, plainOptions, resolveAdapterOptions, PUBLIC_BASE_URL } from './config.ts' export type { Options, ResolvedDeepSeekOptions } from './config.ts' export { @@ -16,7 +15,7 @@ export { DEFAULT_STREAM_IDLE_TIMEOUT_MS, } from './defaults.ts' export { DeepSeekAdapter } from './adapter.ts' -export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions } from './types.ts' +export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions, DeepSeekRouteCredentialOptions } from './types.ts' export { DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET, DEFAULT_MAX_IMAGES_PER_REQUEST, diff --git a/packages/llm/llm-deepseek/src/listing-cache.ts b/packages/llm/llm-deepseek/src/listing-cache.ts index 71173f509d..01c9a57da9 100644 --- a/packages/llm/llm-deepseek/src/listing-cache.ts +++ b/packages/llm/llm-deepseek/src/listing-cache.ts @@ -2,6 +2,7 @@ import { createHash } from 'node:crypto' import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { deepEqualJson } from '@deepseek-ai/dsh-util-values' +import { serializeAuthHeaders } from './auth-headers.ts' import type { ListingSettings } from './listing-config.ts' import { LISTING_TIMEOUT } from './listing.ts' import type { ModelListing } from './listing.ts' @@ -10,10 +11,10 @@ import type { ModelListing } from './listing.ts' export interface ListingCacheDependencies { /** Latest route configuration for automatic refresh; `undefined` stops following the listing. */ readonly settings: () => ListingSettings | undefined - /** The credential the route sends to `url`, or `undefined` when it has none. */ - readonly credential: (url: string) => Promise - /** Perform one listing request authenticated with `credential`; `signal` carries the {@link LISTING_TIMEOUT} request deadline. */ - readonly load: (url: string, credential: string, signal: AbortSignal) => Promise + /** Headers carrying the credential the route sends to `url`, or `undefined` when it has none. */ + readonly credential: (url: string) => Promise> | undefined> + /** Perform one listing request sending `headers`; `signal` carries the {@link LISTING_TIMEOUT} request deadline. */ + readonly load: (url: string, headers: Readonly>, signal: AbortSignal) => Promise /** Wall clock used for listing age. */ readonly now: () => number /** Report a loaded listing. */ @@ -80,14 +81,16 @@ export class ModelListingCache { * @returns the view after any first load of the scope settles. */ async view(settings: ListingSettings, signal?: AbortSignal): Promise { - const credential = await this.dependencies.credential(settings.url) + const headers = await this.dependencies.credential(settings.url) signal?.throwIfAborted() if (this.closed) return this.current() - const scope = credential === undefined ? undefined : `${settings.url}\n${createHash('sha256').update(credential).digest('hex')}` + const scope = headers === undefined + ? undefined + : `${settings.url}\n${createHash('sha256').update(serializeAuthHeaders(headers)).digest('hex')}` if (scope !== this.scope) this.rescope(scope) - if (credential !== undefined) { - if (this.settledAt === undefined) await abandonable(this.start(settings, credential), signal) - else if (this.dependencies.now() - this.settledAt >= settings.maxAgeMs) void this.start(settings, credential) + if (headers !== undefined) { + if (this.settledAt === undefined) await abandonable(this.start(settings, headers), signal) + else if (this.dependencies.now() - this.settledAt >= settings.maxAgeMs) void this.start(settings, headers) } return this.current() } @@ -120,7 +123,7 @@ export class ModelListingCache { this.generation += 1 } - private start(settings: ListingSettings, credential: string): Promise { + private start(settings: ListingSettings, headers: Readonly>): Promise { if (this.inflight !== undefined) return this.inflight clearTimeout(this.timer) this.generation += 1 @@ -128,7 +131,7 @@ export class ModelListingCache { const request = new AbortController() this.request = request const limit = deadline(request.signal, settings.timeoutMs, LISTING_TIMEOUT) - const run = this.dependencies.load(settings.url, credential, limit.signal) + const run = this.dependencies.load(settings.url, headers, limit.signal) .then((listing) => { if (generation !== this.generation) return const changed = !deepEqualJson(this.listing, listing) diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index c682bba792..a9f50b20a6 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -1,5 +1,8 @@ /** Model catalog and request-local dependencies for DeepSeek Messages. */ -import type { LlmModelInfo, ModelModality, SystemPromptUpdate, ToolUpdate, ResolvedRetryPolicy, ImageAttachmentAccess } from '@deepseek-ai/dsh-llm' +import type { + ImageAttachmentAccess, LlmCredentialKind, LlmError, LlmModelInfo, ModelModality, ResolvedRetryPolicy, RouteCredentialGrant, + SystemPromptUpdate, ToolUpdate, +} from '@deepseek-ai/dsh-llm' import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' import type { DeepSeekLlmApiExtensionRequest, PreparedDeepSeekLlmApiExtensions } from '@deepseek-ai/dsh-deepseek-llm-api-extensions' @@ -81,14 +84,30 @@ export interface DeepSeekConnectionOptions { retryPolicy: ResolvedRetryPolicy } -/** Authentication captured by the provider for one request and its file operations. */ -export interface DeepSeekRequestAuth { - /** Credential headers sent unchanged to the resolved endpoint. */ - headers: Readonly> +/** + * Authentication released for one request and its file operations: the route + * credential grant the provider plugin builds, plus the request-failure + * classification bound to that credential. + */ +export interface DeepSeekRequestAuth extends RouteCredentialGrant { /** Classify a failure using the captured credential; callback failure preserves the original error. */ onRequestError?: (error: unknown) => Promise } +/** + * What `routeCredential()` publishes about the route's credential beside the + * request-path hooks, so consumers outside the model request path share the + * route's credential without reading its configuration. + */ +export interface DeepSeekRouteCredentialOptions { + /** Kind of credential the route sends. */ + kind: LlmCredentialKind + /** Credential reference the route resolves, named by diagnostics; omission publishes none. */ + reference?: (connection: Connection) => string | undefined + /** Report whether a credential exists for `endpoint` without reading its value. */ + configured: (connection: Connection, endpoint: string) => Promise +} + /** Constructor options for {@link DeepSeekAdapter}: the operation-local resolution hooks the plugin owns. */ export interface DeepSeekAdapterOptions { /** Report unusable native Messages replay metadata without exposing content or signatures. */ @@ -111,8 +130,20 @@ export interface DeepSeekAdapterOptions Promise /** Refuse a model before any network I/O by throwing an `LlmError`; omission admits every model. */ admit?: (connection: Connection, model: string) => void - /** Resolve authentication from this request's connection snapshot; never re-read the endpoint. */ - resolveAuth: (connection: Connection) => Promise + /** + * Release authentication for `endpoint` from this request's connection + * snapshot, or `undefined` when the route has no credential for it; never + * re-read the endpoint. Model requests pass the connection's own base URL; + * `routeCredential()` consumers pass theirs. + */ + resolveAuth: (connection: Connection, endpoint: string) => Promise + /** + * The failure a model request reports when {@link resolveAuth} releases no + * credential for the route's own endpoint; omission reports `MISSING_CREDENTIAL`. + */ + missingCredential?: (connection: Connection, provider: string) => LlmError + /** Publish the route's credential through `routeCredential()`; omission publishes none. */ + credential?: DeepSeekRouteCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ resolveUserId: () => AnonymousUserId /** Resolve the current durable attachment service; absence rejects image input. */ diff --git a/packages/llm/llm-deepseek/tests/account-routing.spec.ts b/packages/llm/llm-deepseek/tests/account-routing.spec.ts index 4a6cd8ddb8..94d2361d0c 100644 --- a/packages/llm/llm-deepseek/tests/account-routing.spec.ts +++ b/packages/llm/llm-deepseek/tests/account-routing.spec.ts @@ -1,8 +1,7 @@ /** Account route cancellation uses the real loop, registry, and tool lifecycle. */ import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' import { afterEach, expect, it, vi } from 'vitest' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' -import { installAccountTaskCancellation } from '@deepseek-ai/dsh-deepseek-account/src/account-tasks.ts' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, LlmAdapter, type GenerateOptions, type StreamChunk, ToolCallId } from '@deepseek-ai/dsh-llm' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' @@ -33,7 +32,6 @@ function listingRequest(input: string | URL | Request): Response | undefined { async function harness() { const ctx = new Context() contexts.push(ctx) - installAccountTaskCancellation(ctx) for (const plugin of [ LlmRuntime, SessionStore, SessionProjectionRegistry, SystemPrompt, ToolRuntime, NativeToolExecutor, AgentRegistry, ]) { @@ -186,7 +184,7 @@ it('never borrows an account token for a missing API key', async () => { const ctx = new Context() contexts.push(ctx) const resolveToken = vi.fn(async (_url: string) => 'fixture-account-token') - ctx.provide('deepseekAccount', { resolveToken: (url: string): Promise => resolveToken(url) } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: url => resolveToken(url) })) await ctx.plugin(LlmRuntime) await ctx.plugin(DeepSeek, {}) await ctx.plugin(AccountProvider, {}) @@ -200,7 +198,7 @@ it('never borrows an account token for a missing API key', async () => { it('propagates account sign-out to the HTTP request signal', async () => { const ctx = await harness() - ctx.provide('deepseekAccount', { resolveToken: async (_url: string) => 'fixture-account-token' } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-account-token' })) const started = Promise.withResolvers() vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { const listed = listingRequest(url) @@ -254,7 +252,7 @@ it('lists each DeepSeek route only when its own credential is present', async () vi.stubGlobal('fetch', vi.fn((input: string | URL | Request) => Promise.resolve(listingRequest(input) ?? new Response(null, { status: 500 })))) const ctx = await harness() let token: string | undefined - ctx.provide('deepseekAccount', { resolveToken: async (url: string) => new URL(url).origin === 'https://api.deepseek.com' ? token : undefined } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: url => new URL(url).origin === 'https://api.deepseek.com' ? token : undefined })) expect(await ctx.llm.listModels('deepseek-account')).toEqual([]) expect(await ctx.llm.listModels('deepseek-official')).toEqual([]) token = 'fixture-account-token' @@ -269,7 +267,7 @@ it('lists each DeepSeek route only when its own credential is present', async () it('surfaces credential storage failures during catalog discovery', async () => { const ctx = await harness() - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => { throw new Error('storage unavailable') } } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => { throw new Error('storage unavailable') } })) await expect(ctx.llm.listModels('deepseek-account')).rejects.toThrow('storage unavailable') }) diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index 9629892f70..6981f6c039 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -1,7 +1,6 @@ /** HTTP lifecycle, routing and optional Cordis services under real composition. */ import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' -import { installAccountTaskCancellation } from '@deepseek-ai/dsh-deepseek-account/src/account-tasks.ts' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -28,6 +27,7 @@ import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import { DeepSeekAdapter } from '../src/adapter.ts' import { object } from '../src/replay.ts' import { DeepSeekFileStore } from '../src/file-store.ts' +import { resolveAdapterOptions } from '../src/config.ts' import * as Messages from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as AccountProvider from '@deepseek-ai/dsh-llm-deepseek-account' import { adapter, assemble, chunks, MODEL, options, prepareExtensions, server, sse, textEvents, user, sourceModuleLoader } from './helpers.ts' @@ -197,8 +197,8 @@ describe('direct Messages HTTP', () => { const prepare = vi.fn(async () => ({ fields: {}, accept })) const files = new DeepSeekFileStore() const llm = new DeepSeekAdapter({ - options: () => Messages.resolveAdapterOptions({ baseURL: source.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }), resolveUserId: () => 'test-user' as AnonymousUserId, + options: () => resolveAdapterOptions({ baseURL: source.url }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions: prepare, }) @@ -213,11 +213,11 @@ describe('direct Messages HTTP', () => { it('freezes endpoint and defaults for a prepared call while the next call sees new settings', async () => { const first = await endpoint(), second = await endpoint() - let config = Messages.resolveAdapterOptions({ baseURL: first.url, maxTokens: 10, models: [{ id: MODEL, systemPromptUpdate: 'in-history' }] }) + let config = resolveAdapterOptions({ baseURL: first.url, maxTokens: 10, models: [{ id: MODEL, systemPromptUpdate: 'in-history' }] }) const files = new DeepSeekFileStore() - const llm = new DeepSeekAdapter({ options: () => config, resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': snapshot.maxTokens === 10 ? 'first' : 'second' } }), resolveUserId: () => 'user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions }) + const llm = new DeepSeekAdapter({ options: () => config, resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': snapshot.maxTokens === 10 ? 'first' : 'second' }, value: snapshot.maxTokens === 10 ? 'first' : 'second' }), resolveUserId: () => 'user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions }) const prepared = await llm.prepareCall('deepseek-official', MODEL) - config = Messages.resolveAdapterOptions({ baseURL: second.url, maxTokens: 20 }) + config = resolveAdapterOptions({ baseURL: second.url, maxTokens: 20 }) expect(prepared.model.systemPromptUpdate).toBe('in-history') expect((await llm.resolveModel('deepseek-official', MODEL)).systemPromptUpdate).toBeUndefined() await chunks(prepared.stream(options())) @@ -275,8 +275,8 @@ describe('direct Messages HTTP', () => { it('preserves the transport failure when a provider error callback rejects', async () => { vi.stubGlobal('fetch', async () => new Response('Unauthorized', { status: 401 })) const llm = new DeepSeekAdapter({ - options: () => Messages.resolveAdapterOptions({}), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, + options: () => resolveAdapterOptions({}), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key', onRequestError: async () => { throw new Error('credential storage unavailable') }, }), resolveUserId: () => 'fixture-user' as import('@deepseek-ai/dsh-anonymous-user-id').AnonymousUserId, @@ -381,8 +381,7 @@ describe('Cordis provider composition', () => { response.end(body) }) const rejectToken = vi.fn(async (_token: string) => {}) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: (token: string): Promise => rejectToken(token) } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token', reject: rejectToken })) expect((await chunks(ctx.llm.stream(options({ provider })))).at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'error', failure: { code: provider === 'deepseek-account' ? 'ACCOUNT_TOKEN_INVALID' : 'AUTH' } }, }) @@ -397,8 +396,7 @@ describe('Cordis provider composition', () => { response.end('Unauthorized') }) const rejectToken = vi.fn(async (_token: string) => {}) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => token, - rejectToken: (value: string): Promise => rejectToken(value) } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => token, reject: rejectToken })) await chunks(ctx.llm.stream(options({ provider: 'deepseek-account' }))) expect(token).toBe('replacement-login') expect(rejectToken).toHaveBeenCalledExactlyOnceWith('first-login') @@ -409,9 +407,7 @@ describe('Cordis provider composition', () => { response.writeHead(401) response.end(JSON.stringify({ error: { message: 'Authentication Fails (invalid dsh token)' } })) }) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: async (_token: string): Promise => { ctx.emit('deepseek-account/signed-out') } } as DeepSeekAccount) - installAccountTaskCancellation(ctx) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token', reject: () => { ctx.emit('deepseek-account/signed-out') } })) const agent = await ctx.agentLoop.create(SessionId('inference-account-expiry'), { provider: 'deepseek-account', model: MODEL }) agent.followup(user('hello')) await agent.whenIdle() @@ -425,8 +421,7 @@ describe('Cordis provider composition', () => { response.writeHead(401) response.end(JSON.stringify({ error: { message: 'Authentication Fails (invalid dsh token)' } })) }) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: async (_token: string): Promise => { throw new Error('credential storage unavailable') } } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token', reject: () => { throw new Error('credential storage unavailable') } })) expect((await chunks(ctx.llm.stream(options({ provider: 'deepseek-account' })))).at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'error', failure: { code: 'ACCOUNT_TOKEN_INVALID' } }, }) @@ -444,8 +439,7 @@ describe('Cordis provider composition', () => { client_requirements: { 'deepseek-harness': { min_version: '99.0.0' } }, }, ] }) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: async (_token: string): Promise => {} } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token' })) expect((await ctx.llm.listModels('deepseek-account')).map(model => [model.id, model.name])).toEqual([['deepseek-flash', 'DeepSeek-V4.1-Flash']]) await expect(ctx.llm.prepareCall({ provider: 'deepseek-account', model: 'deepseek-v5' })) .rejects.toMatchObject({ code: 'CLIENT_UPGRADE_REQUIRED' }) @@ -459,8 +453,7 @@ describe('Cordis provider composition', () => { response.end(JSON.stringify({ error: { type: 'authentication_error', message: 'API key is invalid' } })) }) const rejectToken = vi.fn(async (_token: string) => {}) - ctx.provide('deepseekAccount', { resolveToken: async (_url: string): Promise => 'fixture-token', - rejectToken: (token: string): Promise => rejectToken(token) } as DeepSeekAccount) + ctx.provide('deepseekAccount', accountStub({ token: () => 'fixture-token', reject: rejectToken })) expect((await chunks(ctx.llm.stream(options({ provider: 'deepseek-account' })))).at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'error', failure: { code: 'AUTH' } }, }) @@ -637,7 +630,7 @@ describe('Cordis provider composition', () => { }) it('rejects invalid catalog context windows at the options resolver', () => { - expect(() => Messages.resolveAdapterOptions({ models: [{ id: 'invalid-window', contextWindow: 0 }] })).toThrow('contextWindow must be a positive integer') + expect(() => resolveAdapterOptions({ models: [{ id: 'invalid-window', contextWindow: 0 }] })).toThrow('contextWindow must be a positive integer') }) @@ -647,10 +640,8 @@ it.each([ ] as const)('selects account or API-key credentials from the actual endpoint %s', async (baseURL, expected) => { vi.stubEnv('DEEPSEEK_API_KEY', 'ambient-key') const { ctx } = await context() - // This consumer uses only resolveToken; the real provider owns origin validation in its own suite. - ctx.provide('deepseekAccount', { - resolveToken: (url: string) => Promise.resolve(url === 'https://api.deepseek.com' ? 'account-token' : undefined), - } as DeepSeekAccount) + // The stand-in releases the credential by exact destination; the real service owns origin validation in its own suite. + ctx.provide('deepseekAccount', accountStub({ token: url => url === 'https://api.deepseek.com' ? 'account-token' : undefined })) await ctx.plugin(LlmRuntime) await ctx.plugin(expected === 'account-token' ? AccountProvider : Messages, { baseURL }) const request = vi.fn((_input, init) => { diff --git a/packages/llm/llm-deepseek/tests/credential.spec.ts b/packages/llm/llm-deepseek/tests/credential.spec.ts deleted file mode 100644 index 6054a07c4f..0000000000 --- a/packages/llm/llm-deepseek/tests/credential.spec.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** Shared credential resolution and metadata-only readiness across DeepSeek consumers. */ -import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it, vi } from 'vitest' -import { credentialRef } from '@deepseek-ai/dsh-credentials' -import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' -import { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey } from '../src/credential.ts' - -const ref = credentialRef('TEST_DEEPSEEK_KEY') - -function context(value?: string): Context { - const ctx = new Context() - ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([ - { source: 'process', values: value === undefined ? {} : { [ref]: value } }, - ])) - return ctx -} - -describe('shared DeepSeek credentials', () => { - it.each([undefined, '', ' valid-key '])('reads the launch environment only without credentials: %j', async (value) => { - const ctx = context(value) - try { - await expect(resolveDeepSeekApiKey(ctx, ref)).resolves.toBe(value ? value.trim() : undefined) - await expect(deepSeekApiKeyConfigured(ctx, ref)).resolves.toBe(Boolean(value)) - } finally { await ctx.fiber.dispose() } - }) - - it('treats the installed service as authoritative and reads no value for configured', async () => { - const ctx = context('ambient-key') - const resolve = vi.fn(async () => undefined) - const describe = vi.fn(async () => ({ configured: false })) - ctx.provide('credentials', { resolve, describe } as never) - try { - await expect(deepSeekApiKeyConfigured(ctx, ref)).resolves.toBe(false) - expect(resolve).not.toHaveBeenCalled() - await expect(resolveDeepSeekApiKey(ctx, ref)).resolves.toBeUndefined() - expect(resolve).toHaveBeenCalledExactlyOnceWith(ref) - } finally { await ctx.fiber.dispose() } - }) - - it.each(['bad key', '非法密钥', 'bad\nkey', ' '])('rejects malformed environment keys without exposing the value: %j', async (value) => { - const ctx = context(value) - try { - await expect(resolveDeepSeekApiKey(ctx, ref)).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) - } finally { await ctx.fiber.dispose() } - }) - - it('validates and normalizes each stored key without caching it', async () => { - const ctx = context('ambient-key') - const resolve = vi.fn().mockResolvedValueOnce({ value: ' stored-key ' }).mockResolvedValueOnce({ value: 'bad key' }) - ctx.provide('credentials', { resolve } as never) - try { - await expect(resolveDeepSeekApiKey(ctx, ref)).resolves.toBe('stored-key') - await expect(resolveDeepSeekApiKey(ctx, ref)).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) - } finally { await ctx.fiber.dispose() } - }) - - it('delegates account destination checks and contains token-removal failures', async () => { - const ctx = context() - try { - await expect(resolveDeepSeekAccountToken(ctx, 'https://allowed.test')).resolves.toBeUndefined() - await expect(rejectDeepSeekAccountToken(ctx, 'old-token')).resolves.toBeUndefined() - const resolveToken = vi.fn(async () => 'account-token') - const rejectToken = vi.fn(async () => { throw new Error('storage failed') }) - ctx.provide('deepseekAccount', { resolveToken, rejectToken } as never) - await expect(resolveDeepSeekAccountToken(ctx, 'https://allowed.test')).resolves.toBe('account-token') - expect(resolveToken).toHaveBeenCalledExactlyOnceWith('https://allowed.test') - await expect(rejectDeepSeekAccountToken(ctx, 'old-token')).resolves.toBeUndefined() - expect(rejectToken).toHaveBeenCalledExactlyOnceWith('old-token') - } finally { await ctx.fiber.dispose() } - }) -}) diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index bb44326318..124830cb5b 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -39,7 +39,7 @@ function harness(config: Config = {}) { const prepare = vi.fn(prepareExtensions) const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions(Object.assign({ baseURL: 'https://gateway.example/custom' }, config)), - resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' } }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments, + resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments, resolveImageAccess: () => ({ readonlyPath: '/workspace/image.png' }), resolveFiles: () => files, prepareExtensions: prepare, }) return { adapter, ensureUploaded, invalidate, readImageRequest, prepare } diff --git a/packages/llm/llm-deepseek/tests/helpers.ts b/packages/llm/llm-deepseek/tests/helpers.ts index 77beea8f04..08af4080c5 100644 --- a/packages/llm/llm-deepseek/tests/helpers.ts +++ b/packages/llm/llm-deepseek/tests/helpers.ts @@ -45,7 +45,7 @@ export async function assemble(stream: AsyncIterable, model = MODEL } export function adapter(config: Config = {}, dependencies: Partial = {}) { const files = new DeepSeekFileStore() - return new DeepSeekAdapter({ options: () => resolveAdapterOptions(config), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions, ...dependencies }) + return new DeepSeekAdapter({ options: () => resolveAdapterOptions(config), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => undefined, resolveImageAccess: () => undefined, resolveFiles: () => files, prepareExtensions, ...dependencies }) } /** * Loopback Messages endpoint recording each model request. diff --git a/packages/llm/llm-deepseek/tests/listing-cache.spec.ts b/packages/llm/llm-deepseek/tests/listing-cache.spec.ts index cd6233745e..6b52e8bd8c 100644 --- a/packages/llm/llm-deepseek/tests/listing-cache.spec.ts +++ b/packages/llm/llm-deepseek/tests/listing-cache.spec.ts @@ -8,6 +8,11 @@ import type { ModelListing } from '../src/listing.ts' afterEach(() => { vi.useRealTimers() }) +/** Header the fixture route sends its credential under. */ +const TOKEN_HEADER = 'x-test-token' +const headersOf = (token: string | undefined): Readonly> | undefined => + token === undefined ? undefined : { [TOKEN_HEADER]: token } + const listing = (...ids: string[]): ModelListing => ({ skipped: 0, entries: ids.map(id => ({ id, requirement: { kind: 'none' }, capabilities: { usable: true, facts: { inputModalities: ['text'] } } })), @@ -16,20 +21,20 @@ const listing = (...ids: string[]): ModelListing => ({ function harness(timeoutMs = 60_000, honorsAbort = true) { let clock = 0 let token: string | undefined = 'token-a' - const loads: Array<{ token: string; signal: AbortSignal; settle: PromiseWithResolvers }> = [] + const loads: Array<{ token: string | undefined; signal: AbortSignal; settle: PromiseWithResolvers }> = [] const info = vi.fn() const warn = vi.fn() const changed = vi.fn() const settings: { -readonly [K in keyof ListingSettings]: ListingSettings[K] } = { url: 'https://api.example/models', timeoutMs, maxAgeMs: 100 } const resolveSettings = vi.fn<() => ListingSettings | undefined>(() => settings) - const resolveCredential = vi.fn(() => Promise.resolve(token)) + const resolveCredential = vi.fn(() => Promise.resolve(headersOf(token))) const cache = new ModelListingCache({ settings: resolveSettings, credential: resolveCredential, - load: (_url, value, signal) => { + load: (_url, headers, signal) => { const settle = Promise.withResolvers() if (honorsAbort) signal.addEventListener('abort', () => { settle.reject(signal.reason) }, { once: true }) - loads.push({ token: value, signal, settle }) + loads.push({ token: headers[TOKEN_HEADER], signal, settle }) return settle.promise }, now: () => clock, @@ -373,7 +378,7 @@ it('retains badges on credential lookup failures, reports the streak once, and r expect(catalog.current().listing).toEqual(badgedListing('New')) expect(changed).toHaveBeenCalledTimes(1) expect(warn).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('check listing configuration and credentials')) - resolveCredential.mockResolvedValue('token-a') + resolveCredential.mockResolvedValue(headersOf('token-a')) advance(100) await vi.advanceTimersByTimeAsync(100) loads[1]!.settle.resolve(badgedListing('Back')) @@ -389,7 +394,7 @@ it.each(['resolve', 'reject'] as const)('awaits a pending automatic credential l await flush() loads[0]!.settle.resolve(listing('a')) await first - const credential = Promise.withResolvers() + const credential = Promise.withResolvers> | undefined>() resolveCredential.mockReturnValue(credential.promise) advance(100) await vi.advanceTimersByTimeAsync(100) @@ -397,7 +402,7 @@ it.each(['resolve', 'reject'] as const)('awaits a pending automatic credential l const disposal = catalog.dispose().then(() => { disposed = true }) await flush() expect(disposed).toBe(false) - if (outcome === 'resolve') credential.resolve('token-a') + if (outcome === 'resolve') credential.resolve(headersOf('token-a')) else credential.reject(new Error('lookup failed')) await disposal expect(loads).toHaveLength(1) diff --git a/packages/llm/llm-deepseek/tests/prepared-call.spec.ts b/packages/llm/llm-deepseek/tests/prepared-call.spec.ts index a54647ef7e..f4c35237d8 100644 --- a/packages/llm/llm-deepseek/tests/prepared-call.spec.ts +++ b/packages/llm/llm-deepseek/tests/prepared-call.spec.ts @@ -2,7 +2,8 @@ import { afterEach, expect, it } from 'vitest' import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' import { DeepSeekAdapter } from '../src/index.ts' -import { Config, plainOptions, resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepseek-api-key' +import { Config } from '@deepseek-ai/dsh-llm-deepseek-api-key' +import { plainOptions, resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepseek-api-key/src/config.ts' import type { ResolvedDeepSeekOptions as DeepSeekConnectionOptions } from '@deepseek-ai/dsh-llm-deepseek-api-key' import { assemble, chunks, MODEL, options, server } from './helpers.ts' @@ -18,7 +19,7 @@ async function endpoint(...args: Parameters) { function adapter(connection: () => DeepSeekConnectionOptions) { return new DeepSeekAdapter({ options: connection, - resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': `key-for-${snapshot.apiKeyEnv}` } }), + resolveAuth: snapshot => Promise.resolve({ headers: { 'x-api-key': `key-for-${snapshot.apiKeyEnv}` }, value: `key-for-${snapshot.apiKeyEnv}` }), resolveUserId: () => '00000000-0000-4000-8000-000000000001' as AnonymousUserId, prepareExtensions: () => Promise.resolve({ fields: {}, accept: () => Promise.resolve() }), }) diff --git a/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts b/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts index 90a2d6f502..778cd5564b 100644 --- a/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts +++ b/packages/llm/llm-deepseek/tests/provider-hooks.spec.ts @@ -23,7 +23,7 @@ async function route(hooks: Pick) { inject: ['llm'], apply: (child: Context) => { registerDeepSeekProvider(child, 'fixture-route', { - options: () => endpoint(), resolveAuth: () => Promise.resolve({ headers: {} }), ...hooks, + options: () => endpoint(), resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key' }), ...hooks, }) }, }) @@ -59,7 +59,7 @@ it('refuses a model before a prepared call exists', async () => { it('refuses a model on a direct adapter stream', () => { const adapter = new DeepSeekAdapter({ options: () => endpoint(), - resolveAuth: () => Promise.resolve({ headers: {} }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'fixture-key' }, value: 'fixture-key' }), resolveUserId: () => 'fixture-user' as AnonymousUserId, prepareExtensions, admit: () => { throw new LlmError('blocked by fixture', 'MODEL_UNSUPPORTED') }, diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts new file mode 100644 index 0000000000..8176bc65aa --- /dev/null +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -0,0 +1,92 @@ +/** The adapter publishes a route credential only for providers that declare one, and refuses requests without a credential. */ +import { afterEach, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import LlmRuntime, { LlmError } from '@deepseek-ai/dsh-llm' +import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' +import { DeepSeekAdapter, registerDeepSeekProvider, resolveAdapterOptions } from '../src/index.ts' +import type { DeepSeekAdapterOptions, DeepSeekRequestAuth, ResolvedDeepSeekOptions } from '../src/index.ts' +import { chunks, options as request, prepareExtensions } from './helpers.ts' + +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + vi.unstubAllGlobals() +}) + +const BASE_URL = 'https://route.deepseek.test/anthropic' +const ALLOWED = 'https://route.deepseek.test/v1/tools/search' +const OTHER = 'https://route.deepseek.test/v1/tools/fetch' +const connection = () => resolveAdapterOptions({ baseURL: BASE_URL }) + +type Hooks = Partial> + +/** Mount the runtime and one fixture route whose credential hooks are `hooks`. */ +async function route(hooks: Hooks): Promise { + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + await ctx.plugin({ + name: 'fixture-route', + inject: ['llm'], + apply: (child: Context) => { + registerDeepSeekProvider(child, 'fixture-route', { options: connection, resolveAuth: () => Promise.resolve(undefined), ...hooks }) + }, + }) + return ctx +} + +/** A direct adapter without a credential, failing requests through `missingCredential` when given. */ +function adapterWithout(missingCredential?: DeepSeekAdapterOptions['missingCredential']): DeepSeekAdapter { + return new DeepSeekAdapter({ + options: connection, + resolveAuth: () => Promise.resolve(undefined), + resolveUserId: () => 'fixture-user' as AnonymousUserId, + prepareExtensions, + ...missingCredential === undefined ? {} : { missingCredential }, + }) +} + +it('publishes no credential for a provider that declares none', async () => { + const ctx = await route({}) + expect(ctx.llm.routeCredential('fixture-route')).toBeUndefined() +}) + +it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { + const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => + endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k' } : undefined) + const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) + const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) + const credential = ctx.llm.routeCredential('fixture-route') + expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' }) + await expect(credential!.configured(ALLOWED)).resolves.toBe(true) + await expect(credential!.configured(OTHER)).resolves.toBe(false) + await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) + await expect(credential!.resolve(OTHER)).resolves.toBeUndefined() + await expect(credential!.resolve(ALLOWED, AbortSignal.abort(new Error('caller left')))).rejects.toThrow('caller left') + expect(resolveAuth).toHaveBeenCalledTimes(2) + expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL]) +}) + +it('omits the reference of a credential kind without one', async () => { + const ctx = await route({ credential: { kind: 'account', configured: () => Promise.resolve(false) } }) + const credential = ctx.llm.routeCredential('fixture-route') + expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL }) + expect(credential).not.toHaveProperty('reference') +}) + +it('fails a request without a credential before any network I/O, with the default diagnostic', async () => { + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + await expect(chunks(adapterWithout().stream(request({ provider: 'fixture-route' })))).rejects.toMatchObject({ + code: 'MISSING_CREDENTIAL', message: 'llm-deepseek: no credential for provider route "fixture-route"', + }) + expect(fetchMock).not.toHaveBeenCalled() +}) + +it('fails a request without a credential with the provider\'s own diagnostic', async () => { + vi.stubGlobal('fetch', vi.fn()) + const missing = adapterWithout((_connection, provider) => new LlmError(`sign in for ${provider}`, 'ACCOUNT_SIGN_IN_REQUIRED')) + await expect(chunks(missing.stream(request({ provider: 'fixture-route' })))).rejects.toMatchObject({ + code: 'ACCOUNT_SIGN_IN_REQUIRED', message: 'sign in for fixture-route', + }) +}) diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index 3c4676ba0d..5dde3d3f9a 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -78,7 +78,7 @@ function adapterOf( const { apiKey, ...rest } = config return new DeepSeekAdapter({ options: () => resolveAdapterOptions({ ...rest }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': apiKey ?? 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': apiKey ?? 'k' }, value: apiKey ?? 'k' }), resolveUserId: () => TEST_USER_ID, resolveAttachments: () => attachments, ...files === undefined ? {} : { resolveFiles: () => files }, @@ -192,7 +192,7 @@ describe('request image target', () => { const attachments = {} as AttachmentStore const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ models: [{ id: 'vision', inputModalities: ['text', 'image'] }] }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, resolveAttachments: () => attachments, resolveImageAccess: (store, ref) => (store === attachments && ref === imageRef @@ -215,7 +215,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, prepareExtensions: prepareExtensions as never, }) @@ -230,7 +230,7 @@ describe('DeepSeekAdapter against a mock server', () => { const server = await mockServer([]) const base = { options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, } const failed = new DeepSeekAdapter({ @@ -259,7 +259,7 @@ describe('DeepSeekAdapter against a mock server', () => { let signalSeen: AbortSignal | undefined const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, prepareExtensions: ((request: { signal: AbortSignal }) => { signalSeen = request.signal @@ -324,7 +324,7 @@ describe('DeepSeekAdapter against a mock server', () => { const accept = vi.fn() const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, prepareExtensions: () => Promise.resolve({ fields: { dsh_test: 1 }, accept: async () => { accept() } }) as never, }) @@ -342,7 +342,7 @@ describe('DeepSeekAdapter against a mock server', () => { const unaccepted = vi.fn() const base = { options: () => resolveAdapterOptions({ baseURL: server.url }), - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), resolveUserId: () => TEST_USER_ID, prepareExtensions: () => Promise.resolve({ fields: { dsh_test: 1 }, @@ -1142,7 +1142,7 @@ describe('DeepSeekAdapter against a mock server', () => { 'rejects image input for text-only model %s before credentials, image reads, or fetch', async (model) => { const server = await mockServer([]) - const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' } })) + const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' })) const attachments = attachmentStoreOf(ref => Promise.resolve(requestImage(ref))) const resolveAttachments = vi.fn(() => attachments.store) const adapter = new DeepSeekAdapter({ @@ -1169,7 +1169,7 @@ describe('DeepSeekAdapter against a mock server', () => { it('rejects vision input without an attachment provider before credentials or fetch', async () => { const server = await mockServer([]) - const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' } })) + const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' })) const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions({ baseURL: server.url, @@ -2320,7 +2320,7 @@ describe('plugin registration and config', () => { it('resolves connection facts and the credential exactly once per stream call', async () => { const server = await mockServer([{ kind: 'sse', events: textEvents }]) const options = vi.fn(() => resolveAdapterOptions({ baseURL: server.url })) - const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'per-request-key' } })) + const resolveAuth = vi.fn(() => Promise.resolve({ headers: { 'x-api-key': 'per-request-key' }, value: 'per-request-key' })) const resolveUserId = vi.fn(() => TEST_USER_ID) const adapter = new DeepSeekAdapter({ options, resolveAuth, resolveUserId, prepareExtensions: noExtensions }) diff --git a/packages/llm/llm-deepseek/tsconfig.json b/packages/llm/llm-deepseek/tsconfig.json index 84c4ffe7a9..e307eab423 100644 --- a/packages/llm/llm-deepseek/tsconfig.json +++ b/packages/llm/llm-deepseek/tsconfig.json @@ -9,7 +9,7 @@ ], "references": [ { "path": "../../credentials/credentials" }, - { "path": "../../credentials/deepseek-account" }, + { "path": "../../account/deepseek-account" }, { "path": "../../../vendor/cosmokit" }, diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 2f4299d8cd..113c698e0d 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -22,6 +22,7 @@ import type { LlmResolvedModelInfo, LlmProviderInfo, ModelModality, + RouteCredential, StreamChunk, SystemPromptUpdate, ToolSchema, @@ -264,6 +265,19 @@ export abstract class LlmAdapter { return { width: image.width, height: image.height, maxBytes: image.bytes } } + /** + * Describe the credential one owned route currently sends, for consumers that + * call the same deployment outside the model request path, such as web + * providers that share a route's credential and endpoint. The default + * publishes none. Implementations answer from one configuration generation + * per call and may throw when that configuration does not resolve. + * @param _provider - a route passed to `registerAdapter()` for this instance. + * @returns the route's current credential, or `undefined` when the route publishes none. + */ + routeCredential(_provider: string): RouteCredential | undefined { + return undefined + } + /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -708,6 +722,19 @@ export class LlmRuntime extends TypertRemoteService { return this.registration(provider).adapter.imageRequestTarget(provider, model, image) } + /** + * Resolve the credential one registered route currently sends, through its + * owning adapter. An unregistered route answers `undefined` rather than + * throwing because callers ask about routes a conversation named earlier, + * which may no longer be mounted; a registered route whose configuration + * does not resolve propagates the adapter's failure. + * @param provider - provider route whose credential is wanted. + * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + */ + routeCredential(provider: string): RouteCredential | undefined { + return this.adapters.get(provider)?.adapter.routeCredential(provider) + } + /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 8a48b89895..53b0acb3e4 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -292,6 +292,87 @@ export interface LlmNativeAuth { oauth: boolean } +/** + * Merge-extensible vocabulary of the credential kinds a provider route sends. + * `api-key` is a provider key read from a credential reference or the launch + * environment; `account` is a grant obtained by signing in. An adapter that + * sends another kind declares it here. + */ +export interface LlmCredentialKindMap { + 'api-key': 'api-key' + account: 'account' +} + +/** Any declared credential kind. */ +export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap] + +/** + * One credential released for one destination. Host-only: it carries the + * secret, so it never crosses a Remote boundary and never enters a log. + */ +export interface RouteCredentialGrant { + /** + * Request headers carrying the credential as the route's own protocol + * expects it, such as `x-api-key` for an API key. Consumers speaking that + * protocol send them unchanged. + */ + readonly headers: Readonly> + /** + * The bare credential value, for destinations whose protocol renders it + * differently from {@link headers}, such as `Authorization: Bearer`. + */ + readonly value: string + /** + * Invalidate this exact credential after the destination rejected it with + * HTTP 401 so no later request resends it. Absent for kinds without + * invalidation. The owner contains storage failures: the caller reports the + * destination's rejection, never a failure of this call. + * @returns settlement after the invalidation attempt. + */ + reject?(): Promise +} + +/** + * The credential one registered provider route currently sends, answered by + * the route's owning adapter so that consumers read no provider configuration + * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * per call from one configuration generation; a caller keeps it for one + * operation only. + */ +export interface RouteCredential { + /** Kind of credential the route sends. */ + readonly kind: LlmCredentialKind + /** + * The route's current request base URL as its configuration resolves it, + * environment fallbacks included: the destination this credential is meant + * for. Consumers derive sibling endpoints of the same deployment from it. + */ + readonly baseURL: string + /** + * Credential reference the route resolves, for diagnostics that tell the user + * where to configure the credential; absent for kinds without a stored + * reference, such as sign-in grants. + */ + readonly reference?: string + /** + * Whether {@link resolve} would release a credential for `endpoint`, checked + * without reading the credential's value, validating it, or contacting the + * destination. Store failures reject. + * @param endpoint - absolute URL the credential would be sent to. + * @returns whether a credential is configured for that destination. + */ + configured(endpoint: string): Promise + /** + * Release the credential for `endpoint`, or `undefined` when none is + * configured or the destination may not receive it. The caller chooses the + * failure it reports for `undefined`. Store and format failures reject. + * @param endpoint - absolute URL the credential will be sent to. + * @param signal - cancellation for the lookup. + * @returns the released credential, or `undefined`. + */ + resolve(endpoint: string, signal?: AbortSignal): Promise +} + /** * One interrogation of a provider endpoint that configuration has not stored * yet. Configuration surfaces send the draft a user is still editing, so the diff --git a/packages/llm/llm/tests/topology.spec.ts b/packages/llm/llm/tests/topology.spec.ts index 98b1be4920..7eddb69b35 100644 --- a/packages/llm/llm/tests/topology.spec.ts +++ b/packages/llm/llm/tests/topology.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, LlmConfigurableProvider, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, LlmConfigurableProvider, RouteCredential, StreamChunk } from '@deepseek-ai/dsh-llm' class NoopAdapter extends LlmAdapter { @@ -339,3 +339,25 @@ describe('imageRequestPricing resolution', () => { expect(ctx.llm.imageRequestPricing('a', 'vision')).toBeUndefined() }) }) + +describe('routeCredential resolution', () => { + it('forwards to the owning adapter and answers undefined everywhere else', async () => { + const ctx = await setup() + const credential: RouteCredential = { + kind: 'api-key', baseURL: 'https://a.example/v1', + configured: () => Promise.resolve(true), + resolve: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), + } + class CredentialAdapter extends NoopAdapter { + override routeCredential(provider: string) { return provider === 'a' ? credential : undefined } + } + const dispose = ctx.llm.registerAdapter(['a', 'b'], new CredentialAdapter()) + ctx.llm.registerAdapter(['plain'], new NoopAdapter()) + expect(ctx.llm.routeCredential('a')).toBe(credential) + expect(ctx.llm.routeCredential('b')).toBeUndefined() + expect(ctx.llm.routeCredential('plain')).toBeUndefined() + expect(ctx.llm.routeCredential('missing')).toBeUndefined() + dispose() + expect(ctx.llm.routeCredential('a')).toBeUndefined() + }) +}) diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 489d3c98ce..0f1a47d350 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -4,6 +4,12 @@ This file is GENERATED from workspace manifests (`scripts/gen-plugin-packages.ts Every package below exports a Cordis plugin that a bundle patch can name in a Loader row. `Config` marks packages whose row accepts a `config` mapping; read the mounted schema from `Config.listConfigs` through `cordis_inspect_query` (filter by `name`, then query the `entry` id) when available, otherwise from the package README. Packages under `experimental` are pre-stable. +## account + +| Package | Config | Description | +|---|---|---| +| `@deepseek-ai/dsh-deepseek-account` | yes | Sign in to DeepSeek and manage account credentials and notifications | + ## acp | Package | Config | Description | @@ -171,7 +177,6 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo |---|---|---| | `@deepseek-ai/dsh-authorization` | no | Authorization seam (ctx.authorization): plugin-owned flows that obtain a credential through a conversation with the human | | `@deepseek-ai/dsh-credentials-local` | yes | File-backed credentials provider ($DSH_HOME/.env under the live process environment) for the DeepSeek Harness | -| `@deepseek-ai/dsh-deepseek-account` | yes | Sign in to DeepSeek and manage account credentials and notifications | ## deliverables diff --git a/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts b/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts index 7c031ca554..260215b12d 100644 --- a/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts +++ b/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts @@ -38,7 +38,7 @@ it('continues the parent through default Messages after a reasoning-bearing cont const connection = resolveAdapterOptions({ baseURL: http.url }) const adapter = new DeepSeekAdapter({ options: () => connection, - resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' } }), + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => '00000000-0000-4000-8000-000000000001' as AnonymousUserId, prepareExtensions: () => Promise.resolve({ fields: {}, accept: () => Promise.resolve() }), }) diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index 5fcfc042a3..42582881ec 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -18,14 +18,14 @@ en: 673ba23a4e608cf2 zh: 042afa607aaf4335 /deepseek-ai-dsh-web-deepseek-api/use-this-package/authentication: - en: b25cbe2a7894c03e - zh: db47f20dffe77a30 + en: 8923728d77eb1256 + zh: 85d1b8408cf1f325 /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: 71549e32f0a69c81 - zh: 9cafbeb60bdf0114 + en: 597dab3fe52fa59d + zh: 4370d01d5a58f2f9 /deepseek-ai-dsh-web-deepseek-api/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -54,8 +54,8 @@ en: 14f9af39f3be4fac zh: 3c7139fba0f17862 /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work: - en: 689b26b5f3af8861 - zh: 02cc62856a83cf48 + en: 3880e7c032129fb7 + zh: ad1450509e3473ab /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md index 63a945d4a4..a653aadad9 100644 --- a/packages/web/web-deepseek-api/README.md +++ b/packages/web/web-deepseek-api/README.md @@ -59,16 +59,16 @@ 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 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 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. +- **Account credential.** The operation sends the credential `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. With the `deepseek-account` model route mounted, the endpoint is under the origin of the base URL that route publishes through `ctx.llm.routeCredential`; without that route, it is under the origin `DEEPSEEK_BASE_URL` names, `https://api.deepseek.com` by default. No sign-in or no account service means no credential. A failed credential read fails the operation without trying another credential. A mounted route whose settings do not resolve, or a `DEEPSEEK_BASE_URL` that is not an HTTP(S) URL without credentials, fails the operation before the credential is read when the operation reaches this source. +- **API key.** With the `deepseek-official` model route mounted, the operation sends the key that route publishes through `ctx.llm.routeCredential`, read under the route's `apiKeyEnv` (`DEEPSEEK_API_KEY` by default), as `Authorization: Bearer` to the origin of the route's base URL. Without that route, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. A mounted route whose settings do not resolve fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`. +- **`auto` billing** follows the conversation. On the `deepseek-account` route it sends the account credential, and without one the API key; without the account route, only the API key. On the `deepseek-official` route it sends only the API key. On any other route or outside a Session it sends the API key, and without a key the account credential; without a key, a mounted account route whose settings do not resolve fails the operation. +- **`account` billing** sends only the account credential on every route, and **`api-key` billing** only the API key; neither falls back to the other credential. Without a credential, the operation fails with a diagnostic for its billing that names the missing sign-in or the Models page and the key reference, and the `*Billing` field on the Web search and fetch settings page. -References use the [shared DeepSeek credential helpers](../../llm/llm-deepseek/README.md#account-credentials): `ctx.credentials` is authoritative, with launch-environment lookup only when that service is absent. Route and own keys receive the same whitespace normalization and format validation as model requests; malformed keys fail before dispatch. +Keys the operation reads itself, `DEEPSEEK_API_KEY` without the API-key route and the own `*ApiKeyEnv`, go through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): `ctx.credentials` is authoritative, with launch-environment lookup only when that service is absent. Route keys and own keys receive the same whitespace normalization and format validation as model requests; malformed keys fail before dispatch. -Each provider's `ready()` answers whether its next operation for that route has a credential, in the order its billing resolves them: a non-empty account token, or a key that `ctx.credentials.describe` reports configured (without that service, the launch environment must carry it). A failed account-token or credential-store read, or a needed route entry whose settings do not resolve, answers false. While these providers are selected, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and `web_fetch` with their prompt guidance from each request for which they answer false. Only presence is checked: a wrong key counts as ready and fails each call. +Each provider's `ready()` answers whether its next operation for that route has a credential, in the order its billing resolves them: a route credential its route reports configured for the endpoint, an account credential the account service releases for the endpoint, or a key that `ctx.credentials.describe` reports configured (without that service, the launch environment must carry it). A failed credential or credential-store read, or a needed route whose settings do not resolve, answers false. While these providers are selected, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and `web_fetch` with their prompt guidance from each request for which they answer false. Only presence is checked: a wrong key counts as ready and fails each call. ### Results and failures @@ -84,7 +84,7 @@ An unparseable own base URL makes that capability's provider unavailable; and a
Implementation internals — click to expand -The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the 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. +The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the credentials the mounted DeepSeek model routes publish through `ctx.llm.routeCredential` 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. @@ -132,7 +132,7 @@ A returning or removed web tool changes the declared tools as [`dsh-tool-web`](. - API query and URL constraints are enforced by the remote service. An unresolvable Fetch target returned HTTP 500 rather than the documented 404 on 2026-10-16, and its failure carries the same endpoint guidance as an endpoint failure. Fetch exposes neither the target status nor the final redirect URL, so results report HTTP 200 and the requested URL; the provider discards the API's page title. - `available()` cannot query asynchronous credential stores; `ready()` does, so model steps withhold the tools when the store lacks the key. A direct `ctx.web.search()` or `ctx.web.fetch()` call can still fail with a missing-credential error. - Search pacing limits send times within one plugin instance. Other processes and clients on the same account share the account-wide 5 QPS limit without coordination, and network jitter can still bunch arrivals; an HTTP 429 fails that search, and `dsh-tool-web` then fails the whole multi-query call. Fetch is not paced, so parallel `web_fetch` calls can exceed the Fetch limit. -- Route endpoints and keys follow only the Loader entries of `@deepseek-ai/dsh-llm-deepseek-api-key` and `@deepseek-ai/dsh-llm-deepseek-account` at the entry root; another package registering the same provider id, such as a test replay adapter, counts as no route, so its conversations use `DEEPSEEK_API_KEY` and the official base. +- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.routeCredential`; an adapter that publishes no credential, such as a test replay adapter, counts as no route, so its conversations use `DEEPSEEK_API_KEY` and the official base. ### Dev Note diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index 8c5a5cc2f6..c59eeb474a 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -59,16 +59,16 @@ 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)下。没有登录、没有账号服务或令牌为空都算没有令牌。账号令牌读取失败时操作失败,不再尝试其他凭据。条目活动但其设置被该路由自身的解析器拒绝时,操作在轮到该来源时失败,不读取该账号令牌。 -- **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 密钥,没有密钥时发送账号令牌;没有密钥且已挂载的账号路由条目设置无法解析时,操作失败。 -- **`account` 计费**在任何路由上只发送账号令牌,**`api-key` 计费**只发送 API 密钥;两者都不回退到另一种凭据。 +- **账号凭据。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点释放的凭据;2026-10-16 公网 Search 与 Fetch 路由已接受该凭据。挂载了 `deepseek-account` 模型路由时,端点位于该路由通过 `ctx.llm.routeCredential` 发布的基础地址的 origin 下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 所指 origin 下,默认 `https://api.deepseek.com`。没有登录或没有账号服务都算没有凭据。凭据读取失败时操作失败,不再尝试其他凭据。已挂载路由的设置无法解析,或 `DEEPSEEK_BASE_URL` 不是不含凭据的 HTTP(S) URL 时,操作在轮到该来源时于读取凭据前失败。 +- **API 密钥。** 挂载了 `deepseek-official` 模型路由时,操作以 `Authorization: Bearer` 把该路由通过 `ctx.llm.routeCredential` 发布的密钥(按路由的 `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 密钥,没有密钥时发送账号凭据;没有密钥且已挂载的账号路由设置无法解析时,操作失败。 +- **`account` 计费**在任何路由上只发送账号凭据,**`api-key` 计费**只发送 API 密钥;两者都不回退到另一种凭据。 没有凭据时,操作失败,诊断信息按计费方式点名缺少的登录或模型页面与密钥引用,以及网页搜索与获取设置页上的 `*Billing` 字段。 -引用使用[共享 DeepSeek 凭据函数](../../llm/llm-deepseek/README.zh.md#account-credentials):`ctx.credentials` 具有权威性,仅在该服务缺席时读取启动环境。路由密钥与单独配置的密钥均接受与模型请求相同的首尾空白规范化和格式校验;格式错误在发送请求前失败。 +操作自行读取的密钥——没有 API 密钥路由时的 `DEEPSEEK_API_KEY` 和单独配置的 `*ApiKeyEnv`——通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:`ctx.credentials` 具有权威性,仅在该服务缺席时读取启动环境。路由密钥与单独配置的密钥均接受与模型请求相同的首尾空白规范化和格式校验;格式错误在发送请求前失败。 -每个提供者的 `ready()` 按其计费方式的解析顺序回答其在该路由上的下一次操作是否有凭据:非空账号令牌,或 `ctx.credentials.describe` 报告已配置的密钥(没有该服务时,启动环境必须包含它)。账号令牌或凭据存储读取失败,或所需路由条目的设置无法解析时,回答 false。这两个提供者被选中时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它们回答 false 的每个请求中撤下 `web_search` 与 `web_fetch` 及其提示词指引。只检查是否存在:错误的密钥仍算就绪,并使每次调用失败。 +每个提供者的 `ready()` 按其计费方式的解析顺序回答其在该路由上的下一次操作是否有凭据:路由报告为该端点已配置的路由凭据、账号服务为该端点释放的账号凭据,或 `ctx.credentials.describe` 报告已配置的密钥(没有该服务时,启动环境必须包含它)。凭据或凭据存储读取失败,或所需路由的设置无法解析时,回答 false。这两个提供者被选中时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它们回答 false 的每个请求中撤下 `web_search` 与 `web_fetch` 及其提示词指引。只检查是否存在:错误的密钥仍算就绪,并使每次调用失败。 ### 结果与失败 @@ -84,7 +84,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的
实现细节 — 点击展开 -[插件](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` 会话事件。工具调用和结果仍按常规记录到会话。 +[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由,以及已挂载的 DeepSeek 模型路由通过 `ctx.llm.routeCredential` 发布的凭据转换为该操作的有序凭据,每个凭据都绑定其发往的 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)。 @@ -132,7 +132,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 - 查询和 URL 约束由远端服务执行。2026-10-16 抓取无法解析的目标域名时返回 HTTP 500,而非文档所述的 404,其失败信息与端点失败附带相同的端点指引。Fetch 既不暴露目标状态,也不暴露最终重定向 URL,因此结果报告 HTTP 200 和请求 URL;提供者丢弃 API 返回的页面标题。 - `available()` 无法查询异步凭据存储;`ready()` 可以,因此凭据存储缺少密钥时,模型步骤会撤下这两个工具。直接调用 `ctx.web.search()` 或 `ctx.web.fetch()` 仍可能因凭据缺失失败。 - Search 限速只约束单个插件实例内的发送时间。同一账号下的其他进程和客户端共享账号级 5 QPS 限制,彼此不协调,网络抖动也可能使请求集中到达;HTTP 429 会使该次搜索失败,随后 `dsh-tool-web` 会使整个多查询调用失败。Fetch 不限速,因此并行的 `web_fetch` 调用可能超过 Fetch 限制。 -- 路由端点与密钥只认入口根部的 `@deepseek-ai/dsh-llm-deepseek-api-key` 与 `@deepseek-ai/dsh-llm-deepseek-account` Loader 条目;以相同提供方 id 注册的其他包(例如测试回放适配器)视为没有路由,其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址。 +- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.routeCredential` 发布的内容;不发布凭据的适配器(例如测试回放适配器)视为没有路由,其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址。 ### 开发备注 diff --git a/packages/web/web-deepseek-api/package.json b/packages/web/web-deepseek-api/package.json index 1c9209b89c..ed155bec20 100644 --- a/packages/web/web-deepseek-api/package.json +++ b/packages/web/web-deepseek-api/package.json @@ -32,39 +32,33 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-web": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*" + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-web": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-http-proxy": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", - "@deepseek-ai/dsh-web": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-http-proxy": "workspace:*", - "@deepseek-ai/cordis-plugin-loader": "workspace:~", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-app-boot": "workspace:*" + "@deepseek-ai/dsh-web": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-deepseek-account": { diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 555bab178b..0b610ce7ab 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -1,36 +1,28 @@ /** - * Register the DeepSeek Search and Fetch APIs in `ctx.web` as `deepseek-search-api` - * and `deepseek-fetch-api`. Each operation is one direct API request without an - * auxiliary model request. `web.searchProvider` and `web.fetchProvider` select them. Each capability's billing setting - * chooses its credential. `auto` follows the conversation: a Session whose latest model request used the - * `deepseek-account` route sends the account token to that route's origin and otherwise the API key; one on the - * `deepseek-official` route sends the API key; any other operation sends the API key and, without a key, the signed-in - * account's token. `account` sends only the account token and `api-key` only the API key. The API key is that of the - * DeepSeek API-key route, sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base without that route. The - * account token goes to the account route's origin, or outside an account conversation without that route to the origin - * of its default base URL. An operation that needs a mounted route whose settings do not resolve fails instead of - * changing its endpoint or credential. A capability with its own `*BaseURL` or `*ApiKeyEnv` uses only that endpoint and - * key instead, whatever its billing + * Register the DeepSeek Search and Fetch APIs in `ctx.web` as `deepseek-search-api` and `deepseek-fetch-api`. Each + * operation is one direct API request without an auxiliary model request. `web.searchProvider` and `web.fetchProvider` + * select them. Each capability's billing setting chooses its credential. `auto` follows the conversation: a Session + * whose latest model request used the `deepseek-account` route sends the account credential to that route's origin and + * otherwise the API key; one on the `deepseek-official` route sends the API key; any other operation sends the API key + * and, without a key, the signed-in account's credential. `account` sends only the account credential and `api-key` + * only the API key. Each mounted DeepSeek model route publishes its credential and base URL through + * `ctx.llm.routeCredential()`: the API key is that of the `deepseek-official` route, sent to its origin, or + * `DEEPSEEK_API_KEY` sent to the official base without that route; the account credential is that of the + * `deepseek-account` route, sent to its origin, or outside an account conversation without that route the signed-in + * account's credential sent to the origin `DEEPSEEK_BASE_URL` names, by default the official one. An operation that + * needs a mounted route whose settings do not resolve fails instead of changing its endpoint or credential. A capability + * with its own `*BaseURL` or `*ApiKeyEnv` uses only that endpoint and key instead, whatever its billing * ([rationale](../../../../.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md#credential-resolution)). * Both providers report themselves not ready when their next operation would have no credential. * @module @deepseek-ai/dsh-web-deepseek-api */ -import { FiberState, type Context, type Volatile } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/cordis-plugin-loader' +import type { Context, Volatile } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' -import { credentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' +import { credentialRef, credentialRefConfigured, resolveCredentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' +import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import type {} from '@deepseek-ai/dsh-llm' -import { - deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey, -} from '@deepseek-ai/dsh-llm-deepseek' -import { - plainAccountOptions, resolveAccountOptions, type Config as AccountRouteConfig, -} from '@deepseek-ai/dsh-llm-deepseek-account' -import { - plainOptions as plainOfficialOptions, resolveAdapterOptions as resolveOfficialOptions, type Config as OfficialRouteConfig, -} from '@deepseek-ai/dsh-llm-deepseek-api-key' +import { assertUsableApiKey, type RouteCredential } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider } from './fetch.ts' @@ -114,9 +106,6 @@ type Capability = 'search' | 'fetch' /** Credential choice of one capability without its own endpoint settings. */ type Billing = Config['searchBilling'] extends Volatile ? B : never -/** Model route whose settings an operation can depend on. */ -type RouteName = keyof typeof ROUTE_PACKAGES - /** * Rule that ordered an operation's credentials: `auto` billing in a conversation on the account route, on the API-key * route, or anywhere else, or an explicit billing. @@ -135,11 +124,14 @@ const ACCOUNT_PROVIDER = 'deepseek-account' /** Provider id of the DeepSeek API-key route. */ const OFFICIAL_PROVIDER = 'deepseek-official' -/** Loader package that registers each model route. */ -const ROUTE_PACKAGES = { - [OFFICIAL_PROVIDER]: '@deepseek-ai/dsh-llm-deepseek-api-key', - [ACCOUNT_PROVIDER]: '@deepseek-ai/dsh-llm-deepseek-account', -} as const +/** Model route whose published credential an operation can send. */ +type RouteName = typeof ACCOUNT_PROVIDER | typeof OFFICIAL_PROVIDER + +/** + * Launch-environment variable naming the DeepSeek deployment the model routes default to. Without the account route, + * its origin receives the signed-in account's credential. + */ +const DEEPSEEK_BASE_URL_ENV = 'DEEPSEEK_BASE_URL' /** Display names, configuration prefix, and operation path of each capability. */ const CAPABILITY = { @@ -203,8 +195,8 @@ export function apply(ctx: Context, config: Config): void { /** * Resolve the ordered credentials and endpoint guidance of one capability without reading credential values. Route - * endpoints use the origin of the route's resolved Messages base URL with `/v1/tools`. - * @param ctx - context with the model, loader, credential, and account services. + * endpoints use the origin of the route's published base URL with `/v1/tools`. + * @param ctx - context with the model, 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. @@ -233,85 +225,133 @@ function resolveTarget( : llmProvider === ACCOUNT_PROVIDER ? 'account-conversation' : llmProvider === OFFICIAL_PROVIDER ? 'official-conversation' : 'other-conversation' 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] : []) + const ref: string = sources.flatMap(keyReference)[0] ?? DEEPSEEK_API_KEY return { guidance: guidance(false), auth: { sources, missingCredentialMessage: missingMessage(capability, rule, ref) } } } /** * The credentials one rule tries, in order. - * @param ctx - context with the model, loader, credential, and account services. + * @param ctx - context with the model, credential, and account services. * @param capability - the capability whose diagnostics misconfigured sources name. * @param rule - the rule. * @returns the sources; the account source is absent in an account conversation without a mounted account route. */ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeekWebAuthSource[] { - const accountConfig = routeConfig(ctx, ACCOUNT_PROVIDER) as AccountRouteConfig | undefined switch (rule) { - case 'account-conversation': return accountConfig === undefined - ? [officialSource(ctx, capability)] : [accountSource(ctx, capability, accountConfig), officialSource(ctx, capability)] + case 'account-conversation': { + const account = routeSource(ctx, capability, ACCOUNT_PROVIDER) + return account === undefined ? [officialSource(ctx, capability)] : [account, officialSource(ctx, capability)] + } case 'official-conversation': case 'api-key': return [officialSource(ctx, capability)] - case 'other-conversation': return [officialSource(ctx, capability), accountSource(ctx, capability, accountConfig)] - case 'account': return [accountSource(ctx, capability, accountConfig)] + case 'other-conversation': return [officialSource(ctx, capability), accountSource(ctx, capability)] + case 'account': return [accountSource(ctx, capability)] /* v8 ignore next -- the switch is exhaustive. */ default: return assertNever(rule) } } /** - * The 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. + * The credential a mounted model route publishes, sent to the Search and Fetch APIs under the origin of the route's + * base URL. + * @param ctx - context with the optional model service. + * @param capability - the capability whose diagnostics a misconfigured source names. + * @param provider - the route. + * @returns the source; undefined when no mounted route publishes a credential as `provider`; a misconfigured source + * when the route's settings do not resolve. */ -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) +function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined { + let credential: RouteCredential | undefined + try { credential = ctx.get('llm')?.routeCredential(provider) } + catch (error: unknown) { return misconfigured(capability, provider, error) } + return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } } /** - * 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. + * The API key of the DeepSeek API-key route sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base + * without that route. + * @returns the source, or a misconfigured source when the route's settings do not resolve. */ -function 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 { - kind: 'account', baseURL: toolsBase(baseURL), - resolveToken: endpoint => resolveDeepSeekAccountToken(ctx, endpoint), - rejectToken: token => rejectDeepSeekAccountToken(ctx, token), - } +function officialSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource { + return routeSource(ctx, capability, OFFICIAL_PROVIDER) ?? apiKeySource(ctx, DEEPSEEK_WEB_API_BASE_URL, DEEPSEEK_API_KEY) } -/** The key under `ref`, read through the shared DeepSeek credential helpers, sent to `baseURL`. */ +/** + * The account credential of the DeepSeek account route sent to its origin, or without that route the signed-in + * account's credential sent to the origin `DEEPSEEK_BASE_URL` names, by default the official one. The account service + * releases its credential only for destinations it allows. + * @returns the source, or a misconfigured source when the route's settings or `DEEPSEEK_BASE_URL` do not resolve. + */ +function accountSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource { + const route = routeSource(ctx, capability, ACCOUNT_PROVIDER) + if (route !== undefined) return route + const configured = nonEmpty(launchEnvironmentOf(ctx).get(DEEPSEEK_BASE_URL_ENV)?.value) + let baseURL = DEEPSEEK_WEB_API_BASE_URL + if (configured !== undefined) { + try { baseURL = toolsBase(deploymentURL(configured)) } + catch (error: unknown) { return misconfiguredDeployment(capability, error) } + } + return { kind: 'route', baseURL, credential: { + kind: 'account', + configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined, + resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined), + } } +} + +/** The key under `ref`, read from the credentials service or the launch environment, sent to `baseURL`. */ function apiKeySource(ctx: Context, baseURL: string, ref: CredentialRef): DeepSeekWebAuthSource { return { kind: 'api-key', baseURL, key: { - ref, configured: () => deepSeekApiKeyConfigured(ctx, ref), resolve: () => resolveDeepSeekApiKey(ctx, ref), + ref, + configured: () => credentialRefConfigured(ctx, ref), + resolve: async () => { + const value = await resolveCredentialRef(ctx, ref) + return value === undefined ? undefined : assertUsableApiKey(value, name, ref) + }, } } } +/** The credential reference an API-key source names in missing-credential diagnostics. */ +function keyReference(source: DeepSeekWebAuthSource): string[] { + switch (source.kind) { + case 'api-key': return [source.key.ref] + case 'route': return source.credential.kind === 'api-key' && source.credential.reference !== undefined ? [source.credential.reference] : [] + case 'misconfigured': return [] + /* v8 ignore next -- the switch is exhaustive. */ + default: return assertNever(source) + } +} + /** * The source of a credential 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. + * @param error - the route's failure. * @returns the source whose diagnostic names the route and both recoveries. */ function misconfigured(capability: Capability, route: RouteName, error: unknown): DeepSeekWebAuthSource { - const { 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.` } + return unresolvedSource(capability, `${credential} to the origin of the ${provider}, and that provider's settings do not resolve`, + error, 'correct that provider\'s settings on the Models page or in the deployment configuration') +} + +/** + * The source of the signed-in account's credential when `DEEPSEEK_BASE_URL` is not an HTTP(S) URL. + * @param capability - the capability that stops. + * @param error - the URL failure. + * @returns the source whose diagnostic names the variable and both recoveries. + */ +function misconfiguredDeployment(capability: Capability, error: unknown): DeepSeekWebAuthSource { + return unresolvedSource(capability, `the DeepSeek account sign-in to the origin of ${DEEPSEEK_BASE_URL_ENV}, and that value does not resolve`, + error, `correct ${DEEPSEEK_BASE_URL_ENV} in the launching environment`) +} + +/** A misconfigured source whose diagnostic names what the operation sends where, the failure, and both recoveries. */ +function unresolvedSource(capability: Capability, destination: string, error: unknown, recovery: string): DeepSeekWebAuthSource { + const { subject, prefix } = CAPABILITY[capability] + return { kind: 'misconfigured', message: `DeepSeek ${subject} API sends ${destination}: ${errorMessage(error)}. ${subject} did not` + + ` send the request. Guide the user to ${recovery}, or to set ${name}.${prefix}BaseURL and ${name}.${prefix}ApiKeyEnv so` + + ` ${subject} uses its own endpoint.` } } /** @@ -321,7 +361,7 @@ function misconfigured(capability: Capability, route: RouteName, error: unknown) * @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 { +function missingMessage(capability: Capability, rule: Rule, keyRef: string): 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` @@ -358,17 +398,17 @@ function errorMessage(error: unknown): string { } /** - * Find the effective config of the active loader entry that registers `provider`, as the model provider directory - * names it. A route registered by another package, nested settings, or an inactive entry counts as absent. + * Accept a deployment base URL that may receive the account credential: HTTP(S) without embedded credentials. + * @param value - the configured URL. + * @returns the value. + * @throws {Error} when the value is not such a URL. */ -function routeConfig(ctx: Context, provider: RouteName): unknown { - const llm = ctx.get('llm'), loader = ctx.get('loader') - if (llm === undefined || loader === undefined || !llm.listProviders().some(row => row.id === provider)) return undefined - const directory = llm.listConfigurableProviders().find(row => row.provider === provider) - if (directory === undefined || directory.settingsPath.length !== 0) return undefined - const entry = [...loader.entries()].find(row => row.options.id === directory.settingsNs && row.options.name === ROUTE_PACKAGES[provider]) - if (entry?.fiber?.state !== FiberState.ACTIVE) return undefined - return entry.fiber.effectiveConfig +function deploymentURL(value: string): string { + const url = new URL(value) + if (!/^https?:$/u.test(url.protocol) || url.username.length > 0 || url.password.length > 0) { + throw new Error(`${DEEPSEEK_BASE_URL_ENV} must be an HTTP(S) URL without credentials`) + } + return value } /** The Search and Fetch API base under the origin of a Messages base URL. */ diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts index 1f61e36381..f8c841bb60 100644 --- a/packages/web/web-deepseek-api/src/transport.ts +++ b/packages/web/web-deepseek-api/src/transport.ts @@ -5,15 +5,13 @@ * @module @deepseek-ai/dsh-web-deepseek-api/transport */ import type { CredentialRef } from '@deepseek-ai/dsh-credentials' +import type { LlmCredentialKind, RouteCredential } from '@deepseek-ai/dsh-llm' import { WebError } from '@deepseek-ai/dsh-web' const USER_AGENT = 'deepseek-harness/0.0.1' -/** - * 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 | { +/** API key of one {@link DeepSeekWebAuthSource}: a credential reference read once per use without retention. */ +export interface DeepSeekWebApiKey { /** Credential reference the key is stored under. */ ref: CredentialRef /** Report key presence without reading or validating its value; store failures reject. */ @@ -27,15 +25,16 @@ export type DeepSeekWebApiKey = string | { * `/search`, to `baseURL`. */ export type DeepSeekWebAuthSource = - /** The account token released for the dispatch endpoint, sent as `x-dsh-auth-token`. */ + /** + * A credential released per use for the dispatch endpoint, as a DeepSeek model route publishes it. An API key is + * sent as `Authorization: Bearer`; any other kind is sent through the headers of its grant. + */ | { - kind: 'account' - /** API base the token is sent to, including its path prefix. */ + kind: 'route' + /** API base the credential 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 - /** Invalidate the exact token rejected by HTTP 401; failures must not replace the request error. */ - rejectToken: (token: string) => Promise + /** The credential's owner: it answers presence and releases a grant for an endpoint, and read failures reject. */ + credential: Omit } /** An API key, sent as `Authorization: Bearer`. */ | { @@ -86,7 +85,7 @@ interface DeepSeekWebRequest { body: object /** Protocol headers without credentials. */ headers?: Readonly> - /** Additional API-key headers; not applied to account tokens. */ + /** Additional headers sent beside an API key; other credential kinds send only their grant's headers. */ apiKeyHeaders?: (key: string) => Readonly> /** Validate and project the response. */ decode: (payload: unknown) => T @@ -101,18 +100,19 @@ interface DeepSeekWebRequest { /** * Check synchronously whether an operation has a source to try, without reading credentials. * @param auth - Sources for the operation. - * @returns Whether any source is an account, a credential reference, a non-empty literal key, or a misconfigured source - * the operation reports. + * @returns Whether any source exists: a route credential, a credential reference, or a misconfigured source the + * operation reports. */ export function hasDeepSeekWebCredential(auth: DeepSeekWebAuth): boolean { - return auth.sources.some(source => source.kind !== 'api-key' || typeof source.key !== 'string' || source.key.length > 0) + return auth.sources.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. + * does. A route source asks its credential whether one is configured for the operation's endpoint; a referenced key is + * only checked for presence, so a malformed or wrong key counts as ready. A misconfigured source or a failed read + * answers false without reading later sources, because the operation fails there too. Nothing is sent and nothing is + * retained. * @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. @@ -121,20 +121,13 @@ export async function isDeepSeekWebAuthReady(auth: DeepSeekWebAuth, path: '/sear 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 + case 'route': { + try { if (await source.credential.configured(joinPath(source.baseURL, path))) return true } + catch (_unreadableCredential) { return false /* The operation fails on this read before it tries another source. */ } break } case 'api-key': { - const { key } = source - if (typeof key === 'string') { - if (key.length > 0) return true - break - } - try { if (await key.configured()) return true } + try { if (await source.key.configured()) return true } catch (_unreadableStore) { return false /* The operation fails on this read before it tries another source. */ } break } @@ -160,15 +153,15 @@ export function invalidResponse(): WebError { return new WebError('DeepSeek returned an invalid response body', 'WEB_PROVIDER_ERROR') } -/** Authentication headers and endpoint for one operation, tagged by the credential that produced them. */ +/** Authentication headers and endpoint for one operation, tagged by the kind of credential that produced them. */ interface SearchAuth { - /** `account` for a DeepSeek account token, `api-key` for an API key. */ - readonly kind: 'account' | 'api-key' + /** Kind of the credential sent; an API-key source sends `api-key`. */ + readonly kind: LlmCredentialKind /** Absolute dispatch URL under the base of the source. */ readonly endpoint: string /** Headers carrying the credential. */ readonly headers: Readonly> - /** Request-bound invalidation, present only when an account token was sent. */ + /** Request-bound invalidation of the sent credential, present when its grant offers one. */ readonly reject?: () => Promise } @@ -234,14 +227,13 @@ export async function dispatchDeepSeekWeb( // malformed/non-JSON error body (normal for gateway 5xx/429s) can only // cost a richer provider message, never the real error. } - // The account service released this token only for its inference - // origin, so the endpoint is not what the user must change. - if (status === 401 && auth.kind === 'account') { + if (status === 401) { // Invalidation can cancel this Session; finish reading the HTTP failure before it does. A cancelled read still - // invalidates the token the status rejected. - try { await auth.reject?.() } - catch (_credentialRemovalFailed) { /* Report the original failure even if credential removal fails. */ } - throw aborted ?? accountRejectedError(message) + // invalidates the credential the status rejected. + await auth.reject?.() + // The account service released its credential only for its inference origin, so the endpoint is not what the + // user must change. + if (auth.kind === 'account') throw aborted ?? accountRejectedError(message) } if (aborted !== undefined) throw aborted throw searchEndpointError(guidance, endpoint, message) @@ -315,21 +307,20 @@ async function authHeaders( throwIfSearchAborted(signal) switch (source.kind) { case 'misconfigured': throw new WebError(source.message, 'WEB_PROVIDER_MISCONFIGURED') - case 'account': { + case 'route': { 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) }, + const grant = await resolveCredential(() => source.credential.resolve(endpoint, signal), signal) + if (grant === undefined) break + const { kind } = source.credential + const invalidate = grant.reject?.bind(grant) + return { + kind, endpoint, + headers: kind === 'api-key' ? { ...request.apiKeyHeaders?.(grant.value), authorization: `Bearer ${grant.value}` } : grant.headers, + ...invalidate === undefined ? {} : { reject: invalidate }, } - break } case 'api-key': { - const { key } = source - // A conditional await in a ternary can produce negative branch counts in V8-to-Istanbul mapping. - let apiKey: string | undefined - if (typeof key === 'string') apiKey = key - else apiKey = await resolveCredential(key.resolve, signal) + const apiKey = await resolveCredential(source.key.resolve, signal) if (apiKey !== undefined && apiKey.length > 0) return { kind: 'api-key', endpoint: joinPath(source.baseURL, request.path), headers: { ...request.apiKeyHeaders?.(apiKey), 'authorization': `Bearer ${apiKey}`, @@ -367,9 +358,7 @@ function assertNever(value: never): never { * @returns the resolved credential, or undefined when the resolver supplied none. * @throws {@link WebError} `WEB_ABORTED` on cancellation, `WEB_PROVIDER_ERROR` when the resolver fails. */ -async function resolveCredential( - resolve: () => Promise, signal?: AbortSignal, -): Promise { +async function resolveCredential(resolve: () => Promise, signal?: AbortSignal): Promise { throwIfSearchAborted(signal) try { return await abortable(resolve(), signal) diff --git a/packages/web/web-deepseek-api/tests/composition.spec.ts b/packages/web/web-deepseek-api/tests/composition.spec.ts index ba93f108bc..71f01ee2b9 100644 --- a/packages/web/web-deepseek-api/tests/composition.spec.ts +++ b/packages/web/web-deepseek-api/tests/composition.spec.ts @@ -10,13 +10,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { Context } from '@deepseek-ai/cordis' import type { ModuleLoaderV2 } from '@deepseek-ai/cordis-plugin-loader' import { boot } from '@deepseek-ai/dsh-app-boot' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import LlmRuntime from '@deepseek-ai/dsh-llm' import * as Account from '@deepseek-ai/dsh-llm-deepseek-account' import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key' import WebRuntime from '@deepseek-ai/dsh-web' import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' const cleanups: Array<() => Promise> = [] @@ -83,7 +83,7 @@ async function bootComposition(web: Record, environment: Record } host.loader.internal = modules host.provide('launchEnvironment', createLaunchEnvironmentSnapshot([{ source: 'process', values: environment }])) - host.provide('deepseekAccount', { resolveToken: async () => 'account-token' } as Pick as DeepSeekAccount) + host.provide('deepseekAccount', accountStub({ token: () => 'account-token' })) }) cleanups.push(async () => { await ctx.fiber.dispose() }) const sent = (): Sent[] => fetchMock.mock.calls.flatMap(([endpoint, init]) => { diff --git a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts index 741ebde66e..abd6896b76 100644 --- a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts +++ b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts @@ -4,10 +4,11 @@ * operation would send. */ import { afterEach, describe, expect, it, vi } from 'vitest' -import { Context, FiberState } from '@deepseek-ai/cordis' +import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -15,20 +16,6 @@ import WebRuntime from '@deepseek-ai/dsh-web' import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api' import { provideRoutes, type RouteRow } from './routes.ts' -/** A value the API-key route resolver throws instead of resolving; undefined lets it resolve normally. */ -const resolverThrow = vi.hoisted(() => ({ value: undefined as string | undefined })) - -vi.mock('@deepseek-ai/dsh-llm-deepseek-api-key', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - resolveAdapterOptions: (...args: Parameters) => { - if (resolverThrow.value !== undefined) throw resolverThrow.value - return original.resolveAdapterOptions(...args) - }, - } -}) - type Operation = 'search' | 'fetch' const OPERATIONS: readonly Operation[] = ['search', 'fetch'] @@ -41,7 +28,6 @@ const mounted: Context[] = [] afterEach(async () => { vi.unstubAllGlobals() - resolverThrow.value = undefined await Promise.all(mounted.splice(0).map(ctx => ctx.fiber.dispose())) }) @@ -53,7 +39,7 @@ interface Setup { /** Model routes the provider directory lists. */ routes?: readonly RouteRow[] /** Account service stand-in. */ - account?: Pick & Partial> + account?: DeepSeekAccount /** Credentials service stand-in. */ credentials?: object /** API response status. */ @@ -81,7 +67,7 @@ async function mount(setup: Setup): Promise<{ ctx: Context; sent: () => Sent[] } const ctx = new Context() mounted.push(ctx) ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: setup.environment ?? {} }])) - if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account as DeepSeekAccount) + if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account) if (setup.credentials !== undefined) ctx.provide('credentials', setup.credentials as never) if (setup.routes !== undefined) provideRoutes(ctx, setup.routes) await ctx.plugin(SessionStore) @@ -121,10 +107,14 @@ function ready(ctx: Context, operation: Operation, route: string | undefined): P return operation === 'search' ? ctx.web.searchReady(route) : ctx.web.fetchReady(route) } -/** The account service of a signed-in user, recording the URLs it is asked for. */ -function signedIn(asked: string[] = []): Pick { - return { resolveToken: async (url: string) => { asked.push(url); return 'account-token' } } +/** The account service of a signed-in user, recording the URLs it is asked for and the tokens it is told to reject. */ +function signedIn(asked: string[] = [], reject?: (token: string) => Promise): DeepSeekAccount { + return accountStub({ token: (url) => { asked.push(url); return 'account-token' }, ...reject === undefined ? {} : { reject } }) } +/** The account service of a signed-out user. */ +const signedOut = (): DeepSeekAccount => accountStub({ token: () => undefined }) +/** An account service whose stored grant cannot be read. */ +const unreadable = (): DeepSeekAccount => accountStub({ token: () => Promise.reject(new Error('grant unreadable')) }) const officialRoute = (config: Record = { baseURL: 'https://route.deepseek.test/anthropic' }): RouteRow => ({ provider: 'deepseek-official', config }) @@ -151,8 +141,8 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', }) it('invalidates the token the API rejects with 401', async () => { - const rejectToken = vi.fn(async () => {}) - const { ctx } = await mount({ routes: bothRoutes, account: { ...signedIn(), rejectToken }, status: 401 }) + const rejectToken = vi.fn(async (_token: string) => {}) + const { ctx } = await mount({ routes: bothRoutes, account: signedIn([], rejectToken), status: 401 }) const failure = operate(ctx, operation, 'deepseek-account') await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' }) await expect(failure).rejects.toThrow('HTTP 401') @@ -160,8 +150,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', }) it.each<[string, Setup['account']]>([ - ['the user is not signed in', { resolveToken: async () => undefined }], - ['the account releases an empty token', { resolveToken: async () => '' }], + ['the user is not signed in', signedOut()], ['no account service is mounted', undefined], ])('sends the API key to the API-key endpoint when %s', async (_label, account) => { const { ctx, sent } = await mount({ @@ -174,7 +163,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', it('is not ready and names both recoveries when neither a sign-in nor the key is available', async () => { const subject = operation === 'search' ? 'Search' : 'Fetch' - const { ctx, sent } = await mount({ routes: bothRoutes, account: { resolveToken: async () => undefined } }) + const { ctx, sent } = await mount({ routes: bothRoutes, account: signedOut() }) expect(await ready(ctx, operation, 'deepseek-account')).toBe(false) await expect(operate(ctx, operation, 'deepseek-account')).rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING', @@ -228,7 +217,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', it('fails instead of sending DEEPSEEK_API_KEY when there is no sign-in and the API-key route settings do not resolve', async () => { const { ctx, sent } = await mount({ routes: [officialRoute({ thinking: 'disabled', reasoningEffort: 'high' }), accountRoute()], - account: { resolveToken: async () => undefined }, environment: { DEEPSEEK_API_KEY: 'chat-key' }, + account: signedOut(), environment: { DEEPSEEK_API_KEY: 'chat-key' }, }) expect(await ready(ctx, operation, 'deepseek-account')).toBe(false) await expect(operate(ctx, operation, 'deepseek-account')).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) @@ -237,7 +226,7 @@ describe.each(OPERATIONS)('%s in a conversation on the DeepSeek account route', it('is not ready and fails without trying the key when the account grant cannot be read', async () => { const { ctx, sent } = await mount({ - routes: bothRoutes, account: { resolveToken: () => Promise.reject(new Error('grant unreadable')) }, + routes: bothRoutes, account: unreadable(), environment: { DEEPSEEK_API_KEY: 'chat-key' }, }) expect(await ready(ctx, operation, 'deepseek-account')).toBe(false) @@ -302,7 +291,7 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => { it('is not ready and names both recoveries without a key and a sign-in', async () => { const subject = operation === 'search' ? 'Search' : 'Fetch' - for (const account of [{ resolveToken: async () => undefined }, undefined]) { + for (const account of [signedOut(), undefined]) { const { ctx, sent } = await mount({ routes: bothRoutes, ...account === undefined ? {} : { account } }) expect(await ready(ctx, operation, 'moonshotai')).toBe(false) await expect(operate(ctx, operation, 'moonshotai')).rejects.toMatchObject({ @@ -364,10 +353,9 @@ describe.each(OPERATIONS)('%s in any other conversation', (operation) => { }) it.each<[string, readonly RouteRow[] | undefined]>([ - ['no model provider directory is mounted', undefined], - ['the route entry is not active', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, state: FiberState.DISPOSED }]], - ['another package registers the route', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, name: '@example/other-llm' }]], - ['the route settings are nested', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, settingsPath: ['routes', 'official'] }]], + ['no model service is mounted', undefined], + ['no route registers deepseek-official', [accountRoute()]], + ['the registered deepseek-official adapter publishes no credential', [{ provider: 'deepseek-official', config: { apiKeyEnv: 'TEAM_KEY' }, withoutCredential: true }]], ])('sends DEEPSEEK_API_KEY to the official base when %s', async (_label, routes) => { const { ctx, sent } = await mount({ ...routes === undefined ? {} : { routes }, @@ -470,8 +458,7 @@ describe.each(OPERATIONS)('%s billed to the signed-in DeepSeek account', (operat }) it.each<[string, Setup['account']]>([ - ['the user is not signed in', { resolveToken: async () => undefined }], - ['the account releases an empty token', { resolveToken: async () => '' }], + ['the user is not signed in', signedOut()], ['no account service is mounted', undefined], ])('is not ready and never sends the key when %s', async (_label, account) => { const { ctx, sent } = await mount({ @@ -503,18 +490,31 @@ describe.each(OPERATIONS)('%s billed to the signed-in DeepSeek account', (operat expect(asked).toEqual([]) }) - it('is not ready and fails without a token when the default account settings do not resolve', async () => { - const { ctx, sent } = await mount({ - config, account: signedIn(), environment: { DEEPSEEK_BASE_URL: 'https://user:secret@internal.deepseek.test/anthropic' }, - }) - expect(await ready(ctx, operation, undefined)).toBe(false) - await expect(operate(ctx, operation)).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) + it('is not ready and never sends the key without the account route and the account service', async () => { + const { ctx, sent } = await mount({ config, routes: [officialRoute()], environment: { DEEPSEEK_API_KEY: 'chat-key' } }) + expect(await ready(ctx, operation, 'moonshotai')).toBe(false) + await expect(operate(ctx, operation, 'moonshotai')).rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING' }) expect(sent()).toEqual([]) }) + it.each(['https://user:secret@internal.deepseek.test/anthropic', 'https://:secret@internal.deepseek.test/anthropic', 'ftp://internal.deepseek.test/anthropic', 'not a url'])( + 'is not ready and fails without a token when DEEPSEEK_BASE_URL is %s and no account route is mounted', async (baseURL) => { + const asked: string[] = [] + const { ctx, sent } = await mount({ config, account: signedIn(asked), environment: { DEEPSEEK_BASE_URL: baseURL } }) + expect(await ready(ctx, operation, undefined)).toBe(false) + const failure = operate(ctx, operation) + await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) + await expect(failure).rejects.toThrow(`DeepSeek ${subject} API sends the DeepSeek account sign-in to the origin of DEEPSEEK_BASE_URL,` + + ' and that value does not resolve: ') + await expect(failure).rejects.toThrow('Guide the user to correct DEEPSEEK_BASE_URL in the launching environment, or to set') + expect(sent()).toEqual([]) + expect(asked).toEqual([]) + }, + ) + it('is not ready and fails when the account grant cannot be read', async () => { const { ctx, sent } = await mount({ - config, routes: bothRoutes, account: { resolveToken: () => Promise.reject(new Error('grant unreadable')) }, + config, routes: bothRoutes, account: unreadable(), environment: { DEEPSEEK_API_KEY: 'chat-key' }, }) expect(await ready(ctx, operation, 'moonshotai')).toBe(false) @@ -523,8 +523,8 @@ describe.each(OPERATIONS)('%s billed to the signed-in DeepSeek account', (operat }) it('invalidates the token the API rejects with 401', async () => { - const rejectToken = vi.fn(async () => {}) - const { ctx } = await mount({ config, routes: bothRoutes, account: { ...signedIn(), rejectToken }, status: 401 }) + const rejectToken = vi.fn(async (_token: string) => {}) + const { ctx } = await mount({ config, routes: bothRoutes, account: signedIn([], rejectToken), status: 401 }) await expect(operate(ctx, operation, 'moonshotai')).rejects.toThrow('HTTP 401') expect(rejectToken).toHaveBeenCalledExactlyOnceWith('account-token') }) @@ -677,10 +677,11 @@ describe('independent capabilities', () => { }) }) -describe('route resolver failures', () => { +describe('route credential failures', () => { it('reports a thrown non-Error value as its string', async () => { - const { ctx, sent } = await mount({ routes: [officialRoute()], environment: { DEEPSEEK_API_KEY: 'chat-key' } }) - resolverThrow.value = 'route resolver unavailable' + const { ctx, sent } = await mount({ + routes: [{ provider: 'deepseek-official', throws: 'route resolver unavailable' }], environment: { DEEPSEEK_API_KEY: 'chat-key' }, + }) const failure = operate(ctx, 'search', 'deepseek-official') await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) await expect(failure).rejects.toThrow('that provider\'s settings do not resolve: route resolver unavailable. Search did not send') diff --git a/packages/web/web-deepseek-api/tests/egress.spec.ts b/packages/web/web-deepseek-api/tests/egress.spec.ts index c47a3c07ba..cbe81aac8c 100644 --- a/packages/web/web-deepseek-api/tests/egress.spec.ts +++ b/packages/web/web-deepseek-api/tests/egress.spec.ts @@ -1,6 +1,7 @@ import { createServer, type Server } from 'node:http' import type { AddressInfo } from 'node:net' import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import { installProxyFromEnvironment } from '@deepseek-ai/dsh-http-proxy' import { customGuidance } from './guidance.ts' @@ -35,7 +36,7 @@ async function observe(run: () => Promise): Promise { import { DeepSeekSearchApiProvider } from '../src/search.ts' describe('deepseek search api egress', () => { it('goes through the proxy', async () => { - const p = new DeepSeekSearchApiProvider(() => ({ auth: { sources: [{ kind: 'api-key', baseURL: 'http://dsk-probe.invalid/api/v1/tools', key: 'probe' }] }, 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: { ref: credentialRef('PROBE_KEY'), configured: async () => true, resolve: async () => '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']) }) }) diff --git a/packages/web/web-deepseek-api/tests/fetch.spec.ts b/packages/web/web-deepseek-api/tests/fetch.spec.ts index 060725780a..31ef9f6e14 100644 --- a/packages/web/web-deepseek-api/tests/fetch.spec.ts +++ b/packages/web/web-deepseek-api/tests/fetch.spec.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import WebRuntime from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider, type DeepSeekFetchApiOptions } from '@deepseek-ai/dsh-web-deepseek-api' import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api' @@ -7,7 +8,8 @@ import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@de import { customGuidance } from './guidance.ts' const fetchProvider = (options: DeepSeekFetchApiOptions) => new DeepSeekFetchApiProvider(() => options) const BASE = 'https://api.deepseek.test/api/v1/tools' -const auth = (key: string, baseURL = BASE): DeepSeekFetchApiOptions['auth'] => ({ sources: [{ kind: 'api-key', baseURL, key }] }) +const auth = (key: string, baseURL = BASE): DeepSeekFetchApiOptions['auth'] => + ({ sources: [{ kind: 'api-key', baseURL, key: { ref: credentialRef('TEST_KEY'), configured: async () => key.length > 0, resolve: async () => key.length > 0 ? key : undefined } }] }) const 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 }) @@ -57,7 +59,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: auth('') }).available()).toBe(false) + expect(fetchProvider({ ...options, auth: { sources: [] } }).available()).toBe(false) + expect(fetchProvider({ ...options, auth: auth('') }).available()).toBe(true) expect(fetchProvider({ ...options, auth: auth('ds-key', 'not a url') }).available()).toBe(false) }) it('unregisters both providers with its plugin fiber', async () => { diff --git a/packages/web/web-deepseek-api/tests/redirect.spec.ts b/packages/web/web-deepseek-api/tests/redirect.spec.ts index 6453872aa8..f1985a350e 100644 --- a/packages/web/web-deepseek-api/tests/redirect.spec.ts +++ b/packages/web/web-deepseek-api/tests/redirect.spec.ts @@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { createServer, type IncomingMessage, type Server } from 'node:http' import type { AddressInfo } from 'node:net' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import { customGuidance } from './guidance.ts' import { dispatchDeepSeekWeb } from '../src/transport.ts' @@ -47,7 +48,7 @@ afterAll(async () => { describe('dispatchDeepSeekWeb redirect policy', () => { it.each([301, 302, 303, 307, 308])('rejects HTTP %i before contacting Location', async (status) => { targetRequests.length = 0 - await expect(dispatchDeepSeekWeb({ sources: [{ kind: 'api-key', baseURL: redirectOrigin, key: TEST_API_KEY }] }, { + await expect(dispatchDeepSeekWeb({ sources: [{ kind: 'api-key', baseURL: redirectOrigin, key: { ref: credentialRef('TEST_API_KEY'), configured: async () => true, resolve: async () => TEST_API_KEY } }] }, { path: `/${status}`, body: { query: TEST_QUERY }, decode: value => value, apiKeyHeaders: key => ({ 'x-api-key': key }), guidance: customGuidance('search'), @@ -57,8 +58,9 @@ describe('dispatchDeepSeekWeb redirect policy', () => { it('rejects a redirect of an account-token request before contacting Location', async () => { targetRequests.length = 0 + const grant = { headers: { 'x-dsh-auth-token': 'redirect-test-token' }, value: 'redirect-test-token' } await expect(dispatchDeepSeekWeb({ sources: [{ - kind: 'account', baseURL: redirectOrigin, resolveToken: async () => 'redirect-test-token', rejectToken: async () => {}, + kind: 'route', baseURL: redirectOrigin, credential: { kind: 'account', configured: async () => true, resolve: async () => grant }, }] }, { path: '/307', body: { query: TEST_QUERY }, decode: value => value, guidance: customGuidance('search'), diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index a6592cea45..620a3b87f5 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -1,48 +1,61 @@ -/** Stand-in model and loader services that expose DeepSeek model routes the way the provider directory does. */ -import { FiberState, type Context } from '@deepseek-ai/cordis' +/** A stand-in model service publishing DeepSeek route credentials the way the route plugins do. */ +import type { Context } from '@deepseek-ai/cordis' +import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' +import type {} from '@deepseek-ai/dsh-deepseek-account' +import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' +import type { RouteCredential } from '@deepseek-ai/dsh-llm' import { Config as AccountConfig } from '@deepseek-ai/dsh-llm-deepseek-account' +import { plainAccountOptions, resolveAccountOptions } from '@deepseek-ai/dsh-llm-deepseek-account/src/config.ts' import { Config as OfficialConfig } from '@deepseek-ai/dsh-llm-deepseek-api-key' +import { plainOptions, resolveAdapterOptions } from '@deepseek-ai/dsh-llm-deepseek-api-key/src/config.ts' /** One model route row. */ export interface RouteRow { /** Provider id the route registers. */ provider: 'deepseek-official' | 'deepseek-account' - /** Route plugin config, parsed by the route package's own schema. */ + /** Route plugin config; the route package's own resolver turns it into the published base URL and key reference. */ config?: Record - /** Loader package name; defaults to the package that registers the provider. */ - name?: string - /** Loader fiber state; defaults to active. */ - state?: FiberState - /** Provider directory settings path; defaults to the entry root. */ - settingsPath?: string[] + /** Publish no credential, as an adapter another package registers under this id does. Defaults to false. */ + withoutCredential?: boolean + /** Value `routeCredential()` throws instead of publishing. */ + throws?: unknown } -const PACKAGES = { - 'deepseek-official': '@deepseek-ai/dsh-llm-deepseek-api-key', - 'deepseek-account': '@deepseek-ai/dsh-llm-deepseek-account', -} as const +/** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */ +function credentialOf(ctx: Context, route: RouteRow): RouteCredential { + const environment = launchEnvironmentOf(ctx) + if (route.provider === 'deepseek-official') { + const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment) + const ref = resolved.apiKeyEnv + return { + kind: 'api-key', baseURL: resolved.baseURL, reference: ref, + configured: () => credentialRefConfigured(ctx, ref), + resolve: async () => { + const key = await resolveCredentialRef(ctx, ref) + return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key } + }, + } + } + const resolved = resolveAccountOptions(plainAccountOptions(AccountConfig(route.config ?? {})), environment) + return { + kind: 'account', baseURL: resolved.protocol.baseURL, + configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined, + resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined), + } +} /** - * Provide `llm` and `loader` stand-ins whose rows describe `routes`. + * Provide an `llm` stand-in whose `routeCredential()` answers for `routes`. * @param ctx - the root context. - * @param routes - route rows; each gets its own loader entry. + * @param routes - route rows, one per provider id. */ export function provideRoutes(ctx: Context, routes: readonly RouteRow[]): void { - const rows = routes.map((route, index) => ({ - route, - entry: { - options: { id: `route-${String(index)}`, name: route.name ?? PACKAGES[route.provider] }, - fiber: { - state: route.state ?? FiberState.ACTIVE, - effectiveConfig: route.provider === 'deepseek-official' ? OfficialConfig(route.config ?? {}) : AccountConfig(route.config ?? {}), - }, - }, - })) ctx.provide('llm', { - listProviders: () => rows.map(({ route }) => ({ id: route.provider })), - listConfigurableProviders: () => rows.map(({ route, entry }) => ({ - provider: route.provider, settingsNs: entry.options.id, settingsPath: route.settingsPath ?? [], - })), + routeCredential: (provider: string): RouteCredential | undefined => { + const route = routes.find(row => row.provider === provider) + if (route === undefined || route.withoutCredential === true) return undefined + if (route.throws !== undefined) throw route.throws + return credentialOf(ctx, route) + }, } as never) - ctx.provide('loader', { entries: () => rows.map(({ entry }) => entry).values() } as never) } diff --git a/packages/web/web-deepseek-api/tests/search.spec.ts b/packages/web/web-deepseek-api/tests/search.spec.ts index 6840c90493..17d3eccfa7 100644 --- a/packages/web/web-deepseek-api/tests/search.spec.ts +++ b/packages/web/web-deepseek-api/tests/search.spec.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import type { Session } from '@deepseek-ai/dsh-session' @@ -20,7 +21,8 @@ const searchProvider = (options: DeepSeekSearchApiOptions): DeepSeekSearchApiPro 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 auth = (key: string, baseURL = BASE): DeepSeekSearchApiOptions['auth'] => + ({ sources: [{ kind: 'api-key', baseURL, key: { ref: credentialRef('TEST_KEY'), configured: async () => key.length > 0, resolve: async () => key.length > 0 ? key : undefined } }] }) const options = { auth: auth('ds-key'), @@ -74,16 +76,18 @@ describe('mapSearchResponse', () => { }) describe('DeepSeekSearchApiProvider availability', () => { - it('is unavailable without a key', () => { - expect(searchProvider({ ...options, auth: auth('') }).available()).toBe(false) + it('is unavailable without a source, and available with a referenced key whose presence only ready() reads', () => { + expect(searchProvider({ ...options, auth: { sources: [] } }).available()).toBe(false) + expect(searchProvider({ ...options, auth: auth('') }).available()).toBe(true) }) it('is available with a key', () => { expect(searchProvider(options).available()).toBe(true) }) - it('is available with only an account token resolver', () => { - expect(searchProvider({ ...options, auth: { sources: [{ kind: 'account', baseURL: BASE, resolveToken: async () => 'account-token', rejectToken: async () => {} }] } }).available()).toBe(true) + it('is available with only a route credential', () => { + const credential = { kind: 'account', configured: async () => true, resolve: async () => undefined } as const + expect(searchProvider({ ...options, auth: { sources: [{ kind: 'route', baseURL: BASE, credential }] } }).available()).toBe(true) }) it('is available with only a misconfigured source, which the search reports', () => { diff --git a/packages/web/web-deepseek-api/tests/transport.spec.ts b/packages/web/web-deepseek-api/tests/transport.spec.ts index 5296e4eb42..c6620a9d13 100644 --- a/packages/web/web-deepseek-api/tests/transport.spec.ts +++ b/packages/web/web-deepseek-api/tests/transport.spec.ts @@ -9,18 +9,39 @@ import { const API_BASE = 'https://api.deepseek.test/v1/tools' const ACCOUNT_BASE = 'https://account.deepseek.test/v1/tools' /** An API-key source on {@link API_BASE}. */ -function keySource(key: DeepSeekWebApiKey = 'ds-key'): DeepSeekWebAuthSource { +function keySource(key: DeepSeekWebApiKey = keyRef(async () => 'ds-key')): DeepSeekWebAuthSource { return { kind: 'api-key', baseURL: API_BASE, key } } /** A referenced key whose presence check and read are the given functions. */ function keyRef(resolve: () => Promise, configured: () => Promise = async () => true): DeepSeekWebApiKey { return { ref: credentialRef('TEST_KEY'), configured, resolve } } -/** An account source on {@link ACCOUNT_BASE}. */ +/** + * A route source on {@link ACCOUNT_BASE} whose account credential releases `resolveToken(endpoint)` as the token header; + * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failures are contained as the + * account service contains them. + */ function accountSource( resolveToken: (endpoint: string) => Promise, rejectToken: (token: string) => Promise = async () => {}, ): DeepSeekWebAuthSource { - return { kind: 'account', baseURL: ACCOUNT_BASE, resolveToken, rejectToken } + const grant = async (endpoint: string) => { + const token = await resolveToken(endpoint) + if (token === undefined || token.length === 0) return undefined + return { headers: { 'x-dsh-auth-token': token }, value: token, reject: async () => { + try { await rejectToken(token) } catch (_storageFailure) { /* Contained as the account service contains it. */ } + } } + } + return { kind: 'route', baseURL: ACCOUNT_BASE, credential: { + kind: 'account', configured: async endpoint => (await grant(endpoint)) !== undefined, resolve: grant, + } } +} +/** A route source on {@link API_BASE} whose API-key credential releases `key`, sent as a bearer token. */ +function keyRouteSource(key: string | undefined, reference = 'ROUTE_KEY'): DeepSeekWebAuthSource { + return { kind: 'route', baseURL: API_BASE, credential: { + kind: 'api-key', reference, + configured: async () => key !== undefined, + resolve: async () => key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key }, + } } } const misconfigured: DeepSeekWebAuthSource = { kind: 'misconfigured', message: 'route settings do not resolve' } /** Search once with the given sources, in order. */ @@ -101,9 +122,24 @@ describe('DeepSeek web credential order', () => { .toEqual([[`${API_BASE}/search`, 'ds-key', undefined]]) }) + it('sends a route API key as a bearer token with the request\'s API-key headers, never the route\'s own headers', async () => { + const { sent } = captureFetch() + await search([keyRouteSource('route-key')]) + const [request] = sent() + expect(request?.url).toBe(`${API_BASE}/search`) + expect(request?.headers).toMatchObject({ 'authorization': 'Bearer route-key', 'x-api-key': 'route-key' }) + expect(request?.headers).not.toHaveProperty('x-dsh-auth-token') + }) + + it('moves past a route whose API key is absent', async () => { + const { sent } = captureFetch() + await search([keyRouteSource(undefined), accountSource(async () => 'account-token')]) + expect(sent().map(row => [row.url, row.headers['x-dsh-auth-token']])).toEqual([[`${ACCOUNT_BASE}/search`, 'account-token']]) + }) + it.each<[string, readonly DeepSeekWebAuthSource[]]>([ ['no sources', []], - ['an empty literal key', [keySource('')]], + ['a referenced key that resolves empty', [keySource(keyRef(async () => ''))]], ['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() @@ -161,7 +197,7 @@ describe('DeepSeek web credential order', () => { describe('DeepSeek web credential availability and readiness', () => { it.each<[boolean, readonly DeepSeekWebAuthSource[]]>([ [false, []], - [false, [keySource('')]], + [true, [keySource(keyRef(async () => undefined, async () => false))]], [true, [keySource()]], [true, [keySource(keyRef(async () => undefined))]], [true, [accountSource(async () => undefined)]], @@ -184,8 +220,8 @@ describe('DeepSeek web credential availability and readiness', () => { it.each<[string, readonly DeepSeekWebAuthSource[], boolean]>([ ['no sources', [], false], - ['an empty literal key', [keySource('')], false], - ['a literal key', [keySource()], true], + ['an unconfigured referenced key', [keySource(keyRef(async () => undefined, async () => false))], false], + ['a configured referenced 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) => { @@ -215,7 +251,7 @@ 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) => { + it.each([false, true])('invalidates the sent account token on 401 and preserves the HTTP error whether or not removal fails: %s', async (fails) => { 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(search([accountSource(async () => 'sent-token', rejectToken)])) @@ -249,6 +285,14 @@ describe('DeepSeek web account authentication', () => { expect(rejectToken).not.toHaveBeenCalled() }) + it('keeps endpoint guidance for a 401 on a route API key, which has no invalidation', async () => { + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'invalid key' }, { status: 401 }))) + const error = await rejectedWebError(search([keyRouteSource('route-key')])) + expect(error.message).toContain('DeepSeek API error (HTTP 401): invalid key') + expect(error.message).toContain('If that endpoint is not intended') + expect(error.message).not.toContain('sign in') + }) + it('retains the HTTP failure when account invalidation cancels the requesting Session', async () => { const controller = new AbortController() const response = jsonResponse({ error: 'invalid token' }, { status: 401 }) diff --git a/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts b/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts index 86f76ffab3..84d2cfc65e 100644 --- a/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts +++ b/packages/web/web-deepseek-api/tests/web-deepseek-api.e2e.ts @@ -1,11 +1,15 @@ import { describe, expect, it } from 'vitest' +import { credentialRef } from '@deepseek-ai/dsh-credentials' import { DeepSeekFetchApiProvider, DeepSeekSearchApiProvider } from '@deepseek-ai/dsh-web-deepseek-api' import { customGuidance } from './guidance.ts' /** 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 auth = { sources: [{ + kind: 'api-key', baseURL, + key: { ref: credentialRef('DEEPSEEK_API_KEY'), configured: async () => apiKey !== undefined, resolve: async () => apiKey }, +}] } as const const maybe = apiKey !== undefined && apiKey.length > 0 && baseURL.length > 0 ? describe : describe.skip maybe('DeepSeek Search and Fetch real API', () => { diff --git a/packages/web/web-deepseek-api/tsconfig.json b/packages/web/web-deepseek-api/tsconfig.json index 0fb683fb97..01466b7c23 100644 --- a/packages/web/web-deepseek-api/tsconfig.json +++ b/packages/web/web-deepseek-api/tsconfig.json @@ -8,7 +8,6 @@ "src" ], "references": [ - { "path": "../../llm/llm-deepseek" }, { "path": "../../util/launch-environment" }, @@ -34,22 +33,13 @@ "path": "../../credentials/credentials" }, { - "path": "../../credentials/deepseek-account" + "path": "../../account/deepseek-account" }, { "path": "../../util/http-proxy" }, - { - "path": "../../../vendor/loader" - }, { "path": "../../llm/llm" - }, - { - "path": "../../llm/llm-deepseek-api-key" - }, - { - "path": "../../llm/llm-deepseek-account" } ] } diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index 6ff6e2b7d0..d83724b59e 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3ed88edabdf63c8d zh: c66176c8a7c9a434 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: 7a765ba931329067 - zh: 6fc14edcc378684a + en: 7e625c9a31ecad31 + zh: 19088d0014d51b24 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a @@ -39,14 +39,14 @@ en: 9842c69ad3636bb3 zh: 3cdc3f816cbdd0cb /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/design-philosophy: - en: 1b1760efbf4568c1 - zh: fca06c959e51ce16 + en: 76d5fb7c1e00079c + zh: 6f0e835157a3c982 /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/source-map: en: 6488e1c85646339f zh: 2b5ca1c6b5939a8c /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/request-flow: - en: d6c3f30b70a5f4b5 - zh: ab7c5b7d6fc3cae6 + en: a45785f95dbde10a + zh: 399bd28592d34721 /deepseek-ai-dsh-web-search-deepseek/further-exploration: en: 3a650478cf33d792 zh: ab4247c4c31f4a90 diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 7f7fb0815b..230f4cc63e 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,11 +58,11 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names the `deepseek-account` provider route and `ctx.deepseekAccount` resolves a token for the search endpoint. The account service resolves one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the token that search sent: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, and that credential resolves for the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. -The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route is `deepseek-account` and `ctx.deepseekAccount` resolves a token for the configured search endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a failed account-token or credential-store read answers false, because the search fails on that read instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. +The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential that reports itself configured for the configured search endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or a failed account-credential or credential-store read answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. -Referenced keys use the [shared DeepSeek credential helpers](../../llm/llm-deepseek/README.md#account-credentials), including the same whitespace normalization and format validation as model requests. A malformed referenced key fails before dispatch; readiness remains a presence-only check. +Referenced keys go through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md) and receive the same whitespace normalization and format validation as model requests. A malformed referenced key fails before dispatch; readiness remains a presence-only check. ### What a search returns @@ -91,7 +91,7 @@ This section explains the design decisions behind the provider; the observable b The provider is built on two commitments: - **Structured blocks only.** DeepSeek runs the search server-side and returns structured `web_search_tool_result` blocks; the provider parses those blocks and never scrapes URLs out of model prose. In strict mode, a response with no such block throws `WEB_PROVIDER_ERROR` instead of degrading. -- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on the account route uses that account's token, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart. +- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on a route that publishes an account credential uses that credential, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart. ### Source map @@ -103,9 +103,9 @@ The provider is built on two commitments: ### Request flow -Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks `ctx.deepseekAccount` for a token when the initiating Session uses the account route, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. +Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.routeCredential` when it publishes one, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. -Readiness captures the same options but reads no API key value: on the account route it first asks `ctx.deepseekAccount` for a token, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured. +Readiness captures the same options but reads no API key value: on a route publishing an account credential it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured.
diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index f27c5367b3..a55dc76495 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,11 +58,11 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明 `deepseek-account` 提供方路由,且 `ctx.deepseekAccount` 为搜索端点解析出 token 时,搜索使用 DeepSeek 账号鉴权。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)解析 token。这类搜索只发送 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并只作废该搜索实际发送的 token:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 +当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 -提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由是 `deepseek-account` 且 `ctx.deepseekAccount` 为配置的搜索端点解析出 token,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查,读取账号 token 或凭据存储失败时回答 false,因为搜索会在该次读取上失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 +提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由发布的账号凭据报告自身已为配置的搜索端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 -引用密钥使用[共享 DeepSeek 凭据函数](../../llm/llm-deepseek/README.zh.md#account-credentials),接受与模型请求相同的首尾空白规范化和格式校验。引用密钥格式错误会在发送请求前失败;就绪判断仍只检查是否存在。 +引用密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取,接受与模型请求相同的首尾空白规范化和格式校验。引用密钥格式错误会在发送请求前失败;就绪判断仍只检查是否存在。 ### 搜索返回什么 @@ -91,7 +91,7 @@ kind: "package-reference" 本提供方建立在两项承诺之上: - **只取结构化块。** DeepSeek 在服务端执行搜索并返回结构化的 `web_search_tool_result` 块;提供方解析这些块,绝不从模型文本中抓取 URL。严格模式下,没有此类块的响应会抛出 `WEB_PROVIDER_ERROR`,而非降级。 -- **会话凭据,逐次解析。** 提供方不新增密钥:来自账号路由会话的搜索使用该账号的 token,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。 +- **会话凭据,逐次解析。** 提供方不新增密钥:来自发布账号凭据的路由会话的搜索使用该凭据,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。 ### 源码地图 @@ -103,9 +103,9 @@ kind: "package-reference" ### 请求流程 -每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话使用账号路由时向 `ctx.deepseekAccount` 请求 token,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 +每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 -就绪判断捕获相同的选项,但不读取 API 密钥的值:账号路由先向 `ctx.deepseekAccount` 请求 token,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。 +就绪判断捕获相同的选项,但不读取 API 密钥的值:发布账号凭据的路由先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。
diff --git a/packages/web/web-search-deepseek/package.json b/packages/web/web-search-deepseek/package.json index cf3d5b11ec..671c5ca268 100644 --- a/packages/web/web-search-deepseek/package.json +++ b/packages/web/web-search-deepseek/package.json @@ -32,33 +32,28 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-web": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/dsh-web": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-http-proxy": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-web": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-http-proxy": "workspace:*" - }, - "peerDependenciesMeta": { - "@deepseek-ai/dsh-deepseek-account": { - "optional": true - } + "@deepseek-ai/dsh-web": "workspace:*" } } diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index af7fad61a5..da16c7c2a6 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -1,10 +1,11 @@ /** * Register a DeepSeek-backed provider in `ctx.web`. It calls the Anthropic-compatible Messages API - * with native `web_search_20250305`. A search initiated by a Session on the DeepSeek account route - * authenticates with the account token when the account service allows the search endpoint; - * every other search reuses `DEEPSEEK_API_KEY`. The provider does not reuse `DEEPSEEK_BASE_URL`; - * auxiliary search has its own endpoint configuration. The provider reports itself not ready for a - * model request whose search would have no credential. + * with native `web_search_20250305`. A search initiated by a Session whose latest model request used + * a route that publishes an account credential through `ctx.llm.routeCredential()` authenticates with + * that credential when its owner allows the search endpoint; every other search reuses + * `DEEPSEEK_API_KEY`. The provider does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own + * endpoint configuration. The provider reports itself not ready for a model request whose search + * would have no credential. * @module @deepseek-ai/dsh-web-search-deepseek */ import type { Volatile } from '@deepseek-ai/cordis' @@ -12,13 +13,11 @@ import type { Volatile } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' -import { credentialRef } from '@deepseek-ai/dsh-credentials' +import { credentialRef, credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' import type { CredentialRef } from '@deepseek-ai/dsh-credentials' -import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { - deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey, -} from '@deepseek-ai/dsh-llm-deepseek' +import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' +import type { RouteCredential } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { @@ -87,20 +86,29 @@ export const Config = z.object({ */ const SEARCH_BASE_URL_ENV = 'DEEPSEEK_SEARCH_BASE_URL' -/** Provider route id `dsh-llm-deepseek-account` registers; `request/context` events record it per Session. */ -const ACCOUNT_PROVIDER = 'deepseek-account' - /** Settings namespace carrying this provider's endpoint, model, and key reference. */ export const WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE = 'web-search-deepseek' /** Options for one search, with the key reference the readiness check reads. */ type SearchOptions = DeepSeekSearchProviderOptions & { readonly apiKeyEnv: CredentialRef } +/** + * The account credential the model route `route` publishes, when it publishes one of that kind. + * @param ctx - plugin context supplying the optional model service. + * @param route - provider route of a model request; undefined names none. + * @returns the route's account credential, or undefined for another kind, no credential, or no route. + * @throws when the route's settings do not resolve. + */ +function accountCredentialOf(ctx: Context, route: string | undefined): RouteCredential | undefined { + const credential = route === undefined ? undefined : ctx.get('llm')?.routeCredential(route) + return credential?.kind === 'account' ? credential : undefined +} + /** * Project one resolved section into the options the provider serves its next * search with. Environment fallbacks stay here rather than in the provider: * every value it reads is already fully defaulted. - * @param ctx - plugin context supplying the credential and environment planes. + * @param ctx - plugin context supplying the credential, model, and environment planes. * @param config - the currently authoritative section. * @returns options for one search. */ @@ -113,15 +121,16 @@ function resolveOptions( : undefined return { ...literalApiKey === undefined ? {} : { apiKey: literalApiKey }, - resolveAccountToken: async (endpoint) => { + resolveAccountCredential: async (endpoint) => { // The latest request context names the route that served the model // request which called this search, as account sign-out reads it. - const provider = ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider - if (provider !== ACCOUNT_PROVIDER) return undefined - return await resolveDeepSeekAccountToken(ctx, endpoint) + const credential = accountCredentialOf(ctx, ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider) + return credential === undefined ? undefined : await credential.resolve(endpoint) + }, + resolveApiKey: async () => { + const value = await resolveCredentialRef(ctx, apiKeyEnv) + return value === undefined ? undefined : assertUsableApiKey(value, name, apiKeyEnv) }, - rejectAccountToken: token => rejectDeepSeekAccountToken(ctx, token), - resolveApiKey: () => resolveDeepSeekApiKey(ctx, apiKeyEnv), apiKeyEnv, baseURL: config.baseURL ?? launchEnvironmentOf(ctx).get(SEARCH_BASE_URL_ENV)?.value @@ -141,27 +150,28 @@ function resolveOptions( /** * Whether the search a model request on `route` would make has a credential, checked in the order - * the search resolves them: the account token first on the account route, then the API key. A failed - * read answers false, because the search fails on that read instead of trying the next credential. - * Only presence is checked: the API key's value is not read and the endpoint is not contacted, so a - * wrong key or an endpoint without native search still counts as configured. - * @param ctx - plugin context supplying the account, credential, and environment planes. + * the search resolves them: the account credential the route publishes first, then the API key. A + * route whose settings do not resolve or a failed read answers false, because the search fails there + * instead of trying the next credential. Only presence is checked: the API key's value is not read + * and the endpoint is not contacted, so a wrong key or an endpoint without native search still + * counts as configured. + * @param ctx - plugin context supplying the model, credential, and environment planes. * @param options - options the next search would use. * @param route - provider route of the model request being assembled. - * @returns whether the account token or an API key is available to that search. + * @returns whether the account credential or an API key is available to that search. */ async function searchConfigured( ctx: Context, options: SearchOptions, route: string | undefined, ): Promise { - const account = ctx.get('deepseekAccount') - if (route === ACCOUNT_PROVIDER && account !== undefined) { - let token: string | undefined - try { token = await account.resolveToken(`${options.baseURL}/messages`) } + let account: RouteCredential | undefined + try { account = accountCredentialOf(ctx, route) } + catch (_unresolvedRoute) { return false /* The search fails on this route before it reads any credential. */ } + if (account !== undefined) { + try { if (await account.configured(`${options.baseURL}/messages`)) return true } catch (_unreadableGrant) { return false /* The search fails on this read before it tries the API key. */ } - if (token !== undefined && token.length > 0) return true } if (options.apiKey !== undefined) return true - try { return await deepSeekApiKeyConfigured(ctx, options.apiKeyEnv) } + try { return await credentialRefConfigured(ctx, options.apiKeyEnv) } catch (_unreadableStore) { return false /* A store that cannot be read supplies no key to the search either. */ } } diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index 32c973946d..ccc14b9f3d 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -14,6 +14,7 @@ import type { WebSearchSource, } from '@deepseek-ai/dsh-web' import type { CredentialRef } from '@deepseek-ai/dsh-credentials' +import type { RouteCredentialGrant } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' import type { AnthropicError, @@ -93,13 +94,11 @@ declare module '@deepseek-ai/dsh-session/types' { /** Resolved provider options (the plugin's `apply` supplies credential and constant defaults). */ export interface DeepSeekSearchProviderOptions { /** - * Resolve the DeepSeek account token for one search endpoint. A token takes - * precedence over every API key and is sent only as `x-dsh-auth-token`; - * `undefined` selects API-key authentication. + * Resolve the DeepSeek account credential for one search endpoint. A credential takes + * precedence over every API key and is sent only through the headers of its grant, which + * also invalidates it after HTTP 401; `undefined` selects API-key authentication. */ - resolveAccountToken?: (endpoint: string) => Promise - /** Invalidate the exact account token rejected by HTTP 401; failures must not replace the search error. */ - rejectAccountToken?: (token: string) => Promise + resolveAccountCredential?: (endpoint: string) => Promise /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */ apiKey?: string /** Resolve the current DeepSeek API key for one search operation. */ @@ -189,11 +188,11 @@ export function mapAnthropicResponse(response: AnthropicResponse): WebSearchResu /** Authentication headers for one search, tagged by the credential that produced them. */ interface SearchAuth { - /** `account` for a DeepSeek account token, `api-key` for an API key. */ + /** `account` for a DeepSeek account credential, `api-key` for an API key. */ readonly kind: 'account' | 'api-key' /** Headers carrying the credential. */ readonly headers: Readonly> - /** Request-bound invalidation, present only when an account token was sent. */ + /** Request-bound invalidation, present when the sent account credential offers one. */ readonly reject?: () => Promise } @@ -226,7 +225,7 @@ export class DeepSeekSearchProvider implements WebSearchProvider { available(): boolean { const options = this.resolveOptions() - return ((options.apiKey?.length ?? 0) > 0 || options.resolveApiKey !== undefined || options.resolveAccountToken !== undefined) + return ((options.apiKey?.length ?? 0) > 0 || options.resolveApiKey !== undefined || options.resolveAccountCredential !== undefined) && URL.canParse(options.baseURL) && isPositiveInteger(options.maxTokens) && isPositiveInteger(options.maxUses) @@ -297,13 +296,12 @@ export class DeepSeekSearchProvider implements WebSearchProvider { // malformed/non-JSON error body (normal for gateway 5xx/429s) can only // cost a richer provider message, never the real error. } - // The account service released this token only for its inference + // The account service released this credential only for its inference // origin, so the endpoint is not what the user must change. if (status === 401 && auth.kind === 'account') { // Invalidation can cancel this Session; finish reading the HTTP failure before it does. A cancelled read - // still invalidates the token the status rejected. - try { await auth.reject?.() } - catch (_credentialRemovalFailed) { /* Report the original failure even if credential removal fails. */ } + // still invalidates the credential the status rejected. + await auth.reject?.() throw aborted ?? accountRejectedError(message) } if (aborted !== undefined) throw aborted @@ -327,18 +325,18 @@ export class DeepSeekSearchProvider implements WebSearchProvider { * @param options - the caller's snapshot, so the credential and the endpoint it is sent to come from one section. * @param endpoint - the Messages endpoint this operation dispatches to. * @param signal - abort signal for the surrounding search. - * @returns the account-token header when one resolves, otherwise the API-key headers, tagged by credential kind. + * @returns the account credential's headers when one resolves, otherwise the API-key headers, tagged by credential kind. */ private async authHeaders( options: DeepSeekSearchProviderOptions, endpoint: string, signal?: AbortSignal, ): Promise { - const { resolveAccountToken, rejectAccountToken } = options - const token = resolveAccountToken === undefined + const { resolveAccountCredential } = options + const credential = resolveAccountCredential === undefined ? undefined - : await resolveCredential(() => resolveAccountToken(endpoint), signal) - if (token !== undefined && token.length > 0) return { - kind: 'account', headers: { 'x-dsh-auth-token': token }, - ...rejectAccountToken === undefined ? {} : { reject: () => rejectAccountToken(token) }, + : await resolveCredential(() => resolveAccountCredential(endpoint), signal) + if (credential !== undefined) { + const invalidate = credential.reject?.bind(credential) + return { kind: 'account', headers: credential.headers, ...invalidate === undefined ? {} : { reject: invalidate } } } const apiKey = await this.apiKey(options, signal) // Official DeepSeek expects `x-api-key`; an Anthropic-compatible proxy @@ -377,9 +375,7 @@ export class DeepSeekSearchProvider implements WebSearchProvider { * @returns the resolved credential, or undefined when the resolver supplied none. * @throws {@link WebError} `WEB_ABORTED` on cancellation, `WEB_PROVIDER_ERROR` when the resolver fails. */ -async function resolveCredential( - resolve: () => Promise, signal?: AbortSignal, -): Promise { +async function resolveCredential(resolve: () => Promise, signal?: AbortSignal): Promise { throwIfSearchAborted(signal) try { return await abortable(resolve(), signal) diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index 3b52fc139a..a1feb29aba 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -11,6 +11,9 @@ import { credentialRef } from '@deepseek-ai/dsh-credentials' import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import LlmRuntime from '@deepseek-ai/dsh-llm' +import type { RouteCredentialGrant } from '@deepseek-ai/dsh-llm' +import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import WebRuntime, { WebError, type WebSearchResult } from '@deepseek-ai/dsh-web' import { @@ -20,6 +23,7 @@ import { import * as deepseekPlugin from '@deepseek-ai/dsh-web-search-deepseek' import { citationSnippets, mapAnthropicResponse } from '../src/provider.ts' import type { AnthropicResponse } from '@deepseek-ai/dsh-web-search-deepseek/src/types.ts' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' /** Construct the provider over a fixed options value; production passes a live thunk. */ import type { DeepSeekSearchProviderOptions } from '@deepseek-ai/dsh-web-search-deepseek' @@ -27,6 +31,22 @@ import type { DeepSeekSearchProviderOptions } from '@deepseek-ai/dsh-web-search- const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchProvider => new DeepSeekSearchProvider(() => options) +/** + * The account credential resolver a route publishes over `token`, with `reject` observing each invalidated token; + * a throwing observer is contained as the account service contains storage failures. + */ +function accountCredential( + token: (endpoint: string) => Promise, reject?: (token: string) => Promise, +): (endpoint: string) => Promise { + return async (endpoint) => { + const value = await token(endpoint) + if (value === undefined || value.length === 0) return undefined + return { headers: { 'x-dsh-auth-token': value }, value, ...reject === undefined ? {} : { reject: async () => { + try { await reject(value) } catch (_storageFailure) { /* Contained as the account service contains it. */ } + } } } + } +} + /** Return the provider's rejected WebError, or propagate an unexpected outcome. */ async function rejectedWebError(operation: Promise): Promise { try { @@ -173,7 +193,7 @@ describe('DeepSeekSearchProvider availability', () => { }) it('is available with only an account token resolver', () => { - expect(searchProvider({ ...options, apiKey: '', resolveAccountToken: async () => 'account-token' }).available()).toBe(true) + expect(searchProvider({ ...options, apiKey: '', resolveAccountCredential: accountCredential(async () => 'account-token') }).available()).toBe(true) }) it('is misconfigured when the base URL is unparseable', () => { @@ -259,7 +279,7 @@ describe('DeepSeekSearchProvider account authentication', () => { 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' }) + await searchProvider({ ...options, resolveAccountCredential: accountCredential(resolveAccountToken), resolveApiKey }).search({ query: 'q' }) const { url, headers } = first() expect(resolveAccountToken).toHaveBeenCalledWith(url) expect(resolveApiKey).not.toHaveBeenCalled() @@ -270,7 +290,7 @@ describe('DeepSeekSearchProvider account authentication', () => { it.each([undefined, ''])('falls back to the API key when the account resolves %j', async (token) => { const { first } = captureFetch() - await searchProvider({ ...options, resolveAccountToken: async () => token }).search({ query: 'q' }) + await searchProvider({ ...options, resolveAccountCredential: accountCredential(async () => token) }).search({ query: 'q' }) const { headers } = first() expect(headers['x-api-key']).toBe('ds-key') expect(headers).not.toHaveProperty('x-dsh-auth-token') @@ -280,7 +300,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const { fetchMock } = captureFetch() await expect(searchProvider({ ...options, - resolveAccountToken: () => Promise.reject(new Error('account storage failed')), + resolveAccountCredential: accountCredential(() => Promise.reject(new Error('account storage failed'))), }).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', @@ -293,7 +313,7 @@ describe('DeepSeekSearchProvider account authentication', () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'invalid token' } }, { status: 401 }))) const error = await rejectedWebError(searchProvider({ ...options, - resolveAccountToken: async () => 'account-token', + resolveAccountCredential: accountCredential(async () => 'account-token'), }).search({ query: 'q' })) expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', @@ -303,11 +323,11 @@ describe('DeepSeekSearchProvider account authentication', () => { }) }) - it.each([false, true])('invalidates the sent account token on 401 and keeps the sign-in guidance when removal fails: %s', async (fails) => { + it.each([false, true])('invalidates the sent account token on 401 and keeps the sign-in guidance whether or not removal fails: %s', async (fails) => { const rejectAccountToken = vi.fn(async (_token: string) => { if (fails) throw new Error('storage failed') }) vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'invalid token' }, { status: 401 }))) const error = await rejectedWebError(searchProvider({ - ...options, resolveAccountToken: async () => 'sent-token', rejectAccountToken, + ...options, resolveAccountCredential: accountCredential(async () => 'sent-token', rejectAccountToken), }).search({ query: 'q' })) expect(error.code).toBe('WEB_PROVIDER_ERROR') expect(error.message).toBe('DeepSeek API error (HTTP 401): invalid token\n\n' @@ -320,7 +340,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const rejectAccountToken = vi.fn(async (_token: string) => {}) vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status }))) const error = await rejectedWebError(searchProvider({ - ...options, resolveAccountToken: async () => token, rejectAccountToken, + ...options, resolveAccountCredential: accountCredential(async () => token, rejectAccountToken), }).search({ query: 'q' })) expect(error.code).toBe('WEB_PROVIDER_ERROR') expect(rejectAccountToken).not.toHaveBeenCalled() @@ -336,7 +356,7 @@ describe('DeepSeekSearchProvider account authentication', () => { vi.stubGlobal('fetch', vi.fn(async () => response)) const rejectAccountToken = vi.fn(async (_token: string) => {}) const error = await rejectedWebError(searchProvider({ - ...options, resolveAccountToken: async () => 'sent-token', rejectAccountToken, + ...options, resolveAccountCredential: accountCredential(async () => 'sent-token', rejectAccountToken), }).search({ query: 'q' }, controller.signal)) expect(error.code).toBe('WEB_ABORTED') expect(rejectAccountToken).toHaveBeenCalledExactlyOnceWith('sent-token') @@ -346,7 +366,7 @@ describe('DeepSeekSearchProvider account authentication', () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 503 }))) const error = await rejectedWebError(searchProvider({ ...options, - resolveAccountToken: async () => 'account-token', + resolveAccountCredential: accountCredential(async () => 'account-token'), }).search({ query: 'q' })) expect(error.message).toContain('Search endpoint configuration is separate from chat.') }) @@ -355,7 +375,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const { fetchMock } = captureFetch() await expect(searchProvider({ ...options, - resolveAccountToken: () => { throw new Error('account service threw') }, + resolveAccountCredential: accountCredential(() => { throw new Error('account service threw') }), }).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', @@ -369,7 +389,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const resolveApiKey = vi.fn(async () => 'resolved-key') const controller = new AbortController() controller.abort(new Error('caller stopped')) - await expect(searchProvider({ ...options, apiKey: '', resolveAccountToken, resolveApiKey }) + await expect(searchProvider({ ...options, apiKey: '', resolveAccountCredential: accountCredential(resolveAccountToken), resolveApiKey }) .search({ query: 'q' }, controller.signal)) .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) expect(resolveAccountToken).not.toHaveBeenCalled() @@ -382,10 +402,10 @@ describe('DeepSeekSearchProvider account authentication', () => { await expect(searchProvider({ ...options, apiKey: '', - resolveAccountToken: async () => { + resolveAccountCredential: accountCredential(async () => { controller.abort(new Error('caller stopped')) return undefined - }, + }), resolveApiKey, }).search({ query: 'q' }, controller.signal)) .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) @@ -397,7 +417,7 @@ describe('DeepSeekSearchProvider account authentication', () => { const controller = new AbortController() const search = searchProvider({ ...options, - resolveAccountToken: () => new Promise(() => {}), + resolveAccountCredential: accountCredential(() => new Promise(() => {})), }).search({ query: 'q' }, controller.signal) controller.abort(new Error('deadline')) await expect(search).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) @@ -764,9 +784,9 @@ describe('web-search-deepseek account route selection', () => { await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) - ctx.provide('deepseekAccount', { - resolveToken: async (url: string) => { asked.push(url); return 'account-token' }, - } as DeepSeekAccount) + await ctx.plugin(LlmRuntime) + await ctx.plugin(AccountRoute, {}) + ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return 'account-token' } })) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) const session = ctx.sessions.create(SessionId(`web-search-account-${provider ?? 'none'}`)) session.append('turn/start', { turn: 1 }) @@ -801,8 +821,9 @@ describe('web-search-deepseek account route selection', () => { await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) - const account: Pick = { resolveToken: async () => current, rejectToken } - ctx.provide('deepseekAccount', account as DeepSeekAccount) + await ctx.plugin(LlmRuntime) + await ctx.plugin(AccountRoute, {}) + ctx.provide('deepseekAccount', accountStub({ token: () => current, reject: rejectToken })) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) const session = ctx.sessions.create(SessionId('web-search-account-late-401')) session.append('turn/start', { turn: 1 }) @@ -816,7 +837,7 @@ describe('web-search-deepseek account route selection', () => { } }) - it.each(['deepseek-official', undefined])('keeps API-key authentication for route %j', async (provider) => { + it.each(['deepseek-official', undefined])('keeps API-key authentication for route %j, whose published credential is no account', async (provider) => { const { headers, asked } = await searchAs(provider) expect(asked).toEqual([]) expect(headers['x-api-key']).toBe('ds-key') @@ -841,7 +862,7 @@ describe('web-search-deepseek search readiness', () => { interface Setup { config?: Record - account?: Pick + account?: DeepSeekAccount credentialsDir?: string } @@ -851,17 +872,16 @@ describe('web-search-deepseek search readiness', () => { * @param asked - receives every URL the account is asked to authenticate. * @returns the account double. */ - function officialOriginAccount(asked: string[] = []): Pick { - return { - resolveToken: (url: string) => { - asked.push(url) - return Promise.resolve(new URL(url).origin === 'https://api.deepseek.com' ? 'account-token' : undefined) - }, - } + function officialOriginAccount(asked: string[] = []): DeepSeekAccount { + return accountStub({ token: (url) => { + asked.push(url) + return new URL(url).origin === 'https://api.deepseek.com' ? 'account-token' : undefined + } }) } /** - * Mount the web seam with the DeepSeek provider selected for search. + * Mount the web seam with the DeepSeek provider selected for search, beside the account model route whose + * published credential the account route answers with. * @param setup - provider config, account double, and credential store. * @returns the composed context. */ @@ -869,10 +889,12 @@ describe('web-search-deepseek search readiness', () => { const ctx = new Context() mounted.push(ctx) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) + await ctx.plugin(LlmRuntime) + await ctx.plugin(AccountRoute, {}) if (setup.credentialsDir !== undefined) { await ctx.plugin(LocalCredentialProvider, { path: join(setup.credentialsDir, '.credentials.yaml'), watch: false }) } - if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account as DeepSeekAccount) + if (setup.account !== undefined) ctx.provide('deepseekAccount', setup.account) await ctx.plugin(deepseekPlugin, setup.config ?? {}) return ctx } @@ -922,9 +944,8 @@ describe('web-search-deepseek search readiness', () => { it.each<[string, Setup]>([ ['a search endpoint outside the account origin', { config: { baseURL: 'https://gateway.test/anthropic/v1' }, account: officialOriginAccount() }], - ['a signed-out account', { account: { resolveToken: () => Promise.resolve(undefined) } }], - ['an empty account token', { account: { resolveToken: () => Promise.resolve('') } }], - ['an unreadable account grant', { account: { resolveToken: () => Promise.reject(new Error('unreadable grant')) } }], + ['a signed-out account', { account: accountStub({ token: () => undefined }) }], + ['an unreadable account grant', { account: accountStub({ token: () => Promise.reject(new Error('unreadable grant')) }) }], ['no account service', {}], ])('is not ready on the account route with %s and no search key', async (_label, setup) => { const ctx = await compose(setup) @@ -967,6 +988,28 @@ describe('web-search-deepseek search readiness', () => { } }) + it('is not ready and fails the search when the initiating route\'s settings do not resolve, despite a literal key', async () => { + const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())) + vi.stubGlobal('fetch', fetchMock) + const ctx = new Context() + mounted.push(ctx) + await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) + ctx.provide('llm', { routeCredential: () => { throw new Error('route settings do not resolve') } } as never) + await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) + expect(await ctx.web.searchReady('deepseek-account')).toBe(false) + expect(await ctx.web.searchReady(undefined)).toBe(true) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + const session = ctx.sessions.create(SessionId('web-search-unresolved-route')) + session.append('turn/start', { turn: 1 }) + session.append('request/context', { provider: 'deepseek-account', model: 'deepseek-v4-flash' }) + const failure = await rejectedWebError(ctx.agents.withInitiator({ session } as Agent, () => ctx.web.search({ query: 'q' }))) + expect(failure.code).toBe('WEB_PROVIDER_ERROR') + expect(failure.message).toContain('route settings do not resolve') + expect(fetchMock).not.toHaveBeenCalled() + }) + it.each<[string, Setup, string | undefined]>([ ['a literal key', { config: { apiKey: 'ds-key' } }, undefined], ['a launch environment key', {}, 'env-key'], @@ -974,7 +1017,7 @@ describe('web-search-deepseek search readiness', () => { if (envKey !== undefined) process.env.DEEPSEEK_API_KEY = envKey const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) - const ctx = await compose({ ...setup, account: { resolveToken: () => Promise.reject(new Error('account storage unreadable')) } }) + const ctx = await compose({ ...setup, account: accountStub({ token: () => Promise.reject(new Error('account storage unreadable')) }) }) expect(await ctx.web.searchReady('deepseek-account')).toBe(false) // A search on that route reads the same grant before any key and fails instead of trying the key. await ctx.plugin(SessionStore) diff --git a/packages/web/web-search-deepseek/tsconfig.json b/packages/web/web-search-deepseek/tsconfig.json index c3f7eec093..bb371f359c 100644 --- a/packages/web/web-search-deepseek/tsconfig.json +++ b/packages/web/web-search-deepseek/tsconfig.json @@ -8,7 +8,6 @@ "src" ], "references": [ - { "path": "../../llm/llm-deepseek" }, { "path": "../../util/launch-environment" }, @@ -34,10 +33,10 @@ "path": "../../credentials/credentials" }, { - "path": "../../credentials/deepseek-account" + "path": "../../util/http-proxy" }, { - "path": "../../util/http-proxy" + "path": "../../llm/llm" } ] } diff --git a/packages/web/web/package.json b/packages/web/web/package.json index 93ce48d033..bf55c66663 100644 --- a/packages/web/web/package.json +++ b/packages/web/web/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-web", - "description": "Abstract web access capability seam (ctx.web) for the DeepSeek Harness — search/fetch provider registry, registration-order-independent selection, request/result vocabulary, and the WebError taxonomy", + "description": "Abstract web access capability seam (ctx.web) for the DeepSeek Harness \u2014 search/fetch provider registry, registration-order-independent selection, request/result vocabulary, and the WebError taxonomy", "version": "0.2.2-rc.1", "publishConfig": { "access": "public" @@ -50,8 +50,8 @@ ], "license": "MIT", "peerDependencies": { - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-package-manifest": "workspace:*", @@ -59,7 +59,7 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "devDependencies": { - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/web/web/src/types.ts b/packages/web/web/src/types.ts index ff632770a4..772c3b368a 100644 --- a/packages/web/web/src/types.ts +++ b/packages/web/web/src/types.ts @@ -5,7 +5,7 @@ * @module @deepseek-ai/dsh-web/types */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' declare module '@deepseek-ai/cordis' { diff --git a/packages/web/web/tsconfig.json b/packages/web/web/tsconfig.json index 601a3e4241..c442590c24 100644 --- a/packages/web/web/tsconfig.json +++ b/packages/web/web/tsconfig.json @@ -18,7 +18,7 @@ "path": "../../../vendor/schemastery" }, { - "path": "../../llm/llm" + "path": "../../util/error" }, { "path": "../../typert/protocol" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0e5a012628..37b70ac998 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -763,7 +763,7 @@ importers: version: link:../../packages/client/ui-theme '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../packages/credentials/deepseek-account + version: link:../../packages/account/deepseek-account '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../packages/util/home-paths @@ -862,7 +862,7 @@ importers: version: link:../../packages/client/connection '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../packages/credentials/deepseek-account + version: link:../../packages/account/deepseek-account '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../packages/host/webserver @@ -1247,6 +1247,37 @@ importers: native/system/packages/linux-x64: {} + packages/account/deepseek-account: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: 4.6.6 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-authorization': + specifier: workspace:* + version: link:../../credentials/authorization + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand + '@deepseek-ai/dsh-credentials': + specifier: workspace:* + version: link:../../credentials/credentials + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../../host/webserver + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + packages/acp/acp: dependencies: '@agentclientprotocol/sdk': @@ -1502,7 +1533,7 @@ importers: version: link:../../credentials/credentials '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-file-reference': specifier: workspace:* version: link:../../context/file-reference @@ -2438,7 +2469,7 @@ importers: version: link:../../credentials/credentials-local '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../../llm/deepseek-llm-api-extensions @@ -3606,7 +3637,7 @@ importers: version: link:../../compaction/compaction '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-host-product-telemetry-otel': specifier: workspace:* version: link:../../host/product-telemetry-otel @@ -3728,7 +3759,7 @@ importers: version: link:../ui-slots '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../host/webserver @@ -5777,7 +5808,7 @@ importers: version: link:../ui-theme '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../host/webserver @@ -8176,9 +8207,9 @@ importers: '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../credentials - '@deepseek-ai/dsh-llm': + '@deepseek-ai/dsh-error': specifier: workspace:* - version: link:../../llm/llm + version: link:../../util/error packages/credentials/credentials: dependencies: @@ -8189,6 +8220,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-launch-environment': + specifier: workspace:* + version: link:../../util/launch-environment packages/credentials/credentials-local: dependencies: @@ -8218,43 +8252,6 @@ importers: specifier: workspace:* version: link:../../util/launch-environment - packages/credentials/deepseek-account: - dependencies: - '@deepseek-ai/schemastery': - specifier: link:../../../vendor/schemastery - version: link:../../../vendor/schemastery - zod: - specifier: 4.6.6 - version: 4.6.6 - devDependencies: - '@deepseek-ai/cordis': - specifier: workspace:~ - version: link:../../../vendor/cordis - '@deepseek-ai/dsh-agent': - specifier: workspace:* - version: link:../../core/agent - '@deepseek-ai/dsh-authorization': - specifier: workspace:* - version: link:../authorization - '@deepseek-ai/dsh-brand': - specifier: workspace:* - version: link:../../util/brand - '@deepseek-ai/dsh-credentials': - specifier: workspace:* - version: link:../credentials - '@deepseek-ai/dsh-host-webserver': - specifier: workspace:* - version: link:../../host/webserver - '@deepseek-ai/dsh-llm': - specifier: workspace:* - version: link:../../llm/llm - '@deepseek-ai/dsh-typert-protocol': - specifier: workspace:* - version: link:../../typert/protocol - '@deepseek-ai/dsh-util-values': - specifier: workspace:* - version: link:../../util/values - packages/deliverables/deliverable-file-references: devDependencies: '@deepseek-ai/cordis': @@ -11608,7 +11605,7 @@ importers: version: link:../../credentials/credentials '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../../llm/deepseek-llm-api-extensions @@ -13334,7 +13331,7 @@ importers: version: link:../../credentials/credentials-local '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../deepseek-llm-api-extensions @@ -13408,9 +13405,12 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../../vendor/loader + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-launch-environment': specifier: workspace:* version: link:../../util/launch-environment @@ -18069,9 +18069,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis - '@deepseek-ai/dsh-llm': + '@deepseek-ai/dsh-error': specifier: workspace:* - version: link:../../llm/llm + version: link:../../util/error packages/web/web-deepseek-api: dependencies: @@ -18082,9 +18082,6 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis - '@deepseek-ai/cordis-plugin-loader': - specifier: workspace:~ - version: link:../../../vendor/loader '@deepseek-ai/dsh-agent': specifier: workspace:* version: link:../../core/agent @@ -18099,7 +18096,7 @@ importers: version: link:../../credentials/credentials-local '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-http-proxy': specifier: workspace:* version: link:../../util/http-proxy @@ -18109,9 +18106,6 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm - '@deepseek-ai/dsh-llm-deepseek': - specifier: workspace:* - version: link:../../llm/llm-deepseek '@deepseek-ai/dsh-llm-deepseek-account': specifier: workspace:* version: link:../../llm/llm-deepseek-account @@ -18170,16 +18164,19 @@ importers: version: link:../../credentials/credentials-local '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account + version: link:../../account/deepseek-account '@deepseek-ai/dsh-http-proxy': specifier: workspace:* version: link:../../util/http-proxy '@deepseek-ai/dsh-launch-environment': specifier: workspace:* version: link:../../util/launch-environment - '@deepseek-ai/dsh-llm-deepseek': + '@deepseek-ai/dsh-llm': specifier: workspace:* - version: link:../../llm/llm-deepseek + version: link:../../llm/llm + '@deepseek-ai/dsh-llm-deepseek-account': + specifier: workspace:* + version: link:../../llm/llm-deepseek-account '@deepseek-ai/dsh-session': specifier: workspace:* version: link:../../core/session @@ -18497,7 +18494,7 @@ importers: version: link:../../packages/credentials/credentials '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../packages/credentials/deepseek-account + version: link:../../packages/account/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../../packages/llm/deepseek-llm-api-extensions diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 88fc939459..665df52875 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -87,7 +87,7 @@ export const SERVICE_PAGE: Record = { compaction: 'compaction.md', cordisInspect: 'extensions.md', authorization: 'credentials.md', - deepseekAccount: 'credentials.md', + deepseekAccount: 'account.md', credentials: 'credentials.md', credentialsController: 'credentials.md', settingsController: 'settings.md', @@ -248,7 +248,7 @@ export const EVENT_SCOPE_PAGE: Record = { 'cordis': 'extensions.md', 'authorization': 'credentials.md', 'credentials': 'credentials.md', - 'deepseek-account': 'credentials.md', + 'deepseek-account': 'account.md', 'domain': 'storage.md', 'forge': 'forge.md', 'fs': 'filesystem.md', @@ -475,6 +475,7 @@ export const LINK_MAP: Readonly> = { LlmResolvedModelInfo: 'llm-streaming.md', LlmFailure: 'llm-streaming.md', LlmImageRequestPricing: 'llm-streaming.md', + RouteCredential: 'llm-streaming.md', LlmModelInfo: 'llm-streaming.md', LlmProviderInfo: 'llm-streaming.md', LlmConfigurableProvider: 'llm-streaming.md', @@ -894,18 +895,19 @@ export const LINK_MAP: Readonly> = { AuthorizationMethod: 'credentials.md', AuthorizationNotice: 'credentials.md', AuthorizationOutcome: 'credentials.md', - AccountView: 'credentials.md', - AccountUpdate: 'credentials.md', - AccountDetails: 'credentials.md', - AccountClientMetadata: 'credentials.md', - AccountNotificationBatch: 'credentials.md', - AccountNotificationId: 'credentials.md', - AccountNotification: 'credentials.md', - AccountNotificationAction: 'credentials.md', - AccountNotificationEvent: 'credentials.md', - AccountUserId: 'credentials.md', - PlatformSession: 'credentials.md', - SignInAttemptId: 'credentials.md', + AccountView: 'account.md', + AccountUpdate: 'account.md', + AccountDetails: 'account.md', + AccountClientMetadata: 'account.md', + AccountNotificationBatch: 'account.md', + AccountNotificationId: 'account.md', + AccountNotification: 'account.md', + AccountNotificationAction: 'account.md', + AccountNotificationEvent: 'account.md', + AccountRequestCredential: 'account.md', + AccountUserId: 'account.md', + PlatformSession: 'account.md', + SignInAttemptId: 'account.md', AuthorizationPrompt: 'credentials.md', AuthorizationRequest: 'credentials.md', AuthorizationSession: 'credentials.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 6643bd5b44..8bcf3227f4 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -296,8 +296,8 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'LLM adapter registry', mode: 'seam', implementations: ['llm-deepseek', 'llm-pi-ai', 'llm-replay'], - consumers: ['agent-loop', 'compaction-basic'], - note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.', + consumers: ['agent-loop', 'compaction-basic', 'web-deepseek-api', 'web-search-deepseek'], + note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service, and the DeepSeek web providers read the credential a route publishes.', }, { key: 'sessionLogDeepSeek', @@ -486,7 +486,7 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Credential seam', mode: 'seam', implementations: ['credentials-local'], - consumers: ['api-settings-controller', 'llm-deepseek', 'llm-pi-ai'], + consumers: ['api-settings-controller', 'llm-deepseek-api-key', 'llm-pi-ai', 'web-deepseek-api', 'web-search-deepseek'], note: 'Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage.', }, { @@ -495,8 +495,8 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'DeepSeek account', mode: 'service', implementations: [], - consumers: ['llm-deepseek'], - note: 'The Host owns browser authorization and local credentials; UI consumers receive state without tokens.', + consumers: ['llm-deepseek-account', 'web-deepseek-api'], + note: 'The Host owns browser authorization and local credentials and releases per-request credentials to the account model route and the web providers; UI consumers receive state without tokens.', }, { key: 'authorization', diff --git a/scripts/plugin-entry-existing-exports.ts b/scripts/plugin-entry-existing-exports.ts index 70a12fd14b..4966421efe 100644 --- a/scripts/plugin-entry-existing-exports.ts +++ b/scripts/plugin-entry-existing-exports.ts @@ -109,8 +109,6 @@ export const EXISTING_PLUGIN_ENTRY_EXPORTS = { 'projectToolUpdates', 'requestImageHandleText', 'requiredImageOffload', 'resolveImageAttachmentAccess', 'resolveRetryPolicy', 'runFirstTokenTime', 'runFirstVisibleTime', 'textOnlyImageText', 'userAgent', ], - '@deepseek-ai/dsh-llm-deepseek-account': ['plainAccountOptions', 'resolveAccountOptions'], - '@deepseek-ai/dsh-llm-deepseek-api-key': ['plainOptions', 'resolveAdapterOptions'], '@deepseek-ai/dsh-llm-pi-ai': ['PiAiAdapter', 'recordKeyFor', 'supportedProtocols'], '@deepseek-ai/dsh-llm-replay': [ 'deriveReplayScript', 'installLlmReplay', 'loadReplayScript', 'loadSessionScripts', 'parseSessionHeader', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 43725880bf..1435978ba4 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1842,6 +1842,16 @@ "symbol": "LlmNativeAuth", "source": "packages/llm/llm/src/types.ts" }, + { + "doc": "docs/subsystems/llm-streaming.md", + "symbol": "RouteCredentialGrant", + "source": "packages/llm/llm/src/types.ts" + }, + { + "doc": "docs/subsystems/llm-streaming.md", + "symbol": "RouteCredential", + "source": "packages/llm/llm/src/types.ts" + }, { "doc": "docs/subsystems/permission-presets.md", "symbol": "Config", diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 6424868d38..c3c54ca0f5 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -88,7 +88,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/computer-use/computer-use': { kind: 'none', reason: 'The registry only reserves provider names; providers own all model-facing tools and guidance.' }, 'packages/document/office-kit': { kind: 'indirect', reason: 'The provider returns rendered and converted bytes; the Office tools own their model-visible results.' }, - 'packages/credentials/deepseek-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, + 'packages/account/deepseek-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, 'packages/client/ui-settings-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, 'packages/client/ui-account-notifications': { kind: 'none', reason: 'Account notification presentation and polling add no model input or Session events.' }, diff --git a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs index a3891bc5b0..c2fcfcf89b 100644 --- a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs +++ b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs @@ -34,8 +34,9 @@ function transportInput(input, transportEndpoint) { /** Provide the signed-in account and start the Search endpoint; both end with the plugin fiber. */ export async function apply(ctx) { ctx.provide('deepseekAccount', { - resolveToken: async endpoint => endpoint.startsWith('https://api.deepseek.com/') ? ACCOUNT_TOKEN : undefined, - rejectToken: async () => {}, + resolveRequestCredential: async endpoint => endpoint.startsWith('https://api.deepseek.com/') + ? { headers: { 'x-dsh-auth-token': ACCOUNT_TOKEN }, value: ACCOUNT_TOKEN, reject: async () => {} } + : undefined, }) let restoreFetch = () => {} await applyLoopbackServerEffect(ctx, { diff --git a/tsconfig.base.json b/tsconfig.base.json index cbceac1a3f..56d6cbd202 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -52,9 +52,9 @@ "@deepseek-ai/dsh-client-ui-settings-account": ["./packages/client/ui-settings-account/src/index.ts"], "@deepseek-ai/dsh-client-ui-settings-account/client": ["./packages/client/ui-settings-account/src/client/index.ts"], "@deepseek-ai/dsh-api-gateway/stream-protocol": ["./packages/api/gateway/src/stream-protocol.ts"], - "@deepseek-ai/dsh-deepseek-account": ["./packages/credentials/deepseek-account/src/index.ts"], - "@deepseek-ai/dsh-deepseek-account/types": ["./packages/credentials/deepseek-account/src/types.ts"], - "@deepseek-ai/dsh-deepseek-account/client-metadata": ["./packages/credentials/deepseek-account/src/client-metadata.ts"], + "@deepseek-ai/dsh-deepseek-account": ["./packages/account/deepseek-account/src/index.ts"], + "@deepseek-ai/dsh-deepseek-account/types": ["./packages/account/deepseek-account/src/types.ts"], + "@deepseek-ai/dsh-deepseek-account/client-metadata": ["./packages/account/deepseek-account/src/client-metadata.ts"], "@deepseek-ai/dsh-experimental-speech-to-text": ["./packages/experimental/speech-to-text/src/index.ts"], "@deepseek-ai/dsh-experimental-translator": ["./packages/experimental/translator/src/index.ts"], "@deepseek-ai/dsh-experimental-translator/types": ["./packages/experimental/translator/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index c2eb718f3a..bdec67243a 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -333,7 +333,7 @@ { "path": "./packages/document/office-kit" }, { "path": "./packages/document/tool-office" }, - { "path": "./packages/credentials/deepseek-account" }, + { "path": "./packages/account/deepseek-account" }, { "path": "./packages/client/ui-deliverables/tsconfig.host.json" }, { "path": "./vendor/cosmokit" }, { "path": "./vendor/schemastery" }, From 2ba494e53395ad2af75500a6e7ae9446d10b6a25 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Tue, 10 Nov 2026 20:08:25 +0800 Subject: [PATCH 02/16] refactor(llm): drop stale credential references from the llm-deepseek project --- packages/llm/llm-deepseek/tsconfig.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/llm/llm-deepseek/tsconfig.json b/packages/llm/llm-deepseek/tsconfig.json index e307eab423..d7b5af77a3 100644 --- a/packages/llm/llm-deepseek/tsconfig.json +++ b/packages/llm/llm-deepseek/tsconfig.json @@ -8,8 +8,6 @@ "src" ], "references": [ - { "path": "../../credentials/credentials" }, - { "path": "../../account/deepseek-account" }, { "path": "../../../vendor/cosmokit" }, From 48a20b9d0379f1e26b780c5ec04ff8820f09a012 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Wed, 11 Nov 2026 12:54:18 +0800 Subject: [PATCH 03/16] docs(upgrade-guide): move the route credential guide to v0.2.2-rc.2 --- .../2026-11-10-llm-route-credential-seam.i18n.yaml | 4 ++-- .../architecture/2026-11-10-llm-route-credential-seam.md | 2 +- .../architecture/2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../llm-route-credential/guide.i18n.yaml | 6 +++--- .../llm-route-credential/guide.md | 0 .../llm-route-credential/guide.zh.md | 0 6 files changed, 7 insertions(+), 7 deletions(-) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/llm-route-credential/guide.i18n.yaml (87%) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/llm-route-credential/guide.md (100%) rename docs/upgrade-guide/{v0.2.2-rc.1 => v0.2.2-rc.2}/llm-route-credential/guide.zh.md (100%) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 2d080f2a52..957eb36d50 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -15,5 +15,5 @@ en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: - en: e558492c672907dc - zh: 3748557528dc3055 + en: f96508aa7cea1e87 + zh: 3eb61bdce43590bc diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index 9e73be3c88..f3af0daf41 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -34,4 +34,4 @@ The web providers consume publications. `web-deepseek-api` builds each operation ## Consequences -Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. +Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 663d216dff..497aec414d 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -34,4 +34,4 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route ## 后果 -新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 +新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml similarity index 87% rename from docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml rename to docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index 752379e39f..feb25c5ab8 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -1,13 +1,13 @@ # Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md /: en: f0cf30e5430471e8 zh: 2e6e871797dfdd6b /deepseek-routes-publish-the-credential-web-consumers-reuse: - en: d7412a58aadc57a0 - zh: 82243a8cd8563083 + en: f0139803159ee9c9 + zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: en: 7a63f24e07fb3d33 zh: 99c64684a589088e diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.md rename to docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md diff --git a/docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.1/llm-route-credential/guide.zh.md rename to docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md From 7d83af645cd64a0d850f524dc0e099e7b07cca28 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Wed, 11 Nov 2026 19:33:52 +0800 Subject: [PATCH 04/16] docs(llm): fix route credential contracts and the package index budget - RouteCredential.configured: the owner may read its store to answer; the contract no longer claims "without reading the credential's value". Same text in the source JSDoc, both llm-streaming type-equiv blocks, and the seam Agent Note. - llm-deepseek README: replace the stale resolveAuth(connection) summary with the resolveAuth(connection, endpoint) contract. - llm-deepseek-account README: the listing cache is keyed by a SHA-256 of the credential headers, not of the token. - web-deepseek-api tests/routes.ts: note that composition.spec.ts covers the real route plugins. - packages/README: restore the document/, credentials/, and util/ rows and raise the verify-doc-budgets ceiling to 1,060 for the account/ row. --- .../2026-11-10-llm-route-credential-seam.i18n.yaml | 4 ++-- .../architecture/2026-11-10-llm-route-credential-seam.md | 2 +- .../architecture/2026-11-10-llm-route-credential-seam.zh.md | 2 +- docs/AGENTS.md | 2 +- docs/subsystems/llm-streaming.md | 4 ++-- docs/subsystems/llm-streaming.zh.md | 4 ++-- packages/README.i18n.yaml | 4 ++-- packages/README.md | 6 +++--- packages/README.zh.md | 6 +++--- packages/llm/llm-deepseek-account/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek-account/README.md | 2 +- packages/llm/llm-deepseek-account/README.zh.md | 2 +- packages/llm/llm-deepseek/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek/README.md | 2 +- packages/llm/llm-deepseek/README.zh.md | 2 +- packages/llm/llm/src/types.ts | 4 ++-- packages/web/web-deepseek-api/tests/routes.ts | 6 +++++- scripts/doc-budgets.manifest.json | 2 +- 18 files changed, 33 insertions(+), 29 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 957eb36d50..6926949697 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,8 +9,8 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: d7f7ef9ed3038ef7 - zh: c003e6b3338d1f3e + en: 5819b658fc81482d + zh: 948e9cb0a668e623 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index f3af0daf41..ba7c05d753 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -10,7 +10,7 @@ Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/ ## Decision -`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that read no value, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, and an optional `reject()` for HTTP 401. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. +`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, and an optional `reject()` for HTTP 401. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. `@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The listing cache scopes by endpoint and a hash of the credential headers. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 497aec414d..9651ca13d6 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不读取值的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`,以及可选的 HTTP 401 `reject()`。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`,以及可选的 HTTP 401 `reject()`。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 `@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。列表缓存以端点和凭据请求头的哈希划分作用域。 diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 818f40b452..d27a99ce49 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -56,7 +56,7 @@ When the gate goes red: 2. **Condense** content that belongs here but can be shorter. 3. **Raise** the ceiling only when the words need the space; justify the manifest diff in the PR. A too-low ceiling is a budget bug. -Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 994; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. +Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 2,080; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 1,060; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. ## The slop checklist diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 5b90d98955..4ab60ea418 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -582,8 +582,8 @@ interface RouteCredential { readonly reference?: string /** * Whether {@link resolve} would release a credential for `endpoint`, checked - * without reading the credential's value, validating it, or contacting the - * destination. Store failures reject. + * without validating the credential or contacting the destination; the owner + * may read its store to answer. Store failures reject. * @param endpoint - absolute URL the credential would be sent to. * @returns whether a credential is configured for that destination. */ diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index f6683eb136..19a694ea5e 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -588,8 +588,8 @@ interface RouteCredential { readonly reference?: string /** * Whether {@link resolve} would release a credential for `endpoint`, checked - * without reading the credential's value, validating it, or contacting the - * destination. Store failures reject. + * without validating the credential or contacting the destination; the owner + * may read its store to answer. Store failures reject. * @param endpoint - absolute URL the credential would be sent to. * @returns whether a credential is configured for that destination. */ diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 81357d69c5..aad4b43c53 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -15,8 +15,8 @@ en: ffc55792d6e922e1 zh: 83bd759638857e2d /packages/package-groups: - en: 2f76ab75d2b0b872 - zh: 7e6ce5f883d805c9 + en: d9e9a1a89c88f2e1 + zh: b48ff513befdad5b /packages/release-expectations: en: 236081c1659b25ab zh: 809110adf003802e diff --git a/packages/README.md b/packages/README.md index a8c0dbc993..426b6c25ab 100644 --- a/packages/README.md +++ b/packages/README.md @@ -57,7 +57,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`experimental/`](experimental/README.md) | Capabilities under evaluation; [status and support policy](experimental/README.md#status) | | [`workflow/`](workflow/README.md) | Workflow seam, PTC process engine, and the model-facing `workflow` tool | | [`web/`](web/README.md) | Web capability family: seam, search/fetch providers, model-facing web tools | -| [`document/`](document/README.md) | Host Office rendering, conversion, and recalculation, the Office tools, and Kit engine resolution | +| [`document/`](document/README.md) | Shared Host Office rendering, conversion, and recalculation, the Office tools, and Kit engine resolution | | [`attachment/`](attachment/README.md) | Durable attachment identity, validation, local content-addressed storage | | [`spill/`](spill/README.md) | Spill capability family: storage seam, local impl, tool-result spill policy | | [`todo/`](todo/README.md) | The model-facing `todo_write` tool | @@ -70,7 +70,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`session/`](session/README.md) | Durable session data plane: persistence seam + backends, projection seam, log-backed titles, session reporting | | [`session-query/`](session-query/README.md) | Session retrieval family: logical corpus, bounded reads, lineage, semantic filtering, SQLite full-text search | | [`settings/`](settings/README.md) | User-settings seam + file-backed provider | -| [`credentials/`](credentials/README.md) | Credential reference and record seam, env-over-`.env` provider, and authorization flows that ask a human | +| [`credentials/`](credentials/README.md) | Credential-reference and credential-record seam + env-over-`.env` provider + authorization flows that ask a human | | [`account/`](account/README.md) | DeepSeek account sign-in and Host-only request credentials | | [`storage/`](storage/README.md) | Non-session storage hub + backends + domain form | | [`workspace/`](workspace/README.md) | Workspace entity | @@ -81,7 +81,7 @@ Every package lives in exactly one group; new packages join existing groups, and | [`host/`](host/README.md) | Web GUI host services, directory picking, application launch, plugin inventory, and product telemetry | | [`client/`](client/README.md) | Web-GUI browser half: shell, wire, object services, slots, `ui-*` plugins | | [`test-support/`](test-support/README.md) | Test infrastructure (testkits, replay, Loader smokes) | -| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups | +| [`util/`](util/README.md) | Low-level utilities and data-only package lists shared across groups (`Branded`, home/path helpers, timeout, retention, official bundle lists) | ----- diff --git a/packages/README.zh.md b/packages/README.zh.md index fda5527ba1..14332e87fd 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -57,7 +57,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`experimental/`](experimental/README.zh.md) | 仍在评估中的能力;[状态与支持策略](experimental/README.zh.md#status) | | [`workflow/`](workflow/README.zh.md) | 工作流 seam、PTC 进程引擎、面向模型的 `workflow` 工具 | | [`web/`](web/README.zh.md) | Web 能力系列:seam、搜索/获取提供方、面向模型的 Web 工具 | -| [`document/`](document/README.zh.md) | 宿主 Office 渲染、转换与重算、Office 工具与 Kit 引擎解析 | +| [`document/`](document/README.zh.md) | 共享宿主 Office 渲染、转换与重算、Office 工具与 Kit 引擎解析 | | [`attachment/`](attachment/README.zh.md) | 持久附件标识、校验、本地内容寻址存储 | | [`spill/`](spill/README.zh.md) | spill 能力系列:存储 seam、本地实现、工具结果 spill 策略 | | [`todo/`](todo/README.zh.md) | 面向模型的 `todo_write` 工具 | @@ -70,7 +70,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`session/`](session/README.zh.md) | 持久会话数据平面:持久化 seam + 后端、投影 seam、基于日志的标题、会话上报 | | [`session-query/`](session-query/README.zh.md) | 会话检索系列:逻辑语料库、有界读取、血缘、语义过滤、SQLite 全文搜索 | | [`settings/`](settings/README.zh.md) | 用户设置 seam + 基于文件的提供方 | -| [`credentials/`](credentials/README.zh.md) | 凭据引用与记录 seam、环境变量优先于 `.env` 的提供方,以及需要向人询问的授权流程 | +| [`credentials/`](credentials/README.zh.md) | 凭据引用与凭据记录 seam + 环境变量优先于 `.env` 的提供方 + 需要向人询问的授权流程 | | [`account/`](account/README.zh.md) | DeepSeek 账号登录与仅限 Host 的请求凭据 | | [`storage/`](storage/README.zh.md) | 非会话存储中枢 + 后端 + 领域形式 | | [`workspace/`](workspace/README.zh.md) | Workspace 实体 | @@ -81,7 +81,7 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`host/`](host/README.zh.md) | Web GUI 宿主服务、目录选择、应用启动、插件清单和产品遥测 | | [`client/`](client/README.zh.md) | web GUI 浏览器半侧:shell、协议层、对象服务、slot、`ui-*` 插件 | | [`test-support/`](test-support/README.zh.md) | 测试基础设施(testkit、回放、Loader 冒烟测试) | -| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表 | +| [`util/`](util/README.zh.md) | 组间共享的低层工具与纯数据包列表(`Branded`、home/路径辅助函数、超时、留存、官方组合包列表) | ----- diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index b2cab10d84..580d4e4d87 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -18,8 +18,8 @@ en: 3d952599a9b0bf85 zh: 231c0331a7d217e3 /deepseek-ai-dsh-llm-deepseek-account/understand-the-implementation: - en: ee65c14a90dfa0dd - zh: 91778b3e940da7f7 + en: 37319d3b3317b0cf + zh: 90362d4dff489e35 /deepseek-ai-dsh-llm-deepseek-account/further-exploration: en: 30a69b9c66d89580 zh: fcc026a6373c1bee diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index 9b5ee9f706..17322210bb 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -63,7 +63,7 @@ The settings namespace is the Cordis entry id, or the plugin name without an ent ## Understand the implementation -Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the token. +Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the credential headers. A failed request the shared transport classifies as `QUOTA` is rewritten to `ACCOUNT_QUOTA` before it leaves this provider, covering an HTTP 402 response and an in-band SSE error alike. The shared transport and the `deepseek-official` route keep `QUOTA`, so the account route's top-up action never appears for an API-key or third-party failure. diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index 2f6958d366..26d6694096 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -63,7 +63,7 @@ kind: "package-reference" ## 理解实现 -账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和 token 的 SHA-256 为键。 +账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和凭据请求头的 SHA-256 为键。 共享传输判定为 `QUOTA` 的失败请求离开本提供方前会被改写为 `ACCOUNT_QUOTA`,HTTP 402 响应与流内 SSE 错误都适用。共享传输与 `deepseek-official` 路由保留 `QUOTA`,因此账号路由的充值操作不会出现在 API Key 或第三方失败上。 diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 68db96e254..47f19261a6 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -9,8 +9,8 @@ en: e66a018af9e2de3c zh: d7188003d01964bb /deepseek-ai-dsh-llm-deepseek/summary: - en: a8871f9ce192ac6a - zh: 7d642e993f4ca71c + en: dc3675dcd430459e + zh: 4abf101572e2e595 /deepseek-ai-dsh-llm-deepseek/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 5333f68e3c..04404624b7 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Provide the shared DeepSeek Messages transport, request configuration, and model capabilities. Compose [API-key](../llm-deepseek-api-key/README.md) or [account](../llm-deepseek-account/README.md) plugins for authentication, model discovery, and provider registration. Valid settings changes affect subsequent calls while in-flight calls retain their configuration. This package can run beside the [pi-ai adapter](../llm-pi-ai/README.md). -`resolveAuth(connection)` returns the provider-owned authentication headers and an optional failure callback bound to that request’s credential. Messages and Files send those headers without selecting a credential mode. Upload reuse is isolated by endpoint and a hash of the authentication headers; raw credentials are not persisted. +`resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: its headers, its bare value, and an optional failure callback, or `undefined` when none is configured. Messages and Files send those headers without selecting a credential mode. Upload reuse is isolated by endpoint and a hash of the authentication headers; raw credentials are not persisted. ## Table of Contents diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 8a83625697..142674331c 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 提供共享的 DeepSeek Messages 传输、请求配置和模型能力。组合 [API key](../llm-deepseek-api-key/README.zh.md) 或[账号](../llm-deepseek-account/README.zh.md)插件以提供鉴权、模型发现与 provider 注册。有效的设置更改在后续请求生效,进行中的请求保留原配置。本包可与 [pi-ai 适配器](../llm-pi-ai/README.zh.md)并用。 -`resolveAuth(connection)` 返回提供方持有的鉴权请求头,以及绑定本次请求凭据的可选失败回调。Messages 和 Files 直接使用这些请求头,不判断凭据类型。上传复用按端点和鉴权请求头的哈希隔离,不持久化原始凭据。 +`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:请求头、裸凭据值以及可选的失败回调;未配置时返回 `undefined`。Messages 和 Files 直接使用这些请求头,不判断凭据类型。上传复用按端点和鉴权请求头的哈希隔离,不持久化原始凭据。 ## 目录 diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 53b0acb3e4..a17f8d6de0 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -356,8 +356,8 @@ export interface RouteCredential { readonly reference?: string /** * Whether {@link resolve} would release a credential for `endpoint`, checked - * without reading the credential's value, validating it, or contacting the - * destination. Store failures reject. + * without validating the credential or contacting the destination; the owner + * may read its store to answer. Store failures reject. * @param endpoint - absolute URL the credential would be sent to. * @returns whether a credential is configured for that destination. */ diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index 620a3b87f5..4180bb486d 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -1,4 +1,8 @@ -/** A stand-in model service publishing DeepSeek route credentials the way the route plugins do. */ +/** + * A stand-in model service publishing DeepSeek route credentials the way the route plugins do. It reimplements their + * publication over the plugins' config resolvers, so `composition.spec.ts`, which boots the real route plugins through + * the Loader, is what covers the production path. + */ import type { Context } from '@deepseek-ai/cordis' import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' import type {} from '@deepseek-ai/dsh-deepseek-account' diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index f301060236..4e37f05fcc 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -5,5 +5,5 @@ "docs/cordis-primer.md": 600, "docs/testing.md": 1350, "packages/AGENTS.md": 810, - "packages/README.md": 994 + "packages/README.md": 1060 } From 3ca18d169ff795f48ec652994359aede596ffc05 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Wed, 11 Nov 2026 20:29:37 +0800 Subject: [PATCH 05/16] fix(account): invalidate a rejected token on the account service mounted at rejection - deepseek-account: the request credential's reject() re-resolves the account service through the resolving context, so a reload between a request and the destination's HTTP 401 still removes the stored grant; without a mounted service the grant stays for the next one to reject. resolveToken and rejectToken become private; the e2e sign-in stand-in and the generated API catalog follow. - llm-deepseek: routeCredential().resolve() publishes the grant's headers, value, and rejection only, keeping the adapter's onRequestError behind the seam. - web-deepseek-api: a route publishing an unparsable base URL becomes a misconfigured source instead of throwing from readiness or dispatch. --- apps/web/tests/cot-translation-paid.e2e.ts | 6 +- docs/subsystems/account.i18n.yaml | 8 +- docs/subsystems/account.md | 21 +---- docs/subsystems/account.zh.md | 21 +---- .../llm-route-credential/guide.i18n.yaml | 4 +- .../v0.2.2-rc.2/llm-route-credential/guide.md | 4 +- .../llm-route-credential/guide.zh.md | 4 +- .../account/deepseek-account/README.i18n.yaml | 8 +- packages/account/deepseek-account/README.md | 6 +- .../account/deepseek-account/README.zh.md | 6 +- .../account/deepseek-account/src/index.ts | 12 ++- .../account/deepseek-account/src/types.ts | 5 +- .../deepseek-account/tests/account.spec.ts | 91 +++++++++++++++---- .../extensions/tool-cordis/src/api-catalog.ts | 14 +-- packages/llm/llm-deepseek/src/adapter.ts | 6 +- packages/llm/llm-deepseek/src/types.ts | 5 +- .../tests/route-credential.spec.ts | 18 +++- packages/web/web-deepseek-api/src/index.ts | 14 +-- .../tests/credential-resolution.spec.ts | 11 +++ packages/web/web-deepseek-api/tests/routes.ts | 6 +- 20 files changed, 162 insertions(+), 108 deletions(-) diff --git a/apps/web/tests/cot-translation-paid.e2e.ts b/apps/web/tests/cot-translation-paid.e2e.ts index 37c2199298..7648cbe3ff 100644 --- a/apps/web/tests/cot-translation-paid.e2e.ts +++ b/apps/web/tests/cot-translation-paid.e2e.ts @@ -142,8 +142,10 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr const account = scaffold.ctx.get('deepseekAccount') if (account === undefined) throw new Error('Shipped native Account service is absent') // Only credential acquisition is nondeterministic; the Loader-owned native route and wire remain real. - const auth = vi.spyOn(account, 'resolveToken').mockImplementation(async (url: string) => - new URL(url).origin === origin ? 'paid-browser-fixture-token' : undefined) + const auth = vi.spyOn(account, 'resolveRequestCredential').mockImplementation(async (url: string) => + new URL(url).origin === origin + ? { headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token', reject: () => Promise.resolve() } + : undefined) resources.restoreAuth = () => { auth.mockRestore() } scaffold.ctx.emit('llm/adapters-updated') const owner = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'llm-deepseek-account') diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index 90e4efdb1c..b202a8713e 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -6,11 +6,11 @@ en: 2302e2999588bac3 zh: 5e0ac058b50036dc /deepseek-account/request-credentials: - en: 76f2eb1df1948c8a - zh: 70f698243f8e3ae8 + en: 808ace524e0dbc0b + zh: c4268221fa4c1c09 /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e /deepseek-account/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit: - en: b2c8c533124a121c - zh: c2a5c227b5a01146 + en: 3065c17cb319f756 + zh: e69c2692a109c38b diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md index 0706d14f80..b3a20e14ff 100644 --- a/docs/subsystems/account.md +++ b/docs/subsystems/account.md @@ -8,7 +8,7 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun ## Request credentials -`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `resolveToken(url)` returns the bare token under the same policy for consumers that compose their own request, and `rejectToken(token)` is the invalidation `reject()` performs. +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`. @@ -81,13 +81,6 @@ Account login, credentials, and client-safe Remote operations. */ @Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -async rejectToken(token: string): Promise - /** * Read existing login identity without creating a device or returning credentials. * @returns optional device/account identifiers and the provider's OS version string. @@ -101,16 +94,10 @@ async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; */ async getPlatformSession(): Promise -/** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. - */ -async resolveToken(url: string): Promise - /** * Release the account credential for one request to `url` as the request - * carries it, together with its invalidation. Host-only. + * carries it, together with its invalidation, which runs on the account + * service mounted when it is called. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ @@ -229,6 +216,6 @@ Local grant removal has completed. Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) -The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken, resolveRequestCredential, registerRunningTaskReport, and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/account/deepseek-account/README.md). +The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveRequestCredential, registerRunningTaskReport, and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/account/deepseek-account/README.md). `AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries. diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index 45d5d03973..341b2923ac 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,7 +8,7 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`resolveToken(url)` 在同一策略下为自行组装请求的消费方返回裸 token,`rejectToken(token)` 则是 `reject()` 执行的失效操作。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。 按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责。 @@ -81,13 +81,6 @@ Account login, credentials, and client-safe Remote operations. */ @Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -async rejectToken(token: string): Promise - /** * Read existing login identity without creating a device or returning credentials. * @returns optional device/account identifiers and the provider's OS version string. @@ -101,16 +94,10 @@ async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; */ async getPlatformSession(): Promise -/** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. - */ -async resolveToken(url: string): Promise - /** * Release the account credential for one request to `url` as the request - * carries it, together with its invalidation. Host-only. + * carries it, together with its invalidation, which runs on the account + * service mounted when it is called. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ @@ -229,6 +216,6 @@ Local grant removal has completed. Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts) -账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken、resolveRequestCredential、registerRunningTaskReport 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/account/deepseek-account/README.zh.md)。 +账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveRequestCredential、registerRunningTaskReport 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/account/deepseek-account/README.zh.md)。 `AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index feb25c5ab8..224eac372f 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -9,8 +9,8 @@ en: f0139803159ee9c9 zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: - en: 7a63f24e07fb3d33 - zh: 99c64684a589088e + en: 09ab43933a9e5950 + zh: a18da5d560cf0c9f /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: en: 64ac045c8d9a1336 zh: 4712f6eacd85a151 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md index 2ec50f9a98..996805e3ee 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md @@ -9,13 +9,13 @@ English | [中文](guide.zh.md) ## Change -`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a value-free `configured(endpoint)` check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`. +`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`. `@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional. `@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report. -`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)`; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. +`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. `@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id without a published credential counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md index 187434d603..18fdd11b89 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md @@ -9,13 +9,13 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 ## 变更 -`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、不读取值的 `configured(endpoint)` 检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。 +`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。 `@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 `@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。 -`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 +`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 `@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 diff --git a/packages/account/deepseek-account/README.i18n.yaml b/packages/account/deepseek-account/README.i18n.yaml index 95ce3a191b..e9ec42ad16 100644 --- a/packages/account/deepseek-account/README.i18n.yaml +++ b/packages/account/deepseek-account/README.i18n.yaml @@ -6,8 +6,8 @@ en: 9dbb9bc3960a11fe zh: ed58987926489d3e /deepseek-ai-dsh-deepseek-account: - en: 06fe55f319bd1b2c - zh: 9559b712e50bbc73 + en: d5aad878bc7d3059 + zh: 3573506e849ad4d4 /deepseek-ai-dsh-deepseek-account/summary: en: 28bcca957bf6abf4 zh: 4a3fc8a59f2925bc @@ -15,8 +15,8 @@ en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: 02b899ac5ad80227 - zh: 0cb4d6984ae6ed62 + en: 210ba1bd070bb8c4 + zh: 4e1286bff076a3b6 /deepseek-ai-dsh-deepseek-account/understand-the-implementation: en: 76d2da2dab100ac3 zh: 2c9404f27915daab diff --git a/packages/account/deepseek-account/README.md b/packages/account/deepseek-account/README.md index 34d87bf729..b26272b1d0 100644 --- a/packages/account/deepseek-account/README.md +++ b/packages/account/deepseek-account/README.md @@ -9,11 +9,11 @@ English | [中文](README.zh.md) Every operation that reaches Platform takes the caller's `AccountClientMetadata`: the client version, the active UI language, and the UTC offset in seconds. The service derives the five Platform client headers from that metadata and the composition's platform, so each request reports the UI that made it instead of the last caller the Host saw. A new sign-in attempt captures the metadata for its initialization, exchange, and cancellation, and a joining caller never replaces it; sign-out captures the metadata for the revocation retries that outlive the request. -getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the model/file origin configured for resolveToken. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID; the snapshot issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot. +getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the inference origin that `resolveRequestCredential` enforces. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID; the snapshot issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot. `desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. -Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that performs that removal after an HTTP 401 while containing storage failures; the account model route and the DeepSeek web providers use it instead of composing headers themselves. +Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. The account model route and the DeepSeek web providers use it instead of composing headers themselves. ## Summary @@ -32,7 +32,7 @@ Device identity reads validate the existing login device record and expose only ## Use this package -The service exposes its client-safe operations through the `account` Remote namespace. The application loads its generated `./remote` contribution; no separate controller is needed. Login, profile, balance, notification, sign-out-impact, and expiry operations remain available through `ctx.remote.account`. Remote `watch` omits the Host-only identity subscription option. `resolveToken`, `rejectToken`, `getPlatformSession`, and `getDeviceIdentity` remain Host-only. +The service exposes its client-safe operations through the `account` Remote namespace. The application loads its generated `./remote` contribution; no separate controller is needed. Login, profile, balance, notification, sign-out-impact, and expiry operations remain available through `ctx.remote.account`. Remote `watch` omits the Host-only identity subscription option. `resolveRequestCredential`, `getPlatformSession`, and `getDeviceIdentity` remain Host-only. `DeepSeekAccount` is the concrete service owning login, credentials, and Remote operations. The `/types` entry exposes types without loading the service implementation. `watch` returns complete state tagged as `snapshot` or `credentials-changed`; Host-only `watch(signal, true)` also receives profile-identity changes, while Remote subscriptions omit that option. diff --git a/packages/account/deepseek-account/README.zh.md b/packages/account/deepseek-account/README.zh.md index 88b4801909..d219131533 100644 --- a/packages/account/deepseek-account/README.zh.md +++ b/packages/account/deepseek-account/README.zh.md @@ -9,11 +9,11 @@ kind: "package-reference" 每个到达 Platform 的操作都接收调用方的 `AccountClientMetadata`:客户端版本、当前界面语言和以秒为单位的 UTC 偏移。服务据此与组合出的平台推导五个 Platform 客户端请求头,因此每个请求报告的是发起它的界面,而不是 Host 上一次见到的调用方。新的登录申请会为该申请的初始化、兑换和取消捕获这份元数据,中途加入的调用方不会替换它;退登则为在请求之后继续进行的撤销重试捕获这份元数据。 -getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 resolveToken 配置的模型及文件请求来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。 +getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 `resolveRequestCredential` 限定的推理来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。 `desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 -资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后执行上述清除并隔离存储失败。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。 +资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。 ## 概述 @@ -32,7 +32,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 ## 使用此包 -服务通过 `account` Remote 命名空间暴露可供客户端使用的操作。应用加载其生成的 `./remote` 贡献,无需单独的 controller。登录、资料、余额、通知、退出影响检查和凭据过期操作均通过 `ctx.remote.account` 调用。Remote `watch` 不接受仅供 Host 使用的身份订阅选项。`resolveToken`、`rejectToken`、`getPlatformSession` 和 `getDeviceIdentity` 仍仅供 Host 使用。 +服务通过 `account` Remote 命名空间暴露可供客户端使用的操作。应用加载其生成的 `./remote` 贡献,无需单独的 controller。登录、资料、余额、通知、退出影响检查和凭据过期操作均通过 `ctx.remote.account` 调用。Remote `watch` 不接受仅供 Host 使用的身份订阅选项。`resolveRequestCredential`、`getPlatformSession` 和 `getDeviceIdentity` 仍仅供 Host 使用。 `DeepSeekAccount` 是具体服务,拥有登录、凭证和 Remote 操作。`/types` 提供不加载服务实现的类型出口。`watch` 返回完整状态与 `snapshot` 或 `credentials-changed` 类型;仅 Host 的 `watch(signal, true)` 还接收资料身份变化,Remote 订阅不启用该选项。 diff --git a/packages/account/deepseek-account/src/index.ts b/packages/account/deepseek-account/src/index.ts index 739907057e..cee5f107e4 100644 --- a/packages/account/deepseek-account/src/index.ts +++ b/packages/account/deepseek-account/src/index.ts @@ -373,7 +373,7 @@ export class DeepSeekAccount extends TypertRemoteService { * @param token - token captured by the rejected inference request. * @returns after matching credentials are removed and the expiry notification is emitted. */ - async rejectToken(token: string): Promise { + private async rejectToken(token: string): Promise { const lifetime = this.detailsLifetime const stored = await this.readCurrentGrant(lifetime) if (stored?.token !== token || this.detailsLifetime !== lifetime) return @@ -450,7 +450,7 @@ export class DeepSeekAccount extends TypertRemoteService { * @param url - actual request destination or API base URL. * @returns stored token, or undefined for other origins or a signed-out account. */ - async resolveToken(url: string): Promise { + private async resolveToken(url: string): Promise { if (this.closed || this.removing !== undefined) return undefined const destination = new URL(url) if (destination.origin !== this.inferenceOrigin || destination.username || destination.password) return undefined @@ -470,18 +470,22 @@ export class DeepSeekAccount extends TypertRemoteService { /** * Release the account credential for one request to `url` as the request - * carries it, together with its invalidation. Host-only. + * carries it, together with its invalidation, which runs on the account + * service mounted when it is called. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ async resolveRequestCredential(url: string): Promise { const token = await this.resolveToken(url) if (token === undefined) return undefined + // The destination answers after a reload may have replaced this instance, so the rejection runs on the account + // service mounted at that time; without one, the grant stays for the next mounted service to reject. + const { ctx } = this return { headers: { [ACCOUNT_TOKEN_HEADER]: token }, value: token, reject: async () => { - try { await this.rejectToken(token) } + try { await ctx.get('deepseekAccount')?.rejectToken(token) } catch (_credentialRemovalFailed) { /* The destination's rejection is the failure to report; the next rejection retries. */ } }, } diff --git a/packages/account/deepseek-account/src/types.ts b/packages/account/deepseek-account/src/types.ts index 9a0f23c772..e49c4455ce 100644 --- a/packages/account/deepseek-account/src/types.ts +++ b/packages/account/deepseek-account/src/types.ts @@ -122,7 +122,10 @@ export interface AccountRequestCredential { readonly value: string /** * Remove the stored token after the destination rejected it, unless a newer - * sign-in replaced it. Storage failures are contained: the caller reports + * sign-in replaced it. The removal runs on the account service mounted when + * this is called, so a reload between the request and the rejection does + * not keep the token; without a mounted service the token stays for the + * next one to reject. Storage failures are contained: the caller reports * the destination's rejection, and the next rejection retries the removal. * @returns settlement after the removal attempt. */ diff --git a/packages/account/deepseek-account/tests/account.spec.ts b/packages/account/deepseek-account/tests/account.spec.ts index a5a1662868..33d4bfd029 100644 --- a/packages/account/deepseek-account/tests/account.spec.ts +++ b/packages/account/deepseek-account/tests/account.spec.ts @@ -157,11 +157,12 @@ async function fixture( const authorization = ctx.plugin(AuthorizationService) await authorization await beforeAccount?.(ctx, origin) - const provider = ctx.plugin(DeepSeekAccount, { + const accountConfig = { platformOrigin: origin, inferenceOrigin, embeddedPageDist, desktopPlatform, allowLoopbackHttp: true, requestHeaders, accountRequestHeaders, rewriteBrowserOrigin, logoutRetryDelayMs: 1, balanceTimeoutMs, - }) + } + let provider = ctx.plugin(DeepSeekAccount, accountConfig) await provider cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose(); await web.dispose() }) const account = ctx.deepseekAccount @@ -184,6 +185,13 @@ async function fixture( invalidateSummary: () => { normalWallets = [{ currency: 'CNY', balance: 'not-a-decimal' }] }, normalWallets: (value: unknown) => { normalWallets = value }, dispose: () => provider.dispose(), exchanged, release, + /** Replace the account service as a settings reload does; the stored grant and the other services stay. */ + remount: async () => { + await provider.dispose() + provider = ctx.plugin(DeepSeekAccount, accountConfig) + await provider + return ctx.deepseekAccount + }, redirect: () => { redirect = true }, hold: () => { hold = true }, initResponse: (value: Record) => { initOverride = value }, @@ -267,7 +275,7 @@ it('stores a grant before redirecting, restores account presence, and signs out await f.account.getProfile(clientMetadata()) expect(await f.account.getPlatformSession()).toEqual({ origin: f.origin, userId: 'test-user', token: 'dsh_mock_test', requestHeaders: {} }) - expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined() await f.account.signOut(clientMetadata()) expect((await f.account.getState()).status).toBe('signed-out') expect(await f.account.getPlatformSession()).toBeNull() @@ -300,9 +308,9 @@ it('allows real account credentials only on the exact official HTTPS origin', as await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'grant', payload: { version: 1, issuer: 'https://platform.deepseek.com', token: 'test-account-token' }, })) - expect(await f.account.resolveToken('https://api.deepseek.com/v1')).toBe('test-account-token') + expect((await f.account.resolveRequestCredential('https://api.deepseek.com/v1'))?.value).toBe('test-account-token') for (const url of ['http://api.deepseek.com', 'https://api.deepseek.com.evil.test', 'https://api.deepseek.com:8443', 'https://user@api.deepseek.com']) { - expect(await f.account.resolveToken(url)).toBeUndefined() + expect(await f.account.resolveRequestCredential(url)).toBeUndefined() } }) @@ -332,7 +340,32 @@ it('contains a storage failure while removing a rejected token', async () => { const credential = await f.account.resolveRequestCredential('http://inference.example.test:8094/v1/tools/search') await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'api-key', key: 'wrong-kind' })) await expect(credential!.reject()).resolves.toBeUndefined() - await expect(f.account.rejectToken('test-account-token')).rejects.toThrow('account: storage') + // The contained failure is the store's: it still holds the unreadable record. + await expect(f.account.getState()).rejects.toThrow('account: storage') +}) + +it('invalidates a rejected token through the account service mounted when the rejection runs', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + // A settings reload replaces the service between the request's dispatch and the destination's answer. + const replacement = await f.remount() + const published: string[] = [] + f.ctx.on('deepseek-account/signed-out', () => { published.push('signed-out') }) + await credential.reject() + expect(published).toEqual(['signed-out']) + expect((await replacement.getState()).status).toBe('signed-out') + expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default'))).toBeUndefined() +}) + +it('keeps a rejected token for the next mounted account service while none is mounted', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + await f.dispose() + await expect(credential.reject()).resolves.toBeUndefined() + expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default'))) + .toMatchObject({ kind: 'grant', payload: { token: 'test-platform-grant' } }) }) it('restricts platform destinations to the configured origin and route', () => { @@ -424,6 +457,16 @@ async function storeAccount(f: Awaited>) { })) } +/** Inference origin a fixture allows a grant `storeAccount` wrote, which official inference refuses as development-issued. */ +const PRIVATE_INFERENCE = 'http://inference.example.test:8094' + +/** The request credential of the stored grant, released for the private inference origin. */ +async function storedCredential(f: Awaited>) { + const credential = await f.account.resolveRequestCredential(`${PRIVATE_INFERENCE}/v1/messages`) + if (credential === undefined) throw new Error('missing stored credential') + return credential +} + it('queries Platform Web endpoints with the stored grant and projects only masked profile and separate recharge and bonus balances', async () => { const f = await fixture() expect(await readDetails(f.account)).toBeNull() @@ -454,7 +497,7 @@ it('publishes sign-out only after local grant removal and refuses token resoluti const observed: string[] = [] f.ctx.on('deepseek-account/signed-out', () => { observed.push('signed-out') }) const pending = f.account.signOut(clientMetadata()) - expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined() await pending expect(observed).toEqual(['signed-out']) expect((await f.account.getState()).status).toBe('signed-out') @@ -855,10 +898,10 @@ it('sends a development grant only to its configured inference origin', async () await f.wait('waiting-browser') await fetch(f.callback(), { redirect: 'manual' }) await f.wait('succeeded') - expect(await f.account.resolveToken('http://inference.example.test:8094/api')).toBe('test-account-token') + expect((await f.account.resolveRequestCredential('http://inference.example.test:8094/api'))?.value).toBe('test-account-token') for (const url of ['https://api.deepseek.com', 'http://inference.example.test:8095/api', 'https://inference.example.test:8094/api', 'http://user@inference.example.test:8094/api']) { - expect(await f.account.resolveToken(url)).toBeUndefined() + expect(await f.account.resolveRequestCredential(url)).toBeUndefined() } }) @@ -1117,14 +1160,14 @@ it.each([{ kind: 'api-key' as const, key: 'wrong-kind' }, { kind: 'grant' as con await expect(f.account.getState()).rejects.toThrow('account: storage') await expect(f.account.getProfile(clientMetadata())).rejects.toThrow('account: storage') await expect(f.account.getPlatformSession()).rejects.toThrow('account: storage') - await expect(f.account.resolveToken('https://api.deepseek.com')).rejects.toThrow('account: storage') + await expect(f.account.resolveRequestCredential('https://api.deepseek.com')).rejects.toThrow('account: storage') await expect(f.account.signOut(clientMetadata())).rejects.toThrow('account: storage') }, ) it('returns no credentials when signed out or disposed', async () => { const f = await fixture() - expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined() expect(await f.account.getPlatformSession()).toBeNull() await f.account.cancelSignIn('missing' as import('@deepseek-ai/dsh-deepseek-account').SignInAttemptId) await f.dispose() @@ -1139,7 +1182,7 @@ it('rejects sign-out and inference grants issued by another environment', async await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'grant', payload: { version: 1, token: 'real-token', issuer: 'https://other.example' }, })) - expect(await f.account.resolveToken('https://private.example')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://private.example')).toBeUndefined() await expect(f.account.signOut(clientMetadata())).rejects.toThrow('account: protocol') }) @@ -1148,7 +1191,7 @@ it('never sends a development issuer grant to official inference', async () => { await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'grant', payload: { version: 1, token: 'real-token', issuer: f.origin }, })) - expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined() + expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined() }) it('merges account cookies when there are no base cookies', async () => { @@ -1632,13 +1675,14 @@ it('ignores a 401 whose response cleanup overlaps a credential replacement', asy }) it('expires an inference-rejected token without another Platform request', async () => { - const f = await fixture() + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) await storeAccount(f) + const credential = await storedCredential(f) const published: string[] = [] f.ctx.on('deepseek-account/signed-out', () => { published.push('signed-out') }) f.ctx.on('deepseek-account/session-expired', () => { published.push('session-expired') }) - await f.account.rejectToken('test-platform-grant') - await f.account.rejectToken('test-platform-grant') + await credential.reject() + await credential.reject() const state = await f.account.getState() expect({ status: state.status, published, detailRequests: f.detailRequests }) .toMatchInlineSnapshot(` @@ -1654,17 +1698,24 @@ it('expires an inference-rejected token without another Platform request', async }) it('retains a replacement login when inference rejects the previous token', async () => { - const f = await fixture() + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, issuer: f.origin, token: 'previous-platform-grant' }, + })) + const previous = await storedCredential(f) await storeAccount(f) - await f.account.rejectToken('previous-platform-grant') + await previous.reject() expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default'))) .toMatchObject({ kind: 'grant', payload: { token: 'test-platform-grant' } }) }) it('ignores an inference rejection while already signed out', async () => { - const f = await fixture() - await f.account.rejectToken('previous-platform-grant') + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + await f.ctx.credentials.deleteRecord(credentialKey('deepseek-account-platform', 'default')) + await credential.reject() expect(await f.account.getState()).toMatchObject({ status: 'signed-out' }) expect(await f.account.getState()).not.toHaveProperty('signOutReason') }) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 48b0edd085..0e7238eef5 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1017,12 +1017,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'id', description: 'notification the user interacted with.' }, { name: 'event', description: 'displayed frame, non-dismiss action click, or explicit dismissal.' }, { name: 'client', description: 'identity of the requesting UI for this call.' }], returns: 'true once the server accepts the event; false if signed out or credentials changed during the call.', }, - { - signature: 'async rejectToken(token: string): Promise', - description: 'Remove an inference-rejected token only while it still matches the stored login.', - parameters: [{ name: 'token', description: 'token captured by the rejected inference request.' }], - returns: 'after matching credentials are removed and the expiry notification is emitted.', - }, { signature: 'async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>', description: 'Read existing login identity without creating a device or returning credentials.', @@ -1035,15 +1029,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [], returns: 'a Host-only snapshot, or null while signed out or when the credential changed during the read.', }, - { - signature: 'async resolveToken(url: string): Promise', - description: 'Resolve a credential only for the inference origin allowed by the provider.', - parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], - returns: 'stored token, or undefined for other origins or a signed-out account.', - }, { signature: 'async resolveRequestCredential(url: string): Promise', - description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation. Host-only.', + description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation, which runs on the account service mounted when it is called. Host-only.', parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], returns: 'the request credential, or undefined for other origins or a signed-out account.', }, diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 0020cf5cde..8529f69988 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -60,7 +60,11 @@ export class DeepSeekAdapter extends LlmAdapt configured: endpoint => publication.configured(connection, endpoint), resolve: async (endpoint, signal) => { signal?.throwIfAborted() - return await this.dependencies.resolveAuth(connection, endpoint) + const auth = await this.dependencies.resolveAuth(connection, endpoint) + if (auth === undefined) return undefined + // The adapter's failure classification stays behind the seam. + const reject = auth.reject?.bind(auth) + return { headers: auth.headers, value: auth.value, ...reject === undefined ? {} : { reject } } }, } } diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index a9f50b20a6..60444fc85e 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -142,7 +142,10 @@ export interface DeepSeekAdapterOptions LlmError - /** Publish the route's credential through `routeCredential()`; omission publishes none. */ + /** + * Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, and + * rejection of {@link resolveAuth} without its failure classification; omission publishes none. + */ credential?: DeepSeekRouteCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ resolveUserId: () => AnonymousUserId diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts index 8176bc65aa..404927a098 100644 --- a/packages/llm/llm-deepseek/tests/route-credential.spec.ts +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -52,26 +52,36 @@ it('publishes no credential for a provider that declares none', async () => { }) it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { + const reject = vi.fn(() => Promise.resolve()) const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => - endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k' } : undefined) + endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, onRequestError: error => Promise.resolve(error) } : undefined) const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) const credential = ctx.llm.routeCredential('fixture-route') expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' }) await expect(credential!.configured(ALLOWED)).resolves.toBe(true) await expect(credential!.configured(OTHER)).resolves.toBe(false) - await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) + // The grant carries the seam's fields only; the adapter's failure classification stays behind it. + const grant = await credential!.resolve(ALLOWED) + expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject']) + expect(grant).toMatchObject({ headers: { 'x-fixture': 'k' }, value: 'k' }) + await grant!.reject!() + expect(reject).toHaveBeenCalledTimes(1) await expect(credential!.resolve(OTHER)).resolves.toBeUndefined() await expect(credential!.resolve(ALLOWED, AbortSignal.abort(new Error('caller left')))).rejects.toThrow('caller left') expect(resolveAuth).toHaveBeenCalledTimes(2) expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL]) }) -it('omits the reference of a credential kind without one', async () => { - const ctx = await route({ credential: { kind: 'account', configured: () => Promise.resolve(false) } }) +it('omits the reference of a credential kind without one and the rejection of a grant without one', async () => { + const ctx = await route({ + resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }), + credential: { kind: 'account', configured: () => Promise.resolve(false) }, + }) const credential = ctx.llm.routeCredential('fixture-route') expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL }) expect(credential).not.toHaveProperty('reference') + await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) }) it('fails a request without a credential before any network I/O, with the default diagnostic', async () => { diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 0b610ce7ab..476dd51256 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -22,7 +22,7 @@ import type {} from '@deepseek-ai/dsh-agent' import { credentialRef, credentialRefConfigured, resolveCredentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { assertUsableApiKey, type RouteCredential } from '@deepseek-ai/dsh-llm' +import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider } from './fetch.ts' @@ -258,13 +258,15 @@ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeek * @param capability - the capability whose diagnostics a misconfigured source names. * @param provider - the route. * @returns the source; undefined when no mounted route publishes a credential as `provider`; a misconfigured source - * when the route's settings do not resolve. + * when the route's settings do not resolve or its published base URL does not parse. */ function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined { - let credential: RouteCredential | undefined - try { credential = ctx.get('llm')?.routeCredential(provider) } - catch (error: unknown) { return misconfigured(capability, provider, error) } - return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } + try { + const credential = ctx.get('llm')?.routeCredential(provider) + return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } + } catch (error: unknown) { + return misconfigured(capability, provider, error) + } } /** diff --git a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts index abd6896b76..dfeda94d4c 100644 --- a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts +++ b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts @@ -687,6 +687,17 @@ describe('route credential failures', () => { await expect(failure).rejects.toThrow('that provider\'s settings do not resolve: route resolver unavailable. Search did not send') expect(sent()).toEqual([]) }) + + it('reports a route publishing an unparsable base URL as misconfigured, before readiness and without sending', async () => { + const { ctx, sent } = await mount({ + routes: [{ provider: 'deepseek-official', publishedBaseURL: 'not a url' }], environment: { DEEPSEEK_API_KEY: 'chat-key' }, + }) + expect(await ready(ctx, 'search', 'deepseek-official')).toBe(false) + const failure = operate(ctx, 'search', 'deepseek-official') + await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' }) + await expect(failure).rejects.toThrow('that provider\'s settings do not resolve: Invalid URL. Search did not send') + expect(sent()).toEqual([]) + }) }) describe('billing settings', () => { diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index 4180bb486d..fff97df6c3 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -23,6 +23,8 @@ export interface RouteRow { withoutCredential?: boolean /** Value `routeCredential()` throws instead of publishing. */ throws?: unknown + /** Base URL published in place of the resolved one, as a route publishing an unparsable base would. */ + publishedBaseURL?: string } /** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */ @@ -32,7 +34,7 @@ function credentialOf(ctx: Context, route: RouteRow): RouteCredential { const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment) const ref = resolved.apiKeyEnv return { - kind: 'api-key', baseURL: resolved.baseURL, reference: ref, + kind: 'api-key', baseURL: route.publishedBaseURL ?? resolved.baseURL, reference: ref, configured: () => credentialRefConfigured(ctx, ref), resolve: async () => { const key = await resolveCredentialRef(ctx, ref) @@ -42,7 +44,7 @@ function credentialOf(ctx: Context, route: RouteRow): RouteCredential { } const resolved = resolveAccountOptions(plainAccountOptions(AccountConfig(route.config ?? {})), environment) return { - kind: 'account', baseURL: resolved.protocol.baseURL, + kind: 'account', baseURL: route.publishedBaseURL ?? resolved.protocol.baseURL, configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined, resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined), } From a6672fb5c35b7deb120eef82f075453ec6700fea Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 12 Nov 2026 12:55:16 +0800 Subject: [PATCH 06/16] fix(llm-deepseek-api-key): prefix key diagnostics with the settings namespace An unusable API key's INVALID_CREDENTIAL diagnostic was prefixed with the literal `llm-deepseek`, left from when the lookup lived in the transport package. It now names the mount's settings namespace, the same value the provider directory lists: the Loader entry id, or the plugin name without an entry. Product profiles mount the route as `llm-deepseek`, so their diagnostic text is unchanged. --- .../llm/llm-deepseek-api-key/README.i18n.yaml | 4 +-- packages/llm/llm-deepseek-api-key/README.md | 2 +- .../llm/llm-deepseek-api-key/README.zh.md | 2 +- .../llm/llm-deepseek-api-key/src/index.ts | 6 ++-- .../tests/discovery.spec.ts | 31 +++++++++++++++++-- packages/llm/llm/src/index.ts | 2 +- 6 files changed, 38 insertions(+), 9 deletions(-) diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index 68ac287b92..01dc753b77 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -15,8 +15,8 @@ en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-api-key/use-this-package: - en: 77aeaaf77e17245f - zh: 5b621a9a4aeea7d9 + en: 78c395041b12b9cc + zh: 289f789926a0fe43 /deepseek-ai-dsh-llm-deepseek-api-key/understand-the-implementation: en: 2fe0f32c15603cd9 zh: 984ce05b82e8e679 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index e646cb1ef2..c5eb1ebb19 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -25,7 +25,7 @@ Authentication resolution returns the validated API key in `x-api-key` for Messa ## Use this package -`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. It reads the key through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): when the credentials service exists, its precedence applies, and only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. +`apiKeyEnv` defaults to `DEEPSEEK_API_KEY` and resolves per request and model discovery. It reads the key through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md): when the credentials service exists, its precedence applies, and only compositions without that service read the launch environment directly. Requests with missing credentials fail with `MISSING_CREDENTIAL`; malformed credentials fail with `INVALID_CREDENTIAL`, whose diagnostic names this plugin's settings namespace and the credential reference. Model discovery returns an empty catalog when the credential is missing, hiding the route from model selectors while retaining its settings entry. Malformed credentials and other lookup failures propagate. Adding or removing a key affects the next discovery call. ```yaml - id: llm-deepseek diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index b26da9ab8b..317c75655b 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用此包 -`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。 +`apiKeyEnv` 默认为 `DEEPSEEK_API_KEY`,在每次请求和模型发现时解析凭据。密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取:已组合 credentials 服务时,按其优先级解析;只有未组合该服务时才直接读取启动环境。请求时凭据缺失以 `MISSING_CREDENTIAL` 失败;格式错误以 `INVALID_CREDENTIAL` 失败,其诊断点名本插件的设置命名空间与凭据引用。模型发现在凭据缺失时返回空目录,在模型选择器中隐藏该路由,但保留其设置入口。凭据格式错误和其他读取失败继续上报。添加或删除密钥会影响下一次模型发现。 ```yaml - id: llm-deepseek diff --git a/packages/llm/llm-deepseek-api-key/src/index.ts b/packages/llm/llm-deepseek-api-key/src/index.ts index 9fa4f2a996..e1e2f3cf35 100644 --- a/packages/llm/llm-deepseek-api-key/src/index.ts +++ b/packages/llm/llm-deepseek-api-key/src/index.ts @@ -32,12 +32,14 @@ interface OfficialConnection extends ResolvedDeepSeekOptions { } export function apply(ctx: Context, config: Config): void { + /** Settings namespace of this mount, which the provider directory lists and credential diagnostics name. */ + const settingsNs = ctx.fiber.entry?.options.id ?? name const options = () => resolveAdapterOptions(plainOptions(config), launchEnvironmentOf(ctx)) options() /** The validated API key, or `undefined` when none is configured; store and format failures propagate. */ const resolveApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { const value = await resolveCredentialRef(ctx, connection.apiKeyEnv) - return value === undefined ? undefined : assertUsableApiKey(value, 'llm-deepseek', connection.apiKeyEnv) + return value === undefined ? undefined : assertUsableApiKey(value, settingsNs, connection.apiKeyEnv) } const resolveAuth = async (connection: ResolvedDeepSeekOptions): Promise => { const key = await resolveApiKey(connection) @@ -70,7 +72,7 @@ export function apply(ctx: Context, config: Config): void { return { ...connection, models: catalog.resolution, offered: catalog.offered, refusals: catalog.refusals, badges: catalog.badges } } ctx.llm.registerConfigurableProviders([ - { provider: PROVIDER, displayName: 'DeepSeek', settingsNs: ctx.fiber.entry?.options.id ?? name, settingsPath: [] }, + { provider: PROVIDER, displayName: 'DeepSeek', settingsNs, settingsPath: [] }, ]) registerDeepSeekProvider(ctx, PROVIDER, { providerName: 'DeepSeek', diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index 528d332e2d..bde4d26873 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -32,13 +32,40 @@ it('advertises configured models with an API key', async () => { } }) -it('reports malformed credentials during discovery', async () => { +it('reports malformed credentials during discovery under the settings namespace the provider directory lists', async () => { vi.stubEnv('DEEPSEEK_API_KEY', 'invalid\nheader') const ctx = new Context() try { await ctx.plugin(LlmRuntime) await ctx.plugin(ApiKey, {}) - await expect(ctx.llm.listModels('deepseek-official')).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) + const [directory] = ctx.llm.listConfigurableProviders() + expect(directory?.settingsNs).toBe('llm-deepseek-api-key') + const failure = ctx.llm.listModels('deepseek-official') + await expect(failure).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) + await expect(failure).rejects.toThrow('llm-deepseek-api-key: the API key resolved from DEEPSEEK_API_KEY contains characters') + } finally { + await ctx.fiber.dispose() + vi.unstubAllEnvs() + } +}) + +it('names the Loader entry id in credential diagnostics, as product profiles mount the route', async () => { + vi.stubEnv('DEEPSEEK_API_KEY', 'invalid\nheader') + const ctx = new Context() + try { + await ctx.plugin(LlmRuntime) + await ctx.plugin({ + name: ApiKey.name, inject: ApiKey.inject, Config: ApiKey.Config, + apply: (inner: Context, config: ApiKey.Config) => { + // The Loader attaches the entry before a plugin applies; product profiles use the id `llm-deepseek`. + Object.defineProperty(inner.fiber, 'entry', { value: { options: { id: 'llm-deepseek' } } }) + ApiKey.apply(inner, config) + }, + }, {}) + expect(ctx.llm.listConfigurableProviders().map(entry => entry.settingsNs)).toEqual(['llm-deepseek']) + await expect(ctx.llm.listModels('deepseek-official')).rejects.toThrow( + 'llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry', + ) } finally { await ctx.fiber.dispose() vi.unstubAllEnvs() diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 113c698e0d..429db6b507 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -160,7 +160,7 @@ export class LlmError extends HarnessError { * module stays dependency-free; both adapters share this one diagnosis instead * of keeping near-identical local copies. * @param raw - the credential exactly as supplied. - * @param pkg - the refusing package name, prefixed to the diagnostic. + * @param pkg - the refusing plugin's settings namespace or package name, prefixed to the diagnostic. * @param ref - the credential reference the value resolved through. * @returns the trimmed, usable key. */ From 8607cf5b0e6bacaf62fe6c21ca37fc3795341be6 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 12 Nov 2026 13:20:13 +0800 Subject: [PATCH 07/16] fix(web): bind route account credentials to their origin and contain failed rejection - web-search-deepseek: the initiating route's account credential is used only when the search endpoint has the origin of that route's base URL. For another origin the provider does not ask the route and sends the API key, and readiness answers the same way. A route publishing an unparsable base URL is treated like settings that do not resolve. - web-deepseek-api, web-search-deepseek: after HTTP 401 a failure of the grant's reject() is contained, so the reported error stays the HTTP rejection whichever owner published the credential. --- ...-11-10-llm-route-credential-seam.i18n.yaml | 4 +- .../2026-11-10-llm-route-credential-seam.md | 2 +- ...2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../web/web-deepseek-api/src/transport.ts | 5 +- .../web-deepseek-api/tests/transport.spec.ts | 8 ++- .../web/web-search-deepseek/README.i18n.yaml | 12 ++--- packages/web/web-search-deepseek/README.md | 10 ++-- packages/web/web-search-deepseek/README.zh.md | 10 ++-- packages/web/web-search-deepseek/src/index.ts | 30 +++++++---- .../web/web-search-deepseek/src/provider.ts | 6 ++- .../tests/deepseek.spec.ts | 54 ++++++++++++++----- 11 files changed, 91 insertions(+), 52 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 6926949697..c528ae84df 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,8 +9,8 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 5819b658fc81482d - zh: 948e9cb0a668e623 + en: 8d28911b4a7aaca0 + zh: db511eb9dfdc5f5e /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index ba7c05d753..7ed0451345 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -18,7 +18,7 @@ The route plugins own credentials. `llm-deepseek-api-key` reads its key through `@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. -The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account`, and the reference helpers otherwise. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 9651ca13d6..e02353e078 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -18,7 +18,7 @@ Status: implemented `@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 -Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类时使用其账号凭据,否则使用引用函数。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 ## 考虑过的替代方案 diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts index f8c841bb60..2508e2c714 100644 --- a/packages/web/web-deepseek-api/src/transport.ts +++ b/packages/web/web-deepseek-api/src/transport.ts @@ -161,7 +161,7 @@ interface SearchAuth { readonly endpoint: string /** Headers carrying the credential. */ readonly headers: Readonly> - /** Request-bound invalidation of the sent credential, present when its grant offers one. */ + /** Request-bound invalidation of the sent credential, present when its grant offers one; the dispatch contains its failure. */ readonly reject?: () => Promise } @@ -230,7 +230,8 @@ export async function dispatchDeepSeekWeb( if (status === 401) { // Invalidation can cancel this Session; finish reading the HTTP failure before it does. A cancelled read still // invalidates the credential the status rejected. - await auth.reject?.() + try { await auth.reject?.() } + catch (_invalidationFailed) { /* The HTTP rejection stays the reported failure when the invalidation itself fails. */ } // The account service released its credential only for its inference origin, so the endpoint is not what the // user must change. if (auth.kind === 'account') throw aborted ?? accountRejectedError(message) diff --git a/packages/web/web-deepseek-api/tests/transport.spec.ts b/packages/web/web-deepseek-api/tests/transport.spec.ts index c6620a9d13..3a082c938f 100644 --- a/packages/web/web-deepseek-api/tests/transport.spec.ts +++ b/packages/web/web-deepseek-api/tests/transport.spec.ts @@ -18,8 +18,8 @@ function keyRef(resolve: () => Promise, configured: () => Pr } /** * A route source on {@link ACCOUNT_BASE} whose account credential releases `resolveToken(endpoint)` as the token header; - * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failures are contained as the - * account service contains them. + * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failure rejects the grant's + * invalidation, as an owner that does not contain its storage failures does. */ function accountSource( resolveToken: (endpoint: string) => Promise, rejectToken: (token: string) => Promise = async () => {}, @@ -27,9 +27,7 @@ function accountSource( const grant = async (endpoint: string) => { const token = await resolveToken(endpoint) if (token === undefined || token.length === 0) return undefined - return { headers: { 'x-dsh-auth-token': token }, value: token, reject: async () => { - try { await rejectToken(token) } catch (_storageFailure) { /* Contained as the account service contains it. */ } - } } + return { headers: { 'x-dsh-auth-token': token }, value: token, reject: () => rejectToken(token) } } return { kind: 'route', baseURL: ACCOUNT_BASE, credential: { kind: 'account', configured: async endpoint => (await grant(endpoint)) !== undefined, resolve: grant, diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index d83724b59e..d25d04cf27 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3ed88edabdf63c8d zh: c66176c8a7c9a434 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: 7e625c9a31ecad31 - zh: 19088d0014d51b24 + en: b9d2e372face46f1 + zh: cc8e5820d6aada38 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a @@ -39,14 +39,14 @@ en: 9842c69ad3636bb3 zh: 3cdc3f816cbdd0cb /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/design-philosophy: - en: 76d5fb7c1e00079c - zh: 6f0e835157a3c982 + en: 9ebf133e28acbd3a + zh: 440399ab6a4f5540 /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/source-map: en: 6488e1c85646339f zh: 2b5ca1c6b5939a8c /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/request-flow: - en: a45785f95dbde10a - zh: 399bd28592d34721 + en: ec407206b9f6371d + zh: a94d1e864102342b /deepseek-ai-dsh-web-search-deepseek/further-exploration: en: 3a650478cf33d792 zh: ab4247c4c31f4a90 diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 230f4cc63e..91411478f7 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,9 +58,9 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, and that credential resolves for the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. -The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential that reports itself configured for the configured search endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or a failed account-credential or credential-store read answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. +The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential for the origin of the configured search endpoint that reports itself configured for that endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or whose published base URL does not parse, or a failed account-credential or credential-store read, answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. Referenced keys go through the credential reference helpers of [`dsh-credentials`](../../credentials/credentials/README.md) and receive the same whitespace normalization and format validation as model requests. A malformed referenced key fails before dispatch; readiness remains a presence-only check. @@ -91,7 +91,7 @@ This section explains the design decisions behind the provider; the observable b The provider is built on two commitments: - **Structured blocks only.** DeepSeek runs the search server-side and returns structured `web_search_tool_result` blocks; the provider parses those blocks and never scrapes URLs out of model prose. In strict mode, a response with no such block throws `WEB_PROVIDER_ERROR` instead of degrading. -- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on a route that publishes an account credential uses that credential, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart. +- **Conversation credentials, resolved per search.** The provider adds no secret: a search from a Session on a route that publishes an account credential for the search endpoint's origin uses that credential, and every other search reuses the `DEEPSEEK_API_KEY` reference. The auxiliary request endpoint stays independent through `$DEEPSEEK_SEARCH_BASE_URL`. A mounted credentials service is authoritative; without one the provider falls back to the launching process environment. Resolving per call means a key stored or rotated in the Web Models page, or an account sign-in, reaches the next search without a restart. ### Source map @@ -103,9 +103,9 @@ The provider is built on two commitments: ### Request flow -Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.routeCredential` when it publishes one, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. +Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.routeCredential` when it publishes one for the search endpoint's origin, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. -Readiness captures the same options but reads no API key value: on a route publishing an account credential it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured. +Readiness captures the same options but reads no API key value: on a route publishing an account credential for the search endpoint's origin it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured. diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index a55dc76495..c4908267e8 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,9 +58,9 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 +当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 -提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由发布的账号凭据报告自身已为配置的搜索端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 +提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由为配置的搜索端点所在 origin 发布了账号凭据且该凭据报告自身已为该端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析或其发布的基础地址无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 引用密钥通过 [`dsh-credentials`](../../credentials/credentials/README.zh.md) 的凭据引用函数读取,接受与模型请求相同的首尾空白规范化和格式校验。引用密钥格式错误会在发送请求前失败;就绪判断仍只检查是否存在。 @@ -91,7 +91,7 @@ kind: "package-reference" 本提供方建立在两项承诺之上: - **只取结构化块。** DeepSeek 在服务端执行搜索并返回结构化的 `web_search_tool_result` 块;提供方解析这些块,绝不从模型文本中抓取 URL。严格模式下,没有此类块的响应会抛出 `WEB_PROVIDER_ERROR`,而非降级。 -- **会话凭据,逐次解析。** 提供方不新增密钥:来自发布账号凭据的路由会话的搜索使用该凭据,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。 +- **会话凭据,逐次解析。** 提供方不新增密钥:发起会话的路由为搜索端点所在 origin 发布账号凭据时,搜索使用该凭据,其余搜索复用 `DEEPSEEK_API_KEY` 引用。辅助请求端点通过 `$DEEPSEEK_SEARCH_BASE_URL` 保持独立。已挂载的凭据服务具有权威性;没有该服务时回退到启动进程的环境。按次解析意味着在 Web 的 Models 页中存储或轮换的密钥,或一次账号登录,无需重启即可用于下一次搜索。 ### 源码地图 @@ -103,9 +103,9 @@ kind: "package-reference" ### 请求流程 -每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 +每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.routeCredential` 为搜索端点所在 origin 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 -就绪判断捕获相同的选项,但不读取 API 密钥的值:发布账号凭据的路由先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。 +就绪判断捕获相同的选项,但不读取 API 密钥的值:路由为搜索端点所在 origin 发布账号凭据时,先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。 diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index da16c7c2a6..40934c78bc 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -2,7 +2,8 @@ * Register a DeepSeek-backed provider in `ctx.web`. It calls the Anthropic-compatible Messages API * with native `web_search_20250305`. A search initiated by a Session whose latest model request used * a route that publishes an account credential through `ctx.llm.routeCredential()` authenticates with - * that credential when its owner allows the search endpoint; every other search reuses + * that credential when the search endpoint has the origin of that route's base URL and the + * credential's owner allows the endpoint; every other search reuses * `DEEPSEEK_API_KEY`. The provider does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own * endpoint configuration. The provider reports itself not ready for a model request whose search * would have no credential. @@ -93,15 +94,19 @@ export const WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE = 'web-search-deepseek' type SearchOptions = DeepSeekSearchProviderOptions & { readonly apiKeyEnv: CredentialRef } /** - * The account credential the model route `route` publishes, when it publishes one of that kind. + * The account credential the model route `route` publishes for the deployment that serves `endpoint`. A route's + * account credential is sent only to the origin of that route's base URL, whatever destinations its owner would + * release it for. * @param ctx - plugin context supplying the optional model service. * @param route - provider route of a model request; undefined names none. - * @returns the route's account credential, or undefined for another kind, no credential, or no route. - * @throws when the route's settings do not resolve. + * @param endpoint - absolute URL the search dispatches to. + * @returns the route's account credential, or undefined for another kind, another origin, no credential, or no route. + * @throws when the route's settings do not resolve, or its published base URL or `endpoint` does not parse. */ -function accountCredentialOf(ctx: Context, route: string | undefined): RouteCredential | undefined { +function accountCredentialOf(ctx: Context, route: string | undefined, endpoint: string): RouteCredential | undefined { const credential = route === undefined ? undefined : ctx.get('llm')?.routeCredential(route) - return credential?.kind === 'account' ? credential : undefined + if (credential?.kind !== 'account') return undefined + return new URL(credential.baseURL).origin === new URL(endpoint).origin ? credential : undefined } /** @@ -124,7 +129,8 @@ function resolveOptions( resolveAccountCredential: async (endpoint) => { // The latest request context names the route that served the model // request which called this search, as account sign-out reads it. - const credential = accountCredentialOf(ctx, ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider) + const route = ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider + const credential = accountCredentialOf(ctx, route, endpoint) return credential === undefined ? undefined : await credential.resolve(endpoint) }, resolveApiKey: async () => { @@ -150,8 +156,9 @@ function resolveOptions( /** * Whether the search a model request on `route` would make has a credential, checked in the order - * the search resolves them: the account credential the route publishes first, then the API key. A - * route whose settings do not resolve or a failed read answers false, because the search fails there + * the search resolves them: the account credential the route publishes for the origin of the search + * endpoint first, then the API key. A route whose settings do not resolve or whose published base URL + * does not parse, or a failed read, answers false, because the search fails there * instead of trying the next credential. Only presence is checked: the API key's value is not read * and the endpoint is not contacted, so a wrong key or an endpoint without native search still * counts as configured. @@ -163,11 +170,12 @@ function resolveOptions( async function searchConfigured( ctx: Context, options: SearchOptions, route: string | undefined, ): Promise { + const endpoint = `${options.baseURL}/messages` let account: RouteCredential | undefined - try { account = accountCredentialOf(ctx, route) } + try { account = accountCredentialOf(ctx, route, endpoint) } catch (_unresolvedRoute) { return false /* The search fails on this route before it reads any credential. */ } if (account !== undefined) { - try { if (await account.configured(`${options.baseURL}/messages`)) return true } + try { if (await account.configured(endpoint)) return true } catch (_unreadableGrant) { return false /* The search fails on this read before it tries the API key. */ } } if (options.apiKey !== undefined) return true diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index ccc14b9f3d..5472a8f2b9 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -96,7 +96,8 @@ export interface DeepSeekSearchProviderOptions { /** * Resolve the DeepSeek account credential for one search endpoint. A credential takes * precedence over every API key and is sent only through the headers of its grant, which - * also invalidates it after HTTP 401; `undefined` selects API-key authentication. + * also invalidates it after HTTP 401; a failure of that invalidation is contained, and the + * search reports the HTTP rejection. `undefined` selects API-key authentication. */ resolveAccountCredential?: (endpoint: string) => Promise /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */ @@ -301,7 +302,8 @@ export class DeepSeekSearchProvider implements WebSearchProvider { if (status === 401 && auth.kind === 'account') { // Invalidation can cancel this Session; finish reading the HTTP failure before it does. A cancelled read // still invalidates the credential the status rejected. - await auth.reject?.() + try { await auth.reject?.() } + catch (_invalidationFailed) { /* The HTTP rejection stays the reported failure when the invalidation itself fails. */ } throw aborted ?? accountRejectedError(message) } if (aborted !== undefined) throw aborted diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index a1feb29aba..9ecd5ee4b9 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -12,7 +12,7 @@ import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' import LlmRuntime from '@deepseek-ai/dsh-llm' -import type { RouteCredentialGrant } from '@deepseek-ai/dsh-llm' +import type { RouteCredential, RouteCredentialGrant } from '@deepseek-ai/dsh-llm' import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import WebRuntime, { WebError, type WebSearchResult } from '@deepseek-ai/dsh-web' @@ -33,7 +33,7 @@ const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchP /** * The account credential resolver a route publishes over `token`, with `reject` observing each invalidated token; - * a throwing observer is contained as the account service contains storage failures. + * a throwing observer rejects the grant's invalidation, as an owner that does not contain its storage failures does. */ function accountCredential( token: (endpoint: string) => Promise, reject?: (token: string) => Promise, @@ -41,9 +41,7 @@ function accountCredential( return async (endpoint) => { const value = await token(endpoint) if (value === undefined || value.length === 0) return undefined - return { headers: { 'x-dsh-auth-token': value }, value, ...reject === undefined ? {} : { reject: async () => { - try { await reject(value) } catch (_storageFailure) { /* Contained as the account service contains it. */ } - } } } + return { headers: { 'x-dsh-auth-token': value }, value, ...reject === undefined ? {} : { reject: () => reject(value) } } } } @@ -58,6 +56,12 @@ async function rejectedWebError(operation: Promise): Promise throw new Error('expected search operation to reject') } +/** + * Base URL of the account route the composed suites mount, set in the route's config so that a `DEEPSEEK_BASE_URL` in + * the environment running them cannot move the route off the origin of the default search endpoint. + */ +const ACCOUNT_ROUTE_BASE = 'https://api.deepseek.com/anthropic' + const options = { apiKey: 'ds-key', baseURL: 'https://api.deepseek.test/anthropic/v1', @@ -772,9 +776,12 @@ describe('web-search-deepseek account route selection', () => { * initiator whose latest request context names `provider`. * @param provider - route recorded by the initiating Session's request context; undefined runs the * search without an initiator while a Session on the account route exists. + * @param routeBaseURL - base URL of the mounted account route, whose origin its credential is published for. * @returns the headers the search sent and the URLs the account was asked about. */ - async function searchAs(provider: string | undefined): Promise<{ headers: Record; asked: string[] }> { + async function searchAs( + provider: string | undefined, routeBaseURL = ACCOUNT_ROUTE_BASE, + ): Promise<{ headers: Record; asked: string[] }> { const fetchMock = vi.fn(async (_input: string, _init?: RequestInit) => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) const asked: string[] = [] @@ -785,7 +792,7 @@ describe('web-search-deepseek account route selection', () => { await ctx.plugin(AgentRegistry) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) await ctx.plugin(LlmRuntime) - await ctx.plugin(AccountRoute, {}) + await ctx.plugin(AccountRoute, { baseURL: routeBaseURL }) ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return 'account-token' } })) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) const session = ctx.sessions.create(SessionId(`web-search-account-${provider ?? 'none'}`)) @@ -808,6 +815,14 @@ describe('web-search-deepseek account route selection', () => { expect(headers).not.toHaveProperty('x-api-key') }) + it('sends the API key when the account route publishes its credential for another origin, without asking the account', async () => { + // The stand-in account releases its token for every destination, so only the origin comparison withholds it. + const { headers, asked } = await searchAs('deepseek-account', 'https://other-deployment.test/anthropic') + expect(asked).toEqual([]) + expect(headers['x-api-key']).toBe('ds-key') + expect(headers).not.toHaveProperty('x-dsh-auth-token') + }) + it('keeps a sign-in that replaced the sent token before its late 401', async () => { let current = 'old-token' const rejectToken = vi.fn(async (token: string) => { if (token === current) current = '' }) @@ -822,7 +837,7 @@ describe('web-search-deepseek account route selection', () => { await ctx.plugin(AgentRegistry) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) await ctx.plugin(LlmRuntime) - await ctx.plugin(AccountRoute, {}) + await ctx.plugin(AccountRoute, { baseURL: ACCOUNT_ROUTE_BASE }) ctx.provide('deepseekAccount', accountStub({ token: () => current, reject: rejectToken })) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) const session = ctx.sessions.create(SessionId('web-search-account-late-401')) @@ -890,7 +905,7 @@ describe('web-search-deepseek search readiness', () => { mounted.push(ctx) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) await ctx.plugin(LlmRuntime) - await ctx.plugin(AccountRoute, {}) + await ctx.plugin(AccountRoute, { baseURL: ACCOUNT_ROUTE_BASE }) if (setup.credentialsDir !== undefined) { await ctx.plugin(LocalCredentialProvider, { path: join(setup.credentialsDir, '.credentials.yaml'), watch: false }) } @@ -942,6 +957,15 @@ describe('web-search-deepseek search readiness', () => { expect(asked).toEqual([]) }) + it('does not ask the account about a search endpoint at another origin than the account route\'s base URL', async () => { + const asked: string[] = [] + // The stand-in account releases its token for every destination, so only the origin comparison withholds it. + const account = accountStub({ token: (url) => { asked.push(url); return 'account-token' } }) + const ctx = await compose({ config: { baseURL: 'https://gateway.test/anthropic/v1' }, account }) + expect(await ctx.web.searchReady('deepseek-account')).toBe(false) + expect(asked).toEqual([]) + }) + it.each<[string, Setup]>([ ['a search endpoint outside the account origin', { config: { baseURL: 'https://gateway.test/anthropic/v1' }, account: officialOriginAccount() }], ['a signed-out account', { account: accountStub({ token: () => undefined }) }], @@ -988,13 +1012,19 @@ describe('web-search-deepseek search readiness', () => { } }) - it('is not ready and fails the search when the initiating route\'s settings do not resolve, despite a literal key', async () => { + it.each<[string, () => RouteCredential, string]>([ + ['settings do not resolve', () => { throw new Error('route settings do not resolve') }, 'route settings do not resolve'], + ['published base URL does not parse', () => ({ + kind: 'account', baseURL: 'not a url', configured: () => Promise.resolve(true), + resolve: () => Promise.resolve({ headers: { 'x-dsh-auth-token': 'account-token' }, value: 'account-token' }), + }), 'Invalid URL'], + ])('is not ready and fails the search when the initiating route\'s %s, despite a literal key', async (_fault, routeCredential, diagnostic) => { const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) const ctx = new Context() mounted.push(ctx) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) - ctx.provide('llm', { routeCredential: () => { throw new Error('route settings do not resolve') } } as never) + ctx.provide('llm', { routeCredential } as never) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) expect(await ctx.web.searchReady('deepseek-account')).toBe(false) expect(await ctx.web.searchReady(undefined)).toBe(true) @@ -1006,7 +1036,7 @@ describe('web-search-deepseek search readiness', () => { session.append('request/context', { provider: 'deepseek-account', model: 'deepseek-v4-flash' }) const failure = await rejectedWebError(ctx.agents.withInitiator({ session } as Agent, () => ctx.web.search({ query: 'q' }))) expect(failure.code).toBe('WEB_PROVIDER_ERROR') - expect(failure.message).toContain('route settings do not resolve') + expect(failure.message).toContain(diagnostic) expect(fetchMock).not.toHaveBeenCalled() }) From eb30025883580d33bc1e1dc3a6452ea8ec6d1fd8 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 12 Nov 2026 13:24:25 +0800 Subject: [PATCH 08/16] docs(web-search-deepseek): keep the module comment at its line count The config catalog records the source line of the plugin's Config. The previous commit grew the module comment by one line, which moved that line and left the generated catalog stale; reflowing the comment keeps the catalog as committed. --- packages/web/web-search-deepseek/src/index.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index 40934c78bc..006749c9d9 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -3,10 +3,9 @@ * with native `web_search_20250305`. A search initiated by a Session whose latest model request used * a route that publishes an account credential through `ctx.llm.routeCredential()` authenticates with * that credential when the search endpoint has the origin of that route's base URL and the - * credential's owner allows the endpoint; every other search reuses - * `DEEPSEEK_API_KEY`. The provider does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own - * endpoint configuration. The provider reports itself not ready for a model request whose search - * would have no credential. + * credential's owner allows the endpoint; every other search reuses `DEEPSEEK_API_KEY`. The provider + * does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own endpoint configuration. The + * provider reports itself not ready for a model request whose search would have no credential. * @module @deepseek-ai/dsh-web-search-deepseek */ import type { Volatile } from '@deepseek-ai/cordis' From 98003bd816581f0b3a4cef077f17ecfe0164bec8 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 12 Nov 2026 14:18:17 +0800 Subject: [PATCH 09/16] test(headless): expect the keyless mount's namespace in key diagnostics The invalid-credential scenario mounts the API-key route as entry `llm-deepseek-keyless`. Since fb007f605d4 the INVALID_CREDENTIAL diagnostic of an unusable key names the settings namespace of the mount instead of the fixed `llm-deepseek`, so the expected stream names `llm-deepseek-keyless` in its two failure records. The file is refreshed through the test's own DSH_SNAPSHOT=refresh mode; nothing else in it changes. --- .../expected/invalid-credential/stream-json.expected.jsonl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl index 9f15c8c621..235e8e695e 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl @@ -9,7 +9,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"say pong","messageSeqs":[8],"source":{"kind":"fallback"}}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title-llm-request","seq":13,"time":0,"data":{"titleProvider":"session-title-first-prompt-llm","messageSeqs":[8],"route":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"Create a concise title for an AI coding-assistant session from the supplied human messages.\nReturn only the title on one line, **in plain text of natural language**, with no quotes, prefix, explanation, Markdown, XML, or terminal control codes. No code is allowed.\nUse the language of the messages.\nAim for about 5 words in non-CJK languages or 10 CJK characters.\nIf the messages give little to name, still return a short best-effort title, such as Greeting, instead of explaining.","messages":[{"content":[{"type":"text","text":"Generate the session title from this JSON array of human messages:\n[{\"seq\":8,\"text\":\"say pong\"}]"}],"source":{"kind":"dsh-session-title-llm"},"role":"user","id":"{{sessionId}}"}],"maxTokens":4096,"reasoningEffort":"off"}}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/attempt","seq":14,"time":0,"data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}]}}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/attempt","seq":14,"time":0,"data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"llm-deepseek-keyless: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}]}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":15,"time":0,"data":{"turn":1,"step":1}}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"error","error":{"message":"llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"error","error":{"message":"llm-deepseek-keyless: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}} {"type":"result","sessionId":"{{sessionId}}","output":""} From bca49d2ee0e5c2dd61713eb60135d0fe42d5453b Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 11:36:30 +0800 Subject: [PATCH 10/16] fix(llm-deepseek-api-key): release the route key only for the route's origin The credential published through ctx.llm.routeCredential() ignored the destination: resolve() and configured() answered for any URL, unlike the account route, whose owner checks the destination. Both now answer only for destinations under the origin of the route's base URL without embedded credentials, and read the credential store for no other destination. Messages, Files, and listing requests derive their URLs from that base URL and are unchanged. --- ...-11-10-llm-route-credential-seam.i18n.yaml | 4 +-- .../2026-11-10-llm-route-credential-seam.md | 2 +- ...2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../llm/llm-deepseek-api-key/README.i18n.yaml | 4 +-- packages/llm/llm-deepseek-api-key/README.md | 2 +- .../llm/llm-deepseek-api-key/README.zh.md | 2 +- .../llm/llm-deepseek-api-key/src/index.ts | 17 +++++++++-- .../tests/discovery.spec.ts | 28 +++++++++++++++++++ 8 files changed, 50 insertions(+), 11 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index c528ae84df..50a9766fee 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,8 +9,8 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 8d28911b4a7aaca0 - zh: db511eb9dfdc5f5e + en: 5c11dfca48a6343b + zh: e637091ff8593f5d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index 7ed0451345..2724189196 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -14,7 +14,7 @@ Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/ `@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The listing cache scopes by endpoint and a hash of the credential headers. -The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. +The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. `@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index e02353e078..72ac5291ed 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -14,7 +14,7 @@ Status: implemented `@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。列表缓存以端点和凭据请求头的哈希划分作用域。 -路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。 +路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。 `@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index 01dc753b77..f1bae2778c 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,8 +9,8 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: 69c60bbfb6aafb7a - zh: 1afe49ea9cdc3cd5 + en: ea0a35b73d3b8f2c + zh: 7e404ed4617c2789 /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index c5eb1ebb19..d387b0b36b 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. +Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL: for another origin, or a URL that embeds credentials, `configured()` answers false and `resolve()` releases nothing, and neither reads the credential store. ## Table of Contents diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index 317c75655b..b0f724fe8a 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。 +鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥:对其他 origin 或内嵌凭据的 URL,`configured()` 回答 false,`resolve()` 不释放任何内容,二者都不读取凭据存储。 ## 目录 diff --git a/packages/llm/llm-deepseek-api-key/src/index.ts b/packages/llm/llm-deepseek-api-key/src/index.ts index e1e2f3cf35..a35e6aebaa 100644 --- a/packages/llm/llm-deepseek-api-key/src/index.ts +++ b/packages/llm/llm-deepseek-api-key/src/index.ts @@ -41,7 +41,17 @@ export function apply(ctx: Context, config: Config): void { const value = await resolveCredentialRef(ctx, connection.apiKeyEnv) return value === undefined ? undefined : assertUsableApiKey(value, settingsNs, connection.apiKeyEnv) } - const resolveAuth = async (connection: ResolvedDeepSeekOptions): Promise => { + /** + * Whether `endpoint` belongs to the deployment this route sends its key to: the origin of the route's base URL, + * without credentials embedded in the URL. + */ + const servedByRoute = (connection: ResolvedDeepSeekOptions, endpoint: string): boolean => { + const destination = new URL(endpoint) + return destination.origin === new URL(connection.baseURL).origin && destination.username === '' && destination.password === '' + } + const resolveAuth = async (connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { + // The store is read only for a destination this route serves, as the presence check below. + if (!servedByRoute(connection, endpoint)) return undefined const key = await resolveApiKey(connection) return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key } } @@ -52,7 +62,7 @@ export function apply(ctx: Context, config: Config): void { ) const listings = createModelListingCache(ctx, name, PROVIDER, { settings: () => options().listing, - credential: async () => (await resolveAuth(options()))?.headers, + credential: async url => (await resolveAuth(options(), url))?.headers, }) let reportedListing: ModelListing | undefined /** Resolve the catalog, reporting each listing's hidden entries and dropped badges once. */ @@ -98,7 +108,8 @@ export function apply(ctx: Context, config: Config): void { credential: { kind: 'api-key', reference: connection => connection.apiKeyEnv, - configured: connection => credentialRefConfigured(ctx, connection.apiKeyEnv), + configured: async (connection, endpoint) => + servedByRoute(connection, endpoint) && await credentialRefConfigured(ctx, connection.apiKeyEnv), }, admit: (connection, model) => { refuseListedModel(model, connection.refusals.get(model)) }, discoverModels: async (provider) => { diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index bde4d26873..976ce160ae 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -94,3 +94,31 @@ it('publishes the route API key for its consumers from the credential planes it vi.unstubAllEnvs() } }) + +it.each([ + 'https://other-origin.example/v1/tools/search', + 'http://route.deepseek.test/v1/tools/search', + 'https://route.deepseek.test:8443/v1/tools/search', + 'https://user@route.deepseek.test/v1/tools/search', + 'https://:secret@route.deepseek.test/v1/tools/search', +])('releases no key for %s, a destination outside the origin of its base URL, without reading the credential store', async (endpoint) => { + const resolve = vi.fn(async () => ({ value: 'stored-key' })) + const describe = vi.fn(async () => ({ configured: true })) + const ctx = new Context() + try { + ctx.provide('credentials', { resolve, describe } as never) + await ctx.plugin(LlmRuntime) + await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) + const credential = ctx.llm.routeCredential('deepseek-official') + await expect(credential!.configured(endpoint)).resolves.toBe(false) + await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() + expect(resolve).not.toHaveBeenCalled() + expect(describe).not.toHaveBeenCalled() + // The same store answers for a destination under the route's origin. + const served = 'https://route.deepseek.test/v1/tools/search' + await expect(credential!.configured(served)).resolves.toBe(true) + await expect(credential!.resolve(served)).resolves.toEqual({ headers: { 'x-api-key': 'stored-key' }, value: 'stored-key' }) + } finally { + await ctx.fiber.dispose() + } +}) From 6a82fdba513e80256112a4f350979447c23badf9 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 11:47:46 +0800 Subject: [PATCH 11/16] fix(web-deepseek-api): accept only a route's own credential kind Search and Fetch picked a route credential by route id without comparing its kind, so an adapter registered as deepseek-official that publishes an account credential had that credential sent under API-key billing, and the reverse held for deepseek-account. A credential whose kind differs from the route's counts as no route, as an adapter publishing no credential already does: API-key billing falls back to DEEPSEEK_API_KEY at the official base, and account billing asks the account service. Readiness and dispatch share the source, so both follow the same rule. --- ...-11-10-llm-route-credential-seam.i18n.yaml | 4 +- .../2026-11-10-llm-route-credential-seam.md | 2 +- ...2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../llm-route-credential/guide.i18n.yaml | 4 +- .../v0.2.2-rc.2/llm-route-credential/guide.md | 2 +- .../llm-route-credential/guide.zh.md | 2 +- .../web/web-deepseek-api/README.i18n.yaml | 4 +- packages/web/web-deepseek-api/README.md | 2 +- packages/web/web-deepseek-api/README.zh.md | 2 +- packages/web/web-deepseek-api/src/index.ts | 18 ++++++-- .../tests/credential-resolution.spec.ts | 44 +++++++++++++++++++ packages/web/web-deepseek-api/tests/routes.ts | 4 +- 12 files changed, 73 insertions(+), 17 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 50a9766fee..ab73ce9fc2 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,8 +9,8 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 5c11dfca48a6343b - zh: e637091ff8593f5d + en: 964d66432578805a + zh: 90b93fb955b60afb /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: 8177946a6bfa1a6d zh: f523f9057b4b47c5 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index 2724189196..08eaef0f5a 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -18,7 +18,7 @@ The route plugins own credentials. `llm-deepseek-api-key` reads its key through `@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. -The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 72ac5291ed..573eafd0e4 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -18,7 +18,7 @@ Status: implemented `@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 -Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 ## 考虑过的替代方案 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index 224eac372f..18492ce96a 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -9,8 +9,8 @@ en: f0139803159ee9c9 zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: - en: 09ab43933a9e5950 - zh: a18da5d560cf0c9f + en: 47b4fa692d98e1cf + zh: 42869beb3efbe290 /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: en: 64ac045c8d9a1336 zh: 4712f6eacd85a151 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md index 996805e3ee..852212e5c3 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md @@ -17,7 +17,7 @@ English | [中文](guide.zh.md) `@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. -`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id without a published credential counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. +`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md index 18fdd11b89..f4edae7d39 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md @@ -17,7 +17,7 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 `@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 -`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 +`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 ## 迁移 diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index 42582881ec..67b48ecaed 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -54,8 +54,8 @@ en: 14f9af39f3be4fac zh: 3c7139fba0f17862 /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work: - en: 3880e7c032129fb7 - zh: ad1450509e3473ab + en: c71abd58d3afbcfe + zh: d463321359b84e94 /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md index a653aadad9..737cf87336 100644 --- a/packages/web/web-deepseek-api/README.md +++ b/packages/web/web-deepseek-api/README.md @@ -132,7 +132,7 @@ A returning or removed web tool changes the declared tools as [`dsh-tool-web`](. - API query and URL constraints are enforced by the remote service. An unresolvable Fetch target returned HTTP 500 rather than the documented 404 on 2026-10-16, and its failure carries the same endpoint guidance as an endpoint failure. Fetch exposes neither the target status nor the final redirect URL, so results report HTTP 200 and the requested URL; the provider discards the API's page title. - `available()` cannot query asynchronous credential stores; `ready()` does, so model steps withhold the tools when the store lacks the key. A direct `ctx.web.search()` or `ctx.web.fetch()` call can still fail with a missing-credential error. - Search pacing limits send times within one plugin instance. Other processes and clients on the same account share the account-wide 5 QPS limit without coordination, and network jitter can still bunch arrivals; an HTTP 429 fails that search, and `dsh-tool-web` then fails the whole multi-query call. Fetch is not paced, so parallel `web_fetch` calls can exceed the Fetch limit. -- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.routeCredential`; an adapter that publishes no credential, such as a test replay adapter, counts as no route, so its conversations use `DEEPSEEK_API_KEY` and the official base. +- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.routeCredential`. An adapter that publishes no credential, such as a test replay adapter, or a credential of the other kind (an account credential as `deepseek-official`, an API key as `deepseek-account`) counts as no route: its conversations use `DEEPSEEK_API_KEY` and the official base, and `account` billing asks the account service as it does without the account route. ### Dev Note diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index c59eeb474a..9075dfe2c5 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -132,7 +132,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 - 查询和 URL 约束由远端服务执行。2026-10-16 抓取无法解析的目标域名时返回 HTTP 500,而非文档所述的 404,其失败信息与端点失败附带相同的端点指引。Fetch 既不暴露目标状态,也不暴露最终重定向 URL,因此结果报告 HTTP 200 和请求 URL;提供者丢弃 API 返回的页面标题。 - `available()` 无法查询异步凭据存储;`ready()` 可以,因此凭据存储缺少密钥时,模型步骤会撤下这两个工具。直接调用 `ctx.web.search()` 或 `ctx.web.fetch()` 仍可能因凭据缺失失败。 - Search 限速只约束单个插件实例内的发送时间。同一账号下的其他进程和客户端共享账号级 5 QPS 限制,彼此不协调,网络抖动也可能使请求集中到达;HTTP 429 会使该次搜索失败,随后 `dsh-tool-web` 会使整个多查询调用失败。Fetch 不限速,因此并行的 `web_fetch` 调用可能超过 Fetch 限制。 -- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.routeCredential` 发布的内容;不发布凭据的适配器(例如测试回放适配器)视为没有路由,其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址。 +- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.routeCredential` 发布的内容。不发布凭据的适配器(例如测试回放适配器),或发布另一种凭据的适配器(以 `deepseek-official` 发布账号凭据,或以 `deepseek-account` 发布 API 密钥),都视为没有路由:其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址,`account` 计费则像没有账号路由时一样询问账号服务。 ### 开发备注 diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 476dd51256..aeebcdd51f 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -22,7 +22,7 @@ import type {} from '@deepseek-ai/dsh-agent' import { credentialRef, credentialRefConfigured, resolveCredentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' +import { assertUsableApiKey, type LlmCredentialKind } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { DeepSeekFetchApiProvider } from './fetch.ts' @@ -127,6 +127,15 @@ const OFFICIAL_PROVIDER = 'deepseek-official' /** Model route whose published credential an operation can send. */ type RouteName = typeof ACCOUNT_PROVIDER | typeof OFFICIAL_PROVIDER +/** + * Credential kind each DeepSeek model route publishes. Billing chooses between the two kinds by route id, so an + * adapter registered under one of these ids that publishes the other kind is not that route. + */ +const ROUTE_CREDENTIAL_KIND = { + [ACCOUNT_PROVIDER]: 'account', + [OFFICIAL_PROVIDER]: 'api-key', +} as const satisfies Record + /** * Launch-environment variable naming the DeepSeek deployment the model routes default to. Without the account route, * its origin receives the signed-in account's credential. @@ -257,13 +266,14 @@ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeek * @param ctx - context with the optional model service. * @param capability - the capability whose diagnostics a misconfigured source names. * @param provider - the route. - * @returns the source; undefined when no mounted route publishes a credential as `provider`; a misconfigured source - * when the route's settings do not resolve or its published base URL does not parse. + * @returns the source; undefined when no mounted route publishes a credential of that route's kind as `provider`; a + * misconfigured source when the route's settings do not resolve or its published base URL does not parse. */ function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined { try { const credential = ctx.get('llm')?.routeCredential(provider) - return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } + if (credential === undefined || credential.kind !== ROUTE_CREDENTIAL_KIND[provider]) return undefined + return { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } } catch (error: unknown) { return misconfigured(capability, provider, error) } diff --git a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts index ddc6c738d5..04082d58e6 100644 --- a/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts +++ b/packages/web/web-deepseek-api/tests/credential-resolution.spec.ts @@ -646,6 +646,50 @@ describe.each(OPERATIONS)('%s with its own endpoint settings', (operation) => { }) }) +describe.each(OPERATIONS)('%s beside an adapter that publishes the other credential kind under a DeepSeek route id', (operation) => { + const accountUnderOfficial: RouteRow = { provider: 'deepseek-official', publishes: 'account', config: { baseURL: 'https://route.deepseek.test/anthropic' } } + const keyUnderAccount: RouteRow = { provider: 'deepseek-account', publishes: 'api-key', config: { baseURL: 'https://account.deepseek.test/anthropic' } } + + it.each(['api-key', 'auto'])('sends DEEPSEEK_API_KEY to the official base under %s billing, never the account credential published as the API-key route', async (billing) => { + const asked: string[] = [] + const { ctx, sent } = await mount({ + config: { [`${operation}Billing`]: billing }, routes: [accountUnderOfficial], account: signedIn(asked), + environment: { DEEPSEEK_API_KEY: 'chat-key' }, + }) + expect(await ready(ctx, operation, 'deepseek-official')).toBe(true) + await operate(ctx, operation, 'deepseek-official') + expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: 'Bearer chat-key', token: null }]) + expect(asked).toEqual([]) + }) + + it('is not ready under API-key billing without a key, and never sends that account credential', async () => { + const asked: string[] = [] + const { ctx, sent } = await mount({ config: { [`${operation}Billing`]: 'api-key' }, routes: [accountUnderOfficial], account: signedIn(asked) }) + expect(await ready(ctx, operation, 'deepseek-official')).toBe(false) + await expect(operate(ctx, operation, 'deepseek-official')).rejects.toMatchObject({ code: 'WEB_PROVIDER_CREDENTIAL_MISSING' }) + expect(sent()).toEqual([]) + expect(asked).toEqual([]) + }) + + it('sends the signed-in account token to the default account origin under account billing, never the API key published as the account route', async () => { + const { ctx, sent } = await mount({ + config: { [`${operation}Billing`]: 'account' }, routes: [keyUnderAccount], account: signedIn(), + environment: { DEEPSEEK_API_KEY: 'chat-key' }, + }) + expect(await ready(ctx, operation, 'deepseek-account')).toBe(true) + await operate(ctx, operation, 'deepseek-account') + expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: null, token: 'account-token' }]) + }) + + it('treats a conversation on that account route id as one without an account route under automatic billing', async () => { + const { ctx, sent } = await mount({ routes: [keyUnderAccount], account: signedIn(), environment: { DEEPSEEK_API_KEY: 'chat-key' } }) + expect(await ready(ctx, operation, 'deepseek-account')).toBe(true) + await operate(ctx, operation, 'deepseek-account') + // The key goes to the official base, not to the base URL that adapter publishes. + expect(sent()).toEqual([{ endpoint: `${OFFICIAL}/${operation}`, authorization: 'Bearer chat-key', token: null }]) + }) +}) + describe('independent capabilities', () => { it('resolves Search from its own settings while Fetch follows the conversation', async () => { const { ctx, sent } = await mount({ diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index fff97df6c3..98b82fbf65 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -25,12 +25,14 @@ export interface RouteRow { throws?: unknown /** Base URL published in place of the resolved one, as a route publishing an unparsable base would. */ publishedBaseURL?: string + /** Credential kind published under this id, as another adapter registered under it can; defaults to the route's own kind. */ + publishes?: 'api-key' | 'account' } /** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */ function credentialOf(ctx: Context, route: RouteRow): RouteCredential { const environment = launchEnvironmentOf(ctx) - if (route.provider === 'deepseek-official') { + if ((route.publishes ?? (route.provider === 'deepseek-official' ? 'api-key' : 'account')) === 'api-key') { const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment) const ref = resolved.apiKeyEnv return { From 1966a5e2bbc18748428ce83c1e4a53e67426ec82 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 14:13:41 +0800 Subject: [PATCH 12/16] fix(llm-deepseek-account): end requests whose account credential is signed out Unloading the account route removed its sign-out listener and running-task report while a model request it had dispatched kept streaming, so a later sign-out neither closed that request nor cancelled its turn. A route credential grant now carries an optional `revoked` signal. The account service aborts it at each sign-out, after the deepseek-account/signed-out listeners return, and the shared transport runs the model request and its file operations under it. The route plugin names that end ACCOUNT_SIGN_IN_REQUIRED and cancels the route's running Agents from the request's own failure callback, so a turn whose route was disabled mid-turn still ends with the signed-out cause, and disabling the route never waits for a turn. The Search and Fetch API providers and Messages search run their request under the same signal and report WEB_PROVIDER_ERROR with sign-in guidance, keeping WEB_ABORTED for caller cancellation. Account model requests outside an Agent turn and account-billed web requests therefore end at sign-out as well. The web-search-account-signout recorded scenario pins the failure the model sees. While the route is disabled, a task it started that is executing a tool is not reported to the sign-out confirmation and ends at its next model request, which fails because the route is no longer registered. The API-key route README Summary exceeded its 100-word limit; the origin detail moves to the usage section. --- ...6-09-17-account-provider-signout.i18n.yaml | 8 +- .../2026-09-17-account-provider-signout.md | 4 +- .../2026-09-17-account-provider-signout.zh.md | 4 +- ...-11-10-llm-route-credential-seam.i18n.yaml | 12 +- .../2026-11-10-llm-route-credential-seam.md | 20 +- ...2026-11-10-llm-route-credential-seam.zh.md | 20 +- apps/web/tests/cot-translation-paid.e2e.ts | 8 +- docs/persistence-catalog.i18n.yaml | 44 ++-- docs/persistence-catalog.md | 22 +- docs/persistence-catalog.zh.md | 22 +- docs/persistence-schema.json | 22 +- docs/subsystems/account.i18n.yaml | 4 +- docs/subsystems/account.md | 11 +- docs/subsystems/account.zh.md | 11 +- docs/subsystems/llm-streaming.i18n.yaml | 4 +- docs/subsystems/llm-streaming.md | 9 +- docs/subsystems/llm-streaming.zh.md | 9 +- .../llm-route-credential/guide.i18n.yaml | 8 +- .../v0.2.2-rc.2/llm-route-credential/guide.md | 8 +- .../llm-route-credential/guide.zh.md | 8 +- .../account/deepseek-account/README.i18n.yaml | 8 +- packages/account/deepseek-account/README.md | 4 +- .../account/deepseek-account/README.zh.md | 4 +- .../account/deepseek-account/src/index.ts | 25 ++- .../account/deepseek-account/src/types.ts | 6 + .../deepseek-account/tests/account-stub.ts | 10 +- .../deepseek-account/tests/account.spec.ts | 61 ++++++ .../extensions/tool-cordis/src/api-catalog.ts | 8 +- .../llm/llm-deepseek-account/README.i18n.yaml | 12 +- packages/llm/llm-deepseek-account/README.md | 5 +- .../llm/llm-deepseek-account/README.zh.md | 5 +- .../llm-deepseek-account/src/account-tasks.ts | 25 ++- .../llm/llm-deepseek-account/src/index.ts | 30 ++- .../tests/account-signout.spec.ts | 148 ++++++++++++++ .../llm/llm-deepseek-api-key/README.i18n.yaml | 8 +- packages/llm/llm-deepseek-api-key/README.md | 4 +- .../llm/llm-deepseek-api-key/README.zh.md | 4 +- packages/llm/llm-deepseek/README.i18n.yaml | 12 +- packages/llm/llm-deepseek/README.md | 6 +- packages/llm/llm-deepseek/README.zh.md | 6 +- packages/llm/llm-deepseek/package.json | 1 + packages/llm/llm-deepseek/src/adapter.ts | 18 +- packages/llm/llm-deepseek/src/types.ts | 12 +- .../tests/account-signout-composition.spec.ts | 190 ++++++++++++++++++ .../llm/llm-deepseek/tests/adapter.spec.ts | 31 ++- packages/llm/llm-deepseek/tests/files.spec.ts | 22 +- .../tests/route-credential.spec.ts | 8 +- packages/llm/llm/src/types.ts | 7 + .../web/web-deepseek-api/README.i18n.yaml | 8 +- packages/web/web-deepseek-api/README.md | 4 +- packages/web/web-deepseek-api/README.zh.md | 4 +- .../web/web-deepseek-api/src/transport.ts | 56 +++++- .../tests/composition.spec.ts | 37 +++- .../web-deepseek-api/tests/transport.spec.ts | 83 +++++++- .../web/web-search-deepseek/README.i18n.yaml | 8 +- packages/web/web-search-deepseek/README.md | 4 +- packages/web/web-search-deepseek/README.zh.md | 4 +- .../web/web-search-deepseek/src/provider.ts | 60 +++++- .../tests/deepseek.spec.ts | 61 +++++- pnpm-lock.yaml | 3 + .../web-search-billing-fixture.mjs | 13 +- .../runtime.cordis.yml | 4 + .../session.v4.jsonl | 22 ++ .../web-search-account-signout/snapshot.yml | 11 + 64 files changed, 1086 insertions(+), 234 deletions(-) create mode 100644 packages/llm/llm-deepseek-account/tests/account-signout.spec.ts create mode 100644 packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts create mode 100644 snapshots/session/web-search-account-signout/runtime.cordis.yml create mode 100644 snapshots/session/web-search-account-signout/session.v4.jsonl create mode 100644 snapshots/session/web-search-account-signout/snapshot.yml diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml index 883bb12bc0..0b8f4fca6a 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml @@ -9,11 +9,11 @@ en: 8d4d00e33af763b2 zh: 61977c82d66ae9bf /agent-note-account-provider-and-active-request-cancellation/decision: - en: d5eb12a1644c6226 - zh: 513d4f22ab74e039 + en: 6f5463ecf88c1435 + zh: 2097b8829e410c6b /agent-note-account-provider-and-active-request-cancellation/alternatives-considered: - en: a072026c1495a1ca - zh: bf053cc04fb33914 + en: 7ed93136cf11074a + zh: aea8dcf2e521a9c2 /agent-note-account-provider-and-active-request-cancellation/consequences: en: 8fd00b6d69b380c0 zh: 3830dc3a93d5de3c diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md index 6b8ef842c5..8ea62952ed 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.md @@ -14,11 +14,11 @@ Selecting credentials from login state changes the billing identity of an existi Account cancellation reads each running Agent’s latest `Session.requestContext()` instead of maintaining another provider field. This logged value remains through tools and retries and follows the next bound request. Idle Agents are excluded. During a new turn’s first preparation it can still name the previous turn’s account route, so sign-out can also interrupt an API-key turn that has not bound its new request yet. A missing account credential rejects a first request without a previous context before transport. -Successful local sign-out publishes an account event. The platform account provider installs the account module’s listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. The account controller shares its predicate for sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. +Successful local sign-out publishes an account event. The account route plugin installs a listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. It registers the same predicate with the account service as the running-task report behind sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. Requests this listener cannot reach end through the withdrawal signal of their credential, which the [route credential decision](2026-11-10-llm-route-credential-seam.md) owns. ## Alternatives considered -A historical set of providers wrongly cancels a turn after it switches to an API-key route. Current settings misclassify an older in-flight request. A second provider field or module-global map duplicates information already recorded in request context. A login-level cancellation signal duplicates the existing Agent and HTTP cancellation chain. +A historical set of providers wrongly cancels a turn after it switches to an API-key route. Current settings misclassify an older in-flight request. A second provider field or module-global map duplicates information already recorded in request context. A login-level cancellation signal in place of this chain duplicates the existing Agent and HTTP cancellation; the credential's withdrawal signal only supplements it. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md index 588dd38bf9..a7a8d2d6fc 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md @@ -14,11 +14,11 @@ Status: implemented 账号取消读取运行中 Agent 最近的 `Session.requestContext()`,不维护额外提供方字段。该已记录值在工具和重试阶段保留,随下一次绑定请求更新;空闲 Agent 不计入。新轮次首次准备期间,它仍可能指向上一轮的账号路由,因此退登也可能打断尚未绑定新请求的 API key 轮次。没有历史上下文的首请求若缺少账号凭据,会在传输前失败。 -本地退登成功后发布账号事件。Platform 账号提供方安装账号模块的监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。账号控制器的退登确认复用同一判断函数。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。 +本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的收回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。 ## Alternatives considered -历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。登录级取消信号重复现有 Agent 与 HTTP 取消链路。 +历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。用登录级取消信号取代这条链路,会重复现有的 Agent 与 HTTP 取消;凭据的收回信号只是对它的补充。 ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index ab73ce9fc2..3ea538f271 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,11 +9,11 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 964d66432578805a - zh: 90b93fb955b60afb + en: 339c58ce1afd8225 + zh: 00b0b683d6de2edc /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: - en: 8177946a6bfa1a6d - zh: f523f9057b4b47c5 + en: d6b2de393add9887 + zh: b5351f9a49387bd6 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: - en: f96508aa7cea1e87 - zh: 3eb61bdce43590bc + en: 748f306d720ade43 + zh: 792386be47105525 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index 08eaef0f5a..b41afa2b2b 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -10,15 +10,15 @@ Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/ ## Decision -`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, and an optional `reject()` for HTTP 401. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. +`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. -`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The listing cache scopes by endpoint and a hash of the credential headers. +`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The transport runs each model request and its file operations under the grant's `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers. -The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. +The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. A request in flight at sign-out ends with its grant's `revoked` signal and fails as `ACCOUNT_SIGN_IN_REQUIRED`, and its failure callback cancels the same Agents, so a request that outlives the plugin still ends its turn with the signed-out cause. -`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, and a `reject()` that removes the grant while it still matches and contains storage failures; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. +`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. -The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. ## Alternatives considered @@ -32,6 +32,16 @@ The web providers consume publications. `web-deepseek-api` builds each operation **Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own. +**Keeping the route plugin's sign-out listener until its tasks end.** Unloading the route then waits for a running turn: disabling the plugin blocks, and every other settings write queues behind that reload, for as long as the turn runs. + +**Cancelling the route's tasks when the route unloads.** A configuration reload or a plugin update would stop turns that no sign-out touched. + +**Returning the sign-out policy to the account service.** The service would again inspect Agents and know route ids, the dependencies this decision removes. + +**Keeping the route's listener or report registered after its plugin unloads.** A registration that outlives the plugin that made it breaks the rule that registrations are effects of their owner, and leaves code of an unloaded plugin running in another scope for as long as the task runs. + ## Consequences Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. + +A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index 573eafd0e4..d025903ed3 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -10,15 +10,15 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`,以及可选的 HTTP 401 `reject()`。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时收回凭据,该信号即中止。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 -`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。列表缓存以端点和凭据请求头的哈希划分作用域。 +`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。 -路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。 +路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。退登时在途的请求随其授权的 `revoked` 信号结束,以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;它的失败回调会取消同一批 Agent,因此比插件存活更久的请求仍会以退登原因结束其回合。 -`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token 和 `reject()`;`reject()` 仅在授权仍一致时删除它并隔离存储失败。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 +`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token、`reject()` 和 `revoked` 信号;`reject()` 仅在授权仍一致时删除它并隔离存储失败,`revoked` 由服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 -Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 ## 考虑过的替代方案 @@ -32,6 +32,16 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route **把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。 +**让路由插件的退登监听保留到其任务结束。** 这样卸载路由要等待运行中的回合:停用插件会被阻塞,其他设置写入也排在这次重载之后,直到回合结束。 + +**路由卸载时取消其任务。** 配置重载或插件更新会停掉与退登无关的回合。 + +**把退登策略放回账号服务。** 账号服务将重新检查 Agent 并认识路由 id,而这正是本决策去掉的依赖。 + +**插件卸载后仍保留路由的监听或报告注册。** 比注册它的插件存活更久的注册违反“注册是其所有者的 effect”这一规则,并让已卸载插件的代码在任务运行期间留在其他作用域里。 + ## 后果 新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 + +退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登收回;路由插件的监听仍会取消 Agent 回合。 diff --git a/apps/web/tests/cot-translation-paid.e2e.ts b/apps/web/tests/cot-translation-paid.e2e.ts index 7648cbe3ff..1e08265e12 100644 --- a/apps/web/tests/cot-translation-paid.e2e.ts +++ b/apps/web/tests/cot-translation-paid.e2e.ts @@ -142,10 +142,12 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr const account = scaffold.ctx.get('deepseekAccount') if (account === undefined) throw new Error('Shipped native Account service is absent') // Only credential acquisition is nondeterministic; the Loader-owned native route and wire remain real. + const credential = { + headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token', + revoked: new AbortController().signal, reject: () => Promise.resolve(), + } const auth = vi.spyOn(account, 'resolveRequestCredential').mockImplementation(async (url: string) => - new URL(url).origin === origin - ? { headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token', reject: () => Promise.resolve() } - : undefined) + new URL(url).origin === origin ? credential : undefined) resources.restoreAuth = () => { auth.mockRestore() } scaffold.ctx.emit('llm/adapters-updated') const owner = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'llm-deepseek-account') diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 0ab9b5b7fe..1d54521a32 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -558,8 +558,8 @@ en: 028791baa24a6a0a zh: 028791baa24a6a0a /session-persistence-event-catalog/resolved-persistence-types/in-history: - en: eef7993dfeef3c9d - zh: 36f6a03a24688113 + en: b952affc9dc40743 + zh: dd5d0872283e3762 /session-persistence-event-catalog/resolved-persistence-types/in-progress: en: 61de2b0c9de8c15b zh: 61de2b0c9de8c15b @@ -1194,8 +1194,8 @@ en: 8d2873c634bf6405 zh: 91e92b5730462cf0 /session-persistence-event-catalog/resolved-persistence-types/replayenvelope: - en: c0559f92b5275c58 - zh: 50616ae676eeee4c + en: 293da0eae99bdbe8 + zh: 244c9cfd281b9451 /session-persistence-event-catalog/resolved-persistence-types/requestcontext: en: 544039047a28b6bb zh: c691f0bb1e23db08 @@ -1245,8 +1245,8 @@ en: 29df35a8cc984e75 zh: 321b4e8bb0ad0850 /session-persistence-event-catalog/resolved-persistence-types/streamchunk: - en: 1585ce86ccaaca53 - zh: b3073eb80e23a11f + en: 71d48d17e3763774 + zh: 8cb0f1d92afa3236 /session-persistence-event-catalog/resolved-persistence-types/subagentcatalogevent: en: 8a56ae8e701509b3 zh: caef4f0223f65470 @@ -1314,8 +1314,8 @@ en: 49fcbb63c824347e zh: 187486d676edfe0e /session-persistence-event-catalog/resolved-persistence-types/toolschema: - en: a1613c3dc1fd1b54 - zh: eb4590c068e2699c + en: d9e99600cd0c02c3 + zh: 9885b7337c349b41 /session-persistence-event-catalog/resolved-persistence-types/toolschema~2: en: 12c14727bb7834e2 zh: b0f3c877873c36db @@ -2007,11 +2007,11 @@ en: bb507524bcc39c53 zh: 8314898562437473 /session-persistence-event-catalog/resolved-persistence-types/type-block-end: - en: c65956b2e4936b98 - zh: 04a10188520dd9e2 + en: 13224de3736d2d48 + zh: 6bf99a32b41f7165 /session-persistence-event-catalog/resolved-persistence-types/type-block-start: - en: 10eec3e1fa456886 - zh: a62e18e8e00a5f18 + en: 598ec19ec3abf6ed + zh: 84efc0177a9fd177 /session-persistence-event-catalog/resolved-persistence-types/type-chunk: en: 4b0ed1fe2caa26fb zh: 8fffdc4f8c3deb79 @@ -2052,8 +2052,8 @@ en: 14e4b48d856bcf57 zh: 72ba176535dc7f3f /session-persistence-event-catalog/resolved-persistence-types/type-finish: - en: df64e36d97f48908 - zh: 86cf679e6b3fdb85 + en: e1b5a95753e1984b + zh: 3a04bd831ff9f12d /session-persistence-event-catalog/resolved-persistence-types/type-goal-change: en: aad2516b62d3ee83 zh: e7204c4dc4e8e408 @@ -2091,8 +2091,8 @@ en: 4bf62582902829c5 zh: c9da9d11402ee1c4 /session-persistence-event-catalog/resolved-persistence-types/type-reasoning-delta: - en: bcafe0c539f6a5e2 - zh: 3be968698a8985bc + en: a2952ab46acfed9d + zh: b4e68befe87800dd /session-persistence-event-catalog/resolved-persistence-types/type-request-context: en: f8addb1a01da9ca1 zh: 4ef11ebddd302c05 @@ -2154,8 +2154,8 @@ en: 28bab22053eabff2 zh: 54c0e424fcb99c05 /session-persistence-event-catalog/resolved-persistence-types/type-text-delta: - en: 908a84e2ee82a7cc - zh: 5d8994c209e864a0 + en: 9856f0f63d3b413c + zh: c3bae6ac9e949696 /session-persistence-event-catalog/resolved-persistence-types/type-todo-write: en: 2fa7ba77598a95b4 zh: 50972b51d77e9155 @@ -2163,8 +2163,8 @@ en: 45ff4145d9e2c7d4 zh: 36a346ff729c4b84 /session-persistence-event-catalog/resolved-persistence-types/type-tool-call-delta: - en: 9663efae6bd28efb - zh: d8765a82a6b537a5 + en: 7c45dcb12f5fedb5 + zh: eea8f79e052f2bf0 /session-persistence-event-catalog/resolved-persistence-types/type-tool-workflow-agent-end: en: 8eb5e1eb95722bc7 zh: 8dd5980029600648 @@ -2196,8 +2196,8 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: 20d2e379fc64c866 - zh: b2d35dba5d3006af + en: 46b4cd2140687d30 + zh: 58103f952fa4ed89 /session-persistence-event-catalog/resolved-persistence-types/type-user-message: en: fd9f5dacef8c0ce8 zh: 79eab747b55dfaac diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index c5f40937d0..203f54c65e 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -2018,7 +2018,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -Sources: [`packages/llm/llm/src/types.ts:521`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:528`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -4564,7 +4564,7 @@ Sources: [`packages/llm/llm/src/types.ts:75`](../packages/llm/llm/src/types.ts) SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -Sources: [`packages/llm/llm/src/types.ts:555`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:562`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4878,7 +4878,7 @@ Sources: [`packages/skill/skill/src/index.ts:149`](../packages/skill/skill/src/i SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -Sources: [`packages/llm/llm/src/types.ts:577`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) One of: @@ -5307,7 +5307,7 @@ Sources: [`packages/llm/llm/src/message.ts:172`](../packages/llm/llm/src/message SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -Sources: [`packages/llm/llm/src/types.ts:598`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:605`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8314,7 +8314,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -Sources: [`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:589`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8328,7 +8328,7 @@ Sources: [`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -Sources: [`packages/llm/llm/src/types.ts:578`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:585`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8546,7 +8546,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -Sources: [`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:591`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8752,7 +8752,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:27`](../packages/llm/llm/src SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -Sources: [`packages/llm/llm/src/types.ts:580`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:587`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9088,7 +9088,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:20`](../packages/llm/llm/src SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -Sources: [`packages/llm/llm/src/types.ts:579`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:586`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9136,7 +9136,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:34`](../packages/llm/llm/src SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -Sources: [`packages/llm/llm/src/types.ts:581`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:588`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -9314,7 +9314,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -Sources: [`packages/llm/llm/src/types.ts:583`](../packages/llm/llm/src/types.ts) +Sources: [`packages/llm/llm/src/types.ts:590`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 74ae5c7936..7ada7ea1b8 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -2020,7 +2020,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8` SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5` -来源:[`packages/llm/llm/src/types.ts:521`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:528`](../packages/llm/llm/src/types.ts) `"in-history"` @@ -4566,7 +4566,7 @@ SHA-256: `814d9434e1ddf9078612b3b34322f26e9363b469213335007f7e9ba7fee9464e` SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` -来源:[`packages/llm/llm/src/types.ts:555`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:562`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4880,7 +4880,7 @@ SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db` SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180` -来源:[`packages/llm/llm/src/types.ts:577`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) 以下类型之一: @@ -5309,7 +5309,7 @@ SHA-256: `4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731` SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2` -来源:[`packages/llm/llm/src/types.ts:598`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:605`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8316,7 +8316,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625` SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` -来源:[`packages/llm/llm/src/types.ts:582`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:589`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8330,7 +8330,7 @@ SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d` SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90` -来源:[`packages/llm/llm/src/types.ts:578`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:585`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8548,7 +8548,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1` -来源:[`packages/llm/llm/src/types.ts:584`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:591`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8754,7 +8754,7 @@ SHA-256: `71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd` SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095` -来源:[`packages/llm/llm/src/types.ts:580`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:587`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9090,7 +9090,7 @@ SHA-256: `e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33` SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65` -来源:[`packages/llm/llm/src/types.ts:579`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:586`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9138,7 +9138,7 @@ SHA-256: `3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6` SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a` -来源:[`packages/llm/llm/src/types.ts:581`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:588`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -9316,7 +9316,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` -来源:[`packages/llm/llm/src/types.ts:583`](../packages/llm/llm/src/types.ts) +来源:[`packages/llm/llm/src/types.ts:590`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 71dc45b012..16a2cf3438 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -88,7 +88,7 @@ {"digest":"0a8a062bc9c3c0d97fd97742262f2ea53dd32297f834e81114870d38ac3dc6da","names":[],"sources":[]}, {"digest":"0a92c5bdfa06c2e2615b777728f3aa95f408d43b9012e7b754568311251db623","names":[],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:29"]}, {"digest":"0aa62ab51b36c0e64b134bd03ba8725d758744180a1a447da49beaad194f219f","names":[],"sources":[]}, - {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:555"]}, + {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:562"]}, {"digest":"0af3ecfb8c60d416fc40a7cc4fb2c4851a8e46608b2b38ab9e510670c971aa1f","names":[],"sources":[]}, {"digest":"0b6d718c693fdf7f06dcccb0bcbbabe78cc63514eafc62d6b2a3899735279d6f","names":["packages/goal/goal/src/types.ts#GoalRef"],"sources":["packages/goal/goal/src/types.ts:20"]}, {"digest":"0b9b8facbe2c19773b3fb0ecc824ccbcc603d41b8f18069faa3807d449572fce","names":[],"sources":[]}, @@ -180,7 +180,7 @@ {"digest":"297fbd8067d7815adae02b89790ec6ff5fb7c2cb0d0eb026e1746c24ec857761","names":[],"sources":[]}, {"digest":"2aad1179f957631477b582e57cd8f538cb82618fc3fb816bde1171154235b065","names":[],"sources":[]}, {"digest":"2ab12a0e345658f9342816d773fe610f049982bcad82631f43b9205abe43e5ee","names":[],"sources":[]}, - {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:580"]}, + {"digest":"2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095","names":[],"sources":["packages/llm/llm/src/types.ts:587"]}, {"digest":"2aed07493b1c65b6d00de5586da1e743cf501684b9ad43a1765fb4007d4ea456","names":[],"sources":[]}, {"digest":"2c4c21f19f426a58f2dac914e34313aa43f8408972de857a486d1f086d5adb6c","names":[],"sources":[]}, {"digest":"2c64d4bc7264fd3f8bed47e96ab8a593bce05a1e4e1c436dcd244a3b7e0c2a9d","names":[],"sources":[]}, @@ -220,7 +220,7 @@ {"digest":"3bca25b2baa6b22be9b577621a7603497f40870ed88a8dac4383d37dc2bb6e18","names":[],"sources":[]}, {"digest":"3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f","names":["packages/core/session/src/types.ts#OptionalSessionSeq"],"sources":["packages/core/session/src/types.ts:66"]}, {"digest":"3bdb8dc6989655b0d4ec361edafb8e2629bc263e1ea591819414fdafc1a413b3","names":[],"sources":[]}, - {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:578"]}, + {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:585"]}, {"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]}, {"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]}, {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, @@ -245,7 +245,7 @@ {"digest":"45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448","names":[],"sources":["packages/interaction/user-approval/src/types.ts:44"]}, {"digest":"477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028","names":[],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:25"]}, {"digest":"47e5d84f1a93450a78c7f3954b43990d0f629af7c034a56313e5deb63e772c1b","names":[],"sources":[]}, - {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:577"]}, + {"digest":"47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180","names":["packages/llm/llm/src/types.ts#StreamChunk"],"sources":["packages/llm/llm/src/types.ts:584"]}, {"digest":"487b65c37bfedb8b72088c4107a0a90a6249701f6b26745f6d98f9b8a22b07c7","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:43"]}, {"digest":"48e5c9861f16ac07e78cb7b5ae9dabdf7bb85c58baed5a51b4ad275050ea58e3","names":[],"sources":[]}, {"digest":"48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb","names":[],"sources":[]}, @@ -323,7 +323,7 @@ {"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]}, {"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:34"]}, {"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:36"]}, - {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:598"]}, + {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:605"]}, {"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:149"]}, {"digest":"67d5f73ceae82f5265258142ad6cf172de2c1fef93ba551b7f0454e0a93bffe0","names":["packages/llm/llm/src/call-config.ts#LlmCallConfig"],"sources":["packages/llm/llm/src/call-config.ts:30"]}, {"digest":"68141cbe3994a5ffcd064c07c75996538437fd9dbf77ce8a2927e89ec577fabe","names":[],"sources":[]}, @@ -411,7 +411,7 @@ {"digest":"871bfd6f7bb91061246768d3377f3fd58d6b8ea7c31f44c714ae7ab215650d62","names":[],"sources":[]}, {"digest":"87b1a33564b9a4d63b00988a524c12259243953aebb9c9a05127d87b27464df9","names":[],"sources":[]}, {"digest":"88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa","names":[],"sources":[]}, - {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:581"]}, + {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:588"]}, {"digest":"8a046b52331959aa3394680d6acbe09b8a5447c6b61375f263445bfcef19b7f1","names":[],"sources":[]}, {"digest":"8a54d228b1b7d8453e4304d32723d489f28b4b33b221f335342146926ad94fc6","names":[],"sources":[]}, {"digest":"8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0","names":[],"sources":[]}, @@ -440,7 +440,7 @@ {"digest":"93cbbc5a7fd0b1aa1ff1b9a6bb5ec52b073f48e5a5200365c45c0cd54059e1b9","names":[],"sources":["packages/interaction/user-approval/src/types.ts:55"]}, {"digest":"93d38436347f67c9022aacbc4472e283d722bcab8eb73fc376aaf7b6a6b9fb35","names":[],"sources":[]}, {"digest":"94c56aeb1564ad735eb773d88636b40761d063efa1610f1308004d32923f5378","names":[],"sources":[]}, - {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:579"]}, + {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:586"]}, {"digest":"95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd","names":[],"sources":[]}, {"digest":"95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60","names":[],"sources":[]}, {"digest":"9645cf93769a6dfb227bd400bd6cb9fa7bab9140f4a851e4ae92514ade6e3114","names":[],"sources":[]}, @@ -474,7 +474,7 @@ {"digest":"a15a19ef63cf5d1b711db1d249821dab0cedcd3a9ad09137b47352c93841fd20","names":[],"sources":[]}, {"digest":"a16e567c8cd2c55cf1e911aed3c200c4e1f6febb1459ff2a9e7adf159afb68cb","names":[],"sources":[]}, {"digest":"a2066bd52f61218ba15b758def2641cc6a8bd3d4a594a488ee4c65be356d7e39","names":[],"sources":[]}, - {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:584"]}, + {"digest":"a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1","names":[],"sources":["packages/llm/llm/src/types.ts:591"]}, {"digest":"a2be0f0cb59f0d4a06557d45847d1938aced238baa77a6da416e590b8b958553","names":[],"sources":[]}, {"digest":"a3a259a1aa5401af786ce08c4a8419681d3000d73467991b5fc563389bc4ebd2","names":[],"sources":[]}, {"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]}, @@ -596,7 +596,7 @@ {"digest":"d0fbb0ca1bbba059830826f33f801da1aced35a2504376d61e020bdfec8d50c0","names":[],"sources":[]}, {"digest":"d28765f87d6b6ab408e0b2f3e7e297791b004b806d8e302c49903ebae815feb2","names":[],"sources":[]}, {"digest":"d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41","names":[],"sources":[]}, - {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:582"]}, + {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:589"]}, {"digest":"d4c799e3d51cae1040362ba4968efc484739e14416c9c1df20c2f108b4ef2eb5","names":[],"sources":[]}, {"digest":"d4e4d575abeb4b72d616dc65c17ac0eaa943cc135609395044c38d5afcb10e31","names":[],"sources":[]}, {"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9","names":[],"sources":[]}, @@ -670,11 +670,11 @@ {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:238"]}, {"digest":"f1996af2602e6f62b5ab179ca5c4af00d8753938b74cc6ef102de09e99e74a7e","names":[],"sources":[]}, {"digest":"f19bee84bf3d20904553cdcd57465232bc1c2a194f54c4d195292ba0487223a6","names":["packages/attachment/attachment/src/types.ts#FileAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:39"]}, - {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:583"]}, + {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:590"]}, {"digest":"f230c0b583e23b25ee0a61dbe4c05e95c1e2ae44b27939501eb9e03696f0c278","names":[],"sources":[]}, {"digest":"f29d63336e8266d80dd7baeab219436db86341304f6be1cd0edb36f5134c4a47","names":[],"sources":[]}, {"digest":"f2da0f27c1e6add59982c37b15e4a4912c5b33466859cce3b13d503600e24aef","names":["packages/llm/llm/src/types.ts#FileBlock"],"sources":["packages/llm/llm/src/types.ts:105"]}, - {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:521"]}, + {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:528"]}, {"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]}, {"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]}, {"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]}, diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index b202a8713e..ff6e299f2a 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -6,8 +6,8 @@ en: 2302e2999588bac3 zh: 5e0ac058b50036dc /deepseek-account/request-credentials: - en: 808ace524e0dbc0b - zh: c4268221fa4c1c09 + en: 8b2ab927576926cf + zh: c383046df37bfade /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md index b3a20e14ff..a550fc9d13 100644 --- a/docs/subsystems/account.md +++ b/docs/subsystems/account.md @@ -8,9 +8,9 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun ## Request credentials -`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released. -Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`. +Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`; a request that outlives the plugin ends through its credential's `revoked` signal, and the plugin's failure callback for that request cancels the work. ## Embedded Platform credentials @@ -97,7 +97,8 @@ async getPlatformSession(): Promise /** * Release the account credential for one request to `url` as the request * carries it, together with its invalidation, which runs on the account - * service mounted when it is called. Host-only. + * service mounted when it is called, and the signal this service aborts + * when it signs out of that credential. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ @@ -204,10 +205,10 @@ Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/accoun #### `deepseek-account/signed-out` — emit -Local grant removal has completed. +Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. ```ts cordis-catalog -/** Local grant removal has completed. +/** Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. * @mode emit */ 'deepseek-account/signed-out'(): void diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index 341b2923ac..6624963d70 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,9 +8,9 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只收回自己释放的凭据。 -按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责。 +按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责;比插件存活更久的请求通过其凭据的 `revoked` 信号结束,插件为该请求提供的失败回调随后取消这些工作。 ## 内嵌 Platform 凭证 @@ -97,7 +97,8 @@ async getPlatformSession(): Promise /** * Release the account credential for one request to `url` as the request * carries it, together with its invalidation, which runs on the account - * service mounted when it is called. Host-only. + * service mounted when it is called, and the signal this service aborts + * when it signs out of that credential. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ @@ -204,10 +205,10 @@ Source: [`packages/account/deepseek-account/src/types.ts`](../../packages/accoun #### `deepseek-account/signed-out` — emit -Local grant removal has completed. +Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. ```ts cordis-catalog -/** Local grant removal has completed. +/** Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. * @mode emit */ 'deepseek-account/signed-out'(): void diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index 712c712ab4..ec3c50fe81 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -36,8 +36,8 @@ en: 58dec2259b0b1c6f zh: fc99fe965acaabf3 /llm-streaming/the-model-request: - en: 1962ba10f5515278 - zh: 9fa56ed8f54136aa + en: a345a763b420ff1a + zh: 10937f0f9b040eea /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 4ab60ea418..2b0427644f 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -527,7 +527,7 @@ interface LlmNativeAuth { } ``` -A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.routeCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. +A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.routeCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. A grant whose owner can withdraw the credential while requests carry it, as an account sign-out does, has a `revoked` signal: the consumer runs each request it authenticates under that signal and reports a request the signal ended as its own failure, not as the caller's cancellation. ```ts type-equiv /** @@ -554,6 +554,13 @@ interface RouteCredentialGrant { * @returns settlement after the invalidation attempt. */ reject?(): Promise + /** + * Aborts when the owner withdraws this credential while requests carrying it + * may be in flight, as an account sign-out does. A consumer ends each request + * it authenticated with this grant and reports that end as its own failure, + * not as the caller's cancellation. Absent for kinds that are never withdrawn. + */ + readonly revoked?: AbortSignal } ``` diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 19a694ea5e..67fa37b2f5 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -533,7 +533,7 @@ interface LlmNativeAuth { } ``` -路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。 +路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时收回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 ```ts type-equiv /** @@ -560,6 +560,13 @@ interface RouteCredentialGrant { * @returns settlement after the invalidation attempt. */ reject?(): Promise + /** + * Aborts when the owner withdraws this credential while requests carrying it + * may be in flight, as an account sign-out does. A consumer ends each request + * it authenticated with this grant and reports that end as its own failure, + * not as the caller's cancellation. Absent for kinds that are never withdrawn. + */ + readonly revoked?: AbortSignal } ``` diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index 18492ce96a..1e48e714c7 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -9,8 +9,8 @@ en: f0139803159ee9c9 zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: - en: 47b4fa692d98e1cf - zh: 42869beb3efbe290 + en: 4e77c6f6c622beb2 + zh: 03f3756a54dcbfa8 /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: - en: 64ac045c8d9a1336 - zh: 4712f6eacd85a151 + en: 6d117f2dfd7593d0 + zh: 1c1579fc7d0ccad0 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md index 852212e5c3..f8dcf10eec 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md @@ -9,21 +9,21 @@ English | [中文](guide.zh.md) ## Change -`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`. +`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, an optional `reject()`, and an optional `revoked` withdrawal signal. `@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional. `@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report. -`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. +`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. A sign-out aborts released credentials' `revoked` signal, ending in-flight account requests: model requests outside a turn fail with `ACCOUNT_SIGN_IN_REQUIRED`, Search and Fetch with `WEB_PROVIDER_ERROR`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. `@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. ## Migration -1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.routeCredential(provider)`. +1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.routeCredential(provider)`, and run each request under the grant's `revoked` signal. 2. In custom `DeepSeekAdapter` or `registerDeepSeekProvider` consumers, return `undefined` from `resolveAuth` when no credential exists, add `value` to every `DeepSeekRequestAuth`, supply `missingCredential` for a route-specific failure, and declare `credential` to publish the route's credential. Pass credential headers, not a token, to `createModelListingCache`. 3. Replace imports of the route plugins' config exports with the plugins' own `Config`, and read a route's endpoint from its published credential instead of its resolver. -4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead. +4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`, returning a `revoked` signal; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead. 5. Update workspace references to `packages/account/deepseek-account`; the npm package name, Remote namespace, and configuration keys are unchanged. 6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `RouteCredentialGrant`. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md index f4edae7d39..de47c7df60 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md @@ -9,21 +9,21 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 ## 变更 -`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。 +`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 收回信号。 `@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 `@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。 -`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 +`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。退登会中止已释放凭据的 `revoked` 信号,从而结束在途的账号请求:回合之外的模型请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,Search 与 Fetch 以 `WEB_PROVIDER_ERROR` 失败。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 `@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 ## 迁移 -1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.routeCredential(provider)`。 +1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.routeCredential(provider)`,并让每个请求受授权的 `revoked` 信号约束。 2. 在自定义的 `DeepSeekAdapter` 或 `registerDeepSeekProvider` 消费方中,没有凭据时让 `resolveAuth` 返回 `undefined`,为每个 `DeepSeekRequestAuth` 加上 `value`,为路由专属的失败提供 `missingCredential`,并声明 `credential` 以发布路由凭据。向 `createModelListingCache` 传递凭据请求头而不是 token。 3. 用路由插件自身的 `Config` 替换对其配置导出的导入,并从路由发布的凭据而非其解析函数读取端点。 -4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential`;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。 +4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential` 并返回 `revoked` 信号;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。 5. 把工作区引用更新为 `packages/account/deepseek-account`;npm 包名、Remote 命名空间和配置键均不变。 6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `RouteCredentialGrant` 的 `resolveAccountCredential`。 diff --git a/packages/account/deepseek-account/README.i18n.yaml b/packages/account/deepseek-account/README.i18n.yaml index e9ec42ad16..791db541dc 100644 --- a/packages/account/deepseek-account/README.i18n.yaml +++ b/packages/account/deepseek-account/README.i18n.yaml @@ -6,8 +6,8 @@ en: 9dbb9bc3960a11fe zh: ed58987926489d3e /deepseek-ai-dsh-deepseek-account: - en: d5aad878bc7d3059 - zh: 3573506e849ad4d4 + en: cc98cb1949c9fe0f + zh: bbb0b8fa319b9abc /deepseek-ai-dsh-deepseek-account/summary: en: 28bcca957bf6abf4 zh: 4a3fc8a59f2925bc @@ -15,8 +15,8 @@ en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: 210ba1bd070bb8c4 - zh: 4e1286bff076a3b6 + en: 68071ab7db44e807 + zh: a9efa62ee12d3fdd /deepseek-ai-dsh-deepseek-account/understand-the-implementation: en: 76d2da2dab100ac3 zh: 2c9404f27915daab diff --git a/packages/account/deepseek-account/README.md b/packages/account/deepseek-account/README.md index b26272b1d0..e9f9a41998 100644 --- a/packages/account/deepseek-account/README.md +++ b/packages/account/deepseek-account/README.md @@ -13,7 +13,7 @@ getPlatformSession exports the stored grant only when its issuer matches platfor `desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. -Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. The account model route and the DeepSeek web providers use it instead of composing headers themselves. +Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures, and a `revoked` signal; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. The account model route and the DeepSeek web providers use it instead of composing headers themselves, and end the request that carries the token when `revoked` aborts. ## Summary @@ -42,7 +42,7 @@ The `/client-metadata` entry provides pure Platform header and cookie helpers fo The profile projection maps `id_profile.picture` to `avatarUrl`, using null when no picture is configured. -Token resolution refuses requests while local sign-out is in progress. Successful local removal publishes `deepseek-account/signed-out` before returning the signed-out snapshot; remote revocation remains independent. +Token resolution refuses requests while local sign-out is in progress. Successful local removal publishes `deepseek-account/signed-out`, then aborts the `revoked` signal of the request credentials released for that sign-in, before returning the signed-out snapshot; a rejected token signs out the same way. Remote revocation remains independent. getProfile / getBalance sends the stored grant in the x-dsh-auth-token header to GET /auth-api/v0/users/current and GET /api/v0/users/get_user_summary on platformOrigin. The grant issuer must match that origin. Host projects only the account UID, profile name, avatar URL, phone or email exactly as masked by Platform, and normal_wallets / bonus_wallets currency/balance strings; response tokens and other fields are discarded. A balance or bonus-amount string is accepted when it matches the numeric grammar Platform's Web client already passes to big.js, which allows an omitted integer or fraction part and a decimal exponent, so values such as 0E-16 and 5.0000000000000000 stay valid; the original string is retained and NaN, Infinity and malformed text are rejected. Bonus wallets remain separate from recharge balances. Credential changes and disposal invalidate in-flight queries. diff --git a/packages/account/deepseek-account/README.zh.md b/packages/account/deepseek-account/README.zh.md index d219131533..db777bbe7c 100644 --- a/packages/account/deepseek-account/README.zh.md +++ b/packages/account/deepseek-account/README.zh.md @@ -13,7 +13,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 `desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 -资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。 +资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token、`reject()` 和 `revoked` 信号的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头,并在 `revoked` 中止时结束携带该 token 的请求。 ## 概述 @@ -42,7 +42,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导 账号资料投影将 `id_profile.picture` 映射为 `avatarUrl`,没有配置头像时返回 null。 -本地退出登录期间拒绝解析 token。本地授权成功删除后,先发布 `deepseek-account/signed-out`,再返回已退出的状态快照;远程撤销独立执行。 +本地退出登录期间拒绝解析 token。本地授权成功删除后,先发布 `deepseek-account/signed-out`,接着中止为该次登录释放的请求凭据的 `revoked` 信号,再返回已退出的状态快照;token 被拒绝时的退登同样如此。远程撤销独立执行。 getProfile / getBalance 将保存的授权 token 通过 x-dsh-auth-token 请求头,向 platformOrigin 上的 GET /auth-api/v0/users/current 和 GET /api/v0/users/get_user_summary 发起请求。授权签发来源必须与该来源一致。Host 只投影账号 UID、资料名称、头像 URL、由 Platform 脱敏的手机号或邮箱(原样保留),以及 normal_wallets / bonus_wallets 的币种和余额字符串,丢弃响应 token 与其他字段。余额和赠金金额字符串只要符合 Platform Web 客户端交给 big.js 的数字文法即可通过,该文法和 big.js 一致,允许省略整数或小数部分以及十进制指数,因此 0E-16、5.0000000000000000 这类值仍然有效;原始字符串会保留,NaN、Infinity 和非法文本仍被拒绝。赠送钱包不计入充值余额。凭证变化和销毁会使进行中的查询失效。 diff --git a/packages/account/deepseek-account/src/index.ts b/packages/account/deepseek-account/src/index.ts index cee5f107e4..4a490edf23 100644 --- a/packages/account/deepseek-account/src/index.ts +++ b/packages/account/deepseek-account/src/index.ts @@ -22,7 +22,7 @@ export type * from './types.ts' declare module '@deepseek-ai/cordis' { interface Context { deepseekAccount: DeepSeekAccount } interface Events { - /** Local grant removal has completed. + /** Local grant removal has completed. After the listeners return, the `revoked` signal of that grant's request credentials aborts. * @mode emit */ 'deepseek-account/signed-out'(): void @@ -128,6 +128,8 @@ export class DeepSeekAccount extends TypertRemoteService { */ private lastProfile: { readonly token: string; readonly profile: Extract } | undefined private detailsLifetime = new AbortController() + /** Aborted at the next sign-out; request credentials of the current sign-in carry its signal. */ + private signedOut = new AbortController() private closed = false private removing: Promise | undefined @@ -390,7 +392,7 @@ export class DeepSeekAccount extends TypertRemoteService { await this.ctx.credentials.deleteRecord(KEY) this.ctx.emit('deepseek-account/session-expired') this.attempt = undefined - this.ctx.emit('deepseek-account/signed-out') + this.publishSignedOut() this.changed('snapshot') return this.getState() })().finally(() => { this.removing = undefined }) @@ -471,11 +473,14 @@ export class DeepSeekAccount extends TypertRemoteService { /** * Release the account credential for one request to `url` as the request * carries it, together with its invalidation, which runs on the account - * service mounted when it is called. Host-only. + * service mounted when it is called, and the signal this service aborts + * when it signs out of that credential. Host-only. * @param url - actual request destination or API base URL. * @returns the request credential, or undefined for other origins or a signed-out account. */ async resolveRequestCredential(url: string): Promise { + // Captured before the token is read, so a sign-out that completes during the read aborts this credential's signal. + const revoked = this.signedOut.signal const token = await this.resolveToken(url) if (token === undefined) return undefined // The destination answers after a reload may have replaced this instance, so the rejection runs on the account @@ -484,6 +489,7 @@ export class DeepSeekAccount extends TypertRemoteService { return { headers: { [ACCOUNT_TOKEN_HEADER]: token }, value: token, + revoked, reject: async () => { try { await ctx.get('deepseekAccount')?.rejectToken(token) } catch (_credentialRemovalFailed) { /* The destination's rejection is the failure to report; the next rejection retries. */ } @@ -585,7 +591,7 @@ export class DeepSeekAccount extends TypertRemoteService { this.revoke(parsed.data.token, platformClientHeaders(this.platform, client)) } this.attempt = undefined - this.ctx.emit('deepseek-account/signed-out') + this.publishSignedOut() this.changed('snapshot') return this.getState() })().finally(() => { this.removing = undefined }) @@ -699,6 +705,17 @@ export class DeepSeekAccount extends TypertRemoteService { this.revocations.add(revocation) } + /** + * Announce a completed sign-out. Listeners run first, so a turn they cancel records that cause before the requests + * still carrying the signed-out token end. A listener that throws does not keep those requests open. + */ + private publishSignedOut(): void { + const signedOut = this.signedOut + this.signedOut = new AbortController() + try { this.ctx.emit('deepseek-account/signed-out') } + finally { signedOut.abort() } + } + private invalidateDetails(): void { this.lastProfile = undefined this.detailsLifetime.abort() diff --git a/packages/account/deepseek-account/src/types.ts b/packages/account/deepseek-account/src/types.ts index e49c4455ce..eac08b8a4a 100644 --- a/packages/account/deepseek-account/src/types.ts +++ b/packages/account/deepseek-account/src/types.ts @@ -130,6 +130,12 @@ export interface AccountRequestCredential { * @returns settlement after the removal attempt. */ reject(): Promise + /** + * Aborts when the account signs out of the sign-in this token belongs to, by the user or after a rejection, once + * `deepseek-account/signed-out` listeners have run. A consumer ends the request that carries the token. It stays + * unaborted when the account service that released it has been unloaded, because no sign-out reaches it then. + */ + readonly revoked: AbortSignal } /** Host-only credentials for an embedded Platform document; never expose through account RPC. */ diff --git a/packages/account/deepseek-account/tests/account-stub.ts b/packages/account/deepseek-account/tests/account-stub.ts index a04352bbac..3f0459dcc8 100644 --- a/packages/account/deepseek-account/tests/account-stub.ts +++ b/packages/account/deepseek-account/tests/account-stub.ts @@ -8,15 +8,18 @@ export interface AccountStubOptions { readonly token: (url: string) => string | undefined | Promise /** Observes each rejected token; a throw is contained, as the service contains storage failures. */ readonly reject?: (token: string) => void | Promise + /** The sign-out signal released credentials carry; without one they carry a signal that never aborts. */ + readonly signedOut?: AbortSignal } /** - * An account service releasing request credentials as the real one does: the token header, the bare token, and an - * invalidation that reports no failure. - * @param options - token policy and rejection observer. + * An account service releasing request credentials as the real one does: the token header, the bare token, the + * sign-out signal, and an invalidation that reports no failure. + * @param options - token policy, rejection observer, and sign-out signal. * @returns the stand-in, typed as the service for `ctx.provide`. */ export function accountStub(options: AccountStubOptions): DeepSeekAccount { + const signedOut = options.signedOut ?? new AbortController().signal const stub: Pick = { async resolveRequestCredential(url) { const token = await options.token(url) @@ -24,6 +27,7 @@ export function accountStub(options: AccountStubOptions): DeepSeekAccount { return { headers: { [ACCOUNT_TOKEN_HEADER]: token }, value: token, + revoked: signedOut, reject: async () => { try { await options.reject?.(token) } catch (_storageFailure) { /* The destination's rejection is the failure to report, as in the service. */ } diff --git a/packages/account/deepseek-account/tests/account.spec.ts b/packages/account/deepseek-account/tests/account.spec.ts index 33d4bfd029..ceabf9491c 100644 --- a/packages/account/deepseek-account/tests/account.spec.ts +++ b/packages/account/deepseek-account/tests/account.spec.ts @@ -503,6 +503,67 @@ it('publishes sign-out only after local grant removal and refuses token resoluti expect((await f.account.getState()).status).toBe('signed-out') }) +it.each(['user sign-out', 'rejected token'] as const)('withdraws released request credentials at a %s, after its listeners ran', async (cause) => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + const observed: boolean[] = [] + f.ctx.on('deepseek-account/signed-out', () => { observed.push(credential.revoked.aborted) }) + expect(credential.revoked.aborted).toBe(false) + if (cause === 'user sign-out') await f.account.signOut(clientMetadata()) + else await (await storedCredential(f)).reject() + expect(observed).toEqual([false]) + expect(credential.revoked.aborted).toBe(true) + // The next sign-in releases its credentials on a signal of its own. + await storeAccount(f) + const next = await storedCredential(f) + expect(next.revoked).not.toBe(credential.revoked) + expect(next.revoked.aborted).toBe(false) +}) + +it('withdraws released request credentials when a sign-out listener throws', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + f.ctx.on('deepseek-account/signed-out', () => { throw new Error('listener failed') }) + await expect(f.account.signOut(clientMetadata())).rejects.toThrow('listener failed') + expect(credential.revoked.aborted).toBe(true) +}) + +it('releases a withdrawn credential when sign-out completes while its token is being read', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const original = f.ctx.credentials.readRecord.bind(f.ctx.credentials) + const reading = Promise.withResolvers() + const release = Promise.withResolvers() + const read = vi.spyOn(f.ctx.credentials, 'readRecord').mockImplementationOnce(async (requested) => { + const record = await original(requested) + reading.resolve(undefined) + await release.promise + return record + }) + try { + const pending = f.account.resolveRequestCredential(`${PRIVATE_INFERENCE}/v1/messages`) + await reading.promise + await f.account.signOut(clientMetadata()) + release.resolve(undefined) + // The token was read before the sign-out removed it, so the credential must not authenticate a request. + expect(await pending).toMatchObject({ value: 'test-platform-grant', revoked: { aborted: true } }) + } finally { read.mockRestore() } +}) + +it('keeps released request credentials when the account service is replaced', async () => { + const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE) + await storeAccount(f) + const credential = await storedCredential(f) + const replacement = await f.remount() + expect(credential.revoked.aborted).toBe(false) + // The replacement withdraws only the credentials it released itself. + const current = await replacement.resolveRequestCredential(`${PRIVATE_INFERENCE}/v1/messages`) + await replacement.signOut(clientMetadata()) + expect({ replaced: credential.revoked.aborted, current: current?.revoked.aborted }).toEqual({ replaced: false, current: true }) +}) + it('discards account details when sign-out races the Platform response', async () => { const f = await fixture() await storeAccount(f) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 00404c88c6..c8f1716276 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1051,7 +1051,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'async resolveRequestCredential(url: string): Promise', - description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation, which runs on the account service mounted when it is called. Host-only.', + description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation, which runs on the account service mounted when it is called, and the signal this service aborts when it signs out of that credential. Host-only.', parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], returns: 'the request credential, or undefined for other origins or a signed-out account.', }, @@ -5321,7 +5321,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ mode: 'emit', signature: '\'deepseek-account/signed-out\'(): void', summary: 'Local grant removal has completed.', - description: 'Local grant removal has completed.', + description: 'Local grant removal has completed. After the listeners return, the `revoked` signal of that grant\'s request credentials aborts.', parameters: [], }, { @@ -5846,7 +5846,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'AccountRequestCredential', - declaration: 'export interface AccountRequestCredential {\n readonly headers: Readonly>;\n readonly value: string;\n reject(): Promise;\n}', + declaration: 'export interface AccountRequestCredential {\n readonly headers: Readonly>;\n readonly value: string;\n reject(): Promise;\n readonly revoked: AbortSignal;\n}', }, { name: 'AccountUpdate', @@ -8710,7 +8710,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'RouteCredentialGrant', - declaration: 'export interface RouteCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n}', + declaration: 'export interface RouteCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}', }, { name: 'RpcId', diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index 580d4e4d87..0b1592817f 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -15,11 +15,11 @@ en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-account/use-this-package: - en: 3d952599a9b0bf85 - zh: 231c0331a7d217e3 + en: a6a05e40662f10ed + zh: eb19e4706ab10515 /deepseek-ai-dsh-llm-deepseek-account/understand-the-implementation: - en: 37319d3b3317b0cf - zh: 90362d4dff489e35 + en: d8253a04dce699e1 + zh: 264f36b1b96d0241 /deepseek-ai-dsh-llm-deepseek-account/further-exploration: en: 30a69b9c66d89580 zh: fcc026a6373c1bee @@ -39,8 +39,8 @@ en: 2ecaa7bbbdd638e9 zh: bb067520885d877b /deepseek-ai-dsh-llm-deepseek-account/known-limitations-and-deferred-work: - en: ee8b7ff23c806e18 - zh: bd26832c8d455012 + en: abf049d0c4c84f80 + zh: add1d6f237ca83ef /deepseek-ai-dsh-llm-deepseek-account/known-limitations-and-deferred-work/dev-note: en: 0525041e573e96b6 zh: b05ed8d852498e6b diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index 17322210bb..b534844f32 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -56,14 +56,14 @@ An offered model shows the badge its listing entry declares under `client_metada | `modelsMaxAgeMs` | `600,000` | Automatic refresh interval after first use, also used after failure; `0` refreshes on access only | | `modelOverrides` | `{}` | Field overrides by model id | -An account request HTTP 401 maps to `ACCOUNT_TOKEN_INVALID` independently of the response body. The account service removes the credential only if it still matches the request token. HTTP 403 and other failures do not clear the login. After `deepseek-account/signed-out`, this plugin cancels running Agents whose latest bound request used this route, keeping their inboxes; it publishes `deepseek-account/model-sign-in-required` for a request that fails with `ACCOUNT_SIGN_IN_REQUIRED`, and registers a running-task report with the account service so its sign-out confirmation knows about that work. +An account request HTTP 401 maps to `ACCOUNT_TOKEN_INVALID` independently of the response body. The account service removes the credential only if it still matches the request token. HTTP 403 and other failures do not clear the login. After `deepseek-account/signed-out`, this plugin cancels running Agents whose latest bound request used this route, keeping their inboxes; it publishes `deepseek-account/model-sign-in-required` for a request that fails with `ACCOUNT_SIGN_IN_REQUIRED`, and registers a running-task report with the account service so its sign-out confirmation knows about that work. A model request or file operation in flight when the account signs out ends with its credential's `revoked` signal and fails with `ACCOUNT_SIGN_IN_REQUIRED`; a listing request keeps its `modelsTimeoutMs` deadline. That request's failure callback cancels the same Agents, so a request that outlives this plugin, after the route was disabled mid-turn, still ends its turn with the signed-out cause. The settings namespace is the Cordis entry id, or the plugin name without an entry. Product profiles retain the official entry id `llm-deepseek` and use `llm-deepseek-account` for the account route. ## Understand the implementation -Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the credential headers. +Account credential lookup and invalidation go through the account service's `resolveRequestCredential`; this plugin retains HTTP error classification and owns the sign-out policy over running Agents in [`account-tasks.ts`](src/account-tasks.ts). Registrations and listeners dispose with the plugin, and disposal aborts an in-flight listing request; a model request in flight keeps its credential and failure callback until it ends, so both can run after disposal. Shared Host wiring supplies attachments, request extensions, anonymous identity, and atomic retry-policy updates; this plugin registers only its own route and uses the transport's `connect` and `admit` hooks for the catalog and the gate. The listing request, its cache, and catalog resolution come from the shared transport, which the API-key route also uses; the cache lives in memory and is keyed by endpoint and a SHA-256 of the credential headers. A failed request the shared transport classifies as `QUOTA` is rewritten to `ACCOUNT_QUOTA` before it leaves this provider, covering an HTTP 402 response and an in-band SSE error alike. The shared transport and the `deepseek-official` route keep `QUOTA`, so the account route's top-up action never appears for an API-key or third-party failure. @@ -99,6 +99,7 @@ Credentials and catalog availability do not enter model input; the protocol tran - The listing's effort levels are ignored. - When the current version can serve no listed model, the account offers no models, and model selectors show their generic empty state rather than an upgrade prompt. - An override can set but not remove `systemPromptUpdate` and `toolUpdate` declarations. +- While this plugin is disabled, a task it started that still runs is not reported to the account's sign-out confirmation, and a sign-out ends it only through a model request in flight. A task that is executing a tool at that moment runs until its next model request, which fails because the route is no longer registered. ### Dev Note diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index 26d6694096..c0614c8907 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -56,14 +56,14 @@ kind: "package-reference" | `modelsMaxAgeMs` | `600,000` | 首次使用后的自动刷新间隔,失败后也按此间隔重试;`0` 表示只在访问时刷新 | | `modelOverrides` | `{}` | 按模型 id 的字段覆盖 | -账号请求的 HTTP 401 与响应正文无关:映射为 `ACCOUNT_TOKEN_INVALID`,并要求账号服务仅在当前 token 仍与请求所用 token 相同时清除凭据。403 和其他错误不会触发清除。`deepseek-account/signed-out` 之后,本插件取消最近一次绑定请求使用本路由的运行中 Agent 并保留其收件箱;请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败时发布 `deepseek-account/model-sign-in-required`,并向账号服务注册运行中任务报告,供其退登确认了解这些工作。 +账号请求的 HTTP 401 与响应正文无关:映射为 `ACCOUNT_TOKEN_INVALID`,并要求账号服务仅在当前 token 仍与请求所用 token 相同时清除凭据。403 和其他错误不会触发清除。`deepseek-account/signed-out` 之后,本插件取消最近一次绑定请求使用本路由的运行中 Agent 并保留其收件箱;请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败时发布 `deepseek-account/model-sign-in-required`,并向账号服务注册运行中任务报告,供其退登确认了解这些工作。账号退登时仍在途的模型请求或文件操作随其凭据的 `revoked` 信号结束,并以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;列表请求仍只受 `modelsTimeoutMs` 期限约束。该请求的失败回调会取消同一批 Agent,因此比本插件存活更久的请求(路由在回合进行中被停用)仍会以退登原因结束其回合。 设置命名空间采用 Cordis entry id,没有 entry 时采用插件名。产品保留 official 的 `llm-deepseek` entry id,账号使用 `llm-deepseek-account`。 ## 理解实现 -账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和凭据请求头的 SHA-256 为键。 +账号凭据的读取与作废经由账号服务的 `resolveRequestCredential`;本插件保留 HTTP 错误分类,并在 [`account-tasks.ts`](src/account-tasks.ts) 中拥有针对运行中 Agent 的退登策略。注册和监听随插件生命周期释放,释放时会中止进行中的列表请求;在途的模型请求会把它的凭据和失败回调保留到请求结束,因此二者可能在释放之后执行。共享 Host 绑定提供附件访问、请求扩展、匿名标识和重试策略的原子更新;本包只注册自己的路由,并通过传输层的 `connect` 与 `admit` 钩子接入目录和门控。列表请求、缓存和目录解析来自共享传输包,API key 路由也使用它们;缓存只在内存中,以端点和凭据请求头的 SHA-256 为键。 共享传输判定为 `QUOTA` 的失败请求离开本提供方前会被改写为 `ACCOUNT_QUOTA`,HTTP 402 响应与流内 SSE 错误都适用。共享传输与 `deepseek-official` 路由保留 `QUOTA`,因此账号路由的充值操作不会出现在 API Key 或第三方失败上。 @@ -99,6 +99,7 @@ kind: "package-reference" - 列表中的推理档位被忽略。 - 当前版本能用的已列出模型一个都没有时,账号不提供任何模型,模型选择器显示通用的空状态,而不是升级提示。 - 覆盖可以设置、但不能移除 `systemPromptUpdate` 与 `toolUpdate` 声明。 +- 本插件被停用期间,它此前启动且仍在运行的任务不会报告给账号的退登确认,退登也只能通过在途的模型请求结束该任务。此时正在执行工具的任务会运行到它的下一次模型请求,该请求因路由已不再注册而失败。 ### 开发备注 diff --git a/packages/llm/llm-deepseek-account/src/account-tasks.ts b/packages/llm/llm-deepseek-account/src/account-tasks.ts index 00843ce2be..e77b5d8617 100644 --- a/packages/llm/llm-deepseek-account/src/account-tasks.ts +++ b/packages/llm/llm-deepseek-account/src/account-tasks.ts @@ -9,11 +9,26 @@ function isRunningAccountTask(agent: Pick, provider return agent.status === 'running' && agent.session.requestContext()?.provider === provider } +/** + * End the running Agents whose latest request used the account route `provider`, keeping their inboxes. + * @param ctx - context whose optional Agent registry is read when this runs; without one nothing is cancelled. + * @param provider - the account route id. + */ +export function cancelAccountTasks(ctx: Context, provider: string): void { + for (const agent of ctx.get('agents')?.list() ?? []) { + if (isRunningAccountTask(agent, provider)) { + agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }) + } + } +} + /** * Cancel signed-out account tasks, publish sign-in guidance for rejected * requests, and report running account work to the account service's * sign-out confirmation. Each listener attaches once the service it needs is - * mounted and detaches with this plugin. + * mounted and detaches with this plugin; a request that outlives the plugin + * ends its tasks through {@link cancelAccountTasks} when its credential is + * signed out. * @param ctx - account route plugin lifetime; Agents and the account service may attach later. * @param provider - the account route id this plugin registers. */ @@ -24,13 +39,7 @@ export function installAccountTaskCancellation(ctx: Context, provider: string): scope.emit('deepseek-account/model-sign-in-required') } }) - scope.on('deepseek-account/signed-out', () => { - for (const agent of scope.agents.list()) { - if (isRunningAccountTask(agent, provider)) { - agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }) - } - } - }) + scope.on('deepseek-account/signed-out', () => { cancelAccountTasks(scope, provider) }) scope.inject(['deepseekAccount'], (reporting) => { reporting.effect(() => reporting.deepseekAccount.registerRunningTaskReport( () => reporting.agents.list().some(agent => isRunningAccountTask(agent, provider)), diff --git a/packages/llm/llm-deepseek-account/src/index.ts b/packages/llm/llm-deepseek-account/src/index.ts index e4d77e1e6e..d9ea06b2db 100644 --- a/packages/llm/llm-deepseek-account/src/index.ts +++ b/packages/llm/llm-deepseek-account/src/index.ts @@ -8,7 +8,7 @@ import { catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveAdapterOptions, resolveListedCatalog, } from '@deepseek-ai/dsh-llm-deepseek' import type { DeepSeekRequestAuth, ListedCatalog, ListingView, ModelListing, ResolvedDeepSeekOptions } from '@deepseek-ai/dsh-llm-deepseek' -import { installAccountTaskCancellation } from './account-tasks.ts' +import { cancelAccountTasks, installAccountTaskCancellation } from './account-tasks.ts' import { Config, plainAccountOptions, resolveAccountOptions } from './config.ts' export { Config } from './config.ts' @@ -32,20 +32,34 @@ export function apply(ctx: Context, config: Config): void { /** The account credential released for one destination; absent without an allowed signed-in account or without the account service. */ const requestCredential = async (endpoint: string): Promise => await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) + /** The failure of a request whose account signed out before it finished: the code a request made after the sign-out fails with. */ + const signedOutMidRequest = (cause: unknown) => new LlmError( + 'The DeepSeek account signed out before this request finished. Sign in to DeepSeek to use the account provider.', + 'ACCOUNT_SIGN_IN_REQUIRED', + { cause }, + ) const resolveAuth = async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { const credential = await requestCredential(endpoint) if (credential === undefined) return undefined return { ...credential, onRequestError: async (error) => { - if (!(error instanceof LlmError)) return error - if (error.code === QUOTA_EXCEEDED_CODE) { - return new LlmError(error.message, ACCOUNT_QUOTA_EXCEEDED_CODE, { ...error.failure, cause: error }) + try { + // A sign-out ends the requests that carry its token, so it is the failure of any request that fails after it. + if (credential.revoked.aborted) return signedOutMidRequest(error) + if (!(error instanceof LlmError)) return error + if (error.code === QUOTA_EXCEEDED_CODE) { + return new LlmError(error.message, ACCOUNT_QUOTA_EXCEEDED_CODE, { ...error.failure, cause: error }) + } + if (error.failure.status !== 401) return error + const rejected = new LlmError(error.message, 'ACCOUNT_TOKEN_INVALID', { ...error.failure, cause: error }) + await credential.reject() + return rejected + } finally { + // A request can outlive this plugin and the sign-out listener it mounts. Once the credential it carried is + // signed out, by the user or by the rejection above, the request ends this route's tasks itself. + if (credential.revoked.aborted) cancelAccountTasks(ctx, PROVIDER) } - if (error.failure.status !== 401) return error - const rejected = new LlmError(error.message, 'ACCOUNT_TOKEN_INVALID', { ...error.failure, cause: error }) - await credential.reject() - return rejected }, } } diff --git a/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts b/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts new file mode 100644 index 0000000000..07f773d8dd --- /dev/null +++ b/packages/llm/llm-deepseek-account/tests/account-signout.spec.ts @@ -0,0 +1,148 @@ +/** A request the account route authenticated ends with the sign-out of its credential and ends the route's running tasks. */ +import { Context } from '@deepseek-ai/cordis' +import { BlockAssembler, LlmRuntime } from '@deepseek-ai/dsh-llm' +import { afterEach, expect, it, vi } from 'vitest' +import { accountStub } from '../../../account/deepseek-account/tests/account-stub.ts' +import * as Account from '../src/index.ts' + +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + vi.restoreAllMocks() +}) + +const SIGNED_OUT_CANCEL = [{ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true }] +const SIGNED_OUT_FAILURE = { + code: 'ACCOUNT_SIGN_IN_REQUIRED', + message: 'The DeepSeek account signed out before this request finished. Sign in to DeepSeek to use the account provider.', +} + +/** + * Mount the runtime, an account whose sign-out the test drives, a registry holding one running account task and one + * running API-key task, and the account route. + * @param options.reject - observes a rejected token, as the account service does before it signs out. + * @param options.agents - false mounts no Agent registry, as a composition without Agents does. + */ +async function route(options: { reject?: (token: string) => void; agents?: boolean } = {}) { + const { reject } = options + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + const signedOut = new AbortController() + const cancelAccountTask = vi.fn() + const cancelApiKeyTask = vi.fn() + if (options.agents !== false) { + ctx.provide('agents', { list: () => [ + { status: 'running', session: { requestContext: () => ({ provider: 'deepseek-account' }) }, cancel: cancelAccountTask }, + { status: 'running', session: { requestContext: () => ({ provider: 'deepseek-official' }) }, cancel: cancelApiKeyTask }, + ] } as never) + } + // The route registers its running-task report once Agents and the account service are both mounted. + ctx.provide('deepseekAccount', Object.assign( + accountStub({ token: () => 'account-token', signedOut: signedOut.signal, ...reject === undefined ? {} : { reject } }), + { registerRunningTaskReport: () => () => {} }, + )) + const plugin = ctx.plugin(Account) + await plugin + return { ctx, signedOut, cancelAccountTask, cancelApiKeyTask, plugin } +} + +/** Answer the Messages request through `messages`; the model listing fails fast, so the route serves its bundled catalog. */ +function upstream(messages: (signal: AbortSignal) => Promise) { + vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { + const url = new URL(input instanceof Request ? input.url : input) + return url.pathname === '/models' ? Promise.resolve(new Response(null, { status: 404 })) : messages(init!.signal!) + }) +} + +/** Hold the Messages request open until its signal aborts, as an open provider response does. */ +function heldUpstream() { + const sent = Promise.withResolvers() + upstream((signal) => { + sent.resolve(signal) + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + }) + return sent.promise +} + +/** Drive one streamed request through the runtime and return its terminal outcome. */ +async function finishOf(ctx: Context) { + const assembler = new BlockAssembler() + for await (const chunk of ctx.llm.stream({ provider: 'deepseek-account', model: 'deepseek-flash', messages: [] })) assembler.push(chunk) + return assembler.finish +} + +it.each([ + { route: 'mounted', unload: false }, + { route: 'unloaded', unload: true }, +])('ends an open request and the running account tasks when its credential is signed out while the route is $route', async ({ unload }) => { + const { ctx, signedOut, cancelAccountTask, cancelApiKeyTask, plugin } = await route() + const sent = heldUpstream() + const finish = finishOf(ctx) + const request = await sent + if (unload) await plugin.dispose() + expect(request.aborted).toBe(false) + // The account service runs the sign-out listeners first; an unloaded route has none left. + ctx.emit('deepseek-account/signed-out') + expect(cancelAccountTask.mock.calls).toEqual(unload ? [] : [SIGNED_OUT_CANCEL]) + signedOut.abort() + expect(request.aborted).toBe(true) + await expect(finish).resolves.toMatchObject({ kind: 'error', failure: SIGNED_OUT_FAILURE }) + // The request that carried the signed-out token ends the tasks itself; a task cancelled twice keeps its first cause. + expect(cancelAccountTask.mock.calls).toEqual(unload ? [SIGNED_OUT_CANCEL] : [SIGNED_OUT_CANCEL, SIGNED_OUT_CANCEL]) + expect(cancelApiKeyTask).not.toHaveBeenCalled() +}) + +it('ends an open request at sign-out in a composition without Agents, which has no task to end', async () => { + const { ctx, signedOut } = await route({ agents: false }) + const sent = heldUpstream() + const finish = finishOf(ctx) + const request = await sent + signedOut.abort() + await expect(finish).resolves.toMatchObject({ kind: 'error', failure: SIGNED_OUT_FAILURE }) + expect(request.aborted).toBe(true) +}) + +it('does not send a request whose credential was signed out before dispatch', async () => { + const { ctx, signedOut, cancelAccountTask } = await route() + const messages = vi.fn(() => Promise.resolve(new Response(null, { status: 500 }))) + upstream(messages) + signedOut.abort() + await expect(finishOf(ctx)).resolves.toMatchObject({ kind: 'error', failure: SIGNED_OUT_FAILURE }) + expect(messages).not.toHaveBeenCalled() + expect(cancelAccountTask.mock.calls).toEqual([SIGNED_OUT_CANCEL]) +}) + +it('reports a provider failure that arrives after the sign-out as the sign-out, without rejecting the token', async () => { + const rejectToken = vi.fn() + const { ctx, signedOut, cancelAccountTask } = await route({ reject: rejectToken }) + upstream(() => { + signedOut.abort() + return Promise.resolve(new Response('Unauthorized', { status: 401 })) + }) + await expect(finishOf(ctx)).resolves.toMatchObject({ kind: 'error', failure: SIGNED_OUT_FAILURE }) + expect(rejectToken).not.toHaveBeenCalled() + expect(cancelAccountTask.mock.calls).toEqual([SIGNED_OUT_CANCEL]) +}) + +it('ends the running account tasks when the rejection of its token signs the account out', async () => { + const signOut: Array<() => void> = [] + const { ctx, signedOut, cancelAccountTask, cancelApiKeyTask } = await route({ reject: () => { for (const run of signOut) run() } }) + signOut.push(() => { signedOut.abort() }) + upstream(() => Promise.resolve(new Response('Unauthorized', { status: 401 }))) + await expect(finishOf(ctx)).resolves.toMatchObject({ kind: 'error', failure: { code: 'ACCOUNT_TOKEN_INVALID' } }) + expect(cancelAccountTask.mock.calls).toEqual([SIGNED_OUT_CANCEL]) + expect(cancelApiKeyTask).not.toHaveBeenCalled() +}) + +it.each([ + { failure: 'a provider error', status: 500, code: 'SERVER' }, + { failure: 'a rejected token whose removal did not sign out', status: 401, code: 'ACCOUNT_TOKEN_INVALID' }, +])('leaves running tasks alone after $failure while the account stays signed in', async ({ status, code }) => { + const { ctx, cancelAccountTask } = await route() + upstream(() => Promise.resolve(new Response('failed', { status }))) + await expect(finishOf(ctx)).resolves.toMatchObject({ kind: 'error', failure: { code } }) + expect(cancelAccountTask).not.toHaveBeenCalled() +}) diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index f1bae2778c..b88b876c62 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,14 +9,14 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: ea0a35b73d3b8f2c - zh: 7e404ed4617c2789 + en: 735e39ebfef73dcb + zh: 42036db3ae53de0f /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 /deepseek-ai-dsh-llm-deepseek-api-key/use-this-package: - en: 78c395041b12b9cc - zh: 289f789926a0fe43 + en: f342f3bba7246464 + zh: 8073e5bf0c760fc6 /deepseek-ai-dsh-llm-deepseek-api-key/understand-the-implementation: en: 2fe0f32c15603cd9 zh: 984ce05b82e8e679 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index d387b0b36b..a4cb98c257 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL: for another origin, or a URL that embeds credentials, `configured()` answers false and `resolve()` releases nothing, and neither reads the credential store. +Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL. ## Table of Contents @@ -35,7 +35,7 @@ Authentication resolution returns the validated API key in `x-api-key` for Messa apiKeyEnv: DEEPSEEK_API_KEY ``` -The endpoint and credential reference come from one configuration resolution. In-flight requests retain that snapshot; subsequent updates affect subsequent calls. Account login state cannot change this route’s credential. +The endpoint and credential reference come from one configuration resolution. In-flight requests retain that snapshot; subsequent updates affect subsequent calls. Account login state cannot change this route’s credential. For a destination at another origin, or a URL that embeds credentials, the published credential's `configured()` answers false and its `resolve()` releases nothing, and neither reads the credential store. `models` is an independently configurable catalog for this provider; defaults and protocol capabilities come from the shared transport. While `models` equals the built-in catalog and the Messages origin is the official API, `https://api.deepseek.com`, the route serves the official `GET https://api.deepseek.com/models` listing instead. Listing requests carry the API key in `x-api-key` and the harness `User-Agent`, and reject redirects; without an API key the route requests nothing. Any other endpoint, including one named by `baseURL` or `$DEEPSEEK_BASE_URL`, serves `models` and requests no listing. Discovery does not probe inference endpoints. diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index b0f724fe8a..f47bbed9cc 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥:对其他 origin 或内嵌凭据的 URL,`configured()` 回答 false,`resolve()` 不释放任何内容,二者都不读取凭据存储。 +鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥。 ## 目录 @@ -35,7 +35,7 @@ kind: "package-reference" apiKeyEnv: DEEPSEEK_API_KEY ``` -端点和凭据引用来自同一次配置解析;进行中的请求保留该快照,后续配置更新仅影响后续请求。账号登录态不影响该路由使用的凭据。 +端点和凭据引用来自同一次配置解析;进行中的请求保留该快照,后续配置更新仅影响后续请求。账号登录态不影响该路由使用的凭据。对其他 origin 的目的地或内嵌凭据的 URL,发布的凭据的 `configured()` 回答 false,`resolve()` 不释放任何内容,二者都不读取凭据存储。 `models` 是该 provider 独立的可配置目录;默认值和协议能力来自共享传输包。当 `models` 等于内置目录、且 Messages 的 origin 是官方 API `https://api.deepseek.com` 时,路由改为提供官方 `GET https://api.deepseek.com/models` 列表。列表请求用 `x-api-key` 携带 API key,带上 harness 的 `User-Agent`,并拒绝重定向;没有 API key 时不发任何请求。其他端点,包括由 `baseURL` 或 `$DEEPSEEK_BASE_URL` 指定的端点,提供 `models`,不请求列表。目录判断不探测推理端点。 diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 47f19261a6..d5e9b834e9 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: - en: 98b9a8d297095e32 - zh: b8f8eb46038214cb + en: bcb58fd33f59dbf2 + zh: ceafdef88eb66b30 /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: 81bf213499f015ba zh: e9107ef322213e56 @@ -39,8 +39,8 @@ en: f13f24b504dcfb50 zh: 69b0ed9e2adf3394 /deepseek-ai-dsh-llm-deepseek/use-this-package/failures-and-recovery: - en: 63b17e204a764a7d - zh: dafcd75c80796d35 + en: 7c78ea559cef349b + zh: 242d690e3e461337 /deepseek-ai-dsh-llm-deepseek/understand-the-implementation: en: 1598ac8a8bb9b6bf zh: fdd089c5ae7722cd @@ -87,5 +87,5 @@ en: 05fe57d81d8d8202 zh: 61e85a6f610842dd /deepseek-ai-dsh-llm-deepseek/known-limitations-and-deferred-work/dev-note: - en: 267aab8281b59242 - zh: 491b454fe920a17e + en: ddc6cf85ac5d9520 + zh: f5dd039bb67ef8db diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 04404624b7..8ae1b83fec 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -91,7 +91,7 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account route owns HTTP 401 classification and the account service the credential invalidation; the transport passes failures to the credential's callback. -Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, and an optional failure callback, or `undefined` when none is configured. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.routeCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. +Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.routeCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. ### Streaming with thinking and images @@ -119,7 +119,7 @@ Configuration accepts Messages only and has no `protocol` field. If resolution r Successful Files responses must contain valid JSON. JSON decoding failures from upload, list, retrieve, and delete throw `INVALID_RESPONSE` with the operation and HTTP status in the message, the status in `LlmError.failure`, and the original parser error as `cause`. Body-read transport and cancellation errors retain their identity. -Non-2xx responses fail with stable codes: `AUTH` (401/403), `QUOTA`, `RATE_LIMIT`, `CONTEXT_WINDOW_EXCEEDED`, `INVALID_REQUEST`, `SERVER`, and `HTTP_` otherwise; pre-response transport failures throw `TRANSPORT`, caller aborts throw `ABORTED`, and stream-idle expiry throws `TIMEOUT`. A request-extension field collision, or a rejected preparation from a directly supplied `prepareExtensions`, fails with `REQUEST_EXTENSION` and appends the cause chain to the message; a post-2xx acceptance failure is logged and the response still streams. A normalized-image rejection names every plausible attachment and its durable position when the provider does not identify a file id. Stale-file rejection removes every named mapping (or every mapping used by the attempt) in one upload-index update and permits one replacement model request. Protocol violations throw `STREAM_CLOSED` or `MALFORMED_RESPONSE`, and a terminal `stop` with no content blocks becomes `EMPTY_RESPONSE`, which the default retry policy retries. A request on the official route without an API key fails with `MISSING_CREDENTIAL`, and a malformed credential fails with `INVALID_CREDENTIAL` naming the reference to fix — never any part of the key. +Non-2xx responses fail with stable codes: `AUTH` (401/403), `QUOTA`, `RATE_LIMIT`, `CONTEXT_WINDOW_EXCEEDED`, `INVALID_REQUEST`, `SERVER`, and `HTTP_` otherwise; pre-response transport failures throw `TRANSPORT`, caller aborts throw `ABORTED`, and stream-idle expiry throws `TIMEOUT`. A request ended by its credential's `revoked` signal fails as the provider's failure callback names it, and as `TRANSPORT` without one. A request-extension field collision, or a rejected preparation from a directly supplied `prepareExtensions`, fails with `REQUEST_EXTENSION` and appends the cause chain to the message; a post-2xx acceptance failure is logged and the response still streams. A normalized-image rejection names every plausible attachment and its durable position when the provider does not identify a file id. Stale-file rejection removes every named mapping (or every mapping used by the attempt) in one upload-index update and permits one replacement model request. Protocol violations throw `STREAM_CLOSED` or `MALFORMED_RESPONSE`, and a terminal `stop` with no content blocks becomes `EMPTY_RESPONSE`, which the default retry policy retries. A request on the official route without an API key fails with `MISSING_CREDENTIAL`, and a malformed credential fails with `INVALID_CREDENTIAL` naming the reference to fix — never any part of the key. Provider plugins own catalog availability. While its API key resolves, the API-key route serves its configured `models`, or the official model listing while `models` is the built-in catalog on the official endpoint; the account route serves its account listing while signed in (see the [API-key](../llm-deepseek-api-key/README.md) and [account](../llm-deepseek-account/README.md) providers). The transport supplies the bundled catalog, the catalog-entry field schemas, and capability resolution, plus the listing machinery both routes share: `requestModelListing`, the credential-scoped `ModelListingCache` (owned by `createModelListingCache` for automatic refresh, notifications, and plugin cleanup), and `resolveListedCatalog` with its client-version gate, listed badges, and `refuseListedModel`; `catalogModelInfo` attaches a listed badge to the advertised entry. Badge text rejects controls, Unicode line separators, bidi controls, and strings made only of whitespace or default-ignorable characters; joined emoji remain valid. A provider may also supply `connect(signal)`, which resolves the connection for exact-model lookups and prepared calls after provider-owned work such as a catalog load, and `admit(connection, model)`, which refuses a model before network I/O. @@ -218,4 +218,4 @@ These limits define where the adapter stops and future work begins. They are cur None. -`deepseek-official` uses only its configured API-key reference; `deepseek-account` uses only the stored DSH grant for the account provider’s allowed inference origin. Both routes share the Messages transport with independently configured model and file settings. Missing or ineligible account credentials reject the request with a sign-in prompt; neither route falls back to the other. Chat and Files requests reject redirects. The account service owns sign-out cancellation using running Agents’ logged request contexts, including tool execution; the transport receives the existing request abort signal. +`deepseek-official` uses only its configured API-key reference; `deepseek-account` uses only the stored DSH grant for the account provider’s allowed inference origin. Both routes share the Messages transport with independently configured model and file settings. Missing or ineligible account credentials reject the request with a sign-in prompt; neither route falls back to the other. Chat and Files requests reject redirects. The account route plugin owns sign-out cancellation using running Agents’ logged request contexts, including tool execution; the transport receives the existing request abort signal and ends a request whose credential is withdrawn. diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 142674331c..82209fba3f 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -91,7 +91,7 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值以及可选的失败回调;未配置时返回 `undefined`。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 +提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者收回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 ### 带 thinking 与图片的流式调用 @@ -119,7 +119,7 @@ Files 模式通过 `maxRequestFilesBytes` 与 `maxImagesPerRequest` 限制保留 成功的 Files 响应必须包含有效 JSON。上传、列举、获取和删除操作的 JSON 解码失败抛出 `INVALID_RESPONSE`,消息包含操作名称与 HTTP 状态,`LlmError.failure` 保留该状态,`cause` 保留原始解析错误。读取响应体时的传输和取消错误保留其原有身份。 -非 2xx 响应以稳定 code 失败:`AUTH`(401/403)、`QUOTA`、`RATE_LIMIT`、`CONTEXT_WINDOW_EXCEEDED`、`INVALID_REQUEST`、`SERVER` 以及其他情况的 `HTTP_`;响应前传输失败抛出 `TRANSPORT`,调用方中止抛出 `ABORTED`,流空闲超时抛出 `TIMEOUT`。请求扩展字段冲突,或直接提供的 `prepareExtensions` 拒绝准备时,使用 `REQUEST_EXTENSION` 失败,并在消息中附上原因链;2xx 后接受失败只记录告警,响应仍会继续流式返回。当提供方未指出 file id 时,规范化图片拒绝会列出所有可能附件及其持久位置。陈旧文件拒绝会在一次上传索引更新中删除全部点名映射(或该次尝试使用的全部映射),并允许一次替换模型请求。协议违规抛出 `STREAM_CLOSED` 或 `MALFORMED_RESPONSE`;不带内容块的终止 `stop` 变成 `EMPTY_RESPONSE`,默认重试策略会重试它。官方路由缺少 API Key 的请求以 `MISSING_CREDENTIAL` 失败;格式错误的凭据以 `INVALID_CREDENTIAL` 失败,并点名需要修复的引用——绝不包含密钥的任何部分。 +非 2xx 响应以稳定 code 失败:`AUTH`(401/403)、`QUOTA`、`RATE_LIMIT`、`CONTEXT_WINDOW_EXCEEDED`、`INVALID_REQUEST`、`SERVER` 以及其他情况的 `HTTP_`;响应前传输失败抛出 `TRANSPORT`,调用方中止抛出 `ABORTED`,流空闲超时抛出 `TIMEOUT`。被凭据的 `revoked` 信号结束的请求按提供方失败回调命名的失败上报,没有回调时为 `TRANSPORT`。请求扩展字段冲突,或直接提供的 `prepareExtensions` 拒绝准备时,使用 `REQUEST_EXTENSION` 失败,并在消息中附上原因链;2xx 后接受失败只记录告警,响应仍会继续流式返回。当提供方未指出 file id 时,规范化图片拒绝会列出所有可能附件及其持久位置。陈旧文件拒绝会在一次上传索引更新中删除全部点名映射(或该次尝试使用的全部映射),并允许一次替换模型请求。协议违规抛出 `STREAM_CLOSED` 或 `MALFORMED_RESPONSE`;不带内容块的终止 `stop` 变成 `EMPTY_RESPONSE`,默认重试策略会重试它。官方路由缺少 API Key 的请求以 `MISSING_CREDENTIAL` 失败;格式错误的凭据以 `INVALID_CREDENTIAL` 失败,并点名需要修复的引用——绝不包含密钥的任何部分。 提供方插件负责目录可用性:API key 路由在能解析到 API key 时提供配置中的 `models`,在官方端点上且 `models` 为内置目录时改为提供官方模型列表;账号路由在登录时提供账号的模型列表(见 [API key](../llm-deepseek-api-key/README.zh.md) 与[账号](../llm-deepseek-account/README.zh.md)提供方)。传输层提供内置目录、目录条目字段的 schema 和能力解析,以及两条路由共用的列表机制:`requestModelListing`、按凭据区分的 `ModelListingCache`(由 `createModelListingCache` 持有,负责自动刷新、通知与插件清理),以及带客户端版本门控和列表角标的 `resolveListedCatalog` 与 `refuseListedModel`;`catalogModelInfo` 把列表角标附到公布的条目上。角标文字拒绝控制字符、Unicode 行分隔符、双向控制符及仅由空白或默认可忽略字符组成的字符串,组合 emoji 仍有效。提供方还可以提供 `connect(signal)`:在提供方自己的工作(例如加载目录)完成后,为精确模型查询和预备调用解析连接;以及 `admit(connection, model)`:在网络请求之前拒绝某个模型。 @@ -218,4 +218,4 @@ loop 保留的响应块会追加到下一个请求,并保留其更早的可复 无。 -`deepseek-official` 仅使用配置的 API Key 引用;`deepseek-account` 仅在账号提供方允许的推理来源使用已保存的 DSH 授权。两条路由共享 Messages 传输,模型与文件设置独立配置。账号凭证缺失或不适用于目标时拒绝请求并提示登录;两条路由均不回退到另一凭证。Chat 和 Files 请求拒绝重定向。账号提供方根据运行中 Agent 已记录的请求上下文负责退登取消,包括工具执行阶段;传输层接收现有请求的中止信号。 +`deepseek-official` 仅使用配置的 API Key 引用;`deepseek-account` 仅在账号提供方允许的推理来源使用已保存的 DSH 授权。两条路由共享 Messages 传输,模型与文件设置独立配置。账号凭证缺失或不适用于目标时拒绝请求并提示登录;两条路由均不回退到另一凭证。Chat 和 Files 请求拒绝重定向。账号路由插件根据运行中 Agent 已记录的请求上下文负责退登取消,包括工具执行阶段;传输层接收现有请求的中止信号,并结束凭据已被收回的请求。 diff --git a/packages/llm/llm-deepseek/package.json b/packages/llm/llm-deepseek/package.json index ca145eb85f..e86db5e922 100644 --- a/packages/llm/llm-deepseek/package.json +++ b/packages/llm/llm-deepseek/package.json @@ -59,6 +59,7 @@ "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-authorization": "workspace:*", "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 8529f69988..5500aaa91b 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -64,7 +64,11 @@ export class DeepSeekAdapter extends LlmAdapt if (auth === undefined) return undefined // The adapter's failure classification stays behind the seam. const reject = auth.reject?.bind(auth) - return { headers: auth.headers, value: auth.value, ...reject === undefined ? {} : { reject } } + return { + headers: auth.headers, value: auth.value, + ...reject === undefined ? {} : { reject }, + ...auth.revoked === undefined ? {} : { revoked: auth.revoked }, + } }, } } @@ -123,14 +127,16 @@ export class DeepSeekAdapter extends LlmAdapt ) const auth = await this.dependencies.resolveAuth(connection, connection.baseURL) if (auth === undefined) throw this.missingCredential(connection, options.provider) + // The request ends with its credential: a withdrawal closes the upstream response as the caller's cancellation does. + const live = auth.revoked === undefined ? signal : AbortSignal.any([signal, auth.revoked]) try { const files = new RequestFiles(this.files, { baseURL: connection.baseURL, headers: auth.headers, }, - connection.filePolicy, connection.filesApiTimeoutMs, signal, activity) + connection.filePolicy, connection.filesApiTimeoutMs, live, activity) let inline = false while (true) { - signal.throwIfAborted() + live.throwIfAborted() files.beginAttempt() let fileIds: Awaited> | undefined if (!inline) { @@ -147,7 +153,7 @@ export class DeepSeekAdapter extends LlmAdapt this.dependencies.onReplayDegrade?.({ provider: options.provider, model: options.model, reason }) }, fileIds) const requestIdentity: Omit = { - signal, + signal: live, ...options.sessionId === undefined ? {} : { sessionId: String(options.sessionId) }, ...options.purpose === undefined ? {} : { purpose: options.purpose }, } @@ -159,7 +165,7 @@ export class DeepSeekAdapter extends LlmAdapt this.dependencies.onExtensionsUnaccepted?.({ provider: options.provider, model: options.model, error }) }, ) - signal.throwIfAborted() + live.throwIfAborted() const betas = [ ...fileIds !== undefined && fileIds.size > 0 ? [MESSAGES_FILES_BETA] : [], ...body.messages.some(message => message.content.some(block => block.type === 'tool_addition' || block.type === 'tool_removal')) @@ -167,7 +173,7 @@ export class DeepSeekAdapter extends LlmAdapt : [], ] const response = await fetch(`${messagesApiRoot(connection.baseURL)}/messages`, { - method: 'POST', signal, body: extensions.payload, redirect: 'error', + method: 'POST', signal: live, body: extensions.payload, redirect: 'error', headers: { ...attributionHeaders(), 'content-type': 'application/json', 'accept': 'text/event-stream', diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index 60444fc85e..7b37ff1616 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -87,10 +87,14 @@ export interface DeepSeekConnectionOptions { /** * Authentication released for one request and its file operations: the route * credential grant the provider plugin builds, plus the request-failure - * classification bound to that credential. + * classification bound to that credential. The grant's `revoked` signal ends + * the request and its file operations as the caller's cancellation does. */ export interface DeepSeekRequestAuth extends RouteCredentialGrant { - /** Classify a failure using the captured credential; callback failure preserves the original error. */ + /** + * Classify a failure using the captured credential; callback failure preserves the original error. The end a + * withdrawn credential causes arrives here too, for the provider plugin to name. + */ onRequestError?: (error: unknown) => Promise } @@ -143,8 +147,8 @@ export interface DeepSeekAdapterOptions LlmError /** - * Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, and - * rejection of {@link resolveAuth} without its failure classification; omission publishes none. + * Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, + * rejection, and withdrawal signal of {@link resolveAuth} without its failure classification; omission publishes none. */ credential?: DeepSeekRouteCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ diff --git a/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts b/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts new file mode 100644 index 0000000000..469cd3be6d --- /dev/null +++ b/packages/llm/llm-deepseek/tests/account-signout-composition.spec.ts @@ -0,0 +1,190 @@ +/** + * Real Loader composition of the account service, the account route, and the Agent loop against a loopback DeepSeek + * stand-in: a sign-out ends the requests that carry its token, whether or not their route is still mounted. + */ +import { once } from 'node:events' +import { createServer } from 'node:http' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, expect, it, vi } from 'vitest' +import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' +import { Context } from '@deepseek-ai/cordis' +import Include from '@deepseek-ai/cordis-plugin-include' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import AuthorizationService from '@deepseek-ai/dsh-authorization' +import { brandString } from '@deepseek-ai/dsh-brand' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import LocalCredentials from '@deepseek-ai/dsh-credentials-local' +import DeepSeekAccount, { type AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' +import LlmRuntime, { type StreamChunk } from '@deepseek-ai/dsh-llm' +import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account' +import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import { profileComposition } from '../../../settings/settings/tests/profile-composition.ts' +import { sourceModuleLoader, sse, start, user } from './helpers.ts' + +const PROVIDER = 'deepseek-account' +const MODEL = 'deepseek-flash' +const CLIENT: AccountClientMetadata = { version: '1.2.3', locale: 'en', timezoneOffsetSeconds: 28_800 } +const SIGNED_OUT = { kind: 'aborted', reason: { kind: 'hook', reason: 'deepseek-account/signed-out' } } + +const cleanup: Array<() => Promise> = [] +afterEach(async () => { + while (cleanup.length) await cleanup.pop()!() + vi.unstubAllEnvs() +}) + +/** One open Messages response of the stand-in. */ +interface OpenResponse { + /** Text deltas written so far. */ + deltas: number + /** Settles when the client closes the response. */ + closed: Promise +} + +/** Loopback DeepSeek stand-in: the account listing, the logout call, and Messages responses that stream until closed. */ +async function upstream() { + const responses: OpenResponse[] = [] + const http = createServer((request, response) => { + request.resume() + request.once('end', () => { + if (request.method === 'GET' && request.url === '/models') { + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify({ data: [{ + id: MODEL, name: 'DeepSeek-V4.1-Flash', context_window: 1_048_576, max_output_tokens: 100_000, + input_modalities: ['text'], output_modalities: ['text'], api_capabilities: { anthropic_messages: {} }, + }] })) + return + } + if (request.url === '/auth-api/v0/users/logout') { + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: null } })) + return + } + if (request.url !== '/anthropic/v1/messages') { response.writeHead(404).end('{}'); return } + const closed = Promise.withResolvers() + const open: OpenResponse = { deltas: 0, closed: closed.promise } + responses.push(open) + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.write(sse([start, { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }])) + const timer = setInterval(() => { + response.write(sse([{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'x' } }])) + open.deltas += 1 + }, 10) + response.once('close', () => { clearInterval(timer); closed.resolve(undefined) }) + }) + }) + http.listen(0, '127.0.0.1') + await once(http, 'listening') + const address = http.address() + if (address === null || typeof address === 'string') throw new Error('missing loopback port') + cleanup.push(async () => { + http.closeAllConnections() + await new Promise((resolve) => { http.close(() => { resolve() }) }) + }) + /** The first Messages response once it has streamed `count` more deltas. */ + const streaming = async (count: number): Promise => { + const from = responses[0]?.deltas ?? 0 + await vi.waitFor(() => { expect(responses[0]?.deltas).toBeGreaterThanOrEqual(from + count) }, { timeout: 10_000, interval: 5 }) + return responses[0]! + } + return { origin: `http://127.0.0.1:${String(address.port)}`, streaming } +} + +/** Boot the profile through the Loader with a signed-in account whose inference origin is the stand-in. */ +async function boot(origin: string) { + const home = await mkdtemp(join(tmpdir(), 'dsh-account-signout-')) + cleanup.push(() => rm(home, { recursive: true, force: true })) + vi.stubEnv('DSH_HOME', home) + vi.stubEnv('DEEPSEEK_BASE_URL', '') + const ctx = new Context() + cleanup.push(() => ctx.fiber.dispose()) + const modules = new Map([ + ['@deepseek-ai/dsh-llm', { module: LlmRuntime }], ['@deepseek-ai/dsh-session', { module: SessionStore }], + ['@deepseek-ai/dsh-session-projection', { module: SessionProjectionRegistry }], ['@deepseek-ai/dsh-system-prompt', { module: SystemPrompt }], + ['@deepseek-ai/dsh-tools', { module: ToolRuntime }], ['@deepseek-ai/dsh-tool-executor-native', { module: NativeToolExecutor }], + ['@deepseek-ai/dsh-agent', { module: AgentRegistry }], ['@deepseek-ai/dsh-agent-loop', { module: AgentLoop, config: { agents: [] } }], + ['@deepseek-ai/dsh-credentials-local', { module: LocalCredentials, config: { path: join(home, '.credentials.yaml'), watch: false } }], + ['@deepseek-ai/dsh-authorization', { module: AuthorizationService }], + ['@deepseek-ai/dsh-deepseek-account', { module: DeepSeekAccount, config: { + platformOrigin: origin, inferenceOrigin: origin, allowLoopbackHttp: true, logoutRetryDelayMs: 1, + } }], + ['@deepseek-ai/dsh-llm-deepseek-account', { module: AccountRoute, config: { baseURL: `${origin}/anthropic` } }], + ]) + await writeFile(join(home, 'cordis.yml'), JSON.stringify( + [...modules].map(([name, { config }]) => ({ name, ...config === undefined ? {} : { config } })), + )) + // The importer supplies source modules while Loader still owns configuration and effects. + for (const name of modules.keys()) { + const directory = join(home, 'node_modules', name) + await mkdir(directory, { recursive: true }) + await writeFile(join(directory, 'package.json'), JSON.stringify({ name, version: '0.1.3-alpha.1', type: 'module' })) + } + ctx.baseUrl = pathToFileURL(home).href + '/' + await ctx.plugin(Loader) + ctx.loader.builtins.include = Include + ctx.loader.internal = sourceModuleLoader(async (name) => { + const found = modules.get(name) + if (found === undefined) throw new Error(`unexpected module ${name}`) + return found.module + }) + const patchPath = await profileComposition(ctx, home, join(home, 'cordis.yml')) + await ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, issuer: origin, token: 'test-platform-grant' }, + })) + /** Switch the account route off through the profile patch, as the plugin switch does. */ + const disableRoute = async (): Promise => { + await writeFile(patchPath, '- id: llm-deepseek-account\n disabled: true\n') + await ctx.hmr.runExclusive(() => ctx.hmr.reconcileProfile()) + } + return { ctx, disableRoute } +} + +const routeListed = (ctx: Context): boolean => ctx.llm.listProviders().some(provider => provider.id === PROVIDER) + +it.each([ + { route: 'mounted', disable: false }, + { route: 'disabled', disable: true }, +])('ends a streaming account turn at sign-out with the signed-out cause while its route is $route', async ({ disable }) => { + const http = await upstream() + const { ctx, disableRoute } = await boot(http.origin) + const agent = await ctx.agentLoop.create(brandString(`signout-${String(disable)}`), { provider: PROVIDER, model: MODEL }) + agent.followup(user()) + await http.streaming(2) + if (disable) { + // Disabling returns while the turn runs, and neither stops the turn nor closes its response. + await disableRoute() + expect(routeListed(ctx)).toBe(false) + await http.streaming(2) + expect(agent.status).toBe('running') + } + const response = await http.streaming(0) + await ctx.deepseekAccount.signOut(CLIENT) + await agent.whenIdle() + await response.closed + const end = agent.session.snapshotEvents().at(-1) + expect({ type: end?.type, reason: (end?.data as { reason?: unknown }).reason }).toEqual({ type: 'turn/end', reason: SIGNED_OUT }) +}) + +it('ends an account model request outside an Agent turn at sign-out, as a sign-in failure', async () => { + const http = await upstream() + const { ctx } = await boot(http.origin) + const chunks: StreamChunk[] = [] + const consumed = (async () => { + for await (const chunk of ctx.llm.stream({ provider: PROVIDER, model: MODEL, messages: [user()] })) chunks.push(chunk) + })() + const response = await http.streaming(2) + await ctx.deepseekAccount.signOut(CLIENT) + await consumed + await response.closed + expect(chunks.at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'error', failure: { + code: 'ACCOUNT_SIGN_IN_REQUIRED', + message: 'The DeepSeek account signed out before this request finished. Sign in to DeepSeek to use the account provider.', + } } }) +}) diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index 767e8f24d9..7665bed167 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -19,7 +19,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' -import LlmRuntime, { createAssistantMessage, createDeveloperMessage, createSystemMessage, createToolResultMessage, createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import LlmRuntime, { createAssistantMessage, createDeveloperMessage, createSystemMessage, createToolResultMessage, createUserMessage, LlmError, type ToolCallId } from '@deepseek-ai/dsh-llm' import type { Message } from '@deepseek-ai/dsh-llm' import { credentialRef } from '@deepseek-ai/dsh-credentials' import LocalCredentials from '@deepseek-ai/dsh-credentials-local' @@ -240,6 +240,35 @@ describe('direct Messages HTTP', () => { await stopped }) + it('ends an open provider response when its credential is withdrawn and lets the provider name the failure', async () => { + const stopped = Promise.withResolvers() + const http = await endpoint((response) => { + response.once('close', () => { stopped.resolve(undefined) }) + response.write(sse(textEvents.slice(0, 3))) + }) + const withdrawn = new AbortController() + const onRequestError = vi.fn(async (error: unknown) => new LlmError('credential withdrawn', 'ACCOUNT_SIGN_IN_REQUIRED', { cause: error })) + const stream = adapter({ baseURL: http.url }, { + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', revoked: withdrawn.signal, onRequestError }), + }).stream(options())[Symbol.asyncIterator]() + expect((await stream.next()).value).toMatchObject({ type: 'block-start' }) + expect((await stream.next()).value).toMatchObject({ type: 'text-delta' }) + const failed = expect(stream.next()).rejects.toMatchObject({ code: 'ACCOUNT_SIGN_IN_REQUIRED', message: 'credential withdrawn' }) + withdrawn.abort() + await failed + await stopped.promise + expect(onRequestError).toHaveBeenCalledExactlyOnceWith(withdrawn.signal.reason) + }) + + it('reports a withdrawal the provider does not name as a transport failure, without contacting the provider', async () => { + const http = await endpoint() + const llm = adapter({ baseURL: http.url }, { + resolveAuth: () => Promise.resolve({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', revoked: AbortSignal.abort() }), + }) + await expect(chunks(llm.stream(options()))).rejects.toMatchObject({ code: 'TRANSPORT' }) + expect(http.requests).toEqual([]) + }) + it('times out an idle HTTP response and closes the connection', async () => { const stopped = Promise.withResolvers() const http = await endpoint((response) => { diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index f6e5b79fb8..032cdf1299 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -28,7 +28,7 @@ function body(init: RequestInit | undefined): string { return init.body } const rejected = (message: string, status = 400) => new Response(JSON.stringify({ error: { type: 'invalid_request_error', message } }), { status }) -function harness(config: Config = {}) { +function harness(config: Config = {}, revoked?: AbortSignal) { const ensureUploaded = vi.fn(async image => ({ record: { fileId: brandString(image.attachment.attachmentId === ref.attachmentId ? 'file-a' : 'file-b') }, uploaded: false, } as Awaited>)) @@ -40,7 +40,8 @@ function harness(config: Config = {}) { const prepare = vi.fn(prepareExtensions) const adapter = new DeepSeekAdapter({ options: () => resolveAdapterOptions(Object.assign({ baseURL: 'https://gateway.example/custom' }, config)), - resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' }, value: 'test-key' }), resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments, + resolveAuth: async () => ({ headers: { 'x-api-key': 'test-key' }, value: 'test-key', ...revoked === undefined ? {} : { revoked } }), + resolveUserId: () => 'test-user' as AnonymousUserId, resolveAttachments: () => attachments, resolveImageAccess: () => ({ readonlyPath: '/workspace/image.png' }), resolveFiles: () => files, prepareExtensions: prepare, }) return { adapter, ensureUploaded, invalidate, readImageRequest, prepare } @@ -208,6 +209,23 @@ describe('Messages Files requests', () => { expect(fetchImpl).toHaveBeenCalledTimes(1) }) + it('ends a pending upload with its withdrawn credential and sends no request', async () => { + const fetchImpl = vi.fn(async () => success()) + vi.stubGlobal('fetch', fetchImpl) + const withdrawn = new AbortController() + const h = harness({}, withdrawn.signal) + const uploading = Promise.withResolvers() + h.ensureUploaded.mockImplementation(async (_version, _connection, _policy, signal) => new Promise((_resolve, reject) => { + signal!.addEventListener('abort', () => { reject(new Error('upload aborted', { cause: signal!.reason })) }, { once: true }) + uploading.resolve(undefined) + })) + const result = expect(chunks(h.adapter.stream(request()))).rejects.toMatchObject({ code: 'TRANSPORT' }) + await uploading.promise + withdrawn.abort() + await result + expect(fetchImpl).not.toHaveBeenCalled() + }) + it('classifies Files recovery only from provider error fields', () => { expect(providerErrorDetail({ extra: 'file-a expired', error: { message: 'invalid request' } })).toBe('invalid request') expect(providerErrorDetail({ error: { code: 'file_not_found', type: 'invalid_request_error', message: 'missing' } })).toBe('file_not_found invalid_request_error missing') diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts index 404927a098..3314455d4e 100644 --- a/packages/llm/llm-deepseek/tests/route-credential.spec.ts +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -53,8 +53,9 @@ it('publishes no credential for a provider that declares none', async () => { it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { const reject = vi.fn(() => Promise.resolve()) + const revoked = new AbortController().signal const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => - endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, onRequestError: error => Promise.resolve(error) } : undefined) + endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, revoked, onRequestError: error => Promise.resolve(error) } : undefined) const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) const credential = ctx.llm.routeCredential('fixture-route') @@ -63,8 +64,9 @@ it('publishes the declared credential from one configuration generation and reso await expect(credential!.configured(OTHER)).resolves.toBe(false) // The grant carries the seam's fields only; the adapter's failure classification stays behind it. const grant = await credential!.resolve(ALLOWED) - expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject']) + expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject', 'revoked']) expect(grant).toMatchObject({ headers: { 'x-fixture': 'k' }, value: 'k' }) + expect(grant!.revoked).toBe(revoked) await grant!.reject!() expect(reject).toHaveBeenCalledTimes(1) await expect(credential!.resolve(OTHER)).resolves.toBeUndefined() @@ -73,7 +75,7 @@ it('publishes the declared credential from one configuration generation and reso expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL]) }) -it('omits the reference of a credential kind without one and the rejection of a grant without one', async () => { +it('omits the reference of a credential kind without one and the rejection and withdrawal of a grant without them', async () => { const ctx = await route({ resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }), credential: { kind: 'account', configured: () => Promise.resolve(false) }, diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 33c924aefd..60b576c1aa 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -330,6 +330,13 @@ export interface RouteCredentialGrant { * @returns settlement after the invalidation attempt. */ reject?(): Promise + /** + * Aborts when the owner withdraws this credential while requests carrying it + * may be in flight, as an account sign-out does. A consumer ends each request + * it authenticated with this grant and reports that end as its own failure, + * not as the caller's cancellation. Absent for kinds that are never withdrawn. + */ + readonly revoked?: AbortSignal } /** diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index 67b48ecaed..db6f262828 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -21,8 +21,8 @@ en: 8923728d77eb1256 zh: 85d1b8408cf1f325 /deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures: - en: 7dbb34d960c1344c - zh: 51a1459415857ab5 + en: e7a5d332ebababe7 + zh: 5020eabd799ebb5c /deepseek-ai-dsh-web-deepseek-api/understand-the-implementation: en: 597dab3fe52fa59d zh: 4370d01d5a58f2f9 @@ -33,8 +33,8 @@ en: dfd3b61aff4a8aa8 zh: 06e2b6cc71f461e2 /deepseek-ai-dsh-web-deepseek-api/model-experience/conversation-tool-results/what-the-model-sees: - en: a9fbb78ffe886f0b - zh: 813dc7ee283018d2 + en: 84b1c849ae37668b + zh: 5a747293d8775f5e /deepseek-ai-dsh-web-deepseek-api/model-experience/conversation-tool-results/token-effect: en: 1f33560e768d18c5 zh: edeedeef2662e4bb diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md index 737cf87336..80b0b68b57 100644 --- a/packages/web/web-deepseek-api/README.md +++ b/packages/web/web-deepseek-api/README.md @@ -74,7 +74,7 @@ Each provider's `ready()` answers whether its next operation for that route has The Search API receives `query`, `count` (the configured count, or the request's smaller `maxResults`), `need_content: false`, and, unless `sendOriginalQuestion` is off, `ori_question`: the text of the initiating Session's latest human prompt with whitespace collapsed and cut to 128 characters. A search outside a Session or without such a prompt omits it. The provider maps `results[].snippet` as the display excerpt and `results[].summary` as the model-facing excerpt, and maps nullable `date` to optional `publishedAt`; `dsh-tool-web` caps each summary. An empty results array is successful. Fetch sends `url` and returns the original Markdown as a text body with HTTP status 200, because the API answers with an error status when the target yields no usable content. Its URL is the requested URL: the API reports no final redirected URL. -An unparseable own base URL makes that capability's provider unavailable; and a `count` outside 1 to 50 makes Search unavailable. A missing credential fails with `WEB_PROVIDER_CREDENTIAL_MISSING`; a needed model route whose settings do not resolve fails with `WEB_PROVIDER_MISCONFIGURED`, naming the resolver failure, the Models page, and the capability's `*BaseURL` and `*ApiKeyEnv`; cancellation uses `WEB_ABORTED`; transport, HTTP, and malformed response failures use `WEB_PROVIDER_ERROR`. Redirects are rejected before contacting their target. Non-success Fetch API statuses are retrieval failures, not target-page statuses. Account-authenticated HTTP 401 responses invalidate only the token sent by that request and provide sign-in guidance; a newer sign-in is preserved, and credential-removal failure does not replace the HTTP error. API-key failures and HTTP 403 never invalidate an account token; other dispatch failures identify the endpoint and say where it came from: for a route endpoint they guide the user to that provider's base URL on the Models page or to the capability's `*BaseURL` and `*ApiKeyEnv`, and for own settings to correcting or removing those fields. No automatic retry or provider fallback occurs. +An unparseable own base URL makes that capability's provider unavailable; and a `count` outside 1 to 50 makes Search unavailable. A missing credential fails with `WEB_PROVIDER_CREDENTIAL_MISSING`; a needed model route whose settings do not resolve fails with `WEB_PROVIDER_MISCONFIGURED`, naming the resolver failure, the Models page, and the capability's `*BaseURL` and `*ApiKeyEnv`; cancellation uses `WEB_ABORTED`; transport, HTTP, and malformed response failures use `WEB_PROVIDER_ERROR`. A request ends when the credential it carries is withdrawn, as an account sign-out does through the grant's `revoked` signal: it fails with `WEB_PROVIDER_ERROR` and guidance to sign in again, or for another credential kind to check that credential on the Models page, unless the caller cancelled as well, which stays `WEB_ABORTED`. Redirects are rejected before contacting their target. Non-success Fetch API statuses are retrieval failures, not target-page statuses. Account-authenticated HTTP 401 responses invalidate only the token sent by that request and provide sign-in guidance; a newer sign-in is preserved, and credential-removal failure does not replace the HTTP error. API-key failures and HTTP 403 never invalidate an account token; other dispatch failures identify the endpoint and say where it came from: for a route endpoint they guide the user to that provider's base URL on the Models page or to the capability's `*BaseURL` and `*ApiKeyEnv`, and for own settings to correcting or removing those fields. No automatic retry or provider fallback occurs. ----- @@ -99,7 +99,7 @@ See the [web subsystem](../../../docs/subsystems/web.md) for service types and [ #### What the model sees -The `web_search` and `web_fetch` tools render sources or Markdown with an external-content notice. Fetch results carry the requested URL and HTTP 200. Errors retain actionable credential or endpoint guidance. Search sends the query, with the triggering question, directly to the Search API. +The `web_search` and `web_fetch` tools render sources or Markdown with an external-content notice. Fetch results carry the requested URL and HTTP 200. Errors retain actionable credential or endpoint guidance; a request the account's sign-out ended reports `The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again; the endpoint does not need changing.` Search sends the query, with the triggering question, directly to the Search API. #### Token effect diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index 9075dfe2c5..6243b8359b 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -74,7 +74,7 @@ Search 与 Fetch 每次操作各自从同一份设置快照解析端点和凭据 Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 `maxResults`)、`need_content: false`,以及在 `sendOriginalQuestion` 未关闭时的 `ori_question`:发起会话中最近一条用户提示的文本,空白折叠后截取至 128 个字符。在会话之外或没有此类提示的搜索不发送该字段。提供者将 `results[].snippet` 映射为展示用摘录,将 `results[].summary` 映射为面向模型的摘录,并将可为 null 的 `date` 映射为可选的 `publishedAt`;`dsh-tool-web` 限制每条摘要的长度。空结果数组表示成功。Fetch 发送 `url`,以文本正文返回原始 Markdown,并报告 HTTP 状态 200,因为目标没有可用内容时 API 会返回错误状态。返回 URL 为请求 URL:API 不报告重定向后的最终 URL。 -单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。 +单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。请求携带的凭据被收回时(例如账号退登通过授权的 `revoked` 信号收回),请求随即结束:以 `WEB_PROVIDER_ERROR` 失败并提供重新登录的指引,其他种类的凭据则指引用户在模型页面检查该凭据;调用方同时取消时仍为 `WEB_ABORTED`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。 ----- @@ -99,7 +99,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 #### 模型看到什么 -`web_search` 和 `web_fetch` 工具在外部内容提示下呈现搜索来源或 Markdown。Fetch 结果包含请求 URL 和 HTTP 200。错误保留可操作的凭据或端点指引。Search 将查询连同触发问题直接发送给 Search API。 +`web_search` 和 `web_fetch` 工具在外部内容提示下呈现搜索来源或 Markdown。Fetch 结果包含请求 URL 和 HTTP 200。错误保留可操作的凭据或端点指引;被账号退登结束的请求报告 `The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again; the endpoint does not need changing.`Search 将查询连同触发问题直接发送给 Search API。 #### Token 影响 diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts index 2508e2c714..befc4d4b65 100644 --- a/packages/web/web-deepseek-api/src/transport.ts +++ b/packages/web/web-deepseek-api/src/transport.ts @@ -163,6 +163,8 @@ interface SearchAuth { readonly headers: Readonly> /** Request-bound invalidation of the sent credential, present when its grant offers one; the dispatch contains its failure. */ readonly reject?: () => Promise + /** Withdrawal of the sent credential, present when its grant offers one; it ends the request. */ + readonly revoked?: AbortSignal } /** Dispatch one operation using a single settings and credential snapshot: one request, with the first present source. @@ -183,6 +185,17 @@ export async function dispatchDeepSeekWeb( throwIfSearchAborted(signal) let response: Response /* jscpd:ignore-start */ + const live = requestSignal(signal, auth.revoked) + /** + * The failure of an interrupted request: the caller's cancellation first, then the withdrawal of the sent credential. + * @param error - what the interrupted fetch or body read threw. + * @returns the failure to report, or undefined when `error` is no interruption. + */ + const interrupted = (error: unknown): WebError | undefined => { + if (signal?.aborted === true) return searchAborted(signal, error) + if (auth.revoked?.aborted === true) return credentialWithdrawnError(auth.kind, error) + return isAbortError(error) ? searchAborted(signal, error) : undefined + } try { response = await fetch(endpoint, { method: 'POST', @@ -195,11 +208,10 @@ export async function dispatchDeepSeekWeb( 'user-agent': USER_AGENT, }, body: JSON.stringify(body), - ...signal !== undefined ? { signal } : {}, + ...live !== undefined ? { signal: live } : {}, }) } catch (error: unknown) { - if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) - throw searchEndpointError( + throw interrupted(error) ?? searchEndpointError( guidance, endpoint, `DeepSeek web request failed: ${String(error)}`, @@ -219,10 +231,10 @@ export async function dispatchDeepSeekWeb( if (typeof detail === 'string' && detail.length > 0) message += `: ${detail}` } } catch (error: unknown) { - // An abort fired mid-body must surface as WEB_ABORTED, not be swallowed + // An interruption mid-body must surface as itself, not be swallowed // into a generic HTTP-error message — cancellation is not a provider // error (the seam's cancellation contract). - if (signal?.aborted === true || isAbortError(error)) aborted = searchAborted(signal, error) + aborted = interrupted(error) // Otherwise: the HTTP status is already captured in `message` above; a // malformed/non-JSON error body (normal for gateway 5xx/429s) can only // cost a richer provider message, never the real error. @@ -246,7 +258,8 @@ export async function dispatchDeepSeekWeb( throwIfSearchAborted(signal) return decode(payload) } catch (error: unknown) { - if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) + const stopped = interrupted(error) + if (stopped !== undefined) throw stopped const message = error instanceof WebError ? error.message : `DeepSeek returned an unprocessable response body: ${String(error)}` @@ -254,6 +267,36 @@ export async function dispatchDeepSeekWeb( } } +/** + * The signal one request runs under: the caller's cancellation and the withdrawal of the credential it carries. + * @param signal - caller cancellation, when the caller supplies one. + * @param revoked - withdrawal of the sent credential, when its grant offers one. + * @returns the composed signal, or undefined when neither exists. + */ +function requestSignal(signal: AbortSignal | undefined, revoked: AbortSignal | undefined): AbortSignal | undefined { + if (signal === undefined || revoked === undefined) return signal ?? revoked + return AbortSignal.any([signal, revoked]) +} + +/** + * Report a request that ended because the owner withdrew the credential it carried. The caller did not cancel, so the + * failure is the provider's. + * @param kind - kind of the withdrawn credential. + * @param cause - what the interrupted fetch or body read threw. + * @returns the provider failure, with sign-in guidance for an account credential. + */ +function credentialWithdrawnError(kind: LlmCredentialKind, cause: unknown): WebError { + return new WebError( + kind === 'account' + ? 'The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again;' + + ' the endpoint does not need changing.' + : 'The credential this web request carried was withdrawn before the request finished. Guide the user to check that' + + ' credential on the Models page.', + 'WEB_PROVIDER_ERROR', + { cause }, + ) +} + /** Replace endpoint guidance with sign-in guidance when DeepSeek rejects the account token. */ function accountRejectedError(message: string): WebError { return new WebError( @@ -318,6 +361,7 @@ async function authHeaders( kind, endpoint, headers: kind === 'api-key' ? { ...request.apiKeyHeaders?.(grant.value), authorization: `Bearer ${grant.value}` } : grant.headers, ...invalidate === undefined ? {} : { reject: invalidate }, + ...grant.revoked === undefined ? {} : { revoked: grant.revoked }, } } case 'api-key': { diff --git a/packages/web/web-deepseek-api/tests/composition.spec.ts b/packages/web/web-deepseek-api/tests/composition.spec.ts index 71f01ee2b9..123d645bc7 100644 --- a/packages/web/web-deepseek-api/tests/composition.spec.ts +++ b/packages/web/web-deepseek-api/tests/composition.spec.ts @@ -44,12 +44,17 @@ interface Sent { * Boot the composition with a fixed launch environment and a stubbed network. * @param web - web-deepseek-api config. * @param environment - launch-environment variables. + * @param account - the sign-out signal of the stubbed account and the answer to Search requests, when not the default. * @returns the booted root context and the Search and Fetch API requests sent so far. */ -async function bootComposition(web: Record, environment: Record) { +async function bootComposition( + web: Record, environment: Record, + account: { signedOut?: AbortSignal; search?: (signal: AbortSignal) => Promise } = {}, +) { // The providers and model listings dispatch to a string endpoint. - const fetchMock = vi.fn(async (url: string, _init?: RequestInit) => { + const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { if (url.endsWith('/models')) return Response.json({ object: 'list', data: [] }) + if (url.endsWith('/search') && account.search !== undefined) return await account.search(init!.signal!) return Response.json(url.endsWith('/search') ? { results: [] } : { content: '# Page' }) }) vi.stubGlobal('fetch', fetchMock) @@ -83,7 +88,9 @@ async function bootComposition(web: Record, environment: Record } host.loader.internal = modules host.provide('launchEnvironment', createLaunchEnvironmentSnapshot([{ source: 'process', values: environment }])) - host.provide('deepseekAccount', accountStub({ token: () => 'account-token' })) + host.provide('deepseekAccount', accountStub({ + token: () => 'account-token', ...account.signedOut === undefined ? {} : { signedOut: account.signedOut }, + })) }) cleanups.push(async () => { await ctx.fiber.dispose() }) const sent = (): Sent[] => fetchMock.mock.calls.flatMap(([endpoint, init]) => { @@ -147,6 +154,30 @@ describe('web-deepseek-api over the real model routes', () => { ]) }) + it('ends an account-billed search in flight when the account signs out, with sign-in guidance', async () => { + const signedOut = new AbortController() + const sent = Promise.withResolvers() + const { ctx } = await bootComposition({ searchBilling: 'account' }, { DEEPSEEK_API_KEY: 'chat-key' }, { + signedOut: signedOut.signal, + search: (signal) => { + sent.resolve(signal) + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + }, + }) + const search = ctx.web.search({ query: 'q' }) + const request = await sent.promise + expect(request.aborted).toBe(false) + signedOut.abort() + await expect(search).rejects.toMatchObject({ + code: 'WEB_PROVIDER_ERROR', + message: 'The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again;' + + ' the endpoint does not need changing.', + }) + expect(request.aborted).toBe(true) + }) + it('withholds API-key billing without a key despite a sign-in', async () => { const { ctx, sent } = await bootComposition({ searchBilling: 'api-key' }, {}) expect(await ctx.web.searchReady('deepseek-account')).toBe(false) diff --git a/packages/web/web-deepseek-api/tests/transport.spec.ts b/packages/web/web-deepseek-api/tests/transport.spec.ts index 3a082c938f..554d1f7671 100644 --- a/packages/web/web-deepseek-api/tests/transport.spec.ts +++ b/packages/web/web-deepseek-api/tests/transport.spec.ts @@ -19,26 +19,31 @@ function keyRef(resolve: () => Promise, configured: () => Pr /** * A route source on {@link ACCOUNT_BASE} whose account credential releases `resolveToken(endpoint)` as the token header; * an empty token releases nothing. `rejectToken` observes each invalidated token, and its failure rejects the grant's - * invalidation, as an owner that does not contain its storage failures does. + * invalidation, as an owner that does not contain its storage failures does. `revoked` is the sign-out signal the + * grant carries, when given. */ function accountSource( resolveToken: (endpoint: string) => Promise, rejectToken: (token: string) => Promise = async () => {}, + revoked?: AbortSignal, ): DeepSeekWebAuthSource { const grant = async (endpoint: string) => { const token = await resolveToken(endpoint) if (token === undefined || token.length === 0) return undefined - return { headers: { 'x-dsh-auth-token': token }, value: token, reject: () => rejectToken(token) } + return { headers: { 'x-dsh-auth-token': token }, value: token, reject: () => rejectToken(token), ...revoked === undefined ? {} : { revoked } } } return { kind: 'route', baseURL: ACCOUNT_BASE, credential: { kind: 'account', configured: async endpoint => (await grant(endpoint)) !== undefined, resolve: grant, } } } -/** A route source on {@link API_BASE} whose API-key credential releases `key`, sent as a bearer token. */ -function keyRouteSource(key: string | undefined, reference = 'ROUTE_KEY'): DeepSeekWebAuthSource { +/** + * A route source on {@link API_BASE} whose API-key credential releases `key`, sent as a bearer token, with the + * withdrawal signal `revoked` when given. + */ +function keyRouteSource(key: string | undefined, reference = 'ROUTE_KEY', revoked?: AbortSignal): DeepSeekWebAuthSource { return { kind: 'route', baseURL: API_BASE, credential: { kind: 'api-key', reference, configured: async () => key !== undefined, - resolve: async () => key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key }, + resolve: async () => key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key, ...revoked === undefined ? {} : { revoked } }, } } } const misconfigured: DeepSeekWebAuthSource = { kind: 'misconfigured', message: 'route settings do not resolve' } @@ -388,6 +393,74 @@ describe('DeepSeek web account authentication', () => { }) }) +describe('DeepSeek web credential withdrawal', () => { + const ACCOUNT_SIGNED_OUT = 'The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek' + + ' again; the endpoint does not need changing.' + const KEY_WITHDRAWN = 'The credential this web request carried was withdrawn before the request finished. Guide the user to check' + + ' that credential on the Models page.' + + /** Hold each request open until its signal aborts, as an unanswered endpoint does. */ + function holdRequests() { + const sent = Promise.withResolvers() + vi.stubGlobal('fetch', vi.fn((_input: string, init?: RequestInit) => { + const signal = init!.signal! + sent.resolve(signal) + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + })) + return sent.promise + } + + it.each<[string, (revoked: AbortSignal) => DeepSeekWebAuthSource, string]>([ + ['an account sign-out', revoked => accountSource(async () => 'account-token', undefined, revoked), ACCOUNT_SIGNED_OUT], + ['the withdrawal of a route key', revoked => keyRouteSource('route-key', 'ROUTE_KEY', revoked), KEY_WITHDRAWN], + ])('ends an open request at %s and reports the withdrawal instead of a cancellation', async (_label, source, message) => { + for (const signal of [undefined, new AbortController().signal]) { + const withdrawn = new AbortController() + const sent = holdRequests() + const pending = rejectedWebError(search([source(withdrawn.signal)], signal)) + const request = await sent + expect(request.aborted).toBe(false) + withdrawn.abort() + const error = await pending + expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message }) + expect(error.cause).toBe(withdrawn.signal.reason) + expect(request.aborted).toBe(true) + } + }) + + it.each([200, 500])('reports a withdrawal that interrupts reading an HTTP %i body', async (status) => { + const withdrawn = new AbortController() + const body = new Response('', { status }) + vi.spyOn(body, 'json').mockImplementation(async (): Promise => { + withdrawn.abort() + throw new DOMException('The operation was aborted.', 'AbortError') + }) + vi.stubGlobal('fetch', vi.fn(async () => body)) + const error = await rejectedWebError(search([accountSource(async () => 'account-token', undefined, withdrawn.signal)])) + expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message: ACCOUNT_SIGNED_OUT }) + }) + + it('reports the caller\'s cancellation when the caller and the withdrawal both ended the request', async () => { + const withdrawn = new AbortController() + const controller = new AbortController() + vi.stubGlobal('fetch', vi.fn(async () => { + withdrawn.abort() + controller.abort(new Error('caller stopped')) + throw new DOMException('The operation was aborted.', 'AbortError') + })) + await expect(search([accountSource(async () => 'account-token', undefined, withdrawn.signal)], controller.signal)) + .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) + }) + + it('keeps reporting a failure of a request whose credential stays in force', async () => { + vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new TypeError('connection refused')))) + const error = await rejectedWebError(search([accountSource(async () => 'account-token', undefined, new AbortController().signal)])) + expect(error.message).toContain('DeepSeek web request failed: TypeError: connection refused') + }) +}) + describe('DeepSeek web cancellation and failures', () => { it('does not start credential resolution or dispatch for a pre-aborted call', async () => { const resolve = vi.fn(async () => 'late-key') diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index d25d04cf27..76e5c0a067 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3ed88edabdf63c8d zh: c66176c8a7c9a434 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: b9d2e372face46f1 - zh: cc8e5820d6aada38 + en: 5bd18e6e586eb4f0 + zh: 133927c4db79ac71 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a @@ -69,8 +69,8 @@ en: 666f5753c99783ab zh: b44328e99bcc45c9 /deepseek-ai-dsh-web-search-deepseek/model-experience/conversation-tool-result-indirectly/what-the-model-sees: - en: 0764d19c9b82aa98 - zh: 88b0ba22ef64225b + en: fbe717bd9c6c43a5 + zh: 598ad961a5561ae1 /deepseek-ai-dsh-web-search-deepseek/model-experience/conversation-tool-result-indirectly/token-effect: en: 01ec43a9b616139d zh: 0a5b7c28fde34bcf diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 91411478f7..741d92499a 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,7 +58,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. An account-authenticated search in flight when the account signs out ends through the credential's `revoked` signal and fails as `WEB_PROVIDER_ERROR` with sign-in guidance. The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential for the origin of the configured search endpoint that reports itself configured for that endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or whose published base URL does not parse, or a failed account-credential or credential-store read, answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. @@ -147,7 +147,7 @@ Independent of the conversation request cache. The auxiliary instruction and nat #### What the model sees -Through `dsh-tool-web`, the conversation model sees deduplicated URLs, titles, dates, and citation snippets from structured search blocks; provider prose is not trusted as an answer. This provider's exact failures include the actionable missing-credential message, which also names DeepSeek Account sign-in, `DeepSeek search credential resolution failed: `, and `DeepSeek search aborted`. An HTTP 401 to an account-authenticated search appends an instruction to guide the user to sign in to DeepSeek again. Other request, HTTP, native-search, and response-body failures append the resolved endpoint and the conditional configuration instruction described above. The consumer owns the error wrapper. +Through `dsh-tool-web`, the conversation model sees deduplicated URLs, titles, dates, and citation snippets from structured search blocks; provider prose is not trusted as an answer. This provider's exact failures include the actionable missing-credential message, which also names DeepSeek Account sign-in, `DeepSeek search credential resolution failed: `, and `DeepSeek search aborted`. An HTTP 401 to an account-authenticated search appends an instruction to guide the user to sign in to DeepSeek again. A search the account's sign-out ended reports `The DeepSeek account signed out before this web search finished. Guide the user to sign in to DeepSeek again; the search endpoint does not need changing.` Other request, HTTP, native-search, and response-body failures append the resolved endpoint and the conditional configuration instruction described above. The consumer owns the error wrapper. #### Token effect diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index c4908267e8..7b7c8ac43c 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 +当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。账号退登时仍在途的账号鉴权搜索会通过凭据的 `revoked` 信号结束,并以 `WEB_PROVIDER_ERROR` 失败,附带登录指引。 提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由为配置的搜索端点所在 origin 发布了账号凭据且该凭据报告自身已为该端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析或其发布的基础地址无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 @@ -147,7 +147,7 @@ kind: "package-reference" #### 模型看到的内容 -通过 `dsh-tool-web`,会话模型会看到结构化搜索块中去重后的 URL、标题、日期与引用 snippet;提供方文本不会作为答案受到信任。该提供方的具体失败消息包括带有处理指引的凭据缺失消息(其中也提到 DeepSeek 账号登录)、`DeepSeek search credential resolution failed: ` 和 `DeepSeek search aborted`。账号鉴权的搜索收到 HTTP 401 时,会追加引导用户重新登录 DeepSeek 的指引。其他请求、HTTP、原生搜索和响应正文失败会追加已解析端点及前述条件式配置指引。错误包装属于消费方。 +通过 `dsh-tool-web`,会话模型会看到结构化搜索块中去重后的 URL、标题、日期与引用 snippet;提供方文本不会作为答案受到信任。该提供方的具体失败消息包括带有处理指引的凭据缺失消息(其中也提到 DeepSeek 账号登录)、`DeepSeek search credential resolution failed: ` 和 `DeepSeek search aborted`。账号鉴权的搜索收到 HTTP 401 时,会追加引导用户重新登录 DeepSeek 的指引。被账号退登结束的搜索报告 `The DeepSeek account signed out before this web search finished. Guide the user to sign in to DeepSeek again; the search endpoint does not need changing.`其他请求、HTTP、原生搜索和响应正文失败会追加已解析端点及前述条件式配置指引。错误包装属于消费方。 #### Token 影响 diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index 5472a8f2b9..5813d1f2d5 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -97,7 +97,8 @@ export interface DeepSeekSearchProviderOptions { * Resolve the DeepSeek account credential for one search endpoint. A credential takes * precedence over every API key and is sent only through the headers of its grant, which * also invalidates it after HTTP 401; a failure of that invalidation is contained, and the - * search reports the HTTP rejection. `undefined` selects API-key authentication. + * search reports the HTTP rejection. The grant's `revoked` signal ends the search when the + * account signs out. `undefined` selects API-key authentication. */ resolveAccountCredential?: (endpoint: string) => Promise /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */ @@ -195,6 +196,8 @@ interface SearchAuth { readonly headers: Readonly> /** Request-bound invalidation, present when the sent account credential offers one. */ readonly reject?: () => Promise + /** Sign-out of the sent account credential, present when its grant offers one; it ends the request. */ + readonly revoked?: AbortSignal } /** @@ -257,6 +260,17 @@ export class DeepSeekSearchProvider implements WebSearchProvider { }) throwIfSearchAborted(signal) let response: Response + const live = requestSignal(signal, auth.revoked) + /** + * The failure of an interrupted request: the caller's cancellation first, then the sign-out of the sent account. + * @param error - what the interrupted fetch or body read threw. + * @returns the failure to report, or undefined when `error` is no interruption. + */ + const interrupted = (error: unknown): WebError | undefined => { + if (signal?.aborted === true) return searchAborted(signal, error) + if (auth.revoked?.aborted === true) return accountSignedOutError(error) + return isAbortError(error) ? searchAborted(signal, error) : undefined + } try { response = await fetch(endpoint, { method: 'POST', @@ -269,11 +283,10 @@ export class DeepSeekSearchProvider implements WebSearchProvider { 'user-agent': USER_AGENT, }, body: JSON.stringify(body), - ...signal !== undefined ? { signal } : {}, + ...live !== undefined ? { signal: live } : {}, }) } catch (error: unknown) { - if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) - throw searchEndpointError( + throw interrupted(error) ?? searchEndpointError( endpoint, `DeepSeek search request failed: ${String(error)}`, error, @@ -289,10 +302,10 @@ export class DeepSeekSearchProvider implements WebSearchProvider { const detail = typeof parsed.error === 'string' ? parsed.error : parsed.error?.message ?? parsed.message if (detail !== undefined && detail.length > 0) message += `: ${detail}` } catch (error: unknown) { - // An abort fired mid-body must surface as WEB_ABORTED, not be swallowed + // An interruption mid-body must surface as itself, not be swallowed // into a generic HTTP-error message — cancellation is not a provider // error (the seam's cancellation contract). - if (signal?.aborted === true || isAbortError(error)) aborted = searchAborted(signal, error) + aborted = interrupted(error) // Otherwise: the HTTP status is already captured in `message` above; a // malformed/non-JSON error body (normal for gateway 5xx/429s) can only // cost a richer provider message, never the real error. @@ -314,7 +327,8 @@ export class DeepSeekSearchProvider implements WebSearchProvider { const payload = await response.json() as AnthropicResponse return mapAnthropicResponse(payload) } catch (error: unknown) { - if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) + const stopped = interrupted(error) + if (stopped !== undefined) throw stopped const message = error instanceof WebError ? error.message : `DeepSeek returned an unprocessable response body: ${String(error)}` @@ -338,7 +352,11 @@ export class DeepSeekSearchProvider implements WebSearchProvider { : await resolveCredential(() => resolveAccountCredential(endpoint), signal) if (credential !== undefined) { const invalidate = credential.reject?.bind(credential) - return { kind: 'account', headers: credential.headers, ...invalidate === undefined ? {} : { reject: invalidate } } + return { + kind: 'account', headers: credential.headers, + ...invalidate === undefined ? {} : { reject: invalidate }, + ...credential.revoked === undefined ? {} : { revoked: credential.revoked }, + } } const apiKey = await this.apiKey(options, signal) // Official DeepSeek expects `x-api-key`; an Anthropic-compatible proxy @@ -391,6 +409,32 @@ async function resolveCredential(resolve: () => Promise, signal?: AbortSig } } +/** + * The signal one search runs under: the caller's cancellation and the sign-out of the account credential it carries. + * @param signal - caller cancellation, when the caller supplies one. + * @param revoked - sign-out of the sent account credential, when its grant offers one. + * @returns the composed signal, or undefined when neither exists. + */ +function requestSignal(signal: AbortSignal | undefined, revoked: AbortSignal | undefined): AbortSignal | undefined { + if (signal === undefined || revoked === undefined) return signal ?? revoked + return AbortSignal.any([signal, revoked]) +} + +/** + * Report a search that ended because the account it authenticated with signed out. The caller did not cancel, so the + * failure is the provider's. + * @param cause - what the interrupted fetch or body read threw. + * @returns the provider failure with sign-in guidance. + */ +function accountSignedOutError(cause: unknown): WebError { + return new WebError( + 'The DeepSeek account signed out before this web search finished. Guide the user to sign in to DeepSeek again;' + + ' the search endpoint does not need changing.', + 'WEB_PROVIDER_ERROR', + { cause }, + ) +} + /** Replace endpoint guidance with sign-in guidance when DeepSeek rejects the account token. */ function accountRejectedError(message: string): WebError { return new WebError( diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index 9e383dfe08..76c26394da 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -35,14 +35,19 @@ const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchP /** * The account credential resolver a route publishes over `token`, with `reject` observing each invalidated token; * a throwing observer rejects the grant's invalidation, as an owner that does not contain its storage failures does. + * `revoked` is the sign-out signal the grant carries, when given. */ function accountCredential( - token: (endpoint: string) => Promise, reject?: (token: string) => Promise, + token: (endpoint: string) => Promise, reject?: (token: string) => Promise, revoked?: AbortSignal, ): (endpoint: string) => Promise { return async (endpoint) => { const value = await token(endpoint) if (value === undefined || value.length === 0) return undefined - return { headers: { 'x-dsh-auth-token': value }, value, ...reject === undefined ? {} : { reject: () => reject(value) } } + return { + headers: { 'x-dsh-auth-token': value }, value, + ...reject === undefined ? {} : { reject: () => reject(value) }, + ...revoked === undefined ? {} : { revoked }, + } } } @@ -367,6 +372,58 @@ describe('DeepSeekSearchProvider account authentication', () => { expect(rejectAccountToken).toHaveBeenCalledExactlyOnceWith('sent-token') }) + const ACCOUNT_SIGNED_OUT = 'The DeepSeek account signed out before this web search finished. Guide the user to sign in to DeepSeek' + + ' again; the search endpoint does not need changing.' + /** A provider authenticating with an account credential whose sign-out signal is `revoked`. */ + const signedIn = (revoked: AbortSignal): DeepSeekSearchProvider => + searchProvider({ ...options, resolveAccountCredential: accountCredential(async () => 'account-token', undefined, revoked) }) + + it('ends an open search when the account signs out and reports sign-in guidance instead of a cancellation', async () => { + for (const signal of [undefined, new AbortController().signal]) { + const signedOut = new AbortController() + const sent = Promise.withResolvers() + vi.stubGlobal('fetch', vi.fn((_input: string, init?: RequestInit) => { + const request = init!.signal! + sent.resolve(request) + return new Promise((_resolve, reject) => { + request.addEventListener('abort', () => { reject(request.reason as Error) }, { once: true }) + }) + })) + const pending = rejectedWebError(signedIn(signedOut.signal).search({ query: 'q' }, signal)) + const request = await sent.promise + expect(request.aborted).toBe(false) + signedOut.abort() + const error = await pending + expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message: ACCOUNT_SIGNED_OUT }) + expect(error.cause).toBe(signedOut.signal.reason) + expect(request.aborted).toBe(true) + } + }) + + it.each([200, 500])('reports a sign-out that interrupts reading an HTTP %i body', async (status) => { + const signedOut = new AbortController() + const body = new Response('', { status }) + vi.spyOn(body, 'json').mockImplementation(async (): Promise => { + signedOut.abort() + throw new DOMException('The operation was aborted.', 'AbortError') + }) + vi.stubGlobal('fetch', vi.fn(async () => body)) + const error = await rejectedWebError(signedIn(signedOut.signal).search({ query: 'q' })) + expect(error).toMatchObject({ code: 'WEB_PROVIDER_ERROR', message: ACCOUNT_SIGNED_OUT }) + }) + + it('reports the caller\'s cancellation when the caller and the sign-out both ended the search', async () => { + const signedOut = new AbortController() + const controller = new AbortController() + vi.stubGlobal('fetch', vi.fn(async () => { + signedOut.abort() + controller.abort(new Error('caller stopped')) + throw new DOMException('The operation was aborted.', 'AbortError') + })) + await expect(signedIn(signedOut.signal).search({ query: 'q' }, controller.signal)) + .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) + }) + 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({ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f16be97700..2bb50f3f77 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13931,6 +13931,9 @@ importers: '@deepseek-ai/dsh-attachment-local': specifier: workspace:* version: link:../../attachment/attachment-local + '@deepseek-ai/dsh-authorization': + specifier: workspace:* + version: link:../../credentials/authorization '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../../credentials/credentials diff --git a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs index c2fcfcf89b..760695f765 100644 --- a/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs +++ b/snapshots/session/web-search-account-billing/web-search-billing-fixture.mjs @@ -1,6 +1,7 @@ /** * Signed-in DeepSeek account stand-in and Search API endpoint for the billing snapshots. The account releases one fixed - * token, and the endpoint answers only a request that carries that token and no API key. + * token, and the endpoint answers only a request that carries that token and no API key. With the plugin config + * `signOutDuringSearch: true`, the account signs out when that request arrives and the endpoint leaves it unanswered. */ import { applyLoopbackServerEffect } from '../loopback-fixture-server.mjs' @@ -32,10 +33,11 @@ function transportInput(input, transportEndpoint) { } /** Provide the signed-in account and start the Search endpoint; both end with the plugin fiber. */ -export async function apply(ctx) { +export async function apply(ctx, config) { + const signedOut = new AbortController() ctx.provide('deepseekAccount', { resolveRequestCredential: async endpoint => endpoint.startsWith('https://api.deepseek.com/') - ? { headers: { 'x-dsh-auth-token': ACCOUNT_TOKEN }, value: ACCOUNT_TOKEN, reject: async () => {} } + ? { headers: { 'x-dsh-auth-token': ACCOUNT_TOKEN }, value: ACCOUNT_TOKEN, revoked: signedOut.signal, reject: async () => {} } : undefined, }) let restoreFetch = () => {} @@ -49,6 +51,11 @@ export async function apply(ctx) { return } request.resume() + if (config?.signOutDuringSearch === true) { + // The sign-out withdraws the credential this request carries, which ends the request on the client side. + signedOut.abort() + return + } response.writeHead(200, { 'content-type': 'application/json' }) response.end(JSON.stringify({ results: [{ diff --git a/snapshots/session/web-search-account-signout/runtime.cordis.yml b/snapshots/session/web-search-account-signout/runtime.cordis.yml new file mode 100644 index 0000000000..d291c27192 --- /dev/null +++ b/snapshots/session/web-search-account-signout/runtime.cordis.yml @@ -0,0 +1,4 @@ +# The stand-in account signs out while the account-billed Search request is in flight. +- id: web-search-billing-fixture + config: + signOutDuringSearch: true diff --git a/snapshots/session/web-search-account-signout/session.v4.jsonl b/snapshots/session/web-search-account-signout/session.v4.jsonl new file mode 100644 index 0000000000..f6f31a5f0c --- /dev/null +++ b/snapshots/session/web-search-account-signout/session.v4.jsonl @@ -0,0 +1,22 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1785078727712,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the web_search tool exactly once to search for DSH sign-out snapshot, then reply with exactly DONE. Do not describe the results."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Use the web_search tool exactly once to search for DSH sign-out snapshot, then reply with exactly DONE. Do not describe the results."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"snapshot-other","model":"other-model"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"snapshot-other","model":"other-model"}} +{"type":"session/title","data":{"title":"Use the web_search tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"Search once, then reply DONE."},{"type":"tool-call","id":"call_00_signout","name":"web_search","arguments":"{\"queries\": [\"DSH sign-out snapshot\"]}"}],"source":{"kind":"model","provider":"snapshot-other","model":"other-model"},"id":"{{message:4}}"},"usage":{"inputTokens":100,"outputTokens":10,"cacheReadTokens":0},"stream":[{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699449132,"index":0,"dt":[],"texts":["Search once, then reply DONE."]},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788699449132,"index":1,"dt":[],"id":"call_00_signout","name":"web_search","args":["{\"queries\": [\"DSH sign-out snapshot\"]}"]},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Search once, then reply DONE."}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_signout","name":"web_search","arguments":"{\"queries\": [\"DSH sign-out snapshot\"]}"}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":10,"cacheReadTokens":0}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"finish","reason":{"kind":"tool-use"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_signout","name":"web_search","arguments":"{\"queries\": [\"DSH sign-out snapshot\"]}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_signout"},"toolCallId":"call_00_signout","content":[{"type":"text","text":"Error: The DeepSeek account signed out before this web request finished. Guide the user to sign in to DeepSeek again; the endpoint does not need changing."}],"isError":true,"id":"{{message:5}}"},"error":{"name":"WebError","code":"WEB_PROVIDER_ERROR"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The search failed because the account signed out; reply DONE."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"snapshot-other","model":"other-model"},"id":"{{message:6}}"},"usage":{"inputTokens":100,"outputTokens":10,"cacheReadTokens":0},"stream":[{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699449132,"index":0,"dt":[],"texts":["The search failed because the account signed out; reply DONE."]},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699449132,"index":1,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The search failed because the account signed out; reply DONE."}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":10,"cacheReadTokens":0}}},{"type":"chunk","time":1788699449132,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/web-search-account-signout/snapshot.yml b/snapshots/session/web-search-account-signout/snapshot.yml new file mode 100644 index 0000000000..bf9c21abec --- /dev/null +++ b/snapshots/session/web-search-account-signout/snapshot.yml @@ -0,0 +1,11 @@ +version: 1 +scenario: web-search-account-signout +profile: headless +composition: web-search-account-billing +recording: authored +header: + class: web-search-account-billing +environment: + # No DeepSeek API key, and a fixed DeepSeek origin for the account token. + DEEPSEEK_API_KEY: '' + DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic From 1baaf819d7adf5a43e0530ba3bd5619551653336 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 15:30:20 +0800 Subject: [PATCH 13/16] docs(llm-route-credential): use the established Chinese term for a withdrawn credential MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Chinese pages of the route credential change rendered "withdraw" as 收回. The bilingual pages on master render it as 撤回 in most places, so the seven pages this branch edited now use that term. The English pages are unchanged; only the Chinese hashes of the pairing records move. --- .../2026-09-17-account-provider-signout.i18n.yaml | 4 ++-- .../architecture/2026-09-17-account-provider-signout.zh.md | 4 ++-- .../2026-11-10-llm-route-credential-seam.i18n.yaml | 4 ++-- .../architecture/2026-11-10-llm-route-credential-seam.zh.md | 4 ++-- docs/subsystems/account.i18n.yaml | 2 +- docs/subsystems/account.zh.md | 2 +- docs/subsystems/llm-streaming.i18n.yaml | 2 +- docs/subsystems/llm-streaming.zh.md | 2 +- .../v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml | 2 +- .../v0.2.2-rc.2/llm-route-credential/guide.zh.md | 2 +- packages/llm/llm-deepseek/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek/README.zh.md | 4 ++-- packages/web/web-deepseek-api/README.i18n.yaml | 2 +- packages/web/web-deepseek-api/README.zh.md | 2 +- 14 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml index 0b8f4fca6a..75d406fe23 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.i18n.yaml @@ -10,10 +10,10 @@ zh: 61977c82d66ae9bf /agent-note-account-provider-and-active-request-cancellation/decision: en: 6f5463ecf88c1435 - zh: 2097b8829e410c6b + zh: 7c9e46f90c8ccffb /agent-note-account-provider-and-active-request-cancellation/alternatives-considered: en: 7ed93136cf11074a - zh: aea8dcf2e521a9c2 + zh: 1ee997e271e919ad /agent-note-account-provider-and-active-request-cancellation/consequences: en: 8fd00b6d69b380c0 zh: 3830dc3a93d5de3c diff --git a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md index a7a8d2d6fc..2fc0872a4b 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-account-provider-signout.zh.md @@ -14,11 +14,11 @@ Status: implemented 账号取消读取运行中 Agent 最近的 `Session.requestContext()`,不维护额外提供方字段。该已记录值在工具和重试阶段保留,随下一次绑定请求更新;空闲 Agent 不计入。新轮次首次准备期间,它仍可能指向上一轮的账号路由,因此退登也可能打断尚未绑定新请求的 API key 轮次。没有历史上下文的首请求若缺少账号凭据,会在传输前失败。 -本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的收回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。 +本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的撤回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。 ## Alternatives considered -历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。用登录级取消信号取代这条链路,会重复现有的 Agent 与 HTTP 取消;凭据的收回信号只是对它的补充。 +历史提供方集合会在轮次切换到 API Key 路由后仍错误取消它。当前设置会误判更早的在途请求。额外的提供方字段或模块级全局映射重复保存请求上下文中已有的信息。用登录级取消信号取代这条链路,会重复现有的 Agent 与 HTTP 取消;凭据的撤回信号只是对它的补充。 ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 3ea538f271..763a04ece1 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -10,10 +10,10 @@ zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: en: 339c58ce1afd8225 - zh: 00b0b683d6de2edc + zh: d82a5074d7849cc8 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: d6b2de393add9887 zh: b5351f9a49387bd6 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: en: 748f306d720ade43 - zh: 792386be47105525 + zh: c28734e1d072feb3 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index d025903ed3..b47687c8b8 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时收回凭据,该信号即中止。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 `@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。 @@ -44,4 +44,4 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route 新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 -退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登收回;路由插件的监听仍会取消 Agent 回合。 +退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。 diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index ff6e299f2a..d54fbdfdf8 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -7,7 +7,7 @@ zh: 5e0ac058b50036dc /deepseek-account/request-credentials: en: 8b2ab927576926cf - zh: c383046df37bfade + zh: a41a275c39103347 /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index 6624963d70..ce7e1c5f31 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,7 +8,7 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只收回自己释放的凭据。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。 按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责;比插件存活更久的请求通过其凭据的 `revoked` 信号结束,插件为该请求提供的失败回调随后取消这些工作。 diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index ec3c50fe81..d432290702 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -37,7 +37,7 @@ zh: fc99fe965acaabf3 /llm-streaming/the-model-request: en: a345a763b420ff1a - zh: 10937f0f9b040eea + zh: c3e0adef1b1036ef /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 67fa37b2f5..cd6ea6501b 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -533,7 +533,7 @@ interface LlmNativeAuth { } ``` -路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时收回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 +路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时撤回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 ```ts type-equiv /** diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml index 1e48e714c7..7577d27ae0 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml @@ -10,7 +10,7 @@ zh: 73bd5dfd53ed8d36 /deepseek-routes-publish-the-credential-web-consumers-reuse/change: en: 4e77c6f6c622beb2 - zh: 03f3756a54dcbfa8 + zh: 2c119f567ff411ff /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: en: 6d117f2dfd7593d0 zh: 1c1579fc7d0ccad0 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md index de47c7df60..712e402000 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md @@ -9,7 +9,7 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 ## 变更 -`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 收回信号。 +`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 撤回信号。 `@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 0495666d6b..76fde08e07 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -28,7 +28,7 @@ zh: 46f199ee79a8c5dc /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: en: bcb58fd33f59dbf2 - zh: ceafdef88eb66b30 + zh: ff512a17c15aeadf /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: f880b79feebb9e63 zh: 0dbbb2378e6f9af3 @@ -88,4 +88,4 @@ zh: bf838648f8ba4e62 /deepseek-ai-dsh-llm-deepseek/known-limitations-and-deferred-work/dev-note: en: ddc6cf85ac5d9520 - zh: f5dd039bb67ef8db + zh: d61436104184ce7c diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 0ae617f627..24595d9603 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -91,7 +91,7 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者收回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 +提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 ### 带 thinking 与图片的流式调用 @@ -220,4 +220,4 @@ loop 保留的响应块会追加到下一个请求,并保留其更早的可复 无。 -`deepseek-official` 仅使用配置的 API Key 引用;`deepseek-account` 仅在账号提供方允许的推理来源使用已保存的 DSH 授权。两条路由共享 Messages 传输,模型与文件设置独立配置。账号凭证缺失或不适用于目标时拒绝请求并提示登录;两条路由均不回退到另一凭证。Chat 和 Files 请求拒绝重定向。账号路由插件根据运行中 Agent 已记录的请求上下文负责退登取消,包括工具执行阶段;传输层接收现有请求的中止信号,并结束凭据已被收回的请求。 +`deepseek-official` 仅使用配置的 API Key 引用;`deepseek-account` 仅在账号提供方允许的推理来源使用已保存的 DSH 授权。两条路由共享 Messages 传输,模型与文件设置独立配置。账号凭证缺失或不适用于目标时拒绝请求并提示登录;两条路由均不回退到另一凭证。Chat 和 Files 请求拒绝重定向。账号路由插件根据运行中 Agent 已记录的请求上下文负责退登取消,包括工具执行阶段;传输层接收现有请求的中止信号,并结束凭据已被撤回的请求。 diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index db6f262828..6d2f73adfb 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -22,7 +22,7 @@ zh: 85d1b8408cf1f325 /deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures: en: e7a5d332ebababe7 - zh: 5020eabd799ebb5c + zh: 6ea098d53d4e9616 /deepseek-ai-dsh-web-deepseek-api/understand-the-implementation: en: 597dab3fe52fa59d zh: 4370d01d5a58f2f9 diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index 6243b8359b..3dbe337001 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -74,7 +74,7 @@ Search 与 Fetch 每次操作各自从同一份设置快照解析端点和凭据 Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 `maxResults`)、`need_content: false`,以及在 `sendOriginalQuestion` 未关闭时的 `ori_question`:发起会话中最近一条用户提示的文本,空白折叠后截取至 128 个字符。在会话之外或没有此类提示的搜索不发送该字段。提供者将 `results[].snippet` 映射为展示用摘录,将 `results[].summary` 映射为面向模型的摘录,并将可为 null 的 `date` 映射为可选的 `publishedAt`;`dsh-tool-web` 限制每条摘要的长度。空结果数组表示成功。Fetch 发送 `url`,以文本正文返回原始 Markdown,并报告 HTTP 状态 200,因为目标没有可用内容时 API 会返回错误状态。返回 URL 为请求 URL:API 不报告重定向后的最终 URL。 -单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。请求携带的凭据被收回时(例如账号退登通过授权的 `revoked` 信号收回),请求随即结束:以 `WEB_PROVIDER_ERROR` 失败并提供重新登录的指引,其他种类的凭据则指引用户在模型页面检查该凭据;调用方同时取消时仍为 `WEB_ABORTED`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。 +单独配置的基础地址无法解析时,该能力的提供者不可用;`count` 不在 1 至 50 之间时,Search 不可用。凭据缺失以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败;所需模型路由的设置无法解析时以 `WEB_PROVIDER_MISCONFIGURED` 失败,并点名解析器的失败原因、模型页面以及该能力的 `*BaseURL` 与 `*ApiKeyEnv`;取消使用 `WEB_ABORTED`;传输、HTTP 和响应格式错误使用 `WEB_PROVIDER_ERROR`。请求携带的凭据被撤回时(例如账号退登通过授权的 `revoked` 信号撤回),请求随即结束:以 `WEB_PROVIDER_ERROR` 失败并提供重新登录的指引,其他种类的凭据则指引用户在模型页面检查该凭据;调用方同时取消时仍为 `WEB_ABORTED`。重定向在联系目标前即被拒绝。Fetch API 的非成功状态表示抓取失败,不代表目标页面的状态。账号鉴权的 HTTP 401 响应只作废该请求实际发送的 token,并提供重新登录指引;更新的登录不受影响,凭据删除失败不会替换原 HTTP 错误。API 密钥失败与 HTTP 403 从不作废账号 token;其他请求失败指出端点及其来源:路由端点指导用户在模型页面检查该提供方的基础地址,或设置该能力的 `*BaseURL` 与 `*ApiKeyEnv`;单独配置指导用户修改或删除这两个字段。不会自动重试或回退至其他提供者。 ----- From 76d7a49e9fa1383d5cdf78bf67c38febcd88c70d Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 15:52:07 +0800 Subject: [PATCH 14/16] docs(upgrade-guide): move the route credential guide to v0.2.2-rc.3 master released 0.2.2-rc.3, which freezes docs/upgrade-guide/v0.2.2-rc.2. The guide of this unmerged change moves to the directory of the current root version, and the route credential Agent Note links to its new path. The guide text is unchanged. --- .../2026-11-10-llm-route-credential-seam.i18n.yaml | 4 ++-- .../architecture/2026-11-10-llm-route-credential-seam.md | 2 +- .../architecture/2026-11-10-llm-route-credential-seam.zh.md | 2 +- .../llm-route-credential/guide.i18n.yaml | 6 +++--- .../llm-route-credential/guide.md | 0 .../llm-route-credential/guide.zh.md | 0 6 files changed, 7 insertions(+), 7 deletions(-) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/llm-route-credential/guide.i18n.yaml (87%) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/llm-route-credential/guide.md (100%) rename docs/upgrade-guide/{v0.2.2-rc.2 => v0.2.2-rc.3}/llm-route-credential/guide.zh.md (100%) diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index 763a04ece1..c46edc0386 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -15,5 +15,5 @@ en: d6b2de393add9887 zh: b5351f9a49387bd6 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: - en: 748f306d720ade43 - zh: c28734e1d072feb3 + en: ff4e2a7346097e54 + zh: 7881f404099276b3 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index b41afa2b2b..fc30a5a383 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -42,6 +42,6 @@ The web providers consume publications. `web-deepseek-api` builds each operation ## Consequences -Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. +Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index b47687c8b8..b370391879 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -42,6 +42,6 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route ## 后果 -新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 +新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml similarity index 87% rename from docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml rename to docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml index 7577d27ae0..5a217379ea 100644 --- a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml @@ -1,13 +1,13 @@ # Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md /: en: f0cf30e5430471e8 zh: 2e6e871797dfdd6b /deepseek-routes-publish-the-credential-web-consumers-reuse: - en: f0139803159ee9c9 - zh: 73bd5dfd53ed8d36 + en: b5392bcd81f69488 + zh: 68cd945f2dde46af /deepseek-routes-publish-the-credential-web-consumers-reuse/change: en: 4e77c6f6c622beb2 zh: 2c119f567ff411ff diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.md rename to docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md diff --git a/docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.2/llm-route-credential/guide.zh.md rename to docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md From 9ce0c815b5e0a8183f55fb46a3018f6be716d862 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 18:08:28 +0800 Subject: [PATCH 15/16] refactor(deepseek-account): declare the account token header before its first use platformHeaders() reads ACCOUNT_TOKEN_HEADER about a hundred lines above the constant's declaration. The call only runs after the module has loaded, so behavior is unchanged; the declaration now sits with the module's imports. --- packages/account/deepseek-account/src/protocol.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/account/deepseek-account/src/protocol.ts b/packages/account/deepseek-account/src/protocol.ts index 2a0160e65e..7a3a46058a 100644 --- a/packages/account/deepseek-account/src/protocol.ts +++ b/packages/account/deepseek-account/src/protocol.ts @@ -2,6 +2,9 @@ import { z } from 'zod' import type { AccountNotificationEvent, AccountNotificationId, SignInErrorCode } from './types.ts' +/** Request header carrying the account token on every request the token authenticates. */ +export const ACCOUNT_TOKEN_HEADER = 'x-dsh-auth-token' + /** Protocol errors expose a stable code, never a response body or authorization URL. */ export class PlatformAuthError extends Error { /** @param code - safe error classification. */ @@ -161,9 +164,6 @@ export function requestNotificationEvent(origin: string, token: string, id: Acco }, signal) } -/** Request header carrying the account token on every request the token authenticates. */ -export const ACCOUNT_TOKEN_HEADER = 'x-dsh-auth-token' - // The grant is provider-owned; deployment requestHeaders cannot override it or the client identity. function accountHeaders(headers: Record, token: string): Record { return { ...headers, [ACCOUNT_TOKEN_HEADER]: token } From fc0abf3f37c6e137733b34293659bede1ecbf0cc Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 13 Nov 2026 19:51:35 +0800 Subject: [PATCH 16/16] refactor(llm): rename routeCredential to providerCredential Reviewers found `routeCredential` unclear. The method takes a provider route id, as `providerInfo()` and `providerRetryPolicy()` on the same adapter do, so the method and its types now carry that prefix: `LlmAdapter.providerCredential()`, `LlmRuntime.providerCredential()`, `ProviderCredential`, `ProviderCredentialGrant`, and `DeepSeekProviderCredentialOptions`. Behavior is unchanged. master never had the old names, so no released surface is renamed; the upgrade guide for this change names the new ones. --- ...ch-offered-by-provider-readiness.i18n.yaml | 4 ++-- ...eb-search-offered-by-provider-readiness.md | 2 +- ...search-offered-by-provider-readiness.zh.md | 2 +- ...026-10-29-web-provider-selection.i18n.yaml | 4 ++-- .../2026-10-29-web-provider-selection.md | 4 ++-- .../2026-10-29-web-provider-selection.zh.md | 4 ++-- ...-11-10-llm-route-credential-seam.i18n.yaml | 8 +++---- .../2026-11-10-llm-route-credential-seam.md | 6 ++--- ...2026-11-10-llm-route-credential-seam.zh.md | 6 ++--- ...-10-15-deepseek-search-fetch-api.i18n.yaml | 4 ++-- .../2026-10-15-deepseek-search-fetch-api.md | 2 +- ...2026-10-15-deepseek-search-fetch-api.zh.md | 2 +- docs/subsystems/account.i18n.yaml | 4 ++-- docs/subsystems/account.md | 2 +- docs/subsystems/account.zh.md | 2 +- docs/subsystems/llm-streaming.i18n.yaml | 8 +++---- docs/subsystems/llm-streaming.md | 18 +++++++------- docs/subsystems/llm-streaming.zh.md | 18 +++++++------- .../llm-route-credential/guide.i18n.yaml | 12 +++++----- .../v0.2.2-rc.3/llm-route-credential/guide.md | 10 ++++---- .../llm-route-credential/guide.zh.md | 10 ++++---- .../extensions/tool-cordis/src/api-catalog.ts | 24 +++++++++---------- .../llm/llm-deepseek-account/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek-account/README.md | 2 +- .../llm/llm-deepseek-account/README.zh.md | 2 +- .../tests/provider.spec.ts | 6 ++--- .../llm/llm-deepseek-api-key/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek-api-key/README.md | 2 +- .../llm/llm-deepseek-api-key/README.zh.md | 2 +- .../tests/discovery.spec.ts | 4 ++-- packages/llm/llm-deepseek/README.i18n.yaml | 4 ++-- packages/llm/llm-deepseek/README.md | 2 +- packages/llm/llm-deepseek/README.zh.md | 2 +- packages/llm/llm-deepseek/src/adapter.ts | 4 ++-- packages/llm/llm-deepseek/src/index.ts | 2 +- packages/llm/llm-deepseek/src/types.ts | 14 +++++------ .../tests/route-credential.spec.ts | 6 ++--- packages/llm/llm/src/index.ts | 10 ++++---- packages/llm/llm/src/types.ts | 8 +++---- packages/llm/llm/tests/topology.spec.ts | 18 +++++++------- .../web/web-deepseek-api/README.i18n.yaml | 12 +++++----- packages/web/web-deepseek-api/README.md | 8 +++---- packages/web/web-deepseek-api/README.zh.md | 8 +++---- packages/web/web-deepseek-api/src/index.ts | 4 ++-- .../web/web-deepseek-api/src/transport.ts | 4 ++-- packages/web/web-deepseek-api/tests/routes.ts | 10 ++++---- .../web/web-search-deepseek/README.i18n.yaml | 8 +++---- packages/web/web-search-deepseek/README.md | 4 ++-- packages/web/web-search-deepseek/README.zh.md | 4 ++-- packages/web/web-search-deepseek/src/index.ts | 10 ++++---- .../web/web-search-deepseek/src/provider.ts | 4 ++-- .../tests/deepseek.spec.ts | 10 ++++---- scripts/gen-cordis-catalog.ts | 2 +- scripts/type-equiv.manifest.json | 4 ++-- 54 files changed, 172 insertions(+), 172 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml index 8344fd2eb2..24af686ace 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.i18n.yaml @@ -9,8 +9,8 @@ en: 32ba2b2b42e8deb5 zh: 6a6532561f81b8e2 /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/decision: - en: 8513348797d8b8c3 - zh: 13d4066e07db0fb9 + en: 023c6db0af5f9424 + zh: 7bdf40c49e381ee3 /agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered: en: 6da221f6b821ea44 zh: b15774011abed7ed diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md index ed8c3c2803..72b06f6f77 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.md @@ -13,7 +13,7 @@ English | [中文](2026-09-27-web-search-offered-by-provider-readiness.zh.md) Each role of the web capability seam owns one part of a per-step check: - **Service Definition.** `WebSearchProvider` and `WebFetchProvider` have an optional `ready(llmProvider)` that answers whether an operation made for a model request on that chat route has a credential to send. It checks configuration only and makes no network calls. `ctx.web.searchReady(llmProvider?)` and `ctx.web.fetchReady(llmProvider?)` resolve the provider with the same rules as `search()` and `fetch()` and return its answer. A provider without `ready()` counts as ready, and a selection failure answers true because the operation reports that failure as a structured `WebError`. -- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.routeCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section. +- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.providerCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section. - **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` with [step activation conditions](../../../../packages/core/tools/README.md#conditional-tools) that ask `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route of the step's model selection. The agent loop resolves conditions before it assembles the step, so the declared tools, the `tool:web_search` and `tool:web_fetch` prompt sections, PTC program bindings, and dispatch all read the same admitted set. The route decides only whether the account token is checked before the API key, which happens on the `deepseek-account` route; an API key counts on every route, so a conversation on another provider's model is offered the DeepSeek web tools whenever a DeepSeek key is configured. A Search or Fetch API capability with its own YAML fields ignores the route and is ready exactly when its own key is configured. diff --git a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md index 96277e8532..0712cacc50 100644 --- a/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-27-web-search-offered-by-provider-readiness.zh.md @@ -13,7 +13,7 @@ Status: implemented web 能力 seam 的每个角色各负责逐步骤检查的一部分: - **Service Definition。** `WebSearchProvider` 与 `WebFetchProvider` 有一个可选的 `ready(llmProvider)`,回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。它只检查配置,不发起网络调用。`ctx.web.searchReady(llmProvider?)` 与 `ctx.web.fetchReady(llmProvider?)` 按与 `search()`、`fetch()` 相同的规则解析提供方并返回其回答。没有 `ready()` 的提供方视为就绪;选择失败时回答 true,因为对应操作会把该失败报告为结构化 `WebError`。 -- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.routeCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。 +- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.providerCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。 - **Consumer。** `dsh-tool-web` 注册 `web_search` 与 `web_fetch` 时各带一个[步骤激活条件](../../../../packages/core/tools/README.zh.md#conditional-tools),以该步骤模型选择的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`。agent loop 在组装该步骤之前解析各条件,因此声明的工具、`tool:web_search` 与 `tool:web_fetch` 提示词段落、PTC 程序绑定与派发都读取同一个准入集合。 路由只决定是否先检查账号 token 再检查 API 密钥,这发生在 `deepseek-account` 路由上;API 密钥在每条路由上都算数,因此只要配置了 DeepSeek 密钥,使用其他提供方模型的对话也会获得 DeepSeek Web 工具。在 YAML 中设置了单独字段的 Search 或 Fetch API 能力不看路由,恰在其自身密钥已配置时就绪。 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml index 4c0e201093..9c22957426 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml @@ -18,8 +18,8 @@ en: 9d68ffca5c8be681 zh: 36bb661f98de0ebb /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/credential-resolution: - en: 6650000bd819e2ce - zh: 9e141db8bc3f51f8 + en: aa5522b172d2c580 + zh: 04561ffe78d69ff4 /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections: en: 5fcd3319fbceed1d zh: 20771646b9c36fa6 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md index 42aca3fdbc..3d11c29843 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md @@ -30,11 +30,11 @@ The Search and Fetch APIs read one `web-deepseek-api` namespace, and each resolv Each of Search and Fetch has a billing setting, `web-deepseek-api.searchBilling` or `fetchBilling`, which the settings page edits as a **Billing** menu under the selected API. The default, `auto`, follows the DeepSeek credential of the conversation; `account` sends only the signed-in account's token and `api-key` only the API key, without falling back to the other. The conversation's route is the `provider` of the initiating Session's latest request context, which account sign-out also reads; `ready()` uses the route of the model request being prepared, so readiness and execution resolve the same plan. -The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.routeCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint. +The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.providerCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint. A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`fetchBaseURL` or `fetchApiKeyEnv` for Fetch) instead, whatever its billing, always sends the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) to its `*BaseURL` (the official base when unset) and never the account token, so an intranet or third-party endpoint receives only the key chosen for it. Each capability has its own fields because a deployment can serve search and fetch from different gateways. These fields are YAML-only, and an empty value counts as unset. Stored values of fields outside the schema, including `baseURL`, `apiKeyEnv`, and `apiKey`, load without schema errors and have no effect. -The DeepSeek model routes publish the credential they send through `ctx.llm.routeCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key. +The DeepSeek model routes publish the credential they send through `ctx.llm.providerCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key. ### Defaults and stored selections diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md index 58bb904d33..cb3c0e67c0 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md @@ -30,11 +30,11 @@ Search 与 Fetch API 读取同一个 `web-deepseek-api` namespace,并各自解 Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling` 或 `fetchBilling`,设置页在选中的 API 下方以**计费方式**下拉框编辑它。默认值 `auto` 跟随会话的 DeepSeek 凭据;`account` 只发送已登录账号的令牌,`api-key` 只发送 API 密钥,都不回退到另一种凭据。会话的路由是发起会话最近一次请求上下文的 `provider`,账号退出登录读取的也是它;`ready()` 使用正在准备的模型请求的路由,因此就绪判断与执行解析出相同的方案。 -账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由通过 `ctx.llm.routeCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。 +账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由通过 `ctx.llm.providerCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。 在 YAML 中设置了非空 `searchBaseURL` 或 `searchApiKeyEnv`(Fetch 为 `fetchBaseURL` 或 `fetchApiKeyEnv`)的能力,则无论计费方式如何,始终把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为官方基础地址),从不发送账号令牌,因此内网或第三方端点只收到为它选择的密钥。每个能力有自己的字段,因为一个部署可以由不同网关提供搜索和抓取。这些字段只能在 YAML 中设置,空值视为未设置。schema 之外字段的已保存值,包括 `baseURL`、`apiKeyEnv` 和 `apiKey`,可以加载而不产生 schema 错误,且不生效。 -DeepSeek 模型路由通过 `ctx.llm.routeCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 +DeepSeek 模型路由通过 `ctx.llm.providerCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。 ### 默认值与已保存的选择 diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml index c46edc0386..a5d7ec13b7 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.i18n.yaml @@ -9,11 +9,11 @@ en: 9665e1879893fe76 zh: 9da30ad0be6fc38d /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision: - en: 339c58ce1afd8225 - zh: d82a5074d7849cc8 + en: aaa2d2c7202408d4 + zh: 134987da042fd07b /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered: en: d6b2de393add9887 zh: b5351f9a49387bd6 /agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences: - en: ff4e2a7346097e54 - zh: 7881f404099276b3 + en: df942606f0d31fa5 + zh: cb1f21dd7f60ab7f diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md index fc30a5a383..c0544bdcfb 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md @@ -10,7 +10,7 @@ Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/ ## Decision -`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.routeCredential(provider)` publishes a `RouteCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. +`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.providerCredential(provider)` publishes a `ProviderCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `ProviderCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request. `@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The transport runs each model request and its file operations under the grant's `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers. @@ -18,7 +18,7 @@ The route plugins own credentials. `llm-deepseek-api-key` reads its key through `@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name. -The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.routeCredential('deepseek-official')` and `routeCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. +The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.providerCredential('deepseek-official')` and `providerCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service. ## Alternatives considered @@ -42,6 +42,6 @@ The web providers consume publications. `web-deepseek-api` builds each operation ## Consequences -Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `routeCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. +Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `providerCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`. A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns. diff --git a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md index b370391879..2282d44a68 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.routeCredential(provider)` 发布一个 `RouteCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 +`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.providerCredential(provider)` 发布一个 `ProviderCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `ProviderCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。 `@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。 @@ -18,7 +18,7 @@ Status: implemented `@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token、`reject()` 和 `revoked` 信号;`reject()` 仅在授权仍一致时删除它并隔离存储失败,`revoked` 由服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。 -Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.routeCredential('deepseek-official')` 和 `routeCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 +Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.providerCredential('deepseek-official')` 和 `providerCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。 ## 考虑过的替代方案 @@ -42,6 +42,6 @@ Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.route ## 后果 -新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `routeCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 +新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `providerCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。 退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。 diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml index d683eb8924..4493a15e53 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml @@ -27,8 +27,8 @@ en: 0dcc97d8105fab60 zh: d80d40ae3a0c601d /agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered: - en: 88708dc170d3e77b - zh: e04536e494769d9c + en: 021a4b08ad534b36 + zh: e98e1f65e50a568b /agent-note-direct-deepseek-search-and-fetch-apis/consequences: en: 7ec21c5b1124e5f8 zh: af769dbdb4face9f diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md index 18c1946887..f6ed9ab69f 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md @@ -52,7 +52,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request **Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider. -**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.routeCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent. +**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.providerCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent. **Split Search and Fetch into separate packages.** The guide serves both APIs from one base with one credential; separate packages would duplicate settings that address one deployment. Independent selection does not require separate packages, because each API registers its own provider id. Each operation lives in its own module, so either API can change without the other. diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md index 324fcd1d0c..fb88219a08 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md @@ -52,7 +52,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek **把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。 -**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.routeCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。 +**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.providerCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。 **把 Search 和 Fetch 拆成两个包。** 指南从同一基础地址、以同一份凭据提供两个 API;拆成两个包会让指向同一部署的设置重复出现。分别选择不需要拆包,因为每个 API 注册自己的提供方 id。每种操作位于独立模块,任一 API 都可以单独修改。 diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index d54fbdfdf8..665e916b45 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -6,8 +6,8 @@ en: 2302e2999588bac3 zh: 5e0ac058b50036dc /deepseek-account/request-credentials: - en: 8b2ab927576926cf - zh: a41a275c39103347 + en: c5fb32307f841c66 + zh: 8ed40c0c99884301 /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md index a550fc9d13..d064016326 100644 --- a/docs/subsystems/account.md +++ b/docs/subsystems/account.md @@ -8,7 +8,7 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun ## Request credentials -`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released. +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. The `deepseek-account` model route publishes this credential through `ctx.llm.providerCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released. Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`; a request that outlives the plugin ends through its credential's `revoked` signal, and the plugin's failure callback for that request cancels the work. diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index ce7e1c5f31..ccbdbd0510 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,7 +8,7 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.providerCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。 按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责;比插件存活更久的请求通过其凭据的 `revoked` 信号结束,插件为该请求提供的失败回调随后取消这些工作。 diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index d432290702..dbb124b198 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -36,8 +36,8 @@ en: 58dec2259b0b1c6f zh: fc99fe965acaabf3 /llm-streaming/the-model-request: - en: a345a763b420ff1a - zh: c3e0adef1b1036ef + en: 61d4131601adbc32 + zh: b83156c875d29b89 /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 @@ -48,5 +48,5 @@ en: 8c140f9c5a799f01 zh: f66b895594247e92 /llm-streaming/service-and-provider-contracts: - en: 4d210152ca139cb0 - zh: d131e11d95666342 + en: 81b4ede66c5e906d + zh: 2ad0ddb1a32e3167 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 2b0427644f..1e93b92f64 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -527,14 +527,14 @@ interface LlmNativeAuth { } ``` -A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.routeCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. A grant whose owner can withdraw the credential while requests carry it, as an account sign-out does, has a `revoked` signal: the consumer runs each request it authenticates under that signal and reports a request the signal ended as its own failure, not as the caller's cancellation. +A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.providerCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. A grant whose owner can withdraw the credential while requests carry it, as an account sign-out does, has a `revoked` signal: the consumer runs each request it authenticates under that signal and reports a request the signal ended as its own failure, not as the caller's cancellation. ```ts type-equiv /** * One credential released for one destination. Host-only: it carries the * secret, so it never crosses a Remote boundary and never enters a log. */ -interface RouteCredentialGrant { +interface ProviderCredentialGrant { /** * Request headers carrying the credential as the route's own protocol * expects it, such as `x-api-key` for an API key. Consumers speaking that @@ -568,11 +568,11 @@ interface RouteCredentialGrant { /** * The credential one registered provider route currently sends, answered by * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * and choose no header names. `ctx.llm.providerCredential()` resolves a new value * per call from one configuration generation; a caller keeps it for one * operation only. */ -interface RouteCredential { +interface ProviderCredential { /** Kind of credential the route sends. */ readonly kind: LlmCredentialKind /** @@ -603,7 +603,7 @@ interface RouteCredential { * @param signal - cancellation for the lookup. * @returns the released credential, or `undefined`. */ - resolve(endpoint: string, signal?: AbortSignal): Promise + resolve(endpoint: string, signal?: AbortSignal): Promise } ``` @@ -950,7 +950,7 @@ The [wire reference](../deepseek-llm-api-wire-extensions.md) defines the exact r `LlmAdapter` is the provider contract: subclass, implement `stream()`, and register one adapter instance with `ctx.llm.registerAdapter(providers, adapter)`. `GenerateOptions.provider` selects the registered adapter; `GenerateOptions.model` is passed to that adapter and need not be registered at lifecycle start. Duplicate provider routes fail atomically. Optional `providerRetryPolicy()` is captured per route with normal defaults, while `providerInfo()` and asynchronous `listModels()` feed `LlmRuntime.listProviders()` / `listModels()` with detached selector metadata. That catalog is advisory rather than a request whitelist: the adapter remains authoritative and may accept unlisted model ids. One asynchronous `resolveModel()` query returns exact model identity plus optional correctness-sensitive context capacity, an adapter-configured `defaultMaxTokens`, and ordered model-owned reasoning ids with an optional deployment default; absent fields mean unavailable metadata or provider-owned behavior, not invalid catalog membership. The resolver receives optional cancellation and must settle promptly after abort. `LlmRuntime.resolveModelInfo()` validates and detaches the aggregate. At the final adapter boundary, `resolveCallConfig()` materializes the output default only when `maxTokens` is absent and validates and materializes reasoning, so direct calls cannot bypass either configured behavior; direct dispatch captures one registration before awaiting that resolution. The agent loop instead uses `prepareCall()` to keep the same registration across model resolution, durable header logging, and dispatch, retain detached context metadata from that exact lookup, and report which config fields the adapter defaulted. Adapter lookup happens at the terminal continuation of the `llm/stream` waterfall, so a listener may short-circuit the call or route a mutable one-shot request before lookup. AgentLoop observes a request attempt once the outer waterfall returns a stream handle; that limited boundary does not prove a lazy terminal adapter was constructed or began provider I/O. The `block-start` / `block-end` `index` correlation and the assembler together mean an adapter only has to emit well-formed chunks — block reassembly is not each adapter's problem. [architecture.md](../architecture.md#turn-flow) shows where `ctx.llm.stream()` and the `llm/stream` waterfall sit in one turn. -Optional `routeCredential()` publishes the credential a route currently sends, with the route's base URL, its kind, and an optional credential reference. `LlmRuntime.routeCredential(provider)` forwards to the owning adapter: an unregistered route answers `undefined`, because callers ask about routes a conversation named earlier, and a registered route whose configuration does not resolve propagates the adapter's failure. The DeepSeek web providers read it to call the deployment of the conversation's route with that route's credential, so no consumer reads another plugin's configuration or chooses its header names. +Optional `providerCredential()` publishes the credential a route currently sends, with the route's base URL, its kind, and an optional credential reference. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter: an unregistered route answers `undefined`, because callers ask about routes a conversation named earlier, and a registered route whose configuration does not resolve propagates the adapter's failure. The DeepSeek web providers read it to call the deployment of the conversation's route with that route's credential, so no consumer reads another plugin's configuration or chooses its header names. ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ @@ -1028,7 +1028,7 @@ declare abstract class LlmAdapter { * @param _provider - a route passed to `registerAdapter()` for this instance. * @returns the route's current credential, or `undefined` when the route publishes none. */ - routeCredential(_provider: string): RouteCredential | undefined; + providerCredential(_provider: string): ProviderCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1216,9 +1216,9 @@ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): * which may no longer be mounted; a registered route whose configuration * does not resolve propagates the adapter's failure. * @param provider - provider route whose credential is wanted. - * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. */ -routeCredential(provider: string): RouteCredential | undefined +providerCredential(provider: string): ProviderCredential | undefined /** * Resolve the exact text one durable file occurrence contributes to every diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index cd6ea6501b..2e8707f13a 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -533,14 +533,14 @@ interface LlmNativeAuth { } ``` -路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.routeCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时撤回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 +路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.providerCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时撤回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 ```ts type-equiv /** * One credential released for one destination. Host-only: it carries the * secret, so it never crosses a Remote boundary and never enters a log. */ -interface RouteCredentialGrant { +interface ProviderCredentialGrant { /** * Request headers carrying the credential as the route's own protocol * expects it, such as `x-api-key` for an API key. Consumers speaking that @@ -574,11 +574,11 @@ interface RouteCredentialGrant { /** * The credential one registered provider route currently sends, answered by * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * and choose no header names. `ctx.llm.providerCredential()` resolves a new value * per call from one configuration generation; a caller keeps it for one * operation only. */ -interface RouteCredential { +interface ProviderCredential { /** Kind of credential the route sends. */ readonly kind: LlmCredentialKind /** @@ -609,7 +609,7 @@ interface RouteCredential { * @param signal - cancellation for the lookup. * @returns the released credential, or `undefined`. */ - resolve(endpoint: string, signal?: AbortSignal): Promise + resolve(endpoint: string, signal?: AbortSignal): Promise } ``` @@ -956,7 +956,7 @@ interface LlmCallConfigAdapterDefaults { `LlmAdapter` 是提供方约定:创建子类、实现 `stream()`,再用 `ctx.llm.registerAdapter(providers, adapter)` 注册一个适配器实例。`GenerateOptions.provider` 选择已注册适配器;`GenerateOptions.model` 会传给该适配器,无需在生命周期启动时注册。重复提供方路由会原子失败。可选的 `providerRetryPolicy()` 会按路由捕获并填入 normal 默认值,`providerInfo()` 与异步 `listModels()` 方法则为 `LlmRuntime.listProviders()` / `listModels()` 提供分离的 selector 元数据。该目录仅供参考,不是请求白名单:适配器仍是权威,并可接受未列出的模型 id。单次异步 `resolveModel()` 查询返回确切模型身份,以及可选的对正确性敏感的上下文容量、适配器配置的 `defaultMaxTokens`、由模型持有的有序推理强度 ID 和可选的部署默认值;字段缺失表示元数据不可用或保留提供方持有的行为,而不表示目录成员关系无效。解析器会接收可选的取消信号,并且必须在信号中止后迅速完成结算。`LlmRuntime.resolveModelInfo()` 会校验聚合结果并返回分离值。在最终适配器边界,`resolveCallConfig()` 仅在 `maxTokens` 缺失时填入输出默认值,并校验和填入推理强度,因此直接调用也无法绕过任何一项已配置行为;直接分派会在等待解析前捕获一项适配器注册。agent loop 则使用 `prepareCall()`,使模型解析、请求头持久记录和分派全程使用同一项注册,保留来自同一次查询的分离上下文元数据,并报告适配器填入的配置字段。适配器查找发生在 `llm/stream` waterfall 的终端 continuation,因此 listener 可以在查找前短路调用,或路由一个可变的一次性请求。AgentLoop 在外层 waterfall 返回流句柄时观察到一次请求尝试;这个有限边界不能证明惰性终端适配器已构造完成或开始提供方 I/O。`block-start` / `block-end` 的 `index` 关联与 assembler 共同意味着适配器只需 emit 格式正确的分片——块重组不是每个适配器各自的问题。`ctx.llm.stream()` 与 `llm/stream` waterfall 在一个轮次中的位置见 [architecture.md](../architecture.zh.md#turn-flow)。 -可选的 `routeCredential()` 发布路由当前发送的凭据,连同路由的基础地址、凭据种类和可选的凭据引用。`LlmRuntime.routeCredential(provider)` 转发给拥有该路由的适配器:未注册的路由回答 `undefined`,因为调用方询问的是会话早先命名的路由;已注册但配置无法解析的路由则传播适配器的失败。DeepSeek Web 提供方据此用会话路由的凭据调用同一部署,因此没有消费方需要读取其他插件的配置或自行选择请求头名称。 +可选的 `providerCredential()` 发布路由当前发送的凭据,连同路由的基础地址、凭据种类和可选的凭据引用。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器:未注册的路由回答 `undefined`,因为调用方询问的是会话早先命名的路由;已注册但配置无法解析的路由则传播适配器的失败。DeepSeek Web 提供方据此用会话路由的凭据调用同一部署,因此没有消费方需要读取其他插件的配置或自行选择请求头名称。 ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ @@ -1034,7 +1034,7 @@ declare abstract class LlmAdapter { * @param _provider - a route passed to `registerAdapter()` for this instance. * @returns the route's current credential, or `undefined` when the route publishes none. */ - routeCredential(_provider: string): RouteCredential | undefined; + providerCredential(_provider: string): ProviderCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1222,9 +1222,9 @@ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): * which may no longer be mounted; a registered route whose configuration * does not resolve propagates the adapter's failure. * @param provider - provider route whose credential is wanted. - * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. */ -routeCredential(provider: string): RouteCredential | undefined +providerCredential(provider: string): ProviderCredential | undefined /** * Resolve the exact text one durable file occurrence contributes to every diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml index 5a217379ea..ce61c10cdf 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.i18n.yaml @@ -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.3/llm-route-credential/guide.md /: - en: f0cf30e5430471e8 - zh: 2e6e871797dfdd6b + en: 56fc7afd90f0fcde + zh: 0b441fc159f25bcf /deepseek-routes-publish-the-credential-web-consumers-reuse: en: b5392bcd81f69488 zh: 68cd945f2dde46af /deepseek-routes-publish-the-credential-web-consumers-reuse/change: - en: 4e77c6f6c622beb2 - zh: 2c119f567ff411ff + en: 7568433b72e2633b + zh: dcd4c6deb72da3a4 /deepseek-routes-publish-the-credential-web-consumers-reuse/migration: - en: 6d117f2dfd7593d0 - zh: 1c1579fc7d0ccad0 + en: 0632d7c9ffce1675 + zh: a8b4d67f469eaee7 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md index f8dcf10eec..7b4b539fb7 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "DeepSeek model routes publish their credential through ctx.llm.routeCredential(); the llm-deepseek credential helpers, the route plugins' config exports, and account Agent inspection are removed." +description: "DeepSeek model routes publish their credential through ctx.llm.providerCredential(); the llm-deepseek credential helpers, the route plugins' config exports, and account Agent inspection are removed." --- # DeepSeek routes publish the credential web consumers reuse @@ -9,7 +9,7 @@ English | [中文](guide.zh.md) ## Change -`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, an optional `reject()`, and an optional `revoked` withdrawal signal. +`LlmAdapter.providerCredential(provider)` and `LlmRuntime.providerCredential(provider)` publish a route's current credential as a `ProviderCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `ProviderCredentialGrant` with protocol headers, the bare value, an optional `reject()`, and an optional `revoked` withdrawal signal. `@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional. @@ -17,13 +17,13 @@ English | [中文](guide.zh.md) `@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. A sign-out aborts released credentials' `revoked` signal, ending in-flight account requests: model requests outside a turn fail with `ACCOUNT_SIGN_IN_REQUIRED`, Search and Fetch with `WEB_PROVIDER_ERROR`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`. -`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. +`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.providerCredential()`, so an adapter registered under a DeepSeek route id that publishes no credential, or a credential of the other kind, counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`. ## Migration -1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.routeCredential(provider)`, and run each request under the grant's `revoked` signal. +1. Replace the removed `llm-deepseek` helpers: read keys with `resolveCredentialRef` and `credentialRefConfigured` from `@deepseek-ai/dsh-credentials` and validate them with `assertUsableApiKey`; read account credentials with `ctx.deepseekAccount.resolveRequestCredential(url)` and invalidate through the returned `reject()`. To reuse a mounted route's credential and endpoint, call `ctx.llm.providerCredential(provider)`, and run each request under the grant's `revoked` signal. 2. In custom `DeepSeekAdapter` or `registerDeepSeekProvider` consumers, return `undefined` from `resolveAuth` when no credential exists, add `value` to every `DeepSeekRequestAuth`, supply `missingCredential` for a route-specific failure, and declare `credential` to publish the route's credential. Pass credential headers, not a token, to `createModelListingCache`. 3. Replace imports of the route plugins' config exports with the plugins' own `Config`, and read a route's endpoint from its published credential instead of its resolver. 4. Make `deepseekAccount` stand-ins used by the account route or the web providers implement `resolveRequestCredential`, returning a `revoked` signal; stand-ins that supplied `ctx.agents` for `hasRunningAccountTasks()` register a report instead. 5. Update workspace references to `packages/account/deepseek-account`; the npm package name, Remote namespace, and configuration keys are unchanged. -6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `RouteCredentialGrant`. +6. Replace `resolveAccountToken` and `rejectAccountToken` in `DeepSeekSearchProviderOptions` with `resolveAccountCredential` returning a `ProviderCredentialGrant`. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md index 712e402000..6e6705bfeb 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己的凭据;移除 llm-deepseek 的凭据辅助函数、路由插件的配置导出和账号服务对 Agent 的检查。" +description: "DeepSeek 模型路由通过 ctx.llm.providerCredential() 发布自己的凭据;移除 llm-deepseek 的凭据辅助函数、路由插件的配置导出和账号服务对 Agent 的检查。" --- # DeepSeek 路由发布 Web 消费方复用的凭据 @@ -9,7 +9,7 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 ## 变更 -`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 撤回信号。 +`LlmAdapter.providerCredential(provider)` 与 `LlmRuntime.providerCredential(provider)` 把路由当前的凭据发布为 `ProviderCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `ProviderCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值、可选的 `reject()`,以及可选的 `revoked` 撤回信号。 `@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。 @@ -17,13 +17,13 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己 `@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。退登会中止已释放凭据的 `revoked` 信号,从而结束在途的账号请求:回合之外的模型请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,Search 与 Fetch 以 `WEB_PROVIDER_ERROR` 失败。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。 -`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 +`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.providerCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据、或发布另一种凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。 ## 迁移 -1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.routeCredential(provider)`,并让每个请求受授权的 `revoked` 信号约束。 +1. 替换被移除的 `llm-deepseek` 辅助函数:用 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 与 `credentialRefConfigured` 读取密钥并用 `assertUsableApiKey` 校验;用 `ctx.deepseekAccount.resolveRequestCredential(url)` 读取账号凭据并通过返回的 `reject()` 作废。要复用已挂载路由的凭据和端点,调用 `ctx.llm.providerCredential(provider)`,并让每个请求受授权的 `revoked` 信号约束。 2. 在自定义的 `DeepSeekAdapter` 或 `registerDeepSeekProvider` 消费方中,没有凭据时让 `resolveAuth` 返回 `undefined`,为每个 `DeepSeekRequestAuth` 加上 `value`,为路由专属的失败提供 `missingCredential`,并声明 `credential` 以发布路由凭据。向 `createModelListingCache` 传递凭据请求头而不是 token。 3. 用路由插件自身的 `Config` 替换对其配置导出的导入,并从路由发布的凭据而非其解析函数读取端点。 4. 让账号路由或 Web 提供方使用的 `deepseekAccount` 替身实现 `resolveRequestCredential` 并返回 `revoked` 信号;为 `hasRunningAccountTasks()` 提供 `ctx.agents` 的替身改为注册报告。 5. 把工作区引用更新为 `packages/account/deepseek-account`;npm 包名、Remote 命名空间和配置键均不变。 -6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `RouteCredentialGrant` 的 `resolveAccountCredential`。 +6. 把 `DeepSeekSearchProviderOptions` 中的 `resolveAccountToken` 与 `rejectAccountToken` 替换为返回 `ProviderCredentialGrant` 的 `resolveAccountCredential`。 diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 45aa44dd40..bba09726ca 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2229,10 +2229,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'dimensions and byte target used by the adapter\'s request serializer.', }, { - signature: 'routeCredential(provider: string): RouteCredential | undefined', + signature: 'providerCredential(provider: string): ProviderCredential | undefined', description: 'Resolve the credential one registered route currently sends, through its owning adapter. An unregistered route answers `undefined` rather than throwing because callers ask about routes a conversation named earlier, which may no longer be mounted; a registered route whose configuration does not resolve propagates the adapter\'s failure.', parameters: [{ name: 'provider', description: 'provider route whose credential is wanted.' }], - returns: 'the route credential, or `undefined` when the route is unregistered or publishes none.', + returns: 'the route\'s credential, or `undefined` when the route is unregistered or publishes none.', }, { signature: 'fileRequestText(ref: FileAttachmentRef): string', @@ -7599,7 +7599,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmAdapter', - declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n routeCredential(_provider: string): RouteCredential | undefined;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', + declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n providerCredential(_provider: string): ProviderCredential | undefined;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', }, { name: 'LlmAttemptId', @@ -7695,7 +7695,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmRuntime', - declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n routeCredential(provider: string): RouteCredential | undefined;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, signa /* …truncated — full shape in source */', + declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n providerCredential(provider: string): ProviderCredential | undefined;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, /* …truncated — full shape in source */', }, { name: 'LocalAtInput', @@ -8501,6 +8501,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'PromptSubmitResult', declaration: 'export type PromptSubmitResult = {\n text: string;\n context?: readonly string[];\n drop?: undefined;\n} | {\n drop: string;\n text?: undefined;\n context?: undefined;\n};', }, + { + name: 'ProviderCredential', + declaration: 'export interface ProviderCredential {\n readonly kind: LlmCredentialKind;\n readonly baseURL: string;\n readonly reference?: string;\n configured(endpoint: string): Promise;\n resolve(endpoint: string, signal?: AbortSignal): Promise;\n}', + }, + { + name: 'ProviderCredentialGrant', + declaration: 'export interface ProviderCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}', + }, { name: 'ProviderRequestId', declaration: 'export type ProviderRequestId = Branded<\'ProviderRequestId\'>;', @@ -8789,14 +8797,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ReviewVerdict', declaration: 'export type ReviewVerdict = \'approved\' | \'changes-requested\' | \'commented\' | \'dismissed\';', }, - { - name: 'RouteCredential', - declaration: 'export interface RouteCredential {\n readonly kind: LlmCredentialKind;\n readonly baseURL: string;\n readonly reference?: string;\n configured(endpoint: string): Promise;\n resolve(endpoint: string, signal?: AbortSignal): Promise;\n}', - }, - { - name: 'RouteCredentialGrant', - declaration: 'export interface RouteCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}', - }, { name: 'RpcId', declaration: 'export type RpcId = Branded<\'rpc-id\'>;', diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index 0b1592817f..ab9e5e1b82 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -9,8 +9,8 @@ en: 8fa1148e0ee9d351 zh: 634ec9d79d5ffbf0 /deepseek-ai-dsh-llm-deepseek-account/summary: - en: 90635454957391b0 - zh: 815bf79ba6056c3c + en: 47201804733ec769 + zh: 3c6751b16a45759f /deepseek-ai-dsh-llm-deepseek-account/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index b534844f32..283b36d3eb 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, the account model listing, and model gating for `deepseek-account`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, the account catalog, and model admission. -Authentication resolution returns the request credential the account service releases for the destination, carrying `x-dsh-auth-token`, with a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route publishes the account credential through `ctx.llm.routeCredential('deepseek-account')` with its base URL, so the DeepSeek web providers send it to the same deployment. +Authentication resolution returns the request credential the account service releases for the destination, carrying `x-dsh-auth-token`, with a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route publishes the account credential through `ctx.llm.providerCredential('deepseek-account')` with its base URL, so the DeepSeek web providers send it to the same deployment. ## Table of Contents diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index c0614c8907..04b6256544 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-account` 注册鉴权、账号模型列表和模型门控。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包负责凭据解析、账号目录和模型准入。 -鉴权解析返回账号服务为目标地址释放的请求凭据,携带 `x-dsh-auth-token`,并附带使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由通过 `ctx.llm.routeCredential('deepseek-account')` 连同其基础地址发布账号凭据,使 DeepSeek Web 提供方把它发往同一部署。 +鉴权解析返回账号服务为目标地址释放的请求凭据,携带 `x-dsh-auth-token`,并附带使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由通过 `ctx.llm.providerCredential('deepseek-account')` 连同其基础地址发布账号凭据,使 DeepSeek Web 提供方把它发往同一部署。 ## 目录 diff --git a/packages/llm/llm-deepseek-account/tests/provider.spec.ts b/packages/llm/llm-deepseek-account/tests/provider.spec.ts index d47617c834..ac9ab397f4 100644 --- a/packages/llm/llm-deepseek-account/tests/provider.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/provider.spec.ts @@ -215,7 +215,7 @@ it('publishes the account credential for its consumers, asking the account for e await ctx.plugin(LlmRuntime) ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return token } })) await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) - const credential = ctx.llm.routeCredential('deepseek-account') + const credential = ctx.llm.providerCredential('deepseek-account') expect(credential).toMatchObject({ kind: 'account', baseURL: 'https://account.deepseek.test/anthropic' }) expect(credential).not.toHaveProperty('reference') const endpoint = 'https://account.deepseek.test/v1/tools/search' @@ -225,7 +225,7 @@ it('publishes the account credential for its consumers, asking the account for e await expect(credential!.configured(endpoint)).resolves.toBe(false) await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() expect(asked).toEqual([endpoint, endpoint, endpoint, endpoint]) - expect(ctx.llm.routeCredential('deepseek-official')).toBeUndefined() + expect(ctx.llm.providerCredential('deepseek-official')).toBeUndefined() }) it('publishes a credential nobody holds without the account service', async () => { @@ -233,7 +233,7 @@ it('publishes a credential nobody holds without the account service', async () = contexts.push(ctx) await ctx.plugin(LlmRuntime) await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) - const credential = ctx.llm.routeCredential('deepseek-account')! + const credential = ctx.llm.providerCredential('deepseek-account')! await expect(credential.configured('https://account.deepseek.test/v1/tools/search')).resolves.toBe(false) await expect(credential.resolve('https://account.deepseek.test/v1/tools/search')).resolves.toBeUndefined() }) diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index b88b876c62..6b0f0744ae 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,8 +9,8 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: 735e39ebfef73dcb - zh: 42036db3ae53de0f + en: 25f6f430c8ce1a6b + zh: b221bef9390771e7 /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index a4cb98c257..c0010921d9 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.routeCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL. +Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.providerCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL. ## Table of Contents diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index f47bbed9cc..59b5229f04 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.routeCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥。 +鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.providerCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥。 ## 目录 diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index 976ce160ae..5f1cb8035f 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -78,7 +78,7 @@ it('publishes the route API key for its consumers from the credential planes it try { await ctx.plugin(LlmRuntime) await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) - const credential = ctx.llm.routeCredential('deepseek-official') + const credential = ctx.llm.providerCredential('deepseek-official') expect(credential).toMatchObject({ kind: 'api-key', baseURL: 'https://route.deepseek.test/anthropic', reference: 'DEEPSEEK_API_KEY' }) const endpoint = 'https://route.deepseek.test/v1/tools/search' await expect(credential!.configured(endpoint)).resolves.toBe(true) @@ -109,7 +109,7 @@ it.each([ ctx.provide('credentials', { resolve, describe } as never) await ctx.plugin(LlmRuntime) await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) - const credential = ctx.llm.routeCredential('deepseek-official') + const credential = ctx.llm.providerCredential('deepseek-official') await expect(credential!.configured(endpoint)).resolves.toBe(false) await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() expect(resolve).not.toHaveBeenCalled() diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index cee7e7d9b6..c929a5cfcc 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: - en: bcb58fd33f59dbf2 - zh: ff512a17c15aeadf + en: 22d74c69c0aa9234 + zh: d70eaf90c93a76d1 /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: f20f2cfbb38e4ba9 zh: c527b91c8b747886 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 7f6cc3edb6..96223b73bc 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -94,7 +94,7 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account route owns HTTP 401 classification and the account service the credential invalidation; the transport passes failures to the credential's callback. -Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.routeCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. +Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.providerCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. ### Streaming with thinking and images diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 22e8c4dfec..84772f3fcd 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -94,7 +94,7 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.routeCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 +提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.providerCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 ### 带 thinking 与图片的流式调用 diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 9bb7f1424c..5f625e687d 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -1,7 +1,7 @@ /** Direct Messages transport with one cancellable lifecycle per model request. */ import { attributionHeaders, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, RouteCredential, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, ProviderCredential, StreamChunk } from '@deepseek-ai/dsh-llm' import type { DeepSeekLlmApiExtensionRequest, DeepSeekLlmApiJson } from '@deepseek-ai/dsh-deepseek-llm-api-extensions' import { idleWatchdog, timeoutOf } from '@deepseek-ai/dsh-timeout' import { modelInfo } from './model-info.ts' @@ -47,7 +47,7 @@ export class DeepSeekAdapter extends LlmAdapt if (entry === undefined) throw new LlmError(`DeepSeek model "${model}" has no declared image projection`, 'UNKNOWN_MODEL') return resolveRequestImageTarget(entry, image) } - override routeCredential(_provider: string): RouteCredential | undefined { + override providerCredential(_provider: string): ProviderCredential | undefined { const publication = this.dependencies.credential if (publication === undefined) return undefined // One configuration generation serves the whole published object, as it does one model request. diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts index 0474969f60..8bd83450b4 100644 --- a/packages/llm/llm-deepseek/src/index.ts +++ b/packages/llm/llm-deepseek/src/index.ts @@ -15,7 +15,7 @@ export { DEFAULT_STREAM_IDLE_TIMEOUT_MS, } from './defaults.ts' export { DeepSeekAdapter } from './adapter.ts' -export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions, DeepSeekRouteCredentialOptions } from './types.ts' +export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions, DeepSeekProviderCredentialOptions } from './types.ts' export { DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET, DEFAULT_MAX_IMAGES_PER_REQUEST, diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index 7b37ff1616..0e483b92a4 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -1,6 +1,6 @@ /** Model catalog and request-local dependencies for DeepSeek Messages. */ import type { - ImageAttachmentAccess, LlmCredentialKind, LlmError, LlmModelInfo, ModelModality, ResolvedRetryPolicy, RouteCredentialGrant, + ImageAttachmentAccess, LlmCredentialKind, LlmError, LlmModelInfo, ModelModality, ProviderCredentialGrant, ResolvedRetryPolicy, SystemPromptUpdate, ToolUpdate, } from '@deepseek-ai/dsh-llm' import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -90,7 +90,7 @@ export interface DeepSeekConnectionOptions { * classification bound to that credential. The grant's `revoked` signal ends * the request and its file operations as the caller's cancellation does. */ -export interface DeepSeekRequestAuth extends RouteCredentialGrant { +export interface DeepSeekRequestAuth extends ProviderCredentialGrant { /** * Classify a failure using the captured credential; callback failure preserves the original error. The end a * withdrawn credential causes arrives here too, for the provider plugin to name. @@ -99,11 +99,11 @@ export interface DeepSeekRequestAuth extends RouteCredentialGrant { } /** - * What `routeCredential()` publishes about the route's credential beside the + * What `providerCredential()` publishes about the route's credential beside the * request-path hooks, so consumers outside the model request path share the * route's credential without reading its configuration. */ -export interface DeepSeekRouteCredentialOptions { +export interface DeepSeekProviderCredentialOptions { /** Kind of credential the route sends. */ kind: LlmCredentialKind /** Credential reference the route resolves, named by diagnostics; omission publishes none. */ @@ -138,7 +138,7 @@ export interface DeepSeekAdapterOptions Promise /** @@ -147,10 +147,10 @@ export interface DeepSeekAdapterOptions LlmError /** - * Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, + * Publish the route's credential through `providerCredential()`, whose `resolve` forwards the headers, value, * rejection, and withdrawal signal of {@link resolveAuth} without its failure classification; omission publishes none. */ - credential?: DeepSeekRouteCredentialOptions + credential?: DeepSeekProviderCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ resolveUserId: () => AnonymousUserId /** Resolve the current durable attachment service; absence rejects image input. */ diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts index 3314455d4e..9c74f6ef14 100644 --- a/packages/llm/llm-deepseek/tests/route-credential.spec.ts +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -48,7 +48,7 @@ function adapterWithout(missingCredential?: DeepSeekAdapterOptions['missingCrede it('publishes no credential for a provider that declares none', async () => { const ctx = await route({}) - expect(ctx.llm.routeCredential('fixture-route')).toBeUndefined() + expect(ctx.llm.providerCredential('fixture-route')).toBeUndefined() }) it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { @@ -58,7 +58,7 @@ it('publishes the declared credential from one configuration generation and reso endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, revoked, onRequestError: error => Promise.resolve(error) } : undefined) const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) - const credential = ctx.llm.routeCredential('fixture-route') + const credential = ctx.llm.providerCredential('fixture-route') expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' }) await expect(credential!.configured(ALLOWED)).resolves.toBe(true) await expect(credential!.configured(OTHER)).resolves.toBe(false) @@ -80,7 +80,7 @@ it('omits the reference of a credential kind without one and the rejection and w resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }), credential: { kind: 'account', configured: () => Promise.resolve(false) }, }) - const credential = ctx.llm.routeCredential('fixture-route') + const credential = ctx.llm.providerCredential('fixture-route') expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL }) expect(credential).not.toHaveProperty('reference') await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 1affba4950..bcc94686db 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -22,7 +22,7 @@ import type { LlmResolvedModelInfo, LlmProviderInfo, ModelModality, - RouteCredential, + ProviderCredential, StreamChunk, SystemPromptUpdate, ToolSchema, @@ -274,7 +274,7 @@ export abstract class LlmAdapter { * @param _provider - a route passed to `registerAdapter()` for this instance. * @returns the route's current credential, or `undefined` when the route publishes none. */ - routeCredential(_provider: string): RouteCredential | undefined { + providerCredential(_provider: string): ProviderCredential | undefined { return undefined } @@ -729,10 +729,10 @@ export class LlmRuntime extends TypertRemoteService { * which may no longer be mounted; a registered route whose configuration * does not resolve propagates the adapter's failure. * @param provider - provider route whose credential is wanted. - * @returns the route credential, or `undefined` when the route is unregistered or publishes none. + * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. */ - routeCredential(provider: string): RouteCredential | undefined { - return this.adapters.get(provider)?.adapter.routeCredential(provider) + providerCredential(provider: string): ProviderCredential | undefined { + return this.adapters.get(provider)?.adapter.providerCredential(provider) } /** diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 60b576c1aa..fdc7320c40 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -310,7 +310,7 @@ export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap] * One credential released for one destination. Host-only: it carries the * secret, so it never crosses a Remote boundary and never enters a log. */ -export interface RouteCredentialGrant { +export interface ProviderCredentialGrant { /** * Request headers carrying the credential as the route's own protocol * expects it, such as `x-api-key` for an API key. Consumers speaking that @@ -342,11 +342,11 @@ export interface RouteCredentialGrant { /** * The credential one registered provider route currently sends, answered by * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.routeCredential()` resolves a new value + * and choose no header names. `ctx.llm.providerCredential()` resolves a new value * per call from one configuration generation; a caller keeps it for one * operation only. */ -export interface RouteCredential { +export interface ProviderCredential { /** Kind of credential the route sends. */ readonly kind: LlmCredentialKind /** @@ -377,7 +377,7 @@ export interface RouteCredential { * @param signal - cancellation for the lookup. * @returns the released credential, or `undefined`. */ - resolve(endpoint: string, signal?: AbortSignal): Promise + resolve(endpoint: string, signal?: AbortSignal): Promise } /** diff --git a/packages/llm/llm/tests/topology.spec.ts b/packages/llm/llm/tests/topology.spec.ts index 7eddb69b35..3a9735fbef 100644 --- a/packages/llm/llm/tests/topology.spec.ts +++ b/packages/llm/llm/tests/topology.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, LlmConfigurableProvider, RouteCredential, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, LlmConfigurableProvider, ProviderCredential, StreamChunk } from '@deepseek-ai/dsh-llm' class NoopAdapter extends LlmAdapter { @@ -340,24 +340,24 @@ describe('imageRequestPricing resolution', () => { }) }) -describe('routeCredential resolution', () => { +describe('providerCredential resolution', () => { it('forwards to the owning adapter and answers undefined everywhere else', async () => { const ctx = await setup() - const credential: RouteCredential = { + const credential: ProviderCredential = { kind: 'api-key', baseURL: 'https://a.example/v1', configured: () => Promise.resolve(true), resolve: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), } class CredentialAdapter extends NoopAdapter { - override routeCredential(provider: string) { return provider === 'a' ? credential : undefined } + override providerCredential(provider: string) { return provider === 'a' ? credential : undefined } } const dispose = ctx.llm.registerAdapter(['a', 'b'], new CredentialAdapter()) ctx.llm.registerAdapter(['plain'], new NoopAdapter()) - expect(ctx.llm.routeCredential('a')).toBe(credential) - expect(ctx.llm.routeCredential('b')).toBeUndefined() - expect(ctx.llm.routeCredential('plain')).toBeUndefined() - expect(ctx.llm.routeCredential('missing')).toBeUndefined() + expect(ctx.llm.providerCredential('a')).toBe(credential) + expect(ctx.llm.providerCredential('b')).toBeUndefined() + expect(ctx.llm.providerCredential('plain')).toBeUndefined() + expect(ctx.llm.providerCredential('missing')).toBeUndefined() dispose() - expect(ctx.llm.routeCredential('a')).toBeUndefined() + expect(ctx.llm.providerCredential('a')).toBeUndefined() }) }) diff --git a/packages/web/web-deepseek-api/README.i18n.yaml b/packages/web/web-deepseek-api/README.i18n.yaml index 6d2f73adfb..d2e5ca1950 100644 --- a/packages/web/web-deepseek-api/README.i18n.yaml +++ b/packages/web/web-deepseek-api/README.i18n.yaml @@ -18,14 +18,14 @@ en: 673ba23a4e608cf2 zh: 042afa607aaf4335 /deepseek-ai-dsh-web-deepseek-api/use-this-package/authentication: - en: 8923728d77eb1256 - zh: 85d1b8408cf1f325 + en: ba52a11cc1840ca6 + zh: d8f238abb1b309c8 /deepseek-ai-dsh-web-deepseek-api/use-this-package/results-and-failures: en: e7a5d332ebababe7 zh: 6ea098d53d4e9616 /deepseek-ai-dsh-web-deepseek-api/understand-the-implementation: - en: 597dab3fe52fa59d - zh: 4370d01d5a58f2f9 + en: ab3a0eaeee8747cf + zh: 449aeb4bce7d7707 /deepseek-ai-dsh-web-deepseek-api/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -54,8 +54,8 @@ en: 14f9af39f3be4fac zh: 3c7139fba0f17862 /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work: - en: c71abd58d3afbcfe - zh: d463321359b84e94 + en: c52fd4fda604976e + zh: 5cc3fad3d756362a /deepseek-ai-dsh-web-deepseek-api/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/web/web-deepseek-api/README.md b/packages/web/web-deepseek-api/README.md index 80b0b68b57..bb141166c7 100644 --- a/packages/web/web-deepseek-api/README.md +++ b/packages/web/web-deepseek-api/README.md @@ -59,8 +59,8 @@ Run the real API tests with `DEEPSEEK_API_KEY` and `DEEPSEEK_SEARCH_API_TEST_BAS Search and Fetch each resolve their endpoint and credential from one settings snapshot per operation, so a saved setting, a model-provider change, a sign-in, or a stored key applies to the next operation. The conversation's route is the `provider` of the initiating Session's latest request context; `ready()` uses the route of the model request being prepared. - **Own settings.** A capability with a non-empty `*BaseURL` or `*ApiKeyEnv` sends only the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) as `Authorization: Bearer` to its `*BaseURL` (`https://api.deepseek.com/v1/tools` when unset) on every route, and never the account token. Without the key, the operation fails with a diagnostic that names the reference and the `*ApiKeyEnv` field. -- **Account credential.** The operation sends the credential `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. With the `deepseek-account` model route mounted, the endpoint is under the origin of the base URL that route publishes through `ctx.llm.routeCredential`; without that route, it is under the origin `DEEPSEEK_BASE_URL` names, `https://api.deepseek.com` by default. No sign-in or no account service means no credential. A failed credential read fails the operation without trying another credential. A mounted route whose settings do not resolve, or a `DEEPSEEK_BASE_URL` that is not an HTTP(S) URL without credentials, fails the operation before the credential is read when the operation reaches this source. -- **API key.** With the `deepseek-official` model route mounted, the operation sends the key that route publishes through `ctx.llm.routeCredential`, read under the route's `apiKeyEnv` (`DEEPSEEK_API_KEY` by default), as `Authorization: Bearer` to the origin of the route's base URL. Without that route, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. A mounted route whose settings do not resolve fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`. +- **Account credential.** The operation sends the credential `ctx.deepseekAccount` releases for the dispatch endpoint as `x-dsh-auth-token`; the public Search and Fetch routes accepted it on 2026-10-16. With the `deepseek-account` model route mounted, the endpoint is under the origin of the base URL that route publishes through `ctx.llm.providerCredential`; without that route, it is under the origin `DEEPSEEK_BASE_URL` names, `https://api.deepseek.com` by default. No sign-in or no account service means no credential. A failed credential read fails the operation without trying another credential. A mounted route whose settings do not resolve, or a `DEEPSEEK_BASE_URL` that is not an HTTP(S) URL without credentials, fails the operation before the credential is read when the operation reaches this source. +- **API key.** With the `deepseek-official` model route mounted, the operation sends the key that route publishes through `ctx.llm.providerCredential`, read under the route's `apiKeyEnv` (`DEEPSEEK_API_KEY` by default), as `Authorization: Bearer` to the origin of the route's base URL. Without that route, it sends `DEEPSEEK_API_KEY` to `https://api.deepseek.com/v1/tools`. A mounted route whose settings do not resolve fails each operation that needs the key, before the key is read; the operation never substitutes the official endpoint or `DEEPSEEK_API_KEY`. - **`auto` billing** follows the conversation. On the `deepseek-account` route it sends the account credential, and without one the API key; without the account route, only the API key. On the `deepseek-official` route it sends only the API key. On any other route or outside a Session it sends the API key, and without a key the account credential; without a key, a mounted account route whose settings do not resolve fails the operation. - **`account` billing** sends only the account credential on every route, and **`api-key` billing** only the API key; neither falls back to the other credential. @@ -84,7 +84,7 @@ An unparseable own base URL makes that capability's provider unavailable; and a
Implementation internals — click to expand -The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the credentials the mounted DeepSeek model routes publish through `ctx.llm.routeCredential` into the operation's ordered credentials, each bound to the API base it is sent to. The [Search provider](src/search.ts) validates response JSON before returning service results; the [Fetch provider](src/fetch.ts) validates the Markdown body. The [transport](src/transport.ts) reads those credentials in order, sends one request with the first present one, and owns cancellation, redirect rejection, and failure guidance; a recording hook runs before dispatch and prevents it by throwing. Search and Fetch API calls emit no auxiliary request event. The [Messages search provider](../web-search-deepseek/README.md) owns its `web/deepseek-search-llm-request` Session event declaration and recording. Tool calls and results retain their normal Session logging. +The [plugin](src/index.ts) reads its settings once per operation, registers both providers, and turns one capability's settings snapshot, the conversation's route, and the credentials the mounted DeepSeek model routes publish through `ctx.llm.providerCredential` into the operation's ordered credentials, each bound to the API base it is sent to. The [Search provider](src/search.ts) validates response JSON before returning service results; the [Fetch provider](src/fetch.ts) validates the Markdown body. The [transport](src/transport.ts) reads those credentials in order, sends one request with the first present one, and owns cancellation, redirect rejection, and failure guidance; a recording hook runs before dispatch and prevents it by throwing. Search and Fetch API calls emit no auxiliary request event. The [Messages search provider](../web-search-deepseek/README.md) owns its `web/deepseek-search-llm-request` Session event declaration and recording. Tool calls and results retain their normal Session logging. See the [web subsystem](../../../docs/subsystems/web.md) for service types and [tool-web](../tool-web/README.md) for bounded model output. @@ -132,7 +132,7 @@ A returning or removed web tool changes the declared tools as [`dsh-tool-web`](. - API query and URL constraints are enforced by the remote service. An unresolvable Fetch target returned HTTP 500 rather than the documented 404 on 2026-10-16, and its failure carries the same endpoint guidance as an endpoint failure. Fetch exposes neither the target status nor the final redirect URL, so results report HTTP 200 and the requested URL; the provider discards the API's page title. - `available()` cannot query asynchronous credential stores; `ready()` does, so model steps withhold the tools when the store lacks the key. A direct `ctx.web.search()` or `ctx.web.fetch()` call can still fail with a missing-credential error. - Search pacing limits send times within one plugin instance. Other processes and clients on the same account share the account-wide 5 QPS limit without coordination, and network jitter can still bunch arrivals; an HTTP 429 fails that search, and `dsh-tool-web` then fails the whole multi-query call. Fetch is not paced, so parallel `web_fetch` calls can exceed the Fetch limit. -- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.routeCredential`. An adapter that publishes no credential, such as a test replay adapter, or a credential of the other kind (an account credential as `deepseek-official`, an API key as `deepseek-account`) counts as no route: its conversations use `DEEPSEEK_API_KEY` and the official base, and `account` billing asks the account service as it does without the account route. +- Route endpoints and credentials follow what the adapter registered as `deepseek-official` or `deepseek-account` publishes through `ctx.llm.providerCredential`. An adapter that publishes no credential, such as a test replay adapter, or a credential of the other kind (an account credential as `deepseek-official`, an API key as `deepseek-account`) counts as no route: its conversations use `DEEPSEEK_API_KEY` and the official base, and `account` billing asks the account service as it does without the account route. ### Dev Note diff --git a/packages/web/web-deepseek-api/README.zh.md b/packages/web/web-deepseek-api/README.zh.md index 3dbe337001..bcc91f5444 100644 --- a/packages/web/web-deepseek-api/README.zh.md +++ b/packages/web/web-deepseek-api/README.zh.md @@ -59,8 +59,8 @@ kind: "package-reference" Search 与 Fetch 每次操作各自从同一份设置快照解析端点和凭据,因此保存的设置、模型提供方变更、登录或存入的密钥从下一次操作开始生效。会话的路由是发起会话最近一次请求上下文的 `provider`;`ready()` 使用正在准备的模型请求的路由。 - **单独配置。** 设置了非空 `*BaseURL` 或 `*ApiKeyEnv` 的能力在任何路由上都只以 `Authorization: Bearer` 把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为 `https://api.deepseek.com/v1/tools`),从不发送账号令牌。没有该密钥时,操作失败,诊断信息点名该引用和 `*ApiKeyEnv` 字段。 -- **账号凭据。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点释放的凭据;2026-10-16 公网 Search 与 Fetch 路由已接受该凭据。挂载了 `deepseek-account` 模型路由时,端点位于该路由通过 `ctx.llm.routeCredential` 发布的基础地址的 origin 下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 所指 origin 下,默认 `https://api.deepseek.com`。没有登录或没有账号服务都算没有凭据。凭据读取失败时操作失败,不再尝试其他凭据。已挂载路由的设置无法解析,或 `DEEPSEEK_BASE_URL` 不是不含凭据的 HTTP(S) URL 时,操作在轮到该来源时于读取凭据前失败。 -- **API 密钥。** 挂载了 `deepseek-official` 模型路由时,操作以 `Authorization: Bearer` 把该路由通过 `ctx.llm.routeCredential` 发布的密钥(按路由的 `apiKeyEnv` 读取,默认 `DEEPSEEK_API_KEY`)发往该路由基础地址的 origin。没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。已挂载路由的设置无法解析时,每个需要该密钥的操作都在读取密钥前失败,绝不改用官方端点或 `DEEPSEEK_API_KEY`。 +- **账号凭据。** 操作通过 `x-dsh-auth-token` 发送 `ctx.deepseekAccount` 为请求端点释放的凭据;2026-10-16 公网 Search 与 Fetch 路由已接受该凭据。挂载了 `deepseek-account` 模型路由时,端点位于该路由通过 `ctx.llm.providerCredential` 发布的基础地址的 origin 下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 所指 origin 下,默认 `https://api.deepseek.com`。没有登录或没有账号服务都算没有凭据。凭据读取失败时操作失败,不再尝试其他凭据。已挂载路由的设置无法解析,或 `DEEPSEEK_BASE_URL` 不是不含凭据的 HTTP(S) URL 时,操作在轮到该来源时于读取凭据前失败。 +- **API 密钥。** 挂载了 `deepseek-official` 模型路由时,操作以 `Authorization: Bearer` 把该路由通过 `ctx.llm.providerCredential` 发布的密钥(按路由的 `apiKeyEnv` 读取,默认 `DEEPSEEK_API_KEY`)发往该路由基础地址的 origin。没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。已挂载路由的设置无法解析时,每个需要该密钥的操作都在读取密钥前失败,绝不改用官方端点或 `DEEPSEEK_API_KEY`。 - **`auto` 计费**跟随会话。在 `deepseek-account` 路由上先发送账号凭据,没有凭据时发送 API 密钥;没有账号路由时只发送 API 密钥。在 `deepseek-official` 路由上只发送 API 密钥。在其他路由上或会话之外先发送 API 密钥,没有密钥时发送账号凭据;没有密钥且已挂载的账号路由设置无法解析时,操作失败。 - **`account` 计费**在任何路由上只发送账号凭据,**`api-key` 计费**只发送 API 密钥;两者都不回退到另一种凭据。 @@ -84,7 +84,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的
实现细节 — 点击展开 -[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由,以及已挂载的 DeepSeek 模型路由通过 `ctx.llm.routeCredential` 发布的凭据转换为该操作的有序凭据,每个凭据都绑定其发往的 API 基础地址。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)按顺序读取这些凭据,用第一个存在的凭据发送一次请求,并负责取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。 +[插件](src/index.ts)在每次操作时读取一次设置,注册两个提供者,并把一个能力的设置快照、会话的路由,以及已挂载的 DeepSeek 模型路由通过 `ctx.llm.providerCredential` 发布的凭据转换为该操作的有序凭据,每个凭据都绑定其发往的 API 基础地址。[Search 提供者](src/search.ts)在返回服务结果前校验响应 JSON;[Fetch 提供者](src/fetch.ts)校验 Markdown 正文。[传输层](src/transport.ts)按顺序读取这些凭据,用第一个存在的凭据发送一次请求,并负责取消、重定向拒绝和失败指引;记录钩子在发送前运行,抛出异常即阻止发送。Search 与 Fetch API 调用不产生辅助请求事件。[Messages 搜索提供方](../web-search-deepseek/README.zh.md)负责声明和记录自身的 `web/deepseek-search-llm-request` 会话事件。工具调用和结果仍按常规记录到会话。 服务类型见 [Web 子系统](../../../docs/subsystems/web.zh.md),受限的模型输出见 [tool-web](../tool-web/README.zh.md)。 @@ -132,7 +132,7 @@ Search API 接收 `query`、`count`(配置的结果数,或请求中更小的 - 查询和 URL 约束由远端服务执行。2026-10-16 抓取无法解析的目标域名时返回 HTTP 500,而非文档所述的 404,其失败信息与端点失败附带相同的端点指引。Fetch 既不暴露目标状态,也不暴露最终重定向 URL,因此结果报告 HTTP 200 和请求 URL;提供者丢弃 API 返回的页面标题。 - `available()` 无法查询异步凭据存储;`ready()` 可以,因此凭据存储缺少密钥时,模型步骤会撤下这两个工具。直接调用 `ctx.web.search()` 或 `ctx.web.fetch()` 仍可能因凭据缺失失败。 - Search 限速只约束单个插件实例内的发送时间。同一账号下的其他进程和客户端共享账号级 5 QPS 限制,彼此不协调,网络抖动也可能使请求集中到达;HTTP 429 会使该次搜索失败,随后 `dsh-tool-web` 会使整个多查询调用失败。Fetch 不限速,因此并行的 `web_fetch` 调用可能超过 Fetch 限制。 -- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.routeCredential` 发布的内容。不发布凭据的适配器(例如测试回放适配器),或发布另一种凭据的适配器(以 `deepseek-official` 发布账号凭据,或以 `deepseek-account` 发布 API 密钥),都视为没有路由:其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址,`account` 计费则像没有账号路由时一样询问账号服务。 +- 路由端点与凭据只认以 `deepseek-official` 或 `deepseek-account` 注册的适配器通过 `ctx.llm.providerCredential` 发布的内容。不发布凭据的适配器(例如测试回放适配器),或发布另一种凭据的适配器(以 `deepseek-official` 发布账号凭据,或以 `deepseek-account` 发布 API 密钥),都视为没有路由:其会话使用 `DEEPSEEK_API_KEY` 与官方基础地址,`account` 计费则像没有账号路由时一样询问账号服务。 ### 开发备注 diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index aeebcdd51f..88f972c641 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -6,7 +6,7 @@ * otherwise the API key; one on the `deepseek-official` route sends the API key; any other operation sends the API key * and, without a key, the signed-in account's credential. `account` sends only the account credential and `api-key` * only the API key. Each mounted DeepSeek model route publishes its credential and base URL through - * `ctx.llm.routeCredential()`: the API key is that of the `deepseek-official` route, sent to its origin, or + * `ctx.llm.providerCredential()`: the API key is that of the `deepseek-official` route, sent to its origin, or * `DEEPSEEK_API_KEY` sent to the official base without that route; the account credential is that of the * `deepseek-account` route, sent to its origin, or outside an account conversation without that route the signed-in * account's credential sent to the origin `DEEPSEEK_BASE_URL` names, by default the official one. An operation that @@ -271,7 +271,7 @@ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeek */ function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined { try { - const credential = ctx.get('llm')?.routeCredential(provider) + const credential = ctx.get('llm')?.providerCredential(provider) if (credential === undefined || credential.kind !== ROUTE_CREDENTIAL_KIND[provider]) return undefined return { kind: 'route', baseURL: toolsBase(credential.baseURL), credential } } catch (error: unknown) { diff --git a/packages/web/web-deepseek-api/src/transport.ts b/packages/web/web-deepseek-api/src/transport.ts index befc4d4b65..7405c1c0da 100644 --- a/packages/web/web-deepseek-api/src/transport.ts +++ b/packages/web/web-deepseek-api/src/transport.ts @@ -5,7 +5,7 @@ * @module @deepseek-ai/dsh-web-deepseek-api/transport */ import type { CredentialRef } from '@deepseek-ai/dsh-credentials' -import type { LlmCredentialKind, RouteCredential } from '@deepseek-ai/dsh-llm' +import type { LlmCredentialKind, ProviderCredential } from '@deepseek-ai/dsh-llm' import { WebError } from '@deepseek-ai/dsh-web' const USER_AGENT = 'deepseek-harness/0.0.1' @@ -34,7 +34,7 @@ export type DeepSeekWebAuthSource = /** API base the credential is sent to, including its path prefix. */ baseURL: string /** The credential's owner: it answers presence and releases a grant for an endpoint, and read failures reject. */ - credential: Omit + credential: Omit } /** An API key, sent as `Authorization: Bearer`. */ | { diff --git a/packages/web/web-deepseek-api/tests/routes.ts b/packages/web/web-deepseek-api/tests/routes.ts index 98b82fbf65..29f0f426c9 100644 --- a/packages/web/web-deepseek-api/tests/routes.ts +++ b/packages/web/web-deepseek-api/tests/routes.ts @@ -7,7 +7,7 @@ import type { Context } from '@deepseek-ai/cordis' import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' import type {} from '@deepseek-ai/dsh-deepseek-account' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import type { RouteCredential } from '@deepseek-ai/dsh-llm' +import type { ProviderCredential } from '@deepseek-ai/dsh-llm' import { Config as AccountConfig } from '@deepseek-ai/dsh-llm-deepseek-account' import { plainAccountOptions, resolveAccountOptions } from '@deepseek-ai/dsh-llm-deepseek-account/src/config.ts' import { Config as OfficialConfig } from '@deepseek-ai/dsh-llm-deepseek-api-key' @@ -21,7 +21,7 @@ export interface RouteRow { config?: Record /** Publish no credential, as an adapter another package registers under this id does. Defaults to false. */ withoutCredential?: boolean - /** Value `routeCredential()` throws instead of publishing. */ + /** Value `providerCredential()` throws instead of publishing. */ throws?: unknown /** Base URL published in place of the resolved one, as a route publishing an unparsable base would. */ publishedBaseURL?: string @@ -30,7 +30,7 @@ export interface RouteRow { } /** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */ -function credentialOf(ctx: Context, route: RouteRow): RouteCredential { +function credentialOf(ctx: Context, route: RouteRow): ProviderCredential { const environment = launchEnvironmentOf(ctx) if ((route.publishes ?? (route.provider === 'deepseek-official' ? 'api-key' : 'account')) === 'api-key') { const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment) @@ -53,13 +53,13 @@ function credentialOf(ctx: Context, route: RouteRow): RouteCredential { } /** - * Provide an `llm` stand-in whose `routeCredential()` answers for `routes`. + * Provide an `llm` stand-in whose `providerCredential()` answers for `routes`. * @param ctx - the root context. * @param routes - route rows, one per provider id. */ export function provideRoutes(ctx: Context, routes: readonly RouteRow[]): void { ctx.provide('llm', { - routeCredential: (provider: string): RouteCredential | undefined => { + providerCredential: (provider: string): ProviderCredential | undefined => { const route = routes.find(row => row.provider === provider) if (route === undefined || route.withoutCredential === true) return undefined if (route.throws !== undefined) throw route.throws diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index 76e5c0a067..a9907cc6f9 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3ed88edabdf63c8d zh: c66176c8a7c9a434 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: 5bd18e6e586eb4f0 - zh: 133927c4db79ac71 + en: bea7705262c58779 + zh: a8c166024477b311 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a @@ -45,8 +45,8 @@ en: 6488e1c85646339f zh: 2b5ca1c6b5939a8c /deepseek-ai-dsh-web-search-deepseek/understand-the-implementation/request-flow: - en: ec407206b9f6371d - zh: a94d1e864102342b + en: f5f0e602ec250162 + zh: 5854cc89c0806644 /deepseek-ai-dsh-web-search-deepseek/further-exploration: en: 3a650478cf33d792 zh: ab4247c4c31f4a90 diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 741d92499a..503822edf5 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,7 +58,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.routeCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. An account-authenticated search in flight when the account signs out ends through the credential's `revoked` signal and fails as `WEB_PROVIDER_ERROR` with sign-in guidance. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names a model route that publishes an account credential through `ctx.llm.providerCredential`, the `deepseek-account` route, the search endpoint has the origin of that route's base URL, and that credential resolves for the search endpoint. The provider asks a route for its credential only at that origin, so an account credential published for another deployment is never sent to the search endpoint. The account service releases one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only the credential's headers, `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the credential that search sent through the credential's own invalidation: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. An account-authenticated search in flight when the account signs out ends through the credential's `revoked` signal and fails as `WEB_PROVIDER_ERROR` with sign-in guidance. The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route publishes an account credential for the origin of the configured search endpoint that reports itself configured for that endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a route whose settings do not resolve or whose published base URL does not parse, or a failed account-credential or credential-store read, answers false, because the search fails there instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. @@ -103,7 +103,7 @@ The provider is built on two commitments: ### Request flow -Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.routeCredential` when it publishes one for the search endpoint's origin, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. +Each search captures the current Config values into provider options — endpoint, model, key reference, limits — then asks the initiating Session's model route for its account credential through `ctx.llm.providerCredential` when it publishes one for the search endpoint's origin, otherwise resolves the credential reference through `ctx.credentials` (or the environment), appends the log-only session event, and dispatches the Messages request with the native `web_search` server tool. The response's `web_search_tool_result` blocks become `sources[]`; `cited_text` entries from text blocks are joined to their URLs as snippets; results are deduplicated by URL; and the service enforces the requested source bound on the way back. Readiness captures the same options but reads no API key value: on a route publishing an account credential for the search endpoint's origin it first asks that credential whether it is configured for the search endpoint, then checks the literal key or asks `ctx.credentials.describe()` (or the environment) whether the key reference is configured. diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index 7b7c8ac43c..a8196222d3 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.routeCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。账号退登时仍在途的账号鉴权搜索会通过凭据的 `revoked` 信号结束,并以 `WEB_PROVIDER_ERROR` 失败,附带登录指引。 +当发起会话最近的 `request/context` 事件指明的模型路由通过 `ctx.llm.providerCredential` 发布账号凭据(即 `deepseek-account` 路由),搜索端点与该路由的基础地址同源,且该凭据为搜索端点解析成功时,搜索使用 DeepSeek 账号鉴权。提供方只在同源时向路由索取凭据,因此为其他部署发布的账号凭据不会发往搜索端点。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)释放凭据。这类搜索只发送该凭据的请求头 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并通过凭据自身的失效操作只作废该搜索实际发送的凭据:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。账号退登时仍在途的账号鉴权搜索会通过凭据的 `revoked` 信号结束,并以 `WEB_PROVIDER_ERROR` 失败,附带登录指引。 提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由为配置的搜索端点所在 origin 发布了账号凭据且该凭据报告自身已为该端点配置,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查;路由设置无法解析或其发布的基础地址无法解析,或读取账号凭据或凭据存储失败时回答 false,因为搜索会在那里失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 @@ -103,7 +103,7 @@ kind: "package-reference" ### 请求流程 -每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.routeCredential` 为搜索端点所在 origin 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 +每次搜索先把当前 Config 段投影为提供方选项——端点、模型、密钥引用、上限——然后在发起会话的模型路由通过 `ctx.llm.providerCredential` 为搜索端点所在 origin 发布账号凭据时向其索取该凭据,否则通过 `ctx.credentials`(或环境)解析凭据引用,追加仅用于日志的会话事件,并以原生 `web_search` 服务器工具分发 Messages 请求。响应中的 `web_search_tool_result` 块变为 `sources[]`;文本块中的 `cited_text` 条目按其 URL 拼接为 snippet;结果按 URL 去重;服务在返回路径上强制执行请求的来源上限。 就绪判断捕获相同的选项,但不读取 API 密钥的值:路由为搜索端点所在 origin 发布账号凭据时,先询问该凭据是否已为搜索端点配置,再检查字面密钥,或询问 `ctx.credentials.describe()`(或环境)密钥引用是否已配置。 diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index 006749c9d9..b63dd86263 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -1,7 +1,7 @@ /** * Register a DeepSeek-backed provider in `ctx.web`. It calls the Anthropic-compatible Messages API * with native `web_search_20250305`. A search initiated by a Session whose latest model request used - * a route that publishes an account credential through `ctx.llm.routeCredential()` authenticates with + * a route that publishes an account credential through `ctx.llm.providerCredential()` authenticates with * that credential when the search endpoint has the origin of that route's base URL and the * credential's owner allows the endpoint; every other search reuses `DEEPSEEK_API_KEY`. The provider * does not reuse `DEEPSEEK_BASE_URL`; auxiliary search has its own endpoint configuration. The @@ -17,7 +17,7 @@ import { credentialRef, credentialRefConfigured, resolveCredentialRef } from '@d import type { CredentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { assertUsableApiKey } from '@deepseek-ai/dsh-llm' -import type { RouteCredential } from '@deepseek-ai/dsh-llm' +import type { ProviderCredential } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' import { @@ -102,8 +102,8 @@ type SearchOptions = DeepSeekSearchProviderOptions & { readonly apiKeyEnv: Crede * @returns the route's account credential, or undefined for another kind, another origin, no credential, or no route. * @throws when the route's settings do not resolve, or its published base URL or `endpoint` does not parse. */ -function accountCredentialOf(ctx: Context, route: string | undefined, endpoint: string): RouteCredential | undefined { - const credential = route === undefined ? undefined : ctx.get('llm')?.routeCredential(route) +function accountCredentialOf(ctx: Context, route: string | undefined, endpoint: string): ProviderCredential | undefined { + const credential = route === undefined ? undefined : ctx.get('llm')?.providerCredential(route) if (credential?.kind !== 'account') return undefined return new URL(credential.baseURL).origin === new URL(endpoint).origin ? credential : undefined } @@ -170,7 +170,7 @@ async function searchConfigured( ctx: Context, options: SearchOptions, route: string | undefined, ): Promise { const endpoint = `${options.baseURL}/messages` - let account: RouteCredential | undefined + let account: ProviderCredential | undefined try { account = accountCredentialOf(ctx, route, endpoint) } catch (_unresolvedRoute) { return false /* The search fails on this route before it reads any credential. */ } if (account !== undefined) { diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index 5813d1f2d5..bff545d5cf 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -14,7 +14,7 @@ import type { WebSearchSource, } from '@deepseek-ai/dsh-web' import type { CredentialRef } from '@deepseek-ai/dsh-credentials' -import type { RouteCredentialGrant } from '@deepseek-ai/dsh-llm' +import type { ProviderCredentialGrant } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-session' import type { AnthropicError, @@ -100,7 +100,7 @@ export interface DeepSeekSearchProviderOptions { * search reports the HTTP rejection. The grant's `revoked` signal ends the search when the * account signs out. `undefined` selects API-key authentication. */ - resolveAccountCredential?: (endpoint: string) => Promise + resolveAccountCredential?: (endpoint: string) => Promise /** Literal DeepSeek API key; when present it wins over {@link resolveApiKey}. */ apiKey?: string /** Resolve the current DeepSeek API key for one search operation. */ diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index 76c26394da..3af5b9666e 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -12,7 +12,7 @@ import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' import LlmRuntime from '@deepseek-ai/dsh-llm' -import type { RouteCredential, RouteCredentialGrant } from '@deepseek-ai/dsh-llm' +import type { ProviderCredential, ProviderCredentialGrant } from '@deepseek-ai/dsh-llm' import * as AccountRoute from '@deepseek-ai/dsh-llm-deepseek-account' import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session' import WebRuntime, { WebError, type WebSearchResult } from '@deepseek-ai/dsh-web' @@ -39,7 +39,7 @@ const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchP */ function accountCredential( token: (endpoint: string) => Promise, reject?: (token: string) => Promise, revoked?: AbortSignal, -): (endpoint: string) => Promise { +): (endpoint: string) => Promise { return async (endpoint) => { const value = await token(endpoint) if (value === undefined || value.length === 0) return undefined @@ -1070,19 +1070,19 @@ describe('web-search-deepseek search readiness', () => { } }) - it.each<[string, () => RouteCredential, string]>([ + it.each<[string, () => ProviderCredential, string]>([ ['settings do not resolve', () => { throw new Error('route settings do not resolve') }, 'route settings do not resolve'], ['published base URL does not parse', () => ({ kind: 'account', baseURL: 'not a url', configured: () => Promise.resolve(true), resolve: () => Promise.resolve({ headers: { 'x-dsh-auth-token': 'account-token' }, value: 'account-token' }), }), 'Invalid URL'], - ])('is not ready and fails the search when the initiating route\'s %s, despite a literal key', async (_fault, routeCredential, diagnostic) => { + ])('is not ready and fails the search when the initiating route\'s %s, despite a literal key', async (_fault, providerCredential, diagnostic) => { const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init: RequestInit = {}) => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) const ctx = new Context() mounted.push(ctx) await ctx.plugin(WebRuntime, { searchProvider: DEEPSEEK_PROVIDER_ID }) - ctx.provide('llm', { routeCredential } as never) + ctx.provide('llm', { providerCredential } as never) await ctx.plugin(deepseekPlugin, { apiKey: 'ds-key' }) expect(await ctx.web.searchReady('deepseek-account')).toBe(false) expect(await ctx.web.searchReady(undefined)).toBe(true) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index a124eb82aa..01d4c94626 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -493,7 +493,7 @@ export const LINK_MAP: Readonly> = { LlmResolvedModelInfo: 'llm-streaming.md', LlmFailure: 'llm-streaming.md', LlmImageRequestPricing: 'llm-streaming.md', - RouteCredential: 'llm-streaming.md', + ProviderCredential: 'llm-streaming.md', LlmModelInfo: 'llm-streaming.md', LlmProviderInfo: 'llm-streaming.md', LlmConfigurableProvider: 'llm-streaming.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index d4dd42d7ae..08d8d22bb3 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1844,12 +1844,12 @@ }, { "doc": "docs/subsystems/llm-streaming.md", - "symbol": "RouteCredentialGrant", + "symbol": "ProviderCredentialGrant", "source": "packages/llm/llm/src/types.ts" }, { "doc": "docs/subsystems/llm-streaming.md", - "symbol": "RouteCredential", + "symbol": "ProviderCredential", "source": "packages/llm/llm/src/types.ts" }, {