From 6eb3805bf3046ba093ea10db5f067cb1f0ea3c8d Mon Sep 17 00:00:00 2001 From: LegGasai Date: Sun, 15 Nov 2026 16:53:29 +0800 Subject: [PATCH] refactor(llm): take the DeepSeek routes' credentials from ctx.deepseekAuth The two DeepSeek route plugins read their own credential and published it through `ctx.llm.providerCredential()` for the web providers. Those providers now ask `ctx.deepseekAuth`, so nothing reads the publication. Each route asks the same service for the credential of its own requests: the API-key route for its key in `x-api-key`, the account route for the account sign-in, both for destinations under the origin of the route's base URL. `LlmAdapter.providerCredential()`, `LlmRuntime.providerCredential()`, `ProviderCredential`, `ProviderCredentialGrant`, and `LlmCredentialKind` are removed from `dsh-llm`, and the `credential` option and `DeepSeekProviderCredentialOptions` from the DeepSeek transport. `DeepSeekRequestAuth` keeps the headers, the withdrawal signal, and the failure callback; its bare `value` and `reject` served only the publication. The API-key route reports an unusable key as `INVALID_CREDENTIAL` with the text it had. Tests of the publication are replaced by tests of the deployment each route connects. --- docs/subsystems/account.i18n.yaml | 4 +- docs/subsystems/account.md | 2 +- docs/subsystems/account.zh.md | 2 +- docs/subsystems/llm-streaming.i18n.yaml | 8 +- docs/subsystems/llm-streaming.md | 103 ------------------ docs/subsystems/llm-streaming.zh.md | 103 ------------------ .../extensions/tool-cordis/src/api-catalog.ts | 26 +---- .../llm/llm-deepseek-account/README.i18n.yaml | 4 +- packages/llm/llm-deepseek-account/README.md | 2 +- .../llm/llm-deepseek-account/README.zh.md | 2 +- .../llm/llm-deepseek-account/src/index.ts | 30 ++--- .../tests/provider.spec.ts | 36 ++---- .../llm/llm-deepseek-api-key/README.i18n.yaml | 4 +- packages/llm/llm-deepseek-api-key/README.md | 2 +- .../llm/llm-deepseek-api-key/README.zh.md | 2 +- .../llm/llm-deepseek-api-key/src/index.ts | 43 +++----- .../tests/discovery.spec.ts | 51 +++------ packages/llm/llm-deepseek/README.i18n.yaml | 4 +- packages/llm/llm-deepseek/README.md | 2 +- packages/llm/llm-deepseek/README.zh.md | 2 +- packages/llm/llm-deepseek/src/adapter.ts | 27 +---- packages/llm/llm-deepseek/src/host.ts | 2 +- packages/llm/llm-deepseek/src/index.ts | 2 +- packages/llm/llm-deepseek/src/types.ts | 40 +++---- .../tests/route-credential.spec.ts | 77 +------------ packages/llm/llm/src/index.ts | 27 ----- packages/llm/llm/src/types.ts | 88 --------------- packages/llm/llm/tests/topology.spec.ts | 24 +--- scripts/gen-cordis-catalog.ts | 1 - scripts/type-equiv.manifest.json | 10 -- 30 files changed, 105 insertions(+), 625 deletions(-) diff --git a/docs/subsystems/account.i18n.yaml b/docs/subsystems/account.i18n.yaml index 665e916b45..9f47a7a3b7 100644 --- a/docs/subsystems/account.i18n.yaml +++ b/docs/subsystems/account.i18n.yaml @@ -6,8 +6,8 @@ en: 2302e2999588bac3 zh: 5e0ac058b50036dc /deepseek-account/request-credentials: - en: c5fb32307f841c66 - zh: 8ed40c0c99884301 + en: e64c33254702eeb8 + zh: 03efb20915a5d9e4 /deepseek-account/embedded-platform-credentials: en: 9a651d70acbe83a6 zh: 4624b0299f5fdd8e diff --git a/docs/subsystems/account.md b/docs/subsystems/account.md index b251b70918..4bce354d4e 100644 --- a/docs/subsystems/account.md +++ b/docs/subsystems/account.md @@ -8,7 +8,7 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun ## Request credentials -`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. Its `revoked` signal aborts when the account signs out of the sign-in that token belongs to, by the user or after a rejection, once the `deepseek-account/signed-out` listeners have returned; the account model route and the DeepSeek web providers run each model, Files, Search, and Fetch request that carries the token under it, so a sign-out ends those requests even after the plugin that sent them has unloaded. The `deepseek-account` model route publishes this credential through `ctx.llm.providerCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released. +`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, 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. Consumers do not call it themselves: [`ctx.deepseekAuth`](../../packages/account/deepseek-auth/README.md) asks for the credential on behalf of the `deepseek-account` model route and the DeepSeek web providers, for a destination under the origin of that route's base URL or, without that route, of `DEEPSEEK_BASE_URL`. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject. A credential released by an account service that has since been replaced keeps an unaborted signal, because the replacement withdraws only the credentials it released. Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`; a request that outlives the plugin ends through its credential's `revoked` signal, and the plugin's failure callback for that request cancels the work. diff --git a/docs/subsystems/account.zh.md b/docs/subsystems/account.zh.md index c6c0b19974..1c15bd9c3d 100644 --- a/docs/subsystems/account.zh.md +++ b/docs/subsystems/account.zh.md @@ -8,7 +8,7 @@ ## 请求凭据 -`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。`deepseek-account` 模型路由通过 `ctx.llm.providerCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。 +`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。其 `revoked` 信号在账号退出该 token 所属的登录时中止,无论退登由用户发起还是由拒绝触发,且在 `deepseek-account/signed-out` 的监听器返回之后;账号模型路由和 DeepSeek Web 提供方让携带该 token 的每个模型、Files、Search 与 Fetch 请求受它约束,因此即使发出请求的插件已卸载,退登仍会结束这些请求。消费方不直接调用它:[`ctx.deepseekAuth`](../../packages/account/deepseek-auth/README.zh.md) 代 `deepseek-account` 模型路由和 DeepSeek Web 提供方索取这份凭据,目标地址位于该路由基础地址的 origin 之下;没有该路由时,位于 `DEEPSEEK_BASE_URL` 的 origin 之下。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。已被替换的账号服务释放的凭据,其信号保持未中止,因为替换后的服务只撤回自己释放的凭据。 按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责;比插件存活更久的请求通过其凭据的 `revoked` 信号结束,插件为该请求提供的失败回调随后取消这些工作。 diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index dbb124b198..49f34b6799 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -36,8 +36,8 @@ en: 58dec2259b0b1c6f zh: fc99fe965acaabf3 /llm-streaming/the-model-request: - en: 61d4131601adbc32 - zh: b83156c875d29b89 + en: 834d3d8d6b5871ab + zh: 393889ec6075f622 /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: en: b0eb4620c6953646 zh: fabf51c7245a4855 @@ -48,5 +48,5 @@ en: 8c140f9c5a799f01 zh: f66b895594247e92 /llm-streaming/service-and-provider-contracts: - en: 81b4ede66c5e906d - zh: 2ad0ddb1a32e3167 + en: 8dc79d4cc82824c2 + zh: 3ebabd3a117ad717 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 1e93b92f64..078f4f4700 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -527,86 +527,6 @@ interface LlmNativeAuth { } ``` -A route's adapter can also publish the credential the route currently sends, so consumers that call the same deployment outside the model request path, such as the DeepSeek web providers, reuse it through `ctx.llm.providerCredential(provider)` instead of reading provider configuration or choosing header names. A grant is Host-only and is held for one operation; `kind` is merge-extensible through `LlmCredentialKindMap`, whose declared members are `api-key` and `account`. A grant whose owner can withdraw the credential while requests carry it, as an account sign-out does, has a `revoked` signal: the consumer runs each request it authenticates under that signal and reports a request the signal ended as its own failure, not as the caller's cancellation. - -```ts type-equiv -/** - * One credential released for one destination. Host-only: it carries the - * secret, so it never crosses a Remote boundary and never enters a log. - */ -interface ProviderCredentialGrant { - /** - * Request headers carrying the credential as the route's own protocol - * expects it, such as `x-api-key` for an API key. Consumers speaking that - * protocol send them unchanged. - */ - readonly headers: Readonly> - /** - * The bare credential value, for destinations whose protocol renders it - * differently from {@link headers}, such as `Authorization: Bearer`. - */ - readonly value: string - /** - * Invalidate this exact credential after the destination rejected it with - * HTTP 401 so no later request resends it. Absent for kinds without - * invalidation. The owner contains storage failures: the caller reports the - * destination's rejection, never a failure of this call. - * @returns settlement after the invalidation attempt. - */ - reject?(): Promise - /** - * Aborts when the owner withdraws this credential while requests carrying it - * may be in flight, as an account sign-out does. A consumer ends each request - * it authenticated with this grant and reports that end as its own failure, - * not as the caller's cancellation. Absent for kinds that are never withdrawn. - */ - readonly revoked?: AbortSignal -} -``` - -```ts type-equiv -/** - * The credential one registered provider route currently sends, answered by - * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.providerCredential()` resolves a new value - * per call from one configuration generation; a caller keeps it for one - * operation only. - */ -interface ProviderCredential { - /** Kind of credential the route sends. */ - readonly kind: LlmCredentialKind - /** - * The route's current request base URL as its configuration resolves it, - * environment fallbacks included: the destination this credential is meant - * for. Consumers derive sibling endpoints of the same deployment from it. - */ - readonly baseURL: string - /** - * Credential reference the route resolves, for diagnostics that tell the user - * where to configure the credential; absent for kinds without a stored - * reference, such as sign-in grants. - */ - readonly reference?: string - /** - * Whether {@link resolve} would release a credential for `endpoint`, checked - * without validating the credential or contacting the destination; the owner - * may read its store to answer. Store failures reject. - * @param endpoint - absolute URL the credential would be sent to. - * @returns whether a credential is configured for that destination. - */ - configured(endpoint: string): Promise - /** - * Release the credential for `endpoint`, or `undefined` when none is - * configured or the destination may not receive it. The caller chooses the - * failure it reports for `undefined`. Store and format failures reject. - * @param endpoint - absolute URL the credential will be sent to. - * @param signal - cancellation for the lookup. - * @returns the released credential, or `undefined`. - */ - resolve(endpoint: string, signal?: AbortSignal): Promise -} -``` - A catalog entry may carry a provider-authored `badge` that selectors show beside the model name. It is display data: `resolveModelInfo` omits it, and no model request carries it. ```ts type-equiv @@ -950,8 +870,6 @@ The [wire reference](../deepseek-llm-api-wire-extensions.md) defines the exact r `LlmAdapter` is the provider contract: subclass, implement `stream()`, and register one adapter instance with `ctx.llm.registerAdapter(providers, adapter)`. `GenerateOptions.provider` selects the registered adapter; `GenerateOptions.model` is passed to that adapter and need not be registered at lifecycle start. Duplicate provider routes fail atomically. Optional `providerRetryPolicy()` is captured per route with normal defaults, while `providerInfo()` and asynchronous `listModels()` feed `LlmRuntime.listProviders()` / `listModels()` with detached selector metadata. That catalog is advisory rather than a request whitelist: the adapter remains authoritative and may accept unlisted model ids. One asynchronous `resolveModel()` query returns exact model identity plus optional correctness-sensitive context capacity, an adapter-configured `defaultMaxTokens`, and ordered model-owned reasoning ids with an optional deployment default; absent fields mean unavailable metadata or provider-owned behavior, not invalid catalog membership. The resolver receives optional cancellation and must settle promptly after abort. `LlmRuntime.resolveModelInfo()` validates and detaches the aggregate. At the final adapter boundary, `resolveCallConfig()` materializes the output default only when `maxTokens` is absent and validates and materializes reasoning, so direct calls cannot bypass either configured behavior; direct dispatch captures one registration before awaiting that resolution. The agent loop instead uses `prepareCall()` to keep the same registration across model resolution, durable header logging, and dispatch, retain detached context metadata from that exact lookup, and report which config fields the adapter defaulted. Adapter lookup happens at the terminal continuation of the `llm/stream` waterfall, so a listener may short-circuit the call or route a mutable one-shot request before lookup. AgentLoop observes a request attempt once the outer waterfall returns a stream handle; that limited boundary does not prove a lazy terminal adapter was constructed or began provider I/O. The `block-start` / `block-end` `index` correlation and the assembler together mean an adapter only has to emit well-formed chunks — block reassembly is not each adapter's problem. [architecture.md](../architecture.md#turn-flow) shows where `ctx.llm.stream()` and the `llm/stream` waterfall sit in one turn. -Optional `providerCredential()` publishes the credential a route currently sends, with the route's base URL, its kind, and an optional credential reference. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter: an unregistered route answers `undefined`, because callers ask about routes a conversation named earlier, and a registered route whose configuration does not resolve propagates the adapter's failure. The DeepSeek web providers read it to call the deployment of the conversation's route with that route's credential, so no consumer reads another plugin's configuration or chooses its header names. - ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ interface PreparedLlmCall { @@ -1019,16 +937,6 @@ declare abstract class LlmAdapter { * @returns the same target used by request serialization, before provider-internal processing. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; - /** - * Describe the credential one owned route currently sends, for consumers that - * call the same deployment outside the model request path, such as web - * providers that share a route's credential and endpoint. The default - * publishes none. Implementations answer from one configuration generation - * per call and may throw when that configuration does not resolve. - * @param _provider - a route passed to `registerAdapter()` for this instance. - * @returns the route's current credential, or `undefined` when the route publishes none. - */ - providerCredential(_provider: string): ProviderCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1209,17 +1117,6 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget -/** - * Resolve the credential one registered route currently sends, through its - * owning adapter. An unregistered route answers `undefined` rather than - * throwing because callers ask about routes a conversation named earlier, - * which may no longer be mounted; a registered route whose configuration - * does not resolve propagates the adapter's failure. - * @param provider - provider route whose credential is wanted. - * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. - */ -providerCredential(provider: string): ProviderCredential | undefined - /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 2e8707f13a..dcebebf666 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -533,86 +533,6 @@ interface LlmNativeAuth { } ``` -路由的适配器还可以发布该路由当前发送的凭据,使在模型请求路径之外调用同一部署的消费方(如 DeepSeek Web 提供方)通过 `ctx.llm.providerCredential(provider)` 复用它,而不读取提供方配置或自行选择请求头名称。授权仅限 Host,且只在一次操作内持有;`kind` 通过 `LlmCredentialKindMap` 可合并扩展,已声明的成员为 `api-key` 和 `account`。所有者可能在请求仍携带凭据时撤回它(例如账号退登),这类授权带有 `revoked` 信号:消费方让它鉴权的每个请求都受该信号约束,并把被该信号结束的请求报告为自身的失败,而不是调用方的取消。 - -```ts type-equiv -/** - * One credential released for one destination. Host-only: it carries the - * secret, so it never crosses a Remote boundary and never enters a log. - */ -interface ProviderCredentialGrant { - /** - * Request headers carrying the credential as the route's own protocol - * expects it, such as `x-api-key` for an API key. Consumers speaking that - * protocol send them unchanged. - */ - readonly headers: Readonly> - /** - * The bare credential value, for destinations whose protocol renders it - * differently from {@link headers}, such as `Authorization: Bearer`. - */ - readonly value: string - /** - * Invalidate this exact credential after the destination rejected it with - * HTTP 401 so no later request resends it. Absent for kinds without - * invalidation. The owner contains storage failures: the caller reports the - * destination's rejection, never a failure of this call. - * @returns settlement after the invalidation attempt. - */ - reject?(): Promise - /** - * Aborts when the owner withdraws this credential while requests carrying it - * may be in flight, as an account sign-out does. A consumer ends each request - * it authenticated with this grant and reports that end as its own failure, - * not as the caller's cancellation. Absent for kinds that are never withdrawn. - */ - readonly revoked?: AbortSignal -} -``` - -```ts type-equiv -/** - * The credential one registered provider route currently sends, answered by - * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.providerCredential()` resolves a new value - * per call from one configuration generation; a caller keeps it for one - * operation only. - */ -interface ProviderCredential { - /** Kind of credential the route sends. */ - readonly kind: LlmCredentialKind - /** - * The route's current request base URL as its configuration resolves it, - * environment fallbacks included: the destination this credential is meant - * for. Consumers derive sibling endpoints of the same deployment from it. - */ - readonly baseURL: string - /** - * Credential reference the route resolves, for diagnostics that tell the user - * where to configure the credential; absent for kinds without a stored - * reference, such as sign-in grants. - */ - readonly reference?: string - /** - * Whether {@link resolve} would release a credential for `endpoint`, checked - * without validating the credential or contacting the destination; the owner - * may read its store to answer. Store failures reject. - * @param endpoint - absolute URL the credential would be sent to. - * @returns whether a credential is configured for that destination. - */ - configured(endpoint: string): Promise - /** - * Release the credential for `endpoint`, or `undefined` when none is - * configured or the destination may not receive it. The caller chooses the - * failure it reports for `undefined`. Store and format failures reject. - * @param endpoint - absolute URL the credential will be sent to. - * @param signal - cancellation for the lookup. - * @returns the released credential, or `undefined`. - */ - resolve(endpoint: string, signal?: AbortSignal): Promise -} -``` - 目录条目可以携带提供方编写的 `badge`,供选择器显示在模型名称旁。它只是展示数据:`resolveModelInfo` 不返回它,模型请求也不携带它。 ```ts type-equiv @@ -956,8 +876,6 @@ interface LlmCallConfigAdapterDefaults { `LlmAdapter` 是提供方约定:创建子类、实现 `stream()`,再用 `ctx.llm.registerAdapter(providers, adapter)` 注册一个适配器实例。`GenerateOptions.provider` 选择已注册适配器;`GenerateOptions.model` 会传给该适配器,无需在生命周期启动时注册。重复提供方路由会原子失败。可选的 `providerRetryPolicy()` 会按路由捕获并填入 normal 默认值,`providerInfo()` 与异步 `listModels()` 方法则为 `LlmRuntime.listProviders()` / `listModels()` 提供分离的 selector 元数据。该目录仅供参考,不是请求白名单:适配器仍是权威,并可接受未列出的模型 id。单次异步 `resolveModel()` 查询返回确切模型身份,以及可选的对正确性敏感的上下文容量、适配器配置的 `defaultMaxTokens`、由模型持有的有序推理强度 ID 和可选的部署默认值;字段缺失表示元数据不可用或保留提供方持有的行为,而不表示目录成员关系无效。解析器会接收可选的取消信号,并且必须在信号中止后迅速完成结算。`LlmRuntime.resolveModelInfo()` 会校验聚合结果并返回分离值。在最终适配器边界,`resolveCallConfig()` 仅在 `maxTokens` 缺失时填入输出默认值,并校验和填入推理强度,因此直接调用也无法绕过任何一项已配置行为;直接分派会在等待解析前捕获一项适配器注册。agent loop 则使用 `prepareCall()`,使模型解析、请求头持久记录和分派全程使用同一项注册,保留来自同一次查询的分离上下文元数据,并报告适配器填入的配置字段。适配器查找发生在 `llm/stream` waterfall 的终端 continuation,因此 listener 可以在查找前短路调用,或路由一个可变的一次性请求。AgentLoop 在外层 waterfall 返回流句柄时观察到一次请求尝试;这个有限边界不能证明惰性终端适配器已构造完成或开始提供方 I/O。`block-start` / `block-end` 的 `index` 关联与 assembler 共同意味着适配器只需 emit 格式正确的分片——块重组不是每个适配器各自的问题。`ctx.llm.stream()` 与 `llm/stream` waterfall 在一个轮次中的位置见 [architecture.md](../architecture.zh.md#turn-flow)。 -可选的 `providerCredential()` 发布路由当前发送的凭据,连同路由的基础地址、凭据种类和可选的凭据引用。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器:未注册的路由回答 `undefined`,因为调用方询问的是会话早先命名的路由;已注册但配置无法解析的路由则传播适配器的失败。DeepSeek Web 提供方据此用会话路由的凭据调用同一部署,因此没有消费方需要读取其他插件的配置或自行选择请求头名称。 - ```ts type-equiv /** One model call whose config and adapter registration were resolved together. */ interface PreparedLlmCall { @@ -1025,16 +943,6 @@ declare abstract class LlmAdapter { * @returns the same target used by request serialization, before provider-internal processing. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; - /** - * Describe the credential one owned route currently sends, for consumers that - * call the same deployment outside the model request path, such as web - * providers that share a route's credential and endpoint. The default - * publishes none. Implementations answer from one configuration generation - * per call and may throw when that configuration does not resolve. - * @param _provider - a route passed to `registerAdapter()` for this instance. - * @returns the route's current credential, or `undefined` when the route publishes none. - */ - providerCredential(_provider: string): ProviderCredential | undefined; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -1215,17 +1123,6 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget -/** - * Resolve the credential one registered route currently sends, through its - * owning adapter. An unregistered route answers `undefined` rather than - * throwing because callers ask about routes a conversation named earlier, - * which may no longer be mounted; a registered route whose configuration - * does not resolve propagates the adapter's failure. - * @param provider - provider route whose credential is wanted. - * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. - */ -providerCredential(provider: string): ProviderCredential | undefined - /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 52b9adaa79..18db490799 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2261,12 +2261,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'provider', description: 'registered provider route.' }, { name: 'model', description: 'exact model id.' }, { name: 'image', description: 'normalized image reference.' }], returns: 'dimensions and byte target used by the adapter\'s request serializer.', }, - { - signature: 'providerCredential(provider: string): ProviderCredential | undefined', - description: 'Resolve the credential one registered route currently sends, through its owning adapter. An unregistered route answers `undefined` rather than throwing because callers ask about routes a conversation named earlier, which may no longer be mounted; a registered route whose configuration does not resolve propagates the adapter\'s failure.', - parameters: [{ name: 'provider', description: 'provider route whose credential is wanted.' }], - returns: 'the route\'s credential, or `undefined` when the route is unregistered or publishes none.', - }, { signature: 'fileRequestText(ref: FileAttachmentRef): string', description: 'Resolve the exact text one durable file occurrence contributes to every provider request in the current execution environment.', @@ -7668,7 +7662,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmAdapter', - declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n providerCredential(_provider: string): ProviderCredential | undefined;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', + declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;\n imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget;\n listModels(_provider: string): Promise;\n resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise;\n async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', }, { name: 'LlmAttemptId', @@ -7690,14 +7684,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'LlmConfigurableProvider', declaration: 'export interface LlmConfigurableProvider {\n provider: string;\n displayName: string;\n settingsNs: string;\n settingsPath: readonly string[];\n declared?: boolean;\n defaultBaseURL?: string;\n baseURLEnv?: readonly string[];\n nativeAuth?: LlmNativeAuth;\n error?: string;\n}', }, - { - name: 'LlmCredentialKind', - declaration: 'export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap];', - }, - { - name: 'LlmCredentialKindMap', - declaration: 'export interface LlmCredentialKindMap {\n \'api-key\': \'api-key\';\n account: \'account\';\n}', - }, { name: 'LlmDiscoveredModel', declaration: 'export interface LlmDiscoveredModel {\n id: string;\n name?: string;\n contextWindow?: number;\n maxTokens?: number;\n inputModalities?: readonly ModelModality[];\n}', @@ -7764,7 +7750,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'LlmRuntime', - declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n providerCredential(provider: string): ProviderCredential | undefined;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, /* …truncated — full shape in source */', + declaration: 'export class LlmRuntime extends TypertRemoteService {\n constructor(ctx: Context);\n registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;\n @Remote\n listProviders(): LlmProviderInfo[];\n registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;\n @Remote\n listConfigurableProviders(): LlmConfigurableProvider[];\n registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void;\n async discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise;\n @Remote(\'discoverModels\')\n async remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise;\n providerRetryPolicy(provider: string): ResolvedRetryPolicy;\n imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;\n imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget;\n fileRequestText(ref: FileAttachmentRef): string;\n async listModels(provider: string): Promise;\n async resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise;\n async resolveCallConfig(config: LlmCallConfig, signal?: AbortSignal): Promise;\n async prepareCall(conf /* …truncated — full shape in source */', }, { name: 'LocalAtInput', @@ -8570,14 +8556,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'PromptSubmitResult', declaration: 'export type PromptSubmitResult = {\n text: string;\n context?: readonly string[];\n drop?: undefined;\n} | {\n drop: string;\n text?: undefined;\n context?: undefined;\n};', }, - { - name: 'ProviderCredential', - declaration: 'export interface ProviderCredential {\n readonly kind: LlmCredentialKind;\n readonly baseURL: string;\n readonly reference?: string;\n configured(endpoint: string): Promise;\n resolve(endpoint: string, signal?: AbortSignal): Promise;\n}', - }, - { - name: 'ProviderCredentialGrant', - declaration: 'export interface ProviderCredentialGrant {\n readonly headers: Readonly>;\n readonly value: string;\n reject?(): Promise;\n readonly revoked?: AbortSignal;\n}', - }, { name: 'ProviderRequestId', declaration: 'export type ProviderRequestId = Branded<\'ProviderRequestId\'>;', diff --git a/packages/llm/llm-deepseek-account/README.i18n.yaml b/packages/llm/llm-deepseek-account/README.i18n.yaml index ab9e5e1b82..b92f55b9e1 100644 --- a/packages/llm/llm-deepseek-account/README.i18n.yaml +++ b/packages/llm/llm-deepseek-account/README.i18n.yaml @@ -9,8 +9,8 @@ en: 8fa1148e0ee9d351 zh: 634ec9d79d5ffbf0 /deepseek-ai-dsh-llm-deepseek-account/summary: - en: 47201804733ec769 - zh: 3c6751b16a45759f + en: 466b1a18951c842f + zh: de5eadda25953caf /deepseek-ai-dsh-llm-deepseek-account/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 diff --git a/packages/llm/llm-deepseek-account/README.md b/packages/llm/llm-deepseek-account/README.md index 283b36d3eb..03243a2587 100644 --- a/packages/llm/llm-deepseek-account/README.md +++ b/packages/llm/llm-deepseek-account/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, the account model listing, and model gating for `deepseek-account`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, the account catalog, and model admission. -Authentication resolution returns the request credential the account service releases for the destination, carrying `x-dsh-auth-token`, with a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route publishes the account credential through `ctx.llm.providerCredential('deepseek-account')` with its base URL, so the DeepSeek web providers send it to the same deployment. +Authentication resolution asks [`ctx.deepseekAuth`](../../account/deepseek-auth/README.md) for the account sign-in the account service releases for the destination, carrying `x-dsh-auth-token`, and adds a failure callback that invalidates that same credential. HTTP 401 classification stays in this provider; a rejected older request cannot clear a replacement login. The route connects its base URL to that service, so the DeepSeek web providers send the account sign-in to the same deployment. ## Table of Contents diff --git a/packages/llm/llm-deepseek-account/README.zh.md b/packages/llm/llm-deepseek-account/README.zh.md index 04b6256544..ebb0b5ba73 100644 --- a/packages/llm/llm-deepseek-account/README.zh.md +++ b/packages/llm/llm-deepseek-account/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-account` 注册鉴权、账号模型列表和模型门控。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包负责凭据解析、账号目录和模型准入。 -鉴权解析返回账号服务为目标地址释放的请求凭据,携带 `x-dsh-auth-token`,并附带使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由通过 `ctx.llm.providerCredential('deepseek-account')` 连同其基础地址发布账号凭据,使 DeepSeek Web 提供方把它发往同一部署。 +鉴权解析向 [`ctx.deepseekAuth`](../../account/deepseek-auth/README.zh.md) 索取账号服务为目标地址释放的账号登录凭据,携带 `x-dsh-auth-token`,并附加使同一凭据失效的失败回调。HTTP 401 的分类由此提供方负责;被拒绝的旧请求不能清除替换后的登录。路由把自己的基础地址登记到该服务,使 DeepSeek Web 提供方把账号登录凭据发往同一部署。 ## 目录 diff --git a/packages/llm/llm-deepseek-account/src/index.ts b/packages/llm/llm-deepseek-account/src/index.ts index 0daf79ad29..e1fe276eb7 100644 --- a/packages/llm/llm-deepseek-account/src/index.ts +++ b/packages/llm/llm-deepseek-account/src/index.ts @@ -2,8 +2,7 @@ import type {} from '@deepseek-ai/cordis-plugin-loader' import type { Context } from '@deepseek-ai/cordis' import { ACCOUNT_QUOTA_EXCEEDED_CODE, APP_IDENTITY, LlmError, QUOTA_EXCEEDED_CODE } from '@deepseek-ai/dsh-llm' -import type { AccountRequestCredential } from '@deepseek-ai/dsh-deepseek-account' -import type {} from '@deepseek-ai/dsh-deepseek-auth' +import type { DeepSeekAuthorization } from '@deepseek-ai/dsh-deepseek-auth' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveAdapterOptions, resolveListedCatalog, @@ -32,36 +31,41 @@ export function apply(ctx: Context, config: Config): void { // Every other DeepSeek consumer billed by the account sends the sign-in to this route's deployment. ctx.effect(() => ctx.deepseekAuth.connect('account', () => ({ baseURL: settings().protocol.baseURL })), 'llm-deepseek-account: account deployment') const supported = resolveAdapterOptions({}).models - /** The account credential released for one destination; absent without an allowed signed-in account or without the account service. */ - const requestCredential = async (endpoint: string): Promise => - await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) + /** + * The account sign-in `ctx.deepseekAuth` releases for one destination under the deployment at `baseURL`; absent + * without an allowed signed-in account or without the account service. + */ + const requestCredential = (baseURL: string, endpoint: string): Promise => + ctx.deepseekAuth.authorize({ + consumer: name, accepts: ['account'], billing: 'account', destination: { url: endpoint }, connections: { account: { baseURL } }, + }) /** The failure of a request whose account signed out before it finished: the code a request made after the sign-out fails with. */ const signedOutMidRequest = (cause: unknown) => new LlmError( 'The DeepSeek account signed out before this request finished. Sign in to DeepSeek to use the account provider.', 'ACCOUNT_SIGN_IN_REQUIRED', { cause }, ) - const resolveAuth = async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { - const credential = await requestCredential(endpoint) + const resolveAuth = async (connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { + const credential = await requestCredential(connection.baseURL, endpoint) if (credential === undefined) return undefined return { ...credential, onRequestError: async (error) => { try { // A sign-out ends the requests that carry its token, so it is the failure of any request that fails after it. - if (credential.revoked.aborted) return signedOutMidRequest(error) + if (credential.revoked?.aborted === true) return signedOutMidRequest(error) if (!(error instanceof LlmError)) return error if (error.code === QUOTA_EXCEEDED_CODE) { return new LlmError(error.message, ACCOUNT_QUOTA_EXCEEDED_CODE, { ...error.failure, cause: error }) } if (error.failure.status !== 401) return error const rejected = new LlmError(error.message, 'ACCOUNT_TOKEN_INVALID', { ...error.failure, cause: error }) - await credential.reject() + await credential.reject?.() return rejected } finally { // A request can outlive this plugin and the sign-out listener it mounts. Once the credential it carried is // signed out, by the user or by the rejection above, the request ends this route's tasks itself. - if (credential.revoked.aborted) cancelAccountTasks(ctx, PROVIDER) + if (credential.revoked?.aborted === true) cancelAccountTasks(ctx, PROVIDER) } }, } @@ -72,7 +76,7 @@ export function apply(ctx: Context, config: Config): void { ) const catalog = createModelListingCache(ctx, name, PROVIDER, { settings: () => settings().catalog, - credential: async url => (await requestCredential(url))?.headers, + credential: async url => (await requestCredential(settings().protocol.baseURL, url))?.headers, }) let loggedListing: ModelListing | undefined /** Resolve the catalog, reporting each listing's hidden entries and dropped badges once. */ @@ -110,10 +114,6 @@ export function apply(ctx: Context, config: Config): void { connect: async signal => connectionOf(await catalog.view(settings().catalog, signal)), resolveAuth, missingCredential, - credential: { - kind: 'account', - configured: async (_connection, endpoint) => (await requestCredential(endpoint)) !== undefined, - }, admit: (connection, model) => { refuseListedModel(model, connection.catalog.refusals.get(model)) }, discoverModels: async (provider) => { const view = await catalog.view(settings().catalog) diff --git a/packages/llm/llm-deepseek-account/tests/provider.spec.ts b/packages/llm/llm-deepseek-account/tests/provider.spec.ts index 93c4f432b5..786c2a9e3c 100644 --- a/packages/llm/llm-deepseek-account/tests/provider.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/provider.spec.ts @@ -217,35 +217,19 @@ it('aborts an in-flight listing request when the plugin is disposed', async () = await expect(pending).resolves.toEqual(expect.any(Array)) }) -it('publishes the account credential for its consumers, asking the account for each endpoint', async () => { +it('connects its deployment, so other DeepSeek consumers send the account sign-in to its origin', async () => { const asked: string[] = [] - let token: string | undefined = 'fixture-account-token' const ctx = new Context() contexts.push(ctx) await ctx.plugin(LlmRuntime) - ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return token } })) + ctx.provide('deepseekAccount', accountStub({ token: (url) => { asked.push(url); return 'fixture-account-token' } })) await ctx.plugin(DeepSeekAuth) - await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) - const credential = ctx.llm.providerCredential('deepseek-account') - expect(credential).toMatchObject({ kind: 'account', baseURL: 'https://account.deepseek.test/anthropic' }) - expect(credential).not.toHaveProperty('reference') - const endpoint = 'https://account.deepseek.test/v1/tools/search' - await expect(credential!.configured(endpoint)).resolves.toBe(true) - await expect(credential!.resolve(endpoint)).resolves.toMatchObject({ headers: { 'x-dsh-auth-token': 'fixture-account-token' }, value: 'fixture-account-token' }) - token = undefined - await expect(credential!.configured(endpoint)).resolves.toBe(false) - await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() - expect(asked).toEqual([endpoint, endpoint, endpoint, endpoint]) - expect(ctx.llm.providerCredential('deepseek-official')).toBeUndefined() -}) - -it('publishes a credential nobody holds without the account service', async () => { - const ctx = new Context() - contexts.push(ctx) - await ctx.plugin(LlmRuntime) - await ctx.plugin(DeepSeekAuth) - await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) - const credential = ctx.llm.providerCredential('deepseek-account')! - await expect(credential.configured('https://account.deepseek.test/v1/tools/search')).resolves.toBe(false) - await expect(credential.resolve('https://account.deepseek.test/v1/tools/search')).resolves.toBeUndefined() + const search = { consumer: 'web-test', accepts: ['account'], billing: 'account', destination: { path: '/v1/tools/search' } } as const + const route = await ctx.plugin(Account, { baseURL: 'https://account.deepseek.test/anthropic' }) + expect(await ctx.deepseekAuth.authorize(search)).toMatchObject({ + kind: 'account', endpoint: 'https://account.deepseek.test/v1/tools/search', headers: { 'x-dsh-auth-token': 'fixture-account-token' }, + }) + await route.dispose() + expect(await ctx.deepseekAuth.authorize(search)).toMatchObject({ endpoint: 'https://api.deepseek.com/v1/tools/search' }) + expect(asked).toEqual(['https://account.deepseek.test/v1/tools/search', 'https://api.deepseek.com/v1/tools/search']) }) diff --git a/packages/llm/llm-deepseek-api-key/README.i18n.yaml b/packages/llm/llm-deepseek-api-key/README.i18n.yaml index 6b0f0744ae..7f01bc99d7 100644 --- a/packages/llm/llm-deepseek-api-key/README.i18n.yaml +++ b/packages/llm/llm-deepseek-api-key/README.i18n.yaml @@ -9,8 +9,8 @@ en: b6871195e386cc64 zh: 742b05a3ca80883c /deepseek-ai-dsh-llm-deepseek-api-key/summary: - en: 25f6f430c8ce1a6b - zh: b221bef9390771e7 + en: 9e46b11b7133c385 + zh: 7ceba18fb20300f0 /deepseek-ai-dsh-llm-deepseek-api-key/table-of-contents: en: 23386452a66b2fbd zh: 4cf93c4bf17b3da2 diff --git a/packages/llm/llm-deepseek-api-key/README.md b/packages/llm/llm-deepseek-api-key/README.md index c0010921d9..f86ca04fc7 100644 --- a/packages/llm/llm-deepseek-api-key/README.md +++ b/packages/llm/llm-deepseek-api-key/README.md @@ -11,7 +11,7 @@ English | [中文](README.zh.md) Register authentication, model discovery, and the official model listing for `deepseek-official`. This plugin shares the [Messages transport](../llm-deepseek/README.md) and owns credential resolution, catalog availability, and model admission. -Authentication resolution returns the validated API key in `x-api-key` for Messages, Files, and listing requests, and publishes the same key through `ctx.llm.providerCredential('deepseek-official')` with the route's base URL and `apiKeyEnv` reference, so the DeepSeek web providers send it as a bearer token to the same deployment. The published credential releases the key only for destinations under the origin of that base URL. +Authentication resolution asks [`ctx.deepseekAuth`](../../account/deepseek-auth/README.md) for the validated API key in `x-api-key` for Messages, Files, and listing requests. The route connects its base URL and `apiKeyEnv` reference to that service, so the DeepSeek web providers send the same key as a bearer token to the same deployment. The key is released only for destinations under the origin of that base URL. ## Table of Contents diff --git a/packages/llm/llm-deepseek-api-key/README.zh.md b/packages/llm/llm-deepseek-api-key/README.zh.md index 59b5229f04..b4918b6cd9 100644 --- a/packages/llm/llm-deepseek-api-key/README.zh.md +++ b/packages/llm/llm-deepseek-api-key/README.zh.md @@ -11,7 +11,7 @@ kind: "package-reference" 为 `deepseek-official` 注册鉴权、模型发现和官方模型列表。通过 [llm-deepseek](../llm-deepseek/README.zh.md) 共用 Messages 请求实现;本包拥有凭据解析、目录可用性判断和模型准入。 -鉴权解析将验证后的 API key 放入 `x-api-key`,供 Messages、Files 和列表请求使用,并通过 `ctx.llm.providerCredential('deepseek-official')` 连同路由的基础地址和 `apiKeyEnv` 引用发布同一密钥,使 DeepSeek Web 提供方以 Bearer 令牌把它发往同一部署。发布的凭据只对该基础地址所在 origin 下的目的地释放密钥。 +鉴权解析向 [`ctx.deepseekAuth`](../../account/deepseek-auth/README.zh.md) 索取验证后的 API key,放入 `x-api-key`,供 Messages、Files 和列表请求使用。路由把自己的基础地址和 `apiKeyEnv` 引用登记到该服务,使 DeepSeek Web 提供方以 Bearer 令牌把同一密钥发往同一部署。密钥只对该基础地址所在 origin 下的目的地释放。 ## 目录 diff --git a/packages/llm/llm-deepseek-api-key/src/index.ts b/packages/llm/llm-deepseek-api-key/src/index.ts index 4aac845a8b..8b4cea8d8e 100644 --- a/packages/llm/llm-deepseek-api-key/src/index.ts +++ b/packages/llm/llm-deepseek-api-key/src/index.ts @@ -1,10 +1,9 @@ /** API-key authentication, credential-gated discovery, and the official model listing for the official DeepSeek route. */ import type { Context } from '@deepseek-ai/cordis' -import { APP_IDENTITY, assertUsableApiKey, LlmError } from '@deepseek-ai/dsh-llm' +import { APP_IDENTITY, INVALID_CREDENTIAL_CODE, LlmError } from '@deepseek-ai/dsh-llm' import type { LlmModelBadge } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/cordis-plugin-loader' -import { credentialRefConfigured, resolveCredentialRef } from '@deepseek-ai/dsh-credentials' -import type {} from '@deepseek-ai/dsh-deepseek-auth' +import { DeepSeekAuthError } from '@deepseek-ai/dsh-deepseek-auth' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { catalogModelInfo, createModelListingCache, refuseListedModel, registerDeepSeekProvider, resolveListedCatalog, @@ -42,24 +41,24 @@ export function apply(ctx: Context, config: Config): void { const connection = options() return { baseURL: connection.baseURL, reference: connection.apiKeyEnv, owner: settingsNs } }), 'llm-deepseek-api-key: API-key deployment') - /** The validated API key, or `undefined` when none is configured; store and format failures propagate. */ - const resolveApiKey = async (connection: ResolvedDeepSeekOptions): Promise => { - const value = await resolveCredentialRef(ctx, connection.apiKeyEnv) - return value === undefined ? undefined : assertUsableApiKey(value, settingsNs, connection.apiKeyEnv) - } /** - * Whether `endpoint` belongs to the deployment this route sends its key to: the origin of the route's base URL, - * without credentials embedded in the URL. + * The key `ctx.deepseekAuth` releases for `endpoint` from one configuration generation, in the header Messages + * expects; `undefined` when none is configured or `endpoint` is outside the route's deployment. An unusable key fails + * as this route's `INVALID_CREDENTIAL`; store failures propagate. */ - const servedByRoute = (connection: ResolvedDeepSeekOptions, endpoint: string): boolean => { - const destination = new URL(endpoint) - return destination.origin === new URL(connection.baseURL).origin && destination.username === '' && destination.password === '' - } const resolveAuth = async (connection: ResolvedDeepSeekOptions, endpoint: string): Promise => { - // The store is read only for a destination this route serves, as the presence check below. - if (!servedByRoute(connection, endpoint)) return undefined - const key = await resolveApiKey(connection) - return key === undefined ? undefined : { headers: { 'x-api-key': key }, value: key } + try { + return await ctx.deepseekAuth.authorize({ + consumer: settingsNs, accepts: ['api-key'], billing: 'api-key', destination: { url: endpoint }, + connections: { 'api-key': { baseURL: connection.baseURL, reference: connection.apiKeyEnv } }, + apiKeyHeaders: ['x-api-key'], + }) + } catch (error) { + if (error instanceof DeepSeekAuthError && error.code === 'INVALID_CREDENTIAL') { + throw new LlmError(error.message, INVALID_CREDENTIAL_CODE, { cause: error }) + } + throw error + } } const missingCredential = (connection: ResolvedDeepSeekOptions) => new LlmError( `llm-deepseek: no API key for provider route "${PROVIDER}"; store ${connection.apiKeyEnv} through the credentials` @@ -111,17 +110,11 @@ export function apply(ctx: Context, config: Config): void { }, resolveAuth, missingCredential, - credential: { - kind: 'api-key', - reference: connection => connection.apiKeyEnv, - configured: async (connection, endpoint) => - servedByRoute(connection, endpoint) && await credentialRefConfigured(ctx, connection.apiKeyEnv), - }, admit: (connection, model) => { refuseListedModel(model, connection.refusals.get(model)) }, discoverModels: async (provider) => { const connection = options() if (connection.listing === undefined) { - if (await resolveApiKey(connection) === undefined) return [] + if (await resolveAuth(connection, connection.baseURL) === undefined) return [] return connection.models.map(model => catalogModelInfo(provider, model)) } const view = await listings.view(connection.listing) diff --git a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts index aed2c2b622..f20bb4e6ec 100644 --- a/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts +++ b/packages/llm/llm-deepseek-api-key/tests/discovery.spec.ts @@ -77,54 +77,37 @@ it('names the Loader entry id in credential diagnostics, as product profiles mou } }) -it('publishes the route API key for its consumers from the credential planes it reads itself', async () => { - vi.stubEnv('DEEPSEEK_API_KEY', 'fixture-api-key') +it('connects its key reference and deployment, so other DeepSeek consumers send its key to its origin', async () => { + vi.stubEnv('DEEPSEEK_API_KEY', 'default-key') + vi.stubEnv('ROUTE_KEY', 'fixture-api-key') const ctx = new Context() try { await ctx.plugin(LlmRuntime) await ctx.plugin(DeepSeekAuth) - await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) - const credential = ctx.llm.providerCredential('deepseek-official') - expect(credential).toMatchObject({ kind: 'api-key', baseURL: 'https://route.deepseek.test/anthropic', reference: 'DEEPSEEK_API_KEY' }) - const endpoint = 'https://route.deepseek.test/v1/tools/search' - await expect(credential!.configured(endpoint)).resolves.toBe(true) - await expect(credential!.resolve(endpoint)).resolves.toEqual({ headers: { 'x-api-key': 'fixture-api-key' }, value: 'fixture-api-key' }) - vi.stubEnv('DEEPSEEK_API_KEY', '') - await expect(credential!.configured(endpoint)).resolves.toBe(false) - await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() - vi.stubEnv('DEEPSEEK_API_KEY', 'invalid\nheader') - await expect(credential!.configured(endpoint)).resolves.toBe(true) - await expect(credential!.resolve(endpoint)).rejects.toMatchObject({ code: 'INVALID_CREDENTIAL' }) + const search = { consumer: 'web-test', accepts: ['api-key'], billing: 'api-key', destination: { path: '/v1/tools/search' } } as const + const route = await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic', apiKeyEnv: 'ROUTE_KEY' }) + expect(await ctx.deepseekAuth.authorize(search)).toEqual({ + kind: 'api-key', endpoint: 'https://route.deepseek.test/v1/tools/search', reference: 'ROUTE_KEY', headers: { authorization: 'Bearer fixture-api-key' }, + }) + vi.stubEnv('ROUTE_KEY', 'invalid\nheader') + await expect(ctx.deepseekAuth.authorize(search)).rejects.toThrow('llm-deepseek-api-key: the API key resolved from ROUTE_KEY contains characters') + await route.dispose() + expect(await ctx.deepseekAuth.authorize(search)).toMatchObject({ endpoint: 'https://api.deepseek.com/v1/tools/search', reference: 'DEEPSEEK_API_KEY' }) } finally { await ctx.fiber.dispose() vi.unstubAllEnvs() } }) -it.each([ - 'https://other-origin.example/v1/tools/search', - 'http://route.deepseek.test/v1/tools/search', - 'https://route.deepseek.test:8443/v1/tools/search', - 'https://user@route.deepseek.test/v1/tools/search', - 'https://:secret@route.deepseek.test/v1/tools/search', -])('releases no key for %s, a destination outside the origin of its base URL, without reading the credential store', async (endpoint) => { - const resolve = vi.fn(async () => ({ value: 'stored-key' })) - const describe = vi.fn(async () => ({ configured: true })) +it('fails a model listing whose credential store cannot be read with the store\'s failure', async () => { + const failure = new Error('credential store unreadable') const ctx = new Context() try { - ctx.provide('credentials', { resolve, describe } as never) + ctx.provide('credentials', { resolve: () => Promise.reject(failure) } as never) await ctx.plugin(LlmRuntime) await ctx.plugin(DeepSeekAuth) - await ctx.plugin(ApiKey, { baseURL: 'https://route.deepseek.test/anthropic' }) - const credential = ctx.llm.providerCredential('deepseek-official') - await expect(credential!.configured(endpoint)).resolves.toBe(false) - await expect(credential!.resolve(endpoint)).resolves.toBeUndefined() - expect(resolve).not.toHaveBeenCalled() - expect(describe).not.toHaveBeenCalled() - // The same store answers for a destination under the route's origin. - const served = 'https://route.deepseek.test/v1/tools/search' - await expect(credential!.configured(served)).resolves.toBe(true) - await expect(credential!.resolve(served)).resolves.toEqual({ headers: { 'x-api-key': 'stored-key' }, value: 'stored-key' }) + await ctx.plugin(ApiKey, { models: [{ id: 'configured-model' }] }) + await expect(ctx.llm.listModels('deepseek-official')).rejects.toBe(failure) } finally { await ctx.fiber.dispose() } diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index c929a5cfcc..6e1d960615 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: 22d74c69c0aa9234 - zh: d70eaf90c93a76d1 + en: 5f8cda73f2c10260 + zh: 2a507d9ee8b9c67a /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: f20f2cfbb38e4ba9 zh: c527b91c8b747886 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 96223b73bc..d7374c5e4c 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -94,7 +94,7 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account route owns HTTP 401 classification and the account service the credential invalidation; the transport passes failures to the credential's callback. -Provider plugins own credentials through three adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, the bare value, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. `credential` publishes the route's credential kind, optional reference, and presence check through `ctx.llm.providerCredential(provider)` together with the route's base URL, so web providers call the same deployment with the same credential without reading provider configuration. The plugins read API keys through the [credential reference helpers](../../credentials/credentials/README.md) of `dsh-credentials` and account credentials through the [account service](../../account/deepseek-account/README.md); this transport reads neither. +Provider plugins supply credentials through two adapter hooks. `resolveAuth(connection, endpoint)` returns the credential one request to `endpoint` carries: the headers the Messages, Files, and listing requests send, an optional failure callback, and an optional `revoked` signal, or `undefined` when none is configured. The signal ends the model request and its file operations when the credential's owner withdraws it, and the failure callback names that end. `missingCredential(connection, provider)` names the failure of a request without one; the default is `MISSING_CREDENTIAL`. The plugins take both the API key and the account sign-in from [`ctx.deepseekAuth`](../../account/deepseek-auth/README.md); this transport reads no credential. ### Streaming with thinking and images diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 84772f3fcd..a1ffac9b31 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -94,7 +94,7 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号路由负责 HTTP 401 分类,账号服务负责凭据失效处理;传输层将错误交给凭据的回调。 -提供方插件通过三个适配器钩子拥有凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、裸凭据值、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。`credential` 通过 `ctx.llm.providerCredential(provider)` 发布路由的凭据种类、可选引用和存在性检查,并附带路由的基础地址,使 Web 提供方无需读取提供方配置即可用同一凭据调用同一部署。插件通过 `dsh-credentials` 的[凭据引用函数](../../credentials/credentials/README.zh.md)读取 API Key,通过[账号服务](../../account/deepseek-account/README.zh.md)读取账号凭据;本传输层两者都不读取。 +提供方插件通过两个适配器钩子提供凭据。`resolveAuth(connection, endpoint)` 返回发往 `endpoint` 的一次请求所携带的凭据:Messages、Files 和列表请求发送的请求头、可选的失败回调以及可选的 `revoked` 信号;未配置时返回 `undefined`。凭据的所有者撤回凭据时,该信号结束模型请求及其文件操作,失败回调为这次结束命名。`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。插件的 API Key 和账号登录凭据都取自 [`ctx.deepseekAuth`](../../account/deepseek-auth/README.zh.md);本传输层不读取任何凭据。 ### 带 thinking 与图片的流式调用 diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 5f625e687d..0803bde860 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -1,7 +1,7 @@ /** Direct Messages transport with one cancellable lifecycle per model request. */ import { attributionHeaders, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, ProviderCredential, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, ImageAttachmentAccessResolver, PreparedAdapterCall, StreamChunk } from '@deepseek-ai/dsh-llm' import type { DeepSeekLlmApiExtensionRequest, DeepSeekLlmApiJson } from '@deepseek-ai/dsh-deepseek-llm-api-extensions' import { idleWatchdog, timeoutOf } from '@deepseek-ai/dsh-timeout' import { modelInfo } from './model-info.ts' @@ -47,31 +47,6 @@ export class DeepSeekAdapter extends LlmAdapt if (entry === undefined) throw new LlmError(`DeepSeek model "${model}" has no declared image projection`, 'UNKNOWN_MODEL') return resolveRequestImageTarget(entry, image) } - override providerCredential(_provider: string): ProviderCredential | undefined { - const publication = this.dependencies.credential - if (publication === undefined) return undefined - // One configuration generation serves the whole published object, as it does one model request. - const connection = this.dependencies.options() - const reference = publication.reference?.(connection) - return { - kind: publication.kind, - baseURL: connection.baseURL, - ...reference === undefined ? {} : { reference }, - configured: endpoint => publication.configured(connection, endpoint), - resolve: async (endpoint, signal) => { - signal?.throwIfAborted() - const auth = await this.dependencies.resolveAuth(connection, endpoint) - if (auth === undefined) return undefined - // The adapter's failure classification stays behind the seam. - const reject = auth.reject?.bind(auth) - return { - headers: auth.headers, value: auth.value, - ...reject === undefined ? {} : { reject }, - ...auth.revoked === undefined ? {} : { revoked: auth.revoked }, - } - }, - } - } override async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise { const connection = await this.connection(signal) this.dependencies.admit?.(connection, model) diff --git a/packages/llm/llm-deepseek/src/host.ts b/packages/llm/llm-deepseek/src/host.ts index 202d9c2bef..0b87c549f0 100644 --- a/packages/llm/llm-deepseek/src/host.ts +++ b/packages/llm/llm-deepseek/src/host.ts @@ -45,7 +45,7 @@ export function createModelListingCache( */ export function registerDeepSeekProvider( ctx: Context, provider: string, dependencies: Pick, - 'options' | 'resolveAuth' | 'missingCredential' | 'credential' | 'providerName' | 'discoverModels' | 'connect' | 'admit'>): void { + 'options' | 'resolveAuth' | 'missingCredential' | 'providerName' | 'discoverModels' | 'connect' | 'admit'>): void { ctx.inject(['settings'], (child) => { child.effect(() => child.settings.configure({ auto: false }, ctx.fiber)) }) let userId: AnonymousUserId | undefined // These conditions repeat on every request of a route; log each first occurrence only. diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts index 8bd83450b4..1c7ab36255 100644 --- a/packages/llm/llm-deepseek/src/index.ts +++ b/packages/llm/llm-deepseek/src/index.ts @@ -15,7 +15,7 @@ export { DEFAULT_STREAM_IDLE_TIMEOUT_MS, } from './defaults.ts' export { DeepSeekAdapter } from './adapter.ts' -export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions, DeepSeekProviderCredentialOptions } from './types.ts' +export type { DeepSeekRequestAuth, DeepSeekAdapterOptions, DeepSeekCatalogModel, DeepSeekConnectionOptions } from './types.ts' export { DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET, DEFAULT_MAX_IMAGES_PER_REQUEST, diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index 0e483b92a4..0efced1afe 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -1,6 +1,6 @@ /** Model catalog and request-local dependencies for DeepSeek Messages. */ import type { - ImageAttachmentAccess, LlmCredentialKind, LlmError, LlmModelInfo, ModelModality, ProviderCredentialGrant, ResolvedRetryPolicy, + ImageAttachmentAccess, LlmError, LlmModelInfo, ModelModality, ResolvedRetryPolicy, SystemPromptUpdate, ToolUpdate, } from '@deepseek-ai/dsh-llm' import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -85,12 +85,18 @@ export interface DeepSeekConnectionOptions { } /** - * Authentication released for one request and its file operations: the route - * credential grant the provider plugin builds, plus the request-failure - * classification bound to that credential. The grant's `revoked` signal ends - * the request and its file operations as the caller's cancellation does. + * Authentication the provider plugin releases for one request and its file operations, with the request-failure + * classification bound to that credential. */ -export interface DeepSeekRequestAuth extends ProviderCredentialGrant { +export interface DeepSeekRequestAuth { + /** Request headers carrying the credential. */ + readonly headers: Readonly> + /** + * Aborts when the owner withdraws the credential while the request may carry it, as an account sign-out does. It + * ends the request and its file operations as the caller's cancellation does. Absent for credentials that are + * never withdrawn. + */ + readonly revoked?: AbortSignal /** * Classify a failure using the captured credential; callback failure preserves the original error. The end a * withdrawn credential causes arrives here too, for the provider plugin to name. @@ -98,20 +104,6 @@ export interface DeepSeekRequestAuth extends ProviderCredentialGrant { onRequestError?: (error: unknown) => Promise } -/** - * What `providerCredential()` publishes about the route's credential beside the - * request-path hooks, so consumers outside the model request path share the - * route's credential without reading its configuration. - */ -export interface DeepSeekProviderCredentialOptions { - /** Kind of credential the route sends. */ - kind: LlmCredentialKind - /** Credential reference the route resolves, named by diagnostics; omission publishes none. */ - reference?: (connection: Connection) => string | undefined - /** Report whether a credential exists for `endpoint` without reading its value. */ - configured: (connection: Connection, endpoint: string) => Promise -} - /** Constructor options for {@link DeepSeekAdapter}: the operation-local resolution hooks the plugin owns. */ export interface DeepSeekAdapterOptions { /** Report unusable native Messages replay metadata without exposing content or signatures. */ @@ -137,8 +129,7 @@ export interface DeepSeekAdapterOptions Promise /** @@ -146,11 +137,6 @@ export interface DeepSeekAdapterOptions LlmError - /** - * Publish the route's credential through `providerCredential()`, whose `resolve` forwards the headers, value, - * rejection, and withdrawal signal of {@link resolveAuth} without its failure classification; omission publishes none. - */ - credential?: DeepSeekProviderCredentialOptions /** Resolve the harness-home anonymous id shared with telemetry and feedback. */ resolveUserId: () => AnonymousUserId /** Resolve the current durable attachment service; absence rejects image input. */ diff --git a/packages/llm/llm-deepseek/tests/route-credential.spec.ts b/packages/llm/llm-deepseek/tests/route-credential.spec.ts index 9c74f6ef14..8766cf50f9 100644 --- a/packages/llm/llm-deepseek/tests/route-credential.spec.ts +++ b/packages/llm/llm-deepseek/tests/route-credential.spec.ts @@ -1,39 +1,14 @@ -/** The adapter publishes a route credential only for providers that declare one, and refuses requests without a credential. */ +/** The adapter refuses a request whose provider releases no credential, with the provider's diagnostic when it names one. */ import { afterEach, expect, it, vi } from 'vitest' -import { Context } from '@deepseek-ai/cordis' -import LlmRuntime, { LlmError } from '@deepseek-ai/dsh-llm' +import { LlmError } from '@deepseek-ai/dsh-llm' import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' -import { DeepSeekAdapter, registerDeepSeekProvider, resolveAdapterOptions } from '../src/index.ts' -import type { DeepSeekAdapterOptions, DeepSeekRequestAuth, ResolvedDeepSeekOptions } from '../src/index.ts' +import { DeepSeekAdapter, resolveAdapterOptions } from '../src/index.ts' +import type { DeepSeekAdapterOptions } from '../src/index.ts' import { chunks, options as request, prepareExtensions } from './helpers.ts' -const contexts: Context[] = [] -afterEach(async () => { - for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() - vi.unstubAllGlobals() -}) +afterEach(() => { vi.unstubAllGlobals() }) -const BASE_URL = 'https://route.deepseek.test/anthropic' -const ALLOWED = 'https://route.deepseek.test/v1/tools/search' -const OTHER = 'https://route.deepseek.test/v1/tools/fetch' -const connection = () => resolveAdapterOptions({ baseURL: BASE_URL }) - -type Hooks = Partial> - -/** Mount the runtime and one fixture route whose credential hooks are `hooks`. */ -async function route(hooks: Hooks): Promise { - const ctx = new Context() - contexts.push(ctx) - await ctx.plugin(LlmRuntime) - await ctx.plugin({ - name: 'fixture-route', - inject: ['llm'], - apply: (child: Context) => { - registerDeepSeekProvider(child, 'fixture-route', { options: connection, resolveAuth: () => Promise.resolve(undefined), ...hooks }) - }, - }) - return ctx -} +const connection = () => resolveAdapterOptions({ baseURL: 'https://route.deepseek.test/anthropic' }) /** A direct adapter without a credential, failing requests through `missingCredential` when given. */ function adapterWithout(missingCredential?: DeepSeekAdapterOptions['missingCredential']): DeepSeekAdapter { @@ -46,46 +21,6 @@ function adapterWithout(missingCredential?: DeepSeekAdapterOptions['missingCrede }) } -it('publishes no credential for a provider that declares none', async () => { - const ctx = await route({}) - expect(ctx.llm.providerCredential('fixture-route')).toBeUndefined() -}) - -it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => { - const reject = vi.fn(() => Promise.resolve()) - const revoked = new AbortController().signal - const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise => - endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, revoked, onRequestError: error => Promise.resolve(error) } : undefined) - const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED) - const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } }) - const credential = ctx.llm.providerCredential('fixture-route') - expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' }) - await expect(credential!.configured(ALLOWED)).resolves.toBe(true) - await expect(credential!.configured(OTHER)).resolves.toBe(false) - // The grant carries the seam's fields only; the adapter's failure classification stays behind it. - const grant = await credential!.resolve(ALLOWED) - expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject', 'revoked']) - expect(grant).toMatchObject({ headers: { 'x-fixture': 'k' }, value: 'k' }) - expect(grant!.revoked).toBe(revoked) - await grant!.reject!() - expect(reject).toHaveBeenCalledTimes(1) - await expect(credential!.resolve(OTHER)).resolves.toBeUndefined() - await expect(credential!.resolve(ALLOWED, AbortSignal.abort(new Error('caller left')))).rejects.toThrow('caller left') - expect(resolveAuth).toHaveBeenCalledTimes(2) - expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL]) -}) - -it('omits the reference of a credential kind without one and the rejection and withdrawal of a grant without them', async () => { - const ctx = await route({ - resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }), - credential: { kind: 'account', configured: () => Promise.resolve(false) }, - }) - const credential = ctx.llm.providerCredential('fixture-route') - expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL }) - expect(credential).not.toHaveProperty('reference') - await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' }) -}) - it('fails a request without a credential before any network I/O, with the default diagnostic', async () => { const fetchMock = vi.fn() vi.stubGlobal('fetch', fetchMock) diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index bcc94686db..e921f26e08 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -22,7 +22,6 @@ import type { LlmResolvedModelInfo, LlmProviderInfo, ModelModality, - ProviderCredential, StreamChunk, SystemPromptUpdate, ToolSchema, @@ -265,19 +264,6 @@ export abstract class LlmAdapter { return { width: image.width, height: image.height, maxBytes: image.bytes } } - /** - * Describe the credential one owned route currently sends, for consumers that - * call the same deployment outside the model request path, such as web - * providers that share a route's credential and endpoint. The default - * publishes none. Implementations answer from one configuration generation - * per call and may throw when that configuration does not resolve. - * @param _provider - a route passed to `registerAdapter()` for this instance. - * @returns the route's current credential, or `undefined` when the route publishes none. - */ - providerCredential(_provider: string): ProviderCredential | undefined { - return undefined - } - /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such @@ -722,19 +708,6 @@ export class LlmRuntime extends TypertRemoteService { return this.registration(provider).adapter.imageRequestTarget(provider, model, image) } - /** - * Resolve the credential one registered route currently sends, through its - * owning adapter. An unregistered route answers `undefined` rather than - * throwing because callers ask about routes a conversation named earlier, - * which may no longer be mounted; a registered route whose configuration - * does not resolve propagates the adapter's failure. - * @param provider - provider route whose credential is wanted. - * @returns the route's credential, or `undefined` when the route is unregistered or publishes none. - */ - providerCredential(provider: string): ProviderCredential | undefined { - return this.adapters.get(provider)?.adapter.providerCredential(provider) - } - /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index fdc7320c40..dae3c7c4ac 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -292,94 +292,6 @@ export interface LlmNativeAuth { oauth: boolean } -/** - * Merge-extensible vocabulary of the credential kinds a provider route sends. - * `api-key` is a provider key read from a credential reference or the launch - * environment; `account` is a grant obtained by signing in. An adapter that - * sends another kind declares it here. - */ -export interface LlmCredentialKindMap { - 'api-key': 'api-key' - account: 'account' -} - -/** Any declared credential kind. */ -export type LlmCredentialKind = LlmCredentialKindMap[keyof LlmCredentialKindMap] - -/** - * One credential released for one destination. Host-only: it carries the - * secret, so it never crosses a Remote boundary and never enters a log. - */ -export interface ProviderCredentialGrant { - /** - * Request headers carrying the credential as the route's own protocol - * expects it, such as `x-api-key` for an API key. Consumers speaking that - * protocol send them unchanged. - */ - readonly headers: Readonly> - /** - * The bare credential value, for destinations whose protocol renders it - * differently from {@link headers}, such as `Authorization: Bearer`. - */ - readonly value: string - /** - * Invalidate this exact credential after the destination rejected it with - * HTTP 401 so no later request resends it. Absent for kinds without - * invalidation. The owner contains storage failures: the caller reports the - * destination's rejection, never a failure of this call. - * @returns settlement after the invalidation attempt. - */ - reject?(): Promise - /** - * Aborts when the owner withdraws this credential while requests carrying it - * may be in flight, as an account sign-out does. A consumer ends each request - * it authenticated with this grant and reports that end as its own failure, - * not as the caller's cancellation. Absent for kinds that are never withdrawn. - */ - readonly revoked?: AbortSignal -} - -/** - * The credential one registered provider route currently sends, answered by - * the route's owning adapter so that consumers read no provider configuration - * and choose no header names. `ctx.llm.providerCredential()` resolves a new value - * per call from one configuration generation; a caller keeps it for one - * operation only. - */ -export interface ProviderCredential { - /** Kind of credential the route sends. */ - readonly kind: LlmCredentialKind - /** - * The route's current request base URL as its configuration resolves it, - * environment fallbacks included: the destination this credential is meant - * for. Consumers derive sibling endpoints of the same deployment from it. - */ - readonly baseURL: string - /** - * Credential reference the route resolves, for diagnostics that tell the user - * where to configure the credential; absent for kinds without a stored - * reference, such as sign-in grants. - */ - readonly reference?: string - /** - * Whether {@link resolve} would release a credential for `endpoint`, checked - * without validating the credential or contacting the destination; the owner - * may read its store to answer. Store failures reject. - * @param endpoint - absolute URL the credential would be sent to. - * @returns whether a credential is configured for that destination. - */ - configured(endpoint: string): Promise - /** - * Release the credential for `endpoint`, or `undefined` when none is - * configured or the destination may not receive it. The caller chooses the - * failure it reports for `undefined`. Store and format failures reject. - * @param endpoint - absolute URL the credential will be sent to. - * @param signal - cancellation for the lookup. - * @returns the released credential, or `undefined`. - */ - resolve(endpoint: string, signal?: AbortSignal): Promise -} - /** * One interrogation of a provider endpoint that configuration has not stored * yet. Configuration surfaces send the draft a user is still editing, so the diff --git a/packages/llm/llm/tests/topology.spec.ts b/packages/llm/llm/tests/topology.spec.ts index 3a9735fbef..98b1be4920 100644 --- a/packages/llm/llm/tests/topology.spec.ts +++ b/packages/llm/llm/tests/topology.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' -import type { GenerateOptions, LlmConfigurableProvider, ProviderCredential, StreamChunk } from '@deepseek-ai/dsh-llm' +import type { GenerateOptions, LlmConfigurableProvider, StreamChunk } from '@deepseek-ai/dsh-llm' class NoopAdapter extends LlmAdapter { @@ -339,25 +339,3 @@ describe('imageRequestPricing resolution', () => { expect(ctx.llm.imageRequestPricing('a', 'vision')).toBeUndefined() }) }) - -describe('providerCredential resolution', () => { - it('forwards to the owning adapter and answers undefined everywhere else', async () => { - const ctx = await setup() - const credential: ProviderCredential = { - kind: 'api-key', baseURL: 'https://a.example/v1', - configured: () => Promise.resolve(true), - resolve: () => Promise.resolve({ headers: { 'x-api-key': 'k' }, value: 'k' }), - } - class CredentialAdapter extends NoopAdapter { - override providerCredential(provider: string) { return provider === 'a' ? credential : undefined } - } - const dispose = ctx.llm.registerAdapter(['a', 'b'], new CredentialAdapter()) - ctx.llm.registerAdapter(['plain'], new NoopAdapter()) - expect(ctx.llm.providerCredential('a')).toBe(credential) - expect(ctx.llm.providerCredential('b')).toBeUndefined() - expect(ctx.llm.providerCredential('plain')).toBeUndefined() - expect(ctx.llm.providerCredential('missing')).toBeUndefined() - dispose() - expect(ctx.llm.providerCredential('a')).toBeUndefined() - }) -}) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index d589a45354..9538caba25 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -494,7 +494,6 @@ export const LINK_MAP: Readonly> = { LlmResolvedModelInfo: 'llm-streaming.md', LlmFailure: 'llm-streaming.md', LlmImageRequestPricing: 'llm-streaming.md', - ProviderCredential: 'llm-streaming.md', LlmModelInfo: 'llm-streaming.md', LlmProviderInfo: 'llm-streaming.md', LlmConfigurableProvider: 'llm-streaming.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 08d8d22bb3..e3e15b1cc4 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1842,16 +1842,6 @@ "symbol": "LlmNativeAuth", "source": "packages/llm/llm/src/types.ts" }, - { - "doc": "docs/subsystems/llm-streaming.md", - "symbol": "ProviderCredentialGrant", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/subsystems/llm-streaming.md", - "symbol": "ProviderCredential", - "source": "packages/llm/llm/src/types.ts" - }, { "doc": "docs/subsystems/permission-presets.md", "symbol": "Config",