Merge remote-tracking branch 'origin/master' into turtle/async-notice-efficiency

This commit is contained in:
turtle1999 committed 2026-10-13 11:33:31 +08:00
commit 92edf5bb0d
252 files changed
+2177 -657

No files matched your search

@@ -3,8 +3,8 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.md
/agent-note-one-ordering-for-configuration-sources-and-what-a-discovered-file-may-not-decide:
en: 1f6ee603f36c2e09
zh: e08197958663219c
en: 35dea8a3a8bdc842
zh: 7a1cdf184ffd889f
/agent-note-one-ordering-for-configuration-sources-and-what-a-discovered-file-may-not-decide/problem:
en: d94bb81479bfa4a1
zh: af44ceaecf84ee51
@@ -4,7 +4,7 @@ Status: implemented
English | [中文](2026-08-04-configuration-source-ownership.zh.md)
The non-secret settings tier below is superseded by [profile-owned live configuration](2026-09-19-profile-owned-live-configuration.md). Credential ordering and environment restrictions remain current.
The non-secret settings tier below is superseded by [profile-owned live configuration](2026-09-19-profile-owned-live-configuration.md), and the credential ordering by [stored credential precedence](2026-10-09-stored-credential-precedence.md). Environment restrictions remain current.
## Problem
@@ -4,7 +4,7 @@ Status: implemented
[English](2026-08-04-configuration-source-ownership.md) | 中文
下文的非秘密 settings 层已由 [profile 所属实时配置](2026-09-19-profile-owned-live-configuration.zh.md) 替代。凭据优先级与环境限制仍然适用。
下文的非秘密 settings 层已由 [profile 所属实时配置](2026-09-19-profile-owned-live-configuration.zh.md) 替代,凭据优先级已由[存储凭据优先级](2026-10-09-stored-credential-precedence.zh.md)替代。环境限制仍然适用。
## Problem
@@ -15,5 +15,5 @@
en: 4089464ad1fb60bd
zh: 3168e9e4a205145d
/agent-note-keep-live-configuration-in-the-owning-profile/consequences:
en: 6033aaa12b2a521b
zh: 43934413c97670de
en: 41bb170694c785d6
zh: 17419fdd6d937dce
@@ -24,6 +24,6 @@ The rejected alternative is retaining settings as a second store behind a config
## Consequences
This supersedes only the non-secret settings tier in [configuration source ownership](2026-08-04-configuration-source-ownership.md); its environment restrictions and credential ordering remain applicable. [Volatile references](2026-09-18-volatile-config-references.md) own reference lifetime and ordinary update behavior.
This supersedes only the non-secret settings tier in [configuration source ownership](2026-08-04-configuration-source-ownership.md); its environment restrictions remain applicable, and [stored credential precedence](2026-10-09-stored-credential-precedence.md) supersedes its credential ordering. [Volatile references](2026-09-18-volatile-config-references.md) own reference lifetime and ordinary update behavior.
Real profile tests cover multiple instances, persisted restart, invalid edits, stale revisions, higher-layer rejection, secret redaction, and configuration expressions. Browser tests exercise form writes and reset through the assembled application. Runtime reference identity is checked across live edits.
@@ -24,6 +24,6 @@ Cordis config patch 替换完整 entry config。编辑会保留普通字段、
## 后果
本决定只替代 [配置来源所有权](2026-08-04-configuration-source-ownership.zh.md) 中的非秘密 settings 层;其中的环境限制和凭据优先级仍适用。[Volatile 引用](2026-09-18-volatile-config-references.zh.md) 负责引用生命周期和普通更新行为。
本决定只替代 [配置来源所有权](2026-08-04-configuration-source-ownership.zh.md) 中的非秘密 settings 层;其中的环境限制仍适用,其凭据优先级已由[存储凭据优先级](2026-10-09-stored-credential-precedence.zh.md)替代。[Volatile 引用](2026-09-18-volatile-config-references.zh.md) 负责引用生命周期和普通更新行为。
真实 profile 测试覆盖多实例、持久化重启、非法编辑、过期修订、高优先级层拒绝、秘密脱敏及配置表达式。浏览器测试通过完整应用执行表单写入和重置,并检查实时编辑前后的运行时引用身份。
@@ -0,0 +1,22 @@
# Bilingual-pair consistency record for 2026-10-09-stored-credential-precedence.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.md
/agent-note-stored-credentials-take-precedence-over-the-launch-environment:
en: 5253af6605ba0fac
zh: 160ac751c664a502
/agent-note-stored-credentials-take-precedence-over-the-launch-environment/problem:
en: 878c68dcfe5b3771
zh: 8a24d16118155245
/agent-note-stored-credentials-take-precedence-over-the-launch-environment/decision:
en: 7cd89bda9f793431
zh: 93d26a948eea63f3
/agent-note-stored-credentials-take-precedence-over-the-launch-environment/per-run-overrides:
en: 7479ffc82280a1fb
zh: ce3d42489191ab2b
/agent-note-stored-credentials-take-precedence-over-the-launch-environment/alternatives-considered:
en: 268add7fd8415280
zh: 0765cbfd3fc7b57c
/agent-note-stored-credentials-take-precedence-over-the-launch-environment/consequences:
en: 2d71fd527b3060c4
zh: fafed884315b9782
@@ -0,0 +1,45 @@
# Agent Note: Stored credentials take precedence over the launch environment
Status: implemented
English | [中文](2026-10-09-stored-credential-precedence.zh.md)
The [headless environment authentication](2026-10-12-headless-environment-auth.md) decision partially supersedes this note's per-run override policy: the shipped headless profile omits the store. The ordering below remains the store's contract when mounted.
## Problem
[Configuration source ownership](2026-08-04-configuration-source-ownership.md) ranked the inherited process environment above `$DSH_HOME/.credentials.yaml`, and `credentials-local` refused `set` and `unset` for a name the launching shell exported. Two kinds of stored credential then had opposite precedence. pi-ai's resolvers read the credential record stored under `llm-pi-ai/<provider>` before any environment variable, so a stored OAuth grant or `api-key` record won over an exported key. A key that the Models page stored under a reference lost to the same exported name. Which credential a request used therefore depended on the provider family, and the Models page disabled its key field whenever the name was exported (#5527).
## Decision
**A stored credential wins for every provider.** `LocalCredentialProvider` resolves a reference in this order:
```text
$DSH_HOME/.credentials.yaml (provider-managed, written by set/unset)
> inherited process environment (fallback; the provider never writes it)
> <invocation cwd>/.env (fallback; the provider never writes it)
> $DSH_HOME/.env (fallback; the provider never writes it)
```
A save always writes the winning layer, so `describe` reports `writable: true` for every reference, and `set` and `unset` never refuse a name because it is exported. `resolve` and `describe` still report the supplying layer as `source` (`file`, `env`, `project-env`, or `user-env`). `authContextFrom` in `llm-pi-ai` answers pi-ai's `env()` from the credential seam before the launch environment, so a pi-ai resolver reads its stored record first, then a stored reference, then the fallbacks in the order above.
The non-secret ordering and the environment restrictions in configuration source ownership are unchanged. This note supersedes only its credential ordering.
## Per-run overrides
The previous order existed so that CI, containers, and a one-shot `DEEPSEEK_API_KEY=… dsh` could override a credential without editing machine state. A fresh CI or container harness home has no `.credentials.yaml`, so its exported secret is still the effective value. A harness home holds a stored key only because someone saved it there, through the Models page or by editing the file. To use an exported value for that name, the user deletes the `refs` entry, or launches with a separate `DSH_HOME`.
## Alternatives considered
**Keep the launch environment on top.** It keeps per-run overrides without touching the store, but it keeps the opposite precedence of stored records and stored references, and the Models page cannot save or replace a key while the launching shell exports the name.
**Refuse a write while only the launch environment supplies the name.** Under the new order such a write takes effect, because the stored value outranks the environment. Refusing it would block the first save of a key for every exported name, and it would keep the read-only field state that the new order removes.
**Warn when a stored value hides an exported variable.** The provider would compare layers on every resolution and report the result for users who keep both values on purpose, such as a shell profile that exports a key for other tools. The Models page help text states the order, and `describe` reports the supplying layer.
## Consequences
- A key left in `.credentials.yaml` overrides an exported variable with the same name, including a CI secret on a machine whose harness home stores a value for that name. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.md) tells affected users how to keep the exported account.
- The Models page can always save, replace, or remove a key, and it does not disable the key field for an exported name.
- There is no per-run flag above the store. A one-run override takes a separate `DSH_HOME`.
- `packages/credentials/credentials-local/tests/local.spec.ts` covers a store over a launch environment value and its return after `unset`; `packages/llm/llm-pi-ai/tests/auth.spec.ts` covers a stored credential that wins over every launch layer.
@@ -0,0 +1,45 @@
# Agent Note: 存储的凭据优先于启动环境
Status: implemented
[English](2026-10-09-stored-credential-precedence.md) | 中文
[Headless 环境认证](2026-10-12-headless-environment-auth.zh.md)决策部分取代本文的单次覆盖策略:随附 headless profile 不挂载存储。存储挂载时仍遵循下述顺序。
## 问题
[配置来源所有权](2026-08-04-configuration-source-ownership.zh.md) 把继承的进程环境排在 `$DSH_HOME/.credentials.yaml` 之前,并且 `credentials-local` 会拒绝对启动 shell 已导出的名字执行 `set` 和 `unset`。于是两类存储的凭据具有相反的优先级。pi-ai 的解析器先读取存储在 `llm-pi-ai/<provider>` 下的凭据记录,再读取任何环境变量,因此存储的 OAuth 授权或 `api-key` 记录会压过导出的密钥;而 Models 页面以引用形式存储的密钥会输给同名的导出变量。一次请求使用哪个凭据因此取决于提供方类别,而且只要该名字被导出,Models 页面就会禁用其密钥输入框(#5527)。
## 决策
**存储的凭据对每个提供方都优先。** `LocalCredentialProvider` 按以下顺序解析引用:
```text
$DSH_HOME/.credentials.yaml (provider-managed, written by set/unset)
> inherited process environment (fallback; the provider never writes it)
> <invocation cwd>/.env (fallback; the provider never writes it)
> $DSH_HOME/.env (fallback; the provider never writes it)
```
保存总是写入胜出的那一层,因此 `describe` 对每个引用都报告 `writable: true`,`set` 与 `unset` 也不会因为名字已被导出而拒绝。`resolve` 与 `describe` 仍以 `source`(`file`、`env`、`project-env` 或 `user-env`)报告提供值的层。`llm-pi-ai` 中的 `authContextFrom` 先从凭据 seam、再从启动环境回答 pi-ai 的 `env()`,因此 pi-ai 解析器依次读取其存储的记录、存储的引用,再按上面的顺序读取后备来源。
配置来源所有权中的非秘密顺序与环境限制保持不变。本 Note 只替代其中的凭据优先级。
## 按次覆盖
之前的顺序让 CI、容器和一次性的 `DEEPSEEK_API_KEY=… dsh` 无需修改机器状态就能覆盖凭据。全新的 CI 或容器 harness home 中没有 `.credentials.yaml`,因此其导出的机密仍是生效值。harness home 中存有密钥,只可能是有人通过 Models 页面或直接编辑该文件存入的。要对该名字使用导出的值,用户应删除对应的 `refs` 条目,或使用单独的 `DSH_HOME` 启动。
## 考虑过的替代方案
**保持启动环境在最上层。** 它无需改动存储就能保留按次覆盖,但会保留存储记录与存储引用之间相反的优先级,而且只要启动 shell 导出了该名字,Models 页面就无法保存或替换密钥。
**只有启动环境提供该名字时拒绝写入。** 在新顺序下这样的写入会生效,因为存储值优先于环境。拒绝它会阻止为每个已导出的名字首次保存密钥,也会保留新顺序已经去掉的只读输入框状态。
**存储值遮蔽导出变量时发出警告。** 提供方需要在每次解析时比较各层,并向有意同时保留两个值的用户报告结果,例如在 shell 配置文件中为其他工具导出密钥的用户。Models 页面的帮助文本说明了该顺序,`describe` 也会报告提供值的层。
## 后果
- 留在 `.credentials.yaml` 中的密钥会覆盖同名的导出变量,包括在 harness home 存有该名字的机器上运行的 CI 机密。[升级指南](../../../../docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.zh.md)说明受影响的用户如何继续使用导出的账户。
- Models 页面总能保存、替换或删除密钥,也不会因名字被导出而禁用密钥输入框。
- 存储之上没有按次生效的标志。一次运行的覆盖需要使用单独的 `DSH_HOME`。
- `packages/credentials/credentials-local/tests/local.spec.ts` 覆盖在启动环境值之上存储、以及 `unset` 后恢复该值;`packages/llm/llm-pi-ai/tests/auth.spec.ts` 覆盖存储的凭据压过每个启动层。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-10-12-headless-environment-auth.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-12-headless-environment-auth.md
/agent-note-headless-jobs-omit-the-interactive-credential-store:
en: c768db5a7e821bf0
zh: 423b3e423d071ddc
/agent-note-headless-jobs-omit-the-interactive-credential-store/problem:
en: 829df36d87975148
zh: 171d29ef2f2e5079
/agent-note-headless-jobs-omit-the-interactive-credential-store/decision:
en: af275ffea713f76b
zh: 12a3bacfcb147df7
/agent-note-headless-jobs-omit-the-interactive-credential-store/alternatives-considered:
en: f6f8dfde4789adc8
zh: ced62f3d1ec402e6
/agent-note-headless-jobs-omit-the-interactive-credential-store/consequences:
en: 1c1a699dc9f5681f
zh: 4a72b09d24f9a005
@@ -0,0 +1,30 @@
# Agent Note: Headless jobs omit the interactive credential store
Status: implemented
English | [中文](2026-10-12-headless-environment-auth.zh.md)
## Problem
The [stored credential precedence](2026-10-09-stored-credential-precedence.md) decision makes GUI saves effective even when the shell exports a key for another application. A headless job sharing that Harness home can then use the GUI account instead of the key explicitly supplied to the job. Changing reference precedence alone would leave pi-ai provider records and saved grants ahead of the environment.
## Decision
The shipped headless bundle disables the base `credentials`, `authorization` and `deepseek-account` rows. API-key adapters already support compositions without the credentials service and resolve through the launch snapshot: process environment, invocation-directory `.env`, then Harness-home `.env`. The profile does not read, migrate, write or delete `.credentials.yaml`. Dependent authorization and account rows are disabled explicitly so ordinary jobs do not emit pending-service warnings.
This partially supersedes the per-run override policy in stored credential precedence for the shipped headless profile. Other profiles and an explicitly restored headless store retain stored-first resolution. The headless [README](../../../../packages/bundle/headless/README.md#credentials) owns the restoration patch.
## Alternatives considered
**Put the environment first in every profile.** It prevents a GUI save from replacing a key left in the launching environment and restores inconsistent reference and provider-record precedence.
**Disable only the credentials row.** It achieves environment selection but leaves authorization and the account provider pending, producing warnings on every launch.
**Add a second precedence mode to the store.** It introduces configuration and record-handling policy into the shared provider when existing adapter fallbacks and profile overrides already supply the required behavior.
## Consequences
- Headless ignores saved API keys, provider records and grants. A provider requiring stored sign-in or the DeepSeek account route fails until the user restores stored authentication; restoring it also restores saved-first precedence.
- Environment and external provider credential chains remain available. Sessions, settings and tools stay composed; omission of the store does not deny filesystem reads by tools.
- Web, SDK and ACP retain the credential store. Their authentication, login and refresh implementations are unchanged.
- Profile-level process tests cover all three environment layers, named and native pi-ai authentication, missing keys, ignored malformed storage, restoration and preservation of the document. Existing headless transcripts and real-model workspace tests cover the remaining composition.
@@ -0,0 +1,30 @@
# Agent Note: Headless 任务不挂载交互式凭据存储
Status: implemented
[English](2026-10-12-headless-environment-auth.md) | 中文
## 问题
[已保存凭据优先级](2026-10-09-stored-credential-precedence.zh.md)的决策保证 GUI 保存的密钥生效,即使 shell 为其他应用导出了密钥。共享同一个 Harness home 的 headless 任务可能因此使用 GUI 的账户,而不是显式传给任务的密钥。只调整引用优先级仍会让 pi-ai 提供方记录和已保存 grant 排在环境变量之前。
## 决策
随附 headless 组合包禁用 base 中的 `credentials`、`authorization` 和 `deepseek-account` 行。API 密钥适配器已经支持不挂载凭据服务的组合,按启动快照解析:进程环境、运行命令的目录 `.env`、Harness home `.env`。该 profile 不读取、迁移、写入或删除 `.credentials.yaml`。显式禁用依赖它的 authorization 和 account 行,避免普通任务输出等待服务的警告。
这部分取代了已保存凭据优先级中针对随附 headless profile 的单次覆盖策略。其他 profile,以及显式恢复存储的 headless,仍按已保存凭据优先解析。headless [README](../../../../packages/bundle/headless/README.zh.md#credentials)负责恢复 patch 的用法。
## 考虑过的替代方案
**在所有 profile 中让环境变量优先。** 这会使 GUI 保存的密钥无法替换启动环境中遗留的密钥,并恢复引用与提供方记录之间不一致的优先级。
**只禁用 credentials 行。** 这能选用环境变量,但 authorization 与 account 提供方会保持 pending,每次启动都产生警告。
**给存储增加第二种优先级模式。** 现有适配器后备与 profile 覆盖已经满足需求;这种做法却会把额外配置和记录处理策略引入共享提供方。
## 后果
- Headless 忽略已保存 API 密钥、提供方记录和 grant。依赖已保存登录凭据的提供方或 DeepSeek account 路由会失败,直到用户恢复存储认证;恢复后也恢复已保存凭据优先。
- 环境变量与提供方外部凭据链仍然可用。会话、settings 与工具继续组合;不挂载存储不会禁止工具读取文件系统。
- Web、SDK 与 ACP 保留凭据存储;其认证、登录和刷新实现不变。
- Profile 进程测试覆盖三个环境层、具名与原生 pi-ai 认证、缺失密钥、忽略畸形存储、恢复存储,以及文件保持原样。现有 headless 录制与真实模型工作区测试覆盖组合中的其余行为。
@@ -18,8 +18,8 @@
en: a9fe46283ea28722
zh: 7b7d1be7c070b893
/agent-note-configure-subagent-persona-tool-visibility-and-depth/decision/depth-is-an-absolute-tree-cap:
en: 9145bec4e3f7eb5b
zh: 986276925cb064d9
en: 28816df0fde0ef56
zh: bf906e6c286645e0
/agent-note-configure-subagent-persona-tool-visibility-and-depth/decision/capability-gating-keeps-providers-honest:
en: 5334afafefdb0f59
zh: 7e96c9a08bbc3d1a
@@ -53,9 +53,9 @@ The depth limit bounds recursive delegation independently of tool visibility. A
The effective parent depth is the greater of durable `SessionHeader.delegationDepth` and runtime `AgentOptions.subagentDepth`. An in-process child records its derived depth in the session header, and resume restores that header, so a restart cannot lower the recursion count.
Every public entry validates the domain rather than relying on one model-facing configuration path. Negative values, fractions, negative zero, non-finite values, unsafe integers, malformed stored parent depth, and derived overflow all reject. A direct `SubagentStartRequest` may omit the cap to leave depth unbounded; loader-resolved `dsh-tool-subagent` configuration instead defaults to `3`, accepts a numeric override, and uses explicit `'provider-managed'` to omit the cap for an out-of-process provider whose deployment owns its recursion budget. Three is a small finite default that still permits a root plus three descendant generations, and the [base profile](../../../../packages/bundle/base/cordis.patch.yml) uses that general policy. A numeric tool cap fails at provider mount when the provider lacks `depthLimit`.
Every public entry validates the domain rather than relying on one model-facing configuration path. Negative values, fractions, negative zero, non-finite values, unsafe integers, malformed stored parent depth, and derived overflow all reject. A direct `SubagentStartRequest` may omit the cap to leave depth unbounded; `dsh-tool-subagent` instead reads the live Host depth setting (initially `1`), accepts a numeric override, and uses explicit `'provider-managed'` to omit the cap for an out-of-process provider whose deployment owns its recursion budget. The [base profile](../../../../packages/bundle/base/cordis.patch.yml) uses the Host setting. A numeric tool cap fails at provider mount when the provider lacks `depthLimit`.
A deployment can combine depth and filtering, but the numeric cap does not synthesize a filter. The delegation tool stays visible at the cap because authorization may depend on runtime state; every attempted start checks the calling agent's current durable and runtime depth, and a rejected start returns an errored tool result without publishing a child. A deployment may separately deny delegation tools in children when its visibility policy is static. Neither choice changes the provider's conversation-history behavior.
A deployment can combine depth and filtering, but the numeric cap does not synthesize a filter. The delegation tool stays visible at the cap because authorization may depend on runtime state; every attempted start checks the calling agent's current durable and runtime depth, and a rejected start returns an errored tool result without publishing a child. A deployment may separately deny delegation tools in children when its visibility policy is static. Neither choice changes the provider's conversation-history behavior. At the cap, the tool contributes an optional runtime-context notice telling the model to work directly. `includeRuntimeContext: false` suppresses this advisory notice; the runtime depth guard remains active. When enabled, the notice reads the live cap and durable depth at request time to keep resumed and reconfigured agents informed without changing their system prompt or tool schemas; unchanged context is not repeatedly appended.
### Capability gating keeps providers honest
@@ -55,9 +55,9 @@ subagent 启动有三个独立的组合控制:`persona`、`toolFilter` 和 `ma
有效父级深度取持久 `SessionHeader.delegationDepth` 与运行时 `AgentOptions.subagentDepth` 中的较大值。进程内子 agent 把推导出的深度记录在会话 header 中,恢复时会重新载入该 header,因此重启无法降低递归计数。
每个公开入口都自行验证值域,而非依赖单一的面向模型配置路径。负值、小数、负零、非有限值、不安全整数、格式错误的存储父级深度以及推导溢出均被拒绝。直接的 `SubagentStartRequest` 可以省略上限,让此机制不约束深度;经 loader 解析的 `dsh-tool-subagent` 配置则默认值为 `3`、接受数值覆盖,并使用显式的 `'provider-managed'` 来省略由进程外提供方部署拥有递归预算时的上限。三是一个较小的有限默认值,仍允许 root 加三代后代,[base profile](../../../../packages/bundle/base/cordis.patch.yml)采用这项通用策略。提供方缺少 `depthLimit` 时,数值工具上限会在提供方挂载阶段失败。
每个公开入口都自行验证值域,而非依赖单一的面向模型配置路径。负值、小数、负零、非有限值、不安全整数、格式错误的存储父级深度以及推导溢出均被拒绝。直接的 `SubagentStartRequest` 可以省略上限,让此机制不约束深度;`dsh-tool-subagent` 则读取实时 Host 深度设置(初始值为 `1`)、接受数值覆盖,并使用显式的 `'provider-managed'` 来省略由进程外提供方部署拥有递归预算时的上限。[base profile](../../../../packages/bundle/base/cordis.patch.yml)采用 Host 设置。提供方缺少 `depthLimit` 时,数值工具上限会在提供方挂载阶段失败。
部署可以组合深度与过滤,但数值上限不会合成过滤器。委派工具在上限处仍然可见,因为授权可能依赖运行时状态;每次尝试启动都会检查调用方 agent 当前的持久与运行时深度,被拒绝的启动返回错误工具结果,且不发布子 agent。可见性策略固定的部署可以另外在子 agent 中 deny 委派工具。两种选择都不改变提供方的对话历史行为。
部署可以组合深度与过滤,但数值上限不会合成过滤器。委派工具在上限处仍然可见,因为授权可能依赖运行时状态;每次尝试启动都会检查调用方 agent 当前的持久与运行时深度,被拒绝的启动返回错误工具结果,且不发布子 agent。可见性策略固定的部署可以另外在子 agent 中 deny 委派工具。两种选择都不改变提供方的对话历史行为。达到上限时,工具贡献一条可选的运行时上下文提示,让模型直接完成工作。`includeRuntimeContext: false` 会抑制这条建议性提示;运行时的深度拦截仍然生效。提示启用时,每次请求读取实时上限与持久深度,使恢复会话或调整配置后的 agent 获知当前限制,同时不改变其系统提示词或工具 schema;未变化的上下文不会重复追加。
### 能力门控保持提供方诚实
@@ -0,0 +1,203 @@
/** Credential selection through the shipped headless profile and real HTTP adapters. */
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { once } from 'node:events'
import type { AddressInfo } from 'node:net'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server'
import { runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
import { describe, expect, it } from 'vitest'
const binScript = fileURLToPath(new URL('../../../../../../apps/cli/src/bin.ts', import.meta.url))
const tsconfigPath = fileURLToPath(new URL('../../../../../../tsconfig.json', import.meta.url))
const savedKey = 'headless-saved-key'
const launchKey = 'headless-launch-key'
const projectKey = 'headless-project-key'
const homeKey = 'headless-home-key'
const processTimeoutMs = 60_000
/** Anthropic SDK events require the SSE event name beside the JSON payload. */
async function startAnthropicServer() {
const keys: Array<string | string[] | undefined> = []
const server = createServer((request, response) => {
keys.push(request.headers['x-api-key'])
request.resume()
response.writeHead(200, { 'content-type': 'text/event-stream' })
for (const event of [
{ type: 'message_start', message: { id: 'auth-test', type: 'message', role: 'assistant', model: 'headless-auth-model', content: [], usage: { input_tokens: 1, output_tokens: 0 } } },
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'mock response recovered' } },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } },
{ type: 'message_stop' },
]) response.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
response.end()
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
return {
keys,
baseURL: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
async close() {
server.closeAllConnections()
await new Promise<void>((resolve, reject) => server.close((error) => {
if (error === undefined) resolve()
else reject(error)
}))
},
}
}
const credentials = JSON.stringify({
version: 1,
refs: { DEEPSEEK_API_KEY: savedKey, ANTHROPIC_API_KEY: savedKey },
records: {
'llm-pi-ai/anthropic': { kind: 'api-key', key: savedKey },
'llm-pi-ai/openai-codex': {
kind: 'grant', payload: { type: 'oauth', access: 'headless-saved-access', refresh: 'headless-saved-refresh', expires: 1 },
},
},
}) + '\n'
describe('headless credential policy', { retry: 0 }, () => {
it.each([
{ name: 'launch environment', launch: launchKey, project: projectKey, home: homeKey, expected: launchKey },
{ name: 'project .env', launch: undefined, project: projectKey, home: homeKey, expected: projectKey },
{ name: 'home .env', launch: undefined, project: undefined, home: homeKey, expected: homeKey },
])('uses $name instead of saved credentials', async (scenario) => {
const server = await startMockLlmServer({ sequence: ['success'], repeatLast: true, apiKey: scenario.expected })
try {
const result = await runLoaderSmoke({
label: `headless credentials: ${scenario.name}`,
tempDirPrefix: 'headless-credentials-', binScript, tsconfigPath, sourceImport: 'tsx/esm',
configPath: '', binArgs: ['headless', 'Reply briefly.'], processTimeoutMs,
env: {
DEEPSEEK_API_KEY: scenario.launch, DEEPSEEK_BASE_URL: server.baseURL, DSH_TELEMETRY_DISABLED: '1',
},
prepare: async (cwd) => {
await mkdir(join(cwd, '.dsh'), { recursive: true })
await writeFile(join(cwd, '.dsh', '.credentials.yaml'), credentials, { mode: 0o600 })
if (scenario.project !== undefined) await writeFile(join(cwd, '.env'), `DEEPSEEK_API_KEY=${scenario.project}\n`)
if (scenario.home !== undefined) await writeFile(join(cwd, '.dsh', '.env'), `DEEPSEEK_API_KEY=${scenario.home}\n`)
},
inspect: async (cwd) => {
expect(await readFile(join(cwd, '.dsh', '.credentials.yaml'), 'utf8')).toBe(credentials)
},
})
expect(result.stdout.trim()).toBe('mock response recovered')
expect(result.stderr).toBe('')
expect(server.requests.length).toBeGreaterThan(0)
expect(server.requests.every(request => request.headers['x-api-key'] === scenario.expected)).toBe(true)
} finally {
await server.close()
}
}, processTimeoutMs + 15_000)
it.each(['named reference', 'native discovery'] as const)('uses launch credentials for pi-ai %s', async (mode) => {
const server = await startAnthropicServer()
try {
const result = await runLoaderSmoke({
label: `headless pi-ai credentials: ${mode}`,
tempDirPrefix: 'headless-pi-credentials-', binScript, tsconfigPath, sourceImport: 'tsx/esm',
configPath: '', binArgs: ['headless', '--patch', './auth.patch.json', 'Reply briefly.'], processTimeoutMs,
env: {
ANTHROPIC_API_KEY: launchKey, ANTHROPIC_AUTH_TOKEN: undefined, ANTHROPIC_OAUTH_TOKEN: undefined,
ANTHROPIC_FEDERATION_RULE_ID: undefined, ANTHROPIC_ORGANIZATION_ID: undefined,
ANTHROPIC_IDENTITY_TOKEN_FILE: undefined, ANTHROPIC_SERVICE_ACCOUNT_ID: undefined, ANTHROPIC_WORKSPACE_ID: undefined,
DEEPSEEK_API_KEY: undefined, DSH_TELEMETRY_DISABLED: '1',
},
prepare: async (cwd) => {
await mkdir(join(cwd, '.dsh'), { recursive: true })
await writeFile(join(cwd, '.dsh', '.credentials.yaml'), credentials, { mode: 0o600 })
await writeFile(join(cwd, 'auth.patch.json'), JSON.stringify([
{ id: 'agent-default-model', config: { provider: 'anthropic', model: 'headless-auth-model' } },
{ id: 'llm-pi-ai', config: { providers: { anthropic: {
...mode === 'named reference' ? { apiKeyEnv: 'ANTHROPIC_API_KEY' } : {},
baseURL: server.baseURL,
models: [{ id: 'headless-auth-model', contextWindow: 32_768, maxTokens: 1024 }],
} } } },
]))
},
inspect: async (cwd) => {
expect(await readFile(join(cwd, '.dsh', '.credentials.yaml'), 'utf8')).toBe(credentials)
},
})
expect(result.stdout.trim()).toBe('mock response recovered')
expect(result.stderr).toBe('')
expect(server.keys.length).toBeGreaterThan(0)
expect(server.keys.every(key => key === launchKey)).toBe(true)
} finally {
await server.close()
}
}, processTimeoutMs + 15_000)
it.each(['no environment key', 'empty environment key', 'invalid stored document', 'restore stored credentials'] as const)('%s', async (mode) => {
const restoring = mode === 'restore stored credentials'
const empty = mode === 'empty environment key'
const missing = mode === 'no environment key' || empty
const document = mode === 'invalid stored document' ? 'invalid: [\n' : credentials
const server = await startMockLlmServer({ sequence: ['success'], repeatLast: true, apiKey: restoring ? savedKey : launchKey })
try {
const result = await runLoaderSmoke({
label: `headless credential boundary: ${mode}`,
tempDirPrefix: 'headless-credential-boundary-', binScript, tsconfigPath, sourceImport: 'tsx/esm',
configPath: '',
binArgs: ['headless', ...restoring ? ['--patch', './auth.patch.json'] : [], 'Reply briefly.'],
processTimeoutMs, expectedExitCode: missing ? 1 : 0,
env: { DEEPSEEK_API_KEY: empty ? '' : missing ? undefined : launchKey, DEEPSEEK_BASE_URL: server.baseURL, DSH_TELEMETRY_DISABLED: '1' },
prepare: async (cwd) => {
await mkdir(join(cwd, '.dsh'), { recursive: true })
await writeFile(join(cwd, '.dsh', '.credentials.yaml'), document, { mode: 0o600 })
if (empty) await writeFile(join(cwd, '.env'), `DEEPSEEK_API_KEY=${projectKey}\n`)
if (restoring) await writeFile(join(cwd, 'auth.patch.json'), JSON.stringify(
['credentials', 'authorization', 'deepseek-account'].map(id => ({ id, disabled: false })),
))
},
inspect: async (cwd) => {
expect(await readFile(join(cwd, '.dsh', '.credentials.yaml'), 'utf8')).toBe(document)
},
})
if (missing) {
expect(result.stdout).toBe('\n')
expect(result.stderr).toContain('MISSING_CREDENTIAL')
expect(server.requests).toHaveLength(0)
} else {
expect(result.stdout.trim()).toBe('mock response recovered')
expect(result.stderr).toBe('')
expect(server.requests.length).toBeGreaterThan(0)
}
} finally {
await server.close()
}
}, processTimeoutMs + 15_000)
it.each([
{ provider: 'deepseek-account', model: 'deepseek-v4-flash', code: 'ACCOUNT_SIGN_IN_REQUIRED' },
{ provider: 'openai-codex', model: 'gpt-5.4', code: 'PI_AI_ERROR: Provider is not configured: openai-codex' },
])('fails without saved sign-in for $provider', async ({ provider, model, code }) => {
const result = await runLoaderSmoke({
label: `headless saved sign-in: ${provider}`,
tempDirPrefix: 'headless-saved-sign-in-', binScript, tsconfigPath, sourceImport: 'tsx/esm',
configPath: '', binArgs: ['headless', '--patch', './auth.patch.json', 'Reply briefly.'],
processTimeoutMs, expectedExitCode: 1,
env: { DEEPSEEK_API_KEY: undefined, OPENAI_API_KEY: undefined, DSH_TELEMETRY_DISABLED: '1' },
prepare: async (cwd) => {
await mkdir(join(cwd, '.dsh'), { recursive: true })
await writeFile(join(cwd, '.dsh', '.credentials.yaml'), credentials, { mode: 0o600 })
await writeFile(join(cwd, 'auth.patch.json'), JSON.stringify([
{ id: 'agent-default-model', config: { provider, model } },
...provider === 'openai-codex' ? [{ id: 'llm-pi-ai', config: { providers: {
[provider]: { models: [{ id: model, contextWindow: 32_768, maxTokens: 1024 }] },
} } }] : [],
]))
},
inspect: async (cwd) => {
expect(await readFile(join(cwd, '.dsh', '.credentials.yaml'), 'utf8')).toBe(credentials)
},
})
expect(result.stdout).toBe('\n')
expect(result.stderr).toContain(code)
expect(result.stderr).not.toContain('pending')
}, processTimeoutMs + 15_000)
})
@@ -8,7 +8,7 @@
{"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":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your parent agent id is \"{{sessionId}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"{{sessionId}}\", message: \"<self-contained result>\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\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 a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
{"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}}
@@ -8,7 +8,7 @@
{"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":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your parent agent id is \"{{sessionId}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"{{sessionId}}\", message: \"<self-contained result>\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\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 a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"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:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"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":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
{"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}}
+19
View File
@@ -47,7 +47,24 @@ function describeSelection(state: Awaited<ReturnType<typeof selectionState>>): s
async function exerciseComposer(page: Page): Promise<string[]> {
const input = page.locator('[data-composer-input][contenteditable="true"]')
await input.click()
// Let the editor observe its insertText selection before native arrow moves;
// a coalesced first notification can otherwise be treated as its own update.
await input.evaluate((el) => {
const onSelectionChange = (): void => {
const selection = el.ownerDocument.getSelection()
if (selection === null || !el.contains(selection.anchorNode) || !el.contains(selection.focusNode)) return
if (selection.isCollapsed && selection.anchorOffset === 16 && el.textContent === 'alpha beta gamma') {
el.dataset.selectionReady = 'inserted'
return
}
if (selection.toString() !== 'beta' || selection.anchorOffset !== 10 || selection.focusOffset !== 6) return
el.dataset.selectionReady = 'selected'
el.ownerDocument.removeEventListener('selectionchange', onSelectionChange)
}
el.ownerDocument.addEventListener('selectionchange', onSelectionChange)
})
await page.keyboard.insertText('alpha beta gamma')
await expect.poll(() => input.getAttribute('data-selection-ready')).toBe('inserted')
await page.keyboard.press('Home')
for (let index = 0; index < 10; index++) await page.keyboard.press('ArrowRight')
for (let index = 0; index < 4; index++) await page.keyboard.press('Shift+ArrowLeft')
@@ -76,6 +93,8 @@ async function exerciseComposer(page: Page): Promise<string[]> {
observations.push(`- ${point.name}: ${describeSelection(await selectionState(page))}`)
}
await expect.poll(() => input.getAttribute('data-selection-ready')).toBe('selected')
await input.evaluate((el) => { delete el.dataset.selectionReady })
const top = points[0]!
const cardBox = await page.locator('[data-composer-card]').boundingBox()
await page.mouse.click(cardBox!.x - 12, top.y)
@@ -52,7 +52,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
const messages = dialog
await messages.getByText('自定义设置', { exact: true }).click()
expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder'))
.toBe('https://api.deepseek.com/anthropic')
.toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)')
await compareOrRefreshGolden(join(EXPECTED, 'cards.expected.md'),
await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode())
await messages.getByLabel('API 密钥', { exact: true }).fill('sk-e2e-messages')
@@ -15,12 +15,14 @@
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 已配置——输入新值可替换
- /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY)
- text: API 密钥来源:已保存凭据
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
- /placeholder: https://api.deepseek.com/anthropic
- /placeholder: https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)
- text: 请填写兼容 Anthropic Messages 协议的 API 地址。
- region "模型目录":
- text: 模型目录 正在使用适配器默认模型
@@ -20,12 +20,13 @@
- button "编辑 openai": 编辑
- button "删除 openai": 删除
- text: openai API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 输入 API 密钥,或留空使用环境认证
- /placeholder: 留空时保留现有认证(OPENAI_API_KEY)
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
- /placeholder: 提供商默认
- /placeholder: https://api.openai.com/v1
- region "模型目录":
- text: 模型目录 已自定义模型目录
- button "恢复默认模型"
@@ -21,7 +21,7 @@
- button "删除 Acme Gateway (acme-gateway)": 删除
- text: Acme Gateway acme-gateway API 密钥
- textbox "API 密钥":
- /placeholder: 输入 API 密钥,或留空使用环境认证
- /placeholder: 输入 API 密钥
- group:
- text: 自定义设置 显示名称
- textbox "显示名称":
@@ -59,8 +59,9 @@
- option "zai"
- option "zai-coding-cn"
- text: API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 输入 API 密钥,或留空使用环境认证
- /placeholder: 留空时保留现有认证(MINIMAX_CN_API_KEY)
- group: 自定义设置
- button "取消"
- button "保存"
@@ -21,7 +21,7 @@
- button "删除 Acme 网关 (acme-gateway)": 删除
- text: Acme 网关 acme-gateway API 密钥
- textbox "API 密钥":
- /placeholder: 输入 API 密钥,或留空使用环境认证
- /placeholder: 输入 API 密钥
- group:
- text: 自定义设置 显示名称
- textbox "显示名称":
@@ -0,0 +1,63 @@
- dialog "设置":
- navigation:
- text: 设置
- button "通用设置"
- button "模型"
- button "内置插件"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list
- tablist "添加方式":
- tab "第三方模型提供商" [selected]
- tab "自定义模型 API"
- paragraph: 从内置目录中选择 OpenAI、Anthropic、Kimi 等提供商,填入其 API 密钥即可使用。
- tabpanel "第三方模型提供商":
- text: 提供商
- combobox "提供商":
- option "amazon-bedrock"
- option "ant-ling"
- option "anthropic"
- option "azure"
- option "baseten"
- option "cerebras"
- option "cloudflare-ai-gateway"
- option "cloudflare-workers-ai"
- option "deepseek"
- option "fireworks"
- option "github-copilot"
- option "google"
- option "google-vertex"
- option "groq"
- option "huggingface"
- option "kimi-coding"
- option "meta"
- option "minimax"
- option "minimax-cn"
- option "mistral"
- option "moonshotai"
- option "moonshotai-cn"
- option "nvidia"
- option "openai"
- option "openai-codex" [selected]
- option "opencode"
- option "opencode-go"
- option "openrouter"
- option "qwen-token-plan"
- option "qwen-token-plan-cn"
- option "qwen-token-plan-individual"
- option "radius"
- option "together"
- option "vercel-ai-gateway"
- option "xai"
- option "xiaomi"
- option "xiaomi-token-plan-ams"
- option "xiaomi-token-plan-cn"
- option "xiaomi-token-plan-sgp"
- option "zai"
- option "zai-coding-cn"
- group: 自定义设置
- button "取消"
- button "保存"
@@ -15,12 +15,14 @@
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 已配置——输入新值可替换
- /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY)
- text: API 密钥来源:已保存凭据
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
- /placeholder: https://api.deepseek.com/anthropic
- /placeholder: https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)
- text: 请填写兼容 Anthropic Messages 协议的 API 地址。
- region "模型目录":
- text: 模型目录 正在使用适配器默认模型
@@ -2,7 +2,8 @@
- heading "添加一个 API Key 开始使用" [level=2]
- paragraph: 配置 DeepSeek 官方模型,即可开始使用。
- text: API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 输入 API 密钥
- /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY)
- button "稍后配置"
- button "保存并继续" [disabled]
@@ -15,12 +15,14 @@
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 已配置——输入新值可替换
- /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY)
- text: API 密钥来源:已保存凭据
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
- /placeholder: https://api.deepseek.com/anthropic
- /placeholder: https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)
- text: 请填写兼容 Anthropic Messages 协议的 API 地址。
- region "模型目录":
- text: 模型目录 已自定义模型目录
@@ -12,8 +12,9 @@
- list:
- listitem:
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 输入 API 密钥
- /placeholder: 留空时保留现有认证(DEEPSEEK_API_KEY)
- group: 自定义设置
- button "取消"
- button "保存"
@@ -63,8 +63,9 @@
- option "zai"
- option "zai-coding-cn"
- text: API 密钥
- button "认证说明": "?"
- textbox "API 密钥":
- /placeholder: 输入 API 密钥,或留空使用环境认证
- /placeholder: 留空时保留现有认证(MINIMAX_CN_API_KEY)
- group: 自定义设置
- button "取消"
- button "保存"
+13 -2
View File
@@ -20,7 +20,7 @@ import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
import type { Browser, Page, Request, Route } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { afterAll, beforeAll, describe, expect, it, onTestFailed, vi } from 'vitest'
import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
@@ -29,6 +29,7 @@ import { openSettings, ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/models-settings', import.meta.url))
const EMPTY_EXPECTED = join(SNAPSHOT_DIR, 'empty.expected.md')
const NATIVE_KEYLESS_EXPECTED = join(SNAPSHOT_DIR, 'native-keyless.expected.md')
const CONFIGURED_EXPECTED = join(SNAPSHOT_DIR, 'configured.expected.md')
const DECLARED_EXPECTED = join(SNAPSHOT_DIR, 'declared.expected.md')
const DECLARED_EDIT_EXPECTED = join(SNAPSHOT_DIR, 'declared-edit.expected.md')
@@ -44,6 +45,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
vi.stubEnv('OPENAI_API_KEY', 'models-settings-test-key')
scaffold = await launchWebScaffold({})
browser = await chromium.launch()
// The scenario asserts the shipped Chinese copy, so the browser asks for it.
@@ -80,6 +82,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
}, 120_000)
afterAll(async () => {
vi.unstubAllEnvs()
await browser?.close()
await scaffold?.close()
})
@@ -120,6 +123,12 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
const options = await pick.locator('option').allTextContents()
expect(options).toContain('anthropic')
expect(options).toContain('minimax-cn')
await pick.selectOption('openai-codex')
await expect.poll(async () => dialog.getByRole('textbox', { name: 'API 密钥', exact: true }).count(), { timeout: 10_000 }).toBe(0)
expect(await dialog.getByRole('button', { name: '认证说明', exact: true }).count()).toBe(0)
expect(await dialog.textContent()).not.toMatch(/oauth/i)
const nativeSnapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(NATIVE_KEYLESS_EXPECTED, nativeSnapshot, MODE)
await pick.selectOption('minimax-cn')
await dialog.getByRole('textbox', { name: 'API 密钥', exact: true }).waitFor({ timeout: 10_000 })
const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
@@ -206,6 +215,8 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized'))
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click()
await dialog.getByText('API 密钥来源:已保存凭据', { exact: true }).waitFor({ timeout: 10_000 })
expect(await dialog.textContent()).not.toMatch(/oauth/i)
await dialog.getByText('自定义设置').click()
const url = dialog.getByLabel('API 地址')
await url.waitFor({ timeout: 10_000 })
@@ -535,7 +546,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
await assertFixtureInventory(SNAPSHOT_DIR, [
'configured.expected.md', 'declared-edit.expected.md', 'declared.expected.md',
'delete.expected.md', 'empty.expected.md', 'model-picker.expected.md',
'native-delete.expected.md', 'catalog-inputs.expected.md',
'native-delete.expected.md', 'native-keyless.expected.md', 'catalog-inputs.expected.md',
'refreshing.expected.md', 'image-only.expected.md',
])
})
@@ -111,7 +111,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await expect.poll(
() => configuredInput.getAttribute('placeholder'),
{ timeout: 10_000 },
).toBe('已配置——输入新值可替换')
).toBe('留空时保留现有认证(DEEPSEEK_API_KEY)')
const secondReloadWarnings = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
@@ -252,7 +252,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await expect.poll(
() => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'),
{ timeout: 10_000 },
).toBe('已配置——输入新值可替换')
).toBe('留空时保留现有认证(DEEPSEEK_API_KEY)')
const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE)
await settings.getByRole('button', { name: '保存', exact: true }).click()
+2 -2
View File
@@ -773,7 +773,7 @@ export interface Config {
## `@deepseek-ai/dsh-credentials-local`
- `source`: [`packages/credentials/credentials-local/src/index.ts:64`](../packages/credentials/credentials-local/src/index.ts)
- `source`: [`packages/credentials/credentials-local/src/index.ts:63`](../packages/credentials/credentials-local/src/index.ts)
```ts config-catalog
/** Plugin config: file location and hot-reload behavior. */
@@ -3999,7 +3999,7 @@ export interface Config {
- `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections`
- `refs`: [`AgentOptions`](subsystems/core.md)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:48`](../packages/subagent/tool-subagent/src/index.ts)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:49`](../packages/subagent/tool-subagent/src/index.ts)
```ts config-catalog
/** Config: which registered provider this tool delegates to, plus child defaults. */
+2 -2
View File
@@ -775,7 +775,7 @@ export interface Config {
## `@deepseek-ai/dsh-credentials-local`
- `source`: [`packages/credentials/credentials-local/src/index.ts:64`](../packages/credentials/credentials-local/src/index.ts)
- `source`: [`packages/credentials/credentials-local/src/index.ts:63`](../packages/credentials/credentials-local/src/index.ts)
```ts config-catalog
/** Plugin config: file location and hot-reload behavior. */
@@ -4001,7 +4001,7 @@ export interface Config {
- `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections`
- `refs`: [`AgentOptions`](subsystems/core.zh.md)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:48`](../packages/subagent/tool-subagent/src/index.ts)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:49`](../packages/subagent/tool-subagent/src/index.ts)
```ts config-catalog
/** Config: which registered provider this tool delegates to, plus child defaults. */
+6 -5
View File
@@ -722,10 +722,6 @@ flowchart TD
pkg_command_goal --> pkg_commands
pkg_command_goal --> pkg_goal
pkg_command_goal --> pkg_llm
pkg_goal_round_driver --> pkg_agent
pkg_goal_round_driver --> pkg_goal
pkg_goal_round_driver --> pkg_llm
pkg_goal_round_driver --> pkg_session
pkg_fs_sandbox --> pkg_fs
pkg_fs_sandbox --> pkg_fs_local
pkg_fs_sandbox --> pkg_sandbox
@@ -1213,6 +1209,11 @@ flowchart TD
pkg_webhook_github --> pkg_host_webserver
pkg_webhook_github --> pkg_session
pkg_webhook_github --> pkg_webhook
pkg_goal_round_driver --> pkg_agent
pkg_goal_round_driver --> pkg_goal
pkg_goal_round_driver --> pkg_llm
pkg_goal_round_driver --> pkg_session
pkg_goal_round_driver --> pkg_subagent
pkg_subagent_acp --> pkg_agent
pkg_subagent_acp --> pkg_llm
pkg_subagent_acp --> pkg_session
@@ -1658,7 +1659,6 @@ flowchart TD
| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`timeout`](../packages/util/timeout) |
| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) |
| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) |
| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
| [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) |
| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) |
@@ -1745,6 +1745,7 @@ flowchart TD
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
| [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) |
| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) |
| [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`subagent-claude-code`](../packages/subagent/subagent-claude-code) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`subagent-codex`](../packages/subagent/subagent-codex) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
+6 -5
View File
@@ -724,10 +724,6 @@ flowchart TD
pkg_command_goal --> pkg_commands
pkg_command_goal --> pkg_goal
pkg_command_goal --> pkg_llm
pkg_goal_round_driver --> pkg_agent
pkg_goal_round_driver --> pkg_goal
pkg_goal_round_driver --> pkg_llm
pkg_goal_round_driver --> pkg_session
pkg_fs_sandbox --> pkg_fs
pkg_fs_sandbox --> pkg_fs_local
pkg_fs_sandbox --> pkg_sandbox
@@ -1215,6 +1211,11 @@ flowchart TD
pkg_webhook_github --> pkg_host_webserver
pkg_webhook_github --> pkg_session
pkg_webhook_github --> pkg_webhook
pkg_goal_round_driver --> pkg_agent
pkg_goal_round_driver --> pkg_goal
pkg_goal_round_driver --> pkg_llm
pkg_goal_round_driver --> pkg_session
pkg_goal_round_driver --> pkg_subagent
pkg_subagent_acp --> pkg_agent
pkg_subagent_acp --> pkg_llm
pkg_subagent_acp --> pkg_session
@@ -1660,7 +1661,6 @@ flowchart TD
| [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`timeout`](../packages/util/timeout) |
| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) |
| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) |
| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
| [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) |
| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) |
@@ -1747,6 +1747,7 @@ flowchart TD
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
| [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) |
| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) |
| [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`subagent-claude-code`](../packages/subagent/subagent-claude-code) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`subagent-codex`](../packages/subagent/subagent-codex) | `subagent` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
+22 -22
View File
@@ -549,8 +549,8 @@
en: 028791baa24a6a0a
zh: 028791baa24a6a0a
/session-persistence-event-catalog/resolved-persistence-types/in-history:
en: 7ee8e3e9b3947c22
zh: 035ceca2d5031800
en: 8bda2ac68f50953b
zh: 190a69ddd097c445
/session-persistence-event-catalog/resolved-persistence-types/in-progress:
en: 61de2b0c9de8c15b
zh: 61de2b0c9de8c15b
@@ -1167,8 +1167,8 @@
en: 07e04c3e336f880f
zh: 6f8986ede9994fa1
/session-persistence-event-catalog/resolved-persistence-types/replayenvelope:
en: 9a80b6f5eb08eaea
zh: 061c632b8f3e4d87
en: 3460f0c910a247fd
zh: 3990587ab01a1907
/session-persistence-event-catalog/resolved-persistence-types/requestcontext:
en: cc8bb7075d546941
zh: 77209abf30744be0
@@ -1215,8 +1215,8 @@
en: ecc15ebadb77afdf
zh: 97ac27d6a4175f6f
/session-persistence-event-catalog/resolved-persistence-types/streamchunk:
en: 0d571899222eb04f
zh: de28c6d67d1763c1
en: 12fe93a89508739b
zh: 03306c0f7b124f0d
/session-persistence-event-catalog/resolved-persistence-types/subagentcatalogevent:
en: 725539dcd5c335ed
zh: 5ca08d3667f84ff9
@@ -1284,8 +1284,8 @@
en: 2258683c3cfa4ce3
zh: 5663aa76c911761b
/session-persistence-event-catalog/resolved-persistence-types/toolschema:
en: 6e1e6ebc7c1c38c8
zh: e47a3ca80c4c3b71
en: eb76c5bd050ffccd
zh: cb24780d4b5f79ac
/session-persistence-event-catalog/resolved-persistence-types/toolschema~2:
en: 12c14727bb7834e2
zh: b0f3c877873c36db
@@ -1932,11 +1932,11 @@
en: bb507524bcc39c53
zh: 8314898562437473
/session-persistence-event-catalog/resolved-persistence-types/type-block-end:
en: 8c5a05fa6adf3e70
zh: 66768b25d6fb3e07
en: c5acb63761d0cbb8
zh: 6caad01b80c6eb0d
/session-persistence-event-catalog/resolved-persistence-types/type-block-start:
en: 5caed426cab416ee
zh: 86f47f90f8c440f2
en: c52a22b7878bde2f
zh: 42f3fae52cf09ebb
/session-persistence-event-catalog/resolved-persistence-types/type-chunk:
en: 2186ede3e9917aea
zh: 0cfef64045dce95b
@@ -1974,8 +1974,8 @@
en: 14e4b48d856bcf57
zh: 72ba176535dc7f3f
/session-persistence-event-catalog/resolved-persistence-types/type-finish:
en: 21627e72a24990ff
zh: d71375de325ee9f8
en: 359385a004565fda
zh: 313f78d5906a3128
/session-persistence-event-catalog/resolved-persistence-types/type-goal-change:
en: aad2516b62d3ee83
zh: e7204c4dc4e8e408
@@ -2013,8 +2013,8 @@
en: 34e5591d75322649
zh: a216839f305c9796
/session-persistence-event-catalog/resolved-persistence-types/type-reasoning-delta:
en: a18feb76be195fa0
zh: 3db7147ee4c5c963
en: 8b5e884e0c0ab11b
zh: 3b291d80028b6583
/session-persistence-event-catalog/resolved-persistence-types/type-request-context:
en: f8addb1a01da9ca1
zh: 4ef11ebddd302c05
@@ -2073,8 +2073,8 @@
en: 1484738718de5312
zh: 3e6fbe9c64068225
/session-persistence-event-catalog/resolved-persistence-types/type-text-delta:
en: 47ae2d57be710450
zh: b072753349ac505e
en: bac4775a1255bbbb
zh: 834b81d203e21b7c
/session-persistence-event-catalog/resolved-persistence-types/type-todo-write:
en: 2fa7ba77598a95b4
zh: 50972b51d77e9155
@@ -2082,8 +2082,8 @@
en: 32f732b97739e4d2
zh: f288e48e356969c0
/session-persistence-event-catalog/resolved-persistence-types/type-tool-call-delta:
en: 1df89f427ccac815
zh: 1bec3d025ea1f7e3
en: a172400ce8d6dbe7
zh: 1d6cba18564d0230
/session-persistence-event-catalog/resolved-persistence-types/type-tool-workflow-agent-end:
en: 8eb5e1eb95722bc7
zh: 8dd5980029600648
@@ -2115,8 +2115,8 @@
en: 1b045de96172be4b
zh: 8a15c6f35b576b37
/session-persistence-event-catalog/resolved-persistence-types/type-usage:
en: fa542ccb91698e56
zh: 7b725c813d69588d
en: a5579e3f96903381
zh: deac8bf4949cf17a
/session-persistence-event-catalog/resolved-persistence-types/type-user-message:
en: fb49c375aec5952c
zh: 19b80920c1068b86
+11 -11
View File
@@ -1986,7 +1986,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8`
SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5`
Sources: [`packages/llm/llm/src/types.ts:396`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:412`](../packages/llm/llm/src/types.ts)
`"in-history"`
@@ -4476,7 +4476,7 @@ Sources: [`packages/llm/llm/src/types.ts:68`](../packages/llm/llm/src/types.ts)
SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555`
Sources: [`packages/llm/llm/src/types.ts:430`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:446`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -4771,7 +4771,7 @@ Sources: [`packages/skill/skill/src/index.ts:146`](../packages/skill/skill/src/i
SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180`
Sources: [`packages/llm/llm/src/types.ts:452`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:468`](../packages/llm/llm/src/types.ts)
One of:
@@ -5196,7 +5196,7 @@ Sources: [`packages/llm/llm/src/message.ts:173`](../packages/llm/llm/src/message
SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2`
Sources: [`packages/llm/llm/src/types.ts:473`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:489`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8009,7 +8009,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625`
SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d`
Sources: [`packages/llm/llm/src/types.ts:457`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:473`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8023,7 +8023,7 @@ Sources: [`packages/llm/llm/src/types.ts:457`](../packages/llm/llm/src/types.ts)
SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90`
Sources: [`packages/llm/llm/src/types.ts:453`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:469`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8229,7 +8229,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8`
SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1`
Sources: [`packages/llm/llm/src/types.ts:459`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:475`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8435,7 +8435,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:28`](../packages/llm/llm/src
SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095`
Sources: [`packages/llm/llm/src/types.ts:455`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:471`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8755,7 +8755,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:21`](../packages/llm/llm/src
SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65`
Sources: [`packages/llm/llm/src/types.ts:454`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:470`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8803,7 +8803,7 @@ Sources: [`packages/llm/llm/src/assistant-stream.ts:35`](../packages/llm/llm/src
SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a`
Sources: [`packages/llm/llm/src/types.ts:456`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:472`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
@@ -8981,7 +8981,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8`
SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515`
Sources: [`packages/llm/llm/src/types.ts:458`](../packages/llm/llm/src/types.ts)
Sources: [`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts)
| Property | Presence | Type |
|---|---|---|
+11 -11
View File
@@ -1988,7 +1988,7 @@ SHA-256: `ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8`
SHA-256: `f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5`
来源:[`packages/llm/llm/src/types.ts:396`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:412`](../packages/llm/llm/src/types.ts)
`"in-history"`
@@ -4478,7 +4478,7 @@ SHA-256: `814d9434e1ddf9078612b3b34322f26e9363b469213335007f7e9ba7fee9464e`
SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555`
来源:[`packages/llm/llm/src/types.ts:430`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:446`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -4773,7 +4773,7 @@ SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db`
SHA-256: `47e9095591ae36e7c39ee62553097772f2bfa16304536a72dbbc3f691f605180`
来源:[`packages/llm/llm/src/types.ts:452`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:468`](../packages/llm/llm/src/types.ts)
以下类型之一:
@@ -5198,7 +5198,7 @@ SHA-256: `4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731`
SHA-256: `66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2`
来源:[`packages/llm/llm/src/types.ts:473`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:489`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8011,7 +8011,7 @@ SHA-256: `1033093edd0db80ff410e00830b523405e00bb0c7684948e531ff65095799625`
SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d`
来源:[`packages/llm/llm/src/types.ts:457`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:473`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8025,7 +8025,7 @@ SHA-256: `d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d`
SHA-256: `3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90`
来源:[`packages/llm/llm/src/types.ts:453`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:469`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8231,7 +8231,7 @@ SHA-256: `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8`
SHA-256: `a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1`
来源:[`packages/llm/llm/src/types.ts:459`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:475`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8437,7 +8437,7 @@ SHA-256: `71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd`
SHA-256: `2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095`
来源:[`packages/llm/llm/src/types.ts:455`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:471`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8757,7 +8757,7 @@ SHA-256: `e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33`
SHA-256: `95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65`
来源:[`packages/llm/llm/src/types.ts:454`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:470`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8805,7 +8805,7 @@ SHA-256: `3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6`
SHA-256: `88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a`
来源:[`packages/llm/llm/src/types.ts:456`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:472`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -8983,7 +8983,7 @@ SHA-256: `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8`
SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515`
来源:[`packages/llm/llm/src/types.ts:458`](../packages/llm/llm/src/types.ts)
来源:[`packages/llm/llm/src/types.ts:474`](../packages/llm/llm/src/types.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
+11 -11
View File
@@ -22422,7 +22422,7 @@
"packages/llm/llm/src/types.ts#ReplayEnvelope"
],
"sources": [
"packages/llm/llm/src/types.ts:430"
"packages/llm/llm/src/types.ts:446"
]
},
{
@@ -22948,7 +22948,7 @@
"digest": "2abb711460e6238d851c30f3e4bdd87a2aa1887ee70575b3d3b7b25610673095",
"names": [],
"sources": [
"packages/llm/llm/src/types.ts:455"
"packages/llm/llm/src/types.ts:471"
]
},
{
@@ -23199,7 +23199,7 @@
"digest": "3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90",
"names": [],
"sources": [
"packages/llm/llm/src/types.ts:453"
"packages/llm/llm/src/types.ts:469"
]
},
{
@@ -23335,7 +23335,7 @@
"packages/llm/llm/src/types.ts#StreamChunk"
],
"sources": [
"packages/llm/llm/src/types.ts:452"
"packages/llm/llm/src/types.ts:468"
]
},
{
@@ -23851,7 +23851,7 @@
"packages/llm/llm/src/types.ts#ToolSchema"
],
"sources": [
"packages/llm/llm/src/types.ts:473"
"packages/llm/llm/src/types.ts:489"
]
},
{
@@ -24375,7 +24375,7 @@
"digest": "88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a",
"names": [],
"sources": [
"packages/llm/llm/src/types.ts:456"
"packages/llm/llm/src/types.ts:472"
]
},
{
@@ -24542,7 +24542,7 @@
"digest": "95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65",
"names": [],
"sources": [
"packages/llm/llm/src/types.ts:454"
"packages/llm/llm/src/types.ts:470"
]
},
{
@@ -24730,7 +24730,7 @@
"digest": "a2b49331716ba0a7078b026d145306a70eae64b7313c3e6204bd931e75ec3bb1",
"names": [],
"sources": [
"packages/llm/llm/src/types.ts:459"
"packages/llm/llm/src/types.ts:475"
]
},
{
@@ -25426,7 +25426,7 @@
"digest": "d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d",
"names": [],
"sources": [
"packages/llm/llm/src/types.ts:457"
"packages/llm/llm/src/types.ts:473"
]
},
{
@@ -25833,7 +25833,7 @@
"digest": "f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515",
"names": [],
"sources": [
"packages/llm/llm/src/types.ts:458"
"packages/llm/llm/src/types.ts:474"
]
},
{
@@ -25861,7 +25861,7 @@
"packages/llm/llm/src/types.ts#SystemPromptUpdate"
],
"sources": [
"packages/llm/llm/src/types.ts:396"
"packages/llm/llm/src/types.ts:412"
]
},
{
+4 -4
View File
@@ -6,14 +6,14 @@
en: 4589c745baf092c7
zh: 3a782e6a06825201
/user-credentials/identity:
en: aba5a25c34e229cc
zh: 96493f925f60b533
en: 0083032b9d19467d
zh: 15d7a7520bac094e
/user-credentials/resolution:
en: baaab4bca76bea6b
zh: 54ccdc03ffd44f63
/user-credentials/description:
en: 17573160805d3014
zh: 36a058a96f45df23
en: f7b09588c0f34952
zh: 1b93d673c5bf6a80
/user-credentials/change-commits:
en: 464315a953330eb2
zh: d9815591f3abc2cb
+8 -8
View File
@@ -15,6 +15,7 @@ A reference names one credential as a POSIX-style environment-variable name. The
type CredentialRef = Branded<'CredentialRef'>
```
<a id="resolution"></a>
## Resolution
`resolve(ref)` returns the value with the provider-defined source layer that supplied it, or `undefined` while unconfigured. Consumers re-resolve at each operation and never cache across operations — that per-operation read is the hot-update mechanism.
@@ -31,7 +32,7 @@ interface ResolvedCredential {
## Description
`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider reports a reference supplied by the live process environment as `writable: false` — a write would appear to succeed while resolution kept returning the shadowing value, so the seam rejects it and the UI can render the reference read-only up front.
`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again.
```ts type-equiv
/**
@@ -136,7 +137,7 @@ Source: [`packages/credentials/authorization/src/index.ts`](../../packages/crede
Abstract credential service over two key spaces that answer two questions.
A CredentialRef answers "what is behind this environment-variable name", layered over the process environment, the provider-managed store, and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret.
A CredentialRef answers "what is behind this environment-variable name": the provider-managed store first, then ambient fallbacks such as the process environment and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret.
A CredentialKey answers "what credential does this plugin hold for this id". Nothing can layer here — an authorization grant has no environment to be read from — so presence of the record is the whole fact, and modifyRecord is the only write path because a correct write depends on the current value (a token refresh is read-decide-replace under one lock).
@@ -160,10 +161,9 @@ abstract resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>
abstract describe(ref: CredentialRef): Promise<CredentialInfo>
/**
* Durably store one value in the provider-managed writable source. Rejects
* while a read-only source shadows the reference — the write would appear
* to succeed while resolution keeps returning the shadowing value — and
* rejects an empty value (use {@link unset}).
* Durably store one value in the provider-managed writable source. The stored
* value takes precedence over ambient fallbacks, and empty values are
* rejected (use {@link unset}).
* @param ref - the reference to store.
* @param value - the non-empty secret value.
*/
@@ -171,8 +171,8 @@ abstract set(ref: CredentialRef, value: string): Promise<void>
/**
* Remove one reference from the provider-managed writable source; removing
* an absent reference is a no-op. Rejects while a read-only source shadows
* the reference, like {@link set}.
* an absent reference is a no-op. Ambient fallback layers may become
* effective again after removal.
* @param ref - the reference to remove.
*/
abstract unset(ref: CredentialRef): Promise<void>
+8 -8
View File
@@ -15,6 +15,7 @@
type CredentialRef = Branded<'CredentialRef'>
```
<a id="resolution"></a>
## 解析
`resolve(ref)` 返回值及提供该值的来源层(由提供方定义);未配置期间返回 `undefined`。消费方在每个操作中重新解析,绝不跨操作缓存——这种按操作进行的读取正是热更新机制。
@@ -31,7 +32,7 @@ interface ResolvedCredential {
## 描述
`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方把由当前进程环境供值的引用报告为 `writable: false`——那样的写入会表面成功而解析持续返回遮蔽值,因此 seam 直接拒绝,界面也得以提前把该引用渲染为只读。
`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。
```ts type-equiv
/**
@@ -136,7 +137,7 @@ Source: [`packages/credentials/authorization/src/index.ts`](../../packages/crede
Abstract credential service over two key spaces that answer two questions.
A CredentialRef answers "what is behind this environment-variable name", layered over the process environment, the provider-managed store, and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret.
A CredentialRef answers "what is behind this environment-variable name": the provider-managed store first, then ambient fallbacks such as the process environment and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret.
A CredentialKey answers "what credential does this plugin hold for this id". Nothing can layer here — an authorization grant has no environment to be read from — so presence of the record is the whole fact, and modifyRecord is the only write path because a correct write depends on the current value (a token refresh is read-decide-replace under one lock).
@@ -160,10 +161,9 @@ abstract resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>
abstract describe(ref: CredentialRef): Promise<CredentialInfo>
/**
* Durably store one value in the provider-managed writable source. Rejects
* while a read-only source shadows the reference — the write would appear
* to succeed while resolution keeps returning the shadowing value — and
* rejects an empty value (use {@link unset}).
* Durably store one value in the provider-managed writable source. The stored
* value takes precedence over ambient fallbacks, and empty values are
* rejected (use {@link unset}).
* @param ref - the reference to store.
* @param value - the non-empty secret value.
*/
@@ -171,8 +171,8 @@ abstract set(ref: CredentialRef, value: string): Promise<void>
/**
* Remove one reference from the provider-managed writable source; removing
* an absent reference is a no-op. Rejects while a read-only source shadows
* the reference, like {@link set}.
* an absent reference is a no-op. Ambient fallback layers may become
* effective again after removal.
* @param ref - the reference to remove.
*/
abstract unset(ref: CredentialRef): Promise<void>
+2 -2
View File
@@ -36,8 +36,8 @@
en: 58dec2259b0b1c6f
zh: fc99fe965acaabf3
/llm-streaming/the-model-request:
en: 824d18f76f990711
zh: 8a2895513652e528
en: 60c661bdcfec52dd
zh: c27a46f6c99efea1
/llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header:
en: f2e6932e211f179b
zh: 75112586a6f3f4aa
+20
View File
@@ -498,11 +498,31 @@ interface LlmConfigurableProvider {
* from outside.
*/
declared?: boolean
/**
* Route endpoint the adapter uses when the profile sets no `baseURL`; the
* adapter may still send an individual model to that model's own endpoint.
* Absent when the route has no fixed endpoint.
*/
defaultBaseURL?: string
/** Authentication the adapter performs when the profile names no credential reference; absent when it reports none. */
nativeAuth?: LlmNativeAuth
/** Configuration diagnostic for repair; unaffected models may remain serviceable. */
error?: string
}
```
A settings editor shows `defaultBaseURL` and `nativeAuth` for a profile that leaves the endpoint or the credential reference unset. `nativeAuth` lists environment variable names, never their values.
```ts type-equiv
/** Authentication a provider route performs without a credential reference in its profile. */
interface LlmNativeAuth {
/** Environment variables the route's authentication reads, in lookup order; empty when it reads none. */
env: readonly string[]
/** Whether a stored OAuth sign-in can authenticate the route. */
oauth: boolean
}
```
```ts type-equiv
/** One adapter-discovered model; catalog membership is advisory, not request validation. */
interface LlmModelInfo {
+20
View File
@@ -504,11 +504,31 @@ interface LlmConfigurableProvider {
* from outside.
*/
declared?: boolean
/**
* Route endpoint the adapter uses when the profile sets no `baseURL`; the
* adapter may still send an individual model to that model's own endpoint.
* Absent when the route has no fixed endpoint.
*/
defaultBaseURL?: string
/** Authentication the adapter performs when the profile names no credential reference; absent when it reports none. */
nativeAuth?: LlmNativeAuth
/** Configuration diagnostic for repair; unaffected models may remain serviceable. */
error?: string
}
```
设置编辑器在提供方配置未设置端点或凭据引用时显示 `defaultBaseURL` 和 `nativeAuth`。`nativeAuth` 只列出环境变量名,不包含变量值。
```ts type-equiv
/** Authentication a provider route performs without a credential reference in its profile. */
interface LlmNativeAuth {
/** Environment variables the route's authentication reads, in lookup order; empty when it reads none. */
env: readonly string[]
/** Whether a stored OAuth sign-in can authenticate the route. */
oauth: boolean
}
```
```ts type-equiv
/** One adapter-discovered model; catalog membership is advisory, not request validation. */
interface LlmModelInfo {
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.2/stored-credentials-precedence/guide.md
/:
en: 9fc8377bd2d6e38c
zh: b77fd76aeee0f592
/a-stored-key-takes-precedence-over-an-exported-variable:
en: 0d002196a3f19850
zh: 7dcbbb6a44216f01
/a-stored-key-takes-precedence-over-an-exported-variable/change:
en: 4ac6ffc5e782f765
zh: 51a69db953708bd3
/a-stored-key-takes-precedence-over-an-exported-variable/migration:
en: d4f534f82476b5e9
zh: 5371eaaae96a3759
@@ -0,0 +1,25 @@
---
kind: upgrade-guide
description: "Stored credentials now precede environment fallbacks when the store is mounted; the shipped headless profile omits stored authentication."
---
# A stored key takes precedence over an exported variable
English | [中文](guide.zh.md)
## Change
Earlier releases used an exported environment variable before the `refs` entry with the same name in `$DSH_HOME/.credentials.yaml` (`~/.dsh/.credentials.yaml` by default). This applied to `DEEPSEEK_API_KEY=… dsh`, a shell profile export, a CI secret, and a container `-e` value. While the name was exported, the Models page could not save a key for it.
Now the stored entry wins. The exported variable applies only while the file stores no value for that name, and `$cwd/.env` and `$DSH_HOME/.env` still apply only after both. The Models page can save and replace a key while the name is exported.
The shipped `headless` profile instead disables the credential store, authorization and DeepSeek account provider. It uses the launch environment, project `.env`, then Harness-home `.env`, and leaves `.credentials.yaml` untouched. Saved API keys and sign-ins no longer authenticate headless jobs by default. Web, SDK and ACP retain the store.
You are affected when a harness home stores a value under `refs` and the process that launches `dsh` exports the same name. This includes a container that mounts such a home. Requests now use the stored key instead of the exported one. A CI job or container that starts with a fresh harness home, without `.credentials.yaml`, is not affected. The [stored credential precedence](../../../../.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.md) Agent Note records the reason.
## Migration
1. Compare the names under `refs` in `$DSH_HOME/.credentials.yaml` with the variables that your shell, CI job, or container exports. A name that appears in only one place needs no action.
2. For each name that appears in both places, keep the stored key if it is the account you want. Otherwise, delete the name's line under `refs`. A running harness reloads the file, so the next request reads the exported variable without a restart.
3. For a headless job, export the required key and run `dsh headless "<task>"`. To keep using a saved key or sign-in, apply the three-row [headless restoration patch](../../../../packages/bundle/headless/README.md#credentials); restored storage also restores saved-first precedence. Existing profile, home or command overlays can override the shipped rows, so inspect `dsh headless --dump-config` when checking the effective composition.
4. Confirm the intended request account and that the launching process exports a non-empty value where needed. Check names and presence without printing credential values. A headless run relying only on a saved credential now fails; restoring storage or supplying supported environment authentication resolves it.
@@ -0,0 +1,25 @@
---
kind: upgrade-guide
description: "挂载存储时,已保存凭据现在优先于环境后备;随附 headless profile 不挂载存储认证。"
---
# 存储的密钥优先于导出的变量
[English](guide.md) | 中文
## 变更
早期版本会先使用导出的环境变量,再使用 `$DSH_HOME/.credentials.yaml`(默认为 `~/.dsh/.credentials.yaml`)中同名的 `refs` 条目。这适用于 `DEEPSEEK_API_KEY=… dsh`、shell 配置文件中的导出、CI 机密和容器 `-e` 值。该名字被导出期间,Models 页面无法为其保存密钥。
现在存储的条目优先。只有当文件没有为该名字存储值时,导出的变量才会生效;`$cwd/.env` 和 `$DSH_HOME/.env` 仍排在两者之后。即使该名字已被导出,Models 页面也可以保存和替换密钥。
随附的 `headless` profile 则禁用凭据存储、authorization 和 DeepSeek account 提供方。它依次使用启动环境、项目 `.env` 和 Harness home `.env`,并保持 `.credentials.yaml` 原样。已保存 API 密钥和登录凭据默认不再为 headless 任务提供认证。Web、SDK 和 ACP 保留存储。
如果某个 harness home 在 `refs` 下存储了值,而启动 `dsh` 的进程导出了同名变量,你就会受到影响。挂载了这类 home 的容器也包括在内。请求现在使用存储的密钥,而不是导出的密钥。以全新 harness home 启动、没有 `.credentials.yaml` 的 CI 作业或容器不受影响。[存储凭据优先级](../../../../.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.zh.md) Agent Note 记录了原因。
## 迁移
1. 将 `$DSH_HOME/.credentials.yaml` 中 `refs` 下的名字,与 shell、CI 作业或容器导出的变量进行比较。只出现在其中一处的名字无需处理。
2. 对同时出现在两处的名字,如果存储的密钥正是你要使用的账户,就保留它。否则,删除 `refs` 下该名字所在的行。运行中的 harness 会重新加载该文件,因此下一次请求无需重启即可读取导出的变量。
3. 对 headless 任务,导出所需密钥并运行 `dsh headless "<task>"`。要继续使用已保存密钥或登录凭据,请应用三行配置的 [headless 恢复 patch](../../../../packages/bundle/headless/README.zh.md#credentials);恢复存储也恢复已保存凭据优先。现有 profile、home 或命令覆盖可以覆盖随附行,因此核对有效组合时请查看 `dsh headless --dump-config`。
4. 确认请求使用预期账户,并在需要时确认启动进程导出了非空值。只检查名字和是否存在,不要打印凭据值。仅依赖已保存凭据的 headless 运行现在会失败;恢复存储或提供受支持的环境认证即可解决。
+2 -2
View File
@@ -9,8 +9,8 @@
en: 2c6b665adc256b4e
zh: 2240e4c1573ebe9c
/configure-models/add-a-third-party-provider:
en: 0fe5f88e692f618c
zh: 4f2e493818d8934f
en: 4b99a9b34d117eea
zh: dddeb5a08c0d3cc6
/configure-models/add-a-custom-model-api:
en: 17867305a3e1b52a
zh: 876fedf1f6f563e4
+3 -1
View File
@@ -16,7 +16,9 @@ Keys are write-only. The page receives a redacted descriptor after saving, never
Choose **Add model provider**. The card opens on **Third-party model provider**: pick a provider dsh ships with — the list shows provider ids such as `anthropic`, `openai`, `moonshotai` for Kimi, or `zai` for GLM — enter its API key, and save. The installed catalog supplies the endpoint, protocol, and model list.
Providers that sign in with OAuth, such as Codex, are not supported here yet.
The authentication **?** explains saved-credential priority and the environment fallbacks displayed for a key field. Leaving the key blank preserves existing authentication. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference.
For an existing profile that names a credential reference, **API key source** shows the layer currently supplying that reference: saved credentials, launch environment, `$cwd/.env`, or `$DSH_HOME/.env`. Native authentication without a named reference has no source label.
## Add a custom model API
+3 -1
View File
@@ -16,7 +16,9 @@
选择**添加模型提供商**。卡片默认打开在**第三方模型提供商**:选取 dsh 自带的提供商——列表显示的是提供商 id,例如 `anthropic`、`openai`、Kimi 对应的 `moonshotai`、GLM 对应的 `zai`——输入其 API 密钥并保存。已安装目录会提供端点、协议和模型列表。
通过 OAuth 登录的提供商(例如 Codex)暂不支持。
认证 **?** 说明已保存凭据的优先级,以及密钥字段所显示的环境后备。密钥留空会保留现有认证。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。
已有 profile 指定凭据引用时,**API 密钥来源**显示当前为该引用供值的层:已保存凭据、启动环境、`$cwd/.env` 或 `$DSH_HOME/.env`。未指定引用的原生认证不显示来源标签。
## 添加自定义模型 API
+1 -1
View File
@@ -144,7 +144,7 @@ export type {
// Provider registry and discovery vocabulary for the llm namespace.
export type {
LlmConfigurableProvider, LlmDiscoveredModel,
LlmModelDiscoveryRequest, LlmProviderInfo,
LlmModelDiscoveryRequest, LlmNativeAuth, LlmProviderInfo,
} from '@deepseek-ai/dsh-llm/types'
// Reference-discovery result vocabulary for the fileReferences and
// sessionReferenceResolver namespaces.
@@ -132,11 +132,12 @@ export class CredentialsController extends TypertRemoteService {
/**
* Run one remote write and report every refusal as `credential/rejected`
* carrying the seam's own message: a read-only source shadowing the reference
* is what a configuration surface must show verbatim. Callers brand the
* reference before entering, so a name outside the grammar never reaches this
* path and fails the same way it does on the read side. The details name only
* the reference, so no failure path can carry the value back out.
* carrying the seam's own message: a provider refusal, such as a stored
* document that no longer parses, is what a settings page must show
* verbatim. Callers brand the reference before entering, so a name outside
* the grammar never reaches this path and fails the same way it does on the
* read side. The details name only the reference, so no failure path can
* carry the value back out.
*/
private async write(ref: string, write: () => Promise<void>): Promise<void> {
try {
@@ -20,9 +20,9 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
*/
'settings/conflict': { readonly ns: string; readonly expected: number; readonly actual: number }
/**
* The provider refused a valid credential write, for example because a
* read-only source shadows the reference. The details name only the
* reference, never the value.
* The provider refused a valid credential write, for example because the
* stored document no longer parses. The details name only the reference,
* never the value.
*/
'credential/rejected': { readonly ref: string }
}
@@ -24,7 +24,7 @@ class LiteralRejectingCredentials extends MemoryCredentials {
/** A store whose provider-owned policy rejects an otherwise valid write. */
class RejectingCredentials extends MemoryCredentials {
override set(): Promise<void> {
return Promise.reject(new Error('a read-only source shadows this reference'))
return Promise.reject(new Error('the stored document no longer parses'))
}
}
@@ -120,7 +120,7 @@ describe('the credentials Remote namespace a configuration surface calls', () =>
const failure = await controller.set('DEEPSEEK_API_KEY', 'sk-live').catch((error: unknown) => error)
const { code, message, details } = remoteErrorOf(failure) ?? {}
expect(code).toBe('credential/rejected')
expect(message).toContain('read-only source')
expect(message).toContain('no longer parses')
expect(details).toEqual({ ref: 'DEEPSEEK_API_KEY' })
})
+2 -2
View File
@@ -105,8 +105,8 @@
name: '@deepseek-ai/dsh-settings'
disabled: !!js "!ctx.get('profileContext')"
# Credential sources: inherited environment over the managed
# `$DSH_HOME/.credentials.yaml`, with project and user `.env` fallbacks.
# Credential sources: managed `$DSH_HOME/.credentials.yaml`, then inherited
# environment, project `.env`, and user `.env` fallbacks.
# Adapters resolve references per request; the Models page writes only the
# managed document, which is never materialized into the process environment.
- id: authorization
+5 -2
View File
@@ -18,8 +18,11 @@
en: 4447012f4c84100d
zh: faf579ae9f04c096
/deepseek-ai-dsh-headless/use-this-package/running-a-one-shot-task:
en: 76a22e98d2b3cc2f
zh: c9eb624609b8cc32
en: 89a48af61a38afc3
zh: fe202a1bb2c11781
/deepseek-ai-dsh-headless/use-this-package/credentials:
en: ca8217837ee9c698
zh: fa20daf27d4e09ef
/deepseek-ai-dsh-headless/use-this-package/choosing-the-session-identity:
en: dbaa2fac63910a4c
zh: 4fd5c17815ca444b
+20
View File
@@ -49,6 +49,26 @@ The task and run options are supplied through three settings:
The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-headless) is the exhaustive source for every accepted field and its JSDoc.
<a id="credentials"></a>
### Credentials
The shipped headless profile disables the managed credential store and its authorization and DeepSeek account consumers. API-key routes use the launch environment, then `<invocation cwd>/.env`, then `$DSH_HOME/.env`. Keys and sign-ins saved by the GUI are ignored without changing their file. Providers that require a saved sign-in fail unless stored authentication is restored; external provider credential chains, such as AWS profiles, remain available.
Unset an empty launch variable to allow its `.env` fallback; an exported empty value shadows that fallback.
To restore stored authentication, add these rows to `$DSH_HOME/profiles/headless/cordis.patch.yml` or a `--patch` overlay:
```yaml
- id: credentials
disabled: false
- id: authorization
disabled: false
- id: deepseek-account
disabled: false
```
The restored store uses [saved credentials before environment fallbacks](../../credentials/credentials-local/README.md). Web, SDK and ACP profiles keep that default ordering. Headless sessions, settings and tool behavior are unchanged; this profile choice is not a filesystem access boundary.
### Choosing the session identity
Every invocation defaults to a fresh `session-<uuid>` identity, which `--json` reports in its opening `session` event. Pass `--session-id <id>` to continue that conversation: the runner adopts the persisted Session with that id, and an id with no stored Session fails before the task runs rather than quietly opening an empty history. Adoption requires the composed `sessionPersistence` and `sessionQuery` services, so a profile that omits either fails loudly instead of returning an id whose history dies with the process. An Agent already live under the requested id in this process is refused: another owner may still drive it, so the runner cannot claim an exclusive run interval over it. The identity is opaque, so the exact string is used, whitespace included. The working directory is resolved through the mounted filesystem provider (`fs.resolve('.')` and `fs.processPath()`), or the process cwd when no filesystem service is mounted; new Sessions record that directory. Adoption compares the recorded cwd with the same provider-resolved directory and refuses a Session that is a subagent or forked session, that recorded no working directory, that runs under an agent preset this profile does not compose, or whose preset record is malformed — the check reads the preset the Session log currently records, so a Session that switched preset while blank is rejected too. A supervisor therefore cannot silently drive someone else's conversation under a different composition; any mismatch fails before the task runs.
+20
View File
@@ -49,6 +49,26 @@ agent 会完成该任务,把提供方的每个非空推理(reasoning)增
生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-headless)是所有受支持字段及其 JSDoc 的完整真源。
<a id="credentials"></a>
### 凭据
随附的 headless profile 禁用托管凭据存储,以及依赖它的 authorization 和 DeepSeek account 消费方。API 密钥路由依次使用启动环境、`<运行命令的目录>/.env` 和 `$DSH_HOME/.env`。GUI 保存的密钥和登录凭据不会被使用,存储文件保持原样。需要已保存登录凭据的提供方会失败,除非恢复存储认证;AWS profile 等提供方外部凭据链仍然可用。
启动变量为空时,请取消导出该变量,让 `.env` 后备生效;已导出的空值会遮蔽后备值。
要恢复存储认证,请把以下行加入 `$DSH_HOME/profiles/headless/cordis.patch.yml` 或 `--patch` 覆盖文件:
```yaml
- id: credentials
disabled: false
- id: authorization
disabled: false
- id: deepseek-account
disabled: false
```
恢复后,存储仍按[已保存凭据优先于环境后备](../../credentials/credentials-local/README.zh.md)解析。Web、SDK 和 ACP profile 保留这一默认顺序。headless 的会话、settings 和工具行为不变;这种 profile 配置选择不构成文件系统访问边界。
### 选择 Session 标识
每次调用默认使用全新的 `session-<uuid>` 标识,`--json` 会在开头的 `session` 事件里报告它。传入 `--session-id <id>` 延续这段对话:runner 沿用该 id 对应的持久化 Session,而该 id 没有持久化 Session 时会在任务运行前失败,而不是悄悄开出一段空历史。沿用要求已组合 `sessionPersistence` 与 `sessionQuery` 服务,因此缺少任一服务的 profile 会显式失败,而不会返回一个历史随进程消失的 id。本进程中已存在持有该 id 的存活 Agent 时会被拒绝:它的原 owner 可能仍在驱动它,runner 无法取得独占的运行区间。标识是不透明的,因此会原样使用调用方给出的字符串,包括空白字符。工作目录通过已挂载的文件系统提供方解析(`fs.resolve('.')` 与 `fs.processPath()`);未挂载文件系统服务时使用进程 cwd,新 Session 会记录该目录。沿用会将已记录 cwd 与同一提供方解析出的目录比较,并拒绝子 agent 或 fork 会话、未记录工作目录的会话、运行在本 profile 不组合的 agent preset 下的会话,以及 preset 记录畸形的会话——该检查读取 Session 日志当前记录的 preset,因此在空白期切换过 preset 的会话同样会被拒绝。因此监督进程无法在另一套组合下悄悄驱动他人的会话;任一不匹配都会在任务运行前失败。
+10
View File
@@ -31,3 +31,13 @@
- id: hmr
disabled: true
# One-shot jobs use launch-time credentials instead of the interactive store.
- id: credentials
disabled: true
- id: authorization
disabled: true
- id: deepseek-account
disabled: true
@@ -18,11 +18,11 @@
en: db5aaf7f702e1f0c
zh: 409a78c14fb2b6e3
/deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys:
en: c2f2a5c06ef20d5b
zh: 49a7eb0b66b4ed53
en: b39c74c9a874f5d4
zh: db0dfcc2de9cab53
/deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider:
en: ec0ba62a4e7185b4
zh: 37d1e1e7a3817d12
en: 0786af5e4ed58c8a
zh: af94474af0749101
/deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers:
en: 9d533c65c82cd4a4
zh: 0a5da334e127c035
+4 -2
View File
@@ -43,11 +43,13 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo
API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords.
The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `<ROUTE>_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material.
The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `<ROUTE>_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the environment variables of the route's `nativeAuth`, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material.
For a profile with a named credential reference, the editor also shows **API key source** from the page's existing redacted `CredentialInfo` snapshot: saved credentials (`file`), launch environment (`env`), `$cwd/.env` (`project-env`), or `$DSH_HOME/.env` (`user-env`). Refreshing that snapshot updates an open editor without a separate editor probe. Unconfigured references, unknown source ids, and reference-free native authentication show no source label: a derived reference cannot identify the native provider's active credential. The label never receives a credential value or changes field writability.
### Editing a provider
The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the deepseek placeholder shows the public endpoint), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. Reasoning effort is deliberately not among the editable fields: it is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, and input types; unrelated model fields survive edits.
The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the placeholder shows the endpoint the profile resolves to, the public endpoint for deepseek, else the `defaultBaseURL` the configurable-provider directory reports for a pi-ai catalog route), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. Reasoning effort is deliberately not among the editable fields: it is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, and input types; unrelated model fields survive edits.
The DeepSeek card edits the `llm-deepseek` endpoint, credentials, and model catalog. It uses Messages, with the default endpoint placeholder `https://api.deepseek.com/anthropic`.
@@ -43,11 +43,13 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会
API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。
编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `<ROUTE>_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。
编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `<ROUTE>_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 环境变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。
profile 有具名凭据引用时,编辑器还会根据页面已有的脱敏 `CredentialInfo` 快照显示 **API 密钥来源**:已保存凭据(`file`)、启动环境(`env`)、`$cwd/.env`(`project-env`)或 `$DSH_HOME/.env`(`user-env`)。快照刷新会更新打开的编辑器,无需单独探测。未配置的引用、未知来源 id 和无引用的原生认证不显示来源标签:派生引用不能说明原生提供商当前采用的凭据。标签从不接收凭据值,也不改变字段的可写性。
### 编辑提供商
收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(deepseek 的占位符显示公共端点)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。推理等级刻意不在可编辑字段之列:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens` 和输入类型;无关的模型字段在编辑后仍会保留。
收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(占位符显示 profile 解析出的端点,deepseek 即公共端点;没有时显示可配置提供商目录为 pi-ai 内置路由报告的 `defaultBaseURL`)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。推理等级刻意不在可编辑字段之列:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens` 和输入类型;无关的模型字段在编辑后仍会保留。
`llm-deepseek` 的 DeepSeek 卡片编辑端点、凭据和模型目录。它使用 Messages,默认端点占位符为 `https://api.deepseek.com/anthropic`。
@@ -275,6 +275,28 @@
color: var(--dsw-alias-label-secondary);
}
.helpButton {
width: 16px;
height: 16px;
padding: 0;
border: 0.5px solid var(--dsw-alias-border-l3);
border-radius: 50%;
corner-shape: round;
background: transparent;
color: var(--dsw-alias-label-tertiary);
font: inherit;
font-size: 11px;
line-height: 15px;
text-align: center;
cursor: help;
}
.helpButton:hover,
.helpButton:focus-visible {
color: var(--dsw-alias-label-primary);
border-color: var(--dsw-alias-label-tertiary);
}
.linkButton {
box-sizing: border-box;
display: inline-flex;
@@ -25,7 +25,7 @@ import { useId, useState } from 'react'
import type { ReactNode } from 'react'
import { Button, IconPlusOutlineRegular, Modal, SegmentedControl } from '@deepseek-ai/dsh-client-ui-primitives'
import type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
import type { SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client'
import type { LlmNativeAuth, SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client'
// Type-only: pulls this package's SlotMap merge (the two Models child slots).
import type {} from './slot-contract.ts'
import { CustomProviderCard } from './CustomProviderCard.tsx'
@@ -92,6 +92,10 @@ interface EditorTarget extends ProviderIdentity {
credentialRef?: string
/** The adapter reports this route as one it does not ship (see {@link ProviderEditorProps.declared}). */
declared?: boolean
/** The route's catalog endpoint (see {@link ProviderEditorProps.defaultBaseURL}). */
defaultBaseURL?: string
/** The route's native authentication (see {@link ProviderEditorProps.nativeAuth}). */
nativeAuth?: LlmNativeAuth
}
/** A dormant directory row the add card can adopt, with its registered namespace. */
@@ -109,7 +113,7 @@ interface CatalogDraft {
/** Values that vary around the shared provider-editor rendering. */
interface ProviderEditorRenderProps extends Pick<
ProviderEditorProps,
'namespace' | 'schema' | 'operations' | 't' | 'readOnly' | 'onClose'
'namespace' | 'schema' | 'operations' | 't' | 'readOnly' | 'onClose' | 'credential'
> {
target: EditorTarget
}
@@ -122,6 +126,8 @@ function renderProviderEditor({ target, ...props }: ProviderEditorRenderProps):
displayName={target.displayName}
settingsPath={target.settingsPath}
{...target.declared === true ? { declared: true } : {}}
{...target.defaultBaseURL === undefined ? {} : { defaultBaseURL: target.defaultBaseURL }}
{...target.nativeAuth === undefined ? {} : { nativeAuth: target.nativeAuth }}
{...props}
/>
)
@@ -200,6 +206,8 @@ function targetOf(row: ProviderRow): EditorTarget {
...credentialRef === undefined ? {} : { credentialRef },
// Only declared routes may expose route-owned fields.
...row.entry.declared === true ? { declared: true } : {},
...row.entry.defaultBaseURL === undefined ? {} : { defaultBaseURL: row.entry.defaultBaseURL },
...row.entry.nativeAuth === undefined ? {} : { nativeAuth: row.entry.nativeAuth },
}
}
@@ -424,6 +432,7 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS
{renderProviderEditor({
target,
namespace,
...row.credential === undefined ? {} : { credential: row.credential },
schema,
operations,
t,
@@ -536,6 +545,7 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS
? renderProviderEditor({
target,
namespace,
...row.credential === undefined ? {} : { credential: row.credential },
schema,
operations,
t,
@@ -626,6 +636,8 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace; renderS
schema={schema}
settingsPath={draft.target.settingsPath}
operations={operations}
{...draft.target.defaultBaseURL === undefined ? {} : { defaultBaseURL: draft.target.defaultBaseURL }}
{...draft.target.nativeAuth === undefined ? {} : { nativeAuth: draft.target.nativeAuth }}
t={t}
readOnly={!state.writable}
onClose={(changed) => { closeEditor(changed, draft.target) }}
@@ -23,10 +23,9 @@
import { useEffect, useMemo, useState } from 'react'
import type { ReactNode } from 'react'
import type {
CredentialInfo, SettingsNamespaceView, SettingsPathOpView,
} from '@deepseek-ai/dsh-api-remotes/client'
import type { CredentialInfo, LlmNativeAuth, SettingsNamespaceView, SettingsPathOpView } from '@deepseek-ai/dsh-api-remotes/client'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
import {
DeepSeekModelsEditor, modelDrafts, validateDeepSeekModels,
} from './DeepSeekModelsEditor.tsx'
@@ -69,6 +68,12 @@ export interface ProviderEditorProps {
settingsPath: readonly string[]
/** The Host operations this card writes and interrogates through. */
operations: ModelsOperations
/** Endpoint the route uses when its profile sets no `baseURL`; absent when the adapter reports none. */
defaultBaseURL?: string
/** Authentication the route performs when its profile names no credential reference; absent when the adapter reports none. */
nativeAuth?: LlmNativeAuth
/** Redacted state of the profile's named credential reference, from the page snapshot. */
credential?: CredentialInfo
/** Section copy. */
t: (key: keyof typeof en) => string
/** Disable writes (read-only settings provider). */
@@ -167,7 +172,6 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
const { namespace, schema, settingsPath, operations, t } = props
const [draft, setDraft] = useState<Record<string, unknown>>(() => draftAt(schema, namespace, settingsPath))
const [keyDraft, setKeyDraft] = useState('')
const [keyState, setKeyState] = useState<CredentialInfo | undefined>(undefined)
const [busy, setBusy] = useState(false)
const [listBusy, setListBusy] = useState(false)
const { onBusyChange } = props
@@ -195,18 +199,6 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
[layout, namespace, schema],
)
useEffect(() => {
let stale = false
setKeyState(undefined)
// The key state is a placeholder hint, not a precondition for editing: a
// refused describe leaves the card without the "already configured" hint.
void operations.describeCredential(keyRef).then((described) => {
if (stale) return
setKeyState(described)
})
return () => { stale = true }
}, [operations, keyRef])
const stringAt = (source: unknown, key: string): string | undefined => {
const value = schema.getPath(source, [key])
return typeof value === 'string' && value.trim().length > 0 ? value : undefined
@@ -324,8 +316,6 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
return <p className={styles['error']}>{props.provider}: {props.t('settingsPathUnresolvable')}</p>
}
const keyLocked = keyState?.writable === false
/**
* The catalog beneath the user layer: what the composition entry pinned, or
* else the schema default that `resolve` would supply. The effective value
@@ -354,11 +344,37 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
const defaultContextWindow = schema.getPath(fallback, ['defaultContextWindow'])
const defaultMaxTokens = schema.getPath(fallback, ['maxTokens'])
const defaultInput = schema.getPath(fallback, ['defaultInput'])
const keyPlaceholder = keyLocked
? t('keyEnvLocked')
: keyState?.configured === true && props.credentialRequired !== true
? t('keyStored')
: family === 'pi-ai' ? t('keyPlaceholderNative') : t('keyPlaceholder')
// A named reference is the only credential the adapter reads for this
// route. Without one, a catalog route authenticates the way the directory
// reports, and a declared route sends no key at all.
const namedRef = stringAt(fallback, 'apiKeyEnv')
const nativeAuth = namedRef === undefined ? props.nativeAuth : undefined
// A derived reference cannot identify a native provider's active credential.
const source = namedRef === undefined || props.credential?.configured !== true
? undefined
: props.credential.source
const keySource = source === 'file' ? t('keySourceFile')
: source === 'env' ? t('keySourceEnv')
: source === 'project-env' ? t('keySourceProjectEnv')
: source === 'user-env' ? t('keySourceUserEnv')
: undefined
// Display method-neutral references without changing the adapter's lookup.
const visibleRefs = (namedRef === undefined ? nativeAuth?.env ?? [] : [namedRef])
.filter(ref => !ref.toLowerCase().includes('oauth'))
const keyHint = visibleRefs[0]
const keyHelp = visibleRefs.length === 0
? undefined
: t('keyHelp').replace('{env}', () => visibleRefs.join(' / '))
const authHelp = keyHelp === undefined ? null : (
<Tooltip label={keyHelp} side="right" delayMs={0} focusDelayMs={0} portal openOnClick>
<button type="button" className={styles['helpButton']} aria-label={t('authHelp')}>?</button>
</Tooltip>
)
// A provider with no native key authentication has no key for this field to store.
const keylessNativeAuth = nativeAuth?.env.length === 0 && nativeAuth.oauth
const keyPlaceholder = keyHint === undefined
? t('keyPlaceholder')
: t('keyPlaceholderFallback').replace('{hint}', () => keyHint)
/** What both family editors take: the rows, whose layer owns them, and the two writes. */
const catalogProps = {
models,
@@ -372,23 +388,29 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
}
return (
<>
<div className={styles['field']}>
<span className={styles['fieldLabel']}>{t('keyInput')}</span>
<input
className={styles['input']}
type="password"
autoComplete="new-password"
value={keyDraft}
placeholder={keyPlaceholder}
aria-label={t('keyInput')}
aria-invalid={shownKeyFailure !== undefined}
required={props.credentialRequired === true}
autoFocus={props.autoFocusCredential === true}
disabled={disabled || keyLocked}
onChange={(event) => { setKeyDraft(event.target.value) }}
/>
{shownKeyFailure === undefined ? null : <p className={styles['error']}>{t(shownKeyFailure)}</p>}
</div>
{keylessNativeAuth
? null
: <div className={styles['field']}>
<span className={styles['fieldLabel']}>
{t('keyInput')}
{authHelp}
</span>
<input
className={styles['input']}
type="password"
autoComplete="new-password"
value={keyDraft}
placeholder={keyPlaceholder}
aria-label={t('keyInput')}
aria-invalid={shownKeyFailure !== undefined}
required={props.credentialRequired === true}
autoFocus={props.autoFocusCredential === true}
disabled={disabled}
onChange={(event) => { setKeyDraft(event.target.value) }}
/>
{keySource === undefined ? null : <span className={styles['advancedHint']}>{keySource}</span>}
{shownKeyFailure === undefined ? null : <p className={styles['error']}>{t(shownKeyFailure)}</p>}
</div>}
{props.credentialOnly === true ? null : <details className={styles['customized']}>
<summary className={styles['customizedSummary']}>{t('customized')}</summary>
<div className={styles['customizedBody']}>
@@ -427,7 +449,10 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
value={stringAt(draft, 'baseURL') ?? ''}
placeholder={family === 'deepseek'
? t('deepSeekBaseUrl')
: stringAt(fallback, 'baseURL') ?? t('baseUrlDefault')}
: (() => {
const baseURL = stringAt(fallback, 'baseURL') ?? props.defaultBaseURL
return baseURL === undefined ? t('baseUrlDefault') : t('baseUrlPlaceholder').replace('{url}', () => baseURL)
})()}
aria-describedby={family === 'deepseek' ? `${props.provider}-endpoint-hint` : undefined}
aria-label={t('baseUrl')}
disabled={disabled}
@@ -38,13 +38,18 @@ export const en = {
retry: 'Retry',
keyInput: 'API key',
keyPlaceholder: 'Enter your API key',
keyPlaceholderNative: 'Enter an API key, or leave blank to use environment authentication',
keyStored: 'Configured — enter a new value to replace',
keyEnvLocked: 'Provided by the launch environment (read-only)',
keyPlaceholderFallback: 'Leave blank to keep existing authentication ({hint})',
keyHelp: 'Saved credentials are used first. Environment fallbacks shown here, in order: {env}. Sources are launch environment, $cwd/.env, then $DSH_HOME/.env.',
authHelp: 'Authentication details',
keySourceFile: 'API key source: saved credentials',
keySourceEnv: 'API key source: launch environment',
keySourceProjectEnv: 'API key source: $cwd/.env',
keySourceUserEnv: 'API key source: $DSH_HOME/.env',
customized: 'Customized settings',
baseUrl: 'Base URL',
baseUrlDefault: 'Provider default',
deepSeekBaseUrl: 'https://api.deepseek.com/anthropic',
baseUrlDefault: 'No default endpoint',
baseUrlPlaceholder: '{url}',
deepSeekBaseUrl: 'https://api.deepseek.com/anthropic (Default to use DEEPSEEK_BASE_URL)',
deepSeekEndpointHint: 'Use an API endpoint compatible with Anthropic Messages.',
models: 'Models',
modelsInherited: 'Using the adapter defaults',
@@ -159,13 +164,18 @@ export const zh: { [Key in keyof typeof en]: string } = {
retry: '重试',
keyInput: 'API 密钥',
keyPlaceholder: '输入 API 密钥',
keyPlaceholderNative: '输入 API 密钥,或留空使用环境认证',
keyStored: '已配置——输入新值可替换',
keyEnvLocked: '由启动环境提供(只读)',
keyPlaceholderFallback: '留空时保留现有认证({hint})',
keyHelp: '优先使用已保存的凭据。此处显示的环境后备按以下顺序排列:{env}。来源依次为启动环境、$cwd/.env、$DSH_HOME/.env。',
authHelp: '认证说明',
keySourceFile: 'API 密钥来源:已保存凭据',
keySourceEnv: 'API 密钥来源:启动环境',
keySourceProjectEnv: 'API 密钥来源:$cwd/.env',
keySourceUserEnv: 'API 密钥来源:$DSH_HOME/.env',
customized: '自定义设置',
baseUrl: 'API 地址',
baseUrlDefault: '提供商默认',
deepSeekBaseUrl: 'https://api.deepseek.com/anthropic',
baseUrlDefault: '没有默认地址',
baseUrlPlaceholder: '{url}',
deepSeekBaseUrl: 'https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)',
deepSeekEndpointHint: '请填写兼容 Anthropic Messages 协议的 API 地址。',
models: '模型目录',
modelsInherited: '正在使用适配器默认模型',
@@ -7,7 +7,7 @@
import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type {
CredentialInfo, LlmDiscoveredModel, LlmModelDiscoveryRequest,
LlmDiscoveredModel, LlmModelDiscoveryRequest,
SettingsNamespaceView, SettingsPathOpView,
} from '@deepseek-ai/dsh-api-remotes/client'
@@ -32,12 +32,6 @@ export type ModelDiscoveryOutcome =
/** The Host operations the Models page and its cards invoke. */
export interface ModelsOperations {
/**
* Read one credential reference's state.
* @param ref - credential reference name.
* @returns the state, or undefined when the reference is unknown or the read was refused.
*/
describeCredential(ref: string): Promise<CredentialInfo | undefined>
/**
* Store one credential literal under its reference.
* @param ref - credential reference name.
@@ -81,10 +75,6 @@ export interface ModelsOperations {
*/
export function createModelsOperations(ctx: ClientContext): ModelsOperations {
return {
describeCredential: async (ref) => {
const response = await ctx.remote.credentials.describe([ref])
return response.ok ? response.value[ref] : undefined
},
storeCredential: async (ref, value) => {
const response = await ctx.remote.credentials.set(ref, value)
return response.ok ? undefined : response.error.message
@@ -9,7 +9,7 @@
import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type {
CredentialInfo, LlmConfigurableProvider, LlmProviderInfo, SettingsNamespaceView,
CredentialInfo, LlmConfigurableProvider, LlmNativeAuth, LlmProviderInfo, SettingsNamespaceView,
} from '@deepseek-ai/dsh-api-remotes/client'
import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
@@ -30,6 +30,8 @@ export interface ProviderDirectoryEntry {
readonly settingsPath: readonly string[]
readonly active: boolean
readonly declared?: boolean
readonly defaultBaseURL?: string
readonly nativeAuth?: LlmNativeAuth
readonly error?: string
}
@@ -52,6 +54,8 @@ export function joinProviderDirectory(
settingsPath: [...entry.settingsPath],
active: active.has(entry.provider),
...entry.declared === undefined ? {} : { declared: entry.declared },
...entry.defaultBaseURL === undefined ? {} : { defaultBaseURL: entry.defaultBaseURL },
...entry.nativeAuth === undefined ? {} : { nativeAuth: entry.nativeAuth },
...entry.error === undefined ? {} : { error: entry.error },
}))
for (const provider of registered) {
@@ -13,7 +13,8 @@ import {
ModelsSection, needsSetup, providerCopy, providerTargetLabel, removeProviderProfile,
} from '../src/client/ModelsSection.tsx'
import type { ModelsSectionInjected, ModelsSectionProps } from '../src/client/ModelsSection.tsx'
import { pathOps } from '../src/client/ProviderEditor.tsx'
import { ProviderEditor, pathOps } from '../src/client/ProviderEditor.tsx'
import type { ProviderEditorProps } from '../src/client/ProviderEditor.tsx'
import {
DeepSeekModelsEditor, formatCapacity, modelDrafts, parseCapacity, validateDeepSeekModels,
} from '../src/client/DeepSeekModelsEditor.tsx'
@@ -193,8 +194,15 @@ function scriptedFace(overrides: {
]))),
listConfigurableProviders: vi.fn(() => Promise.resolve(remoteOk([
{ provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true },
{ provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: true },
{ provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'], active: false },
{
provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: true,
defaultBaseURL: 'https://api.openai.com/v1', nativeAuth: { env: ['OPENAI_API_KEY'], oauth: false },
},
{
provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'], active: false,
defaultBaseURL: 'https://api.anthropic.com',
nativeAuth: { env: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true },
},
{ provider: 'zombie', displayName: 'zombie', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'zombie'], active: false },
{ provider: 'broken', displayName: 'broken', settingsNs: 'llm-pi-ai', settingsPath: ['nope', 'x'], active: false },
{ provider: 'plain', displayName: 'plain', settingsNs: 'llm-plain', settingsPath: ['profiles', 'plain'], active: false },
@@ -256,6 +264,32 @@ function operationsWith(face: object): ModelsOperations {
return bound
}
/** The pi-ai namespace with one more route profile stored in the user layer. */
function piAiNamespaceWith(provider: string, profile: { [key: string]: JsonValue }): SettingsNamespaceView {
const namespace = wireNamespaces().find(view => view.ns === 'llm-pi-ai')!
const providers = { ...(namespace.value as { providers: object }).providers, [provider]: profile }
return { ...namespace, value: { providers }, user: { providers } }
}
/** Render one pi-ai route's editor with the directory and credential facts the page already holds. */
function renderPiAiEditor(
provider: string,
namespace: SettingsNamespaceView,
facts: Pick<ProviderEditorProps, 'defaultBaseURL' | 'nativeAuth' | 'credential'> = {},
): void {
render(<ProviderEditor provider={provider} displayName={provider}
namespace={namespace} settingsPath={['providers', provider]} schema={settingsSchema}
operations={operationsWith(scriptedFace().face)} t={t} readOnly={false} onClose={vi.fn()} {...facts} />)
}
/** Hover the key label's help button and read its tooltip; null when the label has no button. */
function authHelpText(): string | null {
const button = screen.queryByRole('button', { name: en.authHelp })
if (button === null) return null
fireEvent.mouseEnter(button)
return screen.getByRole('tooltip').textContent
}
/** One recorded child-slot dispatch: seat name, owner share, kind options. */
type RenderSlotCall = [name: string, owner: Record<string, unknown>, opts?: { entryKey?: string }]
@@ -866,7 +900,7 @@ describe('ModelsSection', () => {
const baseURL = screen.getByLabelText<HTMLInputElement>(en.baseUrl)
// The deepseek placeholder is pinned to the public endpoint, not the
// effective value (which may reflect a launch-environment override).
expect(baseURL.placeholder).toBe('https://api.deepseek.com/anthropic')
expect(baseURL.placeholder).toBe('https://api.deepseek.com/anthropic (Default to use DEEPSEEK_BASE_URL)')
fireEvent.change(baseURL, { target: { value: 'https://next2' } })
fireEvent.click(screen.getByText(en.apply))
await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) })
@@ -938,7 +972,7 @@ describe('ModelsSection', () => {
/>)
fireEvent.click(screen.getByText(en.customized))
expect(screen.getByLabelText<HTMLInputElement>(en.baseUrl).placeholder)
.toBe('https://api.deepseek.com/anthropic')
.toBe('https://api.deepseek.com/anthropic (Default to use DEEPSEEK_BASE_URL)')
expect(screen.queryByLabelText(en.customApi)).toBeNull()
expect(screen.getByText(en.deepSeekEndpointHint)).toBeTruthy()
fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'sk-messages-test' } })
@@ -1350,7 +1384,7 @@ describe('ModelsSection', () => {
/>)
fireEvent.click(screen.getByText(en.customized))
const baseURL = screen.getByLabelText<HTMLInputElement>(en.baseUrl)
expect(baseURL.placeholder).toBe('https://api.deepseek.com/anthropic')
expect(baseURL.placeholder).toBe('https://api.deepseek.com/anthropic (Default to use DEEPSEEK_BASE_URL)')
fireEvent.change(baseURL, { target: { value: 'https://x' } })
expect(baseURL.value).toBe('https://x')
fireEvent.change(baseURL, { target: { value: '' } })
@@ -1379,14 +1413,15 @@ describe('ModelsSection', () => {
it('edits a pi-ai profile with the curated fields only', async () => {
const { mutate } = await mountSection()
fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) }))
// The configured credential shows as the stored placeholder.
// The field names the profile's reference; a stored value stays hidden.
const editorKey = await screen.findByLabelText<HTMLInputElement>(en.keyInput)
await waitFor(() => { expect(editorKey.placeholder).toBe(en.keyStored) })
expect(editorKey.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY'))
// pi-ai carries Base URL too: the stored override shows as the value and
// the effective profile endpoint as its placeholder source.
// the effective profile endpoint, ahead of the catalog's, as its placeholder.
fireEvent.click(screen.getByText(en.customized))
const url = screen.getByLabelText<HTMLInputElement>(en.baseUrl)
expect(url.value).toBe('https://proxy')
expect(url.placeholder).toBe('https://proxy')
fireEvent.change(url, { target: { value: 'https://proxy/v2' } })
fireEvent.click(screen.getByText(en.apply))
await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) })
@@ -1405,12 +1440,12 @@ describe('ModelsSection', () => {
const pick = await screen.findByLabelText<HTMLSelectElement>(en.provider)
expect([...pick.options].map(option => option.value)).toEqual(['anthropic', 'broken', 'plain'])
expect(pick.value).toBe('anthropic')
// A dormant profile has no endpoint anywhere: the pi-ai placeholder
// falls back to the provider-default wording.
// A dormant route shows its catalog endpoint and the first variable its
// provider reads; a typed key still stores under the derived reference.
fireEvent.click(screen.getByText(en.customized))
expect(screen.getByLabelText<HTMLInputElement>(en.baseUrl).placeholder).toBe(en.baseUrlDefault)
expect(screen.getByLabelText<HTMLInputElement>(en.baseUrl).placeholder).toBe('https://api.anthropic.com')
const addKey = screen.getByLabelText<HTMLInputElement>(en.keyInput)
expect(addKey.placeholder).toBe(en.keyPlaceholderNative)
expect(addKey.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'ANTHROPIC_AUTH_TOKEN'))
fireEvent.change(addKey, { target: { value: 'sk-ant' } })
fireEvent.click(screen.getByText(en.apply))
await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) })
@@ -1520,7 +1555,7 @@ describe('ModelsSection', () => {
renderSlot={() => null}
/>)
const key = await screen.findByLabelText<HTMLInputElement>(en.keyInput)
expect(key.placeholder).toBe(en.keyPlaceholder)
expect(key.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'DEEPSEEK_API_KEY'))
})
it('tells the user to reopen when another writer moved the namespace first', async () => {
@@ -1548,36 +1583,25 @@ describe('ModelsSection', () => {
expect(screen.getByText(en.apply)).toBeTruthy()
})
it('surfaces a shadowed credential write on the card', async () => {
it('surfaces a refused credential write on the card', async () => {
await mountFirstRun({
set: vi.fn(() => Promise.resolve(remoteFail('credentials: DEEPSEEK_API_KEY is shadowed by the read-only environment'))),
set: vi.fn(() => Promise.resolve(remoteFail(
'credentials-local: invalid document at /home/user/.dsh/.credentials.yaml: BAD_INDENT at line 3, column 1',
))),
})
const key = screen.getByLabelText<HTMLInputElement>(en.keyInput)
fireEvent.change(key, { target: { value: 'sk-live' } })
fireEvent.click(screen.getByText(en.apply))
await screen.findByText(/shadowed by the read-only environment/)
await screen.findByText(/invalid document at \/home\/user\/\.dsh\/\.credentials\.yaml/)
expect(screen.queryByRole('status')).toBeNull()
})
it('locks the key input when the launch environment provides the credential', async () => {
const { face } = await mountSection()
face.credentials.describe.mockImplementation((refs: string[]) => Promise.resolve(remoteOk(
Object.fromEntries(refs.map(ref => [ref, {
configured: ref === 'OPENAI_API_KEY', source: 'env', writable: false,
}])),
)))
fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) }))
const editorKey = await screen.findByLabelText<HTMLInputElement>(en.keyInput)
await waitFor(() => { expect(editorKey.placeholder).toBe(en.keyEnvLocked) })
expect(editorKey.disabled).toBe(true)
})
it('keeps a failed credential describe silent and the input usable', async () => {
const { face, set } = await mountSection()
face.credentials.describe.mockImplementation(() => Promise.resolve(remoteFail('down', 'gateway/internal')))
fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) }))
const editorKey = await screen.findByLabelText<HTMLInputElement>(en.keyInput)
expect(editorKey.placeholder).toBe(en.keyPlaceholderNative)
expect(editorKey.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY'))
fireEvent.change(editorKey, { target: { value: 'sk-live' } })
fireEvent.click(screen.getByText(en.apply))
await waitFor(() => { expect(set).toHaveBeenCalledTimes(1) })
@@ -2126,6 +2150,123 @@ describe('apiKeyFailure', () => {
})
})
it.each([
['file', 'keySourceFile'], ['env', 'keySourceEnv'],
['project-env', 'keySourceProjectEnv'], ['user-env', 'keySourceUserEnv'],
] as const)('shows the named credential source %s without reading its value', (source, key) => {
renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), {
credential: { configured: true, source, writable: true },
})
expect(screen.getByText(en[key])).toBeTruthy()
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).value).toBe('')
})
it.each([
['unconfigured', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: false, source: 'env', writable: true }],
['unknown source', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: true, source: 'oauth', writable: true }],
['native authentication', {}, { configured: true, source: 'file', writable: true }],
] as const)('does not guess a source for %s', (_label, profile, credential) => {
renderPiAiEditor('openai', piAiNamespaceWith('openai', profile), { credential })
expect(screen.queryByText(/^API key source:/)).toBeNull()
expect(document.body.textContent).not.toMatch(/oauth/i)
})
it('refreshes the open editor source from the page snapshot without an editor probe', async () => {
const { face, controller } = await mountSection()
const reads = face.credentials.describe.mock.calls.length
fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) }))
expect(screen.getByText(en.keySourceFile)).toBeTruthy()
expect(face.credentials.describe).toHaveBeenCalledTimes(reads)
face.credentials.describe.mockImplementation(refs => Promise.resolve(remoteOk(
Object.fromEntries(refs.map(ref => [ref, { configured: true, source: 'env', writable: true }])),
)))
await act(() => controller.load())
expect(screen.getByText(en.keySourceEnv)).toBeTruthy()
expect(screen.queryByText(en.keySourceFile)).toBeNull()
expect(face.credentials.describe).toHaveBeenCalledTimes(reads + 1)
})
it('keeps an OAuth-only provider on its native authentication path', () => {
renderPiAiEditor('openai-codex', wireNamespaces().find(view => view.ns === 'llm-pi-ai')!, {
nativeAuth: { env: [], oauth: true },
})
expect(screen.queryByLabelText(en.keyInput)).toBeNull()
expect(authHelpText()).toBeNull()
expect(document.body.textContent).not.toMatch(/oauth/i)
})
it.each([
['anthropic', ['ANTHROPIC_API_KEY'], en.keyHelp.replace('{env}', 'ANTHROPIC_API_KEY')],
['openai', ['OPENAI_API_KEY'], en.keyHelp.replace('{env}', 'OPENAI_API_KEY')],
] as const)('opens authentication help for %s on click and dismisses it with Escape', (provider, env, text) => {
renderPiAiEditor(provider, piAiNamespaceWith(provider, {}), {
nativeAuth: { env: [...env], oauth: true },
})
const help = screen.getByLabelText(en.authHelp)
fireEvent.click(help)
const tooltip = screen.getByRole('tooltip')
expect(tooltip.textContent).toBe(text)
expect(help.getAttribute('aria-describedby')).toBe(tooltip.id)
fireEvent.keyDown(document, { key: 'Escape' })
expect(screen.queryByRole('tooltip')).toBeNull()
})
it.each([
['an OAuth-only provider', 'openai-codex', 'CODEX_TOKEN', { env: [], oauth: true }],
[
'a provider with catalog variables and an OAuth sign-in', 'anthropic', 'TEAM_ANTHROPIC_KEY',
{ env: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true },
],
] as const)('names the profile reference of %s instead of its native authentication', (_label, provider, ref, nativeAuth) => {
renderPiAiEditor(provider, piAiNamespaceWith(provider, { apiKeyEnv: ref }), { nativeAuth })
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder)
.toBe(en.keyPlaceholderFallback.replace('{hint}', ref))
expect(authHelpText()).toBe(en.keyHelp.replace('{env}', ref))
expect(document.body.textContent).not.toMatch(/oauth/i)
})
it.each([
[
'with an OAuth sign-in', 'anthropic',
{ env: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true },
'ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY',
],
['without an OAuth sign-in', 'minimax-cn', { env: ['MINIMAX_CN_API_KEY'], oauth: false }, 'MINIMAX_CN_API_KEY'],
] as const)('lists method-neutral fallbacks for a catalog route %s', (_label, provider, nativeAuth, refs) => {
renderPiAiEditor(provider, piAiNamespaceWith(provider, {}), { nativeAuth })
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder)
.toBe(en.keyPlaceholderFallback.replace('{hint}', nativeAuth.env[0]))
expect(authHelpText()).toBe(en.keyHelp.replace('{env}', refs))
expect(document.body.textContent).not.toMatch(/oauth/i)
})
it('shows the next method-neutral fallback without modifying native authentication metadata', () => {
const nativeAuth = { env: ['ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true }
renderPiAiEditor('anthropic', piAiNamespaceWith('anthropic', {}), { nativeAuth })
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder)
.toBe(en.keyPlaceholderFallback.replace('{hint}', 'ANTHROPIC_API_KEY'))
expect(authHelpText()).toBe(en.keyHelp.replace('{env}', 'ANTHROPIC_API_KEY'))
expect(nativeAuth.env).toEqual(['ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'])
expect(document.body.textContent).not.toMatch(/oauth/i)
})
it('keeps a method-specific profile reference usable without displaying its name', () => {
renderPiAiEditor('anthropic', piAiNamespaceWith('anthropic', { apiKeyEnv: 'TEAM_OAUTH_TOKEN' }), {
nativeAuth: { env: ['ANTHROPIC_API_KEY'], oauth: true },
})
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder).toBe(en.keyPlaceholder)
expect(authHelpText()).toBeNull()
expect(document.body.textContent).not.toMatch(/oauth/i)
})
it('offers a plain key field to a route the adapter reports no authentication or endpoint for', () => {
renderPiAiEditor('zombie', wireNamespaces().find(view => view.ns === 'llm-pi-ai')!)
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder).toBe(en.keyPlaceholder)
expect(authHelpText()).toBeNull()
fireEvent.click(screen.getByText(en.customized))
expect(screen.getByLabelText<HTMLInputElement>(en.baseUrl).placeholder).toBe(en.baseUrlDefault)
})
it('renders the localized account row as signed in without an edit action', async () => {
const scripted = scriptedFace({})
const { controller } = await mountFace(scripted)
@@ -11,7 +11,6 @@ afterEach(cleanup)
function operations(discoverModels: ModelsOperations['discoverModels']): ModelsOperations {
return {
discoverModels,
describeCredential: vi.fn(),
storeCredential: vi.fn(),
removeCredential: vi.fn(),
writeSettings: vi.fn(),
@@ -4,7 +4,28 @@ import type { RpcResponse } from '@deepseek-ai/dsh-api-remotes/client'
import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime'
import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts'
import { settingsSchema } from './settings-schema.client.ts'
import { joinProviderDirectory, ModelsSettingsStore, providerUsable } from '../src/client/store.ts'
import { deriveKeyRef, joinProviderDirectory, ModelsSettingsStore, providerUsable } from '../src/client/store.ts'
it.each([
['anthropic', 'ANTHROPIC_API_KEY'],
['moonshotai', 'MOONSHOTAI_API_KEY'],
['moonshotai-cn', 'MOONSHOTAI_CN_API_KEY'],
['google-vertex', 'GOOGLE_VERTEX_API_KEY'],
['constructor', 'CONSTRUCTOR_API_KEY'],
])('stores a typed key for route %s under a reference derived from the route id', (provider, ref) => {
expect(deriveKeyRef(provider)).toBe(ref)
})
it('carries the endpoint and native authentication the adapter reports onto the row', () => {
const nativeAuth = { env: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY'], oauth: true }
expect(joinProviderDirectory([], [{
provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'],
defaultBaseURL: 'https://api.anthropic.com', nativeAuth,
}])).toEqual([{
provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'],
active: false, defaultBaseURL: 'https://api.anthropic.com', nativeAuth,
}])
})
it.each([false, true])('retains configuration diagnostics when the route is active: %s', (active) => {
expect(joinProviderDirectory(active ? [{ id: 'openai', name: 'openai' }] : [], [{
+4 -4
View File
@@ -9,14 +9,14 @@
en: 03fef8e24bd97152
zh: 111354cb879dc264
/credentials-credentials-and-authorization/summary:
en: bf9bc998e950affb
zh: 9a73ac3012dff7b9
en: 93c0b84eb29515a3
zh: d5ade78598c911e7
/credentials-credentials-and-authorization/table-of-contents:
en: 1eb35b015a6c423f
zh: a8a3dceee2c9e943
/credentials-credentials-and-authorization/packages:
en: 2f3632b522c022fc
zh: 7dab6123d68b2a38
en: 11fa50bc79814e6f
zh: 72ff641d914dc4a0
/credentials-credentials-and-authorization/related-documentation:
en: b1d12d492789f933
zh: a945956e071d2f04
+2 -2
View File
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
The `credentials/` group lets configuration name secrets instead of embedding their values. Use `credentials/` to store, look up, and remove credentials, `credentials-local/` for private on-machine storage with per-run environment overrides, and `authorization/` when obtaining a credential requires asking a human. Rotated stored values apply to the next model request, while `DEEPSEEK_API_KEY=… dsh` takes precedence for that run. Configuration files contain only credential names; local secret values remain readable only by the same OS user.
The `credentials/` group lets configuration name secrets instead of embedding their values. Use `credentials/` to store, look up, and remove credentials, `credentials-local/` for private on-machine storage with environment fallbacks, and `authorization/` when obtaining a credential requires asking a human. Rotated stored values apply to the next model request, and a stored value takes precedence over `DEEPSEEK_API_KEY=… dsh`. Configuration files contain only credential names; local secret values remain readable only by the same OS user.
## Table of Contents
@@ -27,7 +27,7 @@ Three packages provide the credential feature: one stores, looks up, and removes
| Package | Role | ctx key |
|---|---|---|
| [`credentials/`](credentials/README.md) | Store, look up, and remove secrets at runtime while configuration only names them | `ctx.credentials` |
| [`credentials-local/`](credentials-local/README.md) | The default on-machine store: a private YAML file, environment overrides win | registers `ctx.credentials` |
| [`credentials-local/`](credentials-local/README.md) | The default on-machine store: a private YAML file that outranks environment fallbacks | registers `ctx.credentials` |
| [`authorization/`](authorization/README.md) | Plugin-owned flows that obtain a credential by asking a human | `ctx.authorization` |
-----
+2 -2
View File
@@ -9,7 +9,7 @@ kind: "package-group"
## 概述
`credentials/` 组让配置引用机密的名字,而不嵌入机密值。使用 `credentials/` 存储、查询和移除凭据;使用 `credentials-local/` 将凭据私密地存储在本机,并支持按次运行的环境覆盖;当需要向人询问以获取凭据时,使用 `authorization/`。轮换后的存储值会作用于下一次模型请求,而 `DEEPSEEK_API_KEY=… dsh` 在该次运行中优先。配置文件只包含凭据名称;本地机密值只有同一 OS 用户可读。
`credentials/` 组让配置引用机密的名字,而不嵌入机密值。使用 `credentials/` 存储、查询和移除凭据;使用 `credentials-local/` 将凭据私密地存储在本机,并以环境作为后备来源;当需要向人询问以获取凭据时,使用 `authorization/`。轮换后的存储值会作用于下一次模型请求,且存储值优先于 `DEEPSEEK_API_KEY=… dsh`。配置文件只包含凭据名称;本地机密值只有同一 OS 用户可读。
## 目录
@@ -27,7 +27,7 @@ kind: "package-group"
| 包 | 角色 | ctx 键 |
|---|---|---|
| [`credentials/`](credentials/README.zh.md) | 在运行时存储、查询与移除机密,而配置只写名字 | `ctx.credentials` |
| [`credentials-local/`](credentials-local/README.zh.md) | 默认本机存储:一个私有 YAML 文件,环境覆盖优先 | 注册 `ctx.credentials` |
| [`credentials-local/`](credentials-local/README.zh.md) | 默认本机存储:一个私有 YAML 文件,优先于环境后备来源 | 注册 `ctx.credentials` |
| [`authorization/`](authorization/README.zh.md) | 由插件拥有、通过询问人来取得凭据的 flow | `ctx.authorization` |
-----
@@ -9,8 +9,8 @@
en: 3b9ce5321aa1976d
zh: 3d78dd8b203b68e6
/deepseek-ai-dsh-credentials-local/summary:
en: 84d1d9bab56bb45a
zh: 6a1a0d919b11915a
en: 40cd6507608b0d52
zh: bc7487364bf6478c
/deepseek-ai-dsh-credentials-local/table-of-contents:
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
@@ -27,8 +27,8 @@
en: 5e3d45470142b9dd
zh: 1f8358f987769d3a
/deepseek-ai-dsh-credentials-local/use-this-package/where-keys-come-from:
en: a746b6550b664db6
zh: 0f6346dabe41d274
en: a55fac148b62e007
zh: fdb3d19ccae676ee
/deepseek-ai-dsh-credentials-local/use-this-package/the-credential-file:
en: 9d6580d151ca0fd2
zh: ffc3a407e0f7ff7d
@@ -36,20 +36,20 @@
en: 76bcb1dab6a112e2
zh: 42669953eef0fc53
/deepseek-ai-dsh-credentials-local/use-this-package/what-can-go-wrong:
en: 31d1ac1df959a6ad
zh: 7c8d335690dc73aa
en: 8b904a0aaf767099
zh: b313fa7b6b61fb26
/deepseek-ai-dsh-credentials-local/understand-the-implementation:
en: 538553a9a48e2f93
zh: d981c42878e80762
/deepseek-ai-dsh-credentials-local/understand-the-implementation/design-philosophy:
en: 697bda9e5ee4dd28
zh: d7e23a8e8cd398e2
en: 2f76cb96086897ce
zh: 6b75376681446446
/deepseek-ai-dsh-credentials-local/understand-the-implementation/source-map:
en: a83715807279a902
zh: fef1884e2a16bd46
/deepseek-ai-dsh-credentials-local/understand-the-implementation/resolution-and-write-paths:
en: 8841486f9eda2f6b
zh: 015a2bbfe8a6fdbf
en: 9627df7e2a0b2768
zh: 79c0d4306df1133a
/deepseek-ai-dsh-credentials-local/understand-the-implementation/reload-lifecycle:
en: c7e531430cad142f
zh: dec27aab2645343f
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
`dsh-credentials-local` keeps API keys and other secrets in a private file under your harness home. You can save credentials through the configuration UI or edit the file directly; changes reload automatically and saved values survive restarts. Credential lookup follows a fixed precedence: the launch environment wins, followed by the stored file, the project's `.env`, and the harness-home `.env`; a newly saved value immediately overrides older `.env` values. Only your OS user can read the file, but agent tool processes run as that same user, so this store cannot isolate secrets from the agent.
`dsh-credentials-local` keeps API keys and other secrets in a private file under your harness home. You can save credentials through the configuration UI or edit the file directly; changes reload automatically and saved values survive restarts. Credential lookup follows a fixed precedence: the stored file wins, followed by the launch environment, the project's `.env`, and the harness-home `.env`; a newly saved value immediately overrides older environment values. Only your OS user can read the file, but agent tool processes run as that same user, so this store cannot isolate secrets from the agent.
## Table of Contents
@@ -72,12 +72,12 @@ Keys are resolved in one fixed order — the first place that has a value wins:
| Place | Writable? | Wins over |
|---|---|---|
| The environment you launched in (`DEEPSEEK_API_KEY=… dsh`) | no | everything |
| The stored file | yes (`set`/`unset`) | both `.env` files |
| The stored file | yes (`set`/`unset`) | everything |
| The environment you launched in (`DEEPSEEK_API_KEY=… dsh`) | not here | both `.env` files |
| Your project's `.env` (`<invocation cwd>/.env`) | not here | your home `.env` |
| Your home `.env` (`$DSH_HOME/.env`) | not here | nothing |
The launching environment wins because a per-run override — `DEEPSEEK_API_KEY=… dsh`, a CI secret, a container `-e` — is this run's explicit intent; it cannot be edited from inside the product, so it is reported read-only and writes to it are refused. Everything else loses to the stored file, which is why a key you save takes effect immediately even when an older key sits in a `.env`; those two `.env` layers resolve when nothing is stored. The environment layer is the launcher's snapshot taken at launch ([environment snapshot](../../util/launch-environment/README.md)), so a variable exported after startup is not seen.
The stored file wins because a credential explicitly saved through the product must take effect consistently for every provider ([decision](../../../.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.md)). The launching environment — `DEEPSEEK_API_KEY=… dsh`, a CI secret, or a container `-e` — is the fallback when no stored value exists; a project `.env` then outranks the harness-home `.env`. A save always writes the winning layer, so `describe` reports `writable: true` for every reference, and its `source` names the place that currently supplies the value. The environment layer is the launcher's snapshot taken at launch ([environment snapshot](../../util/launch-environment/README.md)), so a variable exported after startup is not seen.
### The credential file
@@ -116,7 +116,7 @@ Only your OS user can read the file: the product creates it with owner-only perm
### What can go wrong
- **A key the launching environment supplies is read-only** — `DEEPSEEK_API_KEY=… dsh` wins for this run; saving or removing it is refused. Clear the variable in the launching shell first.
- **A key the launching environment supplies is a fallback** — saving a value stores a higher-priority credential; removing it reveals the launch environment again. To make an exported key apply, delete its entry under `refs` in the file.
- **An empty value cannot be saved** — storing an empty string is refused; remove the key instead.
- **The store refuses to load a file it cannot trust** — a file any other user can read, malformed YAML, or an unreachable path fails at startup; on a live reload the last good content keeps serving with a warning.
- **Changes made at the same time are both kept** — if you edit the file while the product writes, your change is folded in rather than overwritten.
@@ -133,7 +133,7 @@ This section explains the design decisions behind the provider and points at the
### Design philosophy
- **One honest precedence.** The inherited environment wins because it is this run's explicit intent and cannot be edited from inside; everything below it loses to the managed store, so a stored key is never displaced by a stale `.env`.
- **One honest precedence.** The managed store wins for every provider; launch environment, project `.env`, and harness-home `.env` are deterministic fallbacks in that order.
- **The document holds only credentials.** A versioned document with `refs` and `records` sections rather than a dotenv file: a store the harness owns and never materializes into the environment cannot also serve as the user's environment layer, which would shadow non-secret entries behind its precedence.
- **Writes patch, reloads replace.** Line edits preserve comments and untouched entries under the cross-process writer lock; reloads swap the parsed snapshot wholesale so a deleted entry never lingers in memory.
- **Fail loud where trust is at stake.** Boot and reload reject a document that is unreadable, invalid, or readable beyond its owner; a live reload that fails keeps the last good snapshot and warns rather than taking the process down.
@@ -146,7 +146,7 @@ This section explains the design decisions behind the provider and points at the
### Resolution and write paths
`resolve` and `describe` read the inherited environment snapshot, the parsed document snapshot, and the `.env` fallbacks in precedence order. `set`/`unset` queue onto one exclusive operation chain: entry checks reject early (disposed, empty value, environment-shadowed), and the queue re-judges them at run time before a read-modify-write under the writer lock commits and fires `credentials/reference-updated` exactly once.
`resolve` and `describe` read the parsed document snapshot, the inherited environment snapshot, and the `.env` fallbacks in precedence order. `set`/`unset` queue onto one exclusive operation chain: entry checks reject early (disposed or empty value), and the queue performs a read-modify-write under the writer lock before firing `credentials/reference-updated` exactly once.
`modifyRecord` runs on the same chain and lock: it re-reads the document, passes the record as it stands to the mutation, admits the result — a non-empty API key, a grant payload that survives a JSON round trip — renders the record wholesale, and commits, firing `credentials/record-updated` once. A composition the product CLI did not boot has only the inherited environment as its layer.
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
`dsh-credentials-local` 把 API 密钥和其他机密保存在 harness home 下的私有文件中。你可以通过配置界面保存凭据,也可以直接编辑文件;变更会自动重载,保存的值也会跨重启保留。凭据查找采用固定优先级:启动环境优先,其次是存储文件、项目 `.env` 和 harness home 的 `.env`;新保存的值会立即覆盖 `.env` 中的旧值。只有你的 OS 用户能读取该文件,但 agent(智能体)的工具进程以同一用户身份运行,因此该存储无法向 agent 隔离机密。
`dsh-credentials-local` 把 API 密钥和其他机密保存在 harness home 下的私有文件中。你可以通过配置界面保存凭据,也可以直接编辑文件;变更会自动重载,保存的值也会跨重启保留。凭据查找采用固定优先级:存储文件优先,其次是启动环境、项目 `.env` 和 harness home 的 `.env`;新保存的值会立即覆盖环境中的旧值。只有你的 OS 用户能读取该文件,但 agent(智能体)的工具进程以同一用户身份运行,因此该存储无法向 agent 隔离机密。
## 目录
@@ -72,12 +72,12 @@ await ctx.credentials.unset(ref) // remove
| 位置 | 可写? | 优先于 |
|---|---|---|
| 你启动时的环境(`DEEPSEEK_API_KEY=… dsh`) | 否 | 一切 |
| 存储文件 | 是(`set`/`unset`) | 两个 `.env` 文件 |
| 存储文件 | 是(`set`/`unset`) | 一切 |
| 你启动时的环境(`DEEPSEEK_API_KEY=… dsh`) | 不在此处 | 两个 `.env` 文件 |
| 项目的 `.env`(`<invocation cwd>/.env`) | 不在此处 | 主目录 `.env` |
| 主目录的 `.env`(`$DSH_HOME/.env`) | 不在此处 | 无 |
启动环境优先,因为按次覆盖——`DEEPSEEK_API_KEY=… dsh`、CI 机密、容器 `-e`——代表本次运行的明确意图;它无法从产品内部修改,因此被报告为只读,写入会被拒绝。其他一切来源都输给存储文件,这正是你保存的密钥会立即生效的原因,即使某个 `.env` 里还留着更旧的密钥;没有存储任何东西时,那两个 `.env` 层会参与解析。环境层是启动时拍摄的启动器[环境快照](../../util/launch-environment/README.zh.md),因此启动之后才导出的变量不会被看到。
存储文件优先,因为通过产品明确保存的凭据必须对每个提供方一致生效([决策](../../../.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.zh.md))。启动环境——`DEEPSEEK_API_KEY=… dsh`、CI 机密、容器 `-e`——在没有存储值时作为后备;随后是项目 `.env`,最后是 harness home 的 `.env`。保存总是写入胜出的那一层,因此 `describe` 对每个引用都报告 `writable: true`,其 `source` 指明当前提供该值的位置。环境层是启动时拍摄的启动器[环境快照](../../util/launch-environment/README.zh.md),因此启动之后才导出的变量不会被看到。
### 凭据文件本身
@@ -116,7 +116,7 @@ records:
### 可能出错的地方
- **启动环境提供的密钥是只读的**——`DEEPSEEK_API_KEY=… dsh` 在本轮运行中优先,保存或移除它都会被拒绝。请先在启动 shell 中清除该变量。
- **启动环境提供的密钥是后备值**——保存值会写入更高优先级的凭据;移除存储值后才会重新使用启动环境。要让导出的密钥生效,请删除文件中 `refs` 下的对应条目。
- **空值无法保存**——存储空字符串会被拒绝;请改为移除密钥。
- **存储拒绝加载它无法信任的文件**——任何其他用户可读的文件、格式错误的 YAML 或无法访问的路径都会在启动时失败;运行期热重载则保留最后可用内容并告警。
- **同一时刻的修改都会被保留**——如果你在产品写入的同时编辑文件,你的变更会被并入,而不是被覆盖。
@@ -133,7 +133,7 @@ records:
### 设计理念
- **一套明确的优先级。** 继承环境优先,因为它是本次运行的明确意图且无法从进程内部修改;它之下的所有来源都输给受管存储,因此已存密钥永远不会被陈旧的 `.env` 挤掉。
- **一套明确的优先级。** 受管存储对每个提供方都胜出;启动环境、项目 `.env` 与 harness home 的 `.env` 依次是确定的后备来源。
- **文档只存放凭据。** 它是带 `refs` 与 `records` 分节的版本化文档,而不是 dotenv 文件:一个 harness 拥有、且绝不物化进环境的存储,不能同时充当用户的环境层,否则会以自己的优先级遮蔽非机密条目。
- **写入打补丁,重载整体替换。** 行编辑在跨进程写锁下保留注释与未触及条目;重载整体交换解析后的快照,已删除条目绝不在内存滞留。
- **信任攸关处明确报错。** 启动与重载都会拒绝不可读、无效或可被属主之外读取的文档;运行期重载失败时会保留最后可用快照并告警,而不是拖垮进程。
@@ -146,7 +146,7 @@ records:
### 解析与写入路径
`resolve` 与 `describe` 按优先级顺序读取继承环境快照、已解析文档快照与 `.env` 后备层。`set`/`unset` 排入同一条独占操作链:入口检查提前拒绝(已释放、空值、被环境遮蔽),队列在运行时会重新判定,随后在写锁下执行读-改-写、提交,并恰好触发一次 `credentials/reference-updated`。
`resolve` 与 `describe` 按优先级顺序读取已解析文档快照、继承环境快照与 `.env` 后备层。`set`/`unset` 排入同一条独占操作链:入口检查提前拒绝(已释放、空值),随后在写锁下执行读-改-写、提交,并恰好触发一次 `credentials/reference-updated`。
`modifyRecord` 走同一条链与同一把锁:它重新读取文档、把当前记录交给变更函数、准入其结果——非空的 API 密钥、能经受 JSON 往返的 grant payload——整体渲染该记录并提交,恰好触发一次 `credentials/record-updated`。并非由产品 CLI(命令行界面)启动的组合只有继承环境这一层。
@@ -1,20 +1,19 @@
/**
* File-backed credentials provider over `$DSH_HOME/.credentials.yaml`, layered
* against the environment by how much each layer is trusted:
* over the environment in this precedence order:
*
* ```text
* inherited process environment (read-only, wins)
* > $DSH_HOME/.credentials.yaml (provider-managed, writable)
* > <invocation cwd>/.env (read-only fallback)
* > $DSH_HOME/.env (read-only fallback)
* $DSH_HOME/.credentials.yaml (provider-managed, written by set/unset)
* > inherited process environment (fallback; this provider never writes it)
* > <invocation cwd>/.env (fallback; this provider never writes it)
* > $DSH_HOME/.env (fallback; this provider never writes it)
* ```
*
* The inherited environment wins because `DEEPSEEK_API_KEY=… dsh`, a CI
* secret, or a container `-e` is this run's explicit intent; it cannot be
* edited from inside, so it must be *visibly* read-only rather than silently
* shadow writes. Everything below it loses to the managed store, so a key the
* Models page writes takes effect immediately even when an older key sits in
* the user's `.env`.
* The managed store wins because a credential the user explicitly saved in
* the product must take effect consistently for every provider. The launch
* environment, CI secrets included, applies only while the file stores no
* value for the reference. See
* `.agents/notes/implemented/architecture/2026-10-09-stored-credential-precedence.md`.
*
* The invoking project may supply a key, because the product trusts the
* project it is launched in. It ranks below the managed store, so a key stored
@@ -618,24 +617,21 @@ export class LocalCredentialProvider extends CredentialProvider {
}
override resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined> {
const inherited = this.inherited(ref)
if (inherited !== undefined) return Promise.resolve({ value: inherited, source: 'env' })
const stored = this.values.get(ref)
if (stored !== undefined) return Promise.resolve({ value: stored, source: 'file' })
const inherited = this.inherited(ref)
if (inherited !== undefined) return Promise.resolve({ value: inherited, source: 'env' })
const fallback = this.dotenvFallback(ref)
if (fallback !== undefined) return Promise.resolve({ value: fallback.value, source: fallback.source })
return Promise.resolve(undefined)
}
override describe(ref: CredentialRef): Promise<CredentialInfo> {
// Only the inherited environment is unwritable: it is the one layer this
// process cannot edit. A user `.env` value is writable in the sense that
// matters — storing a key replaces it as the effective one.
if (this.inherited(ref) !== undefined) {
return Promise.resolve({ configured: true, source: 'env', writable: false })
}
const stored = this.values.get(ref)
if (stored !== undefined) return Promise.resolve({ configured: true, source: 'file', writable: true })
// Every reference is writable: a set writes the managed file, which
// outranks every fallback, and an unset exposes the fallback again.
if (this.inherited(ref) !== undefined) return Promise.resolve({ configured: true, source: 'env', writable: true })
const fallback = this.dotenvFallback(ref)
if (fallback !== undefined) return Promise.resolve({ configured: true, source: fallback.source, writable: true })
return Promise.resolve({ configured: false, writable: true })
@@ -740,19 +736,16 @@ export class LocalCredentialProvider extends CredentialProvider {
void this.enqueue(() => this.refresh())
}
/** Queue one line edit; entry checks reject early, the queue re-judges them at run time. */
/** Queue one line edit; disposal is checked on entry and again when the queued edit runs. */
private async write(ref: CredentialRef, value: string | undefined): Promise<void> {
const verb = value === undefined ? 'unset' : 'set'
if (this.isClosed()) {
throw new Error(`credentials-local is disposed: cannot ${verb} "${ref}"`)
}
this.assertUnshadowed(ref, verb)
return this.enqueue(async () => {
if (this.isClosed()) {
throw new Error(`credentials-local was disposed before the queued "${ref}" ${verb} ran`)
}
// Re-judged at run time: the environment may have changed while queued.
this.assertUnshadowed(ref, verb)
// The writer lock's exclusive create needs the parent to exist; 0700
// because the harness home holds user-private data.
await mkdir(dirname(this.spec.filename), { recursive: true, mode: 0o700 })
@@ -777,20 +770,6 @@ export class LocalCredentialProvider extends CredentialProvider {
})
}
/**
* Reject a write the inherited environment would shadow into apparent
* no-effect. Only that layer can shadow a write: everything else this
* provider resolves ranks below the document being written.
*/
private assertUnshadowed(ref: CredentialRef, verb: 'set' | 'unset'): void {
if (this.inherited(ref) !== undefined) {
throw new Error(
`credentials-local: "${ref}" is supplied read-only by the launching environment, so ${verb} would be`
+ ' shadowed; unset it in the shell you start dsh from instead',
)
}
}
/**
* Boot read: an absent file is an empty store; an invalid one fails the
* plugin's activation, because a credentials document that exists but
@@ -76,14 +76,14 @@ describe('layering and reads', () => {
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
})
it('lets a non-empty process environment win read-only over the file', async () => {
it('lets the managed file win over a non-empty process environment', async () => {
const dir = await tempDir()
const path = join(dir, '.credentials.yaml')
await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_TEST: from-file\n')
const ctx = await boot({ path, watch: false })
vi.stubEnv('DSH_CRED_TEST', 'from-env')
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-env', source: 'env' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'env', writable: false })
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-file', source: 'file' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
})
it('treats an empty environment value as absent, falling through to the file', async () => {
@@ -106,8 +106,8 @@ describe('layering and reads', () => {
})
describe('layer ladder', () => {
// inherited process env > .credentials.yaml > $DSH_HOME/.env, and the
// invoking directory's .env supplies no credential at all.
// .credentials.yaml > inherited process env > invoking directory .env >
// $DSH_HOME/.env.
async function bootLayered(
path: string,
layers: Parameters<typeof createLaunchEnvironmentSnapshot>[0],
@@ -136,6 +136,19 @@ describe('layer ladder', () => {
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'rotated', source: 'file' })
})
it('stores over a launch environment value and reveals it again after unset', async () => {
const dir = await tempDir()
const ctx = await bootLayered(join(dir, '.credentials.yaml'), [
{ source: 'process', values: { DSH_CRED_TEST: 'from-launch' } },
])
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-launch', source: 'env' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'env', writable: true })
await ctx.credentials.set(KEY, 'stored')
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' })
await ctx.credentials.unset(KEY)
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-launch', source: 'env' })
})
it('serves the user .env only when nothing is stored', async () => {
const dir = await tempDir()
const ctx = await bootLayered(join(dir, '.credentials.yaml'), [
@@ -208,7 +221,7 @@ describe('layer ladder', () => {
await expect(ctx.plugin(LocalCredentialProvider, { path, watch: false })).rejects.toThrow(/EISDIR/)
})
it('lets only the inherited environment shadow the store, read-only', async () => {
it('keeps the managed store writable when the inherited environment also names it', async () => {
const dir = await tempDir()
const path = join(dir, '.credentials.yaml')
await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_TEST: stored\n')
@@ -216,9 +229,10 @@ describe('layer ladder', () => {
{ source: 'process', values: { DSH_CRED_TEST: 'from-shell' } },
{ source: 'user-env', path: '/home/.dsh/.env', values: { DSH_CRED_TEST: 'from-user-env' } },
])
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-shell', source: 'env' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'env', writable: false })
await expect(ctx.credentials.set(KEY, 'next')).rejects.toThrow(/launching environment/)
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
await expect(ctx.credentials.set(KEY, 'next')).resolves.toBeUndefined()
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'next', source: 'file' })
})
})
@@ -364,7 +378,7 @@ describe('document writes', () => {
expect(seen).toEqual([KEY])
})
it('rejects empty values and writes the environment would shadow', async () => {
it('rejects empty values but lets the managed value replace the environment', async () => {
const dir = await tempDir()
const path = join(dir, '.credentials.yaml')
await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_TEST: stored\n')
@@ -373,8 +387,10 @@ describe('document writes', () => {
await expect(ctx.credentials.set(KEY, '')).rejects.toThrow(/empty value/)
vi.stubEnv('DSH_CRED_TEST', 'shadowing')
await expect(ctx.credentials.set(KEY, 'next')).rejects.toThrow(/shadowed/)
await expect(ctx.credentials.unset(KEY)).rejects.toThrow(/shadowed/)
await expect(ctx.credentials.set(KEY, 'next')).resolves.toBeUndefined()
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'next', source: 'file' })
await expect(ctx.credentials.unset(KEY)).resolves.toBeUndefined()
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'shadowing', source: 'env' })
})
it('leaves an empty mapping after unsetting the only entry', async () => {
@@ -33,8 +33,8 @@
en: fd17366bde0425e0
zh: 408fc625b58db7b4
/deepseek-ai-dsh-credentials/use-this-package/what-can-go-wrong:
en: e2d528fe7f9c5846
zh: 934f55ebf276754f
en: 23794d3510273e7f
zh: d89075376de4be29
/deepseek-ai-dsh-credentials/understand-the-implementation:
en: 16370ef642feec6a
zh: a546774827234300
+3 -3
View File
@@ -54,8 +54,8 @@ declare const ctx: Context
const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded
const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined
const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value
await ctx.credentials.set(ref, 'sk-…') // rejects while a read-only source shadows the ref
await ctx.credentials.unset(ref) // no-op when absent; same shadowing rule
await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks
await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again
```
Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value.
@@ -92,7 +92,7 @@ Requests that need the key use its current stored value, so rotating the key tak
### What can go wrong
- **A key the launching environment supplies cannot be overwritten** — `DEEPSEEK_API_KEY=… dsh` (or a CI secret, a container `-e`) wins for this run and is reported read-only; clear the variable in the launching shell before storing a different value.
- **A stored key outranks the launching environment** — while a value is stored, `DEEPSEEK_API_KEY=… dsh` (or a CI secret, a container `-e`) does not apply; `unset` the stored key to use the exported one.
- **An empty value cannot be stored** — storing an empty string is refused; remove the key instead.
- **Key values never appear in configuration UIs or diagnostics** — the UI shows whether a key is set, where it comes from, and whether you can change it; the value itself stays in the store.
@@ -54,8 +54,8 @@ declare const ctx: Context
const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded
const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined
const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value
await ctx.credentials.set(ref, 'sk-…') // rejects while a read-only source shadows the ref
await ctx.credentials.unset(ref) // no-op when absent; same shadowing rule
await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks
await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again
```
用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。
@@ -92,7 +92,7 @@ apiKeyEnv: DEEPSEEK_API_KEY
### 可能出错的地方
- **启动环境提供的密钥无法被覆盖**——`DEEPSEEK_API_KEY=… dsh`(或 CI 机密、容器 `-e`)在本轮运行中优先,并被报告为只读;请先在启动 shell 中清除该变量,再存储其他值。
- **存储的密钥优先于启动环境**——存在存储值时,`DEEPSEEK_API_KEY=… dsh`(或 CI 机密、容器 `-e`)不会生效;要使用导出的密钥,请 `unset` 存储的密钥。
- **空值无法存储**——存储空字符串会被拒绝;请改为移除密钥。
- **密钥值绝不会出现在配置界面或诊断信息中**——界面只显示密钥是否已设置、来自哪里、能否修改;值本身留在存储中。
+10 -10
View File
@@ -155,10 +155,11 @@ declare module '@deepseek-ai/cordis' {
* Abstract credential service over two key spaces that answer two questions.
*
* A {@link CredentialRef} answers "what is behind this environment-variable
* name", layered over the process environment, the provider-managed store, and
* `.env` files. One seam-wide rule binds that half: an empty stored value is
* absent everywhere — `resolve` skips it, `describe` reports it unconfigured —
* so a blank never masquerades as a configured secret.
* name": the provider-managed store first, then ambient fallbacks such as the
* process environment and `.env` files. One seam-wide rule binds that half: an
* empty stored value is absent everywhere — `resolve` skips it, `describe`
* reports it unconfigured — so a blank never masquerades as a configured
* secret.
*
* A {@link CredentialKey} answers "what credential does this plugin hold for
* this id". Nothing can layer here — an authorization grant has no
@@ -191,10 +192,9 @@ export abstract class CredentialProvider extends Service {
abstract describe(ref: CredentialRef): Promise<CredentialInfo>
/**
* Durably store one value in the provider-managed writable source. Rejects
* while a read-only source shadows the reference — the write would appear
* to succeed while resolution keeps returning the shadowing value — and
* rejects an empty value (use {@link unset}).
* Durably store one value in the provider-managed writable source. The stored
* value takes precedence over ambient fallbacks, and empty values are
* rejected (use {@link unset}).
* @param ref - the reference to store.
* @param value - the non-empty secret value.
*/
@@ -202,8 +202,8 @@ export abstract class CredentialProvider extends Service {
/**
* Remove one reference from the provider-managed writable source; removing
* an absent reference is a no-op. Rejects while a read-only source shadows
* the reference, like {@link set}.
* an absent reference is a no-op. Ambient fallback layers may become
* effective again after removal.
* @param ref - the reference to remove.
*/
abstract unset(ref: CredentialRef): Promise<void>
@@ -24,8 +24,8 @@
en: ca75c51c89c2c9b0
zh: 64715dc7e6d02f71
/deepseek-ai-dsh-experimental-webworker-runtime/known-limitations-and-deferred-work:
en: 1bc41bcc7a7e065e
zh: 9e9558ff06c508bc
en: 7a473e73cc9449f9
zh: 2752c65ef3a33463
/deepseek-ai-dsh-experimental-webworker-runtime/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: e88aeb617ffb74ea
@@ -57,6 +57,7 @@ None; this package neither assembles nor sends a provider request.
- **Native TLS listeners require a Node Host**: the worker's `node:https.createServer` rejects activation rather than substituting plaintext. The preview's internal HTTP tunnel does not bind sockets; browser-facing HTTPS belongs to its deployment server.
- **Desktop product telemetry is unavailable**: `got.post` reports an explicit worker-host refusal. Got and its Node HTTP dependencies are excluded from the browser image; Desktop reporting remains disabled in the preview composition.
- **Host package commands are unavailable**: `execa` reports an explicit worker-host refusal; the preview cannot run pnpm, install plugins, or install native dependencies.
- **pi-ai model requests are unavailable**: the replacement exposes a fixed subset of installed provider identifiers with no models, allowing the adapter to register configuration metadata. Its identifiers must stay valid when pi-ai is upgraded; inference entry points report an explicit worker-host refusal.
- **PTC Node programs are unavailable**: the process shim exposes `/dsh/bin/node` as its executable identity so the provider can activate, but the Worker has neither a Node executable nor `stripTypeScriptTypes`. Program execution fails before launching a child.
- **Office conversion requires a Node Host**: the LibreOffice kit replacement rejects converter creation with `unavailable`. The browser image excludes the kit and its engine dependencies; the Office preview reports that conversion is unavailable.
- **Filesystem watchers observe only the mounted VFS**: image seeding is silent and the VFS has no symlinks or external writers. `persistent`, `ref()`, and `unref()` preserve the Node API but cannot control a dedicated Worker's lifetime because browsers expose no ref-counted event loop.
@@ -57,6 +57,7 @@ kind: "package-library"
- **原生 TLS 监听器需要 Node Host**:worker 的 `node:https.createServer` 会拒绝激活,不会替换成明文。预览内部的 HTTP 隧道不绑定套接字;面向浏览器的 HTTPS 由部署服务器提供。
- **桌面产品埋点不可用**:`got.post` 明确报告 worker host 不支持该调用。浏览器镜像不包含 Got 及其 Node HTTP 依赖;预览组合不启用桌面上报。
- **宿主包管理命令不可用**:`execa` 明确报告 worker host 不支持该调用;预览无法运行 pnpm、安装插件或安装原生依赖。
- **pi-ai 模型请求不可用**:替代实现暴露已安装提供方标识的固定子集,不包含模型,使适配器能够注册配置元数据。升级 pi-ai 时必须保持这些标识有效;推理入口明确报告 worker host 不支持该调用。
- **PTC Node 程序不可用**:process shim 用 `/dsh/bin/node` 表示可执行文件身份,使 provider 能够激活,但 Worker 既没有 Node 可执行文件,也没有 `stripTypeScriptTypes`。程序执行会在启动子进程前失败。
- **Office 转换需要 Node Host**:LibreOffice kit 的替代模块以 `unavailable` 拒绝创建转换器。浏览器镜像排除 kit 及其引擎依赖;Office 预览提示转换不可用。
- **文件 watcher 只能观察已挂载的 VFS**:镜像 seed 不产生事件,VFS 也没有符号链接或外部写入方。`persistent`、`ref()` 和 `unref()` 保留 Node API,但浏览器没有引用计数事件循环,因此这些接口不能控制 dedicated Worker 的生存期。
@@ -31,12 +31,11 @@ export const isContextOverflow = notImplementedFail(MODULE, 'isContextOverflow')
export const builtinModels = notImplementedFail(MODULE, 'builtinModels')
/**
* Builtin provider ids as pi-ai 0.84.2 listed them, in catalog order. The list
* is a fixed copy that pi-ai upgrades do not regenerate, so it omits providers
* added since.
* Preview provider ids, in catalog order. This fixed subset must use valid
* installed pi-ai identifiers so the adapter can attach authentication metadata.
*/
const BUILTIN_PROVIDER_IDS: readonly string[] = [
'amazon-bedrock', 'ant-ling', 'anthropic', 'azure-openai-responses', 'baseten', 'cerebras',
'amazon-bedrock', 'ant-ling', 'anthropic', 'azure', 'baseten', 'cerebras',
'cloudflare-ai-gateway', 'cloudflare-workers-ai', 'deepseek', 'fireworks', 'github-copilot',
'google', 'google-vertex', 'groq', 'huggingface', 'kimi-coding', 'minimax', 'minimax-cn',
'mistral', 'moonshotai', 'moonshotai-cn', 'nvidia', 'openai', 'openai-codex', 'opencode',
@@ -817,7 +817,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
{
key: 'credentials',
summary: 'Abstract credential service over two key spaces that answer two questions.',
description: 'Abstract credential service over two key spaces that answer two questions.\n\nA CredentialRef answers "what is behind this environment-variable name", layered over the process environment, the provider-managed store, and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret.\n\nA CredentialKey answers "what credential does this plugin hold for this id". Nothing can layer here — an authorization grant has no environment to be read from — so presence of the record is the whole fact, and modifyRecord is the only write path because a correct write depends on the current value (a token refresh is read-decide-replace under one lock).',
description: 'Abstract credential service over two key spaces that answer two questions.\n\nA CredentialRef answers "what is behind this environment-variable name": the provider-managed store first, then ambient fallbacks such as the process environment and `.env` files. One seam-wide rule binds that half: an empty stored value is absent everywhere — `resolve` skips it, `describe` reports it unconfigured — so a blank never masquerades as a configured secret.\n\nA CredentialKey answers "what credential does this plugin hold for this id". Nothing can layer here — an authorization grant has no environment to be read from — so presence of the record is the whole fact, and modifyRecord is the only write path because a correct write depends on the current value (a token refresh is read-decide-replace under one lock).',
methods: [
{
signature: 'abstract resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>',
@@ -833,12 +833,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: 'abstract set(ref: CredentialRef, value: string): Promise<void>',
description: 'Durably store one value in the provider-managed writable source. Rejects while a read-only source shadows the reference — the write would appear to succeed while resolution keeps returning the shadowing value — and rejects an empty value (use unset).',
description: 'Durably store one value in the provider-managed writable source. The stored value takes precedence over ambient fallbacks, and empty values are rejected (use unset).',
parameters: [{ name: 'ref', description: 'the reference to store.' }, { name: 'value', description: 'the non-empty secret value.' }],
},
{
signature: 'abstract unset(ref: CredentialRef): Promise<void>',
description: 'Remove one reference from the provider-managed writable source; removing an absent reference is a no-op. Rejects while a read-only source shadows the reference, like set.',
description: 'Remove one reference from the provider-managed writable source; removing an absent reference is a no-op. Ambient fallback layers may become effective again after removal.',
parameters: [{ name: 'ref', description: 'the reference to remove.' }],
},
{
@@ -5806,7 +5806,7 @@ 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 error?: string;\n}',
declaration: 'export interface LlmConfigurableProvider {\n provider: string;\n displayName: string;\n settingsNs: string;\n settingsPath: readonly string[];\n declared?: boolean;\n defaultBaseURL?: string;\n nativeAuth?: LlmNativeAuth;\n error?: string;\n}',
},
{
name: 'LlmDiscoveredModel',
@@ -5840,6 +5840,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'LlmModelReasoningInfo',
declaration: 'export interface LlmModelReasoningInfo {\n efforts: readonly LlmReasoningEffortInfo[];\n defaultEffort?: ReasoningEffortId;\n}',
},
{
name: 'LlmNativeAuth',
declaration: 'export interface LlmNativeAuth {\n env: readonly string[];\n oauth: boolean;\n}',
},
{
name: 'LlmProviderInfo',
declaration: 'export interface LlmProviderInfo {\n id: string;\n name: string;\n}',
+1 -1
View File
@@ -141,7 +141,7 @@ At assembly time, each guidance section checks `ctx.tools.get(name, scope)` and
##### Read guidance
```markdown
Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files.
Use the read tool — not shell commands like cat, sed, head, or tail — to inspect text files. Use offset and limit to read a line range or continue a large file.
```
##### Write guidance
+1 -1
View File
@@ -141,7 +141,7 @@ kind: "package-reference"
##### Read 指导
```markdown
Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files.
Use the read tool — not shell commands like cat, sed, head, or tail — to inspect text files. Use offset and limit to read a line range or continue a large file.
```
##### Write 指导
+1 -1
View File
@@ -71,7 +71,7 @@ export function applyReadTool(ctx: Context, caps: ReadToolCaps): void {
order: ctx.systemPrompt.getSectionOrder('TOOL_READ'),
text: ({ scope }) => ctx.tools.get('read', scope) === undefined
? ''
: 'Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files.',
: 'Use the read tool — not shell commands like cat, sed, head, or tail — to inspect text files. Use offset and limit to read a line range or continue a large file.',
})
ctx.tools.register(defineTool({
+1 -1
View File
@@ -1044,7 +1044,7 @@ async function guidanceScope(ctx: Context) {
}
const originalGuidance = {
read: 'Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files.',
read: 'Use the read tool — not shell commands like cat, sed, head, or tail — to inspect text files. Use offset and limit to read a line range or continue a large file.',
write: 'Read an existing file before overwriting it with write (the default fs-observation-policy requires it) and prefer edit for targeted changes.',
edit: 'Read a file before editing it (the default fs-observation-policy requires it), unless you just created or edited it in this session.',
}
@@ -24,8 +24,8 @@
en: a1312339977f1127
zh: 57450327ff7e7d83
/deepseek-ai-dsh-goal-round-driver/use-this-package/when-continuation-stops:
en: 87b20bc93e1c6ebb
zh: 20eebb2538da1551
en: 32ad77251e9f5acd
zh: a72f4c3e95c1a137
/deepseek-ai-dsh-goal-round-driver/use-this-package/after-resume-fork-or-unload:
en: 85d5470b1b330330
zh: e761f9046ba7af8a
+1 -1
View File
@@ -50,7 +50,7 @@ With an exact live agent idle, an active armed goal, and remaining capacity, the
### When continuation stops
A round starts only at whole-agent idle, and completion, pause, and blocking suppress continuation; a host-initiated pause also aborts the turn already running, while a model-initiated pause inside its own turn finishes normally. An edit only invalidates an in-flight round through the revision fence, and the driver continues the new revision. The driver also stops on its own when a turn ends on max tokens, a durability write fails, the agent is cancelled, the plugin unloads, or the round cap is exhausted — at the cap it records a blocker with the stable code `round-limit`. Cancellation never auto-restarts a round: a goal whose round was under way is paused at the next idle point, and a cancellation unrelated to a goal attempt only disarms continuation. A round prompt still queued when the agent reaches idle is removed from the inbox, so later human input does not wait behind it; when the cancelled turn belonged to other work, continuation is disarmed rather than paused.
A round starts only at whole-agent idle and, when the subagent service is loaded, only after the agent's progressing descendants settle; completion, pause, and blocking suppress continuation; a host-initiated pause also aborts the turn already running, while a model-initiated pause inside its own turn finishes normally. An edit only invalidates an in-flight round through the revision fence, and the driver continues the new revision. The driver also stops on its own when a turn ends on max tokens, a durability write fails, the agent is cancelled, the plugin unloads, or the round cap is exhausted — at the cap it records a blocker with the stable code `round-limit`. Cancellation never auto-restarts a round: a goal whose round was under way is paused at the next idle point, and a cancellation unrelated to a goal attempt only disarms continuation. A round prompt still queued when the agent reaches idle is removed from the inbox, so later human input does not wait behind it; when the cancelled turn belonged to other work, continuation is disarmed rather than paused.
### After resume, fork, or unload
+1 -1
View File
@@ -50,7 +50,7 @@ kind: "package-reference"
### 何时停止续行
Round 只在整个 agent 进入 idle 时启动;完成、暂停和阻塞会阻止续行;宿主发起的暂停还会中止正在运行的轮次,而模型在自己轮次内发起的暂停会正常结束。编辑只会通过修订栅栏使进行中的 Round 失效,驱动器会继续新修订。驱动器也会在以下情况自行停止:轮次因 max tokens 结束、持久性写入失败、agent 被取消、插件卸载,或 Round 上限耗尽——上限耗尽时它会以稳定代码 `round-limit` 记录一个 blocker。取消绝不会自动重启 Round:Round 已在进行的 goal 会在下一次 idle 时被暂停;与 goal 尝试无关的取消只会停用续行。agent 进入 idle 时仍在排队的 Round 提示会从收件箱移除,后续人类输入不会排在它后面等待;被取消的轮次属于其他工作时,续行会被停用而不是暂停。
Round 只在整个 agent 进入 idle 时启动;加载了子 agent 服务时,还要等该 agent 仍在推进的后代全部结束后才启动;完成、暂停和阻塞会阻止续行;宿主发起的暂停还会中止正在运行的轮次,而模型在自己轮次内发起的暂停会正常结束。编辑只会通过修订栅栏使进行中的 Round 失效,驱动器会继续新修订。驱动器也会在以下情况自行停止:轮次因 max tokens 结束、持久性写入失败、agent 被取消、插件卸载,或 Round 上限耗尽——上限耗尽时它会以稳定代码 `round-limit` 记录一个 blocker。取消绝不会自动重启 Round:Round 已在进行的 goal 会在下一次 idle 时被暂停;与 goal 尝试无关的取消只会停用续行。agent 进入 idle 时仍在排队的 Round 提示会从收件箱移除,后续人类输入不会排在它后面等待;被取消的轮次属于其他工作时,续行会被停用而不是暂停。
### resume、fork 或卸载之后
+9 -2
View File
@@ -33,7 +33,8 @@
"@deepseek-ai/dsh-goal": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
"@deepseek-ai/cordis": "workspace:~"
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-subagent": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/dsh-agent": "workspace:*",
@@ -45,6 +46,12 @@
"@deepseek-ai/dsh-system-prompt": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-session-projection": "workspace:*"
"@deepseek-ai/dsh-session-projection": "workspace:*",
"@deepseek-ai/dsh-subagent": "workspace:*"
},
"peerDependenciesMeta": {
"@deepseek-ai/dsh-subagent": {
"optional": true
}
}
}
+18 -1
View File
@@ -11,6 +11,7 @@ import type { GoalMessageSource, GoalRef, GoalView } from '@deepseek-ai/dsh-goal
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm'
import type { Session, SessionEvent, UserMessage } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-subagent'
import { renderGoalRoundPrompt } from './prompt.ts'
export { renderGoalRoundPrompt } from './prompt.ts'
@@ -75,6 +76,8 @@ function renderThrown(value: unknown): string {
/** Install automatic same-session continuation and its race fences. */
export function apply(ctx: Context): void {
const states = new Map<Agent, DriverState>()
// Releases drivers still joining subagents when the plugin unloads.
const unloading = Promise.withResolvers<void>()
/** Create state for an exact currently live agent. */
function stateFor(agent: Agent): DriverState {
@@ -99,6 +102,11 @@ export function apply(ctx: Context): void {
return ctx.goals.get(state.agent)
}
/** Whether a goal may receive automatic rounds. */
function drivable(goal: GoalView | undefined): goal is GoalView {
return goal !== undefined && goal.phase === 'active' && goal.activation === 'armed'
}
/** Whether this exact lifecycle is quiescent with no competing prompt. */
function readyToDrive(state: DriverState): boolean {
return ctx.fiber.state === FiberState.ACTIVE
@@ -162,7 +170,15 @@ export function apply(ctx: Context): void {
}
const goal = currentGoal(state)
if (goal === undefined || goal.phase !== 'active' || goal.activation !== 'armed') return
if (!drivable(goal)) return
// A round started while descendants progress would only wait for them.
// Every goal mutation requests a checkpoint, so passing the recheck
// proves this goal view is still current.
const subagents = ctx.get('subagents')
if (subagents !== undefined) {
await Promise.race([subagents.waitForChildren(agent), unloading.promise])
if (!readyAfterCheckpoint(state)) return
}
if (goal.roundsStarted >= goal.maxGoalRounds) {
ctx.goals.block(agent, goalRef(goal), {
code: 'round-limit',
@@ -438,6 +454,7 @@ export function apply(ctx: Context): void {
// Yielded after listener registration, so this close runs first and the
// composite effect removes listeners only after its promise settles.
yield async () => {
unloading.resolve()
const waits: Promise<void>[] = []
for (const state of states.values()) {
state.stopping = true
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff. Show more