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