diff --git a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.i18n.yaml index aad3aa26f0..10a29ee499 100644 --- a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md -2026-07-07-tool-call-timeout-policy.md: ce414e541f8e374dd48e46d68cb00121e0004247 -2026-07-07-tool-call-timeout-policy.zh.md: 6fe3c979a3c4e7b7a6ed803a47af45ad32d52cce +2026-07-07-tool-call-timeout-policy.md: 92618cc8c761b38d7e516c9d00eb3de1c37831a8 +2026-07-07-tool-call-timeout-policy.zh.md: cc633ceaa3840331826f6475e603e78a98f0afd2 diff --git a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md index ce414e541f..92618cc8c7 100644 --- a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md +++ b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md @@ -77,7 +77,7 @@ No new session event is needed for reconstructability: `TOOL_TIMEOUT` is the fin ### Existing tool adaptation -`web_fetch` and `web_search` are migrated. `dsh-tool-web` keeps ownership of their model-facing schemas, and those schemas expose no timeout knob: `web_fetch` dropped its `timeout_ms` parameter to match the reference-agent shape, and `web_search` stays query-only. The tool bodies do not import `@deepseek-ai/dsh-timeout`; they forward `exec.signal` to `ctx.web`. +`web_fetch` and `web_search` are migrated. `dsh-tool-web` keeps ownership of their model-facing schemas, and those schemas expose no timeout knob: `web_fetch` has no `timeout_ms` parameter, while `web_search` accepts a required `queries` array without a timeout argument. The tool bodies do not import `@deepseek-ai/dsh-timeout`; they forward `exec.signal` to `ctx.web`. `dsh-web-fetch-http` keeps one configured provider-level `timeoutMs` as a large resource backstop for direct `ctx.web.fetch()` callers and misconfigured deployments; it owns no model-facing timeout. When a `TOOL_TIMEOUT` signal reaches the fetch provider first, provider-scoped classification treats it as upstream `WEB_ABORTED`, and the outer `tools/execute` wrapper replaces the final tool result with `TOOL_TIMEOUT`. A shipped web-tool deployment configures the provider backstop above the `timeout-policy` budget so the tool-call policy normally wins for model calls. diff --git a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.zh.md b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.zh.md index 6fe3c979a3..cc633ceaa3 100644 --- a/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.zh.md @@ -77,7 +77,7 @@ function toolTimeoutResult(timeoutMs: number): ToolExecutionResult { ### 现有工具适配 -`web_fetch` 和 `web_search` 已迁移。`dsh-tool-web` 保留对其面向模型 schema 的所有权,这些 schema 不暴露超时旋钮:`web_fetch` 移除了 `timeout_ms` 参数以匹配参考 agent(智能体)的形状,`web_search` 保持仅查询。工具体不导入 `@deepseek-ai/dsh-timeout`;它们将 `exec.signal` 转发给 `ctx.web`。 +`web_fetch` 和 `web_search` 已迁移。`dsh-tool-web` 保留对其面向模型 schema 的所有权,这些 schema 不暴露超时旋钮:`web_fetch` 没有 `timeout_ms` 参数,`web_search` 接受必填的 `queries` 数组,但不接受超时参数。工具体不导入 `@deepseek-ai/dsh-timeout`;它们将 `exec.signal` 转发给 `ctx.web`。 `dsh-web-fetch-http` 保留一个在提供方层面配置的 `timeoutMs`,作为较大的资源兜底值,服务于直接调用 `ctx.web.fetch()` 的调用方和配置错误的部署;它不拥有面向模型的超时。当 `TOOL_TIMEOUT` 信号先到达 fetch 提供方时,提供方作用域的分类将其视为上游 `WEB_ABORTED`,而外层 `tools/execute` 包装器将最终工具结果替换为 `TOOL_TIMEOUT`。一个已发布的 web 工具部署将提供方兜底配置为高于 `timeout-policy` 预算,使工具调用策略在模型调用中通常胜出。 diff --git a/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.i18n.yaml index ecca8ab2b0..007b9c0d73 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.md -2026-07-30-client-locale-full-rollout.md: c6c5a8f2faffd3e03462eaad159ae94c53c735ce -2026-07-30-client-locale-full-rollout.zh.md: 8d6220784104944f5d07b533e4f107ceffdfcfea +2026-07-30-client-locale-full-rollout.md: 6701aefa451786d3ca6ac27d7214824a6d903bab +2026-07-30-client-locale-full-rollout.zh.md: 0c05ec9699700d88d786bc661f7013f2ed09ebb2 diff --git a/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.md b/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.md index c6c5a8f2fa..6701aefa45 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.md +++ b/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.md @@ -42,4 +42,4 @@ The "apply layer subscribes to `locale/change` and re-registers for fresh labels - A language switch refreshes the whole UI instantly with zero re-registration; adopting a new package is three steps (dictionary + declare-merge + `locale: NS`), no hand-written glue. - Cost: list-label consumers must know `resolveSlotLabel` (a raw `options.label` read can now hold a function); the `SlotLabel` type catches most misuse statically. - ui-primitives' Chinese defaults still render Chinese under the English locale **until a consumer passes labels** — the unmigrated JsonTree consumer (ui-trajectory) showing its English defaults happens to match that package's all-English status quo. -- Pinning e2e to English means the zh default is covered mainly by package-level component specs and the settings language-switch scenario; browser e2e no longer asserts zh copy. +- Pinning e2e to English means the zh copy surface is covered mainly by package-level component specs and the settings language-switch scenario; browser e2e no longer asserts zh copy. The opening/fallback locale (a browser naming no shipped language, or a non-browser run) is `en`, not zh — see [browser-derived initial locale](../feature/2026-07-31-browser-derived-initial-locale.md). diff --git a/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.zh.md b/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.zh.md index 8d62207841..0c05ec9699 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-30-client-locale-full-rollout.zh.md @@ -42,4 +42,4 @@ typed locale 标准席位(`locale:` 注册声明 → 框架注入强类型 `t` - 语言切换全 UI 即时刷新且零重注册;新包接入 = 字典 + declare-merge + `locale: NS` 三步,无手写胶水。 - 代价:list label 的消费方必须知道 `resolveSlotLabel`(裸读 `options.label` 现在可能拿到函数);类型上 `SlotLabel` 已挡住多数误用。 - ui-primitives 的中文默认值在英文语言下依旧是中文,**直到消费方传入 labels**——未迁移的 JsonTree 消费方(ui-trajectory)显示其英文默认值,恰好符合其整包英文现状。 -- e2e 英文钉死意味着 zh 默认态主要靠包级组件测试与 settings 语言切换用例覆盖,浏览器 e2e 不再验证 zh 文案。 +- e2e 英文钉死意味着 zh 文案面主要靠包级组件测试与 settings 语言切换用例覆盖,浏览器 e2e 不再验证 zh 文案。开场/回落 locale(声明了本应用都不支持语言的浏览器,或非浏览器运行)是 `en` 而非 `zh`,见 [browser-derived initial locale](../feature/2026-07-31-browser-derived-initial-locale.md)。 diff --git a/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.i18n.yaml index 4012912001..5e158d2c8b 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.md -2026-07-30-settings-write-path-integrity.md: c01f04a9b88417115505a8fc9fd3641055e95472 -2026-07-30-settings-write-path-integrity.zh.md: 967acf3266451e5a3974b37bc5703e5d45592007 +2026-07-30-settings-write-path-integrity.md: 7a2d377586ff2bfa7caeb9d4196ee99f70d3e63f +2026-07-30-settings-write-path-integrity.zh.md: fa68bfba04382d6cafd03bf174ebadcd6bafd519 diff --git a/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.md b/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.md index c01f04a9b8..7a2d377586 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.md +++ b/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.md @@ -14,7 +14,7 @@ The provider's write path could destroy state it never observed, and the Service **One operation chain, and every write is a read-modify-write.** Watcher refreshes and persists from every namespace queue share a single settled chain, and `persistSection` begins by reconciling the on-disk text into the seam — publishing any unobserved difference first — before rendering against that fresh text. A write can no longer resurrect a stale document, and an on-disk document that turned invalid fails the write loud rather than being overwritten (the reload path keeps its warn-and-keep-last-good policy; the shared `reconcileFromDisk` throws and each caller picks its policy). The watcher's `ready` signal queues one extra reconcile, closing the startup gap between the initial load and the watcher becoming active. -**Writes hold a `wx`-created `.lock` sibling.** The read-render-rename cycle runs under a cross-process writer lock with exponential backoff and a 2 s acquisition deadline. A contender times out without removing the existing lock because age cannot distinguish a crashed owner from a paused live writer; orphan recovery is an operator action. Readers never lock — the rename commit is atomic — so contention is writer-only. The retry and deadline constants are protocol invariants, not deployment config. +**Writes hold a `wx`-created `.lock` sibling.** The read-render-rename cycle runs under a cross-process writer lock with exponential backoff and a 2 s acquisition deadline. `EEXIST` identifies contention directly; `EPERM` identifies it only when `lstat` confirms that the lock path exists, because Windows may report permission denial for an exclusive create against that existing path. An unrelated permission failure remains loud. A contender times out without removing the existing lock because age cannot distinguish a crashed owner from a paused live writer; orphan recovery is an operator action. Readers never lock — the rename commit is atomic — so contention is writer-only. The retry and deadline constants are protocol invariants, not deployment config. **Observer disposal is quiescent.** Watchers carry an `active` flag checked when a queued invocation would start, so a disposer that ran while the invocation waited prevents the start entirely; started invocations register in a service-level `pendingTails` set that the dispose drain awaits beside the write queues. The `settings/updated` fan-out contains a returned thenable's rejection through the same listener diagnostic as a sync throw, and the event contract now states that the `INVARIANT` rethrow serves synchronous listeners only — invariant companions must stay sync, which the shipped companion already is. diff --git a/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.zh.md b/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.zh.md index 967acf3266..fa68bfba04 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-30-settings-write-path-integrity.zh.md @@ -18,7 +18,7 @@ YAML 写入则整体替换 namespace 节点,把分节内的每条注释都删 **单一操作链,且每次写入都是读-改-写。**watcher 的刷新与来自各 namespace 队列的持久化共享同一条结算链;`persistSection` 会先把磁盘上的文本对账进 seam——任何未被观察到的差异都先发布出去——然后才对照这份新鲜文本渲染。写入不再可能复活一份陈旧文档;磁盘上已变非法的文档会让写入响亮失败,而不是被覆盖(重载路径保持其「告警并保留最后可用值」策略;共享的 `reconcileFromDisk` 抛错,各调用方自选策略)。watcher 的 `ready` 信号会额外排入一次对账,弥合初始加载与 watcher 生效之间的启动缺口。 -**写入持有以 `wx` 创建的同目录 `.lock`。**读-渲染-rename 循环在一把跨进程写锁下运行,采用指数退避与 2 s 获取期限。竞争者会超时,但不会移除现有锁,因为锁龄无法区分已经崩溃的所有者与被暂停但仍存活的写入方;遗留锁恢复须由操作者执行。读方从不加锁——rename 提交是原子的——因此竞争只发生在写方之间。重试与期限常量是协议不变式,而非部署配置。 +**写入持有以 `wx` 创建的同目录 `.lock`。**读-渲染-rename 循环在一把跨进程写锁下运行,采用指数退避与 2 s 获取期限。`EEXIST` 直接表示竞争;只有 `lstat` 确认锁路径存在时,`EPERM` 才表示竞争,因为 Windows 可能把针对该现有路径的独占创建报告为权限拒绝。无关的权限故障仍会响亮失败。竞争者会超时,但不会移除现有锁,因为锁龄无法区分已经崩溃的所有者与被暂停但仍存活的写入方;遗留锁恢复须由操作者执行。读方从不加锁——rename 提交是原子的——因此竞争只发生在写方之间。重试与期限常量是协议不变式,而非部署配置。 **观察者 dispose 达到完全停稳。**watcher 携带一个 `active` 标志,排队的调用即将启动时先检查它,因此在调用等待期间已经运行过的释放器能让这次启动彻底不发生;已启动的调用会登记进服务级的 `pendingTails` 集合,dispose 排空除了等待各写队列,还会等待该集合。`settings/updated` 扇出会把监听器返回的 thenable 的 rejection 收容进与同步抛错相同的监听器诊断;事件约定现已写明 `INVARIANT` 重抛只服务同步监听器——不变式配套插件必须保持同步,而已交付的那个配套插件本就是同步的。 diff --git a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml index ea59089b5d..6fb4396a74 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-30-web-config-plane.md -2026-07-30-web-config-plane.md: 1326f50a792b6c6f791c9515ea03cc362d16fc7e -2026-07-30-web-config-plane.zh.md: bea4bbc237f44864a5fa9bf677267ca0055c13ed +2026-07-30-web-config-plane.md: ac989cb100190e9a41ebf04b5b2d80125d49e0cb +2026-07-30-web-config-plane.zh.md: 26f11352b4362d3cbded3d1dc9205e289ee9b18c diff --git a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md index 1326f50a79..ac989cb100 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md +++ b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md @@ -22,7 +22,7 @@ The request-level configuration seam made LLM adapter configuration restart-free **A hand-written editor over a schema model layer.** `ctx.settingsSchema`, provided by `dsh-client-ui-settings`, rehydrates the wire's `toJSON()` envelope into live schemastery nodes for validation, path resolution, and immutable draft editing — but no generic rendering: the first cut shipped a full schema-driven form renderer, and the resulting page was an unstyled schema dump (every advanced field flattened onto the card, raw field names as labels, the `retryPolicy` unsupported-fallback in the main flow). The hand-written direction won over adding a hint/grouping system, and a further simplification removed the reference input entirely: the card's primary field is one **API key** input, a whole-section provider without a configured key opens as its setup card, and the collapsed 自定义设置 fold carries the curated per-family extras (`baseURL` for both families, `reasoningEffort` for deepseek / `reasoning` for pi-ai, plus direct DeepSeek model rows with `id`, `name`, and `contextWindow`). Existing model fields outside that visible set survive array edits; retry policy, timeouts, and other fields remain owned by `settings.yaml`. Validation still runs the rehydrated schema before writing, while adapter-specific checks reject catalog invariants that the serialized schema cannot express. The card's colors resolve through the `--dsw-alias-*` design tokens; it had named `--border`/`--surface`/`--text-*`, which nothing in this app defines, so it rendered their light-mode fallbacks and stayed light under the dark theme. The model catalog takes the row shape the pi-ai provider form introduces: one bordered entry per model, id and display name on the row, and the capacities behind the row's own disclosure, so the two editors read as one design rather than diverging. Every field keeps the indexed `aria-label` that names it. Both capacities are text fields reading a decimal `K`/`M` suffix (`1M` is 1000K, matching how capacities are quoted) and storing the plain count: a field holds the typed text while it has focus, because re-deriving it from the parsed count on every keystroke would rewrite `1000` to `1K` mid-word, and text that does not parse stays on screen so the save-time rejection names a row the user can still see. The shared class names carry only declared token spellings: `--dsw-alias-border-subtle`, `--dsw-alias-text-tertiary`, and `--dsw-alias-text-primary` are undeclared, so naming them resolves to the light-mode literals in their fallback slots. A styles test now rejects any `--dsw-*` name the token sheet does not declare, so the next editor to name one fails rather than shipping a light-only surface. -**The Models page is a three-domain join with service-shaped apply semantics.** Rows are configured providers; the add card's select is the dormant directory remainder. Route liveness still gates readiness and invalidates the join, but the page does not render it as provider status because configuration presence and runtime availability are distinct. The key path stays reference-shaped without ever showing a reference: a typed key stores **write-only** through `credentials.set` under the profile's `apiKeyEnv`, deriving `_API_KEY` when none exists (the pi-ai profile records the derivation only when a key is entered), so `settings.yaml` never carries a key value; a blank pi-ai key materializes a reference-free profile and preserves provider-native authentication. Profile edits and removals land as minimal path-addressed `settings.mutate` operations against the redacted user section, which never names a secret the page did not receive. Removing a user-layer provider first opens a localized confirmation dialog whose row actions, title, description, and final action identify the same provider; confirmation removes an exact configured+writable derived credential before the profile, while custom, environment, and unidentified targets remain untouched. Both stages are idempotent and a partial failure stays in the dialog for retry. DeepSeek's model list is array-replace configuration: inherited effective rows remain visible until the first edit materializes the complete list in the user layer, and reset unsets the list override. The partial-commit and credential-ownership rationale lives in the [provider credential lifecycle note](../bug-fix/2026-08-06-provider-credential-lifecycle.md). +**The Models page is a three-domain join with service-shaped apply semantics.** Rows are configured providers; the add card's select is the dormant directory remainder. Route liveness still gates readiness and invalidates the join, but the page does not render it as provider status because configuration presence and runtime availability are distinct. The key path stays reference-shaped without ever showing a reference: a typed key stores **write-only** through `credentials.set` under the profile's `apiKeyEnv`, deriving `_API_KEY` when none exists (the pi-ai profile records the derivation only when a key is entered), so `settings.yaml` never carries a key value; a blank pi-ai key materializes a reference-free profile and preserves provider-native authentication. Profile edits and removals land as minimal path-addressed `settings.mutate` operations against the redacted user section, which never names a secret the page did not receive. Removing a user-layer provider first opens a localized confirmation dialog whose row actions, title, description, and final action identify the same provider; confirmation removes an exact configured+writable derived credential before the profile, while custom, environment, and unidentified targets remain untouched. Both stages are idempotent and a partial failure stays in the dialog for retry. DeepSeek's model list is array-replace configuration: inherited effective rows remain visible until the first edit materializes the complete list in the user layer, and reset unsets the list override. `llm.discoverModels` results stay in picker-local state until **Add selected**; configured ids start unchecked, while **Select all** / **Deselect all** changes only that local set, so bulk selection preserves the same capacity-protection rule. The partial-commit and credential-ownership rationale lives in the [provider credential lifecycle note](../bug-fix/2026-08-06-provider-credential-lifecycle.md). ## Alternatives considered @@ -36,4 +36,4 @@ The request-level configuration seam made LLM adapter configuration restart-free ## Consequences -The whole loop is pinned keyless in the browser lane (`apps/web/tests/models-settings.e2e.ts`): the add card offers the dormant pi-ai catalog, adding `minimax-cn` with a typed key writes the reference-only profile into `settings.yaml`, stores the value into the harness home's `.env` under the derived `MINIMAX_CN_API_KEY`, registers the route live on the topology frame, and the customized fold merges `reasoning` beside the reference — zero model calls, ARIA goldens for the add-card, configured, and identified delete-confirmation states, plus a scaffold `harnessHome` so tests never touch a real `~/.dsh` (the provider under test is one whose derived reference cannot collide with a developer's exported keys). The settings-shell scenario intercepts the pathless native intent; Service Definition, provider, wire, React, and native-opener tests separately pin provider absence, custom-path resolution, absent-file materialization, owner-only permissions, hidden remote/unavailable states, duplicate-click collapse, localized failure, macOS text-editor dispatch, and Linux/Windows desktop dispatch. The removal scenario proves cancellation leaves both profile and key intact, then confirmation removes both the profile and its identified managed credential. The DeepSeek onboarding fixture edits the default catalog into a user-owned list, persists an arbitrary model id/name/context window, removes the active row, and observes the model selector's empty-selection fallback. The rename touched 239 files (fixtures, goldens, docs, python) with no compatibility alias. The renderer replacement needed no wire change: apply semantics, redaction, and the directory join were renderer-agnostic all along. Deferred: a per-row models preview (the picker already lists models) and a page address for live routes that never declared configurability. +The whole loop is pinned keyless in the browser lane (`apps/web/tests/models-settings.e2e.ts`): the add card offers the dormant pi-ai catalog, adding `minimax-cn` with a typed key writes the reference-only profile into `settings.yaml`, stores the value into the harness home's `.env` under the derived `MINIMAX_CN_API_KEY`, registers the route live on the topology frame, and the customized fold merges `reasoning` beside the reference — zero model calls, ARIA goldens for the add-card, configured, model-picker, and identified delete-confirmation states, plus a scaffold `harnessHome` so tests never touch a real `~/.dsh` (the provider under test is one whose derived reference cannot collide with a developer's exported keys). The component suite pins configured-id exclusions and both directions of the bulk toggle. The settings-shell scenario intercepts the pathless native intent; Service Definition, provider, wire, React, and native-opener tests separately pin provider absence, custom-path resolution, absent-file materialization, owner-only permissions, hidden remote/unavailable states, duplicate-click collapse, localized failure, macOS text-editor dispatch, and Linux/Windows desktop dispatch. The removal scenario proves cancellation leaves both profile and key intact, then confirmation removes both the profile and its identified managed credential. The DeepSeek onboarding fixture edits the default catalog into a user-owned list, persists an arbitrary model id/name/context window, removes the active row, and observes the model selector's empty-selection fallback. The rename touched 239 files (fixtures, goldens, docs, python) with no compatibility alias. The renderer replacement needed no wire change: apply semantics, redaction, and the directory join were renderer-agnostic all along. Deferred: a per-row models preview (the picker already lists models) and a page address for live routes that never declared configurability. diff --git a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md index bea4bbc237..26f11352b4 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md @@ -22,7 +22,7 @@ Status: implemented **架在 schema 模型层之上的手写编辑器。**`dsh-client-ui-settings` 提供的 `ctx.settingsSchema` 把 wire 的 `toJSON()` 信封还原(rehydrate)为活的 schemastery 节点,用于校验、路径解析与不可变草稿编辑——但不做通用渲染:第一版交付了完整的 schema 驱动表单渲染器,得到的却是一个未加样式、把 schema 原样倾倒出来的页面(每个进阶字段都平铺到卡片上、原始字段名直接充当标签、`retryPolicy` 的「不支持」回退落在主流程里)。手写方向胜过了再加一套提示/分组系统,进一步的简化又把引用输入框整个移除:卡片的主字段是一个 **API 密钥** 输入框,未配置密钥的整分节提供方会以其设置卡片的形式打开,收起的「自定义设置」折叠区承载按家族精选的额外字段(两个家族都有 `baseURL`,deepseek 有 `reasoningEffort`/pi-ai 有 `reasoning`,另有直接 DeepSeek 模型行的 `id`、`name` 和 `contextWindow`)。现有模型字段中不在可见集合内的部分会在数组编辑后保留;重试策略、超时及其他字段仍归 `settings.yaml` 所有。校验仍会在写入前运行还原出的 schema,适配器特有的检查则会拒绝序列化 schema 无法表达的目录不变量。卡片的颜色经 `--dsw-alias-*` 设计 token 解析;它此前引用的 `--border`/`--surface`/`--text-*` 在本应用中无人定义,于是渲染出的是它们的亮色模式回退值,在暗色主题下依旧保持亮色。模型目录采用 pi-ai 提供方表单引入的行形态:每个模型一个带边框的条目,ID 与显示名称落在行上,容量则收在该行自己的折叠区里,使两个编辑器呈现为同一套设计,而不是各自分岔。每个字段都保留那个为其命名的带序号 `aria-label`。两项容量都是文本输入框,读取十进制的 `K`/`M` 后缀(`1M` 即 1000K,与容量的通行标注方式一致)并存储纯数值:字段持有焦点期间保留键入的文本,因为若每次按键都从解析出的数值重新推导该文本,`1000` 会在尚未输完时就被改写成 `1K`;无法解析的文本也会留在屏幕上,因此保存时的拒绝点名的是用户仍能看见的那一行。共用的类名只承载已声明的 token 写法:`--dsw-alias-border-subtle`、`--dsw-alias-text-tertiary` 和 `--dsw-alias-text-primary` 均未声明,写出它们就会解析为各自回退槽位中的亮色模式字面值。现在有一个样式测试会拒绝 token 表未声明的任何 `--dsw-*` 名称,因此下一个写出这类名称的编辑者会当场失败,而不是交付一个只有亮色的界面。 -**Models 页是一次三领域联接,应用语义与服务同形。**每一行是一个已配置的提供方;「新增」卡片的选择框是可配置提供方目录中剩余的休眠条目。路由存活状态仍用于就绪判定,并会使该联接失效,但页面不将其渲染为提供方状态,因为配置存在与运行时可用性是两个不同概念。密钥通道保持引用形态,却从不展示任何引用:键入的密钥经 `credentials.set` **只写**存入 profile 的 `apiKeyEnv` 之下,引用不存在时便派生 `_API_KEY`(仅在输入密钥时,pi-ai profile 才会记录该派生),因此 `settings.yaml` 从不携带密钥值;留空 pi-ai 密钥会具化一个不带引用的 profile,并保留提供方原生认证。profile 的编辑和删除会针对脱敏后的用户分节,以按路径寻址的最小 `settings.mutate` 操作落地,绝不会点名页面未收到的机密。删除用户层提供方时,会先打开本地化确认对话框,其行操作、标题、说明和最终操作都会点名同一个提供方;确认后会先清除与派生目标精确匹配且已配置、可写的凭据,再删除 profile,自定义目标、环境目标和无法识别的目标则保持不变。两个阶段都具备幂等性,部分失败会留在对话框中供重试。DeepSeek 的模型列表是数组替换配置:继承而来的生效模型行会一直显示,直到第一次编辑将完整列表具化到用户层;重置则会取消设置该列表覆盖。部分提交与凭据所有权的理由记录在[提供方凭据生命周期 note](../bug-fix/2026-08-06-provider-credential-lifecycle.md)中。 +**Models 页是一次三领域联接,应用语义与服务同形。**每一行是一个已配置的提供方;「新增」卡片的选择框是可配置提供方目录中剩余的休眠条目。路由存活状态仍用于就绪判定,并会使该联接失效,但页面不将其渲染为提供方状态,因为配置存在与运行时可用性是两个不同概念。密钥通道保持引用形态,却从不展示任何引用:键入的密钥经 `credentials.set` **只写**存入 profile 的 `apiKeyEnv` 之下,引用不存在时便派生 `_API_KEY`(仅在输入密钥时,pi-ai profile 才会记录该派生),因此 `settings.yaml` 从不携带密钥值;留空 pi-ai 密钥会具化一个不带引用的 profile,并保留提供方原生认证。profile 的编辑和删除会针对脱敏后的用户分节,以按路径寻址的最小 `settings.mutate` 操作落地,绝不会点名页面未收到的机密。删除用户层提供方时,会先打开本地化确认对话框,其行操作、标题、说明和最终操作都会点名同一个提供方;确认后会先清除与派生目标精确匹配且已配置、可写的凭据,再删除 profile,自定义目标、环境目标和无法识别的目标则保持不变。两个阶段都具备幂等性,部分失败会留在对话框中供重试。DeepSeek 的模型列表是数组替换配置:继承而来的生效模型行会一直显示,直到第一次编辑将完整列表具化到用户层;重置则会取消设置该列表覆盖。`llm.discoverModels` 的结果会留在选择框的本地状态中,直至点击**添加所选**;已配置的 ID 默认不勾选,**全选**/**取消全选**也只会改变这一本地集合,因此批量选择仍遵守同一条容量保护规则。部分提交与凭据所有权的理由记录在[提供方凭据生命周期 note](../bug-fix/2026-08-06-provider-credential-lifecycle.md)中。 ## 曾考虑的替代方案 @@ -36,4 +36,4 @@ Status: implemented ## 后果 -整条闭环以无密钥方式固定在浏览器测试通道(`apps/web/tests/models-settings.e2e.ts`):「新增」卡片提供休眠的 pi-ai catalog,携键入的密钥添加 `minimax-cn` 会把只含引用的 profile 写入 `settings.yaml`、把密钥值存入 harness 家目录 `.env` 中派生的 `MINIMAX_CN_API_KEY` 之下、路由随拓扑帧注册为存活,「自定义设置」折叠区则把 `reasoning` 合并到引用旁边——全程零模型调用,「新增」卡片态、已配置态与已点名目标的删除确认态各有 ARIA golden,另有脚手架式的 `harnessHome`,测试绝不触碰真实的 `~/.dsh`(受测提供方是派生引用不可能与开发者已导出密钥相撞的那一个)。设置外壳场景会截获无路径参数的原生意图;Service Definition、提供方、wire、React 与原生打开器测试分别固定了提供方缺失、自定义路径解析、缺失文件创建、仅属主权限、远程/不可用时隐藏、重复点击合并、本地化失败、macOS 文本编辑器分发,以及 Linux/Windows 桌面分发。删除场景证明,取消会保留 profile 和密钥,随后的确认会同时删除 profile 及其已识别的受管凭据。DeepSeek 首次使用 fixture 会把默认目录编辑为用户自有列表、持久化任意模型的 ID/名称/上下文窗口、移除活动模型行,并观察模型选择器的空选择回退。这次重命名触及 239 个文件(fixture(测试前置数据)、golden、文档、python),未保留兼容别名。替换渲染器不需要任何 wire 变更:应用语义、脱敏与目录联接从一开始就与渲染器无关。延后事项:每行的模型预览(选择器已能列出模型)和为从未声明可配置性的存活路由提供页面地址。 +整条闭环以无密钥方式固定在浏览器测试通道(`apps/web/tests/models-settings.e2e.ts`):「新增」卡片提供休眠的 pi-ai catalog,携键入的密钥添加 `minimax-cn` 会把只含引用的 profile 写入 `settings.yaml`、把密钥值存入 harness 家目录 `.env` 中派生的 `MINIMAX_CN_API_KEY` 之下、路由随拓扑帧注册为存活,「自定义设置」折叠区则把 `reasoning` 合并到引用旁边——全程零模型调用,「新增」卡片态、已配置态、模型选择框态与已点名目标的删除确认态各有 ARIA golden,另有脚手架式的 `harnessHome`,测试绝不触碰真实的 `~/.dsh`(受测提供方是派生引用不可能与开发者已导出密钥相撞的那一个)。组件测试固定了已配置 ID 的排除与批量切换的两个方向。设置外壳场景会截获无路径参数的原生意图;Service Definition、提供方、wire、React 与原生打开器测试分别固定了提供方缺失、自定义路径解析、缺失文件创建、仅属主权限、远程/不可用时隐藏、重复点击合并、本地化失败、macOS 文本编辑器分发,以及 Linux/Windows 桌面分发。删除场景证明,取消会保留 profile 和密钥,随后的确认会同时删除 profile 及其已识别的受管凭据。DeepSeek 首次使用 fixture 会把默认目录编辑为用户自有列表、持久化任意模型的 ID/名称/上下文窗口、移除活动模型行,并观察模型选择器的空选择回退。这次重命名触及 239 个文件(fixture(测试前置数据)、golden、文档、python),未保留兼容别名。替换渲染器不需要任何 wire 变更:应用语义、脱敏与目录联接从一开始就与渲染器无关。延后事项:每行的模型预览(选择器已能列出模型)和为从未声明可配置性的存活路由提供页面地址。 diff --git a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.i18n.yaml index b9b20c4ad9..c8e0a64d5d 100644 --- a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md -2026-08-05-profile-plugin-bundles.md: 94e3ddad0cfea0a1aaf2efe8d15f26f471bb2bd3 -2026-08-05-profile-plugin-bundles.zh.md: 96d22c57f68ecc72e1afd34fbbd3cfbe3ac24c61 +2026-08-05-profile-plugin-bundles.md: c9f685eecddcd4ea8d8580becef3c32a9693a329 +2026-08-05-profile-plugin-bundles.zh.md: 43680862a13171071e236d56c336b790bbe50432 diff --git a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md index 94e3ddad0c..c9f685eecd 100644 --- a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md +++ b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md @@ -12,7 +12,7 @@ The `dsh` launcher hardcoded its compositions: `base.cordis.yml` + `web.cordis.y Everything becomes a **profile**: a directory `$DSH_HOME/profiles/` with a `package.json` (pnpm-managed out-of-tree plugin `dependencies` plus the profile manifest `dsh.profile` with its ordered `bundles` layer list) and a user `cordis.patch.yml`. A **bundle** is an npm package declaring `"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }`; the two manifest kinds live under distinct `dsh.profile` / `dsh.bundle` keys so a package.json states which role it plays. The tree composes over an empty root by applying each bundle's patch in `dsh.profile.bundles` order, then the user layer and `--patch` overlays — one `applyEntryPatches` call shared by boot and `--dump-config`. App invocation values later moved from launcher-derived patches to startup services in the [app-owned command-line decision](2026-08-06-app-owned-command-line.md). -The shipped bundles are `@deepseek-ai/dsh-base` (shared core rows), `@deepseek-ai/dsh-web-app` (browser Host rows and Web runtime glue), and `@deepseek-ai/dsh-headless` (a direct one-shot runner over base, without web-app). Generic `dsh --profile ` hands its remaining arguments to that profile's command-line startup row: Web owns its flag family, while headless owns its task positional. Patch overlays use launcher-owned `--patch`. `dsh plugin --profile ` is a thin pnpm forwarder that initializes the profile and reconciles `dsh.profile.bundles` with installed bundle declarations; a package without a bundle declaration remains a plain dependency. [Headless as a direct core entry point](2026-08-09-headless-direct-core-entry-point.md) owns the headless composition contract. +The default Profile templates use `@deepseek-ai/dsh-base` (shared core rows), `@deepseek-ai/dsh-web-app` (browser Host rows and Web runtime glue), and `@deepseek-ai/dsh-headless` (a direct one-shot runner over base, without web-app). Generic `dsh --profile ` hands its remaining arguments to that profile's command-line startup row: Web owns its flag family, while headless owns its task positional. Patch overlays use launcher-owned `--patch`. `dsh plugin --profile ` is a thin pnpm forwarder that initializes the profile and reconciles `dsh.profile.bundles` with installed bundle declarations; a package without a bundle declaration remains a plain dependency. [Headless as a direct core entry point](2026-08-09-headless-direct-core-entry-point.md) owns the headless composition contract. Resolution is two-anchored by construction: `dsh.profile.bundles` names resolve from the dsh installation first, then the profile directory — so in-box bundles always come from the same installation as the running `dsh` and pnpm never manages them — while bare plugin names in patch rows resolve through the profile directory's Node parent-walk into the maintained flat fallback `$DSH_HOME/profiles/node_modules` (one symlink per package the installation's app and bundles depend on, healed on every launch). diff --git a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.zh.md b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.zh.md index 96d22c57f6..43680862a1 100644 --- a/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.zh.md @@ -12,7 +12,7 @@ Status: implemented 一切都变成 **profile**:即目录 `$DSH_HOME/profiles/`,其中包含一个 `package.json`(pnpm 管理的树外插件 `dependencies`,加上 profile manifest `dsh.profile` 及其有序的 `bundles` 层列表)和一份用户 `cordis.patch.yml`。**组合包**(bundle)是声明了 `"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }` 的 npm 包;两种 manifest 分别位于互不相同的 `dsh.profile` / `dsh.bundle` 键下,因此一份 package.json 能说明自己扮演哪种角色。配置树在空的根之上组合:按 `dsh.profile.bundles` 顺序应用每个组合包的 patch,然后是用户层与 `--patch` overlay——启动与 `--dump-config` 共享同一条 `applyEntryPatches` 路径。随后,[应用持有命令行的决策](2026-08-06-app-owned-command-line.md)又把调用期取值从启动器派生的 patch 迁移到了启动服务。 -随附的组合包是 `@deepseek-ai/dsh-base`(共享核心配置行)、`@deepseek-ai/dsh-web-app`(浏览器 Host 配置行与 Web 运行时粘合层)和 `@deepseek-ai/dsh-headless`(直接叠加在 base 上且不含 web-app 的一次性 runner)。通用的 `dsh --profile ` 把剩余参数交给该 profile 的命令行启动行:Web 持有自己的 flag ,headless 则持有任务位置参数。patch overlay 使用启动器持有的 `--patch`。`dsh plugin --profile ` 是一层薄薄的 pnpm 转发器,负责初始化 profile,并依据已安装包的组合包声明调和 `dsh.profile.bundles`;没有组合包声明的包保持为普通依赖。[Headless 作为直接 core 入口](2026-08-09-headless-direct-core-entry-point.md)负责 headless 组合约定。 +默认 Profile 模板使用的组合包是 `@deepseek-ai/dsh-base`(共享核心配置行)、`@deepseek-ai/dsh-web-app`(浏览器 Host 配置行与 Web 运行时粘合层)和 `@deepseek-ai/dsh-headless`(直接叠加在 base 上且不含 web-app 的一次性 runner)。通用的 `dsh --profile ` 把剩余参数交给该 profile 的命令行启动行:Web 持有自己的 flag 家族,headless 则持有任务位置参数。patch overlay 使用启动器持有的 `--patch`。`dsh plugin --profile ` 是一层薄薄的 pnpm 转发器,负责初始化 profile,并依据已安装包的组合包声明调和 `dsh.profile.bundles`;没有组合包声明的包保持为普通依赖。[Headless 作为直接 core 入口](2026-08-09-headless-direct-core-entry-point.md)负责 headless 组合约定。 解析在构造上就是双锚点的:`dsh.profile.bundles` 中的名称先从 dsh 安装目录解析,再从 profile 目录解析——因此内置组合包始终来自与运行中 `dsh` 相同的安装,pnpm 从不管理它们——而 patch 行中的裸插件名称经 profile 目录的 Node 父目录逐级查找,落到受维护的扁平回退目录 `$DSH_HOME/profiles/node_modules`(安装目录的应用与各组合包所依赖的每个包各一个符号链接,每次启动时修复)。 diff --git a/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.i18n.yaml index 205757eacc..2b083305ea 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.md -2026-08-10-product-subagent-providers-in-shared-host.md: a747d641ae112d114912958c289fe00b592e6ea5 -2026-08-10-product-subagent-providers-in-shared-host.zh.md: fef69e8a2d18135cbc9d5f0d80134fa5701bbbd0 +2026-08-10-product-subagent-providers-in-shared-host.md: 196e28c1263c4b6d71eaeb59b9ba8457b36f3ff4 +2026-08-10-product-subagent-providers-in-shared-host.zh.md: b36398be50065dd1520fb97ca15416467c580bf2 diff --git a/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.md b/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.md index a747d641ae..196e28c126 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.md +++ b/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.md @@ -6,36 +6,34 @@ English | [中文](2026-08-10-product-subagent-providers-in-shared-host.zh.md) ## Problem -The [Codex and Claude Code provider contracts](../feature/2026-08-04-claude-code-and-codex-subagent-backends.md) were first shipped as independently installable packages that a deployment loaded beside the common subagent tool. Agent Presets later became the ordinary owner of one agent's model-visible tools, but a preset cannot safely own these product providers: `ctx.subagents` is a process registry, provider names are unique, and host consumers resolve the same registry across sessions. Requiring a person to edit both a Profile and a Preset would also make a generic preset row incomplete by itself. +The [Codex and Claude Code provider contracts](../feature/2026-08-04-claude-code-and-codex-subagent-backends.md) were first shipped as independently installable packages that a deployment loaded beside the common subagent tool. Agent Presets later became the ordinary owner of one agent's model-visible tools, but a preset cannot safely own these product providers: `ctx.subagents` is a process registry, provider names are unique within the Host, and host consumers resolve the same registry across sessions. Repeated preset composition would therefore contend for the same configured names. Requiring a person to edit both a Profile and a Preset would also make a generic preset row incomplete by itself. -The placement decision must preserve two independent facts. Loading a provider must not start or authenticate a product, while enabling a tool must remain per preset so two sessions can expose different products. A global product switch, a provider instance per agent, or pre-enumerated combination presets would each create a second owner for one of those facts. +The placement decision must preserve two independent facts. Loading a provider must not start or authenticate a product, while granting a tool must remain per preset so two sessions can expose different products. A global product switch, a provider instance per agent, or pre-enumerated combination presets would each create a second owner for one of those facts. ## Decision -Product providers remain process-scoped host-plane registrations. The [production-install exclusion decision](../simplification/2026-08-12-production-dsh-excludes-product-subagent-providers.md) supersedes only this note's former base-bundle installation choice: production `dsh-base` neither depends on nor mounts them. A Profile that opts in installs the selected provider package and mounts it once on the host plane. Loading either plugin only registers a dormant backend; the corresponding Codex or Claude process starts on the first actual delegation call. Agent Presets independently contribute ordinary `dsh-tool-subagent` rows for `subagent_codex` and `subagent_claude_code`, so a preset can expose neither tool, either one, or both without changing the provider registry. +Product providers remain process-scoped host-plane registrations. The [production-install exclusion decision](../simplification/2026-08-12-production-dsh-excludes-product-subagent-providers.md) supersedes only this note's former base-bundle installation choice: production `dsh-base` neither depends on nor mounts them. A Profile that opts in installs the selected provider Bundle; its patch mounts the default instance, and the Profile may mount additional named instances on the host plane. The [named-instance decision](../feature/2026-08-18-product-subagent-named-instances.md) owns each row's registry identity: both products accept multiple unique `providerName` values while preserving `codex` and `claude-code` as their defaults. Loading either plugin only registers a dormant backend; the corresponding Codex or Claude process starts on the first actual delegation call. Agent Presets independently contribute ordinary `dsh-tool-subagent` rows whose `provider` and `toolName` values expose exactly the configured instances needed by one agent without changing the Host registry. -This note continues to own why a mounted product provider belongs on the host plane while its model-facing tool belongs to an Agent Preset. The production-install exclusion decision owns which Profiles install those optional packages. The provider-contract note continues to own each product protocol, result mapping, cancellation, process-tree lifecycle, and evidence tiers. The [Agent Preset architecture](2026-08-03-per-session-agent-presets.md) continues to own the Host/Agent split, preset authoring, and the rule that edits affect only newly composed sessions. +Each provider package owns its directly installable Bundle patch and private product runtime. This note continues to own process-wide Host placement whenever either provider is installed. The provider-contract note continues to own each product protocol, result mapping, cancellation, process-tree lifecycle, and evidence tiers. The [Agent Preset architecture](2026-08-03-per-session-agent-presets.md) continues to own the Host/Agent split, preset authoring, and the rule that edits affect only newly composed sessions. -The providers use products already selected by the host environment. Codex starts `codex` from `PATH`; Claude Code resolves `claude` through the shared subprocess execution world and passes the exact path to the official SDK. Profile loading does not install a product, create product state, probe a version, test authentication, or add product-specific settings. Missing commands and product failures remain local to the attempted delegation. - -Only a Profile that selects the Claude Code provider carries the Claude Agent SDK's optional platform CLI payload. Production still resolves the host `claude`; the SDK payload remains provider-package installation cost rather than the production executable. +Each Bundle delegates executable selection to its package-owned product runtime: the Codex package runs its declared wrapper, while the Claude Code package lets its pinned Agent SDK select the private native executable. Neither provider consults or falls back to a host product command. Profile loading creates no product state, probes no version or authentication, and may supply each mounted Provider instance's deployment configuration, including the product-specific `permissionMode` values owned by the [non-interactive permissions decision](../feature/2026-08-15-product-subagent-noninteractive-permissions.md), without moving those choices into an Agent Preset or model-facing tool. Missing platform payloads and product failures remain local to the attempted delegation. ## Verification -The base bundle test proves production `dsh-base` contains neither product provider dependency nor provider row. The Web composition explicitly mounts both optional providers and covers none, Codex-only, Claude-only, and both tool sets, including generation isolation after an authored preset changes. Package-owned Loader compositions prove the Codex-only and dual-provider opt-in paths register the selected providers without starting a product process. Keyless ACP snapshots pin the model-visible tool schemas for one and both products, while provider tests separately prove native executable resolution, failure, cancellation, and process-tree quiescence. +The base bundle test proves production `dsh-base` contains neither product provider dependency nor provider row. The Web composition installs both optional Bundles and covers none, Codex-only, Claude-only, and both tool sets, including generation isolation after an authored preset changes. Package-owned Loader compositions prove each Bundle default and additional named instances register without starting a product process. Keyless ACP snapshots pin the Codex two-tool roster and the final four-tool combination, while provider tests separately prove private platform-payload selection without host fallback, configuration isolation, failure, cancellation, and process-tree quiescence. ## Alternatives considered -**Keep product providers opt-in at the Profile layer.** This preserves a smaller default dependency closure but requires the user to edit both a Profile and a Preset. The production-install exclusion decision accepts that installation trade-off; this note retains the requirement that any selected provider is mounted once on the host plane rather than inside the preset. +**Keep product providers opt-in at the Profile layer.** This preserves a smaller default dependency closure but requires the user to edit both a Profile and a Preset. The production-install exclusion decision accepts that installation trade-off; this note retains the requirement that selected provider instances are mounted on the host plane rather than inside the preset. **Store global or per-Profile product enable switches.** A process switch competes with the Preset as owner of model-visible tools and cannot express two sessions using different combinations. Availability and authentication are deployment facts, not another persisted product state. -**Mount a provider inside every Agent Preset.** Provider names belong to a process registry, so the second session would collide with the first. Host consumers also need the registry independently of any one agent's lifetime. +**Mount providers inside every Agent Preset.** Provider names belong to a process registry, so repeated session composition would collide on the same configured names. Host consumers also need the registry independently of any one agent's lifetime. **Ship four product-combination presets.** Four identities duplicate complete compositions to represent two independent tool rows. Ordinary rows already express the full matrix without adding roster or maintenance state. ## Consequences -A user installs each selected product provider in a Profile and exposes its tool through the same Agent Preset authoring path as other plugins. Each new session receives exactly the tools its chosen preset contributes. Profiles that do not select a product provider carry no corresponding package or module-loading footprint; loading a selected provider still starts no product process, login, model call, or product home. +A user installs each selected product provider in a Profile, mounts the required named instances, and exposes their tools through the same Agent Preset authoring path as other plugins. Each new session receives exactly the tools its chosen preset contributes. Profiles that do not select a product provider carry no corresponding package or module-loading footprint; loading selected instances still starts no product process, login, model call, or product home. -The Host registry remains the single provider authority and each Preset remains the single model-tool authority. The trade-off is a two-layer opt-in: the Profile owns installation and host-plane registration, while the Preset owns per-agent exposure. Selecting the Claude provider also accepts its current SDK optional-payload installation cost. +The Host registry remains the single provider authority, each Bundle remains the deployment availability authority, and each Preset remains the model-tool authority. This explicit two-gate lifecycle avoids a global enable switch and keeps package removal independent from per-session authoring. diff --git a/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.zh.md b/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.zh.md index fef69e8a2d..b36398be50 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-10-product-subagent-providers-in-shared-host.zh.md @@ -6,36 +6,34 @@ Status: implemented ## 问题 -[Codex 与 Claude Code 提供方约定](../feature/2026-08-04-claude-code-and-codex-subagent-backends.md)最初以可独立安装的包交付,由部署环境在通用 subagent 工具旁加载。Agent Preset 后来成为单个 agent(智能体)的模型可见工具的常规责任方,但 preset 不能安全地拥有这些产品提供方:`ctx.subagents` 是进程级注册表,提供方名称唯一,而宿主消费方会跨会话解析同一个注册表。如果要求用户同时编辑 Profile 和 Preset,也会使通用 preset 行本身不完整。 +[Codex 与 Claude Code 提供方约定](../feature/2026-08-04-claude-code-and-codex-subagent-backends.md)最初以可独立安装的包交付,由部署环境在通用 subagent 工具旁加载。Agent Preset 后来成为单个 agent(智能体)的模型可见工具的常规责任方,但 preset 不能安全地拥有这些产品提供方:`ctx.subagents` 是进程级注册表,提供方名称在 Host 内唯一,而宿主消费方会跨会话解析同一个注册表。因此,重复组装 preset 会争用同一组已配置名称。如果要求用户同时编辑 Profile 和 Preset,也会使通用 preset 配置项本身不完整。 -归属决策必须同时保留两个彼此独立的事实:加载提供方不得启动产品,也不得对产品执行身份验证;而工具是否启用仍须按 preset 决定,这样两个会话才能暴露不同的产品。全局产品开关、按 agent 创建提供方实例或预先枚举的组合 preset,都会为其中一个事实另设第二责任方。 +归属决策必须同时保留两个彼此独立的事实:加载提供方不得启动产品,也不得对产品执行身份验证;而工具授权仍须按 preset 决定,这样两个会话才能暴露不同的产品。全局产品开关、按 agent 创建提供方实例或预先枚举的组合 preset,都会为其中一个事实另设第二责任方。 ## 决策 -产品提供方仍是进程级的 host plane(宿主平面)注册。[生产安装排除决策](../simplification/2026-08-12-production-dsh-excludes-product-subagent-providers.md)只取代本说明原先由 base bundle 安装提供方的选择:生产 `dsh-base` 既不依赖也不挂载它们。选择产品集成的 Profile 会安装目标提供方包,并在 host plane 挂载一次。加载任一插件只会注册一个休眠后端;对应的 Codex 或 Claude 进程直到第一次实际委派调用时才启动。Agent Preset 分别通过普通的 `dsh-tool-subagent` 行贡献 `subagent_codex` 与 `subagent_claude_code`,因此一个 preset 可以不暴露任何工具、只暴露其中一个或同时暴露两者,而无需更改提供方注册表。 +产品提供方仍是进程级的 host plane(宿主平面)注册。[生产安装排除决策](../simplification/2026-08-12-production-dsh-excludes-product-subagent-providers.md)只取代本说明原先由 base bundle 安装提供方的选择:生产 `dsh-base` 既不依赖也不挂载它们。选择产品集成的 Profile 会安装目标提供方 Bundle;其 patch 挂载默认实例,而 Profile 可以在 host plane 挂载更多命名实例。[命名实例决策](../feature/2026-08-18-product-subagent-named-instances.md)负责每个配置项的注册身份:两个产品都接受多个唯一的 `providerName`,同时保留 `codex` 与 `claude-code` 作为默认值。加载任一插件只会注册一个休眠后端;对应的 Codex 或 Claude 进程直到第一次实际委派调用时才启动。Agent Preset 通过普通 `dsh-tool-subagent` 配置项的 `provider` 与 `toolName` 准确公开单个 agent 所需的已配置实例,而无需更改 Host 注册表。 -本说明继续负责解释为什么已经挂载的产品提供方属于 host plane,而面向模型的工具属于 Agent Preset。生产安装排除决策负责哪些 Profile 安装这些可选包。提供方约定说明继续负责每个产品的协议、结果映射、取消、进程树生命周期与证据层级。[Agent Preset 架构](2026-08-03-per-session-agent-presets.md)仍负责宿主与 agent 的划分、preset 创作,以及改动只影响新组装会话的规则。 +每个提供方包都拥有可直接安装的 Bundle patch 与私有产品运行时。本说明继续负责每个已安装提供方的进程级 Host 放置。提供方约定说明继续负责每个产品的协议、结果映射、取消、进程树生命周期与证据层级。[Agent Preset 架构](2026-08-03-per-session-agent-presets.md)继续负责宿主与 agent 的划分、preset 创作,以及改动只影响新组装会话的规则。 -这些提供方使用宿主环境已经选定的产品。Codex 启动 `codex`,该命令从 `PATH` 解析;Claude Code 通过共享的子进程执行世界解析 `claude`,并把确切路径交给官方 SDK。加载 Profile 不会安装产品、创建产品状态、探测版本、测试身份验证,也不会新增产品专属设置。命令缺失和产品故障仍局限于发生问题的那次委派。 - -只有选择 Claude Code 提供方的 Profile 才会携带 Claude Agent SDK 的可选平台 CLI(命令行界面)载荷。生产环境仍解析宿主提供的 `claude`;这份 SDK 载荷是提供方包的安装成本,而不是生产可执行文件。 +每个 Bundle 都把可执行文件选择交给包自有的产品运行时:Codex 包运行自身声明的 wrapper,Claude Code 包则让锁定的 Agent SDK 选择私有原生可执行文件。两个提供方都不会查询或回退宿主产品命令。加载 Profile 不会创建产品状态、探测版本或测试身份验证;它可以提供每个已挂载 Provider 实例的部署配置,包括由[非交互权限决策](../feature/2026-08-15-product-subagent-noninteractive-permissions.md)负责的产品专属 `permissionMode` 值,但不会把这些选择移入 Agent Preset 或面向模型的工具。平台载荷缺失和产品故障仍局限于发生问题的那次委派。 ## 验证 -base bundle 测试证明生产 `dsh-base` 既不包含产品提供方依赖,也不包含提供方配置行。Web 组装显式挂载两个可选提供方,并覆盖不暴露任何工具、仅暴露 Codex、仅暴露 Claude 和同时暴露两者这四种工具集合,也覆盖自行创作的 preset 发生改动后的代际隔离。由包负责的 Loader 组装证明 Codex-only 与双提供方按需启用路径会注册选中的提供方,而不会启动产品进程。无密钥 ACP(Agent Client Protocol)快照固定单个产品与两个产品同时启用时的模型可见工具 schema,提供方测试则另行证明原生可执行文件解析、失败、取消和进程树完全停稳。 +base bundle 测试证明生产 `dsh-base` 既不包含产品提供方依赖,也不包含提供方配置项。Web 组装会安装两个可选 Bundle,并覆盖不暴露任何工具、仅暴露 Codex、仅暴露 Claude 和同时暴露两者这四种工具集合,也覆盖自行创作的 preset 发生改动后的代际隔离。由包负责的 Loader 组装证明每个 Bundle 默认实例与额外命名实例都会完成注册,而不会启动产品进程。无密钥 ACP(Agent Client Protocol)快照固定 Codex 双工具集合与最终四工具组合,提供方测试则另行证明私有平台载荷选择与无宿主回退、配置隔离、失败、取消和进程树完全停稳。 ## 考虑过的替代方案 -**将产品提供方保留为 Profile 层的按需启用项。** 这样可缩小默认依赖闭包,但要求用户同时编辑 Profile 与 Preset。生产安装排除决策接受这项安装取舍;本说明保留的要求是,任何被选中的提供方都在 host plane 挂载一次,而不是放入 preset。 +**将产品提供方保留为 Profile 层的按需启用项。** 这样可缩小默认依赖闭包,但要求用户同时编辑 Profile 与 Preset。生产安装排除决策接受这项安装取舍;本说明保留的要求是,任何被选中的提供方实例都在 host plane 挂载,而不是放入 preset。 **存储全局或按 Profile 配置的产品启用开关。** 进程级开关会与 Preset 争夺模型可见工具的责任归属,也无法表示两个会话使用不同组合。可用性与身份验证属于部署事实,并非另一份需要持久化的产品状态。 -**在每个 Agent Preset 内挂载一个提供方。** 提供方名称属于进程级注册表,因此第二个会话会与第一个冲突。宿主消费方也需要独立于任何单个 agent 的生命周期使用该注册表。 +**在每个 Agent Preset 内挂载提供方。** 提供方名称属于进程级注册表,因此重复组装会话会在同一组已配置名称上发生冲突。宿主消费方也需要独立于任何单个 agent 的生命周期使用该注册表。 **交付四个产品组合 preset。** 四个身份会复制完整组装,只为表示两条独立的工具行。普通行已经能表达完整矩阵,无需新增名单或维护状态。 ## 后果 -用户在 Profile 中安装每个被选中的产品提供方,再通过与其他插件相同的 Agent Preset 创作路径暴露它的工具。每个新会话只会获得其所选 preset 所贡献的工具。没有选择产品提供方的 Profile 不承担对应包或模块的加载开销;加载已选择的提供方仍不会启动产品进程、登录、调用模型或创建产品主目录。 +用户在 Profile 中安装每个被选中的产品提供方,挂载所需命名实例,再通过与其他插件相同的 Agent Preset 创作路径公开这些实例的工具。每个新会话只会获得其所选 preset 所贡献的工具。没有选择产品提供方的 Profile 不承担对应包或模块的加载开销;加载已选择的实例仍不会启动产品进程、登录、调用模型或创建产品主目录。 -宿主注册表仍是提供方的唯一权威,每个 Preset 仍是模型工具的唯一权威。代价是两层按需启用:Profile 负责安装与 host plane 注册,Preset 负责按 agent 暴露。选择 Claude 提供方还会接受当前 SDK 可选载荷的安装成本。 +Host 注册表仍是提供方的唯一权威,每个 Bundle 仍是部署可用性的权威,每个 Preset 仍是模型工具的权威。这个显式的双门生命周期避免全局启用开关,并让包移除与按会话创作保持独立。 diff --git a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.i18n.yaml index d77b2c75c7..ce1925c821 100644 --- a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md -2026-08-12-plugin-owned-settings-surface.md: 3137cfe81ef3cb78a940f085c559ab4a7b62cce3 -2026-08-12-plugin-owned-settings-surface.zh.md: 8dd5e5ccebf1cfb80b55a615f6049dd391943bd7 +2026-08-12-plugin-owned-settings-surface.md: 722e6cfbe890418e8305f89790e76976027d7775 +2026-08-12-plugin-owned-settings-surface.zh.md: 93e5227d5f6a629fd32f5a2fe22e9882c7f7c5ac diff --git a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md index 3137cfe81e..722e6cfbe8 100644 --- a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md +++ b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md @@ -22,7 +22,7 @@ Together the two meant a user-authored plugin was configurable only by hand-edit **`settings.plugin.item` is keyed on the settings namespace.** The slot moved from `list` to `keyed`, the key being the namespace the card edits, following the `tool.call.toolview` precedent where each tool plugin registers its renderer under the tool name. A card declares `key`, not `id`/`order`. The slot is declared by the Plugins section's `configurable` tab, which owns the card list. -**The tab drives dispatch from the served namespaces.** It reads `settings.describe` once, subscribes to the settings-document invalidation and to connection resets, and dispatches one key per served namespace. What renders is the intersection of two ledgers — namespaces a live Host plugin registered, and cards registered under those keys — computed in the tab's controller from the slot ledger (`ctx.slots.entries`, `ctx.slots.subscribe`) and the wire answer. +**The tab drives dispatch from the served namespaces.** It derives the current served set from `ctx.settingsScope.describe()` and follows that shared settings mirror, while its own listener follows the card slot ledger. It dispatches one key per served namespace. What renders is the intersection of two ledgers — namespaces a live Host plugin registered, and cards registered under those keys — computed in the tab's controller from the slot ledger (`ctx.slots.entries`, `ctx.slots.subscribe`) and the mirror answer. The later [settings describe mirror decision](2026-08-17-settings-describe-mirror.md) owns the browser-wide read and invalidation lifecycle. Keying makes absence the signal, and that is what removes the bookkeeping the previous shape needed. A namespace another surface owns (`ui-theme`, `permission`, `llm-*`, `agent-presets`) has no card under its key, so it renders nothing without declaring anything anywhere. A card whose namespace this deployment does not serve is never dispatched, which also fixes the old empty-state defect: the tab counted registered cards, including ones rendering nothing, so a deployment exposing none showed an empty list instead of its empty line. @@ -56,6 +56,6 @@ A plugin distributed outside this repository is configurable from the settings p Deferred, and larger than this change: the redactor returns a `role('secret')` reachable only through a union, intersection, or transform verbatim (its own `TODO(settings-wire-redaction)`), and `schema.toJSON()` carries a secret's default. That gap predates this change, but serving every registered namespace widens its blast radius from schemas audited in this repository to any third-party schema, so the wire should refuse a namespace it cannot prove it can redact. Also deferred: an assembled-composition test of the headline capability — an overlay-mounted fixture plugin whose Host half registers a namespace and whose `dsh.client` half registers a card, asserted end-to-end. The current coverage proves each half separately; the shipped cards' unchanged output cannot prove the new path. -The wire read the section adds is one `settings.describe` beside the per-scope reads the cards already make. Its invalidation is imprecise in one direction: the wire announces document commits and connection resets, not registrations, so a namespace registered after the section's read joins on the next commit or reconnect. +The section and its cards add no `settings.describe` reads: both derive from the browser-wide mirror. Its invalidation is imprecise in one direction: the wire announces document commits and connection resets, not registrations, so a namespace registered after the mirror's current answer joins on the next commit or reconnect. Two frictions remain for an author outside this repository, both recorded in the section's README. The browser half must be a `dsh.client` package built in the client module system's lazy-CJS factory format, and the `clientBundle` preset that emits it lives in `packages/client/tsdown.client.ts` rather than a published package. The bundle-purity gate forbids importing this package's card chrome or staged-form model as values, so such a card reimplements staging and revision fencing. Sharing them would mean either publishing the preset or declaring a child slot inside the card so the section supplies the chrome; neither is built. diff --git a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.zh.md b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.zh.md index 8dd5e5cceb..93e5227d5f 100644 --- a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.zh.md @@ -22,7 +22,7 @@ Status: implemented **`settings.plugin.item` 以 settings 命名空间为键。** 该 slot 从 `list` 改为 `keyed`,键就是卡片所编辑的命名空间,沿用 `tool.call.toolview` 的先例——每个工具插件把自己的渲染器注册在工具名这个键上。卡片声明 `key`,不再声明 `id`/`order`。该 slot 由「插件」分区的 `configurable` 标签页声明,卡片列表归它所有。 -**标签页以被服务的命名空间驱动派发。** 它读取一次 `settings.describe`,订阅 settings 文档失效通知与连接重置,并为每个被服务的命名空间派发一个键。渲染出来的是两份账本的交集——存活 Host 插件注册的命名空间,以及注册在这些键上的卡片——由标签页的 controller 从 slot 账本(`ctx.slots.entries`、`ctx.slots.subscribe`)与协议答复算出。 +**标签页以被服务的命名空间驱动派发。** 它从 `ctx.settingsScope.describe()` 派生当前被服务的集合并跟随该共享 settings 镜像,自身的监听器只跟随卡片 slot 账本;随后为每个被服务的命名空间派发一个键。渲染出来的是两份账本的交集——存活 Host 插件注册的命名空间,以及注册在这些键上的卡片——由标签页的 controller 从 slot 账本(`ctx.slots.entries`、`ctx.slots.subscribe`)与镜像应答算出。后续的 [settings describe 镜像决策](2026-08-17-settings-describe-mirror.md)持有浏览器全局的读取与失效生命周期。 以命名空间为键,让「缺席」本身成为信号,而这正是它消掉旧形态所需簿记的原因。归别的界面所有的命名空间(`ui-theme`、`permission`、`llm-*`、`agent-presets`)在其键上没有卡片,于是什么都不渲染,且无需在任何地方声明任何东西。命名空间未被本部署服务的卡片根本不会被派发,这同时修掉了旧的空态缺陷:标签页数的是已注册卡片,其中包含那些什么都不渲染的,因此一个都不暴露的部署看到的是空列表,而不是它那行空态文案。 @@ -56,6 +56,6 @@ Status: implemented 以下延后,且都大于本次改动:脱敏器对只能经由 union、intersection 或 transform 抵达的 `role('secret')` 原样返回(其自身的 `TODO(settings-wire-redaction)`),而 `schema.toJSON()` 会携带 secret 的默认值。该缺口早于本次改动,但服务每一个已注册命名空间,把它的影响面从本仓库内经审计的 schema 扩大到任意第三方 schema,因此协议应当拒绝服务它无法证明可安全脱敏的命名空间。同样延后的还有:对本次头号能力的组装态测试——用 overlay 挂载一个 fixture 插件(Host 半注册命名空间、`dsh.client` 半注册卡片)并在端到端断言。当前覆盖分别证明了两个半侧;已发卡片输出未变这一点,证明不了新路径。 -分区新增的协议读取是一次 `settings.describe`,与卡片各自已有的 per-scope 读取并列。它的失效通知在一个方向上不精确:协议通告的是文档提交与连接重置,而非注册行为,因此在分区读取之后才被注册的命名空间,要等下一次提交或重连才会加入。 +分区与其中的卡片都不再新增 `settings.describe` 读取:两者都从浏览器全局的镜像派生。它的失效通知在一个方向上不精确:协议通告的是文档提交与连接重置,而非注册行为,因此在镜像当前应答之后才被注册的命名空间,要等下一次提交或重连才会加入。 对仓库之外的作者仍留有两处摩擦,均记在该分区的 README 里。浏览器半侧必须是按客户端模块系统的 lazy-CJS factory 格式构建的 `dsh.client` 包,而产出它的 `clientBundle` 预设位于 `packages/client/tsdown.client.ts`,并非已发布的包。bundle 纯净度门禁禁止以值的形式导入本包的卡片外观与暂存表单模型,因此这样的卡片要重新实现暂存与 revision 设栅。要共享它们,要么发布该预设,要么在卡片内部声明一层子 slot 让分区提供外观;两者都尚未构建。 diff --git a/.agents/notes/implemented/simplification/2026-08-11-remove-empty-experimental-package-group.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.i18n.yaml similarity index 52% rename from .agents/notes/implemented/simplification/2026-08-11-remove-empty-experimental-package-group.i18n.yaml rename to .agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.i18n.yaml index 945a68054c..35b8cb3aa3 100644 --- a/.agents/notes/implemented/simplification/2026-08-11-remove-empty-experimental-package-group.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-08-11-remove-empty-experimental-package-group.md -2026-08-11-remove-empty-experimental-package-group.md: e5e81e3e3763f216921b3f3b74709b64be3dee37 -2026-08-11-remove-empty-experimental-package-group.zh.md: d44d0daaf346a5fea317f8c8c6a23f26eaa3cec0 +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.md +2026-08-17-settings-describe-mirror.md: a3774699ff328a44aed192a16dea0fa19d03c83c +2026-08-17-settings-describe-mirror.zh.md: c57f5630b4bee0cd77a29a6f5458cb439c7f0585 diff --git a/.agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.md b/.agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.md new file mode 100644 index 0000000000..a3774699ff --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.md @@ -0,0 +1,34 @@ +# Agent Note: Settings describe mirror + +Status: implemented + +English | [中文](2026-08-17-settings-describe-mirror.zh.md) + +## Problem + +A cold web boot issued `settings.describe` fifteen times inside ~200ms, and the count grew by two with every client plugin that owned a preference. Two mechanisms stacked: `SettingsScopeBinder.bind()` started a full-document read per bound scope (six scopes in the product composition, plus the plugin-directory tab, the welcome gate, and the models onboarding join), and `onConnected` emits `connection/reset` on the FIRST connection too, so every one of those readers immediately re-read the answer it had fetched milliseconds earlier. Each reader also carried its own invalidation subscriptions and its own `refreshIfLoaded`-style guard, and fifteen independent reads could in principle land on fifteen different document revisions. + +## Decision + +**One reader, many derivations.** `dsh-client-ui-settings` owns `SettingsDescribeMirror`, the single `settings.describe` reader in the browser: one snapshot store holding the whole answer, refreshed by the owning plugin's two subscriptions (`settings/document-updated`, `connection/reset`). Concurrent `load()` calls fold into the in-flight read plus at most one rerun. The in-flight slot owns a run before its loading publication can synchronously reenter `load()`, then clears inside the run's own try/finally in the same synchronous segment that observes the rerun flag; a `.finally()` on the returned promise would run one microtask later and let a refresh landing in that gap mark a rerun nobody reads. + +`bind()` still returns the unchanged `SettingsScope` face, but the controller is now a selector over the mirror: no read path of its own, the same decode rules, and the write queue kept. A committed write folds its answered view back into the mirror (`acceptView`), so sibling scopes see the new revision with no re-read; the fold invalidates any older in-flight answer, and a write before the first held document reruns that read instead of publishing a partial document. A failed latest write triggers one mirror recovery read. Cross-namespace surfaces — the plugin-directory tab, the permission row (its dynamic enum lives in the namespace schema, which scopes deliberately do not carry), the models join, the agent-preset row's writability, and `hasDocument` — consume `ctx.settingsScope.describe()`, the shared read/fold face (`getSnapshot`/`subscribe`/`ensure`/`acceptView`). + +This decision updates the browser read and invalidation mechanics recorded by [Host-backed Web preferences](../bug-fix/2026-08-06-host-backed-web-preferences.md) and [plugin-owned settings surface](2026-08-12-plugin-owned-settings-surface.md), while preserving their preference-ownership and namespace-exposure decisions. It also replaces the direct settings-read description in [official DeepSeek first-run credential setup](../feature/2026-07-30-deepseek-onboarding-credential-setup.md); that join now derives its settings half from this mirror. + +The cold-boot budget is pinned at two reads by `apps/web/tests/startup-rpc-budget.e2e.ts`: the mirror's eager bind-time read, plus the first-connection reset read, which is kept deliberately — it closes the window where a document commit lands between the eager HTTP read and the SSE subscription and its invalidation is lost. The plan's original target of one read is unreachable without either accepting that lost-invalidation window or delaying the first read until after the SSE stream opens. + +## Alternatives considered + +- **Single-flight sharing inside `bind()` only** — deduplicates the concurrent bursts but keeps N direct readers, N subscription sets, and the revision skew; readers outside the binder (welcome, models, tab, permission) gain nothing. Rejected as treating the symptom. +- **Boot-payload embedding** (host inlines the describe answer into the page boot) — saves the first read but adds a second acquisition path with its own staleness rules on top of the mirror it would still need. Deferred; it composes with the mirror if ever wanted. +- **Per-namespace `settings.describe(ns)`** — shrinks each answer but keeps one read per consumer, so the fan-out and the growth rate stay. Rejected. +- **One read (no first-reset re-read)** — reachable only by accepting the lost-invalidation window between the eager HTTP read and the SSE subscription, or by delaying the first read until the stream opens; both trade correctness or first-paint freshness for one loopback request. Rejected in favor of the pinned two. + +## Consequences + +- Startup `settings.describe` went 15 → 2, and a new preference-owning plugin adds zero reads. +- Every derived surface shows the same document revision at any moment; the per-reader guards (`refreshWelcomeIfLoaded`, `refreshPermissionIfLoaded`, `refreshDocumentIfLoaded`) and their subscriptions are gone. +- The mirror refreshes on every document commit regardless of namespace, so an external settings edit now costs one background read even while no settings surface is open — the price of surfaces that open already fresh. The per-namespace `ns !== spec.namespace` filters are gone with the per-scope subscriptions. +- `credentials.describe` (3 startup calls), `agentPreset.list` (2), and `llm.providers` are separate sources and stay direct; the same mirror pattern fits them if they ever need it. +- A new direct `settings.describe` caller in client code is a budget regression; the e2e's failure message says to grep for callers outside `ui-settings`. diff --git a/.agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.zh.md b/.agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.zh.md new file mode 100644 index 0000000000..c57f5630b4 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-08-17-settings-describe-mirror.zh.md @@ -0,0 +1,34 @@ +# Agent Note:Settings describe 镜像 + +Status: implemented + +[English](2026-08-17-settings-describe-mirror.md) | 中文 + +## 问题 + +一次冷启动的 web boot 在约 200ms 内发出十五次 `settings.describe`,且每新增一个持有偏好设置的客户端插件,该计数再加二。两个机制叠加:`SettingsScopeBinder.bind()` 为每个绑定的 scope 启动一次全量文档读取(产品组合中有六个 scope,外加插件目录 tab、welcome 门与 models onboarding join),而 `onConnected` 在**首次**连接时同样发出 `connection/reset`,于是上述每个读取方都立即重读了几毫秒前刚取到的应答。每个读取方还各自持有失效订阅与各自的 `refreshIfLoaded` 式防护,且十五次独立读取原则上可能落在十五个不同的文档 revision 上。 + +## 决定 + +**一个读取方,多个派生面。**`dsh-client-ui-settings` 持有 `SettingsDescribeMirror`——浏览器中唯一的 `settings.describe` 读取方:一个持有完整应答的快照 store,由所属插件的两个订阅(`settings/document-updated`、`connection/reset`)负责刷新。并发的 `load()` 调用折叠进在飞读取加至多一次尾随重读。在飞槽位会在 loading 发布同步重入 `load()` 之前先取得 run 的所有权,随后在 run 自身 try/finally 内、与读取 rerun 标志相同的同步段中清空;若把清理挂在返回 promise 的 `.finally()` 上,它要晚一个微任务执行,落入该间隙的刷新会标记一个无人读取的 rerun。 + +`bind()` 返回的 `SettingsScope` 面保持不变,但 controller 现在是镜像上的 selector:自身没有读路径,decode 规则不变,写队列保留。提交成功的写入把应答的 view 折回镜像(`acceptView`),兄弟 scope 无需重读即可看到新 revision;这次折叠会废弃更早发出的在飞应答,而首次完整文档尚未建立时到达的写入会让该读取重跑,不会把单个 namespace 发布成残缺文档。失败的最新写入触发一次镜像恢复读取。跨命名空间的表面——插件目录 tab、permission 行(其动态枚举位于命名空间 schema 中,而 scope 有意不携带 schema)、models join、agent-preset 行的可写性、以及 `hasDocument`——消费 `ctx.settingsScope.describe()` 提供的共享读/折叠面(`getSnapshot`/`subscribe`/`ensure`/`acceptView`)。 + +本决策更新了[通过 Host settings 持久化 Web 用户偏好](../bug-fix/2026-08-06-host-backed-web-preferences.md)和[由插件自己拥有的设置表层](2026-08-12-plugin-owned-settings-surface.md)所记录的浏览器读取与失效机制,同时保留其中关于偏好所有权与命名空间暴露的决策。它也取代了 [DeepSeek 官方首次使用凭据配置](../feature/2026-07-30-deepseek-onboarding-credential-setup.md)中的设置直读描述;该联接的 settings 部分现在从本镜像派生。 + +冷启动预算由 `apps/web/tests/startup-rpc-budget.e2e.ts` 钉在两次读取:镜像在绑定时的急切读取,加上首连 reset 触发的读取——后者是有意保留的:它关闭了「文档提交落在急切 HTTP 读取与 SSE 订阅之间、其失效通知丢失」的窗口。方案最初的一次读取目标,若不接受该失效丢失窗口、或不把首次读取推迟到 SSE 流建立之后,无法达成。 + +## 考虑过的备选 + +- **仅在 `bind()` 内做 single-flight 共享**——能去重并发风暴,但仍保留 N 个直连读取方、N 套订阅以及 revision 偏差;binder 之外的读取方(welcome、models、tab、permission)毫无受益。以治标为由否决。 +- **boot 载荷内嵌**(宿主把 describe 应答内联进页面 boot)——省下首次读取,却在镜像仍然需要的前提下增加第二条带自身陈旧规则的取数路径。推迟;若将来需要,它可与镜像叠加。 +- **按命名空间的 `settings.describe(ns)`**——缩小单次应答,但每个消费者仍各读一次,扇出与增长率原样保留。否决。 +- **一次读取(去掉首连 reset 重读)**——只有接受「急切 HTTP 读取与 SSE 订阅之间的失效丢失窗口」、或把首次读取推迟到流建立之后才可达成;两者都在用正确性或首屏新鲜度换一次环回请求。否决,保留钉住的两次。 + +## 后果 + +- 启动期 `settings.describe` 从 15 次降到 2 次,新增持有偏好设置的插件带来零次新增读取。 +- 任一时刻每个派生面看到的都是同一份文档 revision;各读取方的防护(`refreshWelcomeIfLoaded`、`refreshPermissionIfLoaded`、`refreshDocumentIfLoaded`)及其订阅随之消失。 +- 镜像对任何命名空间的文档提交都会刷新,因此在没有任何设置表面打开时,一次外部设置编辑现在也花费一次后台读取——这是「表面打开即新鲜」的代价。随着各 scope 订阅的删除,按命名空间的 `ns !== spec.namespace` 过滤一并消失。 +- `credentials.describe`(启动 3 次)、`agentPreset.list`(2 次)与 `llm.providers` 是另外的数据源,保持直连;若将来需要,同一镜像模式对它们同样适用。 +- 客户端代码中新增直连 `settings.describe` 调用即是预算回归;e2e 的失败信息会提示在 `ui-settings` 之外 grep 调用方。 diff --git a/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.i18n.yaml new file mode 100644 index 0000000000..1b56228555 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.md +2026-08-18-experimental-agent-teams-packages.md: cec73be48a5cde25fae570587d2ecd17a4a87d01 +2026-08-18-experimental-agent-teams-packages.zh.md: 71b702daa8694fddec6e2a0972704f19955cb509 diff --git a/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.md b/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.md new file mode 100644 index 0000000000..cec73be48a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.md @@ -0,0 +1,37 @@ +# Agent Note: Incubate Agent Teams as private experimental packages + +Status: implemented + +English | [中文](2026-08-18-experimental-agent-teams-packages.zh.md) + +## Problem + +Agent Teams needs the real Session log, subagent lifecycle, tools, examples, snapshots, and repository checks while its service and tool contracts continue to change. Placing those packages in a product-role group makes them members of the dsh release family and gives them the same publication expectation as stable packages. + +An experimental directory without a current package previously imposed placement, dependency, promotion, and release rules on no consumer. Agent Teams supplies the concrete consumer, but the directory needs mechanical release exclusion and dependency isolation rather than a documentation-only status. + +## Decision + +`packages/experimental/team` and `packages/experimental/tool-team` are private workspace packages. Their npm names remain `@deepseek-ai/dsh-team` and `@deepseek-ai/dsh-tool-team`, so promotion changes paths and release metadata without renaming imports. + +The dsh release family and local baseline publisher exclude every manifest below `packages/experimental/`. Workspace constraints require each experimental package to set `private: true` and omit `publishConfig`. The same top-level check rejects `dependencies`, `optionalDependencies`, and `peerDependencies` from release packages, release apps, or the Python runtime to an experimental package. Experimental packages may depend on release packages and each other; tests may use them through `devDependencies`, and examples may load them explicitly. + +The generic caller-reserved continuable child identity and selective direct-child drain remain in the stable Subagent service. They own Subagent identity and Activation lifecycle without importing or naming Agent Teams; the experimental Team service consumes them in the permitted direction. + +Experimental status changes publication and compatibility expectations only. The packages retain the repository's ordinary documentation, invariant, lifecycle, security, unit, real-composition, and snapshot requirements. Promotion requires review of the public contracts, limitations, test evidence, release payload, runtime dependents, and a named owner accepting stable-package obligations. + +## Alternatives considered + +**Keep Agent Teams in a product-role group and describe it as opt-in.** Opt-in composition controls model behavior but does not exclude packages from publication or prevent stable packages from taking runtime dependencies on them. + +**Reserve an empty experimental group.** A directory without a current package has no owner or release mechanism to test. The group exists only while concrete packages need its enforced treatment. + +**Move the Subagent prerequisites into the experimental directory.** Child identity allocation and Activation teardown belong to the Subagent owner and contain no Team-specific contract. Moving or duplicating them would invert the dependency or split one lifecycle across packages. + +**Publish experimental packages under different npm names.** Experimental suffixes would make promotion rename every import and configuration row without strengthening release exclusion; private manifests and release-family filtering enforce the actual requirement. + +## Consequences + +Agent Teams can use the full repository graph and quality checks without entering official tarballs or becoming a supported runtime dependency. A release package cannot expose Team until the Team packages are promoted, so CLI and Web experiments use explicit example or experimental compositions instead of the shipped base bundles. + +The product-role grouping is less direct while the packages incubate, and promotion creates path churn. Keeping npm names stable limits that churn to repository paths, metadata, documentation, and composition. diff --git a/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.zh.md b/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.zh.md new file mode 100644 index 0000000000..71b702daa8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 将 Agent Teams 作为私有实验性包孵化 + +Status: implemented + +[English](2026-08-18-experimental-agent-teams-packages.md) | 中文 + +## 问题 + +Agent Teams 的服务与工具约定仍在变化,但它需要使用真实 Session 日志、subagent 生命周期、工具、示例、快照和仓库检查。把这些包放在产品职责组会使其成为 dsh 发布系列成员,并获得与稳定包相同的发布预期。 + +没有实际包的 experimental 目录曾经让没有消费方的放置、依赖、promotion 和发布规则长期存在。Agent Teams 提供了具体消费方,但该目录需要机械强制的发布排除与依赖隔离,不能只用文档标记状态。 + +## 决策 + +`packages/experimental/team` 与 `packages/experimental/tool-team` 是私有 workspace 包。其 npm 名仍为 `@deepseek-ai/dsh-team` 与 `@deepseek-ai/dsh-tool-team`,因此 promotion 只需修改路径与发布元数据,无需重命名 import。 + +dsh 发布系列与本地 baseline 发布器均排除 `packages/experimental/` 下的所有 manifest。workspace 约束要求每个实验性包设置 `private: true` 并省略 `publishConfig`。同一个顶层检查会拒绝发布包、发布 app 或 Python runtime 通过 `dependencies`、`optionalDependencies` 或 `peerDependencies` 依赖实验性包。实验性包可以依赖发布包和其他实验性包;测试可以通过 `devDependencies` 使用它们,示例可以显式加载它们。 + +通用的调用方预留 continuable child 身份和精确 direct-child drain 仍属于稳定 Subagent 服务。它们负责 Subagent 身份与 Activation 生命周期,不 import 或命名 Agent Teams;实验性 Team 服务沿允许的方向消费这些能力。 + +实验性状态只改变发布与兼容性预期。这些包仍须满足仓库的一般文档、不变式、生命周期、安全、单元测试、真实组合测试和快照要求。promotion 前必须评审公开约定、限制、测试证据、发布 payload、运行时依赖方,并由一名具名 owner 接受稳定包义务。 + +## 曾考虑的替代方案 + +**把 Agent Teams 留在产品职责组,并标为显式启用。** 显式启用的组合可以控制模型行为,但不会阻止包发布,也不能阻止稳定包对其建立运行时依赖。 + +**预留空的 experimental 组。** 没有实际包的目录没有 owner,也没有可供测试的发布机制。只有具体包需要这套强制处理时,该组才存在。 + +**把 Subagent 前置能力移入 experimental 目录。** child 身份分配与 Activation teardown 属于 Subagent owner,且不包含 Team 专用约定。移动或复制这些能力会反转依赖方向,或把同一个生命周期拆到多个包中。 + +**使用不同的 npm 名发布实验性包。** experimental 后缀会让 promotion 重命名所有 import 与配置项,却不能加强发布排除;私有 manifest 与发布系列过滤已经强制执行实际要求。 + +## 后果 + +Agent Teams 可以使用完整仓库依赖图与质量检查,而不进入正式 tarball,也不会成为受支持的运行时依赖。在 Team 包 promotion 前,发布包不能暴露 Team,因此 CLI 和 Web 实验使用显式示例或实验性组合,而不是已发布的基础组合包。 + +孵化期间的产品职责分组不够直接,promotion 也会产生路径改动。保持 npm 名稳定后,改动范围仅包括仓库路径、元数据、文档和组合。 diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.i18n.yaml index 87101e680a..10e09d4a49 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md -2026-08-06-host-backed-web-preferences.md: 5d90f2be7c8b4030e9bdc00eed2769491ec009e5 -2026-08-06-host-backed-web-preferences.zh.md: c861c45bff299e06841165a2b36d0781e8f54d99 +2026-08-06-host-backed-web-preferences.md: 2e33d05417bf6c347a57b5c0b6c7281ff1392b5b +2026-08-06-host-backed-web-preferences.zh.md: 1d3518bb33d334d89408916a5f5210a45b938a01 diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md index 5d90f2be7c..2e33d05417 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md +++ b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md @@ -12,9 +12,9 @@ The first theme implementation moved only Appearance to Host settings but awaite ## Decision -The owning Host halves register three schemas: optional `locale.preference` (`zh` or `en`, where absence delegates to the browser), `ui-theme.preference` (`light`, `dark`, or `system`, default `system`), and `ui-conversation.busyEnter` (`queue` or `steer`, default `queue`). The local settings provider stores explicit choices in `$DSH_HOME/settings.yaml`, which resolves to `~/.dsh/settings.yaml` under the default home. The API proxy explicitly exposes all three namespaces beside the other Web settings; registration alone never crosses that configuration boundary. +The owning Host halves register three schemas: optional `locale.preference` (`zh` or `en`, where absence delegates to the browser), `ui-theme.preference` (`light`, `dark`, or `system`, default `system`), and `ui-conversation.busyEnter` (`queue` or `steer`, default `queue`). The local settings provider stores explicit choices in `$DSH_HOME/settings.yaml`, which resolves to `~/.dsh/settings.yaml` under the default home. The API proxy serves every registered namespace to a loopback client; field roles still redact secrets. -`dsh-client-ui-settings` provides `ctx.settingsScope.bind(spec)`, which owns one lifecycle per namespace as the browser mirror of the Host-side settings owner seam. It installs `settings/document-updated` and `connection/reset` listeners before starting a background initial read, so no settings transport can block plugin activation and an invalidation cannot fall into a read-before-subscribe gap, and it publishes a snapshot store (status, section value, revision, writability, host/memory mode) the domain service subscribes to. The default decoder validates each incoming section against the namespace's own serialized wire schema, rehydrated through the colocated `ctx.settingsSchema` service, so domains carry no hand-written wire guards. Domain services take the scope as an ordinary constructor collaborator, publish their provisional defaults immediately—browser-derived locale, system theme, and Queue—then adopt an accepted Host section without writing it back; a service constructed without a scope (standalone dictionary or policy fixtures) simply stays process-local. +`dsh-client-ui-settings` owns one browser-wide settings describe mirror and provides `ctx.settingsScope.bind(spec)` as a per-namespace selector over it. The mirror installs `settings/document-updated` and `connection/reset` listeners before starting its background read, so no settings transport can block plugin activation and an invalidation cannot fall into a read-before-subscribe gap. Each bound scope publishes a snapshot store (status, section value, revision, writability, host/memory mode) the domain service subscribes to, without adding a wire read or listener of its own. The default decoder validates each incoming section against the namespace's own serialized wire schema, rehydrated through the colocated `ctx.settingsSchema` service, so domains carry no hand-written wire guards. Domain services take the scope as an ordinary constructor collaborator, publish their provisional defaults immediately—browser-derived locale, system theme, and Queue—then adopt an accepted Host section without writing it back; a service constructed without a scope (standalone dictionary or policy fixtures) simply stays process-local. The shared read and invalidation lifecycle is specified by the later [settings describe mirror decision](../architecture/2026-08-17-settings-describe-mirror.md). User changes update the live service synchronously and queue a `settings.mutate` path operation through `scope.set`. The scope serializes gestures, sends the latest known namespace revision as `expectedRevision`, records every successful revision, and lets only the latest write settlement republish live state. A rejected or failed latest write reloads Host state. Disposal rejects new work, skips queued operations, suppresses publication by the in-flight operation, and waits for that operation to settle before the plugin reaches quiescence. diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md index c861c45bff..1d3518bb33 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md @@ -12,9 +12,9 @@ Web 的 Appearance、Language 和繁忙态 Enter 偏好原本存在浏览器 `lo ## 决策 -各领域所属的 Host half 注册三份 schema:可选的 `locale.preference`(`zh` 或 `en`,缺失时交由浏览器决定)、`ui-theme.preference`(`light`、`dark` 或 `system`,默认为 `system`),以及 `ui-conversation.busyEnter`(`queue` 或 `steer`,默认为 `queue`)。本地 settings 提供方将显式选择存入 `$DSH_HOME/settings.yaml`,在使用默认 home 时,该路径解析为 `~/.dsh/settings.yaml`。API 代理会显式暴露这三个 namespace,与其他 Web settings 并列;仅注册它们,绝不会跨越该配置边界。 +各领域所属的 Host half 注册三份 schema:可选的 `locale.preference`(`zh` 或 `en`,缺失时交由浏览器决定)、`ui-theme.preference`(`light`、`dark` 或 `system`,默认为 `system`),以及 `ui-conversation.busyEnter`(`queue` 或 `steer`,默认为 `queue`)。本地 settings 提供方将显式选择存入 `$DSH_HOME/settings.yaml`,在使用默认 home 时,该路径解析为 `~/.dsh/settings.yaml`。API 代理会向回环客户端服务每一个已注册的 namespace;字段角色仍会脱敏机密值。 -`dsh-client-ui-settings` 提供 `ctx.settingsScope.bind(spec)`,为每个 namespace 持有一份生命周期,作为 Host 侧 settings owner seam 的浏览器镜像。它在开始后台初始读取之前安装 `settings/document-updated` 和 `connection/reset` 监听器,因此任何 settings 传输都不会阻塞插件激活,失效通知也不会掉入先读取、后订阅的空档;它还会发布一个供领域服务订阅的快照 store(状态、分节值、revision、可写性、host/内存模式)。默认解码器会对照该 namespace 自身的序列化 wire schema(经同包的 `ctx.settingsSchema` 服务还原)校验每个传入分节,因此各领域无需携带手写的 wire 校验器。领域服务把 scope 当作普通的构造函数协作者接收,立即发布各自的暂定默认值:由浏览器派生的 locale、系统主题和 Queue;随后采纳已获接受的 Host 分节,但不将其写回;不带 scope 构造的服务——独立词典或政策 fixture(测试前置数据)——则仅停留在进程本地。 +`dsh-client-ui-settings` 持有一个浏览器全局的 settings describe 镜像,并提供 `ctx.settingsScope.bind(spec)` 作为该镜像上的逐 namespace selector。镜像在开始后台读取之前安装 `settings/document-updated` 和 `connection/reset` 监听器,因此任何 settings 传输都不会阻塞插件激活,失效通知也不会掉入先读取、后订阅的空档。每个绑定的 scope 会发布一个供领域服务订阅的快照 store(状态、分节值、revision、可写性、host/内存模式),自身不再增加协议读取或监听器。默认解码器会对照该 namespace 自身的序列化 wire schema(经同包的 `ctx.settingsSchema` 服务还原)校验每个传入分节,因此各领域无需携带手写的 wire 校验器。领域服务把 scope 当作普通的构造函数协作者接收,立即发布各自的暂定默认值:由浏览器派生的 locale、系统主题和 Queue;随后采纳已获接受的 Host 分节,但不将其写回;不带 scope 构造的服务——独立词典或政策 fixture(测试前置数据)——则仅停留在进程本地。共享读取与失效生命周期由后续的 [settings describe 镜像决策](../architecture/2026-08-17-settings-describe-mirror.md)规定。 用户变更会同步更新实时服务,并经 `scope.set` 将一项 `settings.mutate` 路径操作排入队列。scope 会串行处理手势,以最新已知 namespace revision 作为 `expectedRevision` 发送,记录每次成功写入的 revision,并且只允许最新写入的结算结果重新发布实时状态。最新写入被拒或失败时,scope 会重新加载 Host 状态。插件释放会拒绝新工作、跳过已排队操作、抑制运行中操作发布状态,并等待该操作结算后才让插件达到完全停稳。 diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.i18n.yaml new file mode 100644 index 0000000000..61134679f7 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.md +2026-08-06-plan-narrow-viewport-regression.md: 945d014e0c51cbaf4080e72f50ee60763d851698 +2026-08-06-plan-narrow-viewport-regression.zh.md: 37060129364c65b02cc1729331fc7334797863db diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.md b/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.md new file mode 100644 index 0000000000..945d014e0c --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.md @@ -0,0 +1,33 @@ +# Agent Note: narrow-viewport plan chip click-area regression test + +Status: implemented + +English | [中文](2026-08-06-plan-narrow-viewport-regression.zh.md) + +## Problem + +The external report dsh-external/issues#107 (clustered internally as deepseek-harness#1406) measured that at viewports between 760px and 850px the plan control and the model selector overlapped, with the model selector covering the plan control's click area so plan mode could not be left by mouse at 800×720. Its acceptance list asked for a browser regression test asserting that the plan center hit-tests to the plan button. + +The browser regression test reproduced the report on current master: at 800×720 the plan chip and the model trigger overlapped by 36.9px and the chip's center hit-tested to the trigger's label. The composer control row is `display: flex; justify-content: space-between` with `.trailing { flex: none }`: when the combined control width exceeds the card, the shrinking `.tools` group keeps its flow children inside its `min-width: 0` box, so the chip — the last flow child before the overflow — is painted over the trailing group. The plan-control form changed since the report (select → chip, `c20b988166`/`fe91919346`) and the row gained adaptive behavior (`c8c75ec891`, [web-composer-shared-width-axis](../feature/2026-08-04-web-composer-shared-width-axis.md)), but the row had no wrap, so the overlap survived both. + +## Decision + +The row wraps instead of shrinking its left group into the right group's area: `.row { flex-wrap: wrap }` plus `margin-left: auto` on `.trailing`, which re-anchors the trailing group (model + send) to the right edge of its wrapped line while `space-between` already pins it right on a single line. Wrapping is the acceptance's "wrap, fold, or re-arrange controls when space runs out" option, keeps every control at full width (no label folding that would hide the model name or the Plan wordmark), and holds at every viewport width by construction instead of at a calibrated container-query threshold. + +Add `apps/web/tests/plan-control-row.e2e.ts`: enter plan mode with the real `/plan` command (no argument — the command handler commits plan/mode active without a model round, the lifecycle-chrome precedent), so the test needs no model call in any mode and no API key in replay/refresh; a providers-only fixture mounts the model catalog without a script to consume. The file joins the host-plane e2e pairing like every sibling: excluded from the client graph in `apps/web/tsconfig.json` (it imports host-plane types) AND included in the host aggregate in `tsconfig.host.json`, so exactly one TypeScript program owns it — the pairing that also gives the lint type service its program. + +The geometry golden records stable facts — viewport membership on both axes and disjoint click areas — never absolute coordinates, whose pixel values depend on installed fonts and differ between macOS and Linux. The behavior assertions implement the acceptance directly: the click areas are disjoint, the click at the chip's center (Playwright's actionability check) leaves plan mode through the real command channel (`/plan off` via `commands.execute`), and the last `plan/mode` event in the session log flips inactive. + +## Alternatives considered + +**Seed a cold session (composer-tab-geometry pattern).** Rejected: the exit path executes `/plan off` through `commands.execute`, which needs the live agent a cold seeded session does not have; `connectFreshWorkspace` keeps one, matching the product's user path. + +**Pin absolute bounding boxes in the golden.** Rejected: chip and trigger widths depend on the installed fonts, so absolute coordinates would churn across platforms without a behavior change. + +**Reuse the plan-review fixture shape (exit_plan_mode review takeover).** Rejected: the takeover replaces the composer's control row, which is the surface under test. + +**Container-query label folding for the chip and/or the model trigger.** Rejected for the fix: two packages (ui-plan, ui-model) would need calibrated thresholds and the chip's own icon-only fold still leaves ~7px of overlap at the reported viewport unless the trigger folds too. Wrapping is one rule in one package and holds at every width. + +## Consequences + +Any future change to the control row layout — fonts, gaps, media or container queries — that re-introduces overlap or moves the chip out of the viewport on either axis fails this test. The test needs no API key in replay/refresh modes: plan mode toggles through the command handler without a model round, and a providers-only replay fixture (no recorded script, consumption check skipped) mounts the model directory so the trigger renders its real long label — the width that made the reported overlap measurable; the test asserts that label before measuring. The golden is compared in replay and record modes and rewritten in refresh mode. diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.zh.md b/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.zh.md new file mode 100644 index 0000000000..3706012936 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-06-plan-narrow-viewport-regression.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 窄视口下 Plan chip 点击区域回归测试 + +Status: implemented + +[English](2026-08-06-plan-narrow-viewport-regression.md) | 中文 + +## 问题 + +外部报告 dsh-external/issues#107(内部聚类为 deepseek-harness#1406)测得视口宽度在 760px 到 850px 之间时 Plan 控件与模型选择器发生重叠,模型选择器覆盖 Plan 控件的点击区域,导致在 800×720 下无法用鼠标退出 Plan 模式。其验收清单要求增加浏览器回归测试,断言 Plan 中心命中 Plan 按钮。 + +浏览器回归测试在当前 master 上复现了报告:800×720 下 Plan chip 与模型 trigger 重叠 36.9px,chip 中心命中 trigger 的 label。composer 控制行是 `display: flex; justify-content: space-between` 且 `.trailing { flex: none }`:当控件总宽超过卡片时,可收缩的 `.tools` 组把流内子项留在 `min-width: 0` 的盒内,于是 chip——溢出前最后一个流内子项——被绘制到 trailing 组上方。报告以来 Plan 控件形态已变(select → chip,`c20b988166`/`fe91919346`),控制行也获得过自适应能力(`c8c75ec891`,[web-composer-shared-width-axis](../feature/2026-08-04-web-composer-shared-width-axis.md)),但该行没有换行,重叠在两次重构后依然存在。 + +## 决策 + +控制行换行而不是把左侧组收缩进右侧组的区域:`.row { flex-wrap: wrap }` 加上 `.trailing` 的 `margin-left: auto`——后者把 trailing 组(模型选择 + 发送)重新锚定到换行后的右缘,单行时 `space-between` 已把它钉在右侧。换行是验收中"空间不足时允许换行、折叠或重新排列控件"的选项,保持每个控件全宽(不做会隐藏模型名或 Plan 字样的 label 折叠),并且按构造在所有视口宽度下成立,而非依赖标定的容器查询阈值。 + +新增 `apps/web/tests/plan-control-row.e2e.ts`:通过真实 `/plan` 命令(无参数——命令 handler 不经模型回合即提交 plan/mode active,lifecycle-chrome 先例)进入 Plan 模式,因此测试在任何模式下都无需模型调用,仅在 replay/refresh 下无需 API key;providers-only fixture 挂载模型目录而无脚本可消费。该文件与所有同类 host 平面 e2e 一样采用成对登记:在 `apps/web/tsconfig.json` 的 exclude 列表(它导入 host 平面类型,client 图绝不编译它),同时在 `tsconfig.host.json` 的 host 聚合 include 中——恰好一个 TypeScript 程序拥有它,这也是 lint 类型服务获得程序的配对方式。 + +几何 golden 记录稳定事实——两个轴上的视口内位置与点击区域不相交——绝不记录绝对坐标,其像素值依赖安装字体且在 macOS 与 Linux 间不同。行为断言直接实现验收:点击区域不相交、点击 chip 中心(Playwright 的可操作性检查)经真实命令通道(`commands.execute` 执行 `/plan off`)退出 Plan 模式,且会话日志中最后一条 `plan/mode` 事件翻转为 inactive。 + +## 备选方案 + +**冷会话 seed(composer-tab-geometry 模式)。** 否决:退出路径经 `commands.execute` 执行 `/plan off`,需要 live agent,而冷 seed 会话没有;`connectFreshWorkspace` 保留一个,与产品的用户路径一致。 + +**golden 固定绝对 bounding box。** 否决:chip 与 trigger 宽度依赖安装字体,绝对坐标会在平台间漂移而不反映行为变化。 + +**复用 plan-review fixture 形态(exit_plan_mode review takeover)。** 否决:takeover 会替换 composer 控制行,而被测表面正是控制行。 + +**chip 与/或模型 trigger 的容器查询 label 折叠。** 否决(作为修复):两个包(ui-plan、ui-model)需要各自标定阈值,且 chip 单独折叠为 icon-only 在报告视口下仍剩约 7px 重叠,除非 trigger 也折叠。换行是一个包中的一条规则,且在所有宽度下成立。 + +## 后果 + +任何改变控制行布局的后续改动——字体、间距、媒体查询或容器查询——一旦重新引入重叠或把 chip 沿任一轴移出视口,本测试即失败。测试在 replay/refresh 模式下无需 API key:Plan 模式经命令 handler 切换,不经模型回合;providers-only replay fixture(无录制脚本,跳过消费检查)挂载模型目录,使触发器渲染真实的长标签——正是使报告重叠可测量的宽度;测试在测量前断言该标签。golden 在 replay 与 record 模式下比较,在 refresh 模式下重写。 diff --git a/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.i18n.yaml index 612916a290..bca41cb330 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.md -2026-08-10-subagent-empty-terminal-message-output.md: 693013f6810005ce02b08bd82f1f6a18511c40fb -2026-08-10-subagent-empty-terminal-message-output.zh.md: 64d61af21f838ef3f515db8af116cbdd74e96179 +2026-08-10-subagent-empty-terminal-message-output.md: 24bab01ad844a5b48e0bf6fe0fc54df6403f4bb7 +2026-08-10-subagent-empty-terminal-message-output.zh.md: ab3488806a4f7c019d783e563c79e06aeeb86f33 diff --git a/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.md b/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.md index 693013f681..24bab01ad8 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.md +++ b/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.md @@ -12,7 +12,7 @@ The agent loop appends an empty-content `assistant/message` when a `max-tokens` `dsh-subagent` owns one canonical selection rule in `src/assistant-output.ts`: select the last non-empty assistant message; without one, select the accumulated `text-delta` stream; ignore empty-content messages. The incremental `AssistantOutputFold` implements the rule through `push(event)` for session-event transports, `pushText(text)` for chunk-only transports, and `collect()` for selection. `finalAssistantOutput(events)` applies it to a complete event suffix for the in-process `readResult` and Activation capture. The SDK backend folds notification events; the ACP backend exposes no complete assistant messages and folds raw chunk text. `SubagentResult.output` defines the result contract, and `subagent/end.lastAssistantMessage` uses the same rule. When a child produces neither form of output, the lifecycle field is absent rather than an empty array for both one-shot and continuable runs. A `max-tokens` or `aborted` result retains its actual stop reason. -The foreground delegation tool uses the same selection. A non-`completed` result remains an `isError` tool result, but its message appends the child's partial text after the stop-reason headline so the parent model receives both the failure and available output. +The foreground delegation tool uses the same selection. A non-`completed` result remains an `isError` tool result, but its message presents the optional safe Provider diagnostic owned by the [non-interactive permissions decision](../feature/2026-08-15-product-subagent-noninteractive-permissions.md) after the stop-reason headline and appends the child's partial text afterward. The parent model receives the failure, separate infrastructure detail, and available assistant output without conflating them. ## Verification diff --git a/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.zh.md b/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.zh.md index 64d61af21f..ab3488806a 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-10-subagent-empty-terminal-message-output.zh.md @@ -12,7 +12,7 @@ Status: implemented `dsh-subagent` 在 `src/assistant-output.ts` 中拥有唯一的规范选取规则:选取最后一条非空 assistant 消息;没有时选取累积的 `text-delta` 流;忽略空内容消息。增量的 `AssistantOutputFold` 通过 `push(event)` 处理会话事件传输,通过 `pushText(text)` 处理仅分片传输,并通过 `collect()` 完成选取。`finalAssistantOutput(events)` 把规则应用于完整的事件后缀,供进程内 `readResult` 与 Activation capture 使用。SDK 后端折叠通知事件;ACP 后端不暴露完整的 assistant 消息,而是折叠原始分片文本。`SubagentResult.output` 定义结果约定,`subagent/end.lastAssistantMessage` 使用同一规则。子 agent 不产生这两种输出中的任何一种时,一次性与 continuable 运行的生命周期字段都会缺省,而不是空数组。`max-tokens` 或 `aborted` 结果保留实际的终止原因。 -前台委派工具使用同一选取规则。非 `completed` 的结果仍是 `isError` 工具结果,但其消息会在终止原因标题之后附上子 agent 的部分文本,让父模型同时接收失败信息与已有输出。 +前台委派工具使用同一选取规则。非 `completed` 的结果仍是 `isError` 工具结果,但其消息会在终止原因标题之后呈现由[非交互权限决策](../feature/2026-08-15-product-subagent-noninteractive-permissions.md)负责的可选安全提供方诊断,再附上子 agent 的部分文本。父模型会同时收到失败、独立的基础设施说明与已有 assistant 输出,而且不会把它们混为一体。 ## 验证 diff --git a/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.i18n.yaml new file mode 100644 index 0000000000..f797c08086 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.md +2026-08-18-request-image-payload-bound.md: df10df39d18c7da4660b566e8f0b6a5a60ff8dc1 +2026-08-18-request-image-payload-bound.zh.md: 070f2d194f1459f3f2728fdf9d5d2db2c3a24385 diff --git a/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.md b/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.md new file mode 100644 index 0000000000..df10df39d1 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.md @@ -0,0 +1,35 @@ +# Agent Note: Request-level image payload bound + +Status: implemented + +English | [中文](2026-08-18-request-image-payload-bound.zh.md) + +## Problem + +Every image in session history is base64-inlined into every model request by the pi-ai adapter, so a long session's request body grows monotonically with each admitted image. Gateways cap request-body size; once the accumulated payload crossed such a cap the request was rejected with 413 (`Failed to buffer the request body: length limit exceeded`), and because nothing bounds or trims the assembled request, every retry resent the same oversized body. The session was permanently unusable, and the failure text matched no `classifyPiAiError` rule, so it surfaced as the generic `PI_AI_ERROR`. Admission bounds (per image, per message) cannot prevent this: each image is individually admissible, and the sum still grows without bound. Two screenshots were enough to trigger it in production. + +## Decision + +The pi-ai provider profile carries `maxRequestImageBytes` (default `DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20MiB`, a positive integer, per route, changeable from cordis.yml and the `llm-pi-ai` settings section). At request conversion, `toPiContext` sums the base64 length of every image in history (derived from `ImageAttachmentRef.bytes` without reading data) and, while the sum exceeds the bound, replaces the oldest images with a fixed model-facing placeholder. The placeholder tells the model to read the file again when a path is available or ask the user to attach the image again. The most recent images are omitted last; an image larger than the bound is itself omitted. Offload locations use message and nested block indexes rather than object identity, so replaying the same JSON log produces the same request. Offloaded images are never read from the attachment store. `classifyPiAiError` classifies 413 and specific request-body-cap wording as `INVALID_REQUEST` (resending the same body cannot succeed). Four images admitted at the attachment store's 3.5MiB raw-image default occupy at most 18.67MiB after base64 expansion. The 20MiB request-image default therefore retains four such images and reserves the rest of a 32MiB request for system prompts, history, tools, and JSON. Deployments behind stricter gateways lower the value per route. + +## Offload is conversion, not history + +The placeholder is model-visible but not logged as a session event. It stays within the model-visible ⟺ logged invariant the same way the adapter's other serialization does (`(no output)` fallbacks, text-only folding): the offload locations are a pure function of the logged history and the route configuration, so the exact request remains reconstructable from the session log plus the composition. A logged elision event becomes necessary only when offload decisions gain non-deterministic inputs (for example live gateway feedback), which belongs to the deferred capability-metadata design. + +## Alternatives considered + +- **Fail the request with a clear error instead of offloading.** Keeps the model informed but leaves the session wedged: the user cannot remove images from durable history, so a hard failure at the bound is permanent. Offload keeps the session serviceable, which is the point of the fix. +- **Upload images once and reference them by URL / file id.** Removes the linear body growth entirely and is the right medium-term shape (providers and the internal gateway both document a Files path), but it introduces upload lifecycle management across providers and is far beyond a P0 hotfix. +- **Count the full request body, not only images.** Text and tools contribute little and their sizes are only known after full serialization per protocol; bounding the dominant term with explicit headroom is accurate enough for the failure being fixed and much simpler. Revisit inside the route-capability design. +- **Trim at admission instead.** Admission cannot see future accumulation; only the assembled request knows its total. Admission-side bounds (per-side dimension, bytes) remain as the first layer and are owned by [the dimension-limit note](2026-08-17-image-dimension-admission-limit.md). + +## Related + +- [Per-side image dimension admission limit](2026-08-17-image-dimension-admission-limit.md) — the admission-layer companion fix; together they close the two observed session-poisoning failures (400 dimension, 413 body size). + +## Consequences + +- An image-heavy long session keeps completing requests. The oldest images are omitted first; the most recent image is omitted only when it cannot fit within the bound. +- Crossing the bound rewrites an early message, so the provider prompt-cache prefix ends at the newly offloaded image until the offloaded prefix stabilizes. +- The bound counts base64 image payload only; deployments must keep it below their gateway's request-body cap with headroom, and the shipped default cannot know a private gateway's cap. +- Route capability metadata driving admission and assembly together (image count, per-image size, request size, provider token formulas) remains deferred design work tracked outside this fix. diff --git a/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.zh.md b/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.zh.md new file mode 100644 index 0000000000..070f2d194f --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-18-request-image-payload-bound.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 请求级图片载荷上限 + +Status: implemented + +[English](2026-08-18-request-image-payload-bound.md) | 中文 + +## Problem + +pi-ai 适配器把会话历史中的每张图片 base64 内联进每一个模型请求,长会话的请求体随每张入库图片单调增长。网关对请求体大小设有上限;累积载荷一旦越线,请求被以 413 拒绝(`Failed to buffer the request body: length limit exceeded`),而组装层没有任何约束或裁剪,每次重试都会原样重发同一个超限请求体,会话永久不可用。该报错文本不匹配 `classifyPiAiError` 的任何规则,只能落进笼统的 `PI_AI_ERROR`。准入上限(单图、单消息)无法阻止这一点:每张图片单独看都合规,总和仍然无界增长。线上两张截图即可触发。 + +## Decision + +pi-ai provider profile 增加 `maxRequestImageBytes`(默认 `DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20MiB`,正整数,按路由生效,可从 cordis.yml 与 `llm-pi-ai` settings 段修改)。请求转换时,`toPiContext` 由 `ImageAttachmentRef.bytes` 推算每张历史图片的 base64 长度(无需读取数据)求和,总和超过上限时从最老的图片开始替换为一段固定的模型可见占位文本。占位文本要求模型在有路径时重新读取文件,否则请用户重新附上图片。越新的图片越晚被省略;单张图片本身超过上限时也会被省略。offload 位置用消息与嵌套块的索引表示,不依赖对象身份,因此重放同一份 JSON 日志会产生相同请求。被 offload 的图片不会从附件存储读取。`classifyPiAiError` 把 413 与明确的请求体上限措辞归类为 `INVALID_REQUEST`(原样重发不可能成功)。四张按附件存储默认上限准入的 3.5MiB 原始图片,经 base64 膨胀后最多占 18.67MiB。20MiB 请求图片默认上限因此可保留四张这样的图片,并在 32MiB 请求内为系统提示词、历史、工具与 JSON 保留其余容量。网关更严格的部署按路由调低该值。 + +## offload 是转换而非历史 + +占位文本模型可见,但不记录为会话事件。它与适配器的其他序列化(`(no output)` 回退、纯文本折叠)以同样的方式满足「模型可见 ⟺ 已记录」不变量:offload 位置是已记录历史与路由配置的纯函数,确切请求仍可由会话日志加组合配置重建。只有当 offload 决策引入非确定性输入(例如网关的实时反馈)时才需要记录省略事件,那属于暂缓的能力元数据设计。 + +## Alternatives considered + +- **在上限处直接报错而不 offload。** 模型知情,但会话仍然卡死:用户无法从持久历史中删除图片,越线即永久失败。offload 让会话保持可用,这正是本修复的目标。 +- **图片上传一次、按 URL / file id 引用。** 从结构上消除请求体线性增长,是正确的中期形态(各提供方与内部网关都有 Files 路径),但要跨提供方管理上传生命周期,远超 P0 热修复范围。 +- **统计完整请求体而非只统计图片。** 文本与工具占比很小,且其大小要到按协议完整序列化后才可知;对主导项设上限并留出显式余量,对所修故障足够精确且简单得多。留到路由能力设计中再议。 +- **改在准入侧裁剪。** 准入看不到未来的累积,只有组装后的请求知道自己的总量。准入侧上限(单边尺寸、字节)作为第一层保留,归[尺寸上限笔记](2026-08-17-image-dimension-admission-limit.md)所有。 + +## Related + +- [图片单边尺寸准入上限](2026-08-17-image-dimension-admission-limit.md),准入层的配套修复;两者合起来封住已观测到的两类会话毒化故障(400 尺寸、413 请求体)。 + +## Consequences + +- 图片较多的长会话持续可用。最老的图片优先省略;仅当最新图片本身无法装进上限时才会省略它。 +- 越过上限会改写较早的一条消息,提供方 prompt cache 前缀在新被 offload 的图片处截止,直到被 offload 的前缀稳定。 +- 上限只统计 base64 图片载荷;部署必须让它低于自家网关的请求体上限并留出余量,发行默认值无法预知私有网关的上限。 +- 由路由能力元数据同时驱动准入与组装(图片数量、单图大小、请求大小、提供方 token 公式)的设计仍为暂缓工作,在本修复之外跟踪。 diff --git a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.i18n.yaml b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.i18n.yaml index e8ece4d624..36fa7f01b2 100644 --- a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md -2026-06-21-subagent-capability-seam.md: fa3b4f570bfccdc849a38b3eda16c1c8dd7b1827 -2026-06-21-subagent-capability-seam.zh.md: b25fe64377f98af92dbccb87f755627926975ef2 +2026-06-21-subagent-capability-seam.md: bc84d88d701a5f3018bf00f0ecf8b60750917407 +2026-06-21-subagent-capability-seam.zh.md: baec829a1a01018b490992fa0982bb23e43ba740 diff --git a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md index fa3b4f570b..bc84d88d70 100644 --- a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md +++ b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md @@ -54,11 +54,11 @@ Fresh and forked children are separate providers, not a request flag. `dsh-subag ### Child isolation and the parent log -Each in-process subagent runs in its **own `Session`** (own id, `parentSession` lineage), persisted independently. Remote ACP and one-shot product providers instead mint a parent-scoped lifecycle id and expose no local `Agent` or child `Session`; their internal state remains in the remote process. Across both forms, the parent's log records only the spawn `tool/call` and its `tool/result` (the child's final output), while child steps and tool calls remain outside the parent log. +Each in-process subagent runs in its **own `Session`** (own id, `parentSession` lineage), persisted independently. Remote ACP and one-shot product providers instead mint a parent-scoped lifecycle id and expose no local `Agent` or child `Session`; their internal state remains in the remote process. Across both forms, the parent's log records only the spawn `tool/call` and its `tool/result` (the child's final output, or a failed result with optional provider diagnostic), while child steps and tool calls remain outside the parent log. ### Synchronous collect (first cut) -`dsh-tool-subagent` passes its execution signal to `start()`, awaits the child result, and disposes the run before reporting. Non-completed outcomes become error results rather than successful partial output, and independent result and disposal rejections retain both diagnostics. +`dsh-tool-subagent` passes its execution signal to `start()`, awaits the child result, and disposes the run before reporting. Non-completed outcomes become error results rather than successful partial output; they present the optional safe diagnostic owned by the [non-interactive permissions decision](2026-08-15-product-subagent-noninteractive-permissions.md) separately from partial assistant text. Independent result and disposal rejections remain independently observable. ### Provider selection is config, not model-facing diff --git a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md index b25fe64377..baec829a1a 100644 --- a/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md +++ b/.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md @@ -54,11 +54,11 @@ bash seam([能力 seam](../architecture/2026-06-13-capability-seams.md))在 ### 子 agent 隔离与父日志 -每个进程内 subagent 运行在**自己的 `Session`** 中(独立 id、`parentSession` 谱系),独立持久化。远端 ACP 和一次性产品提供方则会生成一个父级作用域的生命周期 id,且不暴露本地 `Agent` 或子 `Session`;其内部状态留在远端进程中。两种形式下,父日志都仅记录 spawn `tool/call` 及其 `tool/result`(子 agent 的最终输出),而子 agent 的步骤和工具调用均留在父日志之外。 +每个进程内 subagent 运行在**自己的 `Session`** 中(独立 id、`parentSession` 谱系),独立持久化。远端 ACP 和一次性产品提供方则会生成一个父级作用域的生命周期 id,且不暴露本地 `Agent` 或子 `Session`;其内部状态留在远端进程中。两种形式下,父日志都仅记录 spawn `tool/call` 及其 `tool/result`(子 agent 的最终输出,或带可选提供方诊断的失败结果),而子 agent 的步骤和工具调用均留在父日志之外。 ### 同步收集(首版) -`dsh-tool-subagent` 将其执行信号传给 `start()`,等待子 agent 结果,并在报告前 dispose 该 run。非完成态的结果变为错误结果,而非成功的部分输出;结果与 dispose 的拒绝相互独立,且两项诊断信息都会保留。 +`dsh-tool-subagent` 将其执行信号传给 `start()`,等待子 agent 结果,并在报告前 dispose 该 run。非完成态的结果变为错误结果,而非成功的部分输出;它会把由[非交互权限决策](2026-08-15-product-subagent-noninteractive-permissions.md)负责的可选安全诊断与部分 assistant 文本分开呈现。结果与 dispose 的拒绝仍可彼此独立地观察。 ### 提供方选择是配置,不面向模型 diff --git a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.i18n.yaml b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.i18n.yaml index 0c0cf829a3..715da62619 100644 --- a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md -2026-07-08-background-subagent-tasks.md: 412ec61dcdecae1a273c5993d25a4a099a22e864 -2026-07-08-background-subagent-tasks.zh.md: 9d108440c992e150ed62edaef8bf860813a471b8 +2026-07-08-background-subagent-tasks.md: 4dcd961ee5a5db925f8f6ad83e97890eaedb8e63 +2026-07-08-background-subagent-tasks.zh.md: dd8ba47e018bdeeaffccca1fdaf52df75728057b diff --git a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md index 412ec61dcd..4dcd961ee5 100644 --- a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md +++ b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md @@ -8,7 +8,7 @@ English | [中文](2026-07-08-background-subagent-tasks.zh.md) The [subagent seam](2026-06-21-subagent-capability-seam.md) returns a `SubagentRun`, but the model-facing tool originally collected every run synchronously. Independent, slow delegations therefore held the parent call open or ran serially. -Subagents need the same start, collect, list, stop, ownership, notification, and cleanup behavior as other long-running tools without adopting process-stream semantics. The child session remains the detailed trace; the parent needs the final answer and job status. A background child also outlives its starting tool call, so its cancellation and owner-disposal contracts must be explicit. +Subagents need the same start, collect, list, stop, ownership, notification, and cleanup behavior as other long-running tools without adopting process-stream semantics. The child session remains the detailed trace; the parent needs the final answer or safe failure detail plus job status. A background child also outlives its starting tool call, so its cancellation and owner-disposal contracts must be explicit. ## Decision @@ -16,7 +16,7 @@ Each `dsh-tool-subagent` instance may expose `run_in_background`, controlled by Background subagents use the [generic background job runtime](../architecture/2026-06-20-generic-long-running-tool-runtime.md). Collection, listing, cancellation, completion notices, and prompt guidance come from `job_output`, `job_list`, and `job_kill`; there are no subagent-specific companion tools. -Foreground calls retain their synchronous contract: await provider startup and `run.result`, return final text only for `completed`, map other terminal reasons to an errored tool result, and always dispose the run before returning. +Foreground calls retain their synchronous contract: await provider startup and `run.result`, return final text only for `completed`, map other terminal reasons to an errored tool result with the optional safe diagnostic described by the [non-interactive permissions decision](2026-08-15-product-subagent-noninteractive-permissions.md), and always dispose the run before returning. For a background call, the tool validates the parent and refuses an already-aborted execution signal before calling `ctx.jobs.start()`. The job runtime preflights the control API and owner cleanup before invoking the producer starter. That starter creates an independent `AbortController` and begins `ctx.subagents.start()`; after the id is returned, the tool-call signal no longer owns the child. @@ -24,7 +24,7 @@ The task registration maps the subagent seam as follows: - `kind` is `subagent`, `label` is the model-supplied description, and `owner` is the parent agent. - `cancel(reason?)` aborts the task-owned controller. The same signal covers pending provider startup and the published run's remaining work. -- `done` awaits provider startup, the child result, and `run.dispose()`. Completed runs return final text, aborted runs become `killed`, and other stop reasons become `failed`. Startup, result, and disposal failures become failed outcomes rather than rejected task promises. +- `done` awaits provider startup, the child result, and `run.dispose()`. Completed runs return final text, aborted runs become `killed`, and other stop reasons become `failed` with the Provider diagnostic when present. Startup, result, and disposal failures become failed outcomes rather than rejected task promises. - `readOutput` is absent. While live, `job_output` returns status only; after settlement, it returns final output idempotently. Intermediate child activity remains in the child session. ## Lifecycle diff --git a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.zh.md b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.zh.md index 9d108440c9..dd8ba47e01 100644 --- a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.zh.md +++ b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.zh.md @@ -8,7 +8,7 @@ Status: implemented [subagent seam](2026-06-21-subagent-capability-seam.md) 会返回 `SubagentRun`,但原先面向模型的工具会同步收集每一次运行。因此,各自独立的慢速委派要么一直占用父调用,要么按串行方式运行。 -subagent 需要与其他长时间运行的工具相同的启动、收集、列出、停止、归属、通知和清理行为,但不应采用进程流语义。子会话仍是详细记录;父级只需最终答案和任务状态。后台子级的存活时间还会超过启动它的工具调用,因此必须明确其取消和拥有者资源释放约定。 +subagent 需要与其他长时间运行的工具相同的启动、收集、列出、停止、归属、通知和清理行为,但不应采用进程流语义。子会话仍是详细记录;父级只需最终答案或安全失败说明,以及任务状态。后台子级的存活时间还会超过启动它的工具调用,因此必须明确其取消和拥有者资源释放约定。 ## 决策 @@ -16,7 +16,7 @@ subagent 需要与其他长时间运行的工具相同的启动、收集、列 后台 subagent 使用[通用后台任务运行时](../architecture/2026-06-20-generic-long-running-tool-runtime.md)。`job_output`、`job_list` 和 `job_kill` 负责收集、列出、取消、完成通知和提示词引导;系统不提供 subagent 专用的配套工具。 -前台调用保留其同步约定:等待提供方启动和 `run.result`;仅当状态为 `completed` 时返回最终文本;将其他终止原因映射为出错的工具结果;并且始终在返回前释放该运行。 +前台调用保留其同步约定:等待提供方启动和 `run.result`;仅当状态为 `completed` 时返回最终文本;将其他终止原因映射为出错的工具结果,并在存在时附上由[非交互权限决策](2026-08-15-product-subagent-noninteractive-permissions.md)描述的可选安全诊断;而且始终在返回前释放该运行。 对于后台调用,工具会验证父级,并在调用 `ctx.jobs.start()` 前拒绝已中止的执行信号。任务运行时会在调用生产者启动器前,预检控制 API 和拥有者清理。该启动器创建独立的 `AbortController` 并启动 `ctx.subagents.start()`;返回 id 之后,工具调用的信号不再拥有该子级。 @@ -24,7 +24,7 @@ subagent 需要与其他长时间运行的工具相同的启动、收集、列 - `kind` 为 `subagent`,`label` 为模型提供的描述,`owner` 为父 agent(智能体)。 - `cancel(reason?)` 中止任务自有的控制器。同一个信号同时覆盖尚未完成的提供方启动和已发布 run 的剩余工作。 -- `done` 等待提供方启动、子级结果和 `run.dispose()`。已完成的运行返回最终文本,已中止的运行变为 `killed`,其他停止原因变为 `failed`。启动、结果和资源释放失败会转换为失败结果,而不是被拒绝的任务 Promise。 +- `done` 等待提供方启动、子级结果和 `run.dispose()`。已完成的运行返回最终文本,已中止的运行变为 `killed`,其他停止原因变为 `failed`,并在存在时携带提供方诊断。启动、结果和资源释放失败会转换为失败结果,而不是被拒绝的任务 Promise。 - `readOutput` 不存在。任务存活期间,`job_output` 只返回状态;结算后,它以幂等方式返回最终输出。中间的子级活动仍保留在子会话中。 ## 生命周期 diff --git a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.i18n.yaml b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.i18n.yaml index 8695a95bec..842f2c9cd3 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md -2026-07-22-web-multimodal-image-input-and-durable-attachments.md: 8c07b8b786aeeb87a4c2db7c0e6e49928b0ddf2c -2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md: 5d2d2963d6bee729362852701ea58f191f9721b2 +2026-07-22-web-multimodal-image-input-and-durable-attachments.md: 6a12380992c3205d6bb3f5701f093b3335fae2f9 +2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md: a8e94154e435a5359e7928d3b11eba7d1aee92f7 diff --git a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md index 8c07b8b786..6a12380992 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md +++ b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md @@ -140,7 +140,7 @@ Composer thumbnails and each `MessageImage` own ephemeral original-preview state ### Limits and trust boundaries -Version one accepts PNG, JPEG, WebP, and GIF only. SVG and remote URLs are excluded. Default limits are 5 MiB per image, 20 images and 100 MiB aggregate image bytes per message, 40 million intrinsic pixels per image, and 2000 pixels on either side. These deployment-varying limits are validated backend configuration and enforced by the host before persistence. The client connection carrier has an independent configurable `maxRequestBodyBytes` cap (160 MiB by default) for every API request and fails load if it cannot hold the attachment service's aggregate image limit after base64 and envelope expansion; lowering image policy therefore never silently lowers the carrier limit for valid text or other RPCs. A body without a declared length is rejected the moment it crosses the cap rather than drained to its end. +Version one accepts PNG, JPEG, WebP, and GIF only. SVG and remote URLs are excluded. Default limits are 3.5 MiB per image, 20 images and 100 MiB aggregate image bytes per message, 40 million intrinsic pixels per image, and 2000 pixels on either side. These deployment-varying limits are validated backend configuration and enforced by the host before persistence. The client connection carrier has an independent configurable `maxRequestBodyBytes` cap (160 MiB by default) for every API request and fails load if it cannot hold the attachment service's aggregate image limit after base64 and envelope expansion; lowering image policy therefore never silently lowers the carrier limit for valid text or other RPCs. A body without a declared length is rejected the moment it crosses the cap rather than drained to its end. Malformed base64, unsupported or mismatched media, truncated image payloads, excess bytes, excess image count, excess pixels, excess per-side dimensions, missing objects, and integrity mismatches return stable structured failures. Original filenames are reduced to a display basename, control characters are removed, and no local path is logged or returned to the browser. diff --git a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md index 5d2d2963d6..a8e94154e4 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md +++ b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md @@ -140,7 +140,7 @@ Pi-AI 适配器是首条视觉输入路径:它在请求时解析 `ctx.attachme ### 限制与信任边界 -第一版仅接受 PNG、JPEG、WebP 和 GIF。不接受 SVG 和远程 URL。默认限制为每张图片 5 MiB、每条消息 20 张图片和 100 MiB 图片总字节数、每张图片 4,000 万个固有像素,以及任一边 2,000 像素。这些随部署变化的限制属于经过校验的后端配置,并由宿主在持久化前强制执行。客户端连接载体为每个 API 请求设置独立且可配置的 `maxRequestBodyBytes` 上限(默认 160 MiB);如果该上限无法容纳附件服务的图片总量限制经 base64 和请求封装膨胀后的大小,加载就会失败。因此,降低图片策略绝不会静默降低有效文本或其他 RPC 的载体上限。未声明长度的请求体在越过上限的瞬间即被拒绝,而不是先读完再拒。 +第一版仅接受 PNG、JPEG、WebP 和 GIF。不接受 SVG 和远程 URL。默认限制为每张图片 3.5 MiB、每条消息 20 张图片和 100 MiB 图片总字节数、每张图片 4,000 万个固有像素,以及任一边 2,000 像素。这些随部署变化的限制属于经过校验的后端配置,并由宿主在持久化前强制执行。客户端连接载体为每个 API 请求设置独立且可配置的 `maxRequestBodyBytes` 上限(默认 160 MiB);如果该上限无法容纳附件服务的图片总量限制经 base64 和请求封装膨胀后的大小,加载就会失败。因此,降低图片策略绝不会静默降低有效文本或其他 RPC 的载体上限。未声明长度的请求体在越过上限的瞬间即被拒绝,而不是先读完再拒。 格式错误的 base64、不支持或不匹配的媒体、截断的图片数据、超出字节限制、超出图片数量、超出像素限制、超出单边尺寸限制、对象缺失和完整性不匹配都会返回稳定的结构化错误。原始文件名只保留用于显示的末段,控制字符会被移除,并且任何本地路径都不会写入日志或返回浏览器。 diff --git a/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.i18n.yaml index c70efe3121..c25841435c 100644 --- a/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-24-provider-retry-policies.md -2026-07-24-provider-retry-policies.md: 1831ce6b96178d11e7c9927ceccbe07ea578cd2c -2026-07-24-provider-retry-policies.zh.md: 22f18badcb47e4ce086ff2c68c7011612b2eabba +2026-07-24-provider-retry-policies.md: 96979b219aebece96a1bcc09aa3dd572d2b9222d +2026-07-24-provider-retry-policies.zh.md: 02fe13e0ddead035ec750c027e889da08e2557ae diff --git a/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.md b/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.md index 1831ce6b96..96979b219a 100644 --- a/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.md +++ b/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.md @@ -12,7 +12,7 @@ Provider policy must follow the request that actually failed, including a route ## Decision -Each concrete adapter accepts an optional `retryPolicy` inside its provider configuration. The adapter validates and resolves the policy, and `ctx.llm` captures it when that exact provider route registers. When a call enters its final adapter boundary, `ctx.llm` binds the serving registration's immutable policy to that call; the agent loop passes it to closed-step recovery even if the route is disposed or replaced while the request is in flight. `@deepseek-ai/dsh-llm-retry` combines that call-local policy with the failed step's durable provider identity. A call that never reaches a final adapter has no serving policy and delegates. A provider without `retryPolicy` uses the normal defaults. +Each concrete adapter accepts an optional `retryPolicy` inside its provider configuration, validates and resolves it, and exposes that resolved route policy through `providerRetryPolicy()`. Omission selects the shared core normal default of five retries for every composition, including Web, headless, and custom profiles. The effective policy remains route-owned registration state rather than a retry-executor setting. Layered settings may retain normal-only `maxRetries` or `retryableCodes` after changing `mode` to `always`; the resolver ignores those inactive fields while still rejecting unknown keys, and the registered always policy omits them. When a call enters its final adapter boundary, `ctx.llm` binds the serving registration's immutable policy to that call; the agent loop passes it to closed-step recovery even if the route is disposed or replaced while the request is in flight. `@deepseek-ai/dsh-llm-retry` combines that call-local policy with the failed step's durable provider identity. A call that never reaches a final adapter has no serving policy and delegates. ```yaml providers: @@ -44,22 +44,28 @@ Each scheduled retry appends a non-surface `llm/retry` event with the failed pro ## Alternatives considered -**One global `always` switch** — rejected because it cannot isolate the unbounded cost and latency risk to the provider that needs it and can silently apply after runtime rerouting. +**One retry-executor-level `always` switch** — rejected because it cannot isolate the unbounded cost and latency risk to the provider that needs it and can silently apply after runtime rerouting. Provider route policies remain authoritative, and the effective policy is captured only after routing selects a registration. **A separate exact-provider list on `dsh-llm-retry`** — rejected because it duplicates provider route names outside their owning adapter configuration and lets provider registration drift from recovery policy. **A very large finite retry count** — rejected because it eventually violates the requested keep-retrying contract and serializes an arbitrary operational limit as if it were meaningful. +**Adapter-specific omission defaults** — rejected because a shared budget would have to be repeated by every adapter family and every future adapter, making equivalent model routes behave differently depending on their implementation. + +**An LLM deployment-level default** — rejected because it introduces another configuration layer only to make Web differ from other compositions. The product default is uniform, while provider settings retain the existing per-route override. + +**Stamp five retries into profiles when the Web UI writes them** — rejected because existing profiles, settings written outside that UI, and non-Web compositions would retain the old value. + **Provider-SDK retries** — rejected because hidden attempts multiply agent-level budgets, cannot use the closed-step durability boundary, and may splice or discard streamed output without a reconstructable retry record. **Put the error into model context** — rejected because a transport or provider diagnostic is operational state, not conversation content. It can expose sensitive provider details and changes the retried request instead of repeating the failed request. ## Verification -Adapter tests validate nested policies at provider load, prove registration captures configured and default policies, and retain the serving policy across in-flight route replacement. Unit tests select policies from the failed request's serving registration, separate provider and changed-policy histories, exercise always mode beyond the normal budget, pin jitter and delay caps, prove downstream recovery ordering, prove cancellation and disposal drain delegated recovery before reaching quiescence, and prove both abort active backoff waits. Request-level coverage compares the complete messages of failed and retried attempts and rejects both provider error text and discarded partial output. A keyless headless `stream-json` snapshot runs failure, retry, and success through the assembled app, pins the complete `llm/retry` record, and rejects any model-message change between attempts. JSONL and SQLite tests round-trip an always event without `Infinity`; invariant tests bind provider identity to the request header, validate failure and mode-specific timer bounds, and bind retry numbers to provider-policy keys; TUI tests render finite and infinite limits. +Adapter tests validate nested policies at provider load, prove explicit profile policies reach registration, prove omission resolves to five retries, and retain the serving policy across in-flight route replacement. LLM service tests prove adapter policies are captured and omission uses the shared five-retry behavior. Resolver tests prove always mode ignores retained normal-only fields but returns a pure always policy. Unit tests select policies from the failed request's serving registration, separate provider and changed-policy histories, exercise always mode beyond the normal budget, pin jitter and delay caps, prove downstream recovery ordering, prove cancellation and disposal drain delegated recovery before reaching quiescence, and prove both abort active backoff waits. Request-level coverage compares the complete messages of failed and retried attempts and rejects both provider error text and discarded partial output. A keyless headless `stream-json` snapshot runs failure, retry, and success through the assembled app, pins the complete `llm/retry` record, and rejects any model-message change between attempts. The shipped Web composition snapshot pins omitted DeepSeek and pi-ai policies at five retries, then proves settings can write `{ mode: 'always', maxRetries: 5 }` and obtain a pure always policy. JSONL and SQLite tests round-trip an always event without `Infinity`; invariant tests bind provider identity to the request header, validate failure and mode-specific timer bounds, and bind retry numbers to provider-policy keys; TUI tests render finite and infinite limits. ## Consequences -Normal mode remains a finite default, while an explicit always policy can spend unbounded requests and time on permanent authentication, quota, invalid-request, protocol, or context failures. Operators must pair always mode with a cancellable caller and provider-specific cost controls. Retry state stays observable and durable without becoming model-visible, and serving-registration capture prevents adapter lifecycle changes from retroactively changing an in-flight request's recovery contract. +Normal mode remains a finite default, while an explicit always policy can spend unbounded requests and time on permanent authentication, quota, invalid-request, protocol, or context failures. Operators must pair always mode with a cancellable caller and provider-specific cost controls. Any model route using omission defaults may spend up to three more requests and their backoff time than under the former two-retry default, in exchange for recovering from longer transient outages. Retry state stays observable and durable without becoming model-visible, and serving-registration capture prevents adapter lifecycle changes from retroactively changing an in-flight request's recovery contract. This decision extends the closed-step recovery, single visible adapter attempt, structured failure, and durable status design in [bounded recovery for transient LLM request failures](../architecture/2026-06-21-bounded-llm-request-recovery.md). diff --git a/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.zh.md b/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.zh.md index 22f18badcb..02fe13e0dd 100644 --- a/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.zh.md +++ b/.agents/notes/implemented/feature/2026-07-24-provider-retry-policies.zh.md @@ -12,7 +12,7 @@ Status: implemented ## 决策 -每个具体适配器都在其提供方配置中接受可选的 `retryPolicy`。适配器负责校验并解析策略,`ctx.llm` 则在该特定提供方路由注册时捕获策略。当调用进入最终适配器边界时,`ctx.llm` 会把实际提供服务的注册项所持不可变策略绑定到该调用;即使路由在请求进行期间被 dispose(资源释放)或替换,agent loop(智能体循环)仍会把该策略传给已关闭步骤恢复。`@deepseek-ai/dsh-llm-retry` 会把绑定到该调用的策略与失败步骤的持久化提供方标识结合起来。未到达最终适配器的调用没有实际提供服务的策略,因而会委托后续处理。未配置 `retryPolicy` 的提供方使用 normal 默认值。 +每个具体适配器都在其提供方配置中接受可选的 `retryPolicy`,对它进行校验与解析,并通过 `providerRetryPolicy()` 公开解析后的路由策略。省略配置时,Web、headless 与自定义 profile 等所有组合都使用核心共享的 normal 模式五次重试默认值。有效策略仍然是路由拥有的注册状态,而不是重试执行器设置。分层 settings 在把 `mode` 改为 `always` 后可能保留仅属于 normal 的 `maxRetries` 或 `retryableCodes`;解析器会忽略这些未启用字段,同时仍拒绝未知键,注册后的 always 策略也不包含它们。当调用进入最终适配器边界时,`ctx.llm` 会把实际提供服务的注册项所持不可变策略绑定到该调用;即使路由在请求进行期间被 dispose(资源释放)或替换,agent loop(智能体循环)仍会把该策略传给已关闭步骤恢复。`@deepseek-ai/dsh-llm-retry` 会把绑定到该调用的策略与失败步骤的持久化提供方标识结合起来。未到达最终适配器的调用没有实际提供服务的策略,因而会委托后续处理。 ```yaml providers: @@ -44,22 +44,28 @@ always 模式先请求下游恢复,使上下文溢出压缩(compaction)之 ## 曾考虑的替代方案 -**单一全局 `always` 开关**:不予采纳,因为它无法把无界成本与延迟风险限制在确有需要的提供方,还可能在运行时重新路由后悄然生效。 +**重试执行器级的单一 `always` 开关**:不予采纳,因为它无法把无界成本与延迟风险限制在确有需要的提供方,还可能在运行时重新路由后悄然生效。提供方路由策略仍然权威,而且只有在路由选定注册后才捕获有效策略。 **在 `dsh-llm-retry` 上维护单独的指定提供方列表**:不予采纳,因为它会在所属适配器配置之外重复提供方路由名称,并让提供方注册与恢复策略发生偏差。 **设置很大的有限重试次数**:不予采纳,因为它最终仍会违反持续重试的约定,并把任意选取的运维上限序列化成看似有意义的数值。 +**按适配器设置不同的省略默认值**:不予采纳,因为共享预算必须在每种适配器族以及未来的每个适配器中重复配置,同等模型路由也会因实现不同而表现不同。 + +**LLM 部署级默认值**:不予采纳,因为这只为区分 Web 与其他组合增加了一层配置。产品默认值保持统一,提供方 settings 则保留既有的逐路由覆盖能力。 + +**在 Web UI 写入 profile 时把五次重试写死进去**:不予采纳,因为现有 profile、从该 UI 之外写入的 settings 以及非 Web 组合仍会保留旧值。 + **使用提供方 SDK 重试**:不予采纳,因为隐藏尝试会叠加 agent 层预算,无法利用已关闭步骤的持久性边界,还可能在没有可重建重试记录的情况下拼接或丢弃流式输出。 **把错误放入模型上下文**:不予采纳,因为传输或提供方诊断信息属于运维状态,而非对话内容。它可能暴露敏感的提供方细节,并会改变重试请求,无法重复原本失败的请求。 ## 验证 -适配器测试会在提供方加载时校验嵌套策略,证明注册流程会捕获已配置策略和默认策略,并证明请求进行期间替换路由后仍会保留实际提供服务的策略。单元测试根据失败请求实际使用的注册项选择策略、分离不同提供方和策略变更后的重试历史、验证 always 模式可越过 normal 预算、固定抖动和延迟上限、证明下游恢复顺序、证明取消与 dispose 会先排空已委托的恢复再达到完全停稳,并证明二者都会停止正在进行的退避等待。请求级覆盖会比较失败尝试与重试尝试的完整消息,并排除提供方错误文本和丢弃的部分输出。一个无密钥 headless `stream-json` 快照会通过组装后的应用执行失败、重试与成功流程,固定完整的 `llm/retry` 记录,并拒绝各次尝试之间出现任何模型消息变化。JSONL 与 SQLite 测试会往返读写不含 `Infinity` 的 always 事件;不变式测试会将提供方标识绑定到请求头、校验失败事实和各模式的计时器边界,并将重试编号绑定到提供方策略键;TUI 测试会渲染有限和无限上限。 +适配器测试会在提供方加载时校验嵌套策略,证明显式 profile 策略抵达注册流程,证明省略配置会解析为五次重试,并证明请求进行期间替换路由后仍会保留实际提供服务的策略。LLM 服务测试会证明适配器策略被捕获,且省略配置使用共享的五次重试行为。解析器测试会证明 always 模式忽略残留的 normal 专属字段,但返回纯 always 策略。单元测试根据失败请求实际使用的注册项选择策略、分离不同提供方和策略变更后的重试历史、验证 always 模式可越过 normal 预算、固定抖动和延迟上限、证明下游恢复顺序、证明取消与 dispose 会先排空已委托的恢复再达到完全停稳,并证明二者都会停止正在进行的退避等待。请求级覆盖会比较失败尝试与重试尝试的完整消息,并排除提供方错误文本和丢弃的部分输出。一个无密钥 headless `stream-json` 快照会通过组装后的应用执行失败、重试与成功流程,固定完整的 `llm/retry` 记录,并拒绝各次尝试之间出现任何模型消息变化。随附的 Web 组合快照会把省略配置的 DeepSeek 与 pi-ai 策略固定为五次重试,再证明 settings 可以写入 `{ mode: 'always', maxRetries: 5 }` 并得到纯 always 策略。JSONL 与 SQLite 测试会往返读写不含 `Infinity` 的 always 事件;不变式测试会将提供方标识绑定到请求头、校验失败事实和各模式的计时器边界,并将重试编号绑定到提供方策略键;TUI 测试会渲染有限和无限上限。 ## 后果 -normal 模式仍是有限的默认策略;显式的 always 策略可能在永久性的身份验证、配额、无效请求、协议或上下文错误上耗费无限次请求和无限时间。运维方必须为 always 模式配备可取消的调用方和针对提供方的成本控制。重试状态保持可观察且会持久化,但不会对模型可见;捕获实际提供服务的注册项,也能防止适配器生命周期变化反过来改变进行中请求的恢复约定。 +normal 模式仍是有限的默认策略;显式的 always 策略可能在永久性的身份验证、配额、无效请求、协议或上下文错误上耗费无限次请求和无限时间。运维方必须为 always 模式配备可取消的调用方和针对提供方的成本控制。任何使用省略默认值的模型路由相比原先的两次重试默认值,最多会多花费三次请求及其退避时间,以此换取从更长短暂故障中恢复的能力。重试状态保持可观察且会持久化,但不会对模型可见;捕获实际提供服务的注册项,也能防止适配器生命周期变化反过来改变进行中请求的恢复约定。 本决策扩展了[瞬态 LLM(大语言模型)请求失败的有界恢复](../architecture/2026-06-21-bounded-llm-request-recovery.md)中确定的已关闭步骤恢复、单次可见适配器尝试、结构化失败与持久化状态设计。 diff --git a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.i18n.yaml index 5ef2099535..d48293405c 100644 --- a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md -2026-07-30-deepseek-onboarding-credential-setup.md: 823d10a723af70ec4ff51018b8b86198db0f5c29 -2026-07-30-deepseek-onboarding-credential-setup.zh.md: 7e8d79c23c4b1489bfd818c90558f36509635486 +2026-07-30-deepseek-onboarding-credential-setup.md: 87533e7a55f9b1f05f6a4ba58c3c9888780c158c +2026-07-30-deepseek-onboarding-credential-setup.zh.md: 575d8232b4837b57d9508ed613530606c05db1f7 diff --git a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md index 823d10a723..87533e7a55 100644 --- a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md +++ b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md @@ -10,7 +10,7 @@ The [web configuration plane](../architecture/2026-07-30-web-config-plane.md) ma ## Decision -**One readiness projection owns both Models and onboarding facts.** `ui-settings-models` keeps a single store that joins `llm.providers({})`, redacted `settings.describe({})`, and batched `credentials.describe({refs})`. The onboarding projection selects the `deepseek-official` configurable-provider entry owned by the `llm-deepseek` namespace and empty settings path, reads the effective `apiKeyEnv`, and evaluates the matching credential descriptor. A live route with the same provider id but no matching configurable-provider declaration is adapter-absent for onboarding. A configured process-environment credential is ready and remains read-only. +**One readiness projection owns both Models and onboarding facts.** `ui-settings-models` keeps a single store that joins `llm.providers({})`, the redacted namespace views held by the shared settings describe mirror, and batched `credentials.describe({refs})`. The onboarding projection selects the `deepseek-official` configurable-provider entry owned by the `llm-deepseek` namespace and empty settings path, reads the effective `apiKeyEnv`, and evaluates the matching credential descriptor. A live route with the same provider id but no matching configurable-provider declaration is adapter-absent for onboarding. A configured process-environment credential is ready and remains read-only. The later [settings describe mirror decision](../architecture/2026-08-17-settings-describe-mirror.md) owns that settings read and its invalidation ordering. **The settings shell contributes ordering, not provider policy.** `ui-settings` declares a root-scoped `settings.onboarding` list slot and mounts one ordered step at a time while the current surface is the empty Hero. The active registrant receives `complete()` and a private `openSection(id)` callback; completion transfers ownership to the next entry. `ui-settings-models` registers the DeepSeek step, the preceding welcome notice, and its Models section through `slots.inject()`, so every contribution follows one client Cordis plugin's lifecycle and the dialogs cannot stack. Their common presentation is owned by the [shared-modal onboarding decision](2026-08-13-shared-modal-product-onboarding.md). diff --git a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.zh.md b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.zh.md index 7e8d79c23c..575d8232b4 100644 --- a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -**Models 与首次使用引导共享同一个就绪状态投影。**`ui-settings-models` 维护一个 store,把 `llm.providers({})`、脱敏后的 `settings.describe({})` 和批量调用的 `credentials.describe({refs})` 联接为同一份状态。首次使用投影选取由 `llm-deepseek` namespace 与空 settings path 持有的 `deepseek-official` 可配置提供方条目,读取生效的 `apiKeyEnv`,并检查对应的凭据描述符。同 provider id 但没有匹配可配置提供方声明的存活路由,在首次使用引导中视为适配器缺失。通过进程环境提供的凭据若已配置,则判定为就绪并保持只读。 +**Models 与首次使用引导共享同一个就绪状态投影。**`ui-settings-models` 维护一个 store,把 `llm.providers({})`、共享 settings describe 镜像持有的已脱敏 namespace views 和批量调用的 `credentials.describe({refs})` 联接为同一份状态。首次使用投影选取由 `llm-deepseek` namespace 与空 settings path 持有的 `deepseek-official` 可配置提供方条目,读取生效的 `apiKeyEnv`,并检查对应的凭据描述符。同 provider id 但没有匹配可配置提供方声明的存活路由,在首次使用引导中视为适配器缺失。通过进程环境提供的凭据若已配置,则判定为就绪并保持只读。后续的 [settings describe 镜像决策](../architecture/2026-08-17-settings-describe-mirror.md)持有这次 settings 读取及其失效顺序。 **设置外壳只贡献排序,不持有提供方策略。** `ui-settings` 声明一个根作用域的 `settings.onboarding` list slot,并在当前界面为空白 Hero 时,每次只挂载一个有序步骤。当前注册方会收到 `complete()` 和私有 `openSection(id)` 回调;完成当前步骤后,所有权转交给下一项。`ui-settings-models` 通过 `slots.inject()` 注册 DeepSeek 步骤、排在它之前的欢迎声明及 Models 分区,因此所有贡献都跟随同一个 client Cordis 插件的生命周期,两个弹窗也无法堆叠。它们的共用展示由[共用弹窗引导决策](2026-08-13-shared-modal-product-onboarding.md)持有。 diff --git a/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.i18n.yaml b/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.i18n.yaml index ea66531864..9aa0372a26 100644 --- a/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.md -2026-07-31-browser-derived-initial-locale.md: 072f91b730cfc9eaeead7701d2b20d12b443acb3 -2026-07-31-browser-derived-initial-locale.zh.md: 97f0f0007474c21fb618a085b506bc919586f624 +2026-07-31-browser-derived-initial-locale.md: 66fd56327aeb4463bfb8f6426ce7f7962d339782 +2026-07-31-browser-derived-initial-locale.zh.md: 721a785aa476951e7254c50230ddc092b9f8b211 diff --git a/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.md b/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.md index 072f91b730..66fd56327a 100644 --- a/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.md +++ b/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.md @@ -8,29 +8,39 @@ English | [中文](2026-07-31-browser-derived-initial-locale.zh.md) The Settings Language row opened every first visit in Chinese: `LocaleRuntime` read `dsh.locale` from localStorage and fell straight back to `zh` when nothing was stored. The browser already states which languages its user reads — `navigator.languages` is that statement — and the app ignored it, so an English reader met a Chinese product and had to find a Chinese-labelled settings row to escape it. The fallback was doing two jobs at once: the last resort for an unresolvable locale, and the answer for every user who had simply never chosen. +Reading the browser fixed the readers whose browser names a language this app ships, but left the residual case wrong: a browser asking for neither `zh` nor `en` (`fr`, `de`) still fell back to `zh`. Those readers are the least likely to read Chinese. + ## Decision -**The provisional locale resolves through the browser, then `FALLBACK_LOCALE`; an explicit Host preference replaces it live.** `resolveInitialLocale()` in `packages/client/locale/src/client/index.ts` runs at service construction and expresses the browser/fallback order. The nonblocking settings lifecycle then applies optional `locale.preference` from `$DSH_HOME/settings.yaml`; absence leaves the browser-derived value active. +**The provisional locale resolves through the browser, then `FALLBACK_LOCALE` (`en`); an explicit Host preference replaces it live.** `resolveInitialLocale()` in `packages/client/locale/src/client/index.ts` runs at service construction and expresses the browser/fallback order. The nonblocking settings lifecycle then applies optional `locale.preference` from `$DSH_HOME/settings.yaml`; absence leaves the browser-derived value active. + +**One constant serves both the opening locale and the dictionary fallback, because the dictionaries are symmetric.** `FALLBACK_LOCALE` answers both "which language does the UI open in when the browser names none we ship" and "which dictionary backs a key the active locale misses". Those are different questions, and splitting them into two constants would be right if either answer had to differ — but every shipped `zh`/`en` pair declares identical key sets, so the fallback step always resolves and both answers are `en`. The residual case points at English rather than zh because a browser naming neither shipped language is the reader least likely to read Chinese. `scripts/locale-dictionary-parity.spec.ts` gates the symmetry the shared constant depends on: a key added to one side only fails that spec by name, instead of surfacing later as a bare key such as `list.aria` in a running UI. **Browser matching is on the primary subtag, over the ordered list.** `detectBrowserLocale()` walks `[...(navigator.languages ?? []), navigator.language]` and returns the first entry whose primary subtag names a shipped locale, so `zh-Hans-CN` and `zh-TW` both land on `zh` and `en-GB` on `en`, while a browser asking only for languages this app does not ship (`fr`, `de`) yields nothing and leaves `FALLBACK_LOCALE` in charge. `navigator.language` trails the list and covers its absence on hosts that ship a Navigator without `languages` — the DOM lib types it as always present, so that tolerance carries a narrow lint exception, the same environment-boundary distrust the `localStorage` guards already express. -**`window`, not `navigator`, is the browser test.** Node ≥ 21 exposes a global `navigator` reporting the machine's own language (`en-US` on the CI runners), so gating on `navigator` would have let a node boot of the client tree resolve to `en` instead of the documented fallback. Gating on `window` keeps every non-browser run on `FALLBACK_LOCALE`. +**`window`, not `navigator`, is the browser test.** Node ≥ 21 exposes a global `navigator` reporting the machine's own language, so gating on `navigator` would let a node boot of the client tree resolve to the machine's language instead of the documented fallback. Gating on `window` keeps every non-browser run on `FALLBACK_LOCALE`. **An explicit choice is durable.** `setLocale` writes through the Host settings API, so a user who picked a language keeps it across browser origins and system languages that share the same DSH home. Nothing writes the detected locale back: detection is re-derived every boot and stays invisible to the “has the user chosen?” question. -**The browser e2e lane pins browser language.** Scenarios asserting Chinese copy (`access-confirmation`, `models-settings`, `onboarding-deepseek-config`, `settings-chrome`) open their page with `locale: ZH_BROWSER_LOCALE` from `apps/web/tests/support.ts`; `newEnglishPage` advertises `en-US`. `settings-chrome.e2e.ts` opens a fresh Host home with no explicit locale and asserts its English browser produces an English settings surface—the assembled-app proof of this feature. +**`` follows the resolved locale, and the served markup cannot.** `apps/web/index.html` is one static file serving every visitor, so whatever it declares is wrong for somebody: resolution happens in the client, after the document is parsed. The locale plugin therefore sets `document.documentElement.lang` from the active locale — once at activation, because detection or an adopted Host preference may already disagree with the markup, and again on every switch. The markup declares the product default (`en`) so the pre-boot document is not actively misleading. Assistive technology and browser features (pronunciation rules, translation offers, font fallback, spell check) read this attribute, so a stale value misreports the document language rather than merely looking untidy. The attribute carries a BCP 47 tag rather than the app's locale id: `zh` alone leaves the script ambiguous, so the shipped Chinese copy declares `zh-CN`. + +**The browser e2e lane pins browser language.** Scenarios asserting Chinese copy (`access-confirmation`, `models-settings`, `onboarding-deepseek-config`, `settings-chrome`) open their page with `locale: ZH_BROWSER_LOCALE` from `apps/web/tests/support.ts`; `newEnglishPage` advertises `en-US`. `settings-chrome.e2e.ts` opens a fresh Host home with no explicit locale twice: an `en-US` browser and an `fr-FR` one both reach an English surface. The `fr-FR` scenario is the one that pins the fallback — an `en-US` browser would land on English under detection or fallback alike, so only an unshipped language distinguishes them, and the zh scenarios prove detection still overrides the fallback. ## Alternatives considered - **`Intl.DateTimeFormat().resolvedOptions().locale` or a single `navigator.language` read**: both collapse the user's ordered preference list to one tag, so a `['de', 'en', 'zh']` reader gets zh instead of en. The list is the part of the browser statement worth reading. - **Persisting the detected locale on first boot**: it would make detection a one-time event and let a stale first visit outlive a changed browser language, and it destroys the distinction the resolution order rests on — a stored value would no longer mean "the user chose this". - **Full BCP 47 negotiation (`Intl.LocaleMatcher`-style lookup, region and script weighting)**: with exactly two shipped locales that differ in language, primary-subtag matching is the whole of the correct answer; a negotiation layer would be untestable surface with no behavior to justify it. -- **A cordis config key for the default locale**: the deployment does not vary here — the fallback is the product's answer for "no signal at all", not a knob. Repo policy reserves `Config` fields for deployment-varying choices with a current consumer. +- **A cordis config key for the fallback locale**: the deployment does not vary here — the fallback is the product's answer for "no signal at all", not a knob. Repo policy reserves `Config` fields for deployment-varying choices with a current consumer. +- **Two constants, one for the opening locale and one for the dictionary fallback**: it separates two genuinely different questions, and would be required if the answers differed. They do not: the dictionaries are symmetric, so both are `en`, and a second constant would be two names for one value plus a rule nothing enforces. The symmetry itself is worth enforcing, so it is gated directly instead. +- **Keeping `zh` as the dictionary fallback while opening in `en`**: it reads as the conservative choice, but with symmetric dictionaries it never resolves a key that `en` would not, so it buys nothing; and where it would matter — a key present only in `zh` — rendering Chinese text inside an otherwise English UI is worse than the bare key a reviewer would notice. - **Keeping the e2e lane's zh scenarios on storage pinning (`dsh.locale=zh`)**: it would keep the suite green while removing the only place the browser-derived path runs in an assembled app; pinning the browser language instead exercises the new resolution end to end. +- **Serving `` per request, or leaving the static attribute alone**: computing it server-side would need the request's `Accept-Language` to re-derive what the client resolves anyway, duplicating the rule in two places and still losing to a stored preference the server does not read. Leaving it static is what made the attribute permanently wrong for one language or the other. Setting it from the resolved locale keeps one source of truth. ## Consequences -- A first visit from an English browser lands in English, and the Language row still shows the same two self-described options, so the escape hatch is unchanged in either direction. -- `FALLBACK_LOCALE` narrows to its real job — the dictionary fallback and the no-signal answer — and stops standing in for "the user has not chosen". -- Tests that construct a `LocaleRuntime` under jsdom now depend on the environment's `navigator`: specs asserting localized copy declare their browser with one suite-level `usePinnedBrowserLanguages('zh-CN')` (dsh-client-test-runtime), and any future spec asserting a default must do the same. This package's own specs stub the globals directly, because they need shapes the helper deliberately cannot express (absent `languages`, a list decoupled from `language`, no `window` at all). +- A first visit from an English browser lands in English, a Chinese browser in Chinese, and a browser naming neither lands in English rather than Chinese. The Language row still shows the same two self-described options, so the escape hatch is unchanged in either direction. +- Dictionary resolution reverses direction: a key missing from the active locale now falls to `en`, not `zh`. With symmetric dictionaries no shipped key changes behavior, which is why the parity gate exists — it is the assumption that reversal rests on. +- `` now reports the language on screen in both directions, which closes [#2160](https://github.com/deepseek-harness/deepseek-harness/issues/2160). A client that never activates the locale plugin keeps the served default, so the attribute degrades to the old static behavior rather than to a blank value. +- Non-browser runs of the client tree (node boots, the non-jsdom unit lane) now open in `en`. Specs that assert shipped Chinese copy must set `setLocale('zh')` explicitly on the runtime they construct; a suite-level `usePinnedBrowserLanguages('zh-CN')` only works in files that also declare `@vitest-environment jsdom`, because without a `window` the detection path never reads `navigator` at all. Seven `*.client.spec.ts` files carried such a dead pin and were relying on the old `zh` fallback instead. - Detection cost is one array walk per service construction and no implicit settings write; an explicit Host preference may cause one live convergence after plugin activation. diff --git a/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.zh.md b/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.zh.md index 97f0f00074..721a785aa4 100644 --- a/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.zh.md +++ b/.agents/notes/implemented/feature/2026-07-31-browser-derived-initial-locale.zh.md @@ -8,29 +8,39 @@ Status: implemented 设置里的语言行在每一次首访时都以中文开场:`LocaleRuntime` 从 localStorage 读取 `dsh.locale`,读不到就直接回落到 `zh`。浏览器本已声明其使用者阅读哪些语言——`navigator.languages` 就是这份声明——而应用对此视而不见,于是英文读者迎面撞上一个中文产品,还得先找到一行中文标签的设置项才能脱身。回落值当时同时承担两份职责:既是无法解析出 locale 时的最后兜底,也是所有从未做过选择的用户拿到的答案。 +读取浏览器修好了那些浏览器声明了本应用所提供语言的读者,但残余情形依然是错的:既不请求 `zh` 也不请求 `en` 的浏览器(`fr`、`de`)仍会回落到 `zh`。这些读者恰恰最不可能阅读中文。 + ## Decision -**暂定 locale 先经浏览器、再经 `FALLBACK_LOCALE` 解析;显式 Host 偏好会实时替换它。** `packages/client/locale/src/client/index.ts` 中的 `resolveInitialLocale()` 在服务构造时运行,并表达浏览器/回落顺序。随后,非阻塞 settings 生命周期会应用 `$DSH_HOME/settings.yaml` 中可选的 `locale.preference`;若该值缺失,则继续使用由浏览器派生的值。 +**暂定 locale 先经浏览器、再经 `FALLBACK_LOCALE`(`en`)解析;显式 Host 偏好会实时替换它。** `packages/client/locale/src/client/index.ts` 中的 `resolveInitialLocale()` 在服务构造时运行,并表达浏览器/回落顺序。随后,非阻塞 settings 生命周期会应用 `$DSH_HOME/settings.yaml` 中可选的 `locale.preference`;若该值缺失,则继续使用由浏览器派生的值。 + +**开场 locale 与字典回落值共用一个常量,因为两侧字典是对称的。** `FALLBACK_LOCALE` 同时回答「浏览器未声明任何本应用提供的语言时,界面以哪种语言开场」与「当前 locale 的字典缺失某个 key 时由哪本字典兜住」。这是两个不同的问题,若其中任一答案必须不同,拆成两个常量才是对的——但每一对已提供的 `zh`/`en` 字典都声明了完全相同的 key 集合,因此回落这一步总能解析成功,两个答案都是 `en`。残余情形指向英文而非 `zh`,是因为一个声明了本应用都不支持的语言的浏览器,其读者最不可能读中文。`scripts/locale-dictionary-parity.spec.ts` 为这个共用常量所依赖的对称性设了门禁:只加在一侧的 key 会让该用例指名失败,而不是日后在运行中的界面里显现为形如 `list.aria` 的裸 key。 **浏览器匹配按主子标签进行,且遍历有序列表。** `detectBrowserLocale()` 遍历 `[...(navigator.languages ?? []), navigator.language]`,返回主子标签命中已提供 locale 的首个条目,因此 `zh-Hans-CN` 与 `zh-TW` 同归 `zh`、`en-GB` 归 `en`;而只请求本应用不提供的语言(`fr`、`de`)的浏览器则什么都匹配不到,交由 `FALLBACK_LOCALE` 接管。`navigator.language` 排在列表之后,并兜住那些 Navigator 上没有 `languages` 的宿主——DOM 库把它标注为必然存在,所以这份容忍带一条窄口径 lint 例外,与 `localStorage` 守卫表达的环境边界不信任同源。 -**判定浏览器用的是 `window` 而非 `navigator`。** Node ≥ 21 暴露全局 `navigator` 并报告机器自身语言(CI runner 上是 `en-US`),因此以 `navigator` 把关会让 node 启动客户端树时解析成 `en`,而非文档约定的回落值。以 `window` 把关可使所有非浏览器运行都停留在 `FALLBACK_LOCALE`。 +**判定浏览器用的是 `window` 而非 `navigator`。** Node ≥ 21 暴露全局 `navigator` 并报告机器自身语言,因此以 `navigator` 把关会让 node 启动客户端树时解析成机器语言,而非文档约定的回落值。以 `window` 把关可使所有非浏览器运行都停留在 `FALLBACK_LOCALE`。 **显式选择具有持久性。** `setLocale` 通过 Host settings API 写入,因此选过语言的用户可在共享同一 DSH home 的不同浏览器 origin 与系统语言之间保留原选择。没有任何代码把探测到的 locale 写回:探测在每次启动时重新推导,对「用户是否做过选择」这一问题始终不可见。 -**浏览器 e2e 车道固定浏览器语言。** 断言中文文案的场景(`access-confirmation`、`models-settings`、`onboarding-deepseek-config`、`settings-chrome`)以 `apps/web/tests/support.ts` 的 `locale: ZH_BROWSER_LOCALE` 打开页面;`newEnglishPage` 声明 `en-US`。`settings-chrome.e2e.ts` 使用没有显式 locale 的全新 Host home,断言其英文浏览器会生成英文 settings 界面:这是本功能在组装后应用中的证据。 +**`` 跟随解析出的 locale,而所服务的 markup 做不到这一点。** `apps/web/index.html` 是一份静态文件,服务所有访问者,因此它声明什么都必然对某些人是错的:解析发生在客户端,在文档被解析之后。于是由 locale 插件依据当前 locale 设置 `document.documentElement.lang`——激活时设置一次,因为探测结果或已采纳的 Host 偏好可能已与 markup 不一致;此后每次切换再设置一次。markup 声明产品默认值(`en`),使启动前的文档不至于主动误导。无障碍技术与浏览器功能(发音规则、翻译提示、字体回退、拼写检查)都读取该属性,因此陈旧的值是在误报文档语言,而不只是看起来不整齐。该属性承载 BCP 47 标签而非应用内部的 locale id:单独的 `zh` 会使文字(script)含义不明,因此已提供的中文文案声明 `zh-CN`。 + +**浏览器 e2e 车道固定浏览器语言。** 断言中文文案的场景(`access-confirmation`、`models-settings`、`onboarding-deepseek-config`、`settings-chrome`)以 `apps/web/tests/support.ts` 的 `locale: ZH_BROWSER_LOCALE` 打开页面;`newEnglishPage` 声明 `en-US`。`settings-chrome.e2e.ts` 两次使用没有显式 locale 的全新 Host home:`en-US` 浏览器与 `fr-FR` 浏览器都会抵达英文界面。真正钉住回落值的是 `fr-FR` 那个场景——`en-US` 浏览器无论走探测还是走回落都会落在英文,因此只有本应用不提供的语言才能区分二者,而中文场景则证明探测仍然覆盖回落值。 ## Alternatives considered - **`Intl.DateTimeFormat().resolvedOptions().locale` 或单读 `navigator.language`**:两者都把用户的有序偏好列表塌缩成一个标签,于是 `['de', 'en', 'zh']` 的读者拿到的是 zh 而非 en。列表恰恰是浏览器这份声明里最值得读的部分。 - **首次启动即持久化探测结果**:那会把探测变成一次性事件,让一次陈旧的首访凌驾于此后改变的浏览器语言之上,也摧毁了整个解析顺序所依赖的区分——存储值将不再意味着「用户选了它」。 - **完整的 BCP 47 协商(`Intl.LocaleMatcher` 式查找、地区与文字权重)**:在只提供两个语言互异的 locale 时,主子标签匹配就是正确答案的全部;协商层只会带来无行为支撑、也无从测试的表面积。 -- **为默认 locale 增加一个 Cordis 配置键**:此处部署之间并无差异——回落值是产品对「完全没有信号」给出的答案,不是旋钮。仓库策略把 `Config` 字段留给有当前消费方、且随部署变化的选择。 +- **为回落 locale 增加一个 Cordis 配置键**:此处部署之间并无差异——回落值是产品对「完全没有信号」给出的答案,不是旋钮。仓库策略把 `Config` 字段留给有当前消费方、且随部署变化的选择。 +- **拆成两个常量,一个管开场 locale、一个管字典回落**:它区分了两个确实不同的问题,若两个答案不同也确有必要。但它们并不不同:字典是对称的,因此两者都是 `en`,第二个常量只会是同一个值的两个名字,外加一条无人强制的规则。对称性本身值得强制,所以直接为它设门禁。 +- **开场用 `en`、字典回落仍保留 `zh`**:这看起来是保守选择,但在字典对称的前提下,它能解析的 key 与 `en` 完全相同,因此毫无收益;而在它真正会起作用的情形——某个 key 只存在于 `zh`——在整体英文的界面里渲染出中文文本,比让 reviewer 一眼看见裸 key 更糟。 - **让 e2e 车道的中文场景继续钉存储项(`dsh.locale=zh`)**:那会让套件保持绿色,却抹掉浏览器推导路径在组装后应用中唯一的运行处;改钉浏览器语言才能端到端地演练新的解析过程。 +- **按请求服务 ``,或干脆不管这个静态属性**:在服务端计算它需要用请求的 `Accept-Language` 去重新推导客户端本就会解析的结果,使同一条规则在两处重复,而且仍会输给服务端并不读取的存储偏好。放任其保持静态,正是该属性对某一种语言永远错误的原因。依据解析出的 locale 来设置,可保持单一真源。 ## Consequences -- 来自英文浏览器的首访落在英文界面,而语言行依然呈现同样两个以自身语言自述的选项,两个方向的脱身通道都未改变。 -- `FALLBACK_LOCALE` 收窄回它真正的职责——字典回落与无信号时的答案——不再兼职充当「用户尚未选择」。 -- 在 jsdom 下构造 `LocaleRuntime` 的测试现在依赖环境的 `navigator`:断言本地化文案的用例以一行套件级 `usePinnedBrowserLanguages('zh-CN')`(dsh-client-test-runtime)声明其浏览器,今后任何断言默认值的用例同样如此。本包自己的用例直接给全局打桩,因为它们需要该 helper 刻意不表达的形状(`languages` 缺失、列表与 `language` 解耦、完全没有 `window`)。 +- 来自英文浏览器的首访落在英文界面,中文浏览器落在中文界面,而两者皆未声明的浏览器落在英文而非中文界面。语言行依然呈现同样两个以自身语言自述的选项,两个方向的脱身通道都未改变。 +- 字典解析方向发生反转:当前 locale 缺失的 key 现在回落到 `en` 而非 `zh`。在字典对称的前提下,没有任何已提供的 key 行为发生变化——这正是那道对称性门禁存在的原因:它是这次反转所依赖的前提。 +- `` 现在在两个方向上都如实报告屏幕上的语言,这也关闭了 [#2160](https://github.com/deepseek-harness/deepseek-harness/issues/2160)。若某个客户端从未激活 locale 插件,则保留所服务的默认值,因此该属性退化为旧的静态行为,而不会退化为空值。 +- 客户端树的非浏览器运行(node 启动、非 jsdom 单测车道)现在以 `en` 开场。断言已提供中文文案的用例必须在其构造的 runtime 上显式调用 `setLocale('zh')`;套件级的 `usePinnedBrowserLanguages('zh-CN')` 仅在同时声明了 `@vitest-environment jsdom` 的文件中生效,因为没有 `window` 时探测路径根本不会读取 `navigator`。此前有七个 `*.client.spec.ts` 文件带着这样一条失效的固定语句,实际依赖的是旧的 `zh` 回落值。 - 探测的代价是每次服务构造遍历一次数组,且不会隐式写入 settings;插件激活后,显式 Host 偏好可能引发一次实时收敛。 diff --git a/.agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.i18n.yaml b/.agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.i18n.yaml index d34847dc00..53d0c54764 100644 --- a/.agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.md -2026-08-03-web-search-source-scroll.md: 3402f519e1974b99e1f5a87dcd53b4d94a1a8374 -2026-08-03-web-search-source-scroll.zh.md: 8ac1158d054f739bb1f76c87570ac1e75b77e05d +2026-08-03-web-search-source-scroll.md: 6fe532e2a2989e834b926cf48d531ae60a32f58b +2026-08-03-web-search-source-scroll.zh.md: bc1abb5215c618809e79f56d1f9bd6c1ee9dbf15 diff --git a/.agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.md b/.agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.md index 3402f519e1..6fe532e2a2 100644 --- a/.agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.md +++ b/.agents/notes/implemented/feature/2026-08-03-web-search-source-scroll.md @@ -8,13 +8,13 @@ English | [中文](2026-08-03-web-search-source-scroll.zh.md) The `web_search` result card (`WebBlock`, `packages/client/ui-primitives/src/WebBlock.tsx`) rendered its source list with a head/tail collapse: past a `maxSources` count (16 in the details panel, 8 in the chat row via `CHAT_WEB_MAX_SOURCES`) it drew the first `ceil(max/2)` sources, an `… 其余 N 条来源` expand button, then the last `max - ceil(max/2)`, mirroring `TerminalBlock`'s output cap. A user reading the card saw `来源列表已截断` and assumed the frontend had dropped sources it was holding. -It had not. The seam (`capSources`, `packages/web/web/src/index.ts`) cuts the provider's sources to the tool's `searchMaxResults` bound (default 8) and sets `truncated`, and that one capped list feeds both the model-facing render text and the card's `presentationMeta`. The card never holds more sources than that one cut produced. So the collapse was hiding sources the user was entitled to see in full — and, with the default bound at 8 and the panel cap at 16, it almost never even triggered, leaving only the `truncated` note with no way to reveal anything. +It had not. The seam (`capSources`, `packages/web/web/src/index.ts`) cuts each provider result to the tool's `searchMaxResults` bound (default 8); a multi-query call then deduplicates, interleaves, and caps the combined sources at the same bound. The final capped list feeds both the model-facing render text and the card's `presentationMeta`, so the card never holds more sources than the tool returned. The collapse was hiding sources the user was entitled to see in full — and, with the default bound at 8 and the panel cap at 16, it almost never even triggered, leaving only the `truncated` note with no way to reveal anything. ## Decision `WebBlock`'s search arm renders every source it receives in one `
    `, with no head/tail slicing, no expand button, and no `maxSources` prop. `.sources` (`WebBlock.module.css`) gets a fixed `max-height` and `overflow-y: auto`, so a list longer than the card height scrolls in place rather than growing the card or hiding rows. The height is a design constant of the card geometry, so it lives in CSS, not a plugin config field. -The model side is unchanged: the seam still caps sources at `searchMaxResults`, the model-facing render text is untouched, and the `truncated` flag and its `来源列表已截断` indicator stay. The card draws the list the seam produced, in full and scrollable, instead of collapsing its middle. +The model side remains capped at `searchMaxResults`: the seam caps each provider result, the multi-query consumer caps a combined list, and the `truncated` flag and its `来源列表已截断` indicator stay. The card draws the final tool source list in full and scrollable, instead of collapsing its middle. That list is the one the model reads as long as nothing downstream of the tool rewrites the result content alone. A deployment mounting `dsh-spill-policy` breaks that correspondence for an oversized result: `tools/post-execute` replaces the model-facing `content` with a preview plus a spill locator and leaves `presentationMeta` whole, so the card still draws every source while the model reads a bounded excerpt. The card's contract is therefore the view it receives, not the model's context. @@ -36,11 +36,11 @@ Every source the tool returned is always in the DOM, so no source the view carri ## Testing -`packages/client/ui-primitives/tests/web-block.client.spec.tsx` drops the collapse cases (head/tail slice, expand-on-click, collapsed-tail numbering, expander-out-of-numbering, head-alone, default cap) and adds: a 30-source card renders all 30 `
  1. ` with no `[aria-expanded]` and no ` +
      {(candidates ?? []).map(candidate => (
    • diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.module.css b/packages/client/ui-settings-models/src/client/ModelsSection.module.css index 5203524517..6b8c2047a4 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.module.css +++ b/packages/client/ui-settings-models/src/client/ModelsSection.module.css @@ -644,6 +644,12 @@ select.input { --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); } +.candidateActions { + display: flex; + justify-content: flex-end; + margin-bottom: 6px; +} + .candidateList { display: flex; flex-direction: column; diff --git a/packages/client/ui-settings-models/src/client/index.ts b/packages/client/ui-settings-models/src/client/index.ts index cce0a1c55f..6bb403a90f 100644 --- a/packages/client/ui-settings-models/src/client/index.ts +++ b/packages/client/ui-settings-models/src/client/index.ts @@ -21,7 +21,7 @@ import { DeepSeekOnboardingDialog } from './DeepSeekOnboardingDialog.tsx' import type { DeepSeekOnboardingInjected } from './DeepSeekOnboardingDialog.tsx' import { WelcomeNotice } from './WelcomeNotice.tsx' import type { WelcomeNoticeInjected } from './WelcomeNotice.tsx' -import { refreshWelcomeIfLoaded, WelcomeNoticeStore } from './welcome-store.ts' +import { decodeWelcomeSection, WelcomeNoticeStore } from './welcome-store.ts' import { ModelsSettingsStore } from './store.ts' import { createSettingsSchemaOperations } from './schema-operations.ts' import { en, zh, type ModelsKey } from './locales.ts' @@ -56,7 +56,7 @@ export function refreshIfLoaded(controller: ModelsSettingsStore): void { * ui-settings' apply, whose activation order relative to this one is NOT * constrained; registration depends on each slot through `slots.inject()`. */ -export const inject = ['slots', 'locale', 'connection', 'remote', 'settingsSchema'] +export const inject = ['slots', 'locale', 'connection', 'remote', 'settingsScope', 'settingsSchema'] /** * Register the Models section once the `settings.section` declaration is on @@ -69,7 +69,7 @@ export function apply(ctx: ClientContext): void { const connection = ctx.get('connection') as ConnectionHandle const schema = createSettingsSchemaOperations(ctx.settingsSchema) - const controller = new ModelsSettingsStore(connection.api, schema) + const controller = new ModelsSettingsStore(connection.api, schema, ctx.settingsScope.describe()) // Registration-time text (the nav label thunk) and the inject faces share // one bound translate; copy freshness rides the locale revision. const t = ctx.locale.bind(NS) as ModelsSectionInjected['t'] @@ -87,34 +87,35 @@ export function apply(ctx: ClientContext): void { schema, t, }) - const welcomeController = new WelcomeNoticeStore( - connection.api, - connection.isLoopback ? 'host' : 'memory', - ) + // The scope's own memory mode is what keeps a remote browser process-local, + // so the store needs no isLoopback branch of its own. + const welcomeController = new WelcomeNoticeStore(ctx.settingsScope.bind({ + namespace: WELCOME_NOTICE_SETTINGS_NAMESPACE, + decode: decodeWelcomeSection, + })) const welcomeInjected = (): WelcomeNoticeInjected => ({ controller: welcomeController, hooks: { welcome: welcomeController.store }, t, }) - // Pushed invalidations converge every open surface without polling: any - // settings/credentials/topology change refetches once the page loaded. + // Pushed invalidations converge every open surface without polling. The + // settingsScope injection makes ui-settings activate first, and remote + // dispatch preserves listener order; its listener therefore starts the + // mirror refresh before this store joins that refresh. The welcome notice + // follows its settings scope, so it needs no subscription here. ctx.effect(() => { const refreshModels = (): void => { refreshIfLoaded(controller) } - const refreshAll = (): void => { - refreshModels() - refreshWelcomeIfLoaded(welcomeController) - } const disposers = [ - ctx.remote.$on('settings/document-updated', (ns) => { - refreshModels() - if (ns === WELCOME_NOTICE_SETTINGS_NAMESPACE) refreshWelcomeIfLoaded(welcomeController) - }), + ctx.remote.$on('settings/document-updated', () => { refreshModels() }), ctx.remote.$on('credentials/updated', refreshModels), ctx.remote.$on('llm/adapters-updated', refreshModels), - ctx.on('connection/reset', refreshAll), + ctx.on('connection/reset', refreshModels), ] - return () => { for (const dispose of disposers) dispose() } + return () => { + welcomeController.dispose() + for (const dispose of disposers) dispose() + } }, 'ui-settings-models: pushed invalidations') ctx.slots.inject('settings.section', () => ctx.slots.register({ diff --git a/packages/client/ui-settings-models/src/client/locales.ts b/packages/client/ui-settings-models/src/client/locales.ts index a49a4f0ef2..856ef64c7b 100644 --- a/packages/client/ui-settings-models/src/client/locales.ts +++ b/packages/client/ui-settings-models/src/client/locales.ts @@ -72,6 +72,8 @@ export const en = { fetchEmpty: 'The provider listed no models. Add them by hand.', fetchTitle: 'Choose models to add', fetchDescription: 'These are the models this provider has available. Choose the ones to add.', + fetchSelectAll: 'Select all', + fetchDeselectAll: 'Deselect all', fetchAdopt: 'Add selected', customAdd: 'Add a custom provider', customTitle: 'Custom provider', @@ -172,6 +174,8 @@ export const zh: { [Key in keyof typeof en]: string } = { fetchEmpty: '该提供方没有列出任何模型,请手动添加。', fetchTitle: '选择要添加的模型', fetchDescription: '以下是模型提供方的可用模型,勾选要添加的模型。', + fetchSelectAll: '全选', + fetchDeselectAll: '取消全选', fetchAdopt: '添加所选', customAdd: '添加自定义提供方', customTitle: '自定义提供方', diff --git a/packages/client/ui-settings-models/src/client/store.ts b/packages/client/ui-settings-models/src/client/store.ts index 7beacb9fce..5b688db919 100644 --- a/packages/client/ui-settings-models/src/client/store.ts +++ b/packages/client/ui-settings-models/src/client/store.ts @@ -1,6 +1,6 @@ /** * Models settings page store: one snapshot joining the configurable-provider - * directory (`llm.providers`), the settings namespaces (`settings.describe`), + * directory (`llm.providers`), the settings namespaces (shared settings mirror), * and the referenced credentials (`credentials.describe`). The host stays the * single fact source — every mutation writes through the wire and the page * re-renders from the next describe, pushed or refetched. @@ -11,6 +11,7 @@ import type { } from '@deepseek-ai/dsh-api-remotes/client' import type { SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import type { SettingsDescribeFace } from '@deepseek-ai/dsh-client-ui-settings/client' import type { SettingsSchemaOperations } from './schema-operations.ts' /** @@ -114,17 +115,21 @@ export class ModelsSettingsStore { private generation = 0 /** - * @param api - the wire face (settings/credentials/llm domains). + * @param api - the wire face (credentials/llm domains, and settings writes). + * @param describeFace - the shared mirror's describe face (namespace views and writability). */ constructor( private readonly api: Pick, private readonly schema: SettingsSchemaOperations, + private readonly describeFace: SettingsDescribeFace, ) {} /** - * Refresh the whole page snapshot: directory and namespaces in parallel, - * then one batched credential describe over every referenced ref. A - * failure keeps the last good rows and surfaces the error. + * Refresh the whole page snapshot: the provider directory and the mirror's + * settings answer in parallel, then one batched credential describe over + * every referenced ref. Provider failure or absence of an initial settings + * answer keeps the last good rows and surfaces an error; a failed settings + * refresh reuses the mirror's held view. * @returns nothing; the snapshot carries the outcome. */ async load(): Promise { @@ -132,17 +137,20 @@ export class ModelsSettingsStore { this.store.update((s) => { s.status = 'loading'; s.error = null }) let providers: ConfigurableProviderView[] let writable: boolean - let views: SettingsNamespaceView[] + let views: readonly SettingsNamespaceView[] try { - const [providersResponse, settingsResponse] = await Promise.all([ + const [providersResponse] = await Promise.all([ this.api.llm.providers({}), - this.api.settings.describe({}), + this.describeFace.ensure(), ]) if (!providersResponse.result.ok) throw new Error(providersResponse.result.error.message) - if (!settingsResponse.result.ok) throw new Error(settingsResponse.result.error.message) + const mirrored = this.describeFace.getSnapshot() + if (mirrored.view === undefined) { + throw new Error(mirrored.error ?? 'settings are unavailable in this browser') + } providers = providersResponse.result.value.providers - writable = settingsResponse.result.value.writable - views = settingsResponse.result.value.namespaces + writable = mirrored.view.writable + views = mirrored.view.namespaces } catch (error) { if (generation !== this.generation) return this.store.update((s) => { diff --git a/packages/client/ui-settings-models/src/client/welcome-store.ts b/packages/client/ui-settings-models/src/client/welcome-store.ts index 6e139f1a43..82b8e0a662 100644 --- a/packages/client/ui-settings-models/src/client/welcome-store.ts +++ b/packages/client/ui-settings-models/src/client/welcome-store.ts @@ -1,10 +1,14 @@ -/** Welcome-notice state, durable when the browser may use Host settings. */ +/** + * Welcome-notice state derived from the welcome settings scope. The scope is + * the transport: a loopback browser follows the durable Host section, while a + * remote browser's memory-mode scope never answers and the acknowledgement + * stays process-local here. + */ -import type { IApiClient, SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' -import type { SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import type { SettingsScope, SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import { - WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION, + WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_VERSION, } from '../onboarding-copy.ts' /** State rendered by the welcome step. */ @@ -14,113 +18,123 @@ export interface WelcomeNoticeState { error: string | null } -function messageOf(error: unknown): string { - return error instanceof Error ? error.message : String(error) +/** The welcome section as the notice reads it. */ +export type WelcomeSection = Record + +/** + * Accept any object section verbatim; a malformed durable value reads as an + * empty section, so the notice treats it as unacknowledged instead of leaving + * the scope stuck on its previous value. + * @param section - the wire section value. + * @returns the section object, or an empty one for non-object values. + */ +export function decodeWelcomeSection(section: unknown): WelcomeSection { + return typeof section === 'object' && section !== null && !Array.isArray(section) + ? section as WelcomeSection + : {} } -function acknowledgementOf(view: SettingsNamespaceView): string | undefined { - if (typeof view.value !== 'object' || view.value === null) return undefined - const value = (view.value as Record)[WELCOME_NOTICE_ACK_FIELD] - return typeof value === 'string' ? value : undefined +/* v8 ignore next 3 -- closed-union default only defends future source widening */ +function assertNever(_value: never): never { + throw new Error('unexpected welcome settings status') } /** Coordinates durable Host acknowledgement or a process-local remote fallback. */ export class WelcomeNoticeStore { /** uSES-safe state source shared by the registered welcome step. */ - readonly store: SnapshotStore = createSnapshotStore({ + readonly store: SnapshotStore = createSnapshotStore({ status: 'idle', acknowledged: false, error: null, }) - private generation = 0 + private localAcknowledged = false + private saving = false + private following: (() => void) | undefined /** - * @param api - settings wire face used for durable reads and writes. - * @param persistence - remote browsers use memory because settings is loopback-only. + * @param scope - the welcome settings namespace scope; its memory mode is + * what keeps a remote browser process-local. */ - constructor( - private readonly api: Pick, - private readonly persistence: 'host' | 'memory' = 'host', - ) {} + constructor(private readonly scope: SettingsScope) {} - /** Load the acknowledgement from Host settings or initialize process-local state. */ - async load(): Promise { - const generation = ++this.generation - if (this.persistence === 'memory') { - this.store.update((state) => { state.status = 'ready'; state.error = null }) - return - } - this.store.update((state) => { state.status = 'loading'; state.error = null }) - try { - const response = await this.api.settings.describe({}) - if (!response.result.ok) throw new Error(response.result.error.message) - const view = response.result.value.namespaces.find( - candidate => candidate.ns === WELCOME_NOTICE_SETTINGS_NAMESPACE, - ) - if (view === undefined) throw new Error('welcome acknowledgement settings are unavailable') - if (generation !== this.generation) return - this.store.update((state) => { - state.status = 'ready' - state.acknowledged = acknowledgementOf(view) === WELCOME_NOTICE_VERSION - state.error = null - }) - } catch (error) { - if (generation !== this.generation) return - this.store.update((state) => { - state.status = 'error' - state.acknowledged = false - state.error = messageOf(error) - }) - } + /** + * Begin following the bound scope (idempotent) and publish its current answer. + * @returns settlement after the current answer is published. + */ + load(): Promise { + this.following ??= this.scope.subscribe(() => { this.derive() }) + this.derive() + return Promise.resolve() } /** - * Persist this copy version, or advance only this process for a remote browser. - * @returns true when the selected persistence mode accepted the acknowledgement. + * Persist this copy version, or advance only this process for a remote + * browser. Success is judged against the state the write left behind, so a + * refused or failed write reports false after its recovery read settles. + * @returns true when the selected persistence mode holds the acknowledgement. */ async acknowledge(): Promise { - const generation = ++this.generation - if (this.persistence === 'memory') { - this.store.update((state) => { - state.status = 'ready' - state.acknowledged = true - state.error = null - }) + if (this.scope.getSnapshot().mode === 'memory') { + this.localAcknowledged = true + this.derive() return true } + this.saving = true this.store.update((state) => { state.status = 'saving'; state.error = null }) try { - const response = await this.api.settings.mutate({ - ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, - ops: [{ op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION }], + await this.scope.set(WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_VERSION) + } finally { + this.saving = false + } + this.derive() + const { acknowledged } = this.store.getSnapshot() + if (!acknowledged) { + this.store.update((state) => { + state.status = 'error' + state.error = 'the acknowledgement did not persist' }) - if (!response.result.ok) throw new Error(response.result.error.message) - if (generation === this.generation) { - this.store.update((state) => { - state.status = 'ready' - state.acknowledged = true - state.error = null - }) - } - return true - } catch (error) { - if (generation === this.generation) { + } + return acknowledged + } + + /** Stop following the scope. */ + dispose(): void { + this.following?.() + this.following = undefined + } + + private derive(): void { + if (this.saving) return + const scope = this.scope.getSnapshot() + if (scope.mode === 'memory') { + this.store.update((state) => { + state.status = 'ready' + state.acknowledged = this.localAcknowledged + state.error = null + }) + return + } + switch (scope.status) { + case 'loading': + this.store.update((state) => { state.status = 'loading'; state.error = null }) + return + case 'unavailable': this.store.update((state) => { state.status = 'error' state.acknowledged = false - state.error = messageOf(error) + state.error = 'welcome acknowledgement settings are unavailable' }) + return + case 'ready': { + const acknowledged = scope.value?.[WELCOME_NOTICE_ACK_FIELD] === WELCOME_NOTICE_VERSION + this.store.update((state) => { + state.status = 'ready' + state.acknowledged = acknowledged + state.error = null + }) + return } - return false + /* v8 ignore next -- every current settings scope status is handled above */ + default: return assertNever(scope.status) } } } - -/** - * Refresh only after welcome state has left idle. A memory-mode load retains - * acknowledgement so reconnect does not reopen a process-local notice. - * @param controller - welcome state owner whose current status decides whether to load. - */ -export function refreshWelcomeIfLoaded(controller: WelcomeNoticeStore): void { - if (controller.store.getSnapshot().status === 'idle') return - void controller.load() -} diff --git a/packages/client/ui-settings-models/tests/apply.client.spec.ts b/packages/client/ui-settings-models/tests/apply.client.spec.ts index 1e49b46ec5..f098a9b7e8 100644 --- a/packages/client/ui-settings-models/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-models/tests/apply.client.spec.ts @@ -4,29 +4,37 @@ import { describe, expect, it, vi } from 'vitest' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { SlotRegistry } from '@deepseek-ai/dsh-client-runtime/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' -import { SettingsSchemaService } from '@deepseek-ai/dsh-client-ui-settings/src/client/schema.ts' +import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client' import { apply, inject, refreshIfLoaded } from '@deepseek-ai/dsh-client-ui-settings-models/client' +import { + WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION, +} from '../src/onboarding-copy.ts' import { ModelsSection } from '../src/client/ModelsSection.tsx' import { DeepSeekOnboardingDialog } from '../src/client/DeepSeekOnboardingDialog.tsx' import { WelcomeNotice } from '../src/client/WelcomeNotice.tsx' -// The service reads its initial locale from the browser; these specs assert -// the shipped Chinese copy, so they state the browser they assume. -usePinnedBrowserLanguages('zh-CN') +// These specs assert the shipped Chinese copy. The lane has no jsdom `window`, +// so browser-language detection never runs and a fresh LocaleRuntime opens on +// FALLBACK_LOCALE (en); bench stages zh explicitly on the locale instead. -async function bench(isLoopback = true) { +async function bench(isLoopback = true, settings?: object, services: object = {}) { const ctx = new Context() await ctx.plugin(SlotRegistry).await() const locale = new LocaleRuntime(ctx) + locale.setLocale('zh') ctx.provide('locale', locale) // The plugins inject `remote`; forwarded events reach them through the // same `$dispatch` handoff the connection sink makes. new TestRemote(ctx) - // The apply path only captures the wire face; no call leaves this fake - // until a section actually loads. - ctx.provide('connection', { api: {}, isLoopback } as never) - new SettingsSchemaService(ctx) + // Without a settings face the mirror's reads fail and stay contained; the + // Models join itself never fetches until a section actually loads. The real + // ui-settings apply also provides the settingsSchema service. + ctx.provide('connection', { + api: settings === undefined ? services : { ...services, settings }, + isLoopback, + } as never) + await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await() return { ctx, slots: ctx.get('slots') as SlotRegistry, locale } } @@ -45,7 +53,7 @@ function declare(slots: SlotRegistry): () => void { describe('ui-settings-models apply', () => { it('declares the services it uses', () => { - expect(inject).toEqual(['slots', 'locale', 'connection', 'remote', 'settingsSchema']) + expect(inject).toEqual(['slots', 'locale', 'connection', 'remote', 'settingsScope', 'settingsSchema']) }) it('registers the models nav entry for declarations before or after apply', async () => { @@ -206,8 +214,31 @@ describe('pushed invalidations', () => { expect(load).toHaveBeenCalledTimes(1) }) - it('routes only the onboarding namespace invalidation into welcome state', async () => { - const b = await bench() + it('welcome state follows the shared mirror across document commits', async () => { + // The welcome notice derives from its settings scope: a document commit + // reaches it through the mirror's one refresh, with no routing here. + const acknowledgement = { current: undefined as string | undefined } + const settings = { + describe: vi.fn(() => Promise.resolve({ + rpcId: 'apply-welcome' as never, + result: { + ok: true as const, + value: { + writable: true, + hasDocument: false, + namespaces: [{ + ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, + schema: {}, + value: acknowledgement.current === undefined ? {} : { [WELCOME_NOTICE_ACK_FIELD]: acknowledgement.current }, + applies: 'live' as const, + secrets: [], + revision: 0, + }], + }, + }, + })), + } + const b = await bench(true, settings) declare(b.slots) await b.ctx.plugin({ inject: [...inject], apply }).await() const entry = b.slots.entries('settings.onboarding') @@ -216,14 +247,59 @@ describe('pushed invalidations', () => { entry.inject as unknown as () => import('../src/client/WelcomeNotice.tsx').WelcomeNoticeInjected )() - injected.hooks.welcome.update((state) => { state.status = 'ready' }) - const load = vi.spyOn(injected.controller, 'load').mockResolvedValue() + await injected.controller.load() + await vi.waitFor(() => { + expect(injected.hooks.welcome.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: false }) + }) + acknowledgement.current = WELCOME_NOTICE_VERSION + b.ctx.remote.$dispatch('settings/document-updated', ['ui-onboarding', 1]) + await vi.waitFor(() => { + expect(injected.hooks.welcome.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true }) + }) + }) - b.ctx.remote.$dispatch('settings/document-updated', ['llm-deepseek', 1]) - expect(load).not.toHaveBeenCalled() - b.ctx.remote.$dispatch('settings/document-updated', ['ui-onboarding', 2]) - expect(load).toHaveBeenCalledOnce() - b.ctx.emit('connection/reset') - expect(load).toHaveBeenCalledTimes(2) + it('joins the refreshed mirror view on a settings invalidation', async () => { + let revision = 1 + const describe = vi.fn(() => Promise.resolve({ + rpcId: `apply-models-${revision}` as never, + result: { + ok: true as const, + value: { + writable: true, + hasDocument: false, + namespaces: [{ + ns: 'llm-test', + schema: {}, + value: {}, + applies: 'live' as const, + secrets: [], + revision, + }], + }, + }, + })) + const providers = vi.fn(() => Promise.resolve({ + rpcId: 'apply-models-providers' as never, + result: { ok: true as const, value: { providers: [] } }, + })) + const b = await bench(true, { describe }, { llm: { providers } }) + declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const entry = b.slots.entries('settings.section') + .find(candidate => candidate.options.id === 'models')! + const injected = ( + entry.inject as unknown as + () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected + )() + await injected.controller.load() + expect(injected.hooks.snapshot.getSnapshot().namespaces.get('llm-test')?.revision).toBe(1) + + revision = 2 + b.ctx.remote.$dispatch('settings/document-updated', ['llm-test', revision]) + + await vi.waitFor(() => { + expect(injected.hooks.snapshot.getSnapshot().namespaces.get('llm-test')?.revision).toBe(2) + }) + expect(describe).toHaveBeenCalledTimes(2) }) }) diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index e5ec3073c3..4948e12335 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -14,6 +14,7 @@ import { DeepSeekModelsEditor, formatCapacity, modelDrafts, parseCapacity, validateDeepSeekModels, } from '../src/client/DeepSeekModelsEditor.tsx' import { apiKeyFailure } from '../src/client/apiKey.ts' +import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' import { deriveKeyRef, ModelsSettingsStore } from '../src/client/store.ts' import type { ProviderRow } from '../src/client/store.ts' import { en } from '../src/client/locales.ts' @@ -186,7 +187,8 @@ type WireFace = ConstructorParameters[0] async function mountFace(scripted: ReturnType) { const { face, update, replace, mutate, set, unset } = scripted - const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema) + const mirror = new SettingsDescribeMirror(face as never) + const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema, mirror) await controller.load() const injected: ModelsSectionProps = { controller, @@ -196,7 +198,7 @@ async function mountFace(scripted: ReturnType) { t, } const view = render() - return { view, face, update, replace, mutate, set, unset, controller } + return { view, face, update, replace, mutate, set, unset, controller, mirror } } async function mountSection(overrides: Parameters[0] = {}) { @@ -267,7 +269,7 @@ describe('ModelsSection', () => { face.credentials.describe.mockImplementation((payload: { refs: string[] }) => Promise.resolve(ok({ credentials: Object.fromEntries(payload.refs.map(ref => [ref, { configured: false, writable: true }])), }))) - const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema) + const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema, new SettingsDescribeMirror(face as never)) await controller.load() render( { face.credentials.describe.mockImplementation((payload: { refs: string[] }) => Promise.resolve(ok({ credentials: Object.fromEntries(payload.refs.map(ref => [ref, { configured: true, writable: true }])), }))) - const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema) + const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema, new SettingsDescribeMirror(face as never)) await controller.load() cleanup() render( { fireEvent.click(screen.getByText(en.apply)) await waitFor(() => { expect(set).toHaveBeenCalledWith({ ref: 'DEEPSEEK_API_KEY', value: 'sk-live' }) }) expect(update).not.toHaveBeenCalled() - await waitFor(() => { expect(face.settings.describe.mock.calls.length).toBeGreaterThan(1) }) + // The saved key re-loads the join; the settings answer rides the shared + // mirror, so the reload shows as a directory read rather than a describe. + await waitFor(() => { expect(face.llm.providers.mock.calls.length).toBeGreaterThan(1) }) expect((await screen.findByRole('status')).textContent).toBe( providerCopy(en.savedProvider, { provider: 'deepseek-official', displayName: 'DeepSeek' }), ) @@ -959,7 +963,7 @@ describe('ModelsSection', () => { const set = vi.fn() .mockResolvedValueOnce(fail('credential store unavailable', 'credential-rejected')) .mockResolvedValueOnce(ok({})) - const { face, controller } = await mountSection({ mutate, set }) + const { face, controller, mirror } = await mountSection({ mutate, set }) fireEvent.click(screen.getByText(en.add)) await screen.findByLabelText(en.provider) fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'sk-ant' } }) @@ -971,7 +975,12 @@ describe('ModelsSection', () => { hasDocument: false, namespaces: wireNamespaces().map(namespace => namespace.ns === 'llm-pi-ai' ? afterSettings : namespace), })) - await act(async () => { await controller.load() }) + // The refreshed settings answer reaches the page through the mirror's own + // refresh (the document commit's invalidation in production). + await act(async () => { + await mirror.load() + await controller.load() + }) expect(controller.store.getSnapshot().namespaces.get('llm-pi-ai')?.revision).toBe(1) fireEvent.click(screen.getByText(en.apply)) await waitFor(() => { expect(set).toHaveBeenCalledTimes(2) }) @@ -1014,7 +1023,7 @@ describe('ModelsSection', () => { const unhandled = vi.fn() process.on('unhandledRejection', unhandled) try { - const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema) + const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema, new SettingsDescribeMirror(face as never)) await controller.load() render( { it('renders the load failure with a retry control', async () => { const face = scriptedFace() face.face.llm.providers = vi.fn(() => Promise.resolve(fail('directory down', 'internal'))) as never - const controller = new ModelsSettingsStore(face.face as unknown as WireFace, settingsSchema) + const controller = new ModelsSettingsStore( + face.face as unknown as WireFace, settingsSchema, new SettingsDescribeMirror(face.face as never)) await controller.load() render( { hasDocument: false, namespaces: wireNamespaces(), }))) - const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema) + const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema, new SettingsDescribeMirror(face as never)) await controller.load() cleanup() render( { it('loads on first render of an idle controller', async () => { const { face } = scriptedFace() - const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema) + const controller = new ModelsSettingsStore(face as unknown as WireFace, settingsSchema, new SettingsDescribeMirror(face as never)) render( { throw new Error('unused standard hook') }) as never diff --git a/packages/client/ui-settings-models/tests/provider-form.client.spec.tsx b/packages/client/ui-settings-models/tests/provider-form.client.spec.tsx index e5e32498d1..8d7e7f2d3c 100644 --- a/packages/client/ui-settings-models/tests/provider-form.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/provider-form.client.spec.tsx @@ -9,6 +9,7 @@ import { ModelsSection, providerCopy } from '../src/client/ModelsSection.tsx' import type { ModelsSectionInjected, ModelsSectionProps } from '../src/client/ModelsSection.tsx' import { CustomProviderCard } from '../src/client/CustomProviderCard.tsx' import { formatCapacity, parseCapacity } from '../src/client/DeepSeekModelsEditor.tsx' +import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' import { ModelsSettingsStore, deriveKeyRef, protocolChoices } from '../src/client/store.ts' import { en } from '../src/client/locales.ts' import { settingsSchema } from './settings-schema.client.ts' @@ -140,7 +141,8 @@ function firstMutate(mutate: ReturnType): MutateCall { async function mountSection(options: Parameters[0] = {}) { const scripted = scriptedFace(options) - const controller = new ModelsSettingsStore(scripted.face as unknown as WireFace, settingsSchema) + const controller = new ModelsSettingsStore( + scripted.face as unknown as WireFace, settingsSchema, new SettingsDescribeMirror(scripted.face as never)) await controller.load() const injected: ModelsSectionProps = { controller, @@ -605,6 +607,27 @@ describe('endpoint interrogation', () => { // A disclosed output cap rides along with the candidate that has one. expect(firstMutate(mutate).ops[0]?.value).toEqual([{ id: 'a' }, { id: 'b', maxTokens: 2048 }]) }) + + it('selects and clears every discovered candidate in one action', async () => { + const discover = vi.fn(() => Promise.resolve(ok({ + models: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], + }))) + await mountSection({ discover }) + openEditor('openai') + + fireEvent.click(screen.getByText(en.fetchModels)) + const dialog = await screen.findByRole('dialog') + const boxes = [...dialog.querySelectorAll('input[type="checkbox"]')] + expect(boxes.map(box => box.checked)).toEqual([true, true, true]) + + fireEvent.click(within_(dialog, en.fetchDeselectAll)) + expect(boxes.map(box => box.checked)).toEqual([false, false, false]) + expect(within_(dialog, en.fetchSelectAll)).toBeTruthy() + + fireEvent.click(within_(dialog, en.fetchSelectAll)) + expect(boxes.map(box => box.checked)).toEqual([true, true, true]) + expect(within_(dialog, en.fetchDeselectAll)).toBeTruthy() + }) }) describe('provider rows', () => { @@ -639,7 +662,8 @@ describe('provider rows', () => { active: true, }], }))) as never - const controller = new ModelsSettingsStore(scripted.face as unknown as WireFace, settingsSchema) + const controller = new ModelsSettingsStore( + scripted.face as unknown as WireFace, settingsSchema, new SettingsDescribeMirror(scripted.face as never)) await controller.load() render((value: T): RpcResponse { @@ -67,13 +68,14 @@ function api(overrides: { unset: () => Promise.resolve(ok({})), }, } - return { face: face as never, seenRefs } + const wire = face as never + return { face: wire, mirror: new SettingsDescribeMirror(wire), seenRefs } } describe('ModelsSettingsStore', () => { it('joins rows with configured, removable, and credential state', async () => { - const { face, seenRefs } = api() - const store = new ModelsSettingsStore(face, settingsSchema) + const { face, mirror, seenRefs } = api() + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await store.load() const state = store.store.getSnapshot() expect(state.status).toBe('ready') @@ -100,8 +102,8 @@ describe('ModelsSettingsStore', () => { }) it('degrades the credential badge, not the page, when the credential domain fails', async () => { - const { face } = api({ describeCredentials: () => Promise.resolve(fail('no provider')) }) - const store = new ModelsSettingsStore(face, settingsSchema) + const { face, mirror } = api({ describeCredentials: () => Promise.resolve(fail('no provider')) }) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await store.load() const state = store.store.getSnapshot() expect(state.status).toBe('ready') @@ -110,10 +112,10 @@ describe('ModelsSettingsStore', () => { }) it('settles a credential transport rejection without leaving the store loading', async () => { - const { face } = api({ + const { face, mirror } = api({ describeCredentials: () => Promise.reject(new Error('credential transport down')), }) - const store = new ModelsSettingsStore(face, settingsSchema) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await expect(store.load()).resolves.toBeUndefined() expect(store.store.getSnapshot()).toMatchObject({ status: 'ready', @@ -122,22 +124,21 @@ describe('ModelsSettingsStore', () => { }) it('stringifies a non-Error credential transport rejection', async () => { - const { face } = api({ - // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the non-Error rejection is the scenario - describeCredentials: () => Promise.reject('credential transport refusal'), + const { face, mirror } = api({ + describeCredentials: async () => { throw 'credential transport refusal' }, }) - const store = new ModelsSettingsStore(face, settingsSchema) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await expect(store.load()).resolves.toBeUndefined() expect(store.store.getSnapshot().credentialError).toBe('credential transport refusal') }) it('surfaces a directory failure and keeps the last good rows', async () => { - const { face } = api() - const store = new ModelsSettingsStore(face, settingsSchema) + const { face, mirror } = api() + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await store.load() expect(store.store.getSnapshot().rows).toHaveLength(4) const broken = api({ providers: () => Promise.resolve(fail('directory down')) }) - const failing = new ModelsSettingsStore(broken.face, settingsSchema) + const failing = new ModelsSettingsStore(broken.face, settingsSchema, broken.mirror) await failing.load() expect(failing.store.getSnapshot()).toMatchObject({ status: 'error', error: 'directory down' }) // The first store's snapshot is untouched by the second's failure. @@ -148,7 +149,7 @@ describe('ModelsSettingsStore', () => { let release: (() => void) | undefined const gate = new Promise((resolve) => { release = resolve }) let call = 0 - const { face } = api({ + const { face, mirror } = api({ providers: async () => { call += 1 if (call === 1) { @@ -158,7 +159,7 @@ describe('ModelsSettingsStore', () => { return ok({ providers: DIRECTORY }) }, }) - const store = new ModelsSettingsStore(face, settingsSchema) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) const first = store.load() const second = store.load() release?.() @@ -169,7 +170,7 @@ describe('ModelsSettingsStore', () => { describe('edge joins', () => { it('treats a non-object profile as having no credential reference', async () => { - const { face } = api({ + const { face, mirror } = api({ describeSettings: () => Promise.resolve(ok({ writable: true, hasDocument: false, @@ -188,7 +189,7 @@ describe('edge joins', () => { ] as never, })), }) - const store = new ModelsSettingsStore(face, settingsSchema) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await store.load() const state = store.store.getSnapshot() expect(state.rows[0]).toMatchObject({ configured: true, removable: false }) @@ -196,7 +197,7 @@ describe('edge joins', () => { }) it('skips the credential describe entirely when no row names a reference', async () => { - const { face, seenRefs } = api({ + const { face, mirror, seenRefs } = api({ describeSettings: () => Promise.resolve(ok({ writable: true, hasDocument: false, @@ -208,24 +209,56 @@ describe('edge joins', () => { ] as never, })), }) - const store = new ModelsSettingsStore(face, settingsSchema) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await store.load() expect(seenRefs).toEqual([]) expect(store.store.getSnapshot().status).toBe('ready') }) it('surfaces a settings describe failure', async () => { - const { face } = api({ describeSettings: () => Promise.resolve(fail('settings down')) }) - const store = new ModelsSettingsStore(face, settingsSchema) + const { face, mirror } = api({ describeSettings: () => Promise.resolve(fail('settings down')) }) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await store.load() expect(store.store.getSnapshot()).toMatchObject({ status: 'error', error: 'settings down' }) }) + it('reports a terminally unavailable settings mirror precisely', async () => { + const { face } = api() + const store = new ModelsSettingsStore( + face, + settingsSchema, + new SettingsDescribeMirror(face, 'memory'), + ) + await store.load() + expect(store.store.getSnapshot()).toMatchObject({ + status: 'error', + error: 'settings are unavailable in this browser', + }) + }) + + it('reuses a held settings view after its refresh fails', async () => { + let settingsCall = 0 + const { face, mirror } = api({ + describeSettings: () => { + settingsCall += 1 + return Promise.resolve(settingsCall === 1 + ? ok({ writable: true, hasDocument: false, namespaces: NAMESPACES }) + : fail('settings refresh down')) + }, + }) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) + await store.load() + await mirror.load() + expect(mirror.getSnapshot().error).toBe('settings refresh down') + await store.load() + expect(store.store.getSnapshot()).toMatchObject({ status: 'ready', error: null }) + expect(store.store.getSnapshot().rows).toHaveLength(4) + }) + it('stringifies a non-Error load failure', async () => { // The wire can surface non-Error throwables; the store must stringify them. - // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the non-Error rejection is the scenario - const { face } = api({ providers: () => Promise.reject('plain refusal') }) - const store = new ModelsSettingsStore(face, settingsSchema) + const { face, mirror } = api({ providers: async () => { throw 'plain refusal' } }) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) await store.load() expect(store.store.getSnapshot()).toMatchObject({ status: 'error', error: 'plain refusal' }) }) @@ -234,7 +267,7 @@ describe('edge joins', () => { let release: (() => void) | undefined const gate = new Promise((resolve) => { release = resolve }) let call = 0 - const { face } = api({ + const { face, mirror } = api({ providers: async () => { call += 1 if (call === 1) { @@ -244,7 +277,7 @@ describe('edge joins', () => { return ok({ providers: DIRECTORY }) }, }) - const store = new ModelsSettingsStore(face, settingsSchema) + const store = new ModelsSettingsStore(face, settingsSchema, mirror) const first = store.load() const second = store.load() await second diff --git a/packages/client/ui-settings-models/tests/welcome-notice.client.spec.tsx b/packages/client/ui-settings-models/tests/welcome-notice.client.spec.tsx index df7ec2f1c8..bf2674976a 100644 --- a/packages/client/ui-settings-models/tests/welcome-notice.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/welcome-notice.client.spec.tsx @@ -2,9 +2,17 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' +import { Context } from '@deepseek-ai/cordis' +import { SettingsSchemaService } from '@deepseek-ai/dsh-client-ui-settings/src/client/schema.ts' +import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' +import { SettingsScopeController } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-scope.ts' + +/** Stateless schema service for scope construction in this jsdom fixture. */ +const schemaService = new SettingsSchemaService(new Context()) import { WelcomeNotice } from '../src/client/WelcomeNotice.tsx' import type { WelcomeNoticeProps } from '../src/client/WelcomeNotice.tsx' -import { WelcomeNoticeStore } from '../src/client/welcome-store.ts' +import { decodeWelcomeSection, WelcomeNoticeStore } from '../src/client/welcome-store.ts' +import type { WelcomeSection } from '../src/client/welcome-store.ts' import { en, zh } from '../src/client/locales.ts' import { WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_COPY, WELCOME_NOTICE_SETTINGS_NAMESPACE, @@ -20,7 +28,24 @@ function response(value: T) { return { rpcId: 'welcome-rpc' as never, result: { ok: true as const, value } } } -function mount(version?: string, mutateImpl: () => Promise = () => Promise.resolve(response({}))) { +function welcomeView(value: unknown, revision = 0) { + return { + ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, + schema: {}, + value, + base: {}, + user: {}, + applies: 'live' as const, + secrets: [], + revision, + } +} + +function mount( + version?: string, + mutateImpl: () => Promise = () => + Promise.resolve(response(welcomeView({ [WELCOME_NOTICE_ACK_FIELD]: WELCOME_NOTICE_VERSION }, 1))), +) { const appRoot = document.createElement('div') appRoot.id = 'root' document.body.append(appRoot) @@ -30,21 +55,21 @@ function mount(version?: string, mutateImpl: () => Promise = () => Prom describe: () => Promise.resolve(response({ writable: true, hasDocument: false, - namespaces: [{ - ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, - schema: {}, - value: version === undefined ? {} : { [WELCOME_NOTICE_ACK_FIELD]: version }, - base: {}, - user: {}, - applies: 'live' as const, - secrets: [], - revision: 0, - }], + namespaces: [welcomeView(version === undefined ? {} : { [WELCOME_NOTICE_ACK_FIELD]: version })], })), mutate, }, } - const controller = new WelcomeNoticeStore(api as never) + const mirror = new SettingsDescribeMirror(api as never) + const scope = new SettingsScopeController( + api as never, + { namespace: WELCOME_NOTICE_SETTINGS_NAMESPACE, decode: decodeWelcomeSection }, + mirror, + 'host', + schemaService, + ) + const controller = new WelcomeNoticeStore(scope) + void mirror.load() const complete = vi.fn() const unusedHook = (() => { throw new Error('unused standard hook') }) as never const props: WelcomeNoticeProps = { @@ -57,7 +82,7 @@ function mount(version?: string, mutateImpl: () => Promise = () => Prom useWelcome: bindSnapshotSelector(controller.store), t: key => zh[key], } - return { ...render(), complete, controller, mutate, appRoot } + return { ...render(), complete, controller, mirror, mutate, appRoot } } describe('WelcomeNotice', () => { @@ -100,7 +125,10 @@ describe('WelcomeNotice', () => { it('skips itself when this exact version was already acknowledged', async () => { const h = mount(WELCOME_NOTICE_VERSION) - await act(async () => { await h.controller.load() }) + await act(async () => { + await h.mirror.load() + await h.controller.load() + }) expect(screen.queryByRole('dialog')).toBeNull() expect(h.complete).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts b/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts index e1fa7572c3..52d2771b0b 100644 --- a/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts +++ b/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts @@ -1,40 +1,58 @@ import { describe, expect, it, vi } from 'vitest' import type { RpcResponse } from '@deepseek-ai/dsh-api-remotes/client' -import { refreshWelcomeIfLoaded, WelcomeNoticeStore } from '../src/client/welcome-store.ts' +import { Context } from '@deepseek-ai/cordis' +import { SettingsSchemaService } from '@deepseek-ai/dsh-client-ui-settings/src/client/schema.ts' +import { SettingsDescribeMirror } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' +import { SettingsScopeController } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-scope.ts' +import { decodeWelcomeSection, WelcomeNoticeStore } from '../src/client/welcome-store.ts' import { WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION, } from '../src/onboarding-copy.ts' +const schemaService = new SettingsSchemaService(new Context()) + let rpc = 0 function ok(value: T): RpcResponse { return { rpcId: `welcome-${rpc++}` as never, result: { ok: true, value } } } -function namespace(version?: string) { +function namespace(value: unknown = {}, revision = 0) { return { ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, schema: {}, - value: version === undefined ? {} : { [WELCOME_NOTICE_ACK_FIELD]: version }, - base: {}, - user: {}, + value, applies: 'live' as const, secrets: [], - revision: 0, + revision, } } -function deferred() { - let resolve!: (value: T) => void - let reject!: (reason: unknown) => void - const promise = new Promise((res, rej) => { resolve = res; reject = rej }) - return { promise, resolve, reject } +function acknowledgedNamespace(version: string, revision = 1) { + return namespace({ [WELCOME_NOTICE_ACK_FIELD]: version }, revision) +} + +/** The welcome store over a real mirror-derived scope and a fake wire. */ +function buildWelcome( + api: { describe?: ReturnType; mutate?: ReturnType }, + persistence: 'host' | 'memory' = 'host', +) { + const wire = { settings: api } as never + const mirror = new SettingsDescribeMirror(wire, persistence) + const scope = new SettingsScopeController( + wire, + { namespace: WELCOME_NOTICE_SETTINGS_NAMESPACE, decode: decodeWelcomeSection }, + mirror, + persistence, + schemaService, + ) + return { mirror, controller: new WelcomeNoticeStore(scope) } } describe('WelcomeNoticeStore', () => { it('acknowledges in memory without calling loopback-only settings APIs', async () => { - const describe = vi.fn() + const describeCall = vi.fn() const mutate = vi.fn() - const controller = new WelcomeNoticeStore({ settings: { describe, mutate } } as never, 'memory') + const { controller } = buildWelcome({ describe: describeCall, mutate }, 'memory') await controller.load() expect(controller.store.getSnapshot()).toEqual({ status: 'ready', acknowledged: false, error: null }) @@ -42,7 +60,7 @@ describe('WelcomeNoticeStore', () => { expect(controller.store.getSnapshot()).toEqual({ status: 'ready', acknowledged: true, error: null }) await controller.load() expect(controller.store.getSnapshot()).toEqual({ status: 'ready', acknowledged: true, error: null }) - expect(describe).not.toHaveBeenCalled() + expect(describeCall).not.toHaveBeenCalled() expect(mutate).not.toHaveBeenCalled() }) @@ -52,148 +70,101 @@ describe('WelcomeNoticeStore', () => { ['older-copy', false], [WELCOME_NOTICE_VERSION, true], ] as const) { - const api = { - settings: { - describe: vi.fn(() => Promise.resolve(ok({ - writable: true, hasDocument: false, namespaces: [namespace(version)], - }))), - }, - } - const controller = new WelcomeNoticeStore(api as never) + const describeCall = vi.fn(() => Promise.resolve(ok({ + writable: true, + hasDocument: false, + namespaces: [version === undefined ? namespace() : acknowledgedNamespace(version)], + }))) + const { mirror, controller } = buildWelcome({ describe: describeCall }) + await mirror.load() await controller.load() expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged }) } }) - it('persists the owner version through one idempotent path mutation', async () => { - const mutate = vi.fn(() => Promise.resolve(ok(namespace(WELCOME_NOTICE_VERSION)))) - const controller = new WelcomeNoticeStore({ settings: { mutate } } as never) + it('persists the owner version through one revision-fenced mutation', async () => { + const describeCall = vi.fn(() => Promise.resolve(ok({ + writable: true, hasDocument: false, namespaces: [namespace({}, 3)], + }))) + const mutate = vi.fn(() => Promise.resolve(ok(acknowledgedNamespace(WELCOME_NOTICE_VERSION, 4)))) + const { mirror, controller } = buildWelcome({ describe: describeCall, mutate }) + await mirror.load() + await controller.load() await expect(controller.acknowledge()).resolves.toBe(true) expect(mutate).toHaveBeenCalledWith({ ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, ops: [{ op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION }], + expectedRevision: 3, }) expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true }) + // The write answer folded into the mirror; no re-read followed. + expect(describeCall).toHaveBeenCalledTimes(1) }) - it('keeps the notice pending when loading or persistence fails', async () => { - const load = new WelcomeNoticeStore({ - settings: { describe: () => Promise.reject(new Error('offline')) }, - } as never) - await load.load() - expect(load.store.getSnapshot()).toEqual({ status: 'error', acknowledged: false, error: 'offline' }) - - const save = new WelcomeNoticeStore({ - settings: { mutate: () => Promise.reject(new Error('disk full')) }, - } as never) - await expect(save.acknowledge()).resolves.toBe(false) - expect(save.store.getSnapshot()).toEqual({ status: 'error', acknowledged: false, error: 'disk full' }) - - const nonError = new WelcomeNoticeStore({ - // Durable/wire failures are unknown; exercise containment of a non-Error rejection. - settings: { describe: () => Promise.reject(new Error('offline string')) }, - } as never) - await nonError.load() - expect(nonError.store.getSnapshot().error).toBe('offline string') + it('keeps the notice pending while the settings read has not answered', async () => { + const describeCall = vi.fn(() => Promise.reject(new Error('offline'))) + const { mirror, controller } = buildWelcome({ describe: describeCall }) + await mirror.load() + await controller.load() + // No answer stands, so the step renders nothing and never acknowledges. + expect(controller.store.getSnapshot()).toEqual({ status: 'loading', acknowledged: false, error: null }) }) - it('reports business failures, missing namespaces, and malformed durable values', async () => { - for (const describe of [ - () => Promise.resolve({ - rpcId: 'failed' as never, - result: { ok: false as const, error: { code: 'internal' as const, message: 'denied', details: {} } }, - }), - () => Promise.resolve(ok({ writable: true, hasDocument: false, namespaces: [] })), - ]) { - const controller = new WelcomeNoticeStore({ settings: { describe } } as never) - await controller.load() - expect(controller.store.getSnapshot().status).toBe('error') - } + it('reports a failed or refused persistence attempt after its recovery read', async () => { + const describeCall = vi.fn(() => Promise.resolve(ok({ + writable: true, hasDocument: false, namespaces: [namespace()], + }))) + const mutate = vi.fn(() => Promise.reject(new Error('disk full'))) + const { mirror, controller } = buildWelcome({ describe: describeCall, mutate }) + await mirror.load() + await controller.load() + await expect(controller.acknowledge()).resolves.toBe(false) + expect(controller.store.getSnapshot()).toMatchObject({ + status: 'error', + acknowledged: false, + error: 'the acknowledgement did not persist', + }) + // The failed latest write triggered one mirror recovery read. + expect(describeCall).toHaveBeenCalledTimes(2) + }) + it('reports a missing namespace as an error instead of a silent skip', async () => { + const describeCall = vi.fn(() => Promise.resolve(ok({ + writable: true, hasDocument: false, namespaces: [], + }))) + const { mirror, controller } = buildWelcome({ describe: describeCall }) + await mirror.load() + await controller.load() + expect(controller.store.getSnapshot()).toMatchObject({ + status: 'error', + error: 'welcome acknowledgement settings are unavailable', + }) + }) + + it('reads malformed durable values as unacknowledged', async () => { for (const value of [null, 42, { [WELCOME_NOTICE_ACK_FIELD]: 42 }]) { - const controller = new WelcomeNoticeStore({ - settings: { describe: () => Promise.resolve(ok({ - writable: true, - hasDocument: false, - namespaces: [{ ...namespace(), value }], - })) }, - } as never) + const describeCall = vi.fn(() => Promise.resolve(ok({ + writable: true, hasDocument: false, namespaces: [namespace(value)], + }))) + const { mirror, controller } = buildWelcome({ describe: describeCall }) + await mirror.load() await controller.load() expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: false }) } - - const save = new WelcomeNoticeStore({ - settings: { mutate: () => Promise.resolve({ - rpcId: 'failed-save' as never, - result: { - ok: false, - error: { - code: 'settings-rejected', - message: 'denied', - details: { ns: WELCOME_NOTICE_SETTINGS_NAMESPACE }, - }, - }, - }) }, - } as never) - await expect(save.acknowledge()).resolves.toBe(false) - expect(save.store.getSnapshot().error).toBe('denied') }) - it('lets the latest load win over stale success and failure', async () => { - const first = deferred>() - const describe = vi.fn() - .mockImplementationOnce(() => first.promise) - .mockImplementationOnce(() => Promise.resolve(ok({ - writable: true, hasDocument: false, namespaces: [namespace()], - }))) - const controller = new WelcomeNoticeStore({ settings: { describe } } as never) - const stale = controller.load() + it('follows a later document change without an own read', async () => { + const describeCall = vi.fn() + .mockResolvedValueOnce(ok({ writable: true, hasDocument: false, namespaces: [namespace()] })) + .mockResolvedValueOnce(ok({ + writable: true, hasDocument: false, + namespaces: [acknowledgedNamespace(WELCOME_NOTICE_VERSION)], + })) + const { mirror, controller } = buildWelcome({ describe: describeCall }) + await mirror.load() await controller.load() - first.resolve(ok({ - writable: true, hasDocument: false, namespaces: [namespace(WELCOME_NOTICE_VERSION)], - })) - await stale - expect(controller.store.getSnapshot().acknowledged).toBe(false) - - const failed = deferred>() - describe - .mockImplementationOnce(() => failed.promise) - .mockImplementationOnce(() => Promise.resolve(ok({ - writable: true, hasDocument: false, namespaces: [namespace(WELCOME_NOTICE_VERSION)], - }))) - const staleFailure = controller.load() - await controller.load() - failed.reject('stale failure') - await staleFailure - expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true, error: null }) - }) - - it('contains stale acknowledgement settlements and refreshes only a loaded store', async () => { - const write = deferred>() - const describe = vi.fn(() => Promise.resolve(ok({ - writable: true, hasDocument: false, namespaces: [namespace()], - }))) - const controller = new WelcomeNoticeStore({ - settings: { mutate: () => write.promise, describe }, - } as never) - refreshWelcomeIfLoaded(controller) - expect(describe).not.toHaveBeenCalled() - const staleWrite = controller.acknowledge() - await controller.load() - write.resolve(ok(namespace(WELCOME_NOTICE_VERSION))) - await expect(staleWrite).resolves.toBe(true) - expect(controller.store.getSnapshot().acknowledged).toBe(false) - refreshWelcomeIfLoaded(controller) - await vi.waitFor(() => { expect(describe).toHaveBeenCalledTimes(2) }) - - const failedWrite = deferred>() - const staleFailure = new WelcomeNoticeStore({ - settings: { mutate: () => failedWrite.promise, describe }, - } as never) - const pending = staleFailure.acknowledge() - await staleFailure.load() - failedWrite.reject('late failure') - await expect(pending).resolves.toBe(false) - expect(staleFailure.store.getSnapshot().status).toBe('ready') + expect(controller.store.getSnapshot()).toMatchObject({ acknowledged: false }) + await mirror.load() + expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true }) }) }) diff --git a/packages/client/ui-settings-plugins/src/client/index.ts b/packages/client/ui-settings-plugins/src/client/index.ts index 82dea6d796..184511ead1 100644 --- a/packages/client/ui-settings-plugins/src/client/index.ts +++ b/packages/client/ui-settings-plugins/src/client/index.ts @@ -72,26 +72,17 @@ export function apply(ctx: ClientContext): void { 'ui-settings-plugins: credential invalidations', ) - // Which namespaces the Host serves is a registration fact the wire does not - // announce, so the directory re-reads on the two signals that can carry a - // changed composition: a settings document commit and a reconnect. + // Which namespaces the Host serves comes from the shared describe mirror, + // whose owning plugin already refreshes it on document commits and + // reconnects — the tab only derives. const configurable = new ConfigurablePluginsTabController( - api, () => ctx.slots.entries('settings.plugin.item')) + ctx.settingsScope.describe(), () => ctx.slots.entries('settings.plugin.item')) ctx.effect(() => () => { configurable.dispose() }, 'ui-settings-plugins: tab directory') - ctx.effect( - () => ctx.remote.$on('settings/document-updated', () => { void configurable.load() }), - 'ui-settings-plugins: served-namespace invalidations', - ) - ctx.effect( - () => ctx.on('connection/reset', () => { void configurable.load() }), - 'ui-settings-plugins: served-namespace reconnect', - ) // A card registered after the first read joins the list without a wire call. ctx.effect( () => ctx.slots.subscribe('settings.plugin.item', () => { configurable.refresh() }), 'ui-settings-plugins: card ledger', ) - void configurable.load() let tabsVersion = -1 let tabsRevision = -1 diff --git a/packages/client/ui-settings-plugins/src/client/tab-store.ts b/packages/client/ui-settings-plugins/src/client/tab-store.ts index a4ed4439f2..5cd26c69fc 100644 --- a/packages/client/ui-settings-plugins/src/client/tab-store.ts +++ b/packages/client/ui-settings-plugins/src/client/tab-store.ts @@ -10,7 +10,7 @@ * trace and does not count toward the empty line. */ -import type { IApiClient } from '@deepseek-ai/dsh-client-connection/client' +import type { SettingsDescribeFace } from '@deepseek-ai/dsh-client-ui-settings/client' import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' @@ -42,47 +42,23 @@ export interface ConfigurablePluginsTabFace { } } -/** Reads the served namespaces and pairs them with the cards that claim them. */ +/** Derives the served namespaces from the shared describe mirror and pairs them with the cards that claim them. */ export class ConfigurablePluginsTabController { private readonly store = createSnapshotStore({ loaded: false, namespaces: [] }) - /** Last Host answer; kept so a slot mutation republishes without a wire read. */ - private served: readonly string[] = [] - private loaded = false - private generation = 0 private disposed = false + private readonly unsubscribe: () => void /** - * @param api - settings wire face. + * @param describeFace - the shared mirror's describe face; its refreshes + * (document commits, reconnects) are what keep the served set current. * @param entries - reads the cards currently registered into the section's slot. */ constructor( - private readonly api: Pick, + private readonly describeFace: SettingsDescribeFace, private readonly entries: () => readonly StoredEntry[], - ) {} - - /** Opaque read of {@link disposed}: control flow cannot narrow it across awaits. */ - private isDisposed(): boolean { - return this.disposed - } - - /** - * Re-read the served namespaces from the Host and republish. - * @returns settlement after the read, or immediately once disposed. - */ - async load(): Promise { - if (this.isDisposed()) return - const generation = ++this.generation - let response: Awaited> - try { - response = await this.api.settings.describe({}) - } catch (_settingsReadFailure) { - // The tab keeps the namespaces it last knew; the next invalidation - // or reconnect reads again. - return - } - if (this.isDisposed() || generation !== this.generation || !response.result.ok) return - this.served = response.result.value.namespaces.map(view => view.ns) - this.loaded = true + ) { + this.unsubscribe = describeFace.subscribe(() => { this.publish() }) + void describeFace.ensure() this.publish() } @@ -92,10 +68,10 @@ export class ConfigurablePluginsTabController { this.publish() } - /** Stop publishing; an in-flight read settles without touching the store. */ + /** Stop publishing and stop following the mirror. */ dispose(): void { this.disposed = true - this.generation += 1 + this.unsubscribe() } /** @@ -107,17 +83,20 @@ export class ConfigurablePluginsTabController { } private publish(): void { - const served = new Set(this.served) + if (this.disposed) return + const mirrored = this.describeFace.getSnapshot() + const loaded = mirrored.view !== undefined + const served = new Set(mirrored.view?.namespaces.map(view => view.ns) ?? []) const namespaces = this.entries().flatMap(entry => entry.options.key !== undefined && served.has(entry.options.key) ? [entry.options.key] : []) const previous = this.store.getSnapshot() - // Every settings-document commit re-reads, and most of them change nothing - // this section shows. An observable source must keep its snapshot - // reference until the fact moves, or each unrelated save re-renders the - // whole card list (packages/client/AGENTS.md reactive rule 5). - if (previous.loaded === this.loaded + // Every settings-document commit refreshes the mirror, and most commits + // change nothing this section shows. An observable source must keep its + // snapshot reference until the fact moves, or each unrelated save + // re-renders the whole card list (packages/client/AGENTS.md reactive rule 5). + if (previous.loaded === loaded && previous.namespaces.length === namespaces.length && previous.namespaces.every((ns, index) => ns === namespaces[index])) return - this.store.set({ loaded: this.loaded, namespaces }) + this.store.set({ loaded, namespaces }) } } diff --git a/packages/client/ui-settings-plugins/tests/apply.client.spec.ts b/packages/client/ui-settings-plugins/tests/apply.client.spec.ts index b41e89e3ca..23e46e15a5 100644 --- a/packages/client/ui-settings-plugins/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-plugins/tests/apply.client.spec.ts @@ -5,17 +5,16 @@ import { describe, expect, it, vi } from 'vitest' import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' import { SlotRegistry } from '@deepseek-ai/dsh-client-runtime/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' -import { SettingsSchemaService } from '@deepseek-ai/dsh-client-ui-settings/src/client/schema.ts' -import { SettingsScopeBinder } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-scope.ts' +import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-plugins/client' import type { ConfigurablePluginsTabFace, PluginsSettingsSectionInjected, } from '@deepseek-ai/dsh-client-ui-settings-plugins/client' -// The service reads its initial locale from the browser; these specs assert -// the shipped Chinese copy, so they state the browser they assume. -usePinnedBrowserLanguages('zh-CN') +// These specs assert the shipped Chinese copy. The lane has no jsdom `window`, +// so browser-language detection never runs and a fresh LocaleRuntime opens on +// FALLBACK_LOCALE (en); bench stages zh explicitly on the locale instead. /** * @param served - namespaces the Host describes; omitted answers a failed read, @@ -25,6 +24,7 @@ async function bench(served?: string[]) { const ctx = new Context() await ctx.plugin(SlotRegistry).await() const locale = new LocaleRuntime(ctx) + locale.setLocale('zh') ctx.provide('locale', locale) const describeCredentials = vi.fn(() => Promise.resolve({ rpcId: 'c', result: { ok: false, error: {} } })) const describeSettings = vi.fn(() => Promise.resolve(served === undefined @@ -53,7 +53,7 @@ async function bench(served?: string[]) { credentials: { describe: describeCredentials }, }, } as never) - await ctx.plugin(SettingsScopeBinder, new SettingsSchemaService(ctx)).await() + await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await() return { ctx, slots: ctx.get('slots') as SlotRegistry, describeCredentials, describeSettings } } diff --git a/packages/client/ui-settings-plugins/tests/stores.client.spec.ts b/packages/client/ui-settings-plugins/tests/stores.client.spec.ts index 9901bc5eb1..396678698b 100644 --- a/packages/client/ui-settings-plugins/tests/stores.client.spec.ts +++ b/packages/client/ui-settings-plugins/tests/stores.client.spec.ts @@ -8,6 +8,9 @@ import { stubSettingsScope, type StubSettingsScope } from '@deepseek-ai/dsh-clie import { CardForm, numberField, textField } from '../src/client/card-form.ts' import { AgentLoopCardController, type AgentLoopSettings } from '../src/client/agent-loop-card-controller.ts' import { BashCardController, type BashSettings } from '../src/client/bash-card-controller.ts' +import { + SettingsDescribeMirror, type SettingsMirrorSnapshot, +} from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-mirror.ts' import { ConfigurablePluginsTabController } from '../src/client/tab-store.ts' import { WebSearchCardController, type WebSearchSettings } from '../src/client/web-search-card-controller.ts' @@ -555,7 +558,7 @@ describe('ConfigurablePluginsTabController', () => { }, }, })) - return { api: { settings: { describe } } as never, describe } + return { mirror: new SettingsDescribeMirror({ settings: { describe } } as never), describe } } /** Slot ledger stand-in: one stored entry per registered card key. */ @@ -565,9 +568,9 @@ describe('ConfigurablePluginsTabController', () => { it('dispatches the served namespaces a card claims, in card registration order', async () => { const settings = settingsApi(['bash', 'ui-theme', 'agent-loop']) - const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('agent-loop', 'bash')) + const controller = new ConfigurablePluginsTabController(settings.mirror, () => ledger('agent-loop', 'bash')) - await controller.load() + await settings.mirror.ensure() // ui-theme is served but claimed by no card here — another surface owns // it. The order is the cards', not the Host's: plugin activation can @@ -578,9 +581,9 @@ describe('ConfigurablePluginsTabController', () => { it('never dispatches a card whose namespace this deployment does not serve', async () => { const settings = settingsApi(['bash']) - const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash', 'web-search-deepseek')) + const controller = new ConfigurablePluginsTabController(settings.mirror, () => ledger('bash', 'web-search-deepseek')) - await controller.load() + await settings.mirror.ensure() expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash']) }) @@ -588,8 +591,8 @@ describe('ConfigurablePluginsTabController', () => { it('takes a card registered after the read without asking the Host again', async () => { const settings = settingsApi(['bash']) let entries = ledger() - const controller = new ConfigurablePluginsTabController(settings.api, () => entries) - await controller.load() + const controller = new ConfigurablePluginsTabController(settings.mirror, () => entries) + await settings.mirror.ensure() expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual([]) entries = ledger('bash') @@ -599,34 +602,33 @@ describe('ConfigurablePluginsTabController', () => { expect(settings.describe).toHaveBeenCalledOnce() }) - it('keeps the namespaces it knew when a read fails', async () => { + it('keeps the namespaces it knew when a refresh fails', async () => { const settings = settingsApi(['bash']) - const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash')) - await controller.load() + const controller = new ConfigurablePluginsTabController(settings.mirror, () => ledger('bash')) + await settings.mirror.ensure() settings.describe.mockRejectedValueOnce(new Error('offline')) - await controller.load() + await settings.mirror.load() expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash']) }) - it('publishes nothing once disposed, and never claims it was answered', async () => { + it('stops following the mirror once disposed, and never claims it was answered', async () => { const settings = settingsApi(['bash']) - const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash')) + const controller = new ConfigurablePluginsTabController(settings.mirror, () => ledger('bash')) controller.dispose() - await controller.load() + await settings.mirror.load() expect(controller.inject().hooks.configurablePlugins.getSnapshot()) .toEqual({ loaded: false, namespaces: [] }) - expect(settings.describe).not.toHaveBeenCalled() }) it('ignores a slot-ledger change that arrives after disposal', async () => { const settings = settingsApi(['bash']) let entries = ledger() - const controller = new ConfigurablePluginsTabController(settings.api, () => entries) - await controller.load() + const controller = new ConfigurablePluginsTabController(settings.mirror, () => entries) + await settings.mirror.ensure() controller.dispose() entries = ledger('bash') @@ -635,33 +637,49 @@ describe('ConfigurablePluginsTabController', () => { expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual([]) }) - it('drops a read a newer one superseded', async () => { - // The section re-reads on every settings-document invalidation, so a slow - // first answer must not overwrite the newer one that already landed. - const settings = settingsApi(['bash']) - const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash', 'agent-loop')) - const slow = Promise.withResolvers() - settings.describe.mockReturnValueOnce(slow.promise as never) - const stale = controller.load() + it('ignores a mirror notification already queued when disposal starts', () => { + let notify = (): void => {} + let snapshot: SettingsMirrorSnapshot = { + status: 'ready' as const, + view: { writable: true, hasDocument: true, namespaces: [] }, + error: null, + } + const describeFace = { + getSnapshot: () => snapshot, + subscribe: (listener: () => void) => { + notify = listener + return () => {} + }, + ensure: () => Promise.resolve(), + acceptView: vi.fn(), + } as never + const controller = new ConfigurablePluginsTabController(describeFace, () => ledger('bash')) + expect(controller.inject().hooks.configurablePlugins.getSnapshot()) + .toEqual({ loaded: true, namespaces: [] }) - await controller.load() - expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash']) - slow.resolve({ - rpcId: 's-0', - result: { ok: true, value: { writable: true, hasDocument: true, namespaces: [ - { ns: 'agent-loop', schema: {}, value: {}, applies: 'live', secrets: [], revision: 0 }, - ] } }, - }) - await stale + controller.dispose() + snapshot = { + status: 'ready', + view: { + writable: true, + hasDocument: true, + namespaces: [{ + ns: 'bash', schema: {}, value: {}, applies: 'live', secrets: [], revision: 1, + }], + }, + error: null, + } + notify() - expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash']) + expect(controller.inject().hooks.configurablePlugins.getSnapshot()) + .toEqual({ loaded: true, namespaces: [] }) }) it('reports the Host answered even when it serves nothing this tab shows', async () => { const settings = settingsApi(['ui-theme']) - const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash')) + const controller = new ConfigurablePluginsTabController(settings.mirror, () => ledger('bash')) - await controller.load() + await settings.mirror.ensure() expect(controller.inject().hooks.configurablePlugins.getSnapshot()) .toEqual({ loaded: true, namespaces: [] }) diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index 7bf170c1a8..c4188a0eaf 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings/README.md -README.md: 723e6f7120c256406daedd2085eef055b72263fe -README.zh.md: 42f6f6e09ee520542ddc74344be5619adf5adf02 +README.md: 990469573309b3a92b5eeb8bc41d89b226dbd0d4 +README.zh.md: a0ce9d5cf6d4633cec9fbf466083c7a11a947e8e diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index 723e6f7120..9904695733 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -4,8 +4,7 @@ English | [中文](README.zh.md) The settings domain's base layer, with no presentation of its own. It provides `ctx.settingsScope`, the Host transport every preference row binds its durable namespace section through; `ctx.settingsSchema`, the synchronous schema-rehydration, validation, and immutable path-editing service used by settings plugins; and the settings slot types registrants fill: `settings.trigger` / `settings.header` / `settings.close` (chrome content), `settings.action` (ordered content-header actions), `settings.section` (one page per feature), `settings.plugins.tab` (feature-owned pages inside the Plugins section), and `settings.onboarding` (ordered feature-owned pages). It depends on no `ui-*` presentation package, so any feature that owns a preference can reach it; the settings SHELL — the `sidebar.settings` occupant, its navigation, and the chrome — lives in ui-settings-general, because a shell dependency on ui-sidebar would close a reference graph cycle through ui-layout and ui-theme. The shell's own contract types live beside the shell for the same reason. -The plugin injects nothing and waits for nothing: schema operations are synchronous, while `ctx.settingsScope.bind(spec)` resolves the wire face through the caller's context at call time. The bound scope's disposer belongs to the calling fiber, and the caller injects `connection` for the transport and `remote` for invalidation. Listeners exist before the first background read starts, so a row's activation never blocks on the settings transport. A bound scope reloads on the forwarded `settings/document-updated` event for its own namespace and on `connection/reset`. Writes carry one field path and the last known namespace revision as `expectedRevision`; a rejected or failed write re-reads unless a newer write already superseded it, and a stale read never publishes over a newer one. The snapshot carries the resolved section, composition `base`, raw `user`, revision, writability, and host/memory mode. A field is overridden when it is present in `user`, even when its value equals `base`; `unset` clears that override. Without a `decode` in the spec, a section that is not a plain object, fails its rehydrated schema, or carries a schema envelope this client cannot rehydrate publishes no value at all, so a row renders its own absent state instead of a half-decoded one. - +The plugin injects `connection` and `remote` and owns the one `settings.describe` reader in the browser: a shared mirror holding the whole answer, refreshed on every forwarded `settings/document-updated` event and on `connection/reset` (the first connection included — that read closes the window where a commit lands between the eager read and the SSE subscription). Schema operations are synchronous and live on the `settingsSchema` service. `ctx.settingsScope.bind(spec)` returns a per-namespace scope DERIVED from the mirror on the CALLER's context — the scope's disposer belongs to the calling fiber, binding adds no wire read, a row's activation never blocks on the settings transport, and every derived surface shows the same document revision at any moment. Cross-namespace surfaces (schema introspection, the served-namespace directory, `hasDocument`) read the same mirror through `ctx.settingsScope.describe()`, a read/fold face (`getSnapshot`/`subscribe`/`ensure`, plus `acceptView` folding a write answer in). The scope snapshot carries the resolved section, composition `base`, raw `user`, revision, writability, and host/memory mode; a field is overridden when it is present in `user`, even when its value equals `base`, and `unset` clears that override. Writes stay per-scope: one field path fenced by the namespace revision as `expectedRevision`; a committed write folds its answer back into the mirror with no re-read, a rejected or failed latest write triggers one mirror recovery read, and a superseded one leaves recovery to its successor. Without a `decode` in the spec, a section that is not a plain object, fails its rehydrated schema, or carries a schema envelope this client cannot rehydrate publishes no value at all, so a row renders its own absent state instead of a half-decoded one. The cold-boot read count is pinned by `apps/web/tests/startup-rpc-budget.e2e.ts`; a new direct `settings.describe` caller in client code is a regression against it. ## Model Experience None, as the settings domain base serves browser preference storage and slot declarations; nothing here reaches a model request. diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index 42f6f6e09e..a0ce9d5cf6 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -4,8 +4,7 @@ 设置领域的底座,本身不含任何呈现内容。它提供 `ctx.settingsScope`——每个偏好设置行绑定自己那份持久化命名空间分区所用的宿主传输层;`ctx.settingsSchema`——设置插件使用的同步 schema 重建、校验与不可变路径编辑服务;并声明由注册方填充的设置 slot 类型:`settings.trigger`/`settings.header`/`settings.close`(界面框架内容)、`settings.action`(内容标题栏中的有序操作)、`settings.section`(每项功能一页)、`settings.plugins.tab`(“插件”分区内由各功能持有的页面)和 `settings.onboarding`(由各功能持有的有序页面)。它不依赖任何 `ui-*` 呈现包,因此任何持有偏好设置的功能都能够到它;设置**外壳**——`sidebar.settings` 占位方、它的导航与界面框架——位于 ui-settings-general,因为外壳一旦依赖 ui-sidebar,就会经 ui-layout 与 ui-theme 闭合出一条引用图环路。外壳自身的契约类型出于同一原因与外壳放在一起。 -该插件不注入任何服务、也不等待任何服务:schema 操作为同步调用,而 `ctx.settingsScope.bind(spec)` 在调用时经调用方的 context 解析线路面。绑定所得 scope 的 disposer 归调用方 fiber 所有,而由调用方注入 `connection` 取得传输层、注入 `remote` 取得失效通知。监听器在首次后台读取启动之前就已存在,因此某一行的激活绝不会阻塞在设置传输层上。已绑定的 scope 会在收到属于自己命名空间的转发 `settings/document-updated` 事件时、以及在 `connection/reset` 时重新读取。写入携带单一字段路径以及最近已知的命名空间 revision 作为 `expectedRevision`;被拒绝或失败的写入会重新读取,除非已有更新的写入取代了它,而陈旧的读取绝不会覆盖更新的发布结果。快照携带解析后的分区、组合 `base`、原始 `user`、revision、可写性以及 host/内存模式。字段只要出现在 `user` 中即视为覆盖,即使其值与 `base` 相等;`unset` 会清除该覆盖。若 spec 未提供 `decode`,则分区不是普通对象、未通过其重建后的 schema 校验、或携带本客户端无法重建的 schema 信封时,一律不发布任何值,于是行渲染自己的缺失状态,而不是一份半解码的值。 - +该插件注入 `connection` 与 `remote`,并持有浏览器中唯一的 `settings.describe` 读取方:一面持有完整应答的共享镜像,在每次转发的 `settings/document-updated` 事件与 `connection/reset` 时刷新(首次连接也包含在内——这次读取关闭了「提交落在急切读取与 SSE 订阅之间、其失效通知丢失」的窗口)。schema 操作为同步调用,由 `settingsSchema` 服务承载。`ctx.settingsScope.bind(spec)` 在**调用方**的 context 上返回一个由镜像**派生**的按命名空间 scope——scope 的 disposer 归调用方 fiber 所有,绑定不新增任何线路读取,某一行的激活绝不会阻塞在设置传输层上,且任一时刻每个派生面看到的都是同一份文档 revision。跨命名空间的表面(schema 内省、已服务命名空间目录、`hasDocument`)通过 `ctx.settingsScope.describe()` 读同一面镜像,这是一个读取/折叠面(`getSnapshot`/`subscribe`/`ensure`,另有把写应答折入的 `acceptView`)。scope 快照携带解析后的分区、组合 `base`、原始 `user`、revision、可写性以及 host/内存模式;字段只要出现在 `user` 中即视为覆盖,即使其值与 `base` 相等,`unset` 会清除该覆盖。写入仍归各 scope:单一字段路径,以命名空间 revision 作为 `expectedRevision` 围栏;提交成功的写入将应答折回镜像、不再重读,被拒绝或失败的最新写入触发一次镜像恢复读取,被取代的写入则把恢复留给后继者。若 spec 未提供 `decode`,则分区不是普通对象、未通过其重建后的 schema 校验、或携带本客户端无法重建的 schema 信封时,一律不发布任何值,于是行渲染自己的缺失状态,而不是一份半解码的值。冷启动读取次数由 `apps/web/tests/startup-rpc-budget.e2e.ts` 钉住;客户端代码中新增直连 `settings.describe` 调用即是对它的回归。 ## 模型体验 无。设置领域底座为浏览器提供偏好设置存储与 slot 声明;这里没有任何内容进入模型请求。 diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index 9e0d3532dd..f2763da9f7 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -1,16 +1,26 @@ /** * Settings domain base plugin, browser half. Provides `ctx.settingsScope`, the - * settings-namespace Host transport every preference row binds its durable - * section through, and owns the canonical slot-type contract for the settings - * surface. It depends on no `ui-*` presentation package, so any feature that - * owns a preference can reach it: the settings SHELL — the `sidebar.settings` - * occupant, its navigation, and the chrome — lives in ui-settings-general, - * because a shell dependency on ui-sidebar would close a reference cycle - * through ui-layout and ui-theme. Export discipline: packages/client/AGENTS.md. + * settings-namespace scope service every preference row binds its durable + * section through, and owns the one `settings.describe` reader in the browser: + * the describe mirror, whose invalidation subscriptions + * (`settings/document-updated`, `connection/reset`) live here so every derived + * surface refreshes from a single wire read. It depends on no `ui-*` + * presentation package, so any feature that owns a preference can reach it: + * the settings SHELL — the `sidebar.settings` occupant, its navigation, and + * the chrome — lives in ui-settings-general, because a shell dependency on + * ui-sidebar would close a reference cycle through ui-layout and ui-theme. + * Export discipline: packages/client/AGENTS.md. */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +import type { ConnectionHandle } from '@deepseek-ai/dsh-api-remotes/client' +// Type-only pair supplying `$on` and its key face without dragging a build +// artifact into the Host graph (rationale beside the same pair in +// settings-scope.ts). +import type {} from '@deepseek-ai/dsh-api-remotes/types' +import type {} from '@deepseek-ai/dsh-settings/types' import { SettingsSchemaService } from './schema.ts' import { SettingsScopeBinder } from './settings-scope.ts' +import { SettingsDescribeMirror } from './settings-mirror.ts' export type { SettingsGeneralItemOwnerProps, SettingsHeaderOwnerProps, SettingsOnboardingOwnerProps, @@ -19,15 +29,18 @@ export type { export type { SettingsScopeController, SettingsScopeBinder } from './settings-scope.ts' export type { SettingsSchemaService } from './schema.ts' export type { SchemaNode } from './schema.ts' +export type { SettingsDescribeFace, SettingsDescribeView, SettingsMirrorSnapshot } from './settings-mirror.ts' /** - * Required services: none. The transport is resolved per caller through - * `this.ctx` at `bind` time, so this plugin waits for nothing. + * Required services: the wire handle for the mirror's reads and the forwarded + * settings invalidation the mirror refreshes on. */ -export const inject = [] +export const inject = ['connection', 'remote'] /** - * Provide the settings-namespace scope service. + * Provide the settings-namespace scope service over one shared describe + * mirror, and keep that mirror fresh on the two signals that can move the + * settings document: a document commit and a (re)connect. * * Constructing the service in this plugin's fiber keeps its traced methods * bound to each consuming plugin's context. @@ -35,5 +48,22 @@ export const inject = [] */ export function apply(ctx: ClientContext): void { const schema = new SettingsSchemaService(ctx) - new SettingsScopeBinder(ctx, schema) + const connection = ctx.get('connection') as ConnectionHandle + const mirror = new SettingsDescribeMirror( + connection.api, + connection.isLoopback ? 'host' : 'memory', + ) + ctx.effect(() => { + const disposers = [ + (ctx.get('remote') as ClientContext['remote']).$on('settings/document-updated', () => { void mirror.load() }), + ctx.on('connection/reset', () => { void mirror.load() }), + ] + // The first connection also emits connection/reset, so startup normally + // costs two reads (budgeted in startup-rpc-budget.e2e.ts). The in-flight + // fold does not merge them into one; it guarantees at most one pending + // read at a time and that no invalidation arriving mid-read is lost. + void mirror.ensure() + return () => { for (const dispose of disposers) dispose() } + }, 'ui-settings: describe mirror invalidations') + new SettingsScopeBinder(ctx, { mirror, schema }) } diff --git a/packages/client/ui-settings/src/client/settings-mirror.ts b/packages/client/ui-settings/src/client/settings-mirror.ts new file mode 100644 index 0000000000..8e570b6512 --- /dev/null +++ b/packages/client/ui-settings/src/client/settings-mirror.ts @@ -0,0 +1,213 @@ +/** + * Client mirror of the Host settings document: the one `settings.describe` + * reader in the browser. Every settings consumer derives from this store — + * per-namespace scopes through `SettingsScopeBinder.bind`, cross-namespace + * surfaces through the binder's shared describe face — so startup cost and + * freshness are properties of this class, not of how many features own a + * preference. The Host stays the fact source: the mirror re-reads on the + * invalidations its owning plugin subscribes to and folds write answers in + * through {@link SettingsDescribeMirror.acceptView}. + */ + +import type { IApiClient, SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' + +type SettingsFace = Pick + +/** The full `settings.describe` answer the mirror serves. */ +export interface SettingsDescribeView { + /** Every namespace a live Host plugin registered, as the Host reported it. */ + namespaces: readonly SettingsNamespaceView[] + /** Whether the settings provider accepts writes. */ + writable: boolean + /** Whether a native settings document exists for the Host to open. */ + hasDocument: boolean +} + +/** Mirror state every derived settings surface renders from. */ +export interface SettingsMirrorSnapshot { + /** + * `unavailable` is the terminal non-loopback state; `ready` persists across + * later failed refreshes (the held view keeps serving); `idle` means no + * answer is held and no read is running, so `ensure` will start one. + */ + status: 'idle' | 'loading' | 'ready' | 'unavailable' + /** The last good answer; undefined until the first success. */ + view: SettingsDescribeView | undefined + /** The latest refresh failure message, cleared by the next success. */ + error: string | null +} + +/** + * The mirror as cross-namespace surfaces consume it: current answer, + * subscription, first-use read, and the write-answer fold. `load` stays off + * this face — invalidation refreshes belong to the mirror's owning plugin. + */ +export interface SettingsDescribeFace { + /** @returns the current sync snapshot (stable reference until the next change). */ + getSnapshot(): SettingsMirrorSnapshot + /** + * Observe snapshot replacements. + * @param listener - invoked after each snapshot change. + * @returns the disposer removing this listener. + */ + subscribe(listener: () => void): () => void + /** + * Resolve once an answer is held (or the mirror is terminally unavailable), + * reading only from `idle`. + * @returns settlement of the current or newly started read, if any. + */ + ensure(): Promise + /** + * Fold one write answer's namespace view into the held view without a wire + * read, invalidating any older read still in flight. + * @param view - the namespace view a settings write answered with. + */ + acceptView(view: SettingsNamespaceView): void +} + +/** + * Serializes every Host `settings.describe` read behind one snapshot store. + * Concurrent {@link load} calls fold into the in-flight read plus one rerun, + * so an invalidation arriving mid-read is never lost and never duplicated. + */ +export class SettingsDescribeMirror implements SettingsDescribeFace { + private readonly store: SnapshotStore + private inFlight: Promise | undefined + private rerun = false + private generation = 0 + + /** + * @param api - settings wire face. + * @param persistence - remote browsers stay process-local because settings RPCs are loopback-only. + */ + constructor( + private readonly api: SettingsFace, + private readonly persistence: 'host' | 'memory' = 'host', + ) { + this.store = createSnapshotStore({ + status: persistence === 'host' ? 'idle' : 'unavailable', + view: undefined, + error: null, + }) + } + + /** @returns the current sync snapshot (stable reference until the next change). */ + getSnapshot(): SettingsMirrorSnapshot { + return this.store.getSnapshot() + } + + /** + * Observe snapshot replacements. + * @param listener - invoked after each snapshot change. + * @returns the disposer removing this listener. + */ + subscribe(listener: () => void): () => void { + return this.store.subscribe(listener) + } + + /** + * Refresh from the Host. A call during an in-flight read marks one rerun + * after it settles instead of racing a second wire read. + * @returns settlement after this call's freshness is reflected. + */ + load(): Promise { + if (this.persistence === 'memory') return Promise.resolve() + if (this.inFlight !== undefined) { + this.rerun = true + return this.inFlight + } + // Own the slot before the loading publication can synchronously reenter load(). + const run = Promise.resolve().then(() => this.run()) + this.inFlight = run + return run + } + + /** + * Resolve once an answer is held (or the mirror is terminally unavailable), + * reading only from `idle`. The cheap idempotent entry for surfaces that + * render on first use. + * @returns settlement of the current or newly started read, if any. + */ + ensure(): Promise { + if (this.persistence === 'memory') return Promise.resolve() + if (this.inFlight !== undefined) return this.inFlight + if (this.getSnapshot().status === 'idle') return this.load() + return Promise.resolve() + } + + /** + * Fold one write answer's namespace view into the held view without a wire + * read, and invalidate any read still in flight. With no held document, the + * answer is not published as a partial document; an in-flight read reruns so + * it cannot publish a document fetched before the write committed. + * @param view - the namespace view a settings write answered with. + */ + acceptView(view: SettingsNamespaceView): void { + const before = this.store.getSnapshot() + this.generation += 1 + if (this.inFlight !== undefined) this.rerun = true + if (before.view === undefined) return + const namespaces = before.view.namespaces.some(row => row.ns === view.ns) + ? before.view.namespaces.map(row => row.ns === view.ns ? view : row) + : [...before.view.namespaces, view] + this.store.set({ ...before, view: { ...before.view, namespaces } }) + } + + /** + * Convenience row lookup on the held view. + * @param ns - namespace identity. + * @returns the namespace view, or undefined while unanswered or unregistered. + */ + namespace(ns: string): SettingsNamespaceView | undefined { + return this.store.getSnapshot().view?.namespaces.find(row => row.ns === ns) + } + + private async run(): Promise { + // The in-flight slot must clear in the same synchronous segment that + // observes `rerun` false (and on abrupt exit): a `.finally()` on the + // returned promise runs one microtask later, and a `load()` landing in + // that gap would mark a rerun nobody reads, losing the read. + try { + do { + const before = this.store.getSnapshot() + if (before.status === 'idle') this.store.set({ ...before, status: 'loading' }) + // Cleared immediately before the wire read goes out: a load() marked + // earlier (including one reentering from the loading publish above) + // is covered by this very read, while one landing after needs the + // rerun. + this.rerun = false + const generation = ++this.generation + let outcome: { view: SettingsDescribeView } | { failure: string } + try { + const response = await this.api.settings.describe({}) + outcome = response.result.ok + ? { view: response.result.value } + : { failure: response.result.error.message } + } catch (error) { + outcome = { failure: error instanceof Error ? error.message : String(error) } + } + // A write answer invalidates a document read before that write committed. + if (generation !== this.generation) continue + if ('view' in outcome) { + this.store.set({ status: 'ready', view: outcome.view, error: null }) + } else { + const held = this.store.getSnapshot() + // No answer yet: fall back to idle so `ensure` retries; with one, the + // held view keeps serving and only the error field reports the miss. + this.store.set({ + status: held.view === undefined ? 'idle' : 'ready', + view: held.view, + error: outcome.failure, + }) + } + } while (this.shouldRerun()) + } finally { + this.inFlight = undefined + } + } + + private shouldRerun(): boolean { + return this.rerun + } +} diff --git a/packages/client/ui-settings/src/client/settings-scope.ts b/packages/client/ui-settings/src/client/settings-scope.ts index 143838e6ef..36e674c937 100644 --- a/packages/client/ui-settings/src/client/settings-scope.ts +++ b/packages/client/ui-settings/src/client/settings-scope.ts @@ -1,8 +1,11 @@ /** * Host transport for the settings-namespace scope contract. The contract types * live in `dsh-client-runtime` (the common dependency of every feature that - * owns a preference); this file owns the wire behavior and the invalidation - * subscription, both of which are Settings-surface concerns. + * owns a preference); this file owns the per-namespace derivation over the + * shared {@link SettingsDescribeMirror} and the serialized write path, both of + * which are Settings-surface concerns. Reads never touch the wire here: the + * mirror is the one `settings.describe` reader, and every scope is a selector + * over its snapshot. */ import { Service } from '@deepseek-ai/cordis' @@ -21,8 +24,8 @@ import { // Client half declares `ctx.remote` with no generated import, and the // allowlist's `types` subpath is a pure-type source file, so the pair supplies // `$on` and its key face without dragging a build artifact in. The runtime -// `remote` injection belongs to whoever calls `ctx.settingsScope.bind(spec)`: the -// subscription is registered on the caller's own context. +// `remote` injection belongs to the providing plugin's apply, which registers +// the mirror's invalidation subscriptions. import type {} from '@deepseek-ai/dsh-api-remotes/client' import type {} from '@deepseek-ai/dsh-api-remotes/types' // The forwarded event's own declaration: `$on`'s key face is @@ -31,30 +34,40 @@ import type {} from '@deepseek-ai/dsh-api-remotes/types' // cordis `Events` entry (and with it the branded `SettingsNamespace`). import type {} from '@deepseek-ai/dsh-settings/types' import type { SettingsSchemaService } from './schema.ts' +import { SettingsDescribeMirror, type SettingsDescribeFace } from './settings-mirror.ts' + type SettingsFace = Pick /** - * Serializes one namespace's Host reads and writes behind a snapshot store. - * Reads never block plugin activation; writes carry the latest known - * namespace revision and teardown waits for the operation already crossing - * the wire. + * One namespace's derived view over the shared describe mirror, plus that + * namespace's serialized Host writes. Writes carry the latest known namespace + * revision, fold their answers back into the mirror, and teardown waits for + * the operation already crossing the wire. */ export class SettingsScopeController implements SettingsScope { private readonly store: SnapshotStore> private tail: Promise = Promise.resolve() - private readGeneration = 0 private writeGeneration = 0 private disposed = false + private readonly unsubscribe: (() => void) | undefined + /** + * Revision answered by a superseded write still ahead of the mirror: the + * mirror only folds the LATEST settlement in, so a queued successor takes + * its fence from here first. + */ + private pendingRevision: number | undefined /** - * @param api - settings wire face. + * @param api - settings wire face (writes only; reads ride the mirror). * @param spec - namespace identity and optional narrowing decoder. + * @param mirror - the shared describe mirror this scope derives from. * @param persistence - remote browsers remain process-local because settings RPCs are loopback-only. * @param schema - settings-owned schema operations. */ constructor( private readonly api: SettingsFace, private readonly spec: SettingsScopeSpec, + private readonly mirror: SettingsDescribeMirror, private readonly persistence: 'host' | 'memory', private readonly schema: SettingsSchemaService, ) { @@ -67,6 +80,10 @@ export class SettingsScopeController implements SettingsScope { writable: false, mode: persistence, }) + if (persistence === 'host') { + this.unsubscribe = mirror.subscribe(() => { this.derive() }) + this.derive() + } } /** @returns the current sync snapshot (stable reference until the next change). */ @@ -83,15 +100,6 @@ export class SettingsScopeController implements SettingsScope { return this.store.subscribe(listener) } - /** - * Queue a Host refresh; a newer read or user write suppresses stale publication. - * @returns settlement after the queued read completes or is skipped. - */ - load(): Promise { - const generation = ++this.readGeneration - return this.enqueue(() => this.read(generation)) - } - /** * Queue one field write; see {@link SettingsScope.set} for the ordering, * revision, and recovery contract. @@ -114,10 +122,9 @@ export class SettingsScopeController implements SettingsScope { } private write(op: SettingsPathOpView): Promise { - this.readGeneration += 1 const generation = ++this.writeGeneration return this.enqueue(async () => { - const revision = this.getSnapshot().revision + const revision = this.pendingRevision ?? this.getSnapshot().revision let response: Awaited> try { response = await this.api.settings.mutate({ @@ -126,25 +133,39 @@ export class SettingsScopeController implements SettingsScope { ...(revision === undefined ? {} : { expectedRevision: revision }), }) } catch (_settingsWriteFailure) { - if (!this.disposed && generation === this.writeGeneration) await this.read(++this.readGeneration) + await this.recover(generation) return } if (!response.result.ok) { - if (!this.disposed && generation === this.writeGeneration) await this.read(++this.readGeneration) + await this.recover(generation) return } - this.accept(response.result.value, generation === this.writeGeneration) + if (this.disposed) return + if (generation === this.writeGeneration) { + this.pendingRevision = undefined + this.mirror.acceptView(response.result.value) + } else { + this.pendingRevision = response.result.value.revision + } }) } + /** Reload Host state for the latest failed write; superseded failures leave recovery to it. */ + private async recover(generation: number): Promise { + if (this.disposed || generation !== this.writeGeneration) return + this.pendingRevision = undefined + await this.mirror.load() + } + /** - * Stop queued operations and wait for the current wire call to settle. + * Stop queued operations, stop deriving, and wait for the current wire call + * to settle. * @returns settlement after the controller reaches quiescence. */ async dispose(): Promise { this.disposed = true - this.readGeneration += 1 this.writeGeneration += 1 + this.unsubscribe?.() await this.tail } @@ -160,36 +181,25 @@ export class SettingsScopeController implements SettingsScope { return task } - private async read(generation: number): Promise { - let response: Awaited> - try { - response = await this.api.settings.describe({}) - } catch (_settingsReadFailure) { - return - } - if (!response.result.ok || this.disposed) return - const { namespaces, writable } = response.result.value - const view = namespaces.find(candidate => candidate.ns === this.spec.namespace) - const publish = generation === this.readGeneration + private derive(): void { + if (this.disposed) return + const mirrored = this.mirror.getSnapshot() + if (mirrored.view === undefined) return + const { writable } = mirrored.view + const view = mirrored.view.namespaces.find(candidate => candidate.ns === this.spec.namespace) if (view === undefined) { - if (publish) { - this.store.update((draft) => { - draft.status = 'unavailable' - draft.writable = writable - }) - } + this.store.update((draft) => { + draft.status = 'unavailable' + draft.writable = writable + }) return } - this.accept(view, publish, writable) - } - - private accept(view: SettingsNamespaceView, publish: boolean, writable?: boolean): void { - const decoded = publish ? this.decode(view) : undefined + const decoded = this.decode(view) this.store.update((draft) => { draft.revision = view.revision draft.base = view.base draft.user = view.user - if (writable !== undefined) draft.writable = writable + draft.writable = writable if (decoded === undefined) return draft.status = 'ready' draft.value = decoded @@ -227,20 +237,38 @@ declare module '@deepseek-ai/cordis' { * (`packages/client/tsdown.client.ts`). */ export class SettingsScopeBinder extends Service { + private readonly mirror: SettingsDescribeMirror + private readonly schema: SettingsSchemaService + /** * @param ctx - the providing plugin's context. + * @param config - the shared describe mirror every bound scope derives from, + * plus the settings-owned schema operations. */ - constructor(ctx: Context, private readonly schema: SettingsSchemaService) { + constructor(ctx: Context, config: { mirror: SettingsDescribeMirror; schema: SettingsSchemaService }) { super(ctx, 'settingsScope') + this.mirror = config.mirror + this.schema = config.schema } /** - * Bind one namespace scope to settings and connection invalidations on the - * CALLER's plugin lifecycle — the service proxy binds `this.ctx` to the - * caller at call time, so the scope's disposer belongs to the calling fiber. - * Listeners exist before the initial background read starts, so activation - * never blocks on the settings transport. The caller injects `connection` - * for the transport and `remote` for the forwarded settings invalidation. + * The shared mirror's read/fold face for cross-namespace surfaces (schema + * introspection, the served-namespace directory). Per-namespace consumers + * use {@link bind}; both derive from the same snapshot, so they can never + * disagree about the document. + * @returns the describe face over the shared mirror. + */ + describe(): SettingsDescribeFace { + return this.mirror + } + + /** + * Bind one namespace scope on the CALLER's plugin lifecycle — the service + * proxy binds `this.ctx` to the caller at call time, so the scope's disposer + * belongs to the calling fiber. The scope derives from the shared mirror + * (whose invalidation subscriptions live with the providing plugin), so + * binding adds no wire read of its own and activation never blocks on the + * settings transport. * @param spec - domain-owned namespace contract. * @returns the bound scope consumed by the domain's services and rows. */ @@ -250,21 +278,13 @@ export class SettingsScopeBinder extends Service { const controller = new SettingsScopeController( connection.api, spec, + this.mirror, connection.isLoopback ? 'host' : 'memory', this.schema, ) ctx.effect(() => { - const refresh = (namespace?: string): void => { - if (namespace !== undefined && namespace !== spec.namespace) return - void controller.load() - } - const disposers = [ - (ctx.get('remote') as Context['remote']).$on('settings/document-updated', refresh), - ctx.on('connection/reset', () => { refresh() }), - ] - void controller.load() + void this.mirror.ensure() return async () => { - for (const dispose of disposers) dispose() await controller.dispose() } }, `ui-settings: ${spec.namespace} settings scope`) diff --git a/packages/client/ui-settings/tests/plugin.client.spec.ts b/packages/client/ui-settings/tests/plugin.client.spec.ts index 9863b985e3..136e061e0f 100644 --- a/packages/client/ui-settings/tests/plugin.client.spec.ts +++ b/packages/client/ui-settings/tests/plugin.client.spec.ts @@ -1,33 +1,60 @@ /** * The settings domain base plugin's own mounting behavior: it stands up - * `ctx.settingsScope` for every feature that owns a preference row, and the - * service retires with its fiber. + * `ctx.settingsScope` over one shared describe mirror, keeps that mirror + * fresh on settings-document and connection-reset invalidations, and retires + * both the service and the subscriptions with its fiber. */ import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { apply, inject } from '../src/client/index.ts' import { SettingsSchemaService } from '../src/client/schema.ts' import { SettingsScopeBinder } from '../src/client/settings-scope.ts' -/** Boot the browser half over a bare root context; it injects nothing. */ +/** Boot the browser half over a fake loopback connection and test remote. */ function bench() { + const describeCall = vi.fn().mockResolvedValue({ + rpcId: 'plugin-bench' as never, + result: { ok: true, value: { writable: true, hasDocument: true, namespaces: [] } }, + }) const ctx = new Context() - return { ctx, fiber: ctx.plugin({ inject: [...inject], apply }) } + ctx.provide('connection', { + api: { settings: { describe: describeCall } }, + isLoopback: true, + } as never) + new TestRemote(ctx) + return { ctx, describeCall, fiber: ctx.plugin({ inject: [...inject], apply }) } } describe('settings domain base plugin', () => { - it('mounts the scope service under settingsScope', async () => { - const { ctx, fiber } = bench() + it('mounts the scope service under settingsScope and reads once eagerly', async () => { + const { ctx, describeCall, fiber } = bench() await fiber.await() expect(ctx.get('settingsScope')).toBeInstanceOf(SettingsScopeBinder) expect(ctx.get('settingsSchema')).toBeInstanceOf(SettingsSchemaService) + await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(1) }) }) - it('fiber disposal retires the service', async () => { - const { ctx, fiber } = bench() + it('refreshes the mirror on document commits and connection resets, once each', async () => { + const { ctx, describeCall, fiber } = bench() await fiber.await() + await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(1) }) + ctx.remote.$dispatch('settings/document-updated', ['ui-test', 0]) + await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(2) }) + ctx.emit('connection/reset') + await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(3) }) + }) + + it('fiber disposal retires the service and its invalidation subscriptions', async () => { + const { ctx, describeCall, fiber } = bench() + await fiber.await() + await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(1) }) await fiber.dispose() expect(ctx.get('settingsScope')).toBeUndefined() expect(ctx.get('settingsSchema')).toBeUndefined() + ctx.remote.$dispatch('settings/document-updated', ['ui-test', 0]) + ctx.emit('connection/reset') + await Promise.resolve() + expect(describeCall).toHaveBeenCalledTimes(1) }) }) diff --git a/packages/client/ui-settings/tests/settings-mirror.client.spec.ts b/packages/client/ui-settings/tests/settings-mirror.client.spec.ts new file mode 100644 index 0000000000..6439a3000e --- /dev/null +++ b/packages/client/ui-settings/tests/settings-mirror.client.spec.ts @@ -0,0 +1,216 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcResponse, SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' +import { SettingsDescribeMirror, type SettingsDescribeView } from '../src/client/settings-mirror.ts' + +let rpc = 0 + +function ok(value: T): RpcResponse { + return { rpcId: `mirror-${rpc++}` as never, result: { ok: true, value } } +} + +function rejected(message: string): RpcResponse { + return { + rpcId: `mirror-${rpc++}` as never, + result: { + ok: false, + error: { code: 'settings-rejected', message, details: { ns: 'theme' } }, + }, + } +} + +function view(ns: string, revision = 0): SettingsNamespaceView { + return { ns, schema: {}, value: { field: ns }, applies: 'live', secrets: [], revision } +} + +function described(namespaces: SettingsNamespaceView[]): RpcResponse { + return ok({ writable: true, hasDocument: true, namespaces }) +} + +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise((res) => { resolve = res }) + return { promise, resolve } +} + +describe('SettingsDescribeMirror', () => { + it('folds loads before the wire read into it, and mid-flight loads into one rerun', async () => { + const gate = deferred>() + const describeCall = vi.fn() + .mockReturnValueOnce(gate.promise) + .mockResolvedValue(described([view('theme', 1)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + const first = mirror.load() + // Issued before the wire read goes out: covered by that read, no rerun. + const early = mirror.load() + await Promise.resolve() + expect(describeCall).toHaveBeenCalledTimes(1) + // Issued while the read is on the wire: exactly one rerun, however many. + const mid = mirror.load() + const midToo = mirror.load() + gate.resolve(described([view('theme', 0)])) + await Promise.all([first, early, mid, midToo]) + expect(describeCall).toHaveBeenCalledTimes(2) + expect(mirror.getSnapshot().status).toBe('ready') + expect(mirror.namespace('theme')?.revision).toBe(1) + }) + + it('keeps the last good view when a later refresh fails, recording the failure', async () => { + const describeCall = vi.fn() + .mockResolvedValueOnce(described([view('theme', 2)])) + .mockRejectedValueOnce(new Error('host gone')) + .mockResolvedValueOnce(rejected('busy')) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + await mirror.load() + expect(mirror.getSnapshot()).toMatchObject({ status: 'ready', error: null }) + await mirror.load() + expect(mirror.getSnapshot()).toMatchObject({ status: 'ready', error: 'host gone' }) + expect(mirror.namespace('theme')?.revision).toBe(2) + await mirror.load() + expect(mirror.getSnapshot()).toMatchObject({ status: 'ready', error: 'busy' }) + expect(mirror.getSnapshot().view?.namespaces).toHaveLength(1) + }) + + it('returns to idle after a first read that never succeeded, so ensure retries', async () => { + const describeCall = vi.fn() + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValueOnce(described([view('theme', 1)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + await mirror.ensure() + expect(mirror.getSnapshot()).toMatchObject({ status: 'idle', view: undefined, error: 'offline' }) + await mirror.ensure() + expect(mirror.getSnapshot()).toMatchObject({ status: 'ready', error: null }) + expect(describeCall).toHaveBeenCalledTimes(2) + }) + + it('treats ensure as a no-op once ready', async () => { + const describeCall = vi.fn().mockResolvedValue(described([view('theme', 1)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + await mirror.ensure() + await mirror.ensure() + await mirror.ensure() + expect(describeCall).toHaveBeenCalledTimes(1) + }) + + it('memory persistence is terminally unavailable and never touches the wire', async () => { + const describeCall = vi.fn() + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never, 'memory') + await mirror.ensure() + await mirror.load() + expect(mirror.getSnapshot()).toEqual({ status: 'unavailable', view: undefined, error: null }) + expect(describeCall).not.toHaveBeenCalled() + }) + + it('acceptView folds one write answer into the held view without a wire read', async () => { + const describeCall = vi.fn() + .mockResolvedValueOnce(described([view('theme', 1), view('locale', 4)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + await mirror.load() + const seen: number[] = [] + mirror.subscribe(() => { seen.push(mirror.namespace('theme')?.revision ?? -1) }) + mirror.acceptView(view('theme', 9)) + expect(mirror.namespace('theme')?.revision).toBe(9) + expect(mirror.namespace('locale')?.revision).toBe(4) + expect(seen).toEqual([9]) + expect(describeCall).toHaveBeenCalledTimes(1) + }) + + it('acceptView before any answer is a no-op instead of inventing a document', () => { + const describeCall = vi.fn() + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + mirror.acceptView(view('theme', 1)) + expect(mirror.getSnapshot()).toEqual({ status: 'idle', view: undefined, error: null }) + }) + + it('acceptView appends a namespace the held view has not seen yet', async () => { + const describeCall = vi.fn().mockResolvedValueOnce(described([view('theme', 1)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + await mirror.load() + mirror.acceptView(view('fresh-ns', 0)) + expect(mirror.namespace('fresh-ns')).toBeDefined() + expect(mirror.getSnapshot().view?.namespaces).toHaveLength(2) + }) + + it('never loses a load landing between a run settling and its slot clearing', async () => { + // Regression: with the in-flight slot cleared by a promise .finally(), + // a load() in the one-microtask gap after the rerun check marked a rerun + // nobody read, and that refresh never reached the wire. + const describeCall = vi.fn().mockResolvedValue(described([view('theme', 1)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + void mirror.load() + await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(1) }) + void mirror.load() + await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(2) }) + void mirror.load() + await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(3) }) + }) + + it('starts no second run for a load issued inside the loading publish', async () => { + const gate = deferred>() + const describeCall = vi.fn().mockReturnValue(gate.promise) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + let reentered = false + const unsubscribe = mirror.subscribe(() => { + if (reentered) return + reentered = true + void mirror.load() + }) + const loading = mirror.load() + await Promise.resolve() + expect(describeCall).toHaveBeenCalledTimes(1) + gate.resolve(described([view('theme', 1)])) + await loading + unsubscribe() + // The reentrant load folded into the first run rather than racing it. + expect(describeCall).toHaveBeenCalledTimes(1) + expect(mirror.getSnapshot().status).toBe('ready') + }) + + it('lets the first read cover a write folded inside the loading publish', async () => { + const describeCall = vi.fn().mockResolvedValue(described([view('theme', 2)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + const unsubscribe = mirror.subscribe(() => { + unsubscribe() + mirror.acceptView(view('theme', 2)) + }) + + await mirror.load() + + expect(describeCall).toHaveBeenCalledTimes(1) + expect(mirror.getSnapshot().status).toBe('ready') + expect(mirror.namespace('theme')?.revision).toBe(2) + }) + + it('re-reads after a folded write invalidates an in-flight document', async () => { + const slow = deferred>() + const describeCall = vi.fn() + .mockResolvedValueOnce(described([view('theme', 4), view('locale', 1)])) + .mockReturnValueOnce(slow.promise) + .mockResolvedValueOnce(described([view('theme', 5), view('locale', 2)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + await mirror.load() + expect(describeCall).toHaveBeenCalledTimes(1) + const stale = mirror.load() + await Promise.resolve() + mirror.acceptView(view('theme', 5)) + slow.resolve(described([view('theme', 4), view('locale', 2)])) + await stale + expect(describeCall).toHaveBeenCalledTimes(3) + expect(mirror.namespace('theme')?.revision).toBe(5) + expect(mirror.namespace('locale')?.revision).toBe(2) + }) + + it('re-reads after a pre-answer write invalidates the in-flight document', async () => { + const slow = deferred>() + const describeCall = vi.fn() + .mockReturnValueOnce(slow.promise) + .mockResolvedValueOnce(described([view('theme', 2)])) + const mirror = new SettingsDescribeMirror({ settings: { describe: describeCall } } as never) + const loading = mirror.load() + await Promise.resolve() + mirror.acceptView(view('theme', 2)) + slow.resolve(described([view('theme', 1)])) + await loading + expect(describeCall).toHaveBeenCalledTimes(2) + expect(mirror.namespace('theme')?.revision).toBe(2) + }) +}) diff --git a/packages/client/ui-settings/tests/settings-scope.client.spec.ts b/packages/client/ui-settings/tests/settings-scope.client.spec.ts index e8ec66c549..ddbb6784d1 100644 --- a/packages/client/ui-settings/tests/settings-scope.client.spec.ts +++ b/packages/client/ui-settings/tests/settings-scope.client.spec.ts @@ -1,13 +1,14 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { describe, expect, it, vi } from 'vitest' -import type { IApiClient, RpcResponse, SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' +import type { RpcResponse, SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' -import type { SettingsScope, SettingsScopeSpec } from '@deepseek-ai/dsh-client-runtime/client' +import type { SettingsScope } from '@deepseek-ai/dsh-client-runtime/client' import { SettingsSchemaService } from '../src/client/schema.ts' -import { - SettingsScopeBinder, SettingsScopeController as ProductionSettingsScopeController, -} from '../src/client/settings-scope.ts' +import { SettingsScopeController, SettingsScopeBinder } from '../src/client/settings-scope.ts' +import { SettingsDescribeMirror } from '../src/client/settings-mirror.ts' + +const settingsSchema = new SettingsSchemaService(new Context()) interface UiTestSettings { preference: 'light' | 'dark' | 'system' @@ -17,17 +18,6 @@ const ENVELOPE = z.object({ preference: z.union(['light', 'dark', 'system']).default('system'), }).toJSON() -const settingsSchema = new SettingsSchemaService(new Context()) -const SettingsScopeController = class extends ProductionSettingsScopeController { - constructor( - api: Pick, - spec: SettingsScopeSpec, - persistence: 'host' | 'memory' = 'host', - ) { - super(api, spec, persistence, settingsSchema) - } -} - let rpc = 0 function ok(value: T): RpcResponse { @@ -66,6 +56,17 @@ function deferred() { return { promise, resolve, reject } } +/** A host-mode mirror plus a controller derived from it, over one fake wire. */ +function derivedScope( + api: { describe?: ReturnType; mutate?: ReturnType }, + spec: { namespace: string; decode?: (section: unknown) => UiTestSettings | undefined } = { namespace: 'ui-test' }, +) { + const wire = { settings: api } as never + const mirror = new SettingsDescribeMirror(wire) + const scope = new SettingsScopeController(wire, spec, mirror, 'host', settingsSchema) + return { mirror, scope } +} + /** Record each distinct published section, starting from the current one. */ function trackValues(scope: SettingsScope): Array { const seen: Array = [scope.getSnapshot().value] @@ -77,16 +78,13 @@ function trackValues(scope: SettingsScope): Array { - it('starts loading and publishes a schema-valid section with revision and writability', async () => { + it('starts loading and derives a schema-valid section with revision and writability', async () => { const describeCall = vi.fn().mockResolvedValueOnce(described({ preference: 'dark' }, 3)) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { namespace: 'ui-test' }, - ) + const { mirror, scope } = derivedScope({ describe: describeCall }) expect(scope.getSnapshot()).toEqual({ status: 'loading', value: undefined, revision: undefined, writable: false, mode: 'host', }) - await scope.load() + await mirror.load() expect(scope.getSnapshot()).toEqual({ status: 'ready', value: { preference: 'dark' }, revision: 3, writable: true, mode: 'host', }) @@ -101,12 +99,9 @@ describe('SettingsScopeController', () => { .mockResolvedValueOnce(described(['queue'], 7)) .mockResolvedValueOnce(rejected()) .mockRejectedValueOnce(new Error('offline')) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { namespace: 'ui-test' }, - ) + const { mirror, scope } = derivedScope({ describe: describeCall }) const good = trackValues(scope) - for (let i = 0; i < 7; i++) await scope.load() + for (let i = 0; i < 7; i++) await mirror.load() expect(scope.getSnapshot()).toMatchObject({ status: 'ready', value: { preference: 'dark' }, revision: 7, }) @@ -117,45 +112,22 @@ describe('SettingsScopeController', () => { const broken = { ...view({ preference: 'dark' }, 2), schema: null } const describeCall = vi.fn() .mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [broken] })) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { namespace: 'ui-test' }, - ) - await scope.load() + const { mirror, scope } = derivedScope({ describe: describeCall }) + await mirror.load() expect(scope.getSnapshot()).toMatchObject({ status: 'loading', value: undefined, revision: 2 }) }) - it('suppresses a superseded read of an unexposed namespace', async () => { - const describeCall = vi.fn() - .mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [] })) - .mockResolvedValueOnce(described({ preference: 'dark' }, 1)) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { namespace: 'ui-test' }, - ) - const statuses: string[] = [] - scope.subscribe(() => { statuses.push(scope.getSnapshot().status) }) - const stale = scope.load() - const fresh = scope.load() - await Promise.all([stale, fresh]) - expect(statuses).not.toContain('unavailable') - expect(scope.getSnapshot()).toMatchObject({ status: 'ready', value: { preference: 'dark' } }) - }) - it('reports an unexposed namespace as unavailable and recovers when it reappears', async () => { const describeCall = vi.fn() .mockResolvedValueOnce(described({ preference: 'light' }, 1)) .mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [] })) .mockResolvedValueOnce(described({ preference: 'system' }, 2)) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { namespace: 'ui-test' }, - ) - await scope.load() + const { mirror, scope } = derivedScope({ describe: describeCall }) + await mirror.load() expect(scope.getSnapshot().status).toBe('ready') - await scope.load() + await mirror.load() expect(scope.getSnapshot()).toMatchObject({ status: 'unavailable', value: { preference: 'light' } }) - await scope.load() + await mirror.load() expect(scope.getSnapshot()).toMatchObject({ status: 'ready', value: { preference: 'system' }, revision: 2 }) }) @@ -163,18 +135,15 @@ describe('SettingsScopeController', () => { const describeCall = vi.fn() .mockResolvedValueOnce(described({ preference: 'light' }, 1)) .mockResolvedValueOnce(described({ preference: 'dark' }, 2)) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { - namespace: 'ui-test', - decode: section => (section as UiTestSettings).preference === 'dark' - ? section as UiTestSettings - : undefined, - }, - ) - await scope.load() + const { mirror, scope } = derivedScope({ describe: describeCall }, { + namespace: 'ui-test', + decode: section => (section as UiTestSettings).preference === 'dark' + ? section as UiTestSettings + : undefined, + }) + await mirror.load() expect(scope.getSnapshot()).toMatchObject({ status: 'loading', value: undefined, revision: 1 }) - await scope.load() + await mirror.load() expect(scope.getSnapshot()).toMatchObject({ status: 'ready', value: { preference: 'dark' }, revision: 2 }) }) @@ -184,12 +153,9 @@ describe('SettingsScopeController', () => { const mutate = vi.fn() .mockReturnValueOnce(first.promise) .mockResolvedValueOnce(ok(view({ preference: 'light' }, 6))) - const scope = new SettingsScopeController( - { settings: { describe: describeCall, mutate } } as never, - { namespace: 'ui-test' }, - ) + const { mirror, scope } = derivedScope({ describe: describeCall, mutate }) const published = trackValues(scope) - await scope.load() + await mirror.load() const dark = scope.set('preference', 'dark') const light = scope.set('preference', 'light') await vi.waitFor(() => { expect(mutate).toHaveBeenCalledOnce() }) @@ -209,6 +175,41 @@ describe('SettingsScopeController', () => { }) }) + it('folds the latest write answer into the mirror so a sibling scope sees it', async () => { + const describeCall = vi.fn().mockResolvedValueOnce(described({ preference: 'system' }, 4)) + const mutate = vi.fn().mockResolvedValueOnce(ok(view({ preference: 'dark' }, 5))) + const wire = { settings: { describe: describeCall, mutate } } as never + const mirror = new SettingsDescribeMirror(wire) + const writer = new SettingsScopeController(wire, { namespace: 'ui-test' }, mirror, 'host', settingsSchema) + const sibling = new SettingsScopeController(wire, { namespace: 'ui-test' }, mirror, 'host', settingsSchema) + await mirror.load() + await writer.set('preference', 'dark') + expect(describeCall).toHaveBeenCalledTimes(1) + expect(sibling.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, revision: 5 }) + }) + + it('re-reads after a revisionless first write lands during the initial read', async () => { + const initial = deferred>() + const describeCall = vi.fn() + .mockReturnValueOnce(initial.promise) + .mockResolvedValueOnce(described({ preference: 'dark' }, 2)) + const mutate = vi.fn().mockResolvedValueOnce(ok(view({ preference: 'dark' }, 2))) + const { mirror, scope } = derivedScope({ describe: describeCall, mutate }) + const loading = mirror.load() + await Promise.resolve() + + await scope.set('preference', 'dark') + initial.resolve(described({ preference: 'system' }, 1)) + await loading + + expect(mutate).toHaveBeenCalledWith({ + ns: 'ui-test', + ops: [{ op: 'set', path: ['preference'], value: 'dark' }], + }) + expect(describeCall).toHaveBeenCalledTimes(2) + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, revision: 2 }) + }) + it('recovers the latest rejected or thrown write from Host state', async () => { const describeCall = vi.fn() .mockResolvedValueOnce(described({ preference: 'system' }, 2)) @@ -216,63 +217,74 @@ describe('SettingsScopeController', () => { const mutate = vi.fn() .mockResolvedValueOnce(rejected()) .mockRejectedValueOnce(new Error('offline')) - const scope = new SettingsScopeController( - { settings: { describe: describeCall, mutate } } as never, - { namespace: 'ui-test' }, - ) + const { mirror, scope } = derivedScope({ describe: describeCall, mutate }) const published = trackValues(scope) + await mirror.load() await scope.set('preference', 'dark') await scope.set('preference', 'system') expect(published.map(section => section?.preference)).toEqual([undefined, 'system', 'light']) }) it('does not recover superseded rejected or thrown writes', async () => { - const describeCall = vi.fn() + const describeCall = vi.fn().mockResolvedValueOnce(described({ preference: 'system' }, 2)) const mutate = vi.fn() .mockResolvedValueOnce(rejected()) .mockRejectedValueOnce(new Error('offline')) .mockResolvedValueOnce(ok(view({ preference: 'light' }, 3))) - const scope = new SettingsScopeController( - { settings: { describe: describeCall, mutate } } as never, - { namespace: 'ui-test' }, - ) + const { mirror, scope } = derivedScope({ describe: describeCall, mutate }) const published = trackValues(scope) + await mirror.load() await Promise.all([ scope.set('preference', 'dark'), scope.set('preference', 'system'), scope.set('preference', 'light'), ]) - expect(describeCall).not.toHaveBeenCalled() - expect(published.map(section => section?.preference)).toEqual([undefined, 'light']) + expect(describeCall).toHaveBeenCalledTimes(1) + expect(published.map(section => section?.preference)).toEqual([undefined, 'system', 'light']) }) it('keeps the write queue usable when a subscriber throws', async () => { const describeCall = vi.fn() .mockResolvedValueOnce(described({ preference: 'dark' }, 1)) .mockResolvedValueOnce(described({ preference: 'light' }, 2)) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { namespace: 'ui-test' }, - ) + const { mirror, scope } = derivedScope({ describe: describeCall }) let thrown = false scope.subscribe(() => { if (thrown) return thrown = true throw new Error('subscriber failed') }) - await expect(scope.load()).rejects.toThrow('subscriber failed') - await expect(scope.load()).resolves.toBeUndefined() + await expect(mirror.load()).rejects.toThrow('subscriber failed') + await expect(mirror.load()).resolves.toBeUndefined() expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'light' }, revision: 2 }) }) + it('keeps the write queue usable when a write publication listener throws', async () => { + const describeCall = vi.fn().mockResolvedValueOnce(described({ preference: 'system' }, 1)) + const mutate = vi.fn() + .mockResolvedValueOnce(ok(view({ preference: 'dark' }, 2))) + .mockResolvedValueOnce(ok(view({ preference: 'light' }, 3))) + const { mirror, scope } = derivedScope({ describe: describeCall, mutate }) + await mirror.load() + let shouldThrow = true + mirror.subscribe(() => { + if (!shouldThrow) return + shouldThrow = false + throw new Error('write subscriber failed') + }) + + await expect(scope.set('preference', 'dark')).rejects.toThrow('write subscriber failed') + await expect(scope.set('preference', 'light')).resolves.toBeUndefined() + + expect(mutate).toHaveBeenCalledTimes(2) + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'light' }, revision: 3 }) + }) + it('cancels queued and post-dispose writes while draining the in-flight mutation', async () => { const first = deferred>() const mutate = vi.fn().mockReturnValue(first.promise) const describeCall = vi.fn() - const scope = new SettingsScopeController( - { settings: { describe: describeCall, mutate } } as never, - { namespace: 'ui-test' }, - ) + const { scope } = derivedScope({ describe: describeCall, mutate }) const published = trackValues(scope) const dark = scope.set('preference', 'dark') await vi.waitFor(() => { expect(mutate).toHaveBeenCalledOnce() }) @@ -284,24 +296,66 @@ describe('SettingsScopeController', () => { first.resolve(ok(view({ preference: 'dark' }, 1))) await Promise.all([dark, light, stop]) await scope.set('preference', 'system') - await scope.load() expect(mutate).toHaveBeenCalledOnce() expect(describeCall).not.toHaveBeenCalled() expect(published).toEqual([undefined]) }) + it('stops deriving from the mirror after dispose', async () => { + const describeCall = vi.fn() + .mockResolvedValueOnce(described({ preference: 'dark' }, 1)) + .mockResolvedValueOnce(described({ preference: 'light' }, 2)) + const { mirror, scope } = derivedScope({ describe: describeCall }) + await mirror.load() + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' } }) + await scope.dispose() + await mirror.load() + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, revision: 1 }) + }) + + it('ignores a mirror notification already queued when disposal starts', async () => { + let notify = (): void => {} + let snapshot = { + status: 'ready' as const, + view: { + writable: true, hasDocument: true, + namespaces: [view({ preference: 'dark' }, 1)], + }, + error: null, + } + const mirror = { + getSnapshot: () => snapshot, + subscribe: (listener: () => void) => { + notify = listener + return () => {} + }, + } as never + const wire = { settings: {} } as never + const scope = new SettingsScopeController( + wire, { namespace: 'ui-test' }, mirror, 'host', settingsSchema) + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, revision: 1 }) + + await scope.dispose() + snapshot = { + ...snapshot, + view: { ...snapshot.view, namespaces: [view({ preference: 'light' }, 2)] }, + } + notify() + + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, revision: 1 }) + }) + it('keeps a remote browser in memory mode without Host calls', async () => { const describeCall = vi.fn() const mutate = vi.fn() + const wire = { settings: { describe: describeCall, mutate } } as never + const mirror = new SettingsDescribeMirror(wire, 'memory') const scope = new SettingsScopeController( - { settings: { describe: describeCall, mutate } } as never, - { namespace: 'ui-test' }, - 'memory', - ) + wire, { namespace: 'ui-test' }, mirror, 'memory', settingsSchema) expect(scope.getSnapshot()).toEqual({ status: 'unavailable', value: undefined, revision: undefined, writable: false, mode: 'memory', }) - await scope.load() + await mirror.load() await scope.set('preference', 'dark') await scope.dispose() expect(describeCall).not.toHaveBeenCalled() @@ -316,12 +370,9 @@ describe('SettingsScopeController', () => { } const describeCall = vi.fn() .mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [layered] })) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { namespace: 'ui-test' }, - ) + const { mirror, scope } = derivedScope({ describe: describeCall }) - await scope.load() + await mirror.load() expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'dark' }, @@ -334,12 +385,9 @@ describe('SettingsScopeController', () => { const inherited: SettingsNamespaceView = { ...view({ preference: 'system' }, 1), base: { preference: 'system' } } const describeCall = vi.fn() .mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [inherited] })) - const scope = new SettingsScopeController( - { settings: { describe: describeCall } } as never, - { namespace: 'ui-test' }, - ) + const { mirror, scope } = derivedScope({ describe: describeCall }) - await scope.load() + await mirror.load() expect(scope.getSnapshot().user).toBeUndefined() }) @@ -347,11 +395,8 @@ describe('SettingsScopeController', () => { it('clears one field through an unset op fenced by the held revision', async () => { const mutate = vi.fn().mockResolvedValueOnce(ok(view({ preference: 'system' }, 4))) const describeCall = vi.fn().mockResolvedValueOnce(described({ preference: 'dark' }, 3)) - const scope = new SettingsScopeController( - { settings: { describe: describeCall, mutate } } as never, - { namespace: 'ui-test' }, - ) - await scope.load() + const { mirror, scope } = derivedScope({ describe: describeCall, mutate }) + await mirror.load() await scope.unset('preference') @@ -368,64 +413,54 @@ describe('SettingsScopeController', () => { const describeCall = vi.fn() .mockResolvedValueOnce(described({ preference: 'dark' }, 3)) .mockResolvedValueOnce(described({ preference: 'light' }, 5)) - const scope = new SettingsScopeController( - { settings: { describe: describeCall, mutate } } as never, - { namespace: 'ui-test' }, - ) - await scope.load() + const { mirror, scope } = derivedScope({ describe: describeCall, mutate }) + await mirror.load() await scope.unset('preference') expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'light' }, revision: 5 }) }) }) + describe('SettingsScopeBinder.bind', () => { - it('subscribes before the initial read and converges to the latest queued invalidation', async () => { - const initial = deferred>() - const describeCall = vi.fn() - .mockReturnValueOnce(initial.promise) - .mockResolvedValueOnce(described({ preference: 'light' }, 2)) - .mockResolvedValueOnce(described({ preference: 'system' }, 3)) + it('shares one mirror read across bound scopes and disposes each with its fiber', async () => { + const describeCall = vi.fn().mockResolvedValue(described({ preference: 'dark' }, 1)) + const wire = { settings: { describe: describeCall } } + const mirror = new SettingsDescribeMirror(wire as never) const ctx = new Context() - ctx.provide('connection', { - api: { settings: { describe: describeCall } }, - isLoopback: true, - } as never) - let scope!: SettingsScope + ctx.provide('connection', { api: wire, isLoopback: true } as never) + let theme!: SettingsScope + let locale!: SettingsScope new TestRemote(ctx) - await ctx.plugin(SettingsScopeBinder, new SettingsSchemaService(ctx)).await() + await ctx.plugin(SettingsScopeBinder, { mirror, schema: settingsSchema }).await() + expect(ctx.settingsScope.describe()).toBe(mirror) const fiber = ctx.plugin({ inject: ['connection', 'remote', 'settingsScope'], apply: (plugin: Context) => { - scope = plugin.settingsScope.bind({ namespace: 'ui-test' }) + theme = plugin.settingsScope.bind({ namespace: 'ui-test' }) + locale = plugin.settingsScope.bind({ namespace: 'ui-test' }) }, }) await fiber.await() - await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledOnce() }) - ctx.remote.$dispatch('settings/document-updated', ['unrelated', 0]) - ctx.remote.$dispatch('settings/document-updated', ['ui-test', 0]) - ctx.emit('connection/reset') - initial.resolve(described({ preference: 'dark' }, 1)) - await vi.waitFor(() => { expect(describeCall).toHaveBeenCalledTimes(3) }) await vi.waitFor(() => { - expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'system' }, revision: 3 }) + expect(theme.getSnapshot()).toMatchObject({ status: 'ready', value: { preference: 'dark' } }) + expect(locale.getSnapshot()).toMatchObject({ status: 'ready', value: { preference: 'dark' } }) }) + expect(describeCall).toHaveBeenCalledTimes(1) await fiber.dispose() - ctx.remote.$dispatch('settings/document-updated', ['ui-test', 0]) - await Promise.resolve() - expect(describeCall).toHaveBeenCalledTimes(3) + await mirror.load() + expect(theme.getSnapshot()).toMatchObject({ revision: 1 }) }) it('binds a remote browser in memory mode without starting a settings read', async () => { const describeCall = vi.fn() + const wire = { settings: { describe: describeCall } } + const mirror = new SettingsDescribeMirror(wire as never, 'memory') const ctx = new Context() - ctx.provide('connection', { - api: { settings: { describe: describeCall } }, - isLoopback: false, - } as never) + ctx.provide('connection', { api: wire, isLoopback: false } as never) let scope!: SettingsScope new TestRemote(ctx) - await ctx.plugin(SettingsScopeBinder, new SettingsSchemaService(ctx)).await() + await ctx.plugin(SettingsScopeBinder, { mirror, schema: settingsSchema }).await() const fiber = ctx.plugin({ inject: ['connection', 'remote', 'settingsScope'], apply: (plugin: Context) => { diff --git a/packages/client/ui-theme/tests/apply.client.spec.ts b/packages/client/ui-theme/tests/apply.client.spec.ts index d7aaa466e9..3f6b1c73ae 100644 --- a/packages/client/ui-theme/tests/apply.client.spec.ts +++ b/packages/client/ui-theme/tests/apply.client.spec.ts @@ -5,18 +5,17 @@ import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, vi } from 'vitest' import { SlotRegistry } from '@deepseek-ai/dsh-client-runtime/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' -import { SettingsSchemaService } from '@deepseek-ai/dsh-client-ui-settings/src/client/schema.ts' -import { SettingsScopeBinder } from '@deepseek-ai/dsh-client-ui-settings/src/client/settings-scope.ts' +import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client' import { apply, inject, SETTINGS_NS } from '@deepseek-ai/dsh-client-ui-theme/client' import type { AppearanceRowInjected, ThemeRuntime } from '@deepseek-ai/dsh-client-ui-theme/client' import { THEME_SETTINGS_NAMESPACE, ThemeSettingsSchema } from '../src/theme-settings.ts' import { AppearanceRow } from '../src/client/AppearanceRow.tsx' import type { createAppearanceRowStore } from '../src/client/settings-store.ts' -// The service reads its initial locale from the browser; these specs assert -// the shipped Chinese copy, so they state the browser they assume. -usePinnedBrowserLanguages('zh-CN') +// These specs assert the shipped Chinese copy. The lane has no jsdom `window`, +// so browser-language detection never runs and a fresh LocaleRuntime opens on +// FALLBACK_LOCALE (en); bench stages zh explicitly on the locale instead. const SLOT = 'settings.general.item' @@ -30,6 +29,7 @@ async function bench(isLoopback = true) { const ctx = new Context() await ctx.plugin(SlotRegistry).await() const locale = new LocaleRuntime(ctx) + locale.setLocale('zh') ctx.provide('locale', locale) let preference = 'system' const namespace = () => ({ @@ -57,7 +57,7 @@ async function bench(isLoopback = true) { ctx.provide('connection', { api: { settings: { describe, mutate } }, isLoopback } as never) // The settings transport and the forwarded-event port the plugin injects. new TestRemote(ctx) - await ctx.plugin(SettingsScopeBinder, new SettingsSchemaService(ctx)).await() + await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await() return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, describe, mutate, setHostPreference: (next: string) => { preference = next }, @@ -128,13 +128,19 @@ describe('ui-theme apply', () => { it('loads Host settings at boot, refreshes its namespace, and keeps remote browsers process-local', async () => { const b = await bench() + // The shared mirror read once at bench time; a Host-side change reaches it + // through the document invalidation, exactly as production announces one. b.setHostPreference('dark') + b.ctx.remote.$dispatch('settings/document-updated', [THEME_SETTINGS_NAMESPACE, 0]) declareItems(b.slots) await b.ctx.plugin({ inject: [...inject], apply }).await() const theme = b.ctx.get('theme') as ThemeRuntime await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('dark') }) + // The mirror refreshes on every document commit (ns-agnostic); the scope's + // derived value only moves when its own namespace changed. b.ctx.remote.$dispatch('settings/document-updated', ['unrelated', 0]) - expect(b.describe).toHaveBeenCalledOnce() + await vi.waitFor(() => { expect(b.describe).toHaveBeenCalledTimes(3) }) + expect(theme.getTheme().preference).toBe('dark') b.setHostPreference('light') b.ctx.remote.$dispatch('settings/document-updated', [THEME_SETTINGS_NAMESPACE, 0]) await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('light') }) @@ -152,12 +158,15 @@ describe('ui-theme apply', () => { expect(remote.mutate).not.toHaveBeenCalled() }) - it('activates before a slow initial settings read and converges when it settles', async () => { + it('activates before a slow settings refresh and converges when it settles', async () => { const b = await bench() b.setHostPreference('dark') const describe = b.describe.getMockImplementation()! const pending = deferred>>() b.describe.mockImplementationOnce(() => pending.promise) + // The refresh hangs on the wire; the mirror keeps serving the last good + // answer, so activation never blocks on the settings transport. + b.ctx.remote.$dispatch('settings/document-updated', [THEME_SETTINGS_NAMESPACE, 0]) const fiber = b.ctx.plugin({ inject: [...inject], apply }) await fiber.await() const theme = b.ctx.get('theme') as ThemeRuntime @@ -170,9 +179,10 @@ describe('ui-theme apply', () => { it('ignores an invalid preference crossing the settings wire', async () => { const b = await bench() b.setHostPreference('sepia') + b.ctx.remote.$dispatch('settings/document-updated', [THEME_SETTINGS_NAMESPACE, 0]) await b.ctx.plugin({ inject: [...inject], apply }).await() const theme = b.ctx.get('theme') as ThemeRuntime - await vi.waitFor(() => { expect(b.describe).toHaveBeenCalledOnce() }) + await vi.waitFor(() => { expect(b.describe).toHaveBeenCalledTimes(2) }) expect(theme.getTheme().preference).toBe('system') }) diff --git a/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts b/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts index fa7cb27962..ce7463e57f 100644 --- a/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts @@ -166,6 +166,10 @@ function deriveSummary(variant: ToolRowVariant, argsRaw: string): string { const parsed = parseArgs(argsRaw) if (typeof parsed !== 'object' || parsed === null) return firstLine(argsRaw) const args = parsed as Record + if (variant === 'search' && Array.isArray(args.queries)) { + const queries = args.queries.filter((query): query is string => typeof query === 'string' && query !== '') + if (queries.length > 0) return queries.map(firstLine).join(', ') + } const picked = pickString(args, SUMMARY_KEYS[variant]) if (picked !== undefined) return firstLine(picked) for (const v of Object.values(args)) { diff --git a/packages/client/ui-tool/tests/tool-row.client.spec.tsx b/packages/client/ui-tool/tests/tool-row.client.spec.tsx index 28c8b5b236..54808635da 100644 --- a/packages/client/ui-tool/tests/tool-row.client.spec.tsx +++ b/packages/client/ui-tool/tests/tool-row.client.spec.tsx @@ -111,6 +111,13 @@ describe('tool-call-model', () => { expect(toolRowModel('', running({ argsRaw: '' })).summary).toBe('c1') }) + it('joins multi-query web search arguments in the summary', () => { + expect(toolRowModel('web_search', running({ + name: 'web_search', + argsRaw: '{"queries":["first query","second\\nquery"]}', + })).summary).toBe('first query, second') + }) + it('exposes filePath for path/file_path args and skips URL-only reads', () => { expect(toolRowModel('read', running({ name: 'read', argsRaw: '{"path":"src/a.ts"}' })).filePath).toBe('src/a.ts') expect(toolRowModel('write', running({ name: 'write', argsRaw: '{"file_path":"src/a.ts"}' })).filePath).toBe('src/a.ts') diff --git a/packages/client/ui-workflow-run/README.i18n.yaml b/packages/client/ui-workflow-run/README.i18n.yaml index ed480dc9c8..86ff6be938 100644 --- a/packages/client/ui-workflow-run/README.i18n.yaml +++ b/packages/client/ui-workflow-run/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workflow-run/README.md -README.md: 3fcdc632b54be7d1f8f452c6f8b3b2e1525953aa -README.zh.md: 5f0ba0c8f8a251d0ce5977d469ee60637f0454db +README.md: 5093050ac7bd7e5d8a8779c4fe9848ee4f7da28b +README.zh.md: f7b652d87dc01e5161eac8ea3fc9025136feca90 diff --git a/packages/client/ui-workflow-run/README.md b/packages/client/ui-workflow-run/README.md index 3fcdc632b5..5093050ac7 100644 --- a/packages/client/ui-workflow-run/README.md +++ b/packages/client/ui-workflow-run/README.md @@ -12,7 +12,7 @@ Phase groups come only from members that actually started. Exact phase strings s ## Presentation and navigation -The run and each phase derive disclosure control from their current lifecycle facts. The run stays expanded while its own status is running, failed, cancelled, or interrupted, or while any phase contains such a member; each affected phase also stays expanded. Forced-open headers are static expanded rows without button, keyboard, or `aria-expanded` promises. A phase folds once when every member completes, and the run folds once when it and every phase complete. Each clean layer then exposes an ordinary disclosure control whose local choice survives clean rerenders; new activity takes control again, and a remount derives the initial state from current data. The run uses a 32-pixel `--dsw-alias-bg-module-platform` row with persistent right/down chevrons and an inline state dot plus status text, without a badge. Phases use 32-pixel disclosure rows with title and member count in the flexible main area and a fixed precise aggregate-status tail, without another dot. Members use a 16-pixel dot slot, a truncating name area, and a fixed 64-pixel status column. +The run and each phase are controlled disclosures in every status. A mount opens running, failed, cancelled, and interrupted levels and closes fully completed levels; users can then toggle either level with the full row, Enter, or Space. Ordinary running updates preserve the current choice, the first abnormal edge opens once, normal completion closes once, and a completed phase plus the outer run open again when a new running member starts under the same phase key. If an entire new clean cycle arrives in one render while the run remains active, the phase finishes folded but the outer run opens once to expose its updated summary. Completion updates the visible status immediately but delays its automatic close while focus remains inside the content. `WorkflowRunPanel` owns the phase choices, so closing and reopening the outer run does not reset them; a renderer remount reconstructs every initial choice from durable facts. The run uses a 32-pixel `--dsw-alias-bg-module-platform` row with persistent right/down chevrons and an inline state dot plus status text, without a badge. Phases use 32-pixel disclosure rows with title and member count in the flexible main area and a fixed precise aggregate-status tail, without another dot. Members use a 16-pixel dot slot, a truncating name area, and a fixed 64-pixel status column. A member opens a child Session only while every current fact agrees: the member is running, the child id is in the ordinary Session list, the row has `origin: 'subagent'`, its `parentId` is the current Session, and the list row is still running. Underlined member text is the only visible navigation affordance; keyboard focus draws a two-pixel business-primary ring around the name area, while status copy remains `Running`. The component calls only the injected ordinary `sessions.open(id)` action; remote, addressed-only, wrong-parent, or terminal rows remain non-interactive. diff --git a/packages/client/ui-workflow-run/README.zh.md b/packages/client/ui-workflow-run/README.zh.md index 5f0ba0c8f8..f7b652d87d 100644 --- a/packages/client/ui-workflow-run/README.zh.md +++ b/packages/client/ui-workflow-run/README.zh.md @@ -12,7 +12,7 @@ ## 展示与导航 -运行和每个阶段都从当前生命周期事实派生 disclosure 控制。运行自身处于运行中、失败、已取消或已中断,或者任一阶段包含这些状态的成员时,运行保持展开;受影响的阶段也保持展开。强制展开的标题行只是静态展开行,不承诺按钮、键盘操作或 `aria-expanded`。阶段在全部成员完成时折叠一次;运行在自身和全部阶段都完成时折叠一次。每个干净层级随后恢复普通 disclosure 控件,其本地选择在干净状态的 rerender 中保持;新活动会重新取得控制,remount 则从当前数据派生初始状态。运行使用 32 像素 `--dsw-alias-bg-module-platform` 背景行,常驻向右/向下 chevron,并以内联状态点加状态文字表达结局,不使用胶囊。阶段使用 32 像素 disclosure 行,在可伸缩主区显示标题与成员数,在固定尾部精确显示聚合状态且不重复状态点。成员使用 16 像素状态点槽、可省略名称区和固定 64 像素状态列。 +运行和每个阶段在所有状态下都是受控 disclosure。挂载时,运行中、失败、已取消和已中断层级默认展开,全部完成的层级默认折叠;此后用户可以点击整行,或按 Enter、Space 切换任一层级。普通运行更新保留当前选择,首次异常边沿只自动展开一次,正常完成只自动折叠一次;已完成阶段在同一 phase key 下开始新的运行成员时,该 Phase 与外层运行会再次自动展开。若一个完整的新干净周期在同一次渲染中送达,且运行仍处于活动状态,Phase 保持折叠,但外层运行会自动展开一次以展示更新后的摘要。完成状态会立即更新,但只要焦点仍位于展开内容内,自动折叠就会等待焦点离开。Phase 选择由 `WorkflowRunPanel` 持有,因此关闭并重新打开外层运行不会重置它们;renderer remount 会从持久事实重建每层的初始选择。运行使用 32 像素 `--dsw-alias-bg-module-platform` 背景行,常驻向右/向下 chevron,并以内联状态点加状态文字表达结局,不使用胶囊。阶段使用 32 像素 disclosure 行,在可伸缩主区显示标题与成员数,在固定尾部精确显示聚合状态且不重复状态点。成员使用 16 像素状态点槽、可省略名称区和固定 64 像素状态列。 只有所有实时事实同时成立时,成员才可打开子 Session:成员仍在运行、子 id 位于普通 Session 列表、列表行为 `origin: 'subagent'`、`parentId` 等于当前 Session,且列表行仍标记运行。带下划线的成员文字是唯一可见导航提示;键盘聚焦时,名称区显示 2 像素 business-primary 焦点环,右侧状态仍只显示“运行中”。组件只调用注入的普通 `sessions.open(id)`;远程、仅地址化、父级不符或终态的行都不可交互。 diff --git a/packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx b/packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx index 5e24a16717..fe0f300211 100644 --- a/packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx +++ b/packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx @@ -1,4 +1,7 @@ -import { useState, type ReactNode } from 'react' +import { + useLayoutEffect, useMemo, useRef, useState, + type FocusEvent, type MouseEvent, type ReactNode, +} from 'react' import { DisclosureRow, IconChevronRightOutline14, StateDot, type DisclosureRowProps, type StateDotState, @@ -63,34 +66,102 @@ function memberCount(count: number, t: WorkflowRunPanelProps['t']): string { return t(count === 1 ? 'run.members.one' : 'run.members.other', { count }) } -function phaseRequiresExpansion(phase: WorkflowRunPhaseData): boolean { - return phase.members.some(member => member.status !== 'completed') +type DisclosureMode = 'clean' | 'running' | 'abnormal' + +interface DisclosureFacts { + readonly mode: DisclosureMode + readonly activityCount: number } -type StatusDisclosureProps = Omit - -/* v8 ignore next -- DisclosureRow requires the callback but cannot invoke it when expandable is false. */ -const forcedOpenToggle = (): void => {} - -function ManualDisclosure(props: StatusDisclosureProps) { - const [open, setOpen] = useState(false) - return ( - { setOpen(value => !value) }} - /> - ) +interface DisclosureState extends DisclosureFacts { + readonly open: boolean + readonly pendingCleanCollapse: boolean } -function StatusDisclosure({ cleanCycleKey, requiresExpansion, ...props }: StatusDisclosureProps & { - /** Remount a clean Phase when its append-only member count changes between batched renders. */ - readonly cleanCycleKey?: number | undefined - readonly requiresExpansion: boolean -}) { - if (!requiresExpansion) return - return +interface WorkflowDisclosureState { + readonly run: DisclosureState + readonly phases: ReadonlyMap +} + +type StatusDisclosureProps = Omit + +function StatusDisclosure(props: StatusDisclosureProps) { + return +} + +function abnormal(status: WorkflowRunStatus): boolean { + return status === 'failed' || status === 'cancelled' || status === 'interrupted' +} + +function phaseDisclosureFacts(phase: WorkflowRunPhaseData): DisclosureFacts { + const mode = phase.members.some(member => abnormal(member.status)) + ? 'abnormal' + : phase.members.some(member => member.status === 'running') ? 'running' : 'clean' + return { mode, activityCount: phase.members.length } +} + +function runDisclosureFacts( + status: WorkflowRunStatus, + phases: readonly (readonly [string, DisclosureFacts])[], +): DisclosureFacts { + const mode = abnormal(status) || phases.some(([, facts]) => facts.mode === 'abnormal') + ? 'abnormal' + : status === 'running' || phases.some(([, facts]) => facts.mode === 'running') + ? 'running' + : 'clean' + const activityCount = phases.reduce((count, [, facts]) => count + facts.activityCount, 0) + return { mode, activityCount } +} + +function initialDisclosureState(facts: DisclosureFacts): DisclosureState { + return { ...facts, open: facts.mode !== 'clean', pendingCleanCollapse: false } +} + +function advanceDisclosureState( + current: DisclosureState, + facts: DisclosureFacts, + focusWithin: boolean, +): DisclosureState { + const sameFacts = current.mode === facts.mode && current.activityCount === facts.activityCount + if (sameFacts) { + if (!current.pendingCleanCollapse || focusWithin) return current + return { ...current, open: false, pendingCleanCollapse: false } + } + if (facts.mode === 'clean') { + const deferCollapse = current.open && focusWithin + return { ...facts, open: deferCollapse, pendingCleanCollapse: deferCollapse } + } + if (current.mode === 'clean' || (facts.mode === 'abnormal' && current.mode !== 'abnormal')) { + return { ...facts, open: true, pendingCleanCollapse: false } + } + return { ...facts, open: current.open, pendingCleanCollapse: false } +} + +function focusIsWithin(element: HTMLElement | null | undefined): boolean { + if (element === null || element === undefined) return false + return element.contains(element.ownerDocument.activeElement) +} + +function collapsePending(state: DisclosureState): DisclosureState { + if (!state.pendingCleanCollapse) return state + return { ...state, open: false, pendingCleanCollapse: false } +} + +function existingPhaseState( + phases: ReadonlyMap, + key: string, +): DisclosureState { + const phase = phases.get(key) + /* v8 ignore next -- mounted phase callbacks are created from this owner map. */ + if (phase === undefined) throw new Error(`Missing disclosure state for phase ${key}`) + return phase +} + +function preventPendingHeaderFocus(event: MouseEvent): void { + const header = event.currentTarget.querySelector('[data-disclosure-row]') + /* v8 ignore next -- DisclosureRow always renders its header before the content. */ + if (header === null) throw new Error('Missing disclosure header') + if (header.contains(event.target as Node)) event.preventDefault() } function phaseStatusSummary(members: readonly WorkflowRunMemberData[], t: WorkflowRunPanelProps['t']): string { @@ -128,11 +199,12 @@ function navigableMembers( return result } -function RunHeader({ children, count, name, requiresExpansion, status, t }: { +function RunHeader({ children, count, name, onToggle, open, status, t }: { readonly children: ReactNode readonly count: number readonly name: string - readonly requiresExpansion: boolean + readonly onToggle: () => void + readonly open: boolean readonly status: WorkflowRunStatus readonly t: WorkflowRunPanelProps['t'] }) { @@ -140,7 +212,8 @@ function RunHeader({ children, count, name, requiresExpansion, status, t }: { } title={t('run.title', { name })} - requiresExpansion={requiresExpansion} + open={open} + onToggle={onToggle} expandOnRowClick previewChevron={false} keepContentWhenOpen @@ -170,6 +243,9 @@ function MemberRow({ member, navigable, openSession, t }: { readonly t: WorkflowRunPanelProps['t'] }) { const name = readableMember(member.label, t) + const [focused, setFocused] = useState(false) + const renderButton = navigable || focused + const content = ( <> @@ -177,94 +253,213 @@ function MemberRow({ member, navigable, openSession, t }: { {t(STATUS_KEYS[member.status])} ) - if (!navigable) { + if (!renderButton) { return
      {content}
      } return ( ) } -function PhaseSection({ phase, navigable, openSession, t }: { +function PhaseSection({ + contentRef, onContentBlur, onToggle, open, pendingCleanCollapse, + phase, navigable, openSession, t, +}: { + readonly contentRef: (element: HTMLDivElement | null) => void + readonly onContentBlur: (event: FocusEvent) => void + readonly onToggle: () => void + readonly open: boolean + readonly pendingCleanCollapse: boolean readonly phase: WorkflowRunPhaseData readonly navigable: readonly SessionId[] readonly openSession: WorkflowRunInjected['openSession'] readonly t: WorkflowRunPanelProps['t'] }) { return ( - } - title={readablePhase(phase.phase, t)} - cleanCycleKey={phase.members.length} - requiresExpansion={phaseRequiresExpansion(phase)} - expandOnRowClick - previewChevron={false} - keepContentWhenOpen +
      - - {memberCount(phase.members.length, t)} - {phaseStatusSummary(phase.members, t)} - - )} + onMouseDownCapture={pendingCleanCollapse ? preventPendingHeaderFocus : undefined} > -
      - {phase.members.map(member => ( - - ))} -
      - + } + title={readablePhase(phase.phase, t)} + open={open} + onToggle={onToggle} + expandOnRowClick + previewChevron={false} + keepContentWhenOpen + rowClassName={css.phaseHeader} + leadingClassName={css.phaseLeading} + titleClassName={css.phaseTitle} + collapsedContent={( + <> + + {memberCount(phase.members.length, t)} + {phaseStatusSummary(phase.members, t)} + + )} + > +
      + {phase.members.map(member => ( + + ))} +
      +
      +
      ) } /** Render one durable workflow run with status-driven run and phase disclosure. */ export function WorkflowRunPanel({ node, sessionId, useSessions, openSession, t }: WorkflowRunPanelProps) { - const totalMembers = node.data.phases.reduce((count, phase) => count + phase.members.length, 0) - const requiresExpansion = node.data.status !== 'completed' - || node.data.phases.some(phaseRequiresExpansion) + const phaseFacts = useMemo(() => node.data.phases.map(phase => ( + [phase.key, phaseDisclosureFacts(phase)] as const + )), [node.data.phases]) + const runFacts = useMemo( + () => runDisclosureFacts(node.data.status, phaseFacts), + [node.data.status, phaseFacts], + ) + const totalMembers = runFacts.activityCount + const [disclosures, setDisclosures] = useState(() => ({ + run: initialDisclosureState(runFacts), + phases: new Map(phaseFacts.map(([key, facts]) => [key, initialDisclosureState(facts)])), + })) + const runContentRef = useRef(null) + const phaseContentRefs = useRef(new Map()) const navigable = useSessions( sessions => navigableMembers(sessions, node.data.phases, sessionId), shallowEqual, ) + + // Outer hiding unmounts Phase content without a dependable blur event, so this edge settles deferred closes. + useLayoutEffect(() => { + setDisclosures((current) => { + const phases = new Map() + let phasesChanged = current.phases.size !== phaseFacts.length + let phaseStartedCycle = false + for (const [key, facts] of phaseFacts) { + const previous = current.phases.get(key) + const next = previous === undefined + ? initialDisclosureState(facts) + : advanceDisclosureState(previous, facts, focusIsWithin(phaseContentRefs.current.get(key))) + phases.set(key, next) + if (next !== previous) phasesChanged = true + if (previous?.mode === 'clean' + && (facts.mode !== 'clean' || facts.activityCount !== previous.activityCount)) { + phaseStartedCycle = true + } + } + const advancedRun = advanceDisclosureState( + current.run, + runFacts, + focusIsWithin(runContentRef.current), + ) + const run = phaseStartedCycle && runFacts.mode !== 'clean' && !advancedRun.open + ? { ...advancedRun, open: true, pendingCleanCollapse: false } + : advancedRun + return run !== current.run || phasesChanged ? { run, phases } : current + }) + }, [disclosures.run.open, phaseFacts, runFacts]) + + const toggleRun = (): void => { + setDisclosures(current => ({ + ...current, + run: { + ...current.run, + open: !current.run.open, + pendingCleanCollapse: false, + }, + })) + } + const togglePhase = (key: string): void => { + setDisclosures((current) => { + const phases = new Map(current.phases) + const phase = existingPhaseState(phases, key) + phases.set(key, { + ...phase, + open: !phase.open, + pendingCleanCollapse: false, + }) + return { ...current, phases } + }) + } + const settleRunBlur = (event: FocusEvent): void => { + if (event.currentTarget.contains(event.relatedTarget)) return + setDisclosures((current) => { + const run = collapsePending(current.run) + return run === current.run ? current : { ...current, run } + }) + } + const settlePhaseBlur = (key: string, event: FocusEvent): void => { + if (event.currentTarget.contains(event.relatedTarget)) return + setDisclosures((current) => { + const phase = existingPhaseState(current.phases, key) + const next = collapsePending(phase) + if (next === phase) return current + const phases = new Map(current.phases) + phases.set(key, next) + return { ...current, phases } + }) + } + return ( -
      +
      -
      +
      {node.data.phases.length === 0 ? {t('run.empty')} - : node.data.phases.map(phase => ( - - ))} + : node.data.phases.map((phase) => { + const facts = phaseDisclosureFacts(phase) + const disclosure = disclosures.phases.get(phase.key) ?? initialDisclosureState(facts) + return ( + { + if (element === null) phaseContentRefs.current.delete(phase.key) + else phaseContentRefs.current.set(phase.key, element) + }} + onContentBlur={(event) => { settlePhaseBlur(phase.key, event) }} + onToggle={() => { togglePhase(phase.key) }} + open={disclosure.open} + pendingCleanCollapse={disclosure.pendingCleanCollapse} + phase={phase} + navigable={navigable} + openSession={openSession} + t={t} + /> + ) + })}
      diff --git a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx index 38c7d15c70..248f932639 100644 --- a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx +++ b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx @@ -27,6 +27,7 @@ afterEach(cleanup) const PARENT_ID = 'parent' as SessionId const CHILD_ID = 'child-1' as SessionId +const SECOND_ID = 'child-2' as SessionId interface ChatSnapshot { readonly nodes: ReadonlyMap @@ -301,28 +302,62 @@ function panelProps(data: WorkflowRunChatData, sessions = listState(), openSessi } describe('WorkflowRunPanel', () => { - it('forces running run and phase content open without false disclosure controls', () => { - const view = render( { + const running: WorkflowRunChatData = { name: 'audit', status: 'running', phases: [phase({ key: 'research', phase: 'Research' })], - })} />) - expect(screen.getByText('worker')).toBeTruthy() - expect(screen.queryByRole('button', { name: /^audit/ })).toBeNull() - expect(screen.queryByRole('button', { name: /Research/ })).toBeNull() - const rows = [...view.container.querySelectorAll('[data-disclosure-row]')] - expect(rows).toHaveLength(2) - for (const row of rows) { - expect(row.getAttribute('role')).toBeNull() - expect(row.getAttribute('tabindex')).toBeNull() - expect(row.getAttribute('aria-expanded')).toBeNull() - expect(row.getAttribute('data-expandable')).toBeNull() } + const view = render() + const runHeader = screen.getByRole('button', { name: /^audit/ }) + const phaseHeader = screen.getByRole('button', { name: /Research/ }) + expect(runHeader.getAttribute('aria-expanded')).toBe('true') + expect(phaseHeader.getAttribute('aria-expanded')).toBe('true') + expect(screen.getByText('worker')).toBeTruthy() + + fireEvent.click(phaseHeader) + expect(phaseHeader.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByText('worker')).toBeNull() + fireEvent.click(runHeader) + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + + view.rerender() + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByRole('button', { name: /Research/ })).toBeNull() + fireEvent.keyDown(runHeader, { key: 'ArrowDown' }) + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + fireEvent.keyDown(runHeader, { key: ' ' }) + const updatedPhase = screen.getByRole('button', { name: /Research/ }) + expect(updatedPhase.getAttribute('aria-expanded')).toBe('false') + expect(screen.getByText('运行中 2')).toBeTruthy() + fireEvent.keyDown(updatedPhase, { key: 'Enter' }) + expect(screen.getByText('worker')).toBeTruthy() + expect(screen.getByText('second')).toBeTruthy() + + fireEvent.click(runHeader) + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByRole('button', { name: /Research/ })).toBeNull() + fireEvent.keyDown(runHeader, { key: ' ' }) + expect(screen.getByRole('button', { name: /Research/ }).getAttribute('aria-expanded')).toBe('true') }) - it('folds each clean transition once and preserves review choices until activity returns', () => { + it('folds each normal completion once and opens a new same-key activity cycle', () => { const running: WorkflowRunChatData = { name: 'audit', status: 'running', phases: [phase()], } const view = render() + const runningPhase = screen.getByRole('button', { name: /未分阶段/ }) + fireEvent.click(runningPhase) + fireEvent.keyDown(runningPhase, { key: 'Enter' }) + expect(screen.getByText('worker')).toBeTruthy() + const phaseCompleted: WorkflowRunChatData = { ...running, phases: [phase({ @@ -338,27 +373,8 @@ describe('WorkflowRunPanel', () => { fireEvent.click(phaseHeader) expect(screen.getByText('done')).toBeTruthy() - const completed: WorkflowRunChatData = { ...phaseCompleted, status: 'completed' } - view.rerender() - const runHeader = screen.getByRole('button', { name: /^audit/ }) - expect(runHeader.getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByText('未分阶段')).toBeNull() - fireEvent.keyDown(runHeader, { key: 'ArrowDown' }) - expect(runHeader.getAttribute('aria-expanded')).toBe('false') - fireEvent.keyDown(runHeader, { key: 'Enter' }) - expect(runHeader.getAttribute('aria-expanded')).toBe('true') - const completedPhase = screen.getByRole('button', { name: /未分阶段/ }) - fireEvent.keyDown(completedPhase, { key: 'Enter' }) - expect(screen.getByText('done')).toBeTruthy() - fireEvent.keyDown(runHeader, { key: ' ' }) - expect(runHeader.getAttribute('aria-expanded')).toBe('false') - fireEvent.keyDown(runHeader, { key: ' ' }) - expect(runHeader.getAttribute('aria-expanded')).toBe('true') - fireEvent.click(screen.getByRole('button', { name: /未分阶段/ })) - expect(screen.getByText('done')).toBeTruthy() - const cleanUpdate: WorkflowRunChatData = { - ...completed, + ...phaseCompleted, phases: [phase({ members: [{ seq: 1, label: 'reviewed', childId: 'child-1' as SessionId, status: 'completed', @@ -368,13 +384,44 @@ describe('WorkflowRunPanel', () => { view.rerender() expect(screen.getByText('reviewed')).toBeTruthy() - view.rerender() - expect(screen.queryByRole('button', { name: /^audit/ })).toBeNull() - expect(screen.queryByRole('button', { name: /未分阶段/ })).toBeNull() - expect(screen.getByText('worker')).toBeTruthy() - view.rerender() + fireEvent.click(screen.getByRole('button', { name: /未分阶段/ })) + const runHeader = screen.getByRole('button', { name: /^audit/ }) + fireEvent.click(runHeader) + const renewed: WorkflowRunChatData = { + name: 'audit', status: 'running', + phases: [phase({ + members: [ + { seq: 1, label: 'reviewed', childId: CHILD_ID, status: 'completed' }, + { seq: 2, label: 'new', childId: 'child-2' as SessionId, status: 'running' }, + ], + })], + } + view.rerender() + expect(screen.getByRole('button', { name: /^audit/ }).getAttribute('aria-expanded')).toBe('true') + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('true') + expect(screen.getByText('new')).toBeTruthy() + + const renewedPhaseCompleted: WorkflowRunChatData = { + ...renewed, + phases: [phase({ + members: [ + { seq: 1, label: 'reviewed', childId: CHILD_ID, status: 'completed' }, + { seq: 2, label: 'new', childId: 'child-2' as SessionId, status: 'completed' }, + ], + })], + } + view.rerender() + expect(screen.getByRole('button', { name: /^audit/ }).getAttribute('aria-expanded')).toBe('true') + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('false') + fireEvent.click(screen.getByRole('button', { name: /未分阶段/ })) + + view.rerender() expect(screen.getByRole('button', { name: /^audit/ }).getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByText('未分阶段')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: /^audit/ })) + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('true') }) it('refolds a phase when a complete activity cycle arrives as one clean update', () => { @@ -388,21 +435,59 @@ describe('WorkflowRunPanel', () => { const phaseView = render() fireEvent.click(screen.getByRole('button', { name: /未分阶段/ })) expect(screen.getByText('first')).toBeTruthy() + const runHeader = screen.getByRole('button', { name: /^phase-cycle/ }) + fireEvent.click(runHeader) + expect(runHeader.getAttribute('aria-expanded')).toBe('false') phaseView.rerender() + expect(runHeader.getAttribute('aria-expanded')).toBe('true') expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('false') expect(screen.queryByText('first')).toBeNull() expect(screen.queryByText('second')).toBeNull() + + phaseView.rerender() + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByRole('button', { name: /未分阶段/ })).toBeNull() + }) + + it('initializes a newly observed phase before it becomes interactive', () => { + const running: WorkflowRunChatData = { + name: 'dynamic-phase', status: 'running', + phases: [phase({ key: 'research', phase: 'Research' })], + } + const view = render() + view.rerender() + const build = screen.getByRole('button', { name: /Build/ }) + expect(build.getAttribute('aria-expanded')).toBe('true') + fireEvent.click(build) + expect(build.getAttribute('aria-expanded')).toBe('false') }) it('derives the zero-member running and completed states from the current run status', () => { const running: WorkflowRunChatData = { name: 'empty', status: 'running', phases: [] } const view = render() - expect(screen.queryByRole('button', { name: /^empty/ })).toBeNull() + expect(screen.getByRole('button', { name: /^empty/ }).getAttribute('aria-expanded')).toBe('true') expect(screen.getByText('没有启动成员')).toBeTruthy() view.rerender() const header = screen.getByRole('button', { name: /^empty/ }) @@ -413,31 +498,60 @@ describe('WorkflowRunPanel', () => { }) it.each(['failed', 'cancelled', 'interrupted'] as const)( - 'bubbles a %s member to the run and keeps a matching run outcome open', + 'initializes %s attention as an expanded disclosure that remains manually collapsible', (status) => { - const memberView = render() - expect(screen.queryByRole('button', { name: /^member-outcome/ })).toBeNull() - expect(screen.queryByRole('button', { name: /未分阶段/ })).toBeNull() + const runHeader = screen.getByRole('button', { name: /^member-outcome/ }) + const phaseHeader = screen.getByRole('button', { name: /未分阶段/ }) + expect(runHeader.getAttribute('aria-expanded')).toBe('true') + expect(phaseHeader.getAttribute('aria-expanded')).toBe('true') expect(screen.getByText(status)).toBeTruthy() - memberView.unmount() - - render() - expect(screen.queryByRole('button', { name: /^run-outcome/ })).toBeNull() - expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByText('done')).toBeNull() + fireEvent.click(phaseHeader) + fireEvent.click(runHeader) + expect(runHeader.getAttribute('aria-expanded')).toBe('false') }, ) + it('opens the first abnormal edge once and preserves later abnormal choices', () => { + const running: WorkflowRunChatData = { + name: 'audit', status: 'running', phases: [phase()], + } + const view = render() + fireEvent.click(screen.getByRole('button', { name: /未分阶段/ })) + fireEvent.click(screen.getByRole('button', { name: /^audit/ })) + + const failed: WorkflowRunChatData = { + name: 'audit', status: 'running', + phases: [phase({ + members: [{ seq: 1, label: 'failed', childId: CHILD_ID, status: 'failed' }], + })], + } + view.rerender() + expect(screen.getByRole('button', { name: /^audit/ }).getAttribute('aria-expanded')).toBe('true') + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('true') + fireEvent.click(screen.getByRole('button', { name: /未分阶段/ })) + fireEvent.click(screen.getByRole('button', { name: /^audit/ })) + + view.rerender() + expect(screen.getByRole('button', { name: /^audit/ }).getAttribute('aria-expanded')).toBe('false') + fireEvent.click(screen.getByRole('button', { name: /^audit/ })) + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('false') + expect(screen.getByText('失败 1 · 已取消 1')).toBeTruthy() + }) + it('keeps clean sibling phases independent and preserves empty versus absent names', () => { render( { }] }), ], })} />) - expect(screen.queryByRole('button', { name: /^audit/ })).toBeNull() + const runHeader = screen.getByRole('button', { name: /^audit/ }) + expect(runHeader.getAttribute('aria-expanded')).toBe('true') const cleanPhase = screen.getByRole('button', { name: /空阶段名/ }) expect(cleanPhase.getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByRole('button', { name: /未分阶段/ })).toBeNull() + const activePhase = screen.getByRole('button', { name: /未分阶段/ }) + expect(activePhase.getAttribute('aria-expanded')).toBe('true') expect(screen.queryByText('空成员名')).toBeNull() expect(screen.getByText('second')).toBeTruthy() fireEvent.click(cleanPhase) expect(screen.getByText('空成员名')).toBeTruthy() expect(screen.getByText('second')).toBeTruthy() - fireEvent.click(cleanPhase) + fireEvent.click(activePhase) + expect(screen.queryByText('second')).toBeNull() + expect(screen.getByText('空成员名')).toBeTruthy() + fireEvent.click(runHeader) + fireEvent.click(runHeader) + expect(screen.getByRole('button', { name: /空阶段名/ }).getAttribute('aria-expanded')).toBe('true') + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('false') + fireEvent.click(screen.getByRole('button', { name: /空阶段名/ })) expect(screen.queryByText('空成员名')).toBeNull() - expect(screen.getByText('second')).toBeTruthy() }) it('renders mixed and interrupted aggregate status while attention stays visible', () => { @@ -496,6 +618,170 @@ describe('WorkflowRunPanel', () => { expect(interruptedView.container.querySelectorAll('[data-state="warning"]')).toHaveLength(2) }) + it('defers normal completion collapse until focused member content loses focus', () => { + const sessions = listState({ + ids: [PARENT_ID, CHILD_ID, SECOND_ID], + byId: { + ...listState().byId, + [SECOND_ID]: { + id: SECOND_ID, displayTitle: 'second', parentId: PARENT_ID, origin: 'subagent', + running: true, blank: false, updatedAt: 0, + }, + }, + }) + const running: WorkflowRunChatData = { + name: 'audit', status: 'running', phases: [phase({ + members: [ + { seq: 1, label: 'worker', childId: CHILD_ID, status: 'running' }, + { seq: 2, label: 'second', childId: SECOND_ID, status: 'running' }, + ], + })], + } + const view = render() + const member = screen.getByRole('button', { name: '打开 worker' }) + const second = screen.getByRole('button', { name: '打开 second' }) + const runHeader = screen.getByRole('button', { name: /^audit/ }) + const phaseHeader = screen.getByRole('button', { name: /未分阶段/ }) + member.focus() + expect(document.activeElement).toBe(member) + fireEvent.blur(member, { relatedTarget: second }) + second.focus() + expect(runHeader.getAttribute('aria-expanded')).toBe('true') + expect(phaseHeader.getAttribute('aria-expanded')).toBe('true') + + const outside = document.createElement('button') + document.body.append(outside) + fireEvent.blur(second, { relatedTarget: outside }) + outside.focus() + expect(runHeader.getAttribute('aria-expanded')).toBe('true') + expect(phaseHeader.getAttribute('aria-expanded')).toBe('true') + member.focus() + + view.rerender() + expect(runHeader.getAttribute('aria-expanded')).toBe('true') + expect(phaseHeader.getAttribute('aria-expanded')).toBe('true') + const retained = screen.getByRole('button', { name: 'worker' }) + expect(retained.getAttribute('aria-disabled')).toBe('true') + expect(document.activeElement).toBe(retained) + + fireEvent.blur(retained, { relatedTarget: outside }) + outside.focus() + expect(document.activeElement).toBe(outside) + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + fireEvent.click(runHeader) + const completedPhase = screen.getByRole('button', { name: /未分阶段/ }) + expect(completedPhase.getAttribute('aria-expanded')).toBe('false') + fireEvent.click(completedPhase) + expect(screen.queryByRole('button', { name: '打开 worker' })).toBeNull() + expect(screen.getByText('worker')).toBeTruthy() + outside.remove() + }) + + it('handles a pointer blur and header click as one pending-completion close', () => { + const running: WorkflowRunChatData = { + name: 'audit', status: 'running', phases: [phase()], + } + const view = render() + const member = screen.getByRole('button', { name: '打开 worker' }) + member.focus() + view.rerender() + const retained = screen.getByRole('button', { name: 'worker' }) + const phaseHeader = screen.getByRole('button', { name: /未分阶段/ }) + const runHeader = screen.getByRole('button', { name: /^audit/ }) + + expect(fireEvent.mouseDown(retained)).toBe(true) + expect(document.activeElement).toBe(retained) + expect(fireEvent.mouseDown(phaseHeader)).toBe(false) + fireEvent.click(phaseHeader) + expect(phaseHeader.getAttribute('aria-expanded')).toBe('false') + expect(runHeader.getAttribute('aria-expanded')).toBe('true') + + expect(fireEvent.mouseDown(runHeader)).toBe(false) + fireEvent.click(runHeader) + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + }) + + it('settles pending completion when keyboard focus moves from content to its header', () => { + const running: WorkflowRunChatData = { + name: 'audit', status: 'running', phases: [phase()], + } + const view = render() + const member = screen.getByRole('button', { name: '打开 worker' }) + member.focus() + view.rerender() + const retained = screen.getByRole('button', { name: 'worker' }) + const phaseHeader = screen.getByRole('button', { name: /未分阶段/ }) + const runHeader = screen.getByRole('button', { name: /^audit/ }) + fireEvent.blur(retained, { relatedTarget: phaseHeader }) + phaseHeader.focus() + expect(phaseHeader.getAttribute('aria-expanded')).toBe('false') + expect(runHeader.getAttribute('aria-expanded')).toBe('true') + + view.rerender() + expect(runHeader.getAttribute('aria-expanded')).toBe('true') + fireEvent.blur(phaseHeader, { relatedTarget: runHeader }) + runHeader.focus() + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + }) + + it('settles a deferred phase close when the user hides the outer run', () => { + const running: WorkflowRunChatData = { + name: 'audit', status: 'running', phases: [phase()], + } + const view = render() + const member = screen.getByRole('button', { name: '打开 worker' }) + member.focus() + view.rerender() + const runHeader = screen.getByRole('button', { name: /^audit/ }) + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('true') + fireEvent.click(runHeader) + expect(runHeader.getAttribute('aria-expanded')).toBe('false') + fireEvent.click(runHeader) + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('false') + }) + + it('reinitializes manual choices from durable facts after a renderer remount', () => { + const data: WorkflowRunChatData = { + name: 'audit', status: 'running', phases: [phase()], + } + const view = render() + fireEvent.click(screen.getByRole('button', { name: /未分阶段/ })) + fireEvent.click(screen.getByRole('button', { name: /^audit/ })) + view.unmount() + render() + expect(screen.getByRole('button', { name: /^audit/ }).getAttribute('aria-expanded')).toBe('true') + expect(screen.getByRole('button', { name: /未分阶段/ }).getAttribute('aria-expanded')).toBe('true') + }) + it('opens only a running ordinary-list subagent proven to have this parent', () => { const data: WorkflowRunChatData = { name: 'audit', status: 'running', phases: [phase()], @@ -506,6 +792,16 @@ describe('WorkflowRunPanel', () => { expect(openSession).toHaveBeenCalledWith('child-1') }) + it('promotes a running member when its ordinary Session row arrives', () => { + const data: WorkflowRunChatData = { + name: 'audit', status: 'running', phases: [phase()], + } + const view = render() + expect(screen.queryByRole('button', { name: '打开 worker' })).toBeNull() + view.rerender() + expect(screen.getByRole('button', { name: '打开 worker' })).toBeTruthy() + }) + it.each([ ['not in ordinary list', listState({ ids: [PARENT_ID] }), 'running'], ['remote row', listState({ byId: { diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index 016af313f8..abba4371c2 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -2,16 +2,11 @@ import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, vi } from 'vitest' import { SlotRegistry } from '@deepseek-ai/dsh-client-runtime/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client' import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepseek-ai/dsh-client-ui-workspace/client' import { WorkspaceBrowser } from '../src/client/WorkspaceBrowser.tsx' import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' -// The service reads its initial locale from the browser; these specs assert -// the shipped Chinese copy, so they state the browser they assume. -usePinnedBrowserLanguages('zh-CN') - async function bench() { const ctx = new Context() await ctx.plugin(SlotRegistry).await() @@ -37,6 +32,10 @@ async function bench() { } as never) ctx.provide('sessions', { open, clear, search, searchResultLimit: 20, binding, fork } as never) const locale = new LocaleRuntime(ctx) + // These specs assert the shipped Chinese copy. There is no jsdom `window` + // in this lane, so browser-language detection never runs and the locale + // comes from FALLBACK_LOCALE (en): state the asserted locale explicitly. + locale.setLocale('zh') ctx.provide('locale', locale) return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, startSession, rename, diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index 3318a0fe43..fe37fef48a 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -3268,7 +3268,7 @@ describe('dynamic nested workspace context injection', () => { try { await mkdir(join(root, '.git'), { recursive: true }) await write(join(root, 'pkg/AGENTS.md'), 'canonical nested rule') - await write(join(root, 'pkg/CLAUDE.md'), 'distinct nested instruction') + await write(join(root, 'pkg/CLAUDE.md'), 'initial divergent nested rule') await write(join(root, 'pkg/file.txt'), 'hello') const ctx = new Context() await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) @@ -3280,7 +3280,7 @@ describe('dynamic nested workspace context injection', () => { }) const firstText = blocksText(((await syncedWorkspaceContext(ctx, agent))).content) expect(firstText).toContain('canonical nested rule') - expect(firstText).toContain('distinct nested instruction') + expect(firstText).toContain('initial divergent nested rule') await appendAdditionalContexts(ctx, agent) await write(join(root, 'pkg/CLAUDE.md'), 'canonical nested rule') await ctx.tools.execute({ diff --git a/packages/core/session/src/known-event-types.ts b/packages/core/session/src/known-event-types.ts index d65935f1b8..098743dd8a 100644 --- a/packages/core/session/src/known-event-types.ts +++ b/packages/core/session/src/known-event-types.ts @@ -48,6 +48,10 @@ export const KNOWN_SESSION_EVENT_TYPES: ReadonlySet = new Set([ 'step/end', 'step/start', 'subagent/descriptor', + 'team/member', + 'team/message/delivered', + 'team/message/queued', + 'team/task', 'todo/write', 'tool-workflow/agent-end', 'tool-workflow/agent-start', diff --git a/packages/core/session/tests/invariant.spec.ts b/packages/core/session/tests/invariant.spec.ts index 674755321f..b98391cc3b 100644 --- a/packages/core/session/tests/invariant.spec.ts +++ b/packages/core/session/tests/invariant.spec.ts @@ -277,7 +277,7 @@ describe('session-log invariants', () => { content: [{ ...original.data.message.content[0], content: [{ type: 'text', text: 'pruned' }], - }], + }] satisfies typeof original.data.message.content, }), }, { surfaceOp: { op: 'replace', start: original.seq, end: original.seq }, @@ -316,7 +316,7 @@ describe('session-log invariants', () => { content: [{ ...original.data.message.content[0], content: [{ type: 'text', text: 'pruned' }], - }], + }] satisfies typeof original.data.message.content, }), }, { surfaceOp: { op: 'replace', start: original.seq, end: original.seq }, diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index 921784c992..43945ea8db 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -25,7 +25,20 @@ describe('gen-tool-catalog collectToolCatalog', () => { it('boots every shipped tool package and harvests its model-facing schemas', async () => { const catalog = await collectToolCatalog() const names = catalog.flatMap(entry => entry.schemas.map(s => s.name)).sort() - expect(names).toEqual(['ask_user_question', 'bash', 'bash', 'cordis_define', 'cordis_inspect_list', 'cordis_inspect_query', 'cordis_inspect_self', 'cordis_run', 'cordis_stop', 'cordis_undefine', 'create_goal', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'lsp', 'pwsh', 'ralph', 'read', 'read_image', 'report', 'run_code', 'schedule_create', 'schedule_delete', 'schedule_list', 'send_message', 'session_event_read', 'session_event_search', 'session_event_trace', 'session_search', 'session_trace', 'skill', 'str_replace_editor', 'subagent', 'terminal_close', 'terminal_list', 'terminal_open', 'terminal_read', 'terminal_send', 'terminal_signal', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'write']) + expect(names).toEqual([ + 'ask_user_question', 'bash', 'bash', 'cordis_define', 'cordis_inspect_list', + 'cordis_inspect_query', 'cordis_inspect_self', 'cordis_run', 'cordis_stop', + 'cordis_undefine', 'create_goal', 'edit', 'exit_plan_mode', 'followup_task', 'get_goal', 'glob', 'grep', + 'interrupt_agent', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', + 'list_agents', 'list_agents', 'lsp', 'pwsh', 'ralph', + 'read', 'read_image', 'report', 'run_code', 'schedule_create', 'schedule_delete', + 'schedule_list', 'send_message', 'send_message', 'session_event_read', 'session_event_search', + 'session_event_trace', 'session_search', 'session_trace', 'skill', 'spawn_teammate', + 'str_replace_editor', 'subagent', 'team_task_create', + 'team_task_get', 'team_task_list', 'team_task_update', 'terminal_close', 'terminal_list', + 'terminal_open', 'terminal_read', 'terminal_send', 'terminal_signal', 'todo_write', + 'update_goal', 'wait_agent', 'web_fetch', 'web_search', 'workflow', 'write', + ]) // Every tool carries a JSON-Schema `parameters` object (what the model sees). for (const entry of catalog) { for (const schema of entry.schemas) { diff --git a/packages/experimental/AGENTS.md b/packages/experimental/AGENTS.md new file mode 100644 index 0000000000..cab30b777d --- /dev/null +++ b/packages/experimental/AGENTS.md @@ -0,0 +1,9 @@ +# AGENTS.md — Experimental packages + +These rules supplement the [package rules](../AGENTS.md). The [experimental Agent Teams package decision](../../.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.md) owns the rationale. + +- A package belongs here only when its complete public contract is experimental or internal-only. An experimental option inside a release package stays with its owning product role. +- Every package here sets `private: true` and omits `publishConfig`; the dsh release family excludes this directory. +- Release packages and apps must not name packages here in `dependencies`, `optionalDependencies`, or `peerDependencies`. Experimental packages may depend on release packages and each other. Tests may use experimental packages through `devDependencies`; examples may load them explicitly. +- Experimental status does not relax engineering, security, documentation, lifecycle, testing, invariant, or snapshot requirements. +- Promotion moves a package to its product-role group without renaming its `@deepseek-ai/dsh-*` package. Review its public contract, limitations, test evidence, release payload, runtime dependents, and named stable owner before promotion. diff --git a/packages/experimental/README.i18n.yaml b/packages/experimental/README.i18n.yaml new file mode 100644 index 0000000000..f2db56f558 --- /dev/null +++ b/packages/experimental/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/experimental/README.md +README.md: 1c3fd8c76f3331a6606455563b2ea56ff4832dc9 +README.zh.md: d7d40b21ad21764b9f64a71afec8a08446fbdc2e diff --git a/packages/experimental/README.md b/packages/experimental/README.md new file mode 100644 index 0000000000..1c3fd8c76f --- /dev/null +++ b/packages/experimental/README.md @@ -0,0 +1,12 @@ +# experimental/ — private experimental packages + +English | [中文](README.zh.md) + +This group contains prototypes and internal-only Cordis plugins that use the repository's real runtime without joining an official release. Its packages are private, carry no stability or support promise, and retain the same engineering, security, documentation, lifecycle, testing, and snapshot requirements as release packages. + +| Package | Role | ctx key | +|---|---|---| +| `team/` | Implicit-root Agent Teams roster, durable peer mailbox, shared task DAG, and runtime coordination | `ctx.teams` | +| `tool-team/` | Scoped model-facing Agent Teams tools and collaboration guidance | — | + +The [subtree rules](AGENTS.md) define dependency isolation, release exclusion, and promotion. diff --git a/packages/experimental/README.zh.md b/packages/experimental/README.zh.md new file mode 100644 index 0000000000..d7d40b21ad --- /dev/null +++ b/packages/experimental/README.zh.md @@ -0,0 +1,12 @@ +# experimental/:私有实验性包 + +[English](README.md) | 中文 + +本组包含使用仓库真实运行时、但不进入正式发布的原型与内部专用 Cordis 插件。组内包均为私有包,不承诺稳定性或支持,但仍须满足与发布包相同的工程、安全、文档、生命周期、测试和快照要求。 + +| 包 | 职责 | ctx key | +|---|---|---| +| `team/` | 隐式 root Agent Teams roster、持久 peer mailbox、共享任务 DAG 与运行时协调 | `ctx.teams` | +| `tool-team/` | 按 Agent 作用域提供的 Agent Teams 模型工具与协作指引 | — | + +[子树规则](AGENTS.md)规定依赖隔离、发布排除与 promotion。 diff --git a/packages/experimental/team/README.i18n.yaml b/packages/experimental/team/README.i18n.yaml new file mode 100644 index 0000000000..679ab3418b --- /dev/null +++ b/packages/experimental/team/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/experimental/team/README.md +README.md: f676f5b2245fd15559c9e5cd5f969ceece6625c8 +README.zh.md: e85dc59dcd349f69d23408038b4ecead01fbeca6 diff --git a/packages/experimental/team/README.md b/packages/experimental/team/README.md new file mode 100644 index 0000000000..f676f5b224 --- /dev/null +++ b/packages/experimental/team/README.md @@ -0,0 +1,76 @@ +# @deepseek-ai/dsh-team + +English | [中文](README.zh.md) + +Implicit-root Agent Teams domain. `ctx.teams` owns a flat Lead/teammate roster, a durable peer mailbox, and a shared task DAG in the Lead Session log. The [Agent Teams Agent Note](../../../.agents/notes/implemented/feature/2026-08-05-agent-teams.md) owns the coordination and isolation decisions; the [Team subsystem catalog](../../../docs/subsystems/team.md) records the literal durable shapes and service API. + +## Config + +```yaml +- id: team + name: '@deepseek-ai/dsh-team' + config: + maxMembers: 8 + maxTasks: 256 + maxPendingMessagesPerMember: 64 + maxMessageBytes: 65536 + disposalTimeoutMs: 5000 +``` + +Every limit must be a positive safe integer. `maxMembers` counts every name ever provisioned, including failed members, because names are never reusable. `maxTasks` counts non-deleted tasks. The mailbox limit is per target; the byte limit covers the complete framed delivery, including its stable id and sender name. `disposalTimeoutMs` bounds admitted creation, mailbox dispatch, and Team-owned Activation settlement so plugin reload and process shutdown fail visibly instead of waiting forever. + +The service requires Agent, Session, Session persistence, and continuable-subagent services. A composition without durable Session storage does not activate it. + +## Team identity and roster + +Every ordinary runtime root is the implicit Lead of a Team whose `TeamId` equals its `SessionId`; creating a Team is therefore state-free until the first member, message, or task record. A teammate is a named, continuable direct child recorded in that root's Session. Names are lowercase kebab-case, at most 64 characters, and immutable for the Team lifetime. Session ids remain the persistence and authorization identities. + +`spawnTeammate()` first appends and flushes a provisioning member, then asks the configured spawn or fork provider to create the reserved child id. A provider failure appends a durable failed member. Successful inbox admission is flushed in the child Session before the active edge commits. On root recovery, a provisioning record becomes active only when the independently persisted child has matching direct-parent and continuable descriptors plus its initial user message, either still pending in the durable inbox or already recorded in history; otherwise it becomes failed. If recovery wins a same-process provisioning race, the creator accepts the matching terminal state or reports `TEAM_PROVISIONING_CONFLICT` and drains a child that recovery already marked failed. Disposal closes admission, aborts and awaits admitted creation and mailbox-dispatch transactions, then asks the continuation owner to release the roster's exact live direct children and their descendants. Non-Team continuable children of the Lead remain untouched. Cleanup failures make disposal fail visibly. This closes crashes and reload races between root provisioning and its terminal member edge without reusing a name or retaining an orphan Activation. + +Fresh children have no parent-history seed. Fork children capture the Lead's completed-turn prefix once; the in-flight delegation turn is excluded. Inherited Team records carry the old root's `TeamId` and are ignored when an ordinary fork becomes an independent runtime root. Provider-owned subagents outside the roster do not become nested Team Leads. + +The roster reports durable provisioning/failed phases and live `running`/`idle` status. An active but non-resident teammate is `inactive`; later waking delivery cold-resumes it through the continuation owner. + +## Durable mailbox + +`sendMessage()` validates peer membership, appends `team/message/queued`, and flushes before attempting delivery. The result always identifies that durable message; `queued` means immediate delivery was deferred and is not an instruction to resend. Quiet delivery injects, flushes, and acknowledges context immediately when the target is live, but never activates an inactive target; an inactive target's quiet message remains queued. Wakeup delivery becomes the target's next FIFO turn and cold-resumes it when needed. + +The target message begins with `Team message from :` and retains the same id and sender in `TeamMessageSource`. Once the target Session durably holds that identity either in its pending inbox or recorded user-message history, the Lead log appends `team/message/delivered`. Immediate admissions are serialized per target in durable queue order, and recovery dispatches queued-minus-delivered records in the same order. Delivery folds both live and persisted inbox/history state before retrying, so a crash between inbox acceptance and model claim does not duplicate the message. A successful Lead-log flush wakes current `waitForChange()` callers, which then re-list authoritative state. + +The guarantee is process-local retry plus target-Session de-duplication, not cross-process exactly-once delivery. This release has no shared mailbox transaction across processes and no mailbox timeline UI. + +## Shared task board + +Tasks are complete versioned snapshots. Every mutation carries `expectedRevision`; stale callers receive `TEAM_TASK_STALE_REVISION` instead of overwriting a newer value. Any member can create, read, or claim a ready unowned task. The owner or Lead can edit, release, complete, reopen, or delete it; only the Lead can assign another member. Numeric `task-` ids require a safe-integer suffix; creation reports `TEAM_TASK_LIMIT` instead of reusing the final safe id. + +Dependencies must name current non-deleted tasks and form a complete DAG with no self or duplicate edge. A pending task is ready only after every blocker completes. Deleting a task that still has a non-deleted dependent is rejected. Deleted tasks remain tombstones for replay and id stability but do not consume `maxTasks` or appear in `listTasks()`. + +`writeScopes` are normalized workspace-relative prefixes. Views warn when they overlap an in-progress task, but they never block claim or authorize filesystem writes. They are coordination hints, not locks. + +`waitForChange()` waits for one roster, task, mailbox, or live-status edge that occurs after registration, for 10 seconds through one hour; it reports only whether the wait timed out and does not replay a change that already happened. Runtime disposal releases current waits and makes later waits return immediately without a timeout. Callers re-read authoritative state after wakeup or timeout. Cancellation preserves an Error reason or reports a non-Error reason through `TEAM_WAIT_ABORTED` with structural inspection instead of object coercion. `interrupt()` is Lead-only and delegates to the continuable-subagent interrupt path, which cancels only a live teammate's current turn with `keepInbox`; it neither releases task ownership nor deletes durable mail. + +The separate `./invariant` companion replays each candidate Team event against its committed Session prefix. Replay validates every current-version Team payload before it enters folded state, then rejects invalid member transitions, reused names, out-of-range numeric task ids, discontinuous task revisions, invalid task dependencies, duplicate queue/ack records, and acknowledgements with the wrong target before append. Session event `seq` and `time` own ordering and timing instead of duplicated snapshot timestamps. + +## Model Experience + +### Peer messages + +#### What the model sees + +Each delivered peer message is a user-role message. A short first text block names its stable message id and sender; the sender's original content blocks follow unchanged. Roster, task, and mailbox records themselves are log-only and never enter derived model history. + +#### Token effect + +Each peer delivery adds the sender prefix plus message content to the target history. Task and roster mutations add no model tokens; their model-facing representation belongs to `@deepseek-ai/dsh-tool-team` results. + +#### KV Cache effect + +Peer messages append after the target's reusable history prefix. Cold resume reuses the persisted conversation before appending a previously undelivered item. + +## Known Limitations and Deferred Work + +- **One process and one shared checkout** — members share cwd and observe edits immediately; this package provides no worktree, remote member, merge, or filesystem lock. +- **Advisory write scopes** — Bash, formatters, code generators, and direct external writers can bypass filesystem version checks; Leads must coordinate ownership and review the final diff. +- **Flat immutable roster** — only the Lead creates direct teammates; there is no nested Team, rename, deletion, or name reuse. +- **No automatic ownership release** — idle, interruption, process exit, and failed work do not release a task owner. +- **Mailbox is not cross-process exactly-once** — concurrent harness processes over one Team are unsupported. diff --git a/packages/experimental/team/README.zh.md b/packages/experimental/team/README.zh.md new file mode 100644 index 0000000000..e85dc59dcd --- /dev/null +++ b/packages/experimental/team/README.zh.md @@ -0,0 +1,76 @@ +# @deepseek-ai/dsh-team + +[English](README.md) | 中文 + +隐式 Root Agent Teams 领域。`ctx.teams` 在 Lead Session 日志中维护扁平的 Lead/teammate roster、持久 peer mailbox 与共享任务 DAG。[Agent Teams Agent Note](../../../.agents/notes/implemented/feature/2026-08-05-agent-teams.md)负责协作和隔离决策;[Team 子系统目录](../../../docs/subsystems/team.md)记录持久数据的字面形态与服务 API。 + +## 配置 + +```yaml +- id: team + name: '@deepseek-ai/dsh-team' + config: + maxMembers: 8 + maxTasks: 256 + maxPendingMessagesPerMember: 64 + maxMessageBytes: 65536 + disposalTimeoutMs: 5000 +``` + +每个限制都必须是正的安全整数。`maxMembers` 统计所有曾 provision 的名字,包括失败成员,因为名字永不复用。`maxTasks` 统计未删除任务。mailbox 限额按目标成员计算;字节限制覆盖完整的投递帧,包括稳定 id 与发送者名称。`disposalTimeoutMs` 限制已获准创建、mailbox dispatch 与 Team 自有 Activation 的 settlement 时长,使插件 reload 与进程 shutdown 在异常时明确失败,而不是无限等待。 + +该服务要求 Agent、Session、Session persistence 与 continuable-subagent 服务。没有持久 Session 存储的组合不会激活它。 + +## Team 身份与 roster + +每个普通运行时 Root 都是一个隐式 Team 的 Lead,其 `TeamId` 等于 `SessionId`;因此,在写入第一条成员、消息或任务记录前,创建 Team 不需要额外状态。teammate 是记录在 Root Session 中的具名 continuable 直接 child。名字采用小写 kebab-case,最长 64 个字符,在 Team 生命周期内不可变。Session id 始终是持久化与授权身份。 + +`spawnTeammate()` 先追加并 flush provisioning member,再要求配置的 spawn 或 fork provider 使用预留 child id 创建成员。provider 失败会追加持久 failed member。初始 inbox 消息获准后,先 flush child Session,再提交 active 边。Root 恢复时,只有独立持久 child 的直接 parent 与 continuable descriptor 匹配,并且其初始用户消息仍在持久 inbox 中或已经记录进历史,provisioning 才转为 active;否则转为 failed。如果 recovery 在同进程 provisioning 竞争中先完成,creator 会接受匹配终态,或报告 `TEAM_PROVISIONING_CONFLICT` 并 drain 已被 recovery 标为 failed 的 child。dispose 会关闭准入,中止并等待已获准的创建与 mailbox dispatch 事务,再让 continuation owner 释放 roster 中确切的 live direct child 及其后代;Lead 的非 Team continuable child 不受影响。cleanup 失败会让 dispose 明确失败。该对账覆盖 Root provisioning 与终态成员边之间的崩溃和 reload 窗口,同时不复用名字或遗留孤儿 Activation。 + +fresh child 不带 parent 历史 seed。fork child 只捕获一次 Lead 的已完成 turn 前缀,不包含正在执行 delegation 的 turn。继承的 Team 记录带有旧 Root 的 `TeamId`,普通 fork 成为独立运行时 Root 后会忽略这些记录。roster 之外、由 provider 管理的 subagent 不会被误认为嵌套 Team Lead。 + +roster 同时报告持久 provisioning/failed phase 与实时 `running`/`idle` 状态。active 但不驻留的 teammate 显示为 `inactive`;后续 wakeup 投递会经 continuation owner 冷恢复它。 + +## 持久 mailbox + +`sendMessage()` 校验 peer 成员关系,追加 `team/message/queued` 并 flush,之后才尝试投递。结果始终标识该持久消息;`queued` 表示即时投递被推迟,并不表示需要重发。target 为 live 时,quiet 投递会立即注入、flush 并确认上下文,但绝不会激活 inactive target;inactive target 的 quiet 消息会保持 queued。wakeup 投递成为 target 的下一个 FIFO turn,并在需要时冷恢复它。 + +目标消息以 `Team message from :` 开头,并在 `TeamMessageSource` 中保留同一 id 与发送者。target Session 在 pending inbox 或已记录的用户消息历史中持久保存该身份后,Lead 日志才追加 `team/message/delivered`。即时准入按 target 和持久 queue 顺序串行化,恢复也按同一顺序重新投递 queued-minus-delivered 记录。重试前会同时折叠 live 与持久 target 的 inbox/历史状态,因此 inbox 已接受但模型尚未 claim 时发生崩溃也不会复制消息。Lead 日志 flush 成功后会唤醒当前 `waitForChange()` 调用方,调用方随后重新列出权威状态。 + +该保证是进程内重试加 target Session 去重,而不是跨进程 exactly-once。本版本没有跨进程共享 mailbox 事务,也没有 mailbox 时间线 UI。 + +## 共享任务板 + +任务是完整的版本化快照。每次变更都携带 `expectedRevision`;陈旧调用方会收到 `TEAM_TASK_STALE_REVISION`,不会覆盖更新值。任意成员都可以创建、读取或 claim ready 且无 owner 的任务。Owner 或 Lead 可以编辑、释放、完成、重开或删除任务;只有 Lead 可以分配给其他成员。数字 `task-` id 的后缀必须是安全整数;最后一个安全 id 已被占用时,创建会报告 `TEAM_TASK_LIMIT`,而不会复用该 id。 + +依赖必须指向当前未删除任务,并组成完整 DAG,不允许 self edge 或重复 edge。只有所有 blocker 都 completed,pending 任务才 ready。仍被未删除任务依赖的任务不能删除。删除任务作为 tombstone 保留以供回放和维持 id 稳定,但不占用 `maxTasks`,也不出现在 `listTasks()` 中。 + +`writeScopes` 会规范化为 workspace-relative 路径前缀。view 会对与 in-progress 任务的重叠发出警告,但绝不会阻止 claim 或授予文件写权限。它们是协作提示,不是锁。 + +`waitForChange()` 可以等待注册后发生的下一条 roster、task、mailbox 或实时 status 边,时长范围为 10 秒到 1 小时;它只报告等待是否超时,也不会回放调用前已经发生的变化。运行时 dispose 会释放当前等待,并使后续等待不经超时立即返回。调用方需要在唤醒或超时后重新读取权威状态。取消会保留 Error reason;非 Error reason 则通过 `TEAM_WAIT_ABORTED` 以结构化检查结果报告,不再强制转成 object 字符串。`interrupt()` 仅限 Lead,并委托 continuable-subagent 的 interrupt 路径以 `keepInbox` 只取消 live teammate 的当前 turn;它既不释放任务 owner,也不删除持久 mail。 + +独立的 `./invariant` 配套模块会把每条候选 Team event 对照已提交 Session 前缀回放。回放会先验证每个当前版本 Team payload,再将其纳入折叠状态;随后会在 append 前拒绝非法 member 转换、名字复用、超出范围的数字 task id、不连续任务 revision、非法任务依赖、重复 queue/ack,以及 target 不匹配的 acknowledgement。顺序与时间由 Session event 的 `seq` 和 `time` 负责,不在 snapshot 中重复保存。 + +## 模型体验 + +### Peer 消息 + +#### 模型看到的内容 + +每条已投递 peer 消息都是用户角色消息。第一个短文本块包含稳定消息 id 与发送者,之后原样附加发送者的内容块。roster、task 和 mailbox 记录本身只存在于日志,不进入派生模型历史。 + +#### Token 影响 + +每次 peer 投递都会把发送者前缀与消息内容加入 target 历史。任务和 roster 变更不增加模型 token;其面向模型的呈现属于 `@deepseek-ai/dsh-tool-team` 结果。 + +#### KV Cache 影响 + +Peer 消息追加在 target 可复用历史前缀之后。冷恢复会先复用持久对话,再追加尚未投递的消息。 + +## 已知限制与暂缓事项 + +- **单进程、共享 checkout**:所有成员共享 cwd,修改立即可见;本包不提供 worktree、远端成员、自动 merge 或文件锁。 +- **write scope 仅作提示**:Bash、formatter、codegen 和直接外部写入可以绕过文件版本检查;Lead 必须协调 owner 并检查最终 diff。 +- **扁平且不可变的 roster**:只有 Lead 可以创建直接 teammate;不支持嵌套 Team、重命名、删除或名字复用。 +- **不会自动释放 owner**:idle、interrupt、进程退出与工作失败都不会释放任务 owner。 +- **mailbox 不保证跨进程 exactly-once**:不支持多个 harness 进程并发操作同一 Team。 diff --git a/packages/experimental/team/package.json b/packages/experimental/team/package.json new file mode 100644 index 0000000000..8a2423093a --- /dev/null +++ b/packages/experimental/team/package.json @@ -0,0 +1,62 @@ +{ + "name": "@deepseek-ai/dsh-team", + "description": "Implicit-root Agent Teams roster, durable peer mailbox, and shared task DAG", + "version": "0.1.0-rc.7", + "private": true, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/experimental/team" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "@deepseek-ai/schemastery": "workspace:^", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-brand": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-subagent": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", + "@deepseek-ai/dsh-brand": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-persistence-sqlite": "workspace:^", + "@deepseek-ai/dsh-subagent": "workspace:^", + "@deepseek-ai/dsh-subagent-fork-in-process": "workspace:^", + "@deepseek-ai/dsh-subagent-spawn-in-process": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + } +} diff --git a/packages/experimental/team/src/activity.ts b/packages/experimental/team/src/activity.ts new file mode 100644 index 0000000000..3b33f3320b --- /dev/null +++ b/packages/experimental/team/src/activity.ts @@ -0,0 +1,87 @@ +/** One-shot Team change waiters independent of durable state projection. */ + +import type { TeamId, TeamWaitResult } from './types.ts' +import { errorMessage, TeamError } from './error.ts' + +interface Waiter { + readonly resolve: () => void +} + +/** Owns current Team change waiters and releases each at most once. */ +export class TeamActivity { + private readonly waiters = new Map>() + private closed = false + + /** + * Wait for one later Team-domain or member-status change. + * @param id - Team whose next edge wakes the caller. + * @param timeoutMs - bounded wait duration from ten seconds through one hour. + * @param signal - caller cancellation for this wait only. + * @returns whether the wait ended by timeout. + */ + async wait(id: TeamId, timeoutMs: number, signal: AbortSignal): Promise { + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 10_000 || timeoutMs > 3_600_000) { + throw new TeamError('timeoutMs must be an integer from 10000 through 3600000', 'TEAM_INVALID_TIMEOUT') + } + signal.throwIfAborted() + if (this.closed) return { timedOut: false } + const changed = await new Promise((resolve, reject) => { + let waiters = this.waiters.get(id) + if (waiters === undefined) { + waiters = new Set() + this.waiters.set(id, waiters) + } + let settled = false + const finish = (settle: () => void): void => { + /* v8 ignore next -- timeout, abort, and notification may race after one winner removes the others. */ + if (settled) return + settled = true + clearTimeout(timer) + signal.removeEventListener('abort', onAbort) + waiters.delete(waiter) + if (waiters.size === 0) this.waiters.delete(id) + settle() + } + const onAbort = (): void => { + finish(() => { + const reason: unknown = signal.reason + reject(reason instanceof Error + ? reason + : new TeamError(`wait_agent aborted: ${errorMessage(reason)}`, 'TEAM_WAIT_ABORTED')) + }) + } + const waiter: Waiter = { + resolve: () => { + finish(() => { resolve(true) }) + }, + } + waiters.add(waiter) + const timer = setTimeout(() => { finish(() => { resolve(false) }) }, timeoutMs) + signal.addEventListener('abort', onAbort, { once: true }) + // AbortSignal does not replay an abort that wins between the pre-check and listener registration. + /* v8 ignore next -- requires an abort in the synchronous gap between the pre-check and listener registration. */ + if (signal.aborted) onAbort() + }) + return { timedOut: !changed } + } + + /** + * Wake and remove every current waiter for one Team. + * @param id - Team whose current waiters observe the change. + */ + notify(id: TeamId): void { + const waiters = this.waiters.get(id) + if (waiters === undefined) return + this.waiters.delete(id) + for (const waiter of waiters) waiter.resolve() + } + + /** Close admission and wake every current waiter during runtime disposal. */ + close(): void { + this.closed = true + for (const waiters of this.waiters.values()) { + for (const waiter of waiters) waiter.resolve() + } + this.waiters.clear() + } +} diff --git a/packages/experimental/team/src/error.ts b/packages/experimental/team/src/error.ts new file mode 100644 index 0000000000..e0b89b72bd --- /dev/null +++ b/packages/experimental/team/src/error.ts @@ -0,0 +1,23 @@ +/** Typed Agent Teams failures. */ + +import { inspect } from 'node:util' +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** Stable failure raised by the Team domain. */ +export class TeamError extends HarnessError { + constructor(message: string, code: string, options?: ErrorOptions) { + super(message, code, options) + this.name = 'TeamError' + } +} + +/** + * Render an arbitrary thrown value without replacing the original rejection. + * @param error - caught value used in a diagnostic or durable failure record. + * @returns one bounded single-line description. + */ +export function errorMessage(error: unknown): string { + if (error instanceof Error) return error.message + if (typeof error === 'string') return error + return inspect(error, { breakLength: Infinity, compact: true, depth: 4 }) +} diff --git a/packages/experimental/team/src/fold.ts b/packages/experimental/team/src/fold.ts new file mode 100644 index 0000000000..cf439a5322 --- /dev/null +++ b/packages/experimental/team/src/fold.ts @@ -0,0 +1,291 @@ +/** Strict replay fold for Agent Teams log-only events. */ + +import { z } from 'zod' +import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session' +import type { + TeamId, + TeamMemberSnapshot, + TeamMessageId, + TeamMessageSnapshot, + TeamTaskId, + TeamTaskSnapshot, +} from './types.ts' +import { + TeamId as toTeamId, + TeamMessageId as toTeamMessageId, + TeamTaskId as toTeamTaskId, +} from './types.ts' +import { assertTaskGraphCandidate } from './task-graph.ts' + +const nonNegativeSafeInteger = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) +const positiveSafeInteger = nonNegativeSafeInteger.min(1) +const sessionIdSchema = z.string().min(1).transform(value => SessionId(value)) +const teamIdSchema = z.string().min(1).transform(value => toTeamId(value)) +const numericTaskIdPattern = /^task-(\d+)$/u +const teamTaskIdSchema = z.string().min(1).refine((value) => { + const match = numericTaskIdPattern.exec(value) + return match === null || Number.isSafeInteger(Number(match[1])) +}, { message: 'numeric task id suffix must be a safe integer' }).transform(value => toTeamTaskId(value)) +const teamMessageIdSchema = z.string().min(1).transform(value => toTeamMessageId(value)) + +const coreContentBlockTypes = new Set(['text', 'reasoning', 'image', 'tool-call', 'tool-result']) +const imageAttachmentSchema = z.object({ + attachmentId: z.string().min(1), + mediaType: z.enum(['image/png', 'image/jpeg', 'image/webp', 'image/gif']), + bytes: nonNegativeSafeInteger, + width: positiveSafeInteger, + height: positiveSafeInteger, + name: z.string().optional(), +}).strict() + +// ContentBlockMap is merge-extensible. Validate every core variant exactly, +// while retaining JSON-decoded plugin variants under an unknown type tag. +const contentBlockSchema: z.ZodType = z.lazy(() => z.union([ + z.object({ type: z.literal('text'), text: z.string() }).strict(), + z.object({ type: z.literal('reasoning'), text: z.string() }).strict(), + z.object({ type: z.literal('image'), attachment: imageAttachmentSchema }).strict(), + z.object({ + type: z.literal('tool-call'), + id: z.string().min(1), + name: z.string(), + arguments: z.string(), + }).strict(), + z.object({ + type: z.literal('tool-result'), + toolCallId: z.string().min(1), + content: z.array(contentBlockSchema), + isError: z.boolean().optional(), + }).strict(), + z.object({ type: z.string().min(1) }).loose().refine( + block => !coreContentBlockTypes.has(block.type), + { message: 'known content block types must match their declared fields' }, + ), +])) as z.ZodType + +const teamMemberSnapshotSchema = z.object({ + id: sessionIdSchema, + name: z.string(), + description: z.string(), + provider: z.string(), + context: z.enum(['fresh', 'fork']), + phase: z.enum(['provisioning', 'active', 'failed']), + error: z.string().optional(), +}).strict() as z.ZodType + +const teamTaskSnapshotSchema = z.object({ + id: teamTaskIdSchema, + revision: positiveSafeInteger, + subject: z.string(), + description: z.string(), + status: z.enum(['pending', 'in_progress', 'completed', 'deleted']), + ownerId: sessionIdSchema.optional(), + blockedBy: z.array(teamTaskIdSchema), + writeScopes: z.array(z.string()), +}).strict() as z.ZodType + +const teamMessageSnapshotSchema = z.object({ + id: teamMessageIdSchema, + senderId: sessionIdSchema, + senderName: z.string(), + targetId: sessionIdSchema, + delivery: z.enum(['quiet', 'wakeup']), + content: z.array(contentBlockSchema), +}).strict() as z.ZodType + +const teamEventSelectorSchema = z.object({ + version: nonNegativeSafeInteger, + teamId: teamIdSchema, +}).loose() + +const teamMemberEventSchema = z.object({ + version: z.literal(1), + teamId: teamIdSchema, + member: teamMemberSnapshotSchema, +}).strict() as z.ZodType + +const teamTaskEventSchema = z.object({ + version: z.literal(1), + teamId: teamIdSchema, + task: teamTaskSnapshotSchema, +}).strict() as z.ZodType + +const teamMessageQueuedEventSchema = z.object({ + version: z.literal(1), + teamId: teamIdSchema, + message: teamMessageSnapshotSchema, +}).strict() as z.ZodType + +const teamMessageDeliveredEventSchema = z.object({ + version: z.literal(1), + teamId: teamIdSchema, + messageId: teamMessageIdSchema, + targetId: sessionIdSchema, +}).strict() as z.ZodType + +/** Mutable internal replay state. */ +export interface TeamFoldState { + readonly id: TeamId + readonly members: Map + readonly memberIdsByName: Map + readonly tasks: Map + readonly messages: Map + readonly delivered: Set + nextTaskNumber: number +} + +/** + * Construct an empty Team fold for one root Session. + * @param rootId - Session whose TeamId selects applicable records. + * @returns mutable empty replay state. + */ +export function emptyTeamFoldState(rootId: SessionId): TeamFoldState { + return { + id: toTeamId(rootId), + members: new Map(), + memberIdsByName: new Map(), + tasks: new Map(), + messages: new Map(), + delivered: new Set(), + nextTaskNumber: 1, + } +} + +/** Whether one event belongs to the Team domain. */ +export type TeamEventType = + | 'team/member' + | 'team/task' + | 'team/message/queued' + | 'team/message/delivered' + +/** One event owned by the Team domain. */ +export type TeamSessionEvent = SessionEvent + +/** + * Test whether a Session event belongs to the Team domain. + * @param event - candidate Session event. + * @returns whether the event has a Team-owned type. + */ +export function isTeamEvent(event: SessionEvent): event is TeamSessionEvent { + return event.type === 'team/member' + || event.type === 'team/task' + || event.type === 'team/message/queued' + || event.type === 'team/message/delivered' +} + +/** Decode one persisted Team value and retain the schema failure as its cause. */ +function parsePersisted(type: TeamEventType, schema: z.ZodType, value: unknown): T { + try { + return schema.parse(value) + } catch (error: unknown) { + throw new Error(`persisted Agent Teams ${type} payload is invalid`, { cause: error }) + } +} + +/** Decode the complete current-version payload selected by one Team event type. */ +function parseCurrentTeamEvent(event: TeamSessionEvent): TeamSessionEvent { + switch (event.type) { + case 'team/member': + return { ...event, data: parsePersisted(event.type, teamMemberEventSchema, event.data) } + case 'team/task': + return { ...event, data: parsePersisted(event.type, teamTaskEventSchema, event.data) } + case 'team/message/queued': + return { ...event, data: parsePersisted(event.type, teamMessageQueuedEventSchema, event.data) } + case 'team/message/delivered': + return { ...event, data: parsePersisted(event.type, teamMessageDeliveredEventSchema, event.data) } + /* v8 ignore next 2 -- TeamEventType is closed and every member is handled above. */ + default: + return event + } +} + +/** + * Apply one event, ignoring Team records inherited by a different root fork. + * @param state - mutable Team replay state. + * @param event - next contiguous Session event. + */ +export function applyTeamEvent(state: TeamFoldState, event: SessionEvent): void { + if (!isTeamEvent(event)) return + const selector = parsePersisted(event.type, teamEventSelectorSchema, event.data) + if (selector.version !== 1) { + if (selector.teamId !== state.id) return + throw new Error(`unsupported Agent Teams event version ${String(selector.version)}`) + } + const decoded = parseCurrentTeamEvent(event) + if (decoded.data.teamId !== state.id) return + + switch (decoded.type) { + case 'team/member': { + const member = decoded.data.member + const prior = state.members.get(member.id) + const named = state.memberIdsByName.get(member.name) + if (named !== undefined && named !== member.id) { + throw new Error(`teammate name "${member.name}" is reused by another member`) + } + if (prior === undefined) { + if (member.phase !== 'provisioning') throw new Error(`teammate "${member.name}" must begin provisioning`) + state.memberIdsByName.set(member.name, member.id) + } else { + if (prior.name !== member.name || prior.provider !== member.provider || prior.context !== member.context) { + throw new Error(`teammate "${member.id}" changed immutable identity fields`) + } + if (prior.phase !== 'provisioning' || member.phase === 'provisioning') { + throw new Error(`teammate "${member.name}" has an invalid ${prior.phase} -> ${member.phase} transition`) + } + } + state.members.set(member.id, member) + break + } + case 'team/task': { + const task = decoded.data.task + const prior = state.tasks.get(task.id) + if (prior === undefined && task.revision !== 1) { + throw new Error(`team task "${task.id}" must begin at revision 1`) + } + if (prior !== undefined && task.revision !== prior.revision + 1) { + throw new Error(`team task "${task.id}" revision is not contiguous`) + } + assertTaskGraphCandidate(state.tasks, task) + const match = numericTaskIdPattern.exec(task.id) + if (match !== null) { + const number = Number(match[1]) + state.nextTaskNumber = Math.max( + state.nextTaskNumber, + number === Number.MAX_SAFE_INTEGER ? number : number + 1, + ) + } + state.tasks.set(task.id, task) + break + } + case 'team/message/queued': { + const message = decoded.data.message + if (state.messages.has(message.id)) throw new Error(`team message "${message.id}" was queued twice`) + state.messages.set(message.id, message) + break + } + case 'team/message/delivered': { + const queued = state.messages.get(decoded.data.messageId) + if (queued === undefined) throw new Error(`team message "${decoded.data.messageId}" was delivered before queueing`) + if (queued.targetId !== decoded.data.targetId) throw new Error(`team message "${decoded.data.messageId}" target changed`) + if (state.delivered.has(decoded.data.messageId)) throw new Error(`team message "${decoded.data.messageId}" was delivered twice`) + state.delivered.add(decoded.data.messageId) + break + } + /* v8 ignore next 2 -- TeamEventType is closed and every member is handled above. */ + default: + return + } +} + +/** + * Replay one root Session into its current Team state. + * @param rootId - root Session identity selecting Team-owned records. + * @param events - complete contiguous Session log. + * @returns mutable replay state at the end of the log. + */ +export function foldTeam(rootId: SessionId, events: readonly SessionEvent[]): TeamFoldState { + const state = emptyTeamFoldState(rootId) + for (const event of events) applyTeamEvent(state, event) + return state +} diff --git a/packages/experimental/team/src/index.ts b/packages/experimental/team/src/index.ts new file mode 100644 index 0000000000..9b80d4d8dc --- /dev/null +++ b/packages/experimental/team/src/index.ts @@ -0,0 +1,261 @@ +/** Agent Teams service façade over roster, mailbox, task, and runtime lifecycle owners. */ + +import { Context, Service } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type { Agent } from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-session-persistence' +import { TeamActivity } from './activity.ts' +import { errorMessage, TeamError } from './error.ts' +import { TeamJournal } from './journal.ts' +import { TeamRuntimeLifecycle } from './lifecycle.ts' +import { TeamMailbox } from './mailbox.ts' +import { TeamRoster } from './roster.ts' +import type { TeamMembership } from './roster.ts' +import { TeamTaskBoard } from './task-board.ts' +import { TeamId, TeamTaskId } from './types.ts' +import type { + Config, + CreateTeamTaskRequest, + SendTeamMessageRequest, + SendTeamMessageResult, + SpawnTeammateRequest, + SpawnTeammateResult, + TeamMemberView, + TeamTaskView, + TeamWaitResult, + UpdateTeamTaskRequest, +} from './types.ts' + +export type * from './types.ts' +export type { TeamMembership } from './roster.ts' +export { TeamId, TeamMessageId, TeamTaskId } from './types.ts' +export { TeamError } from './error.ts' +export { foldTeam } from './fold.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + teams: TeamService + } +} + +const DEFAULT_MAX_MEMBERS = 8 +const DEFAULT_MAX_TASKS = 256 +const DEFAULT_MAX_PENDING_MESSAGES = 64 +const DEFAULT_MAX_MESSAGE_BYTES = 65_536 +const DEFAULT_DISPOSAL_TIMEOUT_MS = 5_000 + +/** Validate one positive safe-integer deployment limit. */ +function positiveLimit(name: string, value: number): number { + if (!Number.isSafeInteger(value) || value < 1) { + throw new TeamError(`${name} must be a positive safe integer`, 'TEAM_INVALID_CONFIG') + } + return value +} + +/** Agent Teams service backed by the exact live Lead Session log. */ +export class TeamService extends Service { + static inject = ['agents', 'sessions', 'sessionPersistence', 'subagents'] + + static Config: z = z.object({ + maxMembers: z.number().step(1).min(1).default(DEFAULT_MAX_MEMBERS), + maxTasks: z.number().step(1).min(1).default(DEFAULT_MAX_TASKS), + maxPendingMessagesPerMember: z.number().step(1).min(1).default(DEFAULT_MAX_PENDING_MESSAGES), + maxMessageBytes: z.number().step(1).min(1).default(DEFAULT_MAX_MESSAGE_BYTES), + disposalTimeoutMs: z.number().step(1).min(1).default(DEFAULT_DISPOSAL_TIMEOUT_MS), + }) + + /** Validated deployment limits used by every Team operation. */ + private readonly config: Required + + private readonly activity: TeamActivity + private readonly lifecycle: TeamRuntimeLifecycle + private readonly journal: TeamJournal + private readonly roster: TeamRoster + private readonly mailbox: TeamMailbox + private readonly tasks: TeamTaskBoard + + constructor(ctx: Context, config: Config = {}) { + super(ctx, 'teams') + this.config = { + maxMembers: positiveLimit('maxMembers', config.maxMembers ?? DEFAULT_MAX_MEMBERS), + maxTasks: positiveLimit('maxTasks', config.maxTasks ?? DEFAULT_MAX_TASKS), + maxPendingMessagesPerMember: positiveLimit( + 'maxPendingMessagesPerMember', + config.maxPendingMessagesPerMember ?? DEFAULT_MAX_PENDING_MESSAGES, + ), + maxMessageBytes: positiveLimit('maxMessageBytes', config.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES), + disposalTimeoutMs: positiveLimit( + 'disposalTimeoutMs', + config.disposalTimeoutMs ?? DEFAULT_DISPOSAL_TIMEOUT_MS, + ), + } + + this.activity = new TeamActivity() + this.lifecycle = new TeamRuntimeLifecycle(this.config.disposalTimeoutMs) + this.journal = new TeamJournal(ctx, (root) => { this.activity.notify(TeamId(root.id)) }) + this.roster = new TeamRoster(ctx, this.journal, this.lifecycle, this.config.maxMembers) + this.mailbox = new TeamMailbox( + ctx, + this.journal, + this.roster, + this.lifecycle, + this.config.maxPendingMessagesPerMember, + this.config.maxMessageBytes, + ) + this.tasks = new TeamTaskBoard(this.journal, this.config.maxTasks) + + ctx.on('session/event', (session, event) => { this.mailbox.observeSessionEvent(session, event) }) + ctx.on('agent/session-start', ({ agent }) => { this.scheduleRecovery(agent) }) + ctx.on('agent/status', ({ agent }) => { + const membership = this.roster.tryMembership(agent) + if (membership !== undefined) this.activity.notify(membership.id) + }) + ctx.effect(() => () => this.disposeRuntime(), 'teams.runtimeLifecycle()') + for (const agent of ctx.agents.list()) this.scheduleRecovery(agent) + } + + /** + * Resolve one exact live Agent's Team role. + * @param agent - exact live Agent used as the authority credential. + * @returns its root, Team identity, role, and model-facing name. + */ + membership(agent: Agent): TeamMembership { + return this.roster.membership(agent) + } + + /** + * List the runtime-enriched roster visible to one Team member. + * @param agent - exact live Team member. + * @returns Lead and teammate rows in creation order. + */ + listMembers(agent: Agent): TeamMemberView[] { + return this.roster.list(this.roster.membership(agent)) + } + + /** + * Create one named, continuable direct child of the Team Lead. + * @param caller - exact live Lead Agent. + * @param request - immutable name, description, prompt, context mode, provider, and cancellation. + * @returns the active roster row. + */ + async spawnTeammate(caller: Agent, request: SpawnTeammateRequest): Promise { + return await this.roster.spawn(caller, request) + } + + /** + * Queue one durable peer message, then attempt immediate delivery. + * @param caller - exact live sending Team member. + * @param request - target name, content, scheduling mode, and pre-queue cancellation. + * @returns durable message identity and immediate-delivery observation. + */ + async sendMessage(caller: Agent, request: SendTeamMessageRequest): Promise { + return await this.mailbox.send(caller, request) + } + + /** + * Create one unowned pending task in the Team Lead log. + * @param caller - exact live Team member creating the task. + * @param request - task text, blockers, and advisory write scopes. + * @returns the revision-one task view. + */ + async createTask(caller: Agent, request: CreateTeamTaskRequest): Promise { + return await this.tasks.create(this.roster.membership(caller), request) + } + + /** + * Return one task, including a deleted tombstone. + * @param caller - exact live Team member reading the task. + * @param id - Team-local task identity. + * @returns the latest task value and derived readiness diagnostics. + */ + getTask(caller: Agent, id: TeamTaskId): TeamTaskView { + return this.tasks.get(this.roster.membership(caller), id) + } + + /** + * List current non-deleted tasks in numeric creation order. + * @param caller - exact live Team member reading the board. + * @returns detached current task views. + */ + listTasks(caller: Agent): TeamTaskView[] { + return this.tasks.list(this.roster.membership(caller)) + } + + /** + * Compare-and-set one authorized task transition. + * @param caller - exact live Team member authorizing the mutation. + * @param request - task identity, expected revision, action, and action fields. + * @returns the committed next task revision. + */ + async updateTask(caller: Agent, request: UpdateTeamTaskRequest): Promise { + return await this.tasks.update(caller, this.roster.membership(caller), request) + } + + /** + * Wait for the next Team-domain or member-status change. + * @param caller - exact live Team member waiting for activity. + * @param timeoutMs - bounded wait duration from ten seconds through one hour. + * @param signal - caller cancellation for the wait only. + * @returns one observed change or a timeout result. + */ + async waitForChange(caller: Agent, timeoutMs: number, signal: AbortSignal): Promise { + const membership = this.roster.membership(caller) + return await this.activity.wait(membership.id, timeoutMs, signal) + } + + /** + * Interrupt one live teammate turn without clearing its pending inbox. + * @param caller - exact live Lead Agent. + * @param targetName - durable teammate name. + * @returns the target status sampled before cancellation. + */ + interrupt(caller: Agent, targetName: string): { previousStatus: 'running' | 'idle' | 'inactive' } { + return this.roster.interrupt(caller, targetName) + } + + /** + * Resolve a caller without throwing, used by scoped-tool installation and observers. + * @param agent - candidate exact live Agent. + * @returns Team membership, or undefined for non-Team subagents and stale identities. + */ + tryMembership(agent: Agent): TeamMembership | undefined { + return this.roster.tryMembership(agent) + } + + /** Queue one contained recovery pass after publication has unwound. */ + private scheduleRecovery(agent: Agent): void { + queueMicrotask(() => { + if (this.lifecycle.disposed) return + void this.recoverFor(agent).catch((error: unknown) => { + if (this.lifecycle.disposed) return + this.ctx.logger.warn(`Agent Teams recovery for "${agent.id}" failed: ${errorMessage(error)}`) + }) + }) + } + + /** Reconcile roster provisioning before retrying that member's pending mailbox. */ + private async recoverFor(agent: Agent): Promise { + await this.roster.recoverFor(agent, this.lifecycle.signal) + await this.mailbox.recoverFor(agent, this.lifecycle.signal) + } + + /** Stop Team-owned live branches and release every waiter before service disposal completes. */ + private async disposeRuntime(): Promise { + this.lifecycle.close() + this.activity.close() + + const failures: unknown[] = [] + await this.lifecycle.settle(this.roster.pendingCreations(), failures) + await this.lifecycle.settle(this.mailbox.pendingDispatches(), failures) + for (const [root, childIds] of this.roster.liveChildrenByRoot()) { + try { + await this.roster.stopTeammates(root, childIds) + } catch (error: unknown) { + failures.push(error) + } + } + if (failures.length > 0) throw new AggregateError(failures, 'Agent Teams runtime disposal failed') + } +} + +export default TeamService diff --git a/packages/experimental/team/src/invariant.ts b/packages/experimental/team/src/invariant.ts new file mode 100644 index 0000000000..52e28491fe --- /dev/null +++ b/packages/experimental/team/src/invariant.ts @@ -0,0 +1,34 @@ +/** Package-owned relational checks for Agent Teams durable records. */ + +import type { Context } from '@deepseek-ai/cordis' +import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants' +import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import { applyTeamEvent, foldTeam, isTeamEvent } from './fold.ts' + +const PACKAGE_NAME = '@deepseek-ai/dsh-team' + +/** Cordis companion plugin name. */ +export const name = 'team-invariant' +/** Invariant registry required by the companion. */ +export const inject = ['invariants'] + +/** Validate candidate Team events against the committed prefix before append. */ +const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => { + ctx.on('internal/dispatch', (_mode, eventName, args) => { + if (eventName !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (!isTeamEvent(event)) return + try { + const state = foldTeam(session.id, session.events) + applyTeamEvent(state, event) + } catch (error: unknown) { + /* v8 ignore next -- the strict Team fold throws Error instances. */ + const message = error instanceof Error ? error.message : String(error) + fail(`session event ${event.seq} violates the Agent Teams stream: ${message}`) + } + }, { global: true }) +}, { inject: ['sessions'] }) + +/** Register the package invariant companion. */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) diff --git a/packages/experimental/team/src/journal.ts b/packages/experimental/team/src/journal.ts new file mode 100644 index 0000000000..f97e7776f9 --- /dev/null +++ b/packages/experimental/team/src/journal.ts @@ -0,0 +1,71 @@ +/** Serialized Team transactions over the exact live Lead Session log. */ + +import type { Agent } from '@deepseek-ai/dsh-agent' +import type { Context } from '@deepseek-ai/cordis' +import type { SessionEventMap, SessionId } from '@deepseek-ai/dsh-session' +import { foldTeam } from './fold.ts' +import type { TeamEventType, TeamFoldState } from './fold.ts' + +type AppendTeamEvent = (type: T, data: SessionEventMap[T]) => void +type MutableTeamEventType = 'team/member' | 'team/task' | 'team/message/queued' | 'team/message/delivered' + +/** Owns per-Lead transaction order and committed Team event publication. */ +export class TeamJournal { + private readonly tails = new Map>() + + /** + * @param ctx - Team service context with the injected Session service. + * @param onCommit - synchronous notification after the Team event flush succeeds. + */ + constructor( + private readonly ctx: Context, + private readonly onCommit: (root: Agent) => void, + ) {} + + /** + * Fold authoritative Team state for one exact live Lead. + * @param root - exact live Team Lead. + * @returns current replay state selected by the Lead Team id. + */ + state(root: Agent): TeamFoldState { + return foldTeam(root.id, root.session.events) + } + + /** + * Serialize one Lead's asynchronous mutation operation. + * @param rootId - Lead Session identity selecting the transaction queue. + * @param operation - complete read-check-append operation. + * @returns the operation result. + */ + async transact(rootId: SessionId, operation: () => Promise): Promise { + const prior = this.tails.get(rootId) ?? Promise.resolve() + const run = prior.then(operation, operation) + const tail = run.then(() => undefined, () => undefined) + this.tails.set(rootId, tail) + try { + return await run + } finally { + if (this.tails.get(rootId) === tail) this.tails.delete(rootId) + } + } + + /** + * Append and checkpoint one root-owned Team event before publication. + * @param root - exact live Lead whose Session owns the event. + * @param type - Team event discriminant. + * @param data - payload correlated with the event type. + */ + async appendAndFlush( + root: Agent, + type: T, + data: SessionEventMap[T], + ): Promise { + // Team events never enter the conversation surface. This narrower local + // capability removes Session.append's conditional surface argument while + // preserving the event-key/payload correlation. + const append = root.session.append.bind(root.session) as unknown as AppendTeamEvent + append(type, data) + await this.ctx.sessions.flush(root.session) + this.onCommit(root) + } +} diff --git a/packages/experimental/team/src/lifecycle.ts b/packages/experimental/team/src/lifecycle.ts new file mode 100644 index 0000000000..55bdfadb9e --- /dev/null +++ b/packages/experimental/team/src/lifecycle.ts @@ -0,0 +1,87 @@ +/** Shared admission cutoff and bounded settlement for the Team runtime. */ + +import { TeamError } from './error.ts' + +/** Owns the single Team runtime cancellation fact and disposal timeout. */ +export class TeamRuntimeLifecycle { + private readonly controller = new AbortController() + + /** + * @param disposalTimeoutMs - maximum wait for one disposal settlement operation. + */ + constructor(private readonly disposalTimeoutMs: number) {} + + /** Signal aborted exactly when Team runtime admission closes. */ + get signal(): AbortSignal { + return this.controller.signal + } + + /** Whether Team runtime admission is closed. */ + get disposed(): boolean { + return this.signal.aborted + } + + /** The exact cancellation reason used to distinguish expected disposal rejection. */ + get reason(): unknown { + const reason: unknown = this.signal.reason + return reason + } + + /** Whether a rejection is the runtime cancellation, directly or through an Error cause chain. */ + private isCancellation(reason: unknown): boolean { + const seen = new Set() + let current = reason + while (!seen.has(current)) { + if (this.disposed && current === this.reason) return true + if (this.disposed && current instanceof TeamError && current.code === 'TEAM_DISPOSED') return true + if (!(current instanceof Error)) return false + seen.add(current) + current = current.cause + } + return false + } + + /** Close Team runtime admission and cancel admitted interruptible work. */ + close(): void { + this.controller.abort(new TeamError('Agent Teams service disposed', 'TEAM_DISPOSED')) + } + + /** + * Await admitted operations and retain failures other than runtime cancellation. + * @param operations - admitted operations captured after the admission cutoff. + * @param failures - aggregate destination for unexpected rejection or timeout. + */ + async settle(operations: readonly Promise[], failures: unknown[]): Promise { + if (operations.length === 0) return + try { + const outcomes = await this.withTimeout(Promise.allSettled(operations)) + for (const outcome of outcomes) { + if (outcome.status === 'rejected' && !this.isCancellation(outcome.reason)) failures.push(outcome.reason) + } + } catch (error: unknown) { + failures.push(error) + } + } + + /** + * Bound one runtime settlement operation. + * @param operation - settlement that may otherwise block HMR or process shutdown. + * @returns the operation result. + */ + async withTimeout(operation: Promise): Promise { + let timer!: ReturnType + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => { + reject(new TeamError( + `Agent Teams runtime disposal exceeded ${this.disposalTimeoutMs}ms`, + 'TEAM_DISPOSAL_TIMEOUT', + )) + }, this.disposalTimeoutMs) + }) + try { + return await Promise.race([operation, timeout]) + } finally { + clearTimeout(timer) + } + } +} diff --git a/packages/experimental/team/src/mailbox.ts b/packages/experimental/team/src/mailbox.ts new file mode 100644 index 0000000000..b234cef408 --- /dev/null +++ b/packages/experimental/team/src/mailbox.ts @@ -0,0 +1,338 @@ +/** Durable Team mailbox admission, target-local dispatch, acknowledgement, and recovery. */ + +import { randomUUID } from 'node:crypto' +import type { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import { errorMessage, TeamError } from './error.ts' +import type { TeamJournal } from './journal.ts' +import type { TeamRuntimeLifecycle } from './lifecycle.ts' +import type { TeamRoster } from './roster.ts' +import { resolveActiveMember } from './roster.ts' +import { messageAccepted } from './session-message.ts' +import { TeamId, TeamMessageId } from './types.ts' +import type { + SendTeamMessageRequest, + SendTeamMessageResult, + TeamMessageSnapshot, +} from './types.ts' + +/** Owns every process-local state transition for the durable Team mailbox. */ +export class TeamMailbox { + private readonly dispatchTails = new Map>() + private readonly activeDispatches = new Map() + private readonly inFlightMessages = new Set() + private readonly inFlightDispatches = new Set>() + + /** + * @param ctx - Team service context with Agent, Session, persistence, and subagent services. + * @param journal - authoritative Lead-log transaction owner. + * @param roster - Team membership and member-name resolver. + * @param lifecycle - shared Team runtime admission cutoff. + * @param maxPendingMessagesPerMember - per-target queued-minus-delivered limit. + * @param maxMessageBytes - maximum complete sender-framed delivery size. + */ + constructor( + private readonly ctx: Context, + private readonly journal: TeamJournal, + private readonly roster: TeamRoster, + private readonly lifecycle: TeamRuntimeLifecycle, + private readonly maxPendingMessagesPerMember: number, + private readonly maxMessageBytes: number, + ) {} + + /** + * Queue one durable peer message, then attempt immediate delivery. + * @param caller - exact live sending Team member. + * @param request - target name, content, scheduling mode, and pre-queue cancellation. + * @returns durable message identity and immediate-delivery observation. + */ + async send(caller: Agent, request: SendTeamMessageRequest): Promise { + if (this.lifecycle.disposed) throw new TeamError('Agent Teams service is disposing', 'TEAM_DISPOSED') + const operation = this.sendAdmitted(caller, { + ...request, + signal: AbortSignal.any([request.signal, this.lifecycle.signal]), + }) + return await this.trackDispatch(operation) + } + + /** + * Observe target-side durable receipts and checkpoint their Lead-log acknowledgement. + * @param session - exact target Session receiving the event. + * @param event - newly appended Session event. + */ + observeSessionEvent(session: Session, event: SessionEvent): void { + if (this.lifecycle.disposed || event.type !== 'user/message' || event.data.source.kind !== 'team-message') return + const source = event.data.source + const acknowledgement = Promise.resolve().then(async () => { + const root = this.ctx.agents.get(SessionId(source.teamId)) + if (root !== undefined) await this.checkpointDelivered(root, session, source.messageId) + }).catch((error: unknown) => { + this.ctx.logger.warn(`Team message "${source.messageId}" acknowledgement failed: ${errorMessage(error)}`) + }) + void this.trackDispatch(acknowledgement) + } + + /** + * Retry durable pending messages relevant to one started Team member. + * @param agent - newly started exact live Agent. + * @param signal - shared runtime cancellation. + */ + async recoverFor(agent: Agent, signal: AbortSignal): Promise { + signal.throwIfAborted() + const membership = this.roster.tryMembership(agent) + if (membership === undefined) return + const state = this.journal.state(membership.root) + const messages = [...state.messages.values()].filter(message => + !state.delivered.has(message.id) + && (membership.role === 'lead' || message.targetId === agent.id)) + for (const message of messages) { + signal.throwIfAborted() + if (membership.role === 'lead' && message.delivery === 'quiet' + && message.targetId !== membership.root.id && this.ctx.agents.get(message.targetId) === undefined) continue + await this.tryDispatch(membership.root, message, signal) + } + } + + /** + * Return admitted dispatch and acknowledgement operations captured for disposal. + * @returns detached snapshot ordered only by Set insertion. + */ + pendingDispatches(): readonly Promise[] { + return [...this.inFlightDispatches] + } + + /** Queue and dispatch one mailbox item admitted before the disposal cutoff. */ + private async sendAdmitted( + caller: Agent, + request: SendTeamMessageRequest, + ): Promise { + const membership = this.roster.membership(caller) + request.signal.throwIfAborted() + const root = membership.root + const content = structuredClone(request.content) + const queued = await this.journal.transact(root.id, async () => { + request.signal.throwIfAborted() + const state = this.journal.state(root) + const target = resolveActiveMember(root, state, request.target) + if (target.id === caller.id) throw new TeamError('a Team member cannot message itself', 'TEAM_SELF_MESSAGE') + const pendingForTarget = [...state.messages.values()].filter(candidate => + candidate.targetId === target.id && !state.delivered.has(candidate.id)).length + if (pendingForTarget >= this.maxPendingMessagesPerMember) { + throw new TeamError( + `teammate "${target.name}" has ${pendingForTarget} pending messages`, + 'TEAM_MAILBOX_FULL', + ) + } + const queued: TeamMessageSnapshot = { + id: TeamMessageId(`team-message-${randomUUID()}`), + senderId: caller.id, + senderName: membership.name, + targetId: target.id, + delivery: request.delivery, + content, + } + if (Buffer.byteLength(JSON.stringify(this.deliveryContent(queued)), 'utf8') > this.maxMessageBytes) { + throw new TeamError(`team message exceeds ${this.maxMessageBytes} bytes`, 'TEAM_MESSAGE_TOO_LARGE') + } + await this.journal.appendAndFlush(root, 'team/message/queued', { + version: 1, + teamId: TeamId(root.id), + message: queued, + }) + // Register dispatch before releasing the root transaction so concurrent + // senders enter the target-local queue in durable mailbox order. + return { message: queued, dispatch: this.tryDispatch(root, queued, request.signal) } + }) + const accepted = await queued.dispatch + return { messageId: queued.message.id, status: accepted ? 'accepted' : 'queued' } + } + + /** Attempt one queued message exactly once in this process at a time. */ + private tryDispatch(root: Agent, message: TeamMessageSnapshot, signal: AbortSignal): Promise { + if (this.lifecycle.disposed) return Promise.resolve(false) + if (this.inFlightMessages.has(message.id)) return Promise.resolve(false) + this.inFlightMessages.add(message.id) + const operation = this.trackDispatch( + this.tryDispatchAdmitted( + root, + message, + AbortSignal.any([signal, this.lifecycle.signal]), + ), + ) + const forget = (): void => { + this.inFlightMessages.delete(message.id) + } + void operation.then(forget, forget) + return operation + } + + /** Track one dispatch transaction through delivery admission or contained failure. */ + private trackDispatch(operation: Promise): Promise { + this.inFlightDispatches.add(operation) + void operation.then(() => { + this.inFlightDispatches.delete(operation) + }, () => { + this.inFlightDispatches.delete(operation) + }) + return operation + } + + /** Attempt one queued message admitted before the service lifecycle cutoff. */ + private async tryDispatchAdmitted( + root: Agent, + message: TeamMessageSnapshot, + signal: AbortSignal, + ): Promise { + const active = this.activeDispatches.get(message.targetId) + const live = message.targetId === root.id ? root : this.ctx.agents.get(message.targetId) + if (active !== undefined && live !== undefined && message.delivery === 'quiet' + && this.messagePrecedes(root, message.id, active.id)) { + return await this.dispatchOnce(root, message, signal) + } + return await this.serializeDispatch(message, () => this.dispatchOnce(root, message, signal)) + } + + /** Serialize delivery admission for one durable target in queued order. */ + private async serializeDispatch( + message: TeamMessageSnapshot, + operation: () => Promise, + ): Promise { + const targetId = message.targetId + const prior = this.dispatchTails.get(targetId) ?? Promise.resolve() + const dispatch = async (): Promise => { + this.activeDispatches.set(targetId, message) + try { + return await operation() + } finally { + this.activeDispatches.delete(targetId) + } + } + /* v8 ignore next -- dispatch tails absorb rejection, so the recovery callback is a fail-safe backstop. */ + const run = prior.then(dispatch, dispatch) + /* v8 ignore next -- dispatchOnce contains delivery failures and serializeDispatch itself does not throw. */ + const tail = run.then(() => undefined, () => undefined) + this.dispatchTails.set(targetId, tail) + try { + return await run + } finally { + if (this.dispatchTails.get(targetId) === tail) this.dispatchTails.delete(targetId) + } + } + + /** Attempt one queued delivery after target-local ordering admits it. */ + private async dispatchOnce(root: Agent, message: TeamMessageSnapshot, signal: AbortSignal): Promise { + try { + const target = message.targetId === root.id ? root : this.ctx.agents.get(message.targetId) + if (target !== undefined && this.targetRecorded(target.session, message.id)) { + return await this.checkpointDelivered(root, target.session, message.id) + } + const source = { + kind: 'team-message' as const, + teamId: TeamId(root.id), + messageId: message.id, + senderId: message.senderId, + senderName: message.senderName, + } + const content = this.deliveryContent(message) + if (message.targetId === root.id) { + const input = createUserMessage({ content, source }) + if (message.delivery === 'wakeup') { + root.followup(input) + return await this.checkpointDelivered(root, root.session, message.id) + } + root.inject(input) + return await this.checkpointDelivered(root, root.session, message.id) + } + if (message.delivery === 'quiet') { + if (target === undefined) return false + target.inject(createUserMessage({ content, source })) + return await this.checkpointDelivered(root, target.session, message.id) + } + if (target === undefined) { + const recorded = await this.persistedTargetRecorded(message.targetId, message.id, signal) + if (recorded === undefined) return false + if (recorded) { + await this.markDelivered(root, message.id, message.targetId) + return true + } + } + await this.ctx.subagents.followup(root, message.targetId, content, { source, signal }) + return target === undefined + ? true + : await this.checkpointDelivered(root, target.session, message.id) + } catch (error: unknown) { + this.ctx.logger.warn(`team message "${message.id}" remains queued: ${errorMessage(error)}`) + return false + } + } + + /** Whether `left` was durably queued before `right` in one Lead log. */ + private messagePrecedes(root: Agent, left: TeamMessageId, right: TeamMessageId): boolean { + const ids = [...this.journal.state(root).messages.keys()] + return ids.indexOf(left) < ids.indexOf(right) + } + + /** Flush one live target receipt before the Lead records its delivered edge. */ + private async checkpointDelivered( + root: Agent, + target: Session, + messageId: TeamMessageId, + ): Promise { + await this.ctx.sessions.flush(target) + if (!this.targetRecorded(target, messageId)) return false + await this.markDelivered(root, messageId, target.id) + return true + } + + /** Record delivery unless the acknowledgement already exists. */ + private async markDelivered(root: Agent, messageId: TeamMessageId, targetId: SessionId): Promise { + await this.journal.transact(root.id, async () => { + const state = this.journal.state(root) + if (state.delivered.has(messageId)) return + const queued = state.messages.get(messageId) + if (queued === undefined || queued.targetId !== targetId) return + await this.journal.appendAndFlush(root, 'team/message/delivered', { + version: 1, + teamId: TeamId(root.id), + messageId, + targetId, + }) + }) + } + + /** Whether a target Session already contains the durable message identity. */ + private targetRecorded(session: Session, messageId: TeamMessageId): boolean { + const suffix = session.events.slice(session.header.seedLength ?? 0) + return messageAccepted(suffix, message => message.source.kind === 'team-message' + && message.source.messageId === messageId) + } + + /** Frame peer content with stable sender and message identity for the receiving model. */ + private deliveryContent(message: TeamMessageSnapshot): ContentBlock[] { + return [ + { type: 'text', text: `Team message ${message.id} from ${message.senderName}:` }, + ...structuredClone(message.content), + ] + } + + /** Inspect an inactive target before cold resume; uncertainty keeps the mailbox queued. */ + private async persistedTargetRecorded( + targetId: SessionId, + messageId: TeamMessageId, + signal: AbortSignal, + ): Promise { + try { + const stored = await this.ctx.sessionPersistence.inspect(targetId, signal) + const suffix = stored.events.slice(stored.meta.seedLength ?? 0) + return messageAccepted(suffix, message => message.source.kind === 'team-message' + && message.source.messageId === messageId) + } catch (error: unknown) { + this.ctx.logger.warn(`cannot inspect Team message target "${targetId}": ${errorMessage(error)}`) + return undefined + } + } +} diff --git a/packages/experimental/team/src/roster.ts b/packages/experimental/team/src/roster.ts new file mode 100644 index 0000000000..2d8d190fce --- /dev/null +++ b/packages/experimental/team/src/roster.ts @@ -0,0 +1,485 @@ +/** Team membership, continuable-child provisioning, and roster-owned teardown. */ + +import { randomUUID } from 'node:crypto' +import type { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import type { MessageId } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import { foldSubagentDescriptor } from '@deepseek-ai/dsh-subagent' +import type { ContinuableStart } from '@deepseek-ai/dsh-subagent' +import { errorMessage, TeamError } from './error.ts' +import type { TeamFoldState } from './fold.ts' +import type { TeamJournal } from './journal.ts' +import type { TeamRuntimeLifecycle } from './lifecycle.ts' +import { messageAccepted } from './session-message.ts' +import { TeamId } from './types.ts' +import type { + SpawnTeammateRequest, + SpawnTeammateResult, + TeamMemberSnapshot, + TeamMemberView, +} from './types.ts' +import { requiredText } from './validation.ts' + +const MEMBER_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u + +/** Caller identity inside one implicit Team. */ +export interface TeamMembership { + readonly root: Agent + readonly id: TeamId + readonly role: 'lead' | 'teammate' + readonly name: string +} + +/** + * Resolve one active Team member by model-facing name, including the Lead pseudo-row. + * @param root - exact live Team Lead. + * @param state - current Team fold. + * @param rawName - candidate member name. + * @returns resolved durable id and normalized name. + */ +export function resolveActiveMember( + root: Agent, + state: TeamFoldState, + rawName: string, +): { id: SessionId; name: string } { + const name = rawName.trim() + if (name === 'lead') return { id: root.id, name } + const id = state.memberIdsByName.get(name) + const member = id === undefined ? undefined : state.members.get(id) + if (member === undefined || member.phase !== 'active') { + throw new TeamError(`active teammate "${name}" not found`, 'TEAM_MEMBER_NOT_FOUND') + } + return { id: member.id, name } +} + +/** Owns Team identities and the lifecycle of rostered continuable children. */ +export class TeamRoster { + private readonly inFlightCreations = new Set>() + + /** + * @param ctx - Team service context with Agent, Session, persistence, and subagent services. + * @param journal - authoritative Lead-log transaction owner. + * @param lifecycle - shared Team runtime admission cutoff. + * @param maxMembers - maximum immutable roster entries per Team. + */ + constructor( + private readonly ctx: Context, + private readonly journal: TeamJournal, + private readonly lifecycle: TeamRuntimeLifecycle, + private readonly maxMembers: number, + ) {} + + /** + * Resolve one exact live Agent's Team role. + * @param agent - exact live Agent used as the authority credential. + * @returns its root, Team identity, role, and model-facing name. + */ + membership(agent: Agent): TeamMembership { + const membership = this.tryMembership(agent) + if (membership === undefined) { + throw new TeamError(`agent "${agent.id}" is not a member of an active Agent Team`, 'TEAM_NOT_MEMBER') + } + return membership + } + + /** + * Resolve a caller without throwing for scoped installation and lifecycle observers. + * @param agent - candidate exact live Agent. + * @returns Team membership, or undefined for non-Team subagents and stale identities. + */ + tryMembership(agent: Agent): TeamMembership | undefined { + if (this.ctx.agents.get(agent.id) !== agent) return undefined + try { + const parentId = agent.session.header.parentSession + if (parentId !== undefined) { + const root = this.ctx.agents.get(parentId) + if (root !== undefined) { + const member = this.journal.state(root).members.get(agent.id) + if (member?.phase === 'active' || member?.phase === 'provisioning') { + return { root, id: TeamId(root.id), role: 'teammate', name: member.name } + } + // A direct child outside the durable roster is not a teammate. Ordinary + // host forks are independent roots; subagent descriptors distinguish + // provider-owned workers that must not receive a nested Team identity. + if (this.subagentDescriptor(agent)) return undefined + return { root: agent, id: TeamId(agent.id), role: 'lead', name: 'lead' } + } + } + // A continuation can briefly outlive its parent during child-first teardown. + // Do not reinterpret that durable child as a new implicit root Team. A host- + // resumed ordinary fork has no descriptor in its own suffix and remains a + // valid new root whose inherited Team records fold out by TeamId. + if (this.subagentDescriptor(agent)) return undefined + return { root: agent, id: TeamId(agent.id), role: 'lead', name: 'lead' } + } catch { + // This method is used by lifecycle observers and teardown discovery. A + // malformed durable stream is surfaced by authoritative Team operations; + // the non-throwing probe must not veto unrelated Agent lifecycle edges. + return undefined + } + } + + /** + * List the runtime-enriched roster visible to one Team member. + * @param membership - exact caller membership resolved by this roster. + * @returns Lead and teammate rows in creation order. + */ + list(membership: TeamMembership): TeamMemberView[] { + const { root } = membership + const state = this.journal.state(root) + const result: TeamMemberView[] = [{ + id: root.id, + name: 'lead', + role: 'lead', + status: root.status, + ...root.options.model === undefined ? {} : { model: root.options.model }, + diagnostics: [], + }] + for (const member of state.members.values()) { + const live = this.ctx.agents.get(member.id) + const model = live?.options.model ?? root.options.model + result.push({ + id: member.id, + name: member.name, + role: 'teammate', + status: member.phase === 'failed' + ? 'failed' + : member.phase === 'provisioning' + ? 'provisioning' + : live?.status ?? 'inactive', + description: member.description, + provider: member.provider, + context: member.context, + ...model === undefined ? {} : { model }, + diagnostics: member.error === undefined ? [] : [member.error], + }) + } + return result + } + + /** + * Create one named, continuable direct child of the Team Lead. + * @param caller - exact live Lead Agent. + * @param request - immutable name, description, prompt, context mode, provider, and cancellation. + * @returns the active roster row. + */ + async spawn(caller: Agent, request: SpawnTeammateRequest): Promise { + if (this.lifecycle.disposed) throw new TeamError('Agent Teams service is disposing', 'TEAM_DISPOSED') + const operation = this.spawnAdmitted(caller, request) + this.inFlightCreations.add(operation) + try { + return await operation + } finally { + this.inFlightCreations.delete(operation) + } + } + + /** + * Return admitted creation operations captured for ordered disposal. + * @returns detached snapshot ordered only by Set insertion. + */ + pendingCreations(): readonly Promise[] { + return [...this.inFlightCreations] + } + + /** + * Reconcile provisioning state when one Team member Session starts. + * @param agent - newly started exact live Agent. + * @param signal - shared runtime cancellation. + */ + async recoverFor(agent: Agent, signal: AbortSignal): Promise { + signal.throwIfAborted() + const membership = this.tryMembership(agent) + if (membership?.role === 'lead') await this.reconcileProvisioning(membership.root, signal) + } + + /** + * Interrupt one live teammate turn without clearing its pending inbox. + * @param caller - exact live Lead Agent. + * @param targetName - durable teammate name. + * @returns the target status sampled before cancellation. + */ + interrupt(caller: Agent, targetName: string): { previousStatus: 'running' | 'idle' | 'inactive' } { + const membership = this.membership(caller) + if (membership.role !== 'lead') throw new TeamError('only the Team Lead can interrupt teammates', 'TEAM_LEAD_REQUIRED') + const state = this.journal.state(membership.root) + const target = resolveActiveMember(membership.root, state, targetName) + if (target.id === membership.root.id) throw new TeamError('the Team Lead cannot interrupt itself', 'TEAM_INVALID_TARGET') + const live = this.ctx.agents.get(target.id) + if (live === undefined) return { previousStatus: 'inactive' } + const previousStatus = live.status + this.ctx.subagents.interrupt(target.id, { kind: 'ancestor', agent: caller }) + return { previousStatus } + } + + /** + * Group exact live roster children by their current Lead for runtime teardown. + * @returns each live Lead and the roster child ids currently in the Agent registry. + */ + liveChildrenByRoot(): Map { + const teams = new Map() + for (const agent of this.ctx.agents.list()) { + const rootId = agent.session.header.parentSession + if (rootId === undefined) continue + const root = this.ctx.agents.get(rootId) + if (root === undefined || !this.journal.state(root).members.has(agent.id)) continue + const children = teams.get(root) ?? [] + children.push(agent.id) + teams.set(root, children) + } + return teams + } + + /** + * Release exact teammate Activations through the continuation lifecycle owner. + * @param root - exact live Team Lead authorizing release. + * @param childIds - selected roster child ids. + */ + async stopTeammates(root: Agent, childIds: readonly SessionId[]): Promise { + await this.lifecycle.withTimeout(this.ctx.subagents.drainContinuableChildren(root, childIds)) + } + + /** Perform one creation admitted before the Team runtime disposal cutoff. */ + private async spawnAdmitted( + caller: Agent, + request: SpawnTeammateRequest, + ): Promise { + const membership = this.membership(caller) + if (membership.role !== 'lead') { + throw new TeamError('only the Team Lead can create teammates', 'TEAM_LEAD_REQUIRED') + } + const signal = AbortSignal.any([request.signal, this.lifecycle.signal]) + signal.throwIfAborted() + const root = membership.root + const name = this.memberName(request.name) + const description = requiredText(request.description, 'description', 200) + const childId = SessionId(randomUUID()) + const member: TeamMemberSnapshot = { + id: childId, + name, + description, + provider: requiredText(request.provider, 'provider', 200), + context: request.context, + phase: 'provisioning', + } + + await this.journal.transact(root.id, async () => { + const state = this.journal.state(root) + if (state.memberIdsByName.has(name)) { + throw new TeamError(`teammate name "${name}" was already used in this Team`, 'TEAM_MEMBER_NAME_TAKEN') + } + if (state.members.size >= this.maxMembers) { + throw new TeamError(`Team member limit ${this.maxMembers} reached`, 'TEAM_MEMBER_LIMIT') + } + await this.journal.appendAndFlush(root, 'team/member', { version: 1, teamId: TeamId(root.id), member }) + }) + + let started: ContinuableStart + try { + started = await this.ctx.subagents.startContinuable({ + childId, + provider: request.provider, + label: description, + request: { + prompt: request.prompt, + parent: root, + }, + signal, + }) + await this.checkpointInitialPrompt(childId, started.messageId, signal) + } catch (error: unknown) { + const failed: TeamMemberSnapshot = { + ...member, + phase: 'failed', + error: errorMessage(error), + } + try { + const phase = await this.settleProvisioning(root, failed) + await this.stopTeammates(root, [childId]) + if (phase === 'active') { + throw new TeamError( + `teammate "${name}" became active while its creator reported failure`, + 'TEAM_PROVISIONING_CONFLICT', + { cause: error }, + ) + } + } catch (recordError: unknown) { + throw new AggregateError([error, recordError], 'teammate creation and durable failure recording both failed') + } + throw error + } + const active = { + ...member, + phase: 'active' as const, + } satisfies TeamMemberSnapshot + // Once the continuation accepted its first prompt, it is a real child. If + // this checkpoint fails, keep the in-memory active edge instead of inventing + // an impossible active -> failed transition; restart reconciliation covers + // the provisioning-only durable prefix. + const settledPhase = await this.settleProvisioning(root, active) + if (settledPhase === 'failed') { + const conflict = new TeamError( + `teammate "${name}" was reconciled as failed while creation was in progress`, + 'TEAM_PROVISIONING_CONFLICT', + ) + try { + await this.stopTeammates(root, [childId]) + } catch (cleanupError: unknown) { + /* v8 ignore next -- requires the independently tested HMR settlement conflict and cleanup failure together. */ + throw new AggregateError([conflict, cleanupError], 'provisioning conflict cleanup failed') + } + throw conflict + } + return { member: this.memberView(active) } + } + + /** Flush the accepted initial inbox item before the Lead can commit `active`. */ + private async checkpointInitialPrompt( + childId: SessionId, + messageId: MessageId, + signal: AbortSignal, + ): Promise { + while (true) { + signal.throwIfAborted() + const session = this.ctx.sessions.get(childId) + if (session === undefined) { + const stored = await this.ctx.sessionPersistence.inspect(childId, signal) + const suffix = stored.events.slice(stored.meta.seedLength ?? 0) + if (messageAccepted(suffix, message => message.id === messageId)) return + throw new TeamError( + `teammate "${childId}" initial prompt was not durably accepted`, + 'TEAM_PROVISIONING_CONFLICT', + ) + } + + const progress = Promise.withResolvers() + // Abort can win while the durability flush is still pending; mark the + // later-awaited rejection handled without changing its eventual result. + void progress.promise.catch(() => undefined) + const stopEvent = this.ctx.on('session/event', (candidate) => { + if (candidate === session) progress.resolve() + }) + const stopDisposed = this.ctx.on('session/disposed', (candidate) => { + if (candidate === session) progress.resolve() + }) + const onAbort = (): void => { + const reason: unknown = signal.reason + progress.reject(reason instanceof Error + ? reason + : new TeamError(`teammate creation aborted: ${errorMessage(reason)}`, 'TEAM_DISPOSED')) + } + signal.addEventListener('abort', onAbort, { once: true }) + try { + signal.throwIfAborted() + await this.ctx.sessions.flush(session) + const suffix = session.events.slice(session.header.seedLength ?? 0) + if (messageAccepted(suffix, message => message.id === messageId)) return + if (this.ctx.sessions.get(childId) !== session) continue + await progress.promise + } finally { + signal.removeEventListener('abort', onAbort) + stopDisposed() + stopEvent() + } + } + } + + /** Settle provisioning-only members from their independently durable child Sessions. */ + private async reconcileProvisioning(root: Agent, signal: AbortSignal): Promise { + const provisioning = [...this.journal.state(root).members.values()].filter(member => member.phase === 'provisioning') + for (const member of provisioning) { + signal.throwIfAborted() + // A live child means creation is still completing in this process. Its + // creator owns the terminal member edge. + if (this.ctx.agents.get(member.id) !== undefined) continue + let phase: 'active' | 'failed' = 'failed' + let failure = 'provisioning did not leave a resumable child Session' + try { + const loaded = await this.ctx.sessionPersistence.inspect(member.id, signal) + const suffix = loaded.events.slice(loaded.meta.seedLength ?? 0) + const descriptor = foldSubagentDescriptor(suffix) + const acceptedInitialPrompt = messageAccepted(suffix, message => message.source.kind === 'user') + if (loaded.meta.parentSession === root.id + && descriptor?.mode === 'continuable' + && descriptor.provider === member.provider + && acceptedInitialPrompt) { + phase = 'active' + } else { + failure = 'persisted child Session does not match the provisioned continuation' + } + } catch (error: unknown) { + failure = `child Session recovery failed: ${errorMessage(error)}` + } + signal.throwIfAborted() + await this.journal.transact(root.id, async () => { + signal.throwIfAborted() + const current = this.journal.state(root).members.get(member.id) + if (current?.phase !== 'provisioning') return + const settled: TeamMemberSnapshot = { + ...current, + phase, + ...phase === 'failed' ? { error: failure } : {}, + } + await this.journal.appendAndFlush(root, 'team/member', { + version: 1, + teamId: TeamId(root.id), + member: settled, + }) + }) + } + } + + /** Build one runtime member row after successful creation. */ + private memberView(member: TeamMemberSnapshot & { readonly phase: 'active' }): TeamMemberView { + const live = this.ctx.agents.get(member.id) + return { + id: member.id, + name: member.name, + role: 'teammate', + status: live?.status ?? 'inactive', + description: member.description, + provider: member.provider, + context: member.context, + ...live?.options.model === undefined ? {} : { model: live.options.model }, + diagnostics: [], + } + } + + /** Validate a never-reused model-facing teammate name. */ + private memberName(value: string): string { + if (!MEMBER_NAME.test(value) || value.length > 64 || value === 'lead') { + throw new TeamError( + 'teammate name must be lower-kebab-case, at most 64 characters, and not "lead"', + 'TEAM_INVALID_MEMBER_NAME', + ) + } + return value + } + + /** Append one terminal provisioning edge unless recovery already settled it. */ + private async settleProvisioning( + root: Agent, + terminal: TeamMemberSnapshot, + ): Promise<'active' | 'failed'> { + return this.journal.transact(root.id, async () => { + const current = this.journal.state(root).members.get(terminal.id) + /* v8 ignore next 3 -- the append-only provisioning event is committed by this operation before settlement. */ + if (current === undefined) { + throw new TeamError(`provisioned teammate "${terminal.id}" disappeared`, 'TEAM_PROVISIONING_CONFLICT') + } + if (current.phase !== 'provisioning') return current.phase + await this.journal.appendAndFlush(root, 'team/member', { + version: 1, + teamId: TeamId(root.id), + member: terminal, + }) + return terminal.phase === 'active' ? 'active' : 'failed' + }) + } + + /** Whether a Session's own suffix identifies a provider-owned subagent child. */ + private subagentDescriptor(agent: Agent): boolean { + return foldSubagentDescriptor(agent.session.events.slice(agent.session.header.seedLength ?? 0)) !== undefined + } +} diff --git a/packages/experimental/team/src/session-message.ts b/packages/experimental/team/src/session-message.ts new file mode 100644 index 0000000000..1942c37352 --- /dev/null +++ b/packages/experimental/team/src/session-message.ts @@ -0,0 +1,31 @@ +/** Durable Session-message acceptance checks shared by provisioning and mailbox recovery. */ + +import type { UserMessage } from '@deepseek-ai/dsh-llm' +import type { SessionEvent } from '@deepseek-ai/dsh-session' + +type InboxProjection = Record<'next-turn' | 'next-step', UserMessage[]> + +/** Fold the durable inbox suffix into the messages still awaiting a claim. */ +function pendingInboxMessages(events: readonly SessionEvent[]): UserMessage[] { + const inbox: InboxProjection = { 'next-turn': [], 'next-step': [] } + for (const event of events) { + if (event.type !== 'agent/inbox/spliced') continue + const pending = inbox[event.data.target] + pending.splice(event.data.start, event.data.removedCount ?? 0, ...event.data.inserted) + } + return [...inbox['next-turn'], ...inbox['next-step']] +} + +/** + * Test whether one message is model-visible or still durably pending. + * @param events - one Session's non-inherited event suffix. + * @param predicate - identity check for the accepted message. + * @returns whether history or the current inbox contains a match. + */ +export function messageAccepted( + events: readonly SessionEvent[], + predicate: (message: UserMessage) => boolean, +): boolean { + return events.some(event => event.type === 'user/message' && predicate(event.data)) + || pendingInboxMessages(events).some(predicate) +} diff --git a/packages/experimental/team/src/task-board.ts b/packages/experimental/team/src/task-board.ts new file mode 100644 index 0000000000..f987dd9217 --- /dev/null +++ b/packages/experimental/team/src/task-board.ts @@ -0,0 +1,297 @@ +/** Shared Team task DAG commands and runtime-enriched views. */ + +import type { Agent } from '@deepseek-ai/dsh-agent' +import type { TeamMembership } from './roster.ts' +import { TeamError } from './error.ts' +import type { TeamFoldState } from './fold.ts' +import type { TeamJournal } from './journal.ts' +import { resolveActiveMember } from './roster.ts' +import { assertTaskGraphCandidate, TeamTaskGraphError } from './task-graph.ts' +import type { TeamTaskGraphViolation } from './task-graph.ts' +import { TeamId, TeamTaskId } from './types.ts' +import type { + CreateTeamTaskRequest, + TeamTaskSnapshot, + TeamTaskView, + UpdateTeamTaskRequest, +} from './types.ts' +import { requiredText, writeScope } from './validation.ts' + +/** Whether two normalized file or directory prefixes overlap on path components. */ +function scopesOverlap(left: string, right: string): boolean { + return left === right || left.startsWith(`${right}/`) || right.startsWith(`${left}/`) +} + +const TASK_GRAPH_ERROR_CODES: Record = { + missing: 'TEAM_TASK_NOT_FOUND', + duplicate: 'TEAM_INVALID_ARGUMENT', + cycle: 'TEAM_TASK_DEPENDENCY_CYCLE', +} + +/** Owns Team task limits, authorization, transitions, and derived views. */ +export class TeamTaskBoard { + /** + * @param journal - authoritative Lead-log transaction owner. + * @param maxTasks - maximum non-deleted tasks retained by one Team. + */ + constructor( + private readonly journal: TeamJournal, + private readonly maxTasks: number, + ) {} + + /** + * Create one unowned pending task in the Team Lead log. + * @param membership - exact caller membership resolved by the Team roster. + * @param request - task text, blockers, and advisory write scopes. + * @returns the revision-one task view. + */ + async create(membership: TeamMembership, request: CreateTeamTaskRequest): Promise { + const { root } = membership + return this.journal.transact(root.id, async () => { + const state = this.journal.state(root) + const active = [...state.tasks.values()].filter(task => task.status !== 'deleted').length + if (active >= this.maxTasks) { + throw new TeamError(`Team task limit ${this.maxTasks} reached`, 'TEAM_TASK_LIMIT') + } + const id = TeamTaskId(`task-${state.nextTaskNumber}`) + if (state.tasks.has(id)) { + throw new TeamError('Team task id space exhausted', 'TEAM_TASK_LIMIT') + } + const task: TeamTaskSnapshot = { + id, + revision: 1, + subject: requiredText(request.subject, 'subject', 200), + description: requiredText(request.description, 'description', 16_384), + status: 'pending', + blockedBy: this.dependencies(request.blockedBy ?? [], state), + writeScopes: this.writeScopes(request.writeScopes ?? []), + } + this.assertTaskGraph(state, task) + await this.journal.appendAndFlush(root, 'team/task', { version: 1, teamId: TeamId(root.id), task }) + return this.taskView(root, state, task) + }) + } + + /** + * Return one task, including a deleted tombstone. + * @param membership - exact caller membership resolved by the Team roster. + * @param id - Team-local task identity. + * @returns the latest task value and derived readiness diagnostics. + */ + get(membership: TeamMembership, id: TeamTaskId): TeamTaskView { + const { root } = membership + const state = this.journal.state(root) + const task = state.tasks.get(id) + if (task === undefined) throw new TeamError(`team task "${id}" not found`, 'TEAM_TASK_NOT_FOUND') + return this.taskView(root, state, task) + } + + /** + * List current non-deleted tasks in numeric creation order. + * @param membership - exact caller membership resolved by the Team roster. + * @returns detached current task views. + */ + list(membership: TeamMembership): TeamTaskView[] { + const { root } = membership + const state = this.journal.state(root) + return [...state.tasks.values()] + .filter(task => task.status !== 'deleted') + .map(task => this.taskView(root, state, task)) + } + + /** + * Compare-and-set one authorized task transition. + * @param caller - exact live Team member authorizing the mutation. + * @param membership - caller role and exact live Lead. + * @param request - task identity, expected revision, action, and action fields. + * @returns the committed next task revision. + */ + async update( + caller: Agent, + membership: TeamMembership, + request: UpdateTeamTaskRequest, + ): Promise { + const root = membership.root + return this.journal.transact(root.id, async () => { + const state = this.journal.state(root) + const current = state.tasks.get(request.taskId) + if (current === undefined) throw new TeamError(`team task "${request.taskId}" not found`, 'TEAM_TASK_NOT_FOUND') + if (current.revision !== request.expectedRevision) { + throw new TeamError( + `stale team task "${current.id}" revision ${request.expectedRevision}; current revision is ${current.revision}`, + 'TEAM_TASK_STALE_REVISION', + ) + } + if (current.status === 'deleted') throw new TeamError(`team task "${current.id}" is deleted`, 'TEAM_TASK_DELETED') + const lead = membership.role === 'lead' + const owner = current.ownerId === caller.id + const authorizeOwner = (): void => { + if (!lead && !owner) throw new TeamError('task mutation requires its owner or Team Lead', 'TEAM_TASK_UNAUTHORIZED') + } + let next: TeamTaskSnapshot + switch (request.action) { + case 'claim': + if (current.ownerId !== undefined && current.ownerId !== caller.id) { + throw new TeamError(`team task "${current.id}" is owned by another member`, 'TEAM_TASK_ALREADY_CLAIMED') + } + if (current.status !== 'pending' || !this.taskReady(state, current)) { + throw new TeamError(`team task "${current.id}" is not ready to claim`, 'TEAM_TASK_BLOCKED') + } + next = { ...current, status: 'in_progress', ownerId: caller.id } + break + case 'release': + authorizeOwner() + if (current.status !== 'in_progress') throw new TeamError('only an in-progress task can be released', 'TEAM_TASK_INVALID_TRANSITION') + next = this.withoutOwner({ ...current, status: 'pending' }) + break + case 'edit': + authorizeOwner() + if (request.subject === undefined && request.description === undefined && request.writeScopes === undefined) { + throw new TeamError('task edit requires subject, description, or write_scopes', 'TEAM_INVALID_ARGUMENT') + } + next = { + ...current, + ...request.subject === undefined ? {} : { subject: requiredText(request.subject, 'subject', 200) }, + ...request.description === undefined + ? {} + : { description: requiredText(request.description, 'description', 16_384) }, + ...request.writeScopes === undefined ? {} : { writeScopes: this.writeScopes(request.writeScopes) }, + } + break + case 'set_dependencies': + authorizeOwner() + if (request.blockedBy === undefined) throw new TeamError('set_dependencies requires blocked_by', 'TEAM_INVALID_ARGUMENT') + next = { ...current, blockedBy: this.dependencies(request.blockedBy, state, current.id) } + break + case 'complete': + authorizeOwner() + if (current.status !== 'in_progress') throw new TeamError('only an in-progress task can complete', 'TEAM_TASK_INVALID_TRANSITION') + next = { ...current, status: 'completed' } + break + case 'reopen': + authorizeOwner() + if (current.status !== 'completed') throw new TeamError('only a completed task can reopen', 'TEAM_TASK_INVALID_TRANSITION') + next = this.withoutOwner({ ...current, status: 'pending' }) + break + case 'reassign': { + if (!lead) throw new TeamError('only the Team Lead can reassign tasks', 'TEAM_LEAD_REQUIRED') + if (current.status !== 'pending' && current.status !== 'in_progress') { + throw new TeamError( + 'only a pending or in-progress task can be reassigned', + 'TEAM_TASK_INVALID_TRANSITION', + ) + } + if (request.owner === undefined || request.owner.trim().length === 0) { + next = this.withoutOwner({ ...current, status: 'pending' }) + break + } + if (!this.taskReady(state, current)) throw new TeamError(`team task "${current.id}" is blocked`, 'TEAM_TASK_BLOCKED') + const assignee = resolveActiveMember(root, state, request.owner) + next = { ...current, status: 'in_progress', ownerId: assignee.id } + break + } + case 'delete': { + authorizeOwner() + const dependent = [...state.tasks.values()].find(task => + task.status !== 'deleted' && task.id !== current.id && task.blockedBy.includes(current.id)) + if (dependent !== undefined) { + throw new TeamError(`team task "${current.id}" still blocks "${dependent.id}"`, 'TEAM_TASK_HAS_DEPENDENTS') + } + next = { ...current, status: 'deleted' } + break + } + /* v8 ignore next 2 -- TeamTaskAction is closed and every member is handled above. */ + default: + throw new TeamError(`unsupported task action ${String(request.action)}`, 'TEAM_INVALID_ARGUMENT') + } + const task: TeamTaskSnapshot = { + ...next, + revision: current.revision + 1, + } + this.assertTaskGraph(state, task) + await this.journal.appendAndFlush(root, 'team/task', { version: 1, teamId: TeamId(root.id), task }) + return this.taskView(root, state, task) + }) + } + + /** Validate and de-duplicate dependency ids against the current task graph. */ + private dependencies( + values: readonly TeamTaskId[], + state: TeamFoldState, + self?: TeamTaskId, + ): TeamTaskId[] { + const seen = new Set() + const result: TeamTaskId[] = [] + for (const id of values) { + if (id === self) throw new TeamError('a team task cannot block itself', 'TEAM_TASK_DEPENDENCY_CYCLE') + if (seen.has(id)) throw new TeamError(`duplicate blocker "${id}"`, 'TEAM_INVALID_ARGUMENT') + const task = state.tasks.get(id) + if (task === undefined || task.status === 'deleted') { + throw new TeamError(`blocker task "${id}" not found`, 'TEAM_TASK_NOT_FOUND') + } + seen.add(id) + result.push(id) + } + return result + } + + /** Normalize and de-duplicate task write scopes. */ + private writeScopes(values: readonly string[]): string[] { + return [...new Set(values.map(writeScope))] + } + + /** Map shared task-graph validation onto stable command error codes. */ + private assertTaskGraph(state: TeamFoldState, candidate: TeamTaskSnapshot): void { + try { + assertTaskGraphCandidate(state.tasks, candidate) + } catch (error: unknown) { + /* v8 ignore next -- the shared validator is the only statement in the try and throws this exact error. */ + if (!(error instanceof TeamTaskGraphError)) throw error + throw new TeamError(error.message, TASK_GRAPH_ERROR_CODES[error.violation], { cause: error }) + } + } + + /** Whether all current blockers completed. */ + private taskReady(state: TeamFoldState, task: TeamTaskSnapshot): boolean { + return task.blockedBy.every(id => state.tasks.get(id)?.status === 'completed') + } + + /** Remove an optional owner field under exactOptionalPropertyTypes. */ + private withoutOwner(task: TeamTaskSnapshot): TeamTaskSnapshot { + const { ownerId: _ownerId, ...without } = task + return without + } + + /** + * Build one task view with owner name, readiness, and advisory write overlaps. + * A committing caller may pass its pre-append fold because `task` supplies the + * new value explicitly; owner names, blocker readiness, and other task scopes + * do not change when that snapshot is appended. + */ + private taskView(root: Agent, state: TeamFoldState, task: TeamTaskSnapshot): TeamTaskView { + const ownerName = task.ownerId === undefined + ? undefined + : task.ownerId === root.id + ? 'lead' + : state.members.get(task.ownerId)?.name + const warnings = new Set() + for (const other of state.tasks.values()) { + if (other.id === task.id || other.status !== 'in_progress') continue + if (task.writeScopes.some(left => other.writeScopes.some(right => scopesOverlap(left, right)))) { + warnings.add(`write scopes overlap with ${other.id}`) + } + } + return { + id: task.id, + revision: task.revision, + subject: task.subject, + description: task.description, + status: task.status, + blockedBy: structuredClone(task.blockedBy), + writeScopes: structuredClone(task.writeScopes), + ...ownerName === undefined ? {} : { ownerName }, + ready: task.status === 'pending' && this.taskReady(state, task), + writeScopeWarnings: [...warnings], + } + } +} diff --git a/packages/experimental/team/src/task-graph.ts b/packages/experimental/team/src/task-graph.ts new file mode 100644 index 0000000000..38d9dd144c --- /dev/null +++ b/packages/experimental/team/src/task-graph.ts @@ -0,0 +1,69 @@ +/** Complete dependency validation for current Team task snapshots. */ + +import type { TeamTaskId, TeamTaskSnapshot } from './types.ts' + +/** Task dependency relation rejected by the shared graph validator. */ +export type TeamTaskGraphViolation = 'missing' | 'duplicate' | 'cycle' + +/** Package-private task dependency failure retained for command error mapping. */ +export class TeamTaskGraphError extends Error { + /** + * @param message - concrete invalid dependency relation. + * @param violation - stable relation category used by Team commands. + */ + constructor(message: string, readonly violation: TeamTaskGraphViolation) { + super(message) + this.name = 'TeamTaskGraphError' + } +} + +/** + * Validate the complete active task graph after replacing one candidate snapshot. + * @param current - current task snapshots before the candidate event. + * @param candidate - new or next-revision task snapshot. + * @throws {TeamTaskGraphError} when an active dependency is missing, duplicated, self-referential, or cyclic. + */ +export function assertTaskGraphCandidate( + current: ReadonlyMap, + candidate: TeamTaskSnapshot, +): void { + const tasks = new Map(current) + tasks.set(candidate.id, candidate) + + for (const task of tasks.values()) { + if (task.status === 'deleted') continue + const seen = new Set() + for (const blockerId of task.blockedBy) { + if (blockerId === task.id) { + throw new TeamTaskGraphError(`team task "${task.id}" cannot block itself`, 'cycle') + } + if (seen.has(blockerId)) { + throw new TeamTaskGraphError(`team task "${task.id}" repeats blocker "${blockerId}"`, 'duplicate') + } + const blocker = tasks.get(blockerId) + if (blocker === undefined || blocker.status === 'deleted') { + throw new TeamTaskGraphError( + `blocker task "${blockerId}" for "${task.id}" is missing or deleted`, + 'missing', + ) + } + seen.add(blockerId) + } + } + + const visiting = new Set() + const visited = new Set() + const visit = (id: TeamTaskId): void => { + if (visiting.has(id)) { + throw new TeamTaskGraphError(`task dependency cycle includes "${id}"`, 'cycle') + } + if (visited.has(id)) return + const task = tasks.get(id) + if (task === undefined || task.status === 'deleted') return + visiting.add(id) + for (const blockerId of task.blockedBy) visit(blockerId) + visiting.delete(id) + visited.add(id) + } + for (const task of tasks.values()) visit(task.id) +} diff --git a/packages/experimental/team/src/types.ts b/packages/experimental/team/src/types.ts new file mode 100644 index 0000000000..cee2b1064a --- /dev/null +++ b/packages/experimental/team/src/types.ts @@ -0,0 +1,219 @@ +/** Public Agent Teams identities, durable records, and service request values. */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import type { SessionId } from '@deepseek-ai/dsh-session' + +/** Identifies the implicit team rooted at one top-level Session. */ +export type TeamId = Branded<'TeamId'> + +/** + * Brand one root Session identity as its implicit Team identity. + * @param id - Root Session identity. + * @returns the same string branded as a Team identity. + */ +export function TeamId(id: SessionId | string): TeamId { + return id as TeamId +} + +/** Stable identifier for one task in a Team. */ +export type TeamTaskId = Branded<'TeamTaskId'> + +/** + * Brand a validated task id. + * @param id - Team-local task identity. + * @returns the same string branded as a Team task identity. + */ +export function TeamTaskId(id: string): TeamTaskId { + return id as TeamTaskId +} + +/** Stable identifier for one durable peer message. */ +export type TeamMessageId = Branded<'TeamMessageId'> + +/** + * Brand a generated peer-message id. + * @param id - Durable mailbox message identity. + * @returns the same string branded as a Team message identity. + */ +export function TeamMessageId(id: string): TeamMessageId { + return id as TeamMessageId +} + +/** Durable teammate lifecycle. */ +export type TeamMemberPhase = 'provisioning' | 'active' | 'failed' + +/** Whole durable value written on every teammate lifecycle change. */ +export interface TeamMemberSnapshot { + readonly id: SessionId + readonly name: string + readonly description: string + readonly provider: string + readonly context: 'fresh' | 'fork' + readonly phase: TeamMemberPhase + readonly error?: string +} + +/** Current runtime-enriched roster row. */ +export interface TeamMemberView { + readonly id: SessionId + readonly name: string + readonly role: 'lead' | 'teammate' + readonly status: 'running' | 'idle' | 'inactive' | 'provisioning' | 'failed' + readonly description?: string + readonly provider?: string + readonly context?: 'fresh' | 'fork' + readonly model?: string + readonly diagnostics: string[] +} + +/** Durable task lifecycle. */ +export type TeamTaskStatus = 'pending' | 'in_progress' | 'completed' | 'deleted' + +/** Whole durable task snapshot; every mutation increments {@link revision}. */ +export interface TeamTaskSnapshot { + readonly id: TeamTaskId + readonly revision: number + readonly subject: string + readonly description: string + readonly status: TeamTaskStatus + readonly ownerId?: SessionId + readonly blockedBy: TeamTaskId[] + readonly writeScopes: string[] +} + +/** Runtime-enriched task view returned to tools and hosts. */ +export interface TeamTaskView { + readonly id: TeamTaskId + readonly revision: number + readonly subject: string + readonly description: string + readonly status: TeamTaskStatus + readonly blockedBy: TeamTaskId[] + readonly writeScopes: string[] + readonly ownerName?: string + readonly ready: boolean + readonly writeScopeWarnings: string[] +} + +/** One peer message retained until its target Session records it. */ +export interface TeamMessageSnapshot { + readonly id: TeamMessageId + readonly senderId: SessionId + readonly senderName: string + readonly targetId: SessionId + readonly delivery: 'quiet' | 'wakeup' + readonly content: ContentBlock[] +} + +/** Source retained by the target Session for durable mailbox de-duplication. */ +export interface TeamMessageSource { + readonly kind: 'team-message' + readonly teamId: TeamId + readonly messageId: TeamMessageId + readonly senderId: SessionId + readonly senderName: string +} + +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + 'team-message': TeamMessageSource + } +} + +/** Team-service deployment limits. */ +export interface Config { + /** Maximum immutable teammate names retained by one Team. */ + readonly maxMembers?: number + /** Maximum non-deleted tasks retained by one Team. */ + readonly maxTasks?: number + /** Maximum queued-minus-delivered messages for one target member. */ + readonly maxPendingMessagesPerMember?: number + /** Maximum UTF-8 bytes in one complete sender-framed delivery. */ + readonly maxMessageBytes?: number + /** Maximum milliseconds allowed for Team-owned runtime disposal. */ + readonly disposalTimeoutMs?: number +} + +/** Input for creating one durable teammate. */ +export interface SpawnTeammateRequest { + readonly name: string + readonly description: string + readonly prompt: ContentBlock[] + readonly context: 'fresh' | 'fork' + readonly provider: string + readonly signal: AbortSignal +} + +/** Result after one teammate reaches a durable active or failed edge. */ +export interface SpawnTeammateResult { + readonly member: TeamMemberView +} + +/** Input for one durable peer message. */ +export interface SendTeamMessageRequest { + readonly target: string + readonly content: ContentBlock[] + readonly delivery: 'quiet' | 'wakeup' + readonly signal: AbortSignal +} + +/** Result after a peer message enters the durable mailbox. */ +export interface SendTeamMessageResult { + readonly messageId: TeamMessageId + readonly status: 'accepted' | 'queued' +} + +/** Input for creating one shared task. */ +export interface CreateTeamTaskRequest { + readonly subject: string + readonly description: string + readonly blockedBy?: readonly TeamTaskId[] + readonly writeScopes?: readonly string[] +} + +/** Supported task mutation actions. */ +export type TeamTaskAction = + | 'claim' + | 'release' + | 'edit' + | 'set_dependencies' + | 'complete' + | 'reopen' + | 'reassign' + | 'delete' + +/** Compare-and-set mutation of one shared task. */ +export interface UpdateTeamTaskRequest { + readonly taskId: TeamTaskId + readonly expectedRevision: number + readonly action: TeamTaskAction + readonly subject?: string + readonly description?: string + readonly blockedBy?: readonly TeamTaskId[] + readonly writeScopes?: readonly string[] + readonly owner?: string +} + +/** Result of waiting for Team activity. */ +export interface TeamWaitResult { + readonly timedOut: boolean +} + +declare module '@deepseek-ai/dsh-session/types' { + interface SessionEventMap { + /** Whole teammate lifecycle value, stored only in the Team Lead Session. */ + 'team/member': { version: 1; teamId: TeamId; member: TeamMemberSnapshot } + /** Whole shared-task value, stored only in the Team Lead Session. */ + 'team/task': { version: 1; teamId: TeamId; task: TeamTaskSnapshot } + /** Durable mailbox enqueue, stored before delivery is attempted. */ + 'team/message/queued': { version: 1; teamId: TeamId; message: TeamMessageSnapshot } + /** Durable acknowledgement that the target Session recorded the message. */ + 'team/message/delivered': { + version: 1 + teamId: TeamId + messageId: TeamMessageId + targetId: SessionId + } + } +} diff --git a/packages/experimental/team/src/validation.ts b/packages/experimental/team/src/validation.ts new file mode 100644 index 0000000000..01de64f57c --- /dev/null +++ b/packages/experimental/team/src/validation.ts @@ -0,0 +1,34 @@ +/** Input normalization shared by Team roster and task commands. */ + +import { TeamError } from './error.ts' + +/** + * Normalize one required human-authored string. + * @param value - raw input value. + * @param field - diagnostic field name. + * @param maxLength - maximum normalized character count. + * @returns trimmed non-empty text. + */ +export function requiredText(value: string, field: string, maxLength: number): string { + const text = value.trim() + if (text.length === 0) throw new TeamError(`${field} must be non-empty`, 'TEAM_INVALID_ARGUMENT') + if (text.length > maxLength) { + throw new TeamError(`${field} exceeds ${maxLength} characters`, 'TEAM_INVALID_ARGUMENT') + } + return text +} + +/** + * Normalize one workspace-relative path prefix without treating it as a lock. + * @param value - user-authored path prefix. + * @returns normalized slash-separated prefix. + */ +export function writeScope(value: string): string { + const normalized = value.replaceAll('\\', '/').replace(/^\.\//u, '').replace(/\/+$/u, '') + const segments = normalized.split('/') + if (normalized.length === 0 || normalized.startsWith('/') || /^[a-z]:/iu.test(normalized) + || segments.some(segment => segment.length === 0 || segment === '.' || segment === '..')) { + throw new TeamError(`invalid workspace-relative write scope ${JSON.stringify(value)}`, 'TEAM_INVALID_WRITE_SCOPE') + } + return normalized +} diff --git a/packages/experimental/team/tests/fold.spec.ts b/packages/experimental/team/tests/fold.spec.ts new file mode 100644 index 0000000000..d1ed095a99 --- /dev/null +++ b/packages/experimental/team/tests/fold.spec.ts @@ -0,0 +1,325 @@ +import { describe, expect, it } from 'vitest' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionEventMap, SessionEventType } from '@deepseek-ai/dsh-session' +import { + applyTeamEvent, + emptyTeamFoldState, + foldTeam, + isTeamEvent, +} from '../src/fold.ts' +import type { TeamFoldState } from '../src/fold.ts' +import { TeamId, TeamMessageId, TeamTaskId } from '../src/types.ts' +import type { TeamMemberSnapshot, TeamMessageSnapshot, TeamTaskSnapshot } from '../src/types.ts' + +const ROOT = SessionId('team-root') +const TEAM = TeamId(ROOT) +const CHILD = SessionId('child-a') + +function event(type: T, data: SessionEventMap[T], seq: number): SessionEvent { + return { type, data, seq, time: seq } as SessionEvent +} + +/** Queued-minus-delivered mail, the recovery mailbox the fold is responsible for. */ +function pending(state: TeamFoldState): TeamMessageSnapshot[] { + return [...state.messages.values()].filter(message => !state.delivered.has(message.id)) +} + +/** Whether one fold reached the end of its log without applying any Team record. */ +function isEmptyFold(state: TeamFoldState): boolean { + return state.members.size === 0 && state.tasks.size === 0 + && state.messages.size === 0 && state.delivered.size === 0 +} + +function member(overrides: Partial = {}): TeamMemberSnapshot { + return { + id: CHILD, + name: 'worker-a', + description: 'worker', + provider: 'spawn', + context: 'fresh', + phase: 'provisioning', + ...overrides, + } +} + +function task(overrides: Partial = {}): TeamTaskSnapshot { + return { + id: TeamTaskId('task-1'), + revision: 1, + subject: 'subject', + description: 'description', + status: 'pending', + blockedBy: [], + writeScopes: [], + ...overrides, + } +} + +function message(overrides: Partial = {}): TeamMessageSnapshot { + return { + id: TeamMessageId('message-1'), + senderId: ROOT, + senderName: 'lead', + targetId: CHILD, + delivery: 'quiet', + content: [{ type: 'text', text: 'hello' }], + ...overrides, + } +} + +describe('Agent Teams fold', () => { + it('folds current-team records and ignores inherited records', () => { + const records: SessionEvent[] = [ + event('team/member', { version: 1, teamId: TeamId('ancestor'), member: member() }, 0), + event('team/member', { version: 1, teamId: TEAM, member: member() }, 1), + event('team/member', { + version: 1, + teamId: TEAM, + member: member({ phase: 'active' }), + }, 2), + event('team/task', { version: 1, teamId: TEAM, task: task({ id: TeamTaskId('task-7') }) }, 3), + event('team/message/queued', { version: 1, teamId: TEAM, message: message() }, 4), + ] + const state = foldTeam(ROOT, records) + + expect(state).toMatchObject({ id: TEAM }) + expect(state.members.size).toBe(1) + expect(state.tasks.size).toBe(1) + expect(pending(state)).toHaveLength(1) + expect(state.nextTaskNumber).toBe(8) + expect(state.members.get(CHILD)?.name).toBe('worker-a') + expect(isTeamEvent(records[0]!)).toBe(true) + expect(isTeamEvent(event('turn/start', { turn: 1 }, 5))).toBe(false) + }) + + it('enforces teammate identity and lifecycle', () => { + const base = event('team/member', { version: 1, teamId: TEAM, member: member() }, 0) + expect(() => foldTeam(ROOT, [event('team/member', { + version: 1, + teamId: TEAM, + member: member({ phase: 'active' }), + }, 0)])).toThrow(/must begin provisioning/) + expect(() => foldTeam(ROOT, [base, event('team/member', { + version: 1, + teamId: TEAM, + member: member({ name: 'renamed', phase: 'active' }), + }, 1)])).toThrow(/immutable identity/) + expect(() => foldTeam(ROOT, [base, event('team/member', { + version: 1, + teamId: TEAM, + member: member({ phase: 'active' }), + }, 1), event('team/member', { + version: 1, + teamId: TEAM, + member: member({ phase: 'failed' }), + }, 2)])).toThrow(/invalid active -> failed/) + + const duplicateName = member({ id: SessionId('child-b') }) + expect(() => foldTeam(ROOT, [base, event('team/member', { + version: 1, + teamId: TEAM, + member: duplicateName, + }, 1)])).toThrow(/name .* reused/) + }) + + it('enforces task revision continuity', () => { + const first = event('team/task', { version: 1, teamId: TEAM, task: task() }, 0) + expect(() => foldTeam(ROOT, [event('team/task', { + version: 1, + teamId: TEAM, + task: task({ revision: 2 }), + }, 0)])).toThrow(/begin at revision 1/) + expect(() => foldTeam(ROOT, [first, event('team/task', { + version: 1, + teamId: TEAM, + task: task({ revision: 3 }), + }, 1)])).toThrow(/revision is not contiguous/) + }) + + it('rejects every invalid persisted task dependency relation', () => { + const first = event('team/task', { version: 1, teamId: TEAM, task: task() }, 0) + const second = event('team/task', { + version: 1, + teamId: TEAM, + task: task({ + id: TeamTaskId('task-2'), + blockedBy: [TeamTaskId('task-1')], + }), + }, 1) + const invalid: Array<{ records: SessionEvent[]; message: RegExp }> = [ + { + records: [event('team/task', { + version: 1, + teamId: TEAM, + task: task({ blockedBy: [TeamTaskId('missing')] }), + }, 0)], + message: /blocker task "missing" .* is missing or deleted/, + }, + { + records: [event('team/task', { + version: 1, + teamId: TEAM, + task: task({ blockedBy: [TeamTaskId('task-1')] }), + }, 0)], + message: /cannot block itself/, + }, + { + records: [first, event('team/task', { + ...second.data, + task: { ...second.data.task, blockedBy: [TeamTaskId('task-1'), TeamTaskId('task-1')] }, + }, 1)], + message: /repeats blocker/, + }, + { + records: [first, second, event('team/task', { + version: 1, + teamId: TEAM, + task: task({ revision: 2, blockedBy: [TeamTaskId('task-2')] }), + }, 2)], + message: /dependency cycle/, + }, + { + records: [first, second, event('team/task', { + version: 1, + teamId: TEAM, + task: task({ revision: 2, status: 'deleted' }), + }, 2)], + message: /blocker task "task-1" .* is missing or deleted/, + }, + ] + + for (const { records, message: expected } of invalid) { + expect(() => foldTeam(ROOT, records)).toThrow(expected) + } + }) + + it('leaves numeric allocation unchanged for a branded nonstandard task id', () => { + const state = foldTeam(ROOT, [event('team/task', { + version: 1, + teamId: TEAM, + task: task({ id: TeamTaskId('external-task') }), + }, 0)]) + expect(state.nextTaskNumber).toBe(1) + }) + + it('rejects a persisted numeric task id outside the safe integer range', () => { + expect(() => foldTeam(ROOT, [event('team/task', { + version: 1, + teamId: TEAM, + task: task({ id: TeamTaskId('task-9007199254740992') }), + }, 0)])).toThrow(/persisted Agent Teams team\/task payload is invalid/) + }) + + it('enforces mailbox queue and acknowledgement relations', () => { + const queued = event('team/message/queued', { version: 1, teamId: TEAM, message: message() }, 0) + const delivered = event('team/message/delivered', { + version: 1, + teamId: TEAM, + messageId: TeamMessageId('message-1'), + targetId: CHILD, + }, 1) + expect(pending(foldTeam(ROOT, [queued, delivered]))).toEqual([]) + expect(() => foldTeam(ROOT, [queued, queued])).toThrow(/queued twice/) + expect(() => foldTeam(ROOT, [delivered])).toThrow(/delivered before queueing/) + expect(() => foldTeam(ROOT, [queued, event('team/message/delivered', { + ...delivered.data, + targetId: SessionId('other'), + }, 1)])).toThrow(/target changed/) + expect(() => foldTeam(ROOT, [queued, delivered, { ...delivered, seq: 2 }])).toThrow(/delivered twice/) + }) + + it('validates every current-version persisted payload before folding it', () => { + const malformed = [ + { + ...event('team/member', { version: 1, teamId: TEAM, member: member() }, 0), + data: { version: 1, teamId: TEAM, member: { ...member(), name: 42 } }, + }, + { + ...event('team/task', { version: 1, teamId: TEAM, task: task() }, 0), + data: { version: 1, teamId: TEAM, task: { ...task(), blockedBy: [42] } }, + }, + { + ...event('team/message/queued', { version: 1, teamId: TEAM, message: message() }, 0), + data: { + version: 1, + teamId: TEAM, + message: { ...message(), content: [{ type: 'text', text: 42 }] }, + }, + }, + { + ...event('team/message/delivered', { + version: 1, + teamId: TEAM, + messageId: TeamMessageId('message-1'), + targetId: CHILD, + }, 0), + data: { + version: 1, + teamId: TEAM, + messageId: TeamMessageId('message-1'), + targetId: 42, + }, + }, + { + ...event('team/member', { version: 1, teamId: TEAM, member: member() }, 0), + data: { version: 1, teamId: TEAM, member: member(), unexpected: true }, + }, + { + ...event('team/task', { version: 1, teamId: TEAM, task: task() }, 0), + data: { version: 1, teamId: 42, task: task() }, + }, + ] as unknown as SessionEvent[] + + for (const candidate of malformed) { + expect(() => foldTeam(ROOT, [candidate])) + .toThrow(/persisted Agent Teams .* payload is invalid/) + } + }) + + it('retains merge-extensible content blocks while rejecting malformed core variants', () => { + const extension = { type: 'plugin/custom', payload: { value: 1 } } as never + const state = foldTeam(ROOT, [event('team/message/queued', { + version: 1, + teamId: TEAM, + message: message({ content: [extension] }), + }, 0)]) + expect(pending(state)[0]?.content).toEqual([extension]) + }) + + it('rejects unsupported event versions without mutating an empty state', () => { + const state = emptyTeamFoldState(ROOT) + const invalid = event('team/task', { + version: 2 as 1, + teamId: TEAM, + task: task(), + }, 0) + expect(() => { applyTeamEvent(state, invalid) }).toThrow(/unsupported Agent Teams event version 2/) + expect(isEmptyFold(state)).toBe(true) + }) + + it('ignores unsupported inherited Team records before decoding their version', () => { + const inherited = event('team/task', { + version: 2 as 1, + teamId: TeamId('ancestor'), + task: task(), + }, 0) + expect(isEmptyFold(foldTeam(ROOT, [inherited]))).toBe(true) + }) + + it('still validates complete current-version records inherited from another Team', () => { + const inherited = { + ...event('team/task', { + version: 1, + teamId: TeamId('ancestor'), + task: task(), + }, 0), + data: { + version: 1, + teamId: TeamId('ancestor'), + task: { ...task(), subject: 42 }, + }, + } as unknown as SessionEvent + expect(() => foldTeam(ROOT, [inherited])) + .toThrow(/persisted Agent Teams team\/task payload is invalid/) + }) +}) diff --git a/packages/experimental/team/tests/invariant.spec.ts b/packages/experimental/team/tests/invariant.spec.ts new file mode 100644 index 0000000000..0bf994ecab --- /dev/null +++ b/packages/experimental/team/tests/invariant.spec.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import InvariantService, { InvariantError } from '@deepseek-ai/dsh-invariants' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import * as TeamInvariant from '../src/invariant.ts' +import { TeamId, TeamTaskId } from '../src/types.ts' + +async function setup(): Promise { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(InvariantService, { enabled: true }) + await ctx.plugin(TeamInvariant) + return ctx +} + +describe('Agent Teams stream invariant', () => { + it('accepts provisioning and rejects a terminal member as the first edge', async () => { + const ctx = await setup() + const session = ctx.sessions.create(SessionId('team-invariant')) + const member = { + id: SessionId('team-invariant-child'), + name: 'worker', + description: 'worker responsibility', + provider: 'spawn', + context: 'fresh' as const, + phase: 'provisioning' as const, + } + expect(() => { + session.append('team/member', { version: 1, teamId: TeamId(session.id), member }) + }).not.toThrow() + + const invalid = ctx.sessions.create(SessionId('team-invariant-invalid')) + expect(() => { + invalid.append('team/member', { + version: 1, + teamId: TeamId(invalid.id), + member: { ...member, phase: 'active' }, + }) + }).toThrow(expect.objectContaining>({ + code: 'INVARIANT', + packageName: '@deepseek-ai/dsh-team', + })) + expect(invalid.events).toEqual([]) + }) + + it('rejects an invalid task dependency before publication', async () => { + const ctx = await setup() + const session = ctx.sessions.create(SessionId('team-task-invariant')) + + expect(() => { + session.append('team/task', { + version: 1, + teamId: TeamId(session.id), + task: { + id: TeamTaskId('task-1'), + revision: 1, + subject: 'invalid dependency', + description: 'references a missing blocker', + status: 'pending', + blockedBy: [TeamTaskId('missing')], + writeScopes: [], + }, + }) + }).toThrow(expect.objectContaining>({ + code: 'INVARIANT', + packageName: '@deepseek-ai/dsh-team', + })) + expect(session.events).toEqual([]) + }) +}) diff --git a/packages/experimental/team/tests/persistence.spec.ts b/packages/experimental/team/tests/persistence.spec.ts new file mode 100644 index 0000000000..121a98445c --- /dev/null +++ b/packages/experimental/team/tests/persistence.spec.ts @@ -0,0 +1,485 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import SqliteSessionPersistence from '@deepseek-ai/dsh-session-persistence-sqlite' +import SubagentService, { seedDescriptorTurn, snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' +import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' +import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +import TeamService, { foldTeam, TeamId, TeamMessageId } from '../src/index.ts' +import type { TeamMemberSnapshot, TeamMessageSnapshot, TeamTaskSnapshot } from '../src/index.ts' + +const SIGNAL = new AbortController().signal +const PERSISTENCE_TEST_TIMEOUT_MS = 15_000 +const roots: string[] = [] +const contexts = new Set() + +/** Detached durable Team read: the service exposes views, so assertions fold the Lead log. */ +function durable(agent: Agent): { + members: TeamMemberSnapshot[] + tasks: TeamTaskSnapshot[] + pendingMessages: TeamMessageSnapshot[] +} { + const state = foldTeam(agent.id, agent.session.events) + return { + members: [...state.members.values()], + tasks: [...state.tasks.values()], + pendingMessages: [...state.messages.values()].filter(message => !state.delivered.has(message.id)), + } +} + +async function disposeContext(ctx: Context): Promise { + try { + await ctx.fiber.dispose() + } finally { + contexts.delete(ctx) + } +} + +afterEach(async () => { + const failures: unknown[] = [] + for (const ctx of [...contexts].reverse()) { + try { + await disposeContext(ctx) + } catch (error: unknown) { + failures.push(error) + } + } + for (const root of roots.splice(0)) { + try { + await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } catch (error: unknown) { + failures.push(error) + } + } + if (failures.length > 0) throw new AggregateError(failures, 'Agent Teams persistence test cleanup failed') +}) + +interface PersistenceMount { + readonly name: string + mount(ctx: Context, root: string): Promise<{ dispose(): Promise }> +} + +const backends: PersistenceMount[] = [ + { + name: 'JSONL', + mount: async (ctx, root) => await ctx.plugin(JsonlSessionPersistence, { + root: join(root, 'jsonl'), + compression: 'none', + }), + }, + { + name: 'SQLite', + mount: async (ctx, root) => await ctx.plugin(SqliteSessionPersistence, { + path: join(root, 'sessions.sqlite'), + journalMode: 'delete', + }), + }, +] + +async function stack( + backend: PersistenceMount, + root: string, + script: ConstructorParameters[0], +) { + const ctx = new Context() + contexts.add(ctx) + await mountAgentLoopTestDependencies(ctx) + await backend.mount(ctx, root) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(SubagentService) + await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) + await ctx.plugin(TeamService) + const adapter = new MockAdapter(script) + ctx.llm.registerAdapter(['mock'], adapter) + return { + ctx, + adapter, + dispose: async () => { await disposeContext(ctx) }, + } +} + +function provisioning(childId: SessionId, name: string): TeamMemberSnapshot { + return { + id: childId, + name, + description: `${name} recovery`, + provider: 'spawn', + context: 'fresh', + phase: 'provisioning', + } +} + +function persistedChild( + ctx: Context, + rootId: SessionId, + childId: SessionId, + message: ReturnType, +) { + const seed = seedDescriptorTurn(childId, undefined, snapshotSubagentDescriptor({ + mode: 'continuable', + provider: 'spawn', + label: 'persisted child fixture', + agentProvider: 'mock', + agentModel: 'mock', + })) + const child = ctx.sessions.create(childId, { + seed, + meta: { parentSession: rootId, seedLength: 0, origin: 'subagent' }, + }) + child.append('agent/inbox/spliced', { + target: 'next-turn', + start: 0, + inserted: [message], + }) + return child +} + +for (const backend of backends) { + describe(`${backend.name} Agent Teams recovery`, () => { + it('reconciles a persisted child to active and a missing child to durable failed', { + timeout: PERSISTENCE_TEST_TIMEOUT_MS, + }, async () => { + const storageRoot = mkdtempSync(join(tmpdir(), `dsh-team-${backend.name.toLowerCase()}-`)) + roots.push(storageRoot) + const first = await stack(backend, storageRoot, [textResponse('initial child answer')]) + const activeRootId = SessionId(`${backend.name.toLowerCase()}-active-root`) + const failedRootId = SessionId(`${backend.name.toLowerCase()}-failed-root`) + const childId = SessionId(`${backend.name.toLowerCase()}-child`) + const activeRoot = first.ctx.agentLoop.create(activeRootId, { provider: 'mock', model: 'mock' }) + const failedRoot = first.ctx.agentLoop.create(failedRootId, { provider: 'mock', model: 'mock' }) + // Let each root's startup recovery observe the empty initial log before + // simulating the crash-only provisioning prefix. + await Promise.resolve() + await Promise.resolve() + + activeRoot.session.append('team/member', { + version: 1, + teamId: TeamId(activeRoot.id), + member: provisioning(childId, 'recoverable'), + }) + failedRoot.session.append('team/member', { + version: 1, + teamId: TeamId(failedRoot.id), + member: provisioning(SessionId(`${backend.name}-missing`), 'missing'), + }) + await Promise.all([ + first.ctx.sessions.flush(activeRoot.session), + first.ctx.sessions.flush(failedRoot.session), + ]) + await first.ctx.subagents.startContinuable({ + childId, + provider: 'spawn', + label: 'recoverable recovery', + request: { + prompt: [{ type: 'text', text: 'persist before active edge' }], + parent: activeRoot, + }, + signal: SIGNAL, + }) + await vi.waitFor(() => { expect(first.ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + expect((await first.ctx.sessionPersistence.inspect(childId)).events + .some(event => event.type === 'user/message')).toBe(true) + await first.dispose() + + const second = await stack(backend, storageRoot, [textResponse('cold resumed answer')]) + const activeHandle = await second.ctx.agents.resume({ + resumeSessionId: activeRootId, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + const failedHandle = await second.ctx.agents.resume({ + resumeSessionId: failedRootId, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + await vi.waitFor(() => { + expect(durable(activeHandle.agent).members[0]?.phase).toBe('active') + const failedMember = durable(failedHandle.agent).members[0] + expect(failedMember?.phase).toBe('failed') + expect(failedMember?.error).toContain('child Session recovery failed') + }, { timeout: 5_000 }) + + const receipt = await second.ctx.teams.sendMessage(activeHandle.agent, { + target: 'recoverable', + content: [{ type: 'text', text: 'resume after reconciliation' }], + delivery: 'wakeup', + signal: SIGNAL, + }) + expect(receipt.status).toBe('accepted') + await vi.waitFor(() => { expect(second.ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + await vi.waitFor(() => { expect(durable(activeHandle.agent).pendingMessages).toEqual([]) }) + + await activeHandle.dispose() + await failedHandle.dispose() + await second.dispose() + }) + + it('reconciles a provisioning child whose initial prompt is durably pending', { + timeout: PERSISTENCE_TEST_TIMEOUT_MS, + }, async () => { + const storageRoot = mkdtempSync(join(tmpdir(), `dsh-team-pending-${backend.name.toLowerCase()}-`)) + roots.push(storageRoot) + const rootId = SessionId(`${backend.name.toLowerCase()}-pending-root`) + const childId = SessionId(`${backend.name.toLowerCase()}-pending-child`) + const first = await stack(backend, storageRoot, []) + const root = first.ctx.agentLoop.create(rootId, { provider: 'mock', model: 'mock' }) + await Promise.resolve() + await Promise.resolve() + root.session.append('team/member', { + version: 1, + teamId: TeamId(root.id), + member: provisioning(childId, 'pending-worker'), + }) + const initial = createUserMessage({ + content: [{ type: 'text', text: 'durably pending initial task' }], + source: { kind: 'user' }, + }) + const child = persistedChild(first.ctx, rootId, childId, initial) + await Promise.all([ + first.ctx.sessions.flush(root.session), + first.ctx.sessions.flush(child), + ]) + await first.dispose() + + const second = await stack(backend, storageRoot, []) + const rootHandle = await second.ctx.agents.resume({ + resumeSessionId: rootId, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + await vi.waitFor(() => { + expect(durable(rootHandle.agent).members[0]?.phase).toBe('active') + }) + expect(second.adapter.requests).toEqual([]) + const stored = await second.ctx.sessionPersistence.inspect(childId) + expect(stored.events.some(event => event.type === 'agent/inbox/spliced' + && event.data.inserted.some(message => message.id === initial.id))).toBe(true) + + await rootHandle.dispose() + await second.dispose() + }) + + it('replays queued-minus-delivered mail in FIFO order without waking for quiet mail', { + timeout: PERSISTENCE_TEST_TIMEOUT_MS, + }, async () => { + const storageRoot = mkdtempSync(join(tmpdir(), `dsh-team-mail-${backend.name.toLowerCase()}-`)) + roots.push(storageRoot) + const rootId = SessionId(`${backend.name.toLowerCase()}-mail-root`) + + const first = await stack(backend, storageRoot, [textResponse('initial teammate answer')]) + const firstLead = first.ctx.agentLoop.create(rootId, { provider: 'mock', model: 'mock' }) + const started = await first.ctx.teams.spawnTeammate(firstLead, { + name: 'mail-worker', + description: 'mail recovery worker', + prompt: [{ type: 'text', text: 'finish before restart' }], + context: 'fresh', + provider: 'spawn', + signal: SIGNAL, + }) + await vi.waitFor(() => { expect(first.ctx.agents.get(started.member.id)).toBeUndefined() }, { timeout: 5_000 }) + const quiet = await first.ctx.teams.sendMessage(firstLead, { + target: 'mail-worker', + content: [{ type: 'text', text: 'durable quiet context' }], + delivery: 'quiet', + signal: SIGNAL, + }) + expect(quiet.status).toBe('queued') + expect(durable(firstLead).pendingMessages.map(message => message.id)).toEqual([quiet.messageId]) + await first.dispose() + + const second = await stack(backend, storageRoot, [textResponse('resumed teammate answer')]) + const rootHandle = await second.ctx.agents.resume({ + resumeSessionId: rootId, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + await vi.waitFor(() => { + expect(durable(rootHandle.agent).pendingMessages.map(message => message.id)) + .toEqual([quiet.messageId]) + }) + expect(second.ctx.agents.get(started.member.id)).toBeUndefined() + + const waking = await second.ctx.teams.sendMessage(rootHandle.agent, { + target: 'mail-worker', + content: [{ type: 'text', text: 'resume after restart' }], + delivery: 'wakeup', + signal: SIGNAL, + }) + expect(waking.status).toBe('accepted') + await vi.waitFor(() => { expect(second.ctx.agents.get(started.member.id)).toBeUndefined() }, { timeout: 5_000 }) + await vi.waitFor(() => { expect(durable(rootHandle.agent).pendingMessages).toEqual([]) }) + + const child = await second.ctx.sessionPersistence.inspect(started.member.id) + const peerIds = child.events.flatMap(event => event.type === 'user/message' + && event.data.source.kind === 'team-message' + ? [event.data.source.messageId] + : []) + expect(peerIds).toEqual([quiet.messageId, waking.messageId]) + + await rootHandle.dispose() + await second.dispose() + }) + + it('acknowledges target-recorded mail after restart without delivering it twice', { + timeout: PERSISTENCE_TEST_TIMEOUT_MS, + }, async () => { + const storageRoot = mkdtempSync(join(tmpdir(), `dsh-team-dedup-${backend.name.toLowerCase()}-`)) + roots.push(storageRoot) + const rootId = SessionId(`${backend.name.toLowerCase()}-dedup-root`) + const messageId = TeamMessageId(`${backend.name.toLowerCase()}-recorded-message`) + + const first = await stack(backend, storageRoot, [textResponse('initial teammate answer')]) + const firstLead = first.ctx.agentLoop.create(rootId, { provider: 'mock', model: 'mock' }) + const started = await first.ctx.teams.spawnTeammate(firstLead, { + name: 'dedup-worker', + description: 'mail deduplication worker', + prompt: [{ type: 'text', text: 'finish before the crash window' }], + context: 'fresh', + provider: 'spawn', + signal: SIGNAL, + }) + await vi.waitFor(() => { expect(first.ctx.agents.get(started.member.id)).toBeUndefined() }, { timeout: 5_000 }) + + const targetHandle = await first.ctx.agents.resume({ + resumeSessionId: started.member.id, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + targetHandle.agent.session.append('user/message', createUserMessage({ + content: [ + { type: 'text', text: `Team message ${messageId} from lead:` }, + { type: 'text', text: 'already recorded before acknowledgement' }, + ], + source: { + kind: 'team-message', + teamId: TeamId(rootId), + messageId, + senderId: rootId, + senderName: 'lead', + }, + }), { surfaceOp: 'append' }) + await first.ctx.sessions.flush(targetHandle.agent.session) + // Let the pre-queue acknowledgement observer prove there is no mailbox + // row yet before authoring the simulated crash prefix below. + await new Promise((resolve) => { setTimeout(resolve, 0) }) + await targetHandle.dispose() + + const queued: TeamMessageSnapshot = { + id: messageId, + senderId: rootId, + senderName: 'lead', + targetId: started.member.id, + delivery: 'wakeup', + content: [{ type: 'text', text: 'already recorded before acknowledgement' }], + } + firstLead.session.append('team/message/queued', { + version: 1, + teamId: TeamId(rootId), + message: queued, + }) + await first.ctx.sessions.flush(firstLead.session) + expect(durable(firstLead).pendingMessages.map(message => message.id)).toEqual([messageId]) + await first.dispose() + + const second = await stack(backend, storageRoot, []) + const rootHandle = await second.ctx.agents.resume({ + resumeSessionId: rootId, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + await vi.waitFor(() => { expect(durable(rootHandle.agent).pendingMessages).toEqual([]) }) + expect(second.ctx.agents.get(started.member.id)).toBeUndefined() + expect(second.adapter.requests).toEqual([]) + + const child = await second.ctx.sessionPersistence.inspect(started.member.id) + const occurrences = child.events.filter(event => event.type === 'user/message' + && event.data.source.kind === 'team-message' + && event.data.source.messageId === messageId) + expect(occurrences).toHaveLength(1) + + await rootHandle.dispose() + await second.dispose() + }) + + it('acknowledges durably pending target mail without cold-resume duplication', { + timeout: PERSISTENCE_TEST_TIMEOUT_MS, + }, async () => { + const storageRoot = mkdtempSync(join(tmpdir(), `dsh-team-inbox-${backend.name.toLowerCase()}-`)) + roots.push(storageRoot) + const rootId = SessionId(`${backend.name.toLowerCase()}-inbox-root`) + const childId = SessionId(`${backend.name.toLowerCase()}-inbox-child`) + const messageId = TeamMessageId(`${backend.name.toLowerCase()}-pending-team-message`) + const first = await stack(backend, storageRoot, []) + const root = first.ctx.agentLoop.create(rootId, { provider: 'mock', model: 'mock' }) + await Promise.resolve() + await Promise.resolve() + const provisioned = provisioning(childId, 'pending-mail-worker') + const active: TeamMemberSnapshot = { + ...provisioned, + phase: 'active', + } + const queued: TeamMessageSnapshot = { + id: messageId, + senderId: rootId, + senderName: 'lead', + targetId: childId, + delivery: 'wakeup', + content: [{ type: 'text', text: 'already durable in target inbox' }], + } + root.session.append('team/member', { + version: 1, + teamId: TeamId(root.id), + member: provisioned, + }) + root.session.append('team/member', { + version: 1, + teamId: TeamId(root.id), + member: active, + }) + root.session.append('team/message/queued', { + version: 1, + teamId: TeamId(root.id), + message: queued, + }) + const pending = createUserMessage({ + content: [{ type: 'text', text: 'already durable in target inbox' }], + source: { + kind: 'team-message', + teamId: TeamId(rootId), + messageId, + senderId: rootId, + senderName: 'lead', + }, + }) + const child = persistedChild(first.ctx, rootId, childId, pending) + await Promise.all([ + first.ctx.sessions.flush(root.session), + first.ctx.sessions.flush(child), + ]) + await first.dispose() + + const second = await stack(backend, storageRoot, []) + const rootHandle = await second.ctx.agents.resume({ + resumeSessionId: rootId, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + await vi.waitFor(() => { + expect(durable(rootHandle.agent).pendingMessages).toEqual([]) + }) + expect(second.adapter.requests).toEqual([]) + expect(second.ctx.agents.get(childId)).toBeUndefined() + const stored = await second.ctx.sessionPersistence.inspect(childId) + const pendingCopies = stored.events.flatMap(event => event.type === 'agent/inbox/spliced' + ? event.data.inserted.filter(message => message.source.kind === 'team-message' + && message.source.messageId === messageId) + : []) + expect(pendingCopies).toHaveLength(1) + + await rootHandle.dispose() + await second.dispose() + }) + }) +} diff --git a/packages/experimental/team/tests/team.spec.ts b/packages/experimental/team/tests/team.spec.ts new file mode 100644 index 0000000000..dd03cd6438 --- /dev/null +++ b/packages/experimental/team/tests/team.spec.ts @@ -0,0 +1,1692 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { SessionId, type Session } from '@deepseek-ai/dsh-session' +import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import SubagentService from '@deepseek-ai/dsh-subagent' +import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' +import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' +import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +import TeamService, { foldTeam, TeamError, TeamId, TeamMessageId, TeamTaskId } from '../src/index.ts' +import { TeamRuntimeLifecycle } from '../src/lifecycle.ts' +import type { TeamMemberSnapshot, TeamMessageSnapshot, TeamTaskSnapshot } from '../src/index.ts' + +const SIGNAL = new AbortController().signal +const roots: string[] = [] + +afterEach(() => { + vi.useRealTimers() + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +/** Detached durable Team read: the service exposes views, so assertions fold the Lead log. */ +function durable(agent: Agent): { + members: TeamMemberSnapshot[] + tasks: TeamTaskSnapshot[] + pendingMessages: TeamMessageSnapshot[] +} { + const state = foldTeam(agent.id, agent.session.events) + return { + members: [...state.members.values()], + tasks: [...state.tasks.values()], + pendingMessages: [...state.messages.values()].filter(message => !state.delivered.has(message.id)), + } +} + +async function setup( + script: ConstructorParameters[0], + config: ConstructorParameters[1] = {}, +) { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-')) + roots.push(storageRoot) + await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(SubagentService) + await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) + await ctx.plugin(SubagentFork, { providerName: 'fork' }) + const teamFiber = await ctx.plugin(TeamService, config) + const adapter = new MockAdapter(script) + ctx.llm.registerAdapter(['mock'], adapter) + const lead = ctx.agentLoop.create(SessionId('lead'), { provider: 'mock', model: 'mock' }) + return { ctx, lead, adapter, storageRoot, teamFiber } +} + +function content(text: string) { + return [{ type: 'text' as const, text }] +} + +interface TeamServiceInternals { + readonly roster: { + readonly inFlightCreations: Set> + checkpointInitialPrompt(childId: SessionId, messageId: string, signal: AbortSignal): Promise + reconcileProvisioning(root: Agent, signal: AbortSignal): Promise + liveChildrenByRoot(): Map + } + readonly mailbox: { + tryDispatch(root: Agent, message: TeamMessageSnapshot, signal: AbortSignal): Promise + serializeDispatch(message: TeamMessageSnapshot, operation: () => Promise): Promise + markDelivered(root: Agent, messageId: ReturnType, targetId: SessionId): Promise + } + readonly journal: { + state(root: Agent): unknown + } + disposeRuntime(): Promise + recoverFor(agent: Agent): Promise + scheduleRecovery(agent: Agent): void +} + +/** White-box access follows the runtime owners so coverage does not widen the service API. */ +function teamInternals(ctx: Context): TeamServiceInternals { + return ctx.teams as unknown as TeamServiceInternals +} + +function spawn( + ctx: Context, + lead: Agent, + name: string, + options: { context?: 'fresh' | 'fork'; provider?: string } = {}, +) { + const context = options.context ?? 'fresh' + return ctx.teams.spawnTeammate(lead, { + name, + description: `${name} responsibility`, + prompt: content(`${name} initial`), + context, + provider: options.provider ?? (context === 'fork' ? 'fork' : 'spawn'), + signal: SIGNAL, + }) +} + +async function waitNoAgent(ctx: Context, id: SessionId): Promise { + await vi.waitFor(() => { expect(ctx.agents.get(id)).toBeUndefined() }, { timeout: 5_000 }) +} + +async function waitRunning(ctx: Context, id: SessionId): Promise { + return vi.waitFor(() => { + const agent = ctx.agents.get(id) + expect(agent?.status).toBe('running') + return agent! + }, { timeout: 5_000 }) +} + +describe('Team identity and provisioning', () => { + it('rejects deployment limits that are not positive safe integers', async () => { + const fields = [ + 'maxMembers', + 'maxTasks', + 'maxPendingMessagesPerMember', + 'maxMessageBytes', + 'disposalTimeoutMs', + ] as const + for (const field of fields) { + for (const value of [0, 1.5, Number.MAX_SAFE_INTEGER + 1]) { + await expect(setup([], { [field]: value })).rejects.toThrow() + } + } + }) + + it('supports direct-constructor defaults and recovers roots that already exist', async () => { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-direct-')) + roots.push(storageRoot) + await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(SubagentService) + const lead = ctx.agentLoop.create(SessionId('preexisting-lead'), {}) + const service = new TeamService(ctx) + + expect(service.listMembers(lead)).toEqual([expect.objectContaining({ + name: 'lead', + status: 'idle', + diagnostics: [], + })]) + const provisioning = { + id: SessionId('preexisting-child'), + name: 'preexisting-worker', + description: 'preexisting responsibility', + provider: 'spawn', + context: 'fresh' as const, + phase: 'provisioning' as const, + } + lead.session.append('team/member', { + version: 1, + teamId: TeamId(lead.id), + member: provisioning, + }) + expect(service.listMembers(lead)[1]).toEqual(expect.objectContaining({ + name: 'preexisting-worker', + status: 'provisioning', + diagnostics: [], + })) + expect(service.listMembers(lead)[1]).not.toHaveProperty('model') + await Promise.resolve() + }) + + it('creates fresh and fork teammates with immutable names and bounded roster size', async () => { + const { ctx, lead } = await setup([ + textResponse('lead answer'), + textResponse('fork answer'), + textResponse('fresh answer'), + ], { maxMembers: 2 }) + lead.followup(createUserMessage({ content: content('lead turn'), source: { kind: 'user' } })) + await lead.whenIdle() + + const forked = await spawn(ctx, lead, 'fork-worker', { context: 'fork' }) + await waitNoAgent(ctx, forked.member.id) + const fresh = await spawn(ctx, lead, 'fresh-worker') + await waitNoAgent(ctx, fresh.member.id) + + expect((await ctx.sessionPersistence.inspect(forked.member.id)).meta.seedLength).toBeGreaterThan(0) + expect((await ctx.sessionPersistence.inspect(fresh.member.id)).meta.seedLength ?? 0).toBe(0) + expect(ctx.teams.listMembers(lead).map(row => [row.name, row.context, row.status])).toEqual([ + ['lead', undefined, 'idle'], + ['fork-worker', 'fork', 'inactive'], + ['fresh-worker', 'fresh', 'inactive'], + ]) + await expect(spawn(ctx, lead, 'third-worker')).rejects.toMatchObject({ code: 'TEAM_MEMBER_LIMIT' }) + await expect(spawn(ctx, lead, 'fresh-worker')).rejects.toMatchObject({ code: 'TEAM_MEMBER_NAME_TAKEN' }) + }) + + it('flushes the accepted child prompt before committing the active roster edge', async () => { + const { ctx, lead } = await setup([textResponse('checkpointed child answer')]) + const flush = ctx.sessions.flush.bind(ctx.sessions) + const order: string[] = [] + vi.spyOn(ctx.sessions, 'flush').mockImplementation(async (session) => { + if (session.id === lead.id && durable(lead).members[0]?.phase === 'active') { + order.push('lead-active') + } else if (session.id !== lead.id) { + order.push('child') + } + return flush(session) + }) + + const started = await spawn(ctx, lead, 'checkpoint-worker') + expect(order.indexOf('child')).toBeGreaterThanOrEqual(0) + expect(order.indexOf('child')).toBeLessThan(order.indexOf('lead-active')) + await waitNoAgent(ctx, started.member.id) + }) + + it('checkpoints live and detached inbox receipts and aborts an unresolved checkpoint', async () => { + const { ctx, lead } = await setup([]) + const internal = teamInternals(ctx).roster + let liveSession: Session | undefined + const liveFiber = await ctx.plugin(Object.assign(function checkpointFixture(childCtx: Context) { + liveSession = childCtx.sessions.create(SessionId('checkpoint-child')) + }, { inject: ['sessions'] })) + if (liveSession === undefined) throw new Error('checkpoint fixture did not create its Session') + const initial = createUserMessage({ content: content('checkpoint me'), source: { kind: 'user' } }) + const checkpoint = internal.checkpointInitialPrompt(liveSession.id, initial.id, SIGNAL) + await Promise.resolve() + lead.inject(createUserMessage({ content: content('unrelated progress'), source: { kind: 'user' } })) + const unrelatedFiber = await ctx.plugin(Object.assign(function unrelatedCheckpointFixture(childCtx: Context) { + childCtx.sessions.create(SessionId('unrelated-checkpoint-child')) + }, { inject: ['sessions'] })) + await unrelatedFiber.dispose() + liveSession.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, inserted: [initial], + }) + await checkpoint + await liveFiber.dispose() + + await expect(internal.checkpointInitialPrompt(liveSession.id, initial.id, SIGNAL)).resolves.toBeUndefined() + const missing = createUserMessage({ content: content('missing'), source: { kind: 'user' } }) + await expect(internal.checkpointInitialPrompt(liveSession.id, missing.id, SIGNAL)) + .rejects.toMatchObject({ code: 'TEAM_PROVISIONING_CONFLICT' }) + + let disposedSession: Session | undefined + const disposedFiber = await ctx.plugin(Object.assign(function disposedCheckpointFixture(childCtx: Context) { + disposedSession = childCtx.sessions.create(SessionId('disposed-checkpoint-child')) + }, { inject: ['sessions'] })) + if (disposedSession === undefined) throw new Error('disposed checkpoint fixture did not create its Session') + const disposed = internal.checkpointInitialPrompt(disposedSession.id, missing.id, SIGNAL) + const disposedResult = expect(disposed).rejects.toThrow('not found') + await Promise.resolve() + await disposedFiber.dispose() + await disposedResult + + let abortedSession: Session | undefined + const abortedFiber = await ctx.plugin(Object.assign(function abortedCheckpointFixture(childCtx: Context) { + abortedSession = childCtx.sessions.create(SessionId('aborted-checkpoint-child')) + }, { inject: ['sessions'] })) + if (abortedSession === undefined) throw new Error('aborted checkpoint fixture did not create its Session') + const controller = new AbortController() + const aborted = internal.checkpointInitialPrompt(abortedSession.id, missing.id, controller.signal) + await Promise.resolve() + controller.abort({ kind: 'test' }) + await expect(aborted).rejects.toMatchObject({ code: 'TEAM_DISPOSED' }) + + const errorController = new AbortController() + const errorAborted = internal.checkpointInitialPrompt(abortedSession.id, missing.id, errorController.signal) + const errorResult = expect(errorAborted).rejects.toThrow('checkpoint stopped') + await Promise.resolve() + errorController.abort(new Error('checkpoint stopped')) + await errorResult + await abortedFiber.dispose() + }) + + it('drains an accepted child when its initial durability checkpoint fails', async () => { + const { ctx, lead } = await setup(['hang']) + vi.spyOn(teamInternals(ctx).roster, 'checkpointInitialPrompt') + .mockRejectedValueOnce(new Error('checkpoint failed')) + + await expect(spawn(ctx, lead, 'checkpoint-failure')).rejects.toThrow('checkpoint failed') + const member = durable(lead).members[0] + expect(member).toMatchObject({ phase: 'failed', error: 'checkpoint failed' }) + if (member !== undefined) await waitNoAgent(ctx, member.id) + }) + + it('records failed provisioning durably, reserves its name, and counts it against the limit', async () => { + const { ctx, lead } = await setup([], { maxMembers: 1 }) + await expect(spawn(ctx, lead, 'failed-worker', { provider: 'missing' })).rejects.toThrow() + + expect(ctx.teams.listMembers(lead)[1]).toMatchObject({ + name: 'failed-worker', + status: 'failed', + provider: 'missing', + }) + await expect(spawn(ctx, lead, 'failed-worker')).rejects.toMatchObject({ code: 'TEAM_MEMBER_NAME_TAKEN' }) + await expect(spawn(ctx, lead, 'other-worker')).rejects.toMatchObject({ code: 'TEAM_MEMBER_LIMIT' }) + }) + + it('records non-Error provider failures and contains a reversed provisioning settlement race', async () => { + const first = await setup([]) + vi.spyOn(first.ctx.subagents, 'startContinuable').mockRejectedValueOnce('string provider failure') + await expect(spawn(first.ctx, first.lead, 'string-failure')).rejects.toBe('string provider failure') + expect(first.ctx.teams.listMembers(first.lead)[1]).toMatchObject({ + status: 'failed', + diagnostics: ['string provider failure'], + }) + await expect(first.ctx.teams.sendMessage(first.lead, { + target: 'string-failure', content: content('cannot deliver'), delivery: 'quiet', signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_MEMBER_NOT_FOUND' }) + + const second = await setup([]) + vi.spyOn(second.ctx.subagents, 'startContinuable').mockImplementationOnce(async () => { + const provisioning = durable(second.lead).members[0] + if (provisioning === undefined) throw new Error('missing provisioning edge') + second.lead.session.append('team/member', { + version: 1, + teamId: TeamId(second.lead.id), + member: { ...provisioning, phase: 'active' }, + }) + await second.ctx.sessions.flush(second.lead.session) + throw new Error('creator failed after recovery settled active') + }) + await expect(spawn(second.ctx, second.lead, 'reverse-race')).rejects.toBeInstanceOf(AggregateError) + expect(durable(second.lead).members[0]?.phase).toBe('active') + }) + + it('cleans up a child when recovery settles its provisioning record first', async () => { + const { ctx, lead } = await setup(['hang']) + const start = ctx.subagents.startContinuable.bind(ctx.subagents) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + let childId: SessionId | undefined + vi.spyOn(ctx.subagents, 'startContinuable').mockImplementation(async (spec) => { + childId = spec.childId + entered.resolve(undefined) + await release.promise + return start(spec) + }) + + const spawning = spawn(ctx, lead, 'racing-worker') + const rejected = expect(spawning).rejects.toMatchObject({ code: 'TEAM_PROVISIONING_CONFLICT' }) + await entered.promise + await teamInternals(ctx).roster.reconcileProvisioning(lead, SIGNAL) + expect(durable(lead).members[0]?.phase).toBe('failed') + + release.resolve(undefined) + await rejected + if (childId === undefined) throw new Error('reserved child id was not observed') + await waitNoAgent(ctx, childId) + }) + + it('handles a continuation that settles before the active roster view or conflict cleanup lookup', async () => { + const first = await setup([]) + vi.spyOn(teamInternals(first.ctx).roster, 'checkpointInitialPrompt').mockResolvedValueOnce() + vi.spyOn(first.ctx.subagents, 'startContinuable').mockImplementationOnce(async spec => ({ + childId: spec.childId!, + messageId: createUserMessage({ content: content('accepted'), source: { kind: 'user' } }).id, + })) + const inactive = await spawn(first.ctx, first.lead, 'instant-worker') + expect(inactive.member).toMatchObject({ status: 'inactive', diagnostics: [] }) + expect(inactive.member).not.toHaveProperty('model') + + const second = await setup([]) + vi.spyOn(teamInternals(second.ctx).roster, 'checkpointInitialPrompt').mockResolvedValueOnce() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + vi.spyOn(second.ctx.subagents, 'startContinuable').mockImplementationOnce(async (spec) => { + entered.resolve(undefined) + await release.promise + return { + childId: spec.childId!, + messageId: createUserMessage({ content: content('accepted'), source: { kind: 'user' } }).id, + } + }) + const spawning = spawn(second.ctx, second.lead, 'instant-conflict') + const rejected = expect(spawning).rejects.toMatchObject({ code: 'TEAM_PROVISIONING_CONFLICT' }) + await entered.promise + await teamInternals(second.ctx).roster.reconcileProvisioning(second.lead, SIGNAL) + release.resolve(undefined) + await rejected + }) + + it('validates names and permits only the Lead to create or interrupt teammates', async () => { + const { ctx, lead } = await setup(['hang']) + for (const name of ['Lead', 'lead', '-bad', 'bad-', 'bad_name', 'x'.repeat(65)]) { + await expect(spawn(ctx, lead, name)).rejects.toMatchObject({ code: 'TEAM_INVALID_MEMBER_NAME' }) + } + const started = await spawn(ctx, lead, 'worker') + const worker = await waitRunning(ctx, started.member.id) + await expect(spawn(ctx, worker, 'nested')).rejects.toMatchObject({ code: 'TEAM_LEAD_REQUIRED' }) + expect(() => ctx.teams.interrupt(worker, 'worker')).toThrow(expect.objectContaining({ code: 'TEAM_LEAD_REQUIRED' })) + expect(ctx.teams.interrupt(lead, 'worker')).toEqual({ previousStatus: 'running' }) + await waitNoAgent(ctx, worker.id) + expect(ctx.teams.interrupt(lead, 'worker')).toEqual({ previousStatus: 'inactive' }) + expect(() => ctx.teams.interrupt(lead, 'lead')).toThrow(expect.objectContaining({ code: 'TEAM_INVALID_TARGET' })) + }) + + it('validates teammate text fields and pre-provisioning cancellation', async () => { + const { ctx, lead } = await setup([]) + await expect(ctx.teams.spawnTeammate(lead, { + name: 'empty-description', + description: ' ', + prompt: content('unused'), + context: 'fresh', + provider: 'spawn', + signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' }) + await expect(ctx.teams.spawnTeammate(lead, { + name: 'empty-provider', + description: 'valid description', + prompt: content('unused'), + context: 'fresh', + provider: ' ', + signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' }) + const controller = new AbortController() + controller.abort(new TeamError('cancelled before provisioning', 'TEST_CANCELLED')) + await expect(ctx.teams.spawnTeammate(lead, { + name: 'cancelled-worker', + description: 'never provisioned', + prompt: content('unused'), + context: 'fresh', + provider: 'spawn', + signal: controller.signal, + })).rejects.toMatchObject({ code: 'TEST_CANCELLED' }) + expect(durable(lead).members).toEqual([]) + }) + + it('treats an ordinary fork as a new Root Team and filters inherited Team state', async () => { + const { ctx, lead } = await setup([]) + await ctx.teams.createTask(lead, { subject: 'parent task', description: 'belongs to parent' }) + const handle = await ctx.agents.create({ + sessionId: SessionId('ordinary-fork'), + seed: lead.session.events, + meta: { parentSession: lead.id, seedLength: lead.session.seq }, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + + expect(ctx.teams.membership(handle.agent)).toMatchObject({ + id: TeamId(handle.agent.id), + role: 'lead', + name: 'lead', + }) + expect(durable(handle.agent)).toMatchObject({ members: [], tasks: [], pendingMessages: [] }) + await handle.dispose() + }) + + it('rejects stale Agent identities and non-Team subagent children', async () => { + const { ctx, lead } = await setup([textResponse('done')]) + const started = await ctx.subagents.startContinuable({ + provider: 'spawn', + label: 'ordinary worker', + request: { prompt: content('ordinary'), parent: lead }, + signal: SIGNAL, + }) + const live = ctx.agents.get(started.childId) + if (live !== undefined) expect(ctx.teams.tryMembership(live)).toBeUndefined() + await waitNoAgent(ctx, started.childId) + expect(() => ctx.teams.membership(lead)).not.toThrow() + + const impostor = { ...lead } as Agent + expect(ctx.teams.tryMembership(impostor)).toBeUndefined() + expect(() => ctx.teams.membership(impostor)).toThrow(expect.objectContaining({ code: 'TEAM_NOT_MEMBER' })) + + const orphanRoot = await ctx.agents.create({ + sessionId: SessionId('orphan-ordinary-root'), + meta: { parentSession: SessionId('absent-parent') }, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + expect(ctx.teams.membership(orphanRoot.agent)).toMatchObject({ role: 'lead', name: 'lead' }) + await orphanRoot.dispose() + }) + + it('does not reinterpret an orphaned provider child or malformed parent stream as a Team root', async () => { + const first = await setup([textResponse('ordinary child done')]) + const parent = await first.ctx.agents.create({ + sessionId: SessionId('temporary-parent'), + agentOptions: { provider: 'mock', model: 'mock' }, + }) + const started = await first.ctx.subagents.startContinuable({ + provider: 'spawn', + label: 'ordinary child', + request: { prompt: content('finish'), parent: parent.agent }, + signal: SIGNAL, + }) + await waitNoAgent(first.ctx, started.childId) + await parent.dispose() + const orphan = await first.ctx.agents.resume({ + resumeSessionId: started.childId, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + expect(first.ctx.teams.tryMembership(orphan.agent)).toBeUndefined() + expect(teamInternals(first.ctx).roster.liveChildrenByRoot()).toEqual(new Map()) + await orphan.dispose() + + const second = await setup([]) + const child = await second.ctx.agents.create({ + sessionId: SessionId('malformed-parent-child'), + meta: { parentSession: second.lead.id }, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + const journal = teamInternals(second.ctx).journal + const state = journal.state.bind(journal) + journal.state = () => { throw new Error('malformed Team stream') } + expect(second.ctx.teams.tryMembership(child.agent)).toBeUndefined() + journal.state = state + await child.dispose() + }) +}) + +describe('Team shared task DAG', () => { + it('fails loudly when the durable numeric task id space is exhausted', async () => { + const { ctx, lead } = await setup([]) + const id = TeamTaskId(`task-${Number.MAX_SAFE_INTEGER}`) + lead.session.append('team/task', { + version: 1, + teamId: TeamId(lead.id), + task: { + id, + revision: 1, + subject: 'last numeric task', + description: 'occupies the final safe numeric task id', + status: 'pending', + blockedBy: [], + writeScopes: [], + }, + }) + await ctx.sessions.flush(lead.session) + + await expect(ctx.teams.createTask(lead, { + subject: 'cannot allocate', + description: 'no safe numeric task id remains', + })).rejects.toMatchObject({ code: 'TEAM_TASK_LIMIT' }) + }) + + it('bounds non-deleted tasks while retaining deleted task ids as tombstones', async () => { + const { ctx, lead } = await setup([], { maxTasks: 1 }) + const first = await ctx.teams.createTask(lead, { subject: 'first', description: 'first task' }) + await expect(ctx.teams.createTask(lead, { subject: 'overflow', description: 'overflow task' })) + .rejects.toMatchObject({ code: 'TEAM_TASK_LIMIT' }) + + const deleted = await ctx.teams.updateTask(lead, { + taskId: first.id, + expectedRevision: first.revision, + action: 'delete', + }) + const second = await ctx.teams.createTask(lead, { subject: 'second', description: 'second task' }) + expect(deleted.status).toBe('deleted') + expect(second.id).toBe(TeamTaskId('task-2')) + expect(ctx.teams.getTask(lead, first.id).status).toBe('deleted') + expect(ctx.teams.listTasks(lead).map(task => task.id)).toEqual([second.id]) + }) + + it('enforces CAS, ownership, dependencies, transitions, and write-scope warnings', async () => { + const { ctx, lead } = await setup(['hang', 'hang']) + const firstMember = await spawn(ctx, lead, 'alpha') + const alpha = await waitRunning(ctx, firstMember.member.id) + const secondMember = await spawn(ctx, lead, 'beta') + const beta = await waitRunning(ctx, secondMember.member.id) + + const first = await ctx.teams.createTask(alpha, { + subject: 'first', + description: 'first task', + writeScopes: ['src', './src/', 'src'], + }) + const second = await ctx.teams.createTask(beta, { + subject: 'second', + description: 'second task', + blockedBy: [first.id], + writeScopes: ['src/feature'], + }) + expect(first.writeScopes).toEqual(['src']) + await expect(ctx.teams.updateTask(beta, { + taskId: second.id, + expectedRevision: second.revision, + action: 'claim', + })).rejects.toMatchObject({ code: 'TEAM_TASK_BLOCKED' }) + + const claimed = await ctx.teams.updateTask(alpha, { + taskId: first.id, + expectedRevision: first.revision, + action: 'claim', + }) + await expect(ctx.teams.updateTask(beta, { + taskId: first.id, + expectedRevision: claimed.revision, + action: 'claim', + })).rejects.toMatchObject({ code: 'TEAM_TASK_ALREADY_CLAIMED' }) + expect(ctx.teams.getTask(beta, second.id)).toMatchObject({ + ready: false, + writeScopeWarnings: [`write scopes overlap with ${first.id}`], + }) + await expect(ctx.teams.updateTask(beta, { + taskId: first.id, + expectedRevision: claimed.revision, + action: 'edit', + subject: 'stolen', + })).rejects.toMatchObject({ code: 'TEAM_TASK_UNAUTHORIZED' }) + await expect(ctx.teams.updateTask(alpha, { + taskId: first.id, + expectedRevision: first.revision, + action: 'complete', + })).rejects.toMatchObject({ code: 'TEAM_TASK_STALE_REVISION' }) + + const completed = await ctx.teams.updateTask(alpha, { + taskId: first.id, + expectedRevision: claimed.revision, + action: 'complete', + }) + expect(completed.status).toBe('completed') + expect(ctx.teams.getTask(beta, second.id).ready).toBe(true) + const secondClaim = await ctx.teams.updateTask(beta, { + taskId: second.id, + expectedRevision: second.revision, + action: 'claim', + }) + const released = await ctx.teams.updateTask(beta, { + taskId: second.id, + expectedRevision: secondClaim.revision, + action: 'release', + }) + expect(released).toMatchObject({ status: 'pending', ready: true }) + expect('ownerId' in released).toBe(false) + + ctx.teams.interrupt(lead, 'alpha') + ctx.teams.interrupt(lead, 'beta') + await Promise.all([waitNoAgent(ctx, alpha.id), waitNoAgent(ctx, beta.id)]) + }) + + it('rejects malformed scopes and every invalid dependency relation', async () => { + const { ctx, lead } = await setup([]) + const first = await ctx.teams.createTask(lead, { subject: 'one', description: 'one' }) + const second = await ctx.teams.createTask(lead, { + subject: 'two', description: 'two', blockedBy: [first.id], + }) + await expect(ctx.teams.createTask(lead, { + subject: 'bad', description: 'bad', blockedBy: [TeamTaskId('missing')], + })).rejects.toMatchObject({ code: 'TEAM_TASK_NOT_FOUND' }) + await expect(ctx.teams.updateTask(lead, { + taskId: first.id, + expectedRevision: first.revision, + action: 'set_dependencies', + blockedBy: [second.id], + })).rejects.toMatchObject({ code: 'TEAM_TASK_DEPENDENCY_CYCLE' }) + await expect(ctx.teams.updateTask(lead, { + taskId: first.id, + expectedRevision: first.revision, + action: 'set_dependencies', + blockedBy: [first.id], + })).rejects.toMatchObject({ code: 'TEAM_TASK_DEPENDENCY_CYCLE' }) + await expect(ctx.teams.updateTask(lead, { + taskId: first.id, + expectedRevision: first.revision, + action: 'set_dependencies', + blockedBy: [second.id, second.id], + })).rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' }) + for (const scope of ['', '.', '..', '/root', 'C:\\root', 'C:root', 'a//b', 'a/../b']) { + await expect(ctx.teams.createTask(lead, { + subject: 'scope', description: 'scope', writeScopes: [scope], + })).rejects.toMatchObject({ code: 'TEAM_INVALID_WRITE_SCOPE' }) + } + }) + + it('rejects incomplete mutations, invalid transitions, and deletion of a live blocker', async () => { + const { ctx, lead } = await setup([]) + await expect(ctx.teams.createTask(lead, { subject: ' ', description: 'invalid' })) + .rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' }) + await expect(ctx.teams.createTask(lead, { subject: 'invalid', description: '' })) + .rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' }) + await expect(ctx.teams.createTask(lead, { subject: 'x'.repeat(201), description: 'too long' })) + .rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' }) + const blocker = await ctx.teams.createTask(lead, { subject: 'blocker', description: 'blocker' }) + await ctx.teams.createTask(lead, { + subject: 'dependent', description: 'dependent', blockedBy: [blocker.id], + }) + expect(() => ctx.teams.getTask(lead, TeamTaskId('missing'))) + .toThrow(expect.objectContaining({ code: 'TEAM_TASK_NOT_FOUND' })) + for (const action of ['release', 'complete', 'reopen'] as const) { + await expect(ctx.teams.updateTask(lead, { + taskId: blocker.id, + expectedRevision: blocker.revision, + action, + })).rejects.toMatchObject({ code: 'TEAM_TASK_INVALID_TRANSITION' }) + } + await expect(ctx.teams.updateTask(lead, { + taskId: blocker.id, + expectedRevision: blocker.revision, + action: 'edit', + })).rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' }) + await expect(ctx.teams.updateTask(lead, { + taskId: blocker.id, + expectedRevision: blocker.revision, + action: 'set_dependencies', + })).rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' }) + await expect(ctx.teams.updateTask(lead, { + taskId: blocker.id, + expectedRevision: blocker.revision, + action: 'delete', + })).rejects.toMatchObject({ code: 'TEAM_TASK_HAS_DEPENDENTS' }) + }) + + it('supports Lead reassignment, completion, reopen, and deletion permissions', async () => { + const { ctx, lead } = await setup(['hang']) + const started = await spawn(ctx, lead, 'owner') + const owner = await waitRunning(ctx, started.member.id) + const task = await ctx.teams.createTask(owner, { subject: 'lifecycle', description: 'lifecycle' }) + const assigned = await ctx.teams.updateTask(lead, { + taskId: task.id, + expectedRevision: task.revision, + action: 'reassign', + owner: 'owner', + }) + await expect(ctx.teams.updateTask(owner, { + taskId: task.id, + expectedRevision: assigned.revision, + action: 'reassign', + owner: 'lead', + })).rejects.toMatchObject({ code: 'TEAM_LEAD_REQUIRED' }) + const complete = await ctx.teams.updateTask(owner, { + taskId: task.id, + expectedRevision: assigned.revision, + action: 'complete', + }) + await expect(ctx.teams.updateTask(lead, { + taskId: task.id, + expectedRevision: complete.revision, + action: 'reassign', + owner: 'lead', + })).rejects.toMatchObject({ code: 'TEAM_TASK_INVALID_TRANSITION' }) + const reopened = await ctx.teams.updateTask(owner, { + taskId: task.id, + expectedRevision: complete.revision, + action: 'reopen', + }) + const claimed = await ctx.teams.updateTask(owner, { + taskId: task.id, + expectedRevision: reopened.revision, + action: 'claim', + }) + const deleted = await ctx.teams.updateTask(owner, { + taskId: task.id, + expectedRevision: claimed.revision, + action: 'delete', + }) + expect(deleted.status).toBe('deleted') + expect(ctx.teams.listTasks(lead)).toEqual([]) + await expect(ctx.teams.updateTask(owner, { + taskId: task.id, + expectedRevision: deleted.revision, + action: 'edit', + subject: 'late', + })).rejects.toMatchObject({ code: 'TEAM_TASK_DELETED' }) + ctx.teams.interrupt(lead, 'owner') + await waitNoAgent(ctx, owner.id) + }) + + it('covers partial edits, Lead ownership, unassignment, and blocked reassignment', async () => { + const { ctx, lead } = await setup(['hang']) + const started = await spawn(ctx, lead, 'editor') + const editor = await waitRunning(ctx, started.member.id) + const blocker = await ctx.teams.createTask(lead, { subject: 'blocker', description: 'blocker' }) + const task = await ctx.teams.createTask(lead, { + subject: 'draft', + description: 'draft description', + blockedBy: [blocker.id], + }) + await expect(ctx.teams.updateTask(lead, { + taskId: TeamTaskId('missing-update'), expectedRevision: 1, action: 'delete', + })).rejects.toMatchObject({ code: 'TEAM_TASK_NOT_FOUND' }) + await expect(ctx.teams.updateTask(lead, { + taskId: task.id, expectedRevision: task.revision, action: 'reassign', owner: 'editor', + })).rejects.toMatchObject({ code: 'TEAM_TASK_BLOCKED' }) + + const leadClaim = await ctx.teams.updateTask(lead, { + taskId: blocker.id, expectedRevision: blocker.revision, action: 'claim', + }) + expect(leadClaim.ownerName).toBe('lead') + const completedBlocker = await ctx.teams.updateTask(lead, { + taskId: blocker.id, expectedRevision: leadClaim.revision, action: 'complete', + }) + expect(completedBlocker.status).toBe('completed') + const assigned = await ctx.teams.updateTask(lead, { + taskId: task.id, expectedRevision: task.revision, action: 'reassign', owner: 'editor', + }) + const subject = await ctx.teams.updateTask(editor, { + taskId: task.id, expectedRevision: assigned.revision, action: 'edit', subject: 'edited subject', + }) + const description = await ctx.teams.updateTask(editor, { + taskId: task.id, + expectedRevision: subject.revision, + action: 'edit', + description: 'edited description', + }) + const scopes = await ctx.teams.updateTask(editor, { + taskId: task.id, + expectedRevision: description.revision, + action: 'edit', + writeScopes: ['src/nested'], + }) + expect(scopes).toMatchObject({ + subject: 'edited subject', + description: 'edited description', + writeScopes: ['src/nested'], + }) + const unassigned = await ctx.teams.updateTask(lead, { + taskId: task.id, expectedRevision: scopes.revision, action: 'reassign', owner: ' ', + }) + expect(unassigned).toMatchObject({ status: 'pending' }) + expect('ownerId' in unassigned).toBe(false) + + const broad = await ctx.teams.createTask(lead, { + subject: 'broad scope', description: 'broad scope', writeScopes: ['src'], + }) + const narrow = await ctx.teams.createTask(lead, { + subject: 'narrow scope', description: 'narrow scope', writeScopes: ['src/nested'], + }) + const disjoint = await ctx.teams.createTask(lead, { + subject: 'disjoint scope', description: 'disjoint scope', writeScopes: ['docs'], + }) + await ctx.teams.updateTask(lead, { + taskId: broad.id, expectedRevision: broad.revision, action: 'claim', + }) + await ctx.teams.updateTask(lead, { + taskId: narrow.id, expectedRevision: narrow.revision, action: 'claim', + }) + await ctx.teams.updateTask(lead, { + taskId: disjoint.id, expectedRevision: disjoint.revision, action: 'claim', + }) + expect(ctx.teams.getTask(lead, broad.id).writeScopeWarnings) + .toEqual([`write scopes overlap with ${narrow.id}`]) + + ctx.teams.interrupt(lead, 'editor') + await waitNoAgent(ctx, editor.id) + }) +}) + +describe('Team mailbox and waiting', () => { + it('acknowledges waking messages persisted by a busy Lead before model claim', async () => { + const { ctx, lead, teamFiber } = await setup(['hang', 'hang'], { maxPendingMessagesPerMember: 1 }) + const started = await spawn(ctx, lead, 'lead-reporter') + const reporter = await waitRunning(ctx, started.member.id) + lead.followup(createUserMessage({ content: content('keep the Lead busy'), source: { kind: 'user' } })) + await waitRunning(ctx, lead.id) + + const first = await ctx.teams.sendMessage(reporter, { + target: 'lead', content: content('first wakeup report'), delivery: 'wakeup', signal: SIGNAL, + }) + const second = await ctx.teams.sendMessage(reporter, { + target: 'lead', content: content('second wakeup report'), delivery: 'wakeup', signal: SIGNAL, + }) + expect([first.status, second.status]).toEqual(['accepted', 'accepted']) + expect(lead.status).toBe('running') + expect(durable(lead).pendingMessages).toEqual([]) + + const messageIds = new Set([first.messageId, second.messageId]) + const persisted = await ctx.sessionPersistence.inspect(lead.id) + const receiptOrder = persisted.events.flatMap((event) => { + if (event.type === 'agent/inbox/spliced' && event.data.inserted.some(message => + message.source.kind === 'team-message' && messageIds.has(message.source.messageId))) { + return ['agent/inbox/spliced'] + } + if (event.type === 'team/message/delivered' && messageIds.has(event.data.messageId)) { + return ['team/message/delivered'] + } + return [] + }) + expect(receiptOrder).toEqual([ + 'agent/inbox/spliced', + 'team/message/delivered', + 'agent/inbox/spliced', + 'team/message/delivered', + ]) + + const receiptCount = lead.session.events.filter(event => event.type === 'agent/inbox/spliced' + && event.data.inserted.some(message => message.source.kind === 'team-message' + && messageIds.has(message.source.messageId))).length + await teamFiber.dispose() + await ctx.plugin(TeamService, { maxPendingMessagesPerMember: 1 }) + await vi.waitFor(() => { expect(durable(lead).pendingMessages).toEqual([]) }) + expect(lead.session.events.filter(event => event.type === 'agent/inbox/spliced' + && event.data.inserted.some(message => message.source.kind === 'team-message' + && messageIds.has(message.source.messageId)))).toHaveLength(receiptCount) + + lead.cancel({ kind: 'parent' }) + await lead.whenIdle() + }) + + it('flushes a live pending receipt before acknowledgement without inserting a duplicate', async () => { + const { ctx, lead } = await setup(['hang']) + const started = await spawn(ctx, lead, 'pending-target') + const target = await waitRunning(ctx, started.member.id) + const immediate = await ctx.teams.sendMessage(lead, { + target: 'pending-target', + content: content('live quiet receipt'), + delivery: 'quiet', + signal: SIGNAL, + }) + expect(immediate.status).toBe('accepted') + expect(durable(lead).pendingMessages).toEqual([]) + expect(target.inbox.nextStep.some(item => item.source.kind === 'team-message' + && item.source.messageId === immediate.messageId)).toBe(true) + + const message: TeamMessageSnapshot = { + id: TeamMessageId('live-pending-message'), + senderId: lead.id, + senderName: 'lead', + targetId: target.id, + delivery: 'quiet', + content: content('durable pending receipt'), + } + lead.session.append('team/message/queued', { + version: 1, + teamId: TeamId(lead.id), + message, + }) + await ctx.sessions.flush(lead.session) + target.inject(createUserMessage({ + content: content('durable pending receipt'), + source: { + kind: 'team-message', + teamId: TeamId(lead.id), + messageId: message.id, + senderId: lead.id, + senderName: 'lead', + }, + })) + + const flush = ctx.sessions.flush.bind(ctx.sessions) + const flushed: SessionId[] = [] + const flushSpy = vi.spyOn(ctx.sessions, 'flush').mockImplementation(async (session) => { + flushed.push(session.id) + return flush(session) + }) + const delivered = await teamInternals(ctx).mailbox.tryDispatch(lead, message, SIGNAL) + + expect(delivered).toBe(true) + expect(flushed.slice(0, 2)).toEqual([target.id, lead.id]) + expect(target.inbox.nextStep.filter(item => item.source.kind === 'team-message' + && item.source.messageId === message.id)).toHaveLength(1) + expect(durable(lead).pendingMessages).toEqual([]) + + const disappearing: TeamMessageSnapshot = { + ...message, + id: TeamMessageId('disappearing-pending-message'), + content: content('canceled before checkpoint'), + } + lead.session.append('team/message/queued', { + version: 1, + teamId: TeamId(lead.id), + message: disappearing, + }) + await flush(lead.session) + const disappearingInput = createUserMessage({ + content: content('canceled before checkpoint'), + source: { + kind: 'team-message', + teamId: TeamId(lead.id), + messageId: disappearing.id, + senderId: lead.id, + senderName: 'lead', + }, + }) + target.inject(disappearingInput) + flushSpy.mockImplementationOnce(async (session) => { + target.inbox.remove(disappearingInput.id) + return flush(session) + }) + await expect(teamInternals(ctx).mailbox.tryDispatch(lead, disappearing, SIGNAL)).resolves.toBe(false) + expect(durable(lead).pendingMessages.map(pending => pending.id)).toEqual([disappearing.id]) + + ctx.teams.interrupt(lead, 'pending-target') + target.cancel({ kind: 'parent' }) + await waitNoAgent(ctx, target.id) + }) + + it('acknowledges waking messages accepted by a busy target inbox', async () => { + const { ctx, lead } = await setup(['hang'], { maxPendingMessagesPerMember: 1 }) + const started = await spawn(ctx, lead, 'busy-target') + const target = await waitRunning(ctx, started.member.id) + const flush = ctx.sessions.flush.bind(ctx.sessions) + const flushed: SessionId[] = [] + vi.spyOn(ctx.sessions, 'flush').mockImplementation(async (session) => { + flushed.push(session.id) + return flush(session) + }) + + const first = await ctx.teams.sendMessage(lead, { + target: 'busy-target', content: content('first waking message'), delivery: 'wakeup', signal: SIGNAL, + }) + + expect(first.status).toBe('accepted') + expect(flushed).toEqual([lead.id, target.id, lead.id]) + expect(durable(lead).pendingMessages).toEqual([]) + expect(target.inbox.nextTurn.some(message => message.source.kind === 'team-message' + && message.source.messageId === first.messageId)).toBe(true) + + flushed.length = 0 + const second = await ctx.teams.sendMessage(lead, { + target: 'busy-target', content: content('second waking message'), delivery: 'wakeup', signal: SIGNAL, + }) + + expect(second.status).toBe('accepted') + expect(flushed).toEqual([lead.id, target.id, lead.id]) + expect(durable(lead).pendingMessages).toEqual([]) + expect(target.inbox.nextTurn.filter(message => message.source.kind === 'team-message' + && (message.source.messageId === first.messageId || message.source.messageId === second.messageId))) + .toHaveLength(2) + + ctx.teams.interrupt(lead, 'busy-target') + target.cancel({ kind: 'parent' }) + await waitNoAgent(ctx, target.id) + }) + + it('serializes concurrent waking delivery admission for one target', async () => { + const { ctx, lead } = await setup([textResponse('target initial')]) + const target = await spawn(ctx, lead, 'ordered-target') + await waitNoAgent(ctx, target.member.id) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const admitted: string[] = [] + vi.spyOn(ctx.subagents, 'followup').mockImplementation(async (_parent, _childId, blocks) => { + const last = blocks.at(-1) + const text = last?.type === 'text' ? last.text : '' + admitted.push(text) + if (text === 'first waking') { + entered.resolve(undefined) + await release.promise + } + return createUserMessage({ content: blocks, source: { kind: 'user' } }).id + }) + + const first = ctx.teams.sendMessage(lead, { + target: 'ordered-target', content: content('first waking'), delivery: 'wakeup', signal: SIGNAL, + }) + await entered.promise + let secondSettled = false + const second = ctx.teams.sendMessage(lead, { + target: 'ordered-target', content: content('second waking'), delivery: 'wakeup', signal: SIGNAL, + }).finally(() => { secondSettled = true }) + await new Promise((resolve) => { setTimeout(resolve, 0) }) + expect(admitted).toEqual(['first waking']) + expect(secondSettled).toBe(false) + + release.resolve(undefined) + await expect(Promise.all([first, second])).resolves.toMatchObject([ + { status: 'accepted' }, + { status: 'accepted' }, + ]) + expect(admitted).toEqual(['first waking', 'second waking']) + }) + + it('deduplicates live target history and contains inspection and delivery failures', async () => { + const { ctx, lead } = await setup(['hang', textResponse('inactive target initial')]) + const liveStarted = await spawn(ctx, lead, 'live-target') + const live = await waitRunning(ctx, liveStarted.member.id) + const internal = teamInternals(ctx).mailbox + const message: TeamMessageSnapshot = { + id: TeamMessageId('live-recorded-message'), + senderId: lead.id, + senderName: 'lead', + targetId: live.id, + delivery: 'wakeup', + content: content('already in live history'), + } + lead.session.append('team/message/queued', { + version: 1, teamId: TeamId(lead.id), message, + }) + await ctx.sessions.flush(lead.session) + live.session.append('user/message', createUserMessage({ + content: content('different Team message first'), + source: { + kind: 'team-message', + teamId: TeamId(lead.id), + messageId: TeamMessageId('other-message'), + senderId: lead.id, + senderName: 'lead', + }, + }), { surfaceOp: 'append' }) + live.session.append('user/message', createUserMessage({ + content: content('already in live history'), + source: { + kind: 'team-message', + teamId: TeamId(lead.id), + messageId: message.id, + senderId: lead.id, + senderName: 'lead', + }, + }), { surfaceOp: 'append' }) + await expect(internal.tryDispatch(lead, message, SIGNAL)).resolves.toBe(true) + await internal.markDelivered(lead, message.id, live.id) + + const wrongTarget: TeamMessageSnapshot = { + ...message, + id: TeamMessageId('wrong-target-message'), + } + lead.session.append('team/message/queued', { + version: 1, teamId: TeamId(lead.id), message: wrongTarget, + }) + await ctx.sessions.flush(lead.session) + await internal.markDelivered(lead, wrongTarget.id, SessionId('wrong-target')) + await expect(internal.serializeDispatch(wrongTarget, async () => true)).resolves.toBe(true) + const serialEntered = Promise.withResolvers() + const releaseSerial = Promise.withResolvers() + const serialFirst = internal.serializeDispatch(wrongTarget, async () => { + serialEntered.resolve(undefined) + await releaseSerial.promise + return true + }) + await serialEntered.promise + const serialSecond = internal.serializeDispatch({ + ...wrongTarget, id: TeamMessageId('second-serialized-message'), + }, async () => true) + releaseSerial.resolve(undefined) + await expect(Promise.all([serialFirst, serialSecond])).resolves.toEqual([true, true]) + + const warnings: string[] = [] + ctx.logger.warn = ((value: unknown) => { warnings.push(String(value)) }) as typeof ctx.logger.warn + const failedAck = vi.spyOn(ctx.sessions, 'flush').mockRejectedValueOnce(new Error('acknowledgement flush failed')) + live.session.append('user/message', createUserMessage({ + content: content('acknowledgement failure'), + source: { + kind: 'team-message', + teamId: TeamId(lead.id), + messageId: wrongTarget.id, + senderId: lead.id, + senderName: 'lead', + }, + }), { surfaceOp: 'append' }) + await vi.waitFor(() => { + expect(warnings.some(warning => warning.includes('acknowledgement flush failed'))).toBe(true) + }) + failedAck.mockRestore() + + const inactiveStarted = await spawn(ctx, lead, 'inactive-target') + await waitNoAgent(ctx, inactiveStarted.member.id) + const inspect = vi.spyOn(ctx.sessionPersistence, 'inspect').mockRejectedValueOnce(new Error('inspect unavailable')) + const uncertain = await ctx.teams.sendMessage(lead, { + target: 'inactive-target', content: content('inspection failure'), delivery: 'wakeup', signal: SIGNAL, + }) + expect(uncertain.status).toBe('queued') + inspect.mockRestore() + + vi.spyOn(ctx.subagents, 'followup').mockRejectedValueOnce(new Error('delivery unavailable')) + const failed = await ctx.teams.sendMessage(lead, { + target: 'inactive-target', content: content('delivery failure'), delivery: 'wakeup', signal: SIGNAL, + }) + expect(failed.status).toBe('queued') + expect(warnings.some(warning => warning.includes('inspect unavailable'))).toBe(true) + expect(warnings.some(warning => warning.includes('delivery unavailable'))).toBe(true) + + ctx.teams.interrupt(lead, 'live-target') + await waitNoAgent(ctx, live.id) + }) + + it('keeps quiet mail dormant, wakes on follow-up, preserves FIFO, and de-duplicates delivery', async () => { + const { ctx, lead } = await setup(['hang', textResponse('beta first'), textResponse('beta resumed')]) + const alphaStarted = await spawn(ctx, lead, 'alpha') + const alpha = await waitRunning(ctx, alphaStarted.member.id) + const betaStarted = await spawn(ctx, lead, 'beta') + await waitNoAgent(ctx, betaStarted.member.id) + + const quiet = await ctx.teams.sendMessage(alpha, { + target: 'beta', content: content('quiet info'), delivery: 'quiet', signal: SIGNAL, + }) + expect(quiet.status).toBe('queued') + expect(ctx.agents.get(betaStarted.member.id)).toBeUndefined() + const waking = await ctx.teams.sendMessage(alpha, { + target: 'beta', content: content('do another turn'), delivery: 'wakeup', signal: SIGNAL, + }) + expect(waking.status).toBe('accepted') + await waitNoAgent(ctx, betaStarted.member.id) + await vi.waitFor(() => { expect(durable(lead).pendingMessages).toEqual([]) }) + + const stored = await ctx.sessionPersistence.inspect(betaStarted.member.id) + const peerMessages = stored.events.filter(event => event.type === 'user/message' + && event.data.source.kind === 'team-message') + expect(peerMessages.map((event) => { + if (event.type !== 'user/message') return undefined + const block = event.data.content.at(-1) + return block?.type === 'text' ? block.text : undefined + })).toEqual(['quiet info', 'do another turn']) + expect(peerMessages.map(event => event.type === 'user/message' + ? event.data.content[0]?.type === 'text' && event.data.content[0].text + : undefined)).toEqual([ + expect.stringMatching(/^Team message .* from alpha:$/u), + expect.stringMatching(/^Team message .* from alpha:$/u), + ]) + expect(peerMessages.map(event => event.type === 'user/message' && event.data.source.kind === 'team-message' + ? [event.data.source.messageId, event.data.source.senderName] + : undefined)).toEqual([ + [quiet.messageId, 'alpha'], + [waking.messageId, 'alpha'], + ]) + + ctx.teams.interrupt(lead, 'alpha') + await waitNoAgent(ctx, alpha.id) + }) + + it('enforces message byte and pending-count limits without encouraging retry after enqueue', async () => { + const { ctx, lead } = await setup([textResponse('idle')], { + maxMessageBytes: 256, + maxPendingMessagesPerMember: 1, + }) + const target = await spawn(ctx, lead, 'target') + await waitNoAgent(ctx, target.member.id) + await expect(ctx.teams.sendMessage(lead, { + target: 'target', content: content('x'.repeat(300)), delivery: 'quiet', signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_MESSAGE_TOO_LARGE' }) + const queued = await ctx.teams.sendMessage(lead, { + target: 'target', content: content('one'), delivery: 'quiet', signal: SIGNAL, + }) + expect(queued.status).toBe('queued') + await expect(ctx.teams.sendMessage(lead, { + target: 'target', content: content('two'), delivery: 'quiet', signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_MAILBOX_FULL' }) + await expect(ctx.teams.sendMessage(lead, { + target: 'lead', content: content('self'), delivery: 'quiet', signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_SELF_MESSAGE' }) + await expect(ctx.teams.sendMessage(lead, { + target: 'missing', content: content('unknown target'), delivery: 'quiet', signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_MEMBER_NOT_FOUND' }) + const controller = new AbortController() + controller.abort(new TeamError('cancelled before queue', 'TEST_CANCELLED')) + await expect(ctx.teams.sendMessage(lead, { + target: 'target', content: content('cancelled'), delivery: 'quiet', signal: controller.signal, + })).rejects.toMatchObject({ code: 'TEST_CANCELLED' }) + }) + + it('interrupts only the current turn and retains an already accepted follow-up', async () => { + const { ctx, lead } = await setup(['hang', textResponse('after interrupt')]) + const started = await spawn(ctx, lead, 'worker') + const worker = await waitRunning(ctx, started.member.id) + const followup = await ctx.teams.sendMessage(lead, { + target: 'worker', content: content('retained follow-up'), delivery: 'wakeup', signal: SIGNAL, + }) + expect(followup.status).toBe('accepted') + expect(ctx.teams.interrupt(lead, 'worker')).toEqual({ previousStatus: 'running' }) + await vi.waitFor(() => { expect(worker.status).toBe('idle') }) + expect(worker.inbox.nextTurn.some(message => message.source.kind === 'team-message' + && message.source.messageId === followup.messageId)).toBe(true) + worker.cancel({ kind: 'parent' }) + await waitNoAgent(ctx, worker.id) + }) + + it('waits for one change, supports cancellation, times out, and releases waiters on HMR disposal', async () => { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-wait-')) + roots.push(storageRoot) + await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(SubagentService) + const fiber = await ctx.plugin(TeamService) + const service = ctx.teams + const lead = ctx.agentLoop.create(SessionId('wait-lead'), {}) + + await expect(service.waitForChange(lead, 9_999, SIGNAL)) + .rejects.toMatchObject({ code: 'TEAM_INVALID_TIMEOUT' }) + const alreadyAborted = new AbortController() + alreadyAborted.abort(new TeamError('cancelled before wait', 'TEST_CANCELLED')) + await expect(service.waitForChange(lead, 10_000, alreadyAborted.signal)) + .rejects.toMatchObject({ code: 'TEST_CANCELLED' }) + + const changed = service.waitForChange(lead, 10_000, SIGNAL) + const flush = ctx.sessions.flush.bind(ctx.sessions) + const flushEntered = Promise.withResolvers() + const releaseFlush = Promise.withResolvers() + vi.spyOn(ctx.sessions, 'flush').mockImplementationOnce(async (session) => { + flushEntered.resolve(undefined) + await releaseFlush.promise + return await flush(session) + }) + let waitSettled = false + void changed.finally(() => { waitSettled = true }) + const creating = service.createTask(lead, { subject: 'wake', description: 'wake waiter' }) + await flushEntered.promise + expect(waitSettled).toBe(false) + releaseFlush.resolve(undefined) + await creating + await expect(changed).resolves.toEqual({ timedOut: false }) + + const controller = new AbortController() + const cancelled = service.waitForChange(lead, 10_000, controller.signal) + controller.abort(new TeamError('cancelled', 'TEST_CANCELLED')) + await expect(cancelled).rejects.toMatchObject({ code: 'TEST_CANCELLED' }) + + const stringAbort = new AbortController() + const firstWaiter = service.waitForChange(lead, 10_000, stringAbort.signal) + const secondWaiter = service.waitForChange(lead, 10_000, SIGNAL) + stringAbort.abort('string cancellation') + await expect(firstWaiter).rejects.toMatchObject({ + code: 'TEAM_WAIT_ABORTED', + message: 'wait_agent aborted: string cancellation', + }) + await service.createTask(lead, { subject: 'second waiter', description: 'second waiter remains registered' }) + await expect(secondWaiter).resolves.toEqual({ timedOut: false }) + + const objectAbort = new AbortController() + const objectCancelled = service.waitForChange(lead, 10_000, objectAbort.signal) + objectAbort.abort({ kind: 'user' }) + await expect(objectCancelled).rejects.toMatchObject({ + code: 'TEAM_WAIT_ABORTED', + message: "wait_agent aborted: { kind: 'user' }", + }) + + await service.createTask(lead, { subject: 'already changed', description: 'edge-triggered wait' }) + vi.useFakeTimers() + const timeout = service.waitForChange(lead, 10_000, SIGNAL) + await vi.advanceTimersByTimeAsync(10_000) + await expect(timeout).resolves.toEqual({ timedOut: true }) + vi.useRealTimers() + + const disposed = service.waitForChange(lead, 10_000, SIGNAL) + await fiber.dispose() + await expect(disposed).resolves.toEqual({ timedOut: false }) + expect(ctx.get('teams')).toBeUndefined() + }) + + it('disposes live teammate Activations and their waits when the Team service unloads', async () => { + const { ctx, lead, teamFiber } = await setup(['hang']) + const started = await spawn(ctx, lead, 'dispose-worker') + await waitRunning(ctx, started.member.id) + const waiting = ctx.teams.waitForChange(lead, 10_000, SIGNAL) + + await teamFiber.dispose() + + await expect(waiting).resolves.toEqual({ timedOut: false }) + expect(ctx.agents.get(started.member.id)).toBeUndefined() + expect(ctx.get('teams')).toBeUndefined() + }) + + it('closes creation admission and drains an in-flight spawn before unload completes', async () => { + const { ctx, lead, teamFiber } = await setup(['hang']) + const service = ctx.teams + const start = ctx.subagents.startContinuable.bind(ctx.subagents) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + let childId: SessionId | undefined + vi.spyOn(ctx.subagents, 'startContinuable').mockImplementation(async (spec) => { + childId = spec.childId + entered.resolve(undefined) + await release.promise + return start(spec) + }) + const spawning = spawn(ctx, lead, 'disposing-worker') + const rejected = expect(spawning).rejects.toMatchObject({ code: 'TEAM_DISPOSED' }) + await entered.promise + + const disposal = teamFiber.dispose() + await Promise.resolve() + await expect(service.waitForChange(lead, 3_600_000, SIGNAL)).resolves.toEqual({ timedOut: false }) + await expect(service.spawnTeammate(lead, { + name: 'late-worker', + description: 'must not enter after disposal', + prompt: content('late task'), + context: 'fresh', + provider: 'spawn', + signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_DISPOSED' }) + release.resolve(undefined) + + await rejected + await disposal + if (childId !== undefined) expect(ctx.agents.get(childId)).toBeUndefined() + expect(ctx.get('teams')).toBeUndefined() + }) + + it('retains an in-flight creation cleanup failure during disposal', async () => { + const { ctx } = await setup([]) + const internal = teamInternals(ctx) + const cleanupFailure = new Error('creation cleanup failed') + const rejected = Promise.reject(cleanupFailure) + void rejected.catch(() => undefined) + internal.roster.inFlightCreations.add(rejected) + + await expect(internal.disposeRuntime()).rejects.toMatchObject({ errors: [cleanupFailure] }) + }) + + it('recognizes wrapped and coded runtime cancellation during disposal settlement', async () => { + const open = new TeamRuntimeLifecycle(100) + const ordinaryFailure = new Error('ordinary failure before disposal') + const openFailures: unknown[] = [] + await open.settle([Promise.reject(ordinaryFailure)], openFailures) + expect(openFailures).toEqual([ordinaryFailure]) + + const lifecycle = new TeamRuntimeLifecycle(100) + lifecycle.close() + const failures: unknown[] = [] + await lifecycle.settle([ + Promise.reject(new Error('wrapped cancellation', { cause: lifecycle.reason })), + Promise.reject(new TeamError('translated cancellation', 'TEAM_DISPOSED')), + ], failures) + expect(failures).toEqual([]) + + const cyclic = new Error('unrelated cyclic failure') + cyclic.cause = cyclic + await lifecycle.settle([Promise.reject(cyclic)], failures) + expect(failures).toEqual([cyclic]) + }) + + it('disposes a live child even after its durable member edge becomes failed', async () => { + const { ctx, lead } = await setup(['hang']) + const childId = SessionId('failed-live-child') + const member = { + id: childId, + name: 'failed-live-worker', + description: 'failed-live-worker responsibility', + provider: 'spawn', + context: 'fresh' as const, + phase: 'provisioning' as const, + } + lead.session.append('team/member', { + version: 1, + teamId: TeamId(lead.id), + member, + }) + await ctx.subagents.startContinuable({ + childId, + provider: 'spawn', + label: member.description, + request: { prompt: content('failed child task'), parent: lead }, + signal: SIGNAL, + }) + await waitRunning(ctx, childId) + lead.session.append('team/member', { + version: 1, + teamId: TeamId(lead.id), + member: { + ...member, + phase: 'failed', + error: 'creation cleanup is pending', + }, + }) + await ctx.sessions.flush(lead.session) + expect(ctx.teams.listMembers(lead)[1]?.status).toBe('failed') + + const internal = ctx.teams as unknown as { disposeRuntime(): Promise } + await internal.disposeRuntime() + expect(ctx.agents.get(childId)).toBeUndefined() + }) + + it('aborts and awaits an admitted cold mailbox dispatch during disposal', async () => { + const { ctx, lead } = await setup([textResponse('worker done')]) + const started = await spawn(ctx, lead, 'mailbox-worker') + await waitNoAgent(ctx, started.member.id) + const entered = Promise.withResolvers() + const aborted = Promise.withResolvers() + const release = Promise.withResolvers() + vi.spyOn(ctx.subagents, 'followup').mockImplementation(async (_parent, _childId, _content, options) => { + entered.resolve(undefined) + return await new Promise((_resolve, reject) => { + options.signal.addEventListener('abort', () => { + aborted.resolve(undefined) + void release.promise.then(() => { + const reason: unknown = options.signal.reason + reject(reason instanceof Error ? reason : new Error(String(reason))) + }) + }, { once: true }) + }) + }) + + const sending = ctx.teams.sendMessage(lead, { + target: 'mailbox-worker', + content: content('resume during disposal'), + delivery: 'wakeup', + signal: SIGNAL, + }) + await entered.promise + const internal = ctx.teams as unknown as { disposeRuntime(): Promise } + let disposed = false + const disposal = internal.disposeRuntime().then(() => { disposed = true }) + await aborted.promise + await Promise.resolve() + expect(disposed).toBe(false) + release.resolve(undefined) + + await expect(sending).resolves.toMatchObject({ status: 'queued' }) + await disposal + expect(disposed).toBe(true) + expect(ctx.agents.get(started.member.id)).toBeUndefined() + }) + + it('awaits an admitted asynchronous acknowledgement before disposal completes', async () => { + const { ctx, lead } = await setup([]) + const message: TeamMessageSnapshot = { + id: TeamMessageId('dispose-ack-message'), + senderId: SessionId('sender'), + senderName: 'sender', + targetId: lead.id, + delivery: 'wakeup', + content: content('acknowledge before disposal'), + } + lead.session.append('team/message/queued', { + version: 1, + teamId: TeamId(lead.id), + message, + }) + await ctx.sessions.flush(lead.session) + + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const flush = ctx.sessions.flush.bind(ctx.sessions) + let blockReceipt = true + const flushSpy = vi.spyOn(ctx.sessions, 'flush').mockImplementation(async (session) => { + if (blockReceipt && session === lead.session) { + blockReceipt = false + entered.resolve(undefined) + await release.promise + } + return flush(session) + }) + lead.session.append('user/message', createUserMessage({ + content: content('acknowledge before disposal'), + source: { + kind: 'team-message', + teamId: TeamId(lead.id), + messageId: message.id, + senderId: message.senderId, + senderName: message.senderName, + }, + }), { surfaceOp: 'append' }) + + const internal = ctx.teams as unknown as { disposeRuntime(): Promise } + let disposed = false + const disposal = internal.disposeRuntime().then(() => { disposed = true }) + await entered.promise + await Promise.resolve() + const disposedBeforeRelease = disposed + release.resolve(undefined) + await disposal + + expect(disposedBeforeRelease).toBe(false) + expect(disposed).toBe(true) + expect(durable(lead).pendingMessages).toEqual([]) + flushSpy.mockRestore() + }) + + it('bounds Team runtime disposal when a continuation drain never settles', async () => { + const { ctx, lead, teamFiber } = await setup(['hang'], { disposalTimeoutMs: 25 }) + const started = await spawn(ctx, lead, 'stuck-worker') + await waitRunning(ctx, started.member.id) + const drain = vi.spyOn(ctx.subagents, 'drainContinuableChildren') + .mockImplementation(() => new Promise(() => {})) + + const outcome = await Promise.race([ + teamFiber.dispose().then(() => 'disposed'), + new Promise<'hung'>((resolve) => { setTimeout(() => { resolve('hung') }, 1_000) }), + ]) + expect(outcome).toBe('disposed') + expect(drain).toHaveBeenCalledWith(lead, [started.member.id]) + expect(ctx.get('teams')).toBeUndefined() + }) + + it('bounds disposal while an admitted creation ignores cancellation', async () => { + const { ctx, lead } = await setup([], { disposalTimeoutMs: 25 }) + const internal = teamInternals(ctx) + internal.roster.inFlightCreations.add(new Promise(() => {})) + + await expect(internal.disposeRuntime()).rejects.toBeInstanceOf(AggregateError) + await expect(ctx.teams.spawnTeammate(lead, { + name: 'after-timeout', + description: 'admission remains closed', + prompt: content('must reject'), + context: 'fresh', + provider: 'spawn', + signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_DISPOSED' }) + await expect(ctx.teams.sendMessage(lead, { + target: 'nobody', content: content('must reject'), delivery: 'quiet', signal: SIGNAL, + })).rejects.toMatchObject({ code: 'TEAM_DISPOSED' }) + await expect(internal.mailbox.tryDispatch(lead, { + id: TeamMessageId('post-disposal-message'), + senderId: lead.id, + senderName: 'lead', + targetId: lead.id, + delivery: 'quiet', + content: content('must not dispatch'), + }, SIGNAL)).resolves.toBe(false) + }) + + it('contains recovery callback failures and ignores work scheduled after disposal', async () => { + const { ctx, lead, teamFiber } = await setup([]) + const warnings: string[] = [] + ctx.logger.warn = ((value: unknown) => { warnings.push(String(value)) }) as typeof ctx.logger.warn + const internal = teamInternals(ctx) + internal.recoverFor = async () => { throw new Error('forced recovery failure') } + internal.scheduleRecovery(lead) + await Promise.resolve() + await Promise.resolve() + expect(warnings.some(warning => warning.includes('forced recovery failure'))).toBe(true) + + lead.session.append('user/message', createUserMessage({ + content: content('orphan Team source'), + source: { + kind: 'team-message', + teamId: TeamId('absent-team'), + messageId: TeamMessageId('absent-team-message'), + senderId: SessionId('absent-sender'), + senderName: 'absent', + }, + }), { surfaceOp: 'append' }) + await Promise.resolve() + + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + internal.recoverFor = async () => { + entered.resolve(undefined) + await release.promise + throw new Error('failure after disposal') + } + internal.scheduleRecovery(lead) + await entered.promise + await teamFiber.dispose() + release.resolve(undefined) + await Promise.resolve() + await Promise.resolve() + internal.scheduleRecovery(lead) + await Promise.resolve() + }) + + it('reports contained teardown failures without retaining the Team service', async () => { + const { ctx, lead, teamFiber } = await setup(['hang']) + const started = await spawn(ctx, lead, 'failing-drain') + await waitRunning(ctx, started.member.id) + vi.spyOn(ctx.subagents, 'drainContinuableDescendants').mockRejectedValueOnce(new Error('drain failure')) + + await teamFiber.dispose() + expect(ctx.get('teams')).toBeUndefined() + }) + + it('reconciles mismatched persisted children and ignores a concurrently settled member', async () => { + const first = await setup([]) + const liveId = SessionId('live-provisioning-child') + const live = await first.ctx.agents.create({ + sessionId: liveId, + meta: { parentSession: first.lead.id }, + agentOptions: { provider: 'mock', model: 'mock' }, + }) + const provisioning = { + id: liveId, + name: 'mismatched-child', + description: 'mismatched persisted child', + provider: 'spawn', + context: 'fresh' as const, + phase: 'provisioning' as const, + } + first.lead.session.append('team/member', { + version: 1, teamId: TeamId(first.lead.id), member: provisioning, + }) + const reconcileFirst = teamInternals(first.ctx).roster + await reconcileFirst.reconcileProvisioning(first.lead, SIGNAL) + expect(durable(first.lead).members[0]?.phase).toBe('provisioning') + live.agent.session.append('user/message', createUserMessage({ + content: content('persist mismatched child'), source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + await first.ctx.sessions.flush(live.agent.session) + await live.dispose() + await reconcileFirst.reconcileProvisioning(first.lead, SIGNAL) + expect(durable(first.lead).members[0]).toMatchObject({ + phase: 'failed', + error: 'persisted child Session does not match the provisioned continuation', + }) + + const second = await setup([]) + const childId = SessionId('concurrently-settled-child') + const member = { ...provisioning, id: childId, name: 'concurrent-child' } + second.lead.session.append('team/member', { + version: 1, teamId: TeamId(second.lead.id), member, + }) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + vi.spyOn(second.ctx.sessionPersistence, 'inspect').mockImplementationOnce(async () => { + entered.resolve(undefined) + await release.promise + throw new Error('late inspection failure') + }) + const reconcileSecond = teamInternals(second.ctx).roster + const reconciling = reconcileSecond.reconcileProvisioning(second.lead, SIGNAL) + await entered.promise + second.lead.session.append('team/member', { + version: 1, + teamId: TeamId(second.lead.id), + member: { ...member, phase: 'failed', error: 'settled elsewhere' }, + }) + release.resolve(undefined) + await reconciling + expect(durable(second.lead).members[0]).toMatchObject({ + phase: 'failed', error: 'settled elsewhere', + }) + }) +}) diff --git a/packages/experimental/team/tsconfig.json b/packages/experimental/team/tsconfig.json new file mode 100644 index 0000000000..d0defa8242 --- /dev/null +++ b/packages/experimental/team/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cosmokit" }, + { "path": "../../../vendor/schemastery" }, + { "path": "../../../vendor/cordis" }, + { "path": "../../util/brand" }, + { "path": "../../llm/llm" }, + { "path": "../../core/session" }, + { "path": "../../core/agent" }, + { "path": "../../subagent/subagent" }, + { "path": "../../session/session-persistence" }, + { "path": "../../runtime-diagnostics/invariants" } + ] +} diff --git a/packages/experimental/team/tsdown.config.ts b/packages/experimental/team/tsdown.config.ts new file mode 100644 index 0000000000..e630b728b4 --- /dev/null +++ b/packages/experimental/team/tsdown.config.ts @@ -0,0 +1,25 @@ +import { defineConfig } from 'tsdown' + +/** Build the runtime and invariant as independent bundles so shared fold code stays package-local. */ +export default defineConfig([ + { + entry: ['lib/types/index.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + }, + { + entry: ['lib/types/invariant.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + }, +]) diff --git a/packages/experimental/tool-team/README.i18n.yaml b/packages/experimental/tool-team/README.i18n.yaml new file mode 100644 index 0000000000..9a4a8a211e --- /dev/null +++ b/packages/experimental/tool-team/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/experimental/tool-team/README.md +README.md: 1c0b2b4393be25f00af2f6b179ab4f925f9a1763 +README.zh.md: 8ddfebd17eb8f1a7a5cebeebab5ad4a47e091a41 diff --git a/packages/experimental/tool-team/README.md b/packages/experimental/tool-team/README.md new file mode 100644 index 0000000000..1c0b2b4393 --- /dev/null +++ b/packages/experimental/tool-team/README.md @@ -0,0 +1,49 @@ +# @deepseek-ai/dsh-tool-team + +English | [中文](README.zh.md) + +Scoped model-facing adapter for [`ctx.teams`](../team/README.md). It installs the Agent Teams policy and collaboration tools in each implicit Lead and durable teammate scope. Scoped Team definitions shadow same-named legacy global continuable-subagent controls, so a composition that mounts both must disable the legacy definitions. + +## Config + +```yaml +- id: tool-team + name: '@deepseek-ai/dsh-tool-team' + config: + freshProvider: spawn + forkProvider: fork +``` + +`freshProvider` and `forkProvider` select registered continuable-subagent providers. The fixed model policy creates teammates only when the user explicitly asks for Agent Teams or teammates. + +## Tools and authority + +The generated [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-team) owns exact schemas. The adapter supplies teammate creation; quiet and waking peer delivery; roster listing, waiting, and Lead-only interruption; and task create/list/get/compare-and-set update operations. + +Every tool requires the exact calling `Agent`. `spawn_teammate` and `interrupt_agent` enforce Lead authority inside `ctx.teams`, not only in their descriptions. All members can communicate with any peer and use the task board. Task mutations retain the domain's owner/Lead and revision checks. + +`send_message` succeeds once mail is durable and never wakes an inactive target. `followup_task` also makes the message the target's next turn and can cold-resume it. A `queued` result is accepted durable work and must not be retried. Task readiness does not start an owner. Before arming its 10,000-through-3,600,000-millisecond edge wait, `wait_agent` checks for another member that is running or provisioning; without one it returns `noProgress` immediately with instructions to re-list and use `followup_task`. Otherwise it waits for one post-call Team edge, defaulting to 30,000 milliseconds, and callers re-list after wakeup or timeout because earlier changes are not replayed. + +The plugin listens to Agent publication and installs its registrations through that Agent's scope. Fresh creation and cold resume therefore receive the same tool/prompt set before the first model request. Agent disposal and plugin HMR remove every scoped registration; reloading the plugin installs one fresh set in each still-live member without changing its continuation Activation. + +## Model Experience + +### Team policy and tools + +#### What the model sees + +One stable policy section states the exact Team role/name/id, explicit-delegation requirement, shared-cwd behavior, filesystem stale-version recovery, Bash/formatter/codegen risk, task/write-scope coordination, quiet versus waking delivery, no-retry mailbox rule, and the Lead's duty to wait before answering. The ten Team schemas from `spawn_teammate` through `team_task_update` appear only in Team member scopes. + +#### Token effect + +Fixed policy and schema cost on every Team member request. Tool calls add compact JSON roster, task, wait, or receipt results. Peer content is retained by the Team domain in the target's history. + +#### KV Cache effect + +Prefix-stable while the Team plugin generation, configuration, member role/name, and schemas remain unchanged. The per-member identity line differs across Agents. Tool results and peer messages append after the reusable request prefix. + +## Known Limitations and Deferred Work + +- **Prompt policy is coordination, not confinement** — it cannot stop Bash or external processes from writing overlapping files. +- **No autonomous team creation** — ordinary tasks do not trigger delegation unless the user explicitly requests it. +- **No Web controls** — browser roster and task-board presentation is outside this runtime package. diff --git a/packages/experimental/tool-team/README.zh.md b/packages/experimental/tool-team/README.zh.md new file mode 100644 index 0000000000..8ddfebd17e --- /dev/null +++ b/packages/experimental/tool-team/README.zh.md @@ -0,0 +1,49 @@ +# @deepseek-ai/dsh-tool-team + +[English](README.md) | 中文 + +[`ctx.teams`](../team/README.md) 的 scoped 模型适配器。它会在每个隐式 Lead 与持久 teammate scope 中安装 Agent Teams 策略和协作工具。scoped Team 定义会覆盖同名的旧全局 continuable-subagent control,因此同时挂载两者的组合必须禁用旧定义。 + +## 配置 + +```yaml +- id: tool-team + name: '@deepseek-ai/dsh-tool-team' + config: + freshProvider: spawn + forkProvider: fork +``` + +`freshProvider` 与 `forkProvider` 选择已注册的 continuable-subagent provider。固定模型策略仅在用户明确要求 Agent Teams 或 teammate 时创建 teammate。 + +## 工具与权限 + +生成的[工具目录](../../../docs/tool-catalog.md#deepseek-aidsh-tool-team)负责精确 schema。该适配器提供 teammate 创建;quiet 与 waking peer 投递;roster 列表、等待和仅限 Lead 的 interrupt;以及任务 create/list/get/CAS update 操作。 + +每个工具都要求完全相同的调用 `Agent`。`spawn_teammate` 与 `interrupt_agent` 在 `ctx.teams` 内部强制执行 Lead 权限,而不只依赖描述。所有成员都可以与任意 peer 通讯并使用任务板。任务变更保留领域层的 Owner/Lead 与 revision 校验。 + +`send_message` 在 mail 持久化后即成功,并且绝不会唤醒 inactive target。`followup_task` 还会让该消息成为 target 的下一个 turn,并可冷恢复 target。`queued` 结果表示持久工作已经接受,不能重试。任务 ready 不会启动 owner。`wait_agent` 在注册 10,000 到 3,600,000 毫秒的边等待前,会检查是否有另一个 running 或 provisioning member;如果没有,它会立即返回 `noProgress`,提示重新 list 并使用 `followup_task`。否则它会等待调用后发生的一条 Team 边,默认 30,000 毫秒;由于不会回放更早的变化,调用方需要在唤醒或超时后重新 list。 + +插件监听 Agent publication,并通过对应 Agent scope 安装注册。因此,fresh 创建与 cold resume 都会在第一次模型请求前获得相同工具/提示词集合。Agent dispose 和插件 HMR 会移除全部 scoped 注册;重新加载插件会为仍 live 的每个成员安装一套新注册,而不改变 continuation Activation。 + +## 模型体验 + +### Team 策略与工具 + +#### 模型看到的内容 + +一段稳定策略会说明确切 Team role/name/id、显式 delegation 要求、共享 cwd 行为、文件 stale-version 恢复、Bash/formatter/codegen 风险、task/write-scope 协调、quiet 与 waking 投递区别、mailbox 不重试规则,以及 Lead 必须在回答前等待。`spawn_teammate` 到 `team_task_update` 的 10 个 Team schema 只出现在 Team member scope。 + +#### Token 影响 + +每次 Team member 请求都有固定策略与 schema 成本。工具调用会增加紧凑 JSON roster、task、wait 或 receipt 结果。Peer 内容由 Team 领域保留在 target 历史中。 + +#### KV Cache 影响 + +Team 插件 generation、配置、member role/name 与 schema 不变时,前缀保持稳定。每个成员的身份行不同。工具结果与 peer 消息追加在可复用请求前缀之后。 + +## 已知限制与暂缓事项 + +- **提示词策略只负责协调,不负责 confinement**:它无法阻止 Bash 或外部进程写入重叠文件。 +- **不会自主创建 Team**:除非用户明确要求 delegation,普通任务不会触发组队。 +- **没有 Web 控制功能**:浏览器 roster 与任务板呈现不属于该 runtime 包。 diff --git a/packages/experimental/tool-team/package.json b/packages/experimental/tool-team/package.json new file mode 100644 index 0000000000..3aa6c766e2 --- /dev/null +++ b/packages/experimental/tool-team/package.json @@ -0,0 +1,61 @@ +{ + "name": "@deepseek-ai/dsh-tool-team", + "description": "Scoped model-facing Agent Teams tools over ctx.teams", + "version": "0.1.0-rc.7", + "private": true, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/experimental/tool-team" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "@deepseek-ai/schemastery": "workspace:^" + }, + "peerDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-team": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-scope": "workspace:^", + "@deepseek-ai/dsh-subagent": "workspace:^", + "@deepseek-ai/dsh-subagent-fork-in-process": "workspace:^", + "@deepseek-ai/dsh-subagent-spawn-in-process": "workspace:^", + "@deepseek-ai/dsh-tool-subagent-control": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-team": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + } +} diff --git a/packages/experimental/tool-team/src/index.ts b/packages/experimental/tool-team/src/index.ts new file mode 100644 index 0000000000..0e35b85337 --- /dev/null +++ b/packages/experimental/tool-team/src/index.ts @@ -0,0 +1,418 @@ +/** Scoped model-facing tools for the opt-in Agent Teams runtime. */ + +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { TeamTaskId } from '@deepseek-ai/dsh-team' +import type { TeamMemberView } from '@deepseek-ai/dsh-team' +import { defineTool } from '@deepseek-ai/dsh-tools' +import type { InferValue, ValueSchemaSpec } from '@deepseek-ai/dsh-tools' + +/** Cordis plugin name. */ +export const name = 'tool-team' +/** Services required by the Team tool plugin. */ +export const inject = ['agents', 'teams', 'tools', 'systemPrompt'] + +/** Tool routing configuration. */ +export interface Config { + /** Continuable-subagent provider used for fresh teammates. */ + readonly freshProvider?: string + /** Continuable-subagent provider used for completed-prefix fork teammates. */ + readonly forkProvider?: string +} + +/** Loader schema for the opt-in Team tool plugin. */ +export const Config: z = z.object({ + freshProvider: z.string().default('spawn'), + forkProvider: z.string().default('fork'), +}) + +/** Model-facing collaboration guidance shared by Lead and teammates. */ +const POLICY = `Agent Teams is available in this session, but create teammates only when the user explicitly asks to use Agent Teams or teammates. + +The Team Lead and all teammates share the same working directory and filesystem. Edits are immediately visible to every member. Split write work into disjoint scopes, record expected write scopes on shared tasks, and use task dependencies when work must be ordered. Write-scope overlap is advisory, not a lock. + +Prefer read/edit/write for file changes. If a file operation returns FS_STALE_VERSION, read the current file, rebase your intended change onto the new content, and retry. Bash, formatters, code generators, and scripts are not fully protected by the filesystem version guard; coordinate them explicitly and have the Lead review the final diff and run tests. + +Use send_message for quiet information that must not start an idle teammate. Use followup_task when the target should run another turn. A delivered peer item starts with its stable message id and sender name. A successful send is already durable even when its result says queued; do not resend it. Shared-task workflow is list, get, claim with the current revision, perform the work, then complete. Task readiness never starts an owner. Before wait_agent, use list_agents and make sure another required member is running or provisioning; use followup_task first when the required member is inactive. wait_agent observes only changes after that call starts, never wakes a member, and returns noProgress immediately when no other member can produce a change. Re-list after wakeup or timeout. The Lead must wait for required teammates before giving the final answer.` + +const ACTIVE_WAIT_STATUSES: ReadonlySet = new Set(['running', 'provisioning']) +const NO_ACTIVE_PEER_MESSAGE = 'No other Team member is running or provisioning. wait_agent cannot make progress or wake inactive teammates. Re-list with list_agents and team_task_list, then use followup_task to wake each required inactive teammate before waiting again.' + +/** + * One roster row, matching `TeamMemberView`. The Lead pseudo-row omits the + * teammate-only provisioning fields, so only identity, role, status, and + * diagnostics are required. + */ +const MEMBER_VIEW_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + id: { type: 'string', required: true }, + name: { type: 'string', required: true }, + role: { type: 'string', required: true, enum: ['lead', 'teammate'] }, + status: { type: 'string', required: true, enum: ['running', 'idle', 'inactive', 'provisioning', 'failed'] }, + description: { type: 'string' }, + provider: { type: 'string' }, + context: { type: 'string', enum: ['fresh', 'fork'] }, + model: { type: 'string' }, + diagnostics: { type: 'array', required: true, items: { type: 'string' } }, + }, +} as const + +/** One shared task, matching the public `TeamTaskView`. */ +const TASK_VIEW_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + id: { type: 'string', required: true }, + revision: { type: 'integer', required: true }, + subject: { type: 'string', required: true }, + description: { type: 'string', required: true }, + status: { type: 'string', required: true, enum: ['pending', 'in_progress', 'completed', 'deleted'] }, + ownerName: { type: 'string' }, + blockedBy: { type: 'array', required: true, items: { type: 'string' } }, + writeScopes: { type: 'array', required: true, items: { type: 'string' } }, + ready: { type: 'boolean', required: true }, + writeScopeWarnings: { type: 'array', required: true, items: { type: 'string' } }, + }, +} as const + +const SPAWN_VALUE_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + member: { ...MEMBER_VIEW_SCHEMA, required: true }, + }, +} as const + +const MEMBER_LIST_VALUE_SCHEMA = { type: 'array', items: MEMBER_VIEW_SCHEMA } as const + +const SEND_VALUE_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + messageId: { type: 'string', required: true }, + status: { type: 'string', required: true, enum: ['accepted', 'queued'] }, + }, +} as const + +/** `noProgress` is present only on the model-only shortcut that skips the wait. */ +const WAIT_VALUE_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + timedOut: { type: 'boolean', required: true }, + noProgress: { + type: 'object', + additionalProperties: false, + properties: { + reason: { type: 'string', required: true, const: 'no-active-peer' }, + message: { type: 'string', required: true }, + }, + }, + }, +} as const + +const INTERRUPT_VALUE_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + previousStatus: { type: 'string', required: true, enum: ['running', 'idle', 'inactive'] }, + }, +} as const + +const TASK_LIST_VALUE_SCHEMA = { + type: 'object', + additionalProperties: false, + properties: { + tasks: { type: 'array', required: true, items: TASK_VIEW_SCHEMA }, + nextCursor: { type: 'integer' }, + }, +} as const + +/** + * Declare one canonical output schema with compact model-facing JSON. Every + * Team result is a fixed record, so the declared schema is what makes the + * compiler check `execute` against the value the model is promised. + * @param schema - canonical value schema for one tool. + * @returns the `output` declaration accepted by {@link defineTool}. + */ +function jsonOutput(schema: S): { + schema: S + render: (args: unknown, value: InferValue) => [{ type: 'text'; text: string }] +} { + return { + schema, + render: (_args: unknown, value: InferValue) => [{ type: 'text', text: JSON.stringify(value) }], + } +} + +/** Recover the exact caller guaranteed by Agent-scoped tool discovery. */ +function callingAgent(agent: Agent | undefined, toolName: string): Agent { + /* v8 ignore next 2 -- Team tools are registered only in an exact Agent scope, so discovery supplies this carrier. */ + if (agent === undefined) throw new Error(`${toolName} requires a calling Agent`) + return agent +} + +/** Register the complete Team tool set in one exact Agent scope. */ +function install(agent: Agent, ctx: Context, config: Required): () => void { + const scoped = agent.ctx + const disposers: Array<() => unknown> = [] + const register = (disposer: () => unknown): void => { disposers.push(disposer) } + try { + register(scoped.systemPrompt.section({ + name: 'team:policy', + order: 60, + text: () => { + const membership = ctx.teams.membership(agent) + return `${POLICY}\n\nYour Team role is ${membership.role}; your Team name is ${membership.name}; Team id is ${membership.id}.` + }, + })) + + register(scoped.tools.register(defineTool({ + name: 'spawn_teammate', + description: 'Create one named, durable teammate. Only the Team Lead may call this tool.', + parameters: { + name: { type: 'string', required: true, description: 'Unique lower-kebab-case teammate name.' }, + description: { type: 'string', required: true, description: 'Short description of the delegated responsibility.' }, + prompt: { type: 'string', required: true, description: 'Complete initial task for the teammate.' }, + context: { + type: 'string', + enum: ['fresh', 'fork'], + description: 'fresh starts without Lead history; fork inherits completed Lead turns. Defaults to fresh.', + }, + }, + output: jsonOutput(SPAWN_VALUE_SCHEMA), + async execute(args, exec) { + const agent = callingAgent(exec.agent, 'spawn_teammate') + const context = args.context ?? 'fresh' + return await ctx.teams.spawnTeammate(agent, { + name: args.name, + description: args.description, + prompt: [{ type: 'text', text: args.prompt }], + context, + provider: context === 'fork' ? config.forkProvider : config.freshProvider, + signal: exec.signal, + }) + }, + }))) + + const messageTool = (toolName: 'send_message' | 'followup_task', delivery: 'quiet' | 'wakeup'): void => { + register(scoped.tools.register(defineTool({ + name: toolName, + description: delivery === 'quiet' + ? 'Send durable information to another Team member without starting an idle member.' + : 'Send a durable follow-up task to another Team member and start a turn when needed.', + parameters: { + target: { type: 'string', required: true, description: 'Team member name, or lead.' }, + message: { type: 'string', required: true, description: 'Self-contained message for the target.' }, + }, + output: jsonOutput(SEND_VALUE_SCHEMA), + execute(args, exec) { + return ctx.teams.sendMessage(callingAgent(exec.agent, toolName), { + target: args.target, + content: [{ type: 'text', text: args.message }], + delivery, + signal: exec.signal, + }) + }, + }))) + } + messageTool('send_message', 'quiet') + messageTool('followup_task', 'wakeup') + + register(scoped.tools.register(defineTool({ + name: 'list_agents', + description: 'List the Lead and every durable teammate with current runtime status.', + parameters: {}, + output: jsonOutput(MEMBER_LIST_VALUE_SCHEMA), + async execute(_args, exec) { + return Promise.resolve(ctx.teams.listMembers(callingAgent(exec.agent, 'list_agents'))) + }, + }))) + + register(scoped.tools.register(defineTool({ + name: 'wait_agent', + description: 'Wait for the next teammate status, mailbox, or shared-task change after this call starts. This never wakes inactive members and returns noProgress immediately when no other member is running or provisioning. Re-list after wakeup or timeout instead of polling.', + parameters: { + timeout_ms: { + type: 'integer', + description: 'Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000.', + }, + }, + output: jsonOutput(WAIT_VALUE_SCHEMA), + async execute(args, exec) { + const caller = callingAgent(exec.agent, 'wait_agent') + const timeoutMs = args.timeout_ms ?? 30_000 + // Preserve TeamService's authoritative timeout validation before the + // model-only no-progress shortcut. + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 10_000 || timeoutMs > 3_600_000) { + return await ctx.teams.waitForChange(caller, timeoutMs, exec.signal) + } + // The active-peer read and waiter registration must remain one synchronous + // span; awaiting between them can lose the only peer-status edge. + const hasActivePeer = ctx.teams.listMembers(caller).some(member => + member.id !== caller.id && ACTIVE_WAIT_STATUSES.has(member.status)) + if (!hasActivePeer) { + return { + timedOut: false, + noProgress: { + reason: 'no-active-peer' as const, + message: NO_ACTIVE_PEER_MESSAGE, + }, + } + } + return await ctx.teams.waitForChange(caller, timeoutMs, exec.signal) + }, + }))) + + register(scoped.tools.register(defineTool({ + name: 'interrupt_agent', + description: 'Interrupt one teammate\'s current turn while preserving its pending inbox. Team Lead only.', + parameters: { + target: { type: 'string', required: true, description: 'Teammate name.' }, + }, + output: jsonOutput(INTERRUPT_VALUE_SCHEMA), + async execute(args, exec) { + return Promise.resolve(ctx.teams.interrupt( + callingAgent(exec.agent, 'interrupt_agent'), + args.target, + )) + }, + }))) + + register(scoped.tools.register(defineTool({ + name: 'team_task_create', + description: 'Create one unowned pending task on the shared Team task board.', + parameters: { + subject: { type: 'string', required: true, description: 'Concise task title.' }, + description: { type: 'string', required: true, description: 'Complete task details and acceptance criteria.' }, + blocked_by: { type: 'array', items: { type: 'string' }, description: 'Task ids that must complete first.' }, + write_scopes: { + type: 'array', + items: { type: 'string' }, + description: 'Advisory workspace-relative file or directory prefixes this task expects to modify.', + }, + }, + output: jsonOutput(TASK_VIEW_SCHEMA), + async execute(args, exec) { + return await ctx.teams.createTask(callingAgent(exec.agent, 'team_task_create'), { + subject: args.subject, + description: args.description, + ...args.blocked_by === undefined ? {} : { blockedBy: args.blocked_by.map(TeamTaskId) }, + ...args.write_scopes === undefined ? {} : { writeScopes: args.write_scopes }, + }) + }, + }))) + + register(scoped.tools.register(defineTool({ + name: 'team_task_list', + description: 'List shared tasks, including readiness, owner, revision, blockers, and write-scope warnings.', + parameters: { + status: { + type: 'string', + enum: ['pending', 'in_progress', 'completed'], + description: 'Optional exact status filter.', + }, + owner: { type: 'string', description: 'Optional member-name filter; use unowned for tasks without an owner.' }, + ready: { type: 'boolean', description: 'Optional readiness filter.' }, + cursor: { type: 'integer', description: 'Zero-based result offset. Defaults to 0.' }, + limit: { type: 'integer', description: 'Number of rows, 1 through 100. Defaults to 50.' }, + }, + output: jsonOutput(TASK_LIST_VALUE_SCHEMA), + execute(args, exec) { + const status = args.status + const filtered = ctx.teams.listTasks(callingAgent(exec.agent, 'team_task_list')).filter(task => + (status === undefined || task.status === status) + && (args.owner === undefined || (args.owner === 'unowned' ? task.ownerName === undefined : task.ownerName === args.owner)) + && (args.ready === undefined || task.ready === args.ready)) + const cursor = args.cursor ?? 0 + const limit = args.limit ?? 50 + if (!Number.isSafeInteger(cursor) || cursor < 0) throw new Error('cursor must be a non-negative safe integer') + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error('limit must be an integer from 1 through 100') + return Promise.resolve({ + tasks: filtered.slice(cursor, cursor + limit), + ...(cursor + limit < filtered.length ? { nextCursor: cursor + limit } : {}), + }) + }, + }))) + + register(scoped.tools.register(defineTool({ + name: 'team_task_get', + description: 'Read the complete latest value of one shared task before changing or executing it.', + parameters: { + task_id: { type: 'string', required: true, description: 'Shared task id.' }, + }, + output: jsonOutput(TASK_VIEW_SCHEMA), + async execute(args, exec) { + return Promise.resolve(ctx.teams.getTask( + callingAgent(exec.agent, 'team_task_get'), + TeamTaskId(args.task_id), + )) + }, + }))) + + register(scoped.tools.register(defineTool({ + name: 'team_task_update', + description: 'Compare-and-set a shared task action using the latest revision from team_task_get or team_task_list.', + parameters: { + task_id: { type: 'string', required: true, description: 'Shared task id.' }, + expected_revision: { type: 'integer', required: true, description: 'Current task revision used as the CAS precondition.' }, + action: { + type: 'string', + required: true, + enum: ['claim', 'release', 'edit', 'set_dependencies', 'complete', 'reopen', 'reassign', 'delete'], + description: 'Task transition to apply.', + }, + subject: { type: 'string', description: 'Replacement title for edit.' }, + description: { type: 'string', description: 'Replacement details for edit.' }, + blocked_by: { type: 'array', items: { type: 'string' }, description: 'Complete blocker list for set_dependencies.' }, + write_scopes: { type: 'array', items: { type: 'string' }, description: 'Replacement advisory write scopes for edit.' }, + owner: { type: 'string', description: 'Member name for Lead-only reassign; omit to unassign.' }, + }, + output: jsonOutput(TASK_VIEW_SCHEMA), + async execute(args, exec) { + return await ctx.teams.updateTask(callingAgent(exec.agent, 'team_task_update'), { + taskId: TeamTaskId(args.task_id), + expectedRevision: args.expected_revision, + action: args.action, + ...args.subject === undefined ? {} : { subject: args.subject }, + ...args.description === undefined ? {} : { description: args.description }, + ...args.blocked_by === undefined ? {} : { blockedBy: args.blocked_by.map(TeamTaskId) }, + ...args.write_scopes === undefined ? {} : { writeScopes: args.write_scopes }, + ...args.owner === undefined ? {} : { owner: args.owner }, + }) + }, + }))) + } catch (error: unknown) { + for (const dispose of disposers.reverse()) void dispose() + throw error + } + return () => { + for (const dispose of disposers.reverse()) void dispose() + } +} + +/** Install Team tools in every live or subsequently published Team member scope. */ +export function apply(ctx: Context, config: Config = {}): void { + const resolved: Required = { + freshProvider: config.freshProvider ?? 'spawn', + forkProvider: config.forkProvider ?? 'fork', + } + const installed = new Map void>() + const maybeInstall = (agent: Agent): void => { + if (installed.has(agent) || ctx.teams.tryMembership(agent) === undefined) return + installed.set(agent, install(agent, ctx, resolved)) + } + for (const agent of ctx.agents.list()) maybeInstall(agent) + ctx.on('agent/created', ({ agent }) => { maybeInstall(agent) }) + ctx.on('agent/disposed', ({ agent }) => { + installed.get(agent)?.() + installed.delete(agent) + }) + ctx.effect(() => () => { + for (const dispose of installed.values()) dispose() + installed.clear() + }, 'tool-team.scopedTools()') +} diff --git a/packages/experimental/tool-team/src/invariant.ts b/packages/experimental/tool-team/src/invariant.ts new file mode 100644 index 0000000000..9018b62f7b --- /dev/null +++ b/packages/experimental/tool-team/src/invariant.ts @@ -0,0 +1,18 @@ +/** Package-owned invariant companion for the Team tool adapter. */ + +import type { Context } from '@deepseek-ai/cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-tool-team' + +/** Cordis companion plugin name. */ +export const name = 'tool-team-invariant' +/** Invariant registry dependency. */ +export const inject = ['invariants'] + +/** No runtime invariant: the Team service owns durable and authorization relations. */ +const install: InvariantInstaller = () => {} + +/** Register this package's invariant ownership. */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) diff --git a/packages/experimental/tool-team/tests/tool-team.spec.ts b/packages/experimental/tool-team/tests/tool-team.spec.ts new file mode 100644 index 0000000000..f950af4aad --- /dev/null +++ b/packages/experimental/tool-team/tests/tool-team.spec.ts @@ -0,0 +1,442 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import { CallId } from '@deepseek-ai/dsh-llm' +import { scopeOf } from '@deepseek-ai/dsh-scope' +import { SessionId } from '@deepseek-ai/dsh-session' +import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import SubagentService from '@deepseek-ai/dsh-subagent' +import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' +import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' +import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' +import * as ToolSubagentControl from '@deepseek-ai/dsh-tool-subagent-control' +import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' +import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +import TeamService from '../../team/src/index.ts' +import * as toolTeam from '../src/index.ts' + +const SIGNAL = new AbortController().signal +const TOOL_NAMES = [ + 'spawn_teammate', + 'send_message', + 'followup_task', + 'list_agents', + 'wait_agent', + 'interrupt_agent', + 'team_task_create', + 'team_task_list', + 'team_task_get', + 'team_task_update', +].sort() + +const roots: string[] = [] +let callNumber = 0 + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +async function setup(script: ConstructorParameters[0], legacyControl = false) { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-tool-team-')) + roots.push(storageRoot) + await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(SubagentService) + if (legacyControl) await ctx.plugin(ToolSubagentControl) + await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) + await ctx.plugin(SubagentFork, { providerName: 'fork' }) + await ctx.plugin(TeamService) + const fiber = await ctx.plugin(toolTeam) + const adapter = new MockAdapter(script) + ctx.llm.registerAdapter(['mock'], adapter) + const lead = ctx.agentLoop.create(SessionId('tool-team-lead'), { provider: 'mock', model: 'mock' }) + return { ctx, lead, fiber } +} + +function execute( + ctx: Context, + agent: Agent | undefined, + name: string, + args: unknown, + signal: AbortSignal = SIGNAL, +) { + return ctx.tools.execute({ + callId: CallId(`team-call-${++callNumber}`), + name, + arguments: args, + signal, + ...agent === undefined ? {} : { agent }, + }) +} + +function text(result: Awaited>): string { + return result.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') +} + +function spawnedChildId(result: Awaited>): SessionId { + const parsed: unknown = JSON.parse(text(result)) + if (typeof parsed !== 'object' || parsed === null || !('member' in parsed)) { + throw new Error('spawn_teammate result has no member') + } + const member = parsed.member + if (typeof member !== 'object' || member === null || !('id' in member) || typeof member.id !== 'string') { + throw new Error('spawn_teammate result has no member id') + } + return SessionId(member.id) +} + +async function assembly(ctx: Context, agent: Agent) { + const scope = scopeOf(agent.ctx) + if (scope === undefined) throw new Error('expected Agent scope') + return ctx.systemPrompt.assemble({ scope }) +} + +async function waitRunning(ctx: Context, id: SessionId): Promise { + return vi.waitFor(() => { + const child = ctx.agents.get(id) + expect(child?.status).toBe('running') + return child! + }, { timeout: 5_000 }) +} + +async function waitNoAgent(ctx: Context, id: SessionId): Promise { + await vi.waitFor(() => { expect(ctx.agents.get(id)).toBeUndefined() }, { timeout: 5_000 }) +} + +describe('dsh-tool-team', () => { + it('installs the complete scoped schema and shared-checkout policy for roots and teammates', async () => { + const { ctx, lead } = await setup(['hang']) + const leadAssembly = await assembly(ctx, lead) + expect(leadAssembly.tools.map(schema => schema.name).filter(name => TOOL_NAMES.includes(name)).sort()) + .toEqual(TOOL_NAMES) + const leadPrompt = renderPrompt(leadAssembly) + expect(leadPrompt).toContain('create teammates only when the user explicitly asks') + expect(leadPrompt).toContain('FS_STALE_VERSION') + expect(leadPrompt).toContain('Bash, formatters, code generators, and scripts are not fully protected') + expect(leadPrompt).toContain('Task readiness never starts an owner') + expect(leadPrompt).toContain('returns noProgress immediately') + expect(leadPrompt).toContain('Your Team role is lead') + + const spawned = await execute(ctx, lead, 'spawn_teammate', { + name: 'tool-worker', + description: 'exercise scoped tools', + prompt: 'stay available', + }) + expect(spawned.isError).toBe(false) + const childId = spawnedChildId(spawned) + const child = await waitRunning(ctx, childId) + const childAssembly = await assembly(ctx, child) + expect(childAssembly.tools.map(schema => schema.name).filter(name => TOOL_NAMES.includes(name)).sort()) + .toEqual(TOOL_NAMES) + expect(renderPrompt(childAssembly)).toContain('Your Team role is teammate; your Team name is tool-worker') + + const denied = await execute(ctx, child, 'spawn_teammate', { + name: 'nested', description: 'not allowed', prompt: 'no', + }) + expect(denied.isError).toBe(true) + expect(text(denied)).toContain('only the Team Lead') + await execute(ctx, lead, 'interrupt_agent', { target: 'tool-worker' }) + await vi.waitFor(() => { expect(ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + }) + + it('returns actionable no-progress output and renders structured wait cancellation', async () => { + const inactiveSetup = await setup([textResponse('worker done')]) + const inactiveSpawn = await execute(inactiveSetup.ctx, inactiveSetup.lead, 'spawn_teammate', { + name: 'inactive-worker', description: 'finish immediately', prompt: 'finish', + }) + const inactiveId = spawnedChildId(inactiveSpawn) + await waitNoAgent(inactiveSetup.ctx, inactiveId) + const noProgress = await execute(inactiveSetup.ctx, inactiveSetup.lead, 'wait_agent', { timeout_ms: 3_600_000 }) + expect(noProgress.isError).toBe(false) + expect(JSON.parse(text(noProgress))).toEqual({ + timedOut: false, + noProgress: { + reason: 'no-active-peer', + message: 'No other Team member is running or provisioning. wait_agent cannot make progress or wake inactive teammates. Re-list with list_agents and team_task_list, then use followup_task to wake each required inactive teammate before waiting again.', + }, + }) + for (const timeout_ms of [9_999, 3_600_001, Number.MAX_SAFE_INTEGER + 1]) { + const invalid = await execute(inactiveSetup.ctx, inactiveSetup.lead, 'wait_agent', { timeout_ms }) + expect(invalid.isError).toBe(true) + expect(text(invalid)).toContain('timeoutMs must be an integer from 10000 through 3600000') + } + + const activeSetup = await setup(['hang']) + const activeSpawn = await execute(activeSetup.ctx, activeSetup.lead, 'spawn_teammate', { + name: 'active-worker', description: 'stay active', prompt: 'wait', + }) + const activeId = spawnedChildId(activeSpawn) + await waitRunning(activeSetup.ctx, activeId) + const controller = new AbortController() + const waiting = execute(activeSetup.ctx, activeSetup.lead, 'wait_agent', { timeout_ms: 10_000 }, controller.signal) + await new Promise(resolve => setTimeout(resolve, 0)) + controller.abort({ kind: 'user' }) + const aborted = await waiting + expect(aborted.isError).toBe(true) + expect(text(aborted)).toBe("Error: wait_agent aborted: { kind: 'user' }") + await execute(activeSetup.ctx, activeSetup.lead, 'interrupt_agent', { target: 'active-worker' }) + await waitNoAgent(activeSetup.ctx, activeId) + }) + + it('adapts roster, mailbox, wait, and task CAS operations to canonical JSON', async () => { + const { ctx, lead } = await setup(['hang', textResponse('lead received wakeup')]) + const spawned = await execute(ctx, lead, 'spawn_teammate', { + name: 'json-worker', description: 'json worker', prompt: 'wait', context: 'fresh', + }) + const childId = spawnedChildId(spawned) + const child = await waitRunning(ctx, childId) + + const roster = await execute(ctx, child, 'list_agents', {}) + expect(JSON.parse(text(roster))).toMatchObject([ + { name: 'lead', role: 'lead' }, + { name: 'json-worker', role: 'teammate' }, + ]) + // Every Team result reaches the model as compact JSON: indentation would + // spend tokens on every roster, task, and receipt without adding meaning. + expect(text(roster)).toBe(JSON.stringify(JSON.parse(text(roster)))) + const peer = await execute(ctx, child, 'send_message', { target: 'lead', message: 'quiet report' }) + expect(peer.isError).toBe(false) + expect(JSON.parse(text(peer))).toMatchObject({ status: 'accepted' }) + const waking = await execute(ctx, child, 'followup_task', { target: 'lead', message: 'review the report' }) + expect(waking.isError).toBe(false) + expect(JSON.parse(text(waking))).toMatchObject({ status: 'accepted' }) + await lead.whenIdle() + + const created = await execute(ctx, lead, 'team_task_create', { + subject: 'tool task', + description: 'created through tool', + blocked_by: [], + write_scopes: ['src/team'], + }) + const task = JSON.parse(text(created)) as { id: string; revision: number } + const listed = await execute(ctx, child, 'team_task_list', { ready: true, limit: 1 }) + expect(JSON.parse(text(listed))).toMatchObject({ tasks: [{ id: task.id, ready: true }] }) + const read = await execute(ctx, child, 'team_task_get', { task_id: task.id }) + expect(JSON.parse(text(read))).toMatchObject({ id: task.id, revision: 1 }) + const claimed = await execute(ctx, child, 'team_task_update', { + task_id: task.id, + expected_revision: task.revision, + action: 'claim', + }) + expect(JSON.parse(text(claimed))).toMatchObject({ status: 'in_progress', ownerName: 'json-worker' }) + const stale = await execute(ctx, lead, 'team_task_update', { + task_id: task.id, + expected_revision: task.revision, + action: 'delete', + }) + expect(stale.isError).toBe(true) + expect(text(stale)).toContain('stale team task') + + const wait = execute(ctx, lead, 'wait_agent', { timeout_ms: 10_000 }) + const completedCall = new Promise>>((resolve, reject) => { + setTimeout(() => { + void execute(ctx, child, 'team_task_update', { + task_id: task.id, + expected_revision: 2, + action: 'complete', + }).then(resolve, reject) + }, 0) + }) + await expect(wait).resolves.toMatchObject({ isError: false }) + expect((await completedCall).isError).toBe(false) + + const childInterrupt = await execute(ctx, child, 'interrupt_agent', { target: 'json-worker' }) + expect(childInterrupt.isError).toBe(true) + await execute(ctx, lead, 'interrupt_agent', { target: 'json-worker' }) + await vi.waitFor(() => { expect(ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + }) + + it('adapts optional task filters, mutations, pagination, and default waiting', async () => { + const { ctx, lead } = await setup(['hang']) + const spawned = await execute(ctx, lead, 'spawn_teammate', { + name: 'fork-worker', description: 'fork worker', prompt: 'stay active', context: 'fork', + }) + const childId = spawnedChildId(spawned) + await waitRunning(ctx, childId) + + const firstResult = await execute(ctx, lead, 'team_task_create', { + subject: 'first', description: 'first task', + }) + const secondResult = await execute(ctx, lead, 'team_task_create', { + subject: 'second', description: 'second task', + }) + const first = JSON.parse(text(firstResult)) as { id: string; revision: number } + const second = JSON.parse(text(secondResult)) as { id: string; revision: number } + const claimed = await execute(ctx, lead, 'team_task_update', { + task_id: first.id, expected_revision: first.revision, action: 'claim', + }) + const claim = JSON.parse(text(claimed)) as { revision: number } + + expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { + status: 'in_progress', owner: 'lead', cursor: 0, limit: 1, + })))).toMatchObject({ tasks: [{ id: first.id }] }) + expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { + owner: 'unowned', limit: 1, + })))).toMatchObject({ tasks: [{ id: second.id }] }) + expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { + cursor: 0, limit: 1, + })))).toMatchObject({ nextCursor: 1 }) + expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { + cursor: 1, + })))).not.toHaveProperty('nextCursor') + expect((await execute(ctx, lead, 'team_task_list', { cursor: -1 })).isError).toBe(true) + expect((await execute(ctx, lead, 'team_task_list', { limit: 101 })).isError).toBe(true) + + const edited = await execute(ctx, lead, 'team_task_update', { + task_id: first.id, + expected_revision: claim.revision, + action: 'edit', + subject: 'edited', + description: 'edited description', + write_scopes: ['src/team'], + }) + const edit = JSON.parse(text(edited)) as { revision: number } + const dependencies = await execute(ctx, lead, 'team_task_update', { + task_id: first.id, + expected_revision: edit.revision, + action: 'set_dependencies', + blocked_by: [second.id], + }) + expect(dependencies.isError).toBe(false) + const dependency = JSON.parse(text(dependencies)) as { revision: number } + expect((await execute(ctx, lead, 'team_task_update', { + task_id: first.id, + expected_revision: dependency.revision, + action: 'reassign', + owner: 'fork-worker', + })).isError).toBe(true) + + const wait = execute(ctx, lead, 'wait_agent', {}) + const wake = new Promise>>((resolve, reject) => { + setTimeout(() => { + void execute(ctx, lead, 'team_task_create', { + subject: 'wake', description: 'wake default wait', + }).then(resolve, reject) + }, 0) + }) + expect((await wait).isError).toBe(false) + expect((await wake).isError).toBe(false) + + await execute(ctx, lead, 'interrupt_agent', { target: 'fork-worker' }) + await vi.waitFor(() => { expect(ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + }) + + it('removes and reinstalls every scoped registration across plugin HMR without stopping the child', async () => { + const { ctx, lead, fiber } = await setup(['hang']) + const spawned = await execute(ctx, lead, 'spawn_teammate', { + name: 'hmr-worker', description: 'hmr worker', prompt: 'wait', + }) + const childId = spawnedChildId(spawned) + const child = await waitRunning(ctx, childId) + + await fiber.dispose() + expect((await assembly(ctx, lead)).tools.map(schema => schema.name).some(name => TOOL_NAMES.includes(name))).toBe(false) + expect((await assembly(ctx, child)).tools.map(schema => schema.name).some(name => TOOL_NAMES.includes(name))).toBe(false) + expect(ctx.agents.get(childId)).toBe(child) + + const replacement = await ctx.plugin(toolTeam) + expect((await assembly(ctx, lead)).tools.map(schema => schema.name).filter(name => TOOL_NAMES.includes(name)).sort()) + .toEqual(TOOL_NAMES) + expect((await assembly(ctx, child)).tools.map(schema => schema.name).filter(name => TOOL_NAMES.includes(name)).sort()) + .toEqual(TOOL_NAMES) + await execute(ctx, lead, 'interrupt_agent', { target: 'hmr-worker' }) + await vi.waitFor(() => { expect(ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + await replacement.dispose() + }) + + it('shadows legacy global control names only inside Team member scopes', async () => { + const { ctx, lead, fiber } = await setup([], true) + const teamSchema = (await assembly(ctx, lead)).tools.find(schema => schema.name === 'send_message') + expect(JSON.stringify(teamSchema)).toContain('target') + expect(JSON.stringify(teamSchema)).not.toContain('subagent_id') + + await fiber.dispose() + const legacySchema = (await assembly(ctx, lead)).tools.find(schema => schema.name === 'send_message') + expect(JSON.stringify(legacySchema)).toContain('subagent_id') + }) + + it('rolls back partial scoped installation after a same-scope collision', async () => { + const { ctx, lead, fiber } = await setup([]) + await fiber.dispose() + lead.ctx.tools.register(defineContentToolFixture({ + name: 'spawn_teammate', + description: 'intentional collision', + parameters: {}, + async execute() { return [{ type: 'text', text: 'collision' }] }, + })) + + await expect(ctx.plugin(toolTeam)).rejects.toThrow(/already registered/u) + const assembled = await assembly(ctx, lead) + expect(assembled.tools.filter(schema => TOOL_NAMES.includes(schema.name)).map(schema => schema.name)) + .toEqual(['spawn_teammate']) + expect(renderPrompt(assembled)).not.toContain('Your Team role is lead') + }) + + it('resolves direct-apply defaults without Loader schema normalization', async () => { + const { ctx, lead, fiber } = await setup([textResponse('ordinary child')]) + await fiber.dispose() + toolTeam.apply(ctx, {}) + expect((await assembly(ctx, lead)).tools.map(schema => schema.name).filter(name => TOOL_NAMES.includes(name)).sort()) + .toEqual(TOOL_NAMES) + const ordinary = await ctx.subagents.startContinuable({ + provider: 'spawn', + label: 'ordinary child', + request: { prompt: [{ type: 'text', text: 'finish' }], parent: lead }, + signal: SIGNAL, + }) + await vi.waitFor(() => { expect(ctx.agents.get(ordinary.childId)).toBeUndefined() }, { timeout: 5_000 }) + }) + + it('reinstalls Team scope before a cold-resumed teammate request', async () => { + const { ctx, lead } = await setup([textResponse('first'), 'hang']) + const spawned = await execute(ctx, lead, 'spawn_teammate', { + name: 'cold-worker', description: 'cold worker', prompt: 'finish once', + }) + const childId = spawnedChildId(spawned) + await vi.waitFor(() => { expect(ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + + await ctx.teams.sendMessage(lead, { + target: 'cold-worker', + content: [{ type: 'text', text: 'resume with Team scope' }], + delivery: 'wakeup', + signal: SIGNAL, + }) + const resumed = await waitRunning(ctx, childId) + expect((await assembly(ctx, resumed)).tools.map(schema => schema.name) + .filter(name => TOOL_NAMES.includes(name)).sort()).toEqual(TOOL_NAMES) + expect(renderPrompt(await assembly(ctx, resumed))).toContain('Your Team role is teammate; your Team name is cold-worker') + await execute(ctx, lead, 'interrupt_agent', { target: 'cold-worker' }) + await vi.waitFor(() => { expect(ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + }) + + it('fails safely without a calling Agent and has the function-plugin export shape', async () => { + const { ctx } = await setup([]) + const result = await execute(ctx, undefined, 'list_agents', {}) + expect(result.isError).toBe(true) + expect(text(result)).toContain('unknown tool "list_agents"') + expect('default' in toolTeam).toBe(false) + expect(toolTeam.name).toBe('tool-team') + expect(toolTeam.inject).toEqual(['agents', 'teams', 'tools', 'systemPrompt']) + }) + + it('uses configured fresh and fork provider names', async () => { + const { ctx, lead, fiber } = await setup([textResponse('custom')]) + await fiber.dispose() + await ctx.plugin(SubagentSpawn, { providerName: 'team-fresh' }) + await ctx.plugin(toolTeam, { freshProvider: 'team-fresh', forkProvider: 'fork' }) + const result = await execute(ctx, lead, 'spawn_teammate', { + name: 'custom-provider', description: 'custom provider', prompt: 'go', + }) + expect(result.isError).toBe(false) + const childId = spawnedChildId(result) + await vi.waitFor(() => { expect(ctx.agents.get(childId)).toBeUndefined() }, { timeout: 5_000 }) + expect(ctx.teams.listMembers(lead)[1]).toMatchObject({ provider: 'team-fresh' }) + }) +}) diff --git a/packages/experimental/tool-team/tsconfig.json b/packages/experimental/tool-team/tsconfig.json new file mode 100644 index 0000000000..f528b2280c --- /dev/null +++ b/packages/experimental/tool-team/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cosmokit" }, + { "path": "../../../vendor/schemastery" }, + { "path": "../../../vendor/cordis" }, + { "path": "../../core/agent" }, + { "path": "../../core/scope" }, + { "path": "../../core/session" }, + { "path": "../../core/system-prompt" }, + { "path": "../../core/tools" }, + { "path": "../team" }, + { "path": "../../runtime-diagnostics/invariants" } + ] +} diff --git a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts index 58bbbdee3f..c6539aa46a 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -106,7 +106,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { key: 'locale', summary: 'Dictionary registry plus locale preference.', - description: 'Dictionary registry plus locale preference. Lookup chain per key: the entry\'s namespace in the active locale -> that namespace\'s zh fallback -> the shared common namespace (active, then zh) -> the key itself (missing text stays visible, fail loud in the UI rather than blank). Reads go through getLocale; writes only through setLocale; continuous sync through the `locale/change` event, or through the LocaleFace getSnapshot/subscribe pair the render machinery consumes (installed via `ctx.slots.installLocale`).', + description: 'Dictionary registry plus locale preference. Lookup chain per key: the entry\'s namespace in the active locale -> that namespace\'s en fallback -> the shared common namespace (active, then en) -> the key itself (missing text stays visible, fail loud in the UI rather than blank). Reads go through getLocale; writes only through setLocale; continuous sync through the `locale/change` event, or through the LocaleFace getSnapshot/subscribe pair the render machinery consumes (installed via `ctx.slots.installLocale`).', methods: [ { signature: 'getLocale(): LocaleSnapshot', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 8dd07362e9..363adc0c38 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1659,6 +1659,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'once every retained descendant Activation released its `AgentHandle`.', throws: ['an aggregate error after all branches settle when any failed.'], }, + { + signature: 'async drainContinuableChildren(parent: Agent, childIds: readonly SessionId[]): Promise', + description: 'Release selected resident continuable direct children of one exact live parent. Other children of the same parent remain admitted and resident. Absent targets and a manager-less composition are accepted no-ops.', + parameters: [{ name: 'parent', description: 'exact live direct parent authorizing the selected release.' }, { name: 'childIds', description: 'durable direct-child ids to release when resident.' }], + returns: 'once every selected Activation released its `AgentHandle`.', + throws: ['{SubagentError} `UNAUTHORIZED` when a resident target belongs to a different parent or the supplied parent identity is stale.'], + }, { signature: 'listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise', description: 'Enumerate the parent\'s direct session-backed subagents without loading or resuming an Agent and without any query service: the listing merges the live session store with optional session persistence (live-preferred) and serves each child\'s durable mode/label from the registered `subagent` projection unit down a three-rung ladder — the registry\'s watermark snapshot for a live child; for a cold one, a durable projection-cache row when the optional cache serves an own-suffix identity (its `seq` gate proves the value postdates the fork seed, where a child\'s own descriptor is immutable once appended), else one persistence inspection folded through the registry. The projection fold is the single classification authority; per-child diagnostics relay a fold that served no identity or a failed inspection, never a list-time descriptor parse. Absent persistence, enumeration is live-only (a cold child cannot be resumed then either, so its absence is capability absence, not an error). This service consults no Agent registrations, Activations, or providers.\n\nEvery persistence read receives `signal`, and the listing rechecks cancellation around each of those awaits. Read rejections that settle after an abort become a stable `SubagentError` with code `CANCELLED`.', @@ -1767,6 +1774,79 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'teams', + summary: 'Agent Teams service backed by the exact live Lead Session log.', + description: 'Agent Teams service backed by the exact live Lead Session log.', + methods: [ + { + signature: 'membership(agent: Agent): TeamMembership', + description: 'Resolve one exact live Agent\'s Team role.', + parameters: [{ name: 'agent', description: 'exact live Agent used as the authority credential.' }], + returns: 'its root, Team identity, role, and model-facing name.', + }, + { + signature: 'listMembers(agent: Agent): TeamMemberView[]', + description: 'List the runtime-enriched roster visible to one Team member.', + parameters: [{ name: 'agent', description: 'exact live Team member.' }], + returns: 'Lead and teammate rows in creation order.', + }, + { + signature: 'async spawnTeammate(caller: Agent, request: SpawnTeammateRequest): Promise', + description: 'Create one named, continuable direct child of the Team Lead.', + parameters: [{ name: 'caller', description: 'exact live Lead Agent.' }, { name: 'request', description: 'immutable name, description, prompt, context mode, provider, and cancellation.' }], + returns: 'the active roster row.', + }, + { + signature: 'async sendMessage(caller: Agent, request: SendTeamMessageRequest): Promise', + description: 'Queue one durable peer message, then attempt immediate delivery.', + parameters: [{ name: 'caller', description: 'exact live sending Team member.' }, { name: 'request', description: 'target name, content, scheduling mode, and pre-queue cancellation.' }], + returns: 'durable message identity and immediate-delivery observation.', + }, + { + signature: 'async createTask(caller: Agent, request: CreateTeamTaskRequest): Promise', + description: 'Create one unowned pending task in the Team Lead log.', + parameters: [{ name: 'caller', description: 'exact live Team member creating the task.' }, { name: 'request', description: 'task text, blockers, and advisory write scopes.' }], + returns: 'the revision-one task view.', + }, + { + signature: 'getTask(caller: Agent, id: TeamTaskId): TeamTaskView', + description: 'Return one task, including a deleted tombstone.', + parameters: [{ name: 'caller', description: 'exact live Team member reading the task.' }, { name: 'id', description: 'Team-local task identity.' }], + returns: 'the latest task value and derived readiness diagnostics.', + }, + { + signature: 'listTasks(caller: Agent): TeamTaskView[]', + description: 'List current non-deleted tasks in numeric creation order.', + parameters: [{ name: 'caller', description: 'exact live Team member reading the board.' }], + returns: 'detached current task views.', + }, + { + signature: 'async updateTask(caller: Agent, request: UpdateTeamTaskRequest): Promise', + description: 'Compare-and-set one authorized task transition.', + parameters: [{ name: 'caller', description: 'exact live Team member authorizing the mutation.' }, { name: 'request', description: 'task identity, expected revision, action, and action fields.' }], + returns: 'the committed next task revision.', + }, + { + signature: 'async waitForChange(caller: Agent, timeoutMs: number, signal: AbortSignal): Promise', + description: 'Wait for the next Team-domain or member-status change.', + parameters: [{ name: 'caller', description: 'exact live Team member waiting for activity.' }, { name: 'timeoutMs', description: 'bounded wait duration from ten seconds through one hour.' }, { name: 'signal', description: 'caller cancellation for the wait only.' }], + returns: 'one observed change or a timeout result.', + }, + { + signature: 'interrupt(caller: Agent, targetName: string): { previousStatus: \'running\' | \'idle\' | \'inactive\' }', + description: 'Interrupt one live teammate turn without clearing its pending inbox.', + parameters: [{ name: 'caller', description: 'exact live Lead Agent.' }, { name: 'targetName', description: 'durable teammate name.' }], + returns: 'the target status sampled before cancellation.', + }, + { + signature: 'tryMembership(agent: Agent): TeamMembership | undefined', + description: 'Resolve a caller without throwing, used by scoped-tool installation and observers.', + parameters: [{ name: 'agent', description: 'candidate exact live Agent.' }], + returns: 'Team membership, or undefined for non-Team subagents and stale identities.', + }, + ], + }, { key: 'terminals', summary: 'In-process registry for replaceable PTY backends and exact-Agent sessions.', @@ -2894,7 +2974,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ContinuableStartSpec', - declaration: 'export interface ContinuableStartSpec {\n readonly provider: string;\n readonly label: string;\n readonly request: Omit;\n readonly signal: AbortSignal;\n}', + declaration: 'export interface ContinuableStartSpec {\n readonly provider: string;\n readonly label: string;\n readonly childId?: SessionId;\n readonly request: Omit;\n readonly signal: AbortSignal;\n}', }, { name: 'ContinuableSubagentDescriptorData', @@ -2944,6 +3024,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'CreateSessionOptions', declaration: 'export interface CreateSessionOptions {\n readonly seed?: readonly SessionEvent[];\n readonly meta?: {\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly createdAt?: number;\n readonly seedLength?: number;\n readonly origin?: \'subagent\';\n readonly delegationDepth?: number;\n readonly agentPreset?: string;\n };\n}', }, + { + name: 'CreateTeamTaskRequest', + declaration: 'export interface CreateTeamTaskRequest {\n readonly subject: string;\n readonly description: string;\n readonly blockedBy?: readonly TeamTaskId[];\n readonly writeScopes?: readonly string[];\n}', + }, { name: 'CredentialInfo', declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n writable: boolean;\n}', @@ -3756,6 +3840,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SearchResultView', declaration: 'export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;', }, + { + name: 'SendTeamMessageRequest', + declaration: 'export interface SendTeamMessageRequest {\n readonly target: string;\n readonly content: ContentBlock[];\n readonly delivery: \'quiet\' | \'wakeup\';\n readonly signal: AbortSignal;\n}', + }, + { + name: 'SendTeamMessageResult', + declaration: 'export interface SendTeamMessageResult {\n readonly messageId: TeamMessageId;\n readonly status: \'accepted\' | \'queued\';\n}', + }, { name: 'ServerResponse', declaration: 'export interface ServerResponse {\n type: \'server-response\';\n rpcId: RpcId;\n result: RpcResult;\n}', @@ -4104,6 +4196,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SkillViewOptions', declaration: 'export interface SkillViewOptions extends SkillLookupOptions {\n readonly scope?: ScopeKey | undefined;\n}', }, + { + name: 'SpawnTeammateRequest', + declaration: 'export interface SpawnTeammateRequest {\n readonly name: string;\n readonly description: string;\n readonly prompt: ContentBlock[];\n readonly context: \'fresh\' | \'fork\';\n readonly provider: string;\n readonly signal: AbortSignal;\n}', + }, + { + name: 'SpawnTeammateResult', + declaration: 'export interface SpawnTeammateResult {\n readonly member: TeamMemberView;\n}', + }, { name: 'SpillLocator', declaration: 'export type SpillLocator = Branded<\'SpillLocator\'>;', @@ -4170,7 +4270,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SubagentResult', - declaration: 'export interface SubagentResult {\n readonly output: ContentBlock[];\n readonly structured?: unknown;\n readonly stopReason: SubagentStopReason;\n}', + declaration: 'export interface SubagentResult {\n readonly output: ContentBlock[];\n readonly structured?: unknown;\n readonly diagnostic?: string;\n readonly stopReason: SubagentStopReason;\n}', }, { name: 'SubagentRun', @@ -4190,7 +4290,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SubagentRuntime', - declaration: 'export class SubagentRuntime extends Service {\n constructor(ctx: Context);\n async startContinuable(spec: ContinuableStartSpec): Promise;\n async followup(parent: Agent, childId: SessionId, content: ContentBlock[], options: SubagentFollowupOptions): Promise;\n interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void;\n async reportFrom(child: Agent, content: ContentBlock[], options: SubagentReportOptions): Promise;\n registerContinuableSetup(contribution: ContinuableSetupContribution): () => void;\n async drainContinuableDescendants(parents: readonly Agent[]): Promise;\n listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise;\n listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise;\n registerProvider(provider: SubagentProvider): () => void;\n getProvider(name: string): SubagentProvider | undefined;\n list(): string[];\n async start(name: string, request: SubagentStartRequest): Promise;\n}', + declaration: 'export class SubagentRuntime extends Service {\n constructor(ctx: Context);\n async startContinuable(spec: ContinuableStartSpec): Promise;\n async followup(parent: Agent, childId: SessionId, content: ContentBlock[], options: SubagentFollowupOptions): Promise;\n interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void;\n async reportFrom(child: Agent, content: ContentBlock[], options: SubagentReportOptions): Promise;\n registerContinuableSetup(contribution: ContinuableSetupContribution): () => void;\n async drainContinuableDescendants(parents: readonly Agent[]): Promise;\n async drainContinuableChildren(parent: Agent, childIds: readonly SessionId[]): Promise;\n listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise;\n listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise;\n registerProvider(provider: SubagentProvider): () => void;\n getProvider(name: string): SubagentProvider | undefined;\n list(): string[];\n async start(name: string, request: SubagentStartRequest): Promise;\n}', }, { name: 'SubagentStartRequest', @@ -4284,6 +4384,42 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'TableValueOf', declaration: 'export type TableValueOf = S[\'tables\'][N] extends DomainTableSpec ? V : never;', }, + { + name: 'TeamId', + declaration: 'export type TeamId = Branded<\'TeamId\'>;', + }, + { + name: 'TeamMembership', + declaration: 'export interface TeamMembership {\n readonly root: Agent;\n readonly id: TeamId;\n readonly role: \'lead\' | \'teammate\';\n readonly name: string;\n}', + }, + { + name: 'TeamMemberView', + declaration: 'export interface TeamMemberView {\n readonly id: SessionId;\n readonly name: string;\n readonly role: \'lead\' | \'teammate\';\n readonly status: \'running\' | \'idle\' | \'inactive\' | \'provisioning\' | \'failed\';\n readonly description?: string;\n readonly provider?: string;\n readonly context?: \'fresh\' | \'fork\';\n readonly model?: string;\n readonly diagnostics: string[];\n}', + }, + { + name: 'TeamMessageId', + declaration: 'export type TeamMessageId = Branded<\'TeamMessageId\'>;', + }, + { + name: 'TeamTaskAction', + declaration: 'export type TeamTaskAction = \'claim\' | \'release\' | \'edit\' | \'set_dependencies\' | \'complete\' | \'reopen\' | \'reassign\' | \'delete\';', + }, + { + name: 'TeamTaskId', + declaration: 'export type TeamTaskId = Branded<\'TeamTaskId\'>;', + }, + { + name: 'TeamTaskStatus', + declaration: 'export type TeamTaskStatus = \'pending\' | \'in_progress\' | \'completed\' | \'deleted\';', + }, + { + name: 'TeamTaskView', + declaration: 'export interface TeamTaskView {\n readonly id: TeamTaskId;\n readonly revision: number;\n readonly subject: string;\n readonly description: string;\n readonly status: TeamTaskStatus;\n readonly blockedBy: TeamTaskId[];\n readonly writeScopes: string[];\n readonly ownerName?: string;\n readonly ready: boolean;\n readonly writeScopeWarnings: string[];\n}', + }, + { + name: 'TeamWaitResult', + declaration: 'export interface TeamWaitResult {\n readonly timedOut: boolean;\n}', + }, { name: 'TerminalBackend', declaration: 'export interface TerminalBackend {\n readonly type: string;\n spawn(spec: TerminalBackendSpawnSpec): Promise;\n}', @@ -4564,6 +4700,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'TypertTypeModel', declaration: 'export interface TypertTypeModel {\n readonly name: string;\n readonly declaration: string;\n}', }, + { + name: 'UpdateTeamTaskRequest', + declaration: 'export interface UpdateTeamTaskRequest {\n readonly taskId: TeamTaskId;\n readonly expectedRevision: number;\n readonly action: TeamTaskAction;\n readonly subject?: string;\n readonly description?: string;\n readonly blockedBy?: readonly TeamTaskId[];\n readonly writeScopes?: readonly string[];\n readonly owner?: string;\n}', + }, { name: 'UserMessage', declaration: 'export interface UserMessage extends Message {\n readonly role: \'user\';\n}', diff --git a/packages/host/directory-picker-auto/tests/loader-composition.spec.ts b/packages/host/directory-picker-auto/tests/loader-composition.spec.ts index b24bc8ceb1..783e4e1e6f 100644 --- a/packages/host/directory-picker-auto/tests/loader-composition.spec.ts +++ b/packages/host/directory-picker-auto/tests/loader-composition.spec.ts @@ -188,7 +188,10 @@ describe('real Loader composition', () => { // behavior, not the chooser's); await that debounced write so it cannot // race the temp-dir removal, and pin that the persisted row is the // chooser itself — the resolved backend still never reaches the file. - await expect.poll(async () => await readFile(configPath, 'utf8')).toContain('disabled: true') + await expect.poll( + async () => await readFile(configPath, 'utf8'), + { timeout: 15_000 }, + ).toContain('disabled: true') expect(await readFile(configPath, 'utf8')).not.toContain(NATIVE) }) diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 4ac4cf4ed0..cf54a96ec7 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/llm/llm-deepseek/README.md -README.md: af89e7ee3bab6ec209349d047f81308eb6e87cef -README.zh.md: e9ce3206027ffeee9bc49eb7a2ed76ddcbe7bfc8 +README.md: 9bb28e6876b82c521341769123a8b2d0e5d98e09 +README.zh.md: 21c55cfa32bf68e0cac4c0bd72c94c86d955fc00 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index af89e7ee3b..9bb28e6876 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -20,7 +20,7 @@ The package root exposes the Cordis plugin contract and `DeepSeekAdapter`; wire reasoningEffort: high # optional; off | low | high | max — omitted ⇒ high maxTokens: 256000 # optional positive per-request output cap; this is the default streamIdleTimeoutMs: 300000 # optional; positive finite Node timer delay; five-minute default - retryPolicy: # optional; omission uses bounded normal defaults + retryPolicy: # optional; omission uses normal mode with five retries mode: always # normal | always backoff: initialDelayMs: 500 @@ -35,7 +35,7 @@ The package root exposes the Cordis plugin contract and `DeepSeekAdapter`; wire contextWindow: 512000 ``` -The plugin registers the single provider route `deepseek-official` together with its resolved `retryPolicy`. A request selects it with `provider: deepseek-official`; its `model` is passed through as the wire `model` string, so changing DeepSeek models does not require lifecycle-time registration. Omitting `models` advertises `deepseek-v4-flash` as `DeepSeek-V4-Flash` and `deepseek-v4-pro` as `DeepSeek-V4-Pro`, each with a 1,000,000-token context window; an explicit list replaces those defaults, while `models: []` advertises none. Catalog entries are exposed through `ctx.llm.listModels('deepseek-official')` for clients such as ACP editors and the Web selector, but remain advisory: unlisted model ids still pass through unchanged. An omitted entry name defaults to its id. +The plugin registers the single provider route `deepseek-official` together with its resolved `retryPolicy`; omission resolves to normal mode with five retries. A request selects it with `provider: deepseek-official`; its `model` is passed through as the wire `model` string, so changing DeepSeek models does not require lifecycle-time registration. Omitting `models` advertises `deepseek-v4-flash` as `DeepSeek-V4-Flash` and `deepseek-v4-pro` as `DeepSeek-V4-Pro`, each with a 1,000,000-token context window; an explicit list replaces those defaults, while `models: []` advertises none. Catalog entries are exposed through `ctx.llm.listModels('deepseek-official')` for clients such as ACP editors and the Web selector, but remain advisory: unlisted model ids still pass through unchanged. An omitted entry name defaults to its id. `contextWindow` is optional per configured model and is not exposed through the advisory catalog. `ctx.llm.resolveModelInfo('deepseek-official', model).context` returns an exact model value first, then `defaultContextWindow` for an entry without capacity or an unlisted pass-through id. The adapter default is 1,000,000; pressure-sensitive plugins therefore get deployment-owned capacity without treating the model selector as authoritative. Registering another adapter for `deepseek-official` throws `LlmError('DUPLICATE_ADAPTER')`. diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index e9ce320602..21c55cfa32 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -20,7 +20,7 @@ harness LLM(大语言模型)seam 的 DeepSeek chat-completions 适配器: reasoningEffort: high # optional; off | low | high | max — omitted ⇒ high maxTokens: 256000 # optional positive per-request output cap; this is the default streamIdleTimeoutMs: 300000 # optional; positive finite Node timer delay; five-minute default - retryPolicy: # optional; omission uses bounded normal defaults + retryPolicy: # optional; omission uses normal mode with five retries mode: always # normal | always backoff: initialDelayMs: 500 @@ -35,7 +35,7 @@ harness LLM(大语言模型)seam 的 DeepSeek chat-completions 适配器: contextWindow: 512000 ``` -该插件注册唯一提供方路由 `deepseek-official`,同时注册解析后的 `retryPolicy`。请求使用 `provider: deepseek-official` 选择该路由;其 `model` 会作为协议 `model` 字符串原样传递,因此更改 DeepSeek 模型不需要生命周期时注册。省略 `models` 会公布 `deepseek-v4-flash`(名称为 `DeepSeek-V4-Flash`)和 `deepseek-v4-pro`(名称为 `DeepSeek-V4-Pro`),两者的上下文窗口均为 1,000,000 token;显式列表会替换这些默认值,`models: []` 则不公布任何模型。Catalog 配置项通过 `ctx.llm.listModels('deepseek-official')` 公开给 ACP(Agent Client Protocol)编辑器和 Web 选择器等客户端,但仍只提供建议:未列出模型 id 仍原样传递。省略配置项 name 默认为其 id。 +该插件注册唯一提供方路由 `deepseek-official`,并一同注册解析后的 `retryPolicy`;省略时会解析为 normal 模式并重试五次。请求使用 `provider: deepseek-official` 选择该路由;其 `model` 会作为协议 `model` 字符串原样传递,因此更改 DeepSeek 模型不需要生命周期时注册。省略 `models` 会公布 `deepseek-v4-flash`(名称为 `DeepSeek-V4-Flash`)和 `deepseek-v4-pro`(名称为 `DeepSeek-V4-Pro`),两者的上下文窗口均为 1,000,000 token;显式列表会替换这些默认值,`models: []` 则不公布任何模型。Catalog 配置项通过 `ctx.llm.listModels('deepseek-official')` 公开给 ACP(Agent Client Protocol)编辑器和 Web 选择器等客户端,但仍只提供建议:未列出模型 id 仍原样传递。省略配置项 name 默认为其 id。 `contextWindow` 对每个已配置模型都可选,不会通过建议 catalog 公开。`ctx.llm.resolveModelInfo('deepseek-official', model).context` 先返回精确模型值,再对不含容量的配置项或未列出原样传递 id 返回 `defaultContextWindow`。适配器默认值为 1,000,000;因此,压力敏感插件可以获得由部署决定的容量,不会将模型 selector 视为权威。为 `deepseek-official` 注册另一个适配器会抛出 `LlmError('DUPLICATE_ADAPTER')`。 diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts index a7b22ddd88..cbaa0c13b6 100644 --- a/packages/llm/llm-deepseek/src/index.ts +++ b/packages/llm/llm-deepseek/src/index.ts @@ -76,7 +76,7 @@ export interface Config { models?: DeepSeekCatalogModel[] /** Maximum provider idle time while one stream read is outstanding (default five minutes). */ streamIdleTimeoutMs?: number - /** Provider-owned model-request retry policy; omission uses normal defaults. */ + /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig } diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index 553b7d4557..694da1fb3c 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/llm/llm-pi-ai/README.md -README.md: d775e72616822ce0deee063ac0f3fc453af1a126 -README.zh.md: 621d67d1c181c6d4c78ea0078f521acccce92653 +README.md: f696b6bee50b844bfbc6bab7f9def0e785d450c9 +README.zh.md: cace9d1fdfd85a559674b121b79b3dbb86b4337b diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index d775e72616..f696b6bee5 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -8,7 +8,7 @@ The package root exposes the Cordis plugin contract, `PiAiAdapter`, and `support ## Config -Configure credentials, the model catalog, and deployment-specific transport settings per provider, keyed by the provider route itself. `apiKeyEnv` is a credential *reference* resolved per request, so no secret enters this file. Omitting it leaves the route unauthenticated, which for an installed catalog route means pi-ai's provider-native ambient discovery; a configured reference that resolves to nothing fails the request with `MISSING_CREDENTIAL` instead, because falling through would authenticate with whatever unrelated key the environment happens to hold. One credential serves every model on its route. +Configure credentials, the model catalog, and deployment-specific transport settings per provider, keyed by the provider route itself. Each profile may set a `retryPolicy`; omission uses normal mode with five retries. `apiKeyEnv` is a credential *reference* resolved per request, so no secret enters this file. Omitting it leaves the route unauthenticated, which for an installed catalog route means pi-ai's provider-native ambient discovery; a configured reference that resolves to nothing fails the request with `MISSING_CREDENTIAL` instead, because falling through would authenticate with whatever unrelated key the environment happens to hold. One credential serves every model on its route. ```yaml - id: llm @@ -113,7 +113,7 @@ A model that carries reasoning metadata — from the installed catalog or from i A model **without** that metadata — a hand-declared one whose entry declares no `reasoningEfforts`, and a catalog model pi-ai marks as non-reasoning — exposes no `reasoning` at all. pi-ai reports such a model as supporting the single level `off`, but `off` is translated to *omitting* the reasoning option, which is byte-for-byte the request that naming no effort already produces: selecting it could not disable anything, so a provider whose own default is to think would keep thinking with `off` shown as selected. Reporting the capability as unavailable leaves a surface offering the provider's default and nothing that misrepresents it. The profile `reasoning` value, including `off`, is the deployment default when configured; omitting it preserves the provider default. Per-request `GenerateOptions.reasoningEffort` takes precedence, and a level absent from the exact model capability fails the REQUEST with `UNSUPPORTED_REASONING_EFFORT` before network I/O instead of being clamped. Describing a model never fails that way: the models under one provider disagree about which levels they accept, so `resolveModel` reports a profile level the exact model cannot take as no default at all rather than throwing. A throw there would take the whole provider out of every model catalog built over it — one mis-set profile field hiding even the models that do support the level — so a bad configuration surfaces where it is acted on, not where it is described. pi-ai's common stream options represent `off` by omitting `reasoning`. -Supported profile fields are `apiKeyEnv`, `displayName`, `api`, `baseURL`, `models`, `modelOverrides`, `compat`, `defaultContextWindow`, `defaultMaxTokens`, `defaultInput`, `headers`, `reasoning`, `thinkingBudgets`, `cacheRetention`, `transport`, `timeoutMs`, `websocketConnectTimeoutMs`, `streamIdleTimeoutMs`, and `retryPolicy`. Each profile's optional retry policy is captured with that provider route; omission uses bounded normal defaults. The stream-idle interval is a positive finite Node timer delay, defaults to five minutes, and covers only an outstanding provider read, not consumer think time. Harness app attribution wins a conflicting configured header name. +Supported profile fields are `apiKeyEnv`, `displayName`, `api`, `baseURL`, `models`, `modelOverrides`, `compat`, `defaultContextWindow`, `defaultMaxTokens`, `defaultInput`, `headers`, `reasoning`, `thinkingBudgets`, `cacheRetention`, `transport`, `timeoutMs`, `websocketConnectTimeoutMs`, `streamIdleTimeoutMs`, `maxRequestImageBytes`, and `retryPolicy`. Each resolved profile retry policy is captured with that provider route; omission uses the shared bounded normal default of five retries. The stream-idle interval is a positive finite Node timer delay, defaults to five minutes, and covers only an outstanding provider read, not consumer think time. `maxRequestImageBytes` bounds one request's base64-encoded image payload (default 20MiB, a positive integer): every image in history is re-encoded into every request, so when the accumulated payload exceeds the bound, the oldest images are replaced by a fixed text placeholder until the request fits, keeping an image-heavy session serviceable instead of permanently rejected by a gateway request-size cap. The default leaves capacity for system prompts, history, tools, and JSON; deployments behind stricter gateways lower it per route. Harness app attribution wins a conflicting configured header name. The adapter forces pi-ai's SDK `maxRetries` to zero so one `stream()` call makes one provider request. The removed profile fields `maxRetries` and `maxRetryDelayMs` fail load instead of silently multiplying or hiding the separately composed agent-level retry budget. Idle expiry aborts the SDK's stable request signal and surfaces `TIMEOUT`; an earlier caller abort remains `ABORTED`. @@ -163,15 +163,15 @@ pi-ai installs several provider SDKs and lazy-loads the one selected by the cata #### What the model sees -The selected catalog model receives `GenerateOptions.system`, history, tools, and sampling fields supported by pi-ai's common streaming API. This package adds no prompt prose. Provider-native replay metadata is restored only when the adapter validates it for the historical content. +The selected catalog model receives `GenerateOptions.system`, history, tools, and sampling fields supported by pi-ai's common streaming API. This package adds no prompt prose, with one exception: when a request's accumulated base64 image payload exceeds the route's `maxRequestImageBytes`, each offloaded image (oldest first) is replaced by fixed text. The text tells the model to read the file again when a path is available or ask the user to attach the image again. Provider-native replay metadata is restored only when the adapter validates it for the historical content. #### Token effect -Provider tokenization governs exact input. Conversion adds no model-visible text; replay metadata may let a native API reuse provider-side state. +Provider tokenization governs exact input. Conversion adds no model-visible text beyond the image-offload placeholder, which replaces the offloaded image's visual tokens with a short fixed sentence; replay metadata may let a native API reuse provider-side state. #### KV Cache effect -Conversion preserves logical request order without adding text, while the selected provider's serialization and replay state determine reuse. Changing adapter instance, provider, model, or any upstream request token may prevent reuse from the first difference. +Conversion preserves logical request order without adding text, while the selected provider's serialization and replay state determine reuse. Changing adapter instance, provider, model, or any upstream request token may prevent reuse from the first difference. Crossing the image bound rewrites an early message (the newly offloaded image becomes placeholder text), so reuse ends at that message until the offloaded prefix stabilizes. ### Provider response @@ -189,6 +189,7 @@ Recorded response content appends to the next request and does not invalidate it ## Known Limitations and Deferred Work +- **`maxRequestImageBytes` counts base64 image payload only** — text, tools, and JSON structure ride outside the bound, so it must sit below the gateway's request-body cap with headroom. Offload is decided at request conversion as a pure function of history and configuration and is not recorded as a session event; per-route capability metadata (image count, per-image size, total request size) driving admission and assembly together is deferred design work. - **A provider that authenticates through OAuth alone is not offered** — pi-ai resolves OAuth from a *stored* OAuth credential, and this adapter builds its `Models` collection with no credential store and runs no login flow, so every request on such a route fails `Provider is not configured` before it goes out. The configurable-provider directory withholds them; `openai-codex` is the only one the installed catalog ships. A route a settings document already names keeps its entry so a configuration surface can edit or delete it, and `apiKeyEnv` still authenticates it with that key — which for Codex is a token that expires with nothing here to refresh it. - **Provider-native discovery reads the process environment only** — a route naming no credential defers to the catalog provider's own resolution, which interrogates environment variables (`AZURE_OPENAI_API_KEY`, `AWS_PROFILE`, `AWS_ACCESS_KEY_ID`, and each provider's own set). It reads no local credential directory, so `~/.aws/credentials` without an exported `AWS_PROFILE` resolves as unconfigured, and a value held by the harness credential seam is invisible to it unless the process environment carries it too. - **Settings can add or override routes, not remove composition routes** — the user layer merges over the composition `base`, so deleting a `cordis.yml`-provided provider is a composition change; `replace` on the namespace only resets the user layer. @@ -201,4 +202,4 @@ Recorded response content appends to the next request and does not invalidate it - **`GenerateOptions.stop` is unsupported** — pi-ai's common stream options cannot guarantee stop-sequence behavior across providers, so the adapter rejects the field. - **In-history `system` messages use pi-ai's common context conversion** — provider-specific placement follows pi-ai rather than a harness-owned wire override. - **Provider HTTP status is unavailable** — pi-ai error events do not expose a stable HTTP status across providers; failures expose only stable harness error codes. -- **Retry policy is provider-owned, not an SDK retry** — each provider profile may configure nested `retryPolicy`, which `dsh-llm-retry` executes at the agent failed-step extension point; pi-ai SDK retries stay disabled so durable agent steps and `llm/retry` events own every visible attempt, and direct `ctx.llm.stream()` calls remain single-attempt. +- **Retry policy is provider-owned, not an SDK retry** — each provider profile may supply nested `retryPolicy`; omission resolves to normal mode with five retries, and the effective route policy is what `dsh-llm-retry` executes at the agent failed-step extension point. pi-ai SDK retries stay disabled so durable agent steps and `llm/retry` events own every visible attempt, and direct `ctx.llm.stream()` calls remain single-attempt. diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index 621d67d1c1..cace9d1fdf 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -8,7 +8,7 @@ ## 配置 -按提供方配置凭据、模型 catalog 与部署特定传输设置,并以提供方路由本身为键。`apiKeyEnv` 是按请求解析的凭据*引用*,因此机密不进入该文件。省略它会让该路由处于未认证状态;对已安装 catalog 路由而言,这意味着交给 pi-ai 的提供方原生环境发现。已配置却解析不出任何值的引用则相反,会让请求以 `MISSING_CREDENTIAL` 失败,因为放行下去就会用环境里恰好持有的某个无关密钥完成认证。一条凭据服务该路由下的全部模型。 +按提供方配置凭据、模型 catalog 与部署特定传输设置,并以提供方路由本身为键。每个 profile 都可以设置 `retryPolicy`;省略时使用 normal 模式并重试五次。`apiKeyEnv` 是按请求解析的凭据*引用*,因此机密不进入该文件。省略它会让该路由处于未认证状态;对已安装 catalog 路由而言,这意味着交给 pi-ai 的提供方原生环境发现。已配置却解析不出任何值的引用则相反,会让请求以 `MISSING_CREDENTIAL` 失败,因为放行下去就会用环境里恰好持有的某个无关密钥完成认证。一条凭据服务该路由下的全部模型。 ```yaml - id: llm @@ -114,7 +114,7 @@ profile 的 `models` 列表是*替换*该路由已安装 catalog,而不是扩 **没有**这份元数据的模型——条目未声明 `reasoningEfforts` 的手工声明模型,以及 pi-ai 标记为不具备推理能力的 catalog 模型——完全不公开 `reasoning`。pi-ai 会把这类模型报告为只支持 `off` 一档,但 `off` 会被翻译成*省略* reasoning 选项,而那与「不点名任何档位」产出的请求逐字节相同:选它关不掉任何东西,于是自身默认就在思考的提供方,会在界面显示 `off` 被选中的同时继续思考。把该能力报告为不可用,界面就只剩提供方默认这一项,不会再出现自相矛盾的控件。配置 profile 的 `reasoning` 值(包括 `off`)在存在时是部署默认值;省略它会保留提供方默认值。每次请求的 `GenerateOptions.reasoningEffort` 优先;未出现在确切模型能力中的档位会让**请求**在网络 I/O 前以 `UNSUPPORTED_REASONING_EFFORT` 失败,而不会被自动调整。**描述**一个模型则从不这样失败:同一提供方下各模型接受的档位并不一致,因此 `resolveModel` 对该模型拿不下的 profile 档位报告为「没有默认值」,而不是抛错。在那里抛错会让整个提供方从任何基于它构建的模型目录中消失——一个配错的 profile 字段连支持该档位的模型也一并藏起来——所以坏配置暴露在被执行处,而不是被描述处。pi-ai 的通用流选项通过省略 `reasoning` 表示 `off`。 -受支持的 profile 字段是 `apiKeyEnv`、`displayName`、`api`、`baseURL`、`models`、`modelOverrides`、`compat`、`defaultContextWindow`、`defaultMaxTokens`、`defaultInput`、`headers`、`reasoning`、`thinkingBudgets`、`cacheRetention`、`transport`、`timeoutMs`、`websocketConnectTimeoutMs`、`streamIdleTimeoutMs` 和 `retryPolicy`。每个 profile 的可选重试策略都会与该提供方路由一同捕获;省略时使用有界的常规默认值。流空闲间隔必须是正的有限 Node 定时器延迟,默认为五分钟,且只覆盖未完成提供方读取,不包括消费方思考时间。若已配置标头中有同名项,则以 Harness 应用归因为准。 +受支持的 profile 字段是 `apiKeyEnv`、`displayName`、`api`、`baseURL`、`models`、`modelOverrides`、`compat`、`defaultContextWindow`、`defaultMaxTokens`、`defaultInput`、`headers`、`reasoning`、`thinkingBudgets`、`cacheRetention`、`transport`、`timeoutMs`、`websocketConnectTimeoutMs`、`streamIdleTimeoutMs`、`maxRequestImageBytes` 和 `retryPolicy`。每条 profile 解析后的重试策略会随该提供方路由一同捕获;省略时使用共享的有界 normal 默认值并重试五次。流空闲间隔必须是正的有限 Node 定时器延迟,默认为五分钟,且只覆盖未完成提供方读取,不包括消费方思考时间。`maxRequestImageBytes` 约束单个请求的 base64 编码图片载荷(默认 20MiB,正整数):历史中的每张图片都会重新编码进每个请求,累积载荷超过上限时,从最老的图片开始替换为固定文本占位,直到请求装得下,使图片较多的会话保持可用,而不是被网关请求体上限永久拒绝。默认值为系统提示词、历史、工具与 JSON 保留请求容量;网关更严格的部署按路由调低该值。若已配置标头中有同名项,则以 Harness 应用归因为准。 适配器强制 pi-ai SDK `maxRetries` 为零,因此一次 `stream()` 调用只会发起一次提供方请求。已移除 profile 字段 `maxRetries` 和 `maxRetryDelayMs` 会使加载失败,而不是静默倍增或隐藏单独组合的 agent(智能体)级重试预算。空闲超时会 abort SDK 的稳定请求信号,并以 `TIMEOUT` 呈现;较早的调用方 abort 仍为 `ABORTED`。 @@ -164,15 +164,15 @@ pi-ai 会安装多个提供方 SDK,并延迟加载 catalog 模型所选的 SDK #### 模型看到的内容 -所选 catalog 模型会收到 `GenerateOptions.system`、历史、工具,以及 pi-ai 通用流式 API 支持的采样字段。本包不添加提示词文本。只有当适配器验证提供方原生回放元数据与历史内容匹配时,才会恢复这些元数据。 +所选 catalog 模型会收到 `GenerateOptions.system`、历史、工具,以及 pi-ai 通用流式 API 支持的采样字段。本包不添加提示词文本,仅有一个例外:请求累积的 base64 图片载荷超过路由的 `maxRequestImageBytes` 时,被 offload 的图片(从最老开始)会被替换为一段固定文本。该文本要求模型在有路径时重新读取文件,否则请用户重新附上图片。只有当适配器验证提供方原生回放元数据与历史内容匹配时,才会恢复这些元数据。 #### Token 影响 -精确输入取决于提供方 tokenization。转换不添加模型可见文本;回放元数据可能让原生 API 复用提供方侧状态。 +精确输入取决于提供方 tokenization。除图片 offload 占位文本外,转换不添加模型可见文本;占位文本用一句固定短句替代被省略图片的视觉 token。回放元数据可能让原生 API 复用提供方侧状态。 #### KV Cache 影响 -转换保留逻辑请求顺序,不添加文本;复用取决于所选提供方的序列化与回放状态。更改适配器实例、提供方、模型或任何上游请求 token,都可能使复用从首个出现差异的 token 起失效。 +转换保留逻辑请求顺序,不添加文本;复用取决于所选提供方的序列化与回放状态。更改适配器实例、提供方、模型或任何上游请求 token,都可能使复用从首个出现差异的 token 起失效。跨过图片上限会改写较早的一条消息(新被 offload 的图片变为占位文本),复用在该消息处截止,直到被 offload 的前缀稳定。 ### 提供方响应 @@ -190,6 +190,7 @@ pi-ai 事件会变为 harness 推理、文本、工具调用、usage 与 finish ## 已知限制与暂缓事项 +- **`maxRequestImageBytes` 只统计 base64 图片载荷**:文本、工具与 JSON 结构不计入上限,因此该值必须低于网关请求体上限并留出余量。offload 在请求转换时决定,是历史与配置的纯函数,不记录为会话事件;由按路由能力元数据(图片数量、单图大小、请求总大小)同时驱动准入与组装的完整设计属于暂缓工作。 - **仅以 OAuth 认证的提供方不予提供**:pi-ai 的 OAuth 只从*已存储*的 OAuth 凭据解析,而本适配器构造 `Models` 集合时不注入凭据存储、也不运行登录流程,因此这类路由的每个请求都会在发出之前以 `Provider is not configured` 失败。可配置提供方目录因此不列出它们;已安装 catalog 中只有 `openai-codex` 属于此类。settings 文档已经写过的路由仍保留目录条目,配置界面据此可以编辑或删除;`apiKeyEnv` 也仍能用该密钥完成认证——对 Codex 而言那是一个会过期、且这里没有任何环节会去刷新的 token。 - **提供方自带的凭据发现只读进程环境**:不指定凭据的路由交由 catalog 提供方自行解析,而它探测的是环境变量(`AZURE_OPENAI_API_KEY`、`AWS_PROFILE`、`AWS_ACCESS_KEY_ID` 以及各提供方自己的那一组)。它不读任何本地凭据目录,因此只有 `~/.aws/credentials` 而未导出 `AWS_PROFILE` 会被解析为未配置;由 harness 凭据 seam 保管的值,除非进程环境里也有,否则对它不可见。 - **settings 能新增或覆盖路由,但不能移除组合路由**:用户层合并在组合 `base` 之上,因此删除 `cordis.yml` 提供的提供方属于组合变更;对该 namespace 执行 `replace` 只会重置用户层。 @@ -202,4 +203,4 @@ pi-ai 事件会变为 harness 推理、文本、工具调用、usage 与 finish - **不支持 `GenerateOptions.stop`**:pi-ai 的通用流选项无法保证所有提供方都支持 stop sequence,因此适配器会拒绝该字段。 - **历史中的 `system` 消息使用 pi-ai 通用上下文转换**:提供方特定位置由 pi-ai 决定,而非由 harness 拥有的协议覆盖决定。 - **无法获取提供方 HTTP 状态**:pi-ai 错误事件不会在所有提供方上公开稳定 HTTP 状态;失败只公开稳定 harness 错误 code。 -- **重试策略由提供方持有,而不是 SDK 重试**:每个提供方 profile 都可以配置嵌套的 `retryPolicy`,由 `dsh-llm-retry` 在 agent 的失败步骤扩展点上执行;pi-ai SDK 重试仍保持禁用,因此持久化的 agent 步骤与 `llm/retry` 事件记录每次可见尝试,直接 `ctx.llm.stream()` 调用仍只尝试一次。 +- **重试策略由提供方持有,而不是 SDK 重试**:每个提供方 profile 都可以提供嵌套的 `retryPolicy`;省略时解析为 normal 模式并重试五次,`dsh-llm-retry` 会在 agent 的失败步骤扩展点上执行有效路由策略。pi-ai SDK 重试仍保持禁用,因此持久化的 agent 步骤与 `llm/retry` 事件记录每次可见尝试,直接 `ctx.llm.stream()` 调用仍只尝试一次。 diff --git a/packages/llm/llm-pi-ai/src/adapter.ts b/packages/llm/llm-pi-ai/src/adapter.ts index ab1c784351..5ecec593da 100644 --- a/packages/llm/llm-pi-ai/src/adapter.ts +++ b/packages/llm/llm-pi-ai/src/adapter.ts @@ -317,7 +317,7 @@ export class PiAiAdapter extends LlmAdapter { } const context = attachments === undefined ? toPiContext(options, undefined, onReplayDegrade) - : await toPiContext(options, attachments, onReplayDegrade) + : await toPiContext(options, attachments, onReplayDegrade, profile.maxRequestImageBytes) const events = snapshot.models.streamSimple(model, context, { ...profileOptions(profile, reasoning, apiKey), ...options.temperature === undefined ? {} : { temperature: options.temperature }, diff --git a/packages/llm/llm-pi-ai/src/config.ts b/packages/llm/llm-pi-ai/src/config.ts index 4e8e032df0..d1e1f697a9 100644 --- a/packages/llm/llm-pi-ai/src/config.ts +++ b/packages/llm/llm-pi-ai/src/config.ts @@ -34,6 +34,17 @@ import { buildProvider, supportedProtocols } from './provider.ts' /** Default maximum idle interval while an adapter stream read is outstanding. */ export const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000 +/** + * Default request-level bound on base64-encoded image payload. Every image in + * history is re-encoded into every request body, so an unbounded conversation + * eventually exceeds a provider or gateway request-size cap and the session + * can never complete another request. The 20MiB default admits four images at + * the attachment store's 3.5MiB raw-image default after base64 expansion and + * reserves request capacity for system prompts, history, tools, and JSON. + * Deployments behind stricter gateways lower it per route. + */ +export const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024 + /** Context capacity assumed for a model neither configuration nor the catalog sizes. */ export const DEFAULT_CONTEXT_WINDOW = 262_144 @@ -136,7 +147,14 @@ export interface PiAiProviderProfile { websocketConnectTimeoutMs?: number /** Maximum provider idle time while one stream read is outstanding. */ streamIdleTimeoutMs?: number - /** Provider-owned model-request retry policy; omission uses normal defaults. */ + /** + * Maximum base64-encoded image payload per request. When a request's + * accumulated images exceed it, the oldest images are replaced by text + * placeholders until the request fits, so a long session keeps completing + * requests instead of being rejected by a request-size cap. + */ + maxRequestImageBytes?: number + /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig } @@ -151,6 +169,8 @@ export interface ResolvedPiAiProviderProfile apiKeyEnv?: CredentialRef /** Positive finite provider-idle interval after defaulting. */ streamIdleTimeoutMs: number + /** Positive request-level base64 image payload bound after defaulting. */ + maxRequestImageBytes: number /** Immutable retry policy captured with this provider route. */ retryPolicy: ResolvedRetryPolicy /** @@ -248,6 +268,7 @@ const profile = z.object({ timeoutMs: z.natural(), websocketConnectTimeoutMs: z.natural(), streamIdleTimeoutMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_STREAM_IDLE_TIMEOUT_MS), + maxRequestImageBytes: z.number().step(1).min(1).default(DEFAULT_MAX_REQUEST_IMAGE_BYTES), retryPolicy: RetryPolicySchema, }) @@ -323,6 +344,10 @@ export function resolveProfiles( `llm-pi-ai: provider "${provider}" streamIdleTimeoutMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`, ) } + const maxRequestImageBytes = source.maxRequestImageBytes ?? DEFAULT_MAX_REQUEST_IMAGE_BYTES + if (!Number.isInteger(maxRequestImageBytes) || maxRequestImageBytes <= 0) { + throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImageBytes must be a positive integer`) + } // Detached from the configuration object because pi-ai types `Model.input` // mutable. The schema's explicit default covers an absent key, so an empty // list here is always one someone typed — and unlike an entry's, nothing @@ -354,6 +379,7 @@ export function resolveProfiles( displayName, ...apiKeyEnv === undefined ? {} : { apiKeyEnv: credentialRef(apiKeyEnv) }, streamIdleTimeoutMs, + maxRequestImageBytes, retryPolicy: resolveRetryPolicy(retryPolicy, `llm-pi-ai: provider "${provider}" retryPolicy`), ...rest.headers === undefined ? {} : { headers: { ...rest.headers } }, ...rest.thinkingBudgets === undefined ? {} : { thinkingBudgets: { ...rest.thinkingBudgets } }, diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index dcbaabc815..5a2d330b7d 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -26,17 +26,82 @@ function toolResultText(blocks: readonly ContentBlock[]): string { : block.type === 'tool-result' ? toolResultText(block.content) : '').join('') } +/** Model-facing stand-in for an image dropped to fit the request bound. */ +export const OFFLOADED_IMAGE_TEXT + = '[image omitted to keep the request within its image limit; older images are omitted first. If this image is still needed, read its file again when a path is available; otherwise ask the user to attach it again.]' + +/** Base64 length of `bytes` raw bytes (4 output characters per 3 input bytes, padded). */ +function base64Length(bytes: number): number { + return Math.ceil(bytes / 3) * 4 +} + +/** + * Select the images a request must drop to fit the per-request payload bound. + * History order is oldest-first, so the most recent images are omitted last. + * A single image larger than the bound is itself omitted. Locations use + * message and nested block indexes so JSON replay cannot change the result by + * splitting or preserving shared object identities. + * @param messages - complete request history, oldest first. + * @param maxRequestImageBytes - bound on total base64-encoded image payload; undefined leaves every image in place. + * @returns the image locations the conversion replaces with {@link OFFLOADED_IMAGE_TEXT}. + */ +function offloadedImages( + messages: readonly Message[], + maxRequestImageBytes: number | undefined, +): ReadonlySet { + const offloaded = new Set() + if (maxRequestImageBytes === undefined) return offloaded + const images: { location: string; base64Bytes: number }[] = [] + const collect = (messageIndex: number, blocks: readonly ContentBlock[], prefix: readonly number[] = []): void => { + for (const [blockIndex, block] of blocks.entries()) { + const path = [...prefix, blockIndex] + if (block.type === 'image') { + images.push({ + location: `${messageIndex}:${path.join('.')}`, + base64Bytes: base64Length(block.attachment.bytes), + }) + } else if (block.type === 'tool-result') { + collect(messageIndex, block.content, path) + } + } + } + for (const [messageIndex, message] of messages.entries()) collect(messageIndex, message.content) + let total = images.reduce((sum, image) => sum + image.base64Bytes, 0) + for (const image of images) { + if (total <= maxRequestImageBytes) break + offloaded.add(image.location) + total -= image.base64Bytes + } + return offloaded +} + +interface LocatedContentBlock { + readonly block: ContentBlock + readonly path: readonly number[] +} + +/** Attach stable nested indexes to blocks from one message. */ +function locatedBlocks(blocks: readonly ContentBlock[], prefix: readonly number[] = []): LocatedContentBlock[] { + return blocks.map((block, index) => ({ block, path: [...prefix, index] })) +} + async function userContent( - blocks: readonly ContentBlock[], + blocks: readonly LocatedContentBlock[], attachments: AttachmentStore, + offloaded: ReadonlySet, + messageIndex: number, ): Promise { const content: (TextContent | ImageContent)[] = [] - for (const block of blocks) { + for (const { block, path } of blocks) { switch (block.type) { case 'text': if (block.text.length > 0) content.push({ type: 'text', text: block.text }) break case 'image': { + if (offloaded.has(`${messageIndex}:${path.join('.')}`)) { + content.push({ type: 'text', text: OFFLOADED_IMAGE_TEXT }) + break + } const stored = await attachments.readImage(block.attachment) content.push({ type: 'image', @@ -47,7 +112,7 @@ async function userContent( } case 'tool-result': { - const nested = await userContent(block.content, attachments) + const nested = await userContent(locatedBlocks(block.content, path), attachments, offloaded, messageIndex) if (typeof nested === 'string') { if (nested.length > 0) content.push({ type: 'text', text: nested }) } else { @@ -136,36 +201,44 @@ export function toPiContext( ): PiContext /** * Convert harness history to a pi-ai Context while resolving durable images. - * Tool result names are recovered from preceding assistant tool calls. + * Tool result names are recovered from preceding assistant tool calls. When + * the accumulated base64 image payload exceeds `maxRequestImageBytes`, the + * oldest images are replaced by text placeholders until the request fits, so + * an image-heavy session keeps clearing gateway request-size caps. * @param options - the harness request; `options.system` maps to pi-ai's single `systemPrompt` slot. * @param attachments - durable byte resolver for image references. * @param onReplayDegrade - forwarded to {@link toPiAssistant} for each assistant message. + * @param maxRequestImageBytes - request-level bound on base64-encoded image payload; omission leaves every image in place. * @returns the asynchronously resolved pi-ai context. */ export function toPiContext( options: GenerateOptions, attachments: AttachmentStore, onReplayDegrade?: (reason: string) => void, + maxRequestImageBytes?: number, ): Promise export function toPiContext( options: GenerateOptions, attachments?: AttachmentStore, onReplayDegrade?: (reason: string) => void, + maxRequestImageBytes?: number, ): PiContext | Promise { return attachments === undefined ? textOnlyContext(options, onReplayDegrade) - : toPiContextWithImages(options, attachments, onReplayDegrade) + : toPiContextWithImages(options, attachments, onReplayDegrade, maxRequestImageBytes) } async function toPiContextWithImages( options: GenerateOptions, attachments: AttachmentStore, onReplayDegrade?: (reason: string) => void, + maxRequestImageBytes?: number, ): Promise { + const offloaded = offloadedImages(options.messages, maxRequestImageBytes) const toolNames = new Map() const messages: PiMessage[] = [] - for (const message of options.messages) { + for (const [messageIndex, message] of options.messages.entries()) { if (message.role === 'system') { if (contentHasImage(message.content)) { throw new LlmError('pi-ai cannot represent an image in an in-history system message', 'UNSUPPORTED_CONTENT') @@ -185,14 +258,17 @@ async function toPiContextWithImages( continue } // user role: text + tool results (each result becomes its own message). - const regular = message.content.filter(block => block.type !== 'tool-result') - const content = await userContent(regular, attachments) - const results = message.content.filter(block => block.type === 'tool-result') + const located = locatedBlocks(message.content) + const regular = located.filter(({ block }) => block.type !== 'tool-result') + const content = await userContent(regular, attachments, offloaded, messageIndex) + const results = located.filter((entry): entry is LocatedContentBlock & { block: Extract } => ( + entry.block.type === 'tool-result' + )) if (content.length > 0 || results.length === 0) { messages.push({ role: 'user', content, timestamp: 0 }) } - for (const result of results) { - const resultContent = await userContent(result.content, attachments) + for (const { block: result, path } of results) { + const resultContent = await userContent(locatedBlocks(result.content, path), attachments, offloaded, messageIndex) messages.push({ role: 'toolResult', toolCallId: result.toolCallId, diff --git a/packages/llm/llm-pi-ai/src/stream.ts b/packages/llm/llm-pi-ai/src/stream.ts index 22aa7cb579..d45df45a39 100644 --- a/packages/llm/llm-pi-ai/src/stream.ts +++ b/packages/llm/llm-pi-ai/src/stream.ts @@ -40,6 +40,9 @@ function classifyPiAiError(message: string): string { if (/\b(?:401|403)\b/.test(message)) return 'AUTH' if (isQuotaExceededError(message)) return QUOTA_EXCEEDED_CODE if (/\b429\b|rate.?limit/i.test(message)) return 'RATE_LIMIT' + // A rejected request body (gateway or provider size cap): resending the + // same request cannot succeed, so it is invalid, not transient. + if (/\b413\b|failed to buffer the request body:\s*length limit exceeded|payload too large|request body too large/i.test(message)) return 'INVALID_REQUEST' if (/\b400\b|invalid.?request/i.test(message)) return 'INVALID_REQUEST' if (/\b5\d\d\b/.test(message)) return 'SERVER' if (/\btime(?:d)?\s*out\b|timeout/i.test(message)) return 'TIMEOUT' diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts index 8a99887b56..d45a2e3089 100644 --- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts +++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts @@ -12,7 +12,7 @@ import * as LlmPiAi from '@deepseek-ai/dsh-llm-pi-ai' import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { getBuiltinModels } from '@earendil-works/pi-ai/providers/all' -import { resolveProfiles } from '../src/config.ts' +import { DEFAULT_MAX_REQUEST_IMAGE_BYTES, resolveProfiles } from '../src/config.ts' import { assemble } from './assemble.ts' import { closeMockServers, mockServer, textEvents } from './mock-server.ts' @@ -392,7 +392,7 @@ describe('provider profile lifecycle', () => { }) expect(ctx.llm.providerRetryPolicy('anthropic')).toMatchObject({ mode: 'normal', - maxRetries: 2, + maxRetries: 5, }) await fiber.dispose() expect(ctx.llm.listProviders()).toEqual([]) @@ -697,6 +697,7 @@ describe('provider profile lifecycle', () => { }) it('validates empty, underspecified, legacy-shaped, and explicitly blank profiles', () => { + expect(DEFAULT_MAX_REQUEST_IMAGE_BYTES).toBe(20 * 1024 * 1024) // Empty and omitted dicts are the dormant zero-route posture, not errors. expect(resolveProfiles({}).size).toBe(0) expect(resolveProfiles(undefined).size).toBe(0) @@ -710,6 +711,11 @@ describe('provider profile lifecycle', () => { expect(() => resolveProfiles({ openai: { provider: 'openai' } as never })).toThrow(/moved to the providers dict key/) expect(() => resolveProfiles({ openai: { baseURL: '' } })).toThrow(/empty baseURL/) expect(() => resolveProfiles({ openai: { apiKeyEnv: 'not-a-var!' } })).toThrow(/must match/) + expect(() => resolveProfiles({ openai: { maxRequestImageBytes: 0 } })).toThrow(/maxRequestImageBytes/) + expect(resolveProfiles({ openai: {} }).get('openai')?.maxRequestImageBytes) + .toBe(DEFAULT_MAX_REQUEST_IMAGE_BYTES) + expect(resolveProfiles({ openai: { maxRequestImageBytes: 1024 } }).get('openai')?.maxRequestImageBytes) + .toBe(1024) }) it.each(['maxRetries', 'maxRetryDelayMs'] as const)( @@ -731,6 +737,9 @@ describe('provider profile lifecycle', () => { { streamIdleTimeoutMs: 0 }, { streamIdleTimeoutMs: Number.NaN }, { streamIdleTimeoutMs: MAX_TIMER_DELAY_MS + 1 }, + { maxRequestImageBytes: 0 }, + { maxRequestImageBytes: 1.5 }, + { maxRequestImageBytes: Number.NaN }, ] for (const entry of invalid) { const ctx = new Context() diff --git a/packages/llm/llm-pi-ai/tests/context.spec.ts b/packages/llm/llm-pi-ai/tests/context.spec.ts index 01ed3d080c..be41a12b07 100644 --- a/packages/llm/llm-pi-ai/tests/context.spec.ts +++ b/packages/llm/llm-pi-ai/tests/context.spec.ts @@ -3,7 +3,7 @@ import { AttachmentId } from '@deepseek-ai/dsh-attachment' import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import { CallId, createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, Message } from '@deepseek-ai/dsh-llm' -import { toPiContext } from '../src/context.ts' +import { OFFLOADED_IMAGE_TEXT, toPiContext } from '../src/context.ts' import { toPiAssistant } from '../src/replay.ts' const ref: ImageAttachmentRef = { @@ -140,6 +140,92 @@ describe('pi-ai request context conversion', () => { ]) }) + it('replaces the oldest images with placeholders once the request payload bound is exceeded', async () => { + const readImage = vi.fn(() => Promise.resolve({ ref: { ...ref, bytes: 3 }, data: Uint8Array.of(1, 2, 3) })) + const store = { readImage } as unknown as AttachmentStore + const sized: ImageAttachmentRef = { ...ref, bytes: 3 } + const callId = CallId('shot-call') + // Three 3-byte images cost 4 base64 characters each (12 total); a bound of + // 8 forces exactly the oldest one out, including one nested in a tool result. + const context = await toPiContext(request([ + user([{ + type: 'tool-result', + toolCallId: callId, + content: [{ type: 'image', attachment: sized }], + }]), + user([{ type: 'image', attachment: sized }, { type: 'text', text: 'newer' }]), + user([{ type: 'image', attachment: sized }]), + ]), store, undefined, 8) + + expect(context.messages).toEqual([ + { + role: 'toolResult', + toolCallId: 'shot-call', + toolName: 'unknown', + content: [{ type: 'text', text: OFFLOADED_IMAGE_TEXT }], + isError: false, + timestamp: 0, + }, + { + role: 'user', + content: [ + { type: 'image', data: 'AQID', mimeType: 'image/png' }, + { type: 'text', text: 'newer' }, + ], + timestamp: 0, + }, + { role: 'user', content: [{ type: 'image', data: 'AQID', mimeType: 'image/png' }], timestamp: 0 }, + ]) + expect(readImage).toHaveBeenCalledTimes(2) + }) + + it('keeps every image at exactly the payload bound and drops all of them when even the newest cannot fit', async () => { + const sized: ImageAttachmentRef = { ...ref, bytes: 3 } + const exact = await toPiContext(request([ + user([{ type: 'image', attachment: sized }]), + user([{ type: 'image', attachment: sized }]), + ]), attachments, undefined, 8) + expect(exact.messages).toEqual([ + { role: 'user', content: [expect.objectContaining({ type: 'image' })], timestamp: 0 }, + { role: 'user', content: [expect.objectContaining({ type: 'image' })], timestamp: 0 }, + ]) + + const readImage = vi.fn() + const store = { readImage } as unknown as AttachmentStore + const oversized = await toPiContext(request([ + user([{ type: 'image', attachment: { ...ref, bytes: 300 } }]), + ]), store, undefined, 8) + // All-text content collapses to the string form; the placeholder still reaches the model. + expect(oversized.messages).toEqual([ + { role: 'user', content: OFFLOADED_IMAGE_TEXT, timestamp: 0 }, + ]) + expect(readImage).not.toHaveBeenCalled() + }) + + it('offloads repeated image-block occurrences by position rather than shared object identity', async () => { + const sized: ImageAttachmentRef = { ...ref, bytes: 3 } + const shared: ContentBlock = { type: 'image', attachment: sized } + const readImage = vi.fn(() => Promise.resolve({ ref: sized, data: Uint8Array.of(1, 2, 3) })) + const store = { readImage } as unknown as AttachmentStore + const aliased = await toPiContext(request([user([shared, shared])]), store, undefined, 4) + const replayed = await toPiContext(request([user([ + { type: 'image', attachment: { ...sized } }, + { type: 'image', attachment: { ...sized } }, + ])]), store, undefined, 4) + + const expected = [{ + role: 'user', + content: [ + { type: 'text', text: OFFLOADED_IMAGE_TEXT }, + { type: 'image', data: 'AQID', mimeType: 'image/png' }, + ], + timestamp: 0, + }] + expect(aliased.messages).toEqual(expected) + expect(replayed.messages).toEqual(expected) + expect(readImage).toHaveBeenCalledTimes(2) + }) + it('keeps empty text-only users while separating result-only messages', () => { const callId = CallId('unknown-call') expect(toPiContext(request([ diff --git a/packages/llm/llm-pi-ai/tests/convert.spec.ts b/packages/llm/llm-pi-ai/tests/convert.spec.ts index 1a42e4b085..2a3b41b0c4 100644 --- a/packages/llm/llm-pi-ai/tests/convert.spec.ts +++ b/packages/llm/llm-pi-ai/tests/convert.spec.ts @@ -779,6 +779,16 @@ describe('mapStopReason / mapUsage', () => { stopReason: 'error', errorMessage: 'HTTP 400: invalid input: temperature exceeds maximum allowed value', }))).toMatchObject({ kind: 'error', failure: { code: 'INVALID_REQUEST' } }) + expect(mapStopReason(assistant({ stopReason: 'error', errorMessage: 'HTTP 413: Payload Too Large' }))) + .toMatchObject({ kind: 'error', failure: { code: 'INVALID_REQUEST' } }) + expect(mapStopReason(assistant({ + stopReason: 'error', + errorMessage: 'Failed to buffer the request body: length limit exceeded', + }))).toMatchObject({ kind: 'error', failure: { code: 'INVALID_REQUEST' } }) + expect(mapStopReason(assistant({ + stopReason: 'error', + errorMessage: 'vector length limit exceeded', + }))).toMatchObject({ kind: 'error', failure: { code: 'PI_AI_ERROR' } }) }) it.each([ diff --git a/assets/community-wecom-survey.png b/packages/llm/llm-pi-ai/tests/fixtures/qr-code.png similarity index 100% rename from assets/community-wecom-survey.png rename to packages/llm/llm-pi-ai/tests/fixtures/qr-code.png diff --git a/packages/llm/llm-pi-ai/tests/provider-apis.e2e.ts b/packages/llm/llm-pi-ai/tests/provider-apis.e2e.ts index e4c15bb34e..1fe529336f 100644 --- a/packages/llm/llm-pi-ai/tests/provider-apis.e2e.ts +++ b/packages/llm/llm-pi-ai/tests/provider-apis.e2e.ts @@ -210,7 +210,7 @@ for (const profile of providerCases) { if (profile.provider === 'anthropic') { it('sends a real image through the authenticated Anthropic visual path', async () => { const data = new Uint8Array(await readFile( - new URL('../../../../assets/community-wecom-survey.png', import.meta.url), + new URL('./fixtures/qr-code.png', import.meta.url), )) const ref: ImageAttachmentRef = { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), diff --git a/packages/llm/llm-retry/README.i18n.yaml b/packages/llm/llm-retry/README.i18n.yaml index fd2395c33f..2c468f9bc1 100644 --- a/packages/llm/llm-retry/README.i18n.yaml +++ b/packages/llm/llm-retry/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/llm/llm-retry/README.md -README.md: 0a907b5505650f7c2cd5e9933750be3701f8e34b -README.zh.md: 024545e1ed52bb8d4aeac8114ffafc26a04a2ddb +README.md: 1dd530051e387230510414e35701db10c7c7c063 +README.zh.md: 52badf6a6e7d2c2571fa951865f6b4b3f08ae4ad diff --git a/packages/llm/llm-retry/README.md b/packages/llm/llm-retry/README.md index 0a907b5505..1dd530051e 100644 --- a/packages/llm/llm-retry/README.md +++ b/packages/llm/llm-retry/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Function plugin that applies exact-provider retry policy through the agent loop's closed-step `agent/request-error` waterfall. It does not wrap `ctx.llm.stream()`: every adapter call remains one provider attempt, and every retry opens a fresh numbered turn. -Each provider adapter owns an optional nested `retryPolicy`, captured when its route registers on `ctx.llm` and carried with each call that reaches that registration's final adapter boundary. An in-flight failure retains that serving policy if the route is later disposed or replaced; a failure before any final adapter is selected has no provider policy and delegates. Omission uses normal mode: two retries for `EMPTY_RESPONSE`, `RATE_LIMIT`, `SERVER`, `TIMEOUT`, and `TRANSPORT`, with bounded exponential backoff from 500 ms to 10 seconds and 10 percent jitter. `EMPTY_RESPONSE` is the adapters' classification of a degenerate provider completion that produced no durable content, so repeating it is safe. A normal policy can change its finite budget, eligible codes, and backoff. Always mode asks downstream recovery first, then retries every model-request failure without an attempt limit; success, cancellation, or plugin disposal stops it after active delegated recovery reaches quiescence. +Each provider adapter owns an optional nested `retryPolicy`, captured when its route registers on `ctx.llm` and carried with each call that reaches that registration's final adapter boundary. An in-flight failure retains that serving policy if the route is later disposed or replaced; a failure before any final adapter is selected has no provider policy and delegates. Omission uses normal mode: five retries for `EMPTY_RESPONSE`, `RATE_LIMIT`, `SERVER`, `TIMEOUT`, and `TRANSPORT`, with bounded exponential backoff from 500 ms to 10 seconds and 10 percent jitter. `EMPTY_RESPONSE` is the adapters' classification of a degenerate provider completion that produced no durable content, so repeating it is safe. A normal policy can change its finite budget, eligible codes, and backoff. Always mode asks downstream recovery first, then retries every model-request failure without an attempt limit; success, cancellation, or plugin disposal stops it after active delegated recovery reaches quiescence. Both modes use bounded exponential backoff with symmetric jitter. A valid `providerRetryAfterMs` at or below `maxDelayMs` replaces local backoff without jitter. An over-cap provider delay makes normal mode delegate, while always mode uses its configured local backoff so it cannot terminate on that instruction. diff --git a/packages/llm/llm-retry/README.zh.md b/packages/llm/llm-retry/README.zh.md index 024545e1ed..52badf6a6e 100644 --- a/packages/llm/llm-retry/README.zh.md +++ b/packages/llm/llm-retry/README.zh.md @@ -4,7 +4,7 @@ 一个函数插件,通过 agent loop(智能体循环)在已关闭步骤上触发的 `agent/request-error` waterfall(瀑布式事件)应用确切提供方重试策略。它不包装 `ctx.llm.stream()`:每次适配器调用仍是一次提供方尝试,每次重试都会开启新的编号轮次。 -每个提供方适配器都拥有可选的嵌套 `retryPolicy`;路由在 `ctx.llm` 上注册时会捕获该策略,任何到达该注册最终适配器边界的调用都会携带它。如果之后释放或替换路由,进行中的失败仍会保留当时为其提供服务的策略;在选中任何最终适配器前发生的失败没有提供方策略,会继续委托。省略策略时使用 normal mode:为 `EMPTY_RESPONSE`、`RATE_LIMIT`、`SERVER`、`TIMEOUT` 和 `TRANSPORT` 重试两次,并采用从 500 ms 到 10 秒的有界指数退避与 10% jitter。`EMPTY_RESPONSE` 是适配器对未产生任何持久内容的退化提供方完成所作的分类,因此可安全重复。normal 策略可以更改其有限预算、符合条件的 code 和退避配置。always mode 会先请求下游恢复,再无次数上限地重试每个模型请求失败;成功、取消或插件 dispose(资源释放)会在活跃的委托恢复完全停稳后终止它。 +每个提供方适配器都拥有可选的嵌套 `retryPolicy`;路由在 `ctx.llm` 上注册时会捕获该策略,任何到达该注册最终适配器边界的调用都会携带它。如果之后释放或替换路由,进行中的失败仍会保留当时为其提供服务的策略;在选中任何最终适配器前发生的失败没有提供方策略,会继续委托。省略策略时使用 normal mode:为 `EMPTY_RESPONSE`、`RATE_LIMIT`、`SERVER`、`TIMEOUT` 和 `TRANSPORT` 重试五次,并采用从 500 ms 到 10 秒的有界指数退避与 10% jitter。`EMPTY_RESPONSE` 是适配器对未产生任何持久内容的退化提供方完成所作的分类,因此可安全重复。normal 策略可以更改其有限预算、符合条件的 code 和退避配置。always mode 会先请求下游恢复,再无次数上限地重试每个模型请求失败;成功、取消或插件 dispose(资源释放)会在活跃的委托恢复完全停稳后终止它。 两种 mode 都使用带对称 jitter 的有界指数退避。有效 `providerRetryAfterMs` 不超过 `maxDelayMs` 时会替换本地退避,并且不加 jitter。超出上限的提供方延迟会使 normal mode 继续委托;always mode 则改用已配置的本地退避,避免该指令终止重试。 diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml index fce8fa059b..0700b14362 100644 --- a/packages/llm/llm/README.i18n.yaml +++ b/packages/llm/llm/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/llm/llm/README.md -README.md: fb6bd84240b41dd730d45b3eb34c35827dc4c991 -README.zh.md: 5c22767a7c654972cbf614505382fa4755d7d318 +README.md: e6b3c4924ad4e7cf115abdbfb38d22d0f524e377 +README.zh.md: 51f034af632c19ca91c1d2f91a7c9c22714870e0 diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index fb6bd84240..e6b3c4924a 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -8,6 +8,10 @@ Provider-neutral LLM vocabulary and abstract service. This package defines the c An adapter registry plus a single streaming call API, interceptable via a waterfall event. +### Retry policy + +Each provider adapter supplies its resolved route policy. Omitting provider configuration uses bounded normal mode with five retries after the first request. Layered configuration may retain `maxRetries` or `retryableCodes` after changing `mode` to `always`; resolution ignores those inactive normal-mode fields and captures a pure always policy. This service stores the effective policy but does not execute retries. + ### Public API - `ctx.llm.registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle` Register one adapter instance for the given provider routes. Registration is all-or-nothing, and is disposed with the calling fiber. The returned disposer also carries `replace(providers)`: the candidate route set is validated in full before anything moves, so a conflict with another adapter leaves the current routes registered and serving, and the swap itself is one synchronous section with no observable gap. `replace([])` is legal — a registration holding zero routes — unlike an empty initial registration. diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md index 5c22767a7c..51f034af63 100644 --- a/packages/llm/llm/README.zh.md +++ b/packages/llm/llm/README.zh.md @@ -8,6 +8,10 @@ 一个适配器注册表加单一流式调用接口,可通过 waterfall(瀑布式事件)拦截。 +### 重试策略 + +每个提供方适配器都会提供解析后的路由策略。省略提供方配置时使用有界 normal mode,在首次请求后最多重试五次。分层配置把 `mode` 改为 `always` 后可能残留 `maxRetries` 或 `retryableCodes`;解析过程会忽略这些不再生效的 normal-mode 字段,并捕获纯 always 策略。本服务存储有效策略,但不执行重试。 + ### 公开 API - `ctx.llm.registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle` 为给定提供方路由注册一个适配器实例。注册要么全部成功,要么全部不生效,并且会随调用 fiber 一起 dispose(资源释放)。返回的句柄还提供 `replace(providers)`:候选路由集合会在注册状态发生任何变化前完成整体验证,因此与另一适配器发生冲突时,当前路由仍保持注册并继续提供服务。替换会在一次同步操作中完成,不会出现可观察的空档。`replace([])` 合法,表示保留注册但不持有任何路由;初始注册则不得为空。 diff --git a/packages/llm/llm/src/retry-policy.ts b/packages/llm/llm/src/retry-policy.ts index ad9c7af65c..f6e6175cb9 100644 --- a/packages/llm/llm/src/retry-policy.ts +++ b/packages/llm/llm/src/retry-policy.ts @@ -11,7 +11,7 @@ import z from '@deepseek-ai/schemastery' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { EMPTY_RESPONSE_CODE } from './error.ts' -const DEFAULT_MAX_RETRIES = 2 +const DEFAULT_MAX_RETRIES = 5 const DEFAULT_INITIAL_DELAY_MS = 500 const DEFAULT_MAX_DELAY_MS = 10_000 const DEFAULT_JITTER_RATIO = 0.1 @@ -37,7 +37,7 @@ export interface BackoffConfig { export interface NormalRetryPolicyConfig { /** Retry only configured transient failure codes. */ mode: 'normal' - /** Maximum eligible retries after the first request (default 2). */ + /** Maximum eligible retries after the first request (default 5). */ maxRetries?: number /** Stable failure codes eligible for this policy. */ retryableCodes?: string[] @@ -105,7 +105,11 @@ export const RetryPolicySchema: z = z.union([ const NORMAL_POLICY_KEYS: ReadonlySet = new Set([ 'mode', 'maxRetries', 'retryableCodes', 'backoff', ]) -const ALWAYS_POLICY_KEYS: ReadonlySet = new Set(['mode', 'backoff']) +// Layered configuration can retain normal-only fields after switching modes; +// always mode ignores those inactive values while still rejecting unknown keys. +const ALWAYS_POLICY_KEYS: ReadonlySet = new Set([ + 'mode', 'maxRetries', 'retryableCodes', 'backoff', +]) const BACKOFF_KEYS: ReadonlySet = new Set(['initialDelayMs', 'maxDelayMs', 'jitterRatio']) function validateKeys(value: object, allowed: ReadonlySet, path: string): void { diff --git a/packages/llm/llm/tests/retry-policy.spec.ts b/packages/llm/llm/tests/retry-policy.spec.ts index 1860625147..cc7ebb8fa7 100644 --- a/packages/llm/llm/tests/retry-policy.spec.ts +++ b/packages/llm/llm/tests/retry-policy.spec.ts @@ -12,7 +12,7 @@ describe('provider retry policy', () => { expect(policy).toEqual({ mode: 'normal', - maxRetries: 2, + maxRetries: 5, retryableCodes: ['EMPTY_RESPONSE', 'RATE_LIMIT', 'SERVER', 'TIMEOUT', 'TRANSPORT'], initialDelayMs: 500, maxDelayMs: 10_000, @@ -59,6 +59,21 @@ describe('provider retry policy', () => { expect(RetryPolicySchema).toBeDefined() }) + it('ignores normal-only fields retained after switching to always mode', () => { + const layered = { + mode: 'always', + maxRetries: 5, + retryableCodes: ['SERVER'], + } as unknown as RetryPolicyConfig + + expect(resolveRetryPolicy(layered, 'provider.retryPolicy')).toEqual({ + mode: 'always', + initialDelayMs: 500, + maxDelayMs: 10_000, + jitterRatio: 0.1, + }) + }) + it.each([ [{ mode: 'normal', maxRetries: -1 }, /maxRetries/], [{ mode: 'normal', maxRetries: 1.5 }, /maxRetries/], @@ -74,7 +89,6 @@ describe('provider retry policy', () => { [{ mode: 'normal', retryableCodes: [''] }, /non-empty strings/], [{ mode: 'normal', retryableCodes: [429] }, /non-empty strings/], [{ mode: 'normal', maxRetires: 1 }, /unknown key "maxRetires"/], - [{ mode: 'always', maxRetries: 1 }, /unknown key "maxRetries"/], [{ mode: 'always', backoff: { initialDelay: 1 } }, /unknown key "initialDelay"/], [{ mode: 'sometimes' }, /mode must be "normal" or "always"/], ] as const)('rejects invalid policy %#', (config, message) => { diff --git a/packages/llm/llm/tests/service.spec.ts b/packages/llm/llm/tests/service.spec.ts index ed7d8d9bf8..45f523c129 100644 --- a/packages/llm/llm/tests/service.spec.ts +++ b/packages/llm/llm/tests/service.spec.ts @@ -217,7 +217,7 @@ describe('LlmRuntime', () => { expect(ctx.llm.providerRetryPolicy('configured')).toBe(configured) expect(ctx.llm.providerRetryPolicy('defaulted')).toMatchObject({ mode: 'normal', - maxRetries: 2, + maxRetries: 5, }) expect(() => ctx.llm.providerRetryPolicy('missing')).toThrow( expect.objectContaining({ code: 'NO_ADAPTER' }), diff --git a/packages/subagent/README.i18n.yaml b/packages/subagent/README.i18n.yaml index 5a5dc2c181..6b69f7ba0c 100644 --- a/packages/subagent/README.i18n.yaml +++ b/packages/subagent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/README.md -README.md: a863ed3f5ef864b6eb6eb9a7a0c1ee2f40f247d6 -README.zh.md: 1c9bf8ba0814a74c5774d81a34a3266daa9c375b +README.md: 1b3ccb6afba226e0b6bcf9aacd0c9fa752fdfdbb +README.zh.md: a98874baf8d235758dbe370272ecf230cbfb112c diff --git a/packages/subagent/README.md b/packages/subagent/README.md index a863ed3f5e..1b3ccb6afb 100644 --- a/packages/subagent/README.md +++ b/packages/subagent/README.md @@ -18,6 +18,8 @@ This family lets an agent delegate work to child agents. Multiple named provider | [`tool-subagent-control/`](tool-subagent-control/README.md) | Exposes child messaging and listing to the model | registers on `ctx.tools` | | [`tool-subagent-report/`](tool-subagent-report/README.md) | Provides the child-to-parent report channel | registers in child scopes | +The Codex and Claude Code packages are independent optional Profile Bundles. Install either or both with `dsh plugin --profile add @deepseek-ai/dsh-subagent-codex @deepseek-ai/dsh-subagent-claude-code`, then restart that Profile; each package registers only its dormant Host provider. To grant a tool, copy a complete Agent Preset, remove `disabled` from each matching tool row, and start a new Session. Removing one package withdraws only that provider and its private runtime closure on the next Profile start. + See the decisions for the [capability family](../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md), [continuable children](../../.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.md), and [control tools](../../.agents/notes/implemented/simplification/2026-07-26-merge-subagent-control-service.md). The subsystem reference — start requests, results, live runs, the provider contract, continuable background children — is [docs/subsystems/subagent.md](../../docs/subsystems/subagent.md); design rationale in the [subagent capability seam](../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md), [continuable background subagents](../../.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.md), and [merged subagent control service](../../.agents/notes/implemented/simplification/2026-07-26-merge-subagent-control-service.md) Agent Notes. diff --git a/packages/subagent/README.zh.md b/packages/subagent/README.zh.md index 1c9bf8ba08..a98874baf8 100644 --- a/packages/subagent/README.zh.md +++ b/packages/subagent/README.zh.md @@ -18,6 +18,8 @@ | [`tool-subagent-control/`](tool-subagent-control/README.md) | 向模型公开子级消息发送和列举操作 | 注册到 `ctx.tools` | | [`tool-subagent-report/`](tool-subagent-report/README.md) | 提供从子级到父级的报告通道 | 注册到子级作用域 | +Codex 与 Claude Code 包是彼此独立的可选 Profile Bundle。使用 `dsh plugin --profile add @deepseek-ai/dsh-subagent-codex @deepseek-ai/dsh-subagent-claude-code` 安装其中一个或两个包,再重启该 Profile;每个包只注册自己的休眠 Host provider。要授予工具,请复制一份完整 Agent Preset,删除各对应工具行的 `disabled`,再启动新 Session。移除其中一个包后,下一次 Profile 启动只会撤回对应 provider 及其私有运行时闭包。 + 参见有关[能力家族](../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md)、[可继续执行的子级](../../.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.md)和[控制工具](../../.agents/notes/implemented/simplification/2026-07-26-merge-subagent-control-service.md)的决策。 子系统参考——启动请求、结果、实时运行、提供方约定、可续跑后台子 agent——见 [docs/subsystems/subagent.md](../../docs/subsystems/subagent.md);设计依据见 [subagent 能力 seam](../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md)、[可续跑后台 subagent](../../.agents/notes/implemented/feature/2026-07-21-continuable-background-subagents.md)与[合并 subagent 控制服务](../../.agents/notes/implemented/simplification/2026-07-26-merge-subagent-control-service.md) Agent Note。 diff --git a/packages/subagent/subagent-claude-code/README.i18n.yaml b/packages/subagent/subagent-claude-code/README.i18n.yaml index a165540575..70d7ffab83 100644 --- a/packages/subagent/subagent-claude-code/README.i18n.yaml +++ b/packages/subagent/subagent-claude-code/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-claude-code/README.md -README.md: 1a0d6e32b8610769dcc5d8342a4fe88d0c884085 -README.zh.md: 78dab14e5eaddc06ccd07b69dc952a09380e0428 +README.md: 67a8cf199a2e85d975a4df90f56d5dbafb9f1e56 +README.zh.md: 0b8f2f285924de161cefd21c422fd40ac3597ad7 diff --git a/packages/subagent/subagent-claude-code/README.md b/packages/subagent/subagent-claude-code/README.md index 1a0d6e32b8..67a8cf199a 100644 --- a/packages/subagent/subagent-claude-code/README.md +++ b/packages/subagent/subagent-claude-code/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -This package registers the fixed `claude-code` subagent provider. Each accepted run invokes the official Claude Agent SDK in the delegating Session's workspace, resolves the native `claude` executable through the shared subprocess service, submits one self-contained text task, and returns only the final answer through the shared [`dsh-subagent`](../subagent/README.md) result contract. +This package registers a Profile-named Claude Code subagent provider whose default name is `claude-code`. Each accepted run invokes the official Claude Agent SDK in the delegating Session's workspace, lets the pinned SDK select its installed platform CLI, submits one self-contained text task, and returns either the strict final answer or a separate safe failure diagnostic through the shared [`dsh-subagent`](../subagent/README.md) result contract. ## Start and ownership @@ -14,9 +14,9 @@ Local cancellation wins the result race and maps to `aborted`. `dispose()` is id ## Native settings and interaction -The provider deliberately omits the SDK `settingSources` option. The official SDK therefore reads the host's normal user, project, and local Claude settings relative to the parent Session cwd, including native account state and product configuration. The provider neither copies nor filters those files and does not create or modify login state. +The provider deliberately omits the SDK `settingSources` option. The official SDK therefore reads the host's normal user, project, and local Claude settings relative to the parent Session cwd, including native account state and product configuration. The provider neither copies nor filters those files and does not create or modify login state. The Profile-selected `permissionMode` is the one query-level override: Claude Code still owns its settings and sandbox, while the selected native mode decides how this unattended query handles permission checks. -Each query sets `persistSession: false` and disables `AskUserQuestion`. It supplies no `canUseTool`, elicitation, or dialog callback, so unattended interactions fail through the SDK instead of waiting for a user interface this provider does not own. +Each query sets `persistSession: false` and disables `AskUserQuestion`. Except in bypass mode, `canUseTool` immediately denies requests that still require human approval. Plan mode also places `ExitPlanMode` in the SDK's `disallowedTools`, so native settings cannot pre-approve a transition back to execution and the model must return the completed plan as its final answer. MCP elicitation is declined, the known refusal fallback dialog is cancelled, and undeclared dialog kinds use the SDK's no-dialog failure behavior. These decisions never wait for a user interface. A permission denial or unattended callback that contributes to a failed run produces an optional `SubagentResult.diagnostic` containing only the product, effective mode, request category, decision, and fixed safe reason; the shared result boundary limits the complete text to 4096 UTF-8 bytes. Successful and locally cancelled runs do not expose the captured failure detail. ## Capabilities and context @@ -26,40 +26,83 @@ The provider advertises no optional start-time capabilities and reports `inherit | Key | Default | Meaning | |---|---|---| +| `providerName` | `claude-code` | Non-empty registry name on `ctx.subagents`; each mounted instance needs a unique value. | | `env` | `{}` | Explicit SDK/CLI environment layered over the shared credential-scrubbed parent environment. | +| `permissionMode` | `dontAsk` | Native non-interactive permission policy fixed for every run from this Provider instance. | | `disposeGraceMs` | `3000` | Positive finite grace in milliseconds, no greater than [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md), between the shared process-tree owner's termination tiers; disposal then waits for whole-tree exit. | -Production resolves `claude` from the subprocess execution world's credential-scrubbed `PATH`, with explicit `env` entries applied, and passes the resulting path to the SDK as `pathToClaudeCodeExecutable`. On Windows, a resolved `.cmd` or `.bat` path is carried as a quoted, per-spawn environment value that `cmd.exe /v:off` expands once, so valid path metacharacters remain data. The pinned SDK's fixed flags then occupy cmd's command tail and contain no cmd metacharacters; they are not ordinary Windows argv. Native settings and authentication remain authoritative. The plugin does not install another CLI, select a model, create a product home, log in, or probe an account. Credential-shaped ambient variables are removed before the explicit `env` overlay is applied, so an API key or token intended for the child must be supplied there. Non-credential endpoint variables such as `ANTHROPIC_BASE_URL`, along with ordinary ambient values such as `PATH` and `HOME`, remain inherited unless overridden. +| `permissionMode` value | Native behavior | +|---|---| +| `dontAsk` | Deny operations that are not already authorized instead of prompting. | +| `acceptEdits` | Accept file edits; any remaining permission prompt is denied by the unattended callback. | +| `auto` | Let Claude Code's native classifier allow or deny permission requests. | +| `plan` | Run in native planning mode, deny execution approval, and return the completed plan as the final answer. | +| `bypassPermissions` | Explicitly set the SDK's dangerous confirmation and bypass permission checks. | -Production `dsh` does not install or mount this optional provider. A Profile that opts in must install `@deepseek-ai/dsh-subagent-claude-code` and mount it once on the host plane; loading the provider starts no Claude process until a tool call. Full Agent Presets carry a matching product tool row with `disabled: true`; copy a preset and remove that field to expose `subagent_claude_code` only to agents composed from the copy. Its `one-shot` policy keeps omitted or `false` `run_in_background` calls in the foreground, while explicit `true` returns a parent-owned Job id for `job_output` or `job_kill`. The base host and full presets already provide the generic Job registry and controls. +Production omits `pathToClaudeCodeExecutable`, so Agent SDK 0.3.220 selects the matching native `claude` or `claude.exe` from its own platform package and passes that absolute command through the custom-spawn hook to `dsh-subprocess`. The provider does not inspect `PATH`, implement platform selection, or fall back to a host `claude`. Native settings and authentication remain authoritative, while `permissionMode` is the only query-level policy override. The plugin does not select a model, create a product home, log in, or probe an account. Credential-shaped ambient variables are removed before the explicit `env` overlay is applied, so an API key or token intended for the child must be supplied there. Non-credential endpoint variables such as `ANTHROPIC_BASE_URL`, along with ordinary ambient values such as `PATH` and `HOME`, remain inherited unless overridden; `PATH` does not choose the Claude executable. -The standalone composition below shows the complete explicit capability. A Profile based on `@deepseek-ai/dsh-base` keeps its existing Job rows, adds the product provider row, and enables the preset tool row instead of mounting duplicate Job services. +This package is an optional Profile Bundle. Install it into the target Profile, then restart that Profile; installation brings the pinned Agent SDK and one compatible platform CLI payload into that Profile, while the declared `cordis.patch.yml` layer registers only the dormant `claude-code` Host provider and starts no Claude process. Removing the package withdraws that provider and its private runtime closure on the next Profile start. + +```sh +dsh plugin --profile add @deepseek-ai/dsh-subagent-claude-code +dsh plugin --profile remove @deepseek-ai/dsh-subagent-claude-code +dsh --profile +``` + +Installation controls Host availability, not model permission. The Bundle supplies the dormant default `claude-code` row; the Profile may replace that row's complete config or mount additional rows with distinct `providerName`, `permissionMode`, and `env` values. Loading an instance starts no Claude process until a bound tool calls it. Each `dsh-tool-subagent` row names one provider and needs its own `toolName`, so the model sees static tools rather than a dynamic provider selector. Full Agent Presets carry a matching default product tool row with `disabled: true`; copy a preset and remove that field to expose `subagent_claude_code` only to agents composed from the copy. Its `one-shot` policy keeps omitted or `false` `run_in_background` calls in the foreground, while explicit `true` returns a parent-owned Job id for `job_output` or `job_kill`. The base host and full presets already provide the generic Job registry and controls. + +The standalone composition below shows the complete explicit capability. A Profile based on `@deepseek-ai/dsh-base` keeps its existing Job rows, adds the product provider and tool rows, and does not mount duplicate Job services. ```yaml -- id: subagent-claude-code +- id: subagent-claude-safe name: '@deepseek-ai/dsh-subagent-claude-code' config: + providerName: claude-safe + permissionMode: dontAsk env: ANTHROPIC_API_KEY: !!js process.env.ANTHROPIC_API_KEY +- id: subagent-claude-bypass + name: '@deepseek-ai/dsh-subagent-claude-code' + config: + providerName: claude-bypass + permissionMode: bypassPermissions + env: + ANTHROPIC_API_KEY: !!js process.env.ANTHROPIC_API_KEY +``` + +```yaml - id: jobs name: '@deepseek-ai/dsh-jobs-local' - id: tool-jobs name: '@deepseek-ai/dsh-tool-jobs' -- id: tool-subagent-claude-code +- id: tool-subagent-claude-safe + name: '@deepseek-ai/dsh-tool-subagent' + disabled: true + config: + provider: claude-safe + toolName: subagent_claude_safe + backgroundMode: one-shot + maxDepth: provider-managed + +- id: tool-subagent-claude-bypass name: '@deepseek-ai/dsh-tool-subagent' config: - provider: claude-code - toolName: subagent_claude_code + provider: claude-bypass + toolName: subagent_claude_bypass backgroundMode: one-shot maxDepth: provider-managed ``` ## Product compatibility and evidence -The runtime dependency is pinned to `@anthropic-ai/claude-agent-sdk@0.3.220`. Production runs the native `claude` installation. The keyless real-product test uses the SDK-distributed Claude Code 2.1.220 CLI as a deterministic fixture, routed through the same native executable-resolution and Windows batch-shim path; it does not claim compatibility with every independently installed version. Loader composition proves that both product packages coexist without starting either product. +The runtime dependency is pinned to `@anthropic-ai/claude-agent-sdk@0.3.220`, whose eight platform packages carry Claude Code 2.1.220. A normal install selects one payload for the current OS, CPU, and Linux libc. For the current darwin-arm64 payload, `npm pack --dry-run --json` reports 74,858,812 packed bytes and 256,908,856 unpacked bytes; other platforms may differ, and these values are disclosure rather than an installation threshold. The keyless real-product test runs the SDK-selected CLI against a loopback Messages fixture and asserts that the shared subprocess argv begins with that platform package's native executable. Loader composition proves that installing the Bundle registers only the dormant Claude Code provider and starts no product process. + +Installing with optional dependencies omitted, using an unsupported platform, or losing the selected payload leaves provider registration dormant but makes the first delegation fail with the SDK's native-payload startup error. The provider neither probes a host CLI nor retries with one. + +Loader composition proves that the Bundle default, two additional named Claude instances, and the existing Codex package coexist without starting either product. The project owner's identity-scoped distribution authorization covers the official SDK and the official CLI/platform payloads declared by each SDK version. [`THIRD_PARTY_NOTICES.md`](../../../THIRD_PARTY_NOTICES.md) discloses the current optional payload closure without classifying its declared terms as permissive; unrelated non-permissive runtime dependencies continue to fail the notices gate. @@ -69,7 +112,7 @@ The project owner's identity-scoped distribution authorization covers the offici #### What the model sees -The Claude Code child receives the standalone text task as one fresh SDK query. Its workspace is the parent Session cwd, while its model, system instructions, tools, permissions, and authentication come from the host's native Claude settings and product installation. +The Claude Code child receives the standalone text task as one fresh SDK query. Its workspace is the parent Session cwd; its model, system instructions, tools, sandbox, and authentication come from native Claude settings, the selected Provider instance's Profile configuration fixes the query's environment and non-interactive permission mode, and the executable version comes from the Bundle's pinned SDK platform payload. #### Token effect @@ -83,7 +126,7 @@ Independent of the parent request cache. Reuse depends only on Claude Code's own #### What the model sees -Through `dsh-tool-subagent`, a foreground call gives the parent the strict final Claude Code answer or the consumer's exact error for a non-completed result. A background call first returns a Job id; the generic job controls later deliver a completion notice, expose the final answer and status through `job_output`, and let `job_kill` request cancellation. Claude Code reasoning, tool activity, intermediate messages, stderr, workspace diffs, usage, and product ids are not copied into the parent Session. +Through `dsh-tool-subagent`, a foreground call gives the parent the strict final Claude Code answer or an error containing the stop reason and optional safe diagnostic for a non-completed result. A background call first returns a Job id; the generic job controls later deliver a completion notice, expose the final answer or failed status detail through `job_output`, and let `job_kill` request cancellation. Claude Code reasoning, tool activity, intermediate messages, stderr, workspace diffs, usage, product ids, tool inputs, and raw protocol payloads are not copied into the parent Session. #### Token effect @@ -96,10 +139,11 @@ Append-only: foreground adds one result after the reusable parent prefix, while ## Known Limitations and Deferred Work - **One fresh query and process per run** — there is no continuation, resume, pooling, progress stream, or product-session persistence. +- **Static instance selection** — Profile rows fix provider names and tool bindings; calls cannot choose a provider dynamically, and every exposed tool needs a unique `toolName`. - **Host settings are intentionally authoritative** — project and user settings can change model, tools, and behavior; the provider does not provide a filtered or hermetic production mode. -- **Product installation and account state remain native** — a missing or incompatible `claude`, configuration error, or authentication failure is surfaced as a startup or run error; the plugin provides no installer or login flow. -- **The SDK platform CLI remains in the install closure** — production ignores it in favor of the host `claude`, but the current SDK optional dependency is still installed and supplies the keyless compatibility fixture. Removing that payload belongs to the separate product installation-closure follow-up. -- **No human interaction path** — `AskUserQuestion` is disabled and other interactive callbacks are absent, so tasks requiring new approval or input fail instead of suspending. -- **Product payload is final text only** — reasoning, intermediate messages, tool traffic, usage, stderr, and workspace diffs remain product-local; generic Job ids, notices, and status come from the shared job runtime. +- **Authentication and account state remain native** — the Bundle supplies the CLI but does not create an account, log in, or rewrite Claude settings; configuration and authentication failures surface as startup or run errors. +- **The SDK platform payload is required at delegation time** — installs that omit optional dependencies, unsupported platforms, and missing or damaged payloads fail at the first query; there is no host-CLI fallback. +- **No human interaction path** — `AskUserQuestion` is disabled, permission prompts are denied, MCP elicitation is declined, and blocking dialogs fail closed instead of suspending. +- **Assistant payload is final text only** — a failed run may additionally expose the separate safe diagnostic; reasoning, intermediate messages, tool traffic, usage, stderr, and workspace diffs remain product-local, while generic Job ids, notices, and status come from the shared job runtime. - **No optional shared capabilities** — output schemas, child personas, tool filtering, and harness depth enforcement are rejected by the shared service for this provider. - **No wall-clock timeout or side-effect rollback** — the caller cancels long work, and files or external systems changed before cancellation are not restored. diff --git a/packages/subagent/subagent-claude-code/README.zh.md b/packages/subagent/subagent-claude-code/README.zh.md index 78dab14e5e..0b8f2f2859 100644 --- a/packages/subagent/subagent-claude-code/README.zh.md +++ b/packages/subagent/subagent-claude-code/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -本包(package)注册固定的 `claude-code` subagent 提供方。每次接受运行请求后,它都会在发起委托的会话工作区中调用官方 Claude Agent SDK,通过共享子进程服务解析原生 `claude` 可执行文件,提交一个自包含的文本任务,并通过共享的 [`dsh-subagent`](../subagent/README.md) 结果约定仅返回最终答案。 +本包(package)注册由 Profile 命名、默认名称为 `claude-code` 的 Claude Code subagent 提供方。每次接受运行请求后,它都会在发起委托的会话工作区中调用官方 Claude Agent SDK,让锁定版本的 SDK 选择随包安装的平台 CLI,提交一个自包含的文本任务,并通过共享的 [`dsh-subagent`](../subagent/README.md) 结果约定返回严格的最终答案或独立的安全失败诊断。 ## 启动与所有权 @@ -14,9 +14,9 @@ SDK 接收由文本块原样拼接成的任务。提供方会完整迭代 SDK ## 原生设置与交互 -提供方故意省略 SDK 的 `settingSources` 选项。因此,官方 SDK 会相对于父会话 cwd 读取宿主机常规的用户、项目和本地 Claude 设置,包括原生账户状态与产品配置。提供方既不复制也不过滤这些文件,也不会创建或修改登录状态。 +提供方故意省略 SDK 的 `settingSources` 选项。因此,官方 SDK 会相对于父会话 cwd 读取宿主机常规的用户、项目和本地 Claude 设置,包括原生账户状态与产品配置。提供方既不复制也不过滤这些文件,也不会创建或修改登录状态。Profile 选择的 `permissionMode` 是唯一的 query 级覆盖:Claude Code 仍拥有其设置与沙箱,而所选原生模式决定这个无人值守 query 如何处理权限检查。 -每次 query 都设置 `persistSession: false` 并禁用 `AskUserQuestion`。提供方不设置 `canUseTool`、elicitation 或对话回调,因此无人值守交互会经 SDK 失败,而不会等待本提供方不负责的用户界面。 +每次 query 都设置 `persistSession: false` 并禁用 `AskUserQuestion`。除 bypass 模式外,`canUseTool` 会立即拒绝仍需人工审批的请求。Plan 模式还会把 `ExitPlanMode` 放入 SDK 的 `disallowedTools`,因此原生 settings 无法预先放行回到执行模式的转换,模型必须把完整计划作为最终答案返回。MCP elicitation 会被拒绝,已知的拒绝回退对话会被取消,未声明的对话类型则使用 SDK 的无对话失败行为。这些决定都不会等待用户界面。若权限拒绝或无人值守回调参与了一次失败运行,提供方会生成可选的 `SubagentResult.diagnostic`,其中只包含产品、有效模式、请求类别、决定与固定的安全原因;共享结果边界会把完整文本限制在 4096 个 UTF-8 字节以内。成功运行与本地取消不会公开已捕获的失败说明。 ## 能力与上下文 @@ -26,40 +26,83 @@ SDK 接收由文本块原样拼接成的任务。提供方会完整迭代 SDK | 配置键 | 默认值 | 含义 | |---|---|---| +| `providerName` | `claude-code` | `ctx.subagents` 中的非空注册名称;每个已挂载实例都需要唯一值。 | | `env` | `{}` | 显式指定的 SDK/CLI 环境,叠加在由共享机制清除凭证后的父环境之上。 | +| `permissionMode` | `dontAsk` | 为该提供方实例的每次运行固定原生非交互权限策略。 | | `disposeGraceMs` | `3000` | 共享进程树责任方各终止层级之间的宽限期,单位为毫秒且须为正有限值,并不得大于仓库共享的 [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md);随后资源释放会等待整棵进程树退出。 | -生产环境从子进程执行世界清除凭证后的 `PATH` 解析 `claude`,再应用显式 `env` 条目,并把所得路径作为 `pathToClaudeCodeExecutable` 交给 SDK。在 Windows 上,解析到的 `.cmd` 或 `.bat` 路径会作为带引号、仅供本次 spawn 使用的环境值交给 `cmd.exe /v:off` 展开一次,因此合法路径中的元字符仍只是数据。锁定版本的 SDK 随后把固定命令行选项放在 cmd 的命令尾部;这些选项不含 cmd 元字符,也并不是普通的 Windows argv。原生设置与身份验证继续是权威来源。本插件不安装另一份 CLI、不选择模型、不创建产品主目录、不执行登录,也不探测账户。具有凭证特征的环境变量会在显式 `env` 覆盖生效前被清除,因此供子进程使用的 API 密钥或 token 必须在该配置中显式提供。除非被覆盖,`ANTHROPIC_BASE_URL` 等非凭证端点变量以及 `PATH` 和 `HOME` 等普通环境变量仍会被继承。 +| `permissionMode` 值 | 原生行为 | +|---|---| +| `dontAsk` | 不弹出提示,直接拒绝尚未获授权的操作。 | +| `acceptEdits` | 接受文件编辑;其余权限提示由无人值守回调拒绝。 | +| `auto` | 由 Claude Code 原生分类器允许或拒绝权限请求。 | +| `plan` | 使用原生规划模式,拒绝执行审批,并把完整计划作为最终答案返回。 | +| `bypassPermissions` | 显式设置 SDK 的危险确认并跳过权限检查。 | -生产 `dsh` 不会安装或挂载这个可选提供方。选择启用它的 Profile 必须安装 `@deepseek-ai/dsh-subagent-claude-code`,并在 host plane(宿主平面)挂载一次;加载提供方本身不会在工具调用前启动 Claude 进程。完整 Agent Preset 携带对应的产品工具行并设置 `disabled: true`;复制一个 preset 后删除该字段,即可只向由该副本组装的 agent 暴露 `subagent_claude_code`。其 `one-shot` 策略会让省略 `run_in_background` 或传入 `false` 的调用继续在前台等待,而显式传入 `true` 会返回由父 agent 拥有的 Job ID,供 `job_output` 或 `job_kill` 使用。base host(基础宿主)与完整 preset 已提供通用作业注册表和控制工具。 +生产环境会省略 `pathToClaudeCodeExecutable`,因此 Agent SDK 0.3.220 会从自己的平台包中选择匹配的原生 `claude` 或 `claude.exe`,再通过 custom-spawn 钩子把该绝对命令交给 `dsh-subprocess`。提供方不会检查 `PATH`、重复实现平台选择,也不会回退到宿主 `claude`。原生设置与身份验证继续是权威来源,而 `permissionMode` 是唯一的 query 级策略覆盖。本插件不选择模型、不创建产品主目录、不执行登录,也不探测账户。具有凭证特征的环境变量会在显式 `env` 覆盖生效前被清除,因此供子进程使用的 API 密钥或 token 必须在该配置中显式提供。除非被覆盖,`ANTHROPIC_BASE_URL` 等非凭证端点变量以及 `PATH` 和 `HOME` 等普通环境变量仍会被继承;`PATH` 不参与选择 Claude 可执行文件。 -下列独立组装展示完整的显式能力。基于 `@deepseek-ai/dsh-base` 的 Profile 保留已有 Job 行,只新增产品提供方行并启用 preset 工具行,禁止重复挂载 Job 服务。 +本包是可选的 Profile Bundle。将它安装进目标 Profile 后重启该 Profile;安装会把锁定的 Agent SDK 与一个兼容的平台 CLI 载荷带入该 Profile,而包所声明的 `cordis.patch.yml` 层只注册休眠的 `claude-code` Host provider,不会启动 Claude 进程。移除该包后,下一次 Profile 启动会撤回这一 provider 及其私有运行时闭包。 + +```sh +dsh plugin --profile add @deepseek-ai/dsh-subagent-claude-code +dsh plugin --profile remove @deepseek-ai/dsh-subagent-claude-code +dsh --profile +``` + +安装决定 Host 可用性,而不是模型权限。Bundle 会提供休眠的默认 `claude-code` 配置项;Profile 可以替换该配置项的完整 config,也可以挂载更多具有不同 `providerName`、`permissionMode` 与 `env` 的配置项。加载实例本身不会在绑定工具调用前启动 Claude 进程。每个 `dsh-tool-subagent` 配置项指定一个提供方,并需要独立的 `toolName`,因此模型看到的是静态工具,而不是动态提供方选择器。完整 Agent Preset 携带对应的默认产品工具行并设置 `disabled: true`;复制一个 preset 后删除该字段,即可只向由该副本组装的 agent 暴露 `subagent_claude_code`。其 `one-shot` 策略会让省略 `run_in_background` 或传入 `false` 的调用继续在前台等待,而显式传入 `true` 会返回由父 agent 拥有的 Job ID,供 `job_output` 或 `job_kill` 使用。base host(基础宿主)与完整 preset 已提供通用作业注册表和控制工具。 + +下列独立组装展示完整的显式能力。基于 `@deepseek-ai/dsh-base` 的 Profile 保留已有 Job 配置项,新增产品提供方与工具配置项,而且不重复挂载 Job 服务。 ```yaml -- id: subagent-claude-code +- id: subagent-claude-safe name: '@deepseek-ai/dsh-subagent-claude-code' config: + providerName: claude-safe + permissionMode: dontAsk env: ANTHROPIC_API_KEY: !!js process.env.ANTHROPIC_API_KEY +- id: subagent-claude-bypass + name: '@deepseek-ai/dsh-subagent-claude-code' + config: + providerName: claude-bypass + permissionMode: bypassPermissions + env: + ANTHROPIC_API_KEY: !!js process.env.ANTHROPIC_API_KEY +``` + +```yaml - id: jobs name: '@deepseek-ai/dsh-jobs-local' - id: tool-jobs name: '@deepseek-ai/dsh-tool-jobs' -- id: tool-subagent-claude-code +- id: tool-subagent-claude-safe + name: '@deepseek-ai/dsh-tool-subagent' + disabled: true + config: + provider: claude-safe + toolName: subagent_claude_safe + backgroundMode: one-shot + maxDepth: provider-managed + +- id: tool-subagent-claude-bypass name: '@deepseek-ai/dsh-tool-subagent' config: - provider: claude-code - toolName: subagent_claude_code + provider: claude-bypass + toolName: subagent_claude_bypass backgroundMode: one-shot maxDepth: provider-managed ``` ## 产品兼容性与证据 -运行时依赖精确锁定为 `@anthropic-ai/claude-agent-sdk@0.3.220`。生产运行使用原生 `claude` 安装。无密钥真实产品测试使用由 SDK 分发的 Claude Code 2.1.220 CLI 作为确定性 fixture(测试前置数据),并通过同一套原生可执行文件解析路径与 Windows batch shim 路径运行;这项测试不声称兼容每个独立安装的版本。Loader 组合证明两个产品包能够共存且不会启动任一产品。 +运行时依赖精确锁定为 `@anthropic-ai/claude-agent-sdk@0.3.220`,其八个平台包都携带 Claude Code 2.1.220。普通安装会按当前操作系统、CPU 及 Linux libc 选择一个载荷。对于当前 darwin-arm64 载荷,`npm pack --dry-run --json` 报告压缩包为 74,858,812 字节、解包后为 256,908,856 字节;其他平台可能不同,这些数值只用于披露而不是安装阈值。无密钥真实产品测试会让 SDK 选择 CLI,通过回环 Messages fixture 运行它,并断言共享子进程 argv 的首项就是该平台包的原生可执行文件。Loader 组合证明安装该 Bundle 只会注册休眠的 Claude Code provider,不会启动产品进程。 + +如果安装时省略 optional dependencies、当前平台不受支持,或所选载荷缺失,提供方注册仍保持休眠,但第一次委派会以 SDK 的原生载荷启动错误失败。提供方既不会探测宿主 CLI,也不会用它重试。 + +Loader 组合证明 Bundle 默认实例、两个额外命名 Claude 实例与现有 Codex 包可以共存,而且不会启动任一产品。 限定于项目所有者身份的分发授权涵盖官方 SDK 及每个 SDK 版本声明的官方 CLI/平台载荷。[`THIRD_PARTY_NOTICES.md`](../../../THIRD_PARTY_NOTICES.md) 会披露当前可选载荷闭包,但不会认定其中声明的条款属于宽松许可;其他无关的非宽松运行时依赖仍会使第三方声明门禁失败。 @@ -69,7 +112,7 @@ SDK 接收由文本块原样拼接成的任务。提供方会完整迭代 SDK #### 模型看到的内容 -Claude Code 子级会在一个全新的 SDK query 中接收独立文本任务。它的工作区是父会话 cwd;其模型、系统指令、工具、权限和身份验证来自宿主机原生 Claude 设置与产品安装。 +Claude Code 子级会在一个全新的 SDK query 中接收独立文本任务。它的工作区是父会话 cwd;其模型、系统指令、工具、沙箱和身份验证来自原生 Claude 设置,所选提供方实例的 Profile 配置会固定该 query 的环境与非交互权限模式,而可执行版本来自 Bundle 锁定的 SDK 平台载荷。 #### 对 token 的影响 @@ -83,7 +126,7 @@ Claude Code 子级会在一个全新的 SDK query 中接收独立文本任务。 #### 模型看到的内容 -通过 `dsh-tool-subagent`,前台调用会让父级模型看到符合严格成功条件的 Claude Code 最终答案,或者在结果未完成时看到消费方给出的原样错误。后台调用会先返回 Job id;随后通用作业控制面会送达完成通知,通过 `job_output` 公开最终答案与状态,并允许 `job_kill` 请求取消。Claude Code 的推理、工具活动、中间消息、stderr、工作区差异、用量信息和产品标识符均不会复制到父会话。 +通过 `dsh-tool-subagent`,前台调用会让父级模型看到符合严格成功条件的 Claude Code 最终答案;若结果未完成,错误中会包含终止原因和可选的安全诊断。后台调用会先返回 Job id;随后通用作业控制面会送达完成通知,通过 `job_output` 公开最终答案或失败状态 detail,并允许 `job_kill` 请求取消。Claude Code 的推理、工具活动、中间消息、stderr、工作区差异、用量信息、产品标识符、工具输入和原始协议载荷均不会复制到父会话。 #### 对 token 的影响 @@ -96,10 +139,11 @@ Claude Code 子级会在一个全新的 SDK query 中接收独立文本任务。 ## 已知限制与后续工作 - **每次运行均新建一个 query 和一个进程**:不支持续接、恢复、池化、进度流或产品会话持久化。 +- **静态选择实例**:Profile 配置项固定提供方名称与工具绑定;调用无法动态选择提供方,而且每个公开工具都需要唯一的 `toolName`。 - **宿主设置有意保持权威**:项目和用户设置可以改变模型、工具与行为;本提供方不提供经过筛选或与宿主环境隔离的生产模式。 -- **产品安装与账户状态仍由原生机制管理**:`claude` 缺失或不兼容、配置错误或身份验证失败都会呈现为启动错误或运行错误;本插件不提供安装程序或登录流程。 -- **SDK 平台 CLI 仍在安装闭包内**:生产环境会忽略它,改用宿主提供的 `claude`,但当前 SDK 的可选依赖仍会安装,并提供无密钥兼容性 fixture。移除该载荷属于独立的产品安装闭包后续项。 -- **没有人工交互路径**:`AskUserQuestion` 被禁用,其他交互回调也不存在,因此需要新审批或输入的任务会失败而不会挂起。 -- **产品载荷仅包含最终文本**:推理、中间消息、工具通信、用量信息、stderr 和工作区差异仍只保留在产品内部;通用 Job id、通知与状态来自共享作业运行时。 +- **身份验证与账户状态仍由原生机制管理**:Bundle 会提供 CLI,但不会创建账户、登录或改写 Claude 设置;配置与身份验证失败会呈现为启动错误或运行错误。 +- **委派时必须存在 SDK 平台载荷**:省略 optional dependencies 的安装、不受支持的平台以及缺失或损坏的载荷都会在第一次 query 时失败;不会回退到宿主 CLI。 +- **没有人工交互路径**:`AskUserQuestion` 被禁用,权限提示会被拒绝,MCP elicitation 会被拒绝,阻塞对话会快速失败而不会挂起。 +- **assistant 载荷仅包含最终文本**:失败运行可以额外公开独立的安全诊断;推理、中间消息、工具通信、用量信息、stderr 和工作区差异仍只保留在产品内部,通用 Job id、通知与状态来自共享作业运行时。 - **没有可选的共享能力**:对于本提供方,共享服务会拒绝输出 schema、子任务角色设定、工具筛选和 harness 深度强制约束。 - **没有按实际经过时间触发的超时或副作用回滚**:长时间运行的工作由调用方取消,且取消前已更改的文件或外部系统不会恢复原状。 diff --git a/packages/subagent/subagent-claude-code/cordis.patch.yml b/packages/subagent/subagent-claude-code/cordis.patch.yml new file mode 100644 index 0000000000..63c0319626 --- /dev/null +++ b/packages/subagent/subagent-claude-code/cordis.patch.yml @@ -0,0 +1,6 @@ +# This optional Profile layer registers the dormant Claude Code provider. Agent +# presets separately decide whether one session receives its delegation tool. + +- insert: + - id: subagent-claude-code + name: '@deepseek-ai/dsh-subagent-claude-code' diff --git a/packages/subagent/subagent-claude-code/package.json b/packages/subagent/subagent-claude-code/package.json index 0c0e54cf11..fe974b0344 100644 --- a/packages/subagent/subagent-claude-code/package.json +++ b/packages/subagent/subagent-claude-code/package.json @@ -28,9 +28,15 @@ "files": [ "lib/index.js", "lib/invariant.js", + "cordis.patch.yml", "lib/types/**/*.d.ts" ], "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, "peerDependencies": { "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", @@ -43,7 +49,9 @@ "dependencies": { "@anthropic-ai/sdk": "0.93.0", "@anthropic-ai/claude-agent-sdk": "0.3.220", - "@deepseek-ai/schemastery": "workspace:^" + "@deepseek-ai/schemastery": "workspace:^", + "@modelcontextprotocol/sdk": "^1.29.0", + "zod": "^4.4.3" }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", diff --git a/packages/subagent/subagent-claude-code/src/index.ts b/packages/subagent/subagent-claude-code/src/index.ts index ccd150b746..51b4bdc4a2 100644 --- a/packages/subagent/subagent-claude-code/src/index.ts +++ b/packages/subagent/subagent-claude-code/src/index.ts @@ -1,7 +1,7 @@ /** - * Fixed Claude Code one-shot subagent provider. Every accepted run invokes - * the official Agent SDK in the delegating Session's workspace and places - * the SDK-spawned real CLI under the shared subprocess owner. + * Profile-named Claude Code one-shot subagent provider. Every accepted run + * invokes the official Agent SDK in the delegating Session's workspace and + * places the SDK-spawned real CLI under the shared subprocess owner. * * @module @deepseek-ai/dsh-subagent-claude-code */ @@ -18,29 +18,46 @@ import { type SubagentProvider, } from '@deepseek-ai/dsh-subagent' import { + CLAUDE_CODE_PERMISSION_MODES, + DEFAULT_CLAUDE_CODE_PERMISSION_MODE, DEFAULT_DISPOSE_GRACE_MS, startClaudeCodeRun, + type ClaudeCodePermissionMode, type ClaudeCodeRunSpec, } from './run.ts' export const name = 'subagent-claude-code' export const inject = ['subagents', 'subprocess'] -/* jscpd:ignore-start -- sibling product providers intentionally expose the - * same two deployment-owned fields without adding a shared config owner. */ -/** Deployment-owned environment and process-release bound. */ +const DEFAULT_PROVIDER_NAME = 'claude-code' + +/* jscpd:ignore-start -- sibling product providers intentionally expose + * overlapping deployment-owned fields without adding a shared config owner. */ +/** Deployment-owned permission, environment, and process-release settings. */ export interface Config { + /** Provider name on `ctx.subagents` (default `claude-code`). */ + providerName?: string /** * Explicit environment entries layered over the subprocess seam's * credential-scrubbed parent environment. */ env?: Record + /** + * Native non-interactive mode fixed for this Provider instance. Defaults to + * `dontAsk`; `acceptEdits` accepts edits, `auto` uses the native classifier, + * `plan` returns a plan without approving execution, and + * `bypassPermissions` explicitly skips permission checks. + */ + permissionMode?: ClaudeCodePermissionMode /** Grace in milliseconds for Claude Code process-tree termination. */ disposeGraceMs?: number } export const Config: z = z.object({ + providerName: z.string().min(1).default(DEFAULT_PROVIDER_NAME), env: z.dict(z.string()).default({}), + permissionMode: z.union([...CLAUDE_CODE_PERMISSION_MODES]) + .default(DEFAULT_CLAUDE_CODE_PERMISSION_MODE), disposeGraceMs: z.number().default(DEFAULT_DISPOSE_GRACE_MS), }) @@ -50,11 +67,11 @@ type ResolvedConfig = Required /* jscpd:ignore-start -- Cordis registration and shared-seam plumbing mirror * the Codex sibling; each product's lifecycle remains package-private. */ class ClaudeCodeProvider implements SubagentProvider { - readonly name = 'claude-code' readonly capabilities: SubagentCapabilities = NO_START_CAPABILITIES readonly inheritsParentContext = false constructor( + readonly name: string, private readonly ctx: Context, private readonly config: ResolvedConfig, ) {} @@ -66,24 +83,19 @@ class ClaudeCodeProvider implements SubagentProvider { 'subagent-claude-code: no working directory for the child — delegate from a parent session that has one', ) } - const executable = await this.ctx.subprocess.resolveExecutable( - 'claude', - this.config.env, - request.signal, - ) const spec: ClaudeCodeRunSpec = { cwd: resolveChildCwd( 'subagent-claude-code', undefined, parentCwd, ), - executable, + permissionMode: this.config.permissionMode, env: this.config.env, disposeGraceMs: this.config.disposeGraceMs, spawn: spawnSpec => this.ctx.subprocess.spawn(spawnSpec), onError: (error, stopReason) => { this.ctx.logger.warn( - `subagent-claude-code: child run failed (${stopReason}): ${error.message}`, + `subagent-claude-code "${this.name}": child run failed (${stopReason}): ${error.message}`, ) }, } @@ -92,12 +104,17 @@ class ClaudeCodeProvider implements SubagentProvider { } /** - * Register the fixed `claude-code` provider. + * Register one Profile-named Claude Code provider. * @param ctx - context carrying shared subagent and subprocess services. - * @param config - explicit child environment and disposal grace. + * @param config - registry name, permission mode, child environment, and disposal grace. */ export function apply(ctx: Context, config: Config): void { - const resolved = config as ResolvedConfig + const resolved: ResolvedConfig = { + providerName: config.providerName ?? DEFAULT_PROVIDER_NAME, + env: config.env as Record, + permissionMode: config.permissionMode ?? DEFAULT_CLAUDE_CODE_PERMISSION_MODE, + disposeGraceMs: config.disposeGraceMs as number, + } assertPositiveFinite( 'subagent-claude-code', 'disposeGraceMs', @@ -108,6 +125,10 @@ export function apply(ctx: Context, config: Config): void { `subagent-claude-code: disposeGraceMs must be no greater than ${MAX_TIMER_DELAY_MS}`, ) } - ctx.subagents.registerProvider(new ClaudeCodeProvider(ctx, resolved)) + ctx.subagents.registerProvider(new ClaudeCodeProvider( + resolved.providerName, + ctx, + resolved, + )) } /* jscpd:ignore-end */ diff --git a/packages/subagent/subagent-claude-code/src/process.ts b/packages/subagent/subagent-claude-code/src/process.ts index 1e2a259ca2..32a545bf08 100644 --- a/packages/subagent/subagent-claude-code/src/process.ts +++ b/packages/subagent/subagent-claude-code/src/process.ts @@ -6,7 +6,6 @@ */ import { EventEmitter } from 'node:events' -import { extname } from 'node:path' import type { SpawnedProcess, SpawnOptions, @@ -17,8 +16,6 @@ import { type SubprocessSpawnSpec, } from '@deepseek-ai/dsh-subprocess' -const WINDOWS_BATCH_EXECUTABLE_ENV = 'DSH_CLAUDE_CODE_EXECUTABLE' - function thrown(value: unknown): Error { /* v8 ignore next -- the subprocess seam rejects with Error. */ return value instanceof Error ? value : new Error(String(value)) @@ -43,33 +40,22 @@ export function sdkEnvironmentOverlay( * Translate one official SDK spawn request to the shared process owner. * @param options - command, arguments, workspace, environment, and forwarded signal from the SDK. * @param graceMs - process-tree termination grace. - * @param platform - host platform selecting the Windows batch-shim boundary. * @returns the fully explicit shared subprocess request. - * @remarks The batch-shim path quotes only the resolved executable. The pinned SDK - * supplies fixed flag arguments without cmd metacharacters; cmd reparses that tail. */ export function claudeSpawnSpec( options: SpawnOptions, graceMs: number, - platform: NodeJS.Platform = process.platform, ): SubprocessSpawnSpec { if (options.cwd === undefined || options.cwd.length === 0) { throw new Error('subagent-claude-code: SDK spawn request omitted its workspace') } - const extension = extname(options.command).toLowerCase() - const batchShim = platform === 'win32' && (extension === '.cmd' || extension === '.bat') - const env = sdkEnvironmentOverlay(options.env) - const argv = batchShim - ? ['cmd.exe', '/d', '/v:off', '/s', '/c', `%${WINDOWS_BATCH_EXECUTABLE_ENV}%`, ...options.args] - : [options.command, ...options.args] - if (batchShim) env[WINDOWS_BATCH_EXECUTABLE_ENV] = `"${options.command}"` return { - argv, + argv: [options.command, ...options.args], cwd: options.cwd, stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'inherit' }, graceMs, signal: options.signal, - env, + env: sdkEnvironmentOverlay(options.env), } } diff --git a/packages/subagent/subagent-claude-code/src/run.ts b/packages/subagent/subagent-claude-code/src/run.ts index 6c1e0a8dbf..fef044450c 100644 --- a/packages/subagent/subagent-claude-code/src/run.ts +++ b/packages/subagent/subagent-claude-code/src/run.ts @@ -38,14 +38,42 @@ import { /** Default POSIX grace between subprocess termination tiers. */ export const DEFAULT_DISPOSE_GRACE_MS = 3_000 +/** Claude Code permission modes that cannot wait for a human response. */ +export const CLAUDE_CODE_PERMISSION_MODES = [ + 'dontAsk', + 'acceptEdits', + 'auto', + 'plan', + 'bypassPermissions', +] as const satisfies readonly NonNullable[] + +/** Profile-selectable non-interactive Claude Code permission mode. */ +export type ClaudeCodePermissionMode = typeof CLAUDE_CODE_PERMISSION_MODES[number] + +/** Safe default for unattended Claude Code runs. */ +export const DEFAULT_CLAUDE_CODE_PERMISSION_MODE: ClaudeCodePermissionMode = 'dontAsk' + +const SUPPORTED_UNATTENDED_DIALOG_KINDS = [ + 'refusal_fallback_prompt', +] satisfies NonNullable + +function unattendedDiagnostic( + mode: ClaudeCodePermissionMode, + request: 'tool permission' | 'MCP elicitation' | 'user dialog', + decision: 'denied' | 'declined' | 'cancelled', + reason: string, +): string { + return `Claude Code unattended decision (mode: ${mode}; request: ${request}; decision: ${decision}): ${reason}` +} + /* jscpd:ignore-start -- sibling providers intentionally keep product-private * run inputs and error normalization instead of adding a shared lifecycle owner. */ /** Fully resolved inputs for one official Claude Agent SDK query. */ export interface ClaudeCodeRunSpec { /** Parent Session workspace supplied to the SDK and real CLI. */ readonly cwd: string - /** Exact native Claude Code executable resolved from the host PATH. */ - readonly executable: string + /** Profile-selected native non-interactive permission mode. */ + readonly permissionMode: ClaudeCodePermissionMode /** Explicit deployment/test environment layered after shared scrubbing. */ readonly env: Record /** Subprocess termination grace passed to the shared process-tree owner. */ @@ -60,6 +88,11 @@ function thrown(value: unknown): Error { /* v8 ignore next -- typed SDK and subprocess failures reject with Error. */ return value instanceof Error ? value : new Error(String(value)) } + +/** Read live request cancellation across awaited startup cleanup. */ +function isAborted(signal: AbortSignal): boolean { + return signal.aborted +} /* jscpd:ignore-end */ /** @@ -107,13 +140,19 @@ export function successfulResult(message: SDKResultMessage): string { * Consume the complete SDK stream and require one strict success plus normal * iterator completion. * @param query - published official SDK query. + * @param onPermissionDenied - records a safe fact when the SDK reports native denial. * @returns the completed shared result. */ export async function consumeClaudeQuery( query: AsyncIterable, + onPermissionDenied?: () => void, ): Promise { let answer: string | undefined for await (const message of query) { + if (message.type === 'system' && message.subtype === 'permission_denied') { + onPermissionDenied?.() + continue + } if (message.type !== 'result') continue answer = successfulResult(message) } @@ -172,20 +211,59 @@ export async function disposeClaudeCodeChild( * @param spec - Workspace, environment, process service, and disposal policy. * @param controller - per-run cancellation owner. * @param capture - receives the real managed child synchronously from the SDK hook. + * @param captureDiagnostic - receives safe facts from unattended interaction callbacks. * @returns options that inherit native settings while disabling persistence and user questions. */ export function claudeQueryOptions( spec: ClaudeCodeRunSpec, controller: AbortController, capture: (child: SubprocessHandle) => void, + captureDiagnostic: (diagnostic: string) => void, ): Options { return { abortController: controller, cwd: spec.cwd, - pathToClaudeCodeExecutable: spec.executable, env: { ...scrubbedParentEnv(), ...spec.env }, persistSession: false, - disallowedTools: ['AskUserQuestion'], + disallowedTools: spec.permissionMode === 'plan' + ? ['AskUserQuestion', 'ExitPlanMode'] + : ['AskUserQuestion'], + permissionMode: spec.permissionMode, + ...spec.permissionMode === 'bypassPermissions' + ? { allowDangerouslySkipPermissions: true } + : { + canUseTool: () => { + captureDiagnostic(unattendedDiagnostic( + spec.permissionMode, + 'tool permission', + 'denied', + 'the provider does not request human approval', + )) + return Promise.resolve({ + behavior: 'deny' as const, + message: 'This unattended Claude Code subagent cannot request human approval.', + }) + }, + }, + onElicitation: () => { + captureDiagnostic(unattendedDiagnostic( + spec.permissionMode, + 'MCP elicitation', + 'declined', + 'the provider does not collect interactive MCP input', + )) + return Promise.resolve({ action: 'decline' }) + }, + onUserDialog: () => { + captureDiagnostic(unattendedDiagnostic( + spec.permissionMode, + 'user dialog', + 'cancelled', + 'the provider does not render blocking dialogs', + )) + return Promise.resolve({ behavior: 'cancelled' as const }) + }, + supportedDialogKinds: SUPPORTED_UNATTENDED_DIALOG_KINDS, spawnClaudeCodeProcess: (options: SpawnOptions) => { const child = spec.spawn(claudeSpawnSpec(options, spec.disposeGraceMs)) capture(child) @@ -220,12 +298,21 @@ export async function startClaudeCodeRun( let child: SubprocessHandle | undefined let query: Query | undefined + let diagnostic: string | undefined + const captureDiagnostic = (value: string): void => { + diagnostic = value + } try { query = officialQuery({ prompt, - options: claudeQueryOptions(spec, controller, (captured) => { - child = captured - }), + options: claudeQueryOptions( + spec, + controller, + (captured) => { + child = captured + }, + captureDiagnostic, + ), }) if (child === undefined || child.pid <= 0) { throw new Error( @@ -239,12 +326,49 @@ export async function startClaudeCodeRun( request.signal.removeEventListener('abort', onAbort) const cancelledBeforeCleanup = controller.signal.aborted requestCancel() + const startupError = thrown(error) + if (child !== undefined && child.pid <= 0) { + let closeError: Error | undefined + try { + query?.close() + } catch (disposeError: unknown) { + closeError = thrown(disposeError) + } + + let spawnError = startupError + try { + await child.done + } catch (childError: unknown) { + spawnError = thrown(childError) + } + + const cancelled = cancelledBeforeCleanup || isAborted(request.signal) + if (closeError !== undefined) { + const failures = cancelled + ? [ + new Error('subagent-claude-code: request was aborted before SDK startup'), + spawnError, + closeError, + ] + : [spawnError, closeError] + throw new AggregateError( + failures, + cancelled + ? `subagent-claude-code: request was aborted before SDK startup; Claude Code process startup also failed: ${spawnError.message}; query cleanup also failed` + : `subagent-claude-code: Claude Code process startup failed: ${spawnError.message}; query cleanup also failed`, + ) + } + if (cancelled) { + throw new Error('subagent-claude-code: request was aborted before SDK startup') + } + throw spawnError + } if (child !== undefined) { try { await disposeClaudeCodeChild(query, child) } catch (disposeError: unknown) { throw new AggregateError( - [thrown(error), thrown(disposeError)], + [startupError, thrown(disposeError)], 'subagent-claude-code: startup failed and CLI cleanup also failed', ) } @@ -253,23 +377,30 @@ export async function startClaudeCodeRun( query.close() } catch (disposeError: unknown) { throw new AggregateError( - [thrown(error), thrown(disposeError)], + [startupError, thrown(disposeError)], 'subagent-claude-code: startup failed and query cleanup also failed', ) } } - // oxlint-disable-next-line typescript/no-unnecessary-condition -- the request can abort while process cleanup is awaited. - if (cancelledBeforeCleanup || request.signal.aborted) { + if (cancelledBeforeCleanup || isAborted(request.signal)) { throw new Error('subagent-claude-code: request was aborted before SDK startup') } - throw thrown(error) + throw startupError } const publishedQuery = query const publishedChild = child const result = settleRunResult({ - attempt: () => consumeClaudeQuery(publishedQuery), + attempt: () => consumeClaudeQuery(publishedQuery, () => { + captureDiagnostic(unattendedDiagnostic( + spec.permissionMode, + 'tool permission', + 'denied', + 'Claude Code denied the request before an interactive prompt', + )) + }), collectOutput: () => [], + collectDiagnostic: () => diagnostic, cancelled: () => controller.signal.aborted, onError: spec.onError, signal: request.signal, diff --git a/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts b/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts index 37d02657cb..5f339ce22e 100644 --- a/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -12,26 +13,34 @@ const fixtureDir = fileURLToPath(new URL( )) const driver = join(fixtureDir, 'driver.ts') const configPath = join(fixtureDir, 'cordis.yml') +const packageDir = fileURLToPath(new URL('..', import.meta.url)) +const manifest = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8')) as { + dsh?: { bundle?: { patch?: string } } +} +const bundlePatch = manifest.dsh?.bundle?.patch +if (bundlePatch === undefined) throw new Error('Claude Code package must declare a Bundle patch') +const bundlePatchPath = join(packageDir, bundlePatch) const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url)) describe('product-provider public Loader composition', () => { - it('loads both opt-in packages, one-shot task tools, and job controls without starting either product', async () => { + it('loads the Bundle default, two named Claude instances, their tools, and Codex without starting either product', async () => { const { stdout, stderr } = await runLoaderSmoke({ label: 'product-provider Loader composition', tempDirPrefix: 'dsh-product-provider-loader-', binScript: driver, libBinScript: driver, configPath, + binArgs: [configPath, bundlePatchPath], tsconfigPath: repoTsconfig, env: { - // Loading either optional package must not probe or start its binary. + // Loading the optional package must not probe or start a Claude binary. PATH: '', }, }) expect(stderr).toBe('') expect(JSON.parse(stdout)).toEqual({ - registeredProviders: ['codex', 'claude-code'], + registeredProviders: ['codex', 'claude-primary', 'claude-secondary', 'claude-code'], providers: [ { name: 'codex', @@ -53,6 +62,26 @@ describe('product-provider public Loader composition', () => { }, inheritsParentContext: false, }, + { + name: 'claude-primary', + capabilities: { + outputSchema: false, + depthLimit: false, + toolFilter: false, + persona: false, + }, + inheritsParentContext: false, + }, + { + name: 'claude-secondary', + capabilities: { + outputSchema: false, + depthLimit: false, + toolFilter: false, + persona: false, + }, + inheritsParentContext: false, + }, ], tools: [ { @@ -65,6 +94,16 @@ describe('product-provider public Loader composition', () => { parameterNames: ['description', 'prompt', 'run_in_background'], required: ['description', 'prompt'], }, + { + name: 'subagent_claude_primary', + parameterNames: ['description', 'prompt', 'run_in_background'], + required: ['description', 'prompt'], + }, + { + name: 'subagent_claude_secondary', + parameterNames: ['description', 'prompt', 'run_in_background'], + required: ['description', 'prompt'], + }, ], jobTools: ['job_kill', 'job_list', 'job_output'], starts: 0, diff --git a/packages/subagent/subagent-claude-code/tests/messages-fixture.ts b/packages/subagent/subagent-claude-code/tests/messages-fixture.ts index d8a04cf953..78d2f84176 100644 --- a/packages/subagent/subagent-claude-code/tests/messages-fixture.ts +++ b/packages/subagent/subagent-claude-code/tests/messages-fixture.ts @@ -4,6 +4,12 @@ import { createServer, type IncomingHttpHeaders, type ServerResponse } from 'nod export type MessagesBehavior = | { readonly kind: 'complete'; readonly text: string } | { readonly kind: 'hold' } + | { + readonly kind: 'tool-use' + readonly toolName: string + readonly input: Record + readonly finalText?: string + } /** One recorded Anthropic Messages request. */ interface RecordedMessagesRequest { @@ -81,6 +87,67 @@ function complete( response.end() } +function toolUse( + response: ServerResponse, + body: Record, + toolName: string, + input: Record, +): void { + const model = typeof body.model === 'string' ? body.model : 'fixture-model' + response.writeHead(200, { + 'content-type': 'text/event-stream', + 'cache-control': 'no-cache', + connection: 'keep-alive', + }) + event(response, 'message_start', { + type: 'message_start', + message: { + id: 'msg_dsh_fixture_tool_use', + type: 'message', + role: 'assistant', + model, + content: [], + stop_reason: null, + stop_sequence: null, + usage: { + input_tokens: 7, + output_tokens: 0, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }, + }, + }) + event(response, 'content_block_start', { + type: 'content_block_start', + index: 0, + content_block: { + type: 'tool_use', + id: 'toolu_dsh_fixture', + name: toolName, + input: {}, + }, + }) + event(response, 'content_block_delta', { + type: 'content_block_delta', + index: 0, + delta: { + type: 'input_json_delta', + partial_json: JSON.stringify(input), + }, + }) + event(response, 'content_block_stop', { + type: 'content_block_stop', + index: 0, + }) + event(response, 'message_delta', { + type: 'message_delta', + delta: { stop_reason: 'tool_use', stop_sequence: null }, + usage: { output_tokens: 1 }, + }) + event(response, 'message_stop', { type: 'message_stop' }) + response.end() +} + /** * Start a loopback-only Anthropic Messages SSE fixture. * @param behavior - the single response behavior for this fixture. @@ -118,8 +185,15 @@ export async function startMessagesFixture( requestStartedResolve() if (behavior.kind === 'complete') { complete(response, body, behavior.text) + } else if (behavior.kind === 'tool-use' && requests.length === 1) { + toolUse(response, body, behavior.toolName, behavior.input) + } else if ( + behavior.kind === 'tool-use' + && behavior.finalText !== undefined + ) { + complete(response, body, behavior.finalText) } - // A hold deliberately leaves the response pending until client abort. + // A hold, or a tool-use without final text, waits for client abort. }) }) await new Promise((resolve, reject) => { diff --git a/packages/subagent/subagent-claude-code/tests/real-deepseek.e2e.ts b/packages/subagent/subagent-claude-code/tests/real-deepseek.e2e.ts index 89d08a1878..1881e14d33 100644 --- a/packages/subagent/subagent-claude-code/tests/real-deepseek.e2e.ts +++ b/packages/subagent/subagent-claude-code/tests/real-deepseek.e2e.ts @@ -7,7 +7,7 @@ import { rmSync, } from 'node:fs' import { tmpdir } from 'node:os' -import { delimiter, dirname, join, resolve } from 'node:path' +import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { promisify } from 'node:util' import { Context } from '@deepseek-ai/cordis' @@ -87,7 +87,6 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)( ]) mkdirSync(directory) const env = { - PATH: `${dirname(claudeBin)}${delimiter}${process.env.PATH ?? ''}`, ANTHROPIC_AUTH_TOKEN: apiKey, ANTHROPIC_BASE_URL: `${deepSeekBaseUrl()}/anthropic`, ANTHROPIC_MODEL: 'deepseek-v4-pro[1m]', diff --git a/packages/subagent/subagent-claude-code/tests/real-product.spec.ts b/packages/subagent/subagent-claude-code/tests/real-product.spec.ts index f6767817c8..a8e38885ef 100644 --- a/packages/subagent/subagent-claude-code/tests/real-product.spec.ts +++ b/packages/subagent/subagent-claude-code/tests/real-product.spec.ts @@ -1,14 +1,15 @@ import { execFile } from 'node:child_process' import { + existsSync, mkdirSync, mkdtempSync, readFileSync, - symlinkSync, + realpathSync, writeFileSync, } from 'node:fs' import { rm } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { delimiter, dirname, join, resolve } from 'node:path' +import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { promisify } from 'node:util' import type { @@ -23,6 +24,7 @@ import SubagentRuntime from '@deepseek-ai/dsh-subagent' import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as claudeCode from '../src/index.ts' +import type { ClaudeCodePermissionMode } from '../src/run.ts' import { startMessagesFixture, type MessagesBehavior, @@ -119,37 +121,39 @@ interface RealHarness { readonly parent: Agent readonly workspace: string readonly env: Record - readonly executable: string } -async function realHarness(behavior: MessagesBehavior): Promise<{ - readonly harness: RealHarness +interface RealInstanceFixture { readonly fixture: MessagesFixture -}> { + readonly workspace: string + readonly env: Record +} + +async function realInstanceFixture( + behavior: MessagesBehavior, + nativeAllow: readonly string[] = [], +): Promise { const root = mkdtempSync(join(tmpdir(), 'dsh-claude-code-real-')) roots.push(root) const workspace = join(root, 'workspace') const claudeConfig = join(root, 'claude-config') const xdgConfig = join(root, 'xdg') - const nativeBin = join(root, 'native&%literal%!bang!bin') mkdirSync(workspace) mkdirSync(claudeConfig) mkdirSync(xdgConfig) - mkdirSync(nativeBin) - const executable = join(nativeBin, process.platform === 'win32' ? 'claude.cmd' : 'claude') - if (process.platform === 'win32') { - writeFileSync(executable, `@echo off\r\n"${claudeBin}" %*\r\n`) - } else { - symlinkSync(claudeBin, executable) - } writeFileSync( join(claudeConfig, 'settings.json'), - `${JSON.stringify({ model: settingsModel }, null, 2)}\n`, + `${JSON.stringify({ + model: settingsModel, + permissions: { + defaultMode: 'default', + ...nativeAllow.length === 0 ? {} : { allow: nativeAllow }, + }, + }, null, 2)}\n`, ) const fixture = await startMessagesFixture(behavior) fixtures.push(fixture) const env = { - PATH: `${nativeBin}${delimiter}${process.env.PATH ?? ''}`, ANTHROPIC_API_KEY: fakeKey, ANTHROPIC_BASE_URL: fixture.baseUrl, CLAUDE_CONFIG_DIR: claudeConfig, @@ -164,6 +168,16 @@ async function realHarness(behavior: MessagesBehavior): Promise<{ ALL_PROXY: '', NO_PROXY: '127.0.0.1,localhost', } + return { fixture, workspace, env } +} + +interface RealRuntime { + readonly ctx: Context + readonly handles: SubprocessHandle[] + readonly spawnSpecs: SubprocessSpawnSpec[] +} + +async function realRuntime(): Promise { const ctx = new Context() contexts.push(ctx) await ctx.plugin(SubagentRuntime) @@ -177,14 +191,38 @@ async function realHarness(behavior: MessagesBehavior): Promise<{ handles.push(handle) return handle }) - await ctx.plugin(claudeCode, { env, disposeGraceMs: 3_000 }) + return { ctx, handles, spawnSpecs } +} + +async function realHarness( + behavior: MessagesBehavior, + permissionMode?: ClaudeCodePermissionMode, + nativeAllow: readonly string[] = [], +): Promise<{ + readonly harness: RealHarness + readonly fixture: MessagesFixture +}> { + const instance = await realInstanceFixture(behavior, nativeAllow) + const { ctx, handles, spawnSpecs } = await realRuntime() + await ctx.plugin(claudeCode, { + env: instance.env, + ...permissionMode === undefined ? {} : { permissionMode }, + disposeGraceMs: 3_000, + }) const parent = { id: 'real-parent', - session: { header: { cwd: workspace } }, + session: { header: { cwd: instance.workspace } }, } as unknown as Agent return { - harness: { ctx, handles, spawnSpecs, parent, workspace, env, executable }, - fixture, + harness: { + ctx, + handles, + spawnSpecs, + parent, + workspace: instance.workspace, + env: instance.env, + }, + fixture: instance.fixture, } } @@ -225,7 +263,7 @@ describe('real Claude Agent SDK 0.3.220 and its distributed Claude Code 2.1.220 expect(sdkPackage.version).toBe('0.3.220') expect(sdkPackage.claudeCodeVersion).toBe('2.1.220') expect(sdkPackage.optionalDependencies[platformPackage]).toBe('0.3.220') - const version = await execFileAsync(process.platform === 'win32' ? claudeBin : harness.executable, ['--version'], { + const version = await execFileAsync(claudeBin, ['--version'], { env: { ...process.env, ...harness.env }, }) expect(version.stdout.trim()).toBe('2.1.220 (Claude Code)') @@ -242,18 +280,16 @@ describe('real Claude Agent SDK 0.3.220 and its distributed Claude Code 2.1.220 message.type === 'system' && message.subtype === 'init', ) expect(initMessage?.claude_code_version).toBe('2.1.220') - if (process.platform === 'win32') { - expect(harness.spawnSpecs[0]?.argv.slice(0, 6)).toEqual([ - 'cmd.exe', '/d', '/v:off', '/s', '/c', '%DSH_CLAUDE_CODE_EXECUTABLE%', - ]) - const batchExecutable = harness.spawnSpecs[0]?.env?.DSH_CLAUDE_CODE_EXECUTABLE - expect(batchExecutable?.startsWith('"')).toBe(true) - expect(batchExecutable?.endsWith('"')).toBe(true) - expect(batchExecutable?.slice(1, -1).toLowerCase()) - .toBe(harness.executable.toLowerCase()) - } else { - expect(harness.spawnSpecs[0]?.argv[0]).toBe(harness.executable) - } + const spawnedExecutable = harness.spawnSpecs[0]?.argv[0] + expect(spawnedExecutable).toBeDefined() + expect(process.platform === 'win32' + ? realpathSync(spawnedExecutable!).toLowerCase() + : realpathSync(spawnedExecutable!)) + .toBe(process.platform === 'win32' + ? realpathSync(claudeBin).toLowerCase() + : realpathSync(claudeBin)) + expect(harness.spawnSpecs[0]?.env) + .not.toHaveProperty('DSH_CLAUDE_CODE_EXECUTABLE') expect(fixture.requests).toHaveLength(1) const recorded = fixture.requests[0]! @@ -278,6 +314,80 @@ describe('real Claude Agent SDK 0.3.220 and its distributed Claude Code 2.1.220 await expectQuiescent(harness.handles) }) + it('runs two named instances concurrently and unloads one without revoking its run', async () => { + const safeInstance = await realInstanceFixture({ kind: 'hold' }) + const bypassInstance = await realInstanceFixture({ + kind: 'complete', + text: 'NAMED_BYPASS_RESULT', + }) + const { ctx, handles, spawnSpecs } = await realRuntime() + const safeFiber = await ctx.plugin(claudeCode, { + providerName: 'claude-safe', + env: safeInstance.env, + permissionMode: 'dontAsk', + disposeGraceMs: 3_000, + }) + const bypassFiber = await ctx.plugin(claudeCode, { + providerName: 'claude-bypass', + env: bypassInstance.env, + permissionMode: 'bypassPermissions', + disposeGraceMs: 3_000, + }) + const safeParent = { + id: 'safe-parent', + session: { header: { cwd: safeInstance.workspace } }, + } as unknown as Agent + const bypassParent = { + id: 'bypass-parent', + session: { header: { cwd: bypassInstance.workspace } }, + } as unknown as Agent + const safeController = new AbortController() + + const [safeRun, bypassRun] = await Promise.all([ + ctx.subagents.start('claude-safe', { + prompt: [{ type: 'text', text: 'Hold the safe instance.' }], + parent: safeParent, + signal: safeController.signal, + }), + ctx.subagents.start('claude-bypass', { + prompt: [{ type: 'text', text: 'Complete the bypass instance.' }], + parent: bypassParent, + signal: new AbortController().signal, + }), + ]) + await safeInstance.fixture.requestStarted + await safeFiber.dispose() + expect(ctx.subagents.list()).toEqual(['claude-bypass']) + await expect(ctx.subagents.start('claude-safe', { + prompt: [{ type: 'text', text: 'This start must fail.' }], + parent: safeParent, + signal: new AbortController().signal, + })).rejects.toMatchObject({ code: 'NO_PROVIDER' }) + + await expect(bypassRun.result).resolves.toEqual({ + output: [{ type: 'text', text: 'NAMED_BYPASS_RESULT' }], + stopReason: 'completed', + }) + safeController.abort(new Error('cancel only the published safe run')) + await expect(safeRun.result).resolves.toEqual({ + output: [], + stopReason: 'aborted', + }) + await Promise.all([safeRun.dispose(), bypassRun.dispose()]) + expect(safeInstance.fixture.requests).toHaveLength(1) + expect(bypassInstance.fixture.requests).toHaveLength(1) + expect(safeInstance.fixture.requests[0]?.body.messages) + .not.toEqual(bypassInstance.fixture.requests[0]?.body.messages) + expect(spawnSpecs.map(spec => spec.env?.CLAUDE_CONFIG_DIR).sort()) + .toEqual([ + safeInstance.env.CLAUDE_CONFIG_DIR, + bypassInstance.env.CLAUDE_CONFIG_DIR, + ].sort()) + await expectQuiescent(handles) + await bypassFiber.dispose() + expect(ctx.subagents.list()).toEqual([]) + }) + it('maps a real CLI process failure to error', async () => { const { harness, fixture } = await realHarness({ kind: 'hold' }) const run = await startRequest(harness, 'Exercise the failure path.') @@ -294,6 +404,80 @@ describe('real Claude Agent SDK 0.3.220 and its distributed Claude Code 2.1.220 await expectQuiescent(harness.handles) }) + it('overrides interactive settings, denies a write, and returns a safe diagnostic', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-claude-code-denied-target-')) + roots.push(root) + const target = join(root, 'denied.txt') + const { harness } = await realHarness({ + kind: 'tool-use', + toolName: 'Write', + input: { + file_path: target, + content: 'SECRET_TOKEN must not reach the diagnostic', + }, + }) + const run = await startRequest(harness, 'Write the requested fixture file.') + await vi.waitFor(() => { + expect(observedSdkMessages.some(message => + message.type === 'system' + && message.subtype === 'permission_denied')).toBe(true) + }, { timeout: 30_000 }) + expect(existsSync(target)).toBe(false) + harness.handles[0]!.terminate() + const result = await run.result + expect(result).toEqual({ + output: [], + diagnostic: 'Claude Code unattended decision (mode: dontAsk; request: tool permission; decision: denied): Claude Code denied the request before an interactive prompt', + stopReason: 'error', + }) + expect(result.diagnostic).not.toContain(target) + expect(result.diagnostic).not.toContain('SECRET_TOKEN') + await run.dispose() + await expectQuiescent(harness.handles) + }) + + it('runs an explicitly selected bypass write in the isolated workspace', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-claude-code-bypass-target-')) + roots.push(root) + const target = join(root, 'bypass.txt') + const { harness } = await realHarness({ + kind: 'tool-use', + toolName: 'Write', + input: { + file_path: target, + content: 'bypass write completed', + }, + finalText: 'write complete', + }, 'bypassPermissions') + const run = await startRequest(harness, 'Write the requested fixture file.') + await expect(run.result).resolves.toEqual({ + output: [{ type: 'text', text: 'write complete' }], + stopReason: 'completed', + }) + expect(readFileSync(target, 'utf8')).toBe('bypass write completed') + await run.dispose() + await expectQuiescent(harness.handles) + }) + + it('returns the completed plan without approving execution', async () => { + const { harness, fixture } = await realHarness({ + kind: 'tool-use', + toolName: 'ExitPlanMode', + input: {}, + finalText: 'PLAN_ONLY_RESULT', + }, 'plan', ['ExitPlanMode']) + const run = await startRequest(harness, 'Design the fixture change without implementing it.') + await expect(run.result).resolves.toEqual({ + output: [{ type: 'text', text: 'PLAN_ONLY_RESULT' }], + stopReason: 'completed', + }) + expect(fixture.requests).toHaveLength(2) + expect(JSON.stringify(fixture.requests[1]?.body.messages)) + .toContain('ExitPlanMode exists but is not enabled in this context') + await run.dispose() + await expectQuiescent(harness.handles) + }) + it('settles cancellation and leaves the real SDK-spawned CLI tree quiescent', async () => { const { harness, fixture } = await realHarness({ kind: 'hold' }) const controller = new AbortController() diff --git a/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts b/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts index a3df59a74f..8f1ad34d8a 100644 --- a/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts +++ b/packages/subagent/subagent-claude-code/tests/subagent-claude-code.spec.ts @@ -1,13 +1,18 @@ +import { readFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' import { PassThrough } from 'node:stream' +import { fileURLToPath } from 'node:url' import type { Options, Query, SDKMessage, + SDKPermissionDeniedMessage, SDKResultMessage, SpawnOptions, } from '@anthropic-ai/claude-agent-sdk' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' +import * as yaml from 'js-yaml' import { afterEach, beforeEach, @@ -36,6 +41,8 @@ import { sdkEnvironmentOverlay, } from '../src/process.ts' import { + CLAUDE_CODE_PERMISSION_MODES, + DEFAULT_CLAUDE_CODE_PERMISSION_MODE, claudeQueryOptions, consumeClaudeQuery, disposeClaudeCodeChild, @@ -52,6 +59,19 @@ type QueryFactory = (params: { const queryMock = vi.hoisted(() => vi.fn()) +const CLAUDE_AGENT_SDK_VERSION = '0.3.220' +const CLAUDE_CODE_VERSION = '2.1.220' +const CLAUDE_PLATFORM_PACKAGES = [ + '@anthropic-ai/claude-agent-sdk-darwin-arm64', + '@anthropic-ai/claude-agent-sdk-darwin-x64', + '@anthropic-ai/claude-agent-sdk-linux-arm64', + '@anthropic-ai/claude-agent-sdk-linux-arm64-musl', + '@anthropic-ai/claude-agent-sdk-linux-x64', + '@anthropic-ai/claude-agent-sdk-linux-x64-musl', + '@anthropic-ai/claude-agent-sdk-win32-arm64', + '@anthropic-ai/claude-agent-sdk-win32-x64', +] as const + vi.mock('@anthropic-ai/claude-agent-sdk', async importOriginal => ({ ...await importOriginal(), query: queryMock, @@ -189,6 +209,20 @@ function failure( } as SDKResultMessage } +function permissionDenied(): SDKPermissionDeniedMessage { + return { + type: 'system', + subtype: 'permission_denied', + tool_name: 'Bash', + tool_use_id: 'tool-secret', + decision_reason_type: 'mode', + decision_reason: 'contains /private/secret.txt', + message: 'command with SECRET_TOKEN was denied', + uuid: '00000000-0000-4000-8000-000000000001', + session_id: 'session-secret', + } +} + function queryFrom( messages: readonly SDKMessage[], after?: Error, @@ -248,7 +282,7 @@ function fakeRun( const options: FakeRun['options'] = [] const spec: ClaudeCodeRunSpec = { cwd: '/workspace', - executable: '/native/claude', + permissionMode: DEFAULT_CLAUDE_CODE_PERMISSION_MODE, env: { ANTHROPIC_API_KEY: 'fake-key' }, disposeGraceMs: 5, spawn: (spawnSpec) => { @@ -282,6 +316,66 @@ afterEach(() => { }) describe('task admission and package contracts', () => { + it('ships one independently installable provider-only Bundle patch', () => { + const root = fileURLToPath(new URL('..', import.meta.url)) + const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as { + dependencies?: Record + files?: string[] + dsh?: { bundle?: { patch?: string } } + } + expect(manifest.dsh?.bundle?.patch).toBe('./cordis.patch.yml') + expect(manifest.files).toContain('cordis.patch.yml') + expect(manifest.dependencies).toHaveProperty( + '@anthropic-ai/claude-agent-sdk', + CLAUDE_AGENT_SDK_VERSION, + ) + expect(manifest.dependencies).toHaveProperty( + '@modelcontextprotocol/sdk', + '^1.29.0', + ) + expect(manifest.dependencies).toHaveProperty('zod', '^4.4.3') + expect(manifest.dependencies).not.toHaveProperty('@deepseek-ai/dsh-subagent-codex') + + const sdkRoot = dirname(fileURLToPath( + import.meta.resolve('@anthropic-ai/claude-agent-sdk'), + )) + const sdkManifest = JSON.parse(readFileSync( + resolve(sdkRoot, 'package.json'), + 'utf8', + )) as { + version: string + claudeCodeVersion: string + optionalDependencies: Record + } + expect(sdkManifest.version).toBe(CLAUDE_AGENT_SDK_VERSION) + expect(sdkManifest.claudeCodeVersion).toBe(CLAUDE_CODE_VERSION) + expect(sdkManifest.optionalDependencies).toEqual(Object.fromEntries( + CLAUDE_PLATFORM_PACKAGES.map(packageName => [ + packageName, + CLAUDE_AGENT_SDK_VERSION, + ]), + )) + const lockfile = readFileSync(resolve(root, '../../../pnpm-lock.yaml'), 'utf8') + for (const packageName of CLAUDE_PLATFORM_PACKAGES) { + expect(lockfile).toContain( + ` '${packageName}@${CLAUDE_AGENT_SDK_VERSION}':`, + ) + expect(lockfile).toContain( + ` '${packageName}': ${CLAUDE_AGENT_SDK_VERSION}`, + ) + } + + const parsed = yaml.load(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) + const rows = Array.isArray(parsed) + ? (parsed as Array<{ insert?: Array<{ id?: string; name?: string }> }>).flatMap(entry => entry.insert ?? []) + : [] + expect(rows).toEqual([{ + id: 'subagent-claude-code', + name: '@deepseek-ai/dsh-subagent-claude-code', + }]) + expect(JSON.stringify(rows)).not.toContain('tool-subagent') + }) + it('preserves text sequences and rejects empty, blank, and non-text tasks', () => { expect(textTask([ { type: 'text', text: 'one' }, @@ -294,7 +388,7 @@ describe('task admission and package contracts', () => { .toThrow('must not be empty') }) - it('registers one fixed descriptor, validates config, and unregisters on HMR', async () => { + it('registers the default descriptor, validates config, and unregisters on HMR', async () => { const ctx = new Context() await ctx.plugin(SubagentRuntime) await ctx.plugin(LocalSubprocessRuntime) @@ -325,6 +419,146 @@ describe('task admission and package contracts', () => { await ctx.fiber.dispose() }) + it('keeps named instances, runs, and HMR ownership isolated', async () => { + const ctx = new Context() + await ctx.plugin(SubagentRuntime) + await ctx.plugin(LocalSubprocessRuntime) + const safeChild = fakeChild() + const bypassChild = fakeChild() + const spawnSpecs: SubprocessSpawnSpec[] = [] + vi.spyOn(ctx.subprocess, 'resolveExecutable') + .mockResolvedValue('/native/claude') + vi.spyOn(ctx.subprocess, 'spawn').mockImplementation((spec) => { + spawnSpecs.push(spec) + return spec.env?.DSH_CLAUDE_INSTANCE === 'safe' + ? safeChild.handle + : bypassChild.handle + }) + const queryOptions: Options[] = [] + queryMock.mockImplementation(({ options }) => { + queryOptions.push(options) + options.spawnClaudeCodeProcess!(sdkSpawnOptions({ + command: options.pathToClaudeCodeExecutable!, + cwd: options.cwd!, + env: options.env!, + signal: options.abortController!.signal, + })) + return options.permissionMode === 'dontAsk' + ? waitingQuery(options.abortController!.signal) + : queryFrom([success('bypass answer')]) + }) + + const added: string[] = [] + const started: string[] = [] + const ended: string[] = [] + const removed: string[] = [] + ctx.on('subagent/provider-added', provider => void added.push(provider.name)) + ctx.on('subagent/start', info => void started.push(info.provider)) + ctx.on('subagent/end', info => void ended.push(info.provider)) + ctx.on('subagent/provider-removed', providerName => void removed.push(providerName)) + const safeFiber = await ctx.plugin(claudeCode, { + providerName: 'claude-safe', + env: { DSH_CLAUDE_INSTANCE: 'safe' }, + permissionMode: 'dontAsk', + disposeGraceMs: 11, + }) + const bypassFiber = await ctx.plugin(claudeCode, { + providerName: 'claude-bypass', + env: { DSH_CLAUDE_INSTANCE: 'bypass' }, + permissionMode: 'bypassPermissions', + disposeGraceMs: 29, + }) + expect(ctx.subagents.list()).toEqual(['claude-safe', 'claude-bypass']) + expect(added).toEqual(['claude-safe', 'claude-bypass']) + + const safeController = new AbortController() + const [safeRun, bypassRun] = await Promise.all([ + ctx.subagents.start('claude-safe', request(undefined, safeController.signal)), + ctx.subagents.start('claude-bypass', request()), + ]) + await safeFiber.dispose() + expect(ctx.subagents.list()).toEqual(['claude-bypass']) + expect(removed).toEqual(['claude-safe']) + await expect(ctx.subagents.start('claude-safe', request())) + .rejects.toMatchObject({ code: 'NO_PROVIDER' }) + + await expect(bypassRun.result).resolves.toEqual({ + output: [{ type: 'text', text: 'bypass answer' }], + stopReason: 'completed', + }) + safeController.abort(new Error('stop only the safe instance')) + await expect(safeRun.result).resolves.toEqual({ + output: [], + stopReason: 'aborted', + }) + expect(queryOptions.map(options => ({ + instance: options.env?.DSH_CLAUDE_INSTANCE, + permissionMode: options.permissionMode, + }))).toEqual([ + { instance: 'safe', permissionMode: 'dontAsk' }, + { instance: 'bypass', permissionMode: 'bypassPermissions' }, + ]) + expect(spawnSpecs.map(spec => ({ + instance: spec.env?.DSH_CLAUDE_INSTANCE, + graceMs: spec.graceMs, + }))).toEqual([ + { instance: 'safe', graceMs: 11 }, + { instance: 'bypass', graceMs: 29 }, + ]) + + await Promise.all([safeRun.dispose(), bypassRun.dispose()]) + expect([...started].sort()).toEqual(['claude-bypass', 'claude-safe']) + expect([...ended].sort()).toEqual(['claude-bypass', 'claude-safe']) + expect(safeChild.terminate).toHaveBeenCalledOnce() + expect(bypassChild.terminate).toHaveBeenCalledOnce() + await bypassFiber.dispose() + expect(removed).toEqual(['claude-safe', 'claude-bypass']) + await ctx.fiber.dispose() + }) + + it('rejects duplicate provider names without replacing the first instance', async () => { + const ctx = new Context() + await ctx.plugin(SubagentRuntime) + await ctx.plugin(LocalSubprocessRuntime) + const firstFiber = await ctx.plugin(claudeCode, { + providerName: 'claude-duplicate', + }) + const first = ctx.subagents.getProvider('claude-duplicate') + await expect(ctx.plugin(claudeCode, { + providerName: 'claude-duplicate', + permissionMode: 'bypassPermissions', + })).rejects.toMatchObject({ code: 'DUPLICATE_PROVIDER' }) + expect(ctx.subagents.getProvider('claude-duplicate')).toBe(first) + expect(ctx.subagents.list()).toEqual(['claude-duplicate']) + await firstFiber.dispose() + await ctx.fiber.dispose() + }) + + it('accepts only the five fixed non-interactive permission modes', () => { + expect(claudeCode.Config({}).providerName).toBe('claude-code') + expect(claudeCode.Config({ providerName: 'claude-safe' }).providerName) + .toBe('claude-safe') + expect(() => claudeCode.Config({ providerName: '' })).toThrow() + expect(claudeCode.Config({}).permissionMode) + .toBe(DEFAULT_CLAUDE_CODE_PERMISSION_MODE) + for (const permissionMode of CLAUDE_CODE_PERMISSION_MODES) { + expect(claudeCode.Config({ permissionMode }).permissionMode) + .toBe(permissionMode) + } + for (const permissionMode of ['default', 'interactive', 'future-mode']) { + expect(() => claudeCode.Config({ permissionMode } as never)).toThrow() + } + }) + + it('resolves the safe permission default when apply is called directly', async () => { + const ctx = new Context() + await ctx.plugin(SubagentRuntime) + await ctx.plugin(LocalSubprocessRuntime) + claudeCode.apply(ctx, { env: {}, disposeGraceMs: 3_000 }) + expect(ctx.subagents.getProvider('claude-code')).toBeDefined() + await ctx.fiber.dispose() + }) + it('starts through the registered provider with its resolved config and diagnostics', async () => { const ctx = new Context() await ctx.plugin(SubagentRuntime) @@ -333,18 +567,20 @@ describe('task admission and package contracts', () => { const spawn = vi.spyOn(ctx.subprocess, 'spawn') .mockImplementation(() => child.handle) const resolveExecutable = vi.spyOn(ctx.subprocess, 'resolveExecutable') - .mockResolvedValue('/native/claude') + .mockResolvedValue('/host/bin/claude') const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) await ctx.plugin(claudeCode, { + providerName: 'claude-diagnostic', env: { ANTHROPIC_API_KEY: 'provider-fake-key', CLAUDE_CONFIG_DIR: '/private/tmp/dsh-claude-code-unit-config', HOME: '/private/tmp/dsh-claude-code-unit-home', }, + permissionMode: 'auto', disposeGraceMs: 29, }) - await expect(ctx.subagents.start('claude-code', { + await expect(ctx.subagents.start('claude-diagnostic', { ...request(), parent: { id: 'parent-without-cwd', @@ -355,12 +591,17 @@ describe('task admission and package contracts', () => { ) expect(queryMock).not.toHaveBeenCalled() - resolveExecutable.mockRejectedValueOnce(new Error('claude missing from PATH')) - await expect(ctx.subagents.start('claude-code', request())) - .rejects.toThrow('claude missing from PATH') - expect(queryMock).not.toHaveBeenCalled() + vi.stubEnv('PATH', '/host/bin') + queryMock.mockImplementationOnce(() => { + throw new Error( + 'Native CLI binary for fixture-platform not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.', + ) + }) + await expect(ctx.subagents.start('claude-diagnostic', request())) + .rejects.toThrow('Native CLI binary for fixture-platform not found') + expect(resolveExecutable).not.toHaveBeenCalled() - const run = await ctx.subagents.start('claude-code', request()) + const run = await ctx.subagents.start('claude-diagnostic', request()) child.settle({ exitCode: 9, signal: null }) child.stdout.end() await expect(run.result).resolves.toEqual({ @@ -368,15 +609,12 @@ describe('task admission and package contracts', () => { stopReason: 'error', }) expect(warn).toHaveBeenCalledWith(expect.stringContaining( - 'subagent-claude-code: child run failed (error):', + 'subagent-claude-code "claude-diagnostic": child run failed (error):', )) - expect(resolveExecutable).toHaveBeenCalledWith( - 'claude', - expect.objectContaining({ ANTHROPIC_API_KEY: 'provider-fake-key' }), - expect.any(AbortSignal), - ) - expect(queryMock.mock.calls[0]?.[0].options.pathToClaudeCodeExecutable) - .toBe('/native/claude') + expect(resolveExecutable).not.toHaveBeenCalled() + expect(queryMock.mock.calls[1]?.[0].options) + .not.toHaveProperty('pathToClaudeCodeExecutable') + expect(queryMock.mock.calls[1]?.[0].options.permissionMode).toBe('auto') expect(spawn).toHaveBeenCalledWith(expect.objectContaining({ cwd: process.cwd(), graceMs: 29, @@ -456,20 +694,17 @@ describe('official spawn projection', () => { )).toThrow('SDK spawn request omitted its workspace') }) - it.each(['cmd', 'bat'])('routes a Windows .%s shim through cmd.exe', (extension) => { - const command = String.raw`C:\Program Files\Claude\claude.${extension}` + it('forwards the SDK-selected Windows native executable without a batch shim', () => { + const command = String.raw`C:\Program Files\Claude\claude.exe` const spec = claudeSpawnSpec(sdkSpawnOptions({ command, args: ['--output-format', 'stream-json'], - }), 7, 'win32') + }), 7) expect(spec.argv).toEqual([ - 'cmd.exe', '/d', '/v:off', '/s', '/c', '%DSH_CLAUDE_CODE_EXECUTABLE%', - '--output-format', 'stream-json', + command, '--output-format', 'stream-json', ]) - expect(spec.env).toEqual(expect.objectContaining({ - DSH_CLAUDE_CODE_EXECUTABLE: `"${command}"`, - })) + expect(spec.env).not.toHaveProperty('DSH_CLAUDE_CODE_EXECUTABLE') }) it('projects streams, exit facts, listeners, and idempotent tree termination', async () => { @@ -530,16 +765,17 @@ describe('official spawn projection', () => { }) describe('query options and result mapping', () => { - it('builds the fixed unattended options over the scrubbed environment', () => { + it('builds the fixed unattended options over the scrubbed environment', async () => { vi.stubEnv('HOST_VISIBLE', 'visible') vi.stubEnv('HOST_SECRET_TOKEN', 'must-not-leak') vi.stubEnv('DSH_INTERNAL', 'must-not-leak') const child = fakeChild() const spawn = vi.fn(() => child.handle) const captured: SubprocessHandle[] = [] + const diagnostics: string[] = [] const spec: ClaudeCodeRunSpec = { cwd: '/workspace', - executable: '/native/claude', + permissionMode: 'acceptEdits', env: { HOST_VISIBLE: 'overridden', ANTHROPIC_API_KEY: 'explicit-fake-key', @@ -548,32 +784,70 @@ describe('query options and result mapping', () => { spawn, } const controller = new AbortController() - const options = claudeQueryOptions(spec, controller, (value) => { - captured.push(value) - }) + const options = claudeQueryOptions( + spec, + controller, + (value) => { + captured.push(value) + }, + value => diagnostics.push(value), + ) expect(options).toMatchObject({ abortController: controller, cwd: '/workspace', - pathToClaudeCodeExecutable: '/native/claude', persistSession: false, disallowedTools: ['AskUserQuestion'], + permissionMode: 'acceptEdits', + supportedDialogKinds: ['refusal_fallback_prompt'], }) + expect(options).not.toHaveProperty('pathToClaudeCodeExecutable') + expect(options).not.toHaveProperty('allowDangerouslySkipPermissions') expect(options.env).toMatchObject({ HOST_VISIBLE: 'overridden', ANTHROPIC_API_KEY: 'explicit-fake-key', }) expect(options.env).not.toHaveProperty('HOST_SECRET_TOKEN') expect(options.env).not.toHaveProperty('DSH_INTERNAL') - for (const omitted of [ - 'settingSources', - 'canUseTool', - 'onElicitation', - 'onUserDialog', - 'supportedDialogKinds', - ]) { - expect(options).not.toHaveProperty(omitted) - } + expect(options).not.toHaveProperty('settingSources') + + const callbackSignal = new AbortController().signal + await expect(options.canUseTool!( + 'Bash', + { command: 'cat /private/secret.txt', token: 'SECRET_TOKEN' }, + { + signal: callbackSignal, + toolUseID: 'tool-1', + requestId: 'request-1', + blockedPath: '/private/secret.txt', + decisionReason: 'SECRET_TOKEN in /private/secret.txt', + }, + )).resolves.toEqual({ + behavior: 'deny', + message: 'This unattended Claude Code subagent cannot request human approval.', + }) + await expect(options.onElicitation!( + { + serverName: 'private-server', + message: 'enter SECRET_TOKEN', + requestedSchema: { secret: true }, + }, + { signal: callbackSignal }, + )).resolves.toEqual({ action: 'decline' }) + await expect(options.onUserDialog!( + { + dialogKind: 'refusal_fallback_prompt', + payload: { path: '/private/secret.txt', token: 'SECRET_TOKEN' }, + }, + { signal: callbackSignal }, + )).resolves.toEqual({ behavior: 'cancelled' }) + expect(diagnostics).toEqual([ + 'Claude Code unattended decision (mode: acceptEdits; request: tool permission; decision: denied): the provider does not request human approval', + 'Claude Code unattended decision (mode: acceptEdits; request: MCP elicitation; decision: declined): the provider does not collect interactive MCP input', + 'Claude Code unattended decision (mode: acceptEdits; request: user dialog; decision: cancelled): the provider does not render blocking dialogs', + ]) + expect(diagnostics.join('\n')).not.toContain('SECRET_TOKEN') + expect(diagnostics.join('\n')).not.toContain('/private/secret.txt') const spawned = options.spawnClaudeCodeProcess!(sdkSpawnOptions()) expect(spawned).toBeInstanceOf(ManagedClaudeCodeProcess) @@ -585,6 +859,46 @@ describe('query options and result mapping', () => { })) }) + it.each(CLAUDE_CODE_PERMISSION_MODES)( + 'maps the %s mode and only confirms the dangerous bypass', + (permissionMode) => { + const child = fakeChild() + const options = claudeQueryOptions({ + cwd: '/workspace', + permissionMode, + env: {}, + disposeGraceMs: 17, + spawn: () => child.handle, + }, new AbortController(), () => {}, () => {}) + expect(options.permissionMode).toBe(permissionMode) + expect(options.disallowedTools).toEqual(permissionMode === 'plan' + ? ['AskUserQuestion', 'ExitPlanMode'] + : ['AskUserQuestion']) + if (permissionMode === 'bypassPermissions') { + expect(options.allowDangerouslySkipPermissions).toBe(true) + expect(options).not.toHaveProperty('canUseTool') + } else { + expect(options).not.toHaveProperty('allowDangerouslySkipPermissions') + expect(options.canUseTool).toBeTypeOf('function') + } + }, + ) + + it('disallows ExitPlanMode before native plan-mode allow rules', () => { + const child = fakeChild() + const options = claudeQueryOptions({ + cwd: '/workspace', + permissionMode: 'plan', + env: {}, + disposeGraceMs: 17, + spawn: () => child.handle, + }, new AbortController(), () => {}, () => {}) + expect(options.disallowedTools).toEqual([ + 'AskUserQuestion', + 'ExitPlanMode', + ]) + }) + it('accepts only a non-error success with a non-blank final result', () => { expect(successfulResult(success('exact final'))).toBe('exact final') expect(() => successfulResult(success('answer', true))) @@ -614,6 +928,16 @@ describe('query options and result mapping', () => { await expect(consumeClaudeQuery( queryFrom([{ type: 'system', subtype: 'init' } as SDKMessage]), )).rejects.toThrow('ended without a result') + + const onPermissionDenied = vi.fn() + await expect(consumeClaudeQuery(queryFrom([ + permissionDenied(), + success('after denial'), + ]), onPermissionDenied)).resolves.toEqual({ + output: [{ type: 'text', text: 'after denial' }], + stopReason: 'completed', + }) + expect(onPermissionDenied).toHaveBeenCalledOnce() }) }) @@ -667,6 +991,61 @@ describe('run publication, cancellation, and settlement', () => { } }) + it('attaches a safe diagnostic when a permission denial precedes failure', async () => { + const fixture = fakeRun([ + permissionDenied(), + failure('error_during_execution'), + ]) + const run = await startClaudeCodeRun(request(), fixture.spec) + const result = await run.result + expect(result).toEqual({ + output: [], + diagnostic: 'Claude Code unattended decision (mode: dontAsk; request: tool permission; decision: denied): Claude Code denied the request before an interactive prompt', + stopReason: 'error', + }) + expect(result.diagnostic).not.toContain('SECRET_TOKEN') + expect(result.diagnostic).not.toContain('/private/secret.txt') + await run.dispose() + }) + + it('omits captured diagnostics on success and isolates concurrent runs', async () => { + const children = [fakeChild(), fakeChild()] + let childIndex = 0 + const spec: ClaudeCodeRunSpec = { + cwd: '/workspace', + permissionMode: 'dontAsk', + env: {}, + disposeGraceMs: 5, + spawn: () => children[childIndex++]!.handle, + } + queryMock.mockImplementation(({ prompt, options }) => { + options.spawnClaudeCodeProcess!(sdkSpawnOptions()) + return prompt === 'denied then completed' + ? queryFrom([permissionDenied(), success('completed answer')]) + : queryFrom([failure('error_during_execution')]) + }) + + const [completed, failed] = await Promise.all([ + startClaudeCodeRun( + request([{ type: 'text', text: 'denied then completed' }]), + spec, + ), + startClaudeCodeRun( + request([{ type: 'text', text: 'unrelated failure' }]), + spec, + ), + ]) + await expect(completed.result).resolves.toEqual({ + output: [{ type: 'text', text: 'completed answer' }], + stopReason: 'completed', + }) + await expect(failed.result).resolves.toEqual({ + output: [], + stopReason: 'error', + }) + await Promise.all([completed.dispose(), failed.dispose()]) + }) + it('fails closed when iteration rejects after a result', async () => { const fixture = fakeRun( [success('partial final')], @@ -703,7 +1082,7 @@ describe('run publication, cancellation, and settlement', () => { let index = 0 const spec: ClaudeCodeRunSpec = { cwd: '/workspace', - executable: '/native/claude', + permissionMode: 'dontAsk', env: {}, disposeGraceMs: 5, spawn: () => children[index++]!.handle, @@ -754,7 +1133,7 @@ describe('run publication, cancellation, and settlement', () => { request(undefined, parentAbort.signal), { cwd: '/workspace', - executable: '/native/claude', + permissionMode: DEFAULT_CLAUDE_CODE_PERMISSION_MODE, env: {}, disposeGraceMs: 5, spawn: () => child.handle, @@ -842,14 +1221,101 @@ describe('run publication, cancellation, and settlement', () => { expect(factoryController?.signal.aborted).toBe(true) expect(spawned.terminate).toHaveBeenCalledOnce() + const spawnError = Object.assign( + new Error('spawn /sdk/claude EACCES'), + { code: 'EACCES', path: '/sdk/claude' }, + ) const failedSpawn = fakeChild({ pid: -1, - doneError: new Error('spawn failed'), + doneError: spawnError, }) const failed = fakeRun([], undefined, failedSpawn) await expect(startClaudeCodeRun(request(), failed.spec)) - .rejects.toBeInstanceOf(AggregateError) + .rejects.toBe(spawnError) expect(failed.close).toHaveBeenCalledOnce() + expect(failedSpawn.terminate).not.toHaveBeenCalled() + expect(failedSpawn.waitForExit).not.toHaveBeenCalled() + + const failedSpawnAbort = new AbortController() + const cancelledFailedSpawn = fakeChild({ + pid: -1, + doneError: spawnError, + }) + const cancelledFailedClose = vi.fn() + queryMock.mockImplementationOnce(({ options }) => { + options.spawnClaudeCodeProcess!(sdkSpawnOptions()) + failedSpawnAbort.abort(new Error('startup cancelled')) + return queryFrom([], undefined, cancelledFailedClose) + }) + await expect(startClaudeCodeRun( + request(undefined, failedSpawnAbort.signal), + { ...unused.spec, spawn: () => cancelledFailedSpawn.handle }, + )).rejects.toThrow('aborted before SDK startup') + expect(cancelledFailedClose).toHaveBeenCalledOnce() + + const cancelledFailedSpawnCloseError = new Error('cancelled query close failed') + const cancelledFailedSpawnClose = vi.fn(() => { + throw cancelledFailedSpawnCloseError + }) + const cancelledFailedSpawnWithCloseFailure = fakeChild({ + pid: -1, + doneError: spawnError, + }) + const failedSpawnAbortWithCloseFailure = new AbortController() + queryMock.mockImplementationOnce(({ options }) => { + options.spawnClaudeCodeProcess!(sdkSpawnOptions()) + failedSpawnAbortWithCloseFailure.abort(new Error('startup cancelled')) + return queryFrom([], undefined, cancelledFailedSpawnClose) + }) + const cancelledWithCloseFailure = startClaudeCodeRun( + request(undefined, failedSpawnAbortWithCloseFailure.signal), + { ...unused.spec, spawn: () => cancelledFailedSpawnWithCloseFailure.handle }, + ) + await expect(cancelledWithCloseFailure).rejects.toMatchObject({ + message: 'subagent-claude-code: request was aborted before SDK startup; Claude Code process startup also failed: spawn /sdk/claude EACCES; query cleanup also failed', + errors: [ + expect.objectContaining({ message: 'subagent-claude-code: request was aborted before SDK startup' }), + spawnError, + cancelledFailedSpawnCloseError, + ], + }) + expect(cancelledFailedSpawnClose).toHaveBeenCalledOnce() + + const failedSpawnCloseError = new Error('query close failed') + const failedSpawnClose = vi.fn(() => { throw failedSpawnCloseError }) + const failedSpawnWithCloseFailure = fakeChild({ + pid: -1, + doneError: spawnError, + }) + queryMock.mockImplementationOnce(({ options }) => { + options.spawnClaudeCodeProcess!(sdkSpawnOptions()) + return queryFrom([], undefined, failedSpawnClose) + }) + const failedWithCloseFailure = startClaudeCodeRun(request(), { + ...unused.spec, + spawn: () => failedSpawnWithCloseFailure.handle, + }) + await expect(failedWithCloseFailure) + .rejects.toThrow('spawn /sdk/claude EACCES') + await expect(failedWithCloseFailure).rejects.toMatchObject({ + errors: [spawnError, failedSpawnCloseError], + }) + + const cleanupError = new Error('live child cleanup failed') + const constructionError = new Error( + 'query construction failed with a live child', + ) + const liveChildCleanupFailure = fakeChild({ doneError: cleanupError }) + queryMock.mockImplementationOnce(({ options }) => { + options.spawnClaudeCodeProcess!(sdkSpawnOptions()) + throw constructionError + }) + await expect(startClaudeCodeRun(request(), { + ...unused.spec, + spawn: () => liveChildCleanupFailure.handle, + })).rejects.toMatchObject({ + errors: [constructionError, cleanupError], + }) }) }) diff --git a/packages/subagent/subagent-codex/README.i18n.yaml b/packages/subagent/subagent-codex/README.i18n.yaml index da14b8ff30..4bdea58bdf 100644 --- a/packages/subagent/subagent-codex/README.i18n.yaml +++ b/packages/subagent/subagent-codex/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-codex/README.md -README.md: 848d170585710b682fa4ce331010fce7080de673 -README.zh.md: 34e9105e6a78bc16f16997c7df89d4f6412eb50c +README.md: 1b9f777c26fa2e1ee050dfc73bdb648e66e93043 +README.zh.md: f70510dd680a78193ebb45e95b9e666de59db571 diff --git a/packages/subagent/subagent-codex/README.md b/packages/subagent/subagent-codex/README.md index 848d170585..1b9f777c26 100644 --- a/packages/subagent/subagent-codex/README.md +++ b/packages/subagent/subagent-codex/README.md @@ -2,17 +2,17 @@ English | [中文](README.zh.md) -This package registers the fixed `codex` subagent provider. Each accepted run starts the official `codex app-server --stdio` command in the delegating Session's workspace, creates one ephemeral Codex thread, submits one self-contained text task, and returns only the final answer through the shared [`dsh-subagent`](../subagent/README.md) result contract. +This package registers a Profile-named Codex subagent provider whose default name is `codex`. Each accepted run starts the official package-local Codex wrapper with `app-server --stdio` in the delegating Session's workspace, creates one ephemeral Codex thread, submits one self-contained text task, and returns either the selected final answer or a separate safe failure diagnostic through the shared [`dsh-subagent`](../subagent/README.md) result contract. ## Start and ownership -`start(request)` accepts only a non-empty sequence of text blocks and derives the child cwd from the parent Session. It then spawns the fixed command through [`dsh-subprocess`](../../subprocess/subprocess/README.md), performs `initialize` → `initialized` → `thread/start { cwd, ephemeral: true }`, and publishes the run only after Codex returns a valid ephemeral thread. A failure or cancellation before publication closes the wire, terminates the managed process tree, waits for it to exit, and rejects `start()`. +`start(request)` accepts only a non-empty sequence of text blocks and derives the child cwd from the parent Session. It then spawns the fixed command through [`dsh-subprocess`](../../subprocess/subprocess/README.md), performs `initialize` → `initialized`, maps the Profile-selected mode into official `thread/start` approval/reviewer/sandbox fields beside `{ cwd, ephemeral: true }`, and publishes the run only after Codex returns a valid ephemeral thread. A failure or cancellation before publication closes the wire, terminates the managed process tree, waits for it to exit, and rejects `start()`. The published `run.result` starts exactly one turn. It accepts only notifications for that run's thread and turn, then waits for the authoritative `turn/completed` terminal notification. The latest `agentMessage` with `phase: "final_answer"` wins; when Codex emits no explicit final phase, the latest message with `phase: null` is the compatibility fallback. Commentary never replaces either answer, and a successful turn with no nonblank answer settles as an error. -For command and file approvals, the unattended provider selects a non-approval decision offered by the request, preferring `cancel`; the stable 0.147.0 request shape without an offered-decision list falls back to `decline`. It answers permission requests with an empty turn-scoped permission set, answers user-input requests with no answers, and declines MCP elicitation. A request with no legal unattended response, or any unknown server request, fails the run. +For command and file approvals, the unattended provider selects a non-approval decision offered by the request, preferring `cancel`; the stable 0.147.0 request shape without an offered-decision list falls back to `decline`. It answers permission requests with an empty turn-scoped permission set, answers user-input requests with no answers, and declines MCP elicitation. A request with no legal unattended response, or any unknown server request, fails the run. The wire records only the effective mode, request category, decision, and fixed safe reason. It also recognizes declined command/file items and `sandboxError` terminals. Codex 0.147.0 writes some early `never` rejections and sandbox violations only to structured stderr, so the Provider pipes stderr, forwards it unchanged to the host, and matches two fixed signatures in a bounded per-run tail; raw stderr never enters the diagnostic. -Local cancellation wins the result race and maps to `aborted`. A failed turn whose `codexErrorInfo` is `contextWindowExceeded` maps to `max-tokens`; every other remote interrupted or failed turn maps to `error`, and the provider produces no `refusal`. `dispose()` is idempotent: it requests a best-effort `turn/interrupt` with both current ids when they are known, closes the JSON-RPC wire, ends stdin, invokes the shared process-tree termination escalation, and waits for whole-tree exit. Result failure and independent teardown failure remain separate. +Local cancellation wins the result race and maps to `aborted`. A failed turn whose `codexErrorInfo` is `contextWindowExceeded` maps to `max-tokens`; every other remote interrupted or failed turn maps to `error`, and the provider produces no `refusal`. A permission-related error may additionally carry the bounded, non-assistant `SubagentResult.diagnostic`; successful and locally cancelled runs omit it. `dispose()` is idempotent: it requests a best-effort `turn/interrupt` with both current ids when they are known, closes the JSON-RPC wire, ends stdin, invokes the shared process-tree termination escalation, waits for whole-tree exit, and detaches the stderr observer. Result failure and independent teardown failure remain separate. ## Capabilities and context @@ -22,40 +22,83 @@ The provider advertises no optional start-time capabilities and reports `inherit | Key | Default | Meaning | |---|---|---| +| `providerName` | `codex` | Non-empty registry name on `ctx.subagents`; each mounted instance needs a unique value. | | `env` | `{}` | Explicit child environment layered over the subprocess seam's credential-scrubbed parent environment. | +| `permissionMode` | `never` | Native non-interactive approval and sandbox mode fixed for every thread from this Provider instance. | | `disposeGraceMs` | `3000` | Positive finite grace in milliseconds, no greater than [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md), between the shared process-tree owner's termination tiers; disposal then waits for whole-tree exit. | -Production resolves `codex` from `PATH` and uses the host's native Codex configuration and authentication. The plugin does not install Codex, select a model, create `CODEX_HOME`, log in, or probe a version. Credential-shaped ambient variables are removed by the subprocess seam, so an API key intended for the child must be supplied explicitly in `env`; ordinary ambient values such as `PATH` and `HOME` remain available unless overridden. +| `permissionMode` value | `thread/start` fields | Native behavior | +|---|---|---| +| `never` | `approvalPolicy: never`; sandbox omitted | Never ask for approval; execution failures return to the model under the native sandbox. | +| `approve-for-me` | `approvalPolicy: on-request`, `approvalsReviewer: auto_review`, `sandbox: workspace-write` | Route permission requests through Codex automatic review without a human. | +| `dangerously-bypass-approvals-and-sandbox` | `approvalPolicy: never`, `sandbox: danger-full-access` | Skip approval and sandbox enforcement; this value must be selected explicitly. | -Production `dsh` does not install or mount this optional provider. A Profile that opts in must install `@deepseek-ai/dsh-subagent-codex` and mount it once on the host plane; loading the provider starts no Codex process until a tool call. Full Agent Presets carry a matching product tool row with `disabled: true`; copy a preset and remove that field to expose `subagent_codex` only to agents composed from the copy. Its `one-shot` policy keeps omitted or `false` `run_in_background` calls in the foreground, while explicit `true` returns a parent-owned Job id for `job_output` or `job_kill`. The base host and full presets already provide the generic Job registry and controls. +Production resolves the `codex` bin declared by its pinned `@openai/codex@0.147.0` dependency and launches that JavaScript wrapper with the current Node executable. The wrapper selects the matching native platform payload; the provider neither inspects nor falls back to a host `codex` on `PATH`. Native Codex configuration and authentication remain authoritative through the parent cwd, `HOME`, and `CODEX_HOME`, while the Provider overrides only the selected thread approval/reviewer/sandbox fields. All other project, model, provider, MCP, hook, skill, and account settings remain native. The plugin does not select a model, create `CODEX_HOME`, log in, or probe an account. Credential-shaped ambient variables are removed by the subprocess seam before the explicit `env` overlay is applied. -The standalone composition below shows the complete explicit capability. A Profile based on `@deepseek-ai/dsh-base` keeps its existing Job rows, adds the product provider row, and enables the preset tool row instead of mounting duplicate Job services. +This package is an optional Profile Bundle. Install it into the target Profile, then restart that Profile; installation brings the official wrapper and one compatible native platform payload into that Profile, while the declared `cordis.patch.yml` layer registers only the dormant `codex` Host provider and starts no Codex process. Removing the package withdraws that provider and its private runtime closure on the next Profile start. + +```sh +dsh plugin --profile add @deepseek-ai/dsh-subagent-codex +dsh plugin --profile remove @deepseek-ai/dsh-subagent-codex +dsh --profile +``` + +Installation controls Host availability, not model permission. The Bundle supplies the dormant default `codex` row; the Profile may replace that row's complete config or mount additional rows with distinct `providerName`, `permissionMode`, and `env` values. Loading an instance starts no Codex process until a bound tool calls it. Each `dsh-tool-subagent` row names one provider and needs its own `toolName`, so the model sees static tools rather than a dynamic provider selector. Full Agent Presets carry a matching default product tool row with `disabled: true`; copy a preset and remove that field to expose `subagent_codex` only to agents composed from the copy. Its `one-shot` policy keeps omitted or `false` `run_in_background` calls in the foreground, while explicit `true` returns a parent-owned Job id for `job_output` or `job_kill`. The base host and full presets already provide the generic Job registry and controls. + +The standalone composition below shows the complete explicit capability. A Profile based on `@deepseek-ai/dsh-base` keeps its existing Job rows, adds the product provider and tool rows, and does not mount duplicate Job services. ```yaml -- id: subagent-codex +- id: subagent-codex-safe name: '@deepseek-ai/dsh-subagent-codex' config: + providerName: codex-safe + permissionMode: never env: OPENAI_API_KEY: !!js process.env.OPENAI_API_KEY +- id: subagent-codex-bypass + name: '@deepseek-ai/dsh-subagent-codex' + config: + providerName: codex-bypass + permissionMode: dangerously-bypass-approvals-and-sandbox + env: + OPENAI_API_KEY: !!js process.env.OPENAI_API_KEY +``` + +```yaml - id: jobs name: '@deepseek-ai/dsh-jobs-local' - id: tool-jobs name: '@deepseek-ai/dsh-tool-jobs' -- id: tool-subagent-codex +- id: tool-subagent-codex-safe + name: '@deepseek-ai/dsh-tool-subagent' + disabled: true + config: + provider: codex-safe + toolName: subagent_codex_safe + backgroundMode: one-shot + maxDepth: provider-managed + +- id: tool-subagent-codex-bypass name: '@deepseek-ai/dsh-tool-subagent' config: - provider: codex - toolName: subagent_codex + provider: codex-bypass + toolName: subagent_codex_bypass backgroundMode: one-shot maxDepth: provider-managed ``` ## Product compatibility and evidence -The production wire intentionally implements only the app-server methods required by this one-shot contract. Development evidence is pinned to `@openai/codex@0.147.0` / `codex-cli 0.147.0`; the npm package is a test-only dependency, and deployments still supply `codex` on `PATH`. +The production wire intentionally implements only the app-server methods required by this one-shot contract. The runtime dependency and all six optional-dependency aliases are pinned to `@openai/codex@0.147.0` / `codex-cli 0.147.0`. A normal install selects one payload for the current OS and CPU. For the current darwin-arm64 payload, `npm pack --dry-run --json @openai/codex@0.147.0-darwin-arm64` reports 111,199,052 packed bytes and 274,777,843 unpacked bytes. That package contains native `codex`, `codex-code-mode-host`, `rg`, and `zsh` resources; other platforms may differ, and these values are disclosure rather than an installation threshold. The keyless real-product test drives the package wrapper against a loopback Responses fixture, observes the package-local argv, and proves wrapper and native descendants become quiescent. + +Installing with optional dependencies omitted, using an unsupported platform, or losing the selected payload makes the first delegation fail with the wrapper's native-payload startup error. The provider neither probes a host CLI nor retries with one. + +Real-product coverage additionally proves that thread-level `never` overrides an ambient `on-request`, automatic review starts through the official app-server, dangerous bypass writes only in suite-owned temporary storage, safe diagnostics exclude raw commands and paths, and every wrapper/native process exits. + +The same real-product tier proves that two named instances retain separate environments and native modes. ## Model Experience @@ -63,7 +106,7 @@ The production wire intentionally implements only the app-server methods require #### What the model sees -The Codex child receives the standalone text blocks as one turn in a fresh ephemeral thread. Its workspace is the parent Session cwd, and its model, system instructions, tools, sandbox, and authentication come from the native Codex installation and configuration. +The Codex child receives the standalone text blocks as one turn in a fresh ephemeral thread. Its workspace is the parent Session cwd; its model, system instructions, tools, and authentication come from native Codex configuration, the selected Provider instance's Profile configuration fixes the thread's environment, non-interactive approval policy, and sandbox mode, and the executable version comes from the Bundle's pinned platform payload. #### Token effect @@ -77,7 +120,7 @@ Independent of the parent request cache. Reuse depends only on Codex's own provi #### What the model sees -Through `dsh-tool-subagent`, a foreground call gives the parent the selected final Codex answer or the consumer's exact error for a non-completed result. A background call first returns a Job id; the generic job controls later deliver a completion notice, expose the final answer and status through `job_output`, and let `job_kill` request cancellation. Codex commentary, reasoning, tool activity, stderr, workspace diffs, usage, and product ids are not copied into the parent Session. +Through `dsh-tool-subagent`, a foreground call gives the parent the selected final Codex answer or an error containing the stop reason and optional safe diagnostic for a non-completed result. A background call first returns a Job id; the generic job controls later deliver a completion notice, expose the final answer or failed status detail through `job_output`, and let `job_kill` request cancellation. Codex commentary, reasoning, tool activity, raw stderr, workspace diffs, usage, product ids, commands, paths, and protocol payloads are not copied into the parent Session. #### Token effect @@ -90,9 +133,11 @@ Append-only: foreground adds one result after the reusable parent prefix, while ## Known Limitations and Deferred Work - **One fresh process, thread, and turn per run** — there is no continuation, resume, pooling, progress stream, or product-session persistence. -- **Host-managed product installation and account state** — a missing or incompatible `codex`, configuration error, or authentication failure is surfaced as a startup or run error; the plugin provides no installer, login flow, or runtime version gate. +- **Static instance selection** — Profile rows fix provider names and tool bindings; calls cannot choose a provider dynamically, and every exposed tool needs a unique `toolName`. +- **Authentication and account state remain native** — the Bundle supplies the CLI but does not create an account, log in, trust a project, or rewrite Codex settings; configuration and authentication failures surface as startup or run errors. +- **The native platform payload is required at delegation time** — installs that omit optional dependencies, unsupported platforms, and missing or damaged payloads fail at the first run; there is no host-CLI fallback. - **Compatibility is pinned by development evidence** — upgrading from the verified 0.147.0 protocol baseline requires regenerating upstream schema evidence and rerunning handshake, answer-selection, approval, cancellation, keyless real-product, and credentialed DeepSeek nonce tests. -- **No human approval path** — known unattended approval requests are denied and unknown server requests fail closed; deployments cannot configure an allow policy through this package. -- **Product payload is final text only** — reasoning, commentary, intermediate messages, tool traffic, usage, stderr, and workspace diffs remain product-local; generic Job ids, notices, and status come from the shared job runtime. +- **No human approval path** — known unattended approval requests are denied and unknown server requests fail closed; the three Profile modes never create a DSH interaction channel or per-call allow policy. +- **Assistant payload is final text only** — a failed run may additionally expose the separate safe diagnostic; reasoning, commentary, intermediate messages, tool traffic, usage, raw stderr, and workspace diffs remain outside the parent Session, while generic Job ids, notices, and status come from the shared job runtime. - **No optional shared capabilities** — output schemas, child personas, tool filtering, and harness depth enforcement are rejected by the shared service for this provider. - **No wall-clock timeout or side-effect rollback** — the caller cancels long work, and files or external systems changed before cancellation are not restored. diff --git a/packages/subagent/subagent-codex/README.zh.md b/packages/subagent/subagent-codex/README.zh.md index 34e9105e6a..f70510dd68 100644 --- a/packages/subagent/subagent-codex/README.zh.md +++ b/packages/subagent/subagent-codex/README.zh.md @@ -2,17 +2,17 @@ [English](README.md) | 中文 -本包注册固定的 `codex` subagent 提供方。每次接受运行请求后,它都会在发起委托的会话工作区中启动官方 `codex app-server --stdio` 命令,创建一个临时 Codex 线程,提交一个自包含的文本任务,并通过共享的 [`dsh-subagent`](../subagent/README.md) 结果约定仅返回最终答案。 +本包注册由 Profile 命名、默认名称为 `codex` 的 Codex subagent 提供方。每次接受运行请求后,它都会在发起委托的会话工作区中使用 `app-server --stdio` 启动官方包内 Codex wrapper,创建一个临时 Codex 线程,提交一个自包含的文本任务,并通过共享的 [`dsh-subagent`](../subagent/README.md) 结果约定返回选定的最终答案或独立的安全失败诊断。 ## 启动与所有权 -`start(request)` 只接受非空的文本块序列,并根据父会话确定子级 cwd。随后,它通过 [`dsh-subprocess`](../../subprocess/subprocess/README.md) spawn 固定命令,依次执行 `initialize` → `initialized` → `thread/start { cwd, ephemeral: true }`,且仅在 Codex 返回有效的临时线程后才发布此次运行。若在发布前发生失败或取消,它会关闭通信链路、终止受管进程树并等待其退出,然后拒绝 `start()` 调用。 +`start(request)` 只接受非空的文本块序列,并根据父会话确定子级 cwd。随后,它通过 [`dsh-subprocess`](../../subprocess/subprocess/README.md) spawn 固定命令,依次执行 `initialize` → `initialized`,把 Profile 选择的模式映射为官方 `thread/start` approval/reviewer/sandbox 字段并与 `{ cwd, ephemeral: true }` 一起发送,且仅在 Codex 返回有效的临时线程后才发布此次运行。若在发布前发生失败或取消,它会关闭通信链路、终止受管进程树并等待其退出,然后拒绝 `start()` 调用。 已发布的 `run.result` 恰好启动一个轮次。它只接受与此次运行的线程和轮次匹配的通知,随后等待权威的终止通知 `turn/completed`。以最后一条 `phase: "final_answer"` 的 `agentMessage` 为准;若 Codex 没有发出明确的最终阶段,则以最后一条 `phase: null` 的消息作为兼容性回退。过程说明绝不会取代上述任一答案;成功完成的轮次若没有非空白答案,结果也会判为错误。 -对于命令与文件审批,无人值守的提供方会从请求给出的决策选项中选择一项不予批准的决策,并优先选择 `cancel`;稳定的 0.147.0 请求形态没有决策选项列表,因此回退到 `decline`。它对权限请求返回作用域限于当前轮次的空权限集,不向用户输入请求提供任何答案,并拒绝 MCP elicitation。若请求在无人值守模式下没有合法响应,或是未知服务器请求,此次运行就会失败。 +对于命令与文件审批,无人值守的提供方会从请求给出的决策选项中选择一项不予批准的决策,并优先选择 `cancel`;稳定的 0.147.0 请求形态没有决策选项列表,因此回退到 `decline`。它对权限请求返回作用域限于当前轮次的空权限集,不向用户输入请求提供任何答案,并拒绝 MCP elicitation。若请求在无人值守模式下没有合法响应,或是未知服务器请求,此次运行就会失败。wire 只记录有效模式、请求类别、决定与固定的安全原因,也会识别被拒绝的命令/文件 item 和 `sandboxError` 终态。Codex 0.147.0 的部分早期 `never` 拒绝和 sandbox violation 只写入结构化 stderr,因此提供方会 pipe stderr、原样转发给 Host,并在每次运行的有界尾缓冲中匹配两个固定签名;原始 stderr 不会进入诊断。 -本地取消会在结果竞态中胜出并映射为 `aborted`。失败轮次的 `codexErrorInfo` 若为 `contextWindowExceeded`,则映射为 `max-tokens`;其他任何远端中断或失败轮次都映射为 `error`,且该提供方不会产生 `refusal`。`dispose()`(资源释放)具有幂等性:如果当前的两个标识符均已知,它会尽力请求 `turn/interrupt`,关闭 JSON-RPC 通信链路,结束标准输入,调用共享的进程树逐级终止机制,并等待整棵进程树退出。结果失败与独立的清理失败仍彼此分离。 +本地取消会在结果竞态中胜出并映射为 `aborted`。失败轮次的 `codexErrorInfo` 若为 `contextWindowExceeded`,则映射为 `max-tokens`;其他任何远端中断或失败轮次都映射为 `error`,且该提供方不会产生 `refusal`。权限相关错误可以额外携带有界、非 assistant 的 `SubagentResult.diagnostic`;成功和本地取消不会附带它。`dispose()`(资源释放)具有幂等性:如果当前的两个标识符均已知,它会尽力请求 `turn/interrupt`,关闭 JSON-RPC 通信链路,结束标准输入,调用共享的进程树逐级终止机制,等待整棵进程树退出,并移除 stderr observer。结果失败与独立的清理失败仍彼此分离。 ## 能力与上下文 @@ -22,40 +22,83 @@ | 配置键 | 默认值 | 含义 | |---|---|---| +| `providerName` | `codex` | `ctx.subagents` 中的非空注册名称;每个已挂载实例都需要唯一值。 | | `env` | `{}` | 显式指定的子进程环境,叠加在由子进程 seam 清除凭证后的父环境之上。 | +| `permissionMode` | `never` | 为该提供方实例的每个线程固定原生非交互审批与沙箱模式。 | | `disposeGraceMs` | `3000` | 共享进程树责任方各终止层级之间的宽限期,单位为毫秒且须为正有限值,并不得大于仓库共享的 [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md);随后资源释放会等待整棵进程树退出。 | -生产环境会从 `PATH` 中解析 `codex`,并使用宿主机原生的 Codex 配置与身份验证。本插件不安装 Codex、不选择模型、不创建 `CODEX_HOME`、不执行登录,也不探测版本。子进程 seam 会移除具有凭证特征的环境变量,因此供子进程使用的 API 密钥必须在 `env` 中显式提供;除非被覆盖,`PATH` 和 `HOME` 等普通环境变量值仍然可用。 +| `permissionMode` 值 | `thread/start` 字段 | 原生行为 | +|---|---|---| +| `never` | `approvalPolicy: never`;省略 sandbox | 永不请求审批;执行失败会在原生 sandbox 下返回模型。 | +| `approve-for-me` | `approvalPolicy: on-request`、`approvalsReviewer: auto_review`、`sandbox: workspace-write` | 由 Codex 自动评审权限请求,不等待人工。 | +| `dangerously-bypass-approvals-and-sandbox` | `approvalPolicy: never`、`sandbox: danger-full-access` | 跳过审批与 sandbox;必须显式选择该值。 | -生产 `dsh` 不会安装或挂载这个可选提供方。选择启用它的 Profile 必须安装 `@deepseek-ai/dsh-subagent-codex`,并在 host plane(宿主平面)挂载一次;加载提供方本身不会在工具调用前启动 Codex 进程。完整 Agent Preset 携带对应的产品工具行并设置 `disabled: true`;复制一个 preset 后删除该字段,即可只向由该副本组装的 agent 暴露 `subagent_codex`。其 `one-shot` 策略会让省略 `run_in_background` 或传入 `false` 的调用继续在前台等待,而显式传入 `true` 会返回由父 agent 拥有的 Job ID,供 `job_output` 或 `job_kill` 使用。base host(基础宿主)与完整 preset 已提供通用作业注册表和控制工具。 +生产环境会解析锁定的 `@openai/codex@0.147.0` 依赖所声明的 `codex` bin,并使用当前 Node 可执行文件启动该 JavaScript wrapper。Wrapper 会选择匹配的原生平台载荷;提供方既不检查也不回退 `PATH` 中的宿主 `codex`。父会话 cwd、`HOME` 与 `CODEX_HOME` 继续让原生 Codex 配置和身份验证保持权威,而提供方只覆盖选定线程的 approval/reviewer/sandbox 字段。其他项目、模型、provider、MCP、hook、skill 与账户设置仍由原生机制负责。本插件不选择模型、不创建 `CODEX_HOME`、不执行登录,也不探测账户。子进程 seam 会先移除具有凭证特征的环境变量,再应用显式 `env` 覆盖。 -下列独立组装展示完整的显式能力。基于 `@deepseek-ai/dsh-base` 的 Profile 保留已有 Job 行,只新增产品提供方行并启用 preset 工具行,禁止重复挂载 Job 服务。 +本包是可选的 Profile Bundle。将它安装进目标 Profile 后重启该 Profile;安装会把官方 wrapper 与一个兼容的原生平台载荷带入该 Profile,而包所声明的 `cordis.patch.yml` 层只注册休眠的 `codex` Host provider,不会启动 Codex 进程。移除该包后,下一次 Profile 启动会撤回这一 provider 及其私有运行时闭包。 + +```sh +dsh plugin --profile add @deepseek-ai/dsh-subagent-codex +dsh plugin --profile remove @deepseek-ai/dsh-subagent-codex +dsh --profile +``` + +安装决定 Host 可用性,而不是模型权限。Bundle 会提供休眠的默认 `codex` 配置项;Profile 可以替换该配置项的完整 config,也可以挂载更多具有不同 `providerName`、`permissionMode` 与 `env` 的配置项。加载实例本身不会在绑定工具调用前启动 Codex 进程。每个 `dsh-tool-subagent` 配置项指定一个提供方,并需要独立的 `toolName`,因此模型看到的是静态工具,而不是动态提供方选择器。完整 Agent Preset 携带对应的默认产品工具行并设置 `disabled: true`;复制一个 preset 后删除该字段,即可只向由该副本组装的 agent 暴露 `subagent_codex`。其 `one-shot` 策略会让省略 `run_in_background` 或传入 `false` 的调用继续在前台等待,而显式传入 `true` 会返回由父 agent 拥有的 Job ID,供 `job_output` 或 `job_kill` 使用。base host(基础宿主)与完整 preset 已提供通用作业注册表和控制工具。 + +下列独立组装展示完整的显式能力。基于 `@deepseek-ai/dsh-base` 的 Profile 保留已有 Job 配置项,新增产品提供方与工具配置项,而且不重复挂载 Job 服务。 ```yaml -- id: subagent-codex +- id: subagent-codex-safe name: '@deepseek-ai/dsh-subagent-codex' config: + providerName: codex-safe + permissionMode: never env: OPENAI_API_KEY: !!js process.env.OPENAI_API_KEY +- id: subagent-codex-bypass + name: '@deepseek-ai/dsh-subagent-codex' + config: + providerName: codex-bypass + permissionMode: dangerously-bypass-approvals-and-sandbox + env: + OPENAI_API_KEY: !!js process.env.OPENAI_API_KEY +``` + +```yaml - id: jobs name: '@deepseek-ai/dsh-jobs-local' - id: tool-jobs name: '@deepseek-ai/dsh-tool-jobs' -- id: tool-subagent-codex +- id: tool-subagent-codex-safe + name: '@deepseek-ai/dsh-tool-subagent' + disabled: true + config: + provider: codex-safe + toolName: subagent_codex_safe + backgroundMode: one-shot + maxDepth: provider-managed + +- id: tool-subagent-codex-bypass name: '@deepseek-ai/dsh-tool-subagent' config: - provider: codex - toolName: subagent_codex + provider: codex-bypass + toolName: subagent_codex_bypass backgroundMode: one-shot maxDepth: provider-managed ``` ## 产品兼容性与证据 -生产环境的协议层有意只实现这一单次执行约定所需的 app-server 方法。开发证据锁定在 `@openai/codex@0.147.0` / `codex-cli 0.147.0`;该 NPM 包仅作为测试依赖,部署环境仍需通过 `PATH` 提供 `codex`。 +生产环境的协议层有意只实现这一单次执行约定所需的 app-server 方法。运行时依赖与六个 optional-dependency alias 均锁定到 `@openai/codex@0.147.0` / `codex-cli 0.147.0`。普通安装会按当前操作系统与 CPU 选择一个载荷。对于当前 darwin-arm64 载荷,`npm pack --dry-run --json @openai/codex@0.147.0-darwin-arm64` 报告压缩包为 111,199,052 字节、解包后为 274,777,843 字节。该包包含原生 `codex`、`codex-code-mode-host`、`rg` 与 `zsh` 资源;其他平台可能不同,这些数值只用于披露而不是安装阈值。无密钥真实产品测试会驱动包内 wrapper 连接回环 Responses fixture,观测包内 argv,并证明 wrapper 与原生后代进程完全停稳。 + +如果安装时省略 optional dependencies、当前平台不受支持,或所选载荷缺失,第一次委派会以 wrapper 的原生载荷启动错误失败。提供方既不会探测宿主 CLI,也不会用它重试。 + +真实产品覆盖还会证明线程级 `never` 覆盖环境中的 `on-request`,自动评审通过官方 app-server 启动,危险绕过只在测试拥有的临时存储中写入,安全诊断不包含原始命令与路径,而且所有 wrapper/native 进程都会退出。 + +同一真实产品层级还会证明两个命名实例保留彼此独立的环境与原生模式。 ## 模型体验 @@ -63,7 +106,7 @@ #### 模型看到的内容 -Codex 子级会在一个全新的临时线程中,以单个轮次接收这些独立文本块。它的工作区是父会话 cwd;其模型、系统指令、工具、沙箱和身份验证来自原生 Codex 安装与配置。 +Codex 子级会在一个全新的临时线程中,以单个轮次接收这些独立文本块。它的工作区是父会话 cwd;其模型、系统指令、工具和身份验证来自原生 Codex 配置,所选提供方实例的 Profile 配置会固定该线程的环境、非交互审批策略与沙箱模式,而可执行版本来自 Bundle 锁定的平台载荷。 #### 对 token 的影响 @@ -77,7 +120,7 @@ Codex 子级会在一个全新的临时线程中,以单个轮次接收这些 #### 模型看到的内容 -通过 `dsh-tool-subagent`,前台调用会让父级模型看到选定的 Codex 最终答案,或者在结果未完成时看到消费方给出的原样错误。后台调用会先返回 Job id;随后通用作业控制面会送达完成通知,通过 `job_output` 公开最终答案与状态,并允许 `job_kill` 请求取消。Codex 的过程说明、推理(reasoning)、工具活动、stderr、工作区差异、用量信息和产品标识符均不会复制到父会话。 +通过 `dsh-tool-subagent`,前台调用会让父级模型看到选定的 Codex 最终答案;若结果未完成,错误中会包含终止原因和可选的安全诊断。后台调用会先返回 Job id;随后通用作业控制面会送达完成通知,通过 `job_output` 公开最终答案或失败状态 detail,并允许 `job_kill` 请求取消。Codex 的过程说明、推理(reasoning)、工具活动、原始 stderr、工作区差异、用量信息、产品标识符、命令、路径和协议载荷均不会复制到父会话。 #### 对 token 的影响 @@ -90,9 +133,11 @@ Codex 子级会在一个全新的临时线程中,以单个轮次接收这些 ## 已知限制与后续工作 - **每次运行均新建一个进程、一个线程和一个轮次**:不支持续接、恢复、池化、进度流或产品会话持久化。 -- **产品安装和账户状态由宿主管理**:`codex` 缺失或不兼容、配置错误或身份验证失败,都会呈现为启动错误或运行错误;本插件不提供安装程序、登录流程或运行时版本门禁。 +- **静态选择实例**:Profile 配置项固定提供方名称与工具绑定;调用无法动态选择提供方,而且每个公开工具都需要唯一的 `toolName`。 +- **身份验证与账户状态仍由原生机制管理**:Bundle 会提供 CLI,但不会创建账户、登录、信任项目或改写 Codex 设置;配置与身份验证失败会呈现为启动错误或运行错误。 +- **委派时必须存在原生平台载荷**:省略 optional dependencies 的安装、不受支持的平台以及缺失或损坏的载荷都会在第一次运行时失败;不会回退到宿主 CLI。 - **兼容性由开发证据锁定**:若要从已验证的 0.147.0 协议基线升级,必须重新生成上游 schema 证据,并重新运行握手、答案选择、审批、取消、无密钥真实产品以及带密钥的 DeepSeek 随机数测试。 -- **没有人工审批路径**:已知的无人值守审批请求会被拒绝,未知服务器请求会以默认拒绝方式使运行失败;部署方无法通过本包配置允许策略。 -- **产品载荷仅包含最终文本**:推理、过程说明、中间消息、工具通信、用量信息、stderr 和工作区差异仍只保留在产品内部;通用 Job id、通知与状态来自共享作业运行时。 +- **没有人工审批路径**:已知的无人值守审批请求会被拒绝,未知服务器请求会以默认拒绝方式使运行失败;三种 Profile 模式都不会创建 DSH 交互通道或逐次调用 allow 策略。 +- **assistant 载荷仅包含最终文本**:失败运行可以额外公开独立的安全诊断;推理、过程说明、中间消息、工具通信、用量信息、原始 stderr 和工作区差异不会进入父会话,通用 Job id、通知与状态来自共享作业运行时。 - **没有可选的共享能力**:对于本提供方,共享服务会拒绝输出 schema、子任务角色设定、工具筛选和 harness 深度强制约束。 - **没有按实际经过时间触发的超时或副作用回滚**:长时间运行的工作由调用方取消,且取消前已更改的文件或外部系统不会恢复原状。 diff --git a/packages/subagent/subagent-codex/cordis.patch.yml b/packages/subagent/subagent-codex/cordis.patch.yml new file mode 100644 index 0000000000..fb64fdcb9d --- /dev/null +++ b/packages/subagent/subagent-codex/cordis.patch.yml @@ -0,0 +1,5 @@ +# Optional Profile Bundle: register the Codex provider on the Host plane only. +# Agent Presets grant the model-facing tool independently. +- insert: + - id: subagent-codex + name: '@deepseek-ai/dsh-subagent-codex' diff --git a/packages/subagent/subagent-codex/package.json b/packages/subagent/subagent-codex/package.json index 29493a5612..dbe30e18e1 100644 --- a/packages/subagent/subagent-codex/package.json +++ b/packages/subagent/subagent-codex/package.json @@ -28,13 +28,18 @@ "files": [ "lib/index.js", "lib/invariant.js", + "cordis.patch.yml", "lib/types/**/*.d.ts" ], "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, "peerDependencies": { "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", - "@deepseek-ai/dsh-sdk-protocol": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-subagent": "workspace:^", "@deepseek-ai/dsh-subprocess": "workspace:^", @@ -42,7 +47,9 @@ "@deepseek-ai/cordis": "workspace:^" }, "dependencies": { - "@deepseek-ai/schemastery": "workspace:^" + "@deepseek-ai/dsh-sdk-protocol": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^", + "@openai/codex": "0.147.0" }, "devDependencies": { "@deepseek-ai/cordis-plugin-loader": "workspace:^", @@ -50,13 +57,11 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-loader-smoke": "workspace:^", - "@deepseek-ai/dsh-sdk-protocol": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-subagent": "workspace:^", "@deepseek-ai/dsh-subprocess": "workspace:^", "@deepseek-ai/dsh-subprocess-local": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", - "@openai/codex": "0.147.0", "@deepseek-ai/cordis": "workspace:^" } } diff --git a/packages/subagent/subagent-codex/src/index.ts b/packages/subagent/subagent-codex/src/index.ts index 3b1bbec799..d94197edf7 100644 --- a/packages/subagent/subagent-codex/src/index.ts +++ b/packages/subagent/subagent-codex/src/index.ts @@ -1,7 +1,7 @@ /** - * Fixed Codex one-shot subagent provider. Every accepted run starts a fresh - * official `codex app-server --stdio` process in the delegating Session's - * workspace and publishes only after an ephemeral thread exists. + * Profile-named Codex one-shot subagent provider. Every accepted run starts a + * fresh official package-local Codex wrapper with `app-server --stdio` in the + * delegating Session's workspace and publishes only after an ephemeral thread exists. * * @module @deepseek-ai/dsh-subagent-codex */ @@ -18,38 +18,50 @@ import { type SubagentProvider, } from '@deepseek-ai/dsh-subagent' import { + CODEX_PERMISSION_MODES, + DEFAULT_CODEX_PERMISSION_MODE, DEFAULT_DISPOSE_GRACE_MS, startCodexRun, + type CodexPermissionMode, type CodexRunSpec, } from './run.ts' export const name = 'subagent-codex' export const inject = ['subagents', 'subprocess'] -/** Deployment-owned environment and process-release bound. */ +const DEFAULT_PROVIDER_NAME = 'codex' + +/** Deployment-owned permission, environment, and process-release settings. */ export interface Config { + /** Provider name on `ctx.subagents` (default `codex`). */ + providerName?: string /** * Explicit environment entries layered over the subprocess seam's * credential-scrubbed parent environment. */ env?: Record + /** Native non-interactive permission mode fixed for this Provider instance. */ + permissionMode?: CodexPermissionMode /** Grace in milliseconds for app-server process-tree termination. */ disposeGraceMs?: number } export const Config: z = z.object({ + providerName: z.string().min(1).default(DEFAULT_PROVIDER_NAME), env: z.dict(z.string()).default({}), + permissionMode: z.union([...CODEX_PERMISSION_MODES]) + .default(DEFAULT_CODEX_PERMISSION_MODE), disposeGraceMs: z.number().default(DEFAULT_DISPOSE_GRACE_MS), }) type ResolvedConfig = Required class CodexProvider implements SubagentProvider { - readonly name = 'codex' readonly capabilities: SubagentCapabilities = NO_START_CAPABILITIES readonly inheritsParentContext = false constructor( + readonly name: string, private readonly ctx: Context, private readonly config: ResolvedConfig, ) {} @@ -67,12 +79,13 @@ class CodexProvider implements SubagentProvider { undefined, parentCwd, ), + permissionMode: this.config.permissionMode, env: this.config.env, disposeGraceMs: this.config.disposeGraceMs, spawn: spawnSpec => this.ctx.subprocess.spawn(spawnSpec), onError: (error, stopReason) => { this.ctx.logger.warn( - `subagent-codex: child run failed (${stopReason}): ${error.message}`, + `subagent-codex "${this.name}": child run failed (${stopReason}): ${error.message}`, ) }, } @@ -81,12 +94,17 @@ class CodexProvider implements SubagentProvider { } /** - * Register the fixed `codex` provider. + * Register one Profile-named Codex provider. * @param ctx - context carrying shared subagent and subprocess services. - * @param config - explicit child environment and disposal grace. + * @param config - registry name, permission mode, child environment, and disposal grace. */ export function apply(ctx: Context, config: Config): void { - const resolved = config as ResolvedConfig + const resolved: ResolvedConfig = { + providerName: config.providerName ?? DEFAULT_PROVIDER_NAME, + env: config.env as Record, + permissionMode: config.permissionMode ?? DEFAULT_CODEX_PERMISSION_MODE, + disposeGraceMs: config.disposeGraceMs as number, + } assertPositiveFinite( 'subagent-codex', 'disposeGraceMs', @@ -97,5 +115,9 @@ export function apply(ctx: Context, config: Config): void { `subagent-codex: disposeGraceMs must be no greater than ${MAX_TIMER_DELAY_MS}`, ) } - ctx.subagents.registerProvider(new CodexProvider(ctx, resolved)) + ctx.subagents.registerProvider(new CodexProvider( + resolved.providerName, + ctx, + resolved, + )) } diff --git a/packages/subagent/subagent-codex/src/run.ts b/packages/subagent/subagent-codex/src/run.ts index ebce244f3b..3d9693b4e1 100644 --- a/packages/subagent/subagent-codex/src/run.ts +++ b/packages/subagent/subagent-codex/src/run.ts @@ -8,6 +8,9 @@ */ import { randomUUID } from 'node:crypto' +import { readFileSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { dirname, resolve } from 'node:path' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import { @@ -23,28 +26,73 @@ import { CodexAppServerWire } from './wire.ts' /** Default POSIX grace between subprocess termination tiers. */ export const DEFAULT_DISPOSE_GRACE_MS = 3_000 +/** Bounded stderr tail retained only to recognize the wrapper's payload error. */ +const CODEX_STDERR_TAIL_BYTES = 16 * 1024 + +interface CodexPackageManifest { + readonly bin: { + readonly codex: string + } +} + +const codexPackageJsonPath = createRequire(import.meta.url).resolve('@openai/codex/package.json') +const codexPackageManifest = JSON.parse( + readFileSync(codexPackageJsonPath, 'utf8'), +) as CodexPackageManifest + +/** Absolute package-local JavaScript wrapper selected by the package manifest. */ +const CODEX_PACKAGE_BIN = resolve( + dirname(codexPackageJsonPath), + codexPackageManifest.bin.codex, +) + +function missingPayloadDiagnostic(stderr: string): string | undefined { + const platformPackage = /Missing optional dependency (@openai\/codex-[a-z0-9-]+)/ + .exec(stderr)?.[1] + return platformPackage === undefined + ? undefined + : `Missing optional dependency ${platformPackage}` +} + +function withMissingPayloadDiagnostic( + error: Error, + stderr: string, +): Error { + const diagnostic = missingPayloadDiagnostic(stderr) + if (diagnostic === undefined || error.message.includes(diagnostic)) return error + return new Error(`${error.message}: ${diagnostic}`, { cause: error }) +} + +/** Profile-selectable non-interactive Codex permission mode. */ +export type CodexPermissionMode = + | 'never' + | 'approve-for-me' + | 'dangerously-bypass-approvals-and-sandbox' + +/** Native non-interactive Codex modes mapped to official `thread/start` fields. */ +export const CODEX_PERMISSION_MODES = [ + 'never', + 'approve-for-me', + 'dangerously-bypass-approvals-and-sandbox', +] as const satisfies readonly CodexPermissionMode[] + +/** Safe default for unattended Codex runs. */ +export const DEFAULT_CODEX_PERMISSION_MODE: CodexPermissionMode = 'never' /** - * Resolve the fixed app-server command for a platform. - * - * Windows npm and pnpm installs expose `codex.cmd`, which requires `cmd.exe`; - * the argv is constant so no task or configuration text enters the - * shell boundary. - * @param platform - host platform used to select the executable boundary. - * @returns argv for the fixed Codex app-server command. + * Fixed package-local app-server command, independent of the host `PATH`. + * @returns Node, the official wrapper, and the fixed app-server arguments. */ -export function codexAppServerArgv( - platform: NodeJS.Platform = process.platform, -): string[] { - return platform === 'win32' - ? ['cmd.exe', '/d', '/s', '/c', 'codex', 'app-server', '--stdio'] - : ['codex', 'app-server', '--stdio'] +export function codexAppServerArgv(): string[] { + return [process.execPath, CODEX_PACKAGE_BIN, 'app-server', '--stdio'] } /** Fully resolved inputs for one Codex app-server run. */ export interface CodexRunSpec { /** Parent Session workspace, also supplied to `thread/start`. */ readonly cwd: string + /** Profile-selected native non-interactive permission mode. */ + readonly permissionMode: CodexPermissionMode /** Explicit deployment/test environment layered after the shared scrub. */ readonly env: Record /** Subprocess termination grace passed to the shared process-tree owner. */ @@ -125,7 +173,7 @@ export async function startCodexRun( const child = spec.spawn({ argv: codexAppServerArgv(), cwd: spec.cwd, - stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'inherit' }, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' }, graceMs: spec.disposeGraceMs, env: spec.env, }) @@ -133,8 +181,41 @@ export async function startCodexRun( const wire = new CodexAppServerWire( child.stdout as NonNullable, child.stdin as NonNullable, + spec.permissionMode, ) - const disposeProcess = (): Promise => disposeCodexChild(wire, child) + let stderrTail = Buffer.alloc(0) + const onStderr = (chunk: Buffer | string): void => { + const bytes = typeof chunk === 'string' ? Buffer.from(chunk) : chunk + const combined = Buffer.concat([stderrTail, bytes]) + stderrTail = combined.length > CODEX_STDERR_TAIL_BYTES + ? Buffer.from(combined.subarray(combined.length - CODEX_STDERR_TAIL_BYTES)) + : combined + wire.observeStderr(bytes.toString()) + try { + // Synchronous fd forwarding preserves byte order without owning a + // backpressure queue. A slow host sink can block this event-loop turn. + writeFileSync(process.stderr.fd, bytes) + } catch { + // Host stderr is an observation sink, not a child-run failure authority. + } + } + const onStderrError = (): void => { + // Stderr observation is auxiliary. JSON-RPC and child.done remain the + // only terminal authorities if the diagnostic stream itself fails. + } + child.stderr?.on('data', onStderr) + child.stderr?.on('error', onStderrError) + const disposeProcess = async (): Promise => { + try { + await disposeCodexChild(wire, child) + // Let stderr already queued by the process close reach both bounded + // diagnostic consumers before their listeners are detached. + await new Promise((resolve) => { setImmediate(resolve) }) + } finally { + child.stderr?.off('data', onStderr) + child.stderr?.off('error', onStderrError) + } + } const processFailure: Promise = child.done.then( outcome => Promise.reject(new Error( @@ -162,27 +243,38 @@ export async function startCodexRun( await Promise.race([wire.startThread(spec.cwd, request.signal), processFailure]) } catch (error: unknown) { request.signal.removeEventListener('abort', onAbort) + const startupCause = thrown(error) try { await disposeProcess() } catch (disposeError: unknown) { throw new AggregateError( - [thrown(error), thrown(disposeError)], + [withMissingPayloadDiagnostic(startupCause, stderrTail.toString()), thrown(disposeError)], 'subagent-codex: startup failed and app-server cleanup also failed', ) } if (runAbort.signal.aborted) { throw new Error('subagent-codex: request was aborted before run publication') } - throw thrown(error) + throw withMissingPayloadDiagnostic(startupCause, stderrTail.toString()) } const collectOutput = (): ContentBlock[] => wire.collectOutput() const result: Promise = settleRunResult({ - attempt: () => Promise.race([ - wire.runTurn(texts, runAbort.signal), - processFailure, - ]), + attempt: async () => { + try { + return await Promise.race([ + wire.runTurn(texts, runAbort.signal), + processFailure, + ]) + } catch (error: unknown) { + // Give stderr data already queued in Node one turn to reach the wire + // before settlement snapshots the diagnostic; later OS data is best-effort. + await new Promise((resolve) => { setImmediate(resolve) }) + throw withMissingPayloadDiagnostic(thrown(error), stderrTail.toString()) + } + }, collectOutput, + collectDiagnostic: () => wire.collectDiagnostic(), cancelled: () => runAbort.signal.aborted, onError: spec.onError, signal: request.signal, diff --git a/packages/subagent/subagent-codex/src/wire.ts b/packages/subagent/subagent-codex/src/wire.ts index bc00ff0acf..cd94695863 100644 --- a/packages/subagent/subagent-codex/src/wire.ts +++ b/packages/subagent/subagent-codex/src/wire.ts @@ -11,9 +11,57 @@ import type { Readable, Writable } from 'node:stream' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { SubagentResult } from '@deepseek-ai/dsh-subagent' import { JsonRpcLineTransport } from '@deepseek-ai/dsh-sdk-protocol' +import type { CodexPermissionMode } from './run.ts' type JsonObject = Record +const THREAD_PERMISSION_PARAMS: Readonly> = { + never: { approvalPolicy: 'never' }, + 'approve-for-me': { + approvalPolicy: 'on-request', + approvalsReviewer: 'auto_review', + sandbox: 'workspace-write', + }, + 'dangerously-bypass-approvals-and-sandbox': { + approvalPolicy: 'never', + sandbox: 'danger-full-access', + }, +} + +const STDERR_PERMISSION_SIGNATURES = [ + { + text: 'approval policy is Never; reject command', + request: 'command execution', + decision: 'denied', + reason: 'Codex rejected an escalation because the selected policy never asks for approval', + }, + { + text: 'recorded sandbox violation:', + request: 'sandbox execution', + decision: 'failed', + reason: 'Codex reported a sandbox violation', + }, +] as const + +const STDERR_SIGNATURE_TAIL_CHARS = Math.max( + ...STDERR_PERMISSION_SIGNATURES.map(signature => signature.text.length), +) - 1 + +function stderrSignatureTail(value: string): string { + for ( + let length = Math.min(STDERR_SIGNATURE_TAIL_CHARS, value.length) + ; length > 0 + ; length -= 1 + ) { + const tail = value.slice(-length) + if (STDERR_PERMISSION_SIGNATURES.some(signature => + tail.length < signature.text.length && signature.text.startsWith(tail))) { + return tail + } + } + return '' +} + function object(value: unknown, label: string): JsonObject { if (value === null || typeof value !== 'object' || Array.isArray(value)) { throw new Error(`subagent-codex: app-server returned invalid ${label}`) @@ -47,6 +95,24 @@ function isContextWindowExceeded(turn: JsonObject): boolean { && (error as JsonObject).codexErrorInfo === 'contextWindowExceeded' } +function isSandboxFailure(turn: JsonObject): boolean { + if (turn.status !== 'failed') return false + const error = turn.error + return error !== null + && typeof error === 'object' + && !Array.isArray(error) + && (error as JsonObject).codexErrorInfo === 'sandboxError' +} + +function unattendedDiagnostic( + mode: CodexPermissionMode, + request: 'command approval' | 'file approval' | 'permission grant' | 'user input' | 'MCP elicitation' | 'command execution' | 'file change' | 'sandbox execution', + decision: 'cancelled' | 'declined' | 'denied' | 'empty response' | 'failed', + reason: string, +): string { + return `Codex unattended decision (mode: ${mode}; request: ${request}; decision: ${decision}): ${reason}` +} + function thrown(value: unknown): Error { /* v8 ignore next -- typed protocol and stream failures reject with Error. */ return value instanceof Error ? value : new Error(String(value)) @@ -86,18 +152,33 @@ export class CodexAppServerWire { private threadId: string | undefined private turnId: string | undefined private pendingTurnId: string | undefined - private turnCompleted: PromiseWithResolvers | undefined + private turnCompleted: PromiseWithResolvers<{ + readonly params: JsonObject + readonly order: number + }> | undefined private readonly earlyTurnNotifications: Array<{ readonly method: string readonly params: JsonObject + readonly order: number }> = [] private lastFinalAnswer: string | undefined private lastUnphasedAnswer: string | undefined + private diagnostic: string | undefined + private diagnosticOrder = 0 + private observationOrder = 0 + private pendingDiagnostic: { + readonly order: number + readonly request: Parameters[1] + readonly decision: Parameters[2] + readonly reason: string + } | undefined + private stderrTail = '' private closed = false constructor( private readonly input: Readable, output: Writable, + private readonly permissionMode: CodexPermissionMode, ) { this.transport = new JsonRpcLineTransport(input, output) // Fatal protocol state can arrive after the current guarded operation has @@ -154,6 +235,7 @@ export class CodexAppServerWire { const response = object(await this.guarded(this.transport.request('thread/start', { cwd, ephemeral: true, + ...THREAD_PERMISSION_PARAMS[this.permissionMode], }, signal), signal), 'thread/start response') const thread = object(response.thread, 'thread/start thread') const id = string(thread.id, 'thread/start thread id') @@ -174,7 +256,10 @@ export class CodexAppServerWire { texts: readonly string[], signal: AbortSignal, ): Promise { - const completion = Promise.withResolvers() + const completion = Promise.withResolvers<{ + readonly params: JsonObject + readonly order: number + }>() this.turnCompleted = completion const threadId = this.threadId as string const response = object(await this.guarded(this.transport.request('turn/start', { @@ -185,14 +270,25 @@ export class CodexAppServerWire { this.commitTurnId(string(turn.id, 'turn/start turn id')) const completed = await this.guarded(completion.promise, signal) - const terminal = object(completed.turn, 'turn/completed turn') + const terminal = object(completed.params.turn, 'turn/completed turn') const status = terminal.status if (isContextWindowExceeded(terminal)) { return { output: this.collectOutput(), stopReason: 'max-tokens' } } if (status !== 'completed') { + const sandboxFailure = isSandboxFailure(terminal) + if (sandboxFailure) { + this.recordDiagnostic( + 'sandbox execution', + 'failed', + 'Codex reported a sandbox failure', + completed.order, + ) + } const detail = status === 'failed' - ? `: ${JSON.stringify(terminal.error)}` + ? sandboxFailure + ? ': sandboxError' + : ': error' : '' throw new Error(`subagent-codex: Codex turn ended with status ${String(status)}${detail}`) } @@ -226,6 +322,36 @@ export class CodexAppServerWire { : [] } + /** + * The latest safe unattended permission fact observed for this run. + * @returns provider-authored diagnostic text, when one was observed. + */ + collectDiagnostic(): string | undefined { + return this.diagnostic + } + + /** + * Observe product stderr while retaining only enough tail to recognize fixed + * permission signatures. The raw text is never copied into the diagnostic. + * @param chunk - one decoded stderr chunk already forwarded to the host. + */ + observeStderr(chunk: string): void { + const observed = `${this.stderrTail}${chunk}` + let latestIndex = -1 + let latest: (typeof STDERR_PERMISSION_SIGNATURES)[number] | undefined + for (const signature of STDERR_PERMISSION_SIGNATURES) { + const index = observed.lastIndexOf(signature.text) + if (index > latestIndex) { + latestIndex = index + latest = signature + } + } + if (latest !== undefined) { + this.recordDiagnostic(latest.request, latest.decision, latest.reason) + } + this.stderrTail = stderrSignatureTail(observed) + } + /** Detach JSON-RPC listeners and reject outstanding requests. Idempotent. */ close(): void { if (this.closed) return @@ -270,42 +396,162 @@ export class CodexAppServerWire { throw new Error('subagent-codex: turn/start response did not match the active turn') } this.turnId = id + const pendingDiagnostic = this.pendingDiagnostic + this.pendingDiagnostic = undefined + if (pendingDiagnostic !== undefined) { + this.recordDiagnostic( + pendingDiagnostic.request, + pendingDiagnostic.decision, + pendingDiagnostic.reason, + pendingDiagnostic.order, + ) + } const notifications = this.earlyTurnNotifications.splice(0) for (const notification of notifications) { - this.handleNotification(notification.method, notification.params) + this.handleNotification( + notification.method, + notification.params, + notification.order, + ) } } - private validateRunIds(params: JsonObject, nullableTurn = false): void { + /** + * Validate the request's thread and turn association. + * @returns `true` when the matching turn is still provisional, so the caller + * defers its diagnostic until `commitTurnId()`. + */ + private validateRunIds( + params: JsonObject, + nullableTurn = false, + ): boolean { if (params.threadId !== this.threadId) { throw new Error('subagent-codex: app-server request referenced another thread') } - if (nullableTurn && params.turnId === null) return + if (nullableTurn && params.turnId === null) return false const id = string(params.turnId, 'server request turn id') if (this.turnId === undefined) { this.observePendingTurnId(id) - return + return true } if (id !== this.turnId) { throw new Error('subagent-codex: app-server request referenced another turn') } + return false + } + + private recordRequestDiagnostic( + provisional: boolean, + request: Parameters[1], + decision: Parameters[2], + reason: string, + ): void { + const order = this.nextObservationOrder() + if (provisional) { + this.pendingDiagnostic = { + order, + request, + decision, + reason, + } + return + } + this.recordDiagnostic(request, decision, reason, order) + } + + private recordDiagnostic( + request: Parameters[1], + decision: Parameters[2], + reason: string, + order = this.nextObservationOrder(), + ): void { + if (order < this.diagnosticOrder) return + this.diagnosticOrder = order + this.diagnostic = unattendedDiagnostic( + this.permissionMode, + request, + decision, + reason, + ) + } + + private nextObservationOrder(): number { + this.observationOrder += 1 + return this.observationOrder + } + + private recordDeclinedItem(item: JsonObject, order?: number): boolean { + if (item.type === 'commandExecution' && item.status === 'declined') { + this.recordDiagnostic( + 'command execution', + 'declined', + 'Codex declined the command under the selected permission mode', + order, + ) + return true + } + if (item.type === 'fileChange' && item.status === 'declined') { + this.recordDiagnostic( + 'file change', + 'declined', + 'Codex declined the file change under the selected permission mode', + order, + ) + return true + } + return false } private handleServerRequest(method: string, params: JsonObject): Promise { try { switch (method) { case 'item/commandExecution/requestApproval': + { + const provisional = this.validateRunIds(params) + const decision = unattendedDecision(params) + this.recordRequestDiagnostic( + provisional, + 'command approval', + decision === 'cancel' ? 'cancelled' : 'declined', + 'the provider does not grant interactive approval', + ) + return Promise.resolve({ decision }) + } case 'item/fileChange/requestApproval': - this.validateRunIds(params) - return Promise.resolve({ decision: unattendedDecision(params) }) + { + const provisional = this.validateRunIds(params) + const decision = unattendedDecision(params) + this.recordRequestDiagnostic( + provisional, + 'file approval', + decision === 'cancel' ? 'cancelled' : 'declined', + 'the provider does not grant interactive approval', + ) + return Promise.resolve({ decision }) + } case 'item/permissions/requestApproval': - this.validateRunIds(params) + this.recordRequestDiagnostic( + this.validateRunIds(params), + 'permission grant', + 'denied', + 'the provider grants no additional turn permissions', + ) return Promise.resolve({ permissions: {}, scope: 'turn' }) case 'item/tool/requestUserInput': - this.validateRunIds(params) + this.recordRequestDiagnostic( + this.validateRunIds(params), + 'user input', + 'empty response', + 'the provider does not collect interactive answers', + ) return Promise.resolve({ answers: {} }) case 'mcpServer/elicitation/request': - this.validateRunIds(params, true) + this.recordRequestDiagnostic( + this.validateRunIds(params, true), + 'MCP elicitation', + 'declined', + 'the provider does not collect interactive MCP input', + ) return Promise.resolve({ action: 'decline', content: null, _meta: null }) default: throw new Error(`subagent-codex: unsupported app-server request ${JSON.stringify(method)}`) @@ -317,7 +563,11 @@ export class CodexAppServerWire { } } - private handleNotification(method: string, params: JsonObject): void { + private handleNotification( + method: string, + params: JsonObject, + order?: number, + ): void { if (method === 'turn/started') { const threadId = string(params.threadId, 'turn/started thread id') if (threadId !== this.threadId) return @@ -334,12 +584,17 @@ export class CodexAppServerWire { if (this.turnId === undefined) { if (this.turnCompleted !== undefined) { this.observePendingTurnId(id) - this.earlyTurnNotifications.push({ method, params }) + this.earlyTurnNotifications.push({ + method, + params, + order: this.nextObservationOrder(), + }) } return } if (id !== this.turnId) return const item = object(params.item, 'item/completed item') + if (this.recordDeclinedItem(item, order)) return if (item.type !== 'agentMessage') return const text = typeof item.text === 'string' ? item.text @@ -362,13 +617,20 @@ export class CodexAppServerWire { if (turnCompleted === undefined) return if (this.turnId === undefined) { this.observePendingTurnId(id) - this.earlyTurnNotifications.push({ method, params }) + this.earlyTurnNotifications.push({ + method, + params, + order: this.nextObservationOrder(), + }) return } if (id !== this.turnId) return if (!['completed', 'interrupted', 'failed'].includes(String(turn.status))) { throw new Error(`subagent-codex: app-server returned invalid terminal turn status ${String(turn.status)}`) } - turnCompleted.resolve(params) + turnCompleted.resolve({ + params, + order: order ?? this.nextObservationOrder(), + }) } } diff --git a/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts b/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts index 8e265c3207..b55b819989 100644 --- a/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -12,16 +13,24 @@ const fixtureDir = fileURLToPath(new URL( )) const driver = join(fixtureDir, 'driver.ts') const configPath = join(fixtureDir, 'cordis.yml') +const packageDir = fileURLToPath(new URL('..', import.meta.url)) +const manifest = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8')) as { + dsh?: { bundle?: { patch?: string } } +} +const bundlePatch = manifest.dsh?.bundle?.patch +if (bundlePatch === undefined) throw new Error('Codex package must declare a Bundle patch') +const bundlePatchPath = join(packageDir, bundlePatch) const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url)) describe('Codex provider public Loader composition', () => { - it('loads the opt-in package, one-shot task tool, and job controls without starting Codex', async () => { + it('loads the Bundle default, two named instances, their tools, and job controls without starting Codex', async () => { const { stdout, stderr } = await runLoaderSmoke({ label: 'subagent-codex Loader composition', tempDirPrefix: 'dsh-subagent-codex-loader-', binScript: driver, libBinScript: driver, configPath, + binArgs: [configPath, bundlePatchPath], tsconfigPath: repoTsconfig, env: { // Loading the optional package must not probe or start a Codex binary. @@ -31,22 +40,56 @@ describe('Codex provider public Loader composition', () => { expect(stderr).toBe('') expect(JSON.parse(stdout)).toEqual({ - providers: ['codex'], - provider: { - name: 'codex', - capabilities: { - outputSchema: false, - depthLimit: false, - toolFilter: false, - persona: false, + providers: ['codex-primary', 'codex-secondary', 'codex'], + providerDetails: [ + { + name: 'codex', + capabilities: { + outputSchema: false, + depthLimit: false, + toolFilter: false, + persona: false, + }, + inheritsParentContext: false, }, - inheritsParentContext: false, - }, - tool: { - name: 'subagent_codex', - parameterNames: ['description', 'prompt', 'run_in_background'], - required: ['description', 'prompt'], - }, + { + name: 'codex-primary', + capabilities: { + outputSchema: false, + depthLimit: false, + toolFilter: false, + persona: false, + }, + inheritsParentContext: false, + }, + { + name: 'codex-secondary', + capabilities: { + outputSchema: false, + depthLimit: false, + toolFilter: false, + persona: false, + }, + inheritsParentContext: false, + }, + ], + tools: [ + { + name: 'subagent_codex', + parameterNames: ['description', 'prompt', 'run_in_background'], + required: ['description', 'prompt'], + }, + { + name: 'subagent_codex_primary', + parameterNames: ['description', 'prompt', 'run_in_background'], + required: ['description', 'prompt'], + }, + { + name: 'subagent_codex_secondary', + parameterNames: ['description', 'prompt', 'run_in_background'], + required: ['description', 'prompt'], + }, + ], jobTools: ['job_kill', 'job_list', 'job_output'], starts: 0, }) diff --git a/packages/subagent/subagent-codex/tests/real-deepseek.e2e.ts b/packages/subagent/subagent-codex/tests/real-deepseek.e2e.ts index 075b6048f2..c12e96a306 100644 --- a/packages/subagent/subagent-codex/tests/real-deepseek.e2e.ts +++ b/packages/subagent/subagent-codex/tests/real-deepseek.e2e.ts @@ -7,9 +7,9 @@ import { rmSync, writeFileSync, } from 'node:fs' +import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { delimiter, join, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' +import { dirname, join, resolve } from 'node:path' import { promisify } from 'node:util' import { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -24,12 +24,12 @@ import { } from './deepseek-responses-bridge.ts' const execFileAsync = promisify(execFile) -const packageRoot = resolve(fileURLToPath(new URL('..', import.meta.url))) -const codexBinDir = join(packageRoot, 'node_modules', '.bin') +const codexPackageJson = createRequire(import.meta.url).resolve('@openai/codex/package.json') const codexPackage = JSON.parse(readFileSync( - join(packageRoot, 'node_modules', '@openai', 'codex', 'package.json'), + codexPackageJson, 'utf8', -)) as { version: string } +)) as { version: string; bin: { codex: string } } +const codexEntry = resolve(dirname(codexPackageJson), codexPackage.bin.codex) const roots: string[] = [] const contexts: Context[] = [] @@ -88,7 +88,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)( CODEX_HOME: codexHome, HOME: root, XDG_CONFIG_HOME: join(root, 'xdg-config'), - PATH: `${codexBinDir}${delimiter}${process.env.PATH ?? ''}`, + PATH: root, HTTP_PROXY: '', HTTPS_PROXY: '', ALL_PROXY: '', @@ -106,7 +106,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)( return handle }) await ctx.plugin(codex, { env, disposeGraceMs: 2_000 }) - const version = await execFileAsync(join(codexBinDir, 'codex'), ['--version'], { + const version = await execFileAsync(process.execPath, [codexEntry, '--version'], { env: { ...process.env, ...env }, }) expect(codexPackage.version).toBe('0.147.0') diff --git a/packages/subagent/subagent-codex/tests/real-product.spec.ts b/packages/subagent/subagent-codex/tests/real-product.spec.ts index 551d6db765..3b95de4f79 100644 --- a/packages/subagent/subagent-codex/tests/real-product.spec.ts +++ b/packages/subagent/subagent-codex/tests/real-product.spec.ts @@ -1,5 +1,6 @@ import { execFile } from 'node:child_process' import { + cpSync, existsSync, mkdirSync, mkdtempSync, @@ -7,17 +8,19 @@ import { writeFileSync, } from 'node:fs' import { rm } from 'node:fs/promises' +import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { delimiter, join, resolve } from 'node:path' +import { delimiter, dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { promisify } from 'node:util' import { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, vi } from 'vitest' import type { Agent } from '@deepseek-ai/dsh-agent' import SubagentRuntime from '@deepseek-ai/dsh-subagent' -import type { SubprocessHandle } from '@deepseek-ai/dsh-subprocess' +import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as codex from '../src/index.ts' +import type { CodexPermissionMode } from '../src/run.ts' import { startResponsesFixture, type ResponsesBehavior, @@ -27,11 +30,13 @@ import { const execFileAsync = promisify(execFile) const packageRoot = resolve(fileURLToPath(new URL('..', import.meta.url))) const codexBinDir = join(packageRoot, 'node_modules', '.bin') -const codexEntry = join(packageRoot, 'node_modules', '@openai', 'codex', 'bin', 'codex.js') +const codexPackageJson = createRequire(import.meta.url).resolve('@openai/codex/package.json') const codexPackage = JSON.parse(readFileSync( - join(packageRoot, 'node_modules', '@openai', 'codex', 'package.json'), + codexPackageJson, 'utf8', -)) as { version: string } +)) as { version: string; bin: { codex: string } } +const codexEntry = resolve(dirname(codexPackageJson), codexPackage.bin.codex) +const codexPackageRoot = dirname(dirname(codexEntry)) const roots: string[] = [] const fixtures: ResponsesFixture[] = [] @@ -48,23 +53,31 @@ afterEach(async () => { interface RealHarness { readonly ctx: Context readonly handles: SubprocessHandle[] + readonly spawnSpecs: SubprocessSpawnSpec[] readonly parent: Agent readonly env: Record readonly workspace: string } -async function realHarness(script: readonly ResponsesBehavior[]): Promise<{ - readonly harness: RealHarness +interface RealInstanceFixture { readonly fixture: ResponsesFixture -}> { + readonly env: Record + readonly workspace: string +} + +type ResponsesScript = readonly ResponsesBehavior[] | ((workspace: string) => readonly ResponsesBehavior[]) + +async function realInstanceFixture( + script: ResponsesScript, +): Promise { const root = mkdtempSync(join(tmpdir(), 'dsh-codex-real-')) roots.push(root) const workspace = join(root, 'workspace') const codexHome = join(root, 'codex-home') - const fixture = await startResponsesFixture(script) - fixtures.push(fixture) mkdirSync(workspace) mkdirSync(codexHome) + const fixture = await startResponsesFixture(typeof script === 'function' ? script(workspace) : script) + fixtures.push(fixture) writeFileSync(join(codexHome, 'config.toml'), [ 'model = "fixture-model"', 'model_provider = "fixture"', @@ -95,23 +108,61 @@ async function realHarness(script: readonly ResponsesBehavior[]): Promise<{ ALL_PROXY: '', NO_PROXY: '127.0.0.1,localhost', } + return { fixture, env, workspace } +} + +interface RealRuntime { + readonly ctx: Context + readonly handles: SubprocessHandle[] + readonly spawnSpecs: SubprocessSpawnSpec[] +} + +async function realRuntime(): Promise { const ctx = new Context() contexts.push(ctx) await ctx.plugin(SubagentRuntime) await ctx.plugin(LocalSubprocessRuntime) const handles: SubprocessHandle[] = [] + const spawnSpecs: SubprocessSpawnSpec[] = [] const spawn = ctx.subprocess.spawn.bind(ctx.subprocess) vi.spyOn(ctx.subprocess, 'spawn').mockImplementation((spec) => { + spawnSpecs.push(spec) const handle = spawn(spec) handles.push(handle) return handle }) - await ctx.plugin(codex, { env, disposeGraceMs: 2_000 }) + return { ctx, handles, spawnSpecs } +} + +async function realHarness( + script: ResponsesScript, + permissionMode?: CodexPermissionMode, +): Promise<{ + readonly harness: RealHarness + readonly fixture: ResponsesFixture +}> { + const instance = await realInstanceFixture(script) + const { ctx, handles, spawnSpecs } = await realRuntime() + await ctx.plugin(codex, { + env: instance.env, + ...permissionMode === undefined ? {} : { permissionMode }, + disposeGraceMs: 2_000, + }) const parent = { id: 'real-parent', - session: { header: { cwd: workspace } }, + session: { header: { cwd: instance.workspace } }, } as unknown as Agent - return { harness: { ctx, handles, parent, env, workspace }, fixture } + return { + harness: { + ctx, + handles, + spawnSpecs, + parent, + env: instance.env, + workspace: instance.workspace, + }, + fixture: instance.fixture, + } } async function expectQuiescent(handles: readonly SubprocessHandle[]): Promise { @@ -141,12 +192,12 @@ function responseInputTexts(body: Record): string[] { } describe('real @openai/codex 0.147.0 product', () => { - it('passes the exact task and fake authentication to local Responses and returns exact text', async () => { + it('starts approve-for-me through the real app-server and returns exact text', async () => { const sentinel = 'REAL_CODEX_SENTINEL_0_147_0' const task = 'Return the fixture sentinel exactly.' const { harness, fixture } = await realHarness([ { kind: 'complete', text: sentinel }, - ]) + ], 'approve-for-me') expect(codexPackage.version).toBe('0.147.0') const version = await execFileAsync(process.execPath, [codexEntry, '--version'], { env: { ...process.env, ...harness.env }, @@ -164,6 +215,13 @@ describe('real @openai/codex 0.147.0 product', () => { }) await run.dispose() + expect(harness.spawnSpecs[0]?.argv).toEqual([ + process.execPath, + codexEntry, + 'app-server', + '--stdio', + ]) + expect(fixture.requests).toHaveLength(1) const recorded = fixture.requests[0]! expect(recorded.method).toBe('POST') @@ -173,7 +231,98 @@ describe('real @openai/codex 0.147.0 product', () => { await expectQuiescent(harness.handles) }, 60_000) - it('cancels a real app-server command approval without executing the command', async () => { + it('fails a missing platform payload without falling back to a host codex', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-codex-missing-payload-')) + roots.push(root) + const isolatedPackage = join(root, 'node_modules', '@openai', 'codex') + mkdirSync(dirname(isolatedPackage), { recursive: true }) + cpSync(codexPackageRoot, isolatedPackage, { recursive: true, dereference: true }) + const isolatedEntry = join(isolatedPackage, 'bin', 'codex.js') + + await expect(execFileAsync(process.execPath, [isolatedEntry, '--version'], { + env: { + PATH: codexBinDir, + ...process.platform === 'win32' && process.env.SystemRoot !== undefined + ? { SystemRoot: process.env.SystemRoot } + : {}, + }, + })).rejects.toThrow(/Missing optional dependency @openai\/codex-[a-z0-9-]+/) + }, 30_000) + + it('runs two named instances concurrently and unloads one without revoking its run', async () => { + const safeInstance = await realInstanceFixture([{ kind: 'hold' }]) + const bypassInstance = await realInstanceFixture([{ + kind: 'complete', + text: 'NAMED_CODEX_BYPASS_RESULT', + }]) + const { ctx, handles, spawnSpecs } = await realRuntime() + const safeFiber = await ctx.plugin(codex, { + providerName: 'codex-safe', + env: safeInstance.env, + permissionMode: 'never', + disposeGraceMs: 2_000, + }) + const bypassFiber = await ctx.plugin(codex, { + providerName: 'codex-bypass', + env: bypassInstance.env, + permissionMode: 'dangerously-bypass-approvals-and-sandbox', + disposeGraceMs: 2_000, + }) + const safeParent = { + id: 'safe-parent', + session: { header: { cwd: safeInstance.workspace } }, + } as unknown as Agent + const bypassParent = { + id: 'bypass-parent', + session: { header: { cwd: bypassInstance.workspace } }, + } as unknown as Agent + const safeController = new AbortController() + + const [safeRun, bypassRun] = await Promise.all([ + ctx.subagents.start('codex-safe', { + prompt: [{ type: 'text', text: 'Hold the safe instance.' }], + parent: safeParent, + signal: safeController.signal, + }), + ctx.subagents.start('codex-bypass', { + prompt: [{ type: 'text', text: 'Complete the bypass instance.' }], + parent: bypassParent, + signal: new AbortController().signal, + }), + ]) + await safeInstance.fixture.requestStarted + await safeFiber.dispose() + expect(ctx.subagents.list()).toEqual(['codex-bypass']) + await expect(ctx.subagents.start('codex-safe', { + prompt: [{ type: 'text', text: 'This start must fail.' }], + parent: safeParent, + signal: new AbortController().signal, + })).rejects.toMatchObject({ code: 'NO_PROVIDER' }) + + await expect(bypassRun.result).resolves.toEqual({ + output: [{ type: 'text', text: 'NAMED_CODEX_BYPASS_RESULT' }], + stopReason: 'completed', + }) + safeController.abort(new Error('cancel only the published safe run')) + await expect(safeRun.result).resolves.toEqual({ + output: [], + stopReason: 'aborted', + }) + await Promise.all([safeRun.dispose(), bypassRun.dispose()]) + expect(safeInstance.fixture.requests).toHaveLength(1) + expect(bypassInstance.fixture.requests).toHaveLength(1) + expect(safeInstance.fixture.requests[0]?.body.input) + .not.toEqual(bypassInstance.fixture.requests[0]?.body.input) + expect(spawnSpecs.map(spec => spec.env?.CODEX_HOME).sort()).toEqual([ + safeInstance.env.CODEX_HOME, + bypassInstance.env.CODEX_HOME, + ].sort()) + await expectQuiescent(handles) + await bypassFiber.dispose() + expect(ctx.subagents.list()).toEqual([]) + }, 60_000) + + it('overrides on-request with never and reports a denied command safely', async () => { const command = process.platform === 'win32' ? 'cmd /c type nul > approval-side-effect' : 'touch approval-side-effect' @@ -200,6 +349,11 @@ describe('real @openai/codex 0.147.0 product', () => { kind: 'advertisedFunctionCall', choices: commandCalls, }, + { + kind: 'error', + status: 400, + message: 'fixture terminal failure after permission denial', + }, ]) const sideEffect = join(harness.workspace, 'approval-side-effect') const run = await harness.ctx.subagents.start('codex', { @@ -207,14 +361,20 @@ describe('real @openai/codex 0.147.0 product', () => { parent: harness.parent, signal: new AbortController().signal, }) - await expect(run.result).resolves.toEqual({ - output: [], - stopReason: 'error', - }) + const result = await run.result + expect(result.output).toEqual([]) + expect(result.stopReason).toBe('error') + expect([ + 'Codex unattended decision (mode: never; request: command approval; decision: cancelled): the provider does not grant interactive approval', + 'Codex unattended decision (mode: never; request: sandbox execution; decision: failed): Codex reported a sandbox failure', + 'Codex unattended decision (mode: never; request: command execution; decision: denied): Codex rejected an escalation because the selected policy never asks for approval', + ]).toContain(result.diagnostic) + expect(result.diagnostic).not.toContain(command) + expect(result.diagnostic).not.toContain(harness.workspace) await run.dispose() expect(existsSync(sideEffect)).toBe(false) - expect(fixture.requests).toHaveLength(1) + expect(fixture.requests).toHaveLength(2) const tools = fixture.requests[0]!.body.tools as Array> expect(commandCalls.some(call => tools.some(tool => ( tool.type === 'function' && tool.name === call.name @@ -225,6 +385,48 @@ describe('real @openai/codex 0.147.0 product', () => { await expectQuiescent(harness.handles) }, 60_000) + it('executes an explicitly selected dangerous bypass write in the isolated workspace', async () => { + const sideEffect = 'bypass-side-effect' + const { harness, fixture } = await realHarness((workspace): readonly ResponsesBehavior[] => { + const target = join(workspace, sideEffect) + const command = process.platform === 'win32' + ? `powershell.exe -NoLogo -NoProfile -NonInteractive -Command "Set-Content -LiteralPath '${target.replaceAll("'", "''")}' -Value 'bypass' -NoNewline"` + : `printf bypass > ${JSON.stringify(target)}` + const commandCalls = [ + { + name: 'exec_command', + arguments: { + cmd: command, + }, + }, + { + name: 'shell_command', + arguments: { + command, + }, + }, + ] as const + return [ + { kind: 'advertisedFunctionCall', choices: commandCalls }, + { kind: 'complete', text: 'bypass complete' }, + ] + }, 'dangerously-bypass-approvals-and-sandbox') + const target = join(harness.workspace, sideEffect) + const run = await harness.ctx.subagents.start('codex', { + prompt: [{ type: 'text', text: 'Create the fixture side effect.' }], + parent: harness.parent, + signal: new AbortController().signal, + }) + await expect(run.result).resolves.toEqual({ + output: [{ type: 'text', text: 'bypass complete' }], + stopReason: 'completed', + }) + expect(existsSync(target), JSON.stringify(fixture.requests.at(-1)?.body.input)).toBe(true) + expect(readFileSync(target, 'utf8').trim()).toBe('bypass') + await run.dispose() + await expectQuiescent(harness.handles) + }, 60_000) + it('settles cancellation locally and leaves the real app-server tree quiescent', async () => { const { harness, fixture } = await realHarness([{ kind: 'hold' }]) const controller = new AbortController() diff --git a/packages/subagent/subagent-codex/tests/responses-fixture.ts b/packages/subagent/subagent-codex/tests/responses-fixture.ts index 2b6e5868ae..c2ef18d803 100644 --- a/packages/subagent/subagent-codex/tests/responses-fixture.ts +++ b/packages/subagent/subagent-codex/tests/responses-fixture.ts @@ -17,6 +17,7 @@ interface RecordedResponsesRequest { /** Behavior consumed by one Responses request. */ export type ResponsesBehavior = | { readonly kind: 'complete'; readonly text: string } + | { readonly kind: 'error'; readonly status: number; readonly message: string } | { readonly kind: 'functionCall' readonly name: string @@ -275,6 +276,11 @@ export async function startResponsesFixture( response.end(JSON.stringify({ error: { message: 'none of the fixture function calls was advertised' } })) return } + if (behavior.kind === 'error') { + response.writeHead(behavior.status, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ error: { message: behavior.message } })) + return + } response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', diff --git a/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts b/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts index 37b2e9ff0b..6ba6f65e87 100644 --- a/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts +++ b/packages/subagent/subagent-codex/tests/subagent-codex.spec.ts @@ -1,6 +1,10 @@ +import { readFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' import { PassThrough } from 'node:stream' +import { fileURLToPath } from 'node:url' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' +import * as yaml from 'js-yaml' import { describe, expect, it, vi } from 'vitest' import type { Agent } from '@deepseek-ai/dsh-agent' import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' @@ -10,11 +14,14 @@ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { SubprocessHandle, SubprocessOutcome, + SubprocessSpawnSpec, } from '@deepseek-ai/dsh-subprocess' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as codex from '../src/index.ts' import * as invariant from '../src/invariant.ts' import { + CODEX_PERMISSION_MODES, + DEFAULT_CODEX_PERMISSION_MODE, codexAppServerArgv, DEFAULT_DISPOSE_GRACE_MS, disposeCodexChild, @@ -24,8 +31,50 @@ import { } from '../src/run.ts' import { CodexAppServerWire } from '../src/wire.ts' +const { hostStderrWrite } = vi.hoisted(() => ({ + hostStderrWrite: { + capture: false, + failNext: false, + chunks: [] as Buffer[], + }, +})) + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeFileSync( + fd: number, + value: string | Uint8Array, + ): void { + if (fd === 2 && hostStderrWrite.capture) { + if (hostStderrWrite.failNext) { + hostStderrWrite.failNext = false + throw Object.assign(new Error('host stderr broke'), { code: 'EIO' }) + } + const bytes = typeof value === 'string' + ? Buffer.from(value) + : Buffer.from(value.buffer, value.byteOffset, value.byteLength) + hostStderrWrite.chunks.push(bytes) + return + } + actual.writeFileSync(fd, value) + }, + } +}) + type JsonObject = Record +const CODEX_VERSION = '0.147.0' +const CODEX_PLATFORM_PACKAGES = [ + '@openai/codex-darwin-arm64', + '@openai/codex-darwin-x64', + '@openai/codex-linux-arm64', + '@openai/codex-linux-x64', + '@openai/codex-win32-arm64', + '@openai/codex-win32-x64', +] as const + const fakeParent = { id: 'parent', session: { header: { cwd: process.cwd() } }, @@ -101,8 +150,10 @@ interface FakeChild { readonly peer: ProtocolPeer readonly fromChild: PassThrough readonly toChild: PassThrough + readonly stderr: PassThrough readonly settle: (outcome?: SubprocessOutcome) => void readonly fail: (error: Error) => void + readonly setStderr: (text: string) => void readonly terminate: () => void readonly waitForExit: (signal?: AbortSignal) => Promise } @@ -110,6 +161,7 @@ interface FakeChild { function fakeChild(options: FakeChildOptions = {}): FakeChild { const fromChild = new PassThrough() const toChild = new PassThrough() + const stderr = new PassThrough() const peer = new ProtocolPeer(toChild, fromChild) let exited = false let resolveDone!: (outcome: SubprocessOutcome) => void @@ -159,7 +211,7 @@ function fakeChild(options: FakeChildOptions = {}): FakeChild { pid: options.pid ?? 1234, stdin: toChild, stdout: fromChild, - stderr: undefined, + stderr, collected: {}, done, terminate, @@ -170,19 +222,30 @@ function fakeChild(options: FakeChildOptions = {}): FakeChild { peer, fromChild, toChild, + stderr, settle, fail, + setStderr: (text: string): void => { stderr.write(text) }, terminate, waitForExit, } } +function defaultWire(child: FakeChild): CodexAppServerWire { + return new CodexAppServerWire( + child.handle.stdout!, + child.handle.stdin!, + DEFAULT_CODEX_PERMISSION_MODE, + ) +} + function runSpec( child: FakeChild, overrides: Partial = {}, ): CodexRunSpec { return { cwd: process.cwd(), + permissionMode: DEFAULT_CODEX_PERMISSION_MODE, env: {}, disposeGraceMs: DEFAULT_DISPOSE_GRACE_MS, spawn: () => child.handle, @@ -195,7 +258,7 @@ async function initializeWire(): Promise<{ readonly wire: CodexAppServerWire }> { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) wire.start() const initializing = wire.initialize(new AbortController().signal) const initialize = await child.peer.nextMethod('initialize') @@ -260,17 +323,66 @@ function turnCompleted( } describe('task admission and package contracts', () => { - it('resolves the fixed app-server command through the Windows npm shim boundary', () => { - expect(codexAppServerArgv('win32')).toEqual([ - 'cmd.exe', - '/d', - '/s', - '/c', - 'codex', + it('ships one independently installable provider-only Bundle patch', () => { + const root = fileURLToPath(new URL('..', import.meta.url)) + const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as { + dependencies?: Record + files?: string[] + dsh?: { bundle?: { patch?: string } } + } + expect(manifest.dsh?.bundle?.patch).toBe('./cordis.patch.yml') + expect(manifest.files).toContain('cordis.patch.yml') + expect(manifest.dependencies).toHaveProperty( + '@deepseek-ai/dsh-sdk-protocol', + 'workspace:^', + ) + expect(manifest.dependencies).toHaveProperty('@openai/codex', CODEX_VERSION) + expect(manifest.dependencies).not.toHaveProperty('@deepseek-ai/dsh-subagent-claude-code') + + const codexPackageJson = fileURLToPath(import.meta.resolve('@openai/codex/package.json')) + const codexManifest = JSON.parse(readFileSync(codexPackageJson, 'utf8')) as { + version: string + bin: { codex: string } + optionalDependencies: Record + } + expect(codexManifest.version).toBe(CODEX_VERSION) + expect(codexManifest.bin).toEqual({ codex: 'bin/codex.js' }) + expect(codexManifest.optionalDependencies).toEqual(Object.fromEntries( + CODEX_PLATFORM_PACKAGES.map(packageName => [ + packageName, + `npm:@openai/codex@${CODEX_VERSION}-${packageName.slice('@openai/codex-'.length)}`, + ]), + )) + expect(codexAppServerArgv()).toEqual([ + process.execPath, + resolve(dirname(codexPackageJson), codexManifest.bin.codex), 'app-server', '--stdio', ]) - expect(codexAppServerArgv('linux')).toEqual(['codex', 'app-server', '--stdio']) + + const lockfile = readFileSync(resolve(root, '../../../pnpm-lock.yaml'), 'utf8') + for (const packageName of CODEX_PLATFORM_PACKAGES) { + const suffix = packageName.slice('@openai/codex-'.length) + expect(lockfile).toContain(` '@openai/codex@${CODEX_VERSION}-${suffix}':`) + expect(lockfile).toContain( + ` '${packageName}': '@openai/codex@${CODEX_VERSION}-${suffix}'`, + ) + } + + const parsed = yaml.load(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8')) + const rows = Array.isArray(parsed) + ? (parsed as Array<{ insert?: Array<{ id?: string; name?: string }> }>).flatMap(entry => entry.insert ?? []) + : [] + expect(rows).toEqual([{ + id: 'subagent-codex', + name: '@deepseek-ai/dsh-subagent-codex', + }]) + expect(JSON.stringify(rows)).not.toContain('tool-subagent') + }) + + it('uses only the official package-declared wrapper for app-server', () => { + expect(codexAppServerArgv()[0]).toBe(process.execPath) + expect(codexAppServerArgv().slice(2)).toEqual(['app-server', '--stdio']) }) it('accepts one or more text blocks and rejects empty or non-text tasks', () => { @@ -285,7 +397,7 @@ describe('task admission and package contracts', () => { .toThrow('must not be empty') }) - it('registers one fixed descriptor, validates config, and unregisters on HMR', async () => { + it('registers the default descriptor, validates config, and unregisters on HMR', async () => { const ctx = new Context() await ctx.plugin(SubagentRuntime) await ctx.plugin(LocalSubprocessRuntime) @@ -314,6 +426,179 @@ describe('task admission and package contracts', () => { await ctx.fiber.dispose() }) + it('keeps named instances, runs, and HMR ownership isolated', async () => { + const ctx = new Context() + await ctx.plugin(SubagentRuntime) + await ctx.plugin(LocalSubprocessRuntime) + const safeChild = fakeChild() + const bypassChild = fakeChild() + const spawnSpecs: SubprocessSpawnSpec[] = [] + vi.spyOn(ctx.subprocess, 'spawn').mockImplementation((spec) => { + spawnSpecs.push(spec) + return spec.env?.DSH_CODEX_INSTANCE === 'safe' + ? safeChild.handle + : bypassChild.handle + }) + const added: string[] = [] + const started: string[] = [] + const ended: string[] = [] + const removed: string[] = [] + ctx.on('subagent/provider-added', provider => void added.push(provider.name)) + ctx.on('subagent/start', info => void started.push(info.provider)) + ctx.on('subagent/end', info => void ended.push(info.provider)) + ctx.on('subagent/provider-removed', providerName => void removed.push(providerName)) + const safeFiber = await ctx.plugin(codex, { + providerName: 'codex-safe', + env: { DSH_CODEX_INSTANCE: 'safe' }, + permissionMode: 'never', + disposeGraceMs: 11, + }) + const bypassFiber = await ctx.plugin(codex, { + providerName: 'codex-bypass', + env: { DSH_CODEX_INSTANCE: 'bypass' }, + permissionMode: 'dangerously-bypass-approvals-and-sandbox', + disposeGraceMs: 29, + }) + expect(ctx.subagents.list()).toEqual(['codex-safe', 'codex-bypass']) + expect(added).toEqual(['codex-safe', 'codex-bypass']) + + const safeController = new AbortController() + const safeStarting = ctx.subagents.start( + 'codex-safe', + request(undefined, safeController.signal), + ) + const bypassStarting = ctx.subagents.start('codex-bypass', request()) + for (const child of [safeChild, bypassChild]) { + const initialize = await child.peer.nextMethod('initialize') + child.peer.respond(initialize, { userAgent: 'codex-cli 0.147.0' }) + await child.peer.nextMethod('initialized') + const threadStart = await child.peer.nextMethod('thread/start') + child.peer.respond(threadStart, { + thread: { id: 'thread-1', ephemeral: true }, + }) + } + const [safeRun, bypassRun] = await Promise.all([ + safeStarting, + bypassStarting, + ]) + await safeFiber.dispose() + expect(ctx.subagents.list()).toEqual(['codex-bypass']) + expect(removed).toEqual(['codex-safe']) + await expect(ctx.subagents.start('codex-safe', request())) + .rejects.toMatchObject({ code: 'NO_PROVIDER' }) + + const safeTurn = await safeChild.peer.nextMethod('turn/start') + const bypassTurn = await bypassChild.peer.nextMethod('turn/start') + safeChild.peer.respond(safeTurn, { turn: { id: 'turn-safe' } }) + bypassChild.peer.send( + { id: bypassTurn.id, result: { turn: { id: 'turn-bypass' } } }, + agentMessage('bypass answer', 'final_answer', 'turn-bypass'), + turnCompleted('completed', 'turn-bypass'), + ) + await expect(bypassRun.result).resolves.toEqual({ + output: [{ type: 'text', text: 'bypass answer' }], + stopReason: 'completed', + }) + safeController.abort(new Error('stop only the safe instance')) + await expect(safeRun.result).resolves.toEqual({ + output: [], + stopReason: 'aborted', + }) + expect(spawnSpecs.map(spec => ({ + instance: spec.env?.DSH_CODEX_INSTANCE, + graceMs: spec.graceMs, + }))).toEqual([ + { instance: 'safe', graceMs: 11 }, + { instance: 'bypass', graceMs: 29 }, + ]) + + await Promise.all([safeRun.dispose(), bypassRun.dispose()]) + expect([...started].sort()).toEqual(['codex-bypass', 'codex-safe']) + expect([...ended].sort()).toEqual(['codex-bypass', 'codex-safe']) + expect(safeChild.terminate).toHaveBeenCalledOnce() + expect(bypassChild.terminate).toHaveBeenCalledOnce() + await bypassFiber.dispose() + expect(removed).toEqual(['codex-safe', 'codex-bypass']) + await ctx.fiber.dispose() + }) + + it('rejects duplicate provider names without replacing the first instance', async () => { + const ctx = new Context() + await ctx.plugin(SubagentRuntime) + await ctx.plugin(LocalSubprocessRuntime) + const firstFiber = await ctx.plugin(codex, { + providerName: 'codex-duplicate', + }) + const first = ctx.subagents.getProvider('codex-duplicate') + await expect(ctx.plugin(codex, { + providerName: 'codex-duplicate', + permissionMode: 'dangerously-bypass-approvals-and-sandbox', + })).rejects.toMatchObject({ code: 'DUPLICATE_PROVIDER' }) + expect(ctx.subagents.getProvider('codex-duplicate')).toBe(first) + expect(ctx.subagents.list()).toEqual(['codex-duplicate']) + await firstFiber.dispose() + await ctx.fiber.dispose() + }) + + it('accepts only the three fixed non-interactive permission modes', () => { + expect(codex.Config({}).providerName).toBe('codex') + expect(codex.Config({ providerName: 'codex-safe' }).providerName) + .toBe('codex-safe') + expect(() => codex.Config({ providerName: '' })).toThrow() + expect(codex.Config({}).permissionMode).toBe(DEFAULT_CODEX_PERMISSION_MODE) + for (const permissionMode of CODEX_PERMISSION_MODES) { + expect(codex.Config({ permissionMode }).permissionMode).toBe(permissionMode) + } + for (const permissionMode of ['on-request', 'untrusted', 'future-mode']) { + expect(() => codex.Config({ permissionMode } as never)).toThrow() + } + }) + + it('resolves the safe permission default when apply is called directly', async () => { + const ctx = new Context() + await ctx.plugin(SubagentRuntime) + await ctx.plugin(LocalSubprocessRuntime) + codex.apply(ctx, { env: {}, disposeGraceMs: 3_000 }) + expect(ctx.subagents.getProvider('codex')).toBeDefined() + await ctx.fiber.dispose() + }) + + it.each([ + ['never', { approvalPolicy: 'never' }], + ['approve-for-me', { + approvalPolicy: 'on-request', + approvalsReviewer: 'auto_review', + sandbox: 'workspace-write', + }], + ['dangerously-bypass-approvals-and-sandbox', { + approvalPolicy: 'never', + sandbox: 'danger-full-access', + }], + ] as const)('maps %s to the official thread/start fields', async (permissionMode, expected) => { + const child = fakeChild() + const wire = new CodexAppServerWire( + child.handle.stdout!, + child.handle.stdin!, + permissionMode, + ) + wire.start() + const initializing = wire.initialize(new AbortController().signal) + const initialize = await child.peer.nextMethod('initialize') + child.peer.respond(initialize, { userAgent: 'codex-cli 0.147.0' }) + await initializing + await child.peer.nextMethod('initialized') + const starting = wire.startThread('/workspace', new AbortController().signal) + const threadStart = await child.peer.nextMethod('thread/start') + expect(threadStart.params).toEqual({ + cwd: '/workspace', + ephemeral: true, + ...expected, + }) + child.peer.respond(threadStart, { thread: { id: 'thread-1', ephemeral: true } }) + await starting + wire.close() + }) + it('requires a parent session cwd without suggesting unsupported config', async () => { const ctx = new Context() await ctx.plugin(SubagentRuntime) @@ -363,7 +648,7 @@ describe('task admission and package contracts', () => { describe('CodexAppServerWire', () => { it('sends the fixed handshake, thread, and turn payloads and keeps final_answer', async () => { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) expect(wire.collectOutput()).toEqual([]) wire.start() @@ -386,7 +671,11 @@ describe('CodexAppServerWire', () => { const starting = wire.startThread('/workspace', new AbortController().signal) const threadStart = await child.peer.nextMethod('thread/start') - expect(threadStart.params).toEqual({ cwd: '/workspace', ephemeral: true }) + expect(threadStart.params).toEqual({ + cwd: '/workspace', + ephemeral: true, + approvalPolicy: 'never', + }) child.peer.respond(threadStart, { thread: { id: 'thread-1', ephemeral: true } }) await starting @@ -473,7 +762,7 @@ describe('CodexAppServerWire', () => { it('rejects invalid handshake, thread, and turn response shapes', async () => { { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) wire.start() const pending = wire.initialize(new AbortController().signal) const frame = await child.peer.nextMethod('initialize') @@ -483,7 +772,7 @@ describe('CodexAppServerWire', () => { } { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) wire.start() const pending = wire.startThread('/workspace', new AbortController().signal) const frame = await child.peer.nextMethod('thread/start') @@ -586,15 +875,31 @@ describe('CodexAppServerWire', () => { threadId: 'thread-1', turnId: 'turn-1', availableDecisions: ['decline', 'cancel'], + command: 'cat /private/secret.txt', }, }) expect(await child.peer.nextResponse('command')).toMatchObject({ result: { decision: 'cancel' }, }) + expect(wire.collectDiagnostic()).toBeUndefined() child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) await nextTask() + expect(wire.collectDiagnostic()).toBe( + 'Codex unattended decision (mode: never; request: command approval; decision: cancelled): the provider does not grant interactive approval', + ) const requests = [ + { + id: 'command-decline', + method: 'item/commandExecution/requestApproval', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + availableDecisions: ['decline'], + }, + result: { decision: 'decline' }, + diagnostic: 'Codex unattended decision (mode: never; request: command approval; decision: declined): the provider does not grant interactive approval', + }, { id: 'file', method: 'item/fileChange/requestApproval', @@ -604,30 +909,46 @@ describe('CodexAppServerWire', () => { availableDecisions: ['decline'], }, result: { decision: 'decline' }, + diagnostic: 'Codex unattended decision (mode: never; request: file approval; decision: declined): the provider does not grant interactive approval', + }, + { + id: 'file-cancel', + method: 'item/fileChange/requestApproval', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + availableDecisions: ['cancel'], + }, + result: { decision: 'cancel' }, + diagnostic: 'Codex unattended decision (mode: never; request: file approval; decision: cancelled): the provider does not grant interactive approval', }, { id: 'file-default', method: 'item/fileChange/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1' }, result: { decision: 'decline' }, + diagnostic: 'Codex unattended decision (mode: never; request: file approval; decision: declined): the provider does not grant interactive approval', }, { id: 'permissions', method: 'item/permissions/requestApproval', params: { threadId: 'thread-1', turnId: 'turn-1' }, result: { permissions: {}, scope: 'turn' }, + diagnostic: 'Codex unattended decision (mode: never; request: permission grant; decision: denied): the provider grants no additional turn permissions', }, { id: 'user-input', method: 'item/tool/requestUserInput', params: { threadId: 'thread-1', turnId: 'turn-1', questions: [] }, result: { answers: {} }, + diagnostic: 'Codex unattended decision (mode: never; request: user input; decision: empty response): the provider does not collect interactive answers', }, { id: 'mcp', method: 'mcpServer/elicitation/request', params: { threadId: 'thread-1', turnId: null }, result: { action: 'decline', content: null, _meta: null }, + diagnostic: 'Codex unattended decision (mode: never; request: MCP elicitation; decision: declined): the provider does not collect interactive MCP input', }, ] as const for (const serverRequest of requests) { @@ -635,13 +956,205 @@ describe('CodexAppServerWire', () => { expect(await child.peer.nextResponse(serverRequest.id)).toMatchObject({ result: serverRequest.result, }) + expect(wire.collectDiagnostic()).toBe(serverRequest.diagnostic) } + expect(wire.collectDiagnostic()).not.toContain('/private/secret.txt') + child.peer.send(agentMessage('answer', 'final_answer'), turnCompleted('completed')) + await expect(result).resolves.toEqual({ + output: [{ type: 'text', text: 'answer' }], + stopReason: 'completed', + }) + wire.close() + }) + + it('records only a safe diagnostic for an explicit sandbox failure', async () => { + const { child, wire } = await initializeWire() + const result = wire.runTurn(['task'], new AbortController().signal) + const turnStart = await child.peer.nextMethod('turn/start') + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + child.peer.send(turnCompleted('failed', 'turn-1', 'thread-1', { + message: 'failed at /private/secret.txt with SECRET_TOKEN', + additionalDetails: 'raw command payload', + codexErrorInfo: 'sandboxError', + })) + await expect(result).rejects.toThrow('status failed') + expect(wire.collectDiagnostic()).toBe( + 'Codex unattended decision (mode: never; request: sandbox execution; decision: failed): Codex reported a sandbox failure', + ) + expect(wire.collectDiagnostic()).not.toContain('SECRET_TOKEN') + expect(wire.collectDiagnostic()).not.toContain('/private/secret.txt') + wire.close() + }) + + it('records declined command and file items without retaining their payloads', async () => { + const { child, wire } = await initializeWire() + const result = wire.runTurn(['task'], new AbortController().signal) + const turnStart = await child.peer.nextMethod('turn/start') + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + child.peer.send({ + method: 'item/completed', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + item: { + type: 'commandExecution', + status: 'declined', + command: 'cat /private/secret.txt', + }, + }, + }) + await nextTask() + expect(wire.collectDiagnostic()).toBe( + 'Codex unattended decision (mode: never; request: command execution; decision: declined): Codex declined the command under the selected permission mode', + ) + expect(wire.collectDiagnostic()).not.toContain('/private/secret.txt') + + child.peer.send( + { + method: 'item/completed', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + item: { + type: 'fileChange', + status: 'declined', + patch: 'SECRET_TOKEN in /private/secret.txt', + }, + }, + }, + turnCompleted('failed', 'turn-1', 'thread-1', { + message: 'SECRET_TOKEN in /private/secret.txt', + codexErrorInfo: 'other', + }), + ) + await expect(result).rejects.toThrow('status failed') + expect(wire.collectDiagnostic()).toBe( + 'Codex unattended decision (mode: never; request: file change; decision: declined): Codex declined the file change under the selected permission mode', + ) + expect(wire.collectDiagnostic()).not.toContain('SECRET_TOKEN') + expect(wire.collectDiagnostic()).not.toContain('/private/secret.txt') + wire.close() + }) + + it('recognizes large, split, and ordered stderr signatures without retaining raw text', () => { + const first = fakeChild() + const largeWire = new CodexAppServerWire( + first.handle.stdout!, + first.handle.stdin!, + 'never', + ) + largeWire.observeStderr( + `SECRET_TOKEN approval policy is Never; reject command${'x'.repeat(2_048)}`, + ) + expect(largeWire.collectDiagnostic()).toBe( + 'Codex unattended decision (mode: never; request: command execution; decision: denied): Codex rejected an escalation because the selected policy never asks for approval', + ) + expect(largeWire.collectDiagnostic()).not.toContain('SECRET_TOKEN') + + const second = fakeChild() + const splitWire = new CodexAppServerWire( + second.handle.stdout!, + second.handle.stdin!, + 'never', + ) + splitWire.observeStderr('SECRET_TOKEN approval policy is Ne') + splitWire.observeStderr('ver; reject command — /private/secret.txt') + expect(splitWire.collectDiagnostic()).toBe( + 'Codex unattended decision (mode: never; request: command execution; decision: denied): Codex rejected an escalation because the selected policy never asks for approval', + ) + expect(splitWire.collectDiagnostic()).not.toContain('SECRET_TOKEN') + expect(splitWire.collectDiagnostic()).not.toContain('/private/secret.txt') + + const third = fakeChild() + const orderedWire = new CodexAppServerWire( + third.handle.stdout!, + third.handle.stdin!, + 'dangerously-bypass-approvals-and-sandbox', + ) + orderedWire.observeStderr( + 'approval policy is Never; reject command; recorded sandbox violation: path=/private/secret.txt', + ) + expect(orderedWire.collectDiagnostic()).toBe( + 'Codex unattended decision (mode: dangerously-bypass-approvals-and-sandbox; request: sandbox execution; decision: failed): Codex reported a sandbox violation', + ) + expect(orderedWire.collectDiagnostic()).not.toContain('/private/secret.txt') + }) + + it('does not reapply an old stderr signature after a newer request diagnostic', async () => { + const { child, wire } = await initializeWire() + wire.observeStderr('recorded sandbox violation:') + const result = wire.runTurn(['task'], new AbortController().signal) + const turnStart = await child.peer.nextMethod('turn/start') + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + await nextTask() + child.peer.send({ + id: 'file-approval', + method: 'item/fileChange/requestApproval', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + availableDecisions: ['decline'], + }, + }) + await child.peer.nextResponse('file-approval') + expect(wire.collectDiagnostic()).toContain('request: file approval') + wire.observeStderr('later benign stderr') + expect(wire.collectDiagnostic()).toContain('request: file approval') child.peer.send(agentMessage('answer', 'final_answer'), turnCompleted('completed')) await expect(result).resolves.toMatchObject({ stopReason: 'completed' }) wire.close() }) + it('keeps a newer request diagnostic after replaying an older early item', async () => { + const { child, wire } = await initializeWire() + const result = wire.runTurn(['task'], new AbortController().signal) + const turnStart = await child.peer.nextMethod('turn/start') + child.peer.send({ + method: 'item/completed', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + item: { type: 'fileChange', status: 'declined' }, + }, + }) + await nextTask() + child.peer.send({ + id: 'newer-command-request', + method: 'item/commandExecution/requestApproval', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + availableDecisions: ['cancel'], + }, + }) + await child.peer.nextResponse('newer-command-request') + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + child.peer.send(agentMessage('answer', 'final_answer'), turnCompleted('completed')) + await expect(result).resolves.toMatchObject({ stopReason: 'completed' }) + expect(wire.collectDiagnostic()).toContain('request: command approval') + wire.close() + }) + + it('keeps a newer stderr fact after replaying an older early terminal', async () => { + hostStderrWrite.capture = true + hostStderrWrite.chunks.length = 0 + const { child, wire } = await initializeWire() + const result = wire.runTurn(['task'], new AbortController().signal) + const turnStart = await child.peer.nextMethod('turn/start') + child.peer.send(turnCompleted('failed', 'turn-1', 'thread-1', { + message: 'sandbox failure', + codexErrorInfo: 'sandboxError', + })) + await nextTask() + wire.observeStderr('approval policy is Never; reject command') + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + await expect(result).rejects.toThrow('sandboxError') + expect(wire.collectDiagnostic()).toContain('request: command execution') + wire.close() + hostStderrWrite.capture = false + }) + it('fails the run on unknown requests or wrong request association', async () => { for (const serverRequest of [ { @@ -704,6 +1217,44 @@ describe('CodexAppServerWire', () => { wire.close() }) + it('does not retain a diagnostic from a mismatched early item', async () => { + const { child, wire } = await initializeWire() + const result = wire.runTurn(['task'], new AbortController().signal) + const turnStart = await child.peer.nextMethod('turn/start') + child.peer.send({ + method: 'item/completed', + params: { + threadId: 'thread-1', + turnId: 'turn-early', + item: { type: 'fileChange', status: 'declined' }, + }, + }) + child.peer.respond(turnStart, { turn: { id: 'turn-response' } }) + await expect(result).rejects.toThrow('did not match the active turn') + expect(wire.collectDiagnostic()).toBeUndefined() + wire.close() + }) + + it('does not retain a diagnostic from a mismatched provisional request', async () => { + const { child, wire } = await initializeWire() + const result = wire.runTurn(['task'], new AbortController().signal) + const turnStart = await child.peer.nextMethod('turn/start') + child.peer.send({ + id: 'provisional-approval', + method: 'item/commandExecution/requestApproval', + params: { + threadId: 'thread-1', + turnId: 'turn-early', + availableDecisions: ['cancel'], + }, + }) + await child.peer.nextResponse('provisional-approval') + child.peer.respond(turnStart, { turn: { id: 'turn-response' } }) + await expect(result).rejects.toThrow('did not match the active turn') + expect(wire.collectDiagnostic()).toBeUndefined() + wire.close() + }) + it('rejects conflicting early notifications and requests before turn/start', async () => { { const { child, wire } = await initializeWire() @@ -790,7 +1341,7 @@ describe('CodexAppServerWire', () => { it('rejects pending work on abort, EOF, and stream error', async () => { { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) wire.start() const controller = new AbortController() controller.abort('pre-aborted') @@ -800,7 +1351,7 @@ describe('CodexAppServerWire', () => { } { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) wire.start() const controller = new AbortController() const pending = wire.initialize(controller.signal) @@ -811,7 +1362,7 @@ describe('CodexAppServerWire', () => { } { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) wire.start() const pending = wire.initialize(new AbortController().signal) await child.peer.nextMethod('initialize') @@ -821,7 +1372,7 @@ describe('CodexAppServerWire', () => { } { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) wire.start() const pending = wire.initialize(new AbortController().signal) await child.peer.nextMethod('initialize') @@ -831,7 +1382,7 @@ describe('CodexAppServerWire', () => { } { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) wire.start() const pending = wire.initialize(new AbortController().signal) await child.peer.nextMethod('initialize') @@ -864,7 +1415,7 @@ describe('run lifecycle and quiescence', () => { expect(spawn).toHaveBeenCalledWith({ argv: codexAppServerArgv(), cwd: process.cwd(), - stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'inherit' }, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' }, graceMs: DEFAULT_DISPOSE_GRACE_MS, env: { OPENAI_API_KEY: 'fake' }, }) @@ -929,6 +1480,114 @@ describe('run lifecycle and quiescence', () => { await expect(run.result).resolves.toEqual({ output: [], stopReason: 'error' }) await run.dispose() } + { + const child = fakeChild() + const { run, turnStart } = await publishRun(child) + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + child.stderr.emit('error', new Error('stderr broke')) + child.peer.send(agentMessage('answer', 'final_answer'), turnCompleted('completed')) + await expect(run.result).resolves.toEqual({ + output: [{ type: 'text', text: 'answer' }], + stopReason: 'completed', + }) + await run.dispose() + expect(child.stderr.listenerCount('error')).toBe(0) + } + }) + + it('attaches a safe permission diagnostic when a published run fails', async () => { + const { child, run, turnStart } = await publishRun() + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + await nextTask() + child.peer.send({ + id: 'approval-diagnostic', + method: 'item/commandExecution/requestApproval', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + availableDecisions: ['cancel'], + command: 'cat /private/secret.txt', + }, + }) + expect(await child.peer.nextResponse('approval-diagnostic')).toMatchObject({ + result: { decision: 'cancel' }, + }) + child.peer.send(turnCompleted('failed', 'turn-1', 'thread-1', { + message: 'SECRET_TOKEN in /private/secret.txt', + codexErrorInfo: 'other', + })) + await expect(run.result).resolves.toEqual({ + output: [], + diagnostic: 'Codex unattended decision (mode: never; request: command approval; decision: cancelled): the provider does not grant interactive approval', + stopReason: 'error', + }) + await run.dispose() + }) + + it('drains queued stderr before settling a failed published run', async () => { + hostStderrWrite.capture = true + hostStderrWrite.chunks.length = 0 + const { child, run, turnStart } = await publishRun() + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + child.peer.send(turnCompleted('failed', 'turn-1', 'thread-1', { + message: 'fixture terminal failure', + codexErrorInfo: 'badRequest', + })) + setImmediate(() => { + child.stderr.write('approval policy is Never; reject command') + }) + await expect(run.result).resolves.toEqual({ + output: [], + diagnostic: 'Codex unattended decision (mode: never; request: command execution; decision: denied): Codex rejected an escalation because the selected policy never asks for approval', + stopReason: 'error', + }) + await run.dispose() + hostStderrWrite.capture = false + }) + + it('forwards stderr while extracting only a fixed safe permission signature', async () => { + const child = fakeChild() + hostStderrWrite.capture = true + hostStderrWrite.chunks.length = 0 + const { run, turnStart } = await publishRun(child) + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + child.stderr.write('SECRET_TOKEN approval policy is Ne') + child.stderr.write('ver; reject command — /private/secret.txt') + child.stderr.emit('data', 'string stderr suffix') + child.peer.send(turnCompleted('failed', 'turn-1', 'thread-1', { + message: 'fixture terminal failure', + codexErrorInfo: 'badRequest', + })) + await expect(run.result).resolves.toEqual({ + output: [], + diagnostic: 'Codex unattended decision (mode: never; request: command execution; decision: denied): Codex rejected an escalation because the selected policy never asks for approval', + stopReason: 'error', + }) + expect(Buffer.concat(hostStderrWrite.chunks).toString()).toContain('SECRET_TOKEN') + expect(hostStderrWrite.chunks).toHaveLength(3) + await run.dispose() + expect(child.stderr.listenerCount('data')).toBe(0) + hostStderrWrite.capture = false + }) + + it('contains host stderr write failures without changing run settlement', async () => { + const child = fakeChild() + hostStderrWrite.capture = true + hostStderrWrite.failNext = true + const { run, turnStart } = await publishRun(child) + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + child.stderr.write('approval policy is Never; reject command') + child.peer.send(turnCompleted('failed', 'turn-1', 'thread-1', { + message: 'fixture terminal failure', + codexErrorInfo: 'badRequest', + })) + await expect(run.result).resolves.toEqual({ + output: [], + diagnostic: 'Codex unattended decision (mode: never; request: command execution; decision: denied): Codex rejected an escalation because the selected policy never asks for approval', + stopReason: 'error', + }) + await run.dispose() + hostStderrWrite.capture = false }) it('rejects before spawn when pre-aborted and rolls back startup failures', async () => { @@ -939,6 +1598,7 @@ describe('run lifecycle and quiescence', () => { request(undefined, controller.signal), { cwd: process.cwd(), + permissionMode: DEFAULT_CODEX_PERMISSION_MODE, env: {}, disposeGraceMs: 10, spawn, @@ -952,6 +1612,27 @@ describe('run lifecycle and quiescence', () => { child.peer.respond(initialize, null) await expect(starting).rejects.toThrow('invalid initialize response') expect(child.terminate).toHaveBeenCalledTimes(1) + + const stderrChild = fakeChild() + const stderrStarting = startCodexRun(request(), runSpec(stderrChild)) + const stderrInitialize = await stderrChild.peer.nextMethod('initialize') + stderrChild.stderr.emit('error', new Error('startup stderr broke')) + stderrChild.peer.respond(stderrInitialize, { userAgent: 'codex-cli 0.147.0' }) + await stderrChild.peer.nextMethod('initialized') + const stderrThreadStart = await stderrChild.peer.nextMethod('thread/start') + stderrChild.peer.respond(stderrThreadStart, { + thread: { id: 'thread-1', ephemeral: true }, + }) + const stderrRun = await stderrStarting + const stderrTurnStart = await stderrChild.peer.nextMethod('turn/start') + stderrChild.peer.send( + { id: stderrTurnStart.id, result: { turn: { id: 'turn-1' } } }, + agentMessage('answer', 'final_answer'), + turnCompleted('completed'), + ) + await expect(stderrRun.result).resolves.toMatchObject({ stopReason: 'completed' }) + await stderrRun.dispose() + expect(stderrChild.stderr.listenerCount('error')).toBe(0) }) it('rolls back an abort that wins immediately after thread creation', async () => { @@ -965,6 +1646,11 @@ describe('run lifecycle and quiescence', () => { child.peer.respond(initialize, { userAgent: 'codex-cli 0.147.0' }) await child.peer.nextMethod('initialized') const threadStart = await child.peer.nextMethod('thread/start') + expect(threadStart.params).toEqual({ + cwd: process.cwd(), + ephemeral: true, + approvalPolicy: 'never', + }) child.peer.respond(threadStart, { thread: { id: 'thread-1', ephemeral: true } }) controller.abort('startup race') await expect(starting).rejects.toThrow('aborted before run publication') @@ -988,13 +1674,59 @@ describe('run lifecycle and quiescence', () => { expect(child.terminate).toHaveBeenCalledTimes(1) }) + it('surfaces only the wrapper missing-payload diagnostic during startup', async () => { + const child = fakeChild() + child.setStderr([ + `credential-like unrelated stderr ${'x'.repeat(16 * 1024)}`, + 'Error: Missing optional dependency @openai/codex-linux-x64. ' + + 'Reinstall Codex: pnpm add -g @openai/codex@latest', + ].join('\n')) + const starting = startCodexRun(request(), runSpec(child)) + child.settle({ exitCode: 1, signal: null }) + + const error: unknown = await starting.then( + () => undefined, + (failure: unknown) => failure, + ) + expect(error).toBeInstanceOf(Error) + if (!(error instanceof Error)) throw new Error('expected startup failure') + expect(error.message).toContain('Missing optional dependency @openai/codex-linux-x64') + expect(error.message).not.toContain('credential-like unrelated stderr') + expect(error.message).not.toContain('Reinstall Codex') + expect(error.message).not.toContain('pnpm add -g') + expect(child.terminate).toHaveBeenCalledTimes(1) + }) + + it('waits for process settlement before sampling the missing-payload diagnostic', async () => { + const child = fakeChild({ exitOnTerminate: false }) + const starting = startCodexRun(request(), runSpec(child)) + child.fromChild.end() + await vi.waitFor(() => { expect(child.terminate).toHaveBeenCalledTimes(1) }) + + child.setStderr('Error: Missing optional dependency @openai/codex-linux-x64.') + child.settle({ exitCode: 1, signal: null }) + + await expect(starting).rejects.toThrow( + 'Missing optional dependency @openai/codex-linux-x64', + ) + }) + it('keeps overlapping runs isolated', async () => { - const first = fakeChild() - const second = fakeChild() - const runs = await Promise.all([ - publishRun(first), - publishRun(second), - ]) + const initialStderrListeners = { + error: process.stderr.listenerCount('error'), + unpipe: process.stderr.listenerCount('unpipe'), + close: process.stderr.listenerCount('close'), + finish: process.stderr.listenerCount('finish'), + } + const runs = await Promise.all( + Array.from({ length: 6 }, () => publishRun(fakeChild())), + ) + expect({ + error: process.stderr.listenerCount('error'), + unpipe: process.stderr.listenerCount('unpipe'), + close: process.stderr.listenerCount('close'), + finish: process.stderr.listenerCount('finish'), + }).toEqual(initialStderrListeners) for (const [index, entry] of runs.entries()) { const id = `turn-${index + 1}` entry.child.peer.send( @@ -1004,14 +1736,64 @@ describe('run lifecycle and quiescence', () => { ) } const results = await Promise.all(runs.map(entry => entry.run.result)) - expect(results.map(result => result.output)).toEqual([ - [{ type: 'text', text: 'answer-1' }], - [{ type: 'text', text: 'answer-2' }], - ]) - expect(runs[0].run.id).not.toBe(runs[1].run.id) + expect(results.map(result => result.output)).toEqual( + Array.from({ length: 6 }, (_, index) => [ + { type: 'text', text: `answer-${index + 1}` }, + ]), + ) + expect(runs[0]!.run.id).not.toBe(runs[1]!.run.id) await Promise.all(runs.map(entry => entry.run.dispose())) }) + it('isolates permission modes and diagnostics across overlapping runs', async () => { + const first = await publishRun(fakeChild(), undefined, { + permissionMode: 'never', + }) + const second = await publishRun(fakeChild(), undefined, { + permissionMode: 'dangerously-bypass-approvals-and-sandbox', + }) + first.child.peer.respond(first.turnStart, { turn: { id: 'turn-never' } }) + second.child.peer.respond(second.turnStart, { turn: { id: 'turn-bypass' } }) + await nextTask() + first.child.peer.send({ + id: 'never-approval', + method: 'item/commandExecution/requestApproval', + params: { + threadId: 'thread-1', + turnId: 'turn-never', + availableDecisions: ['cancel'], + }, + }) + second.child.peer.send({ + id: 'bypass-elicitation', + method: 'mcpServer/elicitation/request', + params: { threadId: 'thread-1', turnId: null }, + }) + await Promise.all([ + first.child.peer.nextResponse('never-approval'), + second.child.peer.nextResponse('bypass-elicitation'), + ]) + first.child.peer.send(turnCompleted('failed', 'turn-never', 'thread-1', { + message: 'first failure', + codexErrorInfo: 'other', + })) + second.child.peer.send(turnCompleted('failed', 'turn-bypass', 'thread-1', { + message: 'second failure', + codexErrorInfo: 'other', + })) + await expect(first.run.result).resolves.toEqual({ + output: [], + diagnostic: 'Codex unattended decision (mode: never; request: command approval; decision: cancelled): the provider does not grant interactive approval', + stopReason: 'error', + }) + await expect(second.run.result).resolves.toEqual({ + output: [], + diagnostic: 'Codex unattended decision (mode: dangerously-bypass-approvals-and-sandbox; request: MCP elicitation; decision: declined): the provider does not collect interactive MCP input', + stopReason: 'error', + }) + await Promise.all([first.run.dispose(), second.run.dispose()]) + }) + it('uses the registered provider config and logs flattened errors', async () => { const ctx = new Context() await ctx.plugin(SubagentRuntime) @@ -1023,10 +1805,12 @@ describe('run lifecycle and quiescence', () => { warnings.push(String(message)) }) as typeof ctx.logger.warn await ctx.plugin(codex, { + providerName: 'codex-diagnostic', env: { OPENAI_API_KEY: 'fake' }, + permissionMode: 'approve-for-me', disposeGraceMs: 25, }) - const starting = ctx.subagents.start('codex', { + const starting = ctx.subagents.start('codex-diagnostic', { prompt: [{ type: 'text', text: 'task' }], parent: fakeParent, signal: new AbortController().signal, @@ -1035,20 +1819,50 @@ describe('run lifecycle and quiescence', () => { child.peer.respond(initialize, { userAgent: 'codex-cli 0.147.0' }) await child.peer.nextMethod('initialized') const threadStart = await child.peer.nextMethod('thread/start') + expect(threadStart.params).toEqual({ + cwd: process.cwd(), + ephemeral: true, + approvalPolicy: 'on-request', + approvalsReviewer: 'auto_review', + sandbox: 'workspace-write', + }) child.peer.respond(threadStart, { thread: { id: 'thread-1', ephemeral: true } }) const run = await starting - await child.peer.nextMethod('turn/start') - child.settle({ exitCode: 1, signal: null }) - await expect(run.result).resolves.toMatchObject({ stopReason: 'error' }) + const turnStart = await child.peer.nextMethod('turn/start') + child.peer.respond(turnStart, { turn: { id: 'turn-1' } }) + await nextTask() + child.peer.send({ + id: 'provider-approval', + method: 'item/commandExecution/requestApproval', + params: { + threadId: 'thread-1', + turnId: 'turn-1', + availableDecisions: ['cancel'], + command: 'cat /private/secret.txt', + }, + }) + await child.peer.nextResponse('provider-approval') + child.peer.send(turnCompleted('failed', 'turn-1', 'thread-1', { + message: 'SECRET_TOKEN in /private/secret.txt', + codexErrorInfo: 'other', + })) + await expect(run.result).resolves.toEqual({ + output: [], + diagnostic: 'Codex unattended decision (mode: approve-for-me; request: command approval; decision: cancelled): the provider does not grant interactive approval', + stopReason: 'error', + }) expect(spawn).toHaveBeenCalledWith(expect.objectContaining({ + argv: codexAppServerArgv(), env: { OPENAI_API_KEY: 'fake' }, graceMs: 25, cwd: process.cwd(), })) expect(warnings).toEqual([ - expect.stringContaining('subagent-codex: child run failed (error):'), + expect.stringContaining('subagent-codex "codex-diagnostic": child run failed (error): subagent-codex: Codex turn ended with status failed: error'), ]) - await run.dispose().catch(() => {}) + expect(warnings.join('\n')).not.toContain('SECRET_TOKEN') + expect(warnings.join('\n')).not.toContain('/private/secret.txt') + await run.dispose() await ctx.fiber.dispose() }) }) @@ -1056,7 +1870,7 @@ describe('run lifecycle and quiescence', () => { describe('disposeCodexChild', () => { it('closes stdin, terminates, and waits for the managed tree', async () => { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) const end = vi.spyOn(child.toChild, 'end') await disposeCodexChild(wire, child.handle) expect(end).toHaveBeenCalled() @@ -1067,7 +1881,7 @@ describe('disposeCodexChild', () => { it('does not finish disposal before the managed tree exits', async () => { const child = fakeChild({ exitOnTerminate: false }) - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) let disposed = false const disposal = disposeCodexChild(wire, child.handle).then(() => { disposed = true @@ -1081,7 +1895,7 @@ describe('disposeCodexChild', () => { it('contains a concurrently closed stdin error', async () => { const child = fakeChild() - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) vi.spyOn(child.toChild, 'end').mockImplementation(() => { throw new Error('already closed') }) @@ -1094,7 +1908,7 @@ describe('disposeCodexChild', () => { pid: -1, doneError: new Error('spawn failed'), }) - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) await expect(disposeCodexChild(wire, child.handle)) .resolves.toBeUndefined() expect(child.terminate).not.toHaveBeenCalled() @@ -1106,14 +1920,14 @@ describe('disposeCodexChild', () => { const child = fakeChild({ doneError: new Error('close observer failed'), }) - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) await expect(disposeCodexChild(wire, child.handle)) .rejects.toThrow('close observer failed') } { const child = fakeChild() const handle = { ...child.handle, stdin: undefined } - const wire = new CodexAppServerWire(child.handle.stdout!, child.handle.stdin!) + const wire = defaultWire(child) await expect(disposeCodexChild(wire, handle)).resolves.toBeUndefined() } }) diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 7cfdbec38b..d140507b44 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent/README.md -README.md: 9d60a3bd776e867ddf2f8316266970faa6454c9a -README.zh.md: 241e5e8715e7a2e7d4ae8b7385c1ee358a90e2b0 +README.md: 99b28fb7fc62473fa02fef4f3977f29e9935edaa +README.zh.md: 6970c8f21424cb73d170602c52fb98641d5d712d diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index 9d60a3bd77..99b28fb7fc 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -16,12 +16,13 @@ The [subagent family overview](../README.md) maps implementations and model-faci | `getProvider(name)` | Return the provider, or `undefined` when absent. | | `list()` | Return provider names in insertion order. | | `start(name, request)` | Validate an ordinary caller request, resolve its detached `one-shot` descriptor, then await the provider until a real one-shot child is published. Fulfillment returns a holder-owned `SubagentRun`; rejection means the provider has already cleaned every unpublished startup resource, while post-publication turn or infrastructure faults settle through the run. Continuable children never enter through this operation. | -| `startContinuable(spec)` | Establish one durable continuable child and deliver its initial prompt. Resolves with `{ childId, messageId }` when the child's inbox accepts that prompt, without waiting for the turn to start or for the message to reach the Session log; any earlier failure rejects with no ids and rolls the child back entirely. Requires `ctx.agents`, session persistence, and a provider with the `prepareContinuable` capability. | +| `startContinuable(spec)` | Establish one durable continuable child and deliver its initial prompt. Resolves with `{ childId, messageId }` when the child's inbox accepts that prompt, without waiting for the turn to start or for the message to reach the Session log; any earlier failure rejects with no ids and rolls the child back entirely. A caller-reserved `childId` is rejected when the live registries or configured persistence already own it. Requires `ctx.agents`, session persistence, and a provider with the `prepareContinuable` capability. | | `followup(parent, childId, content, { source, signal })` | Deliver one later message from the exact live direct parent as the child's next FIFO turn, matching `Agent.followup()` terminology, and return the accepted `MessageId`. A resident child's inbox accepts it directly (waking a waiting Activation); an absent one cold-resumes from its persisted Session. Requires `ctx.agents`; cold resume also requires session persistence. | | `interrupt(targetSessionId, authority)` | Interrupt one live continuable child's current turn under a human durable parent address (`{ kind: 'user', parentSessionId }`) or an exact live ancestor Agent (`{ kind: 'ancestor', agent }`). Admission is synchronous and the effect asynchronous: it issues `Agent.cancel(cause, { keepInbox: true })` and returns without waiting for the target to observe the signal. Unclaimed pending inbox work, the Activation, and published descendants are preserved; work already claimed into the interrupted turn is not requeued. An absent target is an accepted no-op; a wrong parent address or a stale, self-targeting, or non-ancestor caller rejects with `UNAUTHORIZED`. | | `reportFrom(child, content, { delivery, signal })` | Deliver one selected message from the exact live continuable child to its exact live direct parent and return the accepted stable `MessageId`. Quiet delivery injects next-step context without waking; next-step delivery steers and wakes the parent. | | `registerContinuableSetup(contribution)` | Compose an optional deployment capability into each continuable child's unpublished scope, with immediate revocation from resident children. | | `drainContinuableDescendants(parents)` | Close admission below exact live host-owned parent Agents, stop only their visible continuable descendants, await materializations admitted below those roots through publication or rollback, then release the selected forests child-first. The cutoff lasts until each exact parent leaves the registry; unrelated parent forests and manager-wide admission remain live. | +| `drainContinuableChildren(parent, childIds)` | Release only the named resident continuable direct children of one exact live parent, recursively and child-first. It does not close admission or touch siblings, accepts absent ids as no-ops, and rejects a resident child owned by another parent. This is teardown, so unlike `interrupt()` it does not preserve pending inbox work. | | `listChildren(parentSessionId, signal?)` | List direct session-backed subagents with their `one-shot`/`continuable` mode, `running`/`inactive` activity, origin-classified one-level `hasChildren` hint, and per-child diagnostics, ordered by `createdAt` then id, without loading or resuming them. Reads the live session store and optional session persistence directly (live-only enumeration when persistence is absent) and requires the mounted `sessionProjections` registry; it does not require `ctx.agents`, the continuation manager, or any query service. | | `listDescendants(rootSessionId, signal?)` | Flatten the root's complete session tree in stable pre-order from the same live-preferred corpus, adding each subagent entry's durable `parentId` and root-relative `depth`. Ordinary sessions and one-shot children remain traversal nodes so continuable descendants below them are discovered. Identity, diagnostics, dependencies, and cancellation follow `listChildren()`. | @@ -64,7 +65,7 @@ Both in-process delegation paths fix the child's permission scope at the delegat `provider.start(request): Promise` is the ownership-transfer boundary; the delegation tool also uses it inside its one-shot Task-backed background path. Before fulfillment, the provider owns setup and must cancel, roll back, and quiesce unpublished resources on every failure. After fulfillment, the caller owns the run and must call `dispose()` on every path; remaining prompt and turn work belongs to `SubagentRun.result`. -`SubagentRun.result` resolves to `{ output, structured?, stopReason }`. Child-level failures resolve with a non-`completed` reason; only an infrastructure fault that the seam cannot represent may reject. `dispose()` is idempotent, cancels remaining work, and waits for both result settlement and child-resource quiescence. A result rejection remains on `result`; `dispose()` rejects only for an independent resource-release failure. `output` and the `subagent/end` event's `lastAssistantMessage` use the exported `AssistantOutputFold`/`finalAssistantOutput` helpers to select the child's last non-empty assistant message, or its accumulated assistant text when no such message exists. `output` is `[]` and the event field is absent when the child produced neither ([`SubagentResult.output`](../../../docs/subsystems/subagent.md#the-terminal-result-subagentresult) owns the result contract). +`SubagentRun.result` resolves to `{ output, structured?, diagnostic?, stopReason }`. Child-level failures resolve with a non-`completed` reason; only an infrastructure fault that the seam cannot represent may reject. A provider may add a safe `diagnostic` to a non-completed result after removing tool inputs, file contents, environment values, credentials, and raw protocol payloads and limiting the complete text to 4096 UTF-8 bytes. The field is not assistant output: consumers present it separately, and it does not enter `subagent/end.lastAssistantMessage`. `dispose()` is idempotent, cancels remaining work, and waits for both result settlement and child-resource quiescence. A result rejection remains on `result`; `dispose()` rejects only for an independent resource-release failure. `output` and the `subagent/end` event's `lastAssistantMessage` use the exported `AssistantOutputFold`/`finalAssistantOutput` helpers to select the child's last non-empty assistant message, or its accumulated assistant text when no such message exists. `output` is `[]` and the event field is absent when the child produced neither ([`SubagentResult`](../../../docs/subsystems/subagent.md#the-terminal-result-subagentresult) owns the terminal result contract). A local run publishes an ordinary child agent/session before `start()` fulfills, returns that shared session id as `SubagentRun.id`, exposes the exact child as `SubagentRun.localAgent`, records `request.parent.session.id` in the child's `parentSession` header, and appends the resolved descriptor inside its initial turn. Remote providers instead mint a parent-scoped lifecycle id and return `localAgent: undefined`; without a local child session, their one-shot runs are not part of trace-backed enumeration. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index 241e5e8715..6970c8f214 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -16,12 +16,13 @@ subagent seam 允许一个 agent(智能体)通过具名提供方把工作委 | `getProvider(name)` | 返回提供方;不存在时返回 `undefined`。 | | `list()` | 按插入顺序返回提供方名称。 | | `start(name, request)` | 校验普通调用方请求,解析其已分离的 `one-shot` 描述符,然后等待提供方发布真正的一次性子 agent。兑现时返回由持有方拥有的 `SubagentRun`;如果调用被拒绝,提供方已经清理所有尚未发布的启动资源。发布后的轮次故障或基础设施故障则通过该 run 结算。可继续子 agent 绝不通过此操作进入。 | -| `startContinuable(spec)` | 建立一个持久化的可继续子 agent,并投递其初始提示词。子 agent 的 inbox 一接受该提示词,调用就会兑现为 `{ childId, messageId }`,无需等待轮次开始,也无需等待消息写入会话日志。在此之前发生的任何失败都会使调用被拒绝,不返回任何 id,并完全回滚该子 agent。要求 `ctx.agents`、会话持久化以及具备 `prepareContinuable` 能力的提供方。 | +| `startContinuable(spec)` | 建立一个持久化的可继续子 agent,并投递其初始提示词。子 agent 的 inbox 一接受该提示词,调用就会兑现为 `{ childId, messageId }`,无需等待轮次开始,也无需等待消息写入会话日志。在此之前发生的任何失败都会使调用被拒绝,不返回任何 id,并完全回滚该子 agent。如果在线注册表或已配置的持久化已经占用调用方预留的 `childId`,则拒绝该身份。要求 `ctx.agents`、会话持久化以及具备 `prepareContinuable` 能力的提供方。 | | `followup(parent, childId, content, { source, signal })` | 将来自确切在线直接父级的一条后续消息作为子 agent 的下一个 FIFO 轮次投递,术语与 `Agent.followup()` 一致,并返回被接受的 `MessageId`。驻留中的子 agent 由其 inbox 直接接受(唤醒处于 waiting 的 Activation);不驻留的则从其持久化会话冷恢复。要求 `ctx.agents`;冷恢复还要求会话持久化。 | | `interrupt(targetSessionId, authority)` | 凭人类出示的持久化父级地址 `{ kind: 'user', parentSessionId }`,或确切在线的祖先 Agent `{ kind: 'ancestor', agent }` 进行授权,中断一个在线可继续子级的当前轮次。准入判定同步完成,但取消异步生效:该操作发出 `Agent.cancel(cause, { keepInbox: true })` 后立即返回,不等待目标观察到信号。尚未领取的待处理 inbox 工作、Activation 和已发布的后代均会保留;已经领取到被中断轮次中的工作不会重新入队。目标不存在时视为已接受的空操作;错误的父级地址,或陈旧、指向自身、并非祖先的调用方,会以 `UNAUTHORIZED` 被拒绝。 | | `reportFrom(child, content, { delivery, signal })` | 从确切在线可继续 child 向其确切在线直接 parent 投递一条选中消息,并返回已接受的稳定 `MessageId`。静默投递会注入不唤醒的 next-step 上下文;next-step 投递会 steering 并唤醒 parent。 | | `registerContinuableSetup(contribution)` | 把一项可选部署能力组合到每个可继续 child 尚未发布的作用域中,并支持从驻留 child 立即撤销。 | | `drainContinuableDescendants(parents)` | 在由 host 拥有的确切在线父级 Agent 之下关闭准入,只停止这些父级可见的可继续后代;等待已在这些根节点下获准的物化过程完成发布或回滚后,再按子级优先顺序释放所选的各棵树。该截止状态会持续到每个确切父级离开注册表;无关的父级树仍在线,管理器全局准入仍保持开放。 | +| `drainContinuableChildren(parent, childIds)` | 只释放一个确切在线父级的具名驻留可继续直接子级,并递归保持子级优先顺序。它不关闭准入、不影响同级子级,缺失的 id 视为空操作;若驻留子级属于其他父级,则拒绝。这是拆卸操作,因此与 `interrupt()` 不同,它不会保留待处理的 inbox 工作。 | | `listChildren(parentSessionId, signal?)` | 按 `createdAt`、再按 id 的顺序列出由会话支撑的直接 subagent,包括其 `one-shot`/`continuable` 模式、`running`/`inactive` 活动状态、根据 origin 分类得出的一层 `hasChildren` 提示,以及每个子级的诊断信息,且不会加载或恢复它们。该操作直接读取在线会话存储和可选的会话持久化(没有持久化时只枚举在线子级),并要求已挂载 `sessionProjections` 注册表;不要求 `ctx.agents`、继续执行管理器或任何查询服务。 | | `listDescendants(rootSessionId, signal?)` | 从同一份在线优先语料按稳定 pre-order 展平根的完整会话树,并为每个 subagent 条目附加持久 `parentId` 与相对根的 `depth`。普通会话与一次性 child 仍作为遍历节点,因此其下的可继续后代仍可发现。身份、diagnostic、依赖与取消约定均沿用 `listChildren()`。 | @@ -64,7 +65,7 @@ subagent seam 允许一个 agent(智能体)通过具名提供方把工作委 `provider.start(request): Promise` 是所有权转移边界;委派工具也会在其由 Task 支撑的一次性后台路径中使用它。兑现前,提供方拥有设置过程,并且在任何失败路径上都必须取消、回滚并使尚未发布的资源完全停稳。兑现后,run 的所有权转移给调用方;调用方必须在每条路径上调用 `dispose()`。剩余提示词和轮次工作属于 `SubagentRun.result`。 -`SubagentRun.result` 兑现为 `{ output, structured?, stopReason }`。子 agent 级失败会以非 `completed` 原因兑现;只有 seam 无法表示的基础设施故障才可以拒绝。`dispose()` 是幂等的,会取消剩余工作,并等待结果结算以及子 agent 资源完全停稳。result 的拒绝只通过 `result` 本身报告;只有独立的资源释放失败,才会使 `dispose()` 被拒绝。`output` 与 `subagent/end` 事件的 `lastAssistantMessage` 使用导出的 `AssistantOutputFold`/`finalAssistantOutput` 辅助函数选取子 agent 最后一条非空 assistant 消息;若没有这类消息,则选取其累积的 assistant 文本。子 agent 两种输出均未产生时,`output` 为 `[]`,该事件字段缺省(结果约定归 [`SubagentResult.output`](../../../docs/subsystems/subagent.md#the-terminal-result-subagentresult) 所有)。 +`SubagentRun.result` 兑现为 `{ output, structured?, diagnostic?, stopReason }`。子 agent 级失败会以非 `completed` 原因兑现;只有 seam 无法表示的基础设施故障才可以拒绝。提供方可以为非完成结果附加安全的 `diagnostic`:它会先排除工具输入、文件内容、环境值、凭证与原始协议载荷,并把完整文本限制在 4096 个 UTF-8 字节以内。该字段不是 assistant 输出;消费方会将它分开呈现,它也不会进入 `subagent/end.lastAssistantMessage`。`dispose()` 是幂等的,会取消剩余工作,并等待结果结算以及子 agent 资源完全停稳。result 的拒绝只通过 `result` 本身报告;只有独立的资源释放失败,才会使 `dispose()` 被拒绝。`output` 与 `subagent/end` 事件的 `lastAssistantMessage` 使用导出的 `AssistantOutputFold`/`finalAssistantOutput` 辅助函数选取子 agent 最后一条非空 assistant 消息;若没有这类消息,则选取其累积的 assistant 文本。子 agent 两种输出均未产生时,`output` 为 `[]`,该事件字段缺省(终态结果约定归 [`SubagentResult`](../../../docs/subsystems/subagent.md#the-terminal-result-subagentresult) 所有)。 本地运行会在 `start()` 兑现前发布普通的子 agent/会话,把该共享会话 id 作为 `SubagentRun.id` 返回,以 `SubagentRun.localAgent` 公开准确的子 agent,把 `request.parent.session.id` 记录到子 agent 的 `parentSession` header,并在其初始轮次内追加已解析的描述符。远程提供方则生成 parent 作用域的生命周期 id,并返回 `localAgent: undefined`;由于没有本地 child 会话,其一次性运行不会进入基于追踪的枚举结果。 diff --git a/packages/subagent/subagent/src/continuation.ts b/packages/subagent/subagent/src/continuation.ts index 74e1bf4b0b..652a3ba6c8 100644 --- a/packages/subagent/subagent/src/continuation.ts +++ b/packages/subagent/subagent/src/continuation.ts @@ -114,6 +114,12 @@ export interface ContinuableStartSpec { readonly provider: string /** The initial delegation's short `description`, persisted as the child's creation label. */ readonly label: string + /** + * Optional caller-reserved child identity. Omission preserves the manager's + * UUID allocation; supplying one lets a durable parent record provisioning + * before child materialization without a second identity handshake. + */ + readonly childId?: SessionId /** * The delegation request. The manager reserves the stable child id, resolves * the durable descriptor, and composes the child itself. @@ -404,9 +410,10 @@ export class SubagentContinuationManager { const request = spec.request const parent = request.parent this.assertAdmitting(parent) - this.requirePersistence() + const persistence = this.requirePersistence() assertSubagentMaxDepth(request.maxDepth) - const childId = SessionId(randomUUID()) + const childId = spec.childId ?? SessionId(randomUUID()) + this.assertChildIdAvailable(childId) const childDepth = resolveChildDepth(parent, request.maxDepth) // Snapshot before any await: invalid descriptor JSON rejects the call // before a child exists, and the detached value is what reaches the log. @@ -436,6 +443,18 @@ export class SubagentContinuationManager { const lineageSeedLength = prepared.seed?.length ?? 0 const seed = seedDescriptorTurn(childId, prepared.seed, descriptor) const messageId = await this.locks.run(childId, async () => { + spec.signal.throwIfAborted() + this.assertAdmitting(parent) + this.assertChildIdAvailable(childId) + if (spec.childId !== undefined) { + const persisted = await persistence.listSnapshots(spec.signal) + spec.signal.throwIfAborted() + this.assertAdmitting(parent) + this.assertChildIdAvailable(childId) + if (persisted.some(snapshot => snapshot.header.id === childId)) { + throw new SubagentError(`subagent "${childId}" already exists`, 'DUPLICATE_CHILD') + } + } const activation = await this.materialize({ childId, provider: spec.provider, @@ -456,6 +475,13 @@ export class SubagentContinuationManager { return { childId, messageId } } + /** Reject one child identity already owned by a live Agent or Session. */ + private assertChildIdAvailable(childId: SessionId): void { + if (this.ctx.agents.get(childId) !== undefined || this.ctx.get('sessions')?.get(childId) !== undefined) { + throw new SubagentError(`subagent "${childId}" already exists`, 'DUPLICATE_CHILD') + } + } + /** * Deliver one later message to a known continuable child as its next FIFO * turn. Routing depends only on Activation residency: a `running` Activation @@ -779,10 +805,46 @@ export class SubagentContinuationManager { await this.disposeRoots(targetRoots, 'scoped activation(s)') } + /** + * Release selected resident direct children of one exact live parent without + * closing admission for the parent's other continuable children. Owned + * descendants are released recursively through the same lifecycle. + * @param parent - exact live direct parent authorizing the selected release. + * @param childIds - durable direct-child ids to release when resident. + * @returns once every selected Activation released its handle. + * @throws {SubagentError} `UNAUTHORIZED` when a resident target is not the + * parent's direct continuable child or the parent identity is stale. + */ + async drainChildren(parent: Agent, childIds: readonly SessionId[]): Promise { + if (this.ctx.agents.get(parent.id) !== parent) { + throw new SubagentError('selected child teardown requires the exact live parent agent', 'UNAUTHORIZED') + } + const targets: Activation[] = [] + for (const childId of new Set(childIds)) { + const activation = this.activations.get(childId) + if (activation === undefined) continue + if (activation.parentSession !== parent.id || !activation.ancestry.has(parent)) { + throw new SubagentError( + `subagent "${childId}" is not a direct child of agent "${parent.id}"`, + 'UNAUTHORIZED', + ) + } + targets.push(activation) + } + + // Open every transaction before the first await so cancellation propagates + // across the selected roots in one synchronous span. + for (const activation of targets) { + const disposal = this.dispose(activation) + void disposal.catch(() => undefined) + } + await this.disposeRoots(targets, 'selected activation(s)') + } + /** Dispose independent roots and report every branch failure after all settle. */ private async disposeRoots( roots: readonly Activation[], - failureSubject: 'activation(s)' | 'scoped activation(s)', + failureSubject: 'activation(s)' | 'scoped activation(s)' | 'selected activation(s)', ): Promise { const failures = await Promise.all(roots.map(async (activation) => { try { diff --git a/packages/subagent/subagent/src/index.ts b/packages/subagent/subagent/src/index.ts index fe270f1b4c..45b96a2311 100644 --- a/packages/subagent/subagent/src/index.ts +++ b/packages/subagent/subagent/src/index.ts @@ -308,6 +308,22 @@ export class SubagentRuntime extends Service { await manager.drainDescendants(parents) } + /** + * Release selected resident continuable direct children of one exact live + * parent. Other children of the same parent remain admitted and resident. + * Absent targets and a manager-less composition are accepted no-ops. + * @param parent - exact live direct parent authorizing the selected release. + * @param childIds - durable direct-child ids to release when resident. + * @returns once every selected Activation released its `AgentHandle`. + * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a + * different parent or the supplied parent identity is stale. + */ + async drainContinuableChildren(parent: Agent, childIds: readonly SessionId[]): Promise { + const manager = this.continuations + if (manager === undefined) return + await manager.drainChildren(parent, childIds) + } + /** * Enumerate the parent's direct session-backed subagents without loading or * resuming an Agent and without any query service: the listing merges the live diff --git a/packages/subagent/subagent/src/out-of-process.ts b/packages/subagent/subagent/src/out-of-process.ts index d049dba2be..abb6dd50e7 100644 --- a/packages/subagent/subagent/src/out-of-process.ts +++ b/packages/subagent/subagent/src/out-of-process.ts @@ -16,6 +16,31 @@ import { isAbsolute, resolve } from 'node:path' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { SubagentCapabilities, SubagentResult, SubagentRun, SubagentStopReason } from './types.ts' +/** Maximum UTF-8 size of {@link SubagentResult.diagnostic}. */ +const MAX_SUBAGENT_DIAGNOSTIC_BYTES = 4_096 + +const DIAGNOSTIC_TRUNCATION_SUFFIX = '\n[diagnostic truncated]' +const utf8Encoder = new TextEncoder() +const utf8Decoder = new TextDecoder() + +/** + * Limit provider-authored failure detail without splitting a UTF-8 sequence. + * @param diagnostic - safe diagnostic text produced by the provider. + * @returns the original text, or a visibly truncated value within the limit. + */ +function limitSubagentDiagnostic(diagnostic: string): string { + const bytes = utf8Encoder.encode(diagnostic) + if (bytes.byteLength <= MAX_SUBAGENT_DIAGNOSTIC_BYTES) return diagnostic + + const suffixBytes = utf8Encoder.encode(DIAGNOSTIC_TRUNCATION_SUFFIX).byteLength + let prefixBytes = MAX_SUBAGENT_DIAGNOSTIC_BYTES - suffixBytes + while (((bytes[prefixBytes] as number) & 0b1100_0000) === 0b1000_0000) { + prefixBytes -= 1 + } + return utf8Decoder.decode(bytes.subarray(0, prefixBytes)) + + DIAGNOSTIC_TRUNCATION_SUFFIX +} + /** * The capability advertisement of an out-of-process backend: NONE. A child in * another process cannot honor parent-enforced start features @@ -134,6 +159,8 @@ export interface RunResultSettlement { attempt: () => Promise /** Snapshot the provider exposes when cancellation or failure wins settlement. */ collectOutput: () => ContentBlock[] + /** Snapshot safe provider-authored detail when a failure wins settlement. */ + collectDiagnostic?: (() => string | undefined) | undefined /** Whether local cancellation settled before the attempt's outcome is observed. */ cancelled: () => boolean /** Diagnostic sink for a failure flattened to a stop reason; a throw from it is contained. */ @@ -168,7 +195,15 @@ export async function settleRunResult(parts: RunResultSettlement): Promise { expect(hasUserText(loaded.events, 'child task')).toBe(true) }) + it('uses a caller-reserved child identity and rejects a duplicate reservation', async () => { + const release = Promise.withResolvers() + const adapter = new GatedAdapter([ + { chunks: textResponse('reserved answer'), gate: release.promise }, + ]) + const { ctx, parent } = await setupWith(adapter) + const reservedId = SessionId('00000000-0000-4000-8000-000000000123') + + const started = await ctx.subagents.startContinuable({ + ...startSpec(parent), + childId: reservedId, + }) + expect(started.childId).toBe(reservedId) + await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) + + await expect(ctx.subagents.startContinuable({ + ...startSpec(parent), + childId: reservedId, + })).rejects.toMatchObject({ code: 'DUPLICATE_CHILD' }) + + release.resolve(undefined) + await waitNoActivation(ctx, reservedId) + const loaded = await ctx.sessionPersistence.load(reservedId) + expect(loaded.meta.id).toBe(reservedId) + + await expect(ctx.subagents.startContinuable({ + ...startSpec(parent), + childId: reservedId, + })).rejects.toMatchObject({ code: 'DUPLICATE_CHILD' }) + expect(ctx.agents.get(reservedId)).toBeUndefined() + }) + it('rejects without ids when the provider has no prepareContinuable capability', async () => { const { ctx, parent } = await setup([]) const start = vi.fn(async () => { throw new Error('must not dispatch') }) @@ -745,10 +777,10 @@ describe('continuable durability and teardown', () => { hold.resolve(undefined) + await waitNoActivation(ctx, started.childId) await vi.waitFor(() => { expect(warnings.some(warning => warning.includes('normal settlement cleanup failed'))).toBe(true) - }) - expect(ctx.agents.get(started.childId)).toBeUndefined() + }, { timeout: 5_000 }) }) it('disposes every live Activation forest child-first on manager teardown', async () => { @@ -873,6 +905,86 @@ describe('continuable durability and teardown', () => { await waitNoActivation(ctx, started.childId) }) + it('releases only selected direct children', async () => { + const releaseTarget = Promise.withResolvers() + const releaseSibling = Promise.withResolvers() + const releaseGrandchild = Promise.withResolvers() + const adapter = new GatedAdapter([ + { chunks: textResponse('target'), gate: releaseTarget.promise }, + { chunks: textResponse('sibling'), gate: releaseSibling.promise }, + { chunks: textResponse('grandchild'), gate: releaseGrandchild.promise }, + ]) + const { ctx, parent } = await setupWith(adapter) + const target = await ctx.subagents.startContinuable(startSpec(parent)) + const sibling = await ctx.subagents.startContinuable(startSpec(parent)) + await vi.waitFor(() => { expect(adapter.requests).toHaveLength(2) }) + const targetAgent = ctx.agents.get(target.childId)! + const siblingAgent = ctx.agents.get(sibling.childId)! + const grandchild = await ctx.subagents.startContinuable(startSpec(targetAgent)) + await vi.waitFor(() => { expect(adapter.requests).toHaveLength(3) }) + const cancel = vi.spyOn(targetAgent, 'cancel') + + const drained = ctx.subagents.drainContinuableChildren(parent, [target.childId, target.childId]) + + expect(cancel).toHaveBeenCalledWith({ kind: 'parent' }) + expect(ctx.agents.get(sibling.childId)).toBe(siblingAgent) + releaseTarget.resolve(undefined) + releaseGrandchild.resolve(undefined) + await drained + expect(ctx.agents.get(target.childId)).toBeUndefined() + expect(ctx.agents.get(grandchild.childId)).toBeUndefined() + expect(ctx.agents.get(sibling.childId)).toBe(siblingAgent) + releaseSibling.resolve(undefined) + await waitNoActivation(ctx, sibling.childId) + }) + + it('reports selected-child disposal failures after releasing the child', async () => { + const hold = Promise.withResolvers() + const adapter = new GatedAdapter([{ chunks: textResponse('target'), gate: hold.promise }]) + const { ctx, parent } = await setupWith(adapter) + const target = await ctx.subagents.startContinuable(startSpec(parent)) + await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) + const manager = (ctx.subagents as unknown as { + continuations: { activations: Map Promise } }> } + }).continuations + const activation = manager.activations.get(target.childId)! + const realDispose = activation.handle.dispose.bind(activation.handle) + activation.handle.dispose = async () => { + await realDispose() + throw new Error('selected cleanup failed') + } + + const drained = ctx.subagents.drainContinuableChildren(parent, [target.childId]) + hold.resolve(undefined) + + await expect(drained).rejects.toMatchObject({ code: 'ACTIVATION_TEARDOWN_FAILED' }) + expect(ctx.agents.get(target.childId)).toBeUndefined() + }) + + it('rejects selected-child teardown through another live parent', async () => { + const release = Promise.withResolvers() + const adapter = new GatedAdapter([{ chunks: textResponse('target'), gate: release.promise }]) + const { ctx, parent } = await setupWith(adapter) + const other = ctx.agentLoop.create(SessionId('other-parent'), { provider: 'mock', model: 'mock' }) + const target = await ctx.subagents.startContinuable(startSpec(parent)) + await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) + + await expect(ctx.subagents.drainContinuableChildren(other, [target.childId])) + .rejects.toMatchObject({ code: 'UNAUTHORIZED' }) + expect(ctx.agents.get(target.childId)).toBeDefined() + + release.resolve(undefined) + await waitNoActivation(ctx, target.childId) + }) + + it('rejects selected-child teardown through a stale parent identity', async () => { + const { ctx, parent } = await setup([]) + const stale = { ...parent, id: parent.id } as unknown as Agent + + await expect(ctx.subagents.drainContinuableChildren(stale, [])) + .rejects.toMatchObject({ code: 'UNAUTHORIZED' }) + }) + it('finds scoped descendants after an intermediate one-shot Agent leaves the registry', async () => { const releaseIntermediate = Promise.withResolvers() const releaseDescendant = Promise.withResolvers() diff --git a/packages/subagent/subagent/tests/run-settlement.spec.ts b/packages/subagent/subagent/tests/run-settlement.spec.ts index 9e13d55507..90070c8b5f 100644 --- a/packages/subagent/subagent/tests/run-settlement.spec.ts +++ b/packages/subagent/subagent/tests/run-settlement.spec.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from 'vitest' import { SessionId } from '@deepseek-ai/dsh-session' -import { settleRun } from '../src/index.ts' +import { + settleRun, + settleRunResult, +} from '../src/index.ts' + +const MAX_SUBAGENT_DIAGNOSTIC_BYTES = 4_096 describe('outcome mapping helpers', () => { it.each([ @@ -62,4 +67,51 @@ describe('outcome mapping helpers', () => { detail: 'Error: result failed; dispose failed: Error: reap failed', }) }) + + it('keeps provider diagnostics separate in failed background outcomes', async () => { + await expect(settleRun({ + id: SessionId('child-diagnostic'), + localAgent: undefined, + result: Promise.resolve({ + output: [{ type: 'text', text: 'partial assistant text' }], + diagnostic: 'Claude Code denied a tool request', + stopReason: 'error', + }), + dispose: () => Promise.resolve(), + })).resolves.toEqual({ + status: 'failed', + detail: 'error; diagnostic: Claude Code denied a tool request', + }) + }) + + it('bounds multibyte diagnostics and marks truncation', async () => { + const exact = 'x'.repeat(MAX_SUBAGENT_DIAGNOSTIC_BYTES) + const oversized = '权限'.repeat(MAX_SUBAGENT_DIAGNOSTIC_BYTES) + const controller = new AbortController() + const exactResult = await settleRunResult({ + attempt: async () => { throw new Error('provider failed') }, + collectOutput: () => [], + collectDiagnostic: () => exact, + cancelled: () => false, + signal: controller.signal, + onAbort: () => {}, + }) + expect(exactResult.diagnostic).toBe(exact) + + const result = await settleRunResult({ + attempt: async () => { throw new Error('provider failed') }, + collectOutput: () => [], + collectDiagnostic: () => oversized, + cancelled: () => false, + signal: controller.signal, + onAbort: () => {}, + }) + const limited = result.diagnostic ?? '' + expect(Buffer.byteLength(limited, 'utf8')) + .toBeLessThanOrEqual(MAX_SUBAGENT_DIAGNOSTIC_BYTES) + expect(limited.endsWith('[diagnostic truncated]')).toBe(true) + expect(limited).not.toContain('\uFFFD') + expect(result.stopReason).toBe('error') + expect(result.diagnostic).toBe(limited) + }) }) diff --git a/packages/subagent/subagent/tests/service.spec.ts b/packages/subagent/subagent/tests/service.spec.ts index e387a758e8..05e9785611 100644 --- a/packages/subagent/subagent/tests/service.spec.ts +++ b/packages/subagent/subagent/tests/service.spec.ts @@ -127,11 +127,12 @@ describe('SubagentRuntime', () => { expect('resume' in provider).toBe(false) }) - it('does not expose manager teardown and treats a scoped drain as a no-op when no manager was bound', async () => { + it('does not expose manager teardown and treats public drains as no-ops when no manager was bound', async () => { const { subagents } = await service() // Without `ctx.agents` no manager exists, so nothing was ever materialized. expect('drainContinuable' in subagents).toBe(false) await expect(subagents.drainContinuableDescendants([])).resolves.toBeUndefined() + await expect(subagents.drainContinuableChildren(fakeParent(), [SessionId('child')])).resolves.toBeUndefined() }) it('treats interrupt as an accepted no-op when no manager was bound', async () => { diff --git a/packages/subagent/tool-subagent/README.i18n.yaml b/packages/subagent/tool-subagent/README.i18n.yaml index 41f712ba34..b5e6ebf724 100644 --- a/packages/subagent/tool-subagent/README.i18n.yaml +++ b/packages/subagent/tool-subagent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/tool-subagent/README.md -README.md: 9d7ed2e364f6a9dff26a1c9006535f898bdaabcc -README.zh.md: 8650ee35588c2615e4d6c016cb672030ee2e8194 +README.md: 28e6213b903ffffa7934e244b2a74ada519b32b2 +README.zh.md: deae0f0ff9e19b627a04704eccf4b8874f34068f diff --git a/packages/subagent/tool-subagent/README.md b/packages/subagent/tool-subagent/README.md index 9d7ed2e364..28e6213b90 100644 --- a/packages/subagent/tool-subagent/README.md +++ b/packages/subagent/tool-subagent/README.md @@ -8,9 +8,9 @@ The model-facing delegation tool over one configured `ctx.subagents` provider. C Each plugin instance binds one `provider` to one `toolName`; the model receives no provider selector. Load another distinctly named instance to expose another transport. The tool registers only while its provider exists, avoiding sibling load-order and provider-reload dependencies. Its description follows `provider.inheritsParentContext`: fresh children require standalone prompts, while forked children already see completed parent turns. -A foreground call passes the execution signal through startup and execution, awaits `run.result`, and always awaits `run.dispose()` before returning. Only `completed` returns the canonical `{ kind: 'foreground', runId, output: JsonValue[] }`, rendered as the same final text; abort, refusal, token limit, and other failures become errored tool results whose message appends the child's preserved partial text (the `SubagentResult.output` selection) after the stop-reason headline, so a truncated answer is never reported as success yet never silently lost. If result collection and disposal both reject, the errored result preserves both diagnostics. +A foreground call passes the execution signal through startup and execution, awaits `run.result`, and always awaits `run.dispose()` before returning. Only `completed` returns the canonical `{ kind: 'foreground', runId, output: JsonValue[] }`, rendered as the same final text. Abort, refusal, token limit, and other failures become errored tool results whose message contains the stop-reason headline, an optional provider-authored `SubagentResult.diagnostic`, and then any preserved partial assistant text. The diagnostic remains separate from `SubagentResult.output`, so a truncated answer is never reported as success or confused with infrastructure detail. If result collection and disposal both reject, the errored result preserves both failures. -`backgroundMode` selects both the background route and the omitted `run_in_background` default. `one-shot` waits in the foreground by default; an explicit `true` registers a plain parent-owned Task and returns canonical `{ kind: 'background', jobId }`, rendered as `started background subagent job `, even when the provider supports continuable children. Generic task tools own its later status, collection, cancellation, and notices. `continuable` runs in the background when the argument is omitted or `true`; an explicit `false` waits for the result in the foreground. Its background route requires a provider with the `prepareContinuable` capability, calls `ctx.subagents.startContinuable()`, and returns `{ kind: 'continuable', subagentId }`, rendered as `started subagent `. The route resolves at inbox acceptance: the child owns its own turns from there, so this call neither waits for nor collects a result. The child's transcript by that id remains the source of its detailed output, and the optional global `send_message` tool sends it more work. The continuation service delivers one settlement notice whenever the child's Activation ends, containing its outcome and any final assistant message independently of `report`. Starting continuable work does not require `send_message` to be loaded. See the [background subagent Agent Note](../../../.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md), the [continuable subagents Agent Note](../../../.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md), and the [background-first delegation Agent Note](../../../.agents/notes/implemented/feature/2026-08-11-background-first-continuable-delegation.md). +`backgroundMode` selects both the background route and the omitted `run_in_background` default. `one-shot` waits in the foreground by default; an explicit `true` registers a plain parent-owned Task and returns canonical `{ kind: 'background', jobId }`, rendered as `started background subagent job `, even when the provider supports continuable children. Generic task tools own its later status, collection, cancellation, and notices; a failed Task keeps the stop reason and the same optional provider diagnostic in its detail. `continuable` runs in the background when the argument is omitted or `true`; an explicit `false` waits for the result in the foreground. Its background route requires a provider with the `prepareContinuable` capability, calls `ctx.subagents.startContinuable()`, and returns `{ kind: 'continuable', subagentId }`, rendered as `started subagent `. The route resolves at inbox acceptance: the child owns its own turns from there, so this call neither waits for nor collects a result. The child's transcript by that id remains the source of its detailed output, and the optional global `send_message` tool sends it more work. The continuation service delivers one settlement notice whenever the child's Activation ends, containing its outcome and any final assistant message independently of `report`. Starting continuable work does not require `send_message` to be loaded. See the [background subagent Agent Note](../../../.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md), the [continuable subagents Agent Note](../../../.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md), and the [background-first delegation Agent Note](../../../.agents/notes/implemented/feature/2026-08-11-background-first-continuable-delegation.md). `toolFilter` changes the child's global tool layer but is not a parent-derived authority ceiling. See the [agent-scope security non-goal](../../../.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md#security-and-authority-are-non-goals). @@ -51,7 +51,7 @@ Prefix-stable while provider instances, names, descriptions, and schemas are unc #### What the model sees -The call retains the description and prompt. Success contains only the child's final text; other outcomes become `Error: `. Intermediate child steps stay out of the parent. +The call retains the description and prompt. Success contains only the child's final text; other outcomes become `Error: `, followed by a safe provider diagnostic when present and then any partial assistant text. Intermediate child steps stay out of the parent. #### Token effect @@ -65,7 +65,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Start returns exactly `started subagent ` in configured continuable mode, or `started background subagent job ` in configured one-shot mode. In one-shot mode the generic task surface provides later status, final output, cancellation responses, and notices. In continuable mode this tool returns no result of its own; the child's settlement reaches the parent as a [service-owned notice](../subagent/README.md#settlement-notice), an independently loaded `send_message` tool delivers follow-ups, and the child's transcript by its id is the source of its detailed output. +Start returns exactly `started subagent ` in configured continuable mode, or `started background subagent job ` in configured one-shot mode. In one-shot mode the generic task surface provides later status, final output, cancellation responses, and notices; failed status detail includes the provider diagnostic when the result supplied one. In continuable mode this tool returns no result of its own; the child's settlement reaches the parent as a [service-owned notice](../subagent/README.md#settlement-notice), an independently loaded `send_message` tool delivers follow-ups, and the child's transcript by its id is the source of its detailed output. #### Token effect diff --git a/packages/subagent/tool-subagent/README.zh.md b/packages/subagent/tool-subagent/README.zh.md index 8650ee3558..deae0f0ff9 100644 --- a/packages/subagent/tool-subagent/README.zh.md +++ b/packages/subagent/tool-subagent/README.zh.md @@ -8,9 +8,9 @@ 每个插件实例把一个 `provider` 绑定到一个 `toolName`;模型不会收到提供方选择器。如需公开另一种传输,请加载另一个名称不同的实例。工具只在其提供方存在时注册,从而避免对同级加载顺序和提供方重新加载的依赖。工具描述遵循 `provider.inheritsParentContext`:新建子 agent(智能体)需要独立提示词,而 fork 子 agent 已能看到父级已完成轮次。 -前台调用会让执行信号贯穿启动和执行,等待 `run.result`,并且在返回前总会等待 `run.dispose()`。只有 `completed` 会返回规范值 `{ kind: 'foreground', runId, output: JsonValue[] }`,并渲染为相同的最终文本;中止、拒绝、token 上限和其他失败都会变成出错的工具结果,其消息在终止原因标题之后附带子 agent 保留下来的部分文本(即 `SubagentResult.output` 的选取结果)——被截断的回答不会被报告为成功,也绝不会被悄悄丢弃。如果结果收集与 dispose(资源释放)都 reject,出错的结果会保留两项诊断信息。 +前台调用会让执行信号贯穿启动和执行,等待 `run.result`,并且在返回前总会等待 `run.dispose()`。只有 `completed` 会返回规范值 `{ kind: 'foreground', runId, output: JsonValue[] }`,并渲染为相同的最终文本。中止、拒绝、token 上限和其他失败都会变成出错的工具结果,其消息依次包含终止原因标题、可选的提供方 `SubagentResult.diagnostic`,以及子 agent 保留下来的部分 assistant 文本。诊断与 `SubagentResult.output` 保持分离,因此被截断的回答不会被报告为成功,也不会与基础设施说明混淆。如果结果收集与 dispose(资源释放)都 reject,出错结果会保留两项失败。 -`backgroundMode` 同时选择后台路由与省略 `run_in_background` 时的默认行为。`one-shot` 默认在前台等待;显式传入 `true` 时,它会注册一个归父级所有的普通 Task,并返回规范值 `{ kind: 'background', jobId }`,渲染为 `started background subagent job `,即使提供方支持可继续子 agent 也不例外。通用 Task 工具负责其后续状态、收集、取消和通知。`continuable` 在参数省略或为 `true` 时于后台运行;显式传入 `false` 时则在前台等待结果。其后台路由要求提供方具备 `prepareContinuable` 能力,调用 `ctx.subagents.startContinuable()`,并返回 `{ kind: 'continuable', subagentId }`,渲染为 `started subagent `。该路由在 inbox 接受时结算:子 agent 自此拥有自己的轮次,因此该调用既不等待也不收集结果。通过该 id 查看其 transcript(文本记录)仍是其详细输出的来源,可选的全局 `send_message` 工具则向其发送更多工作。每当子 agent 的 Activation 结束,继续执行服务都会投递一条结算通知,其中包含结束结果及可能存在的最终 assistant 消息,且这项投递不依赖 `report`。启动可继续工作不要求加载 `send_message`。见[后台 subagent Agent Note](../../../.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md)、[可继续的 subagent Agent Note](../../../.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md)和[后台优先委派 Agent Note](../../../.agents/notes/implemented/feature/2026-08-11-background-first-continuable-delegation.md)。 +`backgroundMode` 同时选择后台路由与省略 `run_in_background` 时的默认行为。`one-shot` 默认在前台等待;显式传入 `true` 时,它会注册一个归父级所有的普通 Task,并返回规范值 `{ kind: 'background', jobId }`,渲染为 `started background subagent job `,即使提供方支持可继续子 agent 也不例外。通用 Task 工具负责其后续状态、收集、取消和通知;失败 Task 的 detail 会保留终止原因与同一份可选提供方诊断。`continuable` 在参数省略或为 `true` 时于后台运行;显式传入 `false` 时则在前台等待结果。其后台路由要求提供方具备 `prepareContinuable` 能力,调用 `ctx.subagents.startContinuable()`,并返回 `{ kind: 'continuable', subagentId }`,渲染为 `started subagent `。该路由在 inbox 接受时结算:子 agent 自此拥有自己的轮次,因此该调用既不等待也不收集结果。通过该 id 查看其 transcript(文本记录)仍是其详细输出的来源,可选的全局 `send_message` 工具则向其发送更多工作。每当子 agent 的 Activation 结束,继续执行服务都会投递一条结算通知,其中包含结束结果及可能存在的最终 assistant 消息,且这项投递不依赖 `report`。启动可继续工作不要求加载 `send_message`。见[后台 subagent Agent Note](../../../.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md)、[可继续的 subagent Agent Note](../../../.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md)和[后台优先委派 Agent Note](../../../.agents/notes/implemented/feature/2026-08-11-background-first-continuable-delegation.md)。 `toolFilter` 会改变子 agent 的全局工具层,但不是从父级派生的权限上限。见 [agent 作用域的安全非目标](../../../.agents/notes/implemented/architecture/2026-07-08-agent-scope-contexts.md#security-and-authority-are-non-goals)。 @@ -51,7 +51,7 @@ #### 模型看到的内容 -调用会保留描述和提示词。成功时只包含子 agent 的最终文本;其他结果变为 `Error: `。子 agent 中间步骤不会进入父级。 +调用会保留描述和提示词。成功时只包含子 agent 的最终文本;其他结果会变为 `Error: <终止原因>`,随后在存在时附上安全的提供方诊断,再附上任何部分 assistant 文本。子 agent 中间步骤不会进入父级。 #### Token 影响 @@ -65,7 +65,7 @@ #### 模型看到的内容 -在配置的可继续模式下,启动时返回内容恰为 `started subagent `;在配置的一次性模式下,则返回 `started background subagent job `。一次性模式下,通用 Task 接口提供后续状态、最终输出、取消响应和通知。可继续模式下,本工具不返回自己的结果;子 agent 的结算会以[服务负责的通知](../subagent/README.md#settlement-notice)到达父级,独立加载的 `send_message` 工具会投递后续消息,而通过其 id 查看子 agent 的 transcript 即是其详细输出来源。 +在配置的可继续模式下,启动时返回内容恰为 `started subagent `;在配置的一次性模式下,则返回 `started background subagent job `。一次性模式下,通用 Task 接口提供后续状态、最终输出、取消响应和通知;若结果携带提供方诊断,失败状态的 detail 会包含它。可继续模式下,本工具不返回自己的结果;子 agent 的结算会以[服务负责的通知](../subagent/README.md#settlement-notice)到达父级,独立加载的 `send_message` 工具会投递后续消息,而通过其 id 查看子 agent 的 transcript 即是其详细输出来源。 #### Token 影响 diff --git a/packages/subagent/tool-subagent/src/index.ts b/packages/subagent/tool-subagent/src/index.ts index 711ae5a7f4..86d00c6d0b 100644 --- a/packages/subagent/tool-subagent/src/index.ts +++ b/packages/subagent/tool-subagent/src/index.ts @@ -142,18 +142,25 @@ function stopReasonError(result: SubagentResult): string | undefined { } /** - * Append the child's preserved partial answer to a stop-reason error so a - * truncated or cancelled child's real text still reaches the parent model. + * Append provider-authored failure detail and the child's preserved partial + * answer to a stop-reason error, keeping diagnostic text separate from the + * child's assistant output. * @param error - the stop-reason headline. - * @param output - the child's selected output (`SubagentResult.output`). - * @returns the headline, extended with the partial text when any exists. + * @param result - the child's terminal result. + * @returns the headline, diagnostic, and partial text that are present. */ -function withPartialText(error: string, output: ContentBlock[]): string { - const text = output +function withDiagnosticAndPartialText(error: string, result: SubagentResult): string { + const diagnostic = result.diagnostic === undefined + ? '' + : `\nDiagnostic: ${result.diagnostic}` + const text = result.output .filter((block): block is Extract => block.type === 'text') .map(block => block.text) .join('') - return text.length === 0 ? error : `${error}\nPartial output before the run ended:\n${text}` + const partial = text.length === 0 + ? '' + : `\nPartial output before the run ended:\n${text}` + return `${error}${diagnostic}${partial}` } type ForegroundToolResult = { @@ -173,7 +180,7 @@ async function settleForegroundRun(run: SubagentRun): Promise /** Whether tool descriptions say the child inherits completed turns. */ @@ -65,11 +67,17 @@ class ScriptedSubagentProvider implements SubagentProvider { throw new Error('scripted subagent start aborted before publication') } - const resultFor = (): SubagentResult => ({ - output, - ...wantsStructured ? { structured: this.config.structured ?? { reply } } : {}, - stopReason: state.cancelled ? 'aborted' : stopReason, - }) + const resultFor = (): SubagentResult => { + const terminal = state.cancelled ? 'aborted' : stopReason + return { + output, + ...wantsStructured ? { structured: this.config.structured ?? { reply } } : {}, + ...this.config.diagnostic !== undefined && terminal !== 'completed' + ? { diagnostic: this.config.diagnostic } + : {}, + stopReason: terminal, + } + } const gate = Promise.resolve(this.config.onStart?.(request)) const result = gate.then(() => new Promise((resolve) => { setTimeout(() => { resolve(resultFor()) }, 0) diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index 44c0cdecb5..1ee5e40228 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -185,6 +185,22 @@ describe('dsh-tool-subagent', () => { expect(text(result)).toContain('scripted subagent reply') }) + it('renders provider diagnostics before preserved partial assistant output', async () => { + const ctx = await setup({ provider: 'mock' }, { + reply: 'partial assistant text', + diagnostic: 'Claude Code denied a tool request', + stopReason: 'error', + }) + + const result = await callSubagent(ctx, { description: 'd', prompt: 'p' }) + expect(result.isError).toBe(true) + expect(text(result)).toBe( + 'Error: subagent run failed\n' + + 'Diagnostic: Claude Code denied a tool request\n' + + 'Partial output before the run ended:\npartial assistant text', + ) + }) + it('registers under a configurable toolName so multiple providers can coexist', async () => { // The defining multi-provider use case: two loads, two distinct tool names, // each bound to a different provider — the tool registry rejects duplicate @@ -852,6 +868,36 @@ describe('dsh-tool-subagent background mode', () => { expect(text(again)).toBe('background answer\n[status: completed]') }) + it('preserves provider diagnostics in one-shot background failure detail', async () => { + const ctx = await backgroundSetup({ provider: 'mock' }, { + reply: 'not background output', + diagnostic: 'Claude Code cancelled an unattended dialog', + stopReason: 'error', + }) + const parent = ownerAgent(ctx, 'sess-parent') + + const started = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('diagnostic-background-start'), + name: 'subagent', + arguments: { description: 'd', prompt: 'p', run_in_background: true }, + agent: parent, + }) + expect(text(started)).toBe('started background subagent job subagent-1') + + const output = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('diagnostic-background-output'), + name: 'job_output', + arguments: { job_id: 'subagent-1', wait: true }, + agent: parent, + }) + expect(text(output)).toBe( + '(no new output)\n' + + '[status: failed, error; diagnostic: Claude Code cancelled an unattended dialog]', + ) + }) + it('fails loud when the tasks runtime is not loaded', async () => { const ctx = await setup({ provider: 'mock' }) const result = await callSubagent(ctx, { description: 'd', prompt: 'p', run_in_background: true }) diff --git a/packages/subprocess/subprocess-local/tests/fixtures/process-exit-host.ts b/packages/subprocess/subprocess-local/tests/fixtures/process-exit-host.ts index e59289be09..721c5134c3 100644 --- a/packages/subprocess/subprocess-local/tests/fixtures/process-exit-host.ts +++ b/packages/subprocess/subprocess-local/tests/fixtures/process-exit-host.ts @@ -13,7 +13,6 @@ if ((kind !== 'ordinary' && kind !== 'terminal') } const treeState = join(root, 'tree.json') -const ready = join(root, 'ready') const proceed = join(root, 'proceed') const managedTree = fileURLToPath(new URL('./managed-tree.ts', import.meta.url)) @@ -58,7 +57,6 @@ const published = JSON.parse(await readFile(treeState, 'utf8')) as { root?: unkn if (!Number.isSafeInteger(published.root) || !Number.isSafeInteger(published.descendant)) { throw new Error('managed tree published invalid process ids') } -await writeFile(ready, 'ready') await waitForFile(proceed) if (trigger === 'dispose') { diff --git a/packages/subprocess/subprocess-local/tests/process-exit.spec.ts b/packages/subprocess/subprocess-local/tests/process-exit.spec.ts index 217338fa1e..cfea99f12a 100644 --- a/packages/subprocess/subprocess-local/tests/process-exit.spec.ts +++ b/packages/subprocess/subprocess-local/tests/process-exit.spec.ts @@ -106,11 +106,9 @@ async function runScenario(kind: ManagedKind, trigger: ExitTrigger) { let settled = false let treeGone = false try { + // The host validates tree.json before waiting for proceed, so observing it + // is sufficient readiness; a second marker only adds a redundant Windows poll. state = await readTree(join(root, 'tree.json')) - await vi.waitFor(() => readFile(join(root, 'ready'), 'utf8'), { - interval: 10, - timeout: scenarioTimeoutMs, - }) if (process.platform !== 'win32') identities = await captureIdentities(createProcessInspector(), state) await writeFile(join(root, 'proceed'), 'proceed') const outcome = await child diff --git a/packages/test-support/llm-replay/tests/llm-replay.spec.ts b/packages/test-support/llm-replay/tests/llm-replay.spec.ts index 837f5d9af0..27356a8132 100644 --- a/packages/test-support/llm-replay/tests/llm-replay.spec.ts +++ b/packages/test-support/llm-replay/tests/llm-replay.spec.ts @@ -644,7 +644,7 @@ describe('installLlmReplay (through the real LlmRuntime)', () => { }) expect(ctx.llm.providerRetryPolicy('empty')).toMatchObject({ mode: 'normal', - maxRetries: 2, + maxRetries: 5, initialDelayMs: 500, maxDelayMs: 10_000, jitterRatio: 0.1, diff --git a/packages/util/atomic-write/README.i18n.yaml b/packages/util/atomic-write/README.i18n.yaml index d293beb656..c54e974be8 100644 --- a/packages/util/atomic-write/README.i18n.yaml +++ b/packages/util/atomic-write/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/util/atomic-write/README.md -README.md: a767f24064c368b60d85fed6fa1d88349cab9587 -README.zh.md: 6388e264898e0025fb6586acecab450be3eb9e55 +README.md: 4d0b55291955c9d37f4788c7d37ad8e6ce728f70 +README.zh.md: c2d7f0b49fa123befbb663ac43862a40b4ef19b4 diff --git a/packages/util/atomic-write/README.md b/packages/util/atomic-write/README.md index a767f24064..4d0b552919 100644 --- a/packages/util/atomic-write/README.md +++ b/packages/util/atomic-write/README.md @@ -28,7 +28,7 @@ await withFileLock('/home/u/.dsh/settings.yaml', async () => { - **Same-directory sibling** keeps the rename on one filesystem, so the swap stays atomic. - Parent directories are created; on any failure the temp is removed and the failure rethrown; readers observe either the old or the new complete content. -`withFileLock` serializes the writers of one file across processes, for the read-render-commit cycles a bare atomic commit cannot make safe on its own. The lock is a `wx`-created `.lock` sibling, so readers never contend; waiters back off exponentially and fail with a timeout rather than block forever. A contender never removes the existing lock: age cannot distinguish a crashed owner from a paused live writer. +`withFileLock` serializes the writers of one file across processes, for the read-render-commit cycles a bare atomic commit cannot make safe on its own. The lock is a `wx`-created `.lock` sibling, so readers never contend; waiters back off exponentially and fail with a timeout rather than block forever. `EEXIST` identifies contention directly; `EPERM` does so only when a fresh `lstat` confirms that the lock path exists, covering Windows exclusive-create behavior without hiding an unrelated permission failure. A contender never removes the existing lock: age cannot distinguish a crashed owner from a paused live writer. ## Model Experience diff --git a/packages/util/atomic-write/README.zh.md b/packages/util/atomic-write/README.zh.md index 6388e26489..c2d7f0b49f 100644 --- a/packages/util/atomic-write/README.zh.md +++ b/packages/util/atomic-write/README.zh.md @@ -28,7 +28,7 @@ await withFileLock('/home/u/.dsh/settings.yaml', async () => { - **同目录兄弟文件**保证 rename 落在同一文件系统上,交换保持原子。 - 自动创建父目录;任何失败都会移除临时文件并重新抛出该失败;读取方只会观察到旧内容或完整的新内容。 -`withFileLock` 跨进程串行化同一文件的写入方,服务于单靠原子提交无法保证安全的读-渲染-提交循环。锁是以 `wx` 创建的同目录 `.lock`,因此读取方从不参与竞争;等待方按指数退避,超时即失败而非无限阻塞。竞争者绝不移除现有锁:锁龄无法区分已经崩溃的所有者与被暂停但仍存活的写入方。 +`withFileLock` 跨进程串行化同一文件的写入方,服务于单靠原子提交无法保证安全的读-渲染-提交循环。锁是以 `wx` 创建的同目录 `.lock`,因此读取方从不参与竞争;等待方按指数退避,超时即失败而非无限阻塞。`EEXIST` 直接表示竞争;只有一次新的 `lstat` 确认锁路径存在时,`EPERM` 才表示竞争,从而兼容 Windows 的独占创建行为,又不掩盖无关的权限故障。竞争者绝不移除现有锁:锁龄无法区分已经崩溃的所有者与被暂停但仍存活的写入方。 ## 模型体验 diff --git a/packages/util/atomic-write/src/index.ts b/packages/util/atomic-write/src/index.ts index 70af9fa40b..21c9de5f35 100644 --- a/packages/util/atomic-write/src/index.ts +++ b/packages/util/atomic-write/src/index.ts @@ -11,7 +11,7 @@ */ import { randomBytes } from 'node:crypto' -import { mkdir, rename, rm, writeFile } from 'node:fs/promises' +import { lstat, mkdir, rename, rm, writeFile } from 'node:fs/promises' import { dirname } from 'node:path' /** @@ -63,9 +63,18 @@ export async function writeFileAtomic(filename: string, content: string, options } } -/** Whether an exclusive create failed because the path already exists. */ -function isEEXIST(error: unknown): boolean { - return (error as NodeJS.ErrnoException | null)?.code === 'EEXIST' +/** Whether an exclusive create found an existing lock. */ +async function isLockContention(error: unknown, lockPath: string): Promise { + const code = (error as NodeJS.ErrnoException | null)?.code + if (code === 'EEXIST') return true + if (code !== 'EPERM') return false + try { + await lstat(lockPath) + return true + } catch { + // Keep the original EPERM authoritative when lock existence is unproven. + return false + } } /** @@ -82,10 +91,13 @@ const LOCK_TIMEOUT_MS = 2_000 * Hold the cross-process writer lock for `filename` around one operation. The * lock is a `wx`-created sibling (`.lock`); paired with the * rename-based commit of {@link writeFileAtomic}, readers stay lock-free and - * only writers contend. Contention backs off exponentially and fails with a - * timed-out error after the deadline. The contender never removes an existing - * lock because file age cannot prove that its owner stopped; orphan recovery - * is an operator action. The parent directory must exist. + * only writers contend. `EEXIST` is contention directly; an `EPERM` is + * contention only when a fresh `lstat` confirms the lock path exists, covering + * Windows exclusive-create behavior without hiding an unrelated permission + * failure. Contention backs off exponentially and fails with a timed-out error + * after the deadline. The contender never removes an existing lock because + * file age cannot prove that its owner stopped; orphan recovery is an operator + * action. The parent directory must exist. * @param filename - the file whose writers this lock serializes. * @param operation - the read-render-commit cycle to run while holding the lock. * @returns the operation's result; the lock releases on both outcomes. @@ -102,7 +114,7 @@ export async function withFileLock( await writeFile(lockPath, `${process.pid}\n`, { mode: 0o600, flag: 'wx' }) break } catch (error) { - if (!isEEXIST(error)) throw error + if (!await isLockContention(error, lockPath)) throw error } if (Date.now() >= deadline) { throw new Error(`atomic-write: timed out waiting for the writer lock at ${lockPath}`) diff --git a/packages/util/atomic-write/tests/atomic-write.spec.ts b/packages/util/atomic-write/tests/atomic-write.spec.ts index e71e5b7abd..42cbd287c0 100644 --- a/packages/util/atomic-write/tests/atomic-write.spec.ts +++ b/packages/util/atomic-write/tests/atomic-write.spec.ts @@ -1,9 +1,29 @@ -import { lstat, mkdir, mkdtemp, readFile, readdir, stat, symlink, writeFile } from 'node:fs/promises' +import { lstat, mkdir, mkdtemp, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { withFileLock, writeFileAtomic } from '../src/index.ts' +const state = vi.hoisted(() => ({ failLockCreateWithEPERM: false })) + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeFile: (async (path: unknown, ...rest: never[]) => { + if (state.failLockCreateWithEPERM && String(path).endsWith('.lock')) { + state.failLockCreateWithEPERM = false + throw Object.assign(new Error('EPERM: injected exclusive-create failure'), { code: 'EPERM' }) + } + return (actual.writeFile as (path: unknown, ...args: never[]) => Promise)(path, ...rest) + }) as typeof actual.writeFile, + } +}) + +afterEach(() => { + state.failLockCreateWithEPERM = false +}) + async function scratch(): Promise { return mkdtemp(join(tmpdir(), 'dsh-atomic-write-')) } @@ -48,6 +68,32 @@ describe('writeFileAtomic', () => { }) describe('withFileLock', () => { + it('retries EPERM only when the lock path currently exists', async () => { + const dir = await scratch() + const target = join(dir, 'document') + const lockPath = `${target}.lock` + await writeFile(lockPath, 'holder\n') + const release = setTimeout(() => { void rm(lockPath, { force: true }) }, 50) + state.failLockCreateWithEPERM = true + let called = false + + try { + await withFileLock(target, async () => { called = true }) + } finally { + clearTimeout(release) + } + expect(called).toBe(true) + }) + + it('preserves EPERM when no lock path exists', async () => { + const dir = await scratch() + const operation = vi.fn(async () => {}) + state.failLockCreateWithEPERM = true + + await expect(withFileLock(join(dir, 'document'), operation)).rejects.toMatchObject({ code: 'EPERM' }) + expect(operation).not.toHaveBeenCalled() + }) + it('rejects an invalid parent hierarchy before running the operation', async () => { const dir = await scratch() const parent = join(dir, 'not-a-directory') diff --git a/packages/web/tool-web/README.i18n.yaml b/packages/web/tool-web/README.i18n.yaml index 2e50c2ecb2..bfba84d22d 100644 --- a/packages/web/tool-web/README.i18n.yaml +++ b/packages/web/tool-web/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/web/tool-web/README.md -README.md: 81dc4d3f3dbf9788e68b86513bfa09271fb99c84 -README.zh.md: 8e976f23f72347e12c6aea35f9b99c5d8ad31d85 +README.md: 787b70a5070f48a3bac6435d5d7e8b64c01e0341 +README.zh.md: bce95dbc0eea1bebe59b0b80cafae2a4eb948aa6 diff --git a/packages/web/tool-web/README.md b/packages/web/tool-web/README.md index 81dc4d3f3d..787b70a507 100644 --- a/packages/web/tool-web/README.md +++ b/packages/web/tool-web/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The model-facing web tool suite — `web_search` and `web_fetch` — over the [web capability seam](../web/README.md) (`ctx.web`). It owns model-facing concerns only: tool names, JSON schemas, snake_case argument names, prompt sections, the result-count bound, result formatting, HTML→markdown presentation, and the UI presentation projection — `presentCall`, `presentResult` (a `card: 'web'` result card discriminated by `kind: 'search' | 'fetch'`), and the `output.presentationMeta` that carries the structured search sources or the fetch summary the lossy render text cannot (see the [web-result-card Agent Note](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card.md)). All web access goes through `ctx.web`; this package never imports a concrete provider. Neither tool exposes a model-facing timeout — each tool's cooperative tool-call budget is declared here via config (`fetchTimeoutMs`/`searchTimeoutMs`, attached as `ToolDefinition.timeoutMs`) and enforced by [`@deepseek-ai/dsh-tool-call-timeout-policy`](../../guard/timeout-policy/README.md) (a `tools/execute` wrapper); each tool just forwards `exec.signal` to the seam. +The model-facing web tool suite — `web_search` and `web_fetch` — over the [web capability seam](../web/README.md) (`ctx.web`). It owns model-facing concerns only: tool names, JSON schemas, snake_case argument names, prompt sections, the result-count bound, result formatting, HTML→markdown presentation, and the UI presentation projection — `presentCall`, `presentResult` (a `card: 'web'` result card discriminated by `kind: 'search' | 'fetch'`), and the `output.presentationMeta` that carries the structured search sources or the fetch summary the lossy render text cannot (see the [web-result-card Agent Note](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card.md)). All web access goes through `ctx.web`; this package never imports a concrete provider. Neither tool exposes a model-facing timeout — each tool's cooperative tool-call budget is declared here via config (`fetchTimeoutMs`/`searchTimeoutMs`, attached as `ToolDefinition.timeoutMs`) and enforced by [`@deepseek-ai/dsh-tool-call-timeout-policy`](../../guard/timeout-policy/README.md) (a `tools/execute` wrapper). Single operations forward `exec.signal`; a multi-query search fuses it with batch cancellation so a failed query aborts its siblings. Each tool is registered independently; a product that wants only one disables the other via config (`{ search: false }` / `{ fetch: false }`). Search guidance mentions `web_fetch` only when fetch is also config-enabled; a search-only composition instead tells the model to use returned snippets and cite their URLs. @@ -10,7 +10,7 @@ Each tool is registered independently; a product that wants only one disables th | Tool | Args | Behavior | |---|---|---| -| `web_search` | `query` (string) | Discovery. Returns an optional answer plus source URLs. `max_results` is **not** model-facing — the tool sets the bound (the `searchMaxResults` config, default 8) and passes it to the seam. | +| `web_search` | `queries` (required string[]) | Discovery. Returns an optional answer plus source URLs. It runs one to `searchMaxQueries` distinct searches concurrently and merges their sources in round-robin order before applying the combined `searchMaxResults` cap. A one-item array performs one search. Exact duplicate queries run once. Any failed search aborts the remaining batch, which settles before the call returns an error. Neither bound is model-facing. | | `web_fetch` | `url` (string) | Retrieves a specific URL. HTML bodies are rendered to markdown (turndown with GFM tables/strikethrough); text bodies pass through. A non-2xx status is reported, not an error. The tool-call timeout is deployment policy (`dsh-tool-call-timeout-policy`), not a model argument. | Both tools opt into concurrent scheduling because provider reads return content without mutating parent-agent state. @@ -23,12 +23,13 @@ The normalized service results are also the canonical tool values: `WebSearchRes |---|---|---| | `search` | `true` | Register `web_search`. | | `fetch` | `true` | Register `web_fetch`. | -| `searchMaxResults` | `8` | Upper bound on sources returned by one `web_search` call (the seam truncates a longer provider list and flags it). | +| `searchMaxResults` | `8` | Upper bound on sources returned by one `web_search` call (the seam truncates each provider list; the tool also caps a combined multi-query list). | +| `searchMaxQueries` | `4` | Upper bound on queries accepted by one `web_search` call. The configured value appears in its prompt guidance and schema descriptions. | | `fetchTimeoutMs` | `30000` | Cooperative tool-call timeout budget (ms) for `web_fetch`. | | `searchTimeoutMs` | `30000` | Cooperative tool-call timeout budget (ms) for `web_search`. | | `fetchMaxOutputChars` | `200000` | Cap on source characters converted synchronously and on one complete `web_fetch` output (header, rendered body, and footer); a cut body gets the truncation notice when it fits. | -`fetchTimeoutMs`/`searchTimeoutMs` declare each tool's cooperative timeout budget (attached as `ToolDefinition.timeoutMs`), enforced by [`@deepseek-ai/dsh-tool-call-timeout-policy`](../../guard/timeout-policy/README.md); the model-facing schema exposes no timeout argument. `fetchMaxOutputChars` bounds both synchronous conversion work and the complete rendered result: only that many source characters are converted, and the header, converted prefix, and truncation notice are then capped together. The default leaves headroom above the local provider's 100,000-character body cap, but rendered expansion can still make the final bound truncate the result. +`searchMaxQueries` bounds the accepted array before exact-string deduplication, provider fan-out, and combined provider-answer growth; validation rejects an oversized array before any search starts, then dispatch keeps the first occurrence of each query. Together with each provider's own controls such as `maxUses`, these independent settings are the product's search budgets; the generic seam does not expose provider-internal native-search accounting. `fetchTimeoutMs`/`searchTimeoutMs` declare each tool's cooperative timeout budget (attached as `ToolDefinition.timeoutMs`), enforced by [`@deepseek-ai/dsh-tool-call-timeout-policy`](../../guard/timeout-policy/README.md); the model-facing schema exposes no timeout argument. `fetchMaxOutputChars` bounds both synchronous conversion work and the complete rendered result: only that many source characters are converted, and the header, converted prefix, and truncation notice are then capped together. The default leaves headroom above the local provider's 100,000-character body cap, but rendered expansion can still make the final bound truncate the result. ```yaml - id: tool-web @@ -52,13 +53,13 @@ Search and fetch contribute the web-search and web-fetch guidance below. Search ##### Web search guidance with fetch enabled ```markdown -Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links. +Use the web_search tool to discover current information on the web. The required queries array accepts 1–4 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links. ``` ##### Web search-only guidance ```markdown -Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links. +Use the web_search tool to discover current information on the web. The required queries array accepts 1–4 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links. ``` ##### Web fetch guidance @@ -69,11 +70,11 @@ Use the web_fetch tool to retrieve the content of a specific HTTP(S) URL (for ex #### Token effect -Fixed guidance cost per request for each config-enabled tool, even when a restriction hides its schema. Toggling fetch changes the search guidance as well as registering or removing the fetch section. +Fixed guidance cost per request for each config-enabled tool, even when a restriction hides its schema. Toggling fetch or changing `searchMaxQueries` changes the search guidance; toggling fetch also registers or removes the fetch section. #### KV Cache effect -Prefix-stable while enabled tools, scope, and guidance text are unchanged. Config enablement—including toggling fetch's search-guidance branch—or plugin lifecycle may invalidate reuse from the first changed prompt section; scoped schema restrictions do not remove it. +Prefix-stable while enabled tools, scope, and guidance text are unchanged. Config enablement—including toggling fetch's search-guidance branch—changing `searchMaxQueries`, or plugin lifecycle may invalidate reuse from the first changed prompt section; scoped schema restrictions do not remove it. ### Tool schemas @@ -83,26 +84,40 @@ The model sees the generated [`web_search` and `web_fetch` schemas](../../../doc #### Token effect -Fixed schema cost per request; config disablement removes both schema and guidance, while a scoped restriction removes only the schema. +Fixed schema cost per request for a resolved `searchMaxQueries`; config disablement removes both schema and guidance, while a scoped restriction removes only the schema. #### KV Cache effect -Prefix-stable while definitions and visibility are unchanged. Config enablement, plugin lifecycle, or scoped restrictions may invalidate reuse from the first changed schema token. +Prefix-stable while definitions, resolved query cap, and visibility are unchanged. Config enablement, changing `searchMaxQueries`, plugin lifecycle, or scoped restrictions may invalidate reuse from the first changed schema token. ### Search result #### What the model sees -The optional provider-owned answer is followed by `Sources:` and data-dependent lines shaped exactly `- []()`, optionally suffixed ` — ()`. With neither answer nor sources the result says `No results found.` A capped list adds `(Showing the first sources. Refine the query for more.)`; every result ends `Cite the relevant URLs above as markdown links in your answer.` +The optional provider-owned answer is followed by `Sources:` and data-dependent lines shaped exactly `- []()`, optionally suffixed ` — ()`. A multi-query call runs each exact query string once, preserving its first position; it labels each provider answer with the originating query as a markdown heading, deduplicates sources by URL, and takes one source at each rank from every query before advancing to the next rank. With neither answer nor sources the result says `No results found.` A capped list adds `(Showing the first sources. Refine the query for more.)`; every result ends `Cite the relevant URLs above as markdown links in your answer.` #### Token effect -Data-dependent results are resent until compaction and sources are capped by `searchMaxResults`. +Data-dependent results are resent until compaction; query fan-out is capped by `searchMaxQueries`, and sources are capped by `searchMaxResults`. #### KV Cache effect Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries. +### Search failure + +#### What the model sees + +If any query in a multi-query call fails, `web_search` aborts the other searches, waits for every started search to settle, discards successful results, and returns `Error: ` for the first failure. + +#### Token effect + +Only the retained error result adds tokens; discarded successful results do not enter model history. + +#### KV Cache effect + +Append-only; the error follows the reusable request prefix and does not invalidate existing KV-cache entries. + ### Fetch result #### What the model sees @@ -121,7 +136,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Blank inputs become exactly `Error: query must be a non-empty string` or `Error: url must be a non-empty string`. +Schema validation rejects an absent or non-array `queries` field and non-string array elements before execution. Value errors become exactly `Error: queries must contain at least one query`, `Error: queries must contain at most 1 query` when the configured cap is one, `Error: queries must contain at most queries` for larger caps, `Error: each query must be a non-empty string`, or `Error: url must be a non-empty string`. #### Token effect @@ -133,6 +148,7 @@ Append-only; newly visible content follows the reusable request prefix and does ## Known Limitations and Deferred Work +- **There is no batch-wide native-search counter** — `searchMaxQueries` bounds `ctx.web.search` calls, but a provider may perform several native searches inside each call. For example, a model-backed provider configured with `maxUses` can permit up to `searchMaxQueries × maxUses` native searches; `searchMaxResults` limits only the combined sources returned to the caller. Deployments control cost through these independent consumer and provider settings because the generic seam does not know provider-internal search units. - **HTML→markdown conversion degrades on inputs GFM cannot safely represent** — [turndown](https://github.com/mixmark-io/turndown) (with GFM tables/strikethrough) converts at most `fetchMaxOutputChars` source characters through a real DOM. A conservative 512-level lexical guard passes deeply or ambiguously nested bodies through as raw HTML, conversion exceptions do the same, and table `colspan` is ignored because GFM has no spanning-cell representation; these bounds avoid blocking the event loop or expanding output from an untrusted numeric attribute ([archived dependency decision](../../../.agents/notes/archived/simplification/2026-07-26-turndown-for-tool-web-html-markdown.md)). - **The model-facing API is minimal by design, with promotions deferred** — `max_results` stays a config bound (not a model argument), and `web_fetch` takes only `url` (no `format`/`prompt`/LLM-summarization mode); both are named later steps in [the seam Agent Note](../../../.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md). - **No web-specific permission policy** — both tools execute without requesting `ctx.approval`; a deployment that needs confirmation must add a `tools/pre-execute` policy, and the package does not define persistent URL/domain grants. diff --git a/packages/web/tool-web/README.zh.md b/packages/web/tool-web/README.zh.md index 8e976f23f7..bce95dbc0e 100644 --- a/packages/web/tool-web/README.zh.md +++ b/packages/web/tool-web/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -面向模型的 web 工具套件 `web_search` 与 `web_fetch`,构建于 [web 能力 seam](../web/README.md)(`ctx.web`)之上。它只负责面向模型的事项:工具名称、JSON Schema、snake_case 参数名称、提示词区段、结果数量上限、结果格式、HTML→markdown 呈现,以及 UI 呈现投影——`presentCall`、`presentResult`(以 `kind: 'search' | 'fetch'` 区分的 `card: 'web'` 结果卡片),以及承载有损渲染文本无法携带的结构化搜索来源或抓取摘要的 `output.presentationMeta`(见 [web-result-card Agent Note](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card.md))。所有 web 访问都通过 `ctx.web`;该包绝不导入具体提供方。两个工具都不公开面向模型的超时:每个工具的协作式工具调用超时预算通过配置在此声明(`fetchTimeoutMs`/`searchTimeoutMs`,附加为 `ToolDefinition.timeoutMs`),由 [`@deepseek-ai/dsh-tool-call-timeout-policy`](../../guard/timeout-policy/README.md)(`tools/execute` 包装层)强制执行;每个工具只把 `exec.signal` 转发给 seam。 +面向模型的 web 工具套件 `web_search` 与 `web_fetch`,构建于 [web 能力 seam](../web/README.md)(`ctx.web`)之上。它只负责面向模型的事项:工具名称、JSON Schema、snake_case 参数名称、提示词区段、结果数量上限、结果格式、HTML→markdown 呈现,以及 UI 呈现投影——`presentCall`、`presentResult`(以 `kind: 'search' | 'fetch'` 区分的 `card: 'web'` 结果卡片),以及承载有损渲染文本无法携带的结构化搜索来源或抓取摘要的 `output.presentationMeta`(见 [web-result-card Agent Note](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card.md))。所有 web 访问都通过 `ctx.web`;该包绝不导入具体提供方。两个工具都不公开面向模型的超时:每个工具的协作式工具调用超时预算通过配置在此声明(`fetchTimeoutMs`/`searchTimeoutMs`,附加为 `ToolDefinition.timeoutMs`),由 [`@deepseek-ai/dsh-tool-call-timeout-policy`](../../guard/timeout-policy/README.md)(`tools/execute` 包装层)强制执行。单项操作会转发 `exec.signal`;多查询搜索会把它与批次取消信号融合,使失败查询能够中止其余查询。 每个工具独立注册;只需要其中一个工具的产品可以通过配置禁用另一个(`{ search: false }`/`{ fetch: false }`)。仅当抓取也通过配置启用时,搜索指引才会提及 `web_fetch`;仅启用搜索的组合则会要求模型使用返回的 snippet 并引用其 URL。 @@ -10,7 +10,7 @@ | 工具 | 参数 | 行为 | |---|---|---| -| `web_search` | `query`(string) | 用于发现信息。返回可选答案与来源 URL。`max_results` **不**面向模型:工具设置上限(`searchMaxResults` 配置,默认 8)并传给 seam。 | +| `web_search` | `queries`(必填 string[]) | 用于发现信息。返回可选答案与来源 URL。它会并发执行 1 至 `searchMaxQueries` 个不同搜索,按轮询顺序合并来源,再应用组合后的 `searchMaxResults` 上限。单元素数组执行一次搜索。完全相同的查询只执行一次。任何搜索失败都会中止批次中的其余搜索;批次结算完毕后调用才返回错误。两个上限都不面向模型。 | | `web_fetch` | `url`(string) | 获取特定 URL。HTML 主体渲染为 markdown(turndown,带 GFM 表格/删除线);文本主体原样通过。非 2xx 状态会报告,而非报错。工具调用超时是部署策略(`dsh-tool-call-timeout-policy`),不是模型参数。 | 两个工具都选择并发调度,因为提供方读取会返回内容,不会修改父 agent(智能体)的状态。 @@ -23,12 +23,13 @@ |---|---|---| | `search` | `true` | 注册 `web_search`。 | | `fetch` | `true` | 注册 `web_fetch`。 | -| `searchMaxResults` | `8` | 一次 `web_search` 调用返回的来源数量上限(seam 截断更长的提供方列表并标记)。 | +| `searchMaxResults` | `8` | 一次 `web_search` 调用返回的来源数量上限(seam 截断各提供方列表;工具还会限制多查询组合列表)。 | +| `searchMaxQueries` | `4` | 一次 `web_search` 调用接受的查询数量上限。配置值会出现在提示词指引与 schema 描述中。 | | `fetchTimeoutMs` | `30000` | `web_fetch` 的协作式工具调用超时预算(ms)。 | | `searchTimeoutMs` | `30000` | `web_search` 的协作式工具调用超时预算(ms)。 | | `fetchMaxOutputChars` | `200000` | 同步转换的源字符数与单次完整 `web_fetch` 输出的上限(状态头、渲染后的主体与页脚合并计算);主体被截断时,在能容纳的情况下附带截断提示。 | -`fetchTimeoutMs`/`searchTimeoutMs` 声明每个工具的协作式超时预算(附加为 `ToolDefinition.timeoutMs`),由 [`@deepseek-ai/dsh-tool-call-timeout-policy`](../../guard/timeout-policy/README.md) 强制执行;面向模型的 schema 不公开超时参数。`fetchMaxOutputChars` 同时限制同步转换工作量和完整渲染结果:只转换至多该数量的源字符,随后对状态头、转换后的前缀和截断提示合并设限。默认值为本地提供方的 100,000 字符主体上限留出余量,但渲染膨胀仍可能使最终上限截断结果。 +`searchMaxQueries` 在完全相同的字符串去重前限制可接受数组、提供方请求扇出与组合后的提供方答案增长;校验会在任何搜索开始前拒绝超限数组,随后分发只保留每个查询第一次出现的位置。该设置与各提供方自己的 `maxUses` 等控制项共同构成产品的搜索预算;通用 seam 不公开提供方内部的原生搜索计数。`fetchTimeoutMs`/`searchTimeoutMs` 声明每个工具的协作式超时预算(附加为 `ToolDefinition.timeoutMs`),由 [`@deepseek-ai/dsh-tool-call-timeout-policy`](../../guard/timeout-policy/README.md) 强制执行;面向模型的 schema 不公开超时参数。`fetchMaxOutputChars` 同时限制同步转换工作量和完整渲染结果:只转换至多该数量的源字符,随后对状态头、转换后的前缀和截断提示合并设限。默认值为本地提供方的 100,000 字符主体上限留出余量,但渲染膨胀仍可能使最终上限截断结果。 ```yaml - id: tool-web @@ -52,13 +53,13 @@ ##### 启用抓取时的 Web 搜索指引 ```markdown -Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links. +Use the web_search tool to discover current information on the web. The required queries array accepts 1–4 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links. ``` ##### 仅搜索时的 Web 搜索指引 ```markdown -Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links. +Use the web_search tool to discover current information on the web. The required queries array accepts 1–4 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links. ``` ##### Web 抓取指引 @@ -69,11 +70,11 @@ Use the web_fetch tool to retrieve the content of a specific HTTP(S) URL (for ex #### Token 影响 -每个通过配置启用的工具都会为每次请求增加固定的指引 token 开销,即使限制隐藏了其 schema。切换抓取状态不仅会注册或移除抓取区段,也会更改搜索指引。 +每个通过配置启用的工具都会为每次请求增加固定的指引 token 开销,即使限制隐藏了其 schema。切换抓取状态或更改 `searchMaxQueries` 会改变搜索指引;切换抓取状态还会注册或移除抓取区段。 #### KV Cache 影响 -只要启用工具、scope 与指引文本不变,前缀就保持稳定。配置启用状态(包括因切换抓取状态而改变搜索指引分支)或插件生命周期可能使从第一个变化的提示词区段起的复用失效;scope schema 限制不会移除该区段。 +只要启用工具、scope 与指引文本不变,前缀就保持稳定。配置启用状态(包括因切换抓取状态而改变搜索指引分支)、更改 `searchMaxQueries` 或插件生命周期可能使从第一个变化的提示词区段起的复用失效;scope schema 限制不会移除该区段。 ### 工具 schema @@ -83,26 +84,40 @@ Use the web_fetch tool to retrieve the content of a specific HTTP(S) URL (for ex #### Token 影响 -每次请求都会产生固定的 schema token 开销;通过配置禁用会同时移除 schema 与指引,scope 限制只移除 schema。 +对于已解析的 `searchMaxQueries`,每次请求都会产生固定的 schema token 开销;通过配置禁用会同时移除 schema 与指引,scope 限制只移除 schema。 #### KV Cache 影响 -只要定义与可见性不变,前缀就保持稳定。配置启用状态、插件生命周期或 scope 限制可能使从第一个变化的 schema token 起的复用失效。 +只要定义、已解析查询上限与可见性不变,前缀就保持稳定。配置启用状态、更改 `searchMaxQueries`、插件生命周期或 scope 限制可能使从第一个变化的 schema token 起的复用失效。 ### 搜索结果 #### 模型看到的内容 -可选的提供方答案之后是 `Sources:`,再跟随内容取决于数据且格式严格为 `- []()` 的行,并可添加后缀 ` — ()`。既无答案也无来源时,结果显示 `No results found.`。列表被截断至上限时会添加 `(Showing the first sources. Refine the query for more.)`;每个结果都以 `Cite the relevant URLs above as markdown links in your answer.` 结尾。 +可选的提供方答案之后是 `Sources:`,再跟随内容取决于数据且格式严格为 `- []()` 的行,并可添加后缀 ` — ()`。多查询调用会让每个完全相同的查询字符串只执行一次,并保留它首次出现的位置;调用会用来源查询作为 markdown 标题标注每个提供方答案,按 URL 对来源去重,并从每个查询取得同一排名的一条来源后再推进至下一排名。既无答案也无来源时,结果显示 `No results found.`。列表被截断至上限时会添加 `(Showing the first sources. Refine the query for more.)`;每个结果都以 `Cite the relevant URLs above as markdown links in your answer.` 结尾。 #### Token 影响 -数据相关结果会重复发送直到压缩(compaction),来源数量由 `searchMaxResults` 限制。 +数据相关结果会重复发送直到压缩(compaction);查询请求扇出由 `searchMaxQueries` 限制,来源数量由 `searchMaxResults` 限制。 #### KV Cache 影响 仅追加;新可见内容位于可复用请求前缀之后,不会使现有 KV Cache 条目失效。 +### 搜索失败 + +#### 模型看到的内容 + +多查询调用中的任何查询失败时,`web_search` 会中止其余搜索,等待所有已启动搜索结算,丢弃成功结果,并针对首次失败返回 `Error: `。 + +#### Token 影响 + +只有保留的错误结果会增加 token;被丢弃的成功结果不会进入模型历史。 + +#### KV Cache 影响 + +仅追加;错误位于可复用请求前缀之后,不会使现有 KV Cache 条目失效。 + ### 抓取结果 #### 模型看到的内容 @@ -121,7 +136,7 @@ Use the web_fetch tool to retrieve the content of a specific HTTP(S) URL (for ex #### 模型看到的内容 -空输入精确地变为 `Error: query must be a non-empty string` 或 `Error: url must be a non-empty string`。 +schema 校验会在执行前拒绝缺失或非数组的 `queries` 字段以及非字符串数组元素。值错误精确地变为 `Error: queries must contain at least one query`、配置上限为 1 时的 `Error: queries must contain at most 1 query`、上限更大时的 `Error: queries must contain at most queries`、`Error: each query must be a non-empty string` 或 `Error: url must be a non-empty string`。 #### Token 影响 @@ -133,6 +148,7 @@ Use the web_fetch tool to retrieve the content of a specific HTTP(S) URL (for ex ## 已知限制与暂缓事项 +- **没有覆盖整个批次的原生搜索计数器**:`searchMaxQueries` 限制 `ctx.web.search` 调用数,但提供方可以在每次调用内执行多次原生搜索。例如,配置了 `maxUses` 的模型型提供方最多可以执行 `searchMaxQueries × maxUses` 次原生搜索;`searchMaxResults` 只限制返回给调用方的组合来源。部署通过这些独立的消费方与提供方设置控制成本,因为通用 seam 不知道提供方内部的搜索计量单位。 - **HTML→markdown 转换会在 GFM 无法安全表示的输入上降级**:[turndown](https://github.com/mixmark-io/turndown)(带 GFM 表格/删除线)通过真实 DOM 转换至多 `fetchMaxOutputChars` 个源字符。保守的 512 层词法守卫会将深层或嵌套有歧义的主体作为原始 HTML 直接透传,转换异常也会如此处理;表格的 `colspan` 会被忽略,因为 GFM 无法表示跨列单元格。这些限制可避免阻塞事件循环,也避免不受信任的数值属性使输出膨胀([已归档的依赖决策](../../../.agents/notes/archived/simplification/2026-07-26-turndown-for-tool-web-html-markdown.md))。 - **面向模型的接口有意保持精简,后续扩展暂缓**:`max_results` 保持为配置上限(不是模型参数),`web_fetch` 只接受 `url`(没有 `format`/`prompt`/LLM(大语言模型)摘要模式);两项都列为 [seam Agent Note](../../../.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md) 中的后续步骤。 - **没有 web 专用权限策略**:两个工具都不会请求 `ctx.approval` 就直接执行;需要确认的部署必须添加 `tools/pre-execute` 策略,该包不定义持久化的 URL/域名授权。 diff --git a/packages/web/tool-web/src/index.ts b/packages/web/tool-web/src/index.ts index a0dcfaa09d..4145fdeb0f 100644 --- a/packages/web/tool-web/src/index.ts +++ b/packages/web/tool-web/src/index.ts @@ -9,10 +9,10 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-web' -import { applyWebSearchTool, WEB_SEARCH_MAX_RESULTS } from './search.ts' +import { applyWebSearchTool, WEB_SEARCH_MAX_QUERIES, WEB_SEARCH_MAX_RESULTS } from './search.ts' import { applyWebFetchTool } from './fetch.ts' -export { WEB_SEARCH_MAX_RESULTS, applyWebSearchTool, formatSearchOutput, parseSearchArgs, presentSearchCall, presentSearchResult, searchMetaFromValue, searchMetaFromResult } from './search.ts' +export { WEB_SEARCH_MAX_QUERIES, WEB_SEARCH_MAX_RESULTS, applyWebSearchTool, formatSearchOutput, presentSearchCall, presentSearchResult, searchMetaFromValue, searchMetaFromResult } from './search.ts' export type { WebSearchMeta } from './search.ts' export { applyWebFetchTool, formatFetchOutput, parseFetchArgs, presentFetchCall, presentFetchResult, fetchMetaFromValue, fetchMetaFromResult } from './fetch.ts' export type { WebFetchMeta } from './fetch.ts' @@ -33,7 +33,7 @@ export const DEFAULT_WEB_TOOL_TIMEOUT_MS = 30_000 */ export const DEFAULT_FETCH_MAX_OUTPUT_CHARS = 200_000 -/** Plugin config: which web tools to register, the source cap, per-tool budgets, and the fetch output cap. */ +/** Plugin config: which web tools to register, search bounds, per-tool budgets, and the fetch output cap. */ export interface Config { /** Register `web_search`. Defaults to true. */ search?: boolean @@ -41,6 +41,8 @@ export interface Config { fetch?: boolean /** Upper bound on sources returned by one `web_search` call. */ searchMaxResults?: number + /** Upper bound on queries accepted by one `web_search` call. */ + searchMaxQueries?: number /** Cooperative timeout budget (ms) for `web_fetch`. Defaults to 30000. */ fetchTimeoutMs?: number /** Cooperative timeout budget (ms) for `web_search`. Defaults to 30000. */ @@ -53,6 +55,7 @@ export const Config: z = z.object({ search: z.boolean().default(true), fetch: z.boolean().default(true), searchMaxResults: z.number().default(WEB_SEARCH_MAX_RESULTS), + searchMaxQueries: z.number().default(WEB_SEARCH_MAX_QUERIES), fetchTimeoutMs: z.number().default(DEFAULT_WEB_TOOL_TIMEOUT_MS), searchTimeoutMs: z.number().default(DEFAULT_WEB_TOOL_TIMEOUT_MS), fetchMaxOutputChars: z.number().default(DEFAULT_FETCH_MAX_OUTPUT_CHARS), @@ -81,11 +84,12 @@ export function apply(ctx: Context, config: Config): void { // schemastery (Config) has already filled every defaulted field. const resolved = config as ResolvedConfig assertPositiveInteger('searchMaxResults', resolved.searchMaxResults) + assertPositiveInteger('searchMaxQueries', resolved.searchMaxQueries) assertPositiveInteger('fetchTimeoutMs', resolved.fetchTimeoutMs) assertPositiveInteger('searchTimeoutMs', resolved.searchTimeoutMs) assertPositiveInteger('fetchMaxOutputChars', resolved.fetchMaxOutputChars) if (resolved.search) { - applyWebSearchTool(ctx, resolved.searchMaxResults, resolved.searchTimeoutMs, resolved.fetch) + applyWebSearchTool(ctx, resolved.searchMaxResults, resolved.searchMaxQueries, resolved.searchTimeoutMs, resolved.fetch) } if (resolved.fetch) applyWebFetchTool(ctx, resolved.fetchTimeoutMs, resolved.fetchMaxOutputChars) } diff --git a/packages/web/tool-web/src/search.ts b/packages/web/tool-web/src/search.ts index d3c4acc756..c5acac7515 100644 --- a/packages/web/tool-web/src/search.ts +++ b/packages/web/tool-web/src/search.ts @@ -19,16 +19,36 @@ import type {} from '@deepseek-ai/dsh-system-prompt' */ export const WEB_SEARCH_MAX_RESULTS = 8 +/** Default upper bound on concurrent searches in one tool call. */ +export const WEB_SEARCH_MAX_QUERIES = 4 + +/** Model-facing `web_search` arguments. */ +interface WebSearchArgs { + queries: string[] +} + /** - * Validate value constraints the schema DSL can't express: a non-blank - * `query`. Throws a plain `Error` otherwise. + * Validate value constraints the schema DSL can't express: `queries` is + * non-empty, contains only non-blank strings, and fits the deployment's + * query-count bound. Exact duplicate strings are collapsed after the bound + * check. Throws a plain `Error` otherwise. * * @param args - the schema-validated `web_search` arguments. - * @returns the accepted arguments, passed through unchanged. + * @param maxQueries - the deployment's upper bound on queries in one call. + * @returns the accepted queries in their first-occurrence order. */ -export function parseSearchArgs(args: { query: string }): { query: string } { - if (args.query.trim().length === 0) throw new Error('query must be a non-empty string') - return { query: args.query } +export function parseSearchArgs( + args: WebSearchArgs, + maxQueries: number, +): string[] { + const queries = args.queries + if (queries.length === 0) throw new Error('queries must contain at least one query') + if (queries.length > maxQueries) { + const noun = maxQueries === 1 ? 'query' : 'queries' + throw new Error(`queries must contain at most ${maxQueries} ${noun}`) + } + if (queries.some(query => query.trim().length === 0)) throw new Error('each query must be a non-empty string') + return [...new Set(queries)] } /** Display label for a source: its title, else its hostname. */ @@ -75,13 +95,14 @@ export function formatSearchOutput(result: WebSearchResult): string { } /** - * Pending-call presentation: a search card titled by the query. + * Pending-call presentation: a search card titled by the query list. * - * @param args - the raw tool arguments; only `query` feeds the view. + * @param args - the raw tool arguments; only the query text feeds the view. * @returns the generic card view (`kind: 'search'`) shown while the call runs. */ -export function presentSearchCall(args: { query: string }): GenericCallView { - return { card: 'generic', title: args.query, kind: 'search', rawInput: args.query } +export function presentSearchCall(args: WebSearchArgs): GenericCallView { + const title = args.queries.join(', ') + return { card: 'generic', title, kind: 'search', rawInput: title } } /** @@ -95,7 +116,7 @@ export function presentSearchCall(args: { query: string }): GenericCallView { export interface WebSearchMeta { /** The faithful structured sources, in result order. */ sources: WebSource[] - /** True when the seam cut the source list to honor the result cap. */ + /** True when the seam or multi-query merge cut the source list to honor the result cap. */ truncated: boolean /** The provider-generated answer text, when any. */ answer?: string @@ -175,26 +196,103 @@ export function searchMetaFromResult(meta: unknown): WebSearchMeta | undefined { * `web` capability falls back to the raw `tool/result` content, which is the * same text (see the web-result-card Agent Note). * - * @param args - the raw tool arguments; `query` becomes the result-state title so - * a window-truncated replay that dropped the call head still has one. + * @param args - the raw tool arguments; the queries become the result-state + * title so a window-truncated replay that dropped the call head still has one. * @param result - the final model-facing tool result; `meta` carries the sources. * @returns the search result view, or `undefined` (generic card) on failure or * malformed meta. */ -export function presentSearchResult(args: { query: string }, result: ToolResult): WebSearchResultView | undefined { +export function presentSearchResult(args: WebSearchArgs, result: ToolResult): WebSearchResultView | undefined { if (result.isError) return undefined const meta = searchMetaFromResult(result.meta) if (meta === undefined) return undefined return { card: 'web', kind: 'search', - title: args.query, + title: args.queries.join(', '), sources: meta.sources, truncated: meta.truncated, ...meta.answer !== undefined ? { answer: meta.answer } : {}, } } +/** + * Run one or more searches through the web seam. A single query keeps the + * provider's exact result; multiple queries run concurrently and are merged + * into one normalized result capped at `maxResults`. A failed search aborts + * its siblings, and this function waits for every search to settle before + * rethrowing the first failure. + * + * @param ctx - context whose `web` service performs the searches. + * @param queries - validated non-empty queries. + * @param maxResults - the deployment's source cap for the combined result. + * @param signal - cancellation signal forwarded to every search. + * @returns the combined search result. + */ +async function runSearchQueries( + ctx: Context, + queries: string[], + maxResults: number, + signal: AbortSignal, +): Promise { + if (queries.length === 1) { + return ctx.web.search({ query: queries[0] as string, maxResults }, signal) + } + const controller = new AbortController() + const batchSignal = AbortSignal.any([signal, controller.signal]) + let firstFailure: { error: unknown } | undefined + const results: WebSearchResult[] = [] + const searches = queries.map(async (query, index) => { + try { + results[index] = await ctx.web.search({ query, maxResults }, batchSignal) + } catch (error) { + if (firstFailure === undefined) firstFailure = { error } + controller.abort(error) + throw error + } + }) + await Promise.allSettled(searches) + if (firstFailure !== undefined) throw firstFailure.error + return mergeSearchResults(queries, results, maxResults) +} + +/** Merge per-query results into one deduplicated, round-robin, capped result. */ +function mergeSearchResults( + queries: string[], + results: WebSearchResult[], + maxResults: number, +): WebSearchResult { + const seen = new Set() + const sources: WebSearchSource[] = [] + let sourceRanks = 0 + for (const result of results) { + sourceRanks = Math.max(sourceRanks, result.sources.length) + } + let droppedSource = false + merge: for (let rank = 0; rank < sourceRanks; rank++) { + for (const result of results) { + const source = result.sources[rank] + if (source !== undefined && !seen.has(source.url)) { + seen.add(source.url) + if (sources.length === maxResults) { + droppedSource = true + break merge + } + sources.push(source) + } + } + } + const contents = results.flatMap((result, index) => { + if (result.content === undefined || result.content.length === 0) return [] + return [`### ${queries[index]}\n\n${result.content}`] + }) + return { + ...contents.length > 0 ? { content: contents.join('\n\n') } : {}, + sources, + truncated: results.some(result => result.truncated) || droppedSource, + } +} + /** * Register the `web_search` tool and its system-prompt guidance. * @@ -202,6 +300,7 @@ export function presentSearchResult(args: { query: string }, result: ToolResult) * registrations; both are effect-scoped and unregister on plugin dispose. * @param maxResults - the deployment's source cap, sent as every seam * request's `maxResults`. + * @param maxQueries - the deployment's query cap enforced before provider calls. * @param timeoutMs - the cooperative tool-call budget (ms) attached as the tool's * `ToolDefinition.timeoutMs` for `@deepseek-ai/dsh-tool-call-timeout-policy` to enforce. * @param fetchEnabled - whether the same composition exposes `web_fetch`, which @@ -210,6 +309,7 @@ export function presentSearchResult(args: { query: string }, result: ToolResult) export function applyWebSearchTool( ctx: Context, maxResults: number, + maxQueries: number, timeoutMs: number, fetchEnabled: boolean, ): void { @@ -217,15 +317,20 @@ export function applyWebSearchTool( name: 'tool:web_search', order: 110, text: fetchEnabled - ? 'Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.' - : 'Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links.', + ? `Use the web_search tool to discover current information on the web. The required queries array accepts 1–${maxQueries} non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.` + : `Use the web_search tool to discover current information on the web. The required queries array accepts 1–${maxQueries} non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links.`, }) ctx.tools.register(defineTool({ name: 'web_search', - description: 'Search the web for current information. Returns an optional summary answer and a list of source URLs.', + description: `Search the web for current information. Provide 1–${maxQueries} queries in the required queries array. Returns an optional summary answer and a list of source URLs.`, parameters: { - query: { type: 'string', required: true, description: 'The search query.' }, + queries: { + type: 'array', + required: true, + items: { type: 'string' }, + description: `Required search queries; accepts 1–${maxQueries} items and merges their results.`, + }, }, output: { schema: { @@ -257,11 +362,8 @@ export function applyWebSearchTool( // Provider reads do not mutate parent-agent state. isConcurrencySafe: () => true, async execute(args, exec) { - const input = parseSearchArgs(args) - const result = await ctx.web.search( - { query: input.query, maxResults }, - exec.signal, - ) + const queries = parseSearchArgs(args, maxQueries) + const result = await runSearchQueries(ctx, queries, maxResults, exec.signal) return { ...result.content !== undefined ? { content: result.content } : {}, sources: result.sources.map(projectSource), diff --git a/packages/web/tool-web/tests/integration.spec.ts b/packages/web/tool-web/tests/integration.spec.ts index 1ee7cb359c..1aa1fa6416 100644 --- a/packages/web/tool-web/tests/integration.spec.ts +++ b/packages/web/tool-web/tests/integration.spec.ts @@ -97,7 +97,7 @@ describe('web_search integration over the real Exa provider', () => { JSON.stringify({ results: [{ url: 'https://result.test', title: 'Result', highlights: ['a highlight'] }] }), { status: 200, headers: { 'content-type': 'application/json' } }, ))) - const out = await call('web_search', { query: 'deepseek-official' }) + const out = await call('web_search', { queries: ['deepseek-official'] }) expect(out.isError).toBe(false) expect(out.content.map(b => b.type === 'text' ? b.text : '').join('')).toContain('[Result](https://result.test)') }) @@ -107,10 +107,11 @@ describe('tool-call timeout policy over the migrated web tools', () => { it('neither model schema exposes a timeout parameter after the migration', () => { const byName = new Map(ctx.tools.schemas().map(s => [s.name, s])) const fetchParams = byName.get('web_fetch')!.parameters as { properties: Record } - const searchParams = byName.get('web_search')!.parameters as { properties: Record } + const searchParams = byName.get('web_search')!.parameters as { properties: Record; required?: string[] } expect(Object.keys(fetchParams.properties)).toEqual(['url']) expect('timeout_ms' in fetchParams.properties).toBe(false) - expect(Object.keys(searchParams.properties)).toEqual(['query']) + expect(Object.keys(searchParams.properties)).toEqual(['queries']) + expect(searchParams.required).toEqual(['queries']) }) }) diff --git a/packages/web/tool-web/tests/tool-web.spec.ts b/packages/web/tool-web/tests/tool-web.spec.ts index 5cfd43ba0b..2adad8b79c 100644 --- a/packages/web/tool-web/tests/tool-web.spec.ts +++ b/packages/web/tool-web/tests/tool-web.spec.ts @@ -10,7 +10,6 @@ import * as ToolWeb from '@deepseek-ai/dsh-tool-web' import { formatSearchOutput, formatFetchOutput, - parseSearchArgs, parseFetchArgs, presentSearchCall, presentFetchCall, @@ -20,10 +19,12 @@ import { searchMetaFromResult, fetchMetaFromValue, fetchMetaFromResult, + WEB_SEARCH_MAX_QUERIES, WEB_SEARCH_MAX_RESULTS, } from '@deepseek-ai/dsh-tool-web' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { ToolResult } from '@deepseek-ai/dsh-tools' +import { parseSearchArgs } from '../src/search.ts' const testToolSignal = new AbortController().signal @@ -84,9 +85,14 @@ describe('search formatting', () => { expect(out).toContain('Showing the first 1 sources') }) - it('validates the query', () => { - expect(() => parseSearchArgs({ query: ' ' })).toThrow('non-empty') - expect(parseSearchArgs({ query: 'hi' })).toEqual({ query: 'hi' }) + it('validates queries', () => { + expect(parseSearchArgs({ queries: ['hi'] }, WEB_SEARCH_MAX_QUERIES)).toEqual(['hi']) + expect(parseSearchArgs({ queries: ['one', 'one', ' two '] }, WEB_SEARCH_MAX_QUERIES)) + .toEqual(['one', ' two ']) + expect(() => parseSearchArgs({ queries: [] }, WEB_SEARCH_MAX_QUERIES)).toThrow('at least one query') + expect(() => parseSearchArgs({ queries: ['one', 'two'] }, 1)).toThrow('at most 1 query') + expect(() => parseSearchArgs({ queries: ['one', 'two', 'three'] }, 2)).toThrow('at most 2 queries') + expect(() => parseSearchArgs({ queries: ['ok', ' '] }, WEB_SEARCH_MAX_QUERIES)).toThrow('each query must be a non-empty string') }) it('falls back to the raw URL as a source label when the URL is unparseable', () => { @@ -94,8 +100,8 @@ describe('search formatting', () => { expect(out).toContain('[not a url](not a url)') }) - it('presents a search call as a search-kind card titled by the query', () => { - expect(presentSearchCall({ query: 'find me' })).toEqual({ card: 'generic', title: 'find me', kind: 'search', rawInput: 'find me' }) + it('presents a search call with a joined query title', () => { + expect(presentSearchCall({ queries: ['one', 'two'] })).toEqual({ card: 'generic', title: 'one, two', kind: 'search', rawInput: 'one, two' }) }) }) @@ -145,7 +151,7 @@ describe('web_search presentation meta and result view', () => { content: 'an answer', truncated: true, sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }], }) - expect(presentSearchResult({ query: 'q' }, toolResult(meta, 'rendered'))).toEqual({ + expect(presentSearchResult({ queries: ['q'] }, toolResult(meta, 'rendered'))).toEqual({ card: 'web', kind: 'search', title: 'q', @@ -157,7 +163,7 @@ describe('web_search presentation meta and result view', () => { it('omits the answer from the view when meta carries none', () => { const meta = searchMetaFromValue({ truncated: false, sources: [{ url: 'https://a.test' }] }) - const view = presentSearchResult({ query: 'q' }, toolResult(meta)) + const view = presentSearchResult({ queries: ['q'] }, toolResult(meta)) expect(view).toBeDefined() expect(view && 'answer' in view).toBe(false) expect(view && 'content' in view).toBe(false) @@ -165,11 +171,11 @@ describe('web_search presentation meta and result view', () => { it('falls back to the generic card on an error result', () => { const meta = searchMetaFromValue({ truncated: false, sources: [{ url: 'https://a.test' }] }) - expect(presentSearchResult({ query: 'q' }, toolResult(meta, 'body', true))).toBeUndefined() + expect(presentSearchResult({ queries: ['q'] }, toolResult(meta, 'body', true))).toBeUndefined() }) it('falls back to the generic card on absent or malformed meta', () => { - expect(presentSearchResult({ query: 'q' }, toolResult(undefined))).toBeUndefined() + expect(presentSearchResult({ queries: ['q'] }, toolResult(undefined))).toBeUndefined() expect(searchMetaFromResult(undefined)).toBeUndefined() expect(searchMetaFromResult(null)).toBeUndefined() expect(searchMetaFromResult('nope')).toBeUndefined() @@ -445,7 +451,7 @@ describe('tool-web registration', () => { const names = ctx.tools.schemas().map(s => s.name) expect(names).toContain('web_search') expect(names).toContain('web_fetch') - expect(ctx.tools.executionMode({ signal: testToolSignal, callId: CallId('search-safe'), name: 'web_search', arguments: { query: 'q' } })) + expect(ctx.tools.executionMode({ signal: testToolSignal, callId: CallId('search-safe'), name: 'web_search', arguments: { queries: ['q'] } })) .toEqual({ kind: 'parallel' }) expect(ctx.tools.executionMode({ signal: testToolSignal, callId: CallId('fetch-safe'), name: 'web_fetch', arguments: { url: 'https://a.test' } })) .toEqual({ kind: 'parallel' }) @@ -474,7 +480,7 @@ describe('tool-web registration', () => { expect(ctx.tools.schemas().map(s => s.name)).toContain('web_search') // No provider is registered: the schema stays visible and execution reports // the structured unavailability instead. - const out = await call('web_search', { query: 'q' }) + const out = await call('web_search', { queries: ['q'] }) expect(out.error?.info?.code).toBe('WEB_PROVIDER_UNAVAILABLE') await fiber.dispose() }) @@ -483,7 +489,7 @@ describe('tool-web registration', () => { const { fiber, ctx } = await mountTools() const prompt = await ctx.systemPrompt.assemble() const text = prompt.sections.map(s => s.text).join('\n') - expect(text).toContain('Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.') + expect(text).toContain(`Use the web_search tool to discover current information on the web. The required queries array accepts 1–${WEB_SEARCH_MAX_QUERIES} non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.`) expect(text).toContain('Use the web_fetch tool to retrieve the content of a specific HTTP(S) URL') await fiber.dispose() }) @@ -505,25 +511,156 @@ describe('tool-web execution through the real registry', () => { sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }], } const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider(result) }) - const out = await call('web_search', { query: 'q' }) + const out = await call('web_search', { queries: ['q'] }) expect(out.isError).toBe(false) expect(out.value).toEqual(result) expect(out.content.map(b => b.type === 'text' ? b.text : '').join('')).toContain('[A](https://a.test)') await fiber.dispose() }) + it('executes web_search with multiple queries concurrently and merges results', async () => { + const seen: string[] = [] + let releaseFirst: (() => void) | undefined + const firstResult = new Promise((resolve) => { + releaseFirst = () => { + resolve({ + content: 'answer one', truncated: false, + sources: [ + { url: 'https://a.test', title: 'A' }, + { url: 'https://shared.test' }, + ], + }) + } + }) + const provider: WebSearchProvider = { + id: 'stub-search', + available: () => available, + search: (request) => { + seen.push(request.query) + if (request.query === 'one') return firstResult + return Promise.resolve({ + content: 'answer two', truncated: false, + sources: [ + { url: 'https://b.test', title: 'B' }, + { url: 'https://shared.test' }, + ], + }) + }, + } + const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider }) + const pending = call('web_search', { queries: ['one', 'one', 'two'] }) + try { + await vi.waitFor(() => { expect(seen).toEqual(['one', 'two']) }) + } finally { + releaseFirst?.() + } + const out = await pending + expect(out.isError).toBe(false) + expect(out.value).toEqual({ + content: '### one\n\nanswer one\n\n### two\n\nanswer two', + sources: [ + { url: 'https://a.test', title: 'A' }, + { url: 'https://b.test', title: 'B' }, + { url: 'https://shared.test' }, + ], + truncated: false, + }) + const body = out.content.map(b => b.type === 'text' ? b.text : '').join('') + expect(body).toContain('### one') + expect(body).toContain('### two') + await fiber.dispose() + }) + + it('continues round-robin merging after a shorter result is exhausted', async () => { + const provider: WebSearchProvider = { + id: 'stub-search', + available: () => available, + search: request => Promise.resolve(request.query === 'one' + ? { content: '', sources: [{ url: 'https://a.test' }], truncated: false } + : { sources: [{ url: 'https://b.test' }, { url: 'https://c.test' }], truncated: false }), + } + const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider }) + const out = await call('web_search', { queries: ['one', 'two'] }) + expect(out.isError).toBe(false) + expect(out.value).toEqual({ + sources: [ + { url: 'https://a.test' }, + { url: 'https://b.test' }, + { url: 'https://c.test' }, + ], + truncated: false, + }) + await fiber.dispose() + }) + + it('aborts sibling searches and waits for them to settle before reporting a batch failure', async () => { + let siblingAborted = false + let releaseSibling: (() => void) | undefined + const provider: WebSearchProvider = { + id: 'stub-search', + available: () => available, + search: (request, signal) => { + if (request.query === 'one') return Promise.reject(new Error('first search failed')) + return new Promise((_resolve, reject) => { + releaseSibling = () => { reject(new Error('sibling search stopped')) } + signal?.addEventListener('abort', () => { + siblingAborted = true + }, { once: true }) + }) + }, + } + const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider }) + const pending = call('web_search', { queries: ['one', 'two'] }) + let callSettled = false + void pending.then(() => { callSettled = true }) + try { + await vi.waitFor(() => { expect(siblingAborted).toBe(true) }) + await Promise.resolve() + expect(callSettled).toBe(false) + } finally { + releaseSibling?.() + } + const out = await pending + expect(out.isError).toBe(true) + expect(out.content).toEqual([{ type: 'text', text: 'Error: first search failed' }]) + await fiber.dispose() + }) + + it('caps combined multi-query results to searchMaxResults', async () => { + const provider: WebSearchProvider = { + id: 'stub-search', + available: () => available, + search: request => Promise.resolve({ + sources: request.query === 'one' + ? [{ url: 'https://a.test' }, { url: 'https://b.test' }] + : [{ url: 'https://c.test' }, { url: 'https://d.test' }], + truncated: false, + }), + } + const { fiber, call } = await mountTools({ config: { searchMaxResults: 2 }, webConfig: { searchProvider: 'stub-search' }, search: provider }) + const out = await call('web_search', { queries: ['one', 'two'] }) + expect(out.isError).toBe(false) + expect(out.value).toEqual({ + sources: [{ url: 'https://a.test' }, { url: 'https://c.test' }], + truncated: true, + }) + const body = out.content.map(b => b.type === 'text' ? b.text : '').join('') + expect(body).toContain('Showing the first 2 sources.') + await fiber.dispose() + }) + it('projects the search sources into the tool result meta and derives its web/search view', async () => { const result: WebSearchResult = { content: 'answer', truncated: true, sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }], } const { ctx, fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider(result) }) - const out = await call('web_search', { query: 'q' }) + const out = await call('web_search', { queries: ['q'] }) expect(out.meta).toEqual({ answer: 'answer', truncated: true, sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }], }) - const view = ctx.tools.get('web_search')?.presentResult?.({ query: 'q' }, { content: out.content, isError: out.isError, ...out.meta !== undefined ? { meta: out.meta } : {} }) + const view = ctx.tools.get('web_search')?.presentResult?.({ queries: ['q'] }, { content: out.content, isError: out.isError, ...out.meta !== undefined ? { meta: out.meta } : {} }) expect(view).toMatchObject({ card: 'web', kind: 'search', truncated: true, answer: 'answer' }) await fiber.dispose() }) @@ -546,7 +683,7 @@ describe('tool-web execution through the real registry', () => { it('surfaces a structured WebError when no provider is available', async () => { const { fiber, call } = await mountTools() - const out = await call('web_search', { query: 'q' }) + const out = await call('web_search', { queries: ['q'] }) expect(out.isError).toBe(true) expect(out.error?.info?.code).toBe('WEB_PROVIDER_UNAVAILABLE') await fiber.dispose() @@ -555,15 +692,15 @@ describe('tool-web execution through the real registry', () => { it('surfaces WEB_PROVIDER_AMBIGUOUS for multiple unconfigured providers', async () => { const { ctx, fiber, call } = await mountTools({ search: searchProvider({ sources: [], truncated: false }) }) ctx.web.registerSearchProvider({ id: 'other', available: () => available, search: () => Promise.resolve({ sources: [], truncated: false }) }) - const out = await call('web_search', { query: 'q' }) + const out = await call('web_search', { queries: ['q'] }) expect(out.isError).toBe(true) expect(out.error?.info?.code).toBe('WEB_PROVIDER_AMBIGUOUS') await fiber.dispose() }) - it('rejects invalid arguments with a structured INVALID_ARGS error', async () => { + it.each([{}, { queries: [123] }])('rejects absent or wrongly typed queries with a structured INVALID_ARGS error', async (args) => { const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider({ sources: [], truncated: false }) }) - const out = await call('web_search', { query: 123 }) + const out = await call('web_search', args) expect(out.isError).toBe(true) expect(out.error?.info?.code).toBe('INVALID_ARGS') await fiber.dispose() @@ -635,10 +772,34 @@ describe('tool-web execution through the real registry', () => { } const { ctx, fiber } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider }) const controller = new AbortController() - await ctx.tools.execute({ callId: CallId('search-1'), name: 'web_search', arguments: { query: 'q' }, signal: controller.signal }) + await ctx.tools.execute({ callId: CallId('search-1'), name: 'web_search', arguments: { queries: ['q'] }, signal: controller.signal }) expect(seen.signal).toBe(controller.signal) await fiber.dispose() }) + + it('cascades caller cancellation to every multi-query search', async () => { + const signals: (AbortSignal | undefined)[] = [] + const provider: WebSearchProvider = { + id: 'stub-search', + available: () => available, + search: (_request, signal) => { + signals.push(signal) + return new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => { reject(new Error('search aborted')) }, { once: true }) + }) + }, + } + const { ctx, fiber } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider }) + const controller = new AbortController() + const pending = ctx.tools.execute({ callId: CallId('search-multi-1'), name: 'web_search', arguments: { queries: ['one', 'two'] }, signal: controller.signal }) + await vi.waitFor(() => { expect(signals).toHaveLength(2) }) + expect(signals[0]).toBe(signals[1]) + expect(signals[0]).not.toBe(controller.signal) + controller.abort(new Error('caller cancelled')) + await pending + expect(signals.every(signal => signal?.aborted === true)).toBe(true) + await fiber.dispose() + }) }) describe('searchMaxResults is plugin config', () => { @@ -650,7 +811,7 @@ describe('searchMaxResults is plugin config', () => { search: (request) => { seen.maxResults = request.maxResults; return Promise.resolve({ sources: [], truncated: false }) }, } const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider }) - await call('web_search', { query: 'q' }) + await call('web_search', { queries: ['q'] }) expect(seen.maxResults).toBe(WEB_SEARCH_MAX_RESULTS) await fiber.dispose() }) @@ -663,7 +824,7 @@ describe('searchMaxResults is plugin config', () => { search: () => Promise.resolve({ sources, truncated: false }), } const { fiber, call } = await mountTools({ config: { searchMaxResults: 2 }, webConfig: { searchProvider: 'stub-search' }, search: provider }) - const out = await call('web_search', { query: 'q' }) + const out = await call('web_search', { queries: ['q'] }) expect(out.isError).toBe(false) const body = out.content.map(b => b.type === 'text' ? b.text : '').join('') expect(body).toContain('https://s1.test') @@ -686,6 +847,43 @@ describe('searchMaxResults is plugin config', () => { }) }) +describe('searchMaxQueries is plugin config', () => { + it('exposes the configured cap to the model and enforces it before provider calls', async () => { + const seen: string[] = [] + const provider: WebSearchProvider = { + id: 'stub-search', + available: () => available, + search: (request) => { + seen.push(request.query) + return Promise.resolve({ sources: [], truncated: false }) + }, + } + const { fiber, ctx, call } = await mountTools({ + config: { searchMaxQueries: 2 }, + webConfig: { searchProvider: 'stub-search' }, + search: provider, + }) + const schema = ctx.tools.schemas().find(item => item.name === 'web_search') + expect(schema?.description).toContain('1–2 queries') + const prompt = await ctx.systemPrompt.assemble() + expect(prompt.sections.map(section => section.text).join('\n')).toContain('accepts 1–2 non-empty search queries') + const out = await call('web_search', { queries: ['one', 'two', 'three'] }) + expect(out.isError).toBe(true) + expect(out.content).toEqual([{ type: 'text', text: 'Error: queries must contain at most 2 queries' }]) + expect(seen).toEqual([]) + await fiber.dispose() + }) + + it.each([0, -1, 1.5])('rejects an invalid searchMaxQueries value %s at load', async (value) => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(WebRuntime, {}) + await expect(ctx.plugin(ToolWeb, { searchMaxQueries: value })) + .rejects.toThrow(/tool-web: searchMaxQueries must be a positive integer/) + }) +}) + describe('tool-call timeout budget is plugin config', () => { it('attaches the default 30s budget to web_fetch and web_search', async () => { const { fiber, ctx } = await mountTools() diff --git a/packages/web/web/src/types.ts b/packages/web/web/src/types.ts index 2c7fcb5fcd..9e94bac46b 100644 --- a/packages/web/web/src/types.ts +++ b/packages/web/web/src/types.ts @@ -8,9 +8,10 @@ import { HarnessError } from '@deepseek-ai/dsh-llm' /** - * What one search-capable backend can return. The model-facing argument is just - * a query; `maxResults` is a `dsh-tool-web`-layer bound passed through unchanged - * and enforced on the way back by the seam (see {@link WebSearchResult}). + * What one search-capable backend is asked to search. Each request carries one + * query; a consumer may issue several requests. `maxResults` is a + * `dsh-tool-web`-layer bound passed through unchanged and enforced on the way + * back by the seam (see {@link WebSearchResult}). */ export interface WebSearchRequest { readonly query: string diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 57e14a4c9f..46830f7717 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -640,6 +640,9 @@ importers: '@deepseek-ai/dsh-system-prompt': specifier: workspace:* version: link:../packages/core/system-prompt + '@deepseek-ai/dsh-team': + specifier: workspace:* + version: link:../packages/experimental/team '@deepseek-ai/dsh-terminal': specifier: workspace:* version: link:../packages/terminal/terminal @@ -706,6 +709,9 @@ importers: '@deepseek-ai/dsh-tool-subagent-report': specifier: workspace:* version: link:../packages/subagent/tool-subagent-report + '@deepseek-ai/dsh-tool-team': + specifier: workspace:* + version: link:../packages/experimental/tool-team '@deepseek-ai/dsh-tool-terminal': specifier: workspace:* version: link:../packages/terminal/tool-terminal @@ -4018,6 +4024,110 @@ importers: specifier: workspace:^ version: link:../../runtime-diagnostics/invariants + packages/experimental/team: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: ^4.4.3 + version: 4.4.3 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:^ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:^ + version: link:../../core/agent-loop + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-brand': + specifier: workspace:^ + version: link:../../util/brand + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../runtime-diagnostics/invariants + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-session': + specifier: workspace:^ + version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:^ + version: link:../../session/session-persistence + '@deepseek-ai/dsh-session-persistence-jsonl': + specifier: workspace:^ + version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-session-persistence-sqlite': + specifier: workspace:^ + version: link:../../session/session-persistence-sqlite + '@deepseek-ai/dsh-subagent': + specifier: workspace:^ + version: link:../../subagent/subagent + '@deepseek-ai/dsh-subagent-fork-in-process': + specifier: workspace:^ + version: link:../../subagent/subagent-fork-in-process + '@deepseek-ai/dsh-subagent-spawn-in-process': + specifier: workspace:^ + version: link:../../subagent/subagent-spawn-in-process + + packages/experimental/tool-team: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:^ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:^ + version: link:../../core/agent-loop + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../runtime-diagnostics/invariants + '@deepseek-ai/dsh-scope': + specifier: workspace:^ + version: link:../../core/scope + '@deepseek-ai/dsh-session': + specifier: workspace:^ + version: link:../../core/session + '@deepseek-ai/dsh-session-persistence-jsonl': + specifier: workspace:^ + version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-subagent': + specifier: workspace:^ + version: link:../../subagent/subagent + '@deepseek-ai/dsh-subagent-fork-in-process': + specifier: workspace:^ + version: link:../../subagent/subagent-fork-in-process + '@deepseek-ai/dsh-subagent-spawn-in-process': + specifier: workspace:^ + version: link:../../subagent/subagent-spawn-in-process + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../../core/system-prompt + '@deepseek-ai/dsh-team': + specifier: workspace:^ + version: link:../team + '@deepseek-ai/dsh-tool-subagent-control': + specifier: workspace:^ + version: link:../../subagent/tool-subagent-control + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + packages/extensions/cordis-client-runner: devDependencies: '@deepseek-ai/cordis': @@ -7163,6 +7273,12 @@ importers: '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery + '@modelcontextprotocol/sdk': + specifier: ^1.29.0 + version: 1.29.0(zod@4.4.3) + zod: + specifier: ^4.4.3 + version: 4.4.3 devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ @@ -7197,9 +7313,15 @@ importers: packages/subagent/subagent-codex: dependencies: + '@deepseek-ai/dsh-sdk-protocol': + specifier: workspace:^ + version: link:../../sdk/protocol '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery + '@openai/codex': + specifier: 0.147.0 + version: 0.147.0 devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ @@ -7219,9 +7341,6 @@ importers: '@deepseek-ai/dsh-loader-smoke': specifier: workspace:^ version: link:../../test-support/loader-smoke - '@deepseek-ai/dsh-sdk-protocol': - specifier: workspace:^ - version: link:../../sdk/protocol '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session @@ -7237,9 +7356,6 @@ importers: '@deepseek-ai/dsh-timeout': specifier: workspace:^ version: link:../../util/timeout - '@openai/codex': - specifier: 0.147.0 - version: 0.147.0 packages/subagent/subagent-dsh-sdk: dependencies: diff --git a/scripts/check-workspace-constraints.spec.ts b/scripts/check-workspace-constraints.spec.ts new file mode 100644 index 0000000000..755af09093 --- /dev/null +++ b/scripts/check-workspace-constraints.spec.ts @@ -0,0 +1,67 @@ +/** Experimental-package publication and dependency constraints. */ + +import { describe, expect, it } from 'vitest' +import { + checkExperimentalDependencyIsolation, + checkExperimentalManifest, + type WorkspaceManifest, +} from './check-workspace-constraints.ts' + +const experimental: WorkspaceManifest = { + dir: 'packages/experimental/prototype', + manifest: { name: '@deepseek-ai/dsh-prototype', private: true }, +} + +describe('experimental workspace constraints', () => { + it('requires private manifests without publication metadata', () => { + expect(checkExperimentalManifest(experimental)).toEqual([]) + expect(checkExperimentalManifest({ + ...experimental, + manifest: { ...experimental.manifest, private: false, publishConfig: { access: 'public' } }, + })).toEqual([ + '@deepseek-ai/dsh-prototype: experimental package must set "private": true', + '@deepseek-ai/dsh-prototype: experimental package must omit publishConfig', + ]) + }) + + it.each(['dependencies', 'optionalDependencies', 'peerDependencies'] as const)( + 'rejects release %s on an experimental package', + (section) => { + expect(checkExperimentalDependencyIsolation([experimental, { + dir: 'packages/core/consumer', + manifest: { + name: '@deepseek-ai/dsh-consumer', + [section]: { '@deepseek-ai/dsh-prototype': 'workspace:^' }, + }, + }])).toEqual([ + `@deepseek-ai/dsh-consumer: ${section}.@deepseek-ai/dsh-prototype must not reference an experimental package`, + ]) + }, + ) + + it('allows development and experimental consumers but rejects the Python release runtime', () => { + const manifests: WorkspaceManifest[] = [experimental, { + dir: 'packages/core/test-only', + manifest: { + name: '@deepseek-ai/dsh-test-only', + devDependencies: { '@deepseek-ai/dsh-prototype': 'workspace:^' }, + }, + }, { + dir: 'packages/experimental/consumer', + manifest: { + name: '@deepseek-ai/dsh-experimental-consumer', + dependencies: { '@deepseek-ai/dsh-prototype': 'workspace:^' }, + }, + }, { + dir: 'python/sdk-runtime', + manifest: { + name: '@deepseek-ai/dsh-python-runtime', + dependencies: { '@deepseek-ai/dsh-prototype': 'workspace:^' }, + }, + }] + + expect(checkExperimentalDependencyIsolation(manifests)).toEqual([ + '@deepseek-ai/dsh-python-runtime: dependencies.@deepseek-ai/dsh-prototype must not reference an experimental package', + ]) + }) +}) diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index c8dab964e1..8b98333ce2 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -7,6 +7,7 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs' import { join, relative, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' import { hasTypertRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts' import { collectProjectReferenceFaceViolations } from './project-reference-faces.ts' @@ -47,8 +48,10 @@ const repositoryUrl = 'git+https://github.com/deepseek-harness/deepseek-harness. * their trusted publishing against the repository that runs the workflow. */ const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harness.git' +/** Private packages that participate in workspace checks but not releases. */ +const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/ /** Directories whose packages this repository publishes: one release member each. */ -const releaseMemberDirectory = /^(?:packages\/[^/]+\/[^/]+|apps\/[^/]+|vendor\/[^/]+)$/ +const releaseMemberDirectory = /^(?:packages\/(?!experimental\/)[^/]+\/[^/]+|apps\/[^/]+|vendor\/[^/]+)$/ const localArtifactDirs = new Set(['node_modules']) const appPackageFiles: Readonly> = { @@ -59,7 +62,7 @@ const appPackageFiles: Readonly> = { } /** The subset of package.json fields this constraint check cares about. */ -interface PackageManifest { +export interface PackageManifest { name?: string version?: string private?: boolean @@ -84,10 +87,15 @@ interface PackageManifest { devDependencies?: Record dependencies?: Record optionalDependencies?: Record + dsh?: { + bundle?: { + patch?: string + } + } } /** One workspace manifest and its repo-relative path. */ -interface WorkspaceManifest { +export interface WorkspaceManifest { dir: string manifest: PackageManifest } @@ -131,10 +139,6 @@ function workspaceManifests(): WorkspaceManifest[] { } const packageFileExtras: Readonly> = { - // Profile bundles publish their dsh.bundle.patch layer beside the lib. - '@deepseek-ai/dsh-base': ['cordis.patch.yml'], - '@deepseek-ai/dsh-web-app': ['cordis.patch.yml'], - '@deepseek-ai/dsh-headless': ['cordis.patch.yml'], // Statically linked client libraries keep their stylesheets next to the emitted // JavaScript, which imports them by relative path: the compile shell runs // them through its own CSS pipeline, so the sheets are published artifacts. @@ -161,7 +165,12 @@ function sameStringList(actual: readonly string[] | undefined, expected: readonl } function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] { - const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : [] + const declaredPatch = manifest.dsh?.bundle?.patch + const bundleFiles = declaredPatch === undefined ? [] : [declaredPatch.replace(/^\.\//, '')] + const extras = [ + ...bundleFiles, + ...(manifest.name ? packageFileExtras[manifest.name] ?? [] : []), + ] return [ 'lib/index.js', // Every package publishes its invariant ownership companion as a separate @@ -228,8 +237,18 @@ function usesEmittedTreeDefaults(manifest: PackageManifest): boolean { exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true) } -function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] { +/** Experimental manifest requirements enforced independently from release metadata. */ +export function checkExperimentalManifest({ dir, manifest }: WorkspaceManifest): string[] { + if (!experimentalPackageDirectory.test(dir)) return [] + const label = manifest.name ?? dir const errors: string[] = [] + if (manifest.private !== true) errors.push(`${label}: experimental package must set "private": true`) + if (manifest.publishConfig !== undefined) errors.push(`${label}: experimental package must omit publishConfig`) + return errors +} + +function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] { + const errors = checkExperimentalManifest({ dir, manifest }) const label = manifest.name ?? dir const isLandlockPackageDir = dir.startsWith('native/landlock-run/packages/') const isPublicLandlockPackage = isLandlockPackageDir @@ -271,7 +290,7 @@ function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] { || manifest.repository.directory !== dir) { errors.push(`${label}: release member repository must use ${publishedRepositoryUrl} with directory ${dir}`) } - } else if (manifest.private !== true) { + } else if (!experimentalPackageDirectory.test(dir) && manifest.private !== true) { errors.push(`${label}: package.json must set "private": true`) } @@ -390,6 +409,31 @@ function checkRepositoryVersion(): string[] { /** Dependency sections whose ranges reach a published tarball or a local install. */ const dependencySections = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] as const +/** Dependency sections present in an installed runtime. */ +const runtimeDependencySections = ['dependencies', 'optionalDependencies', 'peerDependencies'] as const + +/** + * Prevent an official runtime from requiring a package its release omits. + * @param manifests - release, private experimental, and deployment-root manifests. + * @returns One error for each forbidden runtime dependency. + */ +export function checkExperimentalDependencyIsolation(manifests: readonly WorkspaceManifest[]): string[] { + const experimentalNames = new Set(manifests + .filter(entry => experimentalPackageDirectory.test(entry.dir)) + .map(entry => entry.manifest.name) + .filter(name => name !== undefined)) + const errors: string[] = [] + for (const { dir, manifest } of manifests) { + if (!releaseMemberDirectory.test(dir) && dir !== 'python/sdk-runtime') continue + for (const section of runtimeDependencySections) { + for (const name of Object.keys(manifest[section] ?? {})) { + if (!experimentalNames.has(name)) continue + errors.push(`${manifest.name ?? dir}: ${section}.${name} must not reference an experimental package`) + } + } + } + return errors +} /** * Require the `workspace:` protocol for every reference to a workspace member. @@ -415,15 +459,25 @@ function checkWorkspaceProtocol(manifests: readonly WorkspaceManifest[]): string return errors } -const manifests = workspaceManifests() -const errors = [ - ...checkRepositoryVersion(), - ...manifests.flatMap(checkWorkspace), - ...checkWorkspaceProtocol(manifests), - ...checkHierarchyShape(), - ...collectProjectReferenceFaceViolations(root), -] -if (errors.length > 0) { - console.error(errors.join('\n')) - process.exitCode = 1 +/** Run the repository constraint gate. */ +export function main(): void { + const manifests = workspaceManifests() + const dependencyManifests = [ + ...manifests, + { dir: 'python/sdk-runtime', manifest: readJson(join(root, 'python/sdk-runtime/package.json')) }, + ] + const errors = [ + ...checkRepositoryVersion(), + ...manifests.flatMap(checkWorkspace), + ...checkWorkspaceProtocol(manifests), + ...checkExperimentalDependencyIsolation(dependencyManifests), + ...checkHierarchyShape(), + ...collectProjectReferenceFaceViolations(root), + ] + if (errors.length > 0) { + console.error(errors.join('\n')) + process.exitCode = 1 + } } + +if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main() diff --git a/scripts/coverage-partitions.spec.ts b/scripts/coverage-partitions.spec.ts new file mode 100644 index 0000000000..749a63d6a7 --- /dev/null +++ b/scripts/coverage-partitions.spec.ts @@ -0,0 +1,232 @@ +import { access, mkdir, mkdtemp, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + COVERAGE_PARTITION_MODE_ENV, + COVERAGE_PARTITIONS_ENV, + COVERAGE_TEST_TIMEOUT_ENV, + CoveragePartitionCoordinator, + coverageTestTimeoutArgs, + forwardedCoverageArgs, + parseCoveragePartitionCount, + type CoverageCommand, + type CoverageCommandResult, +} from './coverage-partitions.ts' + +const passed: CoverageCommandResult = { exitCode: 0, signalCode: null } + +afterEach(() => vi.restoreAllMocks()) + +async function writeBlob(command: CoverageCommand): Promise { + if (command.blobPath === undefined) return + await mkdir(dirname(command.blobPath), { recursive: true }) + await writeFile(command.blobPath, '{}') +} + +async function temporaryRoot(): Promise { + return await mkdtemp(join(tmpdir(), 'dsh-coverage-partitions-')) +} + +describe('coverage partition count', () => { + it.each([ + [undefined, undefined], + ['', undefined], + ['2', 2], + ['3', 3], + ])('parses %j as %j', (raw, expected) => { + expect(parseCoveragePartitionCount(raw)).toBe(expected) + }) + + it.each(['0', '1', '2.5', '02', 'many'])('rejects %j', (raw) => { + expect(() => parseCoveragePartitionCount(raw)) + .toThrow(`${COVERAGE_PARTITIONS_ENV} must be an integer greater than 1`) + }) +}) + +describe('coverage partition timeout', () => { + it('applies one configured timeout to tests and polling', () => { + expect(coverageTestTimeoutArgs('30000')).toEqual([ + '--testTimeout=30000', + '--expect.poll.timeout=30000', + ]) + }) + + it('keeps Vitest defaults when the timeout is absent', () => { + expect(coverageTestTimeoutArgs(undefined)).toEqual([]) + }) + + it('rejects invalid timeout input', () => { + expect(() => coverageTestTimeoutArgs('0')) + .toThrow(`${COVERAGE_TEST_TIMEOUT_ENV} must be a positive integer`) + }) +}) + +describe('coverage forwarded arguments', () => { + it('removes one package-script separator', () => { + expect(forwardedCoverageArgs(['--', 'scripts/example.spec.ts'])).toEqual(['scripts/example.spec.ts']) + }) + + it('preserves direct arguments and a subsequent Vitest separator', () => { + expect(forwardedCoverageArgs(['--testNamePattern=example'])).toEqual(['--testNamePattern=example']) + expect(forwardedCoverageArgs(['--', '--', 'example'])).toEqual(['--', 'example']) + }) +}) + +describe('coverage partition coordinator', () => { + it('runs every single-worker partition before one merged threshold check', async () => { + const root = await temporaryRoot() + const commands: CoverageCommand[] = [] + const runCommand = vi.fn(async (command: CoverageCommand) => { + commands.push(command) + await writeBlob(command) + return passed + }) + const coordinator = new CoveragePartitionCoordinator({ + root, + partitions: 3, + pnpmEntrypoint: '/pnpm.cjs', + vitestArgs: ['--testTimeout=30000'], + runCommand, + }) + + await expect(coordinator.run()).resolves.toBe(0) + + expect(commands.map(command => command.label)).toEqual([ + 'partition 1/3', + 'partition 2/3', + 'partition 3/3', + 'merged coverage report', + ]) + for (const [index, command] of commands.slice(0, 3).entries()) { + expect(command.args).toEqual(expect.arrayContaining([ + '--coverage', + '--coverage.reportOnFailure', + '--maxWorkers=1', + `--shard=${index + 1}/3`, + '--reporter=default', + '--reporter=blob', + '--testTimeout=30000', + ])) + expect(command.env).toEqual({ + [COVERAGE_PARTITIONS_ENV]: undefined, + [COVERAGE_PARTITION_MODE_ENV]: '1', + }) + } + const mergeCommand = commands[3] + if (mergeCommand === undefined) throw new Error('coverage merge command was not observed') + expect(mergeCommand.args).toContain('--coverage') + expect(mergeCommand.args.some(argument => argument.startsWith('--merge-reports='))).toBe(true) + expect(mergeCommand.env).toEqual({ + [COVERAGE_PARTITIONS_ENV]: undefined, + [COVERAGE_PARTITION_MODE_ENV]: undefined, + }) + }) + + it('merges normal test failures and returns their failed status', async () => { + const root = await temporaryRoot() + const reported = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const runCommand = vi.fn(async (command: CoverageCommand) => { + await writeBlob(command) + return command.label === 'partition 2/2' + ? { exitCode: 1, signalCode: null, outputTail: 'specific Vitest failure' } + : passed + }) + const coordinator = new CoveragePartitionCoordinator({ + root, + partitions: 2, + pnpmEntrypoint: '/pnpm.cjs', + runCommand, + }) + + await expect(coordinator.run()).resolves.toBe(1) + expect(reported).toHaveBeenCalledWith('coverage-partitions: FAIL partition 2/2 (exit 1)') + expect(reported).toHaveBeenCalledWith( + 'coverage-partitions: output tail for partition 2/2:\nspecific Vitest failure', + ) + expect(runCommand).toHaveBeenCalledTimes(3) + }) + + it('rejects a missing partition blob before merge', async () => { + const root = await temporaryRoot() + const runCommand = vi.fn(async (command: CoverageCommand) => { + if (command.label !== 'partition 2/2') await writeBlob(command) + return passed + }) + const coordinator = new CoveragePartitionCoordinator({ + root, + partitions: 2, + pnpmEntrypoint: '/pnpm.cjs', + runCommand, + }) + + await expect(coordinator.run()).rejects.toThrow('coverage partitions produced') + expect(runCommand).toHaveBeenCalledTimes(2) + }) + + it('reports signal termination before missing-blob validation', async () => { + const root = await temporaryRoot() + const reported = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const runCommand = vi.fn(async (command: CoverageCommand) => { + if (command.label === 'partition 1/2') await writeBlob(command) + return command.label === 'partition 2/2' + ? { exitCode: null, signalCode: 'SIGTERM' as const } + : passed + }) + const coordinator = new CoveragePartitionCoordinator({ + root, + partitions: 2, + pnpmEntrypoint: '/pnpm.cjs', + runCommand, + }) + + await expect(coordinator.run()).rejects.toThrow('coverage partitions produced') + expect(reported).toHaveBeenCalledWith('coverage-partitions: FAIL partition 2/2 (signal SIGTERM)') + }) + + it('waits for every partition after one spawn failure', async () => { + const root = await temporaryRoot() + const reported = vi.spyOn(console, 'error').mockImplementation(() => undefined) + let secondFinished = false + const runCommand = vi.fn(async (command: CoverageCommand) => { + await writeBlob(command) + if (command.label === 'partition 1/2') { + return { exitCode: null, signalCode: null, error: 'spawn unavailable' } + } + if (command.label === 'partition 2/2') secondFinished = true + return passed + }) + const coordinator = new CoveragePartitionCoordinator({ + root, + partitions: 2, + pnpmEntrypoint: '/pnpm.cjs', + runCommand, + }) + + await expect(coordinator.run()).resolves.toBe(1) + expect(reported).toHaveBeenCalledWith('coverage-partitions: FAIL partition 1/2 (spawn unavailable)') + expect(secondFinished).toBe(true) + expect(runCommand).toHaveBeenCalledTimes(3) + }) + + it('unlinks a link-shaped coverage path without touching its target', async () => { + const root = await temporaryRoot() + const target = await temporaryRoot() + const marker = join(target, 'marker.txt') + await writeFile(marker, 'owned elsewhere') + await symlink(target, join(root, 'coverage'), process.platform === 'win32' ? 'junction' : 'dir') + const runCommand = vi.fn(async (command: CoverageCommand) => { + await writeBlob(command) + return passed + }) + const coordinator = new CoveragePartitionCoordinator({ + root, + partitions: 2, + pnpmEntrypoint: '/pnpm.cjs', + runCommand, + }) + + await expect(coordinator.run()).resolves.toBe(0) + await expect(access(marker)).resolves.toBeUndefined() + }) +}) diff --git a/scripts/coverage-partitions.ts b/scripts/coverage-partitions.ts new file mode 100644 index 0000000000..d9abc06101 --- /dev/null +++ b/scripts/coverage-partitions.ts @@ -0,0 +1,269 @@ +/** Coordinate single-worker Vitest coverage partitions and one merged report. */ +import { spawn } from 'node:child_process' +import { lstat, mkdir, readdir, rm, unlink } from 'node:fs/promises' +import { join, relative, sep } from 'node:path' + +/** Environment variable selecting the number of instrumented coverage processes. */ +export const COVERAGE_PARTITIONS_ENV = 'DSH_COVERAGE_PARTITIONS' + +/** Internal marker that suppresses reports and thresholds inside a partition process. */ +export const COVERAGE_PARTITION_MODE_ENV = 'DSH_COVERAGE_PARTITION_MODE' + +/** Environment variable overriding instrumented test and polling timeouts. */ +export const COVERAGE_TEST_TIMEOUT_ENV = 'DSH_COVERAGE_TEST_TIMEOUT_MS' + +/** One child command owned by the coverage coordinator. */ +export interface CoverageCommand { + /** Diagnostic identity. */ + label: string + /** Node arguments; the first argument is pnpm's JavaScript entrypoint. */ + args: string[] + /** Environment additions for the child. */ + env: Record + /** Working directory for the child. */ + cwd: string + /** Blob the partition must produce; absent for the merge command. */ + blobPath?: string +} + +/** Observable child-process completion. */ +export interface CoverageCommandResult { + /** Numeric process status, or `null` when a signal ended the child. */ + exitCode: number | null + /** Terminating signal, or `null` after an ordinary exit. */ + signalCode: NodeJS.Signals | null + /** Spawn failure recorded independently from process completion. */ + error?: string + /** Bounded combined stdout/stderr tail repeated when the command fails. */ + outputTail?: string +} + +/** Execute one coordinator command with inherited output. */ +export type CoverageCommandRunner = (command: CoverageCommand) => Promise + +/** Construction inputs for {@link CoveragePartitionCoordinator}. */ +export interface CoveragePartitionCoordinatorOptions { + /** Repository root that owns coverage output. */ + root: string + /** Number of concurrent single-worker Vitest processes. */ + partitions: number + /** pnpm JavaScript entrypoint from `npm_execpath`. */ + pnpmEntrypoint: string + /** Additional arguments shared by every partition. */ + vitestArgs?: string[] + /** Child executor, injectable for scheduler tests. */ + runCommand?: CoverageCommandRunner +} + +/** Parse an optional coverage partition count. */ +export function parseCoveragePartitionCount(raw: string | undefined): number | undefined { + if (raw === undefined || raw === '') return undefined + const parsed = Number.parseInt(raw, 10) + if (!Number.isSafeInteger(parsed) || parsed < 2 || String(parsed) !== raw) { + throw new Error(`${COVERAGE_PARTITIONS_ENV} must be an integer greater than 1, got ${JSON.stringify(raw)}.`) + } + return parsed +} + +/** Resolve the paired Vitest timeout arguments used by coverage partitions. */ +export function coverageTestTimeoutArgs(raw: string | undefined): string[] { + if (raw === undefined || raw === '') return [] + const parsed = Number.parseInt(raw, 10) + if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) { + throw new Error(`${COVERAGE_TEST_TIMEOUT_ENV} must be a positive integer, got ${JSON.stringify(raw)}.`) + } + return [`--testTimeout=${raw}`, `--expect.poll.timeout=${raw}`] +} + +/** Remove pnpm's package-script separator before forwarding Vitest arguments. */ +export function forwardedCoverageArgs(args: readonly string[]): string[] { + return [...args.slice(args[0] === '--' ? 1 : 0)] +} + +/** Run instrumented partitions, validate their blobs, and merge once. */ +export class CoveragePartitionCoordinator { + private readonly root: string + private readonly partitions: number + private readonly pnpmEntrypoint: string + private readonly vitestArgs: string[] + private readonly runCommand: CoverageCommandRunner + private readonly temporaryRoot: string + private readonly blobsRoot: string + + /** Create a coordinator from validated process-independent inputs. */ + public constructor(options: CoveragePartitionCoordinatorOptions) { + if (!Number.isSafeInteger(options.partitions) || options.partitions < 2) { + throw new Error(`coverage partitions must be an integer greater than 1, got ${String(options.partitions)}.`) + } + this.root = options.root + this.partitions = options.partitions + this.pnpmEntrypoint = options.pnpmEntrypoint + this.vitestArgs = options.vitestArgs ?? [] + this.runCommand = options.runCommand ?? runCoverageCommand + this.temporaryRoot = join(this.root, 'coverage', '.partitioned') + this.blobsRoot = join(this.temporaryRoot, 'blobs') + } + + /** + * Run every partition before one merged threshold check. + * @returns zero only when every partition and the merge command succeed. + */ + public async run(): Promise { + await removeOwnedTree(join(this.root, 'coverage')) + await mkdir(this.blobsRoot, { recursive: true }) + + try { + const commands = Array.from( + { length: this.partitions }, + (_, index) => this.partitionCommand(index + 1), + ) + const results = await Promise.all(commands.map(async (command) => { + console.log(`coverage-partitions: start ${command.label}`) + const result = await this.runCommand(command) + if (commandFailed(result)) { + console.error(`coverage-partitions: FAIL ${command.label} (${commandFailureReason(result)})`) + if (result.outputTail !== undefined && result.outputTail !== '') { + console.error(`coverage-partitions: output tail for ${command.label}:\n${result.outputTail}`) + } + } + return result + })) + await this.assertCompleteBlobSet(commands) + + const mergeCommand = this.mergeCommand() + console.log(`coverage-partitions: start ${mergeCommand.label}`) + const mergeResult = await this.runCommand(mergeCommand) + return results.some(commandFailed) || commandFailed(mergeResult) ? 1 : 0 + } finally { + await removeOwnedTree(this.temporaryRoot) + } + } + + private partitionCommand(index: number): CoverageCommand { + const blobPath = join(this.blobsRoot, `partition-${index}.json`) + const reportsDirectory = join(this.temporaryRoot, `coverage-${index}`) + return { + label: `partition ${index}/${this.partitions}`, + args: [ + this.pnpmEntrypoint, + 'exec', + 'vitest', + 'run', + '--coverage', + '--coverage.reportOnFailure', + '--maxWorkers=1', + `--shard=${index}/${this.partitions}`, + '--reporter=default', + '--reporter=blob', + `--outputFile.blob=${this.relativePath(blobPath)}`, + `--coverage.reportsDirectory=${this.relativePath(reportsDirectory)}`, + ...this.vitestArgs, + ], + env: { + [COVERAGE_PARTITIONS_ENV]: undefined, + [COVERAGE_PARTITION_MODE_ENV]: '1', + }, + cwd: this.root, + blobPath, + } + } + + private mergeCommand(): CoverageCommand { + return { + label: 'merged coverage report', + args: [ + this.pnpmEntrypoint, + 'exec', + 'vitest', + `--merge-reports=${this.relativePath(this.blobsRoot)}`, + '--coverage', + ], + env: { + [COVERAGE_PARTITIONS_ENV]: undefined, + [COVERAGE_PARTITION_MODE_ENV]: undefined, + }, + cwd: this.root, + } + } + + private relativePath(path: string): string { + return relative(this.root, path).split(sep).join('/') + } + + private async assertCompleteBlobSet(commands: CoverageCommand[]): Promise { + const expected = commands.map((command) => { + if (command.blobPath === undefined) throw new Error(`${command.label} has no blob path.`) + return this.relativePath(command.blobPath) + }).sort() + const actual = (await readdir(this.blobsRoot)) + .map(name => this.relativePath(join(this.blobsRoot, name))) + .sort() + if (actual.length !== expected.length || actual.some((name, index) => name !== expected[index])) { + throw new Error(`coverage partitions produced ${JSON.stringify(actual)}; expected ${JSON.stringify(expected)}.`) + } + } +} + +/** Spawn one pnpm-backed command without a platform shell. */ +function runCoverageCommand(command: CoverageCommand): Promise { + return new Promise((resolveCommand) => { + let outputTail = '' + const env = { ...process.env } + for (const [name, value] of Object.entries(command.env)) { + if (value === undefined) Reflect.deleteProperty(env, name) + else env[name] = value + } + const child = spawn(process.execPath, command.args, { + cwd: command.cwd, + env, + stdio: ['ignore', 'pipe', 'pipe'], + }) + child.stdout.setEncoding('utf8') + child.stderr.setEncoding('utf8') + child.stdout.on('data', (chunk: string) => { + process.stdout.write(chunk) + outputTail = appendOutputTail(outputTail, chunk) + }) + child.stderr.on('data', (chunk: string) => { + process.stderr.write(chunk) + outputTail = appendOutputTail(outputTail, chunk) + }) + child.once('error', (error: Error) => { + resolveCommand({ exitCode: null, signalCode: null, error: error.message, outputTail }) + }) + child.once('close', (exitCode, signalCode) => { + resolveCommand({ exitCode, signalCode, outputTail }) + }) + }) +} + +function appendOutputTail(previous: string, chunk: string): string { + const combined = previous + chunk + return combined.length <= 65_536 ? combined : combined.slice(-65_536) +} + +function commandFailed(result: CoverageCommandResult): boolean { + return result.exitCode !== 0 || result.signalCode !== null || result.error !== undefined +} + +function commandFailureReason(result: CoverageCommandResult): string { + const facts = [ + result.error, + result.exitCode === null ? undefined : `exit ${result.exitCode}`, + result.signalCode === null ? undefined : `signal ${result.signalCode}`, + ].filter((fact): fact is string => fact !== undefined) + return facts.join(', ') || 'no exit code or signal' +} + +async function removeOwnedTree(path: string): Promise { + const metadata = await lstat(path).catch((error: unknown) => { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined + throw error + }) + if (metadata === undefined) return + if (metadata.isSymbolicLink() || !metadata.isDirectory()) { + await unlink(path) + return + } + await rm(path, { recursive: true, force: true }) +} diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 4b9afc529c..a5b73b04c1 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -98,6 +98,7 @@ export const SERVICE_PAGE: Record = { systemPrompt: 'system-prompt.md', jobs: 'jobs.md', sessionTelemetry: 'session-telemetry.md', + teams: 'team.md', tokenMeter: 'token-meter.md', toolResultPruner: 'compaction.md', tools: 'tools.md', @@ -426,6 +427,18 @@ export const LINK_MAP: Readonly> = { JobSnapshot: 'jobs.md', JobStart: 'jobs.md', JobsChangedListener: 'jobs.md', + CreateTeamTaskRequest: 'team.md', + SendTeamMessageRequest: 'team.md', + SendTeamMessageResult: 'team.md', + SpawnTeammateRequest: 'team.md', + SpawnTeammateResult: 'team.md', + TeamId: 'team.md', + TeamMemberView: 'team.md', + TeamMembership: 'team.md', + TeamTaskId: 'team.md', + TeamTaskView: 'team.md', + TeamWaitResult: 'team.md', + UpdateTeamTaskRequest: 'team.md', TokenMeasurement: 'token-meter.md', CodeDispatchLog: 'tools.md', PostToolDecision: 'tools.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index e839ad0052..e46853a8a1 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -67,6 +67,7 @@ const GROUP_ORDER = [ 'core', 'typert', 'goal', + 'experimental', 'process', 'bash', 'pty', @@ -477,6 +478,14 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['tool-subagent', 'tool-subagent-control', 'tool-ralph'], note: 'Providers implement transports; the service also owns optional Activation-based continuation orchestration, tool-subagent selects one-shot or continuable delegation, tool-subagent-control delivers follow-ups, and tool-ralph requires one fresh structured-output route.', }, + { + key: 'teams', + pkg: 'team', + title: 'Agent Teams coordination domain', + mode: 'core', + consumers: ['tool-team'], + note: 'Owns the implicit-root roster, durable peer mailbox, shared task DAG, and continuable-child lifecycle; tool-team contributes the scoped model policy and controls.', + }, { key: 'jobs', pkg: 'jobs', diff --git a/scripts/gen-persistence-catalog.ts b/scripts/gen-persistence-catalog.ts index 38100fd531..4166d1b07d 100644 --- a/scripts/gen-persistence-catalog.ts +++ b/scripts/gen-persistence-catalog.ts @@ -52,6 +52,11 @@ const LINK_MAP: Record = { SessionTitleModelProvenance: 'session-title.md', SessionTitleProviderId: 'session-title.md', SessionTitleSource: 'session-title.md', + TeamId: 'team.md', + TeamMemberSnapshot: 'team.md', + TeamMessageId: 'team.md', + TeamMessageSnapshot: 'team.md', + TeamTaskSnapshot: 'team.md', } /** One log event, extracted from a `SessionEventMap` declaration. */ diff --git a/scripts/gen-third-party-notices.ts b/scripts/gen-third-party-notices.ts index f2411f5eff..3362251f1e 100644 --- a/scripts/gen-third-party-notices.ts +++ b/scripts/gen-third-party-notices.ts @@ -673,7 +673,6 @@ export function render(): string { ) ? collectClaudeDistribution() : undefined - const nonPermissiveDev = devDeps.filter(dep => !isPermissive(dep.license)) // A copyleft license reaching a shipped surface is a distribution decision, // not a rendering detail; the notices cannot quietly absorb it. @@ -693,7 +692,7 @@ export function render(): string { DeepSeek Harness is licensed under [MIT](LICENSE). It depends on the third-party software listed below. Each project remains under its own license; nothing in this file changes those terms. -This file lists **direct** dependencies declared by the workspace and the explicitly disclosed official Claude platform payload closure. It is generated from the workspace manifests by \`scripts/gen-third-party-notices.ts\`: a pre-commit hook regenerates it whenever a staged file changes one of its inputs, and \`scripts/gen-third-party-notices.spec.ts\` asserts in the test lane that the committed bytes match. Deleting a manifest runs no hook, so that case is caught by the assertion instead. Run \`pnpm run verify-third-party-notices\` for the standalone check. +This file lists **direct** dependencies declared by the workspace and the explicitly disclosed official Claude Code platform payload closure. It is generated from the workspace manifests by \`scripts/gen-third-party-notices.ts\`: a pre-commit hook regenerates it whenever a staged file changes one of its inputs, and \`scripts/gen-third-party-notices.spec.ts\` asserts in the test lane that the committed bytes match. Deleting a manifest runs no hook, so that case is caught by the assertion instead. Run \`pnpm run verify-third-party-notices\` for the standalone check. The complete npm transitive closure, including the Landlock launcher workspace, is recorded with exact pinned versions in [\`pnpm-lock.yaml\`](pnpm-lock.yaml) — inspect it with \`pnpm licenses list\`. The Python closure is recorded separately in [\`python/sdk/uv.lock\`](python/sdk/uv.lock). diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 66b8f17eaa..2f1abb810d 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -57,6 +57,8 @@ import * as ToolLsp from '@deepseek-ai/dsh-tool-lsp' import * as ToolSkill from '@deepseek-ai/dsh-tool-skill' import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query' import * as ToolTasks from '@deepseek-ai/dsh-tool-jobs' +import type TeamService from '@deepseek-ai/dsh-team' +import * as ToolTeam from '@deepseek-ai/dsh-tool-team' import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent' import * as ToolWeb from '@deepseek-ai/dsh-tool-web' @@ -507,6 +509,44 @@ const TOOL_PACKAGES: ToolPackage[] = [ note: 'The kind-agnostic background-job controller: background bash commands, PTY sends, and subagents are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers\' `ctx.jobs.start()`.', }, + { + pkg: '@deepseek-ai/dsh-tool-team', + dir: 'tool-team', + source: 'packages/experimental/tool-team/src/index.ts', + requires: ['ctx.tools', 'ctx.systemPrompt', 'ctx.teams', 'an exact live Team member Agent'], + writes: ['tool/call', 'team/member', 'team/message/queued', 'team/message/delivered', 'team/task', 'tool/result'], + async mount(ctx) { + await ctx.plugin(AgentRegistry) + await ctx.plugin(SessionStore) + const session = ctx.sessions.create(SessionId('tool-catalog-team-lead')) + let agent!: Agent + const membership = { + get root() { return agent }, + id: session.id, + role: 'lead' as const, + name: 'lead', + } + ctx.provide('teams', { + tryMembership: (candidate: Agent) => candidate === agent ? membership : undefined, + membership: () => membership, + } as unknown as TeamService) + await ctx.plugin(Object.assign((inner: Context) => { + agent = { + id: session.id, + session, + options: {}, + status: 'idle', + } as unknown as Agent + Object.assign(agent, { ctx: createScope(inner, agent).ctx }) + inner.agents.register(agent) + }, { inject: ['tools', 'systemPrompt', 'agents', 'teams'] })) + await ctx.plugin(ToolTeam) + catalogChildScopes.set(ctx, agent) + }, + scope: ctx => catalogChildScopes.get(ctx) as Agent, + note: + 'All ten tools are scoped to implicit Team Leads and durable teammates. The shipped dsh-base bundle keeps the package disabled; the documented Agent Teams profile patch enables it while disabling the legacy continuable-child control names.', + }, { pkg: '@deepseek-ai/dsh-tool-todo', dir: 'tool-todo', diff --git a/scripts/install-lefthook.spec.ts b/scripts/install-lefthook.spec.ts index 56ca6315d6..f0c76ead6f 100644 --- a/scripts/install-lefthook.spec.ts +++ b/scripts/install-lefthook.spec.ts @@ -529,7 +529,12 @@ describe('worktree-local Lefthook installer', { timeout: 30_000 }, () => { const lockPath = installLockPath(fixture) const runningPath = join(hooksPath(fixture, fixture.main), '.fake-lefthook-running') const install = runInstaller(fixture, fixture.main, { DSH_TEST_LEFTHOOK_DELAY_MS: '250' }) - await waitForPath(runningPath) + try { + await waitForPath(runningPath) + } catch (error) { + await install + throw error + } const replacementRecord = 'replacement owner\n' writeFileSync(lockPath, replacementRecord) diff --git a/scripts/locale-dictionary-parity.spec.ts b/scripts/locale-dictionary-parity.spec.ts new file mode 100644 index 0000000000..b51630f105 --- /dev/null +++ b/scripts/locale-dictionary-parity.spec.ts @@ -0,0 +1,308 @@ +/** + * Gate for the invariant `FALLBACK_LOCALE` rests on: every shipped dictionary + * declares the same keys in `zh` and `en`. + * + * The locale runtime resolves a key through the active locale, then through + * the single fallback locale (`en`), then surfaces the key itself. With + * symmetric dictionaries that middle step always resolves, so one constant can + * serve as both the opening locale and the dictionary fallback. A key added to + * only one side breaks that: a reader of the other language sees a bare key + * such as `list.aria` instead of text. This gate fails on the asymmetry rather + * than waiting for the bare key to reach a UI. + * + * Discovery is deliberately broad, because a gate that silently narrows is + * worse than no gate. It sweeps every workspace package (not just + * `packages/client`), reads dictionaries wherever they are declared — + * `locales.ts`, a `locales/` directory, or inline in the plugin body — and + * pairs `zh`/`en` across sibling files as well as within one module. A `zh` + * dictionary whose `en` counterpart cannot be found anywhere is an error, not + * a skip. + */ + +import type { Dirent } from 'node:fs' +import { readdirSync, readFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import ts from 'typescript' +import { describe, expect, it } from 'vitest' + +const root = fileURLToPath(new URL('..', import.meta.url)) + +/** Repo-relative path with `/` separators, so messages and suffix tests match on every OS. */ +function relative(file: string): string { + return file.slice(root.length).replaceAll('\\', '/') +} + +/** Every `.ts` source file under each workspace package's `src`, excluding declarations. */ +function sourceFiles(): string[] { + const files: string[] = [] + const packagesRoot = resolve(root, 'packages') + for (const group of directories(packagesRoot)) { + for (const pkg of directories(resolve(packagesRoot, group))) { + walk(resolve(packagesRoot, group, pkg, 'src'), files) + } + } + return files.sort() +} + +/** Immediate subdirectory names, or none when the path is not a directory. */ +function directories(dir: string): string[] { + return readEntries(dir).filter(entry => entry.isDirectory()).map(entry => entry.name) +} + +/** + * Directory entries, treating only a genuinely absent directory as empty. + * Any other failure (`EACCES`, I/O) rethrows: silently reading it as "absent" + * would narrow the sweep and let the gate pass while checking less. + * @param dir - absolute directory path. + * @returns entries, or none when the directory does not exist. + */ +function readEntries(dir: string): Dirent[] { + try { + return readdirSync(dir, { withFileTypes: true }) + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [] + throw error + } +} + +function walk(dir: string, out: string[]): void { + for (const entry of readEntries(dir)) { + const full = resolve(dir, entry.name) + if (entry.isDirectory()) walk(full, out) + else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')) out.push(full) + } +} + +/** One discovered dictionary: which file and export name declared it. */ +interface Dictionary { + /** Repo-relative declaring file. */ + file: string + /** Export name, or the registration site for an inline literal. */ + name: string + /** Declared keys, sorted. */ + keys: string[] +} + +/** + * Keys of every top-level `export const = { ... }` object literal whose + * name identifies a locale dictionary, plus inline `register(ns, locale, {...})` + * literals. Read from the AST so the gate never executes package code. + * @param file - absolute path of a candidate module. + * @returns discovered dictionaries, keyed by locale-bearing name. + */ +function dictionariesIn(file: string): Dictionary[] { + const text = readFileSync(file, 'utf8') + // Cheap pre-filter: parsing every package source is wasteful. The pattern + // must admit every shape `localeOf` accepts, or a file would be skipped + // before parsing — the silent narrowing this gate exists to prevent. A bare + // `\b(zh|en)\b` misses `zhSettings`/`accessZh`, because `\b` does not hold + // between `h` and an uppercase letter. + if (!/\b(zh|en)\b|\b(zh|en)[A-Z]|(Zh|En)\b/.test(text)) return [] + const source = ts.createSourceFile(file, text, ts.ScriptTarget.ESNext, true) + const found: Dictionary[] = [] + const rel = relative(file) + + // Module-scope variable declarations, keyed by name. A 3-arg + // `register(NS, 'zh'|'en', dict)` whose third argument is an identifier — + // e.g. a local dictionary variable rather than an inline literal — resolves + // through here so the gate still verifies its symmetry. + const moduleConsts = new Map() + for (const statement of source.statements) { + if (!ts.isVariableStatement(statement)) continue + for (const decl of statement.declarationList.declarations) { + if (ts.isIdentifier(decl.name) && decl.initializer !== undefined) { + moduleConsts.set(decl.name.text, decl.initializer) + } + } + } + + for (const statement of source.statements) { + if (!ts.isVariableStatement(statement)) continue + if (statement.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) !== true) continue + for (const decl of statement.declarationList.declarations) { + if (!ts.isIdentifier(decl.name)) continue + const literal = unwrap(decl.initializer) + if (literal === undefined || !ts.isObjectLiteralExpression(literal)) continue + if (localeOf(decl.name.text) === undefined) continue + found.push({ file: rel, name: decl.name.text, keys: keysOf(literal) }) + } + } + + // A 3-arg `register(ns, 'zh'|'en', dict)` call whose dictionary argument we + // cannot turn into an object literal. We refuse instead of skipping: a + // registration we cannot measure is exactly the silent narrowing this gate + // exists to catch. + const refuse = (ns: string, tag: string, why: string): never => { + throw new Error(`cannot verify register('${ns}', '${tag}', ...) in ${rel}: ${why}`) + } + + // Inline registrations, two shapes. A `[['zh', {...}], ['en', {...}]]` pair + // handed to a registration loop keys off the enclosing array; separate + // `register(NS, 'zh', {...})` / `register(NS, 'en', {...})` calls key off the + // namespace argument, so the two calls pair with each other. + const visit = (node: ts.Node): void => { + if (ts.isCallExpression(node)) { + const callee = node.expression + const name = ts.isPropertyAccessExpression(callee) + ? callee.name.text + : ts.isIdentifier(callee) && callee.text === 'register' ? 'register' : undefined + if (name === 'register' && node.arguments.length >= 3) { + const [ns, tag, dict] = node.arguments + if (ns === undefined || tag === undefined || !ts.isStringLiteral(tag)) return + if (tag.text !== 'zh' && tag.text !== 'en') return + const raw = unwrap(dict) + const literal = raw !== undefined && ts.isIdentifier(raw) + ? (() => { + const resolved = moduleConsts.get(raw.text) + return resolved === undefined ? undefined : unwrap(resolved) + })() + : raw + const why = raw !== undefined && ts.isIdentifier(raw) + ? `third argument ${raw.text} does not resolve to an inline or module-scope object literal` + : 'third argument is neither an object literal nor a resolvable dictionary variable' + if (literal === undefined || !ts.isObjectLiteralExpression(literal)) { + // The dictionary argument must resolve to an object literal; the + // gate refuses rather than skips, so the symmetry it verifies never + // silently narrows. + refuse(ns.getText(source), tag.text, why) + } + const dictionary: ts.ObjectLiteralExpression = literal as ts.ObjectLiteralExpression + // The namespace expression's source text identifies the pair, so the + // zh and en calls for one namespace meet and calls for different + // namespaces stay apart. + found.push({ file: rel, name: `${tag.text}@register:${ns.getText(source)}`, keys: keysOf(dictionary) }) + } + } + if (ts.isArrayLiteralExpression(node) && node.elements.length === 2) { + const site = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1 + for (const element of node.elements) { + if (!ts.isArrayLiteralExpression(element) || element.elements.length !== 2) continue + const [tag, dict] = element.elements + const literal = unwrap(dict) + if (tag === undefined || !ts.isStringLiteral(tag)) continue + if (literal === undefined || !ts.isObjectLiteralExpression(literal)) continue + if (tag.text !== 'zh' && tag.text !== 'en') continue + found.push({ file: rel, name: `${tag.text}@inline:${site}`, keys: keysOf(literal) }) + } + } + ts.forEachChild(node, visit) + } + visit(source) + return found +} + +/** Declared property names of an object literal, sorted. */ +function keysOf(literal: ts.ObjectLiteralExpression): string[] { + const keys: string[] = [] + for (const prop of literal.properties) { + if (!ts.isPropertyAssignment(prop)) continue + if (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) keys.push(prop.name.text) + } + return keys.sort() +} + +/** Look through `satisfies`/`as`/parenthesized wrappers to the literal. */ +function unwrap(node: ts.Expression | undefined): ts.Expression | undefined { + let current = node + while ( + current !== undefined + && (ts.isSatisfiesExpression(current) || ts.isAsExpression(current) || ts.isParenthesizedExpression(current)) + ) { + current = current.expression + } + return current +} + +/** + * The locale a dictionary name declares, and the namespace-ish remainder that + * identifies which pair it belongs to. `zh`/`en`, `zhSettings`/`enSettings`, + * and `settingsZh`/`settingsEn` are the shapes this repo uses. A name-prefix + * shape requires an uppercase ASCII letter at the third position (`[A-Z]`), + * matching the admission of the cheap pre-filter, so `zh2Foo`/`zh_probe` + * cannot be treated as dictionaries in one place and skipped in another. + * @param name - export name or synthetic inline name. + * @returns locale plus pair key, or undefined when the name names no locale. + */ +function localeOf(name: string): { locale: 'zh' | 'en'; pair: string } | undefined { + for (const locale of ['zh', 'en'] as const) { + const other = locale === 'zh' ? 'Zh' : 'En' + if (name === locale) return { locale, pair: '' } + // Synthetic names for inline shapes carry their own pair key after the + // first ':' (the enclosing array's line, or the namespace expression). + if (name.startsWith(`${locale}@`)) return { locale, pair: name.slice(name.indexOf(':')) } + if (name.startsWith(locale) && name.length > 2 && /[A-Z]/.test(name[2] ?? '')) { + return { locale, pair: name.slice(2) } + } + if (name.endsWith(other)) return { locale, pair: name.slice(0, -2) } + } + return undefined +} + +describe('shipped locale dictionaries', () => { + it('declares the same keys in zh and en, so the single fallback locale always resolves', () => { + const files = sourceFiles() + // Guard the discovery itself: an empty or narrowed sweep would pass every + // assertion below while checking nothing. + expect(files.length).toBeGreaterThan(500) + + // Pair within a file first; a dictionary whose counterpart is not in the + // same module then pairs with a sibling in the same directory. Both shapes + // ship here: `locales/settings.ts` exports zh+en together, while + // `locales/zh.ts` + `locales/en.ts` split the common pair across files. + const perFile = new Map() + for (const file of files) { + const dicts = dictionariesIn(file) + if (dicts.length > 0) perFile.set(relative(file), dicts) + } + + const groups = new Map>() + const place = (key: string, locale: 'zh' | 'en', dict: Dictionary): void => { + const slot = groups.get(key) ?? new Map<'zh' | 'en', Dictionary>() + if (slot.has(locale)) { + throw new Error(`two ${locale} dictionaries claim pair ${key}: ${slot.get(locale)?.file} and ${dict.file}`) + } + slot.set(locale, dict) + groups.set(key, slot) + } + + for (const [rel, dicts] of perFile) { + for (const dict of dicts) { + const parsed = localeOf(dict.name) + if (parsed === undefined) continue + const sameFileCounterpart = dicts.some((other) => { + const otherParsed = localeOf(other.name) + return otherParsed !== undefined + && otherParsed.pair === parsed.pair + && otherParsed.locale !== parsed.locale + }) + // Same-file pairs key by file so two pairs in one directory stay + // distinct; split pairs key by directory so siblings meet. + const key = sameFileCounterpart ? `${rel}::${parsed.pair}` : `${dirname(rel)}::${parsed.pair}` + place(key, parsed.locale, dict) + } + } + + const problems: string[] = [] + let comparedPairs = 0 + for (const [key, slot] of [...groups].sort()) { + const zh = slot.get('zh') + const en = slot.get('en') + if (zh === undefined || en === undefined) { + const present = zh ?? en + problems.push(`${present?.file} declares ${present?.name} with no counterpart for pair ${key}`) + continue + } + comparedPairs++ + const zhOnly = zh.keys.filter(k => !en.keys.includes(k)) + const enOnly = en.keys.filter(k => !zh.keys.includes(k)) + if (zhOnly.length > 0) problems.push(`${zh.file} ${zh.name} has keys absent from ${en.name}: ${zhOnly.join(', ')}`) + if (enOnly.length > 0) problems.push(`${en.file} ${en.name} has keys absent from ${zh.name}: ${enOnly.join(', ')}`) + } + + // The shipped dictionary count only grows; a collapse means discovery or + // pairing broke, which would hide real asymmetry. + expect(comparedPairs).toBeGreaterThan(25) + expect(problems).toEqual([]) + }) +}) diff --git a/scripts/publish-npm-baseline.ts b/scripts/publish-npm-baseline.ts index d69923910f..2d5d391fe9 100644 --- a/scripts/publish-npm-baseline.ts +++ b/scripts/publish-npm-baseline.ts @@ -24,7 +24,7 @@ const DEFAULT_REGISTRY = 'https://registry.npm.harnessment.com' const DEFAULT_OUTPUT_DIRECTORY = '.artifacts/npm-baseline' const PACKAGE_PATTERNS = [ 'vendor/*/package.json', - 'packages/*/*/package.json', + 'packages/!(experimental)/*/package.json', 'apps/*/package.json', ] as const const DEPENDENCY_SECTIONS = [ diff --git a/scripts/release/families.spec.ts b/scripts/release/families.spec.ts index 66c3daf83f..22eb0b064a 100644 --- a/scripts/release/families.spec.ts +++ b/scripts/release/families.spec.ts @@ -1,5 +1,6 @@ /** Release family discovery, publish order, tag naming, and the bump judgements. */ +import { resolve } from 'node:path' import { describe, expect, it } from 'vitest' import { releaseFamily, type ReleaseMember } from './families.ts' import { compareVersions, nextVendorVersion, reachesPayload } from './bump.ts' @@ -16,6 +17,13 @@ function member(directory: string, name: string, manifest: Record { + it('excludes private experimental packages from the dsh release', () => { + const members = releaseFamily('dsh').members(resolve(import.meta.dirname, '../..')) + + expect(members.some(member => member.directory.startsWith('packages/experimental/'))).toBe(false) + expect(members.map(member => member.name)).not.toContain('@deepseek-ai/dsh-team') + }) + it('names one tag for the whole dsh family and one per vendored package', () => { const dsh = releaseFamily('dsh') const vendor = releaseFamily('vendor') diff --git a/scripts/release/families.ts b/scripts/release/families.ts index f43939f17d..7ce5566831 100644 --- a/scripts/release/families.ts +++ b/scripts/release/families.ts @@ -305,10 +305,10 @@ export abstract class ReleaseFamily { abstract readonly installedEntry: InstalledEntry | undefined } -/** `packages/*` and `apps/*`: one shared version across the whole family. */ +/** Release packages and apps: one shared version across the whole family. */ class DshFamily extends ReleaseFamily { readonly id = 'dsh' - readonly patterns = ['packages/*/*/package.json', 'apps/*/package.json'] as const + readonly patterns = ['packages/!(experimental)/*/package.json', 'apps/*/package.json'] as const readonly tagPrefix = 'dsh-v' /** diff --git a/scripts/run-coverage-partitions.ts b/scripts/run-coverage-partitions.ts new file mode 100644 index 0000000000..8626665b96 --- /dev/null +++ b/scripts/run-coverage-partitions.ts @@ -0,0 +1,30 @@ +/** CLI entry for partitioned Vitest coverage. */ +import { resolve } from 'node:path' +import { + COVERAGE_PARTITIONS_ENV, + COVERAGE_TEST_TIMEOUT_ENV, + CoveragePartitionCoordinator, + coverageTestTimeoutArgs, + forwardedCoverageArgs, + parseCoveragePartitionCount, +} from './coverage-partitions.ts' + +const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV]) +if (partitions === undefined) { + throw new Error(`${COVERAGE_PARTITIONS_ENV} is required by partitioned coverage.`) +} +const pnpmEntrypoint = process.env.npm_execpath +if (pnpmEntrypoint === undefined || pnpmEntrypoint === '') { + throw new Error('partitioned coverage must be invoked through a pnpm package script.') +} + +const coordinator = new CoveragePartitionCoordinator({ + root: resolve(import.meta.dirname, '..'), + partitions, + pnpmEntrypoint, + vitestArgs: [ + ...coverageTestTimeoutArgs(process.env[COVERAGE_TEST_TIMEOUT_ENV]), + ...forwardedCoverageArgs(process.argv.slice(2)), + ], +}) +process.exitCode = await coordinator.run() diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index d1de2914e8..dce448b2e0 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -101,13 +101,25 @@ describe('gate graph validation', () => { }, ) - it('keeps native Windows coverage blocking while portability inventory remains observational', () => { - const gates = withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')) - const byId = new Map(gates.map(subject => [subject.id, subject])) + it('keeps native Windows coverage blocking while retaining the observational inventory', () => { + const complete = withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')) + const observational = withPnpmEntrypoint(() => gatesForMode('ci-windows-observational')) + .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build') + const byId = new Map(complete.map(subject => [subject.id, subject])) expect(byId.get('coverage')?.allowFailure).not.toBe(true) expect(byId.get('coverage-exempt-heavy')?.allowFailure).not.toBe(true) - expect(byId.get('duplication')?.allowFailure).toBe(true) + expect(byId.get('coverage-exempt-heavy')?.needs).toContain('build') + expect(observational).not.toHaveLength(0) + for (const gate of observational) { + const completeGate = byId.get(gate.id) + expect(completeGate?.allowFailure).toBe(true) + expect(completeGate?.after).toEqual(expect.arrayContaining([ + 'coverage', + 'coverage-exempt-heavy', + ])) + expect(completeGate?.needs).toEqual(gate.needs) + } }) it('applies one configured test and polling timeout to both coverage gates', () => { @@ -139,11 +151,30 @@ describe('gate graph validation', () => { .toThrow('DSH_COVERAGE_TEST_TIMEOUT_MS must be a positive integer') }) + it('selects partitioned coverage only when explicitly configured', () => { + const coverage = withEnv('DSH_COVERAGE_PARTITIONS', '3', () => + withPnpmEntrypoint(() => gatesForMode('ci-windows-complete').find(subject => subject.id === 'coverage'))) + + expect(coverage).toMatchObject({ + displayCommand: 'DSH_COVERAGE_PARTITIONS=3 pnpm run test:coverage:partitioned', + args: ['/private/pnpm.cjs', 'run', 'test:coverage:partitioned'], + streamOutput: true, + }) + }) + + it('rejects an invalid coverage partition count before starting a gate', () => { + expect(() => withEnv('DSH_COVERAGE_PARTITIONS', '1', () => + withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))) + .toThrow('DSH_COVERAGE_PARTITIONS must be an integer greater than 1') + }) + it.each([ ['empty', [], /gate graph has no gates/], ['duplicate ids', [gate('same'), gate('same')], /duplicate gate id "same"/], ['unknown dependencies', [gate('subject', { needs: ['missing'] })], /depends on unknown gate "missing"/], + ['unknown ordering predecessors', [gate('subject', { after: ['missing'] })], /waits for unknown gate "missing"/], ['cycles', [gate('first', { needs: ['second'] }), gate('second', { needs: ['first'] })], /dependency cycle: first -> second -> first/], + ['mixed cycles', [gate('first', { after: ['second'] }), gate('second', { needs: ['first'] })], /dependency cycle: first -> second -> first/], ] as const)('rejects %s before starting a child', async (_label, invalid, message) => { const execute = vi.fn(async (subject: Gate) => resultFor(subject)) @@ -169,6 +200,29 @@ describe('gate graph validation', () => { expect(execute).toHaveBeenCalledWith(root) expect(results[0]).toMatchObject({ gate: dependent, status: 'skipped', error: 'dependency failed or skipped: root' }) }) + + it('runs an ordered follower after its predecessor fails', async () => { + const follower = gate('follower', { after: ['root'] }) + const root = gate('root') + const execute = vi.fn(async (subject: Gate) => resultFor(subject, subject === root ? 'failed' : 'passed')) + + const results = await runGates([follower, root], 2, execute) + + expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['root', 'follower']) + expect(results.map(result => result.status)).toEqual(['passed', 'failed']) + }) + + it('runs an ordered follower after its predecessor is skipped', async () => { + const follower = gate('follower', { after: ['dependent'] }) + const dependent = gate('dependent', { needs: ['root'] }) + const root = gate('root') + const execute = vi.fn(async (subject: Gate) => resultFor(subject, subject === root ? 'failed' : 'passed')) + + const results = await runGates([follower, dependent, root], 2, execute) + + expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['root', 'follower']) + expect(results.map(result => result.status)).toEqual(['passed', 'skipped', 'failed']) + }) }) describe('Oxlint gate', () => { @@ -290,7 +344,7 @@ describe('Node 24 lane ownership', () => { 'built-bin-smoke', ]) expect(subject.find(item => item.id === 'publint')?.needs).toEqual(['build']) - expect(subject.find(item => item.id === 'built-package-invariants')?.needs).toEqual(['publint']) + expect(subject.find(item => item.id === 'built-package-invariants')?.needs).toEqual(['build']) expect(subject.find(item => item.id === 'lint-and-duplication')?.needs).toEqual(['built-package-invariants']) for (const id of [ 'snapshot', @@ -332,6 +386,22 @@ describe('Linux primary graph', () => { }) describe('gate process outcomes', () => { + it('streams selected gate output without retaining it', async () => { + const write = vi.spyOn(process.stdout, 'write').mockReturnValue(true) + try { + const result = await runGate(gate('streamed', { + args: ['-e', "process.stdout.write('live output')"], + streamOutput: true, + })) + + expect(result.status).toBe('passed') + expect(result.output).toEqual([]) + expect(write).toHaveBeenCalledWith('live output') + } finally { + write.mockRestore() + } + }) + it.skipIf(process.platform === 'win32')('reports signal termination independently from exit status', async () => { const result = await runGate(gate('terminated', { args: ['-e', "process.kill(process.pid, 'SIGTERM')"], diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index d26fa77320..1f65fed97e 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -10,6 +10,12 @@ import { availableParallelism } from 'node:os' import { resolve } from 'node:path' import { performance } from 'node:perf_hooks' import { COVERAGE_EXEMPT_ENV, coverageExemptHeavySuites } from './coverage-exempt.ts' +import { + COVERAGE_PARTITIONS_ENV, + COVERAGE_TEST_TIMEOUT_ENV, + coverageTestTimeoutArgs, + parseCoveragePartitionCount, +} from './coverage-partitions.ts' /** A named aggregate exposed by the gate runner. */ export type Mode = @@ -39,8 +45,13 @@ export interface Gate { command: string args: string[] needs?: string[] + /** Gate ids that must settle, regardless of outcome, before this gate starts. */ + after?: string[] env?: Record + /** Keep a failure visible without failing the aggregate. */ allowFailure?: boolean + /** Write child output as it arrives instead of buffering it until completion. */ + streamOutput?: boolean } /** The observed outcome of one gate process. */ @@ -395,7 +406,7 @@ function ciConsumerGates(): Gate[] { pnpmScript('build', 'build'), pnpmScript('node-compat', 'check:node-compat', { label: 'Node compatibility' }), pnpmScript('publint', 'publint', { needs: builtTree }), - builtPackageInvariantsGate(['publint']), + builtPackageInvariantsGate(builtTree), pnpmScript('lint-and-duplication', 'check:ci:lint:contracts-ready', { label: 'lint and duplication', needs: validatedBuild, @@ -415,6 +426,20 @@ function ciConsumerGates(): Gate[] { } function webSnapshotGate(needs: string[]): Gate { + const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS + if (workerRaw !== undefined && workerRaw !== '') { + const workers = Number.parseInt(workerRaw, 10) + if (!Number.isSafeInteger(workers) || workers < 2 || String(workers) !== workerRaw) { + throw new Error(`run-gates: DSH_WEB_SNAPSHOT_WORKERS must be an integer greater than 1, got ${JSON.stringify(workerRaw)}.`) + } + return pnpmScript('web-snapshot', 'test:web:ci', { + label: 'web browser snapshot', + displayCommand: `DSH_SNAPSHOT=replay DSH_WEB_SNAPSHOT_WORKERS=${workers} pnpm run test:web:ci`, + env: { DSH_SNAPSHOT: 'replay' }, + needs, + streamOutput: true, + }) + } return pnpmScript('web-snapshot', 'test:web:built', { label: 'web browser snapshot', displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built', @@ -431,15 +456,23 @@ function ciWindowsBlockingGates(): Gate[] { } function ciWindowsCompleteGates(): Gate[] { + const coverage = coverageGates().map(gate => gate.id === 'coverage-exempt-heavy' + ? { ...gate, needs: [...new Set(['build', ...(gate.needs ?? [])])] } + : gate) + const coverageAfter = coverage.map(gate => gate.id) const observational = ciWindowsObservationalGates() // The required production site replaces the observational MPA build; both // VitePress modes write the same output directory and cannot overlap. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build') - .map(gate => ({ ...gate, allowFailure: true })) + .map(gate => ({ + ...gate, + allowFailure: true, + after: [...new Set([...coverageAfter, ...(gate.after ?? [])])], + })) return [ pnpmScript('build', 'build'), pnpmScript('windows-site', 'docs:build', { label: 'production site' }), - ...coverageGates(), + ...coverage, ...observational, ] } @@ -479,13 +512,14 @@ function lintGate(options: { needs?: string[] } = {}): Gate { // under v8 instrumentation while contributing nothing the thresholds need // (membership rules in scripts/coverage-exempt.ts). // -// DSH_COVERAGE_MAX_WORKERS is the lane's worker budget, so the two parallel -// gates split it instead of each claiming it whole (the failover pool's -// 8 x 6-instance bound assumes one lane never exceeds its value). The exempt +// DSH_COVERAGE_MAX_WORKERS is the ordinary lane's worker budget, so the two +// parallel gates split it instead of each claiming it whole. When +// DSH_COVERAGE_PARTITIONS is set, its single-worker processes replace the +// instrumented share while this budget still sizes the exempt gate. The exempt // gate's wall clock is dominated by its longest single file, so it takes the -// small share. A budget of 1 gives each gate 1 worker; lanes that need a -// strict total of one (the serial reference jobs) also set -// DSH_GATE_CONCURRENCY=1, which keeps the gates from overlapping at all. +// small share. A budget of 1 gives each gate 1 worker; lanes that need a strict +// total of one (the serial reference jobs) also set DSH_GATE_CONCURRENCY=1, +// which keeps the gates from overlapping at all. // DSH_COVERAGE_TEST_TIMEOUT_MS raises Vitest's per-test and expect.poll // defaults together for instrumented lanes whose scheduling overhead exceeds // those defaults. Explicit fixture timeouts remain authoritative. @@ -501,18 +535,12 @@ function coverageWorkerArgs(): { instrumented: string[]; exempt: string[] } { } } -function coverageTimeoutArgs(): string[] { - return [ - ...positiveIntArg('DSH_COVERAGE_TEST_TIMEOUT_MS', '--testTimeout'), - ...positiveIntArg('DSH_COVERAGE_TEST_TIMEOUT_MS', '--expect.poll.timeout'), - ] -} - function coverageGates(): Gate[] { const workers = coverageWorkerArgs() - const timeouts = coverageTimeoutArgs() - return [ - pnpmExec('coverage', [ + const timeouts = coverageTestTimeoutArgs(process.env[COVERAGE_TEST_TIMEOUT_ENV]) + const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV]) + const instrumented = partitions === undefined + ? pnpmExec('coverage', [ 'vitest', 'run', '--coverage', @@ -521,7 +549,15 @@ function coverageGates(): Gate[] { ], { label: 'test:coverage', env: { [COVERAGE_EXEMPT_ENV]: '1' }, - }), + }) + : pnpmScript('coverage', 'test:coverage:partitioned', { + label: 'test:coverage', + displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`, + env: { [COVERAGE_EXEMPT_ENV]: '1' }, + streamOutput: true, + }) + return [ + instrumented, pnpmExec('coverage-exempt-heavy', [ 'vitest', 'run', @@ -681,6 +717,11 @@ function validateGateGraph(gates: readonly Gate[]): void { throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`) } } + for (const predecessor of gate.after ?? []) { + if (!ids.has(predecessor)) { + throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} waits for unknown gate ${JSON.stringify(predecessor)}.`) + } + } } const cycle = findDependencyCycle(gates) @@ -702,8 +743,8 @@ function findDependencyCycle(gates: readonly Gate[]): string[] | undefined { active.set(id, path.length) path.push(id) - for (const dependency of gate.needs ?? []) { - const cycle = visit(dependency) + for (const predecessor of [...(gate.needs ?? []), ...(gate.after ?? [])]) { + const cycle = visit(predecessor) if (cycle !== undefined) return cycle } path.pop() @@ -744,7 +785,7 @@ export async function runGates( for (;;) { let madeProgress = false while (running.length < maxActive) { - const ready = gates.find(gate => states.get(gate.id) === 'pending' && dependenciesPassed(gate, states)) + const ready = gates.find(gate => states.get(gate.id) === 'pending' && predecessorsReady(gate, states)) if (ready === undefined) break states.set(ready.id, 'running') running.push({ gate: ready, promise: execute(ready) }) @@ -753,32 +794,24 @@ export async function runGates( } if (running.length === 0) { - let pending = gates.filter(gate => states.get(gate.id) === 'pending') - while (pending.length > 0) { - const gate = pending.find(item => (item.needs ?? []).some((id) => { - const state = states.get(id) - return state === 'failed' || state === 'skipped' - })) - if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.') - const failedDeps = (gate.needs ?? []).filter((id) => { - const state = states.get(id) - return state === 'failed' || state === 'skipped' - }) - const result: GateResult = { - gate, - status: 'skipped', - durationMs: 0, - output: [], - exitCode: null, - signalCode: null, - error: `dependency failed or skipped: ${failedDeps.join(', ')}`, - } - states.set(gate.id, 'skipped') - results.set(gate.id, result) - observe(result) - pending = pending.filter(item => item !== gate) + const pending = gates.filter(gate => states.get(gate.id) === 'pending') + if (pending.length === 0) break + const gate = pending.find(item => (item.needs ?? []).some(id => gateFailed(states.get(id)))) + if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.') + const failedDeps = (gate.needs ?? []).filter(id => gateFailed(states.get(id))) + const result: GateResult = { + gate, + status: 'skipped', + durationMs: 0, + output: [], + exitCode: null, + signalCode: null, + error: `dependency failed or skipped: ${failedDeps.join(', ')}`, } - break + states.set(gate.id, 'skipped') + results.set(gate.id, result) + observe(result) + continue } if (!madeProgress) { @@ -797,8 +830,17 @@ export async function runGates( }) } -function dependenciesPassed(gate: Gate, states: Map): boolean { +function predecessorsReady(gate: Gate, states: Map): boolean { return (gate.needs ?? []).every(id => states.get(id) === 'passed') + && (gate.after ?? []).every(id => gateSettled(states.get(id))) +} + +function gateSettled(state: GateState | undefined): boolean { + return state === 'passed' || state === 'failed' || state === 'skipped' +} + +function gateFailed(state: GateState | undefined): boolean { + return state === 'failed' || state === 'skipped' } /** @@ -823,10 +865,12 @@ export async function runGate(gate: Gate): Promise { child.stdout.setEncoding('utf8') child.stderr.setEncoding('utf8') child.stdout.on('data', (chunk: string) => { - output.push({ stream: 'stdout', text: chunk }) + if (gate.streamOutput === true) process.stdout.write(chunk) + else output.push({ stream: 'stdout', text: chunk }) }) child.stderr.on('data', (chunk: string) => { - output.push({ stream: 'stderr', text: chunk }) + if (gate.streamOutput === true) process.stderr.write(chunk) + else output.push({ stream: 'stderr', text: chunk }) }) child.on('error', (error) => { spawnError = `failed to start command: ${error.message}` @@ -880,7 +924,7 @@ function printResult(result: GateResult): void { console.error(`command: ${result.gate.displayCommand}`) console.error(`outcome: ${formatGateResultReason(result)}`) } - printOutput(result.output) + if (result.gate.streamOutput !== true) printOutput(result.output) } function printSummary(results: GateResult[], durationMs: number): void { diff --git a/scripts/run-web-snapshots.ts b/scripts/run-web-snapshots.ts new file mode 100644 index 0000000000..c73047085c --- /dev/null +++ b/scripts/run-web-snapshots.ts @@ -0,0 +1,48 @@ +/** Run serial browser owners before one bounded snapshot pool. */ +import { spawn } from 'node:child_process' + +const serialFiles = [ + 'apps/web/tests/hmr-live.e2e.ts', + 'apps/web/tests/cordis-tool-round.e2e.ts', +] +const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS +const workers = Number.parseInt(workerRaw ?? '', 10) +if (!Number.isSafeInteger(workers) || workers < 2 || String(workers) !== workerRaw) { + throw new Error(`DSH_WEB_SNAPSHOT_WORKERS must be an integer greater than 1, got ${JSON.stringify(workerRaw)}.`) +} +const pnpmEntrypoint = process.env.npm_execpath +if (pnpmEntrypoint === undefined || pnpmEntrypoint === '') { + throw new Error('parallel web snapshots must be invoked through a pnpm package script.') +} + +const baseArgs = [pnpmEntrypoint, 'exec', 'vitest', 'run', '--config', 'vitest.web.config.ts'] +let serialStatus = 0 +for (const file of serialFiles) { + serialStatus = await run([...baseArgs, file]) + if (serialStatus !== 0) break +} +if (serialStatus === 0) { + process.exitCode = await run([ + ...baseArgs, + ...serialFiles.map(file => `--exclude=${file}`), + '--fileParallelism', + `--maxWorkers=${String(workers)}`, + ]) +} else { + process.exitCode = serialStatus +} + +function run(args: string[]): Promise { + return new Promise((resolveRun, reject) => { + const child = spawn(process.execPath, args, { stdio: 'inherit' }) + child.once('error', reject) + child.once('exit', (exitCode, signalCode) => { + if (signalCode !== null) { + console.error(`web snapshots terminated by ${signalCode}`) + resolveRun(1) + return + } + resolveRun(exitCode ?? 1) + }) + }) +} diff --git a/scripts/snapshots/translation-prompt-v4/request-response.expected.json b/scripts/snapshots/translation-prompt-v4/request-response.expected.json index 286c07b62a..ddffa0c246 100644 --- a/scripts/snapshots/translation-prompt-v4/request-response.expected.json +++ b/scripts/snapshots/translation-prompt-v4/request-response.expected.json @@ -12,7 +12,7 @@ }, { "role": "assistant", - "content": "# DeepSeek Harness\n\n[English](README.md) | 中文\n\nDeepSeek Harness(`dsh`)是由 [DeepSeek AI](https://deepseek.com) 开发的开源 agent harness(智能体框架)。\n\n它采用**一切皆插件**的架构,并由 [Cordis](https://github.com/cordiverse/cordis) 驱动,其设计参见论文 [_A Programming Paradigm for Spatiotemporal Composability_](https://github.com/cordiverse/paper)。\n\n## 开发者预览\n\nDeepSeek Harness 目前处于 _开发者预览_ 阶段,正在快速迭代。**未来将出现破坏兼容性的变更。**\n\n## 运行\n\n### 通过 `npm` 运行\n\n安装 `Node.js`,然后运行:\n\n```sh\nnpx @deepseek-ai/dsh web\n```\n\n该命令会启动 Web UI,默认地址为 `http://127.0.0.1:3080`。详见 [Web UI 指南](docs/user/guide/index.md)。\n\n### 从源码运行\n\n如需从仓库源码运行:\n\n```sh\ngit clone https://github.com/deepseek-ai/deepseek-harness.git\ncd deepseek-harness\npnpm install\npnpm run build\npnpm dsh web\n```\n\n## 社区与支持\n\n- 欢迎通过 [GitHub Discussions](https://github.com/deepseek-ai/deepseek-harness/discussions) 提交反馈或 bug 报告。\n- 为你的插件仓库添加 [`dsh-plugin`](https://github.com/topics/dsh-plugin) 话题,便于被发现。\n- 欢迎加入 DeepSeek Harness 企微群:扫码添加企微小助手并填写入群问卷,完成后小助手会邀请你入群。\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      企微小助手入群问卷微信公众号
      \"DeepSeek\"DeepSeek\"DeepSeek
      \n\n## 参与贡献\n\n参见 [CONTRIBUTING.md](CONTRIBUTING.md)。\n\n## 开发\n\n请先阅读[开发指南](docs/development.md)与[架构文档](docs/architecture.md)。\n\n面向 agent:请遵循 [AGENTS.md](AGENTS.md)。\n\n## 许可证\n\n[MIT](LICENSE)\n\n第三方依赖及其许可证见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。\n" + "content": "# DeepSeek Harness\n\n[English](README.md) | 中文\n\nDeepSeek Harness(`dsh`)是由 [DeepSeek AI](https://deepseek.com) 开发的开源 agent harness(智能体框架)。\n\n它采用**一切皆插件**的架构,并由 [Cordis](https://github.com/cordiverse/cordis) 驱动,其设计参见论文 [_A Programming Paradigm for Spatiotemporal Composability_](https://github.com/cordiverse/paper)。\n\n## 开发者预览\n\nDeepSeek Harness 目前处于 _开发者预览_ 阶段,正在快速迭代。**未来将出现破坏兼容性的变更。**\n\n## 运行\n\n### 通过 `npm` 运行\n\n安装 `Node.js`,然后运行:\n\n```sh\nnpx @deepseek-ai/dsh web\n```\n\n该命令会启动 Web UI,默认地址为 `http://127.0.0.1:3080`。详见 [Web UI 指南](docs/user/guide/index.md)。\n\n### 从源码运行\n\n如需从仓库源码运行:\n\n```sh\ngit clone https://github.com/deepseek-ai/deepseek-harness.git\ncd deepseek-harness\npnpm install\npnpm run build\npnpm dsh web\n```\n\n## 社区与支持\n\n- 欢迎通过 [GitHub Discussions](https://github.com/deepseek-ai/deepseek-harness/discussions) 提交反馈或 bug 报告。\n- 为你的插件仓库添加 [`dsh-plugin`](https://github.com/topics/dsh-plugin) 话题,便于被发现。\n- 欢迎加入 DeepSeek Harness 企微群:扫码添加企微小助手并填写入群问卷,完成后小助手会邀请你入群。\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      企微小助手入群问卷微信公众号
      \"DeepSeek\"DeepSeek\"DeepSeek
      \n\n## 参与贡献\n\n参见 [CONTRIBUTING.md](CONTRIBUTING.md)。\n\n## 开发\n\n请先阅读[开发指南](docs/development.md)与[架构文档](docs/architecture.md)。\n\n面向 agent:请遵循 [AGENTS.md](AGENTS.md)。\n\n## 许可证\n\n[MIT](LICENSE)\n\n第三方依赖及其许可证见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。\n" }, { "role": "user", diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index cbd01a6fc8..102df3ca65 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -301,6 +301,26 @@ "symbol": "ScheduleView", "source": "packages/schedule/schedule/src/types.ts" }, + { + "doc": "docs/subsystems/team.md", + "symbol": "TeamMemberSnapshot", + "source": "packages/experimental/team/src/types.ts" + }, + { + "doc": "docs/subsystems/team.md", + "symbol": "TeamMessageSnapshot", + "source": "packages/experimental/team/src/types.ts" + }, + { + "doc": "docs/subsystems/team.md", + "symbol": "TeamMessageSource", + "source": "packages/experimental/team/src/types.ts" + }, + { + "doc": "docs/subsystems/team.md", + "symbol": "TeamTaskSnapshot", + "source": "packages/experimental/team/src/types.ts" + }, { "doc": "docs/subsystems/commands.md", "symbol": "CommandInputDescriptor", diff --git a/scripts/verify-config-source-ownership.spec.ts b/scripts/verify-config-source-ownership.spec.ts index 41026c5fe4..3a099156c2 100644 --- a/scripts/verify-config-source-ownership.spec.ts +++ b/scripts/verify-config-source-ownership.spec.ts @@ -14,7 +14,7 @@ describe('configuration source ownership gate', () => { it('rejects inline endpoints in shipped bundle patches', () => { const root = mkdtempSync(join(tmpdir(), 'dsh-config-source-ownership-')) roots.push(root) - const directory = join(root, 'packages/bundle/base') + const directory = join(root, 'packages/subagent/subagent-claude-code') mkdirSync(directory, { recursive: true }) writeFileSync( join(directory, 'cordis.patch.yml'), @@ -22,7 +22,7 @@ describe('configuration source ownership gate', () => { ) expect(collectConfigSourceOwnershipViolations(root)).toEqual([ - 'packages/bundle/base/cordis.patch.yml:2: inlines a credential or endpoint from the environment.' + 'packages/subagent/subagent-claude-code/cordis.patch.yml:2: inlines a credential or endpoint from the environment.' + ' The adapter resolves apiKeyEnv through ctx.credentials and the endpoint through the' + ' environment snapshot; inlining here bypasses both ladders.', ]) diff --git a/scripts/verify-config-source-ownership.ts b/scripts/verify-config-source-ownership.ts index 0684124215..c42e7cb793 100644 --- a/scripts/verify-config-source-ownership.ts +++ b/scripts/verify-config-source-ownership.ts @@ -14,7 +14,8 @@ const SHIPPED_CONFIG_GLOBS = [ 'apps/*/config/*.yml', 'examples/*/*.cordis.yml', 'examples/*/cordis.yml', - 'packages/bundle/*/cordis.patch.yml', + // Bundle identity comes from the package manifest, not the domain directory. + 'packages/*/*/cordis.patch.yml', // The Python runtime ships its own default composition inside the wheel. 'python/*/src/**/cordis.yml', ] diff --git a/scripts/verify-cordis-config.spec.ts b/scripts/verify-cordis-config.spec.ts index 6c1304e16a..f63031e46c 100644 --- a/scripts/verify-cordis-config.spec.ts +++ b/scripts/verify-cordis-config.spec.ts @@ -4,8 +4,15 @@ * metadata field must stay static, and a disabled expression must parse. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { metadataExpressionErrors } from './verify-cordis-config.ts' +import { + bundleManifestPaths, + bundlePluginDependencyErrors, + metadataExpressionErrors, +} from './verify-cordis-config.ts' describe('verify-cordis-config metadata expressions', () => { it('accepts a disabled !!js expression', () => { @@ -37,3 +44,45 @@ describe('verify-cordis-config metadata expressions', () => { expect(problems.some(problem => problem.includes('[0].disabled: disabled expression does not parse'))).toBe(true) }) }) + +describe('workspace Bundle discovery and product dependency closures', () => { + it('discovers a Bundle outside packages/bundle from its manifest declaration', () => { + const fixture = mkdtempSync(join(tmpdir(), 'dsh-bundle-discovery-')) + try { + const bundleDir = join(fixture, 'packages/subagent/example') + const plainDir = join(fixture, 'packages/bundle/plain') + mkdirSync(bundleDir, { recursive: true }) + mkdirSync(plainDir, { recursive: true }) + writeFileSync(join(bundleDir, 'package.json'), JSON.stringify({ + name: '@deepseek-ai/dsh-subagent-example', + dsh: { bundle: { patch: './cordis.patch.yml' } }, + })) + writeFileSync(join(plainDir, 'package.json'), JSON.stringify({ + name: '@deepseek-ai/dsh-plain', + })) + + expect(bundleManifestPaths(fixture)).toEqual([ + 'packages/subagent/example/package.json', + ]) + } finally { + rmSync(fixture, { recursive: true, force: true }) + } + }) + + it('allows a Bundle to mount itself but rejects an undeclared plugin package', () => { + const manifestPath = 'packages/subagent/example/package.json' + const file = 'packages/subagent/example/cordis.patch.yml' + const manifest = { + name: '@deepseek-ai/dsh-subagent-example', + dependencies: {}, + } + const self = { file, name: '@deepseek-ai/dsh-subagent-example' } + expect(bundlePluginDependencyErrors(manifestPath, manifest, [self])).toEqual([]) + expect(bundlePluginDependencyErrors(manifestPath, manifest, [ + self, + { file, name: '@deepseek-ai/dsh-missing-plugin' }, + ])).toEqual([ + `${file}: @deepseek-ai/dsh-missing-plugin must be declared in ${manifestPath} dependencies`, + ]) + }) +}) diff --git a/scripts/verify-cordis-config.ts b/scripts/verify-cordis-config.ts index f2e0aef46c..281be99f50 100644 --- a/scripts/verify-cordis-config.ts +++ b/scripts/verify-cordis-config.ts @@ -20,12 +20,14 @@ interface JsExpr { __jsExpr: string } -interface PackageManifest { +export interface PackageManifest { name?: string dependencies?: Record + optionalDependencies?: Record + dsh?: { bundle?: { patch?: string } } } -interface PluginReference { +export interface PluginReference { file: string name: string } @@ -260,11 +262,14 @@ function validateExampleResolution(): string[] { function validateAppResolution(): string[] { const violations: string[] = [] + const bundleManifests = bundleManifestPaths() // App overlays (and any config left under apps/cli/config) resolve from the // dsh app's own dependency surface — the profile module fallback mirrors it. const appDependencies = { ...readManifest('apps/cli/package.json').dependencies, - // The fallback also links every bundle's own dependencies (healProfilesModuleFallback). + // The fallback also links every in-box bundle's own dependencies + // (healProfilesModuleFallback). Optional Profile bundles stay outside the + // app installation until that Profile installs them. ...Object.fromEntries(globSync('packages/bundle/*/package.json', { cwd: root }) .flatMap(file => Object.entries(readManifest(file).dependencies ?? {}))), } @@ -274,20 +279,50 @@ function validateAppResolution(): string[] { violations.push(...missingPluginDependencies(appReferences, appDependencies, 'apps/cli/package.json or a bundle manifest')) // Each bundle's patch rows must resolve from that bundle's own dependencies: // per-layer resolution anchors on the bundle package directory. - for (const manifestPath of globSync('packages/bundle/*/package.json', { cwd: root })) { + for (const manifestPath of bundleManifests) { const bundleDir = manifestPath.replace(/\/package\.json$/, '') const manifest = readManifest(manifestPath) - const references = pluginReferences.filter(reference => reference.file.startsWith(`${bundleDir}/`)) - violations.push(...missingPluginDependencies( - // A bundle may mount its own package (the web-app runtime row). - references.filter(reference => packageNameFromSpecifier(reference.name) !== manifest.name), - manifest.dependencies ?? {}, - manifestPath, - )) + const patch = manifest.dsh?.bundle?.patch + if (typeof patch !== 'string') continue + const patchFile = relative(root, resolve(root, bundleDir, patch)).replaceAll('\\', '/') + const references = pluginReferences.filter(reference => reference.file === patchFile) + violations.push(...bundlePluginDependencyErrors(manifestPath, manifest, references)) } return violations } +/** + * Discover workspace Bundle packages from their manifest declaration. + * @param repoRoot Repository root to scan. + * @returns Sorted slash-normalized repository-relative package manifest paths. + */ +export function bundleManifestPaths(repoRoot: string = root): string[] { + return globSync('packages/*/*/package.json', { cwd: repoRoot }) + .filter(path => typeof readManifest(path, repoRoot).dsh?.bundle?.patch === 'string') + .map(path => path.replaceAll('\\', '/')) + .sort() +} + +/** + * Validate plugin packages referenced by one Bundle patch. + * @param manifestPath Repository-relative Bundle manifest path. + * @param manifest Parsed Bundle manifest. + * @param references Plugin rows read from the Bundle package directory. + * @returns Missing production dependency diagnostics. + */ +export function bundlePluginDependencyErrors( + manifestPath: string, + manifest: PackageManifest, + references: readonly PluginReference[], +): string[] { + return missingPluginDependencies( + // A Bundle may mount its own package (for example, its provider or runtime row). + references.filter(reference => packageNameFromSpecifier(reference.name) !== manifest.name), + manifest.dependencies ?? {}, + manifestPath, + ) +} + /** * Every configured specifier of a local workspace package must resolve through * the tsconfig `paths` facade to a `.ts`/`.tsx` source file. The `dsh` source @@ -363,8 +398,8 @@ function missingPluginDependencies( : `${[...locations].join(', ')}: ${packageName} must be declared in ${manifestPath} dependencies`) } -function readManifest(path: string): PackageManifest { - return JSON.parse(readFileSync(resolve(root, path), 'utf8')) as PackageManifest +function readManifest(path: string, repoRoot: string = root): PackageManifest { + return JSON.parse(readFileSync(resolve(repoRoot, path), 'utf8')) as PackageManifest } function localPackageDirectories(): Map { diff --git a/tsconfig.base.json b/tsconfig.base.json index 0fadc24b79..472597008e 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -120,6 +120,7 @@ "./packages/preset/*/src/invariant.ts", "./packages/subagent/*/src/invariant.ts", "./packages/jobs/*/src/invariant.ts", + "./packages/experimental/*/src/invariant.ts", "./packages/workflow/*/src/invariant.ts", "./packages/web/*/src/invariant.ts", "./packages/attachment/*/src/invariant.ts", @@ -251,6 +252,7 @@ "./packages/preset/*/src", "./packages/subagent/*/src", "./packages/jobs/*/src", + "./packages/experimental/*/src", "./packages/workflow/*/src", "./packages/web/*/src", "./packages/attachment/*/src", diff --git a/tsconfig.host.json b/tsconfig.host.json index e3667144f2..e203bc2343 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -13,11 +13,13 @@ "apps/web/tests/declared-reasoning.e2e.ts", "apps/web/tests/support.ts", "apps/web/tests/scaffold-hermetic.e2e.ts", + "apps/web/tests/startup-rpc-budget.e2e.ts", "apps/web/tests/minimal-preset.snapshot.ts", "apps/web/tests/message-feedback-protocol.snapshot.ts", "apps/web/tests/live-interactions.e2e.ts", "apps/web/tests/question-composer.e2e.ts", "apps/web/tests/approval-composer.e2e.ts", + "apps/web/tests/plan-control-row.e2e.ts", "apps/web/tests/plan-review.e2e.ts", "apps/web/tests/steering.e2e.ts", "apps/web/tests/navigation-panes.e2e.ts", @@ -269,6 +271,8 @@ { "path": "./packages/jobs/jobs" }, { "path": "./packages/jobs/jobs-local" }, { "path": "./packages/jobs/tool-jobs" }, + { "path": "./packages/experimental/team" }, + { "path": "./packages/experimental/tool-team" }, { "path": "./packages/workflow/workflow" }, { "path": "./packages/workflow/workflow-worker-thread" }, { "path": "./packages/workflow/tool-workflow" }, diff --git a/vitest.config.ts b/vitest.config.ts index 1c351fab6e..b255083cb8 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -5,6 +5,7 @@ import { resolvePwshPath } from './packages/shell/pwsh-local/src/resolve.ts' import { defineConfig } from 'vitest/config' import { standardDecoratorPlugin, vitestExecArgv } from './vitest.shared.ts' import { COVERAGE_EXEMPT_ENV, coverageExemptHeavySuites } from './scripts/coverage-exempt.ts' +import { COVERAGE_PARTITION_MODE_ENV } from './scripts/coverage-partitions.ts' // Prints exact `path:line:col` records for every uncovered statement, branch // path, and function when a file misses the per-file 100% gate — the built-in @@ -100,6 +101,12 @@ const coverageExemptExcludes = coverageExemptRaw === '1' ? coverageExemptHeavySuites.map(suite => suite.exclude) : [] +const coveragePartitionRaw = process.env[COVERAGE_PARTITION_MODE_ENV] +if (coveragePartitionRaw !== undefined && coveragePartitionRaw !== '' && coveragePartitionRaw !== '1') { + throw new Error(`vitest config: ${COVERAGE_PARTITION_MODE_ENV} must be '1' or unset, got ${JSON.stringify(coveragePartitionRaw)}.`) +} +const coveragePartitionMode = coveragePartitionRaw === '1' + // These suites exercise process-global state, process APIs, or timing-sensitive process I/O // that worker threads cannot isolate reliably under aggregate gate contention. // Keep the narrow exception in forks while the rest of the inventory avoids per-file processes. @@ -270,16 +277,20 @@ export default defineConfig({ // Per-file so a well-covered big file can't subsidize a bare one. // Every v8 ignore comment must carry a reason — see the quality-gates Agent Note // (.agents/notes/implemented/process/2026-06-11-quality-gates.md). - thresholds: { - perFile: true, - statements: 100, - branches: 100, - functions: 100, - lines: 100, - }, - reporter: process.env.CI - ? ['text', uncoveredLocationsReporter] - : ['text', 'html', uncoveredLocationsReporter], + thresholds: coveragePartitionMode + ? undefined + : { + perFile: true, + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, + reporter: coveragePartitionMode + ? [] + : process.env.CI + ? ['text', uncoveredLocationsReporter] + : ['text', 'html', uncoveredLocationsReporter], }, }, }) diff --git a/vitest.web.config.ts b/vitest.web.config.ts index 1179144f61..7c20ab6462 100644 --- a/vitest.web.config.ts +++ b/vitest.web.config.ts @@ -27,7 +27,8 @@ export default defineConfig({ 'apps/web/tests/**/*.e2e.ts', 'apps/web/tests/**/*.snapshot.ts', ], - // Browser boot + real-model turns are slow; files share one browser, run serial. + // Local and record runs stay serial. CI runs workspace-mutating HMR and + // dynamic Cordis lifecycle coverage before parallelizing the remaining files. testTimeout: 180_000, hookTimeout: 120_000, fileParallelism: false,