From 8c6179d69d9da06bb14d4babe746fdfd07aac8f5 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sat, 1 Aug 2026 18:48:17 +0800 Subject: [PATCH 01/61] feat(pwsh): add the pwsh-local executor and the pwsh tool Windows-native execution foundation: PwshLocalExecutor implements the bash executor seam over ctx.subprocess (pwsh -NoLogo -NoProfile -NonInteractive -Command, one argv element, no quoting layer; resolvePwshPath probes PowerShell 7 / PATH / Windows PowerShell 5.1 as a pure function), and tool-pwsh is the minimal PowerShell-dialect model-facing tool over ctx.bash (foreground only, managed DSH_* env, timeout/signal/exit markers, terminal and generic presenters). Both packages carry full suites (real pwsh, self-skipping without it) at per-file 100% coverage; vitest's Windows exclusion narrows from packages/bash/* to the bash-requiring packages so the pwsh suites run natively on Windows too. The CLI gains the workspace deps and tsconfig projects without mounting either plugin; the Windows-default roadmap is recorded as a proposed Agent Note. --- ...026-08-01-pwsh-tool-and-executor.i18n.yaml | 6 + .../2026-08-01-pwsh-tool-and-executor.md | 35 ++ .../2026-08-01-pwsh-tool-and-executor.zh.md | 35 ++ .../2026-08-01-windows-pwsh-default.i18n.yaml | 6 + .../2026-08-01-windows-pwsh-default.md | 41 ++ .../2026-08-01-windows-pwsh-default.zh.md | 41 ++ apps/cli/package.json | 2 + docs/config-catalog.md | 44 ++ docs/module-graph.md | 16 + docs/tool-catalog.md | 39 ++ knip.json | 1 + packages/bash/pwsh-local/README.i18n.yaml | 6 + packages/bash/pwsh-local/README.md | 53 +++ packages/bash/pwsh-local/README.zh.md | 53 +++ packages/bash/pwsh-local/package.json | 47 ++ packages/bash/pwsh-local/src/index.ts | 316 ++++++++++++++ packages/bash/pwsh-local/src/invariant.ts | 30 ++ .../bash/pwsh-local/tests/executor.spec.ts | 412 ++++++++++++++++++ packages/bash/pwsh-local/tsconfig.json | 36 ++ packages/bash/tool-pwsh/README.i18n.yaml | 6 + packages/bash/tool-pwsh/README.md | 107 +++++ packages/bash/tool-pwsh/README.zh.md | 107 +++++ packages/bash/tool-pwsh/package.json | 56 +++ packages/bash/tool-pwsh/src/index.ts | 254 +++++++++++ packages/bash/tool-pwsh/src/invariant.ts | 30 ++ .../bash/tool-pwsh/tests/integration.spec.ts | 119 +++++ packages/bash/tool-pwsh/tests/tools.spec.ts | 296 +++++++++++++ packages/bash/tool-pwsh/tsconfig.json | 45 ++ pnpm-lock.yaml | 71 +++ scripts/gen-tool-catalog.ts | 19 + .../verify-package-readme-model-experience.ts | 1 + tsconfig.base.json | 2 + tsconfig.host.json | 2 + vitest.config.ts | 8 +- 34 files changed, 2341 insertions(+), 1 deletion(-) create mode 100644 .agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md create mode 100644 .agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.zh.md create mode 100644 .agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.md create mode 100644 .agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.zh.md create mode 100644 packages/bash/pwsh-local/README.i18n.yaml create mode 100644 packages/bash/pwsh-local/README.md create mode 100644 packages/bash/pwsh-local/README.zh.md create mode 100644 packages/bash/pwsh-local/package.json create mode 100644 packages/bash/pwsh-local/src/index.ts create mode 100644 packages/bash/pwsh-local/src/invariant.ts create mode 100644 packages/bash/pwsh-local/tests/executor.spec.ts create mode 100644 packages/bash/pwsh-local/tsconfig.json create mode 100644 packages/bash/tool-pwsh/README.i18n.yaml create mode 100644 packages/bash/tool-pwsh/README.md create mode 100644 packages/bash/tool-pwsh/README.zh.md create mode 100644 packages/bash/tool-pwsh/package.json create mode 100644 packages/bash/tool-pwsh/src/index.ts create mode 100644 packages/bash/tool-pwsh/src/invariant.ts create mode 100644 packages/bash/tool-pwsh/tests/integration.spec.ts create mode 100644 packages/bash/tool-pwsh/tests/tools.spec.ts create mode 100644 packages/bash/tool-pwsh/tsconfig.json diff --git a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.i18n.yaml b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.i18n.yaml new file mode 100644 index 0000000000..4ced84e22c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.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/feature/2026-08-01-pwsh-tool-and-executor.md +2026-08-01-pwsh-tool-and-executor.md: fd73e929804045d7b810a587c6f088b2f7cff9cc +2026-08-01-pwsh-tool-and-executor.zh.md: f55be1ad0e102311d09b8b7ee1a003778e679cb2 diff --git a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md new file mode 100644 index 0000000000..fd73e92980 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md @@ -0,0 +1,35 @@ +# Agent Note: PowerShell executor and pwsh tool + +Status: implemented + +English | [中文](2026-08-01-pwsh-tool-and-executor.zh.md) + +## Problem + +The harness spoke one shell dialect on every platform: `bash`. Windows hosts could run it only through WSL or Git-Bash shims, and the shipped `dsh-bash-local` executor is POSIX-only (`bash` hardcoded, process-group semantics POSIX). The Windows roadmap — defaulting hosts to `pwsh`, later pwsh TUI/GUI rendering — had no execution foundation: there was no PowerShell implementation of the bash executor seam and no model-facing tool that taught the PowerShell dialect. The bash tool itself is also far larger than a Windows-first profile needs: background tasks, sandbox escalation, and the persistent-PTY twin are all bash-shaped surface that a minimal `pwsh` tool should not carry. + +## Decision + +Two new packages under `packages/bash/`: + +- **`@deepseek-ai/dsh-pwsh-local`** — a local implementation of the `ctx.bash` executor seam over `ctx.subprocess`, mirroring `dsh-bash-local` call-for-call: `resolve()` defaults and caps from config, `run()` fuses the config-clamped timeout with the caller's signal through one deadline, `start()` returns a consuming background handle whose processes belong to the subprocess service. The command string rides as ONE argv element to `pwsh -NoLogo -NoProfile -NonInteractive -Command`, so PowerShell parses it and no shell-quoting layer exists. Executable resolution (`resolvePwshPath`) is a pure function of `(configured, env, platform)`: explicit config first, then Windows probes PowerShell 7's install, PATH entries (quotes stripped), and Windows PowerShell 5.1, else a bare `pwsh` via PATH. +- **`@deepseek-ai/dsh-tool-pwsh`** — the minimal model-facing tool over `ctx.bash`, PowerShell-dialect by contract: foreground only, no `run_in_background`, no sandbox escalation, managed `DSH_*` environment (`DSH_HOME`, `DSH_SHELL=1`, `DSH_SESSION_ID`), result markers `[exit code: N]` / `[timed out after …]` / `[killed by signal: …]`, and `terminal`/`generic` UI presenters. + +Windows vitest coverage is deliberately NOT part of this change: the repo's Windows CI lane owns build/static gates, and unit coverage runs on Linux, where both packages' suites run against a real `pwsh` (preinstalled on the GitHub-hosted runners) or self-skip when absent. The vitest `windowsUnsupportedPackages` exclusion narrows from `packages/bash/*` to the bash-requiring packages so the pwsh suites can also run natively on Windows dev machines. + +The roadmap beyond this decision — defaulting Windows hosts to `pwsh` (bash off), and pwsh TUI/GUI rendering — is recorded separately as [a proposal](../../proposed/feature/2026-08-01-windows-pwsh-default.md). + +## Alternatives considered + +**Extend `dsh-bash-local` with a pwsh mode.** Rejected: the executor's identity is the shell it spawns; a second dialect inside one package doubles its config surface (`shell` switches) and its test matrix, and the two dialects' quirks (signal facts on Windows, quoting domains) belong to their own packages' documentation. + +**Extend `dsh-tool-bash` with a dialect parameter.** Rejected: the bash tool's background/sandbox surface is bash-shaped; a `pwsh` mode would either hide it (conditional schema churn) or inherit it (surface the minimal profile explicitly rejects). The minimal twin keeps the model contract honest. + +**Wire the pwsh tool into the shipped CLI compositions now.** Rejected: mounting `tool-pwsh` + `pwsh-local` in `base.cordis.yml` would change the shipped roster before the Windows-default decision lands; this change ships the capability and its wiring points (`apps/cli` dependencies, tsconfig projects) without switching any default. + +## Consequences + +- The bash executor seam gains a second, Windows-native implementation with an identical request/spec contract, so model-facing consumers beyond `tool-pwsh` (hooks bridges, in-process plugins) can run PowerShell without dialect shims. +- `tool-pwsh` is the model-visible Windows-first profile: no background tasks or escalation to mislead a model into assuming bash-tool parity, and the prompt guidance pins the `[exit code: N]` contract. +- Windows semantics differ where the platform differs: forced termination reports exit 1 with no signal (so `signal`/`killed` status facts are POSIX-only), and PowerShell writes CRLF, which tests normalize. +- The CLI gains two workspace dependencies and two tsconfig projects without mounting either plugin — the composition decision stays with the Windows-default proposal. diff --git a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.zh.md b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.zh.md new file mode 100644 index 0000000000..f55be1ad0e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.zh.md @@ -0,0 +1,35 @@ +# Agent Note: PowerShell 执行器与 pwsh 工具 + +Status: implemented + +[English](2026-08-01-pwsh-tool-and-executor.md) | 中文 + +## 问题 + +harness 在每个平台只说一种 shell 方言:`bash`。Windows 主机只能通过 WSL 或 Git-Bash 垫片运行它,而交付的 `dsh-bash-local` 执行器仅限 POSIX(硬编码 `bash`,进程组语义是 POSIX 的)。Windows 路线图——让主机默认 `pwsh`,之后再做 pwsh TUI/GUI 渲染——没有执行基础:既没有 bash 执行器 seam 的 PowerShell 实现,也没有教模型 PowerShell 方言的面向模型工具。bash 工具本身也远大于 Windows 优先画像所需:后台任务、沙箱升级与持久 PTY 孪生都是 bash 形状的表面,最小化的 `pwsh` 工具不该背负。 + +## 决策 + +在 `packages/bash/` 下新增两个包: + +- **`@deepseek-ai/dsh-pwsh-local`** —— `ctx.bash` 执行器 seam 的本地实现,基于 `ctx.subprocess`,逐调用镜像 `dsh-bash-local`:`resolve()` 从配置默认化并设上限,`run()` 通过一个 deadline 融合配置夹取的超时与调用方信号,`start()` 返回消费式后台句柄,其进程归属于 subprocess 服务。命令字符串作为 ONE argv 元素传给 `pwsh -NoLogo -NoProfile -NonInteractive -Command`,由 PowerShell 解析,不存在 shell 引号层。可执行文件解析(`resolvePwshPath`)是 `(configured, env, platform)` 的纯函数:先显式配置,再在 Windows 上探测 PowerShell 7 安装位置、PATH 条目(剥离引号)与 Windows PowerShell 5.1,否则经 PATH 解析裸 `pwsh`。 +- **`@deepseek-ai/dsh-tool-pwsh`** —— 基于 `ctx.bash` 的最小面向模型工具,契约是 PowerShell 方言:仅前台,没有 `run_in_background`,没有沙箱升级,受管 `DSH_*` 环境(`DSH_HOME`、`DSH_SHELL=1`、`DSH_SESSION_ID`),结果标记 `[exit code: N]` / `[timed out after …]` / `[killed by signal: …]`,以及 `terminal`/`generic` UI presenter。 + +Windows vitest 覆盖率刻意不属本次改动:仓库的 Windows CI 通道负责构建/静态门禁,单元覆盖在 Linux 上运行,两个包的套件在那里以真实 `pwsh` 运行(GitHub 托管 runner 预装)或缺失时自行跳过。vitest 的 `windowsUnsupportedPackages` 排除从 `packages/bash/*` 收窄为真正需要 bash 的包,使 pwsh 套件也能在 Windows 开发机上原生运行。 + +本决策之后的路线图——让 Windows 主机默认 `pwsh`(关闭 bash)与 pwsh TUI/GUI 渲染——另行记录为[提案](../../proposed/feature/2026-08-01-windows-pwsh-default.md)。 + +## 备选方案 + +**给 `dsh-bash-local` 增加 pwsh 模式。** 否决:执行器的身份就是它 spawn 的 shell;在一个包内塞第二种方言会翻倍配置面(`shell` 开关)与测试矩阵,且两种方言的怪癖(Windows 上的信号实情、引号域)应各自归入自己包的文档。 + +**给 `dsh-tool-bash` 增加方言参数。** 否决:bash 工具的后台/沙箱表面是 bash 形状的;`pwsh` 模式要么隐藏它(条件 schema 翻动),要么继承它(把最小画像明确拒绝的表面带进来)。最小孪生让模型契约保持诚实。 + +**现在就接入交付的 CLI 组合。** 否决:在 Windows 默认决策落地前把 `tool-pwsh` + `pwsh-local` 挂进 `base.cordis.yml` 会改变交付清单;本改动交付能力与接线点(`apps/cli` 依赖、tsconfig 工程),不切换任何默认。 + +## 后果 + +- bash 执行器 seam 有了第二个、Windows 原生的实现,请求/规范契约一致,因此 `tool-pwsh` 之外的面向模型消费方(hooks 桥、进程内插件)无需方言垫片即可运行 PowerShell。 +- `tool-pwsh` 是模型可见的 Windows 优先画像:没有后台任务或升级会让模型误以为与 bash 工具对等,提示词指导钉住 `[exit code: N]` 契约。 +- Windows 语义在平台差异处不同:强制终止报告退出码 1 且无信号(因此 `signal`/`killed` 状态实情仅限 POSIX),PowerShell 输出 CRLF,测试做归一化。 +- CLI 增加两个 workspace 依赖与两个 tsconfig 工程,但不挂载任一插件——组合决策留给 Windows 默认提案。 diff --git a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.i18n.yaml b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.i18n.yaml new file mode 100644 index 0000000000..882e7478d3 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.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/proposed/feature/2026-08-01-windows-pwsh-default.md +2026-08-01-windows-pwsh-default.md: 6f3e48f33d98b2d2da7bd288d42a0d2763163ba3 +2026-08-01-windows-pwsh-default.zh.md: 270fd8d95c85400c302540376932228a6023447c diff --git a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.md b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.md new file mode 100644 index 0000000000..6f3e48f33d --- /dev/null +++ b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.md @@ -0,0 +1,41 @@ +# Agent Note: Windows defaults to pwsh (roadmap) + +Status: proposed + +English | [中文](2026-08-01-windows-pwsh-default.zh.md) + +## Problem + +The harness's shipped execution profile is bash-first on every platform. Windows hosts must install a bash shim (WSL or Git-Bash) or fall back to the POSIX-only `dsh-bash-local` behavior; the model-facing bash tool teaches the bash dialect, and the TUI/Web surfaces render terminal output in bash-shaped expectations. The first Windows-native foundation shipped in the [pwsh executor and tool decision](../../implemented/feature/2026-08-01-pwsh-tool-and-executor.md): a PowerShell implementation of the `ctx.bash` seam and a minimal `pwsh` tool — but nothing yet defaults Windows hosts to them. + +## Proposal + +Three follow-up stages, each independently shippable: + +1. **Windows default composition** — the shipped CLI compositions mount `dsh-pwsh-local` as the `ctx.bash` executor and `dsh-tool-pwsh` as the model-facing shell tool on Windows hosts (bash unmounted there), while POSIX hosts keep the bash stack. This is a composition/roster decision in `base.cordis.yml` and the surface overlays, gated by platform; it makes the shipped Windows experience PowerShell-native end to end. +2. **Bash-tool parity twin** — `tool-pwsh` grows the bash tool's missing surface where Windows workflows prove it: `run_in_background` through the generic task runtime, and the persistence-side `DSH_SESSION_JSONL` environment fact. Sandbox escalation stays out until a Windows-confining executor exists. +3. **pwsh TUI/GUI rendering** — the TUI and Web surfaces render pwsh output with PowerShell-aware presentation (native path display, `$env:` facts), the counterpart of the bash terminal cards. This is where terminal/console rendering conventions get a PowerShell twin. + +The stages are deliberately sequenced: composition first (a Windows user gets PowerShell without choosing), then tool parity, then rendering. Nothing in this proposal changes POSIX behavior. + +## Alternatives considered + +**Default Windows to pwsh inside `dsh-bash-local` (one executor, dialect switch).** Rejected for the same reason the executor decision rejected a mode switch: the executor's identity is the shell it spawns, and platform-gated composition is a deployment choice, not an executor config. + +**Ship the Windows default in the same change as the executor/tool.** Rejected: the roster change needs its own evidence (what breaks when the shipped Windows tree stops mounting bash, which tools depend on bash semantics), and it belongs to a composition decision with the approval/PTY surface visible. + +**Keep bash on Windows via a shim and skip PowerShell defaults.** Rejected: it perpetuates the install-tax and the dialect mismatch the roadmap exists to remove; the shim is a deployment requirement, not a product behavior. + +## Acceptance criteria + +- A Windows host running the shipped `dsh` TUI/Web gets `pwsh` as its shell tool and PowerShell as the `ctx.bash` executor without configuration, and `bash` is absent from the model-visible roster there. +- POSIX hosts are byte-for-byte unaffected (same roster, same executor). +- The shipped-composition e2es assert the platform-gated roster on both families. +- Stage 2 lands with task-runtime integration tests; stage 3 lands with TUI/Web rendering snapshots for pwsh output. + +## Risks + +- **Bash-dependent composition rows** — any shipped plugin that assumes `bash` semantics (hook bridges executing shell hooks, workspace tooling) must be audited per stage; the audit may force a staged rollout rather than one switch. +- **Tool-behavior drift** — a minimal `tool-pwsh` that never grows parity invites models to write bash-shaped commands; the prompt guidance and dialect contract mitigate this only if the twin keeps pace. +- **Windows CI coverage gap** — unit coverage runs on Linux; Windows-only regressions in the pwsh stack surface through the Windows build/static lane and e2es, which must be extended per stage rather than assumed. +- **Rendering conventions** — a PowerShell twin for terminal cards is a UI design decision with snapshot surface; deferring it (stage 3) keeps stage 1 shippable without UI churn. diff --git a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.zh.md b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.zh.md new file mode 100644 index 0000000000..270fd8d95c --- /dev/null +++ b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.zh.md @@ -0,0 +1,41 @@ +# Agent Note: Windows 默认改用 pwsh(路线图) + +Status: proposed + +[English](2026-08-01-windows-pwsh-default.md) | 中文 + +## 问题 + +harness 交付的执行画像在每个平台都是 bash 优先。Windows 主机必须安装 bash 垫片(WSL 或 Git-Bash),或退回到仅 POSIX 的 `dsh-bash-local` 行为;面向模型的 bash 工具教的是 bash 方言,TUI/Web 表面以 bash 形状的预期渲染终端输出。第一块 Windows 原生基础已随 [pwsh 执行器与工具决策](../../implemented/feature/2026-08-01-pwsh-tool-and-executor.md) 交付:`ctx.bash` seam 的 PowerShell 实现与最小化的 `pwsh` 工具——但还没有任何东西让 Windows 主机默认使用它们。 + +## 提案 + +三个阶段,各自可独立交付: + +1. **Windows 默认组合**——交付的 CLI 组合在 Windows 主机上挂载 `dsh-pwsh-local` 作为 `ctx.bash` 执行器、`dsh-tool-pwsh` 作为面向模型的 shell 工具(那里不挂载 bash),POSIX 主机保持 bash 栈。这是 `base.cordis.yml` 与 surface 覆盖层里按平台门控的组合/清单决策;它让交付的 Windows 体验端到端 PowerShell 原生。 +2. **bash 工具对等孪生**——在 Windows 工作流证明需要的地方,`tool-pwsh` 补齐 bash 工具缺失的表面:经由通用任务运行时的 `run_in_background`,以及持久化侧 `DSH_SESSION_JSONL` 环境实情。在出现 Windows 约束执行器之前,沙箱升级保持缺席。 +3. **pwsh TUI/GUI 渲染**——TUI 与 Web 表面以 PowerShell 感知的呈现渲染 pwsh 输出(原生路径显示、`$env:` 实情),即 bash 终端卡片的对应物。这是终端/控制台渲染约定获得 PowerShell 孪生的地方。 + +各阶段刻意排序:先组合(Windows 用户无需选择即获得 PowerShell),再工具对等,最后渲染。本提案不改变任何 POSIX 行为。 + +## 备选方案 + +**在 `dsh-bash-local` 内部让 Windows 默认 pwsh(一个执行器,方言开关)。** 否决,理由与执行器决策否决模式开关相同:执行器的身份就是它 spawn 的 shell,而按平台门控的组合是部署选择,不是执行器配置。 + +**把 Windows 默认与执行器/工具一起交付。** 否决:清单变更需要自己的证据(交付的 Windows 树停挂 bash 后什么会坏、哪些工具依赖 bash 语义),并且它属于带批准/PTY 表面可见的组合决策。 + +**用垫片在 Windows 上保留 bash,跳过 PowerShell 默认。** 否决:这延续了安装税与路线图要消除的方言错配;垫片是部署要求,不是产品行为。 + +## 验收标准 + +- 运行交付版 `dsh` TUI/Web 的 Windows 主机无需配置即获得 `pwsh` 作为其 shell 工具、PowerShell 作为 `ctx.bash` 执行器,且那里的模型可见清单中没有 `bash`。 +- POSIX 主机逐字节不受影响(清单相同,执行器相同)。 +- 交付组合 e2e 在两个平台族上断言按平台门控的清单。 +- 阶段 2 附带任务运行时集成测试落地;阶段 3 附带 pwsh 输出的 TUI/Web 渲染快照落地。 + +## 风险 + +- **依赖 bash 的组合行**——任何假设 bash 语义的交付插件(执行 shell hooks 的 hooks 桥、工作区工具)必须按阶段审计;审计可能迫使分阶段推出而非一次切换。 +- **工具行为漂移**——永远不补齐对等的 `tool-pwsh` 会诱使模型写 bash 形状的命令;只有当孪生跟上节奏时,提示词指导与方言契约才能缓解这一点。 +- **Windows CI 覆盖缺口**——单元覆盖在 Linux 上运行;pwsh 栈里仅 Windows 的回归通过 Windows 构建/静态通道与 e2e 浮出,必须按阶段扩展而不是想当然。 +- **渲染约定**——终端卡片的 PowerShell 孪生是带快照表面的 UI 设计决策;把它延期(阶段 3)让阶段 1 无需 UI 翻动即可交付。 diff --git a/apps/cli/package.json b/apps/cli/package.json index 2269ceaffb..8d90f864e8 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -77,6 +77,7 @@ "@deepseek-ai/dsh-repeat-tool-guard": "workspace:^", "@deepseek-ai/dsh-pty": "workspace:^", "@deepseek-ai/dsh-pty-local": "workspace:^", + "@deepseek-ai/dsh-pwsh-local": "workspace:^", "@deepseek-ai/dsh-sandbox-local": "workspace:^", "@deepseek-ai/dsh-sandbox-policy": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", @@ -120,6 +121,7 @@ "@deepseek-ai/dsh-tool-skill": "workspace:^", "@deepseek-ai/dsh-tool-str-replace-editor": "workspace:^", "@deepseek-ai/dsh-tool-subagent": "workspace:^", + "@deepseek-ai/dsh-tool-pwsh": "workspace:^", "@deepseek-ai/dsh-tool-tasks": "workspace:^", "@deepseek-ai/dsh-tool-todo": "workspace:^", "@deepseek-ai/dsh-tool-web": "workspace:^", diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 20f835bb7f..46e563c323 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -963,6 +963,36 @@ export interface Config { Source: [`packages/pty/pty-local/src/config.ts:6`](../packages/pty/pty-local/src/config.ts) +## `@deepseek-ai/dsh-pwsh-local` + +Requires: `subprocess` + +```ts config-catalog +/** Plugin config (all optional — `static Config` supplies the defaults). */ +export interface Config { + /** Default working directory for commands (default: process.cwd()). */ + cwd?: string + /** Default foreground timeout in milliseconds. */ + timeoutMs?: number + /** Upper bound for per-call timeout overrides. */ + maxTimeoutMs?: number + /** Per-stream in-memory output cap; overflow spills to a temp file. */ + maxOutputBytes?: number + /** Per-stream spill-file cap; larger streams retain only their in-memory tail. */ + maxSpillBytes?: number + /** Grace period for kill escalation and for inherited pipes after shell exit. */ + graceMs?: number + /** + * Explicit pwsh executable. When omitted, well-known Windows install + * locations are probed first (PowerShell 7, then Windows PowerShell 5.1), + * falling back to a bare `pwsh` resolved through PATH. + */ + pwshPath?: string +} +``` + +Source: [`packages/bash/pwsh-local/src/index.ts:43`](../packages/bash/pwsh-local/src/index.ts) + ## `@deepseek-ai/dsh-repeat-tool-guard` ```ts config-catalog @@ -1788,6 +1818,20 @@ export interface Config { Source: [`packages/pty/tool-pty/src/index.ts:35`](../packages/pty/tool-pty/src/index.ts) +## `@deepseek-ai/dsh-tool-pwsh` + +Requires: `tools` · `bash` · `systemPrompt` + +```ts config-catalog +/** Plugin config (currently empty; kept as a schema so deployments can grow it). */ +export interface Config { + /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */ + dshHome?: string +} +``` + +Source: [`packages/bash/tool-pwsh/src/index.ts:31`](../packages/bash/tool-pwsh/src/index.ts) + ## `@deepseek-ai/dsh-tool-ralph` Requires: `tools` · `workflows` · `subagents` · `systemPrompt` diff --git a/docs/module-graph.md b/docs/module-graph.md index 87789c9edb..090aac7301 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -40,7 +40,9 @@ flowchart TD pkg_bash["bash"] pkg_bash_local["bash-local"] pkg_bash_sandbox["bash-sandbox"] + pkg_pwsh_local["pwsh-local"] pkg_tool_bash["tool-bash"] + pkg_tool_pwsh["tool-pwsh"] end subgraph group_fs["packages/fs"] pkg_fs["fs"] @@ -505,6 +507,10 @@ flowchart TD pkg_bash_local --> pkg_invariants pkg_bash_local --> pkg_subprocess pkg_bash_local --> pkg_timeout + pkg_pwsh_local --> pkg_bash + pkg_pwsh_local --> pkg_invariants + pkg_pwsh_local --> pkg_subprocess + pkg_pwsh_local --> pkg_timeout pkg_fs_local --> pkg_fs pkg_fs_local --> pkg_invariants pkg_fs_policy --> pkg_fs @@ -704,6 +710,14 @@ flowchart TD pkg_tool_bash --> pkg_tasks pkg_tool_bash --> pkg_tools pkg_tool_bash --> pkg_user_approval + pkg_tool_pwsh --> pkg_agent + pkg_tool_pwsh --> pkg_bash + pkg_tool_pwsh --> pkg_invariants + pkg_tool_pwsh --> pkg_llm + pkg_tool_pwsh --> pkg_paths + pkg_tool_pwsh --> pkg_session_persistence + pkg_tool_pwsh --> pkg_system_prompt + pkg_tool_pwsh --> pkg_tools pkg_tool_fs --> pkg_fs pkg_tool_fs --> pkg_invariants pkg_tool_fs --> pkg_llm @@ -1134,6 +1148,7 @@ flowchart TD | [`token-meter`](../packages/llm/token-meter) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session-projection/session-projection) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session-projection/session-projection) | | [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`pwsh-local`](../packages/bash/pwsh-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants) | | [`fs-policy`](../packages/fs/fs-policy) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants) | | [`skill-local`](../packages/skill/skill-local) | `skill` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`skill`](../packages/skill/skill) | @@ -1175,6 +1190,7 @@ flowchart TD | [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-bash`](../packages/bash/tool-bash) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | +| [`tool-pwsh`](../packages/bash/tool-pwsh) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | | [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) | diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index d19a7adf52..a00a2876a8 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -19,6 +19,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.codeRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/code-dispatch-start + tool/code-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated TypeScript SDK section, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`, `ctx.systemPrompt`, `ctx.userInteraction (execution time, opportunistic)` | `tool/call`, `plan/mode inactive on an approved review`, `tool/result` | - | exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-interaction seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary. | | `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.bash`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | +| `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. | | `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect`, `cordis_mount`, `cordis_unmount` | `ctx.tools` | `tool/call`, `tool/result`, `process-local temporary Plugin lifecycle` | - | Not in any shipped tree (a deliberate opt-in — temporary Plugin code reaches the real runtime, see .agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins created by cordis_mount may register ADDITIONAL model-visible tools until unmounted or DSH restarts; a full changed request header logs those tool-set changes. | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.tools`, `ctx.pty`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`, `ctx.fs` | `tool/call`, `fs/observed after successful file operations`, `tool/result` | - | Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal surface. | @@ -205,6 +206,44 @@ Source: [`packages/bash/tool-bash/src/index.ts`](../packages/bash/tool-bash/src/ The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. +## `@deepseek-ai/dsh-tool-pwsh` + +### `pwsh` + +Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. Each call runs in a fresh pwsh process: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\...`); read environment variables with `$env:NAME`. Non-zero exits are reported as `[exit code: N]`. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. + +```json +{ + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The PowerShell command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"Get-Process\" → \"List running processes\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + } + }, + "required": [ + "command", + "description" + ] +} +``` + +Source: [`packages/bash/tool-pwsh/src/index.ts`](../packages/bash/tool-pwsh/src/index.ts) + +The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. + ## `@deepseek-ai/dsh-tool-cordis` ### `cordis_inspect` diff --git a/knip.json b/knip.json index 30b1821cd3..b64e9cc403 100644 --- a/knip.json +++ b/knip.json @@ -5,6 +5,7 @@ ], "ignoreBinaries": [ "bwrap", + "pwsh", "python3", "sandbox-exec", "taskkill" diff --git a/packages/bash/pwsh-local/README.i18n.yaml b/packages/bash/pwsh-local/README.i18n.yaml new file mode 100644 index 0000000000..836ab2dd84 --- /dev/null +++ b/packages/bash/pwsh-local/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/bash/pwsh-local/README.md +README.md: a97612ab4e11bf4a3fcfb77daf0624a894b02ad4 +README.zh.md: d6751dac6df789eec9727c1380f1a4c91da60728 diff --git a/packages/bash/pwsh-local/README.md b/packages/bash/pwsh-local/README.md new file mode 100644 index 0000000000..a97612ab4e --- /dev/null +++ b/packages/bash/pwsh-local/README.md @@ -0,0 +1,53 @@ +# @deepseek-ai/dsh-pwsh-local + +English | [中文](README.zh.md) + +Local PowerShell implementation of the `@deepseek-ai/dsh-bash` executor seam over the [`@deepseek-ai/dsh-subprocess`](../../subprocess/subprocess/README.md) service: `PwshLocalExecutor` spawns `pwsh -NoLogo -NoProfile -NonInteractive -Command ` per call as a managed process through `ctx.subprocess`, and owns everything PowerShell-shaped — executable resolution, command defaulting and caps, timeout/cancel classification, the model-friendly terminal environment, and the model-facing stdout/stderr merge for background reads. Group mechanics (bounded spill-backed output, credential scrub, kill escalation, disposal) are the subprocess service's. + +The command string rides as ONE argv element to `-Command`: PowerShell itself parses the text, and no intermediate shell exists, so there is no shell-quoting layer to escape (the `bash -c` string domain has no equivalent here). Native Win32 paths (`C:\...`) pass through unchanged. + +The package root exports the default and named `PwshLocalExecutor` plugin, its `Config`, and the pure `resolvePwshPath`/`candidatePwshPaths` helpers. + +## Config + +```yaml +- id: bash + name: '@deepseek-ai/dsh-pwsh-local' + config: + cwd: C:\path\to\workspace # default: process.cwd() + timeoutMs: 120000 # default foreground timeout + maxTimeoutMs: 600000 # cap for per-call overrides + maxOutputBytes: 64000 # per-stream in-memory cap; overflow spills to disk + maxSpillBytes: 67108864 # per-stream full-output spill cap + graceMs: 3000 # kill escalation and post-exit pipe-drain grace + pwshPath: C:\Program Files\PowerShell\7\pwsh.exe # explicit executable; else well-known locations, then PATH +``` + +## Behavior (and where it came from) + +The Windows counterpart of `dsh-bash-local`, deliberately mirroring its semantics call-for-call: + +- **Spawn per call, no shell state** — every call is a fresh non-interactive `pwsh -Command` (deterministic; no profile files). The `-NoLogo -NoProfile -NonInteractive` flags disable startup banners, profile loading, and prompts that would garble tool output. +- **Executable resolution** — `resolvePwshPath` prefers an explicit `pwshPath`, then on Windows probes PowerShell 7's install location, every PATH entry (Microsoft Store installs; surrounding quotes stripped), and Windows PowerShell 5.1 as a legacy last resort, checking `existsSync` on each; elsewhere it falls back to a bare `pwsh` resolved through PATH. Resolution is a pure function of `(configured, env, platform)` and happens once at construction. +- **Configured budgets over managed groups** — `resolve()` fills `workdir`/`timeoutMs`/`stdoutMaxBytes` from config, and every spawn hands the service explicit byte caps, spill cap, and `graceMs`. Tree termination (taskkill on Windows, process-group signals on POSIX), the post-exit pipe-drain grace, tail-keep truncation, and bounded spill files are [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) mechanics. A foreground `BashExecRequest.stdoutMaxBytes` can raise stdout's capture budget for one trusted caller; stderr and background runs still use `maxOutputBytes`. +- **Timeout and cancel classification** — `run()` fuses its config-clamped timeout with the caller's signal through one deadline; only the executor's own timeout reports `timedOut`, an upstream cancel reports `aborted`, and a self-terminated command reports neither ([timeout-library Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md)). Windows reports forced termination as exit 1 without a signal, so signal-stamped facts (`signal`, `killed` status) are POSIX-only there; the timeout/abort classification is platform-independent. +- **Model-friendly terminal env** — `NO_COLOR=1 PAGER=cat GIT_PAGER=cat` (no `TERM=dumb`: that is a POSIX concept; `NO_COLOR` is honored by modern PowerShell renderers) merged as ordinary env under the service's credential scrub and `DSH_*` channel rules; an explicit caller entry still wins. +- **Background processes** — `start()` returns a live `BashProcess` handle immediately, no timeout applies, and the handle's `readOutput()` merges the service's offset-based stdout/stderr reads into one marked-section delta with a consuming cursor. A still-running process belongs to the subprocess service, so it survives executor reloads and dies (killed and joined) with the service's disposal. Everything task-shaped (ids, ownership, polling, notices) lives in the generic [`ctx.tasks` runtime](../../tasks/tasks/README.md), which the tool layer registers the handle with — this executor never sees a session or a registry. + +## Model Experience + +Indirectly, through `dsh-tool-pwsh`, which renders this executor's bounded stdout/stderr tails, background-process deltas, spill-file paths, and infrastructure failures. + +#### KV Cache effect + +No direct invalidation; the named consumer owns any request-prefix changes. + +## Known Limitations and Deferred Work + +- **Unconfined by itself** — this executor always runs commands with the harness process's authority; deployments needing confinement compose a sandboxing bash executor or policy instead. +- **No persistent shell or PTY** — every call starts a fresh `pwsh -Command`; interactive terminal sessions remain deferred until the roadmap's pwsh TUI/GUI rendering work lands. +- **The command string is PowerShell text** — the `-Command` domain has no shell-quoting layer, but a model-facing command is parsed by PowerShell itself, so PowerShell syntax errors are command failures, not launch failures. +- **A background spawn-failure note is single-delivery** — the subprocess service buffers no output for a process that never ran, so the executor injects `spawn failed: …` into exactly one `readOutput()` delta; a reader that discards that delta cannot recover it. +- **Windows termination reports no signal** — a force-killed process settles as exit 1 with `signal: null`, so signal-based status classification (POSIX `killed`) does not apply on Windows; `kill()`-initiated stops still stamp `killed` directly. + +Scrub-heuristic and spill-retention caveats live with [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md), which owns those mechanics. diff --git a/packages/bash/pwsh-local/README.zh.md b/packages/bash/pwsh-local/README.zh.md new file mode 100644 index 0000000000..d6751dac6d --- /dev/null +++ b/packages/bash/pwsh-local/README.zh.md @@ -0,0 +1,53 @@ +# @deepseek-ai/dsh-pwsh-local + +[English](README.md) | 中文 + +`@deepseek-ai/dsh-bash` 执行器 seam 的本地 PowerShell 实现,基于 [`@deepseek-ai/dsh-subprocess`](../../subprocess/subprocess/README.md) 服务:`PwshLocalExecutor` 每次调用以受管进程的方式通过 `ctx.subprocess` spawn `pwsh -NoLogo -NoProfile -NonInteractive -Command `,并拥有所有 PowerShell 形状的职责——可执行文件解析、命令默认化与上限、超时/取消分类、面向模型的终端环境,以及后台读取的 stdout/stderr 合并。进程组机制(有界 spill 输出、凭据清理、终止升级、销毁)属于 subprocess 服务。 + +命令字符串作为 ONE argv 元素传给 `-Command`:由 PowerShell 自己解析文本,不存在中间 shell,因此没有需要转义的 shell 引号层(`bash -c` 字符串域在这里没有对应物)。原生 Win32 路径(`C:\...`)原样通过。 + +包根导出默认与具名 `PwshLocalExecutor` 插件、其 `Config`,以及纯函数 `resolvePwshPath`/`candidatePwshPaths` 辅助函数。 + +## 配置 + +```yaml +- id: bash + name: '@deepseek-ai/dsh-pwsh-local' + config: + cwd: C:\path\to\workspace # default: process.cwd() + timeoutMs: 120000 # default foreground timeout + maxTimeoutMs: 600000 # cap for per-call overrides + maxOutputBytes: 64000 # per-stream in-memory cap; overflow spills to disk + maxSpillBytes: 67108864 # per-stream full-output spill cap + graceMs: 3000 # kill escalation and post-exit pipe-drain grace + pwshPath: C:\Program Files\PowerShell\7\pwsh.exe # explicit executable; else well-known locations, then PATH +``` + +## 行为(及其由来) + +作为 `dsh-bash-local` 的 Windows 对应物,逐调用地镜像其语义: + +- **每次调用新建进程,无 shell 状态**——每次调用都是全新的非交互 `pwsh -Command`(确定性;不加载 profile 文件)。`-NoLogo -NoProfile -NonInteractive` 关闭启动横幅、profile 加载与会干扰工具输出的提示符。 +- **可执行文件解析**——`resolvePwshPath` 优先显式 `pwshPath`,然后在 Windows 上依次探测 PowerShell 7 安装位置、每个 PATH 条目(Microsoft Store 安装;剥离两端引号)以及作为遗留兜底的 Windows PowerShell 5.1,逐一检查 `existsSync`;其他平台回退为通过 PATH 解析的裸 `pwsh`。解析是 `(configured, env, platform)` 的纯函数,在构造时执行一次。 +- **受管进程组之上的配置预算**——`resolve()` 从配置填充 `workdir`/`timeoutMs`/`stdoutMaxBytes`,每次 spawn 都向服务提供显式字节上限、spill 上限与 `graceMs`。进程树终止(Windows 用 taskkill,POSIX 用进程组信号)、退出后管道排空宽限、保尾截断与有界 spill 文件是 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 的机制。前台 `BashExecRequest.stdoutMaxBytes` 可为单个受信调用方提高 stdout 捕获预算;stderr 与后台运行仍使用 `maxOutputBytes`。 +- **超时与取消分类**——`run()` 通过一个 deadline 融合配置夹取的超时与调用方信号;只有执行器自身超时报告 `timedOut`,上游取消报告 `aborted`,自我终止的命令两者都不报告(见 [timeout 库 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md))。Windows 将强制终止报告为退出码 1 且无信号,因此基于信号的实情(`signal`、`killed` 状态)在那里仅限 POSIX;超时/取消分类与平台无关。 +- **面向模型的终端环境**——`NO_COLOR=1 PAGER=cat GIT_PAGER=cat`(没有 `TERM=dumb`:那是 POSIX 概念;现代 PowerShell 渲染器遵循 `NO_COLOR`),作为普通 env 在服务的凭据清理与 `DSH_*` 通道规则之下合并;显式调用方条目仍然优先。 +- **后台进程**——`start()` 立即返回存活的 `BashProcess` 句柄,不设超时;句柄的 `readOutput()` 把服务基于偏移的 stdout/stderr 读取合并为带标记分段的增量与消费游标。仍在运行的进程属于 subprocess 服务,因此它跨执行器重载存活,并随服务销毁(被终止并 join)。一切任务形状的职责(id、所有权、轮询、通知)都在通用 [`ctx.tasks` 运行时](../../tasks/tasks/README.md) 中,由工具层把句柄注册进去——本执行器从不接触会话或注册表。 + +## 模型体验 + +间接地,经由 `dsh-tool-pwsh` 呈现本执行器的有界 stdout/stderr 尾部、后台进程增量、spill 文件路径与基础设施失败。 + +#### KV Cache 影响 + +无直接失效;具名消费方拥有请求前缀的任何变更。 + +## 已知局限与延期工作 + +- **自身不设沙箱**——本执行器始终以 harness 进程的权限运行命令;需要约束的部署应组合沙箱化 bash 执行器或策略。 +- **无持久 shell 或 PTY**——每次调用都是全新的 `pwsh -Command`;交互式终端会话在路线图的 pwsh TUI/GUI 渲染工作落地之前保持延期。 +- **命令字符串是 PowerShell 文本**——`-Command` 域没有 shell 引号层,但面向模型的命令由 PowerShell 自己解析,因此 PowerShell 语法错误是命令失败,而非启动失败。 +- **后台 spawn 失败提示只投递一次**——subprocess 服务不会为从未运行的进程缓冲输出,因此执行器只把 `spawn failed: …` 注入一次 `readOutput()` 增量;丢弃该增量的读取方无法恢复它。 +- **Windows 终止不报告信号**——被强制终止的进程以退出码 1、`signal: null` 结束,因此基于信号的状态分类(POSIX `killed`)在 Windows 上不适用;`kill()` 发起的停止仍会直接盖上 `killed`。 + +清理启发式与 spill 保留的注意事项由 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 持有,它拥有这些机制。 diff --git a/packages/bash/pwsh-local/package.json b/packages/bash/pwsh-local/package.json new file mode 100644 index 0000000000..b7a63188b9 --- /dev/null +++ b/packages/bash/pwsh-local/package.json @@ -0,0 +1,47 @@ +{ + "name": "@deepseek-ai/dsh-pwsh-local", + "description": "Local PowerShell implementation of the DeepSeek Harness bash executor seam", + "version": "0.0.1", + "private": true, + "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", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-bash": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-subprocess": "^0.0.1", + "@deepseek-ai/dsh-timeout": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "dependencies": { + "schemastery": "^3.18.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-bash": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-subprocess": "workspace:^", + "@deepseek-ai/dsh-subprocess-local": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/bash/pwsh-local/src/index.ts b/packages/bash/pwsh-local/src/index.ts new file mode 100644 index 0000000000..2bf8b904c2 --- /dev/null +++ b/packages/bash/pwsh-local/src/index.ts @@ -0,0 +1,316 @@ +/** + * Local PowerShell implementation of the bash executor seam. Each command runs + * as `pwsh -NoLogo -NoProfile -NonInteractive -Command ` in a managed + * process spawned through `ctx.subprocess`; the executor owns command + * defaulting, deadlines and cause classification, the model-friendly terminal + * environment, and the model-facing stdout/stderr merge for background reads. + * + * The command string is passed as ONE argv element to `-Command`: PowerShell + * itself parses the text, and no intermediate shell exists, so there is no + * shell-quoting layer to escape (the `bash -c` string domain has no + * equivalent here). Native Win32 paths (`C:\...`) pass through unchanged. + * + * @module @deepseek-ai/dsh-pwsh-local + */ + +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { Context } from 'cordis' +import z from 'schemastery' +import { BashExecutor } from '@deepseek-ai/dsh-bash' +import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult, CollectedOutput } from '@deepseek-ai/dsh-bash' +import type { SubprocessCollect, SubprocessHandle, SubprocessOutputReader, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { clampTimeout, deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' + +/** + * Model-friendly environment overrides for PowerShell: disable colors and + * pagers that would garble tool output. `TERM=dumb` is a POSIX concept and is + * deliberately absent; `NO_COLOR` is honored by modern pwsh renderers. + */ +export const ENV_OVERRIDES = { + NO_COLOR: '1', + PAGER: 'cat', + GIT_PAGER: 'cat', +} as const + +/** Default SIGTERM→SIGKILL grace period (the `graceMs` config). */ +const DEFAULT_GRACE_MS = 3_000 + +/** Default per-stream spill cap (the `maxSpillBytes` config). */ +const DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024 + +/** Plugin config (all optional — `static Config` supplies the defaults). */ +export interface Config { + /** Default working directory for commands (default: process.cwd()). */ + cwd?: string + /** Default foreground timeout in milliseconds. */ + timeoutMs?: number + /** Upper bound for per-call timeout overrides. */ + maxTimeoutMs?: number + /** Per-stream in-memory output cap; overflow spills to a temp file. */ + maxOutputBytes?: number + /** Per-stream spill-file cap; larger streams retain only their in-memory tail. */ + maxSpillBytes?: number + /** Grace period for kill escalation and for inherited pipes after shell exit. */ + graceMs?: number + /** + * Explicit pwsh executable. When omitted, well-known Windows install + * locations are probed first (PowerShell 7, then Windows PowerShell 5.1), + * falling back to a bare `pwsh` resolved through PATH. + */ + pwshPath?: string +} + +/** The shape after schemastery applied the defaults (cwd/pwshPath have none). */ +type ResolvedConfig = Required> & Pick + +/** + * Well-known Windows PowerShell install locations plus PATH entries, newest + * first. Explicitly parameterized (env) so resolution is a pure function of + * its inputs on every platform. + * @param env - the environment to probe; defaults to the process environment. + * @returns candidate `pwsh` executable paths in resolution order. + */ +export function candidatePwshPaths(env: NodeJS.ProcessEnv = process.env): string[] { + const programFiles = env.ProgramFiles ?? 'C:\\Program Files' + const systemRoot = env.SystemRoot ?? 'C:\\Windows' + const candidates = [ + join(programFiles, 'PowerShell', '7', 'pwsh.exe'), + ] + // Microsoft Store installs (and any user-added location) live on PATH; + // entries may carry surrounding quotes from `setx`-style definitions. + for (const entry of (env.PATH ?? '').split(';')) { + const trimmed = entry.trim().replace(/^"|"$/g, '') + if (trimmed.length === 0) continue + candidates.push(join(trimmed, 'pwsh.exe')) + } + // Windows PowerShell 5.1 remains the last-resort fallback on legacy hosts. + candidates.push(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')) + return candidates +} + +/** + * Resolve the pwsh executable this executor spawns. + * @param configured - an explicit `pwshPath` config value, trusted as-is. + * @param env - the environment to probe on Windows; defaults to the process environment. + * @param platform - the platform to resolve for; defaults to the process platform. + * @returns the first existing well-known location on Windows (PowerShell 7 + * install, a PATH entry such as the Microsoft Store install, then Windows + * PowerShell 5.1), else `pwsh` for PATH resolution. + */ +export function resolvePwshPath( + configured?: string, + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): string { + if (configured !== undefined && configured.length > 0) return configured + if (platform === 'win32') { + for (const candidate of candidatePwshPaths(env)) { + if (existsSync(candidate)) return candidate + } + } + return 'pwsh' +} + +/** Project a settled collect-mode reader into the final CollectedOutput shape. */ +function finalOutput(reader: SubprocessOutputReader): CollectedOutput { + const read = reader.readFrom(0) + return { + text: read.text, + truncated: read.lossy, + ...read.spillPath !== undefined ? { spillPath: read.spillPath } : {}, + } +} + +function assertPositiveFinite(name: string, value: number): void { + if (!Number.isFinite(value) || value <= 0) { + throw new Error(`pwsh-local: ${name} must be a positive finite number`) + } +} + +/** + * Local PowerShell executor over `ctx.subprocess`. Bounded output, spill + * files, and process-tree termination are the subprocess service's mechanics; + * this executor supplies their configured budgets per spawn. + */ +export class PwshLocalExecutor extends BashExecutor { + static inject = ['subprocess'] + + static Config: z = z.object({ + cwd: z.string(), + timeoutMs: z.number().default(120_000), + maxTimeoutMs: z.number().default(600_000), + maxOutputBytes: z.number().default(64_000), + maxSpillBytes: z.number().default(DEFAULT_MAX_SPILL_BYTES), + graceMs: z.number().default(DEFAULT_GRACE_MS), + pwshPath: z.string(), + }) + + /** Validated config (schemastery applied the defaults before construction). */ + readonly config: ResolvedConfig + + /** The pwsh executable resolved once at construction. */ + readonly pwshPath: string + + constructor(ctx: Context, config: Config) { + super(ctx) + // Schemastery fills these fields before construction; the type does not encode that step. + this.config = config as ResolvedConfig + assertPositiveFinite('timeoutMs', this.config.timeoutMs) + assertPositiveFinite('maxTimeoutMs', this.config.maxTimeoutMs) + assertPositiveFinite('maxOutputBytes', this.config.maxOutputBytes) + assertPositiveFinite('maxSpillBytes', this.config.maxSpillBytes) + assertPositiveFinite('graceMs', this.config.graceMs) + this.pwshPath = resolvePwshPath(this.config.pwshPath) + } + + /** + * Resolve a request into a fully-specified spec: fill `workdir` from + * `config.cwd` (else `process.cwd()`), and `timeoutMs` from + * `config.timeoutMs`, capped at `config.maxTimeoutMs`. + */ + resolve(request: BashExecRequest): BashExecSpec { + const timeoutMs = clampTimeout( + request.timeoutMs, + this.config.timeoutMs, + this.config.maxTimeoutMs, + 'pwsh-local: request.timeoutMs', + ) + const stdoutMaxBytes = request.stdoutMaxBytes ?? this.config.maxOutputBytes + assertPositiveFinite('request.stdoutMaxBytes', stdoutMaxBytes) + return { + command: request.command, + workdir: request.workdir ?? this.config.cwd ?? process.cwd(), + timeoutMs, + stdoutMaxBytes, + ...request.signal ? { signal: request.signal } : {}, + ...request.stdin !== undefined ? { stdin: request.stdin } : {}, + ...request.env !== undefined ? { env: request.env } : {}, + ...request.dshEnv !== undefined ? { dshEnv: request.dshEnv } : {}, + sandboxPolicy: request.sandboxPolicy, + } + } + + /** Map one resolved bash spec onto a fully-specified subprocess spawn. */ + private spawnSpec(spec: BashExecSpec, stdoutMaxBytes: number, signal: AbortSignal | undefined): SubprocessSpawnSpec { + const collect = (maxBytes: number): SubprocessCollect => + ({ maxBytes, spill: { maxBytes: this.config.maxSpillBytes } }) + return { + argv: [this.pwshPath, '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', spec.command], + cwd: spec.workdir, + stdio: { + stdin: spec.stdin !== undefined ? { data: spec.stdin } : 'ignore', + stdout: collect(stdoutMaxBytes), + stderr: collect(this.config.maxOutputBytes), + }, + graceMs: this.config.graceMs, + signal, + env: { ...ENV_OVERRIDES, ...spec.env, ...spec.dshEnv }, + } + } + + /** The collect-mode readers the executor itself requested (present by construction). */ + private static collected(handle: SubprocessHandle): { stdout: SubprocessOutputReader; stderr: SubprocessOutputReader } { + const { stdout, stderr } = handle.collected + /* v8 ignore start -- collect dispositions expose both readers by the seam contract; defensive. */ + if (stdout === undefined || stderr === undefined) { + throw new Error('pwsh-local: subprocess implementation dropped a requested collect stream') + } + /* v8 ignore stop */ + return { stdout, stderr } + } + + async run(spec: BashExecSpec): Promise { + // One deadline combines timeout and upstream cancellation; disposal clears its timer. + using d = deadline(spec.signal, spec.timeoutMs, 'BASH_TIMEOUT') + const handle = this.ctx.subprocess.spawn(this.spawnSpec(spec, spec.stdoutMaxBytes, d.signal)) + const outcome = await handle.done + const collected = PwshLocalExecutor.collected(handle) + // Only this executor's timeout reason counts as timedOut; outer deadlines count as aborts. + const timedOut = timeoutOf(d.signal, 'BASH_TIMEOUT') !== undefined + const aborted = d.signal.aborted && !timedOut + return { + ...outcome, + timedOut, + aborted, + timeoutMs: spec.timeoutMs, + stdout: finalOutput(collected.stdout), + stderr: finalOutput(collected.stderr), + } + } + + start(spec: BashExecSpec): BashProcess { + // Background runs ignore timeoutMs; callers stop them through kill() or spec.signal. + const running = this.ctx.subprocess.spawn(this.spawnSpec(spec, this.config.maxOutputBytes, spec.signal)) + const collected = PwshLocalExecutor.collected(running) + + // A spawn failure produces no process output, so the subprocess service has nothing + // to buffer; the note is delivered exactly once through the read path. + let spawnFailureNote: string | undefined + const consumeSpawnFailure = (): string => { + const note = spawnFailureNote ?? '' + spawnFailureNote = undefined + return note + } + + let stdoutOffset = 0 + let stderrOffset = 0 + const proc: BashProcess = { + status: 'running', + exitCode: null, + signal: null, + done: running.done.then((outcome) => { + // Any signal termination is killed, including a command signaling itself. + if (proc.status === 'running') { + proc.status = spec.signal?.aborted === true || outcome.signal !== null ? 'killed' : 'completed' + } + proc.exitCode = outcome.exitCode + proc.signal = outcome.signal + this.onProcessDone(proc, collected.stderr.readFrom(0).text) + }, (error: unknown) => { + // Background spawn failures settle as killed and surface through the read path. + proc.status = 'killed' + spawnFailureNote = `spawn failed: ${String(error)}` + this.onProcessDone(proc, spawnFailureNote) + }), + readOutput: (): BashProcessRead => { + const out = collected.stdout.readFrom(stdoutOffset) + const err = collected.stderr.readFrom(stderrOffset) + stdoutOffset = out.nextOffset + stderrOffset = err.nextOffset + + // A failed spawn never produced process output, so the note and real + // stderr text are mutually exclusive. + const errText = err.text.length > 0 ? err.text : consumeSpawnFailure() + // Single newline between sections: stdout chunks usually end with one + // already; add it only when missing. + const separator = out.text.length > 0 && !out.text.endsWith('\n') ? '\n' : '' + const delta = out.text + + (errText.length > 0 ? `${separator}[stderr]\n${errText}` : '') + return { + delta, + lossy: out.lossy || err.lossy, + ...out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {}, + ...err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {}, + } + }, + kill: (): boolean => { + if (proc.status !== 'running') return false + proc.status = 'killed' + running.terminate() + return true + }, + } + return proc + } + + /** + * Settlement hook for subclasses that attach execution facts to a process. + * The base implementation is intentionally empty. + * @param _proc - the settled process handle. + * @param _stderr - the process's retained stderr tail used by subclasses for settlement classification. + */ + protected onProcessDone(_proc: BashProcess, _stderr: string): void {} +} + +export default PwshLocalExecutor diff --git a/packages/bash/pwsh-local/src/invariant.ts b/packages/bash/pwsh-local/src/invariant.ts new file mode 100644 index 0000000000..4bb1c1ea30 --- /dev/null +++ b/packages/bash/pwsh-local/src/invariant.ts @@ -0,0 +1,30 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-pwsh-local`. + * @module @deepseek-ai/dsh-pwsh-local/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-pwsh-local' + +/** Cordis companion plugin name. */ +export const name = 'pwsh-local-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: this package exposes no independent event sequence or mutable data relation + * beyond contracts enforced at its owning seam. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/bash/pwsh-local/tests/executor.spec.ts b/packages/bash/pwsh-local/tests/executor.spec.ts new file mode 100644 index 0000000000..cd72e47db4 --- /dev/null +++ b/packages/bash/pwsh-local/tests/executor.spec.ts @@ -0,0 +1,412 @@ +/** + * Real-process tests for `@deepseek-ai/dsh-pwsh-local`: the LOCAL subprocess + * service plus a REAL pwsh executable, exercised through the executor seam + * (`resolve` → `run`/`start`). These verify the world — actual PowerShell + * runs, output capture, truncation and spill, deadlines, kill escalation, and + * the background-handle contract. The suite self-skips when no `pwsh` is on + * PATH (a CI accommodation for hosts without PowerShell); the pure unit tests + * (config validation, executable resolution) run on every platform. PowerShell + * writes CRLF on Windows, so exact text assertions normalize line endings. + */ + +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { spawnSync } from 'node:child_process' +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { PwshLocalExecutor, candidatePwshPaths, resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local' +import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' +import type { BashProcess } from '@deepseek-ai/dsh-bash' + +const spillDir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-exec-spec-')) + +const hasPwsh = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 + +/** Normalize PowerShell's platform line endings (CRLF on Windows, LF elsewhere). */ +const lf = (text: string): string => text.replace(/\r\n/g, '\n') + +/** Case-insensitive path equality on Windows (Get-Location may re-case the drive). */ +function samePath(actual: string, expected: string): boolean { + const norm = (value: string) => (process.platform === 'win32' ? value.toLowerCase() : value) + return norm(actual) === norm(expected) +} + +async function setup(config: ConstructorParameters[1] = {}) { + const ctx = new Context() + await ctx.plugin(LocalSubprocessService) + ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir } + // A short kill grace via the REAL config path, so escalation tests stay fast. + await ctx.plugin(PwshLocalExecutor, { graceMs: 200, ...config }) + const bash = ctx.bash as PwshLocalExecutor + return { ctx, bash } +} + +/** + * Poll a handle's consuming readOutput until the ACCUMULATED delta contains + * `expected`; returns the accumulation (reads never re-deliver, so the caller + * gets everything produced up to the match). + */ +async function readUntil(proc: BashProcess, expected: string, timeoutMs = 5_000): Promise { + const deadline = Date.now() + timeoutMs + let all = '' + while (Date.now() < deadline) { + all += proc.readOutput().delta + if (lf(all).includes(expected)) return lf(all) + await new Promise(resolve => setTimeout(resolve, 20)) + } + throw new Error(`process output did not include ${JSON.stringify(expected)}; accumulated ${JSON.stringify(lf(all))}`) +} + +describe('resolvePwshPath and candidatePwshPaths (pure, every platform)', () => { + it('trusts an explicit configured path verbatim', () => { + expect(resolvePwshPath('C:\\custom\\pwsh.exe')).toBe('C:\\custom\\pwsh.exe') + expect(resolvePwshPath('pwsh')).toBe('pwsh') + }) + + it('falls through an empty configured path to platform resolution', () => { + // SystemRoot points at a non-existent tree so the Windows PowerShell 5.1 + // fallback candidate cannot exist either. + expect(resolvePwshPath('', { PATH: 'P:\\Store', SystemRoot: 'S:\\no-windows' }, 'win32')).toBe('pwsh') + }) + + it('returns pwsh on non-Windows platforms regardless of the environment', () => { + expect(resolvePwshPath(undefined, { ProgramFiles: 'P:\\Program Files' }, 'linux')).toBe('pwsh') + expect(resolvePwshPath(undefined, { PATH: 'P:\\Store' }, 'darwin')).toBe('pwsh') + }) + + it('lists PowerShell 7, PATH entries (quotes stripped), then Windows PowerShell 5.1 on win32', () => { + const candidates = candidatePwshPaths({ + ProgramFiles: 'P:\\Program Files', + SystemRoot: 'S:\\Windows', + PATH: ';"Q:\\quoted store";' + ';', + }) + expect(candidates).toEqual([ + join('P:\\Program Files', 'PowerShell', '7', 'pwsh.exe'), + join('Q:\\quoted store', 'pwsh.exe'), + join('S:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), + ]) + // A missing PATH contributes no entries (the empty-string fallback). + expect(candidatePwshPaths({ ProgramFiles: 'P:\\Program Files', SystemRoot: 'S:\\Windows' })) + .toEqual([ + join('P:\\Program Files', 'PowerShell', '7', 'pwsh.exe'), + join('S:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), + ]) + }) + + it('returns the first EXISTING win32 candidate, else pwsh', () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-resolve-')) + const store = join(dir, 'store') + mkdirSync(store, { recursive: true }) + writeFileSync(join(store, 'pwsh.exe'), '') + // The existing PATH entry wins over the non-existent Program Files install. + expect(resolvePwshPath(undefined, { ProgramFiles: join(dir, 'missing'), PATH: store }, 'win32')) + .toBe(join(store, 'pwsh.exe')) + // No candidate exists anywhere (SystemRoot points at a non-existent tree, + // so even the Windows PowerShell 5.1 fallback cannot exist) → the + // PATH-resolution fallback. + expect(resolvePwshPath(undefined, { ProgramFiles: join(dir, 'missing'), PATH: join(dir, 'empty'), SystemRoot: join(dir, 'no-windows') }, 'win32')) + .toBe('pwsh') + }) +}) + +describe.skipIf(!hasPwsh)('PwshLocalExecutor.run', () => { + it('resolves with output and the effective timeout', async () => { + const { bash } = await setup({ timeoutMs: 5_000 }) + const result = await bash.run(bash.resolve({ command: 'Write-Output hi' })) + expect(result.exitCode).toBe(0) + expect(lf(result.stdout.text)).toBe('hi\n') + expect(result.timeoutMs).toBe(5_000) + }) + + it('uses config cwd, overridable per call', async () => { + const first = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-a-')) + const second = mkdtempSync(join(tmpdir(), 'dsh-pwsh-cwd-b-')) + const { bash } = await setup({ cwd: first }) + const fromConfig = await bash.run(bash.resolve({ command: '(Get-Location).Path' })) + expect(samePath(fromConfig.stdout.text.trim(), first)).toBe(true) + const fromCall = await bash.run(bash.resolve({ command: '(Get-Location).Path', workdir: second })) + expect(samePath(fromCall.stdout.text.trim(), second)).toBe(true) + }) + + it('defaults cwd to process.cwd()', async () => { + const { bash } = await setup() + const result = await bash.run(bash.resolve({ command: '(Get-Location).Path' })) + expect(samePath(result.stdout.text.trim(), process.cwd())).toBe(true) + }) + + it('caps per-call timeouts at maxTimeoutMs', async () => { + const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 }) + const result = await bash.run(bash.resolve({ command: 'Write-Output ok', timeoutMs: 99_999 })) + expect(result.timeoutMs).toBe(2_000) + }) + + it('rejects invalid numeric config and timeout overrides', async () => { + await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/) + await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/) + await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/) + await expect(setup({ maxSpillBytes: 0 })).rejects.toThrow(/maxSpillBytes/) + await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/) + + const { bash } = await setup() + expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/) + expect(() => bash.resolve({ command: 'Write-Output ok', timeoutMs: -1 })).toThrow(/request\.timeoutMs/) + expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: Number.NaN })).toThrow(/request\.stdoutMaxBytes/) + expect(() => bash.resolve({ command: 'Write-Output ok', stdoutMaxBytes: -1 })).toThrow(/request\.stdoutMaxBytes/) + }) + + it('defaults stdoutMaxBytes to maxOutputBytes and lets foreground callers raise stdout only', async () => { + const { bash } = await setup({ maxOutputBytes: 100 }) + expect(bash.resolve({ command: 'Write-Output ok' }).stdoutMaxBytes).toBe(100) + + // Raw Console writes avoid PowerShell's own line-ending and formatting + // layers, so the byte counts are exact on every platform. + const result = await bash.run(bash.resolve({ + command: '[Console]::Out.Write("x" * 500); [Console]::Error.WriteLine("e" * 500)', + stdoutMaxBytes: 500, + })) + + expect(result.stdout.text).toBe('x'.repeat(500)) + expect(result.stdout.truncated).toBe(false) + expect(result.stderr.truncated).toBe(true) + expect(result.stderr.text.length).toBeLessThanOrEqual(100) + }) + + it('per-call timeout takes precedence under the cap and kills on expiry', async () => { + const { bash } = await setup({ timeoutMs: 60_000 }) + const result = await bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', timeoutMs: 100 })) + expect(result.timedOut).toBe(true) + // Mutually exclusive: a timeout classifies as timedOut, never also aborted. + expect(result.aborted).toBe(false) + expect(result.timeoutMs).toBe(100) + }) + + it('propagates abort signals', async () => { + const { bash } = await setup() + const controller = new AbortController() + const pending = bash.run(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal })) + setTimeout(() => { controller.abort() }, 50) + const result = await pending + expect(result.aborted).toBe(true) + // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut. + expect(result.timedOut).toBe(false) + }) + + it('classifies a self-killed command as neither timed out nor aborted', async () => { + const { bash } = await setup({ timeoutMs: 60_000 }) + const result = await bash.run(bash.resolve({ command: 'Stop-Process -Id $PID' })) + expect(result.timedOut).toBe(false) + expect(result.aborted).toBe(false) + // Windows reports a forced termination without a signal; POSIX reports SIGTERM. + if (process.platform === 'win32') { + expect(result.signal).toBeNull() + } else { + expect(result.signal).toBe('SIGTERM') + } + }) + + it('rejects on spawn failure (bad workdir)', async () => { + const { bash } = await setup() + await expect(bash.run(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/) + }) + + it('resolve() carries stdin/env/dshEnv onto the spec, and run() threads them to the command', async () => { + const { bash } = await setup() + const spec = bash.resolve({ + command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:SEAM_VAR][$env:DSH_SEAM_VAR]"', + stdin: 'piped\n', + env: { SEAM_VAR: 'env-ok' }, + dshEnv: { DSH_SEAM_VAR: 'dsh-ok' }, + }) + // resolve() keeps the optional input/environment fields verbatim. + expect(spec.stdin).toBe('piped\n') + expect(spec.env).toEqual({ SEAM_VAR: 'env-ok' }) + expect(spec.dshEnv).toEqual({ DSH_SEAM_VAR: 'dsh-ok' }) + const result = await bash.run(spec) + expect(lf(result.stdout.text)).toBe('piped\n[env-ok][dsh-ok]\n') + }) + + it('resolve() omits stdin/env/dshEnv when the request supplies none', async () => { + const { bash } = await setup() + const spec = bash.resolve({ command: 'Write-Output ok' }) + expect('stdin' in spec).toBe(false) + expect('env' in spec).toBe(false) + expect('dshEnv' in spec).toBe(false) + }) +}) + +describe.skipIf(!hasPwsh)('PwshLocalExecutor.start (background process handles)', () => { + it('start returns immediately with a running handle that settles as completed', async () => { + const { bash } = await setup() + const before = Date.now() + const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Milliseconds 200; Write-Output done' })) + expect(Date.now() - before).toBeLessThan(150) + expect(proc.status).toBe('running') + await proc.done + expect(proc.status).toBe('completed') + expect(proc.exitCode).toBe(0) + }) + + it('threads stdin and extra env into a background process', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ + command: '$s = ([Console]::In.ReadToEnd()).TrimEnd(); Write-Output $s; Write-Output "[$env:BG_VAR][$env:DSH_BG_VAR]"', + stdin: 'bg-stdin\n', + env: { BG_VAR: 'bg-env' }, + dshEnv: { DSH_BG_VAR: 'bg-dsh-env' }, + })) + const output = await readUntil(proc, '[bg-env][bg-dsh-env]') + expect(output).toBe('bg-stdin\n[bg-env][bg-dsh-env]\n') + await proc.done + expect(proc.exitCode).toBe(0) + }) + + it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ command: 'Write-Output first; Start-Sleep -Seconds 1; Write-Output second' })) + const first = await readUntil(proc, 'first\n') + expect(lf(first)).toBe('first\n') + await proc.done + // Read-after-exit returns the remaining buffered output — once. + const second = proc.readOutput() + expect(lf(second.delta)).toBe('second\n') + expect(second.lossy).toBe(false) + expect(proc.readOutput().delta).toBe('') + }) + + it('readOutput marks stderr sections', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ command: 'Write-Output out; [Console]::Error.WriteLine("err")' })) + await proc.done + expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n') + }) + + it('readOutput reports stderr-only deltas without a leading newline', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ command: '[Console]::Error.WriteLine("err")' })) + await proc.done + expect(lf(proc.readOutput().delta)).toBe('[stderr]\nerr\n') + }) + + it('readOutput adds a separator only when stdout lacks a trailing newline', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ command: '[Console]::Out.Write("out"); [Console]::Error.WriteLine("err")' })) + await proc.done + expect(lf(proc.readOutput().delta)).toBe('out\n[stderr]\nerr\n') + }) + + it('readOutput flags lossy reads and reports stdout spill paths', async () => { + const { bash } = await setup({ maxOutputBytes: 100 }) + const proc = bash.start(bash.resolve({ command: '1..100 | ForEach-Object { "line-$_" }' })) + await proc.done + const read = proc.readOutput() + // Window slid past offset 0 → lossy, spill path points at the full stream. + expect(read.lossy).toBe(true) + expect(read.stdoutSpillPath).toBeDefined() + }) + + it('readOutput reports stderr spill paths', async () => { + const { bash } = await setup({ maxOutputBytes: 100 }) + const proc = bash.start(bash.resolve({ command: '1..100 | ForEach-Object { [Console]::Error.WriteLine("line-$_") }' })) + await proc.done + const read = proc.readOutput() + expect(read.lossy).toBe(true) + expect(read.stderrSpillPath).toBeDefined() + expect(lf(read.delta)).toContain('[stderr]') + }) + + it('kill() terminates the process tree: true once, false after settlement', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' })) + expect(proc.kill()).toBe(true) + await proc.done + expect(proc.status).toBe('killed') + expect(proc.kill()).toBe(false) + }) + + it('kill() returns false for a naturally completed process', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ command: 'Write-Output ok' })) + await proc.done + expect(proc.status).toBe('completed') + expect(proc.kill()).toBe(false) + }) + + it('a spec.signal abort settles the handle as killed, not completed', async () => { + const { bash } = await setup() + const controller = new AbortController() + const proc = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60', signal: controller.signal })) + controller.abort() + await proc.done + expect(proc.status).toBe('killed') + }) + + it.skipIf(process.platform === 'win32')('a self-signal exit settles the handle as killed, not completed (POSIX)', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ command: 'Stop-Process -Id $PID' })) + await proc.done + expect(proc.status).toBe('killed') + expect(proc.exitCode).toBeNull() + expect(proc.signal).toBe('SIGTERM') + }) + + it('a background spawn failure settles as killed with the error readable on stderr', async () => { + const { bash } = await setup() + const proc = bash.start(bash.resolve({ command: 'Write-Output ok', workdir: '/nonexistent-dsh' })) + // done resolves (never rejects) even though the process never ran. + await expect(proc.done).resolves.toBeUndefined() + expect(proc.status).toBe('killed') + expect(proc.readOutput().delta).toContain('spawn failed:') + }) +}) + +describe.skipIf(!hasPwsh)('process lifecycle ownership (the subprocess service, not the executor)', () => { + it('a background process survives executor-fiber disposal and dies with the subprocess service', async () => { + const ctx = new Context() + const managerFiber = await ctx.plugin(LocalSubprocessService) + ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir } + const executorFiber = await ctx.plugin(PwshLocalExecutor, { graceMs: 200 }) + const bash = ctx.bash as PwshLocalExecutor + + // The child prints its own pid so the test can probe liveness through the + // public read surface alone. + const proc = bash.start(bash.resolve({ command: 'Write-Output $PID; Start-Sleep -Seconds 60' })) + const pid = Number((await readUntil(proc, '\n')).trim()) + expect(Number.isInteger(pid) && pid > 0).toBe(true) + + // Executor reload/disposal leaves background work running — the + // handle stays live and readable, mirroring the task runtime's + // registrations-outlive-producer-fibers contract. + await executorFiber.dispose() + expect(proc.status).toBe('running') + expect(() => process.kill(pid, 0)).not.toThrow() + + // Service disposal kills the group and AWAITS its exit (no orphans). + await managerFiber.dispose() + expect(() => process.kill(pid, 0)).toThrow() + await proc.done + // POSIX reports the kill as a signal; Windows reports a forced + // termination as exit 1 with no signal (indistinguishable from a crash), + // so the status stamp follows the platform's exit facts. + expect(proc.status).toBe(process.platform === 'win32' ? 'completed' : 'killed') + }) + + it('service disposal settles running handles and leaves settled ones untouched', async () => { + const ctx = new Context() + const managerFiber = await ctx.plugin(LocalSubprocessService) + ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir } + await ctx.plugin(PwshLocalExecutor, { graceMs: 200 }) + const bash = ctx.bash as PwshLocalExecutor + + const finished = bash.start(bash.resolve({ command: 'Write-Output done' })) + await finished.done + expect(finished.status).toBe('completed') + const running = bash.start(bash.resolve({ command: 'Start-Sleep -Seconds 60' })) + + await managerFiber.dispose() + // A settled process was untouched; the live one was terminated and joined. + expect(finished.status).toBe('completed') + await running.done + expect(running.status).toBe(process.platform === 'win32' ? 'completed' : 'killed') + }) +}) diff --git a/packages/bash/pwsh-local/tsconfig.json b/packages/bash/pwsh-local/tsconfig.json new file mode 100644 index 0000000000..53ccc94926 --- /dev/null +++ b/packages/bash/pwsh-local/tsconfig.json @@ -0,0 +1,36 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/timeout" + }, + { + "path": "../../bash/bash" + }, + { + "path": "../../subprocess/subprocess" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/bash/tool-pwsh/README.i18n.yaml b/packages/bash/tool-pwsh/README.i18n.yaml new file mode 100644 index 0000000000..e16107e42f --- /dev/null +++ b/packages/bash/tool-pwsh/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/bash/tool-pwsh/README.md +README.md: 4f1d62dbf49fef678e3285776c466286535d66da +README.zh.md: bbeece3c648d8b1903eed1a66d2e14774c7ace8c diff --git a/packages/bash/tool-pwsh/README.md b/packages/bash/tool-pwsh/README.md new file mode 100644 index 0000000000..4f1d62dbf4 --- /dev/null +++ b/packages/bash/tool-pwsh/README.md @@ -0,0 +1,107 @@ +# @deepseek-ai/dsh-tool-pwsh + +English | [中文](README.zh.md) + +The model-facing `pwsh` tool registered over the `ctx.bash` executor seam. Intended for Windows compositions where a PowerShell executor (e.g. `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. Minimal by design — no background tasks, no sandbox escalation, no persistent shell: this is the "works on my Windows machine" profile until the full bash-tool feature set gets a PowerShell twin. + +Requires a loaded executor implementation; the plugin stays pending until `ctx.bash` exists (`inject: ['tools', 'bash', 'systemPrompt']`). + +The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`) plus the pure `renderPwshOutput` helper and its result type; execution and presentation remain implementation details covered by same-package tests. + +The plugin also contributes the `tool:pwsh` prompt section (order 105): check the `[exit code: N]` marker on every result and investigate failures before moving on. + +## Tools + +### `pwsh` + +| Arg | Type | Notes | +|---|---|---| +| `command` | string (required) | Run via `pwsh -Command`. No state persists between calls — use `workdir`, not `cd`. | +| `description` | string (required) | One-line, active-voice summary of the command (5-10 words), for UI/log display only — no effect on execution. | +| `timeoutMs` | number | Timeout override in milliseconds. The executor applies its configured default and cap. | +| `workdir` | string | Working directory for this call. Defaults to the calling agent's session cwd (`session.header.cwd`) so each session runs in its own workspace; a relative `workdir` is resolved against that same identity. | + +`command`, `workdir`, and `timeoutMs` are resolved against the executor's config defaults via `ctx.bash.resolve()` before execution. The workdir default is applied in the tool layer from the calling agent's `session.header.cwd` BEFORE `resolve()` — the per-session cwd must come from `exec.agent`, since N sessions share one executor; only when no session cwd is available does the executor fall back to its own config / `process.cwd()`. + +### Managed shell environment + +Every call receives a freshly collected trusted `DSH_*` environment. `DSH_HOME` is the absolute Harness home resolved by [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) (`dshHome` config, then ambient `$DSH_HOME`, then `~/.dsh`) and `DSH_SHELL=1` identifies the managed child. Agent calls additionally receive `DSH_SESSION_ID=agent.session.header.id`. The snapshot passes through the dedicated `BashExecRequest.dshEnv` channel; `process.env` is never modified. + +Result text contains stdout, an optional `[stderr]` section, then applicable timeout, signal, and exit-code markers: `[timed out after ms]`, `[killed by signal: ]`, and `[exit code: N]`, each separated by a newline only when the accumulated text lacks one. Nonzero exit remains a model-interpreted result rather than `isError`. Only infrastructure failures — spawn errors and aborts (`tool call aborted`) — produce `isError`. + +The canonical success is `{ kind: 'foreground', ...BashRunResult }` for a completed foreground process. Programmatic consumers use the typed fields without parsing the rendered text. + +## UI presentation + +The tool owns its `presentCall`/`presentResult` render intent. A call is a `terminal` card carrying command, description, and optional cwd; a completed result is a `generic` card with the rendered output in a `console` fence. These presenters are pure and replay-safe. + +## Model Experience + +### System prompt + +#### What the model sees + +Every request in this plugin's registration scope contains the pwsh guidance below. Scoped tool restrictions can hide the schema without removing this independently registered section. + +##### Pwsh guidance + +```markdown +Check the [exit code: N] marker on every pwsh result; investigate failures before moving on. +``` + +#### Token effect + +Small fixed input cost per request while the plugin is active. + +#### KV Cache effect + +Prefix-stable while the registration scope and prompt text are unchanged. Plugin activation or disposal may invalidate reuse from this prompt section. + +### Tool schemas + +#### What the model sees + +The model sees the generated [`pwsh` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-pwsh). Agent-scoped tool restrictions can remove the definition for that agent. + +#### Token effect + +Fixed schema cost on every request where the tool is visible. + +#### KV Cache effect + +Prefix-stable while visibility and the tool definition are unchanged. A restriction or config change may invalidate reuse from the first changed token. + +### Foreground result + +#### What the model sees + +The renderer emits the data-dependent stdout tail, then optional `[stderr]` and the stderr tail. Conditional lines are exactly `[timed out after ms]`, `[killed by signal: ]`, and `[exit code: ]`. + +#### Token effect + +Zero result tokens before a call. Output is bounded per stream, while each emitted line remains in history until compaction. + +#### KV Cache effect + +Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries. + +### Tool errors + +#### What the model sees + +Validation and infrastructure failures are normalized as `Error: `. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got `, and `tool call aborted`. + +#### Token effect + +Only the failing call adds these retained tokens; an aborted call adds no command output. + +#### KV Cache effect + +Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries. + +## Known Limitations and Deferred Work + +- **Foreground-only** — no `run_in_background`; long-running work must stay within the executor timeout or wait for the bash-tool twin. +- **No sandbox escalation** — `sandbox_permissions`/`justification` are absent; a confining composition denies through the executor, and escalation waits for the full twin. +- **PowerShell-dialect contract** — the model must write PowerShell (native paths, `$env:` variables), not bash; there is no dialect translation. +- **Windows-default roadmap deferred** — defaulting Windows hosts to `pwsh` over `bash`, and pwsh TUI/GUI rendering support, are planned separately and deliberately not part of this package yet. diff --git a/packages/bash/tool-pwsh/README.zh.md b/packages/bash/tool-pwsh/README.zh.md new file mode 100644 index 0000000000..bbeece3c64 --- /dev/null +++ b/packages/bash/tool-pwsh/README.zh.md @@ -0,0 +1,107 @@ +# @deepseek-ai/dsh-tool-pwsh + +[English](README.md) | 中文 + +面向模型的 `pwsh` 工具,注册在 `ctx.bash` 执行器 seam 之上。面向由 PowerShell 执行器(如 `@deepseek-ai/dsh-pwsh-local`)支撑 `ctx.bash` 的 Windows 组合;工具契约是 PowerShell 方言:原生 `C:\...` 路径与 `$env:NAME` 变量。刻意保持最小——无后台任务、无沙箱升级、无持久 shell:在完整 bash 工具功能集获得 PowerShell 孪生之前,这就是 "works on my Windows machine" 画像。 + +需要一个已加载的执行器实现;插件在 `ctx.bash` 存在之前保持 pending(`inject: ['tools', 'bash', 'systemPrompt']`)。 + +包根只暴露 Cordis 插件契约(`name`、`inject`、`Config`、`apply`)以及纯函数 `renderPwshOutput` 及其结果类型;执行与呈现是同一包测试覆盖的实现细节。 + +该插件还贡献 `tool:pwsh` 提示词段(order 105):检查每个结果上的 `[exit code: N]` 标记,并在继续前调查失败。 + +## 工具 + +### `pwsh` + +| 参数 | 类型 | 说明 | +|---|---|---| +| `command` | string(必填) | 通过 `pwsh -Command` 运行。调用之间不保留状态——用 `workdir`,不要用 `cd`。 | +| `description` | string(必填) | 命令的一句话主动语态摘要(5-10 词),仅用于 UI/日志展示——不影响执行。 | +| `timeoutMs` | number | 毫秒级超时覆盖。执行器应用其配置的默认值与上限。 | +| `workdir` | string | 本次调用的工作目录。默认取调用 agent(智能体)的会话 cwd(`session.header.cwd`),使每个会话在自己的工作区运行;相对 `workdir` 基于同一身份解析。 | + +`command`、`workdir` 与 `timeoutMs` 在执行前经 `ctx.bash.resolve()` 按执行器配置默认值解析。workdir 默认值在工具层取自调用 agent 的 `session.header.cwd`,先于 `resolve()` 应用——每个会话的 cwd 必须来自 `exec.agent`,因为 N 个会话共享一个执行器;只有没有会话 cwd 时,执行器才回退到自己的配置 / `process.cwd()`。 + +### 受管 shell 环境 + +每次调用都会收到一份新收集的受信 `DSH_*` 环境。`DSH_HOME` 是由 [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) 解析的 Harness 绝对主目录(`dshHome` 配置,其次环境变量 `$DSH_HOME`,再其次 `~/.dsh`),`DSH_SHELL=1` 标识受管子进程。agent 调用额外收到 `DSH_SESSION_ID=agent.session.header.id`。该快照经由专用 `BashExecRequest.dshEnv` 通道传递;`process.env` 永不被修改。 + +结果文本包含 stdout、可选的 `[stderr]` 分段,以及适用的超时、信号与退出码标记:`[timed out after ms]`、`[killed by signal: ]` 与 `[exit code: N]`,仅在累积文本缺少换行时才补一个分隔换行。非零退出仍是模型自行解读的结果,而不是 `isError`。只有基础设施失败——spawn 错误与中止(`tool call aborted`)——才产生 `isError`。 + +规范成功值为已完成前台进程的 `{ kind: 'foreground', ...BashRunResult }`。程序化消费方使用类型化字段,而不解析渲染文本。 + +## UI 呈现 + +工具拥有自己的 `presentCall`/`presentResult` 渲染意图。调用是携带命令、描述与可选 cwd 的 `terminal` 卡片;完成结果是 `generic` 卡片,渲染输出放在 `console` 围栏内。这些 presenter 是纯函数且可重放。 + +## 模型体验 + +### 系统提示词 + +#### 模型看到的内容 + +该插件注册作用域内的每个请求都包含下方 pwsh 指导。作用域工具限制可以隐藏 schema,而不移除这个独立注册的提示词段。 + +##### Pwsh 指导 + +```markdown +Check the [exit code: N] marker on every pwsh result; investigate failures before moving on. +``` + +#### Token 影响 + +插件激活期间每个请求有少量固定输入成本。 + +#### KV Cache 影响 + +注册作用域与提示词文本不变时前缀稳定。插件激活或销毁可能使该提示词段的复用失效。 + +### 工具 schema + +#### 模型看到的内容 + +模型看到生成的 [`pwsh` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-pwsh)。agent 作用域的工具限制可以为该 agent 移除定义。 + +#### Token 影响 + +工具可见时每个请求有固定的 schema 成本。 + +#### KV Cache 影响 + +可见性与工具定义不变时前缀稳定。限制或配置变更可能从第一个改变的 token 起使复用失效。 + +### 前台结果 + +#### 模型看到的内容 + +渲染器输出依赖数据的 stdout 尾部,然后是可选 `[stderr]` 与 stderr 尾部。条件行恰为 `[timed out after ms]`、`[killed by signal: ]` 与 `[exit code: ]`。 + +#### Token 影响 + +调用前零结果 token。输出按流有界,每条已发出行在压缩前保留在历史中。 + +#### KV Cache 影响 + +只追加;新可见内容跟在可复用请求前缀之后,不会使既有 KV-cache 条目失效。 + +### 工具错误 + +#### 模型看到的内容 + +校验与基础设施失败被规范化为 `Error: `。本包的稳定消息为 `invalid command: expected a non-empty string`、`invalid description: expected a non-empty string`、`invalid timeoutMs: expected a positive number, got ` 与 `tool call aborted`。 + +#### Token 影响 + +只有失败的调用会增加这些保留 token;中止的调用不增加命令输出。 + +#### KV Cache 影响 + +只追加;新可见内容跟在可复用请求前缀之后,不会使既有 KV-cache 条目失效。 + +## 已知局限与延期工作 + +- **仅前台**——没有 `run_in_background`;长时间运行的工作必须留在执行器超时之内,或等待 bash 工具孪生。 +- **无沙箱升级**——没有 `sandbox_permissions`/`justification`;受约束的组合通过执行器拒绝,升级等待完整孪生。 +- **PowerShell 方言契约**——模型必须写 PowerShell(原生路径、`$env:` 变量),而不是 bash;没有方言翻译。 +- **Windows 默认路线图延期**——让 Windows 主机默认用 `pwsh` 而非 `bash`,以及 pwsh TUI/GUI 渲染支持,都另行规划,刻意不纳入本包。 diff --git a/packages/bash/tool-pwsh/package.json b/packages/bash/tool-pwsh/package.json new file mode 100644 index 0000000000..90e12438d8 --- /dev/null +++ b/packages/bash/tool-pwsh/package.json @@ -0,0 +1,56 @@ +{ + "name": "@deepseek-ai/dsh-tool-pwsh", + "description": "Model-facing pwsh tool over the bash executor seam", + "version": "0.0.1", + "private": true, + "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", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-agent": "^0.0.1", + "@deepseek-ai/dsh-bash": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-llm": "^0.0.1", + "@deepseek-ai/dsh-paths": "^0.0.1", + "@deepseek-ai/dsh-session-persistence": "^0.0.1", + "@deepseek-ai/dsh-system-prompt": "^0.0.1", + "@deepseek-ai/dsh-tools": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "dependencies": { + "schemastery": "^3.18.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-bash": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-paths": "workspace:^", + "@deepseek-ai/dsh-pwsh-local": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-subprocess-local": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/bash/tool-pwsh/src/index.ts b/packages/bash/tool-pwsh/src/index.ts new file mode 100644 index 0000000000..96073fcf93 --- /dev/null +++ b/packages/bash/tool-pwsh/src/index.ts @@ -0,0 +1,254 @@ +/** + * Model-facing `pwsh` tool over the `ctx.bash` executor seam. Intended for + * Windows compositions where a PowerShell executor (e.g. + * `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is + * PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. + * + * Minimal by design: no background tasks, no sandbox escalation — this is the + * "works on my Windows machine" profile until the full bash-tool feature set + * gets a PowerShell twin. + * + * @module @deepseek-ai/dsh-tool-pwsh + */ + +import { isAbsolute, resolve as resolvePath } from 'node:path' +import { Context } from 'cordis' +import z from 'schemastery' +import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools' +import type { TerminalCallView, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import type { Agent } from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-session-persistence' +import type {} from '@deepseek-ai/dsh-system-prompt' +import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-bash' +import type { BashRunResult, DshEnvironment } from '@deepseek-ai/dsh-bash' +import { DSH_HOME_ENV, resolveDshHome } from '@deepseek-ai/dsh-paths' + +export const name = 'tool-pwsh' +export const inject = ['tools', 'bash', 'systemPrompt'] + +/** Plugin config (currently empty; kept as a schema so deployments can grow it). */ +export interface Config { + /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */ + dshHome?: string +} + +/** Runtime configuration schema for the pwsh tool plugin. */ +export const Config: z = z.object({ + dshHome: z.string(), +}) + +/** Parsed tool args; execute validates value constraints absent from ParameterSchemaSpec. */ +interface PwshToolArgs { + command: string + description: string + timeoutMs?: number + workdir?: string +} + +/** The canonical foreground result of one pwsh call (the `output.schema` value shape). */ +interface PwshForegroundResult { + kind: 'foreground' + exitCode: number | null + signal: NodeJS.Signals | null + timedOut: boolean + aborted: boolean + timeoutMs: number + stdout: { text: string; truncated: boolean; spillPath?: string } + stderr: { text: string; truncated: boolean; spillPath?: string } +} + +function validatePwshArgs(args: PwshToolArgs): void { + if (args.command.trim().length === 0) { + throw new Error('invalid command: expected a non-empty string') + } + if (args.description.trim().length === 0) { + throw new Error('invalid description: expected a non-empty string') + } + if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) { + throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`) + } +} + +function pwshDescription(): string { + return 'Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. ' + + 'Each call runs in a fresh pwsh process: no state (cwd, variables, functions) persists between calls — ' + + 'pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\\...`); read environment ' + + 'variables with `$env:NAME`. Non-zero exits are reported as `[exit code: N]`. ' + + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available.' +} + +/** + * Resolve an explicit workdir first, making a relative one session-workspace-relative; + * otherwise use the session header cwd and leave executor defaulting as the fallback. + */ +function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent }): string | undefined { + const headerCwd = exec.agent?.session.header.cwd + if (modelWorkdir === undefined) return headerCwd + if (headerCwd !== undefined && !isAbsolute(modelWorkdir)) { + return resolvePath(headerCwd, modelWorkdir) + } + return modelWorkdir +} + +/** + * The model-facing text of one foreground pwsh result: stdout, a marked + * stderr section, then the applicable timeout, signal, and exit markers — + * each separated by a newline only when the accumulated text lacks one, so a + * trailing newline in stdout never produces a blank line. + * + * @param value - the canonical foreground result (the schema-derived value shape). + * @returns the model-facing text. + */ +function renderPwshOutput(value: RenderablePwshOutput): string { + let rendered = value.stdout.text + const marker = (line: string): void => { + rendered += rendered.length > 0 && !rendered.endsWith('\n') ? `\n${line}` : line + } + if (value.stderr.text.length > 0) marker(`[stderr]\n${value.stderr.text}`) + if (value.timedOut) marker(`[timed out after ${value.timeoutMs}ms]`) + if (value.signal !== null) marker(`[killed by signal: ${value.signal}]`) + if (value.exitCode !== null) marker(`[exit code: ${value.exitCode}]`) + return rendered +} + +/** + * Detach the executor DTO from readonly seam interfaces into plain JSON data. + * @param result - the executor's run outcome. + * @returns the canonical foreground result the tool returns and renders. + */ +function canonicalPwshResult(result: BashRunResult): PwshForegroundResult { + const output = (stream: BashRunResult['stdout']) => ({ + text: stream.text, + truncated: stream.truncated, + ...stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {}, + }) + return { + kind: 'foreground', + exitCode: result.exitCode, + signal: result.signal, + timedOut: result.timedOut, + aborted: result.aborted, + timeoutMs: result.timeoutMs, + stdout: output(result.stdout), + stderr: output(result.stderr), + } +} + +/** The rendered fields of a foreground result — the schema-derived value shape (no `kind`, plain-string signal). */ +interface RenderablePwshOutput { + exitCode: number | null + signal: string | null + timedOut: boolean + timeoutMs: number + stdout: { text: string } + stderr: { text: string } +} + +/** + * The managed `DSH_*` snapshot for one pwsh call: the harness home, a shell + * marker, and the session identity when an agent is present. + */ +function collectDshEnv(exec: ToolExecution, dshHome: string): DshEnvironment { + const values: Record = { + [DSH_HOME_ENV]: dshHome, + [`${DSH_ENV_PREFIX}SHELL`]: '1', + } + if (exec.agent !== undefined) { + values[`${DSH_ENV_PREFIX}SESSION_ID`] = exec.agent.session.header.id + } + return values +} + +export function apply(ctx: Context, config: Config = {}): void { + const dshHome = resolveDshHome(config.dshHome) + + ctx.systemPrompt.section({ + name: 'tool:pwsh', + order: 105, + text: 'Check the [exit code: N] marker on every pwsh result; investigate failures before moving on.', + }) + + ctx.tools.register(defineTool({ + name: 'pwsh', + description: pwshDescription(), + parameters: { + command: { type: 'string', required: true, description: 'The PowerShell command to execute.' }, + description: { + type: 'string', + required: true, + description: 'Clear, concise description of what this command does in active voice, ' + + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; ' + + '"git status" → "Show working tree status"; "Get-Process" → "List running processes".', + }, + timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' }, + workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' }, + }, + output: { + schema: { + type: 'object', + additionalProperties: false, + properties: { + kind: { type: 'string', required: true, const: 'foreground' }, + exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] }, + signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] }, + timedOut: { type: 'boolean', required: true }, + aborted: { type: 'boolean', required: true }, + timeoutMs: { type: 'number', required: true }, + stdout: { + type: 'object', + additionalProperties: false, + required: true, + properties: { + text: { type: 'string', required: true }, + truncated: { type: 'boolean', required: true }, + spillPath: { type: 'string' }, + }, + }, + stderr: { + type: 'object', + additionalProperties: false, + required: true, + properties: { + text: { type: 'string', required: true }, + truncated: { type: 'boolean', required: true }, + spillPath: { type: 'string' }, + }, + }, + }, + }, + render: (_args, value) => [{ + type: 'text', + text: renderPwshOutput(value), + }], + }, + async execute(args: PwshToolArgs, exec) { + validatePwshArgs(args) + const workdir = resolveWorkdir(args.workdir, exec) + const result = await ctx.bash.run(ctx.bash.resolve({ + command: args.command, + ...workdir !== undefined ? { workdir } : {}, + ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {}, + dshEnv: collectDshEnv(exec, dshHome), + signal: exec.signal, + })) + if (result.aborted) { + const error = new HarnessError('tool call aborted', TOOL_ABORTED) + error.name = 'AbortError' + throw error + } + return canonicalPwshResult(result) + }, + presentCall: (args: PwshToolArgs): TerminalCallView => ({ + card: 'terminal', + title: args.command, + description: args.description, + ...args.workdir !== undefined ? { cwd: args.workdir } : {}, + }), + presentResult: (_args: unknown, result: ToolResult): ToolResultView | undefined => { + const block = result.content.length === 1 ? result.content[0] : undefined + if (block === undefined || block.type !== 'text') return undefined + return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${block.text.replace(/\n+$/, '')}\n\`\`\`` }] } + }, + })) +} diff --git a/packages/bash/tool-pwsh/src/invariant.ts b/packages/bash/tool-pwsh/src/invariant.ts new file mode 100644 index 0000000000..dd6370b490 --- /dev/null +++ b/packages/bash/tool-pwsh/src/invariant.ts @@ -0,0 +1,30 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-tool-pwsh`. + * @module @deepseek-ai/dsh-tool-pwsh/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-tool-pwsh' + +/** Cordis companion plugin name. */ +export const name = 'tool-pwsh-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: this package exposes no independent event sequence or mutable data relation + * beyond contracts enforced at its owning seam. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/bash/tool-pwsh/tests/integration.spec.ts b/packages/bash/tool-pwsh/tests/integration.spec.ts new file mode 100644 index 0000000000..c703c6aa0e --- /dev/null +++ b/packages/bash/tool-pwsh/tests/integration.spec.ts @@ -0,0 +1,119 @@ +/** + * Integration tests: the REAL `@deepseek-ai/dsh-pwsh-local` executor plus the + * `pwsh` tool, exercised through `ctx.tools.execute()` with a real PowerShell + * process. These verify the world — actual commands run, stdout/stderr come + * back, exit codes render, timeouts abort, and per-session cwd resolution + * works. The suite self-skips when no `pwsh` is on PATH (a CI accommodation + * for hosts without PowerShell); the fake-executor suite (tools.spec.ts) + * carries the coverage gate. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { spawnSync } from 'node:child_process' +import { Context } from 'cordis' +import { CallId } from '@deepseek-ai/dsh-llm' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry, { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' +import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' +import { PwshLocalExecutor } from '@deepseek-ai/dsh-pwsh-local' +import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh' + +const testToolSignal = new AbortController().signal + +const hasPwsh = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 + +/** Normalize PowerShell's platform line endings (CRLF on Windows, LF elsewhere). */ +const lf = (text: string): string => text.replace(/\r\n/g, '\n') + +let dir: string +let ctx: Context + +let callCounter = 0 +function call(name: string, args: unknown, agentObj?: object, signal?: AbortSignal) { + return ctx.tools.execute({ + signal: signal ?? testToolSignal, + callId: CallId(`it-${++callCounter}`), + name, + arguments: args, + ...agentObj ? { agent: agentObj as never } : {}, + }) +} + +function text(result: { content: { type: string; text?: string }[] }): string { + return result.content.filter(b => b.type === 'text').map(b => b.text).join('') +} + +describe.skipIf(!hasPwsh)('pwsh tool over the real pwsh executor', () => { + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'dsh-tool-pwsh-')) + await writeFile(join(dir, 'greeting.txt'), 'hello pwsh\n') + + ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(LocalSubprocessService) + await ctx.plugin(PwshLocalExecutor, { timeoutMs: 20_000, graceMs: 200 }) + await ctx.plugin(ToolPwsh) + }) + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }) + }) + + const agent = () => ({ session: { header: { id: 'session-int', cwd: dir } } }) + + it('runs a command and returns stdout with the exit marker', async () => { + const result = await call('pwsh', { command: 'Write-Output hi', description: 'say hi' }, agent()) + expect(result.isError).toBe(false) + if (result.isError) throw new Error('expected pwsh success') + expect(result.value).toMatchObject({ kind: 'foreground', exitCode: 0 }) + expect(lf(text(result))).toBe('hi\n[exit code: 0]') + }) + + it('returns stderr in a marked section and a nonzero exit as a marker, not an error', async () => { + const result = await call('pwsh', { + command: '[Console]::Error.WriteLine("boom"); exit 3', + description: 'fail loudly', + }, agent()) + expect(result.isError).toBe(false) + expect(lf(text(result))).toBe('[stderr]\nboom\n[exit code: 3]') + }) + + it('resolves relative paths in the session workspace', async () => { + const result = await call('pwsh', { + command: 'Get-Content greeting.txt', + description: 'read greeting', + }, agent()) + expect(result.isError).toBe(false) + expect(lf(text(result))).toBe('hello pwsh\n[exit code: 0]') + }) + + it('a per-call timeout kills the run and reports the timed-out marker, not an error', async () => { + const result = await call('pwsh', { + command: 'Start-Sleep -Seconds 60', + description: 'sleep forever', + timeoutMs: 100, + }, agent()) + expect(result.isError).toBe(false) + if (result.isError) throw new Error('expected a timed-out foreground result') + expect(result.value).toMatchObject({ kind: 'foreground', timedOut: true, aborted: false }) + // Windows reports the forced termination as exit 1 without a signal; + // POSIX reports SIGTERM — the timeout marker is the stable fact. + expect(lf(text(result))).toContain('[timed out after 100ms]') + }) + + it('an upstream cancellation aborts the run', async () => { + const controller = new AbortController() + const pending = call('pwsh', { + command: 'Start-Sleep -Seconds 60', + description: 'sleep forever', + }, agent(), controller.signal) + setTimeout(() => { controller.abort() }, 50) + const result = await pending + expect(result.isError).toBe(true) + expect(result.error).toMatchObject({ info: { name: 'AbortError', code: TOOL_ABORTED } }) + }) +}) diff --git a/packages/bash/tool-pwsh/tests/tools.spec.ts b/packages/bash/tool-pwsh/tests/tools.spec.ts new file mode 100644 index 0000000000..5361130991 --- /dev/null +++ b/packages/bash/tool-pwsh/tests/tools.spec.ts @@ -0,0 +1,296 @@ +/** + * Consumer-surface tests for the `pwsh` tool over a FAKE bash executor, + * exercised through `ctx.tools.execute()` so nothing bypasses the tool + * registry. The fake executor makes every seam outcome scriptable — output + * text, truncation, timeout, abort, nonzero exits — so these tests verify the + * schema, argument validation, workdir derivation, managed `DSH_*` collection, + * abort translation, canonical result projection, rendering, and the UI + * presenters. Real-pwsh behavior is pinned separately in integration.spec.ts. + */ + +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve as resolvePath } from 'node:path' +import { CallId } from '@deepseek-ai/dsh-llm' +import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry, { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' +import { BashExecutor } from '@deepseek-ai/dsh-bash' +import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from '@deepseek-ai/dsh-bash' +import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh' + +const testToolSignal = new AbortController().signal + +/** + * A scriptable fake executor: `resolve()` mirrors the real defaulting, `run()` + * returns the armed script, `start()` throws — the pwsh tool must NEVER create + * a background task. + */ +class FakeBash extends BashExecutor { + requests: BashExecRequest[] = [] + specs: BashExecSpec[] = [] + startCalls = 0 + handler: (spec: BashExecSpec) => BashRunResult = () => runResult('') + + override resolve(request: BashExecRequest): BashExecSpec { + this.requests.push(request) + return { + command: request.command, + workdir: request.workdir ?? process.cwd(), + timeoutMs: request.timeoutMs ?? 60_000, + stdoutMaxBytes: request.stdoutMaxBytes ?? 64_000, + ...request.signal ? { signal: request.signal } : {}, + ...request.stdin !== undefined ? { stdin: request.stdin } : {}, + ...request.env !== undefined ? { env: request.env } : {}, + ...request.dshEnv !== undefined ? { dshEnv: request.dshEnv } : {}, + sandboxPolicy: request.sandboxPolicy, + } + } + + override async run(spec: BashExecSpec): Promise { + this.specs.push(spec) + return this.handler(spec) + } + + override start(): BashProcess { + this.startCalls++ + throw new Error('the pwsh tool must never start a background task') + } +} + +/** A successful run result over the given stdout; overrides script the failure shapes. */ +function runResult(stdout: string, overrides?: Partial): BashRunResult { + return { + exitCode: 0, + signal: null, + timedOut: false, + aborted: false, + timeoutMs: 60_000, + stdout: { text: stdout, truncated: false }, + stderr: { text: '', truncated: false }, + ...overrides, + } +} + +async function setup(config: Partial = {}) { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(FakeBash) + await ctx.plugin(ToolPwsh, config) + const bash = ctx.bash as FakeBash + return { ctx, bash } +} + +/** A stand-in agent whose session header carries the given cwd and id. */ +const agent = (cwd?: string, id = 'session-1') => ({ session: { header: { id, ...cwd !== undefined ? { cwd } : {} } } }) + +let callCounter = 0 +function call( + ctx: Context, + name: string, + args: unknown, + options: { agent?: object; signal?: AbortSignal } = {}, +) { + return ctx.tools.execute({ + signal: testToolSignal, + callId: CallId(`call-${++callCounter}`), + name, + arguments: args, + ...options.agent ? { agent: options.agent as never } : {}, + ...options.signal ? { signal: options.signal } : {}, + }) +} + +function text(result: { content: { type: string; text?: string }[] }): string { + return result.content.filter(b => b.type === 'text').map(b => b.text).join('') +} + +describe('registration', () => { + it('registers the pwsh tool with its prompt section and schema', async () => { + const { ctx } = await setup() + const schema = ctx.tools.schemas().find(s => s.name === 'pwsh') + expect(schema).toBeDefined() + expect(schema?.description).toContain('PowerShell command') + expect(schema?.parameters.properties).toMatchObject({ + command: { type: 'string' }, + description: { type: 'string' }, + timeoutMs: { type: 'number' }, + workdir: { type: 'string' }, + }) + expect(schema?.parameters.required).toEqual(['command', 'description']) + const prompt = renderPrompt(await ctx.systemPrompt.assemble()) + expect(prompt).toContain('Check the [exit code: N] marker on every pwsh result') + }) + + it('stays pending until ctx.bash exists (inject)', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(ToolPwsh) + expect(ctx.tools.schemas()).toHaveLength(0) + }) + + it('unregisters everything on fiber disposal (HMR safety)', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(FakeBash) + const fiber = await ctx.plugin(ToolPwsh) + expect(ctx.tools.schemas()).toHaveLength(1) + await fiber.dispose() + expect(ctx.tools.schemas()).toHaveLength(0) + }) +}) + +describe('argument validation', () => { + it('rejects a blank command or description and a non-positive timeoutMs', async () => { + const { ctx } = await setup() + expect(text(await call(ctx, 'pwsh', { command: ' ', description: 'd' }))).toContain('expected a non-empty string') + expect(text(await call(ctx, 'pwsh', { command: 'Write-Output hi', description: ' ' }))).toContain('expected a non-empty string') + expect(text(await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'd', timeoutMs: -1 }))) + .toContain('invalid timeoutMs: expected a positive number') + }) +}) + +describe('execution through the bash seam', () => { + it('forwards command, session cwd, timeout, and managed DSH_* environment', async () => { + const dshHome = mkdtempSync(join(tmpdir(), 'dsh-tool-pwsh-home-')) + const { ctx, bash } = await setup({ dshHome }) + bash.handler = () => runResult('hi\n') + const result = await call(ctx, 'pwsh', { + command: 'Write-Output hi', + description: 'say hi', + timeoutMs: 1234, + }, { agent: agent('/sessions/s1') }) + expect(result.isError).toBe(false) + const request = bash.requests[0] + expect(request?.command).toBe('Write-Output hi') + expect(request?.workdir).toBe('/sessions/s1') + expect(request?.timeoutMs).toBe(1234) + expect(request?.dshEnv).toEqual({ + DSH_HOME: dshHome, + DSH_SHELL: '1', + DSH_SESSION_ID: 'session-1', + }) + expect(bash.specs[0]?.workdir).toBe('/sessions/s1') + }) + + it('resolves a relative workdir against the session cwd, absolute ones verbatim', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('ok\n') + await call(ctx, 'pwsh', { command: 'pwd', description: 'cwd', workdir: 'sub/dir' }, { agent: agent('/sessions/s1') }) + expect(bash.requests[0]?.workdir).toBe(resolvePath('/sessions/s1', 'sub/dir')) + await call(ctx, 'pwsh', { command: 'pwd', description: 'cwd', workdir: resolvePath('/abs/path') }, { agent: agent('/sessions/s1') }) + expect(bash.requests[1]?.workdir).toBe(resolvePath('/abs/path')) + }) + + it('omits workdir and the session id without an agent, so executor defaulting applies', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('ok\n') + await call(ctx, 'pwsh', { command: 'Write-Output ok', description: 'ok' }) + expect(bash.requests[0]).not.toHaveProperty('workdir') + const dshEnv = bash.requests[0]?.dshEnv + expect(dshEnv).toBeDefined() + expect(dshEnv?.['DSH_SHELL']).toBe('1') + expect(dshEnv?.['DSH_HOME']).toEqual(expect.any(String)) + expect(dshEnv).not.toHaveProperty('DSH_SESSION_ID') + }) + + it('forwards exec.signal into the resolved request', async () => { + const { ctx, bash } = await setup() + const controller = new AbortController() + bash.handler = () => runResult('ok\n') + await call(ctx, 'pwsh', { command: 'Write-Output ok', description: 'ok' }, { signal: controller.signal }) + expect(bash.requests[0]?.signal).toBe(controller.signal) + }) + + it('projects the canonical foreground result with stdout, stderr, and exit facts', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('out\n', { + exitCode: 2, + stderr: { text: 'err\n', truncated: false }, + timeoutMs: 5000, + }) + const result = await call(ctx, 'pwsh', { command: 'failing', description: 'fail' }) + expect(result.isError).toBe(false) + if (result.isError) throw new Error('expected pwsh success') + expect(result.value).toEqual({ + kind: 'foreground', + exitCode: 2, + signal: null, + timedOut: false, + aborted: false, + timeoutMs: 5000, + stdout: { text: 'out\n', truncated: false }, + stderr: { text: 'err\n', truncated: false }, + }) + expect(text(result)).toBe('out\n[stderr]\nerr\n[exit code: 2]') + }) + + it('renders the truncation tail, the exit marker, and a timeout marker from the executor streams', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('tail', { + stdout: { text: 'tail', truncated: true, spillPath: '/spill/out.log' }, + stderr: { text: '', truncated: false }, + }) + const result = await call(ctx, 'pwsh', { command: 'noisy', description: 'noise' }) + expect(text(result)).toBe('tail\n[exit code: 0]') + + bash.handler = () => runResult('', { timedOut: true, exitCode: null, signal: 'SIGTERM', timeoutMs: 500 }) + const timedOut = await call(ctx, 'pwsh', { command: 'slow', description: 'slow' }) + // A timeout kill carries both facts, mirroring the bash tool's markers. + expect(text(timedOut)).toBe('[timed out after 500ms]\n[killed by signal: SIGTERM]') + }) + + it('translates an aborted run into the TOOL_ABORTED HarnessError', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('', { aborted: true, exitCode: null, signal: 'SIGTERM' }) + const result = await call(ctx, 'pwsh', { command: 'Start-Sleep -Seconds 60', description: 'sleep' }) + expect(result.isError).toBe(true) + expect(result.error).toMatchObject({ info: { name: 'AbortError', code: TOOL_ABORTED } }) + }) + + it('never starts a background task', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('ok\n') + await call(ctx, 'pwsh', { command: 'Write-Output ok', description: 'ok' }) + bash.handler = () => runResult('', { exitCode: 1 }) + await call(ctx, 'pwsh', { command: 'missing', description: 'missing' }) + expect(bash.startCalls).toBe(0) + }) +}) + +describe('UI presentation', () => { + it('a real execute renders the console view through the tool definition presenter', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('hi\n') + const args = { command: 'Write-Output hi', description: 'say hi' } + const result = await call(ctx, 'pwsh', args, { agent: agent('/w') }) + const view = ctx.tools.get('pwsh')?.presentResult?.(args, result) + expect(view).toEqual({ + card: 'generic', + content: [{ type: 'text', text: '```console\nhi\n[exit code: 0]\n```' }], + }) + }) + + it('the pending call view is a terminal card carrying command, description, and optional cwd', async () => { + const { ctx } = await setup() + const definition = ctx.tools.get('pwsh') + expect(definition?.presentCall?.({ command: 'Get-Process', description: 'List processes' })) + .toEqual({ card: 'terminal', title: 'Get-Process', description: 'List processes' }) + expect(definition?.presentCall?.({ command: 'Get-Process', description: 'List processes', workdir: 'C:\\work' })) + .toMatchObject({ cwd: 'C:\\work' }) + }) + + it('presentResult falls back to undefined for multi-block or non-text content', async () => { + const { ctx } = await setup() + const definition = ctx.tools.get('pwsh') + const args = { command: 'Write-Output hi', description: 'say hi' } + const multi = { content: [{ type: 'text' as const, text: 'a' }, { type: 'text' as const, text: 'b' }], isError: false } + expect(definition?.presentResult?.(args, multi as never)).toBeUndefined() + const image = { content: [{ type: 'image' as const, text: 'a' }], isError: false } + expect(definition?.presentResult?.(args, image as never)).toBeUndefined() + }) +}) diff --git a/packages/bash/tool-pwsh/tsconfig.json b/packages/bash/tool-pwsh/tsconfig.json new file mode 100644 index 0000000000..2811462193 --- /dev/null +++ b/packages/bash/tool-pwsh/tsconfig.json @@ -0,0 +1,45 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../session-persistence/session-persistence" + }, + { + "path": "../../bash/bash" + }, + { + "path": "../../util/paths" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8b38715d30..af21e15b04 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -309,6 +309,9 @@ importers: '@deepseek-ai/dsh-pty-local': specifier: workspace:^ version: link:../../packages/pty/pty-local + '@deepseek-ai/dsh-pwsh-local': + specifier: workspace:^ + version: link:../../packages/bash/pwsh-local '@deepseek-ai/dsh-repeat-tool-guard': specifier: workspace:^ version: link:../../packages/guard/repeat-tool-guard @@ -426,6 +429,9 @@ importers: '@deepseek-ai/dsh-tool-goal': specifier: workspace:^ version: link:../../packages/goal/tool-goal + '@deepseek-ai/dsh-tool-pwsh': + specifier: workspace:^ + version: link:../../packages/bash/tool-pwsh '@deepseek-ai/dsh-tool-ralph': specifier: workspace:^ version: link:../../packages/workflow/tool-ralph @@ -941,6 +947,31 @@ importers: specifier: 0.0.0-test.0 version: 0.0.0-test.0 + packages/bash/pwsh-local: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + devDependencies: + '@deepseek-ai/dsh-bash': + specifier: workspace:^ + version: link:../bash + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-subprocess': + specifier: workspace:^ + version: link:../../subprocess/subprocess + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:^ + version: link:../../subprocess/subprocess-local + '@deepseek-ai/dsh-timeout': + specifier: workspace:^ + version: link:../../util/timeout + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/bash/tool-bash: dependencies: schemastery: @@ -1011,6 +1042,46 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/bash/tool-pwsh: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + devDependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent + '@deepseek-ai/dsh-bash': + specifier: workspace:^ + version: link:../bash + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-paths': + specifier: workspace:^ + version: link:../../util/paths + '@deepseek-ai/dsh-pwsh-local': + specifier: workspace:^ + version: link:../pwsh-local + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:^ + version: link:../../session-persistence/session-persistence + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:^ + version: link:../../subprocess/subprocess-local + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/client/connection: dependencies: '@deepseek-ai/dsh-commands': diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 3db63b4271..5f8272ae3f 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -17,6 +17,7 @@ import GoalService from '@deepseek-ai/dsh-goal' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools' import LocalBashExecutor from '@deepseek-ai/dsh-bash-local' +import { PwshLocalExecutor } from '@deepseek-ai/dsh-pwsh-local' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import UserInteractionService from '@deepseek-ai/dsh-user-interaction' @@ -31,6 +32,7 @@ import * as SkillLocal from '@deepseek-ai/dsh-skill-local' import LocalTaskService from '@deepseek-ai/dsh-tasks-local' import * as ToolAskUser from '@deepseek-ai/dsh-tool-ask-user' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' +import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh' import * as ToolBashPersistent from '@deepseek-ai/dsh-tool-bash-persistent' import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis' import * as ToolFs from '@deepseek-ai/dsh-tool-fs' @@ -167,6 +169,23 @@ const TOOL_PACKAGES: ToolPackage[] = [ note: 'The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled.', }, + { + pkg: '@deepseek-ai/dsh-tool-pwsh', + dir: 'tool-pwsh', + source: 'packages/bash/tool-pwsh/src/index.ts', + requires: ['ctx.tools', 'ctx.bash', 'ctx.systemPrompt'], + writes: ['tool/call', 'tool/result'], + async mount(ctx) { + // The pwsh tool consumes the bash executor seam; the schema harvest + // mounts the pwsh-local implementation so the inject resolves without + // executing anything (registration never spawns a process). + await ctx.plugin(LocalSubprocessService) + await ctx.plugin(PwshLocalExecutor) + await ctx.plugin(ToolPwsh) + }, + note: + 'The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\\...` paths and `$env:NAME` variables.', + }, { pkg: '@deepseek-ai/dsh-tool-cordis', dir: 'tool-cordis', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 4104ff8fdc..ed723c26f5 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -43,6 +43,7 @@ const NO_MODEL_EXPERIENCE_SECTION: Readonly> = { const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/bash/bash': { kind: 'indirect', reason: 'The service interface delegates all model rendering to dsh-tool-bash.' }, 'packages/bash/bash-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-bash.' }, + 'packages/bash/pwsh-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-pwsh.' }, 'packages/code-runtime/code-runtime': { kind: 'indirect', reason: 'The service interface delegates model rendering to Code Mode in dsh-tools.' }, 'packages/code-runtime/code-runtime-worker': { kind: 'indirect', reason: 'The worker backend delegates model rendering to Code Mode in dsh-tools.' }, 'packages/typert/registry': { kind: 'none', reason: 'Runtime type registry; consumers (cordis_inspect, wire faces, gates) own any model-visible projection of registry contents.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 2d078202e7..213c9be688 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -52,6 +52,8 @@ "@deepseek-ai/dsh-session-title/client": ["./packages/session-title/session-title/src/client.ts"], "@deepseek-ai/dsh-plan-mode/types": ["./packages/plan/plan-mode/src/types.ts"], "@deepseek-ai/dsh-plan-mode/client": ["./packages/plan/plan-mode/src/client.ts"], + "@deepseek-ai/dsh-pwsh-local": ["./packages/bash/pwsh-local/src/index.ts"], + "@deepseek-ai/dsh-tool-pwsh": ["./packages/bash/tool-pwsh/src/index.ts"], "@deepseek-ai/dsh-goal/types": ["./packages/goal/goal/src/types.ts"], "@deepseek-ai/dsh-goal/client": ["./packages/goal/goal/src/client.ts"], "@deepseek-ai/dsh-llm/types": ["./packages/llm/llm/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index bae800f3ff..99217311e6 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -136,6 +136,8 @@ { "path": "./packages/llm/llm-deepseek" }, { "path": "./packages/llm/llm-pi-ai" }, { "path": "./packages/bash/bash-local" }, + { "path": "./packages/bash/pwsh-local" }, + { "path": "./packages/bash/tool-pwsh" }, { "path": "./packages/sandbox/sandbox" }, { "path": "./packages/sandbox/sandbox-local" }, { "path": "./packages/sandbox/sandbox-policy" }, diff --git a/vitest.config.ts b/vitest.config.ts index 5f542feee6..0fa2a6dd53 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -11,7 +11,13 @@ const pathsPlugin = (): ReturnType => tsconfigPaths({ proj const windowsUnsupportedPackages = process.platform === 'win32' ? [ - 'packages/bash/*', + // Bash-requiring suites (a real POSIX shell is unavailable on Windows). + // The pwsh-requiring suites (pwsh-local, tool-pwsh) deliberately stay + // INCLUDED: PowerShell ships with Windows, so they run natively here. + 'packages/bash/bash-local', + 'packages/bash/bash-sandbox', + 'packages/bash/tool-bash', + 'packages/bash/tool-bash-persistent', 'packages/hooks/*', 'packages/subprocess/*', 'packages/pty/pty-local', From 30c421ed75083d7d8ee5cb3c52fb32e9f64c34f1 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sat, 1 Aug 2026 19:34:12 +0800 Subject: [PATCH 02/61] fix(pwsh): pin CI expectations for the mirror design - jscpd: the executor/tool mirror dsh-bash-local/dsh-tool-bash by design (Agent Note), so the mirrored regions carry explicit ignore markers with reasons instead of being flagged as duplication. - pwsh-local: a self-terminated process reports SIGTERM or SIGKILL on POSIX (PowerShell's Stop-Process choice), not only SIGTERM. - gen-tool-catalog.spec: the shipped-tool completeness list gains 'pwsh'. --- packages/bash/pwsh-local/src/index.ts | 2 ++ packages/bash/pwsh-local/tests/executor.spec.ts | 8 +++++--- packages/bash/tool-pwsh/src/index.ts | 9 +++++++++ packages/core/tools/tests/gen-tool-catalog.spec.ts | 2 +- 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/bash/pwsh-local/src/index.ts b/packages/bash/pwsh-local/src/index.ts index 2bf8b904c2..8548731a28 100644 --- a/packages/bash/pwsh-local/src/index.ts +++ b/packages/bash/pwsh-local/src/index.ts @@ -22,6 +22,7 @@ import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashR import type { SubprocessCollect, SubprocessHandle, SubprocessOutputReader, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import { clampTimeout, deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' +/* jscpd:ignore-start -- deliberate call-for-call mirror of dsh-bash-local (Agent Note: pwsh-tool-and-executor). */ /** * Model-friendly environment overrides for PowerShell: disable colors and * pagers that would garble tool output. `TERM=dumb` is a POSIX concept and is @@ -312,5 +313,6 @@ export class PwshLocalExecutor extends BashExecutor { */ protected onProcessDone(_proc: BashProcess, _stderr: string): void {} } +/* jscpd:ignore-end */ export default PwshLocalExecutor diff --git a/packages/bash/pwsh-local/tests/executor.spec.ts b/packages/bash/pwsh-local/tests/executor.spec.ts index cd72e47db4..1794666911 100644 --- a/packages/bash/pwsh-local/tests/executor.spec.ts +++ b/packages/bash/pwsh-local/tests/executor.spec.ts @@ -197,11 +197,12 @@ describe.skipIf(!hasPwsh)('PwshLocalExecutor.run', () => { const result = await bash.run(bash.resolve({ command: 'Stop-Process -Id $PID' })) expect(result.timedOut).toBe(false) expect(result.aborted).toBe(false) - // Windows reports a forced termination without a signal; POSIX reports SIGTERM. + // Windows reports a forced termination without a signal; POSIX reports the + // terminating signal PowerShell chose (SIGTERM, or SIGKILL for the hard kill). if (process.platform === 'win32') { expect(result.signal).toBeNull() } else { - expect(result.signal).toBe('SIGTERM') + expect(['SIGTERM', 'SIGKILL']).toContain(result.signal) } }) @@ -347,7 +348,8 @@ describe.skipIf(!hasPwsh)('PwshLocalExecutor.start (background process handles)' await proc.done expect(proc.status).toBe('killed') expect(proc.exitCode).toBeNull() - expect(proc.signal).toBe('SIGTERM') + // PowerShell picks SIGTERM for Stop-Process, SIGKILL for the hard kill. + expect(['SIGTERM', 'SIGKILL']).toContain(proc.signal) }) it('a background spawn failure settles as killed with the error readable on stderr', async () => { diff --git a/packages/bash/tool-pwsh/src/index.ts b/packages/bash/tool-pwsh/src/index.ts index 96073fcf93..704c35647c 100644 --- a/packages/bash/tool-pwsh/src/index.ts +++ b/packages/bash/tool-pwsh/src/index.ts @@ -58,6 +58,7 @@ interface PwshForegroundResult { stderr: { text: string; truncated: boolean; spillPath?: string } } +/* jscpd:ignore-start -- minimal mirror of dsh-tool-bash's validation and execute plumbing (Agent Note). */ function validatePwshArgs(args: PwshToolArgs): void { if (args.command.trim().length === 0) { throw new Error('invalid command: expected a non-empty string') @@ -69,6 +70,7 @@ function validatePwshArgs(args: PwshToolArgs): void { throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`) } } +/* jscpd:ignore-end */ function pwshDescription(): string { return 'Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. ' @@ -185,6 +187,10 @@ export function apply(ctx: Context, config: Config = {}): void { workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' }, }, output: { + // The foreground result wire shape mirrors dsh-tool-bash's by contract — + // consumers of one must accept the other (see the pwsh-tool-and-executor + // Agent Note). + /* jscpd:ignore-start -- deliberate foreground-result schema symmetry with dsh-tool-bash. */ schema: { type: 'object', additionalProperties: false, @@ -217,11 +223,13 @@ export function apply(ctx: Context, config: Config = {}): void { }, }, }, + /* jscpd:ignore-end */ render: (_args, value) => [{ type: 'text', text: renderPwshOutput(value), }], }, + /* jscpd:ignore-start -- the foreground execute path mirrors dsh-tool-bash's by design (see the pwsh-tool-and-executor Agent Note). */ async execute(args: PwshToolArgs, exec) { validatePwshArgs(args) const workdir = resolveWorkdir(args.workdir, exec) @@ -239,6 +247,7 @@ export function apply(ctx: Context, config: Config = {}): void { } return canonicalPwshResult(result) }, + /* jscpd:ignore-end */ presentCall: (args: PwshToolArgs): TerminalCallView => ({ card: 'terminal', title: args.command, diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index 1ab8bc2730..73c3e44e89 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -23,7 +23,7 @@ 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_inspect', 'cordis_mount', 'cordis_unmount', 'create_goal', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'lsp', 'ralph', 'read', 'run_code', 'session_event_read', 'session_event_search', 'session_event_trace', 'session_search', 'session_trace', 'skill', 'str_replace_editor', 'subagent', 'task_kill', 'task_list', 'task_output', '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_inspect', 'cordis_mount', 'cordis_unmount', 'create_goal', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'lsp', 'pwsh', 'ralph', 'read', 'run_code', 'session_event_read', 'session_event_search', 'session_event_trace', 'session_search', 'session_trace', 'skill', 'str_replace_editor', 'subagent', 'task_kill', 'task_list', 'task_output', 'terminal_close', 'terminal_list', 'terminal_open', 'terminal_read', 'terminal_send', 'terminal_signal', 'todo_write', 'update_goal', '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) { From 5ca7e1ada9f8a7f33a41f6a893421d648ad9adc8 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sat, 1 Aug 2026 19:43:05 +0800 Subject: [PATCH 03/61] docs(config-catalog): refresh the pwsh-local source line after the jscpd markers --- docs/config-catalog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index a687dff035..f5caf51007 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -991,7 +991,7 @@ export interface Config { } ``` -Source: [`packages/bash/pwsh-local/src/index.ts:43`](../packages/bash/pwsh-local/src/index.ts) +Source: [`packages/bash/pwsh-local/src/index.ts:44`](../packages/bash/pwsh-local/src/index.ts) ## `@deepseek-ai/dsh-repeat-tool-guard` From 1c3887673a8cfe1670c1c2baa7db09fba5bfed9d Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sat, 1 Aug 2026 21:56:32 +0800 Subject: [PATCH 04/61] test(fs-search): re-record the glob-sampling snapshot against the real API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The scenario previously carried an authored fixture; W4 of #1119 review requires a live transcript. Recording surfaced two composition bugs that are fixed here alongside it: - provider ids: the app and the replay catalog both named the old 'deepseek' provider, which no adapter registers; both now use 'deepseek-official' - the live config lacked persistenceCompression: none, so record-mode sessions were written zstd-compressed and could not be harvested (the snapshot twin already forced plaintext) Recorded logs also need deterministic replay: - packChunks: false in both configs — the eager-drain batch boundaries that split packed delta runs are timing-dependent, so a packed log of a long reasoning stream cannot replay-match its live record - the fixture's request/header config and request/context are normalized to the replay-produced minimal shape (the live adapter logs model capabilities llm-replay has no data for), and tool-result path separators are canonicalized to '/' for the Linux golden posixOnly is restored now that the fixture is recorded. --- examples/acp-agent/tests/acp.snapshot.ts | 13 +- .../tests/fs-search.cordis.snapshot.yml | 8 +- examples/acp-agent/tests/fs-search.cordis.yml | 7 +- .../snapshots/fs-glob-sampling/session.jsonl | 145 +++++++++++++++--- 4 files changed, 142 insertions(+), 31 deletions(-) diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index 277d0b20ca..abdf10e367 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -181,16 +181,23 @@ const SCENARIOS: Scenario[] = [ // `--sort=modified` order, pinning over-cap glob sampling without depending // on a host-installed ripgrep binary or a PATH stand-in. POSIX-only because // the displayed paths carry `/` separators the session-log comparison - // cannot normalize. + // cannot normalize. Recorded (not authored): the assistant turn is a real + // model transcript; re-record with `test:snapshot:record -t fs-glob-sampling`. + // The composition disables packed chunk rows (fs-search.cordis.yml), whose + // run boundaries depend on eager-drain timing, and the recorded fixture's + // `request/header` config and `request/context` are normalized to the + // replay-produced minimal shape (the live adapter logs model capabilities + // like maxTokens/reasoningEffort that llm-replay has no data for), and its + // tool-result paths are canonicalized to `/` separators. { name: 'fs-glob-sampling', hasModelTurn: true, - recorded: false, + recorded: true, + posixOnly: true, pinsHeader: true, headerClass: 'fs-search', configPath: FS_SEARCH_CONFIG, prepareWorkspace: prepareFsSearchWorkspace, - posixOnly: true, }, { name: 'fs-read', hasModelTurn: true, recorded: true }, { name: 'fs-write', hasModelTurn: true, recorded: true }, diff --git a/examples/acp-agent/tests/fs-search.cordis.snapshot.yml b/examples/acp-agent/tests/fs-search.cordis.snapshot.yml index 141691a087..5fcb2248f3 100644 --- a/examples/acp-agent/tests/fs-search.cordis.snapshot.yml +++ b/examples/acp-agent/tests/fs-search.cordis.snapshot.yml @@ -3,7 +3,7 @@ name: '@deepseek-ai/dsh-llm-replay' config: providers: - - id: deepseek + - id: deepseek-official name: DeepSeek models: - id: deepseek-v4-pro @@ -17,10 +17,14 @@ - id: acp-agent name: '@deepseek-ai/dsh-acp-demo' config: - provider: deepseek + provider: deepseek-official model: deepseek-v4-pro persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' persistenceCompression: none + # Unpacked rows: the eager-drain batch boundaries that split packed delta + # runs are timing-dependent, so packed logs cannot replay-match a live + # record of a long reasoning stream. + packChunks: false workspaceContext: false skills: enabled: false diff --git a/examples/acp-agent/tests/fs-search.cordis.yml b/examples/acp-agent/tests/fs-search.cordis.yml index 153128f914..0f6d5d9a63 100644 --- a/examples/acp-agent/tests/fs-search.cordis.yml +++ b/examples/acp-agent/tests/fs-search.cordis.yml @@ -16,9 +16,14 @@ - id: acp-agent name: '@deepseek-ai/dsh-acp-demo' config: - provider: deepseek + provider: deepseek-official model: deepseek-v4-pro persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" + # Unpacked rows: the eager-drain batch boundaries that split packed delta + # runs are timing-dependent, so packed logs cannot replay-match a live + # record of a long reasoning stream. + packChunks: false workspaceContext: false skills: enabled: false diff --git a/examples/acp-agent/tests/snapshots/fs-glob-sampling/session.jsonl b/examples/acp-agent/tests/snapshots/fs-glob-sampling/session.jsonl index ca51259632..f1c26ca911 100644 --- a/examples/acp-agent/tests/snapshots/fs-glob-sampling/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-glob-sampling/session.jsonl @@ -1,25 +1,120 @@ -{"type":"session","version":0,"id":"f5a99d52-3eaa-4ce7-858d-61d4fd77df2a","createdAt":1785218400000,"cwd":"{{cwd}}","delegationDepth":0} -{"type":"turn/start","seq":0,"time":1785218400001,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":1,"time":1785218400002,"data":{"content":[{"type":"text","text":"Call glob exactly once with pattern * and path tree. Then reply with exactly GLOB_SAMPLED and nothing else."}],"source":{"kind":"user"},"role":"user","id":"6790985f-1de2-42f8-a7f1-24e46d6439c7"},"surfaceOp":"append"} -{"type":"session/title","seq":2,"time":1785218400003,"data":{"title":"Call glob exactly once with","messageSeqs":[1],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":3,"time":1785218400004,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":4,"time":1785218400005,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"request/context","seq":5,"time":1785483397569,"data":{"provider":"deepseek","model":"deepseek-v4-pro"}} -{"type":"assistant/chunk","seq":6,"time":1785218400007,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":7,"time":1785218400008,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"glob-sampling-call","name":"glob","argumentsDelta":"{\"pattern\":\"*\",\"path\":\"tree\"}"}}} -{"type":"assistant/chunk","seq":8,"time":1785218400009,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"glob-sampling-call","name":"glob","arguments":"{\"pattern\":\"*\",\"path\":\"tree\"}"}}}} -{"type":"assistant/chunk","seq":9,"time":1785218400010,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1,"outputTokens":1}}}} -{"type":"assistant/chunk","seq":10,"time":1785483397579,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":11,"time":1785483397579,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"glob-sampling-call","name":"glob","arguments":"{\"pattern\":\"*\",\"path\":\"tree\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-pro"},"id":"a127cfe5-39fb-462c-8e5a-a8c79bd0e52b"},"usage":{"inputTokens":1,"outputTokens":1}},"sourceEventSeqs":[6,7,8,9,10],"surfaceOp":"append"} -{"type":"tool/call","seq":12,"time":1785483397579,"data":{"turn":1,"step":1,"callId":"glob-sampling-call","name":"glob","arguments":"{\"pattern\":\"*\",\"path\":\"tree\"}"}} -{"type":"tool/result","seq":13,"time":1785483398062,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"glob-sampling-call"},"content":[{"type":"tool-result","toolCallId":"glob-sampling-call","content":[{"type":"text","text":"tree/archive/a.ts\ntree/docs/guide.md\ntree/src/index.ts\ntree/test/spec.ts\n\n(Showing 4 of 8 paths, sampled across 4 of the 6 top-level entries this pattern matched instead of taken in modification-time order. Narrow path to inspect a specific subtree. The complete result could not be saved; narrow pattern or path to see more.)"}],"isError":false}],"role":"user","id":"2beecb2e-627d-43dc-a936-03e1dc874093"},"meta":{"shape":"paths","paths":["tree/archive/a.ts","tree/docs/guide.md","tree/src/index.ts","tree/test/spec.ts"],"truncated":true,"total":8}},"sourceEventSeqs":[12],"surfaceOp":"append"} -{"type":"step/end","seq":14,"time":1785483398062,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":15,"time":1785483398072,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":16,"time":1785218400017,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} -{"type":"assistant/chunk","seq":17,"time":1785218400018,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":0,"text":"GLOB_SAMPLED"}}} -{"type":"assistant/chunk","seq":18,"time":1785218400019,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"GLOB_SAMPLED"}}}} -{"type":"assistant/chunk","seq":19,"time":1785218400020,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":1,"outputTokens":1}}}} -{"type":"assistant/chunk","seq":20,"time":1785483398078,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":21,"time":1785483398078,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"GLOB_SAMPLED"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-pro"},"id":"ce2334a4-be71-490b-a502-29186a9ced5c"},"usage":{"inputTokens":1,"outputTokens":1}},"sourceEventSeqs":[16,17,18,19,20],"surfaceOp":"append"} -{"type":"step/end","seq":22,"time":1785483398078,"data":{"turn":1,"step":2}} -{"type":"turn/end","seq":23,"time":1785483398079,"data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"session","version":0,"id":"4428b809-66d5-4ea2-9a03-89de742fcda1","createdAt":1785591986068,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"turn/start","seq":0,"time":1785591986072,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} +{"type":"user/message","seq":1,"time":1785591986073,"data":{"content":[{"type":"text","text":"Call glob exactly once with pattern * and path tree. Then reply with exactly GLOB_SAMPLED and nothing else."}],"source":{"kind":"user"},"role":"user","id":"3d05fb76-4185-460b-9c6a-8c1b2495bc9f"},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1785591986074,"data":{"title":"Call glob exactly once with","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1785591986092,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1785591986093,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","seq":5,"time":1785591986094,"data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} +{"type":"assistant/chunk","seq":6,"time":1785591987500,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":7,"time":1785591987500,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":8,"time":1785591987529,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":9,"time":1785591987587,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} +{"type":"assistant/chunk","seq":10,"time":1785591987588,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":11,"time":1785591987588,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":12,"time":1785591987588,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" call"}}} +{"type":"assistant/chunk","seq":13,"time":1785591987588,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" glob"}}} +{"type":"assistant/chunk","seq":14,"time":1785591987639,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} +{"type":"assistant/chunk","seq":15,"time":1785591987639,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" once"}}} +{"type":"assistant/chunk","seq":16,"time":1785591987639,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":17,"time":1785591987685,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" pattern"}}} +{"type":"assistant/chunk","seq":18,"time":1785591987685,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" *"}}} +{"type":"assistant/chunk","seq":19,"time":1785591987876,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":20,"time":1785591987877,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" path"}}} +{"type":"assistant/chunk","seq":21,"time":1785591987877,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" tree"}}} +{"type":"assistant/chunk","seq":22,"time":1785591987877,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} +{"type":"assistant/chunk","seq":23,"time":1785591987877,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" then"}}} +{"type":"assistant/chunk","seq":24,"time":1785591987877,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} +{"type":"assistant/chunk","seq":25,"time":1785591987877,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":26,"time":1785591987877,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} +{"type":"assistant/chunk","seq":27,"time":1785591987877,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} +{"type":"assistant/chunk","seq":28,"time":1785591987878,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"G"}}} +{"type":"assistant/chunk","seq":29,"time":1785591987878,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"LOB"}}} +{"type":"assistant/chunk","seq":30,"time":1785591987878,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"_S"}}} +{"type":"assistant/chunk","seq":31,"time":1785591987878,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"AM"}}} +{"type":"assistant/chunk","seq":32,"time":1785591987878,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"PL"}}} +{"type":"assistant/chunk","seq":33,"time":1785591987878,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ED"}}} +{"type":"assistant/chunk","seq":34,"time":1785591987977,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} +{"type":"assistant/chunk","seq":35,"time":1785591988034,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":36,"time":1785591988035,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":""}}} +{"type":"assistant/chunk","seq":37,"time":1785591988090,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"{"}}} +{"type":"assistant/chunk","seq":38,"time":1785591988090,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":39,"time":1785591988090,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"pattern"}}} +{"type":"assistant/chunk","seq":40,"time":1785591988091,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":41,"time":1785591988136,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":42,"time":1785591988136,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":43,"time":1785591988136,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"*"}}} +{"type":"assistant/chunk","seq":44,"time":1785591988193,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":45,"time":1785591988207,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":46,"time":1785591988207,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":47,"time":1785591988207,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"path"}}} +{"type":"assistant/chunk","seq":48,"time":1785591988207,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":49,"time":1785591988207,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":50,"time":1785591988284,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":51,"time":1785591988284,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"tree"}}} +{"type":"assistant/chunk","seq":52,"time":1785591988284,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":53,"time":1785591988338,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","argumentsDelta":"}"}}} +{"type":"assistant/chunk","seq":54,"time":1785591988427,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to call glob exactly once with pattern * and path tree, then reply with exactly \"GLOB_SAMPLED\"."}}}} +{"type":"assistant/chunk","seq":55,"time":1785591988427,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","arguments":"{\"pattern\": \"*\", \"path\": \"tree\"}"}}}} +{"type":"assistant/chunk","seq":56,"time":1785591988427,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1286,"outputTokens":87,"cacheReadTokens":0,"reasoningTokens":28}}}} +{"type":"assistant/chunk","seq":57,"time":1785591988427,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":58,"time":1785591988430,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to call glob exactly once with pattern * and path tree, then reply with exactly \"GLOB_SAMPLED\"."},{"type":"tool-call","id":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","arguments":"{\"pattern\": \"*\", \"path\": \"tree\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"b74cbab2-c017-4e44-8c09-a7745d8b274a"},"usage":{"inputTokens":1286,"outputTokens":87,"cacheReadTokens":0,"reasoningTokens":28}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57],"surfaceOp":"append"} +{"type":"tool/call","seq":59,"time":1785591988431,"data":{"turn":1,"step":1,"callId":"call_00_1cLZjkCW0vxVw0e3xVfh3430","name":"glob","arguments":"{\"pattern\": \"*\", \"path\": \"tree\"}"}} +{"type":"tool/result","seq":60,"time":1785591988476,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_1cLZjkCW0vxVw0e3xVfh3430"},"content":[{"type":"tool-result","toolCallId":"call_00_1cLZjkCW0vxVw0e3xVfh3430","content":[{"type":"text","text":"tree/archive/a.ts\ntree/docs/guide.md\ntree/src/index.ts\ntree/test/spec.ts\n\n(Showing 4 of 8 paths, sampled across 4 of the 6 top-level entries this pattern matched instead of taken in modification-time order. Narrow path to inspect a specific subtree. The complete result could not be saved; narrow pattern or path to see more.)"}],"isError":false}],"role":"user","id":"10284f88-4890-49ed-9a17-56edbd6bfaa7"},"meta":{"shape":"paths","paths":["tree/archive/a.ts","tree/docs/guide.md","tree/src/index.ts","tree/test/spec.ts"],"truncated":true,"total":8}},"sourceEventSeqs":[59],"surfaceOp":"append"} +{"type":"step/end","seq":61,"time":1785591988476,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":62,"time":1785591988482,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":63,"time":1785591989939,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":64,"time":1785591989939,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":65,"time":1785591989939,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" glob"}}} +{"type":"assistant/chunk","seq":66,"time":1785591989939,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" result"}}} +{"type":"assistant/chunk","seq":67,"time":1785591989939,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" shows"}}} +{"type":"assistant/chunk","seq":68,"time":1785591989988,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" it"}}} +{"type":"assistant/chunk","seq":69,"time":1785591990024,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" was"}}} +{"type":"assistant/chunk","seq":70,"time":1785591990127,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" sampled"}}} +{"type":"assistant/chunk","seq":71,"time":1785591990128,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" -"}}} +{"type":"assistant/chunk","seq":72,"time":1785591990128,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} +{"type":"assistant/chunk","seq":73,"time":1785591990128,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"4"}}} +{"type":"assistant/chunk","seq":74,"time":1785591990454,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" of"}}} +{"type":"assistant/chunk","seq":75,"time":1785591990454,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} +{"type":"assistant/chunk","seq":76,"time":1785591990454,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"8"}}} +{"type":"assistant/chunk","seq":77,"time":1785591990454,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" paths"}}} +{"type":"assistant/chunk","seq":78,"time":1785591990454,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" across"}}} +{"type":"assistant/chunk","seq":79,"time":1785591990454,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} +{"type":"assistant/chunk","seq":80,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"4"}}} +{"type":"assistant/chunk","seq":81,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" of"}}} +{"type":"assistant/chunk","seq":82,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" "}}} +{"type":"assistant/chunk","seq":83,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"6"}}} +{"type":"assistant/chunk","seq":84,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" top"}}} +{"type":"assistant/chunk","seq":85,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"-level"}}} +{"type":"assistant/chunk","seq":86,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" entries"}}} +{"type":"assistant/chunk","seq":87,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":88,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} +{"type":"assistant/chunk","seq":89,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" need"}}} +{"type":"assistant/chunk","seq":90,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":91,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} +{"type":"assistant/chunk","seq":92,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":93,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" exactly"}}} +{"type":"assistant/chunk","seq":94,"time":1785591990455,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} +{"type":"assistant/chunk","seq":95,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"G"}}} +{"type":"assistant/chunk","seq":96,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"LOB"}}} +{"type":"assistant/chunk","seq":97,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"_S"}}} +{"type":"assistant/chunk","seq":98,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"AM"}}} +{"type":"assistant/chunk","seq":99,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"PL"}}} +{"type":"assistant/chunk","seq":100,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ED"}}} +{"type":"assistant/chunk","seq":101,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\""}}} +{"type":"assistant/chunk","seq":102,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" as"}}} +{"type":"assistant/chunk","seq":103,"time":1785591990456,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" instructed"}}} +{"type":"assistant/chunk","seq":104,"time":1785591990470,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":105,"time":1785591990470,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} +{"type":"assistant/chunk","seq":106,"time":1785591990470,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"G"}}} +{"type":"assistant/chunk","seq":107,"time":1785591990470,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"LOB"}}} +{"type":"assistant/chunk","seq":108,"time":1785591990470,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"_S"}}} +{"type":"assistant/chunk","seq":109,"time":1785591990470,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"AM"}}} +{"type":"assistant/chunk","seq":110,"time":1785591990518,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"PL"}}} +{"type":"assistant/chunk","seq":111,"time":1785591990518,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ED"}}} +{"type":"assistant/chunk","seq":112,"time":1785591990526,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The glob result shows it was sampled - 4 of 8 paths across 4 of 6 top-level entries. I need to reply with exactly \"GLOB_SAMPLED\" as instructed."}}}} +{"type":"assistant/chunk","seq":113,"time":1785591990527,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"GLOB_SAMPLED"}}}} +{"type":"assistant/chunk","seq":114,"time":1785591990527,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":188,"outputTokens":48,"cacheReadTokens":1280,"reasoningTokens":41}}}} +{"type":"assistant/chunk","seq":115,"time":1785591990527,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":116,"time":1785591990527,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The glob result shows it was sampled - 4 of 8 paths across 4 of 6 top-level entries. I need to reply with exactly \"GLOB_SAMPLED\" as instructed."},{"type":"text","text":"GLOB_SAMPLED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"dd3a9c28-43b2-4fdc-8089-1547309a71c0"},"usage":{"inputTokens":188,"outputTokens":48,"cacheReadTokens":1280,"reasoningTokens":41}},"sourceEventSeqs":[63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115],"surfaceOp":"append"} +{"type":"step/end","seq":117,"time":1785591990527,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":118,"time":1785591990528,"data":{"turn":1,"reason":{"kind":"completed"}}} From d73888478ab3dd568f499a8b8a6e7fd9649df00f Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 14:17:46 +0800 Subject: [PATCH 05/61] feat(bash-env): extract the shared DSH_* environment registry into its own package --- packages/bash/bash-env/README.i18n.yaml | 6 + packages/bash/bash-env/README.md | 51 ++++ packages/bash/bash-env/README.zh.md | 51 ++++ packages/bash/bash-env/package.json | 50 ++++ packages/bash/bash-env/src/index.ts | 217 ++++++++++++++++ packages/bash/bash-env/src/invariant.ts | 30 +++ packages/bash/bash-env/tests/bash-env.spec.ts | 237 ++++++++++++++++++ packages/bash/bash-env/tsconfig.json | 36 +++ .../cordis/tool-cordis/src/api-catalog.ts | 2 +- python/sdk-runtime/package.json | 1 + .../verify-package-readme-model-experience.ts | 1 + tsconfig.base.json | 1 + tsconfig.host.json | 1 + vitest.config.ts | 3 +- 14 files changed, 685 insertions(+), 2 deletions(-) create mode 100644 packages/bash/bash-env/README.i18n.yaml create mode 100644 packages/bash/bash-env/README.md create mode 100644 packages/bash/bash-env/README.zh.md create mode 100644 packages/bash/bash-env/package.json create mode 100644 packages/bash/bash-env/src/index.ts create mode 100644 packages/bash/bash-env/src/invariant.ts create mode 100644 packages/bash/bash-env/tests/bash-env.spec.ts create mode 100644 packages/bash/bash-env/tsconfig.json diff --git a/packages/bash/bash-env/README.i18n.yaml b/packages/bash/bash-env/README.i18n.yaml new file mode 100644 index 0000000000..90d43daa7b --- /dev/null +++ b/packages/bash/bash-env/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/bash/bash-env/README.md +README.md: 7b939326d4effd14fc83ef0ad4e133f019f1011f +README.zh.md: aeb33629def3fcc10294bbca19b37d43dcc73a0c diff --git a/packages/bash/bash-env/README.md b/packages/bash/bash-env/README.md new file mode 100644 index 0000000000..7b939326d4 --- /dev/null +++ b/packages/bash/bash-env/README.md @@ -0,0 +1,51 @@ +# @deepseek-ai/dsh-bash-env + +English | [中文](README.zh.md) + +The tool-independent shell environment plugin: owns the `ctx.bashEnv` registry of trusted, per-execution `DSH_*` variables that the model-facing shell tools (`dsh-tool-bash`, `dsh-tool-pwsh`) collect into every shell call's environment. Built-in shell facts (`DSH_HOME`, `DSH_SHELL=1`, `DSH_SESSION_ID`) are owned by the registry itself; other plugins register additional enumerable facts with effect-scoped disposal, and duplicate ownership or undeclared runtime keys fail loudly. + +The package root exports the Cordis plugin contract (`name`, `inject`, `Config`, `apply`) plus the `BashEnvRegistry` service class and its contributor types; consumers use `ctx.bashEnv` after loading this plugin. + +## Config + +```yaml +- id: bash-env + name: '@deepseek-ai/dsh-bash-env' + config: + dshHome: C:\Users\me\.dsh # default: $DSH_HOME, then ~/.dsh +``` + +## Managed environment + +Every foreground and background model shell call receives a newly collected trusted `DSH_*` environment. `DSH_HOME` is the absolute Harness home resolved by [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) (`dshHome` config, then ambient `$DSH_HOME`, then `~/.dsh`) and `DSH_SHELL=1` identifies the managed child. Agent calls additionally receive `DSH_SESSION_ID=agent.session.header.id`; when the active persistence seam locates a JSONL artifact they also receive `DSH_SESSION_JSONL=`. The JSONL path is a location hint: it may not exist before the first flush or contain the current buffered turn, and it is not an authorization credential. + +`ctx.bashEnv` owns collection. Other plugins can register an effect-scoped contributor with a stable name, declared keys/descriptions, and `resolve(execution: ToolExecution)`; duplicate ownership and undeclared runtime keys fail loudly, while `list()` enumerates declarations without executing providers. Harness built-ins reserve `DSH_HOME`, `DSH_SHELL`, and `DSH_SESSION_ID`; this plugin's persistence translator owns `DSH_SESSION_JSONL` by reading the backend-neutral `sessionPersistence.locate()` seam. + +```ts +import type { Context } from 'cordis' +import type {} from '@deepseek-ai/dsh-bash-env' + +export const inject = ['bashEnv'] + +export function apply(ctx: Context): void { + ctx.bashEnv.register({ + name: 'deployment-region', + variables: { DSH_DEPLOYMENT_REGION: { description: 'Current deployment region.' } }, + resolve: execution => execution.agent === undefined ? {} : { DSH_DEPLOYMENT_REGION: 'cn-north' }, + }) +} +``` + +The overlay is computed from the current `ToolExecution` and passed through the dedicated `BashExecRequest.dshEnv` channel. The local executors remove all inherited `DSH_*` before merging that snapshot, so nested harnesses and concurrent parent/child agents cannot leak stale identities. `process.env` is never modified. The shell tools' descriptions teach the generic `$DSH_*` convention rather than naming persistence-specific variables or adding a permanent system-prompt section. + +## Model Experience + +Indirectly, through the shell tools (`dsh-tool-bash`, `dsh-tool-pwsh`), which collect this registry's managed `DSH_*` snapshot into every shell-tool call. + +#### KV Cache effect + +No direct invalidation; the named consumers own any request-prefix changes. + +## Known Limitations and Deferred Work + +- **`list()` enumerates contributor-declared variables only** — registry-owned built-ins (`DSH_HOME`, `DSH_SHELL`, `DSH_SESSION_ID`) are not included, so diagnostics, prompt, or UI code must not treat `list()` as an exhaustive environment catalog. diff --git a/packages/bash/bash-env/README.zh.md b/packages/bash/bash-env/README.zh.md new file mode 100644 index 0000000000..aeb33629de --- /dev/null +++ b/packages/bash/bash-env/README.zh.md @@ -0,0 +1,51 @@ +# @deepseek-ai/dsh-bash-env + +[English](README.md) | 中文 + +工具无关的 shell 环境插件:拥有 `ctx.bashEnv` 注册表,管理受信任的、每次执行收集的 `DSH_*` 变量,供模型可见的 shell 工具(`dsh-tool-bash`、`dsh-tool-pwsh`)收集进每次 shell 调用的环境。内置 shell 事实(`DSH_HOME`、`DSH_SHELL=1`、`DSH_SESSION_ID`)归注册表自身所有;其他插件可以注册额外的可枚举事实,注册随插件纤维(fiber)释放,重复所有权或未声明的运行时键会响亮失败。 + +包根导出 Cordis 插件契约(`name`、`inject`、`Config`、`apply`)以及 `BashEnvRegistry` 服务类及其 contributor 类型;消费者在加载本插件后使用 `ctx.bashEnv`。 + +## Config + +```yaml +- id: bash-env + name: '@deepseek-ai/dsh-bash-env' + config: + dshHome: C:\Users\me\.dsh # default: $DSH_HOME, then ~/.dsh +``` + +## Managed environment + +每次前台与后台模型 shell 调用都会收到一份新收集的受信任 `DSH_*` 环境。`DSH_HOME` 是由 [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) 解析的 Harness 主目录绝对路径(`dshHome` 配置,然后环境变量 `$DSH_HOME`,然后 `~/.dsh`),`DSH_SHELL=1` 标识受管理的子进程。带 agent 的调用额外收到 `DSH_SESSION_ID=agent.session.header.id`;当活动的持久化 seam 定位到 JSONL 工件时,它们还会收到 `DSH_SESSION_JSONL=<绝对目标路径>`。JSONL 路径只是位置提示:首次 flush 之前它可能不存在,也不一定包含当前缓冲中的轮次,并且它不是授权凭据。 + +`ctx.bashEnv` 负责收集。其他插件可以注册一个受 effect 作用域约束的 contributor,带有稳定名称、已声明的键/描述以及 `resolve(execution: ToolExecution)`;重复所有权与未声明的运行时键会响亮失败,而 `list()` 只枚举声明、不执行 provider。Harness 内置键保留 `DSH_HOME`、`DSH_SHELL` 与 `DSH_SESSION_ID`;本插件的持久化翻译器通过读取与后端无关的 `sessionPersistence.locate()` seam 拥有 `DSH_SESSION_JSONL`。 + +```ts +import type { Context } from 'cordis' +import type {} from '@deepseek-ai/dsh-bash-env' + +export const inject = ['bashEnv'] + +export function apply(ctx: Context): void { + ctx.bashEnv.register({ + name: 'deployment-region', + variables: { DSH_DEPLOYMENT_REGION: { description: 'Current deployment region.' } }, + resolve: execution => execution.agent === undefined ? {} : { DSH_DEPLOYMENT_REGION: 'cn-north' }, + }) +} +``` + +覆盖层根据当前 `ToolExecution` 计算,并通过专用的 `BashExecRequest.dshEnv` 通道传递。本地执行器在合并该快照前移除所有继承的 `DSH_*`,因此嵌套 harness 与并发的父子 agent 无法泄漏过期的身份。`process.env` 永不被修改。shell 工具的描述只教授通用的 `$DSH_*` 约定,而不是点名持久化相关的变量或添加常驻的 system-prompt 段落。 + +## Model Experience + +Indirectly, through the shell tools (`dsh-tool-bash`, `dsh-tool-pwsh`), which collect this registry's managed `DSH_*` snapshot into every shell-tool call. + +#### KV Cache effect + +No direct invalidation; the named consumers own any request-prefix changes. + +## Known Limitations and Deferred Work + +- **`list()` 只枚举 contributor 声明的变量** — 注册表自有的内置键(`DSH_HOME`、`DSH_SHELL`、`DSH_SESSION_ID`)不包含在内,因此诊断、prompt 或 UI 代码不得把 `list()` 当作完整的环境目录。 diff --git a/packages/bash/bash-env/package.json b/packages/bash/bash-env/package.json new file mode 100644 index 0000000000..9ea29ad57c --- /dev/null +++ b/packages/bash/bash-env/package.json @@ -0,0 +1,50 @@ +{ + "name": "@deepseek-ai/dsh-bash-env", + "description": "Tool-independent managed DSH_* shell environment registry", + "version": "0.0.1", + "private": true, + "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", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-bash": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-paths": "^0.0.1", + "@deepseek-ai/dsh-session-persistence": "^0.0.1", + "@deepseek-ai/dsh-tools": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "dependencies": { + "schemastery": "^3.18.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-bash": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-paths": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/bash/bash-env/src/index.ts b/packages/bash/bash-env/src/index.ts new file mode 100644 index 0000000000..c7caa89f08 --- /dev/null +++ b/packages/bash/bash-env/src/index.ts @@ -0,0 +1,217 @@ +/** + * Tool-independent shell environment plugin: owns the `ctx.bashEnv` registry of + * trusted, per-execution `DSH_*` variables consumed by the model-facing shell + * tools (`dsh-tool-bash`, `dsh-tool-pwsh`). Built-in shell facts are owned by + * the registry itself while plugins can register additional, enumerable facts + * with effect-scoped disposal. + * + * @module @deepseek-ai/dsh-bash-env + */ + +import { Service, type Context } from 'cordis' +import z from 'schemastery' +import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-bash' +import type { DshEnvironment, DshEnvironmentKey } from '@deepseek-ai/dsh-bash' +import { DSH_HOME_ENV, resolveDshHome } from '@deepseek-ai/dsh-paths' +import type { ToolExecution } from '@deepseek-ai/dsh-tools' +import type {} from '@deepseek-ai/dsh-session-persistence' + +declare module 'cordis' { + interface Context { + bashEnv: BashEnvRegistry + } +} + +export const name = 'bash-env' +export const inject: string[] = [] + +/** Plugin config (all optional — the built-in facts resolve without defaults). */ +export interface Config { + /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */ + dshHome?: string +} + +/** Runtime configuration schema for the bash-env plugin. */ +export const Config: z = z.object({ + dshHome: z.string(), +}) + +/** Model-visible metadata for one managed `DSH_*` environment variable. */ +export interface BashEnvVariable { + /** Concise description of the environment fact represented by the variable. */ + description: string +} + +/** + * A plugin contribution to the managed environment of each model shell call. + * Declared keys make ownership conflicts detectable before the first command; + * `resolve` computes only the values available for the current execution. + */ +export interface BashEnvContributor { + /** Stable contributor name used in diagnostics and duplicate detection. */ + name: string + /** Complete set of `DSH_*` keys this contributor may return. */ + variables: Readonly> + /** + * Resolve this contributor's available values for one tool execution. + * @param execution - the shell tool execution and its optional calling agent. + * @returns a partial map containing only keys declared in {@link variables}. + */ + resolve(execution: ToolExecution): Readonly>> +} + +/** An enumerable declaration returned by {@link BashEnvRegistry.list}. */ +export interface BashEnvVariableInfo extends BashEnvVariable { + /** Contributor that owns the variable. */ + contributor: string + /** Declared `DSH_*` environment variable name. */ + key: DshEnvironmentKey +} + +const DSH_SHELL_KEY = `${DSH_ENV_PREFIX}SHELL` as const +const DSH_SESSION_ID_KEY = `${DSH_ENV_PREFIX}SESSION_ID` as const +const DSH_SESSION_JSONL_KEY = `${DSH_ENV_PREFIX}SESSION_JSONL` as const +const RESERVED_BASH_ENV_KEYS = new Set([ + DSH_HOME_ENV, + DSH_SHELL_KEY, + DSH_SESSION_ID_KEY, +]) +const BASH_ENV_KEY_SUFFIX = /^[A-Z][A-Z0-9_]*$/ + +/** + * Registry (`ctx.bashEnv`) for trusted, per-execution `DSH_*` variables. + * The namespace is rebuilt for every model shell call: ambient `DSH_*` values + * are discarded by the executor, then the registry's current snapshot is + * injected. Built-in shell facts remain owned by the registry itself while + * plugins can register additional, enumerable facts with effect-scoped + * disposal. + */ +export class BashEnvRegistry extends Service { + private readonly contributors = new Map() + private readonly keyOwners = new Map() + private readonly dshHome: string + + /** + * Create and install the `ctx.bashEnv` service. + * @param ctx - Cordis context that owns the service and registrations. + * @param config - home-directory configuration for the built-in variables. + */ + constructor(ctx: Context, config: Config = {}) { + super(ctx, 'bashEnv') + this.dshHome = resolveDshHome(config.dshHome) + } + + /** + * Register one environment contributor. Names and keys are unique; built-in + * keys are reserved. Registration is disposed with the calling plugin fiber. + * @param contributor - declared key ownership and per-execution resolver. + * @returns the disposer that unregisters the contribution. + */ + register(contributor: BashEnvContributor): () => void { + const dispose = this.ctx.effect(function* (this: BashEnvRegistry) { + if (contributor.name.trim().length === 0) { + throw new Error('bash env contributor name must be non-empty') + } + if (this.contributors.has(contributor.name)) { + throw new Error(`bash env contributor "${contributor.name}" is already registered`) + } + + const variables = Object.entries(contributor.variables) as [DshEnvironmentKey, BashEnvVariable][] + for (const [key, variable] of variables) { + if (!key.startsWith(DSH_ENV_PREFIX) + || !BASH_ENV_KEY_SUFFIX.test(key.slice(DSH_ENV_PREFIX.length))) { + throw new Error(`bash env contributor "${contributor.name}" declared invalid key "${key}"`) + } + if (RESERVED_BASH_ENV_KEYS.has(key)) { + throw new Error(`bash env contributor "${contributor.name}" cannot own reserved key "${key}"`) + } + if (variable.description.trim().length === 0) { + throw new Error(`bash env contributor "${contributor.name}" must describe "${key}"`) + } + const owner = this.keyOwners.get(key) + if (owner !== undefined) { + throw new Error(`bash env key "${key}" is already owned by contributor "${owner}"; contributor "${contributor.name}" cannot also own it`) + } + } + + this.contributors.set(contributor.name, contributor) + for (const [key] of variables) this.keyOwners.set(key, contributor.name) + yield () => { + this.contributors.delete(contributor.name) + for (const [key] of variables) this.keyOwners.delete(key) + } + }.bind(this), 'bashEnv.register()') + return () => void dispose() + } + + /** + * Build the trusted `DSH_*` snapshot for one shell tool execution. + * @param execution - the current tool execution. + * @returns an immutable environment overlay containing built-ins and current contributions. + */ + collect(execution: ToolExecution): DshEnvironment { + const values: Record = { + [DSH_HOME_ENV]: this.dshHome, + [DSH_SHELL_KEY]: '1', + } + if (execution.agent !== undefined) { + values[DSH_SESSION_ID_KEY] = execution.agent.session.header.id + } + + for (const contributor of [...this.contributors.values()].sort((left, right) => left.name.localeCompare(right.name))) { + const resolved = contributor.resolve(execution) + for (const [rawKey, value] of Object.entries(resolved)) { + const key = rawKey as DshEnvironmentKey + if (!Object.hasOwn(contributor.variables, key)) { + throw new Error(`bash env contributor "${contributor.name}" returned undeclared key "${key}"`) + } + if (typeof value !== 'string') { + throw new Error(`bash env contributor "${contributor.name}" returned a non-string value for "${key}"`) + } + values[key] = value + } + } + + return Object.freeze(Object.fromEntries(Object.entries(values).sort(([left], [right]) => left.localeCompare(right)))) + } + + // TODO(bash-env-list-builtins): Include registry-owned built-ins before diagnostics, + // prompt, or UI code treats list() as an exhaustive environment catalog. + /** + * Enumerate plugin-contributed variables without executing their resolvers. + * @returns declarations sorted by environment variable name. + */ + list(): BashEnvVariableInfo[] { + return [...this.contributors.values()] + .flatMap(contributor => Object.entries(contributor.variables).map(([key, variable]) => ({ + contributor: contributor.name, + description: variable.description, + key: key as DshEnvironmentKey, + }))) + .sort((left, right) => left.key.localeCompare(right.key)) + } +} + +/** + * Load the bash-env plugin: register the `ctx.bashEnv` service and the + * shell-agnostic persistence contributor (`DSH_SESSION_JSONL`). + * @param ctx - Cordis context that owns the service and registrations. + * @param config - home-directory configuration for the built-in variables. + */ +export function apply(ctx: Context, config: Config = {}): void { + const registry = new BashEnvRegistry(ctx, config) + registry.register({ + name: 'session-persistence', + variables: { + [DSH_SESSION_JSONL_KEY]: { + description: 'Absolute target path of the current session JSONL when the active persistence backend provides one.', + }, + }, + resolve(execution) { + const agent = execution.agent + if (agent === undefined) return {} + const location = ctx.get('sessionPersistence')?.locate(agent.session.header) + return location?.kind === 'jsonl' ? { [DSH_SESSION_JSONL_KEY]: location.path } : {} + }, + }) +} diff --git a/packages/bash/bash-env/src/invariant.ts b/packages/bash/bash-env/src/invariant.ts new file mode 100644 index 0000000000..31f842c56d --- /dev/null +++ b/packages/bash/bash-env/src/invariant.ts @@ -0,0 +1,30 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-bash-env`. + * @module @deepseek-ai/dsh-bash-env/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-bash-env' + +/** Cordis companion plugin name. */ +export const name = 'bash-env-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: the environment registry validates ownership and collected values at each + * registration/collection; it publishes no independent snapshot that a companion could cross-check. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/bash/bash-env/tests/bash-env.spec.ts b/packages/bash/bash-env/tests/bash-env.spec.ts new file mode 100644 index 0000000000..c93a768f80 --- /dev/null +++ b/packages/bash/bash-env/tests/bash-env.spec.ts @@ -0,0 +1,237 @@ +/** + * Registry tests for `@deepseek-ai/dsh-bash-env`: built-in facts, contributor + * ownership and validation, collection ordering, effect-scoped disposal, and + * the explicit disposer contract. + */ + +import { homedir } from 'node:os' +import { join, resolve } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from 'cordis' +import { CallId } from '@deepseek-ai/dsh-llm' +import type { Agent } from '@deepseek-ai/dsh-agent' +import type { ToolExecution } from '@deepseek-ai/dsh-tools' +import { BashEnvRegistry } from '@deepseek-ai/dsh-bash-env' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' + +const testToolSignal = new AbortController().signal + +afterEach(() => vi.unstubAllEnvs()) + +function execution(sessionId?: string): ToolExecution { + return { + signal: testToolSignal, + token: Symbol('bash-env-test') as ToolExecution['token'], + callId: CallId('bash-env-call'), + name: 'bash', + arguments: { command: 'true' }, + ...(sessionId === undefined + ? {} + : { agent: { session: { header: { version: 0, id: sessionId, createdAt: 0 } } } as Agent }), + } +} + +describe('BashEnvRegistry', () => { + it('collects unconditional shell facts and the current agent session id', () => { + const ctx = new Context() + const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) + + expect(registry.collect(execution())).toEqual({ + DSH_HOME: resolve('./test-dsh-home'), + DSH_SHELL: '1', + }) + expect(registry.collect(execution('session-a'))).toEqual({ + DSH_HOME: resolve('./test-dsh-home'), + DSH_SESSION_ID: 'session-a', + DSH_SHELL: '1', + }) + }) + + it('resolves DSH_HOME from the ambient override or the user-home default', () => { + vi.stubEnv('DSH_HOME', './ambient-dsh-home') + const fromEnvironment = new BashEnvRegistry(new Context()) + expect(fromEnvironment.collect(execution()).DSH_HOME).toBe(resolve('./ambient-dsh-home')) + + vi.stubEnv('DSH_HOME', undefined) + const fromDefault = new BashEnvRegistry(new Context()) + expect(fromDefault.collect(execution()).DSH_HOME).toBe(join(homedir(), '.dsh')) + }) + + it('collects declared contributor variables and omits unavailable values', () => { + const ctx = new Context() + const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) + registry.register({ + name: 'optional-session-fact', + variables: { + DSH_SESSION_OPTIONAL: { description: 'Optional session-scoped test fact.' }, + }, + resolve: exec => exec.agent === undefined ? {} : { DSH_SESSION_OPTIONAL: exec.agent.session.header.id }, + }) + registry.register({ + name: 'always-available-fact', + variables: { + DSH_ALWAYS_AVAILABLE: { description: 'Always-available test fact.' }, + }, + resolve: () => ({ DSH_ALWAYS_AVAILABLE: 'yes' }), + }) + + expect(registry.collect(execution())).not.toHaveProperty('DSH_SESSION_OPTIONAL') + expect(registry.collect(execution()).DSH_ALWAYS_AVAILABLE).toBe('yes') + expect(registry.collect(execution('session-b')).DSH_SESSION_OPTIONAL).toBe('session-b') + expect(registry.list()).toEqual([ + { + contributor: 'always-available-fact', + description: 'Always-available test fact.', + key: 'DSH_ALWAYS_AVAILABLE', + }, + { + contributor: 'optional-session-fact', + description: 'Optional session-scoped test fact.', + key: 'DSH_SESSION_OPTIONAL', + }, + ]) + }) + + it('rejects duplicate variable ownership at registration time', () => { + const ctx = new Context() + const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) + registry.register({ + name: 'first', + variables: { DSH_SHARED: { description: 'First owner.' } }, + resolve: () => ({ DSH_SHARED: 'first' }), + }) + + expect(() => registry.register({ + name: 'second', + variables: { DSH_SHARED: { description: 'Second owner.' } }, + resolve: () => ({ DSH_SHARED: 'second' }), + })).toThrow(/DSH_SHARED.*first.*second|DSH_SHARED.*second.*first/) + }) + + it('rejects duplicate contributor names and malformed declarations', () => { + const registry = new BashEnvRegistry(new Context(), { dshHome: './test-dsh-home' }) + registry.register({ + name: 'declared', + variables: { DSH_DECLARED: { description: 'Declared fact.' } }, + resolve: () => ({}), + }) + + expect(() => registry.register({ + name: 'declared', + variables: { DSH_ANOTHER: { description: 'Another fact.' } }, + resolve: () => ({}), + })).toThrow(/already registered/) + expect(() => registry.register({ + name: ' ', + variables: { DSH_BLANK_NAME: { description: 'Blank owner.' } }, + resolve: () => ({}), + })).toThrow(/name must be non-empty/) + expect(() => registry.register({ + name: 'invalid-key', + variables: { dsh_invalid: { description: 'Invalid key.' } } as unknown as Record<'DSH_INVALID', { description: string }>, + resolve: () => ({}), + })).toThrow(/invalid key/) + expect(() => registry.register({ + name: 'reserved-key', + variables: { DSH_HOME: { description: 'Reserved key.' } }, + resolve: () => ({}), + })).toThrow(/reserved key/) + expect(() => registry.register({ + name: 'blank-description', + variables: { DSH_BLANK_DESCRIPTION: { description: ' ' } }, + resolve: () => ({}), + })).toThrow(/must describe/) + }) + + it('rejects undeclared variables returned by a contributor', () => { + const ctx = new Context() + const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) + registry.register({ + name: 'drifted-provider', + variables: { DSH_DECLARED: { description: 'Declared fact.' } }, + resolve: () => ({ DSH_UNDECLARED: 'bad' }), + }) + + expect(() => registry.collect(execution())).toThrow(/drifted-provider.*DSH_UNDECLARED/) + }) + + it('rejects non-string values returned by a contributor', () => { + const registry = new BashEnvRegistry(new Context(), { dshHome: './test-dsh-home' }) + registry.register({ + name: 'wrong-value-type', + variables: { DSH_STRING: { description: 'String fact.' } }, + resolve: () => ({ DSH_STRING: 42 }) as unknown as Record<'DSH_STRING', string>, + }) + + expect(() => registry.collect(execution())).toThrow(/wrong-value-type.*non-string.*DSH_STRING/) + }) + + it('removes an effect-scoped contributor when its plugin is disposed', async () => { + const ctx = new Context() + const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) + const fiber = await ctx.plugin({ + inject: ['bashEnv'], + apply(inner: Context) { + inner.bashEnv.register({ + name: 'temporary', + variables: { DSH_TEMPORARY: { description: 'Temporary fact.' } }, + resolve: () => ({ DSH_TEMPORARY: 'present' }), + }) + }, + }) + + expect(registry.collect(execution()).DSH_TEMPORARY).toBe('present') + await fiber.dispose() + expect(registry.collect(execution())).not.toHaveProperty('DSH_TEMPORARY') + }) + + it('returns an explicit contributor disposer', () => { + const registry = new BashEnvRegistry(new Context(), { dshHome: './test-dsh-home' }) + const dispose = registry.register({ + name: 'explicit-disposal', + variables: { DSH_EXPLICIT_DISPOSAL: { description: 'Explicitly disposed fact.' } }, + resolve: () => ({ DSH_EXPLICIT_DISPOSAL: 'present' }), + }) + + expect(registry.collect(execution()).DSH_EXPLICIT_DISPOSAL).toBe('present') + dispose() + expect(registry.collect(execution())).not.toHaveProperty('DSH_EXPLICIT_DISPOSAL') + }) + + it('the plugin registers the service and the persistence contributor on load', async () => { + const ctx = new Context() + await ctx.plugin(BashEnvPlugin) + expect(ctx.bashEnv).toBeInstanceOf(BashEnvRegistry) + expect(ctx.bashEnv.list()).toEqual([ + { + contributor: 'session-persistence', + description: 'Absolute target path of the current session JSONL when the active persistence backend provides one.', + key: 'DSH_SESSION_JSONL', + }, + ]) + }) + + it('the persistence contributor resolves DSH_SESSION_JSONL only for a jsonl backend', async () => { + const ctx = new Context() + await ctx.plugin(BashEnvPlugin) + ctx.provide('sessionPersistence', { + locate: () => ({ kind: 'jsonl' as const, path: 'C:\\sessions\\s.jsonl' }), + }) + expect(ctx.bashEnv.collect(execution('sess-p')).DSH_SESSION_JSONL).toBe('C:\\sessions\\s.jsonl') + }) + + it('the persistence contributor omits the variable for a non-jsonl backend', async () => { + const ctx = new Context() + await ctx.plugin(BashEnvPlugin) + ctx.provide('sessionPersistence', { + locate: () => ({ kind: 'sqlite' as const, path: 'C:\\sessions\\s.db' }), + }) + expect(ctx.bashEnv.collect(execution('sess-p'))).not.toHaveProperty('DSH_SESSION_JSONL') + }) + + it('the persistence contributor omits the variable without a persistence backend', async () => { + const ctx = new Context() + await ctx.plugin(BashEnvPlugin) + expect(ctx.bashEnv.collect(execution('sess-p'))).not.toHaveProperty('DSH_SESSION_JSONL') + }) +}) diff --git a/packages/bash/bash-env/tsconfig.json b/packages/bash/bash-env/tsconfig.json new file mode 100644 index 0000000000..bcf5eb5229 --- /dev/null +++ b/packages/bash/bash-env/tsconfig.json @@ -0,0 +1,36 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../bash/bash" + }, + { + "path": "../../util/paths" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../session-persistence/session-persistence" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 2beb8a3c77..e7dc0187ea 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -184,7 +184,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'collect(execution: ToolExecution): DshEnvironment', - jsDoc: '/**\n * Build the trusted `DSH_*` snapshot for one bash tool execution.\n * @param execution - the current tool execution.\n * @returns an immutable environment overlay containing built-ins and current contributions.\n */', + jsDoc: '/**\n * Build the trusted `DSH_*` snapshot for one shell tool execution.\n * @param execution - the current tool execution.\n * @returns an immutable environment overlay containing built-ins and current contributions.\n */', }, { signature: 'list(): BashEnvVariableInfo[]', diff --git a/python/sdk-runtime/package.json b/python/sdk-runtime/package.json index 5af9f4fc8c..65c79bda58 100644 --- a/python/sdk-runtime/package.json +++ b/python/sdk-runtime/package.json @@ -14,6 +14,7 @@ "@deepseek-ai/dsh-agent-spine-demo": "workspace:^", "@deepseek-ai/dsh-app-boot": "workspace:^", "@deepseek-ai/dsh-bash": "workspace:^", + "@deepseek-ai/dsh-bash-env": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", "@deepseek-ai/dsh-brand": "workspace:^", "@deepseek-ai/dsh-code-runtime": "workspace:^", diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index ed723c26f5..041972cb9f 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -42,6 +42,7 @@ const NO_MODEL_EXPERIENCE_SECTION: Readonly> = { */ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/bash/bash': { kind: 'indirect', reason: 'The service interface delegates all model rendering to dsh-tool-bash.' }, + 'packages/bash/bash-env': { kind: 'indirect', reason: 'The env service surfaces managed DSH_* facts through the shell tools (dsh-tool-bash/dsh-tool-pwsh); it registers no prompt or schema of its own.' }, 'packages/bash/bash-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-bash.' }, 'packages/bash/pwsh-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-pwsh.' }, 'packages/code-runtime/code-runtime': { kind: 'indirect', reason: 'The service interface delegates model rendering to Code Mode in dsh-tools.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 44fc039f8a..a21de0d323 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -55,6 +55,7 @@ "@deepseek-ai/dsh-plan-mode/client": ["./packages/plan/plan-mode/src/client.ts"], "@deepseek-ai/dsh-pwsh-local": ["./packages/bash/pwsh-local/src/index.ts"], "@deepseek-ai/dsh-tool-pwsh": ["./packages/bash/tool-pwsh/src/index.ts"], + "@deepseek-ai/dsh-bash-env": ["./packages/bash/bash-env/src/index.ts"], "@deepseek-ai/dsh-goal/types": ["./packages/goal/goal/src/types.ts"], "@deepseek-ai/dsh-goal/client": ["./packages/goal/goal/src/client.ts"], "@deepseek-ai/dsh-llm/types": ["./packages/llm/llm/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index da821faa10..70869ede22 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -138,6 +138,7 @@ { "path": "./packages/llm/llm-deepseek" }, { "path": "./packages/llm/llm-pi-ai" }, { "path": "./packages/bash/bash-local" }, + { "path": "./packages/bash/bash-env" }, { "path": "./packages/bash/pwsh-local" }, { "path": "./packages/bash/tool-pwsh" }, { "path": "./packages/sandbox/sandbox" }, diff --git a/vitest.config.ts b/vitest.config.ts index 0fa2a6dd53..14d5be103f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -14,10 +14,11 @@ const windowsUnsupportedPackages = process.platform === 'win32' // Bash-requiring suites (a real POSIX shell is unavailable on Windows). // The pwsh-requiring suites (pwsh-local, tool-pwsh) deliberately stay // INCLUDED: PowerShell ships with Windows, so they run natively here. + // Replacing the old 'packages/bash/*' glob with this explicit list also + // newly INCLUDES packages/bash/bash (the pure seam package) on Windows. 'packages/bash/bash-local', 'packages/bash/bash-sandbox', 'packages/bash/tool-bash', - 'packages/bash/tool-bash-persistent', 'packages/hooks/*', 'packages/subprocess/*', 'packages/pty/pty-local', From 87db82e8219213256f104d39bbc90a43d0c74557 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 14:18:01 +0800 Subject: [PATCH 06/61] refactor(tool-bash): consume ctx.bashEnv from the shared bash-env package --- packages/bash/tool-bash/package.json | 6 +- packages/bash/tool-bash/src/index.ts | 196 +----------------- .../bash/tool-bash/tests/bash-env.spec.ts | 193 ----------------- .../bash/tool-bash/tests/integration.spec.ts | 4 +- packages/bash/tool-bash/tests/tools.spec.ts | 10 +- packages/bash/tool-bash/tsconfig.json | 9 +- 6 files changed, 23 insertions(+), 395 deletions(-) delete mode 100644 packages/bash/tool-bash/tests/bash-env.spec.ts diff --git a/packages/bash/tool-bash/package.json b/packages/bash/tool-bash/package.json index c34e1c6e7b..c9734b46eb 100644 --- a/packages/bash/tool-bash/package.json +++ b/packages/bash/tool-bash/package.json @@ -29,12 +29,11 @@ "peerDependencies": { "@deepseek-ai/dsh-agent": "^0.0.1", "@deepseek-ai/dsh-bash": "^0.0.1", + "@deepseek-ai/dsh-bash-env": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "@deepseek-ai/dsh-llm": "^0.0.1", - "@deepseek-ai/dsh-paths": "^0.0.1", "@deepseek-ai/dsh-sandbox": "^0.0.1", "@deepseek-ai/dsh-sandbox-policy": "^0.0.1", - "@deepseek-ai/dsh-session-persistence": "^0.0.1", "@deepseek-ai/dsh-system-prompt": "^0.0.1", "@deepseek-ai/dsh-tasks": "^0.0.1", "@deepseek-ai/dsh-tools": "^0.0.1", @@ -49,15 +48,14 @@ "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-bash": "workspace:^", + "@deepseek-ai/dsh-bash-env": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-subprocess-local": "workspace:^", - "@deepseek-ai/dsh-paths": "workspace:^", "@deepseek-ai/dsh-sandbox": "workspace:^", "@deepseek-ai/dsh-sandbox-policy": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", - "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tasks": "workspace:^", diff --git a/packages/bash/tool-bash/src/index.ts b/packages/bash/tool-bash/src/index.ts index 3b3874bc59..c2a5c3e288 100644 --- a/packages/bash/tool-bash/src/index.ts +++ b/packages/bash/tool-bash/src/index.ts @@ -8,205 +8,39 @@ * @module @deepseek-ai/dsh-tool-bash */ -import { Service, type Context } from 'cordis' +import type { Context } from 'cordis' import z from 'schemastery' import { isAbsolute, resolve as resolvePath } from 'node:path' import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools' import type { GenericCallView, TerminalCallView, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools' import { HarnessError } from '@deepseek-ai/dsh-llm' import type { Agent } from '@deepseek-ai/dsh-agent' -import type {} from '@deepseek-ai/dsh-session-persistence' import type {} from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-tasks' import type {} from '@deepseek-ai/dsh-user-approval' +import type {} from '@deepseek-ai/dsh-bash-env' import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' import { ESCALATION_TARGETS, approveEscalation, canonicalPath, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy' import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-bash' -import type { BashRunResult, DshEnvironment, DshEnvironmentKey } from '@deepseek-ai/dsh-bash' -import { DSH_HOME_ENV, resolveDshHome } from '@deepseek-ai/dsh-paths' +import type { BashRunResult } from '@deepseek-ai/dsh-bash' import { processOutcome } from './background.ts' import { parseExitStatus, renderProcessRead, renderResult } from './render.ts' -declare module 'cordis' { - interface Context { - bashEnv: BashEnvRegistry - } -} - export const name = 'tool-bash' -export const inject = ['tools', 'bash', 'systemPrompt'] +export const inject = ['tools', 'bash', 'systemPrompt', 'bashEnv'] -/** Configuration for the bash tool and its managed child environment. */ +/** Configuration for the bash tool. */ export interface Config { /** Expose `run_in_background` (default true); disabled calls are also rejected. */ enableRunInBackground?: boolean - /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */ - dshHome?: string } /** Runtime configuration schema for the bash tool plugin. */ export const Config: z = z.object({ enableRunInBackground: z.boolean().default(true), - dshHome: z.string(), }) -/** Model-visible metadata for one managed `DSH_*` environment variable. */ -export interface BashEnvVariable { - /** Concise description of the environment fact represented by the variable. */ - description: string -} - -/** - * A plugin contribution to the managed environment of each model bash call. - * Declared keys make ownership conflicts detectable before the first command; - * `resolve` computes only the values available for the current execution. - */ -export interface BashEnvContributor { - /** Stable contributor name used in diagnostics and duplicate detection. */ - name: string - /** Complete set of `DSH_*` keys this contributor may return. */ - variables: Readonly> - /** - * Resolve this contributor's available values for one tool execution. - * @param execution - the bash tool execution and its optional calling agent. - * @returns a partial map containing only keys declared in {@link variables}. - */ - resolve(execution: ToolExecution): Readonly>> -} - -/** An enumerable declaration returned by {@link BashEnvRegistry.list}. */ -export interface BashEnvVariableInfo extends BashEnvVariable { - /** Contributor that owns the variable. */ - contributor: string - /** Declared `DSH_*` environment variable name. */ - key: DshEnvironmentKey -} - -const DSH_SHELL_KEY = `${DSH_ENV_PREFIX}SHELL` as const -const DSH_SESSION_ID_KEY = `${DSH_ENV_PREFIX}SESSION_ID` as const -const DSH_SESSION_JSONL_KEY = `${DSH_ENV_PREFIX}SESSION_JSONL` as const -const RESERVED_BASH_ENV_KEYS = new Set([ - DSH_HOME_ENV, - DSH_SHELL_KEY, - DSH_SESSION_ID_KEY, -]) -const BASH_ENV_KEY_SUFFIX = /^[A-Z][A-Z0-9_]*$/ - -/** - * Registry (`ctx.bashEnv`) for trusted, per-execution `DSH_*` variables. - * The namespace is rebuilt for every model bash call: ambient `DSH_*` values - * are discarded by the executor, then the registry's current snapshot is - * injected. Built-in shell facts remain owned by the registry itself while - * plugins can register additional, enumerable facts with effect-scoped - * disposal. - */ -export class BashEnvRegistry extends Service { - private readonly contributors = new Map() - private readonly keyOwners = new Map() - private readonly dshHome: string - - /** - * Create and install the `ctx.bashEnv` service. - * @param ctx - Cordis context that owns the service and registrations. - * @param config - home-directory configuration for the built-in variables. - */ - constructor(ctx: Context, config: Config = {}) { - super(ctx, 'bashEnv') - this.dshHome = resolveDshHome(config.dshHome) - } - - /** - * Register one environment contributor. Names and keys are unique; built-in - * keys are reserved. Registration is disposed with the calling plugin fiber. - * @param contributor - declared key ownership and per-execution resolver. - * @returns the disposer that unregisters the contribution. - */ - register(contributor: BashEnvContributor): () => void { - const dispose = this.ctx.effect(function* (this: BashEnvRegistry) { - if (contributor.name.trim().length === 0) { - throw new Error('bash env contributor name must be non-empty') - } - if (this.contributors.has(contributor.name)) { - throw new Error(`bash env contributor "${contributor.name}" is already registered`) - } - - const variables = Object.entries(contributor.variables) as [DshEnvironmentKey, BashEnvVariable][] - for (const [key, variable] of variables) { - if (!key.startsWith(DSH_ENV_PREFIX) - || !BASH_ENV_KEY_SUFFIX.test(key.slice(DSH_ENV_PREFIX.length))) { - throw new Error(`bash env contributor "${contributor.name}" declared invalid key "${key}"`) - } - if (RESERVED_BASH_ENV_KEYS.has(key)) { - throw new Error(`bash env contributor "${contributor.name}" cannot own reserved key "${key}"`) - } - if (variable.description.trim().length === 0) { - throw new Error(`bash env contributor "${contributor.name}" must describe "${key}"`) - } - const owner = this.keyOwners.get(key) - if (owner !== undefined) { - throw new Error(`bash env key "${key}" is already owned by contributor "${owner}"; contributor "${contributor.name}" cannot also own it`) - } - } - - this.contributors.set(contributor.name, contributor) - for (const [key] of variables) this.keyOwners.set(key, contributor.name) - yield () => { - this.contributors.delete(contributor.name) - for (const [key] of variables) this.keyOwners.delete(key) - } - }.bind(this), 'bashEnv.register()') - return () => void dispose() - } - - /** - * Build the trusted `DSH_*` snapshot for one bash tool execution. - * @param execution - the current tool execution. - * @returns an immutable environment overlay containing built-ins and current contributions. - */ - collect(execution: ToolExecution): DshEnvironment { - const values: Record = { - [DSH_HOME_ENV]: this.dshHome, - [DSH_SHELL_KEY]: '1', - } - if (execution.agent !== undefined) { - values[DSH_SESSION_ID_KEY] = execution.agent.session.header.id - } - - for (const contributor of [...this.contributors.values()].sort((left, right) => left.name.localeCompare(right.name))) { - const resolved = contributor.resolve(execution) - for (const [rawKey, value] of Object.entries(resolved)) { - const key = rawKey as DshEnvironmentKey - if (!Object.hasOwn(contributor.variables, key)) { - throw new Error(`bash env contributor "${contributor.name}" returned undeclared key "${key}"`) - } - if (typeof value !== 'string') { - throw new Error(`bash env contributor "${contributor.name}" returned a non-string value for "${key}"`) - } - values[key] = value - } - } - - return Object.freeze(Object.fromEntries(Object.entries(values).sort(([left], [right]) => left.localeCompare(right)))) - } - - // TODO(bash-env-list-builtins): Include registry-owned built-ins before diagnostics, - // prompt, or UI code treats list() as an exhaustive environment catalog. - /** - * Enumerate plugin-contributed variables without executing their resolvers. - * @returns declarations sorted by environment variable name. - */ - list(): BashEnvVariableInfo[] { - return [...this.contributors.values()] - .flatMap(contributor => Object.entries(contributor.variables).map(([key, variable]) => ({ - contributor: contributor.name, - description: variable.description, - key: key as DshEnvironmentKey, - }))) - .sort((left, right) => left.key.localeCompare(right.key)) - } -} - /** Parsed tool args; execute validates value constraints absent from ParameterSchemaSpec. */ interface BashToolArgs { command: string @@ -354,24 +188,6 @@ const BACKGROUND_OUTPUT_PROPERTIES = { } as const export function apply(ctx: Context, config: Config = {}): void { - // FIXME(bash-env-ownership): Move ctx.bashEnv to a tool-independent shell - // environment plugin; replacing this tool with persistent Bash must not - // remove the managed DSH_* contributor seam. - const bashEnv = new BashEnvRegistry(ctx, config) - bashEnv.register({ - name: 'session-persistence', - variables: { - [DSH_SESSION_JSONL_KEY]: { - description: 'Absolute target path of the current session JSONL when the active persistence backend provides one.', - }, - }, - resolve(execution) { - const agent = execution.agent - if (agent === undefined) return {} - const location = ctx.get('sessionPersistence')?.locate(agent.session.header) - return location?.kind === 'jsonl' ? { [DSH_SESSION_JSONL_KEY]: location.path } : {} - }, - }) const backgroundEnabled = config.enableRunInBackground ?? true const defaultMode = ctx.bash.sandboxMode const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS @@ -522,7 +338,7 @@ export function apply(ctx: Context, config: Config = {}): void { ? standingPolicy : { ...(standingPolicy as SandboxExecutionPolicy), mode: approvedMode } const workdir = resolveWorkdir(args.workdir, exec, standingPolicy?.workspaceRoot) - const dshEnv = bashEnv.collect(exec) + const dshEnv = ctx.bashEnv.collect(exec) const request = { command: args.command, ...workdir !== undefined ? { workdir } : {}, diff --git a/packages/bash/tool-bash/tests/bash-env.spec.ts b/packages/bash/tool-bash/tests/bash-env.spec.ts deleted file mode 100644 index d988075c5b..0000000000 --- a/packages/bash/tool-bash/tests/bash-env.spec.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { homedir } from 'node:os' -import { join, resolve } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { Context } from 'cordis' -import { CallId } from '@deepseek-ai/dsh-llm' -import type { Agent } from '@deepseek-ai/dsh-agent' -import type { ToolExecution } from '@deepseek-ai/dsh-tools' -import { BashEnvRegistry } from '@deepseek-ai/dsh-tool-bash' - -const testToolSignal = new AbortController().signal - -afterEach(() => vi.unstubAllEnvs()) - -function execution(sessionId?: string): ToolExecution { - return { - signal: testToolSignal, - token: Symbol('bash-env-test') as ToolExecution['token'], - callId: CallId('bash-env-call'), - name: 'bash', - arguments: { command: 'true' }, - ...(sessionId === undefined - ? {} - : { agent: { session: { header: { version: 0, id: sessionId, createdAt: 0 } } } as Agent }), - } -} - -describe('BashEnvRegistry', () => { - it('collects unconditional shell facts and the current agent session id', () => { - const ctx = new Context() - const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) - - expect(registry.collect(execution())).toEqual({ - DSH_HOME: resolve('./test-dsh-home'), - DSH_SHELL: '1', - }) - expect(registry.collect(execution('session-a'))).toEqual({ - DSH_HOME: resolve('./test-dsh-home'), - DSH_SESSION_ID: 'session-a', - DSH_SHELL: '1', - }) - }) - - it('resolves DSH_HOME from the ambient override or the user-home default', () => { - vi.stubEnv('DSH_HOME', './ambient-dsh-home') - const fromEnvironment = new BashEnvRegistry(new Context()) - expect(fromEnvironment.collect(execution()).DSH_HOME).toBe(resolve('./ambient-dsh-home')) - - vi.stubEnv('DSH_HOME', undefined) - const fromDefault = new BashEnvRegistry(new Context()) - expect(fromDefault.collect(execution()).DSH_HOME).toBe(join(homedir(), '.dsh')) - }) - - it('collects declared contributor variables and omits unavailable values', () => { - const ctx = new Context() - const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) - registry.register({ - name: 'optional-session-fact', - variables: { - DSH_SESSION_OPTIONAL: { description: 'Optional session-scoped test fact.' }, - }, - resolve: exec => exec.agent === undefined ? {} : { DSH_SESSION_OPTIONAL: exec.agent.session.header.id }, - }) - registry.register({ - name: 'always-available-fact', - variables: { - DSH_ALWAYS_AVAILABLE: { description: 'Always-available test fact.' }, - }, - resolve: () => ({ DSH_ALWAYS_AVAILABLE: 'yes' }), - }) - - expect(registry.collect(execution())).not.toHaveProperty('DSH_SESSION_OPTIONAL') - expect(registry.collect(execution()).DSH_ALWAYS_AVAILABLE).toBe('yes') - expect(registry.collect(execution('session-b')).DSH_SESSION_OPTIONAL).toBe('session-b') - expect(registry.list()).toEqual([ - { - contributor: 'always-available-fact', - description: 'Always-available test fact.', - key: 'DSH_ALWAYS_AVAILABLE', - }, - { - contributor: 'optional-session-fact', - description: 'Optional session-scoped test fact.', - key: 'DSH_SESSION_OPTIONAL', - }, - ]) - }) - - it('rejects duplicate variable ownership at registration time', () => { - const ctx = new Context() - const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) - registry.register({ - name: 'first', - variables: { DSH_SHARED: { description: 'First owner.' } }, - resolve: () => ({ DSH_SHARED: 'first' }), - }) - - expect(() => registry.register({ - name: 'second', - variables: { DSH_SHARED: { description: 'Second owner.' } }, - resolve: () => ({ DSH_SHARED: 'second' }), - })).toThrow(/DSH_SHARED.*first.*second|DSH_SHARED.*second.*first/) - }) - - it('rejects duplicate contributor names and malformed declarations', () => { - const registry = new BashEnvRegistry(new Context(), { dshHome: './test-dsh-home' }) - registry.register({ - name: 'declared', - variables: { DSH_DECLARED: { description: 'Declared fact.' } }, - resolve: () => ({}), - }) - - expect(() => registry.register({ - name: 'declared', - variables: { DSH_ANOTHER: { description: 'Another fact.' } }, - resolve: () => ({}), - })).toThrow(/already registered/) - expect(() => registry.register({ - name: ' ', - variables: { DSH_BLANK_NAME: { description: 'Blank owner.' } }, - resolve: () => ({}), - })).toThrow(/name must be non-empty/) - expect(() => registry.register({ - name: 'invalid-key', - variables: { dsh_invalid: { description: 'Invalid key.' } } as unknown as Record<'DSH_INVALID', { description: string }>, - resolve: () => ({}), - })).toThrow(/invalid key/) - expect(() => registry.register({ - name: 'reserved-key', - variables: { DSH_HOME: { description: 'Reserved key.' } }, - resolve: () => ({}), - })).toThrow(/reserved key/) - expect(() => registry.register({ - name: 'blank-description', - variables: { DSH_BLANK_DESCRIPTION: { description: ' ' } }, - resolve: () => ({}), - })).toThrow(/must describe/) - }) - - it('rejects undeclared variables returned by a contributor', () => { - const ctx = new Context() - const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) - registry.register({ - name: 'drifted-provider', - variables: { DSH_DECLARED: { description: 'Declared fact.' } }, - resolve: () => ({ DSH_UNDECLARED: 'bad' }), - }) - - expect(() => registry.collect(execution())).toThrow(/drifted-provider.*DSH_UNDECLARED/) - }) - - it('rejects non-string values returned by a contributor', () => { - const registry = new BashEnvRegistry(new Context(), { dshHome: './test-dsh-home' }) - registry.register({ - name: 'wrong-value-type', - variables: { DSH_STRING: { description: 'String fact.' } }, - resolve: () => ({ DSH_STRING: 42 }) as unknown as Record<'DSH_STRING', string>, - }) - - expect(() => registry.collect(execution())).toThrow(/wrong-value-type.*non-string.*DSH_STRING/) - }) - - it('removes an effect-scoped contributor when its plugin is disposed', async () => { - const ctx = new Context() - const registry = new BashEnvRegistry(ctx, { dshHome: './test-dsh-home' }) - const fiber = await ctx.plugin({ - inject: ['bashEnv'], - apply(inner: Context) { - inner.bashEnv.register({ - name: 'temporary', - variables: { DSH_TEMPORARY: { description: 'Temporary fact.' } }, - resolve: () => ({ DSH_TEMPORARY: 'present' }), - }) - }, - }) - - expect(registry.collect(execution()).DSH_TEMPORARY).toBe('present') - await fiber.dispose() - expect(registry.collect(execution())).not.toHaveProperty('DSH_TEMPORARY') - }) - - it('returns an explicit contributor disposer', () => { - const registry = new BashEnvRegistry(new Context(), { dshHome: './test-dsh-home' }) - const dispose = registry.register({ - name: 'explicit-disposal', - variables: { DSH_EXPLICIT_DISPOSAL: { description: 'Explicitly disposed fact.' } }, - resolve: () => ({ DSH_EXPLICIT_DISPOSAL: 'present' }), - }) - - expect(registry.collect(execution()).DSH_EXPLICIT_DISPOSAL).toBe('present') - dispose() - expect(registry.collect(execution())).not.toHaveProperty('DSH_EXPLICIT_DISPOSAL') - }) -}) diff --git a/packages/bash/tool-bash/tests/integration.spec.ts b/packages/bash/tool-bash/tests/integration.spec.ts index 5616afcdef..b76f24bc04 100644 --- a/packages/bash/tool-bash/tests/integration.spec.ts +++ b/packages/bash/tool-bash/tests/integration.spec.ts @@ -14,6 +14,7 @@ import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' /** @@ -32,8 +33,9 @@ async function harness(adapter: MockAdapter, sessionRoot?: string, dshHome?: str await ctx.plugin(LocalTaskService) await ctx.plugin(ToolTasks) await ctx.plugin(LocalSubprocessService) + await ctx.plugin(BashEnvPlugin, dshHome === undefined ? {} : { dshHome }) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) - await ctx.plugin(ToolBash, dshHome === undefined ? {} : { dshHome }) + await ctx.plugin(ToolBash) ctx.llm.registerAdapter(['mock'], adapter) return ctx } diff --git a/packages/bash/tool-bash/tests/tools.spec.ts b/packages/bash/tool-bash/tests/tools.spec.ts index a52b3f16f1..22fe3bc4b6 100644 --- a/packages/bash/tool-bash/tests/tools.spec.ts +++ b/packages/bash/tool-bash/tests/tools.spec.ts @@ -20,6 +20,7 @@ import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' import { processOutcome } from '../src/background.ts' import { renderProcessRead, renderResult } from '../src/render.ts' @@ -281,6 +282,7 @@ describe('bash tool', () => { await ctx.plugin(LocalSubprocessService) ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir } await ctx.plugin(LocalBashExecutor, { maxOutputBytes: 100, graceMs: 200 }) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(ToolBash) const result = await call(ctx, 'bash', { command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done', description: 'test command' }) expect(text(result)).toContain('[output truncated; full output: ') @@ -403,6 +405,7 @@ describe('bash tool', () => { await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRegistry) // inject: ['tools', 'bash'] keeps the plugin pending until bash exists. + await ctx.plugin(BashEnvPlugin) await ctx.plugin(ToolBash) expect(ctx.tools.schemas()).toHaveLength(0) await ctx.plugin(LocalSubprocessService) @@ -493,6 +496,7 @@ describe('background execution through the task runtime', () => { await ctx.plugin(LocalTaskService) await ctx.plugin(ToolTasks) await ctx.plugin(CountingStartExecutor) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(ToolBash) const controller = new AbortController() @@ -520,6 +524,7 @@ describe('background execution through the task runtime', () => { await ctx.plugin(AgentRegistry) await ctx.plugin(LocalTaskService) await ctx.plugin(CountingStartExecutor) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(ToolBash) const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true }) @@ -534,6 +539,7 @@ describe('background execution through the task runtime', () => { await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRegistry) await ctx.plugin(LocalSubprocessService) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(LocalBashExecutor, {}) await ctx.plugin(ToolBash, { enableRunInBackground: false }) @@ -568,6 +574,7 @@ describe('sandbox escalation through the generic task producer', () => { await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRegistry) await ctx.plugin(RecordingSandboxExecutor) + await ctx.plugin(BashEnvPlugin) await expect(ctx.plugin(ToolBash)).rejects.toThrow('tool-bash: the mounted bash executor confines but ctx.sandboxPolicy is missing') }) @@ -1097,8 +1104,9 @@ describe('the model-facing bash tool builds its request from named args only (no } await ctx.plugin(LocalTaskService) await ctx.plugin(ToolTasks) + await ctx.plugin(BashEnvPlugin, { dshHome: recordingDshHome }) await ctx.plugin(RecordingBashExecutor) - await ctx.plugin(ToolBash, { dshHome: recordingDshHome }) + await ctx.plugin(ToolBash) return { ctx, bash: ctx.bash as RecordingBashExecutor } } diff --git a/packages/bash/tool-bash/tsconfig.json b/packages/bash/tool-bash/tsconfig.json index 00e9195f9f..b122ed58ca 100644 --- a/packages/bash/tool-bash/tsconfig.json +++ b/packages/bash/tool-bash/tsconfig.json @@ -26,21 +26,18 @@ { "path": "../../core/agent" }, - { - "path": "../../session-persistence/session-persistence" - }, { "path": "../../bash/bash" }, - { - "path": "../../util/paths" - }, { "path": "../../tasks/tasks" }, { "path": "../../core/system-prompt" }, + { + "path": "../../bash/bash-env" + }, { "path": "../../ui/user-approval" }, From af9af8ca05093f99ad48446ab245b25b92870c18 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 14:18:15 +0800 Subject: [PATCH 07/61] fix(pwsh-local): pin UTF-8 I/O so the Windows PowerShell 5.1 fallback cannot garble output --- packages/bash/pwsh-local/src/index.ts | 18 +++++++- .../bash/pwsh-local/tests/executor.spec.ts | 44 ++++++++++++++++++- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/packages/bash/pwsh-local/src/index.ts b/packages/bash/pwsh-local/src/index.ts index 8548731a28..b93bbb8d89 100644 --- a/packages/bash/pwsh-local/src/index.ts +++ b/packages/bash/pwsh-local/src/index.ts @@ -34,6 +34,17 @@ export const ENV_OVERRIDES = { GIT_PAGER: 'cat', } as const +/** + * UTF-8 I/O pinning prepended to every command. The subprocess collector + * decodes output bytes as UTF-8, but Windows PowerShell 5.1 (the last-resort + * executable fallback) writes the console/OEM code page by default, which + * garbles non-ASCII output; pwsh 7 defaults to UTF-8 and is unaffected. The + * statements ride on line 1 after `; ` separators so PowerShell error line + * numbers stay accurate. + */ +export const ENCODING_PREAMBLE = + '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); $OutputEncoding = [System.Text.UTF8Encoding]::new($false); ' + /** Default SIGTERM→SIGKILL grace period (the `graceMs` config). */ const DEFAULT_GRACE_MS = 3_000 @@ -197,7 +208,7 @@ export class PwshLocalExecutor extends BashExecutor { const collect = (maxBytes: number): SubprocessCollect => ({ maxBytes, spill: { maxBytes: this.config.maxSpillBytes } }) return { - argv: [this.pwshPath, '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', spec.command], + argv: [this.pwshPath, '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', `${ENCODING_PREAMBLE}${spec.command}`], cwd: spec.workdir, stdio: { stdin: spec.stdin !== undefined ? { data: spec.stdin } : 'ignore', @@ -307,7 +318,10 @@ export class PwshLocalExecutor extends BashExecutor { /** * Settlement hook for subclasses that attach execution facts to a process. - * The base implementation is intentionally empty. + * The base implementation is intentionally empty. Mirrored from + * `dsh-bash-local` (whose sandboxing subclass consumes the same hook); it is + * the declared seam for a future pwsh-confining subclass and has no consumer + * in this package yet. * @param _proc - the settled process handle. * @param _stderr - the process's retained stderr tail used by subclasses for settlement classification. */ diff --git a/packages/bash/pwsh-local/tests/executor.spec.ts b/packages/bash/pwsh-local/tests/executor.spec.ts index 1794666911..5113f6a988 100644 --- a/packages/bash/pwsh-local/tests/executor.spec.ts +++ b/packages/bash/pwsh-local/tests/executor.spec.ts @@ -15,13 +15,17 @@ import { join } from 'node:path' import { spawnSync } from 'node:child_process' import { describe, expect, it } from 'vitest' import { Context } from 'cordis' -import { PwshLocalExecutor, candidatePwshPaths, resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local' +import { PwshLocalExecutor, ENCODING_PREAMBLE, candidatePwshPaths, resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' +import SubprocessService from '@deepseek-ai/dsh-subprocess' +import type { SubprocessHandle, SubprocessOutputReader, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import type { BashProcess } from '@deepseek-ai/dsh-bash' const spillDir = mkdtempSync(join(tmpdir(), 'dsh-pwsh-exec-spec-')) -const hasPwsh = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 +// The probe follows the executor's own resolution (Program Files installs on +// Windows are found even when bare `pwsh` is not on PATH). +const hasPwsh = spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 /** Normalize PowerShell's platform line endings (CRLF on Windows, LF elsewhere). */ const lf = (text: string): string => text.replace(/\r\n/g, '\n') @@ -110,6 +114,42 @@ describe('resolvePwshPath and candidatePwshPaths (pure, every platform)', () => }) }) +describe('spawn construction (pure, every platform)', () => { + /** A subprocess service that records spawn specs and settles instantly. */ + class CapturingSubprocessService extends SubprocessService { + specs: SubprocessSpawnSpec[] = [] + private readonly reader: SubprocessOutputReader = { + readFrom: () => ({ text: '', lossy: false, nextOffset: 0 }), + } + override spawn(spec: SubprocessSpawnSpec): SubprocessHandle { + this.specs.push(spec) + return { + pid: -1, + stdin: undefined, + stdout: undefined, + stderr: undefined, + collected: { stdout: this.reader, stderr: this.reader }, + done: Promise.resolve({ exitCode: 0, signal: null }), + terminate: () => {}, + waitForExit: async () => true, + } + } + } + + it('runs every command as ONE argv element under the UTF-8 encoding preamble', async () => { + const ctx = new Context() + const subprocess = new CapturingSubprocessService(ctx) + await ctx.plugin(PwshLocalExecutor) + await ctx.bash.run(ctx.bash.resolve({ command: 'Write-Output 你好' })) + expect(subprocess.specs).toHaveLength(1) + const { argv } = subprocess.specs[0]! + expect(argv.slice(0, 5)).toEqual([expect.any(String), '-NoLogo', '-NoProfile', '-NonInteractive', '-Command']) + expect(argv[5]).toBe(`${ENCODING_PREAMBLE}Write-Output 你好`) + expect(ENCODING_PREAMBLE).toContain('[Console]::OutputEncoding') + expect(ENCODING_PREAMBLE).toContain('$OutputEncoding') + }) +}) + describe.skipIf(!hasPwsh)('PwshLocalExecutor.run', () => { it('resolves with output and the effective timeout', async () => { const { bash } = await setup({ timeoutMs: 5_000 }) From 33810ae7747570d3764c9092dcc74e16fbb3212e Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 14:18:29 +0800 Subject: [PATCH 08/61] feat(tool-pwsh): mirror dsh-tool-bash call-for-call minus the sandbox surface --- packages/bash/tool-pwsh/README.i18n.yaml | 4 +- packages/bash/tool-pwsh/README.md | 46 +- packages/bash/tool-pwsh/README.zh.md | 122 +++--- packages/bash/tool-pwsh/package.json | 11 +- packages/bash/tool-pwsh/src/background.ts | 31 ++ packages/bash/tool-pwsh/src/index.ts | 220 +++++----- packages/bash/tool-pwsh/src/render.ts | 81 ++++ .../bash/tool-pwsh/tests/integration.spec.ts | 53 ++- packages/bash/tool-pwsh/tests/loader.spec.ts | 63 +++ packages/bash/tool-pwsh/tests/tools.spec.ts | 401 ++++++++++++++++-- packages/bash/tool-pwsh/tsconfig.json | 8 +- 11 files changed, 821 insertions(+), 219 deletions(-) create mode 100644 packages/bash/tool-pwsh/src/background.ts create mode 100644 packages/bash/tool-pwsh/src/render.ts create mode 100644 packages/bash/tool-pwsh/tests/loader.spec.ts diff --git a/packages/bash/tool-pwsh/README.i18n.yaml b/packages/bash/tool-pwsh/README.i18n.yaml index e16107e42f..102e50d0ce 100644 --- a/packages/bash/tool-pwsh/README.i18n.yaml +++ b/packages/bash/tool-pwsh/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/bash/tool-pwsh/README.md -README.md: 4f1d62dbf49fef678e3285776c466286535d66da -README.zh.md: bbeece3c648d8b1903eed1a66d2e14774c7ace8c +README.md: b5acc73a68d3b309860554d4c1e8d979eb8d1eec +README.zh.md: 4d678c42194b78da8b4b10e01f8b9e666d6236d8 diff --git a/packages/bash/tool-pwsh/README.md b/packages/bash/tool-pwsh/README.md index 4f1d62dbf4..b5acc73a68 100644 --- a/packages/bash/tool-pwsh/README.md +++ b/packages/bash/tool-pwsh/README.md @@ -2,13 +2,13 @@ English | [中文](README.zh.md) -The model-facing `pwsh` tool registered over the `ctx.bash` executor seam. Intended for Windows compositions where a PowerShell executor (e.g. `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. Minimal by design — no background tasks, no sandbox escalation, no persistent shell: this is the "works on my Windows machine" profile until the full bash-tool feature set gets a PowerShell twin. +The model-facing `pwsh` tool registered over the `ctx.bash` executor seam. Intended for Windows compositions where a PowerShell executor (e.g. `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. Behavior mirrors `dsh-tool-bash` call-for-call minus the sandbox surface — foreground and `run_in_background` execution through the generic task runtime, the managed `DSH_*` environment through the shared `bash-env` registry, and the bash marker/truncation rendering story (a clean exit produces no marker). -Requires a loaded executor implementation; the plugin stays pending until `ctx.bash` exists (`inject: ['tools', 'bash', 'systemPrompt']`). +Requires a loaded executor implementation and the `bash-env` plugin; the tool stays pending until both exist (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`). -The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`) plus the pure `renderPwshOutput` helper and its result type; execution and presentation remain implementation details covered by same-package tests. +The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`); result rendering (`src/render.ts`) and background-task adaptation (`src/background.ts`) mirror the bash tool's structure and stay reachable through the package's `./src/*` export. -The plugin also contributes the `tool:pwsh` prompt section (order 105): check the `[exit code: N]` marker on every result and investigate failures before moving on. +The plugin also contributes the `tool:pwsh` prompt section (order 105): non-zero exits are reported as `[exit code: N]` markers, and Windows interruption settles as exit 1 without a signal marker. ## Tools @@ -20,20 +20,23 @@ The plugin also contributes the `tool:pwsh` prompt section (order 105): check th | `description` | string (required) | One-line, active-voice summary of the command (5-10 words), for UI/log display only — no effect on execution. | | `timeoutMs` | number | Timeout override in milliseconds. The executor applies its configured default and cap. | | `workdir` | string | Working directory for this call. Defaults to the calling agent's session cwd (`session.header.cwd`) so each session runs in its own workspace; a relative `workdir` is resolved against that same identity. | +| `run_in_background` | boolean | Return a task id immediately; no timeout applies. | `command`, `workdir`, and `timeoutMs` are resolved against the executor's config defaults via `ctx.bash.resolve()` before execution. The workdir default is applied in the tool layer from the calling agent's `session.header.cwd` BEFORE `resolve()` — the per-session cwd must come from `exec.agent`, since N sessions share one executor; only when no session cwd is available does the executor fall back to its own config / `process.cwd()`. ### Managed shell environment -Every call receives a freshly collected trusted `DSH_*` environment. `DSH_HOME` is the absolute Harness home resolved by [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) (`dshHome` config, then ambient `$DSH_HOME`, then `~/.dsh`) and `DSH_SHELL=1` identifies the managed child. Agent calls additionally receive `DSH_SESSION_ID=agent.session.header.id`. The snapshot passes through the dedicated `BashExecRequest.dshEnv` channel; `process.env` is never modified. +Every foreground and background model pwsh call receives a freshly collected trusted `DSH_*` environment through the shared [`dsh-bash-env`](../bash-env/) registry: `DSH_HOME` (the absolute Harness home), `DSH_SHELL=1`, the agent's `DSH_SESSION_ID`, and `DSH_SESSION_JSONL` when the active persistence backend locates one. Plugins contributing `DSH_*` facts to `ctx.bashEnv` apply to pwsh calls exactly as they do to bash calls. The snapshot passes through the dedicated `BashExecRequest.dshEnv` channel; `process.env` is never modified. The description teaches the generic `$env:DSH_*` convention rather than naming persistence-specific variables. -Result text contains stdout, an optional `[stderr]` section, then applicable timeout, signal, and exit-code markers: `[timed out after ms]`, `[killed by signal: ]`, and `[exit code: N]`, each separated by a newline only when the accumulated text lacks one. Nonzero exit remains a model-interpreted result rather than `isError`. Only infrastructure failures — spawn errors and aborts (`tool call aborted`) — produce `isError`. +Result text contains stdout, an optional `[stderr]` section, then applicable truncation, timeout, signal, and exit markers. A clean exit (0, no signal) produces no marker; an empty body renders as `(no output)`. Truncation links a safe complete spill file or reports it unavailable. Timeout is reported independently of final exit status; nonzero exit remains a model-interpreted result rather than `isError`. Windows reports forced termination as exit 1 without a signal, so `[killed by signal: …]` is POSIX-only there. Only infrastructure failures — spawn errors and aborts (`tool call aborted`) — produce `isError`. -The canonical success is `{ kind: 'foreground', ...BashRunResult }` for a completed foreground process. Programmatic consumers use the typed fields without parsing the rendered text. +The canonical success is `{ kind: 'foreground', ...BashRunResult }` for a completed foreground process or `{ kind: 'background', taskId }` for a published task. The renderer preserves exactly `started background task ` for background acks; programmatic consumers use the typed fields without parsing the rendered text. + +When `run_in_background` is true, this plugin preflights `ctx.tasks.start()` before spawning, registers the calling agent as owner, and adapts the returned `BashProcess` handle into generic cancel/done/incremental-output hooks. The task runtime owns ids, cross-session isolation, completion notices, waiting, and disposal cleanup; this plugin only maps pwsh exit facts into task output and outcome detail. `enableRunInBackground: false` removes the parameter and rejects a forced background call at execution time. ## UI presentation -The tool owns its `presentCall`/`presentResult` render intent. A call is a `terminal` card carrying command, description, and optional cwd; a completed result is a `generic` card with the rendered output in a `console` fence. These presenters are pure and replay-safe. +The tool owns its `presentCall`/`presentResult` render intent. A call is a `terminal` card carrying command, description, and optional cwd; a completed result is a `generic` card with the rendered output in a `console` fence. The bash tool's terminal card with its parsed exit-status pill has no pwsh counterpart yet — a PowerShell-aware presentation is roadmap work. These presenters are pure and replay-safe. ## Model Experience @@ -46,7 +49,7 @@ Every request in this plugin's registration scope contains the pwsh guidance bel ##### Pwsh guidance ```markdown -Check the [exit code: N] marker on every pwsh result; investigate failures before moving on. +Non-zero exits are reported as `[exit code: N]` markers; investigate failures before moving on. On Windows a killed process settles as `[exit code: 1]` without a signal marker; treat a bare exit 1 after an interruption as a termination, not a command failure. ``` #### Token effect @@ -75,7 +78,7 @@ Prefix-stable while visibility and the tool definition are unchanged. A restrict #### What the model sees -The renderer emits the data-dependent stdout tail, then optional `[stderr]` and the stderr tail. Conditional lines are exactly `[timed out after ms]`, `[killed by signal: ]`, and `[exit code: ]`. +The renderer emits the data-dependent stdout tail, then optional `[stderr]` and the stderr tail. Conditional lines are exactly `[output truncated; full output: ]`, `[timed out after ms]`, `[killed by signal: ]`, and `[exit code: ]` (nonzero exits only); an empty body renders as `(no output)`. #### Token effect @@ -85,11 +88,25 @@ Zero result tokens before a call. Output is bounded per stream, while each emitt Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries. +### Background result + +#### What the model sees + +A background start renders exactly `started background task `; subsequent reads and status flow through the generic `task_output`/`task_kill` tools, including the lossy-read spill notice when in-memory truncation dropped unread bytes. + +#### Token effect + +The ack is a fixed short line; task output is bounded per read. + +#### KV Cache effect + +Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries. + ### Tool errors #### What the model sees -Validation and infrastructure failures are normalized as `Error: `. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got `, and `tool call aborted`. +Validation and infrastructure failures are normalized as `Error: `. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got `, `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`, and `tool call aborted`. #### Token effect @@ -101,7 +118,8 @@ Append-only; newly visible content follows the reusable request prefix and does ## Known Limitations and Deferred Work -- **Foreground-only** — no `run_in_background`; long-running work must stay within the executor timeout or wait for the bash-tool twin. -- **No sandbox escalation** — `sandbox_permissions`/`justification` are absent; a confining composition denies through the executor, and escalation waits for the full twin. +- **No sandbox escalation** — `sandbox_permissions`/`justification` are absent; escalation waits for a Windows-confining executor (the bash tool's sandbox surface is not mirrored). +- **No persistent shell or PTY** — every call starts a fresh `pwsh -Command`; the PTY backends are Linux/macOS-only today, and a Windows ConPTY persistent shell is roadmap work. - **PowerShell-dialect contract** — the model must write PowerShell (native paths, `$env:` variables), not bash; there is no dialect translation. -- **Windows-default roadmap deferred** — defaulting Windows hosts to `pwsh` over `bash`, and pwsh TUI/GUI rendering support, are planned separately and deliberately not part of this package yet. +- **Generic UI presentation** — results use the generic card; a PowerShell-aware terminal card with exit-status pill is roadmap work. +- **Session-cwd identity is not canonicalized** — the workdir base is the session header cwd as-is, unlike the bash tool's sandbox-root-canonicalized identity; only the sandbox-less case applies here. diff --git a/packages/bash/tool-pwsh/README.zh.md b/packages/bash/tool-pwsh/README.zh.md index bbeece3c64..4d678c4219 100644 --- a/packages/bash/tool-pwsh/README.zh.md +++ b/packages/bash/tool-pwsh/README.zh.md @@ -2,106 +2,124 @@ [English](README.md) | 中文 -面向模型的 `pwsh` 工具,注册在 `ctx.bash` 执行器 seam 之上。面向由 PowerShell 执行器(如 `@deepseek-ai/dsh-pwsh-local`)支撑 `ctx.bash` 的 Windows 组合;工具契约是 PowerShell 方言:原生 `C:\...` 路径与 `$env:NAME` 变量。刻意保持最小——无后台任务、无沙箱升级、无持久 shell:在完整 bash 工具功能集获得 PowerShell 孪生之前,这就是 "works on my Windows machine" 画像。 +注册在 `ctx.bash` 执行器 seam 之上的模型可见 `pwsh` 工具。面向由 PowerShell 执行器(如 `@deepseek-ai/dsh-pwsh-local`)支撑 `ctx.bash` 的 Windows 组合;工具契约是 PowerShell 方言:原生 `C:\...` 路径与 `$env:NAME` 变量。行为与 `dsh-tool-bash` 逐调用对齐、减去 sandbox 面——通过通用任务运行时执行前台与 `run_in_background`、通过共享 `bash-env` 注册表管理 `DSH_*` 环境、以及 bash 的 marker/截断渲染故事(干净退出不产生 marker)。 -需要一个已加载的执行器实现;插件在 `ctx.bash` 存在之前保持 pending(`inject: ['tools', 'bash', 'systemPrompt']`)。 +需要已加载的执行器实现与 `bash-env` 插件;两者都存在前工具保持 pending(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。 -包根只暴露 Cordis 插件契约(`name`、`inject`、`Config`、`apply`)以及纯函数 `renderPwshOutput` 及其结果类型;执行与呈现是同一包测试覆盖的实现细节。 +包根只导出 Cordis 插件契约(`name`、`inject`、`Config`、`apply`);结果渲染(`src/render.ts`)与后台任务适配(`src/background.ts`)镜像 bash 工具的结构,并可通过包的 `./src/*` 导出访问。 -该插件还贡献 `tool:pwsh` 提示词段(order 105):检查每个结果上的 `[exit code: N]` 标记,并在继续前调查失败。 +插件还贡献 `tool:pwsh` prompt section(order 105):非零退出以 `[exit code: N]` marker 报告,Windows 上的中断以无 signal 的 exit 1 结算。 ## 工具 ### `pwsh` -| 参数 | 类型 | 说明 | +| Arg | Type | Notes | |---|---|---| -| `command` | string(必填) | 通过 `pwsh -Command` 运行。调用之间不保留状态——用 `workdir`,不要用 `cd`。 | -| `description` | string(必填) | 命令的一句话主动语态摘要(5-10 词),仅用于 UI/日志展示——不影响执行。 | -| `timeoutMs` | number | 毫秒级超时覆盖。执行器应用其配置的默认值与上限。 | -| `workdir` | string | 本次调用的工作目录。默认取调用 agent(智能体)的会话 cwd(`session.header.cwd`),使每个会话在自己的工作区运行;相对 `workdir` 基于同一身份解析。 | +| `command` | string (required) | 通过 `pwsh -Command` 运行。调用之间不保留状态——用 `workdir`,不要用 `cd`。 | +| `description` | string (required) | 命令的一行主动语态摘要(5-10 词),仅用于 UI/日志展示——不影响执行。 | +| `timeoutMs` | number | 超时覆盖值(毫秒)。执行器应用其配置的默认值与上限。 | +| `workdir` | string | 本次调用的工作目录。默认取调用 agent 的会话 cwd(`session.header.cwd`),使每个会话在自己的工作区运行;相对 `workdir` 基于同一身份解析。 | +| `run_in_background` | boolean | 立即返回任务 id;不适用超时。 | -`command`、`workdir` 与 `timeoutMs` 在执行前经 `ctx.bash.resolve()` 按执行器配置默认值解析。workdir 默认值在工具层取自调用 agent 的 `session.header.cwd`,先于 `resolve()` 应用——每个会话的 cwd 必须来自 `exec.agent`,因为 N 个会话共享一个执行器;只有没有会话 cwd 时,执行器才回退到自己的配置 / `process.cwd()`。 +`command`、`workdir` 与 `timeoutMs` 在执行前经 `ctx.bash.resolve()` 按执行器配置默认值解析。workdir 默认值在工具层于 `resolve()` 之前从调用 agent 的 `session.header.cwd` 取得——每次会话的 cwd 必须来自 `exec.agent`,因为 N 个会话共享一个执行器;仅当没有会话 cwd 时执行器才回退到自己的配置 / `process.cwd()`。 -### 受管 shell 环境 +### Managed shell environment -每次调用都会收到一份新收集的受信 `DSH_*` 环境。`DSH_HOME` 是由 [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) 解析的 Harness 绝对主目录(`dshHome` 配置,其次环境变量 `$DSH_HOME`,再其次 `~/.dsh`),`DSH_SHELL=1` 标识受管子进程。agent 调用额外收到 `DSH_SESSION_ID=agent.session.header.id`。该快照经由专用 `BashExecRequest.dshEnv` 通道传递;`process.env` 永不被修改。 +每次前台与后台模型 pwsh 调用都会通过共享的 [`dsh-bash-env`](../bash-env/) 注册表收到一份新收集的受信任 `DSH_*` 环境:`DSH_HOME`(Harness 主目录绝对路径)、`DSH_SHELL=1`、agent 的 `DSH_SESSION_ID`,以及活跃持久化后端定位到 JSONL 时的 `DSH_SESSION_JSONL`。向 `ctx.bashEnv` 贡献 `DSH_*` 事实的插件对 pwsh 调用与 bash 调用一视同仁。快照通过专用的 `BashExecRequest.dshEnv` 通道传递;`process.env` 永不被修改。描述只教授通用的 `$env:DSH_*` 约定,而不是点名持久化相关的变量。 -结果文本包含 stdout、可选的 `[stderr]` 分段,以及适用的超时、信号与退出码标记:`[timed out after ms]`、`[killed by signal: ]` 与 `[exit code: N]`,仅在累积文本缺少换行时才补一个分隔换行。非零退出仍是模型自行解读的结果,而不是 `isError`。只有基础设施失败——spawn 错误与中止(`tool call aborted`)——才产生 `isError`。 +结果文本包含 stdout、可选的 `[stderr]` 段,然后是适用的截断、超时、signal 与退出 marker。干净退出(0、无 signal)不产生 marker;空体渲染为 `(no output)`。截断会链接一个安全的完整 spill 文件,或报告其不可用。超时独立于最终退出状态报告;非零退出仍是模型解读的结果而非 `isError`。Windows 上强制终止以无 signal 的 exit 1 结算,因此 `[killed by signal: …]` 在那里仅存在于 POSIX。只有基础设施失败——spawn 错误与中止(`tool call aborted`)——产生 `isError`。 -规范成功值为已完成前台进程的 `{ kind: 'foreground', ...BashRunResult }`。程序化消费方使用类型化字段,而不解析渲染文本。 +规范成功形态是已完成前台进程的 `{ kind: 'foreground', ...BashRunResult }` 或已发布任务的 `{ kind: 'background', taskId }`。渲染器对后台 ack 精确保留 `started background task `;编程消费者使用类型化字段而不解析渲染文本。 -## UI 呈现 +当 `run_in_background` 为 true 时,本插件在 spawn 前预检 `ctx.tasks.start()`,把调用 agent 注册为 owner,并将返回的 `BashProcess` 句柄适配为通用的 cancel/done/增量输出钩子。任务运行时拥有 id、跨会话隔离、完成通知、等待与清理;本插件只把 pwsh 退出事实映射进任务输出与结果明细。`enableRunInBackground: false` 会移除参数并在执行时拒绝强制的后台调用。 -工具拥有自己的 `presentCall`/`presentResult` 渲染意图。调用是携带命令、描述与可选 cwd 的 `terminal` 卡片;完成结果是 `generic` 卡片,渲染输出放在 `console` 围栏内。这些 presenter 是纯函数且可重放。 +## UI presentation -## 模型体验 +工具拥有自己的 `presentCall`/`presentResult` 呈现意图。调用是携带命令、描述与可选 cwd 的 `terminal` 卡;完成的结果是以 `console` 围栏包裹渲染输出的 `generic` 卡。bash 工具那种带解析退出状态 pill 的 terminal 卡在 pwsh 侧暂无对应——PowerShell 感知的呈现属于路线图工作。这些 presenter 是纯函数且可重放。 -### 系统提示词 +## Model Experience -#### 模型看到的内容 +### System prompt -该插件注册作用域内的每个请求都包含下方 pwsh 指导。作用域工具限制可以隐藏 schema,而不移除这个独立注册的提示词段。 +#### What the model sees -##### Pwsh 指导 +本插件注册作用域内的每个请求都包含下面的 pwsh 指引。作用域工具限制可以隐藏 schema,但不会移除这个独立注册的段落。 + +##### Pwsh guidance ```markdown -Check the [exit code: N] marker on every pwsh result; investigate failures before moving on. +Non-zero exits are reported as `[exit code: N]` markers; investigate failures before moving on. On Windows a killed process settles as `[exit code: 1]` without a signal marker; treat a bare exit 1 after an interruption as a termination, not a command failure. ``` -#### Token 影响 +#### Token effect -插件激活期间每个请求有少量固定输入成本。 +插件激活期间每次请求的固定小额输入成本。 -#### KV Cache 影响 +#### KV Cache effect -注册作用域与提示词文本不变时前缀稳定。插件激活或销毁可能使该提示词段的复用失效。 +注册作用域与 prompt 文本不变时前缀稳定。插件激活或释放可能使该 prompt 段落的复用失效。 -### 工具 schema +### Tool schemas -#### 模型看到的内容 +#### What the model sees -模型看到生成的 [`pwsh` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-pwsh)。agent 作用域的工具限制可以为该 agent 移除定义。 +模型看到生成的 [`pwsh` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-pwsh)。按 agent 作用域的工具限制可以移除该 agent 的定义。 -#### Token 影响 +#### Token effect -工具可见时每个请求有固定的 schema 成本。 +工具可见的每个请求上的固定 schema 成本。 -#### KV Cache 影响 +#### KV Cache effect -可见性与工具定义不变时前缀稳定。限制或配置变更可能从第一个改变的 token 起使复用失效。 +可见性与工具定义不变时前缀稳定。限制或配置变更可能从首个变化 token 起使复用失效。 -### 前台结果 +### Foreground result -#### 模型看到的内容 +#### What the model sees -渲染器输出依赖数据的 stdout 尾部,然后是可选 `[stderr]` 与 stderr 尾部。条件行恰为 `[timed out after ms]`、`[killed by signal: ]` 与 `[exit code: ]`。 +渲染器输出数据相关的 stdout 尾部,然后是可选的 `[stderr]` 与 stderr 尾部。条件行精确为 `[output truncated; full output: ]`、`[timed out after ms]`、`[killed by signal: ]` 与 `[exit code: ]`(仅非零退出);空体渲染为 `(no output)`。 -#### Token 影响 +#### Token effect -调用前零结果 token。输出按流有界,每条已发出行在压缩前保留在历史中。 +调用前零结果 token。每个流的输出有界,而每条已发出的行保留在历史中直到压缩。 -#### KV Cache 影响 +#### KV Cache effect -只追加;新可见内容跟在可复用请求前缀之后,不会使既有 KV-cache 条目失效。 +仅追加;新出现的内容跟随可复用的请求前缀,不会使既有 KV-cache 条目失效。 -### 工具错误 +### Background result -#### 模型看到的内容 +#### What the model sees -校验与基础设施失败被规范化为 `Error: `。本包的稳定消息为 `invalid command: expected a non-empty string`、`invalid description: expected a non-empty string`、`invalid timeoutMs: expected a positive number, got ` 与 `tool call aborted`。 +后台启动精确渲染为 `started background task `;随后的读取与状态通过通用 `task_output`/`task_kill` 工具流转,包括内存截断丢弃未读字节时的 lossy 读取 spill 通知。 -#### Token 影响 +#### Token effect -只有失败的调用会增加这些保留 token;中止的调用不增加命令输出。 +ack 是固定短行;任务输出按读取有界。 -#### KV Cache 影响 +#### KV Cache effect -只追加;新可见内容跟在可复用请求前缀之后,不会使既有 KV-cache 条目失效。 +仅追加;新出现的内容跟随可复用的请求前缀,不会使既有 KV-cache 条目失效。 -## 已知局限与延期工作 +### Tool errors -- **仅前台**——没有 `run_in_background`;长时间运行的工作必须留在执行器超时之内,或等待 bash 工具孪生。 -- **无沙箱升级**——没有 `sandbox_permissions`/`justification`;受约束的组合通过执行器拒绝,升级等待完整孪生。 -- **PowerShell 方言契约**——模型必须写 PowerShell(原生路径、`$env:` 变量),而不是 bash;没有方言翻译。 -- **Windows 默认路线图延期**——让 Windows 主机默认用 `pwsh` 而非 `bash`,以及 pwsh TUI/GUI 渲染支持,都另行规划,刻意不纳入本包。 +#### What the model sees + +校验与基础设施失败规范化为 `Error: `。本包的稳定消息包括 `invalid command: expected a non-empty string`、`invalid description: expected a non-empty string`、`invalid timeoutMs: expected a positive number, got `、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks` 与 `tool call aborted`。 + +#### Token effect + +只有失败的调用会新增这些保留 token;被中止的调用不产生命令输出。 + +#### KV Cache effect + +仅追加;新出现的内容跟随可复用的请求前缀,不会使既有 KV-cache 条目失效。 + +## Known Limitations and Deferred Work + +- **无 sandbox 升级** — 没有 `sandbox_permissions`/`justification`;升级等待 Windows-confining 执行器(bash 工具的 sandbox 面不被镜像)。 +- **无持久 shell 或 PTY** — 每次调用都启动全新的 `pwsh -Command`;PTY 后端目前仅限 Linux/macOS,Windows ConPTY 持久 shell 属于路线图工作。 +- **PowerShell 方言契约** — 模型必须写 PowerShell(原生路径、`$env:` 变量),而不是 bash;没有方言翻译。 +- **通用 UI 呈现** — 结果使用 generic 卡;带退出状态 pill 的 PowerShell 感知 terminal 卡属于路线图工作。 +- **会话 cwd 身份不做规范化** — workdir 基座直接取会话头 cwd 原值,不同于 bash 工具经 sandbox-root 规范化的身份;此处只涉及无 sandbox 场景。 diff --git a/packages/bash/tool-pwsh/package.json b/packages/bash/tool-pwsh/package.json index 90e12438d8..7f43cd57e8 100644 --- a/packages/bash/tool-pwsh/package.json +++ b/packages/bash/tool-pwsh/package.json @@ -29,11 +29,11 @@ "peerDependencies": { "@deepseek-ai/dsh-agent": "^0.0.1", "@deepseek-ai/dsh-bash": "^0.0.1", + "@deepseek-ai/dsh-bash-env": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "@deepseek-ai/dsh-llm": "^0.0.1", - "@deepseek-ai/dsh-paths": "^0.0.1", - "@deepseek-ai/dsh-session-persistence": "^0.0.1", "@deepseek-ai/dsh-system-prompt": "^0.0.1", + "@deepseek-ai/dsh-tasks": "^0.0.1", "@deepseek-ai/dsh-tools": "^0.0.1", "cordis": "^4.0.0-rc.7" }, @@ -43,13 +43,16 @@ "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-bash": "workspace:^", + "@deepseek-ai/dsh-bash-env": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", - "@deepseek-ai/dsh-paths": "workspace:^", + "@deepseek-ai/dsh-loader-smoke": "workspace:^", "@deepseek-ai/dsh-pwsh-local": "workspace:^", - "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-subprocess-local": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tasks": "workspace:^", + "@deepseek-ai/dsh-tasks-local": "workspace:^", + "@deepseek-ai/dsh-tool-tasks": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "cordis": "^4.0.0-rc.7" } diff --git a/packages/bash/tool-pwsh/src/background.ts b/packages/bash/tool-pwsh/src/background.ts new file mode 100644 index 0000000000..5e3464f76b --- /dev/null +++ b/packages/bash/tool-pwsh/src/background.ts @@ -0,0 +1,31 @@ +/** + * Generic-task adaptation for background pwsh process handles — the shell-agnostic + * twin of `dsh-tool-bash`'s background adaptation. + * + * @module @deepseek-ai/dsh-tool-pwsh/background + */ + +import type { BashProcess } from '@deepseek-ai/dsh-bash' + +/* jscpd:ignore-start -- deliberate twin of dsh-tool-bash/background.ts (Agent Note). */ + +/** + * Map a settled background process onto the generic task-outcome vocabulary: + * `killed` stays `killed` (detail: the signal when one is known), everything + * else is `completed` with the exit code as detail. A nonzero command exit is + * reported, not failed, exactly like the foreground rendering. + * @param proc - the settled process handle. + * @returns the outcome for the `ctx.tasks` registration. + */ +export function processOutcome(proc: BashProcess): { status: 'completed' | 'killed'; detail: string } { + // TODO(background-infrastructure-outcome): widen BashProcess with an explicit + // infrastructure-failure outcome, then map spawn failures and + // sandbox.runnerFailed to task `failed`. The current seam aliases a spawn + // failure with a signal-less kill and a runner failure with an ordinary + // wrapper exit; real nonzero command exits must remain `completed`. + if (proc.status === 'killed') { + return { status: 'killed', detail: proc.signal !== null ? `signal: ${proc.signal}` : 'killed before exit' } + } + return { status: 'completed', detail: `exit code: ${proc.exitCode ?? 0}` } +} +/* jscpd:ignore-end */ diff --git a/packages/bash/tool-pwsh/src/index.ts b/packages/bash/tool-pwsh/src/index.ts index 704c35647c..c8a02f0428 100644 --- a/packages/bash/tool-pwsh/src/index.ts +++ b/packages/bash/tool-pwsh/src/index.ts @@ -4,38 +4,48 @@ * `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is * PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. * - * Minimal by design: no background tasks, no sandbox escalation — this is the - * "works on my Windows machine" profile until the full bash-tool feature set - * gets a PowerShell twin. + * Behavior mirrors `dsh-tool-bash` call-for-call minus the sandbox surface: + * foreground and `run_in_background` execution (background handles register + * with the generic `ctx.tasks` runtime), the managed `DSH_*` environment + * through the shared `bash-env` registry, and the bash marker/truncation + * rendering story. UI presentation stays on the existing generic/terminal + * cards; a pwsh-specific rendering twin is roadmap work. * * @module @deepseek-ai/dsh-tool-pwsh */ import { isAbsolute, resolve as resolvePath } from 'node:path' -import { Context } from 'cordis' +import type { Context } from 'cordis' import z from 'schemastery' import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools' -import type { TerminalCallView, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools' +import type { TerminalCallView, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools' import { HarnessError } from '@deepseek-ai/dsh-llm' import type { Agent } from '@deepseek-ai/dsh-agent' -import type {} from '@deepseek-ai/dsh-session-persistence' import type {} from '@deepseek-ai/dsh-system-prompt' -import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-bash' -import type { BashRunResult, DshEnvironment } from '@deepseek-ai/dsh-bash' -import { DSH_HOME_ENV, resolveDshHome } from '@deepseek-ai/dsh-paths' +import type {} from '@deepseek-ai/dsh-tasks' +import type {} from '@deepseek-ai/dsh-bash-env' +import type { BashRunResult } from '@deepseek-ai/dsh-bash' +import { processOutcome } from './background.ts' +import { renderPwshProcessRead, renderPwshResult } from './render.ts' + +declare module '@deepseek-ai/dsh-tasks' { + interface TaskKindMap { + pwsh: 'pwsh' + } +} export const name = 'tool-pwsh' -export const inject = ['tools', 'bash', 'systemPrompt'] +export const inject = ['tools', 'bash', 'systemPrompt', 'bashEnv'] -/** Plugin config (currently empty; kept as a schema so deployments can grow it). */ +/** Configuration for the pwsh tool. */ export interface Config { - /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */ - dshHome?: string + /** Expose `run_in_background` (default true); disabled calls are also rejected. */ + enableRunInBackground?: boolean } /** Runtime configuration schema for the pwsh tool plugin. */ export const Config: z = z.object({ - dshHome: z.string(), + enableRunInBackground: z.boolean().default(true), }) /** Parsed tool args; execute validates value constraints absent from ParameterSchemaSpec. */ @@ -44,6 +54,7 @@ interface PwshToolArgs { description: string timeoutMs?: number workdir?: string + run_in_background?: boolean } /** The canonical foreground result of one pwsh call (the `output.schema` value shape). */ @@ -72,12 +83,18 @@ function validatePwshArgs(args: PwshToolArgs): void { } /* jscpd:ignore-end */ -function pwshDescription(): string { +function pwshDescription(backgroundEnabled: boolean): string { + const background = backgroundEnabled + ? 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`.' + : 'Background execution is not available; long-running commands must finish within the timeout.' return 'Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. ' + 'Each call runs in a fresh pwsh process: no state (cwd, variables, functions) persists between calls — ' + 'pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\\...`); read environment ' + 'variables with `$env:NAME`. Non-zero exits are reported as `[exit code: N]`. ' - + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available.' + + 'Current harness environment facts are exposed through managed `$env:DSH_*` variables; inspect them when needed. ' + + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. ' + + 'On Windows a force-killed command settles as `[exit code: 1]` without a signal marker — treat it as an interruption, not a command failure. ' + + background } /** @@ -93,32 +110,7 @@ function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent return modelWorkdir } -/** - * The model-facing text of one foreground pwsh result: stdout, a marked - * stderr section, then the applicable timeout, signal, and exit markers — - * each separated by a newline only when the accumulated text lacks one, so a - * trailing newline in stdout never produces a blank line. - * - * @param value - the canonical foreground result (the schema-derived value shape). - * @returns the model-facing text. - */ -function renderPwshOutput(value: RenderablePwshOutput): string { - let rendered = value.stdout.text - const marker = (line: string): void => { - rendered += rendered.length > 0 && !rendered.endsWith('\n') ? `\n${line}` : line - } - if (value.stderr.text.length > 0) marker(`[stderr]\n${value.stderr.text}`) - if (value.timedOut) marker(`[timed out after ${value.timeoutMs}ms]`) - if (value.signal !== null) marker(`[killed by signal: ${value.signal}]`) - if (value.exitCode !== null) marker(`[exit code: ${value.exitCode}]`) - return rendered -} - -/** - * Detach the executor DTO from readonly seam interfaces into plain JSON data. - * @param result - the executor's run outcome. - * @returns the canonical foreground result the tool returns and renders. - */ +/** Detach the executor DTO from readonly seam interfaces into plain JSON data. */ function canonicalPwshResult(result: BashRunResult): PwshForegroundResult { const output = (stream: BashRunResult['stdout']) => ({ text: stream.text, @@ -132,48 +124,32 @@ function canonicalPwshResult(result: BashRunResult): PwshForegroundResult { timedOut: result.timedOut, aborted: result.aborted, timeoutMs: result.timeoutMs, + /* jscpd:ignore-start -- the canonical projection and background-handle shape mirror dsh-tool-bash's by design (Agent Note). */ stdout: output(result.stdout), stderr: output(result.stderr), } } -/** The rendered fields of a foreground result — the schema-derived value shape (no `kind`, plain-string signal). */ -interface RenderablePwshOutput { - exitCode: number | null - signal: string | null - timedOut: boolean - timeoutMs: number - stdout: { text: string } - stderr: { text: string } -} - -/** - * The managed `DSH_*` snapshot for one pwsh call: the harness home, a shell - * marker, and the session identity when an agent is present. - */ -function collectDshEnv(exec: ToolExecution, dshHome: string): DshEnvironment { - const values: Record = { - [DSH_HOME_ENV]: dshHome, - [`${DSH_ENV_PREFIX}SHELL`]: '1', - } - if (exec.agent !== undefined) { - values[`${DSH_ENV_PREFIX}SESSION_ID`] = exec.agent.session.header.id - } - return values -} +/** Canonical background-handle properties shared by the pwsh output union. */ +const BACKGROUND_OUTPUT_PROPERTIES = { + kind: { type: 'string', required: true, const: 'background' }, + taskId: { type: 'string', required: true }, +} as const +/* jscpd:ignore-end */ export function apply(ctx: Context, config: Config = {}): void { - const dshHome = resolveDshHome(config.dshHome) + const backgroundEnabled = config.enableRunInBackground ?? true ctx.systemPrompt.section({ name: 'tool:pwsh', order: 105, - text: 'Check the [exit code: N] marker on every pwsh result; investigate failures before moving on.', + text: 'Non-zero exits are reported as `[exit code: N]` markers; investigate failures before moving on. ' + + 'On Windows a killed process settles as `[exit code: 1]` without a signal marker; treat a bare exit 1 after an interruption as a termination, not a command failure.', }) ctx.tools.register(defineTool({ name: 'pwsh', - description: pwshDescription(), + description: pwshDescription(backgroundEnabled), parameters: { command: { type: 'string', required: true, description: 'The PowerShell command to execute.' }, description: { @@ -185,59 +161,111 @@ export function apply(ctx: Context, config: Config = {}): void { }, timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' }, workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' }, + ...backgroundEnabled ? { + run_in_background: { type: 'boolean' as const, description: 'Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies.' }, + } : {}, }, output: { // The foreground result wire shape mirrors dsh-tool-bash's by contract — // consumers of one must accept the other (see the pwsh-tool-and-executor // Agent Note). - /* jscpd:ignore-start -- deliberate foreground-result schema symmetry with dsh-tool-bash. */ + /* jscpd:ignore-start -- deliberate result-schema symmetry with dsh-tool-bash. */ schema: { - type: 'object', - additionalProperties: false, - properties: { - kind: { type: 'string', required: true, const: 'foreground' }, - exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] }, - signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] }, - timedOut: { type: 'boolean', required: true }, - aborted: { type: 'boolean', required: true }, - timeoutMs: { type: 'number', required: true }, - stdout: { + oneOf: [ + { type: 'object', additionalProperties: false, - required: true, - properties: { - text: { type: 'string', required: true }, - truncated: { type: 'boolean', required: true }, - spillPath: { type: 'string' }, - }, + properties: BACKGROUND_OUTPUT_PROPERTIES, }, - stderr: { + { type: 'object', additionalProperties: false, - required: true, properties: { - text: { type: 'string', required: true }, - truncated: { type: 'boolean', required: true }, - spillPath: { type: 'string' }, + kind: { type: 'string', required: true, const: 'foreground' }, + exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] }, + signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] }, + timedOut: { type: 'boolean', required: true }, + aborted: { type: 'boolean', required: true }, + timeoutMs: { type: 'number', required: true }, + stdout: { + type: 'object', + additionalProperties: false, + required: true, + properties: { + text: { type: 'string', required: true }, + truncated: { type: 'boolean', required: true }, + spillPath: { type: 'string' }, + }, + }, + stderr: { + type: 'object', + additionalProperties: false, + required: true, + properties: { + text: { type: 'string', required: true }, + truncated: { type: 'boolean', required: true }, + spillPath: { type: 'string' }, + }, + }, }, }, - }, + ], }, /* jscpd:ignore-end */ render: (_args, value) => [{ type: 'text', - text: renderPwshOutput(value), + text: value.kind === 'background' + ? `started background task ${value.taskId}` + : renderPwshResult(value), }], }, - /* jscpd:ignore-start -- the foreground execute path mirrors dsh-tool-bash's by design (see the pwsh-tool-and-executor Agent Note). */ + /* jscpd:ignore-start -- the execute path mirrors dsh-tool-bash's by design (see the pwsh-tool-and-executor Agent Note). */ async execute(args: PwshToolArgs, exec) { validatePwshArgs(args) const workdir = resolveWorkdir(args.workdir, exec) - const result = await ctx.bash.run(ctx.bash.resolve({ + const request = { command: args.command, ...workdir !== undefined ? { workdir } : {}, ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {}, - dshEnv: collectDshEnv(exec, dshHome), + dshEnv: ctx.bashEnv.collect(exec), + } + if (args.run_in_background === true) { + // Undeclared keys are allowed, so schema omission also needs enforcement. + if (!backgroundEnabled) { + throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)') + } + const tasks = ctx.get('tasks') + if (tasks === undefined) { + throw new Error('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks') + } + // The caller owns cancellation until ctx.tasks commits detached ownership. + /* v8 ignore start -- the bash twin's branch is exercised by its sandbox-approval mid-call abort; + pwsh has no approval surface, and the tool registry's pre-dispatch abort check intercepts + already-aborted signals first, so this mirror-only guard has no reachable trigger. */ + if (exec.signal.aborted) { + const error = new HarnessError('tool call aborted', TOOL_ABORTED) + error.name = 'AbortError' + throw error + } + /* v8 ignore end */ + // Task preflight finishes before the starter can spawn a process. + const id = tasks.start({ + kind: 'pwsh', + label: args.command, + ...exec.agent ? { owner: exec.agent } : {}, + run: () => { + const proc = ctx.bash.start(ctx.bash.resolve(request)) + return { + cancel: () => void proc.kill(), + done: proc.done.then(() => processOutcome(proc)), + readOutput: () => renderPwshProcessRead(proc.readOutput()), + } + }, + }) + return { kind: 'background' as const, taskId: id } + } + const result = await ctx.bash.run(ctx.bash.resolve({ + ...request, signal: exec.signal, })) if (result.aborted) { diff --git a/packages/bash/tool-pwsh/src/render.ts b/packages/bash/tool-pwsh/src/render.ts new file mode 100644 index 0000000000..42f4bc696c --- /dev/null +++ b/packages/bash/tool-pwsh/src/render.ts @@ -0,0 +1,81 @@ +/** + * Model-facing result rendering for the pwsh tool — the PowerShell twin of + * `dsh-tool-bash`'s renderer minus the sandbox surface: stdout, a marked + * stderr section, truncation notices with spill paths, then exit-status + * markers. Non-zero exits are reported, not errored — the model decides how to + * react; only infrastructure failures (spawn errors, aborts) surface as + * isError results. + * + * @module @deepseek-ai/dsh-tool-pwsh/render + */ + +import type { BashProcessRead, CollectedOutput } from '@deepseek-ai/dsh-bash' + +/* jscpd:ignore-start -- deliberate twin of dsh-tool-bash/render.ts minus the sandbox surface (Agent Note). */ + +/** Append the truncation notice (with the full-output spill path) to a stream's text. */ +function streamText(output: CollectedOutput): string { + if (!output.truncated) return output.text + return `${output.text}\n[output truncated; full output: ${output.spillPath ?? '(unavailable)'}]` +} + +/** The renderable foreground result shape (the schema-derived value, no `kind`). */ +export interface RenderablePwshResult { + exitCode: number | null + signal: string | null + timedOut: boolean + timeoutMs: number + stdout: CollectedOutput + stderr: CollectedOutput +} + +/** + * Shape one finished run into the text the model sees: stdout, then a marked + * stderr section, then exit-status markers, matching the bash tool's story — + * a clean exit (0, no signal) produces no marker. + * @param result - the completed foreground run from the executor. + * @returns the model-facing text: output body (or `(no output)`), then any timeout/signal/exit markers, each on its own line. + */ +export function renderPwshResult(result: RenderablePwshResult): string { + const out = streamText(result.stdout) + const err = streamText(result.stderr) + + let body = out + if (err.length > 0) { + // Single newline between sections (stdout usually ends with one already). + if (body.length > 0 && !body.endsWith('\n')) body += '\n' + body += `[stderr]\n${err}` + } + if (body.length === 0) body = '(no output)' + + const markers: string[] = [] + // A command may trap the termination and exit 0 after timeout; still report interruption. + if (result.timedOut) markers.push(`[timed out after ${result.timeoutMs}ms]`) + if (result.signal !== null) { + markers.push(`[killed by signal: ${result.signal}]`) + } else if (result.exitCode !== 0) { + markers.push(`[exit code: ${result.exitCode}]`) + } + if (markers.length === 0) return body + + if (!body.endsWith('\n')) body += '\n' + return body + markers.join('\n') +} + +/** + * Shape one background-process read into the `task_output` delta the model + * sees: the incremental delta, plus the lossy-read notice (with full-stream + * spill paths) when in-memory truncation dropped unread bytes. + * @param read - one incremental read from the process handle. + * @returns the delta text with any loss notice appended. + */ +export function renderPwshProcessRead(read: BashProcessRead): string { + const notices: string[] = [] + if (read.lossy) { + const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((path): path is string => path !== undefined) + notices.push(`[some output was dropped from memory; full output: ${paths.length > 0 ? paths.join(', ') : '(unavailable)'}]`) + } + if (notices.length === 0) return read.delta + return `${read.delta}${read.delta.length > 0 && !read.delta.endsWith('\n') ? '\n' : ''}${notices.join('\n')}` +} +/* jscpd:ignore-end */ diff --git a/packages/bash/tool-pwsh/tests/integration.spec.ts b/packages/bash/tool-pwsh/tests/integration.spec.ts index c703c6aa0e..711f7663b1 100644 --- a/packages/bash/tool-pwsh/tests/integration.spec.ts +++ b/packages/bash/tool-pwsh/tests/integration.spec.ts @@ -2,10 +2,11 @@ * Integration tests: the REAL `@deepseek-ai/dsh-pwsh-local` executor plus the * `pwsh` tool, exercised through `ctx.tools.execute()` with a real PowerShell * process. These verify the world — actual commands run, stdout/stderr come - * back, exit codes render, timeouts abort, and per-session cwd resolution - * works. The suite self-skips when no `pwsh` is on PATH (a CI accommodation - * for hosts without PowerShell); the fake-executor suite (tools.spec.ts) - * carries the coverage gate. + * back, exit codes render, timeouts abort, background tasks settle through the + * generic task runtime, and per-session cwd resolution works. The suite + * self-skips when no `pwsh` is on PATH (a CI accommodation for hosts without + * PowerShell); the fake-executor suite (tools.spec.ts) carries the coverage + * gate. */ import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -17,13 +18,18 @@ import { Context } from 'cordis' import { CallId } from '@deepseek-ai/dsh-llm' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' +import LocalTaskService from '@deepseek-ai/dsh-tasks-local' +import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' -import { PwshLocalExecutor } from '@deepseek-ai/dsh-pwsh-local' +import { PwshLocalExecutor, resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local' import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' const testToolSignal = new AbortController().signal -const hasPwsh = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 +// The probe follows the executor's own resolution (Program Files installs on +// Windows are found even when bare `pwsh` is not on PATH). +const hasPwsh = spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 /** Normalize PowerShell's platform line endings (CRLF on Windows, LF elsewhere). */ const lf = (text: string): string => text.replace(/\r\n/g, '\n') @@ -54,7 +60,10 @@ describe.skipIf(!hasPwsh)('pwsh tool over the real pwsh executor', () => { ctx = new Context() await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRegistry) + await ctx.plugin(LocalTaskService) + await ctx.plugin(ToolTasks) await ctx.plugin(LocalSubprocessService) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(PwshLocalExecutor, { timeoutMs: 20_000, graceMs: 200 }) await ctx.plugin(ToolPwsh) }) @@ -65,12 +74,12 @@ describe.skipIf(!hasPwsh)('pwsh tool over the real pwsh executor', () => { const agent = () => ({ session: { header: { id: 'session-int', cwd: dir } } }) - it('runs a command and returns stdout with the exit marker', async () => { + it('runs a command and returns stdout with no marker on a clean exit', async () => { const result = await call('pwsh', { command: 'Write-Output hi', description: 'say hi' }, agent()) expect(result.isError).toBe(false) if (result.isError) throw new Error('expected pwsh success') expect(result.value).toMatchObject({ kind: 'foreground', exitCode: 0 }) - expect(lf(text(result))).toBe('hi\n[exit code: 0]') + expect(lf(text(result))).toBe('hi\n') }) it('returns stderr in a marked section and a nonzero exit as a marker, not an error', async () => { @@ -88,7 +97,7 @@ describe.skipIf(!hasPwsh)('pwsh tool over the real pwsh executor', () => { description: 'read greeting', }, agent()) expect(result.isError).toBe(false) - expect(lf(text(result))).toBe('hello pwsh\n[exit code: 0]') + expect(lf(text(result))).toBe('hello pwsh\n') }) it('a per-call timeout kills the run and reports the timed-out marker, not an error', async () => { @@ -116,4 +125,30 @@ describe.skipIf(!hasPwsh)('pwsh tool over the real pwsh executor', () => { expect(result.isError).toBe(true) expect(result.error).toMatchObject({ info: { name: 'AbortError', code: TOOL_ABORTED } }) }) + + it('a background run settles through the REAL task_output tool', async () => { + const started = await call('pwsh', { + command: 'Start-Sleep -Milliseconds 300; Write-Output bg-done', + description: 'background greeting', + run_in_background: true, + }) + expect(started.isError).toBe(false) + if (started.isError) throw new Error('expected background pwsh success') + expect(started.value).toMatchObject({ kind: 'background' }) + const taskId = (started.value as { taskId: string }).taskId + + // The output delta and the terminal status can land in separate reads + // (Windows flushes the child pipe at exit), so collect incrementally — + // the same two-step shape as the bash background suite. + const deadline = Date.now() + 10_000 + let output = '' + while (Date.now() < deadline) { + const read = await call('task_output', { task_id: taskId }) + output += text(read) + if (output.includes('bg-done') && output.includes('[status: completed, exit code: 0]')) break + await new Promise(resolve => setTimeout(resolve, 50)) + } + expect(output).toContain('bg-done') + expect(output).toContain('[status: completed, exit code: 0]') + }) }) diff --git a/packages/bash/tool-pwsh/tests/loader.spec.ts b/packages/bash/tool-pwsh/tests/loader.spec.ts new file mode 100644 index 0000000000..7037162579 --- /dev/null +++ b/packages/bash/tool-pwsh/tests/loader.spec.ts @@ -0,0 +1,63 @@ +/** + * REAL-composition tier (packages/AGENTS.md): boot the examples-owned + * tool-pwsh Loader fixture as a subprocess through the same app/boot path a + * deployment uses, execute real foreground and background pwsh commands + * through the tool registry, and assert the assembled model-visible surface: + * schema, prompt section, and rendered results. Self-skips when no `pwsh` + * executable exists (a CI accommodation for hosts without PowerShell). + */ + +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { spawnSync } from 'node:child_process' +import { describe, expect, it } from 'vitest' +import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' +import { resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local' + +// The probe follows the executor's own resolution (Program Files installs on +// Windows are found even when bare `pwsh` is not on PATH). +const hasPwsh = spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 + +const driver = fileURLToPath(new URL( + '../../../../examples/acp-agent/tests/fixtures/bash/tool-pwsh/driver.ts', + import.meta.url, +)) +const configPath = fileURLToPath(new URL( + '../../../../examples/acp-agent/tests/fixtures/bash/tool-pwsh/cordis.yml', + import.meta.url, +)) +const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url)) + +interface PwshLoaderReport { + schemaHasRunInBackground: boolean + promptHasMarkerSection: boolean + foregroundText: string + backgroundText: string +} + +describe.skipIf(!hasPwsh)('tool-pwsh through a real Loader composition', () => { + it('registers the pwsh surface and renders real foreground and background results', async () => { + let report: PwshLoaderReport | undefined + const { stderr } = await runLoaderSmoke({ + label: 'tool-pwsh loader smoke', + tempDirPrefix: 'tool-pwsh-loader-', + binScript: driver, + libBinScript: driver, + configPath, + tsconfigPath: repoTsconfig, + inspect: async (cwd) => { + report = JSON.parse(await readFile(join(cwd, 'pwsh-loader-report.json'), 'utf8')) as PwshLoaderReport + }, + }) + expect(stderr).not.toContain('UNHANDLED') + expect(report).toBeDefined() + expect(report).toMatchObject({ + schemaHasRunInBackground: true, + promptHasMarkerSection: true, + }) + expect(report?.foregroundText).toBe('loader-ok\n') + expect(report?.backgroundText).toContain('loader-bg-ok') + expect(report?.backgroundText).toContain('[status: completed, exit code: 0]') + }, LOADER_SMOKE_TEST_TIMEOUT_MS) +}) diff --git a/packages/bash/tool-pwsh/tests/tools.spec.ts b/packages/bash/tool-pwsh/tests/tools.spec.ts index 5361130991..9d1eedba08 100644 --- a/packages/bash/tool-pwsh/tests/tools.spec.ts +++ b/packages/bash/tool-pwsh/tests/tools.spec.ts @@ -2,10 +2,11 @@ * Consumer-surface tests for the `pwsh` tool over a FAKE bash executor, * exercised through `ctx.tools.execute()` so nothing bypasses the tool * registry. The fake executor makes every seam outcome scriptable — output - * text, truncation, timeout, abort, nonzero exits — so these tests verify the - * schema, argument validation, workdir derivation, managed `DSH_*` collection, - * abort translation, canonical result projection, rendering, and the UI - * presenters. Real-pwsh behavior is pinned separately in integration.spec.ts. + * text, truncation, timeout, abort, nonzero exits, background handles — so + * these tests verify the schema, argument validation, workdir derivation, + * managed `DSH_*` collection, abort translation, canonical result projection, + * rendering, background task wiring, and the UI presenters. Real-pwsh behavior + * is pinned separately in integration.spec.ts. */ import { describe, expect, it } from 'vitest' @@ -15,23 +16,33 @@ import { tmpdir } from 'node:os' import { join, resolve as resolvePath } from 'node:path' import { CallId } from '@deepseek-ai/dsh-llm' import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' -import ToolRegistry, { TOOL_ABORTED } from '@deepseek-ai/dsh-tools' +import ToolRegistry, { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' +import LocalTaskService from '@deepseek-ai/dsh-tasks-local' +import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { SessionId } from '@deepseek-ai/dsh-session' import { BashExecutor } from '@deepseek-ai/dsh-bash' import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from '@deepseek-ai/dsh-bash' import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' +import type { BashProcessRead } from '@deepseek-ai/dsh-bash' +import { processOutcome } from '../src/background.ts' +import { renderPwshProcessRead } from '../src/render.ts' const testToolSignal = new AbortController().signal /** * A scriptable fake executor: `resolve()` mirrors the real defaulting, `run()` - * returns the armed script, `start()` throws — the pwsh tool must NEVER create - * a background task. + * returns the armed foreground script, `start()` returns the armed background + * handle. */ class FakeBash extends BashExecutor { requests: BashExecRequest[] = [] specs: BashExecSpec[] = [] startCalls = 0 handler: (spec: BashExecSpec) => BashRunResult = () => runResult('') + backgroundHandler: (spec: BashExecSpec) => BashProcess = () => fakeProcess('bg-ok\n') override resolve(request: BashExecRequest): BashExecSpec { this.requests.push(request) @@ -53,9 +64,10 @@ class FakeBash extends BashExecutor { return this.handler(spec) } - override start(): BashProcess { + override start(spec: BashExecSpec): BashProcess { this.startCalls++ - throw new Error('the pwsh tool must never start a background task') + this.specs.push(spec) + return this.backgroundHandler(spec) } } @@ -73,33 +85,95 @@ function runResult(stdout: string, overrides?: Partial): BashRunR } } -async function setup(config: Partial = {}) { +/** A settled successful background handle; overrides script failure shapes. */ +function fakeProcess(delta = 'bg-ok\n'): BashProcess { + let consumed = false + return { + status: 'completed', + exitCode: 0, + signal: null, + done: Promise.resolve(), + readOutput: () => { + if (consumed) return { delta: '', lossy: false } + consumed = true + return { delta, lossy: false } + }, + kill: () => false, + } +} + +/** A running background handle whose kill() settles it as killed (like a real task_kill). */ +function killableProcess(): BashProcess { + let resolveDone: () => void = () => {} + const done = new Promise((resolve) => { resolveDone = resolve }) + const proc: BashProcess = { + status: 'running', + exitCode: null, + signal: null, + done, + readOutput: () => ({ delta: '', lossy: false }), + kill: () => { + if (proc.status !== 'running') return false + proc.status = 'killed' + proc.signal = 'SIGTERM' + resolveDone() + return true + }, + } + return proc +} + +async function setup(toolConfig: Partial = {}, dshHome?: string) { const ctx = new Context() await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(BashEnvPlugin, dshHome === undefined ? {} : { dshHome }) await ctx.plugin(FakeBash) - await ctx.plugin(ToolPwsh, config) + await ctx.plugin(ToolPwsh, toolConfig) const bash = ctx.bash as FakeBash return { ctx, bash } } -/** A stand-in agent whose session header carries the given cwd and id. */ -const agent = (cwd?: string, id = 'session-1') => ({ session: { header: { id, ...cwd !== undefined ? { cwd } : {} } } }) +/** Full harness: the generic task runtime + its control surface, then the pwsh tool. */ +async function setupWithTasks(toolConfig: Partial = {}, dshHome?: string) { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(LocalTaskService) + await ctx.plugin(ToolTasks) + await ctx.plugin(BashEnvPlugin, dshHome === undefined ? {} : { dshHome }) + await ctx.plugin(FakeBash) + await ctx.plugin(ToolPwsh, toolConfig) + const bash = ctx.bash as FakeBash + return { ctx, bash } +} + +/** + * Build a fake {@link Agent} with the shared agent/session identity, give it a + * dedicated lifecycle fiber for `Agent.ctx`, and register it in `ctx.agents`. + */ +function registerFakeAgent(ctx: Context, sessionId: string): Agent { + const scopeFiber = ctx.plugin(() => {}) + const id = SessionId(sessionId) + const agent = { + id, + ctx: scopeFiber.ctx, + session: { id, header: { version: 0, id, createdAt: 0 } }, + } as unknown as Agent + ctx.agents.register(agent) + return agent +} let callCounter = 0 -function call( - ctx: Context, - name: string, - args: unknown, - options: { agent?: object; signal?: AbortSignal } = {}, -) { +function call(ctx: Context, name: string, args: unknown, agent?: Agent) { return ctx.tools.execute({ signal: testToolSignal, callId: CallId(`call-${++callCounter}`), name, arguments: args, - ...options.agent ? { agent: options.agent as never } : {}, - ...options.signal ? { signal: options.signal } : {}, + ...agent ? { agent } : {}, }) } @@ -107,6 +181,23 @@ function text(result: { content: { type: string; text?: string }[] }): string { return result.content.filter(b => b.type === 'text').map(b => b.text).join('') } +async function callUntilText( + ctx: Context, + name: string, + args: unknown, + expected: string, + timeoutMs = 5_000, +): Promise>> { + const deadline = Date.now() + timeoutMs + let last: Awaited> | undefined + while (Date.now() < deadline) { + last = await call(ctx, name, args) + if (text(last).includes(expected)) return last + await new Promise(resolve => setTimeout(resolve, 20)) + } + throw new Error(`tool output did not include ${JSON.stringify(expected)}; last text ${JSON.stringify(last === undefined ? '' : text(last))}`) +} + describe('registration', () => { it('registers the pwsh tool with its prompt section and schema', async () => { const { ctx } = await setup() @@ -118,10 +209,12 @@ describe('registration', () => { description: { type: 'string' }, timeoutMs: { type: 'number' }, workdir: { type: 'string' }, + run_in_background: { type: 'boolean' }, }) expect(schema?.parameters.required).toEqual(['command', 'description']) const prompt = renderPrompt(await ctx.systemPrompt.assemble()) - expect(prompt).toContain('Check the [exit code: N] marker on every pwsh result') + expect(prompt).toContain('Non-zero exits are reported as `[exit code: N]` markers') + expect(prompt).toContain('without a signal marker') }) it('stays pending until ctx.bash exists (inject)', async () => { @@ -136,6 +229,7 @@ describe('registration', () => { const ctx = new Context() await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRegistry) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(FakeBash) const fiber = await ctx.plugin(ToolPwsh) expect(ctx.tools.schemas()).toHaveLength(1) @@ -157,13 +251,15 @@ describe('argument validation', () => { describe('execution through the bash seam', () => { it('forwards command, session cwd, timeout, and managed DSH_* environment', async () => { const dshHome = mkdtempSync(join(tmpdir(), 'dsh-tool-pwsh-home-')) - const { ctx, bash } = await setup({ dshHome }) + const { ctx, bash } = await setup({}, dshHome) bash.handler = () => runResult('hi\n') + const agent = registerFakeAgent(ctx, 'session-1') + Object.assign(agent.session.header, { cwd: '/sessions/s1' }) const result = await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'say hi', timeoutMs: 1234, - }, { agent: agent('/sessions/s1') }) + }, agent) expect(result.isError).toBe(false) const request = bash.requests[0] expect(request?.command).toBe('Write-Output hi') @@ -180,9 +276,11 @@ describe('execution through the bash seam', () => { it('resolves a relative workdir against the session cwd, absolute ones verbatim', async () => { const { ctx, bash } = await setup() bash.handler = () => runResult('ok\n') - await call(ctx, 'pwsh', { command: 'pwd', description: 'cwd', workdir: 'sub/dir' }, { agent: agent('/sessions/s1') }) + const agent = registerFakeAgent(ctx, 'session-cwd') + Object.assign(agent.session.header, { cwd: '/sessions/s1' }) + await call(ctx, 'pwsh', { command: 'pwd', description: 'cwd', workdir: 'sub/dir' }, agent) expect(bash.requests[0]?.workdir).toBe(resolvePath('/sessions/s1', 'sub/dir')) - await call(ctx, 'pwsh', { command: 'pwd', description: 'cwd', workdir: resolvePath('/abs/path') }, { agent: agent('/sessions/s1') }) + await call(ctx, 'pwsh', { command: 'pwd', description: 'cwd', workdir: resolvePath('/abs/path') }, agent) expect(bash.requests[1]?.workdir).toBe(resolvePath('/abs/path')) }) @@ -202,7 +300,12 @@ describe('execution through the bash seam', () => { const { ctx, bash } = await setup() const controller = new AbortController() bash.handler = () => runResult('ok\n') - await call(ctx, 'pwsh', { command: 'Write-Output ok', description: 'ok' }, { signal: controller.signal }) + await ctx.tools.execute({ + signal: controller.signal, + callId: CallId('call-signal'), + name: 'pwsh', + arguments: { command: 'Write-Output ok', description: 'ok' }, + }) expect(bash.requests[0]?.signal).toBe(controller.signal) }) @@ -229,19 +332,60 @@ describe('execution through the bash seam', () => { expect(text(result)).toBe('out\n[stderr]\nerr\n[exit code: 2]') }) - it('renders the truncation tail, the exit marker, and a timeout marker from the executor streams', async () => { + it('renders a clean exit without a marker and an empty body as (no output)', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('hi\n') + const clean = await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'say hi' }) + expect(text(clean)).toBe('hi\n') + + bash.handler = () => runResult('') + const empty = await call(ctx, 'pwsh', { command: 'Write-Output -NoNewline ""', description: 'nothing' }) + expect(text(empty)).toBe('(no output)') + }) + + it('renders stderr-only output without a stdout prefix', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('', { + stderr: { text: 'err\n', truncated: false }, + exitCode: 1, + }) + const result = await call(ctx, 'pwsh', { command: 'fail', description: 'fail' }) + expect(text(result)).toBe('[stderr]\nerr\n[exit code: 1]') + }) + + it('inserts the separating newline before the stderr section when stdout lacks one', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('out', { + stderr: { text: 'err\n', truncated: false }, + exitCode: 1, + }) + const result = await call(ctx, 'pwsh', { command: 'fail', description: 'fail' }) + expect(text(result)).toBe('out\n[stderr]\nerr\n[exit code: 1]') + }) + + it('renders the truncation notice with the spill path, then markers', async () => { const { ctx, bash } = await setup() bash.handler = () => runResult('tail', { stdout: { text: 'tail', truncated: true, spillPath: '/spill/out.log' }, stderr: { text: '', truncated: false }, }) const result = await call(ctx, 'pwsh', { command: 'noisy', description: 'noise' }) - expect(text(result)).toBe('tail\n[exit code: 0]') + expect(text(result)).toBe('tail\n[output truncated; full output: /spill/out.log]') bash.handler = () => runResult('', { timedOut: true, exitCode: null, signal: 'SIGTERM', timeoutMs: 500 }) const timedOut = await call(ctx, 'pwsh', { command: 'slow', description: 'slow' }) // A timeout kill carries both facts, mirroring the bash tool's markers. - expect(text(timedOut)).toBe('[timed out after 500ms]\n[killed by signal: SIGTERM]') + expect(text(timedOut)).toBe('(no output)\n[timed out after 500ms]\n[killed by signal: SIGTERM]') + }) + + it('renders the truncation notice with (unavailable) when no spill path exists', async () => { + const { ctx, bash } = await setup() + bash.handler = () => runResult('tail', { + stdout: { text: 'tail', truncated: true }, + stderr: { text: '', truncated: false }, + }) + const result = await call(ctx, 'pwsh', { command: 'noisy', description: 'noise' }) + expect(text(result)).toBe('tail\n[output truncated; full output: (unavailable)]') }) it('translates an aborted run into the TOOL_ABORTED HarnessError', async () => { @@ -251,15 +395,124 @@ describe('execution through the bash seam', () => { expect(result.isError).toBe(true) expect(result.error).toMatchObject({ info: { name: 'AbortError', code: TOOL_ABORTED } }) }) +}) - it('never starts a background task', async () => { - const { ctx, bash } = await setup() - bash.handler = () => runResult('ok\n') - await call(ctx, 'pwsh', { command: 'Write-Output ok', description: 'ok' }) - bash.handler = () => runResult('', { exitCode: 1 }) - await call(ctx, 'pwsh', { command: 'missing', description: 'missing' }) +describe('background execution through the task runtime', () => { + it('run_in_background acks with the task id, readable through the REAL task_output tool', async () => { + const { ctx } = await setupWithTasks() + const started = await call(ctx, 'pwsh', { command: 'Write-Output bg-ok', description: 'test command', run_in_background: true }) + expect(started.isError).toBe(false) + if (started.isError) throw new Error('expected background pwsh success') + expect(started.value).toEqual({ kind: 'background', taskId: 'pwsh-1' }) + expect(text(started)).toBe('started background task pwsh-1') + + const read = await callUntilText(ctx, 'task_output', { task_id: 'pwsh-1' }, 'bg-ok') + expect(text(read)).toContain('bg-ok') + // A later read reports the terminal outcome in the generic status line. + const final = await callUntilText(ctx, 'task_output', { task_id: 'pwsh-1' }, '[status: completed, exit code: 0]') + expect(final.isError).toBe(false) + }) + + it('a running background task is killable through the REAL task_kill tool', async () => { + const { ctx, bash } = await setupWithTasks() + bash.backgroundHandler = () => killableProcess() + await call(ctx, 'pwsh', { command: 'Start-Sleep -Seconds 60', description: 'test command', run_in_background: true }) + + const killed = await call(ctx, 'task_kill', { task_id: 'pwsh-1' }) + expect(text(killed)).toBe('requested cancellation of task pwsh-1') + // The cancel reached the process handle; the task settles as killed with + // the signal detail mapped by processOutcome. + const final = await call(ctx, 'task_output', { task_id: 'pwsh-1', wait: true }) + expect(text(final)).toContain('[status: killed, signal: SIGTERM]') + }) + + it('a background task started by an agent is registered with that agent as owner', async () => { + const { ctx } = await setupWithTasks() + const agent = registerFakeAgent(ctx, 'sess-owner') + const started = await call(ctx, 'pwsh', { command: 'Start-Sleep -Seconds 60', description: 'test command', run_in_background: true }, agent) + expect(text(started)).toBe('started background task pwsh-1') + + const anon = await call(ctx, 'task_output', { task_id: 'pwsh-1' }) + expect(anon.isError).toBe(true) + expect(text(anon)).toMatch(/belongs to another session/) + + const killed = await call(ctx, 'task_kill', { task_id: 'pwsh-1' }, agent) + expect(killed.isError).toBe(false) + await call(ctx, 'task_output', { task_id: 'pwsh-1', wait: true }, agent) // await settlement — no orphan + }) + + it('fails loud when the task runtime is not loaded', async () => { + const { ctx } = await setup() // no LocalTaskService / ToolTasks + const result = await call(ctx, 'pwsh', { command: 'Start-Sleep -Seconds 60', description: 'test command', run_in_background: true }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks') + }) + + it('a pre-aborted call is skipped before the process starts', async () => { + const { ctx, bash } = await setupWithTasks() + const controller = new AbortController() + controller.abort() + const result = await ctx.tools.execute({ + callId: CallId('call-pre-aborted'), + name: 'pwsh', + arguments: { command: 'Start-Sleep -Seconds 60', description: 'test command', run_in_background: true }, + signal: controller.signal, + }) + expect(result.isError).toBe(true) + expect(result.error).toEqual({ + message: 'tool call aborted before dispatch', + info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH }, + }) expect(bash.startCalls).toBe(0) }) + + it('never spawns the process when tasks.start preflight throws (no orphan, by construction)', async () => { + // With no control surface, task preflight fails before the executor can spawn. + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(LocalTaskService) + await ctx.plugin(BashEnvPlugin) + await ctx.plugin(FakeBash) + await ctx.plugin(ToolPwsh) + const bash = ctx.bash as FakeBash + + const result = await call(ctx, 'pwsh', { command: 'Start-Sleep -Seconds 60', description: 'test command', run_in_background: true }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('no control surface is attached') + // Declare-then-execute: the failed preflight means no process ever ran. + expect(bash.startCalls).toBe(0) + }) + + it('enableRunInBackground: false removes the parameter and flips the description', async () => { + const { ctx } = await setup({ enableRunInBackground: false }) + const schema = ctx.tools.schemas().find(s => s.name === 'pwsh')! + expect(Object.keys(schema.parameters.properties as Record)) + .toEqual(['command', 'description', 'timeoutMs', 'workdir']) + expect(schema.description).toContain('Background execution is not available') + expect(schema.description).not.toContain('run_in_background') + + // Schema omission is advertising; execution must also enforce the opt-out. + const forced = await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'test command', run_in_background: true }) + expect(forced.isError).toBe(true) + expect(text(forced)).toContain('run_in_background is disabled for this deployment') + const foreground = await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'test command' }) + expect(foreground.isError).toBe(false) + }) + + it('applies the built-in background default when apply() receives a bare config', async () => { + // Bypasses the schemastery defaults on purpose: apply() must stand on its + // own `?? true` fallback when embedded programmatically without the schema. + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(BashEnvPlugin) + await ctx.plugin(FakeBash) + ToolPwsh.apply(ctx, {}) + const schema = ctx.tools.schemas()[0]! + expect(schema.parameters.properties).toHaveProperty('run_in_background') + expect(schema.description).toContain('task_output') + }) }) describe('UI presentation', () => { @@ -267,11 +520,11 @@ describe('UI presentation', () => { const { ctx, bash } = await setup() bash.handler = () => runResult('hi\n') const args = { command: 'Write-Output hi', description: 'say hi' } - const result = await call(ctx, 'pwsh', args, { agent: agent('/w') }) + const result = await call(ctx, 'pwsh', args) const view = ctx.tools.get('pwsh')?.presentResult?.(args, result) expect(view).toEqual({ card: 'generic', - content: [{ type: 'text', text: '```console\nhi\n[exit code: 0]\n```' }], + content: [{ type: 'text', text: '```console\nhi\n```' }], }) }) @@ -294,3 +547,75 @@ describe('UI presentation', () => { expect(definition?.presentResult?.(args, image as never)).toBeUndefined() }) }) + +describe('renderPwshProcessRead', () => { + const base: BashProcessRead = { delta: 'out\n', lossy: false } + + it('returns the delta verbatim for a lossless read', () => { + expect(renderPwshProcessRead(base)).toBe('out\n') + expect(renderPwshProcessRead({ delta: '', lossy: false })).toBe('') + }) + + it('appends the loss notice with the available spill paths', () => { + expect(renderPwshProcessRead({ ...base, lossy: true, stdoutSpillPath: 'C:\\spill\\out.log' })) + .toBe('out\n[some output was dropped from memory; full output: C:\\spill\\out.log]') + expect(renderPwshProcessRead({ + ...base, + lossy: true, + stdoutSpillPath: 'C:\\spill\\out.log', + stderrSpillPath: 'C:\\spill\\err.log', + })) + .toBe('out\n[some output was dropped from memory; full output: C:\\spill\\out.log, C:\\spill\\err.log]') + }) + + it('reports (unavailable) when a lossy read has no safe spill path', () => { + expect(renderPwshProcessRead({ ...base, lossy: true })) + .toBe('out\n[some output was dropped from memory; full output: (unavailable)]') + }) + + it('an empty lossy delta is the notice alone', () => { + expect(renderPwshProcessRead({ delta: '', lossy: true, stderrSpillPath: 'C:\\spill\\err.log' })) + .toBe('[some output was dropped from memory; full output: C:\\spill\\err.log]') + }) + + it('inserts the separating newline only when the delta lacks one', () => { + expect(renderPwshProcessRead({ delta: 'tail', lossy: true })) + .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]') + expect(renderPwshProcessRead({ delta: 'tail\n', lossy: true })) + .toBe('tail\n[some output was dropped from memory; full output: (unavailable)]') + }) +}) + +describe('processOutcome', () => { + function settled(over: Partial): BashProcess { + return { + status: 'completed', + exitCode: 0, + signal: null, + done: Promise.resolve(), + readOutput: () => ({ delta: '', lossy: false }), + kill: () => false, + ...over, + } + } + + it('maps a signal-killed process to killed with the signal detail', () => { + expect(processOutcome(settled({ status: 'killed', signal: 'SIGTERM' }))) + .toEqual({ status: 'killed', detail: 'signal: SIGTERM' }) + }) + + it('maps a killed process without a recorded signal (kill raced exit / spawn failure)', () => { + expect(processOutcome(settled({ status: 'killed', exitCode: null }))) + .toEqual({ status: 'killed', detail: 'killed before exit' }) + }) + + it('maps a completed process to its exit code', () => { + expect(processOutcome(settled({ exitCode: 3 }))) + .toEqual({ status: 'completed', detail: 'exit code: 3' }) + }) + + it('defensively reads a null exit code as 0 (handle shapes from other executors)', () => { + expect(processOutcome(settled({ exitCode: null }))) + .toEqual({ status: 'completed', detail: 'exit code: 0' }) + }) +}) diff --git a/packages/bash/tool-pwsh/tsconfig.json b/packages/bash/tool-pwsh/tsconfig.json index 2811462193..61b2c69448 100644 --- a/packages/bash/tool-pwsh/tsconfig.json +++ b/packages/bash/tool-pwsh/tsconfig.json @@ -26,14 +26,14 @@ { "path": "../../core/agent" }, - { - "path": "../../session-persistence/session-persistence" - }, { "path": "../../bash/bash" }, { - "path": "../../util/paths" + "path": "../../bash/bash-env" + }, + { + "path": "../../tasks/tasks" }, { "path": "../../core/system-prompt" From 96cf8a2fbc1fa439653fd6446786c24fe64e8010 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 14:18:42 +0800 Subject: [PATCH 09/61] chore(compositions): mount bash-env and the pwsh tool in shipped and demo compositions --- apps/cli/composition.md | 3 + apps/cli/config/base.cordis.yml | 3 + apps/cli/package.json | 1 + apps/cli/src/web.ts | 2 +- apps/cli/tsconfig.json | 3 + examples/acp-agent/tests/acp.snapshot.ts | 6 ++ .../tests/fixtures/bash/tool-pwsh/cordis.yml | 27 ++++++++ .../tests/fixtures/bash/tool-pwsh/driver.ts | 67 +++++++++++++++++++ .../acp-agent/tests/pwsh.cordis.snapshot.yml | 37 ++++++++++ examples/acp-agent/tests/pwsh.cordis.yml | 36 ++++++++++ examples/package.json | 3 + .../agent-spine-demo/README.i18n.yaml | 4 +- packages/examples/agent-spine-demo/README.md | 2 +- .../examples/agent-spine-demo/README.zh.md | 2 +- .../examples/agent-spine-demo/package.json | 3 + .../examples/agent-spine-demo/src/index.ts | 4 +- .../examples/agent-spine-demo/tsconfig.json | 3 + 17 files changed, 200 insertions(+), 6 deletions(-) create mode 100644 examples/acp-agent/tests/fixtures/bash/tool-pwsh/cordis.yml create mode 100644 examples/acp-agent/tests/fixtures/bash/tool-pwsh/driver.ts create mode 100644 examples/acp-agent/tests/pwsh.cordis.snapshot.yml create mode 100644 examples/acp-agent/tests/pwsh.cordis.yml diff --git a/apps/cli/composition.md b/apps/cli/composition.md index c4deb098c4..54755185ab 100644 --- a/apps/cli/composition.md +++ b/apps/cli/composition.md @@ -54,6 +54,8 @@ flowchart LR cfg --> plugin_tui_approval plugin_tui_permission["permission
@deepseek-ai/dsh-permission"] cfg --> plugin_tui_permission + plugin_tui_bash_env["bash-env
@deepseek-ai/dsh-bash-env"] + cfg --> plugin_tui_bash_env plugin_tui_tool_bash["tool-bash
@deepseek-ai/dsh-tool-bash"] cfg --> plugin_tui_tool_bash plugin_tui_tool_tasks["tool-tasks
@deepseek-ai/dsh-tool-tasks"] @@ -165,6 +167,7 @@ flowchart LR | `bash-sandbox` | `@deepseek-ai/dsh-bash-sandbox` | | `approval` | `@deepseek-ai/dsh-user-approval` | | `permission` | `@deepseek-ai/dsh-permission` | +| `bash-env` | `@deepseek-ai/dsh-bash-env` | | `tool-bash` | `@deepseek-ai/dsh-tool-bash` | | `tool-tasks` | `@deepseek-ai/dsh-tool-tasks` | | `fs-policy` | `@deepseek-ai/dsh-fs-policy` | diff --git a/apps/cli/config/base.cordis.yml b/apps/cli/config/base.cordis.yml index df7ed94258..a3d0dce332 100644 --- a/apps/cli/config/base.cordis.yml +++ b/apps/cli/config/base.cordis.yml @@ -174,6 +174,9 @@ sandbox: danger-full-access approval: never +- id: bash-env + name: '@deepseek-ai/dsh-bash-env' + - id: tool-bash name: '@deepseek-ai/dsh-tool-bash' diff --git a/apps/cli/package.json b/apps/cli/package.json index a6be4e9d90..710ba1f61c 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -23,6 +23,7 @@ "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-app-boot": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", + "@deepseek-ai/dsh-bash-env": "workspace:^", "@deepseek-ai/dsh-bash-sandbox": "workspace:^", "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/dsh-client-hmr": "workspace:^", diff --git a/apps/cli/src/web.ts b/apps/cli/src/web.ts index 4fbfba4d8d..4af7a42013 100644 --- a/apps/cli/src/web.ts +++ b/apps/cli/src/web.ts @@ -11,7 +11,7 @@ import type { Context } from 'cordis' import { addHarnessSourceSection, resolveConfigPath } from '@deepseek-ai/dsh-app-boot' import type {} from '@deepseek-ai/dsh-host-webserver' import type {} from '@deepseek-ai/dsh-system-prompt' -import type {} from '@deepseek-ai/dsh-tool-bash' +import type {} from '@deepseek-ai/dsh-bash-env' import { AppCLIEntry } from './app-cli-entry.ts' // The shared core every `dsh` surface mounts, plus this surface's overlay over it. diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json index 2f995abf87..aafdf5ad9a 100644 --- a/apps/cli/tsconfig.json +++ b/apps/cli/tsconfig.json @@ -23,6 +23,9 @@ { "path": "../../packages/ui/app-boot" }, + { + "path": "../../packages/bash/bash-env" + }, { "path": "../../packages/bash/tool-bash" }, diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index 326a7ee0c0..f191b5ce1b 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -154,6 +154,12 @@ const SCENARIOS: Scenario[] = [ configPath: PTY_CONFIG, }, { name: 'bash-tool-turn', hasModelTurn: true, recorded: true }, + // The pwsh-tool-turn scenario is NOT registered yet: its overlay + // (pwsh.cordis.yml / pwsh.cordis.snapshot.yml) swaps the bundle's bash tool + // for the PowerShell twin, so its header class needs its own prompt/tool + // sidecars and a recorded transcript. Both require a keyed environment + // (`test:snapshot:record`); the composition ships so the scenario can be + // registered and recorded in one keyed pass. { name: 'todo-write', hasModelTurn: true, recorded: true }, { name: 'skill-load', diff --git a/examples/acp-agent/tests/fixtures/bash/tool-pwsh/cordis.yml b/examples/acp-agent/tests/fixtures/bash/tool-pwsh/cordis.yml new file mode 100644 index 0000000000..c152b6ca67 --- /dev/null +++ b/examples/acp-agent/tests/fixtures/bash/tool-pwsh/cordis.yml @@ -0,0 +1,27 @@ +# Minimal tool-pwsh composition: real app boot path, real pwsh executor, real +# foreground + background tool calls; driven by the package's loader.spec.ts. +- id: system-prompt + name: '@deepseek-ai/dsh-system-prompt' + +- id: tools + name: '@deepseek-ai/dsh-tools' + +- id: subprocess + name: '@deepseek-ai/dsh-subprocess-local' + +- id: bash + name: '@deepseek-ai/dsh-pwsh-local' + config: + graceMs: 200 + +- id: bash-env + name: '@deepseek-ai/dsh-bash-env' + +- id: tasks + name: '@deepseek-ai/dsh-tasks-local' + +- id: tool-tasks + name: '@deepseek-ai/dsh-tool-tasks' + +- id: tool-pwsh + name: '@deepseek-ai/dsh-tool-pwsh' diff --git a/examples/acp-agent/tests/fixtures/bash/tool-pwsh/driver.ts b/examples/acp-agent/tests/fixtures/bash/tool-pwsh/driver.ts new file mode 100644 index 0000000000..9899bfcd17 --- /dev/null +++ b/examples/acp-agent/tests/fixtures/bash/tool-pwsh/driver.ts @@ -0,0 +1,67 @@ +#!/usr/bin/env node +/** + * Test driver: boot the tool-pwsh Loader composition, execute one real + * foreground and one real background pwsh command through the tool registry, + * and persist the observed model-visible output to `./pwsh-loader-report.json` + * for the package spec's inspect step. + */ + +import { writeFile } from 'node:fs/promises' +import { boot, resolveConfigPath } from '@deepseek-ai/dsh-app-boot' +import { CallId } from '@deepseek-ai/dsh-llm' + +const configPath = process.argv[2] +if (configPath === undefined) throw new Error('tool-pwsh driver requires a config path') + +const ctx = await boot('tool-pwsh-loader-smoke', resolveConfigPath(configPath, undefined)) +try { + const schema = ctx.tools.schemas().find(tool => tool.name === 'pwsh') + if (schema === undefined) throw new Error('pwsh tool not registered by the composition') + const prompt = (await ctx.systemPrompt.assemble()).sections.find(section => section.name === 'tool:pwsh') + + const foreground = await ctx.tools.execute({ + signal: new AbortController().signal, + callId: CallId('loader-fg'), + name: 'pwsh', + arguments: { command: 'Write-Output loader-ok', description: 'loader foreground' }, + }) + const foregroundText = foreground.content.filter(block => block.type === 'text').map(block => block.text).join('') + + const background = await ctx.tools.execute({ + signal: new AbortController().signal, + callId: CallId('loader-bg'), + name: 'pwsh', + arguments: { + command: 'Start-Sleep -Milliseconds 200; Write-Output loader-bg-ok', + description: 'loader background', + run_in_background: true, + }, + }) + const taskId = (background.value as { taskId: string }).taskId + + // The output delta and the terminal status can land in separate reads + // (Windows flushes the child pipe at exit), so accumulate both. + let backgroundText = '' + const deadline = Date.now() + 10_000 + while (Date.now() < deadline) { + const read = await ctx.tools.execute({ + signal: new AbortController().signal, + callId: CallId('loader-bg-read'), + name: 'task_output', + arguments: { task_id: taskId }, + }) + backgroundText += read.content.filter(block => block.type === 'text').map(block => block.text).join('') + if (backgroundText.includes('loader-bg-ok') && backgroundText.includes('[status: completed')) break + await new Promise(resolve => setTimeout(resolve, 50)) + } + + await writeFile('./pwsh-loader-report.json', JSON.stringify({ + schemaHasRunInBackground: Object.hasOwn(schema.parameters.properties as object, 'run_in_background'), + promptHasMarkerSection: prompt?.text.includes('Non-zero exits are reported as `[exit code: N]` markers') === true, + // Normalize PowerShell's platform line endings (CRLF on Windows, LF elsewhere). + foregroundText: foregroundText.replace(/\r\n/g, '\n'), + backgroundText: backgroundText.replace(/\r\n/g, '\n'), + })) +} finally { + await ctx.fiber.dispose() +} diff --git a/examples/acp-agent/tests/pwsh.cordis.snapshot.yml b/examples/acp-agent/tests/pwsh.cordis.snapshot.yml new file mode 100644 index 0000000000..c52dbbaf57 --- /dev/null +++ b/examples/acp-agent/tests/pwsh.cordis.snapshot.yml @@ -0,0 +1,37 @@ +# Minimal keyless composition: real app, pwsh executor, and pwsh tool; replayed model. +- id: llm-replay + name: '@deepseek-ai/dsh-llm-replay' + config: + providers: + - id: deepseek-official + name: DeepSeek + models: + - id: deepseek-v4-pro + +- id: subprocess + name: '@deepseek-ai/dsh-subprocess-local' + +- id: bash + name: '@deepseek-ai/dsh-pwsh-local' + +- id: bash-env + name: '@deepseek-ai/dsh-bash-env' + +- id: acp-agent + name: '@deepseek-ai/dsh-acp-demo' + config: + provider: deepseek-official + model: deepseek-v4-pro + persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + persistenceCompression: none + workspaceContext: false + skills: + enabled: false + toolTasks: false + goals: false + # The pwsh tool replaces the bundle's bash tool in this composition. + toolBash: false + persona: You are a concise snapshot agent working in {{cwd}}. + +- id: tool-pwsh + name: '@deepseek-ai/dsh-tool-pwsh' diff --git a/examples/acp-agent/tests/pwsh.cordis.yml b/examples/acp-agent/tests/pwsh.cordis.yml new file mode 100644 index 0000000000..46a595d7ff --- /dev/null +++ b/examples/acp-agent/tests/pwsh.cordis.yml @@ -0,0 +1,36 @@ +# Minimal live counterpart for the pwsh-tool-turn snapshot composition. +- id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek' + config: + apiKey: !!js process.env.DEEPSEEK_API_KEY + baseURL: !!js process.env.DEEPSEEK_BASE_URL + models: + - id: deepseek-v4-pro + +- id: subprocess + name: '@deepseek-ai/dsh-subprocess-local' + +- id: bash + name: '@deepseek-ai/dsh-pwsh-local' + +- id: bash-env + name: '@deepseek-ai/dsh-bash-env' + +- id: acp-agent + name: '@deepseek-ai/dsh-acp-demo' + config: + provider: deepseek-official + model: deepseek-v4-pro + persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" + workspaceContext: false + skills: + enabled: false + toolTasks: false + goals: false + # The pwsh tool replaces the bundle's bash tool in this composition. + toolBash: false + persona: You are a concise snapshot agent working in {{cwd}}. + +- id: tool-pwsh + name: '@deepseek-ai/dsh-tool-pwsh' diff --git a/examples/package.json b/examples/package.json index 97e7918361..7cbd7d2498 100644 --- a/examples/package.json +++ b/examples/package.json @@ -14,6 +14,7 @@ "@deepseek-ai/dsh-agent-spine-demo": "workspace:*", "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-bash": "workspace:*", + "@deepseek-ai/dsh-bash-env": "workspace:*", "@deepseek-ai/dsh-bash-local": "workspace:*", "@deepseek-ai/dsh-bash-sandbox": "workspace:*", "@deepseek-ai/dsh-cli-demo": "workspace:*", @@ -42,6 +43,7 @@ "@deepseek-ai/dsh-plan-mode": "workspace:*", "@deepseek-ai/dsh-pty": "workspace:*", "@deepseek-ai/dsh-pty-local": "workspace:*", + "@deepseek-ai/dsh-pwsh-local": "workspace:*", "@deepseek-ai/dsh-repeat-tool-guard": "workspace:*", "@deepseek-ai/dsh-repository-plugin": "workspace:*", "@deepseek-ai/dsh-sandbox-local": "workspace:*", @@ -81,6 +83,7 @@ "@deepseek-ai/dsh-tool-goal": "workspace:*", "@deepseek-ai/dsh-tool-lsp": "workspace:*", "@deepseek-ai/dsh-tool-pty": "workspace:*", + "@deepseek-ai/dsh-tool-pwsh": "workspace:*", "@deepseek-ai/dsh-tool-ralph": "workspace:*", "@deepseek-ai/dsh-tool-session-query": "workspace:*", "@deepseek-ai/dsh-tool-skill": "workspace:*", diff --git a/packages/examples/agent-spine-demo/README.i18n.yaml b/packages/examples/agent-spine-demo/README.i18n.yaml index ba1d18b7e7..8cbf8ce122 100644 --- a/packages/examples/agent-spine-demo/README.i18n.yaml +++ b/packages/examples/agent-spine-demo/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/examples/agent-spine-demo/README.md -README.md: 34d68b0791746c28528124853a4d8ea82b68138d -README.zh.md: 1b0a644595e35d8703d0600812268b0950b79182 +README.md: 7ea2f4afbe5d0bea62cf0fc2c7ecdd1496d20aef +README.zh.md: cb4202ac0e72db7c85967425671144e743f31b62 diff --git a/packages/examples/agent-spine-demo/README.md b/packages/examples/agent-spine-demo/README.md index 34d68b0791..7ea2f4afbe 100644 --- a/packages/examples/agent-spine-demo/README.md +++ b/packages/examples/agent-spine-demo/README.md @@ -59,7 +59,7 @@ import type { Config } from '@deepseek-ai/dsh-agent-spine-demo' // workspaceContext requires { maxBytes } or false; the other owner schemas supply defaults. ``` -The bundle FORWARDS each field to the child that owns it: `agents` and `maxParallelToolCalls` to `agent-loop` (`agents` defaults to `[]`; the cap defaults there), so each app supplies its own pre-created agents — TUI and headless apps pre-create `main`, while the ACP app creates agents on demand at `session/new`; `includeHarnessIdentity`, `persona`, and `toolOrder` to `dsh-system-prompt`; `tools` to the tool registry for its presentation mode; `sessionTitle` to the fallback title service; `skills.registry`, `skills.local`, and `skills.tool` to the skill registry, local provider, and model-facing consumer; the required `workspaceContext` choice to `dsh-workspace-context` (`{ maxBytes }` enables loading and `false` disables it); `invariants` to the invariant service; and `toolBash`/`toolTasks` to the two model-facing tool plugins the bundle owns. It always mounts `dsh-llm-retry`, while each leaf adapter owns its nested `retryPolicy`. Omitted `sessionTitle` uses the explicit example policy of 5 words, 40 fallback bytes, and 80 accepted-title bytes. A `goals` object opts into the persisted domain, model tools, and same-session driver while forwarding `goals.domain` and `goals.tool` to their owners; omission or `false` leaves the stack absent so headless callers retain one-turn settlement. Set `skills.enabled: false` to omit both the local provider and model-facing skill tool, set `toolBash: false` when another plugin owns the `bash` tool name, and set `toolTasks: false` to retain the task service for foreground producers without exposing `task_output` / `task_list` / `task_kill`. It resolves `dshHome` once through [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) and forwards that absolute value to tool-bash's managed environment and enabled local skill discovery. An absent top-level `dshHome` adopts `skills.local.dshHome`; supplying both with different resolved paths fails loudly. `toolBash.enableRunInBackground` controls only the bundled bash producer; independently loaded producers keep their own config. Workspace instructions register before the skill catalog so their session-prefix message renders first. App packages use `pickSpineConfig()` to copy only these bundle-owned fields. +The bundle FORWARDS each field to the child that owns it: `agents` and `maxParallelToolCalls` to `agent-loop` (`agents` defaults to `[]`; the cap defaults there), so each app supplies its own pre-created agents — TUI and headless apps pre-create `main`, while the ACP app creates agents on demand at `session/new`; `includeHarnessIdentity`, `persona`, and `toolOrder` to `dsh-system-prompt`; `tools` to the tool registry for its presentation mode; `sessionTitle` to the fallback title service; `skills.registry`, `skills.local`, and `skills.tool` to the skill registry, local provider, and model-facing consumer; the required `workspaceContext` choice to `dsh-workspace-context` (`{ maxBytes }` enables loading and `false` disables it); `invariants` to the invariant service; and `toolBash`/`toolTasks` to the two model-facing tool plugins the bundle owns. It always mounts `dsh-llm-retry`, while each leaf adapter owns its nested `retryPolicy`. Omitted `sessionTitle` uses the explicit example policy of 5 words, 40 fallback bytes, and 80 accepted-title bytes. A `goals` object opts into the persisted domain, model tools, and same-session driver while forwarding `goals.domain` and `goals.tool` to their owners; omission or `false` leaves the stack absent so headless callers retain one-turn settlement. Set `skills.enabled: false` to omit both the local provider and model-facing skill tool, set `toolBash: false` when another plugin owns the `bash` tool name, and set `toolTasks: false` to retain the task service for foreground producers without exposing `task_output` / `task_list` / `task_kill`. It resolves `dshHome` once through [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) and forwards that absolute value to the shared `bash-env` managed environment and enabled local skill discovery. An absent top-level `dshHome` adopts `skills.local.dshHome`; supplying both with different resolved paths fails loudly. `toolBash.enableRunInBackground` controls only the bundled bash producer; independently loaded producers keep their own config. Workspace instructions register before the skill catalog so their session-prefix message renders first. App packages use `pickSpineConfig()` to copy only these bundle-owned fields. For example, `{ invariants: { enabled: true, package_allowlist: ['^@deepseek-ai/dsh-'], package_blocklist: ['agent-loop$'] } }` keeps the package-owned companions mounted but suppresses the blocked owner. Blocklist matches override allowlist matches; see [`dsh-invariants`](../../support/invariants/README.md) for regex and lifecycle rules. diff --git a/packages/examples/agent-spine-demo/README.zh.md b/packages/examples/agent-spine-demo/README.zh.md index 1b0a644595..cb4202ac0e 100644 --- a/packages/examples/agent-spine-demo/README.zh.md +++ b/packages/examples/agent-spine-demo/README.zh.md @@ -59,7 +59,7 @@ import type { Config } from '@deepseek-ai/dsh-agent-spine-demo' // workspaceContext requires { maxBytes } or false; the other owner schemas supply defaults. ``` -组合包将每个字段转发给拥有它的子节点:`agents` 与 `maxParallelToolCalls` 交给 `agent-loop`(`agents` 默认为 `[]`,上限在该处默认),因此每个应用提供自己的预创建 agent;TUI 和无头应用预创建 `main`,ACP 应用则在 `session/new` 按需创建 agent;`includeHarnessIdentity`、`persona` 与 `toolOrder` 交给 `dsh-system-prompt`;`tools` 交给工具注册表以配置呈现模式;`sessionTitle` 交给后备标题服务;`skills.registry`、`skills.local` 与 `skills.tool` 分别交给 skill 注册表、本地提供方和面向模型的消费方;必填的 `workspaceContext` 选择交给 `dsh-workspace-context`(`{ maxBytes }` 启用加载,`false` 禁用);`invariants` 交给不变式服务;`toolBash`/`toolTasks` 交给组合包拥有的两个面向模型工具插件。组合包始终挂载 `dsh-llm-retry`,而每个叶节点适配器拥有自己的嵌套 `retryPolicy`。省略 `sessionTitle` 时采用显式示例策略:5 个词、40 个后备字节、80 个可接受标题字节。`goals` 对象会选用持久化领域、模型工具和同会话 Goal Round 驱动器,并将 `goals.domain` 与 `goals.tool` 转发给各自拥有者;省略或设为 `false` 会让整个栈缺席,使无头调用方继续以单轮次结算。设置 `skills.enabled: false` 会同时省略本地提供方和面向模型的 skill 工具;当另一个插件拥有 `bash` 工具名时设置 `toolBash: false`;设置 `toolTasks: false` 会保留供前台生产方使用的任务服务,但不公开 `task_output`/`task_list`/`task_kill`。它对 `dshHome` 只解析一次,解析通过 [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) 完成,并将所得绝对值转发给 tool-bash 的托管环境和已启用的本地 skill 发现。顶层 `dshHome` 缺席时采用 `skills.local.dshHome`;两者同时提供但解析后的路径不同会明确失败。`toolBash.enableRunInBackground` 只控制内置 bash 生产方;独立加载的生产方保留各自配置。工作区指令先于 skill 目录注册,因此其会话前缀消息先渲染。应用包使用 `pickSpineConfig()`,只复制这些由组合包拥有的字段。 +组合包将每个字段转发给拥有它的子节点:`agents` 与 `maxParallelToolCalls` 交给 `agent-loop`(`agents` 默认为 `[]`,上限在该处默认),因此每个应用提供自己的预创建 agent;TUI 和无头应用预创建 `main`,ACP 应用则在 `session/new` 按需创建 agent;`includeHarnessIdentity`、`persona` 与 `toolOrder` 交给 `dsh-system-prompt`;`tools` 交给工具注册表以配置呈现模式;`sessionTitle` 交给后备标题服务;`skills.registry`、`skills.local` 与 `skills.tool` 分别交给 skill 注册表、本地提供方和面向模型的消费方;必填的 `workspaceContext` 选择交给 `dsh-workspace-context`(`{ maxBytes }` 启用加载,`false` 禁用);`invariants` 交给不变式服务;`toolBash`/`toolTasks` 交给组合包拥有的两个面向模型工具插件。组合包始终挂载 `dsh-llm-retry`,而每个叶节点适配器拥有自己的嵌套 `retryPolicy`。省略 `sessionTitle` 时采用显式示例策略:5 个词、40 个后备字节、80 个可接受标题字节。`goals` 对象会选用持久化领域、模型工具和同会话 Goal Round 驱动器,并将 `goals.domain` 与 `goals.tool` 转发给各自拥有者;省略或设为 `false` 会让整个栈缺席,使无头调用方继续以单轮次结算。设置 `skills.enabled: false` 会同时省略本地提供方和面向模型的 skill 工具;当另一个插件拥有 `bash` 工具名时设置 `toolBash: false`;设置 `toolTasks: false` 会保留供前台生产方使用的任务服务,但不公开 `task_output`/`task_list`/`task_kill`。它对 `dshHome` 只解析一次,解析通过 [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) 完成,并将所得绝对值转发给共享 `bash-env` 的托管环境和已启用的本地 skill 发现。顶层 `dshHome` 缺席时采用 `skills.local.dshHome`;两者同时提供但解析后的路径不同会明确失败。`toolBash.enableRunInBackground` 只控制内置 bash 生产方;独立加载的生产方保留各自配置。工作区指令先于 skill 目录注册,因此其会话前缀消息先渲染。应用包使用 `pickSpineConfig()`,只复制这些由组合包拥有的字段。 例如,`{ invariants: { enabled: true, package_allowlist: ['^@deepseek-ai/dsh-'], package_blocklist: ['agent-loop$'] } }` 会让包拥有的配套插件保持挂载,但抑制被阻止的拥有者。Blocklist 匹配优先于 allowlist 匹配;正则表达式与生命周期规则见 [`dsh-invariants`](../../support/invariants/README.md)。 diff --git a/packages/examples/agent-spine-demo/package.json b/packages/examples/agent-spine-demo/package.json index 82178c48de..10c6ce7e55 100644 --- a/packages/examples/agent-spine-demo/package.json +++ b/packages/examples/agent-spine-demo/package.json @@ -43,6 +43,7 @@ "@deepseek-ai/dsh-skill-local": "^0.0.1", "@deepseek-ai/dsh-system-prompt": "^0.0.1", "@deepseek-ai/dsh-tasks-local": "^0.0.1", + "@deepseek-ai/dsh-bash-env": "^0.0.1", "@deepseek-ai/dsh-tool-bash": "^0.0.1", "@deepseek-ai/dsh-tool-goal": "^0.0.1", "@deepseek-ai/dsh-tool-skill": "^0.0.1", @@ -55,6 +56,7 @@ "@cordisjs/plugin-timer": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-bash-env": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", "@deepseek-ai/dsh-bash-sandbox": "workspace:^", "@deepseek-ai/dsh-fs-local": "workspace:^", @@ -77,6 +79,7 @@ "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tasks": "workspace:^", "@deepseek-ai/dsh-tasks-local": "workspace:^", + "@deepseek-ai/dsh-bash-env": "workspace:^", "@deepseek-ai/dsh-tool-bash": "workspace:^", "@deepseek-ai/dsh-tool-fs": "workspace:^", "@deepseek-ai/dsh-tool-goal": "workspace:^", diff --git a/packages/examples/agent-spine-demo/src/index.ts b/packages/examples/agent-spine-demo/src/index.ts index 32e348bf75..30c51fc941 100644 --- a/packages/examples/agent-spine-demo/src/index.ts +++ b/packages/examples/agent-spine-demo/src/index.ts @@ -29,6 +29,7 @@ import * as agentInvariant from '@deepseek-ai/dsh-agent/invariant' import * as scopeInvariant from '@deepseek-ai/dsh-scope/invariant' import * as agentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant' import * as toolBash from '@deepseek-ai/dsh-tool-bash' +import * as bashEnv from '@deepseek-ai/dsh-bash-env' import * as workspaceContext from '@deepseek-ai/dsh-workspace-context' import * as toolSkill from '@deepseek-ai/dsh-tool-skill' import * as toolTasks from '@deepseek-ai/dsh-tool-tasks' @@ -234,7 +235,8 @@ export function apply(ctx: Context, config: Config): void { ctx.plugin(scopeInvariant) ctx.plugin(agentLoopInvariant) if (config.toolBash !== false) { - ctx.plugin(toolBash, Object.assign({}, config.toolBash, { dshHome })) + ctx.plugin(bashEnv, { dshHome }) + ctx.plugin(toolBash, config.toolBash ?? {}) } if (config.workspaceContext !== false) { ctx.plugin(workspaceContext, config.workspaceContext) diff --git a/packages/examples/agent-spine-demo/tsconfig.json b/packages/examples/agent-spine-demo/tsconfig.json index 670cd9a629..6a0091a6f6 100644 --- a/packages/examples/agent-spine-demo/tsconfig.json +++ b/packages/examples/agent-spine-demo/tsconfig.json @@ -68,6 +68,9 @@ { "path": "../../util/paths" }, + { + "path": "../../bash/bash-env" + }, { "path": "../../bash/tool-bash" }, From 4e62fea09532796abd0b5b819040bfc38ce22cbc Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 14:18:55 +0800 Subject: [PATCH 10/61] docs: record the pwsh/bash parity decision and refresh catalogs and bilingual pairs --- ...026-08-01-pwsh-tool-and-executor.i18n.yaml | 4 +- .../2026-08-01-pwsh-tool-and-executor.md | 4 +- .../2026-08-01-pwsh-tool-and-executor.zh.md | 4 +- ...2026-08-02-pwsh-tool-bash-parity.i18n.yaml | 6 ++ .../2026-08-02-pwsh-tool-bash-parity.md | 33 ++++++++ .../2026-08-02-pwsh-tool-bash-parity.zh.md | 33 ++++++++ .../2026-08-01-windows-pwsh-default.i18n.yaml | 4 +- .../2026-08-01-windows-pwsh-default.md | 14 ++-- .../2026-08-01-windows-pwsh-default.zh.md | 14 ++-- AGENTS.md | 2 +- docs/config-catalog.md | 34 ++++++--- docs/cordis-catalog/services.md | 6 +- docs/tool-catalog.md | 76 +------------------ packages/bash/README.i18n.yaml | 4 +- packages/bash/README.md | 5 +- packages/bash/README.zh.md | 5 +- packages/bash/pwsh-local/README.i18n.yaml | 4 +- packages/bash/pwsh-local/README.md | 3 +- packages/bash/pwsh-local/README.zh.md | 3 +- 19 files changed, 136 insertions(+), 122 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md create mode 100644 .agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md diff --git a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.i18n.yaml b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.i18n.yaml index 4ced84e22c..d4ec255235 100644 --- a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.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-01-pwsh-tool-and-executor.md -2026-08-01-pwsh-tool-and-executor.md: fd73e929804045d7b810a587c6f088b2f7cff9cc -2026-08-01-pwsh-tool-and-executor.zh.md: f55be1ad0e102311d09b8b7ee1a003778e679cb2 +2026-08-01-pwsh-tool-and-executor.md: 7206f8ffe6640f8499f8453c40ab5846b23112c6 +2026-08-01-pwsh-tool-and-executor.zh.md: 5a48adb79fed209d2d2ecb9514fd51538491f04c diff --git a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md index fd73e92980..7206f8ffe6 100644 --- a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md +++ b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.md @@ -13,7 +13,7 @@ The harness spoke one shell dialect on every platform: `bash`. Windows hosts cou Two new packages under `packages/bash/`: - **`@deepseek-ai/dsh-pwsh-local`** — a local implementation of the `ctx.bash` executor seam over `ctx.subprocess`, mirroring `dsh-bash-local` call-for-call: `resolve()` defaults and caps from config, `run()` fuses the config-clamped timeout with the caller's signal through one deadline, `start()` returns a consuming background handle whose processes belong to the subprocess service. The command string rides as ONE argv element to `pwsh -NoLogo -NoProfile -NonInteractive -Command`, so PowerShell parses it and no shell-quoting layer exists. Executable resolution (`resolvePwshPath`) is a pure function of `(configured, env, platform)`: explicit config first, then Windows probes PowerShell 7's install, PATH entries (quotes stripped), and Windows PowerShell 5.1, else a bare `pwsh` via PATH. -- **`@deepseek-ai/dsh-tool-pwsh`** — the minimal model-facing tool over `ctx.bash`, PowerShell-dialect by contract: foreground only, no `run_in_background`, no sandbox escalation, managed `DSH_*` environment (`DSH_HOME`, `DSH_SHELL=1`, `DSH_SESSION_ID`), result markers `[exit code: N]` / `[timed out after …]` / `[killed by signal: …]`, and `terminal`/`generic` UI presenters. +- **`@deepseek-ai/dsh-tool-pwsh`** — the model-facing tool over `ctx.bash`, PowerShell-dialect by contract, mirroring `dsh-tool-bash` call-for-call minus the sandbox surface: foreground and `run_in_background` execution through the generic task runtime, managed `DSH_*` environment through the shared [`dsh-bash-env`](../feature/2026-08-02-pwsh-tool-bash-parity.md) registry, and the bash marker/truncation rendering story (a clean exit produces no marker). The parity decision supersedes this note's minimal-profile tool description. Windows vitest coverage is deliberately NOT part of this change: the repo's Windows CI lane owns build/static gates, and unit coverage runs on Linux, where both packages' suites run against a real `pwsh` (preinstalled on the GitHub-hosted runners) or self-skip when absent. The vitest `windowsUnsupportedPackages` exclusion narrows from `packages/bash/*` to the bash-requiring packages so the pwsh suites can also run natively on Windows dev machines. @@ -30,6 +30,6 @@ The roadmap beyond this decision — defaulting Windows hosts to `pwsh` (bash of ## Consequences - The bash executor seam gains a second, Windows-native implementation with an identical request/spec contract, so model-facing consumers beyond `tool-pwsh` (hooks bridges, in-process plugins) can run PowerShell without dialect shims. -- `tool-pwsh` is the model-visible Windows-first profile: no background tasks or escalation to mislead a model into assuming bash-tool parity, and the prompt guidance pins the `[exit code: N]` contract. +- `tool-pwsh` is the model-visible Windows-first shell tool: behaviorally interchangeable with the bash tool for foreground and background work (minus sandbox), with prompt guidance that states the marker contract precisely. - Windows semantics differ where the platform differs: forced termination reports exit 1 with no signal (so `signal`/`killed` status facts are POSIX-only), and PowerShell writes CRLF, which tests normalize. - The CLI gains two workspace dependencies and two tsconfig projects without mounting either plugin — the composition decision stays with the Windows-default proposal. diff --git a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.zh.md b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.zh.md index f55be1ad0e..5a48adb79f 100644 --- a/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.zh.md +++ b/.agents/notes/implemented/feature/2026-08-01-pwsh-tool-and-executor.zh.md @@ -13,7 +13,7 @@ harness 在每个平台只说一种 shell 方言:`bash`。Windows 主机只能 在 `packages/bash/` 下新增两个包: - **`@deepseek-ai/dsh-pwsh-local`** —— `ctx.bash` 执行器 seam 的本地实现,基于 `ctx.subprocess`,逐调用镜像 `dsh-bash-local`:`resolve()` 从配置默认化并设上限,`run()` 通过一个 deadline 融合配置夹取的超时与调用方信号,`start()` 返回消费式后台句柄,其进程归属于 subprocess 服务。命令字符串作为 ONE argv 元素传给 `pwsh -NoLogo -NoProfile -NonInteractive -Command`,由 PowerShell 解析,不存在 shell 引号层。可执行文件解析(`resolvePwshPath`)是 `(configured, env, platform)` 的纯函数:先显式配置,再在 Windows 上探测 PowerShell 7 安装位置、PATH 条目(剥离引号)与 Windows PowerShell 5.1,否则经 PATH 解析裸 `pwsh`。 -- **`@deepseek-ai/dsh-tool-pwsh`** —— 基于 `ctx.bash` 的最小面向模型工具,契约是 PowerShell 方言:仅前台,没有 `run_in_background`,没有沙箱升级,受管 `DSH_*` 环境(`DSH_HOME`、`DSH_SHELL=1`、`DSH_SESSION_ID`),结果标记 `[exit code: N]` / `[timed out after …]` / `[killed by signal: …]`,以及 `terminal`/`generic` UI presenter。 +- **`@deepseek-ai/dsh-tool-pwsh`** —— 基于 `ctx.bash` 的面向模型工具,契约是 PowerShell 方言,逐调用镜像 `dsh-tool-bash`、减去 sandbox 面:经通用任务运行时执行前台与 `run_in_background`,经共享 [`dsh-bash-env`](../feature/2026-08-02-pwsh-tool-bash-parity.md) 注册表管理 `DSH_*` 环境,以及 bash 的 marker/截断渲染故事(干净退出不产生 marker)。parity 决策取代了本 note 的最小画像工具描述。 Windows vitest 覆盖率刻意不属本次改动:仓库的 Windows CI 通道负责构建/静态门禁,单元覆盖在 Linux 上运行,两个包的套件在那里以真实 `pwsh` 运行(GitHub 托管 runner 预装)或缺失时自行跳过。vitest 的 `windowsUnsupportedPackages` 排除从 `packages/bash/*` 收窄为真正需要 bash 的包,使 pwsh 套件也能在 Windows 开发机上原生运行。 @@ -30,6 +30,6 @@ Windows vitest 覆盖率刻意不属本次改动:仓库的 Windows CI 通道 ## 后果 - bash 执行器 seam 有了第二个、Windows 原生的实现,请求/规范契约一致,因此 `tool-pwsh` 之外的面向模型消费方(hooks 桥、进程内插件)无需方言垫片即可运行 PowerShell。 -- `tool-pwsh` 是模型可见的 Windows 优先画像:没有后台任务或升级会让模型误以为与 bash 工具对等,提示词指导钉住 `[exit code: N]` 契约。 +- `tool-pwsh` 是模型可见的 Windows 优先 shell 工具:在前台与后台工作(减 sandbox)上与 bash 工具行为可互换,提示词指导精确陈述 marker 契约。 - Windows 语义在平台差异处不同:强制终止报告退出码 1 且无信号(因此 `signal`/`killed` 状态实情仅限 POSIX),PowerShell 输出 CRLF,测试做归一化。 - CLI 增加两个 workspace 依赖与两个 tsconfig 工程,但不挂载任一插件——组合决策留给 Windows 默认提案。 diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml new file mode 100644 index 0000000000..dcf840b868 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.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/feature/2026-08-02-pwsh-tool-bash-parity.md +2026-08-02-pwsh-tool-bash-parity.md: 3dcd1e8d4e7e6ea6841695f63012be184fa90f73 +2026-08-02-pwsh-tool-bash-parity.zh.md: 03aa9ed2109153d2e0426e7b680eb18c91f89aa7 diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md new file mode 100644 index 0000000000..3dcd1e8d4e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md @@ -0,0 +1,33 @@ +# Agent Note: pwsh tool bash parity + +Status: implemented + +English | [中文](2026-08-02-pwsh-tool-bash-parity.zh.md) + +## Problem + +The first Windows-native foundation shipped `dsh-tool-pwsh` as a deliberately minimal profile — foreground only, no background tasks, no managed-environment parity beyond three hardcoded `DSH_*` keys, and a marker story ("always `[exit code: N]`") that diverged from the bash tool's rendering without being declared. Review of that change found the model-visible contract drifting from the implementation: the description promised spill-path reporting the renderer never performed, the README claimed exports that did not exist and rendering the tool did not do, and the tool's own tests pinned the lossy behavior. The minimal profile also left the `DSH_*` contributor seam duplicated-by-absence: plugins contributing environment facts to `ctx.bashEnv` had no effect on pwsh calls. + +## Decision + +`dsh-tool-pwsh` now mirrors `dsh-tool-bash` call-for-call, minus the sandbox surface, and its model-visible text describes exactly that behavior: + +- **Rendering adopts the bash story verbatim**: stdout, a marked `[stderr]` section, truncation notices with spill paths, `(no output)` for an empty body, and exit markers only for non-zero exits — a clean exit produces no marker. The description and the `tool:pwsh` prompt section state this precisely ("Non-zero exits are reported as `[exit code: N]` markers"), deliberately not copying the bash prompt's "every result" phrasing, which its own renderer contradicts. +- **`run_in_background` is wired through the generic task runtime** exactly like the bash tool: preflight, owner registration, `task_output`/`task_kill` control, and the same outcome mapping. `pwsh-local`'s already-mirrored `start()` handle backs it. +- **The `DSH_*` environment is shared, not duplicated**: `BashEnvRegistry` moved out of `dsh-tool-bash` into a new tool-independent `@deepseek-ai/dsh-bash-env` package (`ctx.bashEnv` + built-ins + the session-persistence contributor), and both shell tools inject it. Contributors apply to pwsh calls exactly as they do to bash calls, resolving the bash tool's `FIXME(bash-env-ownership)`. +- **Windows reality is pinned where bash has no analog**: every command runs under a UTF-8 I/O preamble so the Windows PowerShell 5.1 fallback cannot garble non-ASCII output through the UTF-8-decoding collector, and the prompts teach that Windows forced termination settles as exit 1 without a signal marker. +- **Out of scope, unchanged**: sandbox escalation (waits for a Windows-confining executor), persistent PTY shells (backends are Linux/macOS-only; ConPTY is roadmap work), and pwsh-specific TUI/GUI presentation (generic/terminal cards stay; a PowerShell-aware terminal card with an exit pill is roadmap work). + +## Alternatives considered + +**Keep the minimal profile and fix only the claims.** Rejected: the review's core finding was that text contracts copied from bash drift without the corresponding implementation; a minimal tool plus accurate claims still leaves pwsh calls without background execution, without contributor parity, and with a divergent marker story that must be re-justified forever. + +**Extract a fully shared tool implementation base (abstract shell dialect, two thin leaves).** Considered and deferred: the bash-env extraction and the structural mirror (`render.ts`/`background.ts` twins) are the foundation it would rest on; a full base waits until a third dialect or the persistent-PTY twin makes the abstraction's shape observable. + +## Consequences + +- The bash and pwsh tools are now behaviorally interchangeable for foreground and background shell work (minus sandbox), and the pwsh prompt/description sentences are each backed by the renderer — the reviewer's grep-against-code check passes. +- `@deepseek-ai/dsh-bash-env` is a new shipped package; `dsh-tool-bash`'s `dshHome` config moved there, so compositions mounting the shell tools must also mount `bash-env` (the spine bundles do). +- Windows-only semantics (CRLF normalization, forced-termination exit-1/signal-null, POSIX-only self-signal) remain pinned by tests as before. +- The pwsh tool's per-file coverage gate rides on the scriptable fake-executor suite (`tests/tools.spec.ts`); the real-pwsh integration and Loader-composition suites self-skip where `pwsh` is absent, mirroring the bash suites' division of labor. +- The roadmap proposal's parity stage is delivered; its remaining stages are the Windows default composition and pwsh TUI/GUI rendering. diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md new file mode 100644 index 0000000000..03aa9ed210 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md @@ -0,0 +1,33 @@ +# Agent Note: pwsh 工具与 bash 对齐 + +Status: implemented + +[English](2026-08-02-pwsh-tool-bash-parity.md) | 中文 + +## 问题 + +首个 Windows 原生基础交付的 `dsh-tool-pwsh` 是刻意最小的画像——仅前台、无后台任务、受管环境只有三个硬编码 `DSH_*` 键、以及一个未声明就偏离 bash 工具的 marker 故事("恒打 `[exit code: N]`")。对该变更的 review 发现模型可见契约与实现脱节:描述承诺了渲染器从未执行的 spill 路径报告,README 宣称了不存在的导出与工具未做的渲染,工具自己的测试还钉死了有损行为。最小画像还让 `DSH_*` contributor seam 因缺席而重复:向 `ctx.bashEnv` 贡献环境事实的插件对 pwsh 调用毫无作用。 + +## 决策 + +`dsh-tool-pwsh` 现在逐调用镜像 `dsh-tool-bash`,减去 sandbox 面,其模型可见文本精确描述这一行为: + +- **渲染完全采用 bash 故事**:stdout、带标记的 `[stderr]` 段、带 spill 路径的截断通知、空体渲染 `(no output)`、退出 marker 仅限非零退出——干净退出不产生 marker。描述与 `tool:pwsh` prompt section 精确陈述这一点("Non-zero exits are reported as `[exit code: N]` markers"),刻意不复制 bash prompt 中与其自身渲染矛盾的 "every result" 措辞。 +- **`run_in_background` 经通用任务运行时接线**,与 bash 工具完全一致:预检、owner 注册、`task_output`/`task_kill` 控制与相同的结果映射。其背后是 `pwsh-local` 早已镜像好的 `start()` 句柄。 +- **`DSH_*` 环境共享而非复制**:`BashEnvRegistry` 从 `dsh-tool-bash` 迁入新的工具无关包 `@deepseek-ai/dsh-bash-env`(`ctx.bashEnv` + 内置事实 + session-persistence contributor),两个 shell 工具都注入它。contributor 对 pwsh 调用与 bash 调用一视同仁,并消化了 bash 工具的 `FIXME(bash-env-ownership)`。 +- **Windows 现实在 bash 无对应处钉死**:每条命令都在 UTF-8 I/O preamble 下运行,使 Windows PowerShell 5.1 兜底无法经 UTF-8 解码的 collector 破坏非 ASCII 输出;prompt 教授 Windows 强制终止以无 signal 的 exit 1 结算。 +- **范围外,不变**:sandbox 升级(等待 Windows-confining 执行器)、持久 PTY shell(后端仅限 Linux/macOS;ConPTY 属路线图)、pwsh 专属 TUI/GUI 呈现(维持 generic/terminal 卡;带退出 pill 的 PowerShell 感知 terminal 卡属路线图)。 + +## 备选方案 + +**保留最小画像,只修声明。** 否决:review 的核心发现是"从 bash 复制的文本契约在缺少对应实现时会漂移";最小工具加准确声明仍让 pwsh 调用没有后台执行、没有 contributor 对等、并留下一个必须永远重新辩护的偏离 marker 故事。 + +**提取完全共享的工具实现基座(抽象 shell 方言,两个薄叶子)。** 考虑后推迟:bash-env 提取与结构镜像(`render.ts`/`background.ts` 孪生)是它要立足的基础;在出现第三种方言或持久 PTY 孪生、让抽象的形态可观察之前,不做完整基座。 + +## 后果 + +- bash 与 pwsh 工具在前台与后台 shell 工作(减 sandbox)上行为可互换,pwsh 的 prompt/描述句每句都有渲染器背书——reviewer 的"拿代码 grep 对证"检查通过。 +- `@deepseek-ai/dsh-bash-env` 成为新的交付包;`dsh-tool-bash` 的 `dshHome` 配置迁往那里,因此挂载 shell 工具的组合也必须挂载 `bash-env`(spine bundle 已如此)。 +- Windows 专属语义(CRLF 归一化、强制终止 exit-1/signal-null、仅 POSIX 的自信号)一如既往由测试钉住。 +- pwsh 工具的 per-file 覆盖门禁由可脚本化的 fake-executor 套件(`tests/tools.spec.ts`)承担;真实 pwsh 的集成与 Loader 组合套件在无 `pwsh` 的宿主自跳过,与 bash 套件的分工一致。 +- 路线图提案的 parity 阶段已交付;其余阶段是 Windows 默认组合与 pwsh TUI/GUI 渲染。 diff --git a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.i18n.yaml b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.i18n.yaml index 882e7478d3..5e7f47f278 100644 --- a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.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/proposed/feature/2026-08-01-windows-pwsh-default.md -2026-08-01-windows-pwsh-default.md: 6f3e48f33d98b2d2da7bd288d42a0d2763163ba3 -2026-08-01-windows-pwsh-default.zh.md: 270fd8d95c85400c302540376932228a6023447c +2026-08-01-windows-pwsh-default.md: a310174b6864bb880070280835ccfd8623e26342 +2026-08-01-windows-pwsh-default.zh.md: 079c1e3cac789a5e3fa4d0bb889026b3fb69f78c diff --git a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.md b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.md index 6f3e48f33d..a310174b68 100644 --- a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.md +++ b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.md @@ -6,17 +6,16 @@ English | [中文](2026-08-01-windows-pwsh-default.zh.md) ## Problem -The harness's shipped execution profile is bash-first on every platform. Windows hosts must install a bash shim (WSL or Git-Bash) or fall back to the POSIX-only `dsh-bash-local` behavior; the model-facing bash tool teaches the bash dialect, and the TUI/Web surfaces render terminal output in bash-shaped expectations. The first Windows-native foundation shipped in the [pwsh executor and tool decision](../../implemented/feature/2026-08-01-pwsh-tool-and-executor.md): a PowerShell implementation of the `ctx.bash` seam and a minimal `pwsh` tool — but nothing yet defaults Windows hosts to them. +The harness's shipped execution profile is bash-first on every platform. Windows hosts must install a bash shim (WSL or Git-Bash) or fall back to the POSIX-only `dsh-bash-local` behavior; the model-facing bash tool teaches the bash dialect, and the TUI/Web surfaces render terminal output in bash-shaped expectations. The first Windows-native foundation shipped in the [pwsh executor and tool decision](../../implemented/feature/2026-08-01-pwsh-tool-and-executor.md): a PowerShell implementation of the `ctx.bash` seam and a parity `pwsh` tool — but nothing yet defaults Windows hosts to them. ## Proposal -Three follow-up stages, each independently shippable: +Two follow-up stages, each independently shippable. The former stage 2 (bash-tool parity twin) shipped with the [pwsh tool bash parity decision](../../implemented/feature/2026-08-02-pwsh-tool-bash-parity.md): `tool-pwsh` now mirrors `tool-bash` for foreground and background work minus the sandbox surface, shares the `DSH_*` environment through `dsh-bash-env`, and carries a keyless application snapshot of its assembled surface. 1. **Windows default composition** — the shipped CLI compositions mount `dsh-pwsh-local` as the `ctx.bash` executor and `dsh-tool-pwsh` as the model-facing shell tool on Windows hosts (bash unmounted there), while POSIX hosts keep the bash stack. This is a composition/roster decision in `base.cordis.yml` and the surface overlays, gated by platform; it makes the shipped Windows experience PowerShell-native end to end. -2. **Bash-tool parity twin** — `tool-pwsh` grows the bash tool's missing surface where Windows workflows prove it: `run_in_background` through the generic task runtime, and the persistence-side `DSH_SESSION_JSONL` environment fact. Sandbox escalation stays out until a Windows-confining executor exists. -3. **pwsh TUI/GUI rendering** — the TUI and Web surfaces render pwsh output with PowerShell-aware presentation (native path display, `$env:` facts), the counterpart of the bash terminal cards. This is where terminal/console rendering conventions get a PowerShell twin. +2. **pwsh TUI/GUI rendering** — the TUI and Web surfaces render pwsh output with PowerShell-aware presentation (native path display, `$env:` facts), the counterpart of the bash terminal cards. This is where terminal/console rendering conventions get a PowerShell twin. -The stages are deliberately sequenced: composition first (a Windows user gets PowerShell without choosing), then tool parity, then rendering. Nothing in this proposal changes POSIX behavior. +The stages are deliberately sequenced: composition first (a Windows user gets PowerShell without choosing), then rendering. Nothing in this proposal changes POSIX behavior. ## Alternatives considered @@ -31,11 +30,10 @@ The stages are deliberately sequenced: composition first (a Windows user gets Po - A Windows host running the shipped `dsh` TUI/Web gets `pwsh` as its shell tool and PowerShell as the `ctx.bash` executor without configuration, and `bash` is absent from the model-visible roster there. - POSIX hosts are byte-for-byte unaffected (same roster, same executor). - The shipped-composition e2es assert the platform-gated roster on both families. -- Stage 2 lands with task-runtime integration tests; stage 3 lands with TUI/Web rendering snapshots for pwsh output. +- Stage 1 lands with the keyless pwsh-tool snapshot already in place from the parity change; stage 2 lands with TUI/Web rendering snapshots for pwsh output. ## Risks - **Bash-dependent composition rows** — any shipped plugin that assumes `bash` semantics (hook bridges executing shell hooks, workspace tooling) must be audited per stage; the audit may force a staged rollout rather than one switch. -- **Tool-behavior drift** — a minimal `tool-pwsh` that never grows parity invites models to write bash-shaped commands; the prompt guidance and dialect contract mitigate this only if the twin keeps pace. - **Windows CI coverage gap** — unit coverage runs on Linux; Windows-only regressions in the pwsh stack surface through the Windows build/static lane and e2es, which must be extended per stage rather than assumed. -- **Rendering conventions** — a PowerShell twin for terminal cards is a UI design decision with snapshot surface; deferring it (stage 3) keeps stage 1 shippable without UI churn. +- **Rendering conventions** — a PowerShell twin for terminal cards is a UI design decision with snapshot surface; deferring it (stage 2) keeps stage 1 shippable without UI churn. diff --git a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.zh.md b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.zh.md index 270fd8d95c..079c1e3cac 100644 --- a/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.zh.md +++ b/.agents/notes/proposed/feature/2026-08-01-windows-pwsh-default.zh.md @@ -6,17 +6,16 @@ Status: proposed ## 问题 -harness 交付的执行画像在每个平台都是 bash 优先。Windows 主机必须安装 bash 垫片(WSL 或 Git-Bash),或退回到仅 POSIX 的 `dsh-bash-local` 行为;面向模型的 bash 工具教的是 bash 方言,TUI/Web 表面以 bash 形状的预期渲染终端输出。第一块 Windows 原生基础已随 [pwsh 执行器与工具决策](../../implemented/feature/2026-08-01-pwsh-tool-and-executor.md) 交付:`ctx.bash` seam 的 PowerShell 实现与最小化的 `pwsh` 工具——但还没有任何东西让 Windows 主机默认使用它们。 +harness 交付的执行画像在每个平台都是 bash 优先。Windows 主机必须安装 bash 垫片(WSL 或 Git-Bash),或退回到仅 POSIX 的 `dsh-bash-local` 行为;面向模型的 bash 工具教的是 bash 方言,TUI/Web 表面以 bash 形状的预期渲染终端输出。第一块 Windows 原生基础已随 [pwsh 执行器与工具决策](../../implemented/feature/2026-08-01-pwsh-tool-and-executor.md) 交付:`ctx.bash` seam 的 PowerShell 实现与对等的 `pwsh` 工具——但还没有任何东西让 Windows 主机默认使用它们。 ## 提案 -三个阶段,各自可独立交付: +两个阶段,各自可独立交付。原阶段 2(bash 工具对等孪生)已随 [pwsh 工具与 bash 对齐决策](../../implemented/feature/2026-08-02-pwsh-tool-bash-parity.md) 交付:`tool-pwsh` 现在在前台与后台工作(减 sandbox 面)上镜像 `tool-bash`,通过 `dsh-bash-env` 共享 `DSH_*` 环境,并携带其组装表面的 keyless 应用快照。 1. **Windows 默认组合**——交付的 CLI 组合在 Windows 主机上挂载 `dsh-pwsh-local` 作为 `ctx.bash` 执行器、`dsh-tool-pwsh` 作为面向模型的 shell 工具(那里不挂载 bash),POSIX 主机保持 bash 栈。这是 `base.cordis.yml` 与 surface 覆盖层里按平台门控的组合/清单决策;它让交付的 Windows 体验端到端 PowerShell 原生。 -2. **bash 工具对等孪生**——在 Windows 工作流证明需要的地方,`tool-pwsh` 补齐 bash 工具缺失的表面:经由通用任务运行时的 `run_in_background`,以及持久化侧 `DSH_SESSION_JSONL` 环境实情。在出现 Windows 约束执行器之前,沙箱升级保持缺席。 -3. **pwsh TUI/GUI 渲染**——TUI 与 Web 表面以 PowerShell 感知的呈现渲染 pwsh 输出(原生路径显示、`$env:` 实情),即 bash 终端卡片的对应物。这是终端/控制台渲染约定获得 PowerShell 孪生的地方。 +2. **pwsh TUI/GUI 渲染**——TUI 与 Web 表面以 PowerShell 感知的呈现渲染 pwsh 输出(原生路径显示、`$env:` 实情),即 bash 终端卡片的对应物。这是终端/控制台渲染约定获得 PowerShell 孪生的地方。 -各阶段刻意排序:先组合(Windows 用户无需选择即获得 PowerShell),再工具对等,最后渲染。本提案不改变任何 POSIX 行为。 +各阶段刻意排序:先组合(Windows 用户无需选择即获得 PowerShell),再渲染。本提案不改变任何 POSIX 行为。 ## 备选方案 @@ -31,11 +30,10 @@ harness 交付的执行画像在每个平台都是 bash 优先。Windows 主机 - 运行交付版 `dsh` TUI/Web 的 Windows 主机无需配置即获得 `pwsh` 作为其 shell 工具、PowerShell 作为 `ctx.bash` 执行器,且那里的模型可见清单中没有 `bash`。 - POSIX 主机逐字节不受影响(清单相同,执行器相同)。 - 交付组合 e2e 在两个平台族上断言按平台门控的清单。 -- 阶段 2 附带任务运行时集成测试落地;阶段 3 附带 pwsh 输出的 TUI/Web 渲染快照落地。 +- 阶段 1 落地时,parity 变更带来的 keyless pwsh 工具快照已经就位;阶段 2 附带 pwsh 输出的 TUI/Web 渲染快照落地。 ## 风险 - **依赖 bash 的组合行**——任何假设 bash 语义的交付插件(执行 shell hooks 的 hooks 桥、工作区工具)必须按阶段审计;审计可能迫使分阶段推出而非一次切换。 -- **工具行为漂移**——永远不补齐对等的 `tool-pwsh` 会诱使模型写 bash 形状的命令;只有当孪生跟上节奏时,提示词指导与方言契约才能缓解这一点。 - **Windows CI 覆盖缺口**——单元覆盖在 Linux 上运行;pwsh 栈里仅 Windows 的回归通过 Windows 构建/静态通道与 e2e 浮出,必须按阶段扩展而不是想当然。 -- **渲染约定**——终端卡片的 PowerShell 孪生是带快照表面的 UI 设计决策;把它延期(阶段 3)让阶段 1 无需 UI 翻动即可交付。 +- **渲染约定**——终端卡片的 PowerShell 孪生是带快照表面的 UI 设计决策;把它延期(阶段 2)让阶段 1 无需 UI 翻动即可交付。 diff --git a/AGENTS.md b/AGENTS.md index b7128ff89d..9d798a4c8a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ packages/ @deepseek-ai/dsh- workspaces at packages/// core/ product API spine: session, system-prompt, tools, agent, agent-loop typert/ type graph generator, loader, and runtime registry llm/ LLM seam + DeepSeek adapters (direct-fetch + pi-ai design twin) - bash/ bash executor seam + local impl + model-facing bash tools + bash/ bash executor seam + local/pwsh impls + model-facing shell tools subprocess/ subprocess seam + local process-tree impl pty/ persistent PTY seam/backend/tools fs/ filesystem seam + local impl + policy gate + read/write/edit tools diff --git a/docs/config-catalog.md b/docs/config-catalog.md index f3c1fc5726..c9790212af 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -192,7 +192,19 @@ export interface GoalConfig { Depends on: [`AgentLoopConfig`](#deepseek-aidsh-agent-loop) · [`GoalDomainConfig`](#deepseek-aidsh-goal) · [`InvariantConfig`](#deepseek-aidsh-invariants) · [`SessionTitleConfig`](#deepseek-aidsh-session-title) · [`SkillLocal`](../packages/skill/skill-local/src/index.ts) · [`SkillRegistryConfig`](#deepseek-aidsh-skill) · [`SystemPromptConfig`](#deepseek-aidsh-system-prompt) · [`toolBash`](../packages/bash/tool-bash/src/index.ts) · [`toolGoal`](../packages/goal/tool-goal/src/index.ts) · [`ToolsConfig`](#deepseek-aidsh-tools) · [`toolSkill`](../packages/skill/tool-skill/src/index.ts) · [`toolTasks`](../packages/tasks/tool-tasks/src/index.ts) · [`workspaceContext`](../packages/context/workspace-context/src/index.ts) -Source: [`packages/examples/agent-spine-demo/src/index.ts:89`](../packages/examples/agent-spine-demo/src/index.ts) +Source: [`packages/examples/agent-spine-demo/src/index.ts:90`](../packages/examples/agent-spine-demo/src/index.ts) + +## `@deepseek-ai/dsh-bash-env` + +```ts config-catalog +/** Plugin config (all optional — the built-in facts resolve without defaults). */ +export interface Config { + /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */ + dshHome?: string +} +``` + +Source: [`packages/bash/bash-env/src/index.ts:29`](../packages/bash/bash-env/src/index.ts) ## `@deepseek-ai/dsh-bash-local` @@ -991,7 +1003,7 @@ export interface Config { } ``` -Source: [`packages/bash/pwsh-local/src/index.ts:44`](../packages/bash/pwsh-local/src/index.ts) +Source: [`packages/bash/pwsh-local/src/index.ts:55`](../packages/bash/pwsh-local/src/index.ts) ## `@deepseek-ai/dsh-repeat-tool-guard` @@ -1692,19 +1704,17 @@ Source: [`packages/llm/token-meter/src/types.ts:12`](../packages/llm/token-meter ## `@deepseek-ai/dsh-tool-bash` -Requires: `tools` · `bash` · `systemPrompt` +Requires: `tools` · `bash` · `systemPrompt` · `bashEnv` ```ts config-catalog -/** Configuration for the bash tool and its managed child environment. */ +/** Configuration for the bash tool. */ export interface Config { /** Expose `run_in_background` (default true); disabled calls are also rejected. */ enableRunInBackground?: boolean - /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */ - dshHome?: string } ``` -Source: [`packages/bash/tool-bash/src/index.ts:41`](../packages/bash/tool-bash/src/index.ts) +Source: [`packages/bash/tool-bash/src/index.ts:34`](../packages/bash/tool-bash/src/index.ts) ## `@deepseek-ai/dsh-tool-bash-persistent` @@ -1844,17 +1854,17 @@ Source: [`packages/pty/tool-pty/src/index.ts:35`](../packages/pty/tool-pty/src/i ## `@deepseek-ai/dsh-tool-pwsh` -Requires: `tools` · `bash` · `systemPrompt` +Requires: `tools` · `bash` · `systemPrompt` · `bashEnv` ```ts config-catalog -/** Plugin config (currently empty; kept as a schema so deployments can grow it). */ +/** Configuration for the pwsh tool. */ export interface Config { - /** DeepSeek Harness home directory exposed as `DSH_HOME`; defaults to `$DSH_HOME` or `~/.dsh`. */ - dshHome?: string + /** Expose `run_in_background` (default true); disabled calls are also rejected. */ + enableRunInBackground?: boolean } ``` -Source: [`packages/bash/tool-pwsh/src/index.ts:31`](../packages/bash/tool-pwsh/src/index.ts) +Source: [`packages/bash/tool-pwsh/src/index.ts:41`](../packages/bash/tool-pwsh/src/index.ts) ## `@deepseek-ai/dsh-tool-ralph` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 22bc6343ea..2c6ff22cc4 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -297,7 +297,7 @@ Source: [`packages/bash/bash/src/index.ts:51`](../../packages/bash/bash/src/inde ## `ctx.bashEnv` — `BashEnvRegistry` -Registry (`ctx.bashEnv`) for trusted, per-execution `DSH_*` variables. The namespace is rebuilt for every model bash call: ambient `DSH_*` values are discarded by the executor, then the registry's current snapshot is injected. Built-in shell facts remain owned by the registry itself while plugins can register additional, enumerable facts with effect-scoped disposal. +Registry (`ctx.bashEnv`) for trusted, per-execution `DSH_*` variables. The namespace is rebuilt for every model shell call: ambient `DSH_*` values are discarded by the executor, then the registry's current snapshot is injected. Built-in shell facts remain owned by the registry itself while plugins can register additional, enumerable facts with effect-scoped disposal. ```ts cordis-catalog /** @@ -309,7 +309,7 @@ Registry (`ctx.bashEnv`) for trusted, per-execution `DSH_*` variables. The names register(contributor: BashEnvContributor): () => void /** - * Build the trusted `DSH_*` snapshot for one bash tool execution. + * Build the trusted `DSH_*` snapshot for one shell tool execution. * @param execution - the current tool execution. * @returns an immutable environment overlay containing built-ins and current contributions. */ @@ -324,7 +324,7 @@ list(): BashEnvVariableInfo[] Types: [DshEnvironment](../core-data-structures/subprocess.md) · [ToolExecution](../core-data-structures/tools.md) -Source: [`packages/bash/tool-bash/src/index.ts:104`](../../packages/bash/tool-bash/src/index.ts) +Source: [`packages/bash/bash-env/src/index.ts:89`](../../packages/bash/bash-env/src/index.ts) ## `ctx.clientModuleHost` — `ClientModuleHostService` diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index a00a2876a8..7ae66b3d37 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -18,8 +18,8 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`, `ctx.userInteraction` | `tool/call`, `tool/result after a UI/provider answers the question` | - | ask_user_question pauses the tool call until the active UI provider returns a human answer. | | `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.codeRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/code-dispatch-start + tool/code-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated TypeScript SDK section, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`, `ctx.systemPrompt`, `ctx.userInteraction (execution time, opportunistic)` | `tool/call`, `plan/mode inactive on an approved review`, `tool/result` | - | exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-interaction seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary. | -| `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.bash`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | -| `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. | +| `@deepseek-ai/dsh-tool-bash` | - | `ctx.tools`, `ctx.bash`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | +| `@deepseek-ai/dsh-tool-pwsh` | - | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. | | `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect`, `cordis_mount`, `cordis_unmount` | `ctx.tools` | `tool/call`, `tool/result`, `process-local temporary Plugin lifecycle` | - | Not in any shipped tree (a deliberate opt-in — temporary Plugin code reaches the real runtime, see .agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins created by cordis_mount may register ADDITIONAL model-visible tools until unmounted or DSH restarts; a full changed request header logs those tool-set changes. | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.tools`, `ctx.pty`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`, `ctx.fs` | `tool/call`, `fs/observed after successful file operations`, `tool/result` | - | Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal surface. | @@ -166,82 +166,10 @@ exit_plan_mode stays in the model-facing schema while planning is inactive so tr ## `@deepseek-ai/dsh-tool-bash` -### `bash` - -Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. - -```json -{ - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The bash command to execute." - }, - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - }, - "run_in_background": { - "type": "boolean", - "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." - } - }, - "required": [ - "command", - "description" - ] -} -``` - -Source: [`packages/bash/tool-bash/src/index.ts`](../packages/bash/tool-bash/src/index.ts) - The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. ## `@deepseek-ai/dsh-tool-pwsh` -### `pwsh` - -Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. Each call runs in a fresh pwsh process: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\...`); read environment variables with `$env:NAME`. Non-zero exits are reported as `[exit code: N]`. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. - -```json -{ - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The PowerShell command to execute." - }, - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"Get-Process\" → \"List running processes\"." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - } - }, - "required": [ - "command", - "description" - ] -} -``` - -Source: [`packages/bash/tool-pwsh/src/index.ts`](../packages/bash/tool-pwsh/src/index.ts) - The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. ## `@deepseek-ai/dsh-tool-cordis` diff --git a/packages/bash/README.i18n.yaml b/packages/bash/README.i18n.yaml index 0af14fda76..66cc852e04 100644 --- a/packages/bash/README.i18n.yaml +++ b/packages/bash/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/bash/README.md -README.md: e60ad9b0e4c48cf35a2601e7dec4d2d50807707b -README.zh.md: deb23ea820de40c99f0affd3726d9a49857039ea +README.md: ef82e9f4684ecf551ac7701d812088dd6b2ef6d0 +README.zh.md: 84ff244ec3d1ff5d385a3eb334e4cf9f1fe31e03 diff --git a/packages/bash/README.md b/packages/bash/README.md index e60ad9b0e4..ef82e9f468 100644 --- a/packages/bash/README.md +++ b/packages/bash/README.md @@ -2,13 +2,16 @@ English | [中文](README.zh.md) -The canonical three-package capability seam (see [capability seams](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)): an abstract executor interface, concrete implementations, and the model-facing tool that consumes it. All **product** packages. +The capability family spans the canonical executor seam, its implementations, the shared shell environment, and the model-facing tools. All **product** packages. | Package | Role | ctx key | |---|---|---| | `bash/` | Abstract bash executor seam (interface + vocabulary; sandbox result facts carry the [`sandbox/`](../sandbox/README.md) seam's mode/enforcement vocabulary, and the managed-env/output vocabulary is re-exported from the [`subprocess/`](../subprocess/README.md) seam) | `ctx.bash` | | `bash-local/` | Local `BashExecutor` implementation over the [`subprocess/`](../subprocess/README.md) service (command defaulting, deadlines, terminal env, background-read merge) | (registers `ctx.bash`) | | `bash-sandbox/` | Sandbox-consuming `BashExecutor` (wraps every command argv via `ctx.sandbox`, stamps denial/enforcement facts; extends `bash-local`'s mechanics) | (registers `ctx.bash`) | +| `pwsh-local/` | Local PowerShell `BashExecutor` implementation over the [`subprocess/`](../subprocess/README.md) service (executable resolution, UTF-8-pinned spawn, Windows termination semantics) | (registers `ctx.bash`) | +| `bash-env/` | Tool-independent managed `DSH_*` shell environment registry shared by the shell tools (built-in facts + effect-scoped contributors) | (registers `ctx.bashEnv`) | | `tool-bash/` | Model-facing `bash` schema; background processes register with the generic [`tasks/`](../tasks/README.md) runtime | (registers on `ctx.tools`) | +| `tool-pwsh/` | Model-facing PowerShell-dialect `pwsh` schema (behavior mirrors `tool-bash` minus the sandbox surface); background processes register with the generic [`tasks/`](../tasks/README.md) runtime | (registers on `ctx.tools`) | The interface lives at `bash/bash/`. `bash-sandbox` replacing `bash-local` without touching the interface or the tool is the split doing exactly what it exists for — a leaf `cordis.yml` picks one executor entry, plus a `ctx.sandbox` provider entry for the confined one (see [the acp-agent example's default composition](../../examples/acp-agent/)). diff --git a/packages/bash/README.zh.md b/packages/bash/README.zh.md index deb23ea820..84ff244ec3 100644 --- a/packages/bash/README.zh.md +++ b/packages/bash/README.zh.md @@ -2,13 +2,16 @@ [English](README.md) | 中文 -规范的三包能力 seam(见[能力 seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)):抽象执行器接口、具体实现,以及消费该接口的面向模型工具。这些全是**产品**包。 +能力家族横跨规范执行器 seam、其实现、共享 shell 环境与面向模型的工具。这些全是**产品**包。 | 包 | 职责 | ctx key | |---|---|---| | `bash/` | 抽象 bash 执行器 seam(接口 + 词汇;沙箱结果事实携带 [`sandbox/`](../sandbox/README.md) seam 的模式/强制执行词汇,受管环境/输出词汇则从 [`subprocess/`](../subprocess/README.md) seam 重导出) | `ctx.bash` | | `bash-local/` | 构建在 [`subprocess/`](../subprocess/README.md) 服务之上的本地 `BashExecutor` 实现(命令默认值补全、deadline、终端环境、后台读取合并) | (注册 `ctx.bash`) | | `bash-sandbox/` | 消费沙箱的 `BashExecutor`(通过 `ctx.sandbox` 包装每个命令 argv,标记拒绝/强制执行事实;扩展 `bash-local` 的机制) | (注册 `ctx.bash`) | +| `pwsh-local/` | 构建在 [`subprocess/`](../subprocess/README.md) 服务之上的本地 PowerShell `BashExecutor` 实现(可执行文件解析、UTF-8 固定 spawn、Windows 终止语义) | (注册 `ctx.bash`) | +| `bash-env/` | 工具无关的受管 `DSH_*` shell 环境注册表,由 shell 工具共享(内置事实 + 受 effect 作用域约束的 contributor) | (注册 `ctx.bashEnv`) | | `tool-bash/` | 面向模型的 `bash` schema;后台进程注册到通用 [`tasks/`](../tasks/README.md) 运行时 | (注册到 `ctx.tools`) | +| `tool-pwsh/` | 面向模型的 PowerShell 方言 `pwsh` schema(行为镜像 `tool-bash`,减去 sandbox 面);后台进程注册到通用 [`tasks/`](../tasks/README.md) 运行时 | (注册到 `ctx.tools`) | 接口位于 `bash/bash/`。以 `bash-sandbox` 替换 `bash-local`,同时不改动接口或工具,正是这种拆分存在的意义:叶级 `cordis.yml` 选择一个执行器插件条目;受限实现还需再选择一个 `ctx.sandbox` 提供方插件条目(见 [acp-agent 示例的默认组合](../../examples/acp-agent/))。 diff --git a/packages/bash/pwsh-local/README.i18n.yaml b/packages/bash/pwsh-local/README.i18n.yaml index 836ab2dd84..40455ff56b 100644 --- a/packages/bash/pwsh-local/README.i18n.yaml +++ b/packages/bash/pwsh-local/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/bash/pwsh-local/README.md -README.md: a97612ab4e11bf4a3fcfb77daf0624a894b02ad4 -README.zh.md: d6751dac6df789eec9727c1380f1a4c91da60728 +README.md: 430419cc34added1e983e3fc119cfeb1eebb6829 +README.zh.md: 4a1246a31a22143d6a260cc7b3024dc490f19b7f diff --git a/packages/bash/pwsh-local/README.md b/packages/bash/pwsh-local/README.md index a97612ab4e..430419cc34 100644 --- a/packages/bash/pwsh-local/README.md +++ b/packages/bash/pwsh-local/README.md @@ -28,6 +28,7 @@ The package root exports the default and named `PwshLocalExecutor` plugin, its ` The Windows counterpart of `dsh-bash-local`, deliberately mirroring its semantics call-for-call: - **Spawn per call, no shell state** — every call is a fresh non-interactive `pwsh -Command` (deterministic; no profile files). The `-NoLogo -NoProfile -NonInteractive` flags disable startup banners, profile loading, and prompts that would garble tool output. +- **UTF-8 I/O pinned** — every command runs with `[Console]::OutputEncoding` and `$OutputEncoding` set to UTF-8 first, so the Windows PowerShell 5.1 fallback (or any host whose console code page is not UTF-8) cannot garble non-ASCII output: the subprocess collector decodes bytes as UTF-8. pwsh 7 defaults to UTF-8 and is unaffected. - **Executable resolution** — `resolvePwshPath` prefers an explicit `pwshPath`, then on Windows probes PowerShell 7's install location, every PATH entry (Microsoft Store installs; surrounding quotes stripped), and Windows PowerShell 5.1 as a legacy last resort, checking `existsSync` on each; elsewhere it falls back to a bare `pwsh` resolved through PATH. Resolution is a pure function of `(configured, env, platform)` and happens once at construction. - **Configured budgets over managed groups** — `resolve()` fills `workdir`/`timeoutMs`/`stdoutMaxBytes` from config, and every spawn hands the service explicit byte caps, spill cap, and `graceMs`. Tree termination (taskkill on Windows, process-group signals on POSIX), the post-exit pipe-drain grace, tail-keep truncation, and bounded spill files are [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) mechanics. A foreground `BashExecRequest.stdoutMaxBytes` can raise stdout's capture budget for one trusted caller; stderr and background runs still use `maxOutputBytes`. - **Timeout and cancel classification** — `run()` fuses its config-clamped timeout with the caller's signal through one deadline; only the executor's own timeout reports `timedOut`, an upstream cancel reports `aborted`, and a self-terminated command reports neither ([timeout-library Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md)). Windows reports forced termination as exit 1 without a signal, so signal-stamped facts (`signal`, `killed` status) are POSIX-only there; the timeout/abort classification is platform-independent. @@ -36,7 +37,7 @@ The Windows counterpart of `dsh-bash-local`, deliberately mirroring its semantic ## Model Experience -Indirectly, through `dsh-tool-pwsh`, which renders this executor's bounded stdout/stderr tails, background-process deltas, spill-file paths, and infrastructure failures. +Indirectly, through `dsh-tool-pwsh`, which renders this executor's bounded stdout/stderr tails, background-process deltas (through the generic task runtime), spill-file paths, and infrastructure failures. #### KV Cache effect diff --git a/packages/bash/pwsh-local/README.zh.md b/packages/bash/pwsh-local/README.zh.md index d6751dac6d..4a1246a31a 100644 --- a/packages/bash/pwsh-local/README.zh.md +++ b/packages/bash/pwsh-local/README.zh.md @@ -28,6 +28,7 @@ 作为 `dsh-bash-local` 的 Windows 对应物,逐调用地镜像其语义: - **每次调用新建进程,无 shell 状态**——每次调用都是全新的非交互 `pwsh -Command`(确定性;不加载 profile 文件)。`-NoLogo -NoProfile -NonInteractive` 关闭启动横幅、profile 加载与会干扰工具输出的提示符。 +- **UTF-8 I/O 固定**——每条命令都先以 UTF-8 设置 `[Console]::OutputEncoding` 与 `$OutputEncoding`,因此 Windows PowerShell 5.1 兜底(或任何控制台代码页非 UTF-8 的主机)不会破坏非 ASCII 输出:subprocess collector 以 UTF-8 解码字节。pwsh 7 默认为 UTF-8,不受影响。 - **可执行文件解析**——`resolvePwshPath` 优先显式 `pwshPath`,然后在 Windows 上依次探测 PowerShell 7 安装位置、每个 PATH 条目(Microsoft Store 安装;剥离两端引号)以及作为遗留兜底的 Windows PowerShell 5.1,逐一检查 `existsSync`;其他平台回退为通过 PATH 解析的裸 `pwsh`。解析是 `(configured, env, platform)` 的纯函数,在构造时执行一次。 - **受管进程组之上的配置预算**——`resolve()` 从配置填充 `workdir`/`timeoutMs`/`stdoutMaxBytes`,每次 spawn 都向服务提供显式字节上限、spill 上限与 `graceMs`。进程树终止(Windows 用 taskkill,POSIX 用进程组信号)、退出后管道排空宽限、保尾截断与有界 spill 文件是 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 的机制。前台 `BashExecRequest.stdoutMaxBytes` 可为单个受信调用方提高 stdout 捕获预算;stderr 与后台运行仍使用 `maxOutputBytes`。 - **超时与取消分类**——`run()` 通过一个 deadline 融合配置夹取的超时与调用方信号;只有执行器自身超时报告 `timedOut`,上游取消报告 `aborted`,自我终止的命令两者都不报告(见 [timeout 库 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md))。Windows 将强制终止报告为退出码 1 且无信号,因此基于信号的实情(`signal`、`killed` 状态)在那里仅限 POSIX;超时/取消分类与平台无关。 @@ -36,7 +37,7 @@ ## 模型体验 -间接地,经由 `dsh-tool-pwsh` 呈现本执行器的有界 stdout/stderr 尾部、后台进程增量、spill 文件路径与基础设施失败。 +间接地,经由 `dsh-tool-pwsh` 呈现本执行器的有界 stdout/stderr 尾部、后台进程增量(经通用任务运行时)、spill 文件路径与基础设施失败。 #### KV Cache 影响 From 22c872097db5ebd334f2439e1a29c4b086004459 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 14:19:06 +0800 Subject: [PATCH 11/61] chore(deps): sync the lockfile and drop the resolved pwsh binary ignore --- knip.json | 1 - pnpm-lock.yaml | 85 +++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 70 insertions(+), 16 deletions(-) diff --git a/knip.json b/knip.json index efc2fbea42..7cabe21ced 100644 --- a/knip.json +++ b/knip.json @@ -5,7 +5,6 @@ ], "ignoreBinaries": [ "bwrap", - "pwsh", "python3", "sandbox-exec", "taskkill" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1d6e3c2cb3..f7108c88b5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -147,6 +147,9 @@ importers: '@deepseek-ai/dsh-app-boot': specifier: workspace:^ version: link:../../packages/ui/app-boot + '@deepseek-ai/dsh-bash-env': + specifier: workspace:^ + version: link:../../packages/bash/bash-env '@deepseek-ai/dsh-bash-local': specifier: workspace:^ version: link:../../packages/bash/bash-local @@ -590,6 +593,9 @@ importers: '@deepseek-ai/dsh-bash': specifier: workspace:* version: link:../packages/bash/bash + '@deepseek-ai/dsh-bash-env': + specifier: workspace:* + version: link:../packages/bash/bash-env '@deepseek-ai/dsh-bash-local': specifier: workspace:* version: link:../packages/bash/bash-local @@ -674,6 +680,9 @@ importers: '@deepseek-ai/dsh-pty-local': specifier: workspace:* version: link:../packages/pty/pty-local + '@deepseek-ai/dsh-pwsh-local': + specifier: workspace:* + version: link:../packages/bash/pwsh-local '@deepseek-ai/dsh-repeat-tool-guard': specifier: workspace:* version: link:../packages/guard/repeat-tool-guard @@ -791,6 +800,9 @@ importers: '@deepseek-ai/dsh-tool-pty': specifier: workspace:* version: link:../packages/pty/tool-pty + '@deepseek-ai/dsh-tool-pwsh': + specifier: workspace:* + version: link:../packages/bash/tool-pwsh '@deepseek-ai/dsh-tool-ralph': specifier: workspace:* version: link:../packages/workflow/tool-ralph @@ -895,6 +907,37 @@ importers: specifier: ^4.0.0-rc.7 version: link:../../../vendor/cordis + packages/bash/bash-env: + dependencies: + schemastery: + specifier: ^3.18.0 + version: link:../../../vendor/schemastery + devDependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent + '@deepseek-ai/dsh-bash': + specifier: workspace:^ + version: link:../bash + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-paths': + specifier: workspace:^ + version: link:../../util/paths + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:^ + version: link:../../session-persistence/session-persistence + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + cordis: + specifier: ^4.0.0-rc.7 + version: link:../../../vendor/cordis + packages/bash/bash-local: dependencies: schemastery: @@ -954,7 +997,7 @@ importers: dependencies: schemastery: specifier: ^3.18.0 - version: 3.18.0 + version: link:../../../vendor/schemastery devDependencies: '@deepseek-ai/dsh-bash': specifier: workspace:^ @@ -973,7 +1016,7 @@ importers: version: link:../../util/timeout cordis: specifier: ^4.0.0-rc.7 - version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + version: link:../../../vendor/cordis packages/bash/tool-bash: dependencies: @@ -993,6 +1036,9 @@ importers: '@deepseek-ai/dsh-bash': specifier: workspace:^ version: link:../bash + '@deepseek-ai/dsh-bash-env': + specifier: workspace:^ + version: link:../bash-env '@deepseek-ai/dsh-bash-local': specifier: workspace:^ version: link:../bash-local @@ -1002,9 +1048,6 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../../llm/llm - '@deepseek-ai/dsh-paths': - specifier: workspace:^ - version: link:../../util/paths '@deepseek-ai/dsh-sandbox': specifier: workspace:^ version: link:../../sandbox/sandbox @@ -1014,9 +1057,6 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session - '@deepseek-ai/dsh-session-persistence': - specifier: workspace:^ - version: link:../../session-persistence/session-persistence '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../session-persistence/session-persistence-jsonl @@ -1049,7 +1089,7 @@ importers: dependencies: schemastery: specifier: ^3.18.0 - version: 3.18.0 + version: link:../../../vendor/schemastery devDependencies: '@deepseek-ai/dsh-agent': specifier: workspace:^ @@ -1057,33 +1097,42 @@ importers: '@deepseek-ai/dsh-bash': specifier: workspace:^ version: link:../bash + '@deepseek-ai/dsh-bash-env': + specifier: workspace:^ + version: link:../bash-env '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../../llm/llm - '@deepseek-ai/dsh-paths': + '@deepseek-ai/dsh-loader-smoke': specifier: workspace:^ - version: link:../../util/paths + version: link:../../support/loader-smoke '@deepseek-ai/dsh-pwsh-local': specifier: workspace:^ version: link:../pwsh-local - '@deepseek-ai/dsh-session-persistence': - specifier: workspace:^ - version: link:../../session-persistence/session-persistence '@deepseek-ai/dsh-subprocess-local': specifier: workspace:^ version: link:../../subprocess/subprocess-local '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt + '@deepseek-ai/dsh-tasks': + specifier: workspace:^ + version: link:../../tasks/tasks + '@deepseek-ai/dsh-tasks-local': + specifier: workspace:^ + version: link:../../tasks/tasks-local + '@deepseek-ai/dsh-tool-tasks': + specifier: workspace:^ + version: link:../../tasks/tool-tasks '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools cordis: specifier: ^4.0.0-rc.7 - version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + version: link:../../../vendor/cordis packages/client/connection: dependencies: @@ -2748,6 +2797,9 @@ importers: '@deepseek-ai/dsh-agent-loop': specifier: workspace:^ version: link:../../core/agent-loop + '@deepseek-ai/dsh-bash-env': + specifier: workspace:^ + version: link:../../bash/bash-env '@deepseek-ai/dsh-bash-local': specifier: workspace:^ version: link:../../bash/bash-local @@ -6302,6 +6354,9 @@ importers: '@deepseek-ai/dsh-bash': specifier: workspace:^ version: link:../../packages/bash/bash + '@deepseek-ai/dsh-bash-env': + specifier: workspace:^ + version: link:../../packages/bash/bash-env '@deepseek-ai/dsh-bash-local': specifier: workspace:^ version: link:../../packages/bash/bash-local From 64f9e68bd96c11c0c7e2f8e394066ad5e0265df9 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 15:31:52 +0800 Subject: [PATCH 12/61] test(acp): register and record the keyed pwsh-tool-turn snapshot scenario --- examples/acp-agent/tests/acp.snapshot.ts | 18 ++++++--- .../tests/snapshots/pwsh-tool-turn/input.json | 7 ++++ .../snapshots/pwsh-tool-turn/session.jsonl | 32 ++++++++++++++++ .../pwsh-tool-turn/stdout.expected.jsonl | 4 ++ .../pwsh-tool-turn/system-prompt.expected.md | 5 +++ .../pwsh-tool-turn/tool-schemas.expected.json | 38 +++++++++++++++++++ 6 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 examples/acp-agent/tests/snapshots/pwsh-tool-turn/input.json create mode 100644 examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl create mode 100644 examples/acp-agent/tests/snapshots/pwsh-tool-turn/stdout.expected.jsonl create mode 100644 examples/acp-agent/tests/snapshots/pwsh-tool-turn/system-prompt.expected.md create mode 100644 examples/acp-agent/tests/snapshots/pwsh-tool-turn/tool-schemas.expected.json diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index f191b5ce1b..c762e28904 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -44,6 +44,7 @@ const SESSION_TITLE_CONFIG = fileURLToPath(new URL('../session-title.cordis.yml' const LSP_CONFIG = fileURLToPath(new URL('./lsp.cordis.yml', import.meta.url)) const WEB_CONFIG = fileURLToPath(new URL('../web.cordis.yml', import.meta.url)) const FS_SEARCH_CONFIG = fileURLToPath(new URL('./fs-search.cordis.yml', import.meta.url)) +const PWSH_CONFIG = fileURLToPath(new URL('./pwsh.cordis.yml', import.meta.url)) const SNAPSHOTS_DIR = join(dirname(fileURLToPath(import.meta.url)), 'snapshots') const PACKED_CHUNKS_SOURCE = 'hook-cc-pretool-deny' @@ -154,12 +155,17 @@ const SCENARIOS: Scenario[] = [ configPath: PTY_CONFIG, }, { name: 'bash-tool-turn', hasModelTurn: true, recorded: true }, - // The pwsh-tool-turn scenario is NOT registered yet: its overlay - // (pwsh.cordis.yml / pwsh.cordis.snapshot.yml) swaps the bundle's bash tool - // for the PowerShell twin, so its header class needs its own prompt/tool - // sidecars and a recorded transcript. Both require a keyed environment - // (`test:snapshot:record`); the composition ships so the scenario can be - // registered and recorded in one keyed pass. + // The pwsh overlay (pwsh.cordis.yml / pwsh.cordis.snapshot.yml) swaps the + // bundle's bash tool for the PowerShell twin, so its header class pins its + // own prompt/tool sidecars and a recorded transcript. + { + name: 'pwsh-tool-turn', + hasModelTurn: true, + recorded: true, + pinsHeader: true, + headerClass: 'pwsh', + configPath: PWSH_CONFIG, + }, { name: 'todo-write', hasModelTurn: true, recorded: true }, { name: 'skill-load', diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/input.json b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/input.json new file mode 100644 index 0000000000..4101a2c1f3 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/input.json @@ -0,0 +1,7 @@ +{ + "steps": [ + { "op": "initialize" }, + { "op": "newSession" }, + { "op": "prompt", "text": "Use the pwsh tool to run exactly: Write-Output PWSH_OK. Then reply with the single word DONE and stop." } + ] +} diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl new file mode 100644 index 0000000000..061d3261a3 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl @@ -0,0 +1,32 @@ +{"type":"session","version":0,"id":"1ec0d099-552b-44e1-8fb8-fd9742fbdc1c","createdAt":1785655505943,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"turn/start","seq":0,"time":1785655505948,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} +{"type":"user/message","seq":1,"time":1785655505948,"data":{"content":[{"type":"text","text":"Use the pwsh tool to run exactly: Write-Output PWSH_OK. Then reply with the single word DONE and stop."}],"source":{"kind":"user"},"role":"user","id":"e3bca81a-d4e4-46fb-aa30-916f785c27a0"},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1785655505949,"data":{"title":"Use the pwsh tool to","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1785655505971,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1785655505972,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","seq":5,"time":1785655505972,"data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} +{"type":"assistant/chunk","seq":6,"time":1785655506674,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"reasoning-chunks","seq0":7,"time0":1785655506674,"data":{"turn":1,"step":1,"index":0,"dt":[157,27,1,0,0,0,38,0,0,43,0,0,0,50,0,1,0,0,0,36,0,1,0,0],"texts":["The"," user"," wants"," me"," to"," run"," a"," PowerShell"," command"," that"," outputs"," \"","P","WS","H","_OK","\""," and"," then"," reply"," with"," \"","D","ONE","\"."]}} +{"type":"assistant/chunk","seq":32,"time":1785655507160,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} +{"type":"tool-call-chunks","seq0":33,"time0":1785655507161,"data":{"turn":1,"step":1,"index":1,"dt":[51,0,0,0,0,32,0,0,0,55,1,0,0,0,74,0,0,0,1,45,0,42,0,0,0,0,54,0],"id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","args":["","{","\"","command","\"",": ","\"","Write","-","Output"," P","WS","H","_OK","\"",", ","\"","description","\"",": ","\"","Output"," P","WS","H","_OK"," string","\"","}"]}} +{"type":"assistant/chunk","seq":62,"time":1785655507601,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a PowerShell command that outputs \"PWSH_OK\" and then reply with \"DONE\"."}}}} +{"type":"assistant/chunk","seq":63,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}}}} +{"type":"assistant/chunk","seq":64,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":816,"outputTokens":96,"cacheReadTokens":0,"reasoningTokens":25}}}} +{"type":"assistant/chunk","seq":65,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":66,"time":1785655507604,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to run a PowerShell command that outputs \"PWSH_OK\" and then reply with \"DONE\"."},{"type":"tool-call","id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"4d81cc10-507e-49a8-96f4-aa3ae5ad2eb5"},"usage":{"inputTokens":816,"outputTokens":96,"cacheReadTokens":0,"reasoningTokens":25}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65],"surfaceOp":"append"} +{"type":"tool/call","seq":67,"time":1785655507605,"data":{"turn":1,"step":1,"callId":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}} +{"type":"tool/result","seq":68,"time":1785655507994,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_oEhmLGLNsvlumiE0WkXD0511"},"content":[{"type":"tool-result","toolCallId":"call_00_oEhmLGLNsvlumiE0WkXD0511","content":[{"type":"text","text":"PWSH_OK\r\n"}],"isError":false}],"role":"user","id":"84a96d55-5bd5-46fc-ab0d-918882c504e2"}},"sourceEventSeqs":[67],"surfaceOp":"append"} +{"type":"step/end","seq":69,"time":1785655507994,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":70,"time":1785655508000,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":71,"time":1785655508608,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"reasoning-chunks","seq0":72,"time0":1785655508608,"data":{"turn":1,"step":2,"index":0,"dt":[168,38,0,60,1,0,0,0,0,27,1,0,0,0,46,0,0,0,0,0,41],"texts":["The"," command"," successfully"," output"," \"","P","WS","H","_OK","\"."," Now"," I"," should"," reply"," with"," \"","D","ONE","\""," as"," instructed","."]}} +{"type":"assistant/chunk","seq":94,"time":1785655508990,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} +{"type":"assistant/chunk","seq":95,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} +{"type":"assistant/chunk","seq":96,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} +{"type":"assistant/chunk","seq":97,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The command successfully output \"PWSH_OK\". Now I should reply with \"DONE\" as instructed."}}}} +{"type":"assistant/chunk","seq":98,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} +{"type":"assistant/chunk","seq":99,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":34,"outputTokens":25,"cacheReadTokens":896,"reasoningTokens":22}}}} +{"type":"assistant/chunk","seq":100,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":101,"time":1785655508991,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The command successfully output \"PWSH_OK\". Now I should reply with \"DONE\" as instructed."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"d8905016-347c-477a-a8f7-2b31839a8357"},"usage":{"inputTokens":34,"outputTokens":25,"cacheReadTokens":896,"reasoningTokens":22}},"sourceEventSeqs":[71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100],"surfaceOp":"append"} +{"type":"step/end","seq":102,"time":1785655508992,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":103,"time":1785655508992,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/stdout.expected.jsonl new file mode 100644 index 0000000000..82ae8907ca --- /dev/null +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/stdout.expected.jsonl @@ -0,0 +1,4 @@ +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/system-prompt.expected.md new file mode 100644 index 0000000000..9b51477daf --- /dev/null +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/system-prompt.expected.md @@ -0,0 +1,5 @@ +You are an AI agent powered by the DeepSeek Harness SDK. + +You are a concise snapshot agent working in {{cwd}}. + +Non-zero exits are reported as `[exit code: N]` markers; investigate failures before moving on. On Windows a killed process settles as `[exit code: 1]` without a signal marker; treat a bare exit 1 after an interruption as a termination, not a command failure. diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/tool-schemas.expected.json new file mode 100644 index 0000000000..6f6d3fa729 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/tool-schemas.expected.json @@ -0,0 +1,38 @@ +{ + "initial": [ + { + "name": "pwsh", + "description": "Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. Each call runs in a fresh pwsh process: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\\...`); read environment variables with `$env:NAME`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$env:DSH_*` variables; inspect them when needed. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. On Windows a force-killed command settles as `[exit code: 1]` without a signal marker — treat it as an interruption, not a command failure. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The PowerShell command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"Get-Process\" → \"List running processes\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." + } + }, + "required": [ + "command", + "description" + ] + } + } + ], + "changes": [] +} From 8fa1201f6eeaec72bbe4e08d49a965da231ffd07 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 16:06:25 +0800 Subject: [PATCH 13/61] chore: trigger CI merge-ref recalculation From ab4963c43db67273cdb7314cee99bfe8e750ae9a Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 16:25:27 +0800 Subject: [PATCH 14/61] fix(scripts): mount bash-env in the tool-catalog harvest --- docs/tool-catalog.md | 80 ++++++++++++++++++++++++++++++++++++- scripts/gen-tool-catalog.ts | 3 ++ 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 5a7b47719c..56a6eaaedc 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -18,8 +18,8 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`, `ctx.userInteraction` | `tool/call`, `tool/result after a UI/provider answers the question` | - | ask_user_question pauses the tool call until the active UI provider returns a human answer. | | `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.codeRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/code-dispatch-start + tool/code-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated TypeScript SDK section, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`, `ctx.systemPrompt`, `ctx.userInteraction (execution time, opportunistic)` | `tool/call`, `plan/mode inactive on an approved review`, `tool/result` | - | exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-interaction seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary. | -| `@deepseek-ai/dsh-tool-bash` | - | `ctx.tools`, `ctx.bash`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | -| `@deepseek-ai/dsh-tool-pwsh` | - | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. | +| `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.bash`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | +| `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. | | `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect`, `cordis_mount`, `cordis_unmount` | `ctx.tools` | `tool/call`, `tool/result`, `process-local temporary Plugin lifecycle` | - | Not in any shipped tree (a deliberate opt-in — temporary Plugin code reaches the real runtime, see .agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins created by cordis_mount may register ADDITIONAL model-visible tools until unmounted or DSH restarts; a full changed request header logs those tool-set changes. | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.tools`, `ctx.pty`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`, `ctx.fs` | `tool/call`, `fs/observed after successful file operations`, `tool/result` | - | Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal surface. | @@ -168,10 +168,86 @@ exit_plan_mode stays in the model-facing schema while planning is inactive so tr ## `@deepseek-ai/dsh-tool-bash` +### `bash` + +Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. + +```json +{ + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." + } + }, + "required": [ + "command", + "description" + ] +} +``` + +Source: [`packages/bash/tool-bash/src/index.ts`](../packages/bash/tool-bash/src/index.ts) + The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. ## `@deepseek-ai/dsh-tool-pwsh` +### `pwsh` + +Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. Each call runs in a fresh pwsh process: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\...`); read environment variables with `$env:NAME`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$env:DSH_*` variables; inspect them when needed. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. On Windows a force-killed command settles as `[exit code: 1]` without a signal marker — treat it as an interruption, not a command failure. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. + +```json +{ + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The PowerShell command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"Get-Process\" → \"List running processes\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." + } + }, + "required": [ + "command", + "description" + ] +} +``` + +Source: [`packages/bash/tool-pwsh/src/index.ts`](../packages/bash/tool-pwsh/src/index.ts) + The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. ## `@deepseek-ai/dsh-tool-cordis` diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 26d751591f..9af8fbe7c2 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -19,6 +19,7 @@ import GoalService from '@deepseek-ai/dsh-goal' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools' import LocalBashExecutor from '@deepseek-ai/dsh-bash-local' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' import { PwshLocalExecutor } from '@deepseek-ai/dsh-pwsh-local' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' @@ -196,6 +197,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ writes: ['tool/call', 'tool/result'], async mount(ctx) { await ctx.plugin(LocalSubprocessService) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(LocalBashExecutor) await ctx.plugin(ToolBash) }, @@ -213,6 +215,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ // mounts the pwsh-local implementation so the inject resolves without // executing anything (registration never spawns a process). await ctx.plugin(LocalSubprocessService) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(PwshLocalExecutor) await ctx.plugin(ToolPwsh) }, From cdb2aac382cb20116a2d7380b2cb471267dc0aa5 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 16:39:52 +0800 Subject: [PATCH 15/61] docs(module-graph): refresh after the master merge --- docs/module-graph.md | 121 +++++++++++++++++++++++-------------------- 1 file changed, 64 insertions(+), 57 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 2da7b99e6d..5c709fc06f 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -38,6 +38,7 @@ flowchart TD end subgraph group_bash["packages/bash"] pkg_bash["bash"] + pkg_bash_env["bash-env"] pkg_bash_local["bash-local"] pkg_bash_sandbox["bash-sandbox"] pkg_pwsh_local["pwsh-local"] @@ -697,26 +698,11 @@ flowchart TD pkg_tool_goal --> pkg_session pkg_tool_goal --> pkg_system_prompt pkg_tool_goal --> pkg_tools - pkg_tool_bash --> pkg_agent - pkg_tool_bash --> pkg_bash - pkg_tool_bash --> pkg_invariants - pkg_tool_bash --> pkg_llm - pkg_tool_bash --> pkg_paths - pkg_tool_bash --> pkg_sandbox - pkg_tool_bash --> pkg_sandbox_policy - pkg_tool_bash --> pkg_session_persistence - pkg_tool_bash --> pkg_system_prompt - pkg_tool_bash --> pkg_tasks - pkg_tool_bash --> pkg_tools - pkg_tool_bash --> pkg_user_approval - pkg_tool_pwsh --> pkg_agent - pkg_tool_pwsh --> pkg_bash - pkg_tool_pwsh --> pkg_invariants - pkg_tool_pwsh --> pkg_llm - pkg_tool_pwsh --> pkg_paths - pkg_tool_pwsh --> pkg_session_persistence - pkg_tool_pwsh --> pkg_system_prompt - pkg_tool_pwsh --> pkg_tools + pkg_bash_env --> pkg_bash + pkg_bash_env --> pkg_invariants + pkg_bash_env --> pkg_paths + pkg_bash_env --> pkg_session_persistence + pkg_bash_env --> pkg_tools pkg_tool_fs --> pkg_fs pkg_tool_fs --> pkg_invariants pkg_tool_fs --> pkg_llm @@ -905,6 +891,25 @@ flowchart TD pkg_tool_workflow --> pkg_system_prompt pkg_tool_workflow --> pkg_tools pkg_tool_workflow --> pkg_workflow + pkg_tool_bash --> pkg_agent + pkg_tool_bash --> pkg_bash + pkg_tool_bash --> pkg_bash_env + pkg_tool_bash --> pkg_invariants + pkg_tool_bash --> pkg_llm + pkg_tool_bash --> pkg_sandbox + pkg_tool_bash --> pkg_sandbox_policy + pkg_tool_bash --> pkg_system_prompt + pkg_tool_bash --> pkg_tasks + pkg_tool_bash --> pkg_tools + pkg_tool_bash --> pkg_user_approval + pkg_tool_pwsh --> pkg_agent + pkg_tool_pwsh --> pkg_bash + pkg_tool_pwsh --> pkg_bash_env + pkg_tool_pwsh --> pkg_invariants + pkg_tool_pwsh --> pkg_llm + pkg_tool_pwsh --> pkg_system_prompt + pkg_tool_pwsh --> pkg_tasks + pkg_tool_pwsh --> pkg_tools pkg_subagent_acp --> pkg_agent pkg_subagent_acp --> pkg_invariants pkg_subagent_acp --> pkg_llm @@ -994,27 +999,6 @@ flowchart TD pkg_client_ui_plan --> pkg_client_ui_slots pkg_client_ui_plan --> pkg_invariants pkg_client_ui_plan --> pkg_plan_mode - pkg_agent_spine_demo --> pkg_agent - pkg_agent_spine_demo --> pkg_agent_loop - pkg_agent_spine_demo --> pkg_goal - pkg_agent_spine_demo --> pkg_goal_session - pkg_agent_spine_demo --> pkg_invariants - pkg_agent_spine_demo --> pkg_llm - pkg_agent_spine_demo --> pkg_llm_retry - pkg_agent_spine_demo --> pkg_paths - pkg_agent_spine_demo --> pkg_scope - pkg_agent_spine_demo --> pkg_session - pkg_agent_spine_demo --> pkg_session_title - pkg_agent_spine_demo --> pkg_skill - pkg_agent_spine_demo --> pkg_skill_local - pkg_agent_spine_demo --> pkg_system_prompt - pkg_agent_spine_demo --> pkg_tasks_local - pkg_agent_spine_demo --> pkg_tool_bash - pkg_agent_spine_demo --> pkg_tool_goal - pkg_agent_spine_demo --> pkg_tool_skill - pkg_agent_spine_demo --> pkg_tool_tasks - pkg_agent_spine_demo --> pkg_tools - pkg_agent_spine_demo --> pkg_workspace_context pkg_sdk_protocol --> pkg_invariants pkg_sdk_protocol --> pkg_llm pkg_sdk_protocol --> pkg_session @@ -1050,6 +1034,39 @@ flowchart TD pkg_jsonrpc --> pkg_sdk_protocol pkg_jsonrpc --> pkg_session pkg_jsonrpc --> pkg_subagent + pkg_agent_spine_demo --> pkg_agent + pkg_agent_spine_demo --> pkg_agent_loop + pkg_agent_spine_demo --> pkg_bash_env + pkg_agent_spine_demo --> pkg_goal + pkg_agent_spine_demo --> pkg_goal_session + pkg_agent_spine_demo --> pkg_invariants + pkg_agent_spine_demo --> pkg_llm + pkg_agent_spine_demo --> pkg_llm_retry + pkg_agent_spine_demo --> pkg_paths + pkg_agent_spine_demo --> pkg_scope + pkg_agent_spine_demo --> pkg_session + pkg_agent_spine_demo --> pkg_session_title + pkg_agent_spine_demo --> pkg_skill + pkg_agent_spine_demo --> pkg_skill_local + pkg_agent_spine_demo --> pkg_system_prompt + pkg_agent_spine_demo --> pkg_tasks_local + pkg_agent_spine_demo --> pkg_tool_bash + pkg_agent_spine_demo --> pkg_tool_goal + pkg_agent_spine_demo --> pkg_tool_skill + pkg_agent_spine_demo --> pkg_tool_tasks + pkg_agent_spine_demo --> pkg_tools + pkg_agent_spine_demo --> pkg_workspace_context + pkg_sdk_client --> pkg_invariants + pkg_sdk_client --> pkg_llm + pkg_sdk_client --> pkg_sdk_protocol + pkg_sdk_client --> pkg_session + pkg_subagent_dsh_sdk --> pkg_agent + pkg_subagent_dsh_sdk --> pkg_invariants + pkg_subagent_dsh_sdk --> pkg_llm + pkg_subagent_dsh_sdk --> pkg_sdk_client + pkg_subagent_dsh_sdk --> pkg_session + pkg_subagent_dsh_sdk --> pkg_subagent + pkg_subagent_dsh_sdk --> pkg_subprocess pkg_acp_demo --> pkg_acp pkg_acp_demo --> pkg_agent_spine_demo pkg_acp_demo --> pkg_app_boot @@ -1070,17 +1087,6 @@ flowchart TD pkg_cli_demo --> pkg_session_persistence_jsonl pkg_cli_demo --> pkg_tools pkg_cli_demo --> pkg_workspace_context - pkg_sdk_client --> pkg_invariants - pkg_sdk_client --> pkg_llm - pkg_sdk_client --> pkg_sdk_protocol - pkg_sdk_client --> pkg_session - pkg_subagent_dsh_sdk --> pkg_agent - pkg_subagent_dsh_sdk --> pkg_invariants - pkg_subagent_dsh_sdk --> pkg_llm - pkg_subagent_dsh_sdk --> pkg_sdk_client - pkg_subagent_dsh_sdk --> pkg_session - pkg_subagent_dsh_sdk --> pkg_subagent - pkg_subagent_dsh_sdk --> pkg_subprocess ``` | Package | Group | Depends on | @@ -1210,8 +1216,7 @@ flowchart TD | [`session-telemetry-otel`](../packages/telemetry/session-telemetry-otel) | `telemetry` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`session`](../packages/core/session), [`session-telemetry`](../packages/telemetry/session-telemetry) | | [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-bash`](../packages/bash/tool-bash) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | -| [`tool-pwsh`](../packages/bash/tool-pwsh) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`bash-env`](../packages/bash/bash-env) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`session-persistence`](../packages/session-persistence/session-persistence), [`tools`](../packages/core/tools) | | [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | | [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) | @@ -1243,6 +1248,8 @@ flowchart TD | [`tool-pty`](../packages/pty/tool-pty) | `pty` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`pty`](../packages/pty/pty), [`retention`](../packages/util/retention), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | | [`tool-tasks`](../packages/tasks/tool-tasks) | `tasks` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | +| [`tool-bash`](../packages/bash/tool-bash) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`bash-env`](../packages/bash/bash-env), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | +| [`tool-pwsh`](../packages/bash/tool-pwsh) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`bash-env`](../packages/bash/bash-env), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | | [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | @@ -1254,14 +1261,14 @@ flowchart TD | [`client-ui-model`](../packages/client/ui-model) | `client` | [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-command`](../packages/client/ui-command), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-permission`](../packages/client/ui-permission) | `client` | [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-schema-form`](../packages/client/schema-form), [`client-ui-command`](../packages/client/ui-command), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants), [`permission`](../packages/ui/permission) | | [`client-ui-plan`](../packages/client/ui-plan) | `client` | [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants), [`plan-mode`](../packages/plan/plan-mode) | -| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`paths`](../packages/util/paths), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`skill`](../packages/skill/skill), [`skill-local`](../packages/skill/skill-local), [`system-prompt`](../packages/core/system-prompt), [`tasks-local`](../packages/tasks/tasks-local), [`tool-bash`](../packages/bash/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-skill`](../packages/skill/tool-skill), [`tool-tasks`](../packages/tasks/tool-tasks), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | | [`sdk-protocol`](../packages/sdk/sdk-protocol) | `sdk` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`tool-ralph`](../packages/workflow/tool-ralph) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`subagent-fork`](../packages/subagent/subagent-fork) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | | [`subagent-spawn`](../packages/subagent/subagent-spawn) | `subagent` | [`invariants`](../packages/support/invariants), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | | [`jsonrpc`](../packages/ui/jsonrpc) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/sdk-protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | -| [`acp-demo`](../packages/examples/acp-demo) | `examples` | [`acp`](../packages/acp/acp), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | -| [`cli-demo`](../packages/examples/cli-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | +| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`bash-env`](../packages/bash/bash-env), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`paths`](../packages/util/paths), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`skill`](../packages/skill/skill), [`skill-local`](../packages/skill/skill-local), [`system-prompt`](../packages/core/system-prompt), [`tasks-local`](../packages/tasks/tasks-local), [`tool-bash`](../packages/bash/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-skill`](../packages/skill/tool-skill), [`tool-tasks`](../packages/tasks/tool-tasks), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | | [`sdk-client`](../packages/sdk/sdk-client) | `sdk` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/sdk-protocol), [`session`](../packages/core/session) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/sdk-client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | +| [`acp-demo`](../packages/examples/acp-demo) | `examples` | [`acp`](../packages/acp/acp), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | +| [`cli-demo`](../packages/examples/cli-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | From 480c12077f0e510b65d890b8205e73124b63d497 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 16:43:30 +0800 Subject: [PATCH 16/61] fix(tool-bash): mount bash-env in the base test harness --- packages/bash/tool-bash/tests/tools.spec.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/bash/tool-bash/tests/tools.spec.ts b/packages/bash/tool-bash/tests/tools.spec.ts index 22fe3bc4b6..b463bf4ef2 100644 --- a/packages/bash/tool-bash/tests/tools.spec.ts +++ b/packages/bash/tool-bash/tests/tools.spec.ts @@ -36,6 +36,7 @@ async function setup() { await ctx.plugin(AgentRegistry) await ctx.plugin(LocalSubprocessService) ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir } + await ctx.plugin(BashEnvPlugin) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 }) await ctx.plugin(ToolBash) return ctx @@ -51,6 +52,7 @@ async function setupWithTasks() { await ctx.plugin(ToolTasks) await ctx.plugin(LocalSubprocessService) ;(ctx.subprocess as LocalSubprocessService).internals = { spillDir } + await ctx.plugin(BashEnvPlugin) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, graceMs: 200 }) await ctx.plugin(ToolBash) return ctx From a79d7c896ce3e0c67207dd1a62ef0e37ee675af7 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 16:53:29 +0800 Subject: [PATCH 17/61] fix(tool-bash): mount bash-env in the sandboxed and HMR-safety harnesses; normalize the pwsh-tool-turn fixture line endings for Linux replay --- examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl | 2 +- packages/bash/tool-bash/tests/tools.spec.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl index 061d3261a3..333948541c 100644 --- a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl @@ -15,7 +15,7 @@ {"type":"assistant/chunk","seq":65,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":66,"time":1785655507604,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to run a PowerShell command that outputs \"PWSH_OK\" and then reply with \"DONE\"."},{"type":"tool-call","id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"4d81cc10-507e-49a8-96f4-aa3ae5ad2eb5"},"usage":{"inputTokens":816,"outputTokens":96,"cacheReadTokens":0,"reasoningTokens":25}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65],"surfaceOp":"append"} {"type":"tool/call","seq":67,"time":1785655507605,"data":{"turn":1,"step":1,"callId":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}} -{"type":"tool/result","seq":68,"time":1785655507994,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_oEhmLGLNsvlumiE0WkXD0511"},"content":[{"type":"tool-result","toolCallId":"call_00_oEhmLGLNsvlumiE0WkXD0511","content":[{"type":"text","text":"PWSH_OK\r\n"}],"isError":false}],"role":"user","id":"84a96d55-5bd5-46fc-ab0d-918882c504e2"}},"sourceEventSeqs":[67],"surfaceOp":"append"} +{"type":"tool/result","seq":68,"time":1785655507994,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_oEhmLGLNsvlumiE0WkXD0511"},"content":[{"type":"tool-result","toolCallId":"call_00_oEhmLGLNsvlumiE0WkXD0511","content":[{"type":"text","text":"PWSH_OK\n"}],"isError":false}],"role":"user","id":"84a96d55-5bd5-46fc-ab0d-918882c504e2"}},"sourceEventSeqs":[67],"surfaceOp":"append"} {"type":"step/end","seq":69,"time":1785655507994,"data":{"turn":1,"step":1}} {"type":"step/start","seq":70,"time":1785655508000,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":71,"time":1785655508608,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/packages/bash/tool-bash/tests/tools.spec.ts b/packages/bash/tool-bash/tests/tools.spec.ts index b463bf4ef2..30a997b975 100644 --- a/packages/bash/tool-bash/tests/tools.spec.ts +++ b/packages/bash/tool-bash/tests/tools.spec.ts @@ -191,6 +191,7 @@ async function setupSandboxed(withApproval = false) { await ctx.plugin(SandboxPolicyService, {}) await ctx.plugin(RecordingSandboxExecutor) if (withApproval) await ctx.plugin(ApprovalService) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(ToolBash) return { ctx, bash: ctx.bash as RecordingSandboxExecutor } } @@ -393,6 +394,7 @@ describe('bash tool', () => { await ctx.plugin(ToolRegistry) await ctx.plugin(LocalSubprocessService) await ctx.plugin(LocalBashExecutor, {}) + await ctx.plugin(BashEnvPlugin) const fiber = await ctx.plugin(ToolBash) expect(ctx.tools.schemas()).toHaveLength(1) expect((await ctx.systemPrompt.assemble()).sections.map(s => s.name)).toEqual(['harness:identity', 'deployment:persona', 'tool:bash']) From 7201a417c2c9cb15ae62e9baa746c088d92a1a02 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 17:25:47 +0800 Subject: [PATCH 18/61] fix(subagent): mount bash-env in the spawn and headless e2e harnesses --- examples/headless-agent/tests/harness.ts | 2 ++ packages/subagent/subagent-spawn/tests/harness.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/examples/headless-agent/tests/harness.ts b/examples/headless-agent/tests/harness.ts index c354205388..756cc58e39 100644 --- a/examples/headless-agent/tests/harness.ts +++ b/examples/headless-agent/tests/harness.ts @@ -4,6 +4,7 @@ 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 { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' @@ -61,6 +62,7 @@ export async function codingHarness(workdir: string, options: CodingHarnessOptio models: [{ id: 'deepseek-v4-flash', contextWindow: options.modelContextWindow }], }) await ctx.plugin(LocalSubprocessService) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(LocalBashExecutor, { cwd: workdir, timeoutMs: 30_000 }) await ctx.plugin(ToolBash) await ctx.plugin(ToolTodo) diff --git a/packages/subagent/subagent-spawn/tests/harness.ts b/packages/subagent/subagent-spawn/tests/harness.ts index afa1d2a1d2..389ef5e2a7 100644 --- a/packages/subagent/subagent-spawn/tests/harness.ts +++ b/packages/subagent/subagent-spawn/tests/harness.ts @@ -3,6 +3,7 @@ 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 { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' @@ -29,6 +30,7 @@ export async function spawnHarness(workdir: string): Promise { await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LlmDeepSeek) await ctx.plugin(LocalSubprocessService) + await ctx.plugin(BashEnvPlugin) await ctx.plugin(LocalBashExecutor, { cwd: workdir, timeoutMs: 30_000 }) await ctx.plugin(ToolBash) await ctx.plugin(SubagentService) From eeffd2cfcef6ce54f9e2ee1eb26b23dcb72d08d7 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 17:35:46 +0800 Subject: [PATCH 19/61] fix(headless): mount bash-env in the code-mode harnesses --- examples/headless-agent/tests/code-mode.e2e.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/headless-agent/tests/code-mode.e2e.ts b/examples/headless-agent/tests/code-mode.e2e.ts index 1f708ab601..b8362fc6f8 100644 --- a/examples/headless-agent/tests/code-mode.e2e.ts +++ b/examples/headless-agent/tests/code-mode.e2e.ts @@ -13,6 +13,7 @@ import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' +import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' @@ -57,6 +58,7 @@ async function codeModeHarness(cwd: string): Promise { await harness.plugin(AgentLoop, { agents: [] }) await harness.plugin(LlmDeepSeek) await harness.plugin(LocalSubprocessService) + await harness.plugin(BashEnvPlugin) await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 }) await harness.plugin(ToolBash) await harness.plugin(WorkerCodeRuntime, {}) @@ -117,6 +119,7 @@ async function backgroundCodeModeHarness(cwd: string): Promise { await harness.plugin(LocalTaskService) await harness.plugin(ToolTasks, {}) await harness.plugin(LocalSubprocessService) + await harness.plugin(BashEnvPlugin) await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 }) await harness.plugin(ToolBash) return harness From 447c3fd17fe72ac7b52b549510cd170304e81617 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 17:49:58 +0800 Subject: [PATCH 20/61] fix(sdk): include bash-env in the generated bash feature composition --- packages/sdk/helper/src/features/builtin/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/sdk/helper/src/features/builtin/index.ts b/packages/sdk/helper/src/features/builtin/index.ts index 2aa6c40e71..d2e1068ce4 100644 --- a/packages/sdk/helper/src/features/builtin/index.ts +++ b/packages/sdk/helper/src/features/builtin/index.ts @@ -34,6 +34,7 @@ export function createBuiltinRegistry(profile: ProjectProfile): FeatureRegistry required: true, baseResources: [ { kind: 'npm-cordis-config-entry', id: 'subprocess', package: '@deepseek-ai/dsh-subprocess-local' }, + { kind: 'npm-cordis-config-entry', id: 'bash-env', package: '@deepseek-ai/dsh-bash-env' }, { kind: 'npm-cordis-config-entry', id: 'tool-bash', package: '@deepseek-ai/dsh-tool-bash' }, ], options: [ From 48f0881e441cb7e75680f809882b1fd312e6cfc5 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 18:17:30 +0800 Subject: [PATCH 21/61] docs: describe the minimal pwsh profile as no persistent PTY, not no background tasks --- .../feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml | 2 +- .../implemented/feature/2026-08-02-pwsh-tool-bash-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml index dcf840b868..582d3fb592 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.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-02-pwsh-tool-bash-parity.md -2026-08-02-pwsh-tool-bash-parity.md: 3dcd1e8d4e7e6ea6841695f63012be184fa90f73 +2026-08-02-pwsh-tool-bash-parity.md: f5e3ecfa7e34240ef226f0bceda5d83194667744 2026-08-02-pwsh-tool-bash-parity.zh.md: 03aa9ed2109153d2e0426e7b680eb18c91f89aa7 diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md index 3dcd1e8d4e..f5e3ecfa7e 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md @@ -6,7 +6,7 @@ English | [中文](2026-08-02-pwsh-tool-bash-parity.zh.md) ## Problem -The first Windows-native foundation shipped `dsh-tool-pwsh` as a deliberately minimal profile — foreground only, no background tasks, no managed-environment parity beyond three hardcoded `DSH_*` keys, and a marker story ("always `[exit code: N]`") that diverged from the bash tool's rendering without being declared. Review of that change found the model-visible contract drifting from the implementation: the description promised spill-path reporting the renderer never performed, the README claimed exports that did not exist and rendering the tool did not do, and the tool's own tests pinned the lossy behavior. The minimal profile also left the `DSH_*` contributor seam duplicated-by-absence: plugins contributing environment facts to `ctx.bashEnv` had no effect on pwsh calls. +The first Windows-native foundation shipped `dsh-tool-pwsh` as a deliberately minimal profile — foreground only (a fresh process per call; no persistent PTY session), no managed-environment parity beyond three hardcoded `DSH_*` keys, and a marker story ("always `[exit code: N]`") that diverged from the bash tool's rendering without being declared. Review of that change found the model-visible contract drifting from the implementation: the description promised spill-path reporting the renderer never performed, the README claimed exports that did not exist and rendering the tool did not do, and the tool's own tests pinned the lossy behavior. The minimal profile also left the `DSH_*` contributor seam duplicated-by-absence: plugins contributing environment facts to `ctx.bashEnv` had no effect on pwsh calls. ## Decision From a30f3f1a04d3a559041dac89ff62d6b098967e0d Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 19:00:51 +0800 Subject: [PATCH 22/61] docs(catalog): refresh the pwsh tool entry to the parity tool and fix requires lists --- docs/tool-catalog.md | 6 +++--- scripts/gen-tool-catalog.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 56a6eaaedc..27115e9f28 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -18,8 +18,8 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`, `ctx.userInteraction` | `tool/call`, `tool/result after a UI/provider answers the question` | - | ask_user_question pauses the tool call until the active UI provider returns a human answer. | | `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.codeRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/code-dispatch-start + tool/code-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated TypeScript SDK section, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`, `ctx.systemPrompt`, `ctx.userInteraction (execution time, opportunistic)` | `tool/call`, `plan/mode inactive on an approved review`, `tool/result` | - | exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-interaction seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary. | -| `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.bash`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | -| `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. | +| `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.bash`, `ctx.bashEnv`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | +| `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.tools`, `ctx.bash`, `ctx.bashEnv`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); it mirrors the bash tool call-for-call minus the sandbox surface — `run_in_background` runs register with the generic `ctx.tasks` runtime and are collected/stopped through the `task_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-bash-env`. Each call runs in a fresh process (no persistent PTY session; ConPTY is roadmap work), with native `C:\...` paths and `$env:NAME` variables. | | `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect`, `cordis_mount`, `cordis_unmount` | `ctx.tools` | `tool/call`, `tool/result`, `process-local temporary Plugin lifecycle` | - | Not in any shipped tree (a deliberate opt-in — temporary Plugin code reaches the real runtime, see .agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins created by cordis_mount may register ADDITIONAL model-visible tools until unmounted or DSH restarts; a full changed request header logs those tool-set changes. | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.tools`, `ctx.pty`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`, `ctx.fs` | `tool/call`, `fs/observed after successful file operations`, `tool/result` | - | Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal surface. | @@ -248,7 +248,7 @@ Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. Eac Source: [`packages/bash/tool-pwsh/src/index.ts`](../packages/bash/tool-pwsh/src/index.ts) -The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\...` paths and `$env:NAME` variables. +The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); it mirrors the bash tool call-for-call minus the sandbox surface — `run_in_background` runs register with the generic `ctx.tasks` runtime and are collected/stopped through the `task_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-bash-env`. Each call runs in a fresh process (no persistent PTY session; ConPTY is roadmap work), with native `C:\...` paths and `$env:NAME` variables. ## `@deepseek-ai/dsh-tool-cordis` diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 9af8fbe7c2..1692b9fead 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -193,7 +193,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ pkg: '@deepseek-ai/dsh-tool-bash', dir: 'tool-bash', source: 'packages/bash/tool-bash/src/index.ts', - requires: ['ctx.tools', 'ctx.bash', 'ctx.tasks at call time for run_in_background'], + requires: ['ctx.tools', 'ctx.bash', 'ctx.bashEnv', 'ctx.tasks at call time for run_in_background'], writes: ['tool/call', 'tool/result'], async mount(ctx) { await ctx.plugin(LocalSubprocessService) @@ -208,7 +208,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ pkg: '@deepseek-ai/dsh-tool-pwsh', dir: 'tool-pwsh', source: 'packages/bash/tool-pwsh/src/index.ts', - requires: ['ctx.tools', 'ctx.bash', 'ctx.systemPrompt'], + requires: ['ctx.tools', 'ctx.bash', 'ctx.bashEnv', 'ctx.tasks at call time for run_in_background'], writes: ['tool/call', 'tool/result'], async mount(ctx) { // The pwsh tool consumes the bash executor seam; the schema harvest @@ -220,7 +220,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ await ctx.plugin(ToolPwsh) }, note: - 'The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); minimal by design — foreground only, no sandbox escalation, native `C:\\...` paths and `$env:NAME` variables.', + 'The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); it mirrors the bash tool call-for-call minus the sandbox surface — `run_in_background` runs register with the generic `ctx.tasks` runtime and are collected/stopped through the `task_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-bash-env`. Each call runs in a fresh process (no persistent PTY session; ConPTY is roadmap work), with native `C:\\...` paths and `$env:NAME` variables.', }, { pkg: '@deepseek-ai/dsh-tool-cordis', From c376802f44d4588781963c1a37e7e06c30028a34 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 19:37:09 +0800 Subject: [PATCH 23/61] fix(acp-snapshot): skip pwshOnly scenarios without pwsh and mount task tools in the pwsh composition --- docs/testing.i18n.yaml | 4 +- docs/testing.md | 2 +- docs/testing.zh.md | 2 +- examples/acp-agent/tests/acp.snapshot.ts | 9 ++++ .../acp-agent/tests/pwsh.cordis.snapshot.yml | 2 +- examples/acp-agent/tests/pwsh.cordis.yml | 2 +- .../snapshots/pwsh-tool-turn/session.jsonl | 2 +- .../pwsh-tool-turn/system-prompt.expected.md | 2 + .../pwsh-tool-turn/tool-schemas.expected.json | 52 +++++++++++++++++++ packages/support/acp-snapshot/src/suite.ts | 28 ++++++++-- .../support/acp-snapshot/tests/suite.spec.ts | 8 +++ 11 files changed, 101 insertions(+), 12 deletions(-) diff --git a/docs/testing.i18n.yaml b/docs/testing.i18n.yaml index df4b94e6ce..ba8b076346 100644 --- a/docs/testing.i18n.yaml +++ b/docs/testing.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 docs/testing.md -testing.md: 8c16dea5e90ff330992a2d0e38f47abc9da20b26 -testing.zh.md: f99f02e2a733a94cadeffddc2c5033242bfde59b +testing.md: e441b4f467b031aecb595b86664ec8d7aeddf2c7 +testing.zh.md: f787cf0c3131acc8f4ddaf4da2f6205f5a0f0a48 diff --git a/docs/testing.md b/docs/testing.md index 8c16dea5e9..e441b4f467 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -46,4 +46,4 @@ An e2e assertion re-runs the command or re-reads the file externally; a keyword ## When a snapshot test is required -Every non-trivial model-, protocol-, or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock/test-only compositions, and PR rationale do not replace the assembled transcript; extend the harness when needed. ACP automation scenarios use `examples//tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory (`examples/acp-agent` is primary); `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. Completed interactive-terminal journeys use JSONL-driven scenarios under `apps/cli/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when input, Loader selection, or terminal teardown changes. Browser-rendered web GUI journeys use `apps/web/tests/snapshots/`. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness can express it before implementation. +Every non-trivial model-, protocol-, or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock-only compositions, and PR rationale do not replace the assembled transcript. ACP automation scenarios use `examples//tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory; `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. The `pwsh-tool-turn` ACP scenario boots real `pwsh` and skips where it is absent. Completed interactive-terminal journeys use JSONL-driven scenarios under `apps/cli/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when terminal teardown changes. Browser-rendered web GUI journeys use `apps/web/tests/snapshots/`. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness expresses it before implementation. diff --git a/docs/testing.zh.md b/docs/testing.zh.md index f99f02e2a7..f787cf0c31 100644 --- a/docs/testing.zh.md +++ b/docs/testing.zh.md @@ -46,4 +46,4 @@ e2e 断言应重新运行命令或从外部重新读取文件;对 agent 自身 ## 何时需要快照测试 -每项非平凡的模型可见、协议可见或人类可见变更,都必须在同一 PR 中,通过可运行示例所属的快照套件添加或更新无密钥场景。包测试、e2e 断言、mock 与仅测试组合、PR 理由都不能取代组装后的 transcript;必要时应扩展 harness。ACP 自动化场景使用 `examples//tests/snapshots/`,即基于 [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) 套件工厂的场景表(`examples/acp-agent` 为主套件);`examples/headless-agent` 拥有 `stream-json` 快照与回放 fixture。已完成的交互式终端旅程使用 `apps/cli/tests/snapshots/` 下由 JSONL 驱动的场景;瞬态呈现使用包内语义矩阵,输入、Loader 选择或终端清理发生变化时还要添加 PTY 用例。新的能力 seam、生命周期形态或 transcript 呈现接口在计划阶段就要列出每个覆盖层级,并在实现前验证 harness 能够表达它们。 +每项非平凡的模型可见、协议可见或人类可见变更,都必须在同一 PR 中,通过可运行示例所属的快照套件添加或更新无密钥场景。包测试、e2e 断言、mock 与仅测试组合、PR 理由都不能取代组装后的 transcript。ACP 自动化场景使用 `examples//tests/snapshots/`,即基于 [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) 套件工厂的场景表;`examples/headless-agent` 拥有 `stream-json` 快照与回放 fixture。`pwsh-tool-turn` ACP 场景启动真实 `pwsh`,在无 `pwsh` 的主机上跳过。已完成的交互式终端旅程使用 `apps/cli/tests/snapshots/` 下由 JSONL 驱动的场景;瞬态呈现使用包内语义矩阵,终端清理发生变化时还要添加 PTY 用例。新的能力 seam、生命周期形态或 transcript 呈现接口在计划阶段就要列出每个覆盖层级,并在实现前验证 harness 能够表达它们。 diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index 41e34acc42..7e36e854d6 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -1,5 +1,6 @@ import { fileURLToPath } from 'node:url' import { readFileSync } from 'node:fs' +import { spawnSync } from 'node:child_process' import { mkdir, utimes, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { homedir } from 'node:os' @@ -168,6 +169,9 @@ const SCENARIOS: Scenario[] = [ pinsHeader: true, headerClass: 'pwsh', configPath: PWSH_CONFIG, + // The composition boots the real pwsh executor; hosts without a `pwsh` + // binary skip the run (fixtures stay guarded). + pwshOnly: true, }, { name: 'todo-write', hasModelTurn: true, recorded: true }, { @@ -431,11 +435,16 @@ const SCENARIOS: Scenario[] = [ }, ] +// Hosts without a `pwsh` binary skip the pwsh-tool-turn run (its fixtures +// stay guarded); the probe follows the executor's own resolution. +const hasPwsh = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 + defineAcpSnapshotSuite({ agent: AGENT, snapshotsDir: SNAPSHOTS_DIR, scenarios: SCENARIOS, mode: snapshotModeFromEnv(process.env.DSH_SNAPSHOT), + hasPwsh, }) it('packed ACP fixture retains every chunk row kind without changing the logical session', () => { diff --git a/examples/acp-agent/tests/pwsh.cordis.snapshot.yml b/examples/acp-agent/tests/pwsh.cordis.snapshot.yml index c52dbbaf57..91fdeabf53 100644 --- a/examples/acp-agent/tests/pwsh.cordis.snapshot.yml +++ b/examples/acp-agent/tests/pwsh.cordis.snapshot.yml @@ -27,7 +27,7 @@ workspaceContext: false skills: enabled: false - toolTasks: false +# task_output/task_kill stay mounted so background pwsh runs are readable and killable. goals: false # The pwsh tool replaces the bundle's bash tool in this composition. toolBash: false diff --git a/examples/acp-agent/tests/pwsh.cordis.yml b/examples/acp-agent/tests/pwsh.cordis.yml index 46a595d7ff..cb8305c7d9 100644 --- a/examples/acp-agent/tests/pwsh.cordis.yml +++ b/examples/acp-agent/tests/pwsh.cordis.yml @@ -26,7 +26,7 @@ workspaceContext: false skills: enabled: false - toolTasks: false +# task_output/task_kill stay mounted so background pwsh runs are readable and killable. goals: false # The pwsh tool replaces the bundle's bash tool in this composition. toolBash: false diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl index 333948541c..061d3261a3 100644 --- a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl @@ -15,7 +15,7 @@ {"type":"assistant/chunk","seq":65,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":66,"time":1785655507604,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to run a PowerShell command that outputs \"PWSH_OK\" and then reply with \"DONE\"."},{"type":"tool-call","id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"4d81cc10-507e-49a8-96f4-aa3ae5ad2eb5"},"usage":{"inputTokens":816,"outputTokens":96,"cacheReadTokens":0,"reasoningTokens":25}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65],"surfaceOp":"append"} {"type":"tool/call","seq":67,"time":1785655507605,"data":{"turn":1,"step":1,"callId":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}} -{"type":"tool/result","seq":68,"time":1785655507994,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_oEhmLGLNsvlumiE0WkXD0511"},"content":[{"type":"tool-result","toolCallId":"call_00_oEhmLGLNsvlumiE0WkXD0511","content":[{"type":"text","text":"PWSH_OK\n"}],"isError":false}],"role":"user","id":"84a96d55-5bd5-46fc-ab0d-918882c504e2"}},"sourceEventSeqs":[67],"surfaceOp":"append"} +{"type":"tool/result","seq":68,"time":1785655507994,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_oEhmLGLNsvlumiE0WkXD0511"},"content":[{"type":"tool-result","toolCallId":"call_00_oEhmLGLNsvlumiE0WkXD0511","content":[{"type":"text","text":"PWSH_OK\r\n"}],"isError":false}],"role":"user","id":"84a96d55-5bd5-46fc-ab0d-918882c504e2"}},"sourceEventSeqs":[67],"surfaceOp":"append"} {"type":"step/end","seq":69,"time":1785655507994,"data":{"turn":1,"step":1}} {"type":"step/start","seq":70,"time":1785655508000,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":71,"time":1785655508608,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/system-prompt.expected.md index 9b51477daf..f354648c41 100644 --- a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/system-prompt.expected.md @@ -3,3 +3,5 @@ You are an AI agent powered by the DeepSeek Harness SDK. You are a concise snapshot agent working in {{cwd}}. Non-zero exits are reported as `[exit code: N]` markers; investigate failures before moving on. On Windows a killed process settles as `[exit code: 1]` without a signal marker; treat a bare exit 1 after an interruption as a termination, not a command failure. + +Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/tool-schemas.expected.json index 6f6d3fa729..611de722e3 100644 --- a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/tool-schemas.expected.json @@ -32,6 +32,58 @@ "description" ] } + }, + { + "name": "task_kill", + "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", + "parameters": { + "type": "object", + "properties": { + "task_id": { + "type": "string", + "description": "Task id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the task." + } + }, + "required": [ + "task_id" + ] + } + }, + { + "name": "task_list", + "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "task_output", + "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", + "parameters": { + "type": "object", + "properties": { + "task_id": { + "type": "string", + "description": "Task id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." + } + }, + "required": [ + "task_id" + ] + } } ], "changes": [] diff --git a/packages/support/acp-snapshot/src/suite.ts b/packages/support/acp-snapshot/src/suite.ts index c8434bb8c9..f9e97dd45b 100644 --- a/packages/support/acp-snapshot/src/suite.ts +++ b/packages/support/acp-snapshot/src/suite.ts @@ -161,25 +161,37 @@ export interface Scenario { * test is skipped on Windows; its fixtures stay guarded on every platform. */ posixOnly?: boolean + /** + * Whether the scenario boots a composition that needs a real `pwsh` on PATH + * (the pwsh-tool-turn scenario). The run test is skipped when the suite's + * {@link SnapshotSuiteOptions.hasPwsh} probe is false; fixtures stay guarded + * on every platform. + */ + pwshOnly?: boolean } /** * Whether a scenario's run test is skipped for this mode and host: record mode - * skips authored (non-`recorded`) scenarios, and {@link Scenario.posixOnly} - * scenarios skip on Windows. + * skips authored (non-`recorded`) scenarios, {@link Scenario.posixOnly} + * scenarios skip on Windows, and {@link Scenario.pwshOnly} scenarios skip + * when the caller's `hasPwsh` probe is false. * * @param scenario The scenario whose run test is being registered. * @param recording Whether the suite runs in record mode. * @param platform The running Node platform, injectable for unit coverage. + * @param hasPwsh The caller's pwsh-availability probe; `pwshOnly` scenarios + * skip unless it is true. * @returns True when the scenario's run test must not execute. */ export function scenarioSkipped( scenario: Scenario, recording: boolean, platform: NodeJS.Platform = process.platform, + hasPwsh?: boolean, ): boolean { if (recording && !scenario.recorded) return true - return scenario.posixOnly === true && platform === 'win32' + if (scenario.posixOnly === true && platform === 'win32') return true + return scenario.pwshOnly === true && hasPwsh !== true } /** One stdout expected output selected for a platform run. */ @@ -220,6 +232,11 @@ export interface SnapshotSuiteOptions { * from `$DSH_SNAPSHOT` — env reading stays outside this library. */ mode: 'replay' | 'record' | 'refresh' + /** + * Whether a real `pwsh` executable is available on this host (the probe the + * caller owns; `pwshOnly` scenarios skip when this is not true). + */ + hasPwsh?: boolean } /** One scenario's generated claim on a shared snapshot file. */ @@ -973,8 +990,9 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { scenarioSuite('snapshot scenarios', () => { for (const scenario of scenarios) { // In RECORD mode, only re-run the `recorded` (live-API) scenarios; the `authored` ones - // (sidecar-driven errors/cancel) are never re-recorded. `posixOnly` scenarios skip on Windows. - it.skipIf(scenarioSkipped(scenario, RECORDING))(`snapshot: ${scenario.name} matches the expected outputs`, async ({ expect }) => { + // (sidecar-driven errors/cancel) are never re-recorded. `posixOnly` scenarios skip on Windows; + // `pwshOnly` scenarios skip when the caller's `hasPwsh` probe is false. + it.skipIf(scenarioSkipped(scenario, RECORDING, process.platform, options.hasPwsh))(`snapshot: ${scenario.name} matches the expected outputs`, async ({ expect }) => { const dir = join(snapshotsDir, scenario.name) const input = JSON.parse(await readFile(join(dir, 'input.json'), 'utf8')) as InputScript const overrideFile = join(dir, 'replay.override.json') diff --git a/packages/support/acp-snapshot/tests/suite.spec.ts b/packages/support/acp-snapshot/tests/suite.spec.ts index 6f16844595..d8cb177a16 100644 --- a/packages/support/acp-snapshot/tests/suite.spec.ts +++ b/packages/support/acp-snapshot/tests/suite.spec.ts @@ -459,6 +459,7 @@ describe('stdoutExpectedVariants', () => { describe('scenarioSkipped', () => { const authored: Scenario = { name: 'authored', hasModelTurn: true, recorded: false } const posix: Scenario = { name: 'posix-cancel', hasModelTurn: true, recorded: false, posixOnly: true } + const pwsh: Scenario = { name: 'pwsh-tool', hasModelTurn: true, recorded: false, pwshOnly: true } it('skips authored scenarios only while recording', () => { expect(scenarioSkipped(authored, true, 'linux')).toBe(true) @@ -471,6 +472,13 @@ describe('scenarioSkipped', () => { expect(scenarioSkipped(posix, false, 'darwin')).toBe(false) expect(scenarioSkipped(authored, false, 'win32')).toBe(false) }) + + it('skips pwshOnly scenarios when the host lacks pwsh, and runs them otherwise', () => { + expect(scenarioSkipped(pwsh, false, 'linux', false)).toBe(true) + expect(scenarioSkipped(pwsh, false, 'win32', true)).toBe(false) + expect(scenarioSkipped(pwsh, false, 'linux', true)).toBe(false) + expect(scenarioSkipped(authored, false, 'linux', false)).toBe(false) + }) }) describe('fixtureContext', () => { From d8ee37d87a48de06cf80a3f1c71464608fca327e Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 19:37:25 +0800 Subject: [PATCH 24/61] fix(tool-pwsh): present background calls on the generic card like the bash tool --- packages/bash/tool-pwsh/src/index.ts | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/packages/bash/tool-pwsh/src/index.ts b/packages/bash/tool-pwsh/src/index.ts index c8a02f0428..30ab72482f 100644 --- a/packages/bash/tool-pwsh/src/index.ts +++ b/packages/bash/tool-pwsh/src/index.ts @@ -18,7 +18,7 @@ import { isAbsolute, resolve as resolvePath } from 'node:path' import type { Context } from 'cordis' import z from 'schemastery' import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools' -import type { TerminalCallView, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools' +import type { GenericCallView, TerminalCallView, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools' import { HarnessError } from '@deepseek-ai/dsh-llm' import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-system-prompt' @@ -276,12 +276,25 @@ export function apply(ctx: Context, config: Config = {}): void { return canonicalPwshResult(result) }, /* jscpd:ignore-end */ - presentCall: (args: PwshToolArgs): TerminalCallView => ({ - card: 'terminal', - title: args.command, - description: args.description, - ...args.workdir !== undefined ? { cwd: args.workdir } : {}, - }), + presentCall: (args: PwshToolArgs): TerminalCallView | GenericCallView => { + // Background acknowledgements carry no terminal exit status; the generic + // card mirrors the bash tool's background presentation. + if (args.run_in_background === true) { + return { + card: 'generic', + title: args.command, + kind: 'execute', + rawInput: args.command, + content: [{ type: 'text', text: args.description }], + } + } + return { + card: 'terminal', + title: args.command, + description: args.description, + ...args.workdir !== undefined ? { cwd: args.workdir } : {}, + } + }, presentResult: (_args: unknown, result: ToolResult): ToolResultView | undefined => { const block = result.content.length === 1 ? result.content[0] : undefined if (block === undefined || block.type !== 'text') return undefined From 12c6f43bf1f65e441b33fba44d3b1684ad2f3e8e Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 19:37:29 +0800 Subject: [PATCH 25/61] fix(tool-bash): report foreground aborts as the TOOL_ABORTED HarnessError --- packages/bash/tool-bash/src/index.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/bash/tool-bash/src/index.ts b/packages/bash/tool-bash/src/index.ts index c2a5c3e288..91a88c9cca 100644 --- a/packages/bash/tool-bash/src/index.ts +++ b/packages/bash/tool-bash/src/index.ts @@ -381,7 +381,11 @@ export function apply(ctx: Context, config: Config = {}): void { ...request, signal: exec.signal, })) - if (result.aborted) throw new Error('command aborted') + if (result.aborted) { + const error = new HarnessError('tool call aborted', TOOL_ABORTED) + error.name = 'AbortError' + throw error + } return { kind: 'foreground' as const, ...canonicalBashResult(result) } }, presentCall: presentBashCall, From 5e437d399680a2e784d6f39c6ea33cdd056f6bc7 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 19:37:45 +0800 Subject: [PATCH 26/61] docs(pwsh): scope the encoding claim, document the PATH probe and preamble limitation, and fix catalog requires lists --- .../feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml | 4 ++-- .../feature/2026-08-02-pwsh-tool-bash-parity.md | 2 +- .../feature/2026-08-02-pwsh-tool-bash-parity.zh.md | 2 +- docs/config-catalog.md | 5 +++-- docs/tool-catalog.md | 4 ++-- packages/bash/pwsh-local/README.i18n.yaml | 4 ++-- packages/bash/pwsh-local/README.md | 3 ++- packages/bash/pwsh-local/README.zh.md | 3 ++- packages/bash/pwsh-local/src/index.ts | 7 ++++--- scripts/gen-tool-catalog.ts | 4 ++-- 10 files changed, 21 insertions(+), 17 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml index 582d3fb592..913cf0cc06 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.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-02-pwsh-tool-bash-parity.md -2026-08-02-pwsh-tool-bash-parity.md: f5e3ecfa7e34240ef226f0bceda5d83194667744 -2026-08-02-pwsh-tool-bash-parity.zh.md: 03aa9ed2109153d2e0426e7b680eb18c91f89aa7 +2026-08-02-pwsh-tool-bash-parity.md: fb0f3fff1ed00dfde286781733881facfb1e6c7b +2026-08-02-pwsh-tool-bash-parity.zh.md: 9dc84bcd5e53c52d5d68b2db61cf79fe7fb97bb9 diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md index f5e3ecfa7e..fb0f3fff1e 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md @@ -15,7 +15,7 @@ The first Windows-native foundation shipped `dsh-tool-pwsh` as a deliberately mi - **Rendering adopts the bash story verbatim**: stdout, a marked `[stderr]` section, truncation notices with spill paths, `(no output)` for an empty body, and exit markers only for non-zero exits — a clean exit produces no marker. The description and the `tool:pwsh` prompt section state this precisely ("Non-zero exits are reported as `[exit code: N]` markers"), deliberately not copying the bash prompt's "every result" phrasing, which its own renderer contradicts. - **`run_in_background` is wired through the generic task runtime** exactly like the bash tool: preflight, owner registration, `task_output`/`task_kill` control, and the same outcome mapping. `pwsh-local`'s already-mirrored `start()` handle backs it. - **The `DSH_*` environment is shared, not duplicated**: `BashEnvRegistry` moved out of `dsh-tool-bash` into a new tool-independent `@deepseek-ai/dsh-bash-env` package (`ctx.bashEnv` + built-ins + the session-persistence contributor), and both shell tools inject it. Contributors apply to pwsh calls exactly as they do to bash calls, resolving the bash tool's `FIXME(bash-env-ownership)`. -- **Windows reality is pinned where bash has no analog**: every command runs under a UTF-8 I/O preamble so the Windows PowerShell 5.1 fallback cannot garble non-ASCII output through the UTF-8-decoding collector, and the prompts teach that Windows forced termination settles as exit 1 without a signal marker. +- **Windows reality is pinned where bash has no analog**: every command runs under a UTF-8 output preamble so the Windows PowerShell 5.1 fallback cannot garble non-ASCII output through the UTF-8-decoding collector, and the prompts teach that Windows forced termination settles as exit 1 without a signal marker. - **Out of scope, unchanged**: sandbox escalation (waits for a Windows-confining executor), persistent PTY shells (backends are Linux/macOS-only; ConPTY is roadmap work), and pwsh-specific TUI/GUI presentation (generic/terminal cards stay; a PowerShell-aware terminal card with an exit pill is roadmap work). ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md index 03aa9ed210..9dc84bcd5e 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md @@ -15,7 +15,7 @@ Status: implemented - **渲染完全采用 bash 故事**:stdout、带标记的 `[stderr]` 段、带 spill 路径的截断通知、空体渲染 `(no output)`、退出 marker 仅限非零退出——干净退出不产生 marker。描述与 `tool:pwsh` prompt section 精确陈述这一点("Non-zero exits are reported as `[exit code: N]` markers"),刻意不复制 bash prompt 中与其自身渲染矛盾的 "every result" 措辞。 - **`run_in_background` 经通用任务运行时接线**,与 bash 工具完全一致:预检、owner 注册、`task_output`/`task_kill` 控制与相同的结果映射。其背后是 `pwsh-local` 早已镜像好的 `start()` 句柄。 - **`DSH_*` 环境共享而非复制**:`BashEnvRegistry` 从 `dsh-tool-bash` 迁入新的工具无关包 `@deepseek-ai/dsh-bash-env`(`ctx.bashEnv` + 内置事实 + session-persistence contributor),两个 shell 工具都注入它。contributor 对 pwsh 调用与 bash 调用一视同仁,并消化了 bash 工具的 `FIXME(bash-env-ownership)`。 -- **Windows 现实在 bash 无对应处钉死**:每条命令都在 UTF-8 I/O preamble 下运行,使 Windows PowerShell 5.1 兜底无法经 UTF-8 解码的 collector 破坏非 ASCII 输出;prompt 教授 Windows 强制终止以无 signal 的 exit 1 结算。 +- **Windows 现实在 bash 无对应处钉死**:每条命令都在 UTF-8 输出 preamble 下运行,使 Windows PowerShell 5.1 兜底无法经 UTF-8 解码的 collector 破坏非 ASCII 输出;prompt 教授 Windows 强制终止以无 signal 的 exit 1 结算。 - **范围外,不变**:sandbox 升级(等待 Windows-confining 执行器)、持久 PTY shell(后端仅限 Linux/macOS;ConPTY 属路线图)、pwsh 专属 TUI/GUI 呈现(维持 generic/terminal 卡;带退出 pill 的 PowerShell 感知 terminal 卡属路线图)。 ## 备选方案 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 2149981ad3..f14a7a5900 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -996,8 +996,9 @@ export interface Config { graceMs?: number /** * Explicit pwsh executable. When omitted, well-known Windows install - * locations are probed first (PowerShell 7, then Windows PowerShell 5.1), - * falling back to a bare `pwsh` resolved through PATH. + * locations and PATH entries are probed in order (PowerShell 7 install, + * PATH entries such as the Microsoft Store install, then Windows + * PowerShell 5.1), falling back to a bare `pwsh` resolved through PATH. */ pwshPath?: string } diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 27115e9f28..38125bcd4a 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -18,8 +18,8 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`, `ctx.userInteraction` | `tool/call`, `tool/result after a UI/provider answers the question` | - | ask_user_question pauses the tool call until the active UI provider returns a human answer. | | `@deepseek-ai/dsh-tools` | `run_code` | `ctx.tools`, `ctx.codeRuntime (execution time)`, `ctx.systemPrompt` | `tool/call`, `one tool/code-dispatch-start + tool/code-dispatch pair per bridged sub-call`, `tool/result` | - | Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry's only wire contribution; the other visible capabilities are declared in a generated TypeScript SDK section, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result. | | `@deepseek-ai/dsh-plan-mode` | `exit_plan_mode` | `ctx.tools`, `ctx.systemPrompt`, `ctx.userInteraction (execution time, opportunistic)` | `tool/call`, `plan/mode inactive on an approved review`, `tool/result` | - | exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-interaction seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary. | -| `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.bash`, `ctx.bashEnv`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | -| `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.tools`, `ctx.bash`, `ctx.bashEnv`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); it mirrors the bash tool call-for-call minus the sandbox surface — `run_in_background` runs register with the generic `ctx.tasks` runtime and are collected/stopped through the `task_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-bash-env`. Each call runs in a fresh process (no persistent PTY session; ConPTY is roadmap work), with native `C:\...` paths and `$env:NAME` variables. | +| `@deepseek-ai/dsh-tool-bash` | `bash` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt`, `ctx.bashEnv`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.tasks` runtime and is collected/stopped through the `task_*` tools from `@deepseek-ai/dsh-tool-tasks`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled. | +| `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt`, `ctx.bashEnv`, `ctx.tasks at call time for run_in_background` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.bash`); it mirrors the bash tool call-for-call minus the sandbox surface — `run_in_background` runs register with the generic `ctx.tasks` runtime and are collected/stopped through the `task_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-bash-env`. Each call runs in a fresh process (no persistent PTY session; ConPTY is roadmap work), with native `C:\...` paths and `$env:NAME` variables. | | `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect`, `cordis_mount`, `cordis_unmount` | `ctx.tools` | `tool/call`, `tool/result`, `process-local temporary Plugin lifecycle` | - | Not in any shipped tree (a deliberate opt-in — temporary Plugin code reaches the real runtime, see .agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins created by cordis_mount may register ADDITIONAL model-visible tools until unmounted or DSH restarts; a full changed request header logs those tool-set changes. | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.tools`, `ctx.pty`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`, `ctx.fs` | `tool/call`, `fs/observed after successful file operations`, `tool/result` | - | Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal surface. | diff --git a/packages/bash/pwsh-local/README.i18n.yaml b/packages/bash/pwsh-local/README.i18n.yaml index 40455ff56b..d58935d285 100644 --- a/packages/bash/pwsh-local/README.i18n.yaml +++ b/packages/bash/pwsh-local/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/bash/pwsh-local/README.md -README.md: 430419cc34added1e983e3fc119cfeb1eebb6829 -README.zh.md: 4a1246a31a22143d6a260cc7b3024dc490f19b7f +README.md: bb5d941b0cc98fb14e0b47d5bbe0bffb5192edd8 +README.zh.md: efd8aac2b8766d1082b85905fce9867151b77310 diff --git a/packages/bash/pwsh-local/README.md b/packages/bash/pwsh-local/README.md index 430419cc34..bb5d941b0c 100644 --- a/packages/bash/pwsh-local/README.md +++ b/packages/bash/pwsh-local/README.md @@ -28,7 +28,7 @@ The package root exports the default and named `PwshLocalExecutor` plugin, its ` The Windows counterpart of `dsh-bash-local`, deliberately mirroring its semantics call-for-call: - **Spawn per call, no shell state** — every call is a fresh non-interactive `pwsh -Command` (deterministic; no profile files). The `-NoLogo -NoProfile -NonInteractive` flags disable startup banners, profile loading, and prompts that would garble tool output. -- **UTF-8 I/O pinned** — every command runs with `[Console]::OutputEncoding` and `$OutputEncoding` set to UTF-8 first, so the Windows PowerShell 5.1 fallback (or any host whose console code page is not UTF-8) cannot garble non-ASCII output: the subprocess collector decodes bytes as UTF-8. pwsh 7 defaults to UTF-8 and is unaffected. +- **UTF-8 output pinned** — every command runs with `[Console]::OutputEncoding` and `$OutputEncoding` set to UTF-8 first, so the Windows PowerShell 5.1 fallback (or any host whose console code page is not UTF-8) cannot garble non-ASCII output: the subprocess collector decodes bytes as UTF-8. Input encoding is left at the host default; pwsh 7 defaults to UTF-8 and is unaffected. - **Executable resolution** — `resolvePwshPath` prefers an explicit `pwshPath`, then on Windows probes PowerShell 7's install location, every PATH entry (Microsoft Store installs; surrounding quotes stripped), and Windows PowerShell 5.1 as a legacy last resort, checking `existsSync` on each; elsewhere it falls back to a bare `pwsh` resolved through PATH. Resolution is a pure function of `(configured, env, platform)` and happens once at construction. - **Configured budgets over managed groups** — `resolve()` fills `workdir`/`timeoutMs`/`stdoutMaxBytes` from config, and every spawn hands the service explicit byte caps, spill cap, and `graceMs`. Tree termination (taskkill on Windows, process-group signals on POSIX), the post-exit pipe-drain grace, tail-keep truncation, and bounded spill files are [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) mechanics. A foreground `BashExecRequest.stdoutMaxBytes` can raise stdout's capture budget for one trusted caller; stderr and background runs still use `maxOutputBytes`. - **Timeout and cancel classification** — `run()` fuses its config-clamped timeout with the caller's signal through one deadline; only the executor's own timeout reports `timedOut`, an upstream cancel reports `aborted`, and a self-terminated command reports neither ([timeout-library Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md)). Windows reports forced termination as exit 1 without a signal, so signal-stamped facts (`signal`, `killed` status) are POSIX-only there; the timeout/abort classification is platform-independent. @@ -50,5 +50,6 @@ No direct invalidation; the named consumer owns any request-prefix changes. - **The command string is PowerShell text** — the `-Command` domain has no shell-quoting layer, but a model-facing command is parsed by PowerShell itself, so PowerShell syntax errors are command failures, not launch failures. - **A background spawn-failure note is single-delivery** — the subprocess service buffers no output for a process that never ran, so the executor injects `spawn failed: …` into exactly one `readOutput()` delta; a reader that discards that delta cannot recover it. - **Windows termination reports no signal** — a force-killed process settles as exit 1 with `signal: null`, so signal-based status classification (POSIX `killed`) does not apply on Windows; `kill()`-initiated stops still stamp `killed` directly. +- **The encoding preamble precedes the command** — PowerShell requires `param(...)` and `using namespace`/`using assembly` statements at the very top of a script, so a command whose first statement is one of those cannot run under the UTF-8 output preamble; prefix such scripts with a no-op statement (or `& { … }`) first. Scrub-heuristic and spill-retention caveats live with [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md), which owns those mechanics. diff --git a/packages/bash/pwsh-local/README.zh.md b/packages/bash/pwsh-local/README.zh.md index 4a1246a31a..efd8aac2b8 100644 --- a/packages/bash/pwsh-local/README.zh.md +++ b/packages/bash/pwsh-local/README.zh.md @@ -28,7 +28,7 @@ 作为 `dsh-bash-local` 的 Windows 对应物,逐调用地镜像其语义: - **每次调用新建进程,无 shell 状态**——每次调用都是全新的非交互 `pwsh -Command`(确定性;不加载 profile 文件)。`-NoLogo -NoProfile -NonInteractive` 关闭启动横幅、profile 加载与会干扰工具输出的提示符。 -- **UTF-8 I/O 固定**——每条命令都先以 UTF-8 设置 `[Console]::OutputEncoding` 与 `$OutputEncoding`,因此 Windows PowerShell 5.1 兜底(或任何控制台代码页非 UTF-8 的主机)不会破坏非 ASCII 输出:subprocess collector 以 UTF-8 解码字节。pwsh 7 默认为 UTF-8,不受影响。 +- **UTF-8 输出固定**——每条命令都先以 UTF-8 设置 `[Console]::OutputEncoding` 与 `$OutputEncoding`,因此 Windows PowerShell 5.1 兜底(或任何控制台代码页非 UTF-8 的主机)不会破坏非 ASCII 输出:subprocess collector 以 UTF-8 解码字节。输入编码保持宿主默认;pwsh 7 默认为 UTF-8,不受影响。 - **可执行文件解析**——`resolvePwshPath` 优先显式 `pwshPath`,然后在 Windows 上依次探测 PowerShell 7 安装位置、每个 PATH 条目(Microsoft Store 安装;剥离两端引号)以及作为遗留兜底的 Windows PowerShell 5.1,逐一检查 `existsSync`;其他平台回退为通过 PATH 解析的裸 `pwsh`。解析是 `(configured, env, platform)` 的纯函数,在构造时执行一次。 - **受管进程组之上的配置预算**——`resolve()` 从配置填充 `workdir`/`timeoutMs`/`stdoutMaxBytes`,每次 spawn 都向服务提供显式字节上限、spill 上限与 `graceMs`。进程树终止(Windows 用 taskkill,POSIX 用进程组信号)、退出后管道排空宽限、保尾截断与有界 spill 文件是 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 的机制。前台 `BashExecRequest.stdoutMaxBytes` 可为单个受信调用方提高 stdout 捕获预算;stderr 与后台运行仍使用 `maxOutputBytes`。 - **超时与取消分类**——`run()` 通过一个 deadline 融合配置夹取的超时与调用方信号;只有执行器自身超时报告 `timedOut`,上游取消报告 `aborted`,自我终止的命令两者都不报告(见 [timeout 库 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md))。Windows 将强制终止报告为退出码 1 且无信号,因此基于信号的实情(`signal`、`killed` 状态)在那里仅限 POSIX;超时/取消分类与平台无关。 @@ -50,5 +50,6 @@ - **命令字符串是 PowerShell 文本**——`-Command` 域没有 shell 引号层,但面向模型的命令由 PowerShell 自己解析,因此 PowerShell 语法错误是命令失败,而非启动失败。 - **后台 spawn 失败提示只投递一次**——subprocess 服务不会为从未运行的进程缓冲输出,因此执行器只把 `spawn failed: …` 注入一次 `readOutput()` 增量;丢弃该增量的读取方无法恢复它。 - **Windows 终止不报告信号**——被强制终止的进程以退出码 1、`signal: null` 结束,因此基于信号的状态分类(POSIX `killed`)在 Windows 上不适用;`kill()` 发起的停止仍会直接盖上 `killed`。 +- **编码 preamble 位于命令之前**——PowerShell 要求 `param(...)` 与 `using namespace`/`using assembly` 语句位于脚本最顶部,因此以其中一种开头的命令无法在 UTF-8 输出 preamble 下运行;请先用无操作语句(或 `& { … }`)开头。 清理启发式与 spill 保留的注意事项由 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 持有,它拥有这些机制。 diff --git a/packages/bash/pwsh-local/src/index.ts b/packages/bash/pwsh-local/src/index.ts index b93bbb8d89..b966a579af 100644 --- a/packages/bash/pwsh-local/src/index.ts +++ b/packages/bash/pwsh-local/src/index.ts @@ -35,7 +35,7 @@ export const ENV_OVERRIDES = { } as const /** - * UTF-8 I/O pinning prepended to every command. The subprocess collector + * UTF-8 output pinning prepended to every command. The subprocess collector * decodes output bytes as UTF-8, but Windows PowerShell 5.1 (the last-resort * executable fallback) writes the console/OEM code page by default, which * garbles non-ASCII output; pwsh 7 defaults to UTF-8 and is unaffected. The @@ -67,8 +67,9 @@ export interface Config { graceMs?: number /** * Explicit pwsh executable. When omitted, well-known Windows install - * locations are probed first (PowerShell 7, then Windows PowerShell 5.1), - * falling back to a bare `pwsh` resolved through PATH. + * locations and PATH entries are probed in order (PowerShell 7 install, + * PATH entries such as the Microsoft Store install, then Windows + * PowerShell 5.1), falling back to a bare `pwsh` resolved through PATH. */ pwshPath?: string } diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 1692b9fead..88e07f697c 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -193,7 +193,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ pkg: '@deepseek-ai/dsh-tool-bash', dir: 'tool-bash', source: 'packages/bash/tool-bash/src/index.ts', - requires: ['ctx.tools', 'ctx.bash', 'ctx.bashEnv', 'ctx.tasks at call time for run_in_background'], + requires: ['ctx.tools', 'ctx.bash', 'ctx.systemPrompt', 'ctx.bashEnv', 'ctx.tasks at call time for run_in_background'], writes: ['tool/call', 'tool/result'], async mount(ctx) { await ctx.plugin(LocalSubprocessService) @@ -208,7 +208,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ pkg: '@deepseek-ai/dsh-tool-pwsh', dir: 'tool-pwsh', source: 'packages/bash/tool-pwsh/src/index.ts', - requires: ['ctx.tools', 'ctx.bash', 'ctx.bashEnv', 'ctx.tasks at call time for run_in_background'], + requires: ['ctx.tools', 'ctx.bash', 'ctx.systemPrompt', 'ctx.bashEnv', 'ctx.tasks at call time for run_in_background'], writes: ['tool/call', 'tool/result'], async mount(ctx) { // The pwsh tool consumes the bash executor seam; the schema harvest From ed39ff096fe6424853bc41ce16cc945dba321119 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 20:07:26 +0800 Subject: [PATCH 27/61] test(fixtures): pin the TOOL_ABORTED message and keep the pwsh fixture replayable; restore trimmed testing.md clauses --- docs/testing.i18n.yaml | 4 ++-- docs/testing.md | 2 +- docs/testing.zh.md | 2 +- examples/acp-agent/tests/acp.snapshot.ts | 2 +- .../acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl | 2 +- .../acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl | 2 +- scripts/doc-budgets.manifest.json | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/testing.i18n.yaml b/docs/testing.i18n.yaml index ba8b076346..3d7569c620 100644 --- a/docs/testing.i18n.yaml +++ b/docs/testing.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 docs/testing.md -testing.md: e441b4f467b031aecb595b86664ec8d7aeddf2c7 -testing.zh.md: f787cf0c3131acc8f4ddaf4da2f6205f5a0f0a48 +testing.md: d460d9ba76eab84b79e8c66454325d03d7c5908e +testing.zh.md: 821e49b6593b924e754d5ed0d588dd1b5b566051 diff --git a/docs/testing.md b/docs/testing.md index e441b4f467..d460d9ba76 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -46,4 +46,4 @@ An e2e assertion re-runs the command or re-reads the file externally; a keyword ## When a snapshot test is required -Every non-trivial model-, protocol-, or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock-only compositions, and PR rationale do not replace the assembled transcript. ACP automation scenarios use `examples//tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory; `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. The `pwsh-tool-turn` ACP scenario boots real `pwsh` and skips where it is absent. Completed interactive-terminal journeys use JSONL-driven scenarios under `apps/cli/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when terminal teardown changes. Browser-rendered web GUI journeys use `apps/web/tests/snapshots/`. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness expresses it before implementation. +Every non-trivial model-, protocol-, or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock/test-only compositions, and PR rationale do not replace the assembled transcript; extend the harness when needed. ACP automation scenarios use `examples//tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory (`examples/acp-agent` is primary); `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. The `pwsh-tool-turn` ACP scenario boots real `pwsh` and skips where it is absent. Completed interactive-terminal journeys use JSONL-driven scenarios under `apps/cli/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when input, Loader selection, or terminal teardown changes. Browser-rendered web GUI journeys use `apps/web/tests/snapshots/`. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness expresses it before implementation. diff --git a/docs/testing.zh.md b/docs/testing.zh.md index f787cf0c31..821e49b659 100644 --- a/docs/testing.zh.md +++ b/docs/testing.zh.md @@ -46,4 +46,4 @@ e2e 断言应重新运行命令或从外部重新读取文件;对 agent 自身 ## 何时需要快照测试 -每项非平凡的模型可见、协议可见或人类可见变更,都必须在同一 PR 中,通过可运行示例所属的快照套件添加或更新无密钥场景。包测试、e2e 断言、mock 与仅测试组合、PR 理由都不能取代组装后的 transcript。ACP 自动化场景使用 `examples//tests/snapshots/`,即基于 [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) 套件工厂的场景表;`examples/headless-agent` 拥有 `stream-json` 快照与回放 fixture。`pwsh-tool-turn` ACP 场景启动真实 `pwsh`,在无 `pwsh` 的主机上跳过。已完成的交互式终端旅程使用 `apps/cli/tests/snapshots/` 下由 JSONL 驱动的场景;瞬态呈现使用包内语义矩阵,终端清理发生变化时还要添加 PTY 用例。新的能力 seam、生命周期形态或 transcript 呈现接口在计划阶段就要列出每个覆盖层级,并在实现前验证 harness 能够表达它们。 +每项非平凡的模型可见、协议可见或人类可见变更,都必须在同一 PR 中,通过可运行示例所属的快照套件添加或更新无密钥场景。包测试、e2e 断言、mock 与仅测试组合、PR 理由都不能取代组装后的 transcript;必要时应扩展 harness。ACP 自动化场景使用 `examples//tests/snapshots/`,即基于 [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) 套件工厂的场景表(`examples/acp-agent` 为主套件);`examples/headless-agent` 拥有 `stream-json` 快照与回放 fixture。`pwsh-tool-turn` ACP 场景启动真实 `pwsh`,在无 `pwsh` 的主机上跳过。已完成的交互式终端旅程使用 `apps/cli/tests/snapshots/` 下由 JSONL 驱动的场景;瞬态呈现使用包内语义矩阵,输入、Loader 选择或终端清理发生变化时还要添加 PTY 用例。新的能力 seam、生命周期形态或 transcript 呈现接口在计划阶段就要列出每个覆盖层级,并在实现前验证 harness 能够表达它们。 diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index 7e36e854d6..824780ae0f 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -436,7 +436,7 @@ const SCENARIOS: Scenario[] = [ ] // Hosts without a `pwsh` binary skip the pwsh-tool-turn run (its fixtures -// stay guarded); the probe follows the executor's own resolution. +// stay guarded); a bare `pwsh` probe keeps this suite dependency-light. const hasPwsh = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 defineAcpSnapshotSuite({ diff --git a/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl b/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl index 5fe449ae48..a26655947d 100644 --- a/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/chunk","seq":14,"time":1785487611319,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":15,"time":1785487611319,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_wait","name":"bash","arguments":"{\"command\":\"node -e \\\"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\\\"\",\"description\":\"Wait until cancellation\"}"},{"type":"tool-call","id":"call_skipped","name":"bash","arguments":"{\"command\":\"printf skipped > skipped.txt\",\"description\":\"Write skipped marker\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"bd630f41-b45d-4183-a785-1ff6e7049b62"},"usage":{"inputTokens":10,"outputTokens":10}},"sourceEventSeqs":[7,8,9,10,11,12,13,14],"surfaceOp":"append"} {"type":"tool/call","seq":16,"time":1785487611319,"data":{"turn":1,"step":1,"callId":"call_wait","name":"bash","arguments":"{\"command\":\"node -e \\\"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\\\"\",\"description\":\"Wait until cancellation\"}"}} -{"type":"tool/result","seq":17,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_wait"},"content":[{"type":"tool-result","toolCallId":"call_wait","content":[{"type":"text","text":"Error: command aborted"}],"isError":true}],"role":"user","id":"252903b2-b4e1-4a33-81d8-d5befefcb27e"}},"sourceEventSeqs":[16],"surfaceOp":"append"} +{"type":"tool/result","seq":17,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_wait"},"content":[{"type":"tool-result","toolCallId":"call_wait","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true}],"role":"user","id":"252903b2-b4e1-4a33-81d8-d5befefcb27e"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"tool/call","seq":18,"time":1785487611378,"data":{"turn":1,"step":1,"callId":"call_skipped","name":"bash","arguments":"{\"command\":\"printf skipped > skipped.txt\",\"description\":\"Write skipped marker\"}"}} {"type":"tool/result","seq":19,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_skipped"},"content":[{"type":"tool-result","toolCallId":"call_skipped","content":[{"type":"text","text":"Error: tool call aborted before dispatch"}],"isError":true}],"role":"user","id":"282c5c8c-7296-4545-8014-e6393b351436"},"error":{"name":"AbortError","code":"ABORTED_BEFORE_DISPATCH"}},"sourceEventSeqs":[18],"surfaceOp":"append"} {"type":"step/end","seq":20,"time":1785487611378,"data":{"turn":1,"step":1}} diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl index 061d3261a3..333948541c 100644 --- a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl @@ -15,7 +15,7 @@ {"type":"assistant/chunk","seq":65,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":66,"time":1785655507604,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to run a PowerShell command that outputs \"PWSH_OK\" and then reply with \"DONE\"."},{"type":"tool-call","id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"4d81cc10-507e-49a8-96f4-aa3ae5ad2eb5"},"usage":{"inputTokens":816,"outputTokens":96,"cacheReadTokens":0,"reasoningTokens":25}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65],"surfaceOp":"append"} {"type":"tool/call","seq":67,"time":1785655507605,"data":{"turn":1,"step":1,"callId":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}} -{"type":"tool/result","seq":68,"time":1785655507994,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_oEhmLGLNsvlumiE0WkXD0511"},"content":[{"type":"tool-result","toolCallId":"call_00_oEhmLGLNsvlumiE0WkXD0511","content":[{"type":"text","text":"PWSH_OK\r\n"}],"isError":false}],"role":"user","id":"84a96d55-5bd5-46fc-ab0d-918882c504e2"}},"sourceEventSeqs":[67],"surfaceOp":"append"} +{"type":"tool/result","seq":68,"time":1785655507994,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_oEhmLGLNsvlumiE0WkXD0511"},"content":[{"type":"tool-result","toolCallId":"call_00_oEhmLGLNsvlumiE0WkXD0511","content":[{"type":"text","text":"PWSH_OK\n"}],"isError":false}],"role":"user","id":"84a96d55-5bd5-46fc-ab0d-918882c504e2"}},"sourceEventSeqs":[67],"surfaceOp":"append"} {"type":"step/end","seq":69,"time":1785655507994,"data":{"turn":1,"step":1}} {"type":"step/start","seq":70,"time":1785655508000,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":71,"time":1785655508608,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 5c88ab3fc2..4387a894f1 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -4,7 +4,7 @@ "docs/architecture.md": 2160, "docs/cordis-primer.md": 600, "docs/defensive-patterns.md": 550, - "docs/testing.md": 1100, + "docs/testing.md": 1120, "examples/AGENTS.md": 310, "packages/AGENTS.md": 675, "packages/README.md": 920 From efcee43c7d6fadef21f10bed10d7715019b2cdcf Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 20:07:43 +0800 Subject: [PATCH 28/61] docs(tools): document the abort message and the background call card; pin both with tests --- packages/bash/pwsh-local/README.i18n.yaml | 4 ++-- packages/bash/pwsh-local/README.md | 2 +- packages/bash/pwsh-local/README.zh.md | 2 +- packages/bash/tool-bash/README.i18n.yaml | 4 ++-- packages/bash/tool-bash/README.md | 2 +- packages/bash/tool-bash/README.zh.md | 2 +- packages/bash/tool-bash/tests/tools.spec.ts | 7 +++++-- packages/bash/tool-pwsh/README.i18n.yaml | 4 ++-- packages/bash/tool-pwsh/README.md | 2 +- packages/bash/tool-pwsh/README.zh.md | 2 +- packages/bash/tool-pwsh/tests/tools.spec.ts | 16 ++++++++++++++++ 11 files changed, 33 insertions(+), 14 deletions(-) diff --git a/packages/bash/pwsh-local/README.i18n.yaml b/packages/bash/pwsh-local/README.i18n.yaml index d58935d285..49d38f2b25 100644 --- a/packages/bash/pwsh-local/README.i18n.yaml +++ b/packages/bash/pwsh-local/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/bash/pwsh-local/README.md -README.md: bb5d941b0cc98fb14e0b47d5bbe0bffb5192edd8 -README.zh.md: efd8aac2b8766d1082b85905fce9867151b77310 +README.md: c5e0cc524e32d2218e734539c74adcddb663d4f3 +README.zh.md: 7906d8a511ee72ecdffaddaf88ddebe195a20857 diff --git a/packages/bash/pwsh-local/README.md b/packages/bash/pwsh-local/README.md index bb5d941b0c..c5e0cc524e 100644 --- a/packages/bash/pwsh-local/README.md +++ b/packages/bash/pwsh-local/README.md @@ -50,6 +50,6 @@ No direct invalidation; the named consumer owns any request-prefix changes. - **The command string is PowerShell text** — the `-Command` domain has no shell-quoting layer, but a model-facing command is parsed by PowerShell itself, so PowerShell syntax errors are command failures, not launch failures. - **A background spawn-failure note is single-delivery** — the subprocess service buffers no output for a process that never ran, so the executor injects `spawn failed: …` into exactly one `readOutput()` delta; a reader that discards that delta cannot recover it. - **Windows termination reports no signal** — a force-killed process settles as exit 1 with `signal: null`, so signal-based status classification (POSIX `killed`) does not apply on Windows; `kill()`-initiated stops still stamp `killed` directly. -- **The encoding preamble precedes the command** — PowerShell requires `param(...)` and `using namespace`/`using assembly` statements at the very top of a script, so a command whose first statement is one of those cannot run under the UTF-8 output preamble; prefix such scripts with a no-op statement (or `& { … }`) first. +- **The encoding preamble precedes the command** — PowerShell requires `param(...)`, `#requires`, and `using namespace`/`using assembly` statements at the very top of a script, so a command whose first statement is one of those cannot run under the UTF-8 output preamble; prefix such scripts with a no-op statement (or `& { … }`) first. Scrub-heuristic and spill-retention caveats live with [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md), which owns those mechanics. diff --git a/packages/bash/pwsh-local/README.zh.md b/packages/bash/pwsh-local/README.zh.md index efd8aac2b8..7906d8a511 100644 --- a/packages/bash/pwsh-local/README.zh.md +++ b/packages/bash/pwsh-local/README.zh.md @@ -50,6 +50,6 @@ - **命令字符串是 PowerShell 文本**——`-Command` 域没有 shell 引号层,但面向模型的命令由 PowerShell 自己解析,因此 PowerShell 语法错误是命令失败,而非启动失败。 - **后台 spawn 失败提示只投递一次**——subprocess 服务不会为从未运行的进程缓冲输出,因此执行器只把 `spawn failed: …` 注入一次 `readOutput()` 增量;丢弃该增量的读取方无法恢复它。 - **Windows 终止不报告信号**——被强制终止的进程以退出码 1、`signal: null` 结束,因此基于信号的状态分类(POSIX `killed`)在 Windows 上不适用;`kill()` 发起的停止仍会直接盖上 `killed`。 -- **编码 preamble 位于命令之前**——PowerShell 要求 `param(...)` 与 `using namespace`/`using assembly` 语句位于脚本最顶部,因此以其中一种开头的命令无法在 UTF-8 输出 preamble 下运行;请先用无操作语句(或 `& { … }`)开头。 +- **编码 preamble 位于命令之前**——PowerShell 要求 `param(...)`、`#requires` 与 `using namespace`/`using assembly` 语句位于脚本最顶部,因此以其中一种开头的命令无法在 UTF-8 输出 preamble 下运行;请先用无操作语句(或 `& { … }`)开头。 清理启发式与 spill 保留的注意事项由 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 持有,它拥有这些机制。 diff --git a/packages/bash/tool-bash/README.i18n.yaml b/packages/bash/tool-bash/README.i18n.yaml index 9d53b52d02..fc7f0d443e 100644 --- a/packages/bash/tool-bash/README.i18n.yaml +++ b/packages/bash/tool-bash/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/bash/tool-bash/README.md -README.md: 29b9fba369e1fc6a4b8bb7bdd6543b7678df627d -README.zh.md: 31f691f7bfb8d2cb905751663151c3f6a6bc6c57 +README.md: e3c8c445c8959b7f49705bb59af2bf61e0e716c8 +README.zh.md: fc5b3794187dcfd1f8b382bc805595c8ae887c55 diff --git a/packages/bash/tool-bash/README.md b/packages/bash/tool-bash/README.md index 29b9fba369..e3c8c445c8 100644 --- a/packages/bash/tool-bash/README.md +++ b/packages/bash/tool-bash/README.md @@ -141,7 +141,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Validation and policy failures are normalized as `Error: `. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got `, `invalid escalation: sandbox_permissions requires a justification`, `invalid escalation: justification is only valid together with sandbox_permissions`, `invalid justification: expected a non-empty sentence`, `background execution is disabled for this bash tool`, `background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, `sandbox escalation to "" is not strictly wider than this call's current "" mode`, the approval-availability/rejection/cancellation variants, and `command aborted`. +Validation and policy failures are normalized as `Error: `. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got `, `invalid escalation: sandbox_permissions requires a justification`, `invalid escalation: justification is only valid together with sandbox_permissions`, `invalid justification: expected a non-empty sentence`, `background execution is disabled for this bash tool`, `background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, `sandbox escalation to "" is not strictly wider than this call's current "" mode`, the approval-availability/rejection/cancellation variants, and `tool call aborted`. #### Token effect diff --git a/packages/bash/tool-bash/README.zh.md b/packages/bash/tool-bash/README.zh.md index 31f691f7bf..fc5b379418 100644 --- a/packages/bash/tool-bash/README.zh.md +++ b/packages/bash/tool-bash/README.zh.md @@ -141,7 +141,7 @@ renderer 先输出依数据而定的 stdout 尾部,再输出可选的 `[stderr #### 模型看到的内容 -验证和策略失败统一为 `Error: `。此包的稳定消息包括 `invalid command: expected a non-empty string`、`invalid description: expected a non-empty string`、`invalid timeoutMs: expected a positive number, got `、`invalid escalation: sandbox_permissions requires a justification`、`invalid escalation: justification is only valid together with sandbox_permissions`、`invalid justification: expected a non-empty sentence`、`background execution is disabled for this bash tool`、`background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、`sandbox escalation to "" is not strictly wider than this call's current "" mode`、审批不可用/拒绝/取消变体,以及 `command aborted`。 +验证和策略失败统一为 `Error: `。此包的稳定消息包括 `invalid command: expected a non-empty string`、`invalid description: expected a non-empty string`、`invalid timeoutMs: expected a positive number, got `、`invalid escalation: sandbox_permissions requires a justification`、`invalid escalation: justification is only valid together with sandbox_permissions`、`invalid justification: expected a non-empty sentence`、`background execution is disabled for this bash tool`、`background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、`sandbox escalation to "" is not strictly wider than this call's current "" mode`、审批不可用/拒绝/取消变体,以及 `tool call aborted`。 #### Token 影响 diff --git a/packages/bash/tool-bash/tests/tools.spec.ts b/packages/bash/tool-bash/tests/tools.spec.ts index 30a997b975..e6228ceca8 100644 --- a/packages/bash/tool-bash/tests/tools.spec.ts +++ b/packages/bash/tool-bash/tests/tools.spec.ts @@ -305,7 +305,7 @@ describe('bash tool', () => { expect(text(result)).toMatch(/ENOENT/) }) - it('surfaces foreground aborts as isError', async () => { + it('surfaces foreground aborts as the structured TOOL_ABORTED error', async () => { const ctx = await setup() const controller = new AbortController() const pending = ctx.tools.execute({ @@ -317,7 +317,10 @@ describe('bash tool', () => { setTimeout(() => { controller.abort() }, 50) const result = await pending expect(result.isError).toBe(true) - expect(text(result)).toMatch(/aborted/) + expect(result.error).toMatchObject({ + message: 'tool call aborted', + info: { name: 'AbortError', code: TOOL_ABORTED }, + }) }) // Type and required-key violations are rejected by the harness diff --git a/packages/bash/tool-pwsh/README.i18n.yaml b/packages/bash/tool-pwsh/README.i18n.yaml index 102e50d0ce..030d24c7c2 100644 --- a/packages/bash/tool-pwsh/README.i18n.yaml +++ b/packages/bash/tool-pwsh/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/bash/tool-pwsh/README.md -README.md: b5acc73a68d3b309860554d4c1e8d979eb8d1eec -README.zh.md: 4d678c42194b78da8b4b10e01f8b9e666d6236d8 +README.md: dfe26a63684d61dcdd6f969c2c2261dac79325c7 +README.zh.md: 2344f8477e5b15f2c4d366dd82b46358eacbc1b7 diff --git a/packages/bash/tool-pwsh/README.md b/packages/bash/tool-pwsh/README.md index b5acc73a68..dfe26a6368 100644 --- a/packages/bash/tool-pwsh/README.md +++ b/packages/bash/tool-pwsh/README.md @@ -36,7 +36,7 @@ When `run_in_background` is true, this plugin preflights `ctx.tasks.start()` bef ## UI presentation -The tool owns its `presentCall`/`presentResult` render intent. A call is a `terminal` card carrying command, description, and optional cwd; a completed result is a `generic` card with the rendered output in a `console` fence. The bash tool's terminal card with its parsed exit-status pill has no pwsh counterpart yet — a PowerShell-aware presentation is roadmap work. These presenters are pure and replay-safe. +The tool owns its `presentCall`/`presentResult` render intent. A foreground call is a `terminal` card carrying command, description, and optional cwd; a `run_in_background` call is a `generic` card with the raw command, mirroring the bash tool's background presentation. A completed result is a `generic` card with the rendered output in a `console` fence. The bash tool's terminal card with its parsed exit-status pill has no pwsh counterpart yet — a PowerShell-aware presentation is roadmap work. These presenters are pure and replay-safe. ## Model Experience diff --git a/packages/bash/tool-pwsh/README.zh.md b/packages/bash/tool-pwsh/README.zh.md index 4d678c4219..2344f8477e 100644 --- a/packages/bash/tool-pwsh/README.zh.md +++ b/packages/bash/tool-pwsh/README.zh.md @@ -36,7 +36,7 @@ ## UI presentation -工具拥有自己的 `presentCall`/`presentResult` 呈现意图。调用是携带命令、描述与可选 cwd 的 `terminal` 卡;完成的结果是以 `console` 围栏包裹渲染输出的 `generic` 卡。bash 工具那种带解析退出状态 pill 的 terminal 卡在 pwsh 侧暂无对应——PowerShell 感知的呈现属于路线图工作。这些 presenter 是纯函数且可重放。 +工具拥有自己的 `presentCall`/`presentResult` 呈现意图。前台调用是携带命令、描述与可选 cwd 的 `terminal` 卡;`run_in_background` 调用是携带原始命令的 `generic` 卡,镜像 bash 工具的后台呈现。完成的结果是以 `console` 围栏包裹渲染输出的 `generic` 卡。bash 工具那种带解析退出状态 pill 的 terminal 卡在 pwsh 侧暂无对应——PowerShell 感知的呈现属于路线图工作。这些 presenter 是纯函数且可重放。 ## Model Experience diff --git a/packages/bash/tool-pwsh/tests/tools.spec.ts b/packages/bash/tool-pwsh/tests/tools.spec.ts index 9d1eedba08..218099326f 100644 --- a/packages/bash/tool-pwsh/tests/tools.spec.ts +++ b/packages/bash/tool-pwsh/tests/tools.spec.ts @@ -537,6 +537,22 @@ describe('UI presentation', () => { .toMatchObject({ cwd: 'C:\\work' }) }) + it('a background pending call renders the generic card like the bash tool', async () => { + const { ctx } = await setup() + const definition = ctx.tools.get('pwsh') + expect(definition?.presentCall?.({ + command: 'Start-Sleep -Seconds 60', + description: 'long wait', + run_in_background: true, + })).toEqual({ + card: 'generic', + title: 'Start-Sleep -Seconds 60', + kind: 'execute', + rawInput: 'Start-Sleep -Seconds 60', + content: [{ type: 'text', text: 'long wait' }], + }) + }) + it('presentResult falls back to undefined for multi-block or non-text content', async () => { const { ctx } = await setup() const definition = ctx.tools.get('pwsh') From 6ae0f78c2ad792394408c8a54245dd03a5df1a65 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 20:27:06 +0800 Subject: [PATCH 29/61] fix(tools): pin the abort error info in the cancel fixture, close the jscpd mirror block, and restore the pwsh binary ignore --- .../acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl | 2 +- knip.json | 1 + packages/bash/tool-pwsh/src/index.ts | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl b/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl index a26655947d..a05cd1c28f 100644 --- a/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/chunk","seq":14,"time":1785487611319,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":15,"time":1785487611319,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_wait","name":"bash","arguments":"{\"command\":\"node -e \\\"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\\\"\",\"description\":\"Wait until cancellation\"}"},{"type":"tool-call","id":"call_skipped","name":"bash","arguments":"{\"command\":\"printf skipped > skipped.txt\",\"description\":\"Write skipped marker\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"bd630f41-b45d-4183-a785-1ff6e7049b62"},"usage":{"inputTokens":10,"outputTokens":10}},"sourceEventSeqs":[7,8,9,10,11,12,13,14],"surfaceOp":"append"} {"type":"tool/call","seq":16,"time":1785487611319,"data":{"turn":1,"step":1,"callId":"call_wait","name":"bash","arguments":"{\"command\":\"node -e \\\"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\\\"\",\"description\":\"Wait until cancellation\"}"}} -{"type":"tool/result","seq":17,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_wait"},"content":[{"type":"tool-result","toolCallId":"call_wait","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true}],"role":"user","id":"252903b2-b4e1-4a33-81d8-d5befefcb27e"}},"sourceEventSeqs":[16],"surfaceOp":"append"} +{"type":"tool/result","seq":17,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_wait"},"content":[{"type":"tool-result","toolCallId":"call_wait","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true}],"role":"user","id":"252903b2-b4e1-4a33-81d8-d5befefcb27e","error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"tool/call","seq":18,"time":1785487611378,"data":{"turn":1,"step":1,"callId":"call_skipped","name":"bash","arguments":"{\"command\":\"printf skipped > skipped.txt\",\"description\":\"Write skipped marker\"}"}} {"type":"tool/result","seq":19,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_skipped"},"content":[{"type":"tool-result","toolCallId":"call_skipped","content":[{"type":"text","text":"Error: tool call aborted before dispatch"}],"isError":true}],"role":"user","id":"282c5c8c-7296-4545-8014-e6393b351436"},"error":{"name":"AbortError","code":"ABORTED_BEFORE_DISPATCH"}},"sourceEventSeqs":[18],"surfaceOp":"append"} {"type":"step/end","seq":20,"time":1785487611378,"data":{"turn":1,"step":1}} diff --git a/knip.json b/knip.json index 71ee4faa3c..3ad4bad366 100644 --- a/knip.json +++ b/knip.json @@ -5,6 +5,7 @@ ], "ignoreBinaries": [ "bwrap", + "pwsh", "python3", "sandbox-exec", "taskkill" diff --git a/packages/bash/tool-pwsh/src/index.ts b/packages/bash/tool-pwsh/src/index.ts index 30ab72482f..9423fe36e6 100644 --- a/packages/bash/tool-pwsh/src/index.ts +++ b/packages/bash/tool-pwsh/src/index.ts @@ -276,6 +276,7 @@ export function apply(ctx: Context, config: Config = {}): void { return canonicalPwshResult(result) }, /* jscpd:ignore-end */ + /* jscpd:ignore-start -- the background call card mirrors presentBashCall's by design (Agent Note). */ presentCall: (args: PwshToolArgs): TerminalCallView | GenericCallView => { // Background acknowledgements carry no terminal exit status; the generic // card mirrors the bash tool's background presentation. @@ -295,6 +296,7 @@ export function apply(ctx: Context, config: Config = {}): void { ...args.workdir !== undefined ? { cwd: args.workdir } : {}, } }, + /* jscpd:ignore-end */ presentResult: (_args: unknown, result: ToolResult): ToolResultView | undefined => { const block = result.content.length === 1 ? result.content[0] : undefined if (block === undefined || block.type !== 'text') return undefined From 7b7525c0912de8a4f9af4fd63e69e7bdc188e41b Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 21:28:22 +0800 Subject: [PATCH 30/61] fix(fixtures): repair the cancel-fixture abort error placement; exempt pwsh-local coverage on pwsh-less hosts The hand-edit in 348ab41151 put the seq-17 abort error inside the tool-result message and dropped a closing brace, breaking every JSONL consumer; tool-calls.ts appends 'error' as a data-level sibling of 'message' (the seq-19 shape), so the fixture now matches the emitter. Coverage: pwsh-local's executor suites self-skip without a real pwsh, which left per-file 100% unreachable on pwsh-less contributor hosts (mirror of the existing windowsCoverageExclusions contract). A PATH-only probe exempts only pwsh-local/src/index.ts; CI runners ship pwsh and still enforce the full bar. docs/testing.md (+zh, pairing re-recorded) names the prerequisite; the testing.md budget rises 1120->1150 because the coverage-gate contract genuinely grew. --- docs/testing.i18n.yaml | 4 ++-- docs/testing.md | 2 +- docs/testing.zh.md | 2 +- .../snapshots/cancel-tool-calls/session.jsonl | 2 +- scripts/doc-budgets.manifest.json | 2 +- vitest.config.ts | 14 ++++++++++++++ 6 files changed, 20 insertions(+), 6 deletions(-) diff --git a/docs/testing.i18n.yaml b/docs/testing.i18n.yaml index 3d7569c620..a5160543fb 100644 --- a/docs/testing.i18n.yaml +++ b/docs/testing.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 docs/testing.md -testing.md: d460d9ba76eab84b79e8c66454325d03d7c5908e -testing.zh.md: 821e49b6593b924e754d5ed0d588dd1b5b566051 +testing.md: 5e766bb684d9d76a1c9e854a2aef95796a31ec12 +testing.zh.md: 21b3f98e9ddbbb6f77621cff9ce206ae17125bc3 diff --git a/docs/testing.md b/docs/testing.md index d460d9ba76..5e766bb684 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -7,7 +7,7 @@ How this repo tests, tier by tier, and the rules that keep a green suite meaning ## Tiers - **Unit** (`pnpm run test`): vitest over package and example specs under their `tests/**` directories plus repository script specs under `scripts/**/*.spec.ts`; tests stay with the code area they exercise. Every registry gets an HMR-safety test (dispose the contributing fiber, assert cleanup). Prefer edge cases, error paths, event ordering, concurrency races, and permanent contract regressions (see `packages/core/agent-loop/tests/contract-regressions.spec.ts`). -- **Coverage gate** (`pnpm run test:coverage`): the gating run, per-file 100% on `packages/*/*/src`. An uncovered line is often dead code the gate is correctly flagging for deletion, not a missing test to bolt on. Line coverage is necessary, never sufficient — it proves lines ran, not that the feature works as shipped. +- **Coverage gate** (`pnpm run test:coverage`): the gating run, per-file 100% on `packages/*/*/src`. An uncovered line is often dead code the gate is correctly flagging for deletion, not a missing test to bolt on. Line coverage is necessary, never sufficient — it proves lines ran, not that the feature works as shipped. Per-file 100% on `packages/bash/pwsh-local/src` needs a real `pwsh`: without one its executor suites self-skip and `vitest.config.ts` exempts the file so pwsh-less hosts stay green, while CI runners ship pwsh and enforce the full bar. - **Real-API e2e** (`pnpm run test:e2e`): with-key tests against live provider APIs — the DeepSeek model plus provider-specific smokes that gate on their own keys (`EXA_API_KEY`, `PERPLEXITY_API_KEY`, …); each suite self-skips without its key so keyless CI stays green ([real-API e2e Agent Note](../.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md)). - **Snapshot** (`pnpm run test:snapshot`): keyless expected outputs cover external behavior — transport contracts and presentation, while persisted logs pin assembled backend behavior. ACP boots the real automation-server example, replays a recorded session, and diffs normalized JSON-RPC plus the re-persisted log ([ACP snapshot Agent Note](../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md)); headless pins `stream-json` through its real one-shot process. TUI journeys replay primary/child JSONL through the real loop and tools, then project ANSI into semantic terminal-state outputs; package snapshots retain transient states and a real PTY covers the process boundary ([TUI snapshot Agent Note](../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)). Use `pnpm run test:snapshot:record` when a model transcript changes and `pnpm run test:snapshot:refresh` when replay input remains valid; review every JSONL and expected-output diff. One ACP scenario (`text-turn`) pins full system-prompt/tool-schema content; other fixtures tokenize it so an edit churns one line ([pinned-header Agent Note](../.agents/notes/archived/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)). - **Web browser snapshot** (`pnpm run test:web`; required Linux PR gate): Chromium compares replayed browser output with `apps/web/tests/snapshots/`. CI forces read-only `DSH_SNAPSHOT=replay`, never writing expected outputs; record/refresh stay local and every diff is reviewed ([web e2e lane](../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md), [CI gate decision](../.agents/notes/implemented/testing/2026-07-30-web-browser-snapshot-ci-gate.md)). `test:web` [builds first](../.agents/notes/implemented/bug-fix/2026-07-28-themed-scrollbars-and-reserved-gutter.md) for plugin CSS. diff --git a/docs/testing.zh.md b/docs/testing.zh.md index 821e49b659..21b3f98e9d 100644 --- a/docs/testing.zh.md +++ b/docs/testing.zh.md @@ -7,7 +7,7 @@ ## 层级 - **单元测试**(`pnpm run test`):vitest 运行包(package)和示例各自的 `tests/**` 目录下的测试,以及匹配 `scripts/**/*.spec.ts` 的仓库脚本测试;测试文件与其所覆盖的代码区域放在一起。每个注册表都有一个 HMR(热模块替换)安全测试(dispose(资源释放)贡献的 fiber,断言清理完成)。优先覆盖边界情况、错误路径、事件顺序、并发竞态,以及永久性契约回归(见 `packages/core/agent-loop/tests/contract-regressions.spec.ts`)。 -- **覆盖率门禁**(`pnpm run test:coverage`):门禁级运行,对 `packages/*/*/src` 按文件 100% 覆盖。未覆盖的行往往是门禁正确标记出的死代码(应删除),而非需要补写的测试。行覆盖率是必要条件,但永远不是充分条件:它证明行被执行过,不证明功能按交付预期工作。 +- **覆盖率门禁**(`pnpm run test:coverage`):门禁级运行,对 `packages/*/*/src` 按文件 100% 覆盖。未覆盖的行往往是门禁正确标记出的死代码(应删除),而非需要补写的测试。行覆盖率是必要条件,但永远不是充分条件:它证明行被执行过,不证明功能按交付预期工作。`packages/bash/pwsh-local/src` 的按文件 100% 覆盖需要真实的 `pwsh`:缺少它时其 executor 套件会自动跳过,`vitest.config.ts` 会豁免该文件以使无 pwsh 的主机保持绿色,而 CI runner 自带 pwsh,仍按完整标准执行门禁。 - **真实 API e2e**(`pnpm run test:e2e`):带密钥测试调用真实提供方 API,包括 DeepSeek 模型以及各提供方特有的冒烟测试;这些测试各自由自己的密钥控制(`EXA_API_KEY`、`PERPLEXITY_API_KEY` 等),缺少密钥时套件会自动跳过,使 keyless CI 保持绿色([真实 API e2e Agent Note](../.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md))。 - **快照**(`pnpm run test:snapshot`):无密钥预期输出覆盖对外行为(传输契约与呈现),持久化日志则固定组装后的后端行为。ACP 启动真实的自动化服务器示例、回放录制会话,并对归一化 JSON-RPC 与重新持久化的日志执行 diff([ACP 快照 Agent Note](../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md));headless 通过真实单次运行进程固定 `stream-json`。TUI 旅程通过真实循环与工具回放主会话与子会话 JSONL,再将 ANSI 投影为语义化终端状态输出;包级快照保留瞬态状态,真实 PTY 覆盖进程边界([TUI 快照 Agent Note](../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md))。当模型 transcript(文本记录)发生变化时使用 `pnpm run test:snapshot:record`,回放输入仍然有效时使用 `pnpm run test:snapshot:refresh`;请审查每一处 JSONL 与预期输出差异。一个 ACP 场景(`text-turn`)固定完整的系统提示词与工具 schema 内容;其他 fixture(测试前置数据)将其 token 化,因此修改只会扰动一行([pinned-header Agent Note](../.agents/notes/archived/testing/2026-07-06-pin-request-header-content-in-one-scenario.md))。 - **Web 浏览器快照**(`pnpm run test:web`;必需的 Linux PR(Pull Request)门禁):Chromium 将回放后的浏览器输出与 `apps/web/tests/snapshots/` 比较。CI 强制只读的 `DSH_SNAPSHOT=replay`,绝不写入预期输出;record/refresh 留在本地,每处 diff 都须评审([web e2e 车道](../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md)、[CI 门禁决策](../.agents/notes/implemented/testing/2026-07-30-web-browser-snapshot-ci-gate.md))。`test:web` 会[先构建](../.agents/notes/implemented/bug-fix/2026-07-28-themed-scrollbars-and-reserved-gutter.md)以交付插件 CSS。 diff --git a/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl b/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl index a05cd1c28f..d66020b594 100644 --- a/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/chunk","seq":14,"time":1785487611319,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":15,"time":1785487611319,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_wait","name":"bash","arguments":"{\"command\":\"node -e \\\"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\\\"\",\"description\":\"Wait until cancellation\"}"},{"type":"tool-call","id":"call_skipped","name":"bash","arguments":"{\"command\":\"printf skipped > skipped.txt\",\"description\":\"Write skipped marker\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"bd630f41-b45d-4183-a785-1ff6e7049b62"},"usage":{"inputTokens":10,"outputTokens":10}},"sourceEventSeqs":[7,8,9,10,11,12,13,14],"surfaceOp":"append"} {"type":"tool/call","seq":16,"time":1785487611319,"data":{"turn":1,"step":1,"callId":"call_wait","name":"bash","arguments":"{\"command\":\"node -e \\\"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\\\"\",\"description\":\"Wait until cancellation\"}"}} -{"type":"tool/result","seq":17,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_wait"},"content":[{"type":"tool-result","toolCallId":"call_wait","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true}],"role":"user","id":"252903b2-b4e1-4a33-81d8-d5befefcb27e","error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[16],"surfaceOp":"append"} +{"type":"tool/result","seq":17,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_wait"},"content":[{"type":"tool-result","toolCallId":"call_wait","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true}],"role":"user","id":"252903b2-b4e1-4a33-81d8-d5befefcb27e"},"error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"tool/call","seq":18,"time":1785487611378,"data":{"turn":1,"step":1,"callId":"call_skipped","name":"bash","arguments":"{\"command\":\"printf skipped > skipped.txt\",\"description\":\"Write skipped marker\"}"}} {"type":"tool/result","seq":19,"time":1785487611378,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_skipped"},"content":[{"type":"tool-result","toolCallId":"call_skipped","content":[{"type":"text","text":"Error: tool call aborted before dispatch"}],"isError":true}],"role":"user","id":"282c5c8c-7296-4545-8014-e6393b351436"},"error":{"name":"AbortError","code":"ABORTED_BEFORE_DISPATCH"}},"sourceEventSeqs":[18],"surfaceOp":"append"} {"type":"step/end","seq":20,"time":1785487611378,"data":{"turn":1,"step":1}} diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 4387a894f1..9e8d6076ec 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -4,7 +4,7 @@ "docs/architecture.md": 2160, "docs/cordis-primer.md": 600, "docs/defensive-patterns.md": 550, - "docs/testing.md": 1120, + "docs/testing.md": 1150, "examples/AGENTS.md": 310, "packages/AGENTS.md": 675, "packages/README.md": 920 diff --git a/vitest.config.ts b/vitest.config.ts index 14d5be103f..458b1134b1 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,3 +1,4 @@ +import { spawnSync } from 'node:child_process' import tsconfigPaths from 'vite-tsconfig-paths' import { defineConfig } from 'vitest/config' import { vitestExecArgv } from './vitest.shared.ts' @@ -39,6 +40,18 @@ const windowsCoverageExclusions = process.platform === 'win32' ] : [] +// Mirrors windowsCoverageExclusions: pwsh-local's run/start/lifecycle suites +// self-skip without a real pwsh (executor.spec.ts hasPwsh), leaving this file +// far below per-file 100% on pwsh-less hosts; the exemption keeps those hosts +// green while CI runners ship pwsh and still enforce the full bar. The probe +// is deliberately PATH-only (narrower than the suites' resolvePwshPath): a +// win32 host where only install-location pwsh or 5.1 resolves forfeits the +// exemption while the suites still run, so the gate can only get stricter, +// never falsely green. +const pwshCoverageExclusions = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 + ? [] + : ['packages/bash/pwsh-local/src/index.ts'] + const testIncludes = [ 'packages/*/*/tests/**/*.spec.{ts,tsx}', 'apps/*/tests/**/*.spec.ts', @@ -203,6 +216,7 @@ export default defineConfig({ 'packages/ui/tui/src/index.ts', ...windowsUnsupportedPackages.map(path => `${path}/src/**/*.ts`), ...windowsCoverageExclusions, + ...pwshCoverageExclusions, ], // 100% or it doesn't merge (docs/testing.md: excessive tests are welcome). // Per-file so a well-covered big file can't subsidize a bare one. From b2838fb2beb2727fb59e634976e81de37963a639 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 21:46:53 +0800 Subject: [PATCH 31/61] fix(pwsh): close the remaining review threads - scrubbedParentEnv folds case before the DSH_ prefix check (Windows env names are case-insensitive; a parent dsh_* entry read back as \* in the child) and the service spec pins the lowercase probe. - The acp.snapshot.ts pwsh probe follows resolvePwshPath() like the package suites, so a Windows host with only an install-location pwsh still runs the scenario. - pwsh-tool-turn is re-recorded around [Console]::Out.Write('PWSH_OK'): the fixture carries no platform newline, so one recording replays on Windows and POSIX alike (record + refresh; replay-verified keyless). - The pwsh-local Known Limitations bullet drops the self-defeating no-op advice: & { } is scoped to param(...), using/#requires scripts run from a file (both languages, pairing re-recorded). - The capability-seams graph moves ctx.bashEnv ownership to bash-env and lists pwsh-local/tool-pwsh on the ctx.bash seam (source updated, docs regenerated). - The tool-bash presenter fixture retires the stale 'command aborted' literal for the shipped 'tool call aborted' message. --- docs/capability-seams.md | 13 +++- examples/acp-agent/tests/acp.snapshot.ts | 12 ++-- .../tests/snapshots/pwsh-tool-turn/input.json | 2 +- .../snapshots/pwsh-tool-turn/session.jsonl | 64 +++++++++---------- packages/bash/pwsh-local/README.i18n.yaml | 4 +- packages/bash/pwsh-local/README.md | 2 +- packages/bash/pwsh-local/README.zh.md | 2 +- packages/bash/tool-bash/tests/tools.spec.ts | 4 +- packages/subprocess/subprocess/src/index.ts | 7 +- .../subprocess/tests/service.spec.ts | 5 +- scripts/gen-doc-graphs.ts | 11 ++-- 11 files changed, 72 insertions(+), 54 deletions(-) diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 561b59e10e..6b69cae609 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -108,6 +108,9 @@ flowchart LR pkg_subagent_acp["subagent-acp"] pkg_bash["bash"] svc_bash["ctx.bash
Bash executor seam"] + pkg_pwsh_local["pwsh-local"] + pkg_tool_pwsh["tool-pwsh"] + pkg_bash_env["bash-env"] svc_bashEnv["ctx.bashEnv
Managed bash environment registry"] pkg_pty["pty"] svc_pty["ctx.pty
Persistent PTY session registry"] @@ -170,6 +173,7 @@ flowchart LR pkg_agent_loop --> svc_agentLoop pkg_approval --> svc_approval pkg_bash --> svc_bash + pkg_bash_env --> svc_bashEnv pkg_bash_local --> svc_bash pkg_bash_sandbox --> svc_bash pkg_code_runtime --> svc_codeRuntime @@ -197,6 +201,7 @@ flowchart LR pkg_plan_mode --> svc_planMode pkg_pty --> svc_pty pkg_pty_local --> svc_pty + pkg_pwsh_local --> svc_bash pkg_sandbox --> svc_sandbox pkg_sandbox_local --> svc_sandbox pkg_sandbox_policy --> svc_sandboxPolicy @@ -234,7 +239,6 @@ flowchart LR pkg_tasks --> svc_tasks pkg_tasks_local --> svc_tasks pkg_token_meter --> svc_tokenMeter - pkg_tool_bash --> svc_bashEnv pkg_tools --> svc_tools pkg_tui --> svc_tui pkg_tui --> svc_userInteraction @@ -260,6 +264,9 @@ flowchart LR svc_bash --> pkg_hooks_claude svc_bash --> pkg_hooks_codex svc_bash --> pkg_tool_bash + svc_bash --> pkg_tool_pwsh + svc_bashEnv --> pkg_tool_bash + svc_bashEnv --> pkg_tool_pwsh svc_clientModuleHost --> pkg_hmr svc_codeRuntime --> pkg_tools svc_commands --> pkg_tui @@ -381,8 +388,8 @@ flowchart LR | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`agent-spine-demo`](../packages/examples/agent-spine-demo) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. | | `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | Folds revisioned objective state from the session log and keeps live continuation activation process-local. | | `ctx.subprocess` | `seam` | [`subprocess`](../packages/subprocess/subprocess) | [`subprocess-local`](../packages/subprocess/subprocess-local) | [`bash-local`](../packages/bash/bash-local), [`bash-sandbox`](../packages/bash/bash-sandbox), [`lsp-local`](../packages/lsp/lsp-local), [`subagent-acp`](../packages/subagent/subagent-acp) | - | The bash executors, the LSP host, and the ACP subagent backend spawn their children through ctx.subprocess; the service owns tree lifetime, stdio dispositions (pipes, inherit, bounded spill-backed collection), and kill escalation. | -| `ctx.bash` | `seam` | [`bash`](../packages/bash/bash) | [`bash-local`](../packages/bash/bash-local), [`bash-sandbox`](../packages/bash/bash-sandbox) | [`tool-bash`](../packages/bash/tool-bash), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | - | The model-facing bash tools and hook bridges consume this seam; sandboxed or remote executors replace bash-local without touching them. | -| `ctx.bashEnv` | `core` | [`tool-bash`](../packages/bash/tool-bash) | - | - | - | Plugins declare effect-scoped DSH_* facts; tool-bash collects one trusted snapshot per execution and the executor rebuilds the namespace. | +| `ctx.bash` | `seam` | [`bash`](../packages/bash/bash) | [`bash-local`](../packages/bash/bash-local), [`bash-sandbox`](../packages/bash/bash-sandbox), [`pwsh-local`](../packages/bash/pwsh-local) | [`tool-bash`](../packages/bash/tool-bash), [`tool-pwsh`](../packages/bash/tool-pwsh), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | - | The model-facing shell tools and hook bridges consume this seam; sandboxed, remote, or PowerShell executors replace bash-local without touching them. | +| `ctx.bashEnv` | `core` | [`bash-env`](../packages/bash/bash-env) | - | [`tool-bash`](../packages/bash/tool-bash), [`tool-pwsh`](../packages/bash/tool-pwsh) | - | Plugins declare effect-scoped DSH_* facts; each shell tool collects one trusted snapshot per execution and its executor rebuilds the namespace. | | `ctx.pty` | `seam` | [`pty`](../packages/pty/pty) | [`pty-local`](../packages/pty/pty-local) | [`tool-pty`](../packages/pty/tool-pty) | - | The registry owns exact-Agent session identity and cleanup; backends own terminal mechanics, while tool-pty exposes the owner-scoped model surface. | | `ctx.sandbox` | `seam` | [`sandbox`](../packages/sandbox/sandbox) | [`sandbox-local`](../packages/sandbox/sandbox-local) | [`bash-sandbox`](../packages/bash/bash-sandbox), [`pty-local`](../packages/pty/pty-local) | - | Consumers hand over the exact argv they are about to spawn; same-world backends wrap it under a per-call policy and report enforcement. | | `ctx.sandboxPolicy` | `core` | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | - | [`bash-sandbox`](../packages/bash/bash-sandbox), [`fs-sandbox`](../packages/fs/fs-sandbox), [`pty-local`](../packages/pty/pty-local) | - | The one home for the deployment default mode + workspace root; only the sandboxed executor and provider read the service (the tool layers use the pure `sandbox/mode` fold it also exports). Both enforcing families read it so bash and fs cannot confine to different roots. | diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index 824780ae0f..c107a1e2b0 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -6,6 +6,7 @@ import { dirname, join } from 'node:path' import { homedir } from 'node:os' import { expect, it } from 'vitest' import { defineAcpSnapshotSuite, type Scenario, type SnapshotSuiteOptions } from '@deepseek-ai/dsh-acp-snapshot' +import { resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local' import { decodeStorageRecord } from '@deepseek-ai/dsh-session' /** @@ -170,7 +171,9 @@ const SCENARIOS: Scenario[] = [ headerClass: 'pwsh', configPath: PWSH_CONFIG, // The composition boots the real pwsh executor; hosts without a `pwsh` - // binary skip the run (fixtures stay guarded). + // binary skip the run (fixtures stay guarded). The recorded turn writes + // PWSH_OK via [Console]::Out.Write so the fixture carries no platform + // newline and one recording replays on every host. pwshOnly: true, }, { name: 'todo-write', hasModelTurn: true, recorded: true }, @@ -435,9 +438,10 @@ const SCENARIOS: Scenario[] = [ }, ] -// Hosts without a `pwsh` binary skip the pwsh-tool-turn run (its fixtures -// stay guarded); a bare `pwsh` probe keeps this suite dependency-light. -const hasPwsh = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 +// Hosts without a usable PowerShell skip the pwsh-tool-turn run (its fixtures +// stay guarded); the probe follows the executor's own resolution so a Windows +// host with only an install-location pwsh still runs the scenario. +const hasPwsh = spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 defineAcpSnapshotSuite({ agent: AGENT, diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/input.json b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/input.json index 4101a2c1f3..653e9a346c 100644 --- a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/input.json +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/input.json @@ -2,6 +2,6 @@ "steps": [ { "op": "initialize" }, { "op": "newSession" }, - { "op": "prompt", "text": "Use the pwsh tool to run exactly: Write-Output PWSH_OK. Then reply with the single word DONE and stop." } + { "op": "prompt", "text": "Use the pwsh tool to run exactly: [Console]::Out.Write('PWSH_OK'). Then reply with the single word DONE and stop." } ] } diff --git a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl index 333948541c..9dc17ef799 100644 --- a/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl +++ b/examples/acp-agent/tests/snapshots/pwsh-tool-turn/session.jsonl @@ -1,32 +1,32 @@ -{"type":"session","version":0,"id":"1ec0d099-552b-44e1-8fb8-fd9742fbdc1c","createdAt":1785655505943,"cwd":"{{cwd}}","delegationDepth":0} -{"type":"turn/start","seq":0,"time":1785655505948,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} -{"type":"user/message","seq":1,"time":1785655505948,"data":{"content":[{"type":"text","text":"Use the pwsh tool to run exactly: Write-Output PWSH_OK. Then reply with the single word DONE and stop."}],"source":{"kind":"user"},"role":"user","id":"e3bca81a-d4e4-46fb-aa30-916f785c27a0"},"surfaceOp":"append"} -{"type":"session/title","seq":2,"time":1785655505949,"data":{"title":"Use the pwsh tool to","messageSeqs":[1],"source":{"kind":"fallback"}}} -{"type":"step/start","seq":3,"time":1785655505971,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":4,"time":1785655505972,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} -{"type":"request/context","seq":5,"time":1785655505972,"data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} -{"type":"assistant/chunk","seq":6,"time":1785655506674,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"reasoning-chunks","seq0":7,"time0":1785655506674,"data":{"turn":1,"step":1,"index":0,"dt":[157,27,1,0,0,0,38,0,0,43,0,0,0,50,0,1,0,0,0,36,0,1,0,0],"texts":["The"," user"," wants"," me"," to"," run"," a"," PowerShell"," command"," that"," outputs"," \"","P","WS","H","_OK","\""," and"," then"," reply"," with"," \"","D","ONE","\"."]}} -{"type":"assistant/chunk","seq":32,"time":1785655507160,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} -{"type":"tool-call-chunks","seq0":33,"time0":1785655507161,"data":{"turn":1,"step":1,"index":1,"dt":[51,0,0,0,0,32,0,0,0,55,1,0,0,0,74,0,0,0,1,45,0,42,0,0,0,0,54,0],"id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","args":["","{","\"","command","\"",": ","\"","Write","-","Output"," P","WS","H","_OK","\"",", ","\"","description","\"",": ","\"","Output"," P","WS","H","_OK"," string","\"","}"]}} -{"type":"assistant/chunk","seq":62,"time":1785655507601,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a PowerShell command that outputs \"PWSH_OK\" and then reply with \"DONE\"."}}}} -{"type":"assistant/chunk","seq":63,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}}}} -{"type":"assistant/chunk","seq":64,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":816,"outputTokens":96,"cacheReadTokens":0,"reasoningTokens":25}}}} -{"type":"assistant/chunk","seq":65,"time":1785655507602,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":66,"time":1785655507604,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to run a PowerShell command that outputs \"PWSH_OK\" and then reply with \"DONE\"."},{"type":"tool-call","id":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"4d81cc10-507e-49a8-96f4-aa3ae5ad2eb5"},"usage":{"inputTokens":816,"outputTokens":96,"cacheReadTokens":0,"reasoningTokens":25}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65],"surfaceOp":"append"} -{"type":"tool/call","seq":67,"time":1785655507605,"data":{"turn":1,"step":1,"callId":"call_00_oEhmLGLNsvlumiE0WkXD0511","name":"pwsh","arguments":"{\"command\": \"Write-Output PWSH_OK\", \"description\": \"Output PWSH_OK string\"}"}} -{"type":"tool/result","seq":68,"time":1785655507994,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_oEhmLGLNsvlumiE0WkXD0511"},"content":[{"type":"tool-result","toolCallId":"call_00_oEhmLGLNsvlumiE0WkXD0511","content":[{"type":"text","text":"PWSH_OK\n"}],"isError":false}],"role":"user","id":"84a96d55-5bd5-46fc-ab0d-918882c504e2"}},"sourceEventSeqs":[67],"surfaceOp":"append"} -{"type":"step/end","seq":69,"time":1785655507994,"data":{"turn":1,"step":1}} -{"type":"step/start","seq":70,"time":1785655508000,"data":{"turn":1,"step":2}} -{"type":"assistant/chunk","seq":71,"time":1785655508608,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"reasoning-chunks","seq0":72,"time0":1785655508608,"data":{"turn":1,"step":2,"index":0,"dt":[168,38,0,60,1,0,0,0,0,27,1,0,0,0,46,0,0,0,0,0,41],"texts":["The"," command"," successfully"," output"," \"","P","WS","H","_OK","\"."," Now"," I"," should"," reply"," with"," \"","D","ONE","\""," as"," instructed","."]}} -{"type":"assistant/chunk","seq":94,"time":1785655508990,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"assistant/chunk","seq":95,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} -{"type":"assistant/chunk","seq":96,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} -{"type":"assistant/chunk","seq":97,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The command successfully output \"PWSH_OK\". Now I should reply with \"DONE\" as instructed."}}}} -{"type":"assistant/chunk","seq":98,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} -{"type":"assistant/chunk","seq":99,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":34,"outputTokens":25,"cacheReadTokens":896,"reasoningTokens":22}}}} -{"type":"assistant/chunk","seq":100,"time":1785655508991,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":101,"time":1785655508991,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The command successfully output \"PWSH_OK\". Now I should reply with \"DONE\" as instructed."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"d8905016-347c-477a-a8f7-2b31839a8357"},"usage":{"inputTokens":34,"outputTokens":25,"cacheReadTokens":896,"reasoningTokens":22}},"sourceEventSeqs":[71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100],"surfaceOp":"append"} -{"type":"step/end","seq":102,"time":1785655508992,"data":{"turn":1,"step":2}} -{"type":"turn/end","seq":103,"time":1785655508992,"data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"session","version":0,"id":"0b7ff6ab-2486-4b2f-a43e-0fa29a1a46ed","createdAt":1785678162241,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"turn/start","seq":0,"time":1785678162244,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} +{"type":"user/message","seq":1,"time":1785678162245,"data":{"content":[{"type":"text","text":"Use the pwsh tool to run exactly: [Console]::Out.Write('PWSH_OK'). Then reply with the single word DONE and stop."}],"source":{"kind":"user"},"role":"user","id":"6efbdc24-7abe-4f34-ac6d-15f93d49ad9a"},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1785678162246,"data":{"title":"Use the pwsh tool to","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1785678162261,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1785678162261,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","seq":5,"time":1785678162262,"data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} +{"type":"assistant/chunk","seq":6,"time":1785678162968,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"reasoning-chunks","seq0":7,"time0":1785678162968,"data":{"turn":1,"step":1,"index":0,"dt":[393,0,0,0,1,0,0,0,0,0,17,0,0,0,0,0,0,0,1,290,0],"texts":["The"," user"," wants"," me"," to"," run"," a"," PowerShell"," command"," and"," then"," reply"," with"," \"","D","ONE","\"."," Let"," me"," execute"," it","."]}} +{"type":"assistant/chunk","seq":29,"time":1785678163671,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} +{"type":"tool-call-chunks","seq0":30,"time0":1785678163671,"data":{"turn":1,"step":1,"index":1,"dt":[0,0,0,0,0,0,17,0,0,0,0,0,109,0,0,0,0,0,0,22,0,0,0,0,275,0,1,0,0,0,0,0,0,0],"id":"call_00_e0MSVSocL0o4UWjOdG4c2072","name":"pwsh","args":["","{","\"","command","\"",": ","\"","[","Console","]","::","Out",".Write","('","P","WS","H","_OK","')","\"",", ","\"","description","\"",": ","\"","Write"," P","WS","H","_OK"," to"," console","\"","}"]}} +{"type":"assistant/chunk","seq":65,"time":1785678164124,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a PowerShell command and then reply with \"DONE\". Let me execute it."}}}} +{"type":"assistant/chunk","seq":66,"time":1785678164124,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_e0MSVSocL0o4UWjOdG4c2072","name":"pwsh","arguments":"{\"command\": \"[Console]::Out.Write('PWSH_OK')\", \"description\": \"Write PWSH_OK to console\"}"}}}} +{"type":"assistant/chunk","seq":67,"time":1785678164124,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":1255,"outputTokens":99,"cacheReadTokens":0,"reasoningTokens":22}}}} +{"type":"assistant/chunk","seq":68,"time":1785678164124,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":69,"time":1785678164126,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to run a PowerShell command and then reply with \"DONE\". Let me execute it."},{"type":"tool-call","id":"call_00_e0MSVSocL0o4UWjOdG4c2072","name":"pwsh","arguments":"{\"command\": \"[Console]::Out.Write('PWSH_OK')\", \"description\": \"Write PWSH_OK to console\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"6e968eea-46b8-4489-8005-5e898d53c1a9"},"usage":{"inputTokens":1255,"outputTokens":99,"cacheReadTokens":0,"reasoningTokens":22}},"sourceEventSeqs":[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68],"surfaceOp":"append"} +{"type":"tool/call","seq":70,"time":1785678164127,"data":{"turn":1,"step":1,"callId":"call_00_e0MSVSocL0o4UWjOdG4c2072","name":"pwsh","arguments":"{\"command\": \"[Console]::Out.Write('PWSH_OK')\", \"description\": \"Write PWSH_OK to console\"}"}} +{"type":"tool/result","seq":71,"time":1785678164405,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_e0MSVSocL0o4UWjOdG4c2072"},"content":[{"type":"tool-result","toolCallId":"call_00_e0MSVSocL0o4UWjOdG4c2072","content":[{"type":"text","text":"PWSH_OK"}],"isError":false}],"role":"user","id":"964dfad5-651e-47f0-90a5-fe5bc711a3ff"}},"sourceEventSeqs":[70],"surfaceOp":"append"} +{"type":"step/end","seq":72,"time":1785678164405,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":73,"time":1785678164410,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":74,"time":1785678165135,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"reasoning-chunks","seq0":75,"time0":1785678165136,"data":{"turn":1,"step":2,"index":0,"dt":[176,44,56,0,0,42,0,0,0,48,0,0,0,48,0,0,60,0,0,0,0,39,0,0],"texts":["The"," command"," executed"," successfully"," and"," printed"," \"","P","WS","H","_OK","\"."," Now"," I"," need"," to"," reply"," with"," \"","D","ONE","\""," and"," stop","."]}} +{"type":"assistant/chunk","seq":100,"time":1785678165649,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} +{"type":"assistant/chunk","seq":101,"time":1785678165649,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} +{"type":"assistant/chunk","seq":102,"time":1785678165649,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} +{"type":"assistant/chunk","seq":103,"time":1785678165693,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The command executed successfully and printed \"PWSH_OK\". Now I need to reply with \"DONE\" and stop."}}}} +{"type":"assistant/chunk","seq":104,"time":1785678165693,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} +{"type":"assistant/chunk","seq":105,"time":1785678165693,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":90,"outputTokens":28,"cacheReadTokens":1280,"reasoningTokens":25}}}} +{"type":"assistant/chunk","seq":106,"time":1785678165693,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":107,"time":1785678165693,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The command executed successfully and printed \"PWSH_OK\". Now I need to reply with \"DONE\" and stop."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"91f35706-53e9-4fcd-891e-2c9eafccde98"},"usage":{"inputTokens":90,"outputTokens":28,"cacheReadTokens":1280,"reasoningTokens":25}},"sourceEventSeqs":[74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106],"surfaceOp":"append"} +{"type":"step/end","seq":108,"time":1785678165694,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":109,"time":1785678165694,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/packages/bash/pwsh-local/README.i18n.yaml b/packages/bash/pwsh-local/README.i18n.yaml index 49d38f2b25..0d11b89d6b 100644 --- a/packages/bash/pwsh-local/README.i18n.yaml +++ b/packages/bash/pwsh-local/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/bash/pwsh-local/README.md -README.md: c5e0cc524e32d2218e734539c74adcddb663d4f3 -README.zh.md: 7906d8a511ee72ecdffaddaf88ddebe195a20857 +README.md: e061d1bd614fa4aa13d3ae9418c2e4af47d72518 +README.zh.md: 3a8d2b7ea41c02dbaf72273b0e9ef0f2c023068f diff --git a/packages/bash/pwsh-local/README.md b/packages/bash/pwsh-local/README.md index c5e0cc524e..e061d1bd61 100644 --- a/packages/bash/pwsh-local/README.md +++ b/packages/bash/pwsh-local/README.md @@ -50,6 +50,6 @@ No direct invalidation; the named consumer owns any request-prefix changes. - **The command string is PowerShell text** — the `-Command` domain has no shell-quoting layer, but a model-facing command is parsed by PowerShell itself, so PowerShell syntax errors are command failures, not launch failures. - **A background spawn-failure note is single-delivery** — the subprocess service buffers no output for a process that never ran, so the executor injects `spawn failed: …` into exactly one `readOutput()` delta; a reader that discards that delta cannot recover it. - **Windows termination reports no signal** — a force-killed process settles as exit 1 with `signal: null`, so signal-based status classification (POSIX `killed`) does not apply on Windows; `kill()`-initiated stops still stamp `killed` directly. -- **The encoding preamble precedes the command** — PowerShell requires `param(...)`, `#requires`, and `using namespace`/`using assembly` statements at the very top of a script, so a command whose first statement is one of those cannot run under the UTF-8 output preamble; prefix such scripts with a no-op statement (or `& { … }`) first. +- **The encoding preamble precedes the command** — PowerShell requires `param(...)`, `#requires`, and `using namespace`/`using assembly` statements at the very top of a script, so a command whose first statement is one of those cannot run under the UTF-8 output preamble. Wrap a `param(...)` script in `& { … }` (a param block legally heads a script block); `using` statements and `#requires` have no in-command workaround (`#requires` is inert inside `-Command` regardless of position) — run such scripts from a file instead. Scrub-heuristic and spill-retention caveats live with [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md), which owns those mechanics. diff --git a/packages/bash/pwsh-local/README.zh.md b/packages/bash/pwsh-local/README.zh.md index 7906d8a511..3a8d2b7ea4 100644 --- a/packages/bash/pwsh-local/README.zh.md +++ b/packages/bash/pwsh-local/README.zh.md @@ -50,6 +50,6 @@ - **命令字符串是 PowerShell 文本**——`-Command` 域没有 shell 引号层,但面向模型的命令由 PowerShell 自己解析,因此 PowerShell 语法错误是命令失败,而非启动失败。 - **后台 spawn 失败提示只投递一次**——subprocess 服务不会为从未运行的进程缓冲输出,因此执行器只把 `spawn failed: …` 注入一次 `readOutput()` 增量;丢弃该增量的读取方无法恢复它。 - **Windows 终止不报告信号**——被强制终止的进程以退出码 1、`signal: null` 结束,因此基于信号的状态分类(POSIX `killed`)在 Windows 上不适用;`kill()` 发起的停止仍会直接盖上 `killed`。 -- **编码 preamble 位于命令之前**——PowerShell 要求 `param(...)`、`#requires` 与 `using namespace`/`using assembly` 语句位于脚本最顶部,因此以其中一种开头的命令无法在 UTF-8 输出 preamble 下运行;请先用无操作语句(或 `& { … }`)开头。 +- **编码 preamble 位于命令之前**——PowerShell 要求 `param(...)`、`#requires` 与 `using namespace`/`using assembly` 语句位于脚本最顶部,因此以其中一种开头的命令无法在 UTF-8 输出 preamble 下运行。`param(...)` 脚本可包进 `& { … }`(param 块可以合法地位于脚本块开头);`using` 语句与 `#requires` 在命令内没有变通办法(`#requires` 在 `-Command` 中无论位置如何都不生效)——此类脚本请改从文件运行。 清理启发式与 spill 保留的注意事项由 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 持有,它拥有这些机制。 diff --git a/packages/bash/tool-bash/tests/tools.spec.ts b/packages/bash/tool-bash/tests/tools.spec.ts index e6228ceca8..4f913d78ee 100644 --- a/packages/bash/tool-bash/tests/tools.spec.ts +++ b/packages/bash/tool-bash/tests/tools.spec.ts @@ -1017,9 +1017,9 @@ describe('tool-owned UI presentation (presentCall / presentResult)', () => { // not renderResult output, so a generic fenced card, no terminal output/exit. const out = ctx.tools.get('bash')!.presentResult!( { command: 'x', description: 'x' }, - { content: [{ type: 'text', text: 'command aborted' }], isError: true }, + { content: [{ type: 'text', text: 'tool call aborted' }], isError: true }, ) - expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ncommand aborted\n```' }] }) + expect(out).toEqual({ card: 'generic', content: [{ type: 'text', text: '```console\ntool call aborted\n```' }] }) }) it('bash presentResult: leaves a non-text (unexpected) result untouched → undefined (UI keeps raw content)', async () => { diff --git a/packages/subprocess/subprocess/src/index.ts b/packages/subprocess/subprocess/src/index.ts index 5d0bbe2c76..d484faa24d 100644 --- a/packages/subprocess/subprocess/src/index.ts +++ b/packages/subprocess/subprocess/src/index.ts @@ -45,7 +45,10 @@ export const SENSITIVE_ENV_PATTERN = /KEY|PASSWORD|SECRET|TOKEN/i * `HOME`, locale, and proxy variables survive, so child CLIs run normally; * harness identity never leaks implicitly (a deliberately forwarded * credential or current `DSH_*` fact goes through the spec's explicit `env`, - * which merges after this scrub). Exported as a plain function so spawners + * which merges after this scrub). Both scrubs match case-insensitively: + * Windows environment names are case-insensitive, so a parent `dsh_*` entry + * would otherwise survive and read back as `$env:DSH_*` in the child; + * deliberate lowercase `dsh_*` names on POSIX are implausible. Exported as a plain function so spawners * that cannot route through the service (node-pty backends, SDK-managed * transports) share the one scrub definition. * @returns a fresh environment object safe to hand to a child spawn. @@ -53,7 +56,7 @@ export const SENSITIVE_ENV_PATTERN = /KEY|PASSWORD|SECRET|TOKEN/i export function scrubbedParentEnv(): Record { const env: Record = {} for (const [key, value] of Object.entries(process.env)) { - if (value !== undefined && !SENSITIVE_ENV_PATTERN.test(key) && !key.startsWith(DSH_ENV_PREFIX)) env[key] = value + if (value !== undefined && !SENSITIVE_ENV_PATTERN.test(key) && !key.toUpperCase().startsWith(DSH_ENV_PREFIX)) env[key] = value } return env } diff --git a/packages/subprocess/subprocess/tests/service.spec.ts b/packages/subprocess/subprocess/tests/service.spec.ts index 28a1dce299..d0ef5c9fd6 100644 --- a/packages/subprocess/subprocess/tests/service.spec.ts +++ b/packages/subprocess/subprocess/tests/service.spec.ts @@ -52,20 +52,23 @@ describe('SubprocessService seam', () => { await expect(ctx.plugin(SecondService)).rejects.toThrow(/service "subprocess" has been registered/) }) - it('scrubbedParentEnv drops credential-shaped and DSH_ names but keeps PATH', () => { + it('scrubbedParentEnv drops credential-shaped and DSH_ names (case-insensitively) but keeps PATH', () => { process.env.DSH_SCRUB_PROBE = 'stale' + process.env.dsh_scrub_probe_lower = 'stale' process.env.SCRUB_PROBE_TOKEN = 'secret' process.env.SCRUB_PROBE_PASSWORD = 'secret' process.env.SCRUB_PROBE_PLAIN = 'visible' try { const env = scrubbedParentEnv() expect(env.DSH_SCRUB_PROBE).toBeUndefined() + expect(env.dsh_scrub_probe_lower).toBeUndefined() expect(env.SCRUB_PROBE_TOKEN).toBeUndefined() expect(env.SCRUB_PROBE_PASSWORD).toBeUndefined() expect(env.SCRUB_PROBE_PLAIN).toBe('visible') expect(env.PATH).toBeDefined() } finally { delete process.env.DSH_SCRUB_PROBE + delete process.env.dsh_scrub_probe_lower delete process.env.SCRUB_PROBE_TOKEN delete process.env.SCRUB_PROBE_PASSWORD delete process.env.SCRUB_PROBE_PLAIN diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 2bbfe56b2c..842467c764 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -338,16 +338,17 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'bash', title: 'Bash executor seam', mode: 'seam', - implementations: ['bash-local', 'bash-sandbox'], - consumers: ['tool-bash', 'hooks-claude', 'hooks-codex'], - note: 'The model-facing bash tools and hook bridges consume this seam; sandboxed or remote executors replace bash-local without touching them.', + implementations: ['bash-local', 'bash-sandbox', 'pwsh-local'], + consumers: ['tool-bash', 'tool-pwsh', 'hooks-claude', 'hooks-codex'], + note: 'The model-facing shell tools and hook bridges consume this seam; sandboxed, remote, or PowerShell executors replace bash-local without touching them.', }, { key: 'bashEnv', - pkg: 'tool-bash', + pkg: 'bash-env', title: 'Managed bash environment registry', mode: 'core', - note: 'Plugins declare effect-scoped DSH_* facts; tool-bash collects one trusted snapshot per execution and the executor rebuilds the namespace.', + consumers: ['tool-bash', 'tool-pwsh'], + note: 'Plugins declare effect-scoped DSH_* facts; each shell tool collects one trusted snapshot per execution and its executor rebuilds the namespace.', }, { key: 'pty', From 725cd3afd06ffe62b852cd43eade5f9079c6eba3 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 22:06:29 +0800 Subject: [PATCH 32/61] docs(catalog): regenerate the cordis services catalog for the scrub JSDoc line shift --- docs/cordis-catalog/services.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 19384976a2..790e18ce1e 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -2097,7 +2097,7 @@ abstract spawn(spec: SubprocessSpawnSpec): SubprocessHandle Types: [SubprocessHandle](../core-data-structures/subprocess.md) · [SubprocessSpawnSpec](../core-data-structures/subprocess.md) -Source: [`packages/subprocess/subprocess/src/index.ts:88`](../../packages/subprocess/subprocess/src/index.ts) +Source: [`packages/subprocess/subprocess/src/index.ts:91`](../../packages/subprocess/subprocess/src/index.ts) ## `ctx.systemPrompt` — `SystemPrompt` From d6a763020b36e0332686eb02fc7ff3905ecbe235 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 22:08:35 +0800 Subject: [PATCH 33/61] docs(pwsh-local): list the 5.1 non-ASCII stdin gap under Known Limitations (both languages) --- packages/bash/pwsh-local/README.i18n.yaml | 4 ++-- packages/bash/pwsh-local/README.md | 1 + packages/bash/pwsh-local/README.zh.md | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/bash/pwsh-local/README.i18n.yaml b/packages/bash/pwsh-local/README.i18n.yaml index 0d11b89d6b..c097bc6e77 100644 --- a/packages/bash/pwsh-local/README.i18n.yaml +++ b/packages/bash/pwsh-local/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/bash/pwsh-local/README.md -README.md: e061d1bd614fa4aa13d3ae9418c2e4af47d72518 -README.zh.md: 3a8d2b7ea41c02dbaf72273b0e9ef0f2c023068f +README.md: 76a30939d68ac866880f906b928b265628f4de1e +README.zh.md: af98af1b83baa72ad8345362b583b61fa634d29a diff --git a/packages/bash/pwsh-local/README.md b/packages/bash/pwsh-local/README.md index e061d1bd61..76a30939d6 100644 --- a/packages/bash/pwsh-local/README.md +++ b/packages/bash/pwsh-local/README.md @@ -51,5 +51,6 @@ No direct invalidation; the named consumer owns any request-prefix changes. - **A background spawn-failure note is single-delivery** — the subprocess service buffers no output for a process that never ran, so the executor injects `spawn failed: …` into exactly one `readOutput()` delta; a reader that discards that delta cannot recover it. - **Windows termination reports no signal** — a force-killed process settles as exit 1 with `signal: null`, so signal-based status classification (POSIX `killed`) does not apply on Windows; `kill()`-initiated stops still stamp `killed` directly. - **The encoding preamble precedes the command** — PowerShell requires `param(...)`, `#requires`, and `using namespace`/`using assembly` statements at the very top of a script, so a command whose first statement is one of those cannot run under the UTF-8 output preamble. Wrap a `param(...)` script in `& { … }` (a param block legally heads a script block); `using` statements and `#requires` have no in-command workaround (`#requires` is inert inside `-Command` regardless of position) — run such scripts from a file instead. +- **Non-ASCII stdin under Windows PowerShell 5.1 may be mis-decoded** — the preamble pins output encoding only; `[Console]::InputEncoding` stays at the host default because setting it under redirected stdin throws. pwsh 7 defaults to UTF-8 and is unaffected. Scrub-heuristic and spill-retention caveats live with [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md), which owns those mechanics. diff --git a/packages/bash/pwsh-local/README.zh.md b/packages/bash/pwsh-local/README.zh.md index 3a8d2b7ea4..af98af1b83 100644 --- a/packages/bash/pwsh-local/README.zh.md +++ b/packages/bash/pwsh-local/README.zh.md @@ -51,5 +51,6 @@ - **后台 spawn 失败提示只投递一次**——subprocess 服务不会为从未运行的进程缓冲输出,因此执行器只把 `spawn failed: …` 注入一次 `readOutput()` 增量;丢弃该增量的读取方无法恢复它。 - **Windows 终止不报告信号**——被强制终止的进程以退出码 1、`signal: null` 结束,因此基于信号的状态分类(POSIX `killed`)在 Windows 上不适用;`kill()` 发起的停止仍会直接盖上 `killed`。 - **编码 preamble 位于命令之前**——PowerShell 要求 `param(...)`、`#requires` 与 `using namespace`/`using assembly` 语句位于脚本最顶部,因此以其中一种开头的命令无法在 UTF-8 输出 preamble 下运行。`param(...)` 脚本可包进 `& { … }`(param 块可以合法地位于脚本块开头);`using` 语句与 `#requires` 在命令内没有变通办法(`#requires` 在 `-Command` 中无论位置如何都不生效)——此类脚本请改从文件运行。 +- **Windows PowerShell 5.1 下的非 ASCII stdin 可能被错误解码**——preamble 只固定输出编码;`[Console]::InputEncoding` 保持主机默认,因为在重定向 stdin 下设置它会抛出异常。pwsh 7 默认 UTF-8,不受影响。 清理启发式与 spill 保留的注意事项由 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 持有,它拥有这些机制。 From b482f12d571f0b11713239dc2d114f5964cc812d Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 00:21:17 +0800 Subject: [PATCH 34/61] fix(coverage): probe the pwsh exemption with the executor's own resolution The review caught the pwshCoverageExclusions comment claiming the inverse of the code's behavior: a bare-PATH probe FAILING grants the exemption, so a win32 host where only install-location pwsh (or 5.1) resolves kept the exemption while its suites ran - over-exempting, never tightening. resolvePwshPath/candidatePwshPaths move to the dependency-free pwsh-local/src/resolve.ts (index.ts re-exports; public API unchanged) and vitest.config.ts probes with that shared definition, so the exemption is active exactly when the suites skip. The two spec headers stop saying 'on PATH' for a probe that is deliberately not PATH-only, and the parity note records the abort backport as the one both-ways parity change (both languages, pairing re-recorded); catalogs regenerated for the line shift. --- ...2026-08-02-pwsh-tool-bash-parity.i18n.yaml | 4 +- .../2026-08-02-pwsh-tool-bash-parity.md | 1 + .../2026-08-02-pwsh-tool-bash-parity.zh.md | 3 +- docs/config-catalog.md | 2 +- packages/bash/pwsh-local/src/index.ts | 53 ++-------------- packages/bash/pwsh-local/src/resolve.ts | 60 +++++++++++++++++++ .../bash/pwsh-local/tests/executor.spec.ts | 4 +- .../bash/tool-pwsh/tests/integration.spec.ts | 2 +- vitest.config.ts | 10 ++-- 9 files changed, 78 insertions(+), 61 deletions(-) create mode 100644 packages/bash/pwsh-local/src/resolve.ts diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml index 913cf0cc06..6cbc24d8aa 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.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-02-pwsh-tool-bash-parity.md -2026-08-02-pwsh-tool-bash-parity.md: fb0f3fff1ed00dfde286781733881facfb1e6c7b -2026-08-02-pwsh-tool-bash-parity.zh.md: 9dc84bcd5e53c52d5d68b2db61cf79fe7fb97bb9 +2026-08-02-pwsh-tool-bash-parity.md: 417c6d6bc91eb3afaa38976e0013e4fbe72854ca +2026-08-02-pwsh-tool-bash-parity.zh.md: 926433526b3820f7b4770acb3ee172448970b601 diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md index fb0f3fff1e..417c6d6bc9 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md @@ -27,6 +27,7 @@ The first Windows-native foundation shipped `dsh-tool-pwsh` as a deliberately mi ## Consequences - The bash and pwsh tools are now behaviorally interchangeable for foreground and background shell work (minus sandbox), and the pwsh prompt/description sentences are each backed by the renderer — the reviewer's grep-against-code check passes. +- Parity ran BOTH ways once: the pwsh tool's structured foreground abort (`HarnessError('tool call aborted', TOOL_ABORTED)` with name `AbortError`) was backported to the bash tool, replacing its uncoded `Error('command aborted')` — a model-visible/logged change pinned by exact-shape tests on both sides and by the cancel-tool-calls fixture. - `@deepseek-ai/dsh-bash-env` is a new shipped package; `dsh-tool-bash`'s `dshHome` config moved there, so compositions mounting the shell tools must also mount `bash-env` (the spine bundles do). - Windows-only semantics (CRLF normalization, forced-termination exit-1/signal-null, POSIX-only self-signal) remain pinned by tests as before. - The pwsh tool's per-file coverage gate rides on the scriptable fake-executor suite (`tests/tools.spec.ts`); the real-pwsh integration and Loader-composition suites self-skip where `pwsh` is absent, mirroring the bash suites' division of labor. diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md index 9dc84bcd5e..926433526b 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md @@ -26,7 +26,8 @@ Status: implemented ## 后果 -- bash 与 pwsh 工具在前台与后台 shell 工作(减 sandbox)上行为可互换,pwsh 的 prompt/描述句每句都有渲染器背书——reviewer 的"拿代码 grep 对证"检查通过。 +- bash 与 pwsh 工具在前台与后台 shell 工作(减 sandbox)上行为可互换,pwsh 的 prompt/描述句每句都有渲染器背书——reviewer 的“拿代码 grep 对证”检查通过。 +- 对齐也反向发生过一次:pwsh 工具的结构化前台中止(`HarnessError('tool call aborted', TOOL_ABORTED)`,name 为 `AbortError`)被回移到 bash 工具,取代其无码的 `Error('command aborted')`——这是模型可见/入日志的变更,由两侧的精确形状测试与 cancel-tool-calls fixture 钉住。 - `@deepseek-ai/dsh-bash-env` 成为新的交付包;`dsh-tool-bash` 的 `dshHome` 配置迁往那里,因此挂载 shell 工具的组合也必须挂载 `bash-env`(spine bundle 已如此)。 - Windows 专属语义(CRLF 归一化、强制终止 exit-1/signal-null、仅 POSIX 的自信号)一如既往由测试钉住。 - pwsh 工具的 per-file 覆盖门禁由可脚本化的 fake-executor 套件(`tests/tools.spec.ts`)承担;真实 pwsh 的集成与 Loader 组合套件在无 `pwsh` 的宿主自跳过,与 bash 套件的分工一致。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index f14a7a5900..9a2eb8f0be 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1004,7 +1004,7 @@ export interface Config { } ``` -Source: [`packages/bash/pwsh-local/src/index.ts:55`](../packages/bash/pwsh-local/src/index.ts) +Source: [`packages/bash/pwsh-local/src/index.ts:54`](../packages/bash/pwsh-local/src/index.ts) ## `@deepseek-ai/dsh-repeat-tool-guard` diff --git a/packages/bash/pwsh-local/src/index.ts b/packages/bash/pwsh-local/src/index.ts index b966a579af..316d2c8651 100644 --- a/packages/bash/pwsh-local/src/index.ts +++ b/packages/bash/pwsh-local/src/index.ts @@ -13,14 +13,13 @@ * @module @deepseek-ai/dsh-pwsh-local */ -import { existsSync } from 'node:fs' -import { join } from 'node:path' import { Context } from 'cordis' import z from 'schemastery' import { BashExecutor } from '@deepseek-ai/dsh-bash' import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult, CollectedOutput } from '@deepseek-ai/dsh-bash' import type { SubprocessCollect, SubprocessHandle, SubprocessOutputReader, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import { clampTimeout, deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' +import { resolvePwshPath } from './resolve.ts' /* jscpd:ignore-start -- deliberate call-for-call mirror of dsh-bash-local (Agent Note: pwsh-tool-and-executor). */ /** @@ -77,53 +76,9 @@ export interface Config { /** The shape after schemastery applied the defaults (cwd/pwshPath have none). */ type ResolvedConfig = Required> & Pick -/** - * Well-known Windows PowerShell install locations plus PATH entries, newest - * first. Explicitly parameterized (env) so resolution is a pure function of - * its inputs on every platform. - * @param env - the environment to probe; defaults to the process environment. - * @returns candidate `pwsh` executable paths in resolution order. - */ -export function candidatePwshPaths(env: NodeJS.ProcessEnv = process.env): string[] { - const programFiles = env.ProgramFiles ?? 'C:\\Program Files' - const systemRoot = env.SystemRoot ?? 'C:\\Windows' - const candidates = [ - join(programFiles, 'PowerShell', '7', 'pwsh.exe'), - ] - // Microsoft Store installs (and any user-added location) live on PATH; - // entries may carry surrounding quotes from `setx`-style definitions. - for (const entry of (env.PATH ?? '').split(';')) { - const trimmed = entry.trim().replace(/^"|"$/g, '') - if (trimmed.length === 0) continue - candidates.push(join(trimmed, 'pwsh.exe')) - } - // Windows PowerShell 5.1 remains the last-resort fallback on legacy hosts. - candidates.push(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')) - return candidates -} - -/** - * Resolve the pwsh executable this executor spawns. - * @param configured - an explicit `pwshPath` config value, trusted as-is. - * @param env - the environment to probe on Windows; defaults to the process environment. - * @param platform - the platform to resolve for; defaults to the process platform. - * @returns the first existing well-known location on Windows (PowerShell 7 - * install, a PATH entry such as the Microsoft Store install, then Windows - * PowerShell 5.1), else `pwsh` for PATH resolution. - */ -export function resolvePwshPath( - configured?: string, - env: NodeJS.ProcessEnv = process.env, - platform: NodeJS.Platform = process.platform, -): string { - if (configured !== undefined && configured.length > 0) return configured - if (platform === 'win32') { - for (const candidate of candidatePwshPaths(env)) { - if (existsSync(candidate)) return candidate - } - } - return 'pwsh' -} +// Resolution lives in its own dependency-free module so the repository's +// coverage-gate probe shares the exact definition the suites use. +export { candidatePwshPaths, resolvePwshPath } from './resolve.ts' /** Project a settled collect-mode reader into the final CollectedOutput shape. */ function finalOutput(reader: SubprocessOutputReader): CollectedOutput { diff --git a/packages/bash/pwsh-local/src/resolve.ts b/packages/bash/pwsh-local/src/resolve.ts new file mode 100644 index 0000000000..c6ded2f883 --- /dev/null +++ b/packages/bash/pwsh-local/src/resolve.ts @@ -0,0 +1,60 @@ +/** + * PowerShell executable resolution, dependency-free so non-package consumers + * (the repository's coverage-gate probe in `vitest.config.ts`) can share the + * ONE resolution definition with the executor and its suites — a probe that + * resolved differently from the code under test could exempt a file whose + * suites actually run. + * + * @module @deepseek-ai/dsh-pwsh-local/resolve + */ + +import { existsSync } from 'node:fs' +import { join } from 'node:path' + +/** + * Well-known Windows PowerShell install locations plus PATH entries, newest + * first. Explicitly parameterized (env) so resolution is a pure function of + * its inputs on every platform. + * @param env - the environment to probe; defaults to the process environment. + * @returns candidate `pwsh` executable paths in resolution order. + */ +export function candidatePwshPaths(env: NodeJS.ProcessEnv = process.env): string[] { + const programFiles = env.ProgramFiles ?? 'C:\\Program Files' + const systemRoot = env.SystemRoot ?? 'C:\\Windows' + const candidates = [ + join(programFiles, 'PowerShell', '7', 'pwsh.exe'), + ] + // Microsoft Store installs (and any user-added location) live on PATH; + // entries may carry surrounding quotes from `setx`-style definitions. + for (const entry of (env.PATH ?? '').split(';')) { + const trimmed = entry.trim().replace(/^"|"$/g, '') + if (trimmed.length === 0) continue + candidates.push(join(trimmed, 'pwsh.exe')) + } + // Windows PowerShell 5.1 remains the last-resort fallback on legacy hosts. + candidates.push(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')) + return candidates +} + +/** + * Resolve the pwsh executable this executor spawns. + * @param configured - an explicit `pwshPath` config value, trusted as-is. + * @param env - the environment to probe on Windows; defaults to the process environment. + * @param platform - the platform to resolve for; defaults to the process platform. + * @returns the first existing well-known location on Windows (PowerShell 7 + * install, a PATH entry such as the Microsoft Store install, then Windows + * PowerShell 5.1), else `pwsh` for PATH resolution. + */ +export function resolvePwshPath( + configured?: string, + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): string { + if (configured !== undefined && configured.length > 0) return configured + if (platform === 'win32') { + for (const candidate of candidatePwshPaths(env)) { + if (existsSync(candidate)) return candidate + } + } + return 'pwsh' +} diff --git a/packages/bash/pwsh-local/tests/executor.spec.ts b/packages/bash/pwsh-local/tests/executor.spec.ts index 5113f6a988..4552f2eeec 100644 --- a/packages/bash/pwsh-local/tests/executor.spec.ts +++ b/packages/bash/pwsh-local/tests/executor.spec.ts @@ -3,8 +3,8 @@ * service plus a REAL pwsh executable, exercised through the executor seam * (`resolve` → `run`/`start`). These verify the world — actual PowerShell * runs, output capture, truncation and spill, deadlines, kill escalation, and - * the background-handle contract. The suite self-skips when no `pwsh` is on - * PATH (a CI accommodation for hosts without PowerShell); the pure unit tests + * the background-handle contract. The suite self-skips when no usable `pwsh` + * resolves (a CI accommodation for hosts without PowerShell); the pure unit tests * (config validation, executable resolution) run on every platform. PowerShell * writes CRLF on Windows, so exact text assertions normalize line endings. */ diff --git a/packages/bash/tool-pwsh/tests/integration.spec.ts b/packages/bash/tool-pwsh/tests/integration.spec.ts index 711f7663b1..c347866f50 100644 --- a/packages/bash/tool-pwsh/tests/integration.spec.ts +++ b/packages/bash/tool-pwsh/tests/integration.spec.ts @@ -4,7 +4,7 @@ * process. These verify the world — actual commands run, stdout/stderr come * back, exit codes render, timeouts abort, background tasks settle through the * generic task runtime, and per-session cwd resolution works. The suite - * self-skips when no `pwsh` is on PATH (a CI accommodation for hosts without + * self-skips when no usable `pwsh` resolves (a CI accommodation for hosts without * PowerShell); the fake-executor suite (tools.spec.ts) carries the coverage * gate. */ diff --git a/vitest.config.ts b/vitest.config.ts index 458b1134b1..c922cb8a32 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,5 +1,6 @@ import { spawnSync } from 'node:child_process' import tsconfigPaths from 'vite-tsconfig-paths' +import { resolvePwshPath } from './packages/bash/pwsh-local/src/resolve.ts' import { defineConfig } from 'vitest/config' import { vitestExecArgv } from './vitest.shared.ts' import { COVERAGE_EXEMPT_ENV, coverageExemptHeavySuites } from './scripts/coverage-exempt.ts' @@ -44,11 +45,10 @@ const windowsCoverageExclusions = process.platform === 'win32' // self-skip without a real pwsh (executor.spec.ts hasPwsh), leaving this file // far below per-file 100% on pwsh-less hosts; the exemption keeps those hosts // green while CI runners ship pwsh and still enforce the full bar. The probe -// is deliberately PATH-only (narrower than the suites' resolvePwshPath): a -// win32 host where only install-location pwsh or 5.1 resolves forfeits the -// exemption while the suites still run, so the gate can only get stricter, -// never falsely green. -const pwshCoverageExclusions = spawnSync('pwsh', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 +// runs the suites' own resolution (the dependency-free resolve.ts module), +// so the exemption is active exactly when the suites skip — a mismatched +// narrower probe could exempt the file on hosts whose suites actually run. +const pwshCoverageExclusions = spawnSync(resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], { encoding: 'utf8' }).status === 0 ? [] : ['packages/bash/pwsh-local/src/index.ts'] From f4d243e3001e3e1691e4445b1443759a49ffa112 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 00:31:32 +0800 Subject: [PATCH 35/61] chore(knip): drop the stale pwsh ignoreBinaries entry Every bare spawnSync('pwsh') became resolvePwshPath(), so knip's config hint correctly flags the ignore as unused. --- knip.json | 1 - 1 file changed, 1 deletion(-) diff --git a/knip.json b/knip.json index 3ad4bad366..71ee4faa3c 100644 --- a/knip.json +++ b/knip.json @@ -5,7 +5,6 @@ ], "ignoreBinaries": [ "bwrap", - "pwsh", "python3", "sandbox-exec", "taskkill" From dc4d2dc86827f0202a53bb2df5aead3eb9c99659 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 20:26:39 +0800 Subject: [PATCH 36/61] docs(bash): document the bashEnv hard dependency and dedupe the demo manifest - tool-bash README (both languages) now shows the real four-service inject and attributes the session-persistence contributor to dsh-bash-env. - pwsh-local README names the also-exported ENV_OVERRIDES/ENCODING_PREAMBLE. - agent-spine-demo drops the duplicate bash-env devDependency key. --- packages/bash/pwsh-local/README.i18n.yaml | 4 ++-- packages/bash/pwsh-local/README.md | 2 +- packages/bash/pwsh-local/README.zh.md | 2 +- packages/bash/tool-bash/README.i18n.yaml | 4 ++-- packages/bash/tool-bash/README.md | 4 ++-- packages/bash/tool-bash/README.zh.md | 4 ++-- packages/examples/agent-spine-demo/package.json | 1 - 7 files changed, 10 insertions(+), 11 deletions(-) diff --git a/packages/bash/pwsh-local/README.i18n.yaml b/packages/bash/pwsh-local/README.i18n.yaml index c097bc6e77..1b78ca75f9 100644 --- a/packages/bash/pwsh-local/README.i18n.yaml +++ b/packages/bash/pwsh-local/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/bash/pwsh-local/README.md -README.md: 76a30939d68ac866880f906b928b265628f4de1e -README.zh.md: af98af1b83baa72ad8345362b583b61fa634d29a +README.md: 9deba9c1b63ccfdb9e1805b9896db33f144839bf +README.zh.md: e45c820e1d5e31aebd9ed365c6130850f1db2a62 diff --git a/packages/bash/pwsh-local/README.md b/packages/bash/pwsh-local/README.md index 76a30939d6..9deba9c1b6 100644 --- a/packages/bash/pwsh-local/README.md +++ b/packages/bash/pwsh-local/README.md @@ -6,7 +6,7 @@ Local PowerShell implementation of the `@deepseek-ai/dsh-bash` executor seam ove The command string rides as ONE argv element to `-Command`: PowerShell itself parses the text, and no intermediate shell exists, so there is no shell-quoting layer to escape (the `bash -c` string domain has no equivalent here). Native Win32 paths (`C:\...`) pass through unchanged. -The package root exports the default and named `PwshLocalExecutor` plugin, its `Config`, and the pure `resolvePwshPath`/`candidatePwshPaths` helpers. +The package root exports the default and named `PwshLocalExecutor` plugin, its `Config`, the pure `resolvePwshPath`/`candidatePwshPaths` helpers, and the `ENV_OVERRIDES`/`ENCODING_PREAMBLE` constants the executor injects into every spawn. ## Config diff --git a/packages/bash/pwsh-local/README.zh.md b/packages/bash/pwsh-local/README.zh.md index af98af1b83..e45c820e1d 100644 --- a/packages/bash/pwsh-local/README.zh.md +++ b/packages/bash/pwsh-local/README.zh.md @@ -6,7 +6,7 @@ 命令字符串作为 ONE argv 元素传给 `-Command`:由 PowerShell 自己解析文本,不存在中间 shell,因此没有需要转义的 shell 引号层(`bash -c` 字符串域在这里没有对应物)。原生 Win32 路径(`C:\...`)原样通过。 -包根导出默认与具名 `PwshLocalExecutor` 插件、其 `Config`,以及纯函数 `resolvePwshPath`/`candidatePwshPaths` 辅助函数。 +包根导出默认与具名 `PwshLocalExecutor` 插件、其 `Config`、纯函数 `resolvePwshPath`/`candidatePwshPaths` 辅助函数,以及执行器注入每次 spawn 的 `ENV_OVERRIDES`/`ENCODING_PREAMBLE` 常量。 ## 配置 diff --git a/packages/bash/tool-bash/README.i18n.yaml b/packages/bash/tool-bash/README.i18n.yaml index fc7f0d443e..19370b6c64 100644 --- a/packages/bash/tool-bash/README.i18n.yaml +++ b/packages/bash/tool-bash/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/bash/tool-bash/README.md -README.md: e3c8c445c8959b7f49705bb59af2bf61e0e716c8 -README.zh.md: fc5b3794187dcfd1f8b382bc805595c8ae887c55 +README.md: c168b3bfe49faec0be8bd7664411f538a8142edf +README.zh.md: 3b94f8bc2e4aca8ade15c4e2e1e35d1674c66fdb diff --git a/packages/bash/tool-bash/README.md b/packages/bash/tool-bash/README.md index e3c8c445c8..c168b3bfe4 100644 --- a/packages/bash/tool-bash/README.md +++ b/packages/bash/tool-bash/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The model-facing `bash` tool registered over the `ctx.bash` executor seam. Foreground execution stays behind that seam; a background process handle is registered with the generic `ctx.tasks` runtime and controlled through `task_output`, `task_list`, and `task_kill` from `@deepseek-ai/dsh-tool-tasks`. -Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`); the plugin stays pending until `ctx.bash` exists (`inject: ['tools', 'bash', 'systemPrompt']`). +Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`) and the [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) registry; the plugin stays pending until every injected service exists (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`). The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`); result rendering and background-process adaptation remain implementation details covered by same-package tests. @@ -30,7 +30,7 @@ The plugin also contributes the `tool:bash` prompt section (order 105): check th Every foreground and background model bash call receives a newly collected trusted `DSH_*` environment. `DSH_HOME` is the absolute Harness home resolved by [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) (`dshHome` config, then ambient `$DSH_HOME`, then `~/.dsh`) and `DSH_SHELL=1` identifies the managed child. Agent calls additionally receive `DSH_SESSION_ID=agent.session.header.id`; when the active persistence seam locates a JSONL artifact they also receive `DSH_SESSION_JSONL=`. The JSONL path is a location hint: it may not exist before the first flush or contain the current buffered turn, and it is not an authorization credential. -`ctx.bashEnv` owns collection. Other plugins can register an effect-scoped contributor with a stable name, declared keys/descriptions, and `resolve(execution: ToolExecution)`; duplicate ownership and undeclared runtime keys fail loudly, while `list()` enumerates declarations without executing providers. Harness built-ins reserve `DSH_HOME`, `DSH_SHELL`, and `DSH_SESSION_ID`; tool-bash's persistence translator owns `DSH_SESSION_JSONL` by reading the backend-neutral `sessionPersistence.locate()` seam. +`ctx.bashEnv` owns collection. Other plugins can register an effect-scoped contributor with a stable name, declared keys/descriptions, and `resolve(execution: ToolExecution)`; duplicate ownership and undeclared runtime keys fail loudly, while `list()` enumerates declarations without executing providers. Harness built-ins reserve `DSH_HOME`, `DSH_SHELL`, and `DSH_SESSION_ID`; `dsh-bash-env`'s session-persistence contributor owns `DSH_SESSION_JSONL` by reading the backend-neutral `sessionPersistence.locate()` seam. ```ts import type { Context } from 'cordis' diff --git a/packages/bash/tool-bash/README.zh.md b/packages/bash/tool-bash/README.zh.md index fc5b379418..3b94f8bc2e 100644 --- a/packages/bash/tool-bash/README.zh.md +++ b/packages/bash/tool-bash/README.zh.md @@ -4,7 +4,7 @@ 模型侧 `bash` 工具,注册在 `ctx.bash` 执行器 seam 上。前台执行始终位于该 seam 之后;后台进程句柄会注册到通用 `ctx.tasks` 运行时,并通过 `task_output`、`task_list` 和 `task_kill` 控制;这些工具由 `@deepseek-ai/dsh-tool-tasks` 提供。 -需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`);在 `ctx.bash` 可用之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt']`)。 +需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`)与 [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) 注册表;在每个注入服务就绪之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。 包(package)根只公开 Cordis 插件契约(`name`、`inject`、`Config`、`apply`);结果渲染和后台进程适配仍是实现细节,由同包测试覆盖。 @@ -30,7 +30,7 @@ 每次模型发起的前台或后台 bash 调用都会收到新收集的一组可信 `DSH_*` 环境变量。`DSH_HOME` 是由 [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) 解析出的 Harness home 绝对路径(依次采用 `dshHome` 配置、环境中的 `$DSH_HOME`、`~/.dsh`),`DSH_SHELL=1` 则标识受托管的子进程。Agent 调用还会收到 `DSH_SESSION_ID=agent.session.header.id`;当活跃的持久化 seam 找到 JSONL 产物时,也会收到 `DSH_SESSION_JSONL=`。JSONL 路径只是位置提示:首次 flush 前它可能尚不存在,也可能不包含当前缓冲的轮次,并且它不是授权凭据。 -`ctx.bashEnv` 持有收集过程。其他插件可以注册具有 effect 作用域的贡献方,提供稳定名称、已声明的键/说明以及 `resolve(execution: ToolExecution)`;重复持有或运行时返回未声明的键会快速失败,而 `list()` 无需执行提供方即可列举声明。Harness 内置项保留 `DSH_HOME`、`DSH_SHELL` 和 `DSH_SESSION_ID`;tool-bash 的持久化转换器持有 `DSH_SESSION_JSONL`,其值来自后端无关的 `sessionPersistence.locate()` seam。 +`ctx.bashEnv` 持有收集过程。其他插件可以注册具有 effect 作用域的贡献方,提供稳定名称、已声明的键/说明以及 `resolve(execution: ToolExecution)`;重复持有或运行时返回未声明的键会快速失败,而 `list()` 无需执行提供方即可列举声明。Harness 内置项保留 `DSH_HOME`、`DSH_SHELL` 和 `DSH_SESSION_ID`;`dsh-bash-env` 的会话持久化贡献方持有 `DSH_SESSION_JSONL`,其值来自后端无关的 `sessionPersistence.locate()` seam。 ```ts import type { Context } from 'cordis' diff --git a/packages/examples/agent-spine-demo/package.json b/packages/examples/agent-spine-demo/package.json index 10c6ce7e55..0d32a387ca 100644 --- a/packages/examples/agent-spine-demo/package.json +++ b/packages/examples/agent-spine-demo/package.json @@ -79,7 +79,6 @@ "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tasks": "workspace:^", "@deepseek-ai/dsh-tasks-local": "workspace:^", - "@deepseek-ai/dsh-bash-env": "workspace:^", "@deepseek-ai/dsh-tool-bash": "workspace:^", "@deepseek-ai/dsh-tool-fs": "workspace:^", "@deepseek-ai/dsh-tool-goal": "workspace:^", From a228fe15a20a5558753f909ef57c6c01c8f67b82 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 20:31:43 +0800 Subject: [PATCH 37/61] docs(graph): regenerate the module graph for the merged tree The merge resolved the module-graph.md conflict by regenerating doc GRAPHS (gen-doc-graphs) while this file belongs to gen-module-graph; verify-module-graph is a static-lane gate outside doc-sync, so the staleness only surfaced on CI. --- docs/module-graph.md | 119 ++++++++++++++++++++++++++----------------- 1 file changed, 71 insertions(+), 48 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index edb925960b..88de6c11ea 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -38,9 +38,12 @@ flowchart TD end subgraph group_bash["packages/bash"] pkg_bash["bash"] + pkg_bash_env["bash-env"] pkg_bash_local["bash-local"] pkg_bash_sandbox["bash-sandbox"] + pkg_pwsh_local["pwsh-local"] pkg_tool_bash["tool-bash"] + pkg_tool_pwsh["tool-pwsh"] end subgraph group_fs["packages/fs"] pkg_fs["fs"] @@ -504,6 +507,10 @@ flowchart TD pkg_bash_local --> pkg_invariants pkg_bash_local --> pkg_subprocess pkg_bash_local --> pkg_timeout + pkg_pwsh_local --> pkg_bash + pkg_pwsh_local --> pkg_invariants + pkg_pwsh_local --> pkg_subprocess + pkg_pwsh_local --> pkg_timeout pkg_fs_local --> pkg_fs pkg_fs_local --> pkg_invariants pkg_fs_policy --> pkg_fs @@ -691,18 +698,11 @@ flowchart TD pkg_tool_goal --> pkg_session pkg_tool_goal --> pkg_system_prompt pkg_tool_goal --> pkg_tools - pkg_tool_bash --> pkg_agent - pkg_tool_bash --> pkg_bash - pkg_tool_bash --> pkg_invariants - pkg_tool_bash --> pkg_llm - pkg_tool_bash --> pkg_paths - pkg_tool_bash --> pkg_sandbox - pkg_tool_bash --> pkg_sandbox_policy - pkg_tool_bash --> pkg_session_persistence - pkg_tool_bash --> pkg_system_prompt - pkg_tool_bash --> pkg_tasks - pkg_tool_bash --> pkg_tools - pkg_tool_bash --> pkg_user_approval + pkg_bash_env --> pkg_bash + pkg_bash_env --> pkg_invariants + pkg_bash_env --> pkg_paths + pkg_bash_env --> pkg_session_persistence + pkg_bash_env --> pkg_tools pkg_tool_fs --> pkg_fs pkg_tool_fs --> pkg_invariants pkg_tool_fs --> pkg_llm @@ -886,6 +886,25 @@ flowchart TD pkg_tool_workflow --> pkg_system_prompt pkg_tool_workflow --> pkg_tools pkg_tool_workflow --> pkg_workflow + pkg_tool_bash --> pkg_agent + pkg_tool_bash --> pkg_bash + pkg_tool_bash --> pkg_bash_env + pkg_tool_bash --> pkg_invariants + pkg_tool_bash --> pkg_llm + pkg_tool_bash --> pkg_sandbox + pkg_tool_bash --> pkg_sandbox_policy + pkg_tool_bash --> pkg_system_prompt + pkg_tool_bash --> pkg_tasks + pkg_tool_bash --> pkg_tools + pkg_tool_bash --> pkg_user_approval + pkg_tool_pwsh --> pkg_agent + pkg_tool_pwsh --> pkg_bash + pkg_tool_pwsh --> pkg_bash_env + pkg_tool_pwsh --> pkg_invariants + pkg_tool_pwsh --> pkg_llm + pkg_tool_pwsh --> pkg_system_prompt + pkg_tool_pwsh --> pkg_tasks + pkg_tool_pwsh --> pkg_tools pkg_subagent_acp --> pkg_agent pkg_subagent_acp --> pkg_invariants pkg_subagent_acp --> pkg_llm @@ -984,27 +1003,6 @@ flowchart TD pkg_client_ui_subagent --> pkg_invariants pkg_client_ui_subagent --> pkg_subagent pkg_client_ui_subagent --> pkg_token_meter - pkg_agent_spine_demo --> pkg_agent - pkg_agent_spine_demo --> pkg_agent_loop - pkg_agent_spine_demo --> pkg_goal - pkg_agent_spine_demo --> pkg_goal_session - pkg_agent_spine_demo --> pkg_invariants - pkg_agent_spine_demo --> pkg_llm - pkg_agent_spine_demo --> pkg_llm_retry - pkg_agent_spine_demo --> pkg_paths - pkg_agent_spine_demo --> pkg_scope - pkg_agent_spine_demo --> pkg_session - pkg_agent_spine_demo --> pkg_session_title - pkg_agent_spine_demo --> pkg_skill - pkg_agent_spine_demo --> pkg_skill_local - pkg_agent_spine_demo --> pkg_system_prompt - pkg_agent_spine_demo --> pkg_tasks_local - pkg_agent_spine_demo --> pkg_tool_bash - pkg_agent_spine_demo --> pkg_tool_goal - pkg_agent_spine_demo --> pkg_tool_skill - pkg_agent_spine_demo --> pkg_tool_tasks - pkg_agent_spine_demo --> pkg_tools - pkg_agent_spine_demo --> pkg_workspace_context pkg_sdk_protocol --> pkg_invariants pkg_sdk_protocol --> pkg_llm pkg_sdk_protocol --> pkg_session @@ -1040,6 +1038,39 @@ flowchart TD pkg_jsonrpc --> pkg_sdk_protocol pkg_jsonrpc --> pkg_session pkg_jsonrpc --> pkg_subagent + pkg_agent_spine_demo --> pkg_agent + pkg_agent_spine_demo --> pkg_agent_loop + pkg_agent_spine_demo --> pkg_bash_env + pkg_agent_spine_demo --> pkg_goal + pkg_agent_spine_demo --> pkg_goal_session + pkg_agent_spine_demo --> pkg_invariants + pkg_agent_spine_demo --> pkg_llm + pkg_agent_spine_demo --> pkg_llm_retry + pkg_agent_spine_demo --> pkg_paths + pkg_agent_spine_demo --> pkg_scope + pkg_agent_spine_demo --> pkg_session + pkg_agent_spine_demo --> pkg_session_title + pkg_agent_spine_demo --> pkg_skill + pkg_agent_spine_demo --> pkg_skill_local + pkg_agent_spine_demo --> pkg_system_prompt + pkg_agent_spine_demo --> pkg_tasks_local + pkg_agent_spine_demo --> pkg_tool_bash + pkg_agent_spine_demo --> pkg_tool_goal + pkg_agent_spine_demo --> pkg_tool_skill + pkg_agent_spine_demo --> pkg_tool_tasks + pkg_agent_spine_demo --> pkg_tools + pkg_agent_spine_demo --> pkg_workspace_context + pkg_sdk_client --> pkg_invariants + pkg_sdk_client --> pkg_llm + pkg_sdk_client --> pkg_sdk_protocol + pkg_sdk_client --> pkg_session + pkg_subagent_dsh_sdk --> pkg_agent + pkg_subagent_dsh_sdk --> pkg_invariants + pkg_subagent_dsh_sdk --> pkg_llm + pkg_subagent_dsh_sdk --> pkg_sdk_client + pkg_subagent_dsh_sdk --> pkg_session + pkg_subagent_dsh_sdk --> pkg_subagent + pkg_subagent_dsh_sdk --> pkg_subprocess pkg_acp_demo --> pkg_acp pkg_acp_demo --> pkg_agent_spine_demo pkg_acp_demo --> pkg_app_boot @@ -1060,17 +1091,6 @@ flowchart TD pkg_cli_demo --> pkg_session_persistence_jsonl pkg_cli_demo --> pkg_tools pkg_cli_demo --> pkg_workspace_context - pkg_sdk_client --> pkg_invariants - pkg_sdk_client --> pkg_llm - pkg_sdk_client --> pkg_sdk_protocol - pkg_sdk_client --> pkg_session - pkg_subagent_dsh_sdk --> pkg_agent - pkg_subagent_dsh_sdk --> pkg_invariants - pkg_subagent_dsh_sdk --> pkg_llm - pkg_subagent_dsh_sdk --> pkg_sdk_client - pkg_subagent_dsh_sdk --> pkg_session - pkg_subagent_dsh_sdk --> pkg_subagent - pkg_subagent_dsh_sdk --> pkg_subprocess ``` | Package | Group | Depends on | @@ -1159,6 +1179,7 @@ flowchart TD | [`token-meter`](../packages/llm/token-meter) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session-projection/session-projection) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session-projection/session-projection) | | [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`pwsh-local`](../packages/bash/pwsh-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants) | | [`fs-policy`](../packages/fs/fs-policy) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants) | | [`skill-local`](../packages/skill/skill-local) | `skill` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`skill`](../packages/skill/skill) | @@ -1199,7 +1220,7 @@ flowchart TD | [`session-telemetry-otel`](../packages/telemetry/session-telemetry-otel) | `telemetry` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`session`](../packages/core/session), [`session-telemetry`](../packages/telemetry/session-telemetry) | | [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-bash`](../packages/bash/tool-bash) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | +| [`bash-env`](../packages/bash/bash-env) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`session-persistence`](../packages/session-persistence/session-persistence), [`tools`](../packages/core/tools) | | [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | | [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) | @@ -1230,6 +1251,8 @@ flowchart TD | [`tool-pty`](../packages/pty/tool-pty) | `pty` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`pty`](../packages/pty/pty), [`retention`](../packages/util/retention), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | | [`tool-tasks`](../packages/tasks/tool-tasks) | `tasks` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | +| [`tool-bash`](../packages/bash/tool-bash) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`bash-env`](../packages/bash/bash-env), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | +| [`tool-pwsh`](../packages/bash/tool-pwsh) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`bash-env`](../packages/bash/bash-env), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | | [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`tasks`](../packages/tasks/tasks), [`tools`](../packages/core/tools) | @@ -1242,14 +1265,14 @@ flowchart TD | [`client-ui-permission`](../packages/client/ui-permission) | `client` | [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-schema-form`](../packages/client/schema-form), [`client-ui-command`](../packages/client/ui-command), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants), [`permission`](../packages/ui/permission) | | [`client-ui-plan`](../packages/client/ui-plan) | `client` | [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants), [`plan-mode`](../packages/plan/plan-mode) | | [`client-ui-subagent`](../packages/client/ui-subagent) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter) | -| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`paths`](../packages/util/paths), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`skill`](../packages/skill/skill), [`skill-local`](../packages/skill/skill-local), [`system-prompt`](../packages/core/system-prompt), [`tasks-local`](../packages/tasks/tasks-local), [`tool-bash`](../packages/bash/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-skill`](../packages/skill/tool-skill), [`tool-tasks`](../packages/tasks/tool-tasks), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | | [`sdk-protocol`](../packages/sdk/sdk-protocol) | `sdk` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`tool-ralph`](../packages/workflow/tool-ralph) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`subagent-fork`](../packages/subagent/subagent-fork) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | | [`subagent-spawn`](../packages/subagent/subagent-spawn) | `subagent` | [`invariants`](../packages/support/invariants), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | | [`jsonrpc`](../packages/ui/jsonrpc) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/sdk-protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | -| [`acp-demo`](../packages/examples/acp-demo) | `examples` | [`acp`](../packages/acp/acp), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | -| [`cli-demo`](../packages/examples/cli-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | +| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`bash-env`](../packages/bash/bash-env), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`paths`](../packages/util/paths), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`skill`](../packages/skill/skill), [`skill-local`](../packages/skill/skill-local), [`system-prompt`](../packages/core/system-prompt), [`tasks-local`](../packages/tasks/tasks-local), [`tool-bash`](../packages/bash/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-skill`](../packages/skill/tool-skill), [`tool-tasks`](../packages/tasks/tool-tasks), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | | [`sdk-client`](../packages/sdk/sdk-client) | `sdk` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/sdk-protocol), [`session`](../packages/core/session) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/sdk-client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | +| [`acp-demo`](../packages/examples/acp-demo) | `examples` | [`acp`](../packages/acp/acp), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | +| [`cli-demo`](../packages/examples/cli-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | From 90c9087a3ef6e61e7b90ff5758e92d3ffa4e5352 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 20:57:26 +0800 Subject: [PATCH 38/61] test(web): follow the structured abort message in the bash-abort-row scenario master's new disclosure test pins the literal the abort backport retired; the seeded cancel fixture now carries 'Error: tool call aborted', so the test literals and the ARIA golden follow (replay-verified on Linux). --- apps/web/tests/bash-abort-row.e2e.ts | 4 ++-- apps/web/tests/snapshots/bash-abort-row/ui.expected.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/web/tests/bash-abort-row.e2e.ts b/apps/web/tests/bash-abort-row.e2e.ts index 717cebdd36..3d48442747 100644 --- a/apps/web/tests/bash-abort-row.e2e.ts +++ b/apps/web/tests/bash-abort-row.e2e.ts @@ -56,7 +56,7 @@ describe.skipIf(MODE === 'record')('web e2e: cancelled Bash row disclosure', () const row = page.locator('[data-sample="bash"]').first() const call = row.locator('xpath=..') await expect.poll(() => row.getAttribute('aria-expanded')).toBe('false') - await expect.poll(() => call.getByText('Error: command aborted', { exact: true }).count()).toBe(1) + await expect.poll(() => call.getByText('Error: tool call aborted', { exact: true }).count()).toBe(1) await row.click() await expect.poll(() => row.getAttribute('aria-expanded')).toBe('true') @@ -64,7 +64,7 @@ describe.skipIf(MODE === 'record')('web e2e: cancelled Bash row disclosure', () await call.getByText('OUT', { exact: true }).waitFor() await call.getByText('Wait until cancellation', { exact: false }).waitFor() await call.getByText('setInterval(() => {}, 1000)', { exact: false }).waitFor() - await expect.poll(() => call.getByText('Error: command aborted', { exact: true }).count()).toBe(2) + await expect.poll(() => call.getByText('Error: tool call aborted', { exact: true }).count()).toBe(2) const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) // The borrowed fixture's UTC date is still the previous day in PDT; diff --git a/apps/web/tests/snapshots/bash-abort-row/ui.expected.md b/apps/web/tests/snapshots/bash-abort-row/ui.expected.md index 8f09d36efd..c95c6b8de6 100644 --- a/apps/web/tests/snapshots/bash-abort-row/ui.expected.md +++ b/apps/web/tests/snapshots/bash-abort-row/ui.expected.md @@ -14,10 +14,10 @@ - img - img - text: Context injection -- 'button "Failed Bash Error: command aborted" [expanded]': +- 'button "Failed Bash Error: tool call aborted" [expanded]': - img - - text: "Failed Bash Error: command aborted" -- text: "IN { \"command\": \"node -e \\\"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\\\"\", \"description\": \"Wait until cancellation\" } OUT Error: command aborted" + - text: "Failed Bash Error: tool call aborted" +- text: "IN { \"command\": \"node -e \\\"require('node:fs').writeFileSync('started.txt', 'started'); setInterval(() => {}, 1000)\\\"\", \"description\": \"Wait until cancellation\" } OUT Error: tool call aborted" - button "Inspect" - 'button "Failed Bash Error: tool call aborted before dispatch"': - img From 3d1166fcdd2a574d157deac2b7d7b03c35f1401e Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 22:47:53 +0800 Subject: [PATCH 39/61] feat(bash): shell tools reject a mismatched executor dialect at load The seam gains ShellDialect ('bash' | 'powershell' - concrete shells, not families: zsh or fish would be their own values, never 'bash'); bash-local declares bash (bash-sandbox inherits), pwsh-local declares powershell, and both tools throw at load when the mounted executor speaks another dialect - previously tool-pwsh over bash-local handed PowerShell text to bash -c and the deployment error surfaced as ordinary nonzero exits. Pinned by mismatch tests on both tools; the parity note records the contract (both languages). Also from the review round: the tool-bash README's managed-environment section becomes a summary linking the owning dsh-bash-env contract (the duplicated prose carried a stale owner in its example import), the pwshOnly JSDoc drops the stale 'on PATH' phrasing, and the task-tools contract comment in the two pwsh compositions is indented into its block. --- ...2026-08-02-pwsh-tool-bash-parity.i18n.yaml | 4 ++-- .../2026-08-02-pwsh-tool-bash-parity.md | 1 + .../2026-08-02-pwsh-tool-bash-parity.zh.md | 1 + docs/cordis-catalog/services.md | 2 +- .../acp-agent/tests/pwsh.cordis.snapshot.yml | 3 ++- examples/acp-agent/tests/pwsh.cordis.yml | 3 ++- packages/bash/bash-local/src/index.ts | 2 ++ packages/bash/bash/README.i18n.yaml | 4 ++-- packages/bash/bash/README.md | 2 +- packages/bash/bash/README.zh.md | 2 +- packages/bash/bash/src/index.ts | 16 +++++++++++++ packages/bash/bash/tests/service.spec.ts | 2 ++ packages/bash/pwsh-local/src/index.ts | 2 ++ packages/bash/tool-bash/README.i18n.yaml | 4 ++-- packages/bash/tool-bash/README.md | 23 ++----------------- packages/bash/tool-bash/README.zh.md | 23 ++----------------- packages/bash/tool-bash/src/index.ts | 5 ++++ packages/bash/tool-bash/tests/tools.spec.ts | 21 ++++++++++++++++- packages/bash/tool-pwsh/README.i18n.yaml | 4 ++-- packages/bash/tool-pwsh/README.md | 2 +- packages/bash/tool-pwsh/README.zh.md | 2 +- packages/bash/tool-pwsh/src/index.ts | 5 ++++ packages/bash/tool-pwsh/tests/tools.spec.ts | 17 +++++++++++++- .../tmux-context/tests/tmux-context.spec.ts | 2 ++ packages/support/acp-snapshot/src/suite.ts | 2 +- t1120.json | 1 + zh-tail.txt | 3 +++ 27 files changed, 98 insertions(+), 60 deletions(-) create mode 100644 t1120.json create mode 100644 zh-tail.txt diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml index 6cbc24d8aa..d5b4798e33 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.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-02-pwsh-tool-bash-parity.md -2026-08-02-pwsh-tool-bash-parity.md: 417c6d6bc91eb3afaa38976e0013e4fbe72854ca -2026-08-02-pwsh-tool-bash-parity.zh.md: 926433526b3820f7b4770acb3ee172448970b601 +2026-08-02-pwsh-tool-bash-parity.md: 286acbce3289331a107924120da91464b2303bab +2026-08-02-pwsh-tool-bash-parity.zh.md: 4de34c1416821436c156b1b19b7ae775779e8915 diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md index 417c6d6bc9..286acbce32 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md @@ -29,6 +29,7 @@ The first Windows-native foundation shipped `dsh-tool-pwsh` as a deliberately mi - The bash and pwsh tools are now behaviorally interchangeable for foreground and background shell work (minus sandbox), and the pwsh prompt/description sentences are each backed by the renderer — the reviewer's grep-against-code check passes. - Parity ran BOTH ways once: the pwsh tool's structured foreground abort (`HarnessError('tool call aborted', TOOL_ABORTED)` with name `AbortError`) was backported to the bash tool, replacing its uncoded `Error('command aborted')` — a model-visible/logged change pinned by exact-shape tests on both sides and by the cancel-tool-calls fixture. - `@deepseek-ai/dsh-bash-env` is a new shipped package; `dsh-tool-bash`'s `dshHome` config moved there, so compositions mounting the shell tools must also mount `bash-env` (the spine bundles do). +- The seam now carries a `dialect` (`ShellDialect`: `bash` | `powershell` — concrete shells, not families; a POSIX-ish sibling would be its own value), and both shell tools reject a mismatched executor at load, so pairing tool-pwsh with bash-local (or the reverse) fails loud instead of surfacing commands handed to the wrong parser as ordinary nonzero exits. - Windows-only semantics (CRLF normalization, forced-termination exit-1/signal-null, POSIX-only self-signal) remain pinned by tests as before. - The pwsh tool's per-file coverage gate rides on the scriptable fake-executor suite (`tests/tools.spec.ts`); the real-pwsh integration and Loader-composition suites self-skip where `pwsh` is absent, mirroring the bash suites' division of labor. - The roadmap proposal's parity stage is delivered; its remaining stages are the Windows default composition and pwsh TUI/GUI rendering. diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md index 926433526b..4de34c1416 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md @@ -29,6 +29,7 @@ Status: implemented - bash 与 pwsh 工具在前台与后台 shell 工作(减 sandbox)上行为可互换,pwsh 的 prompt/描述句每句都有渲染器背书——reviewer 的“拿代码 grep 对证”检查通过。 - 对齐也反向发生过一次:pwsh 工具的结构化前台中止(`HarnessError('tool call aborted', TOOL_ABORTED)`,name 为 `AbortError`)被回移到 bash 工具,取代其无码的 `Error('command aborted')`——这是模型可见/入日志的变更,由两侧的精确形状测试与 cancel-tool-calls fixture 钉住。 - `@deepseek-ai/dsh-bash-env` 成为新的交付包;`dsh-tool-bash` 的 `dshHome` 配置迁往那里,因此挂载 shell 工具的组合也必须挂载 `bash-env`(spine bundle 已如此)。 +- seam 现在携带 `dialect`(`ShellDialect`:`bash` | `powershell`——具体 shell 而非家族;类 POSIX 的同胞将是自己的值),两个 shell 工具在加载时拒绝不匹配的执行器:把 tool-pwsh 与 bash-local 误配(或反之)会响亮失败,而不是让交错 parser 的命令表现为普通非零退出。 - Windows 专属语义(CRLF 归一化、强制终止 exit-1/signal-null、仅 POSIX 的自信号)一如既往由测试钉住。 - pwsh 工具的 per-file 覆盖门禁由可脚本化的 fake-executor 套件(`tests/tools.spec.ts`)承担;真实 pwsh 的集成与 Loader 组合套件在无 `pwsh` 的宿主自跳过,与 bash 套件的分工一致。 - 路线图提案的 parity 阶段已交付;其余阶段是 Windows 默认组合与 pwsh TUI/GUI 渲染。 diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index eb6993962c..111741a1a7 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -293,7 +293,7 @@ abstract start(spec: BashExecSpec): BashProcess Types: [BashExecRequest](../core-data-structures/bash.md) · [BashExecSpec](../core-data-structures/bash.md) · [BashProcess](../core-data-structures/bash.md) · [BashRunResult](../core-data-structures/bash.md) -Source: [`packages/bash/bash/src/index.ts:51`](../../packages/bash/bash/src/index.ts) +Source: [`packages/bash/bash/src/index.ts:59`](../../packages/bash/bash/src/index.ts) ## `ctx.bashEnv` — `BashEnvRegistry` diff --git a/examples/acp-agent/tests/pwsh.cordis.snapshot.yml b/examples/acp-agent/tests/pwsh.cordis.snapshot.yml index 91fdeabf53..9daab43aff 100644 --- a/examples/acp-agent/tests/pwsh.cordis.snapshot.yml +++ b/examples/acp-agent/tests/pwsh.cordis.snapshot.yml @@ -27,7 +27,8 @@ workspaceContext: false skills: enabled: false -# task_output/task_kill stay mounted so background pwsh runs are readable and killable. + # task_output/task_kill stay mounted (the bundle's toolTasks default) so + # background pwsh runs are readable and killable. goals: false # The pwsh tool replaces the bundle's bash tool in this composition. toolBash: false diff --git a/examples/acp-agent/tests/pwsh.cordis.yml b/examples/acp-agent/tests/pwsh.cordis.yml index cb8305c7d9..7021ae2116 100644 --- a/examples/acp-agent/tests/pwsh.cordis.yml +++ b/examples/acp-agent/tests/pwsh.cordis.yml @@ -26,7 +26,8 @@ workspaceContext: false skills: enabled: false -# task_output/task_kill stay mounted so background pwsh runs are readable and killable. + # task_output/task_kill stay mounted (the bundle's toolTasks default) so + # background pwsh runs are readable and killable. goals: false # The pwsh tool replaces the bundle's bash tool in this composition. toolBash: false diff --git a/packages/bash/bash-local/src/index.ts b/packages/bash/bash-local/src/index.ts index 0f5a1b4e4d..7bc57fad0b 100644 --- a/packages/bash/bash-local/src/index.ts +++ b/packages/bash/bash-local/src/index.ts @@ -80,6 +80,8 @@ function assertPositiveFinite(name: string, value: number): void { export class LocalBashExecutor extends BashExecutor { static inject = ['subprocess'] + readonly dialect = 'bash' as const + static Config: z = z.object({ cwd: z.string(), timeoutMs: z.number().default(120_000), diff --git a/packages/bash/bash/README.i18n.yaml b/packages/bash/bash/README.i18n.yaml index 4a2c37ad91..de2e7510e0 100644 --- a/packages/bash/bash/README.i18n.yaml +++ b/packages/bash/bash/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/bash/bash/README.md -README.md: d7bf746969f52000fe298b65b995b7c631d8001c -README.zh.md: a7c0cac0bce2154362c822c213a44f3c507d541c +README.md: b4dbfb6cd9af92d65e30be8d0237b17611b6cbe8 +README.zh.md: 8cf73948970bf0ba465d04b5bedc7e4146fdd217 diff --git a/packages/bash/bash/README.md b/packages/bash/bash/README.md index d7bf746969..b4dbfb6cd9 100644 --- a/packages/bash/bash/README.md +++ b/packages/bash/bash/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The **bash executor seam**: an abstract `BashExecutor` service (`ctx.bash`) defining WHAT a bash backend does — run foreground commands and start background processes — without saying HOW. Task ids, ownership, collection, cancellation, and notices belong to the generic `ctx.tasks` runtime. +The **bash executor seam**: an abstract `BashExecutor` service (`ctx.bash`) defining WHAT a bash backend does — run foreground commands and start background processes — without saying HOW. Every implementation declares its `dialect` (`ShellDialect`: the concrete shell that parses the command string, `bash` or `powershell`), and the model-facing shell tools reject a mismatched executor at load. Task ids, ownership, collection, cancellation, and notices belong to the generic `ctx.tasks` runtime. This package is the interface quarter of the bash capability, split so each concern can evolve (and be swapped) independently: diff --git a/packages/bash/bash/README.zh.md b/packages/bash/bash/README.zh.md index a7c0cac0bc..8cf7394897 100644 --- a/packages/bash/bash/README.zh.md +++ b/packages/bash/bash/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -**bash 执行器 seam**:抽象 `BashExecutor` 服务(`ctx.bash`)定义 bash 后端做什么,即运行前台命令与启动后台进程,但不规定如何实现。task id、所有权、收集、取消与通知属于通用 `ctx.tasks` 运行时。 +**bash 执行器 seam**:抽象 `BashExecutor` 服务(`ctx.bash`)定义 bash 后端做什么,即运行前台命令与启动后台进程,但不规定如何实现。每个实现声明自己的 `dialect`(`ShellDialect`:解析命令字符串的具体 shell,`bash` 或 `powershell`),模型侧 shell 工具在加载时拒绝不匹配的执行器。task id、所有权、收集、取消与通知属于通用 `ctx.tasks` 运行时。 本包(package)是 bash 能力中负责接口的四分之一,各项职责因此可以独立演进(和替换): diff --git a/packages/bash/bash/src/index.ts b/packages/bash/bash/src/index.ts index 4f8ae112a9..756f866e73 100644 --- a/packages/bash/bash/src/index.ts +++ b/packages/bash/bash/src/index.ts @@ -29,6 +29,14 @@ declare module 'cordis' { } } +/** + * The shell language a command string is written in. Values name concrete + * shells, not families — the executor hands the string verbatim to that + * shell's parser (`bash -c`, `pwsh -Command`), so a POSIX-ish sibling such + * as zsh or fish would be its own dialect, never `bash`. + */ +export type ShellDialect = 'bash' | 'powershell' + /** * Abstract bash execution service. Subclass, implement the abstract methods, * and load the subclass as a plugin — it registers as `ctx.bash` (one @@ -53,6 +61,14 @@ export abstract class BashExecutor extends Service { super(ctx, 'bash') } + /** + * The shell dialect this executor's `run`/`start` parse commands with. + * Model-facing shell tools reject a mismatched executor at load + * (misconfiguration fails loud): a PowerShell command handed to `bash -c` + * would otherwise surface as an ordinary nonzero exit. + */ + abstract readonly dialect: ShellDialect + /** * The sandbox mode this executor applies by default, or `undefined` when it * does not sandbox commands. diff --git a/packages/bash/bash/tests/service.spec.ts b/packages/bash/bash/tests/service.spec.ts index cacfe85eca..33eb9a61b0 100644 --- a/packages/bash/bash/tests/service.spec.ts +++ b/packages/bash/bash/tests/service.spec.ts @@ -10,6 +10,8 @@ import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashR * owes the abstract class. */ class StubExecutor extends BashExecutor { + readonly dialect = 'bash' as const + resolve(request: BashExecRequest): BashExecSpec { return { command: request.command, diff --git a/packages/bash/pwsh-local/src/index.ts b/packages/bash/pwsh-local/src/index.ts index 316d2c8651..8fc7f43054 100644 --- a/packages/bash/pwsh-local/src/index.ts +++ b/packages/bash/pwsh-local/src/index.ts @@ -104,6 +104,8 @@ function assertPositiveFinite(name: string, value: number): void { export class PwshLocalExecutor extends BashExecutor { static inject = ['subprocess'] + readonly dialect = 'powershell' as const + static Config: z = z.object({ cwd: z.string(), timeoutMs: z.number().default(120_000), diff --git a/packages/bash/tool-bash/README.i18n.yaml b/packages/bash/tool-bash/README.i18n.yaml index 19370b6c64..6eaff6daa5 100644 --- a/packages/bash/tool-bash/README.i18n.yaml +++ b/packages/bash/tool-bash/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/bash/tool-bash/README.md -README.md: c168b3bfe49faec0be8bd7664411f538a8142edf -README.zh.md: 3b94f8bc2e4aca8ade15c4e2e1e35d1674c66fdb +README.md: be89acf06dbc6b4c420dd7fd34eb6ccb842c1fbd +README.zh.md: 7886addd4c941d81a90546518a5967f64edcdf61 diff --git a/packages/bash/tool-bash/README.md b/packages/bash/tool-bash/README.md index c168b3bfe4..be89acf06d 100644 --- a/packages/bash/tool-bash/README.md +++ b/packages/bash/tool-bash/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The model-facing `bash` tool registered over the `ctx.bash` executor seam. Foreground execution stays behind that seam; a background process handle is registered with the generic `ctx.tasks` runtime and controlled through `task_output`, `task_list`, and `task_kill` from `@deepseek-ai/dsh-tool-tasks`. -Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`) and the [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) registry; the plugin stays pending until every injected service exists (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`). +Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`) and the [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) registry; the plugin stays pending until every injected service exists (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`), and rejects an executor whose `dialect` is not `bash` at load — a bash command handed to another shell's parser would surface as an ordinary nonzero exit. The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`); result rendering and background-process adaptation remain implementation details covered by same-package tests. @@ -28,26 +28,7 @@ The plugin also contributes the `tool:bash` prompt section (order 105): check th ### Managed shell environment -Every foreground and background model bash call receives a newly collected trusted `DSH_*` environment. `DSH_HOME` is the absolute Harness home resolved by [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) (`dshHome` config, then ambient `$DSH_HOME`, then `~/.dsh`) and `DSH_SHELL=1` identifies the managed child. Agent calls additionally receive `DSH_SESSION_ID=agent.session.header.id`; when the active persistence seam locates a JSONL artifact they also receive `DSH_SESSION_JSONL=`. The JSONL path is a location hint: it may not exist before the first flush or contain the current buffered turn, and it is not an authorization credential. - -`ctx.bashEnv` owns collection. Other plugins can register an effect-scoped contributor with a stable name, declared keys/descriptions, and `resolve(execution: ToolExecution)`; duplicate ownership and undeclared runtime keys fail loudly, while `list()` enumerates declarations without executing providers. Harness built-ins reserve `DSH_HOME`, `DSH_SHELL`, and `DSH_SESSION_ID`; `dsh-bash-env`'s session-persistence contributor owns `DSH_SESSION_JSONL` by reading the backend-neutral `sessionPersistence.locate()` seam. - -```ts -import type { Context } from 'cordis' -import type {} from '@deepseek-ai/dsh-tool-bash' - -export const inject = ['bashEnv'] - -export function apply(ctx: Context): void { - ctx.bashEnv.register({ - name: 'deployment-region', - variables: { DSH_DEPLOYMENT_REGION: { description: 'Current deployment region.' } }, - resolve: execution => execution.agent === undefined ? {} : { DSH_DEPLOYMENT_REGION: 'cn-north' }, - }) -} -``` - -The overlay is computed from the current `ToolExecution` and passed through the dedicated `BashExecRequest.dshEnv` channel. The local executor removes all inherited `DSH_*` before merging that snapshot, so nested harnesses and concurrent parent/child agents cannot leak stale identities. `process.env` is never modified. The tool description teaches the generic `$DSH_*` convention rather than naming persistence-specific variables or adding a permanent system-prompt section. +Every foreground and background model bash call receives a freshly collected trusted `DSH_*` environment through the shared [`dsh-bash-env`](../bash-env/README.md) registry: `DSH_HOME` (the absolute Harness home), `DSH_SHELL=1`, the agent's `DSH_SESSION_ID`, and `DSH_SESSION_JSONL` when the active persistence backend locates one. The registry contract — contributor registration, loud duplicate/undeclared-key failure, the built-in reservations, and the contributor example — lives in that package's README. The snapshot passes through the dedicated `BashExecRequest.dshEnv` channel; the local executor removes all inherited `DSH_*` before merging it, so nested harnesses and concurrent parent/child agents cannot leak stale identities, and `process.env` is never modified. The tool description teaches the generic `$DSH_*` convention rather than naming persistence-specific variables or adding a permanent system-prompt section. Result text contains stdout, an optional `[stderr]` section, then applicable sandbox-denial, timeout, signal, exit-code, and truncation markers. Timeout is reported independently of final exit status; nonzero exit remains a model-interpreted result rather than `isError`. Truncation links a safe complete spill file or reports it unavailable. Only infrastructure failures such as spawn errors and aborts produce `isError`. diff --git a/packages/bash/tool-bash/README.zh.md b/packages/bash/tool-bash/README.zh.md index 3b94f8bc2e..7886addd4c 100644 --- a/packages/bash/tool-bash/README.zh.md +++ b/packages/bash/tool-bash/README.zh.md @@ -4,7 +4,7 @@ 模型侧 `bash` 工具,注册在 `ctx.bash` 执行器 seam 上。前台执行始终位于该 seam 之后;后台进程句柄会注册到通用 `ctx.tasks` 运行时,并通过 `task_output`、`task_list` 和 `task_kill` 控制;这些工具由 `@deepseek-ai/dsh-tool-tasks` 提供。 -需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`)与 [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) 注册表;在每个注入服务就绪之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。 +需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`)与 [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) 注册表;在每个注入服务就绪之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`),并在加载时拒绝 `dialect` 不为 `bash` 的执行器——bash 命令被交给其他 shell 解析只会表现为普通的非零退出。 包(package)根只公开 Cordis 插件契约(`name`、`inject`、`Config`、`apply`);结果渲染和后台进程适配仍是实现细节,由同包测试覆盖。 @@ -28,26 +28,7 @@ ### 托管 shell 环境 -每次模型发起的前台或后台 bash 调用都会收到新收集的一组可信 `DSH_*` 环境变量。`DSH_HOME` 是由 [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) 解析出的 Harness home 绝对路径(依次采用 `dshHome` 配置、环境中的 `$DSH_HOME`、`~/.dsh`),`DSH_SHELL=1` 则标识受托管的子进程。Agent 调用还会收到 `DSH_SESSION_ID=agent.session.header.id`;当活跃的持久化 seam 找到 JSONL 产物时,也会收到 `DSH_SESSION_JSONL=`。JSONL 路径只是位置提示:首次 flush 前它可能尚不存在,也可能不包含当前缓冲的轮次,并且它不是授权凭据。 - -`ctx.bashEnv` 持有收集过程。其他插件可以注册具有 effect 作用域的贡献方,提供稳定名称、已声明的键/说明以及 `resolve(execution: ToolExecution)`;重复持有或运行时返回未声明的键会快速失败,而 `list()` 无需执行提供方即可列举声明。Harness 内置项保留 `DSH_HOME`、`DSH_SHELL` 和 `DSH_SESSION_ID`;`dsh-bash-env` 的会话持久化贡献方持有 `DSH_SESSION_JSONL`,其值来自后端无关的 `sessionPersistence.locate()` seam。 - -```ts -import type { Context } from 'cordis' -import type {} from '@deepseek-ai/dsh-tool-bash' - -export const inject = ['bashEnv'] - -export function apply(ctx: Context): void { - ctx.bashEnv.register({ - name: 'deployment-region', - variables: { DSH_DEPLOYMENT_REGION: { description: 'Current deployment region.' } }, - resolve: execution => execution.agent === undefined ? {} : { DSH_DEPLOYMENT_REGION: 'cn-north' }, - }) -} -``` - -overlay 根据当前 `ToolExecution` 计算,并通过专用的 `BashExecRequest.dshEnv` 通道传递。本地执行器会先删除继承的所有 `DSH_*`,再合并该快照,因此嵌套 harness 和并发的父/子 agent 不会泄漏陈旧身份。它绝不会修改 `process.env`。工具说明只教授通用 `$DSH_*` 约定,不会点名持久化专用变量,也不会添加永久的系统提示词段落。 +每次模型发起的前台或后台 bash 调用都会通过共享的 [`dsh-bash-env`](../bash-env/README.md) 注册表收到新收集的一组可信 `DSH_*` 环境变量:`DSH_HOME`(Harness home 绝对路径)、`DSH_SHELL=1`、agent 的 `DSH_SESSION_ID`,以及当活跃持久化后端能定位时的 `DSH_SESSION_JSONL`。注册表契约——贡献方注册、重复/未声明键的响亮失败、内置项保留与贡献方示例——住在该包的 README 里。快照通过专用的 `BashExecRequest.dshEnv` 通道传递;本地执行器会先删除继承的所有 `DSH_*` 再合并,因此嵌套 harness 和并发的父/子 agent 不会泄漏陈旧身份,且绝不修改 `process.env`。工具说明只教授通用 `$DSH_*` 约定,不会点名持久化专用变量,也不会添加永久的系统提示词段落。 结果文本依次包含 stdout、可选的 `[stderr]` 段落和适用的沙箱拒绝、超时、信号、退出代码及截断标记。超时与最终退出状态分别报告;非零退出仍是由模型解释的结果,不会成为 `isError`。截断结果会链接安全的完整 spill 文件,或报告文件不可用。只有 spawn 错误和中止等基础设施故障才会产生 `isError`。 diff --git a/packages/bash/tool-bash/src/index.ts b/packages/bash/tool-bash/src/index.ts index 91a88c9cca..41a2491375 100644 --- a/packages/bash/tool-bash/src/index.ts +++ b/packages/bash/tool-bash/src/index.ts @@ -188,6 +188,11 @@ const BACKGROUND_OUTPUT_PROPERTIES = { } as const export function apply(ctx: Context, config: Config = {}): void { + // Model commands are written in bash; a mismatched executor would hand + // them to another shell's parser and surface as ordinary nonzero exits. + if (ctx.bash.dialect !== 'bash') { + throw new Error(`tool-bash: the mounted executor speaks '${ctx.bash.dialect}', not bash — mount a bash executor (e.g. dsh-bash-local) or the matching shell tool`) + } const backgroundEnabled = config.enableRunInBackground ?? true const defaultMode = ctx.bash.sandboxMode const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS diff --git a/packages/bash/tool-bash/tests/tools.spec.ts b/packages/bash/tool-bash/tests/tools.spec.ts index 4f913d78ee..9cb2330928 100644 --- a/packages/bash/tool-bash/tests/tools.spec.ts +++ b/packages/bash/tool-bash/tests/tools.spec.ts @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import { CallId } from '@deepseek-ai/dsh-llm' import { BashExecutor } from '@deepseek-ai/dsh-bash' -import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult } from '@deepseek-ai/dsh-bash' +import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult, ShellDialect } from '@deepseek-ai/dsh-bash' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import AgentRegistry from '@deepseek-ai/dsh-agent' @@ -101,6 +101,8 @@ async function callUntilText( } class RecordingSandboxExecutor extends BashExecutor { + readonly dialect = 'bash' as const + readonly modes: Array = [] override get sandboxMode() { @@ -154,6 +156,8 @@ class RecordingSandboxExecutor extends BashExecutor { /** Test executor that records whether the background start boundary was crossed. */ class CountingStartExecutor extends BashExecutor { + readonly dialect: ShellDialect = 'bash' + starts = 0 resolve(request: BashExecRequest): BashExecSpec { @@ -361,6 +365,19 @@ describe('bash tool', () => { expect(text(result)).toContain('tool execution arguments must be losslessly JSON-serializable') }) + it('rejects an executor speaking another shell dialect at load', async () => { + class PowershellDialectExecutor extends CountingStartExecutor { + override readonly dialect: ShellDialect = 'powershell' + } + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(BashEnvPlugin) + await ctx.plugin(PowershellDialectExecutor) + await expect(ctx.plugin(ToolBash)).rejects.toThrow("the mounted executor speaks 'powershell', not bash") + }) + it('registers the bash schema with run_in_background exposed by default', async () => { const ctx = await setup() const schemas = ctx.tools.schemas() @@ -1067,6 +1084,8 @@ describe('the model-facing bash tool builds its request from named args only (no * hands back an already-settled fake handle so the task registration completes. */ class RecordingBashExecutor extends BashExecutor { + readonly dialect = 'bash' as const + readonly requests: BashExecRequest[] = [] resolve(request: BashExecRequest): BashExecSpec { this.requests.push(request) diff --git a/packages/bash/tool-pwsh/README.i18n.yaml b/packages/bash/tool-pwsh/README.i18n.yaml index 030d24c7c2..642f2c2089 100644 --- a/packages/bash/tool-pwsh/README.i18n.yaml +++ b/packages/bash/tool-pwsh/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/bash/tool-pwsh/README.md -README.md: dfe26a63684d61dcdd6f969c2c2261dac79325c7 -README.zh.md: 2344f8477e5b15f2c4d366dd82b46358eacbc1b7 +README.md: 7bc1c0998a67ee772ec54eb46bebed52e5164588 +README.zh.md: 4f74b7cb4b737fd4c4f788586568676423f59cd4 diff --git a/packages/bash/tool-pwsh/README.md b/packages/bash/tool-pwsh/README.md index dfe26a6368..7bc1c0998a 100644 --- a/packages/bash/tool-pwsh/README.md +++ b/packages/bash/tool-pwsh/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The model-facing `pwsh` tool registered over the `ctx.bash` executor seam. Intended for Windows compositions where a PowerShell executor (e.g. `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. Behavior mirrors `dsh-tool-bash` call-for-call minus the sandbox surface — foreground and `run_in_background` execution through the generic task runtime, the managed `DSH_*` environment through the shared `bash-env` registry, and the bash marker/truncation rendering story (a clean exit produces no marker). -Requires a loaded executor implementation and the `bash-env` plugin; the tool stays pending until both exist (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`). +Requires a loaded executor implementation and the `bash-env` plugin; the tool stays pending until both exist (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`), and rejects an executor whose `dialect` is not `powershell` at load — a PowerShell command handed to `bash -c` would surface as an ordinary nonzero exit. The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`); result rendering (`src/render.ts`) and background-task adaptation (`src/background.ts`) mirror the bash tool's structure and stay reachable through the package's `./src/*` export. diff --git a/packages/bash/tool-pwsh/README.zh.md b/packages/bash/tool-pwsh/README.zh.md index 2344f8477e..4f74b7cb4b 100644 --- a/packages/bash/tool-pwsh/README.zh.md +++ b/packages/bash/tool-pwsh/README.zh.md @@ -4,7 +4,7 @@ 注册在 `ctx.bash` 执行器 seam 之上的模型可见 `pwsh` 工具。面向由 PowerShell 执行器(如 `@deepseek-ai/dsh-pwsh-local`)支撑 `ctx.bash` 的 Windows 组合;工具契约是 PowerShell 方言:原生 `C:\...` 路径与 `$env:NAME` 变量。行为与 `dsh-tool-bash` 逐调用对齐、减去 sandbox 面——通过通用任务运行时执行前台与 `run_in_background`、通过共享 `bash-env` 注册表管理 `DSH_*` 环境、以及 bash 的 marker/截断渲染故事(干净退出不产生 marker)。 -需要已加载的执行器实现与 `bash-env` 插件;两者都存在前工具保持 pending(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。 +需要已加载的执行器实现与 `bash-env` 插件;两者都存在前工具保持 pending(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`),并在加载时拒绝 `dialect` 不为 `powershell` 的执行器——PowerShell 命令被交给 `bash -c` 只会表现为普通的非零退出。 包根只导出 Cordis 插件契约(`name`、`inject`、`Config`、`apply`);结果渲染(`src/render.ts`)与后台任务适配(`src/background.ts`)镜像 bash 工具的结构,并可通过包的 `./src/*` 导出访问。 diff --git a/packages/bash/tool-pwsh/src/index.ts b/packages/bash/tool-pwsh/src/index.ts index 9423fe36e6..969a9a777f 100644 --- a/packages/bash/tool-pwsh/src/index.ts +++ b/packages/bash/tool-pwsh/src/index.ts @@ -138,6 +138,11 @@ const BACKGROUND_OUTPUT_PROPERTIES = { /* jscpd:ignore-end */ export function apply(ctx: Context, config: Config = {}): void { + // Model commands are written in PowerShell; a mismatched executor would + // hand them to bash and surface as ordinary nonzero exits. + if (ctx.bash.dialect !== 'powershell') { + throw new Error(`tool-pwsh: the mounted executor speaks '${ctx.bash.dialect}', not powershell — mount dsh-pwsh-local or the matching shell tool`) + } const backgroundEnabled = config.enableRunInBackground ?? true ctx.systemPrompt.section({ diff --git a/packages/bash/tool-pwsh/tests/tools.spec.ts b/packages/bash/tool-pwsh/tests/tools.spec.ts index 218099326f..620be2f354 100644 --- a/packages/bash/tool-pwsh/tests/tools.spec.ts +++ b/packages/bash/tool-pwsh/tests/tools.spec.ts @@ -23,7 +23,7 @@ import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { SessionId } from '@deepseek-ai/dsh-session' import { BashExecutor } from '@deepseek-ai/dsh-bash' -import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from '@deepseek-ai/dsh-bash' +import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult, ShellDialect } from '@deepseek-ai/dsh-bash' import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh' import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' import type { BashProcessRead } from '@deepseek-ai/dsh-bash' @@ -38,6 +38,8 @@ const testToolSignal = new AbortController().signal * handle. */ class FakeBash extends BashExecutor { + readonly dialect: ShellDialect = 'powershell' + requests: BashExecRequest[] = [] specs: BashExecSpec[] = [] startCalls = 0 @@ -199,6 +201,19 @@ async function callUntilText( } describe('registration', () => { + it('rejects an executor speaking another shell dialect at load', async () => { + class BashDialectExecutor extends FakeBash { + override readonly dialect = 'bash' as const + } + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(BashEnvPlugin) + await ctx.plugin(BashDialectExecutor) + await expect(ctx.plugin(ToolPwsh)).rejects.toThrow("the mounted executor speaks 'bash', not powershell") + }) + it('registers the pwsh tool with its prompt section and schema', async () => { const { ctx } = await setup() const schema = ctx.tools.schemas().find(s => s.name === 'pwsh') diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index 1d94399184..54954f8e4d 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -48,6 +48,8 @@ function runResult(stdout: string, overrides: Partial = {}): Bash /** A scriptable fake `ctx.bash` recording the command it was asked to run. */ class FakeBash extends BashExecutor { + readonly dialect = 'bash' as const + commands: string[] = [] result: BashRunResult = runResult(`${tmuxLine()}\n`) runError?: Error diff --git a/packages/support/acp-snapshot/src/suite.ts b/packages/support/acp-snapshot/src/suite.ts index f9e97dd45b..db59c9265b 100644 --- a/packages/support/acp-snapshot/src/suite.ts +++ b/packages/support/acp-snapshot/src/suite.ts @@ -162,7 +162,7 @@ export interface Scenario { */ posixOnly?: boolean /** - * Whether the scenario boots a composition that needs a real `pwsh` on PATH + * Whether the scenario boots a composition that needs a usable `pwsh` * (the pwsh-tool-turn scenario). The run test is skipped when the suite's * {@link SnapshotSuiteOptions.hasPwsh} probe is false; fixtures stay guarded * on every platform. diff --git a/t1120.json b/t1120.json new file mode 100644 index 0000000000..3e064c460c --- /dev/null +++ b/t1120.json @@ -0,0 +1 @@ +[{"comments":{"nodes":[{"body":"🟡 **warning**: Duplicated contract with a stale example import: the §Managed shell environment section carries the full bashEnv registry contract (both prose paragraphs, the contributor code example, and the overlay paragraph) near-verbatim duplicated in this PR's new owning home, packages/bash/bash-env/README.md. The tool-bash copy's example still reads `import type {} from '@deepseek-ai/dsh-tool-bash'` to get `ctx.bashEnv` typed — but this PR moved the `declare module 'cordis'` merge to dsh-bash-env (tool-bash only type-imports it, so the example compiles transitively but names the wrong owner). tool-pwsh's README shows the intended post-extraction shape: a one-paragraph summary linking to ../bash-env/. Trim tool-bash's section to the bash-specific facts plus the link, keep the contract and example in bash-env only (one home per fact; symmetry between the two shell tools), update both language sides and re-record the pairing. Non-blocking, but worth fixing before merge since the stale example is a direct consequence of this PR's extraction.\n\n\u003csub\u003e🤖 v5\u003c/sub\u003e"}]},"id":"PRRT_kwDOS3Pfcs6V_H8o","isResolved":false,"line":30,"path":"packages/bash/tool-bash/README.md"},{"comments":{"nodes":[{"body":"🔵 **suggestion**: Nit: `Scenario.pwshOnly`'s JSDoc says the composition \"needs a real `pwsh` on PATH\", but the probe is caller-owned and the shipped caller (examples/acp-agent/tests/acp.snapshot.ts:441) deliberately follows resolvePwshPath() — Program Files installs are found even when bare `pwsh` is not on PATH. This is the same stale \"on PATH\" phrasing already corrected in the executor.spec.ts and integration.spec.ts headers this round. One-word fix: \"a usable `pwsh`\".\n\n\u003csub\u003e🤖 v5\u003c/sub\u003e"}]},"id":"PRRT_kwDOS3Pfcs6V_H8w","isResolved":false,"line":164,"path":"packages/support/acp-snapshot/src/suite.ts"},{"comments":{"nodes":[{"body":"🔵 **suggestion**: Optional nit: the `# task_output/task_kill stay mounted so background pwsh runs are readable and killable.` contract comment sits at column 0 mid-way through the acp-agent config map (between `skills` and `goals` keys), in both pwsh.cordis.yml and pwsh.cordis.snapshot.yml. Valid YAML and a genuinely useful pin (the mounting decision is the bundle's toolTasks default, invisible in this file), but indent it into the block or move it above the composition's plugin list where the decision reads naturally.\n\n\u003csub\u003e🤖 v5\u003c/sub\u003e"}]},"id":"PRRT_kwDOS3Pfcs6V_H82","isResolved":false,"line":30,"path":"examples/acp-agent/tests/pwsh.cordis.yml"},{"comments":{"nodes":[{"body":"🟡 **warning**: 拒绝 shell 工具与执行器方言不匹配: 当组合误将 `tool-pwsh` 与 `dsh-bash-local` 搭配时,当前注入会正常完成,PowerShell 命令却被交给 `bash -c`,通常只返回普通的非零退出标记;反向将 `tool-bash` 搭配 `pwsh-local` 也一样。新增第二种方言后,`ctx.bash` 需要暴露可校验的方言能力,并让两个工具在加载时拒绝不匹配的执行器,否则明显的部署错误会静默表现为命令失败。\n\n\u003csub\u003e🤖 v6\u003c/sub\u003e"}]},"id":"PRRT_kwDOS3Pfcs6V_H88","isResolved":false,"line":141,"path":"packages/bash/tool-pwsh/src/index.ts"}] diff --git a/zh-tail.txt b/zh-tail.txt new file mode 100644 index 0000000000..3429afb031 --- /dev/null +++ b/zh-tail.txt @@ -0,0 +1,3 @@ +overlay 根据当前 `ToolExecution` 计算,并通过专用的 `BashExecRequest.dshEnv` 通道传递。本地执行器会先删除继承的所有 `DSH_*`,再合并该快照,因此嵌套 harness 和并发的父/子 agent 不会泄漏陈旧身份。它绝不会修改 `process.env`。工具说明只教授通用 `$DSH_*` 约定,不会点名持久化专用变量,也不会添加永久的系统提示词段落。 + +结果文本依次包含 stdout、可选的 `[stderr]` 段落和适用的沙箱拒绝、超时、信号、退出代码及截断标记。超时与最终退出状态分别报告;非零退出仍是由模型解释的结果,不会成为 `isError`。截断结果会链接安全的完整 spill 文件,或报告文件不可用。只有 spawn 错误和中止等基础设施故障才会产生 `isError`。 From 9ae358e0876fbd6864266ff30a0e3082a884a3a3 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 22:48:49 +0800 Subject: [PATCH 40/61] chore: drop a stray scratch file --- zh-tail.txt | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 zh-tail.txt diff --git a/zh-tail.txt b/zh-tail.txt deleted file mode 100644 index 3429afb031..0000000000 --- a/zh-tail.txt +++ /dev/null @@ -1,3 +0,0 @@ -overlay 根据当前 `ToolExecution` 计算,并通过专用的 `BashExecRequest.dshEnv` 通道传递。本地执行器会先删除继承的所有 `DSH_*`,再合并该快照,因此嵌套 harness 和并发的父/子 agent 不会泄漏陈旧身份。它绝不会修改 `process.env`。工具说明只教授通用 `$DSH_*` 约定,不会点名持久化专用变量,也不会添加永久的系统提示词段落。 - -结果文本依次包含 stdout、可选的 `[stderr]` 段落和适用的沙箱拒绝、超时、信号、退出代码及截断标记。超时与最终退出状态分别报告;非零退出仍是由模型解释的结果,不会成为 `isError`。截断结果会链接安全的完整 spill 文件,或报告文件不可用。只有 spawn 错误和中止等基础设施故障才会产生 `isError`。 From b43358e215719e158b811c19f1ae493038188af3 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 22:50:25 +0800 Subject: [PATCH 41/61] chore: drop another stray scratch file --- t1120.json | 1 - 1 file changed, 1 deletion(-) delete mode 100644 t1120.json diff --git a/t1120.json b/t1120.json deleted file mode 100644 index 3e064c460c..0000000000 --- a/t1120.json +++ /dev/null @@ -1 +0,0 @@ -[{"comments":{"nodes":[{"body":"🟡 **warning**: Duplicated contract with a stale example import: the §Managed shell environment section carries the full bashEnv registry contract (both prose paragraphs, the contributor code example, and the overlay paragraph) near-verbatim duplicated in this PR's new owning home, packages/bash/bash-env/README.md. The tool-bash copy's example still reads `import type {} from '@deepseek-ai/dsh-tool-bash'` to get `ctx.bashEnv` typed — but this PR moved the `declare module 'cordis'` merge to dsh-bash-env (tool-bash only type-imports it, so the example compiles transitively but names the wrong owner). tool-pwsh's README shows the intended post-extraction shape: a one-paragraph summary linking to ../bash-env/. Trim tool-bash's section to the bash-specific facts plus the link, keep the contract and example in bash-env only (one home per fact; symmetry between the two shell tools), update both language sides and re-record the pairing. Non-blocking, but worth fixing before merge since the stale example is a direct consequence of this PR's extraction.\n\n\u003csub\u003e🤖 v5\u003c/sub\u003e"}]},"id":"PRRT_kwDOS3Pfcs6V_H8o","isResolved":false,"line":30,"path":"packages/bash/tool-bash/README.md"},{"comments":{"nodes":[{"body":"🔵 **suggestion**: Nit: `Scenario.pwshOnly`'s JSDoc says the composition \"needs a real `pwsh` on PATH\", but the probe is caller-owned and the shipped caller (examples/acp-agent/tests/acp.snapshot.ts:441) deliberately follows resolvePwshPath() — Program Files installs are found even when bare `pwsh` is not on PATH. This is the same stale \"on PATH\" phrasing already corrected in the executor.spec.ts and integration.spec.ts headers this round. One-word fix: \"a usable `pwsh`\".\n\n\u003csub\u003e🤖 v5\u003c/sub\u003e"}]},"id":"PRRT_kwDOS3Pfcs6V_H8w","isResolved":false,"line":164,"path":"packages/support/acp-snapshot/src/suite.ts"},{"comments":{"nodes":[{"body":"🔵 **suggestion**: Optional nit: the `# task_output/task_kill stay mounted so background pwsh runs are readable and killable.` contract comment sits at column 0 mid-way through the acp-agent config map (between `skills` and `goals` keys), in both pwsh.cordis.yml and pwsh.cordis.snapshot.yml. Valid YAML and a genuinely useful pin (the mounting decision is the bundle's toolTasks default, invisible in this file), but indent it into the block or move it above the composition's plugin list where the decision reads naturally.\n\n\u003csub\u003e🤖 v5\u003c/sub\u003e"}]},"id":"PRRT_kwDOS3Pfcs6V_H82","isResolved":false,"line":30,"path":"examples/acp-agent/tests/pwsh.cordis.yml"},{"comments":{"nodes":[{"body":"🟡 **warning**: 拒绝 shell 工具与执行器方言不匹配: 当组合误将 `tool-pwsh` 与 `dsh-bash-local` 搭配时,当前注入会正常完成,PowerShell 命令却被交给 `bash -c`,通常只返回普通的非零退出标记;反向将 `tool-bash` 搭配 `pwsh-local` 也一样。新增第二种方言后,`ctx.bash` 需要暴露可校验的方言能力,并让两个工具在加载时拒绝不匹配的执行器,否则明显的部署错误会静默表现为命令失败。\n\n\u003csub\u003e🤖 v6\u003c/sub\u003e"}]},"id":"PRRT_kwDOS3Pfcs6V_H88","isResolved":false,"line":141,"path":"packages/bash/tool-pwsh/src/index.ts"}] From f14f826648bbb7280bf06c8abd4bf5d95e7c0483 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 23:16:53 +0800 Subject: [PATCH 42/61] revert(bash): drop the executor dialect guard The ShellDialect marker on BashExecutor and the load-time rejection in tool-bash/tool-pwsh force every test and example fake executor to declare a dialect for a guard with no in-repo or plausible deployment to catch (shipped compositions always pair the tool with its matching executor), and they break the example composition suites that stub ctx.bash without a dialect (agent-spine-demo/cli-demo/acp-demo lost the bash tool). Keep the non-dialect doc fixes that landed with the attempt: the tool-bash README bashEnv contract trim with the stale example import removed, the acp-snapshot suite.ts 'usable pwsh' JSDoc, and the pwsh.cordis.yml comment indent. The parity note records the attempt and revert under Alternatives. --- ...2026-08-02-pwsh-tool-bash-parity.i18n.yaml | 4 ++-- .../2026-08-02-pwsh-tool-bash-parity.md | 3 ++- .../2026-08-02-pwsh-tool-bash-parity.zh.md | 3 ++- docs/cordis-catalog/services.md | 2 +- packages/bash/bash-local/src/index.ts | 2 -- packages/bash/bash/README.i18n.yaml | 4 ++-- packages/bash/bash/README.md | 2 +- packages/bash/bash/README.zh.md | 2 +- packages/bash/bash/src/index.ts | 16 -------------- packages/bash/bash/tests/service.spec.ts | 2 -- packages/bash/pwsh-local/src/index.ts | 2 -- packages/bash/tool-bash/README.i18n.yaml | 4 ++-- packages/bash/tool-bash/README.md | 2 +- packages/bash/tool-bash/README.zh.md | 2 +- packages/bash/tool-bash/src/index.ts | 5 ----- packages/bash/tool-bash/tests/tools.spec.ts | 21 +------------------ packages/bash/tool-pwsh/README.i18n.yaml | 4 ++-- packages/bash/tool-pwsh/README.md | 2 +- packages/bash/tool-pwsh/README.zh.md | 2 +- packages/bash/tool-pwsh/src/index.ts | 5 ----- packages/bash/tool-pwsh/tests/tools.spec.ts | 17 +-------------- .../tmux-context/tests/tmux-context.spec.ts | 2 -- 22 files changed, 21 insertions(+), 87 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml index d5b4798e33..e17e4685e3 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.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-02-pwsh-tool-bash-parity.md -2026-08-02-pwsh-tool-bash-parity.md: 286acbce3289331a107924120da91464b2303bab -2026-08-02-pwsh-tool-bash-parity.zh.md: 4de34c1416821436c156b1b19b7ae775779e8915 +2026-08-02-pwsh-tool-bash-parity.md: bf40c440b9f7f330412d8949f59c54d541152d45 +2026-08-02-pwsh-tool-bash-parity.zh.md: bc67dac29900eacf9e615e76fe947e3e642a3979 diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md index 286acbce32..bf40c440b9 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.md @@ -22,6 +22,8 @@ The first Windows-native foundation shipped `dsh-tool-pwsh` as a deliberately mi **Keep the minimal profile and fix only the claims.** Rejected: the review's core finding was that text contracts copied from bash drift without the corresponding implementation; a minimal tool plus accurate claims still leaves pwsh calls without background execution, without contributor parity, and with a divergent marker story that must be re-justified forever. +**Reject a mismatched executor dialect at load.** Attempted and reverted before merge: a `ShellDialect` marker (`bash` | `powershell`) on `BashExecutor`, with both shell tools throwing when the mounted executor speaks another shell. It forced every executor implementation — including each test and example fake — to declare a dialect, adding noise to every shell-tool test for a guard with no in-repo or plausible deployment to catch (shipped compositions always pair tool-pwsh with `dsh-pwsh-local` and tool-bash with `dsh-bash-local`). The pairing contract stays documented in each tool's README instead. + **Extract a fully shared tool implementation base (abstract shell dialect, two thin leaves).** Considered and deferred: the bash-env extraction and the structural mirror (`render.ts`/`background.ts` twins) are the foundation it would rest on; a full base waits until a third dialect or the persistent-PTY twin makes the abstraction's shape observable. ## Consequences @@ -29,7 +31,6 @@ The first Windows-native foundation shipped `dsh-tool-pwsh` as a deliberately mi - The bash and pwsh tools are now behaviorally interchangeable for foreground and background shell work (minus sandbox), and the pwsh prompt/description sentences are each backed by the renderer — the reviewer's grep-against-code check passes. - Parity ran BOTH ways once: the pwsh tool's structured foreground abort (`HarnessError('tool call aborted', TOOL_ABORTED)` with name `AbortError`) was backported to the bash tool, replacing its uncoded `Error('command aborted')` — a model-visible/logged change pinned by exact-shape tests on both sides and by the cancel-tool-calls fixture. - `@deepseek-ai/dsh-bash-env` is a new shipped package; `dsh-tool-bash`'s `dshHome` config moved there, so compositions mounting the shell tools must also mount `bash-env` (the spine bundles do). -- The seam now carries a `dialect` (`ShellDialect`: `bash` | `powershell` — concrete shells, not families; a POSIX-ish sibling would be its own value), and both shell tools reject a mismatched executor at load, so pairing tool-pwsh with bash-local (or the reverse) fails loud instead of surfacing commands handed to the wrong parser as ordinary nonzero exits. - Windows-only semantics (CRLF normalization, forced-termination exit-1/signal-null, POSIX-only self-signal) remain pinned by tests as before. - The pwsh tool's per-file coverage gate rides on the scriptable fake-executor suite (`tests/tools.spec.ts`); the real-pwsh integration and Loader-composition suites self-skip where `pwsh` is absent, mirroring the bash suites' division of labor. - The roadmap proposal's parity stage is delivered; its remaining stages are the Windows default composition and pwsh TUI/GUI rendering. diff --git a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md index 4de34c1416..bc67dac299 100644 --- a/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md +++ b/.agents/notes/implemented/feature/2026-08-02-pwsh-tool-bash-parity.zh.md @@ -22,6 +22,8 @@ Status: implemented **保留最小画像,只修声明。** 否决:review 的核心发现是"从 bash 复制的文本契约在缺少对应实现时会漂移";最小工具加准确声明仍让 pwsh 调用没有后台执行、没有 contributor 对等、并留下一个必须永远重新辩护的偏离 marker 故事。 +**在加载时拒绝不匹配的执行器方言。** 合并前尝试过并撤回:在 `BashExecutor` 上加 `ShellDialect` 标记(`bash` | `powershell`),两个 shell 工具在挂载的执行器说另一种方言时抛错。它迫使每个执行器实现——包括每个测试与示例的 fake——都要声明 dialect,为一道仓内及合理部署中都没有目标可拦的护栏(交付组合总是把 tool-pwsh 配 `dsh-pwsh-local`、tool-bash 配 `dsh-bash-local`)给每个 shell 工具测试添噪。配对契约改由各工具 README 记录。 + **提取完全共享的工具实现基座(抽象 shell 方言,两个薄叶子)。** 考虑后推迟:bash-env 提取与结构镜像(`render.ts`/`background.ts` 孪生)是它要立足的基础;在出现第三种方言或持久 PTY 孪生、让抽象的形态可观察之前,不做完整基座。 ## 后果 @@ -29,7 +31,6 @@ Status: implemented - bash 与 pwsh 工具在前台与后台 shell 工作(减 sandbox)上行为可互换,pwsh 的 prompt/描述句每句都有渲染器背书——reviewer 的“拿代码 grep 对证”检查通过。 - 对齐也反向发生过一次:pwsh 工具的结构化前台中止(`HarnessError('tool call aborted', TOOL_ABORTED)`,name 为 `AbortError`)被回移到 bash 工具,取代其无码的 `Error('command aborted')`——这是模型可见/入日志的变更,由两侧的精确形状测试与 cancel-tool-calls fixture 钉住。 - `@deepseek-ai/dsh-bash-env` 成为新的交付包;`dsh-tool-bash` 的 `dshHome` 配置迁往那里,因此挂载 shell 工具的组合也必须挂载 `bash-env`(spine bundle 已如此)。 -- seam 现在携带 `dialect`(`ShellDialect`:`bash` | `powershell`——具体 shell 而非家族;类 POSIX 的同胞将是自己的值),两个 shell 工具在加载时拒绝不匹配的执行器:把 tool-pwsh 与 bash-local 误配(或反之)会响亮失败,而不是让交错 parser 的命令表现为普通非零退出。 - Windows 专属语义(CRLF 归一化、强制终止 exit-1/signal-null、仅 POSIX 的自信号)一如既往由测试钉住。 - pwsh 工具的 per-file 覆盖门禁由可脚本化的 fake-executor 套件(`tests/tools.spec.ts`)承担;真实 pwsh 的集成与 Loader 组合套件在无 `pwsh` 的宿主自跳过,与 bash 套件的分工一致。 - 路线图提案的 parity 阶段已交付;其余阶段是 Windows 默认组合与 pwsh TUI/GUI 渲染。 diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 111741a1a7..eb6993962c 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -293,7 +293,7 @@ abstract start(spec: BashExecSpec): BashProcess Types: [BashExecRequest](../core-data-structures/bash.md) · [BashExecSpec](../core-data-structures/bash.md) · [BashProcess](../core-data-structures/bash.md) · [BashRunResult](../core-data-structures/bash.md) -Source: [`packages/bash/bash/src/index.ts:59`](../../packages/bash/bash/src/index.ts) +Source: [`packages/bash/bash/src/index.ts:51`](../../packages/bash/bash/src/index.ts) ## `ctx.bashEnv` — `BashEnvRegistry` diff --git a/packages/bash/bash-local/src/index.ts b/packages/bash/bash-local/src/index.ts index 7bc57fad0b..0f5a1b4e4d 100644 --- a/packages/bash/bash-local/src/index.ts +++ b/packages/bash/bash-local/src/index.ts @@ -80,8 +80,6 @@ function assertPositiveFinite(name: string, value: number): void { export class LocalBashExecutor extends BashExecutor { static inject = ['subprocess'] - readonly dialect = 'bash' as const - static Config: z = z.object({ cwd: z.string(), timeoutMs: z.number().default(120_000), diff --git a/packages/bash/bash/README.i18n.yaml b/packages/bash/bash/README.i18n.yaml index de2e7510e0..4a2c37ad91 100644 --- a/packages/bash/bash/README.i18n.yaml +++ b/packages/bash/bash/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/bash/bash/README.md -README.md: b4dbfb6cd9af92d65e30be8d0237b17611b6cbe8 -README.zh.md: 8cf73948970bf0ba465d04b5bedc7e4146fdd217 +README.md: d7bf746969f52000fe298b65b995b7c631d8001c +README.zh.md: a7c0cac0bce2154362c822c213a44f3c507d541c diff --git a/packages/bash/bash/README.md b/packages/bash/bash/README.md index b4dbfb6cd9..d7bf746969 100644 --- a/packages/bash/bash/README.md +++ b/packages/bash/bash/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The **bash executor seam**: an abstract `BashExecutor` service (`ctx.bash`) defining WHAT a bash backend does — run foreground commands and start background processes — without saying HOW. Every implementation declares its `dialect` (`ShellDialect`: the concrete shell that parses the command string, `bash` or `powershell`), and the model-facing shell tools reject a mismatched executor at load. Task ids, ownership, collection, cancellation, and notices belong to the generic `ctx.tasks` runtime. +The **bash executor seam**: an abstract `BashExecutor` service (`ctx.bash`) defining WHAT a bash backend does — run foreground commands and start background processes — without saying HOW. Task ids, ownership, collection, cancellation, and notices belong to the generic `ctx.tasks` runtime. This package is the interface quarter of the bash capability, split so each concern can evolve (and be swapped) independently: diff --git a/packages/bash/bash/README.zh.md b/packages/bash/bash/README.zh.md index 8cf7394897..a7c0cac0bc 100644 --- a/packages/bash/bash/README.zh.md +++ b/packages/bash/bash/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -**bash 执行器 seam**:抽象 `BashExecutor` 服务(`ctx.bash`)定义 bash 后端做什么,即运行前台命令与启动后台进程,但不规定如何实现。每个实现声明自己的 `dialect`(`ShellDialect`:解析命令字符串的具体 shell,`bash` 或 `powershell`),模型侧 shell 工具在加载时拒绝不匹配的执行器。task id、所有权、收集、取消与通知属于通用 `ctx.tasks` 运行时。 +**bash 执行器 seam**:抽象 `BashExecutor` 服务(`ctx.bash`)定义 bash 后端做什么,即运行前台命令与启动后台进程,但不规定如何实现。task id、所有权、收集、取消与通知属于通用 `ctx.tasks` 运行时。 本包(package)是 bash 能力中负责接口的四分之一,各项职责因此可以独立演进(和替换): diff --git a/packages/bash/bash/src/index.ts b/packages/bash/bash/src/index.ts index 756f866e73..4f8ae112a9 100644 --- a/packages/bash/bash/src/index.ts +++ b/packages/bash/bash/src/index.ts @@ -29,14 +29,6 @@ declare module 'cordis' { } } -/** - * The shell language a command string is written in. Values name concrete - * shells, not families — the executor hands the string verbatim to that - * shell's parser (`bash -c`, `pwsh -Command`), so a POSIX-ish sibling such - * as zsh or fish would be its own dialect, never `bash`. - */ -export type ShellDialect = 'bash' | 'powershell' - /** * Abstract bash execution service. Subclass, implement the abstract methods, * and load the subclass as a plugin — it registers as `ctx.bash` (one @@ -61,14 +53,6 @@ export abstract class BashExecutor extends Service { super(ctx, 'bash') } - /** - * The shell dialect this executor's `run`/`start` parse commands with. - * Model-facing shell tools reject a mismatched executor at load - * (misconfiguration fails loud): a PowerShell command handed to `bash -c` - * would otherwise surface as an ordinary nonzero exit. - */ - abstract readonly dialect: ShellDialect - /** * The sandbox mode this executor applies by default, or `undefined` when it * does not sandbox commands. diff --git a/packages/bash/bash/tests/service.spec.ts b/packages/bash/bash/tests/service.spec.ts index 33eb9a61b0..cacfe85eca 100644 --- a/packages/bash/bash/tests/service.spec.ts +++ b/packages/bash/bash/tests/service.spec.ts @@ -10,8 +10,6 @@ import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashR * owes the abstract class. */ class StubExecutor extends BashExecutor { - readonly dialect = 'bash' as const - resolve(request: BashExecRequest): BashExecSpec { return { command: request.command, diff --git a/packages/bash/pwsh-local/src/index.ts b/packages/bash/pwsh-local/src/index.ts index 8fc7f43054..316d2c8651 100644 --- a/packages/bash/pwsh-local/src/index.ts +++ b/packages/bash/pwsh-local/src/index.ts @@ -104,8 +104,6 @@ function assertPositiveFinite(name: string, value: number): void { export class PwshLocalExecutor extends BashExecutor { static inject = ['subprocess'] - readonly dialect = 'powershell' as const - static Config: z = z.object({ cwd: z.string(), timeoutMs: z.number().default(120_000), diff --git a/packages/bash/tool-bash/README.i18n.yaml b/packages/bash/tool-bash/README.i18n.yaml index 6eaff6daa5..c22dd9c62c 100644 --- a/packages/bash/tool-bash/README.i18n.yaml +++ b/packages/bash/tool-bash/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/bash/tool-bash/README.md -README.md: be89acf06dbc6b4c420dd7fd34eb6ccb842c1fbd -README.zh.md: 7886addd4c941d81a90546518a5967f64edcdf61 +README.md: f21b6b4344fcfb94d88f1f7e1c4444ee89e0ead8 +README.zh.md: c9dd3f2250631f3300edaf2c246e6925f3e12005 diff --git a/packages/bash/tool-bash/README.md b/packages/bash/tool-bash/README.md index be89acf06d..f21b6b4344 100644 --- a/packages/bash/tool-bash/README.md +++ b/packages/bash/tool-bash/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The model-facing `bash` tool registered over the `ctx.bash` executor seam. Foreground execution stays behind that seam; a background process handle is registered with the generic `ctx.tasks` runtime and controlled through `task_output`, `task_list`, and `task_kill` from `@deepseek-ai/dsh-tool-tasks`. -Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`) and the [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) registry; the plugin stays pending until every injected service exists (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`), and rejects an executor whose `dialect` is not `bash` at load — a bash command handed to another shell's parser would surface as an ordinary nonzero exit. +Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`) and the [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) registry; the plugin stays pending until every injected service exists (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`). The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`); result rendering and background-process adaptation remain implementation details covered by same-package tests. diff --git a/packages/bash/tool-bash/README.zh.md b/packages/bash/tool-bash/README.zh.md index 7886addd4c..c9dd3f2250 100644 --- a/packages/bash/tool-bash/README.zh.md +++ b/packages/bash/tool-bash/README.zh.md @@ -4,7 +4,7 @@ 模型侧 `bash` 工具,注册在 `ctx.bash` 执行器 seam 上。前台执行始终位于该 seam 之后;后台进程句柄会注册到通用 `ctx.tasks` 运行时,并通过 `task_output`、`task_list` 和 `task_kill` 控制;这些工具由 `@deepseek-ai/dsh-tool-tasks` 提供。 -需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`)与 [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) 注册表;在每个注入服务就绪之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`),并在加载时拒绝 `dialect` 不为 `bash` 的执行器——bash 命令被交给其他 shell 解析只会表现为普通的非零退出。 +需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`)与 [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) 注册表;在每个注入服务就绪之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。 包(package)根只公开 Cordis 插件契约(`name`、`inject`、`Config`、`apply`);结果渲染和后台进程适配仍是实现细节,由同包测试覆盖。 diff --git a/packages/bash/tool-bash/src/index.ts b/packages/bash/tool-bash/src/index.ts index 41a2491375..91a88c9cca 100644 --- a/packages/bash/tool-bash/src/index.ts +++ b/packages/bash/tool-bash/src/index.ts @@ -188,11 +188,6 @@ const BACKGROUND_OUTPUT_PROPERTIES = { } as const export function apply(ctx: Context, config: Config = {}): void { - // Model commands are written in bash; a mismatched executor would hand - // them to another shell's parser and surface as ordinary nonzero exits. - if (ctx.bash.dialect !== 'bash') { - throw new Error(`tool-bash: the mounted executor speaks '${ctx.bash.dialect}', not bash — mount a bash executor (e.g. dsh-bash-local) or the matching shell tool`) - } const backgroundEnabled = config.enableRunInBackground ?? true const defaultMode = ctx.bash.sandboxMode const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS diff --git a/packages/bash/tool-bash/tests/tools.spec.ts b/packages/bash/tool-bash/tests/tools.spec.ts index 9cb2330928..4f913d78ee 100644 --- a/packages/bash/tool-bash/tests/tools.spec.ts +++ b/packages/bash/tool-bash/tests/tools.spec.ts @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import { CallId } from '@deepseek-ai/dsh-llm' import { BashExecutor } from '@deepseek-ai/dsh-bash' -import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult, ShellDialect } from '@deepseek-ai/dsh-bash' +import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult } from '@deepseek-ai/dsh-bash' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import AgentRegistry from '@deepseek-ai/dsh-agent' @@ -101,8 +101,6 @@ async function callUntilText( } class RecordingSandboxExecutor extends BashExecutor { - readonly dialect = 'bash' as const - readonly modes: Array = [] override get sandboxMode() { @@ -156,8 +154,6 @@ class RecordingSandboxExecutor extends BashExecutor { /** Test executor that records whether the background start boundary was crossed. */ class CountingStartExecutor extends BashExecutor { - readonly dialect: ShellDialect = 'bash' - starts = 0 resolve(request: BashExecRequest): BashExecSpec { @@ -365,19 +361,6 @@ describe('bash tool', () => { expect(text(result)).toContain('tool execution arguments must be losslessly JSON-serializable') }) - it('rejects an executor speaking another shell dialect at load', async () => { - class PowershellDialectExecutor extends CountingStartExecutor { - override readonly dialect: ShellDialect = 'powershell' - } - const ctx = new Context() - await ctx.plugin(SystemPrompt) - await ctx.plugin(ToolRegistry) - await ctx.plugin(AgentRegistry) - await ctx.plugin(BashEnvPlugin) - await ctx.plugin(PowershellDialectExecutor) - await expect(ctx.plugin(ToolBash)).rejects.toThrow("the mounted executor speaks 'powershell', not bash") - }) - it('registers the bash schema with run_in_background exposed by default', async () => { const ctx = await setup() const schemas = ctx.tools.schemas() @@ -1084,8 +1067,6 @@ describe('the model-facing bash tool builds its request from named args only (no * hands back an already-settled fake handle so the task registration completes. */ class RecordingBashExecutor extends BashExecutor { - readonly dialect = 'bash' as const - readonly requests: BashExecRequest[] = [] resolve(request: BashExecRequest): BashExecSpec { this.requests.push(request) diff --git a/packages/bash/tool-pwsh/README.i18n.yaml b/packages/bash/tool-pwsh/README.i18n.yaml index 642f2c2089..030d24c7c2 100644 --- a/packages/bash/tool-pwsh/README.i18n.yaml +++ b/packages/bash/tool-pwsh/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/bash/tool-pwsh/README.md -README.md: 7bc1c0998a67ee772ec54eb46bebed52e5164588 -README.zh.md: 4f74b7cb4b737fd4c4f788586568676423f59cd4 +README.md: dfe26a63684d61dcdd6f969c2c2261dac79325c7 +README.zh.md: 2344f8477e5b15f2c4d366dd82b46358eacbc1b7 diff --git a/packages/bash/tool-pwsh/README.md b/packages/bash/tool-pwsh/README.md index 7bc1c0998a..dfe26a6368 100644 --- a/packages/bash/tool-pwsh/README.md +++ b/packages/bash/tool-pwsh/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The model-facing `pwsh` tool registered over the `ctx.bash` executor seam. Intended for Windows compositions where a PowerShell executor (e.g. `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables. Behavior mirrors `dsh-tool-bash` call-for-call minus the sandbox surface — foreground and `run_in_background` execution through the generic task runtime, the managed `DSH_*` environment through the shared `bash-env` registry, and the bash marker/truncation rendering story (a clean exit produces no marker). -Requires a loaded executor implementation and the `bash-env` plugin; the tool stays pending until both exist (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`), and rejects an executor whose `dialect` is not `powershell` at load — a PowerShell command handed to `bash -c` would surface as an ordinary nonzero exit. +Requires a loaded executor implementation and the `bash-env` plugin; the tool stays pending until both exist (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`). The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`); result rendering (`src/render.ts`) and background-task adaptation (`src/background.ts`) mirror the bash tool's structure and stay reachable through the package's `./src/*` export. diff --git a/packages/bash/tool-pwsh/README.zh.md b/packages/bash/tool-pwsh/README.zh.md index 4f74b7cb4b..2344f8477e 100644 --- a/packages/bash/tool-pwsh/README.zh.md +++ b/packages/bash/tool-pwsh/README.zh.md @@ -4,7 +4,7 @@ 注册在 `ctx.bash` 执行器 seam 之上的模型可见 `pwsh` 工具。面向由 PowerShell 执行器(如 `@deepseek-ai/dsh-pwsh-local`)支撑 `ctx.bash` 的 Windows 组合;工具契约是 PowerShell 方言:原生 `C:\...` 路径与 `$env:NAME` 变量。行为与 `dsh-tool-bash` 逐调用对齐、减去 sandbox 面——通过通用任务运行时执行前台与 `run_in_background`、通过共享 `bash-env` 注册表管理 `DSH_*` 环境、以及 bash 的 marker/截断渲染故事(干净退出不产生 marker)。 -需要已加载的执行器实现与 `bash-env` 插件;两者都存在前工具保持 pending(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`),并在加载时拒绝 `dialect` 不为 `powershell` 的执行器——PowerShell 命令被交给 `bash -c` 只会表现为普通的非零退出。 +需要已加载的执行器实现与 `bash-env` 插件;两者都存在前工具保持 pending(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。 包根只导出 Cordis 插件契约(`name`、`inject`、`Config`、`apply`);结果渲染(`src/render.ts`)与后台任务适配(`src/background.ts`)镜像 bash 工具的结构,并可通过包的 `./src/*` 导出访问。 diff --git a/packages/bash/tool-pwsh/src/index.ts b/packages/bash/tool-pwsh/src/index.ts index 969a9a777f..9423fe36e6 100644 --- a/packages/bash/tool-pwsh/src/index.ts +++ b/packages/bash/tool-pwsh/src/index.ts @@ -138,11 +138,6 @@ const BACKGROUND_OUTPUT_PROPERTIES = { /* jscpd:ignore-end */ export function apply(ctx: Context, config: Config = {}): void { - // Model commands are written in PowerShell; a mismatched executor would - // hand them to bash and surface as ordinary nonzero exits. - if (ctx.bash.dialect !== 'powershell') { - throw new Error(`tool-pwsh: the mounted executor speaks '${ctx.bash.dialect}', not powershell — mount dsh-pwsh-local or the matching shell tool`) - } const backgroundEnabled = config.enableRunInBackground ?? true ctx.systemPrompt.section({ diff --git a/packages/bash/tool-pwsh/tests/tools.spec.ts b/packages/bash/tool-pwsh/tests/tools.spec.ts index 620be2f354..218099326f 100644 --- a/packages/bash/tool-pwsh/tests/tools.spec.ts +++ b/packages/bash/tool-pwsh/tests/tools.spec.ts @@ -23,7 +23,7 @@ import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { SessionId } from '@deepseek-ai/dsh-session' import { BashExecutor } from '@deepseek-ai/dsh-bash' -import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult, ShellDialect } from '@deepseek-ai/dsh-bash' +import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from '@deepseek-ai/dsh-bash' import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh' import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env' import type { BashProcessRead } from '@deepseek-ai/dsh-bash' @@ -38,8 +38,6 @@ const testToolSignal = new AbortController().signal * handle. */ class FakeBash extends BashExecutor { - readonly dialect: ShellDialect = 'powershell' - requests: BashExecRequest[] = [] specs: BashExecSpec[] = [] startCalls = 0 @@ -201,19 +199,6 @@ async function callUntilText( } describe('registration', () => { - it('rejects an executor speaking another shell dialect at load', async () => { - class BashDialectExecutor extends FakeBash { - override readonly dialect = 'bash' as const - } - const ctx = new Context() - await ctx.plugin(SystemPrompt) - await ctx.plugin(ToolRegistry) - await ctx.plugin(AgentRegistry) - await ctx.plugin(BashEnvPlugin) - await ctx.plugin(BashDialectExecutor) - await expect(ctx.plugin(ToolPwsh)).rejects.toThrow("the mounted executor speaks 'bash', not powershell") - }) - it('registers the pwsh tool with its prompt section and schema', async () => { const { ctx } = await setup() const schema = ctx.tools.schemas().find(s => s.name === 'pwsh') diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index 54954f8e4d..1d94399184 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -48,8 +48,6 @@ function runResult(stdout: string, overrides: Partial = {}): Bash /** A scriptable fake `ctx.bash` recording the command it was asked to run. */ class FakeBash extends BashExecutor { - readonly dialect = 'bash' as const - commands: string[] = [] result: BashRunResult = runResult(`${tmuxLine()}\n`) runError?: Error From d11b8286830371800d60944cae932f5dfaf30c8d Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 23:16:59 +0800 Subject: [PATCH 43/61] docs(acp-snapshot): document Scenario.pwshOnly and the hasPwsh probe The host-variance paragraph documented posixOnly and pinsNativeWindowsStdout but not the pwshOnly flag and SnapshotSuiteOptions.hasPwsh probe added with the pwsh-tool-turn scenario; add the parallel sentence on both language sides and re-record the pairing. --- packages/support/acp-snapshot/README.i18n.yaml | 4 ++-- packages/support/acp-snapshot/README.md | 2 +- packages/support/acp-snapshot/README.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/support/acp-snapshot/README.i18n.yaml b/packages/support/acp-snapshot/README.i18n.yaml index 376cea9dcd..4fa3b34202 100644 --- a/packages/support/acp-snapshot/README.i18n.yaml +++ b/packages/support/acp-snapshot/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/support/acp-snapshot/README.md -README.md: e7988733827ef1d4de67d6d49764a4836e33d17c -README.zh.md: e2466feb5e2025cb99f252b4206bfacb711bccda +README.md: 015eda6b25202f219a49f10e286b6c22061171bf +README.zh.md: 2581dd4b8e270adaebea46144045180df4cc0582 diff --git a/packages/support/acp-snapshot/README.md b/packages/support/acp-snapshot/README.md index e798873382..015eda6b25 100644 --- a/packages/support/acp-snapshot/README.md +++ b/packages/support/acp-snapshot/README.md @@ -55,7 +55,7 @@ A scenario booting a differently-composed tree sets its own `configPath` (an ove A pin owns its generated `system-prompt.expected.md` or `tool-schemas.expected.json` by default; `systemPromptSource` and `toolSchemasSource` name another pin when the complete corresponding sequence is identical, so each distinct version is committed once. The pin's `session.jsonl` stores `"system":"{{system}}","tools":"{{tools}}"` while retaining config, reason, and any model-visible prefix. A pin with legitimate mid-run header changes declares `expectedHeaderChanges`; a shared source must declare the same count, and record/refresh rejects claimants that generate different bytes. -Every scenario compares `stdout.expected.jsonl` with cwd-rooted separators canonicalized to `/`. On Windows, `pinsNativeWindowsStdout` additionally compares the complete `stdout.expected.windows.jsonl` after the shared expected output and requires that sidecar exactly when enabled. A scenario requiring a non-Windows host declares `posixOnly`, which skips its run test on Windows while the fixture guards keep covering its committed files everywhere; examples include POSIX process semantics (e.g. cancelling a live bash call kills a detached process group) and generated paths Windows cannot represent. +Every scenario compares `stdout.expected.jsonl` with cwd-rooted separators canonicalized to `/`. On Windows, `pinsNativeWindowsStdout` additionally compares the complete `stdout.expected.windows.jsonl` after the shared expected output and requires that sidecar exactly when enabled. A scenario requiring a non-Windows host declares `posixOnly`, which skips its run test on Windows while the fixture guards keep covering its committed files everywhere; examples include POSIX process semantics (e.g. cancelling a live bash call kills a detached process group) and generated paths Windows cannot represent. A scenario whose composition needs a usable `pwsh` declares `pwshOnly`; the suite's `hasPwsh` probe follows the executor's own resolution (so Program Files installs count), and the run test is skipped when no usable `pwsh` resolves while the fixture guards keep covering its committed files everywhere. The example also ships a `cordis.snapshot.yml` replay overlay next to its `cordis.yml` (the bin swaps them under `DSH_SNAPSHOT=replay` — [single-source replay config Agent Note](../../../.agents/notes/archived/testing/2026-07-04-single-source-acp-replay-config.md)); replay fixtures are served by [`dsh-llm-replay`](../llm-replay/README.md), which this package points at via the `DSH_SNAPSHOT_*` env vars it sets on the child. `pnpm run test:snapshot:record` calls the live LLM and rewrites the recorded scenarios' model fixtures; `pnpm run test:snapshot:refresh` stays keyless, runs the replay overlay, and rewrites stdout, comparable session-log expected outputs, and owned prompt and tool-schema sidecars from the committed model scripts. Fixture roles, record/replay/refresh semantics, and scenario-table fields are documented on `Scenario` and in the [snapshot Agent Note](../../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md). diff --git a/packages/support/acp-snapshot/README.zh.md b/packages/support/acp-snapshot/README.zh.md index e2466feb5e..2581dd4b8e 100644 --- a/packages/support/acp-snapshot/README.zh.md +++ b/packages/support/acp-snapshot/README.zh.md @@ -55,7 +55,7 @@ defineAcpSnapshotSuite({ 每个 pin 默认拥有其生成的 `system-prompt.expected.md` 或 `tool-schemas.expected.json`;当完整的对应序列相同时,`systemPromptSource` 和 `toolSchemasSource` 指定另一个 pin 作为来源,因此每个不同版本只提交一次。该 pin 的 `session.jsonl` 存储 `"system":"{{system}}","tools":"{{tools}}"`,同时保留配置、原因和任何模型可见前缀。具有合法运行中 header 变更的 pin 声明 `expectedHeaderChanges`;共享来源必须声明相同的 header 变更数量,录制/刷新会拒绝生成不同字节的共享引用方。 -每个场景都比较 `stdout.expected.jsonl`,其中以 cwd 为根的分隔符规范化为 `/`。在 Windows 上,`pinsNativeWindowsStdout` 还会在共享预期输出之后比较完整 `stdout.expected.windows.jsonl`,并在启用时精确要求该 sidecar。需要非 Windows 主机的场景声明 `posixOnly`,在 Windows 上跳过运行测试,但 fixture 保护仍在所有平台覆盖其已提交文件;示例包括 POSIX 进程语义(例如取消实时 bash 调用会终止脱离进程组)和 Windows 无法表示的生成路径。 +每个场景都比较 `stdout.expected.jsonl`,其中以 cwd 为根的分隔符规范化为 `/`。在 Windows 上,`pinsNativeWindowsStdout` 还会在共享预期输出之后比较完整 `stdout.expected.windows.jsonl`,并在启用时精确要求该 sidecar。需要非 Windows 主机的场景声明 `posixOnly`,在 Windows 上跳过运行测试,但 fixture 保护仍在所有平台覆盖其已提交文件;示例包括 POSIX 进程语义(例如取消实时 bash 调用会终止脱离进程组)和 Windows 无法表示的生成路径。组合需要可用 `pwsh` 的场景声明 `pwshOnly`;套件的 `hasPwsh` 探测遵循执行器自身的解析(因此 Program Files 安装也计入),在解析不到可用 `pwsh` 时跳过运行测试,而 fixture 保护仍处处覆盖其已提交文件。 示例还发布 `cordis.snapshot.yml` 回放 overlay,位于 `cordis.yml` 旁边(bin 在 `DSH_SNAPSHOT=replay` 下交换它们,见[单源回放配置 Agent Note](../../../.agents/notes/archived/testing/2026-07-04-single-source-acp-replay-config.md));回放 fixture 由 [`dsh-llm-replay`](../llm-replay/README.md) 提供,该包通过对子级设置的 `DSH_SNAPSHOT_*` env var 指向它。`pnpm run test:snapshot:record` 调用实时 LLM,并重写已记录场景的模型 fixture;`pnpm run test:snapshot:refresh` 保持无密钥,运行回放 overlay,并从已提交模型脚本重写 stdout、可比较会话日志预期输出,以及各 pin 自有的提示词与工具 schema sidecar。Fixture 角色、录制/回放/刷新语义和场景表字段记录在 `Scenario` 以及[快照 Agent Note](../../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md) 中。 From b50120e090802dc69942e528aeac31d4c403daee Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 23:38:41 +0800 Subject: [PATCH 44/61] docs: attribute the hasPwsh probe to the caller and name the bash dialect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round-four nits: the acp-snapshot README said 'the suite's hasPwsh probe follows the executor's own resolution' — hasPwsh is caller-supplied, and the resolvePwshPath-following behavior belongs to the shipped acp-agent caller; reword to 'the caller-supplied hasPwsh probe (the shipped acp-agent suite follows the executor's own resolution...)' on both language sides. And the tool-bash README loses its only explicit pairing sentence with the dialect guard reverted, so state the contract plainly: 'The tool contract is bash-dialect — mount a bash-parsing executor' (both languages, pairing re-recorded). --- packages/bash/tool-bash/README.i18n.yaml | 4 ++-- packages/bash/tool-bash/README.md | 2 +- packages/bash/tool-bash/README.zh.md | 2 +- packages/support/acp-snapshot/README.i18n.yaml | 4 ++-- packages/support/acp-snapshot/README.md | 2 +- packages/support/acp-snapshot/README.zh.md | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/bash/tool-bash/README.i18n.yaml b/packages/bash/tool-bash/README.i18n.yaml index c22dd9c62c..fb33cffefb 100644 --- a/packages/bash/tool-bash/README.i18n.yaml +++ b/packages/bash/tool-bash/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/bash/tool-bash/README.md -README.md: f21b6b4344fcfb94d88f1f7e1c4444ee89e0ead8 -README.zh.md: c9dd3f2250631f3300edaf2c246e6925f3e12005 +README.md: 35a5647365dab6daa903c14cba8b83702b50305d +README.zh.md: eb7901f3445117988d77e6d39b73681480b7a754 diff --git a/packages/bash/tool-bash/README.md b/packages/bash/tool-bash/README.md index f21b6b4344..35a5647365 100644 --- a/packages/bash/tool-bash/README.md +++ b/packages/bash/tool-bash/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The model-facing `bash` tool registered over the `ctx.bash` executor seam. Foreground execution stays behind that seam; a background process handle is registered with the generic `ctx.tasks` runtime and controlled through `task_output`, `task_list`, and `task_kill` from `@deepseek-ai/dsh-tool-tasks`. -Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`) and the [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) registry; the plugin stays pending until every injected service exists (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`). +Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`) and the [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) registry; the plugin stays pending until every injected service exists (`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`). The tool contract is bash-dialect — mount a bash-parsing executor. The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`); result rendering and background-process adaptation remain implementation details covered by same-package tests. diff --git a/packages/bash/tool-bash/README.zh.md b/packages/bash/tool-bash/README.zh.md index c9dd3f2250..eb7901f344 100644 --- a/packages/bash/tool-bash/README.zh.md +++ b/packages/bash/tool-bash/README.zh.md @@ -4,7 +4,7 @@ 模型侧 `bash` 工具,注册在 `ctx.bash` 执行器 seam 上。前台执行始终位于该 seam 之后;后台进程句柄会注册到通用 `ctx.tasks` 运行时,并通过 `task_output`、`task_list` 和 `task_kill` 控制;这些工具由 `@deepseek-ai/dsh-tool-tasks` 提供。 -需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`)与 [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) 注册表;在每个注入服务就绪之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。 +需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`)与 [`@deepseek-ai/dsh-bash-env`](../bash-env/README.md) 注册表;在每个注入服务就绪之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`)。工具契约是 bash 方言——请挂载能解析 bash 的执行器。 包(package)根只公开 Cordis 插件契约(`name`、`inject`、`Config`、`apply`);结果渲染和后台进程适配仍是实现细节,由同包测试覆盖。 diff --git a/packages/support/acp-snapshot/README.i18n.yaml b/packages/support/acp-snapshot/README.i18n.yaml index 4fa3b34202..362de9fbd1 100644 --- a/packages/support/acp-snapshot/README.i18n.yaml +++ b/packages/support/acp-snapshot/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/support/acp-snapshot/README.md -README.md: 015eda6b25202f219a49f10e286b6c22061171bf -README.zh.md: 2581dd4b8e270adaebea46144045180df4cc0582 +README.md: c8fe6907848a7b661c4bfb60c871f077753fda8b +README.zh.md: 0aa28f4b2c3df1a30e5fd33a80401712f81d6614 diff --git a/packages/support/acp-snapshot/README.md b/packages/support/acp-snapshot/README.md index 015eda6b25..c8fe690784 100644 --- a/packages/support/acp-snapshot/README.md +++ b/packages/support/acp-snapshot/README.md @@ -55,7 +55,7 @@ A scenario booting a differently-composed tree sets its own `configPath` (an ove A pin owns its generated `system-prompt.expected.md` or `tool-schemas.expected.json` by default; `systemPromptSource` and `toolSchemasSource` name another pin when the complete corresponding sequence is identical, so each distinct version is committed once. The pin's `session.jsonl` stores `"system":"{{system}}","tools":"{{tools}}"` while retaining config, reason, and any model-visible prefix. A pin with legitimate mid-run header changes declares `expectedHeaderChanges`; a shared source must declare the same count, and record/refresh rejects claimants that generate different bytes. -Every scenario compares `stdout.expected.jsonl` with cwd-rooted separators canonicalized to `/`. On Windows, `pinsNativeWindowsStdout` additionally compares the complete `stdout.expected.windows.jsonl` after the shared expected output and requires that sidecar exactly when enabled. A scenario requiring a non-Windows host declares `posixOnly`, which skips its run test on Windows while the fixture guards keep covering its committed files everywhere; examples include POSIX process semantics (e.g. cancelling a live bash call kills a detached process group) and generated paths Windows cannot represent. A scenario whose composition needs a usable `pwsh` declares `pwshOnly`; the suite's `hasPwsh` probe follows the executor's own resolution (so Program Files installs count), and the run test is skipped when no usable `pwsh` resolves while the fixture guards keep covering its committed files everywhere. +Every scenario compares `stdout.expected.jsonl` with cwd-rooted separators canonicalized to `/`. On Windows, `pinsNativeWindowsStdout` additionally compares the complete `stdout.expected.windows.jsonl` after the shared expected output and requires that sidecar exactly when enabled. A scenario requiring a non-Windows host declares `posixOnly`, which skips its run test on Windows while the fixture guards keep covering its committed files everywhere; examples include POSIX process semantics (e.g. cancelling a live bash call kills a detached process group) and generated paths Windows cannot represent. A scenario whose composition needs a usable `pwsh` declares `pwshOnly`; the caller-supplied `hasPwsh` probe (the shipped acp-agent suite follows the executor's own resolution, so Program Files installs count) skips the run test when no usable `pwsh` resolves while the fixture guards keep covering its committed files everywhere. The example also ships a `cordis.snapshot.yml` replay overlay next to its `cordis.yml` (the bin swaps them under `DSH_SNAPSHOT=replay` — [single-source replay config Agent Note](../../../.agents/notes/archived/testing/2026-07-04-single-source-acp-replay-config.md)); replay fixtures are served by [`dsh-llm-replay`](../llm-replay/README.md), which this package points at via the `DSH_SNAPSHOT_*` env vars it sets on the child. `pnpm run test:snapshot:record` calls the live LLM and rewrites the recorded scenarios' model fixtures; `pnpm run test:snapshot:refresh` stays keyless, runs the replay overlay, and rewrites stdout, comparable session-log expected outputs, and owned prompt and tool-schema sidecars from the committed model scripts. Fixture roles, record/replay/refresh semantics, and scenario-table fields are documented on `Scenario` and in the [snapshot Agent Note](../../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md). diff --git a/packages/support/acp-snapshot/README.zh.md b/packages/support/acp-snapshot/README.zh.md index 2581dd4b8e..0aa28f4b2c 100644 --- a/packages/support/acp-snapshot/README.zh.md +++ b/packages/support/acp-snapshot/README.zh.md @@ -55,7 +55,7 @@ defineAcpSnapshotSuite({ 每个 pin 默认拥有其生成的 `system-prompt.expected.md` 或 `tool-schemas.expected.json`;当完整的对应序列相同时,`systemPromptSource` 和 `toolSchemasSource` 指定另一个 pin 作为来源,因此每个不同版本只提交一次。该 pin 的 `session.jsonl` 存储 `"system":"{{system}}","tools":"{{tools}}"`,同时保留配置、原因和任何模型可见前缀。具有合法运行中 header 变更的 pin 声明 `expectedHeaderChanges`;共享来源必须声明相同的 header 变更数量,录制/刷新会拒绝生成不同字节的共享引用方。 -每个场景都比较 `stdout.expected.jsonl`,其中以 cwd 为根的分隔符规范化为 `/`。在 Windows 上,`pinsNativeWindowsStdout` 还会在共享预期输出之后比较完整 `stdout.expected.windows.jsonl`,并在启用时精确要求该 sidecar。需要非 Windows 主机的场景声明 `posixOnly`,在 Windows 上跳过运行测试,但 fixture 保护仍在所有平台覆盖其已提交文件;示例包括 POSIX 进程语义(例如取消实时 bash 调用会终止脱离进程组)和 Windows 无法表示的生成路径。组合需要可用 `pwsh` 的场景声明 `pwshOnly`;套件的 `hasPwsh` 探测遵循执行器自身的解析(因此 Program Files 安装也计入),在解析不到可用 `pwsh` 时跳过运行测试,而 fixture 保护仍处处覆盖其已提交文件。 +每个场景都比较 `stdout.expected.jsonl`,其中以 cwd 为根的分隔符规范化为 `/`。在 Windows 上,`pinsNativeWindowsStdout` 还会在共享预期输出之后比较完整 `stdout.expected.windows.jsonl`,并在启用时精确要求该 sidecar。需要非 Windows 主机的场景声明 `posixOnly`,在 Windows 上跳过运行测试,但 fixture 保护仍在所有平台覆盖其已提交文件;示例包括 POSIX 进程语义(例如取消实时 bash 调用会终止脱离进程组)和 Windows 无法表示的生成路径。组合需要可用 `pwsh` 的场景声明 `pwshOnly`;调用方提供的 `hasPwsh` 探测(随附的 acp-agent 套件遵循执行器自身的解析,因此 Program Files 安装也计入)在解析不到可用 `pwsh` 时跳过运行测试,而 fixture 保护仍处处覆盖其已提交文件。 示例还发布 `cordis.snapshot.yml` 回放 overlay,位于 `cordis.yml` 旁边(bin 在 `DSH_SNAPSHOT=replay` 下交换它们,见[单源回放配置 Agent Note](../../../.agents/notes/archived/testing/2026-07-04-single-source-acp-replay-config.md));回放 fixture 由 [`dsh-llm-replay`](../llm-replay/README.md) 提供,该包通过对子级设置的 `DSH_SNAPSHOT_*` env var 指向它。`pnpm run test:snapshot:record` 调用实时 LLM,并重写已记录场景的模型 fixture;`pnpm run test:snapshot:refresh` 保持无密钥,运行回放 overlay,并从已提交模型脚本重写 stdout、可比较会话日志预期输出,以及各 pin 自有的提示词与工具 schema sidecar。Fixture 角色、录制/回放/刷新语义和场景表字段记录在 `Scenario` 以及[快照 Agent Note](../../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md) 中。 From a92ffff10a0f7757327595754c6e3a42655957d2 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 00:08:54 +0800 Subject: [PATCH 45/61] fix(host): prefer pwsh for the Windows directory picker and force DPI awareness The win32 branch now spawns pwsh.exe (PowerShell 7) first and falls back to powershell.exe (Windows PowerShell 5.1) only when pwsh is missing (ENOENT), mirroring the Zenity-KDialog fallback. PowerShell 7 renders the modern IFileDialog folder picker; the 5.1 fallback keeps the legacy tree functional. Both runtimes execute the identical script, which opts the process into system DPI awareness (SetProcessDPIAware) before any window exists, fixing the blurry bitmap-stretched dialog on scaled displays. --- .../src/native-picker.ts | 14 +++++++ .../tests/native-picker.spec.ts | 42 +++++++++++++++++-- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/packages/host/directory-picker-native/src/native-picker.ts b/packages/host/directory-picker-native/src/native-picker.ts index 2c8e236acc..079211f5a3 100644 --- a/packages/host/directory-picker-native/src/native-picker.ts +++ b/packages/host/directory-picker-native/src/native-picker.ts @@ -64,8 +64,15 @@ export async function pickNativeDirectory( } if (platform === 'win32') { + // PowerShell 7 renders the modern IFileDialog folder picker, while Windows + // PowerShell 5.1's FolderBrowserDialog is hardwired to the legacy + // SHBrowseForFolder tree; prefer pwsh and fall back only when it is absent. + // Both hosts spawn DPI-unaware, so the script opts the process into system + // DPI awareness before any window is created. const script = [ "$ErrorActionPreference = 'Stop'", + "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class DpiAware { [DllImport(\"user32.dll\")] public static extern bool SetProcessDPIAware(); }'", + '[DpiAware]::SetProcessDPIAware() | Out-Null', 'Add-Type -AssemblyName System.Windows.Forms', '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog', "$dialog.Description = 'Select Workspace Directory'", @@ -76,6 +83,13 @@ export async function pickNativeDirectory( ' [Console]::WriteLine($dialog.SelectedPath)', '}', ].join('; ') + try { + const result = await run('pwsh.exe', ['-NoProfile', '-STA', '-Command', script], signal) + return outputPath(result.stdout) + } catch (error: unknown) { + rethrowIfAborted(signal, error) + if (!isMissingCommand(error)) throw error + } const result = await run('powershell.exe', ['-NoProfile', '-STA', '-Command', script], signal) return outputPath(result.stdout) } diff --git a/packages/host/directory-picker-native/tests/native-picker.spec.ts b/packages/host/directory-picker-native/tests/native-picker.spec.ts index 87e25ff877..8d26c6ab36 100644 --- a/packages/host/directory-picker-native/tests/native-picker.spec.ts +++ b/packages/host/directory-picker-native/tests/native-picker.spec.ts @@ -46,28 +46,62 @@ describe('native directory picker', () => { await expect(pickNativeDirectory(signal(), { platform: 'darwin', run })).rejects.toBe(reason) }) - it('uses the Windows STA folder dialog and maps empty output to cancellation', async () => { + it('prefers pwsh for the Windows folder dialog and maps empty output to cancellation', async () => { const run = vi.fn(async () => ({ stdout: 'C:\\work\\project\r\n', stderr: '' })) await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).resolves.toBe('C:\\work\\project') expect(run).toHaveBeenCalledWith( - 'powershell.exe', + 'pwsh.exe', expect.arrayContaining(['-NoProfile', '-STA', '-Command']), expect.any(AbortSignal), ) - expect(run.mock.calls[0]?.[1].at(-1)).toContain("$ErrorActionPreference = 'Stop'") + const script = run.mock.calls[0]?.[1].at(-1) + expect(script).toContain("$ErrorActionPreference = 'Stop'") + expect(script).toContain('SetProcessDPIAware') run.mockResolvedValueOnce({ stdout: '', stderr: '' }) await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).resolves.toBeNull() run.mockRejectedValueOnce(failure(1, 'Add-Type failed')) await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).rejects.toThrow('command failed') }) + it('falls back to Windows PowerShell 5.1 only when pwsh is missing', async () => { + const run = vi.fn() + .mockRejectedValueOnce(failure('ENOENT')) + .mockResolvedValueOnce({ stdout: 'C:\\work\\fallback\r\n', stderr: '' }) + await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).resolves.toBe('C:\\work\\fallback') + expect(run.mock.calls.map(call => call[0])).toEqual(['pwsh.exe', 'powershell.exe']) + // Both runtimes execute the identical script, so DPI awareness holds either way. + expect(run.mock.calls[0]?.[1].at(-1)).toBe(run.mock.calls[1]?.[1].at(-1)) + + const cancelled = vi.fn() + .mockRejectedValueOnce(failure('ENOENT')) + .mockResolvedValueOnce({ stdout: '', stderr: '' }) + await expect(pickNativeDirectory(signal(), { platform: 'win32', run: cancelled })).resolves.toBeNull() + + const failed = vi.fn() + .mockRejectedValueOnce(failure('ENOENT')) + .mockRejectedValueOnce(failure(2)) + await expect(pickNativeDirectory(signal(), { platform: 'win32', run: failed })).rejects.toThrow('command failed') + + const brokenPwsh = vi.fn(async () => { throw failure(7) }) + await expect(pickNativeDirectory(signal(), { platform: 'win32', run: brokenPwsh })).rejects.toThrow('command failed') + expect(brokenPwsh).toHaveBeenCalledOnce() + }) + + it('does not fall back when the caller aborted the pwsh spawn', async () => { + const abort = new AbortController() + abort.abort(new Error('closed')) + const run = vi.fn(async () => { throw failure('ENOENT') }) + await expect(pickNativeDirectory(abort.signal, { platform: 'win32', run })).rejects.toThrow('command failed') + expect(run).toHaveBeenCalledOnce() + }) + it('runs the default command adapter without a shell and preserves command failures', async () => { execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { callback(null, 'C:\\work\\default\r\n', '') }) await expect(pickNativeDirectory(signal(), { platform: 'win32' })).resolves.toBe('C:\\work\\default') const [command, args, options] = execFileMock.mock.calls[0]! - expect(command).toBe('powershell.exe') + expect(command).toBe('pwsh.exe') expect(args).toEqual(expect.arrayContaining(['-NoProfile', '-STA', '-Command'])) expect(options.encoding).toBe('utf8') expect(options.windowsHide).toBe(true) From 5c515896653b42cf61fa5c62d76c82d33d27a735 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 00:08:58 +0800 Subject: [PATCH 46/61] docs(picker): record the pwsh-first DPI-aware Windows picker fix README pairs document the pwsh-preferred adapter and the PowerShell 7 requirement for the modern dialog; the 2026-07-27 picker note's Windows adapter fact is updated in place, and a new bug-fix note records the defect, the fallback decision, and the DPI awareness rationale. --- ...26-08-01-windows-picker-pwsh-dpi.i18n.yaml | 6 +++++ .../2026-08-01-windows-picker-pwsh-dpi.md | 26 +++++++++++++++++++ .../2026-08-01-windows-picker-pwsh-dpi.zh.md | 26 +++++++++++++++++++ ...ative-workspace-directory-picker.i18n.yaml | 4 +-- ...07-27-native-workspace-directory-picker.md | 2 +- ...27-native-workspace-directory-picker.zh.md | 2 +- .../directory-picker-native/README.i18n.yaml | 4 +-- .../host/directory-picker-native/README.md | 3 ++- .../host/directory-picker-native/README.zh.md | 3 ++- 9 files changed, 68 insertions(+), 8 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml create mode 100644 .agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md create mode 100644 .agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml new file mode 100644 index 0000000000..f4619714d1 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.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-01-windows-picker-pwsh-dpi.md +2026-08-01-windows-picker-pwsh-dpi.md: 2c90821be3e4800d624cb2f54dcd6661756784bc +2026-08-01-windows-picker-pwsh-dpi.zh.md: ff8a535af396ed5ede51cbd3c69c1944d28ce95e diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md new file mode 100644 index 0000000000..2c90821be3 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md @@ -0,0 +1,26 @@ +# Agent Note: Windows directory picker prefers pwsh and forces DPI awareness + +Status: implemented + +English | [中文](2026-08-01-windows-picker-pwsh-dpi.zh.md) + +## Problem + +The Windows branch of the native directory picker spawned Windows PowerShell 5.1's `FolderBrowserDialog`, which .NET Framework hardwires to the legacy `SHBrowseForFolder` tree dialog: no address bar, search, or quick access. The same process is DPI-unaware (`powershell.exe` declares no DPI awareness), so on scaled displays Windows renders the dialog at 96 DPI and bitmap-stretches it — blurry text and soft edges. Both defects were visible at once on any display above 100 % scaling. + +## Decision + +The win32 branch in `packages/host/directory-picker-native` now spawns `pwsh.exe` (PowerShell 7) first and falls back to `powershell.exe` (Windows PowerShell 5.1) only when pwsh is missing (`ENOENT`), mirroring the Zenity→KDialog fallback. PowerShell 7's WinForms `FolderBrowserDialog` supports `AutoUpgradeEnabled` (added in .NET Core 3.0, absent from .NET Framework) and renders the modern Explorer-style folder picker. Both runtimes execute the identical script, which calls `SetProcessDPIAware()` (user32) before any window exists, so the dialog is system-DPI-aware no matter which host serves it. `-STA` stays explicit for both, and the fallback keeps the seam's cancellation/failure contract (`null` on cancel, a retryable error otherwise). The host-boundary, RPC trust, and cancellation decisions stay with the [picker feature note](../feature/2026-07-27-native-workspace-directory-picker.md). + +## Alternatives considered + +- **Require PowerShell 7.** Rejected: pwsh is not a Windows built-in, so machines without it would lose the only workspace-creation route; the 5.1 fallback keeps the dialog functional, and DPI is corrected there too. +- **Import `resolvePwshPath` from `dsh-pwsh-local`.** Rejected for this change: a host GUI package importing from a bash-executor package is a cross-seam coupling, and PATH-based `execFile` resolution plus `ENOENT` fallback already covers the practical installs (Program Files, Store aliases); single-source resolution remains a follow-up if the two consumers drift. +- **Set DPI awareness in the harness process.** Rejected: DPI awareness is per-process, and the dialog lives in a spawned child that inherits nothing from the parent's absent declaration. +- **Per-monitor v2 (`SetProcessDpiAwarenessContext`).** Deferred: system-aware is the ceiling .NET Framework WinForms supports, the shell dialog handles per-monitor rendering itself on modern Windows, and one call keeps both runtimes on a single code path. + +## Consequences + +- Machines with PowerShell 7 get the modern folder picker; 5.1-only machines keep the legacy tree — now sharp — and the package README's Known Limitations documents the gap. +- No new packages or runtime dependencies; the fallback reuses the existing `ENOENT` classification and abort propagation. +- The command boundary (`DirectoryPickerRunner`) pins the spawn order and script content in unit tests; real dialog rendering remains a manual Windows check, as before. diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md new file mode 100644 index 0000000000..ff8a535af3 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md @@ -0,0 +1,26 @@ +# Agent Note: Windows 目录选择器优先 pwsh 并强制 DPI awareness + +Status: implemented + +[English](2026-08-01-windows-picker-pwsh-dpi.md) | 中文 + +## 问题 + +原生目录选择器的 Windows 分支原先启动 Windows PowerShell 5.1 的 `FolderBrowserDialog`,而 .NET Framework 将其硬编码为旧版 `SHBrowseForFolder` 树形对话框:没有地址栏、搜索或快速访问。同一进程又是 DPI-unaware 的(`powershell.exe` 未声明任何 DPI awareness),因此在缩放显示器上,Windows 会以 96 DPI 渲染该对话框再位图拉伸——文字模糊、边缘发虚。任何超过 100% 缩放的显示器上,两个缺陷同时可见。 + +## 决策 + +`packages/host/directory-picker-native` 的 win32 分支现在先启动 `pwsh.exe`(PowerShell 7),仅当 pwsh 缺失(`ENOENT`)时才回退到 `powershell.exe`(Windows PowerShell 5.1),与 Zenity→KDialog 的回退方式一致。PowerShell 7 的 WinForms `FolderBrowserDialog` 支持 `AutoUpgradeEnabled`(.NET Core 3.0 加入;.NET Framework 没有),呈现现代资源管理器风格文件夹选择器。两个运行时执行完全相同的脚本,脚本在任何窗口存在前调用 `SetProcessDPIAware()`(user32),因此无论由哪个宿主服务,对话框都系统 DPI aware。两个运行时都显式保留 `-STA`;回退维持 seam 的取消/失败契约(取消返回 `null`,其余为可重试错误)。宿主边界、RPC 信任与取消决策仍归[选择器功能 Note](../feature/2026-07-27-native-workspace-directory-picker.md)所有。 + +## 考虑过的替代方案 + +- **强制要求 PowerShell 7。** 否决:pwsh 并非 Windows 内置,没有它的机器将失去唯一的工作区创建路径;5.1 回退保持对话框可用,且 DPI 在那里同样被修正。 +- **从 `dsh-pwsh-local` 导入 `resolvePwshPath`。** 本变更否决:host GUI 包依赖 bash 执行器包是跨 seam 耦合;PATH 上的 `execFile` 解析加 `ENOENT` 回退已覆盖实际安装形态(Program Files、Store 别名);若两个消费者日后漂移,单一来源解析留作后续。 +- **在 harness 进程内设置 DPI awareness。** 否决:DPI awareness 是进程级的,而对话框位于派生的子进程中,不会继承父进程缺失的声明。 +- **Per-monitor v2(`SetProcessDpiAwarenessContext`)。** 暂缓:system-aware 是 .NET Framework WinForms 的上限,现代 Windows 中 shell 对话框自身处理 per-monitor 渲染,且一次调用让两个运行时共用一条代码路径。 + +## 后果 + +- 装有 PowerShell 7 的机器获得现代文件夹选择器;只有 5.1 的机器保留旧版树——但现在清晰了——包 README 的已知限制记录了该差距。 +- 无新增包或运行时依赖;回退复用既有的 `ENOENT` 分类与中止传播。 +- 命令边界(`DirectoryPickerRunner`)在单元测试中固定启动顺序与脚本内容;真实对话框渲染仍与以前一样属于手动 Windows 检查。 diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml index 1faf10a4c8..12cb856fe2 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.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-27-native-workspace-directory-picker.md -2026-07-27-native-workspace-directory-picker.md: 98f9dc9bed5358e816d4324462d5ea7657f9007f -2026-07-27-native-workspace-directory-picker.zh.md: ca765778fae734fd47a05652aea7021328ed4ab6 +2026-07-27-native-workspace-directory-picker.md: c18b4263d4e97290d69ac229e7423558bdb4c3b1 +2026-07-27-native-workspace-directory-picker.zh.md: 7267516d7eea4b3cfecc2ca8f18305896eaffede diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md index 98f9dc9bed..c18b4263d4 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md @@ -30,7 +30,7 @@ The native dialog RPC is accepted only from a loopback socket with same-origin b Platform adapters invoke native tools without a shell: - macOS: `osascript` and the system folder chooser. -- Windows: PowerShell in STA mode and `FolderBrowserDialog`. +- Windows: `pwsh` (PowerShell 7) in STA mode with a Windows PowerShell 5.1 fallback, always DPI-aware ([picker fix](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)). - Linux: `zenity`, with `kdialog` as a fallback when Zenity is unavailable. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md index ca765778fa..7267516d7e 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md @@ -30,7 +30,7 @@ Status: implemented 平台适配器不经 shell,直接调用原生工具: - macOS:`osascript` 和系统文件夹选择器。 -- Windows:采用 STA 模式的 PowerShell 和 `FolderBrowserDialog`。 +- Windows:采用 STA 模式的 `pwsh`(PowerShell 7),并以 Windows PowerShell 5.1 回退,且始终 DPI aware(见[选择器修复](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))。 - Linux:使用 `zenity`;Zenity 不可用时回退到 `kdialog`。 ## 考虑过的替代方案 diff --git a/packages/host/directory-picker-native/README.i18n.yaml b/packages/host/directory-picker-native/README.i18n.yaml index e798bd6471..9abdfb129a 100644 --- a/packages/host/directory-picker-native/README.i18n.yaml +++ b/packages/host/directory-picker-native/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/host/directory-picker-native/README.md -README.md: 0b54c651d4f5382021d0f8832ab4f1146b7652c8 -README.zh.md: e5ac2762a691a16a7e6d9d6dd9aefc70a59dcd4f +README.md: ab4326fed886e9bb2fa550ae9865550eed7c2583 +README.zh.md: cb2e067d340df1696e1b1195ec99f6d63509cc20 diff --git a/packages/host/directory-picker-native/README.md b/packages/host/directory-picker-native/README.md index 0b54c651d4..ab4326fed8 100644 --- a/packages/host/directory-picker-native/README.md +++ b/packages/host/directory-picker-native/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS, an STA PowerShell `FolderBrowserDialog` on Windows, and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md). +The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS, `pwsh` (PowerShell 7) with a Windows PowerShell 5.1 fallback on Windows — the dialog script opts the process into system DPI awareness — and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md). **Dual-face package**: the browser half (`./client`) registers a renderless flow occupant into [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes — each `open` request drives `host.pickDirectory` and reports the one outcome (picked path / cancel / failure) through the hole's owner conversation. One cordis.yml row therefore composes both sides of the native interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). @@ -17,3 +17,4 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **Linux requires desktop tooling** — with neither Zenity nor KDialog installed, `pick` rejects with an actionable error; it does not fall back to a typed-path prompt (the browse backend is that fallback at the composition level). +- **Windows needs PowerShell 7 for the modern picker** — `pwsh` renders the Explorer-style folder dialog; a machine with only Windows PowerShell 5.1 falls back to the legacy folder tree, DPI-corrected but not the modern UI. diff --git a/packages/host/directory-picker-native/README.zh.md b/packages/host/directory-picker-native/README.zh.md index e5ac2762a6..cb2e067d34 100644 --- a/packages/host/directory-picker-native/README.zh.md +++ b/packages/host/directory-picker-native/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Windows 使用以 STA 模式运行的 PowerShell `FolderBrowserDialog`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。 +[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Windows 使用 `pwsh`(PowerShell 7)并以 Windows PowerShell 5.1 回退——对话框脚本会把进程设为系统 DPI aware——Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。 **双面包**:browser half(`./client`)向 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞注册一个无渲染的流程占用者——每次 `open` 请求驱动 `host.pickDirectory`,并经洞的 owner 会话上报唯一结果(所选路径/取消/失败)。因此一行 cordis.yml 同时组合原生交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 @@ -17,3 +17,4 @@ ## 已知限制与延期工作 - **Linux 依赖桌面工具**——Zenity 与 KDialog 均未安装时,`pick` 以包含解决建议的错误拒绝;它不会回退为手输路径提示(组合层面的回退是 browse 后端)。 +- **Windows 需要 PowerShell 7 才能使用现代选择器**——`pwsh` 呈现资源管理器风格的文件夹对话框;只有 Windows PowerShell 5.1 的机器会回退到旧版文件夹树,DPI 已修正,但界面不是现代的。 From da1b1ff87db705d5cfc1afbdc25c1b919437652f Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Sun, 2 Aug 2026 00:23:30 +0800 Subject: [PATCH 47/61] fix(host): drop the folder-dialog Description both picker modes render badly .NET 10's modern FolderBrowserDialog renders Description as a bottom strip above the folder input, and the 5.1 classic dialog as an unthemed white box; the property is dropped entirely and a regression assertion pins its absence. --- .../bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml | 4 ++-- .../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md | 2 +- .../bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md | 2 +- packages/host/directory-picker-native/src/native-picker.ts | 5 +++-- .../host/directory-picker-native/tests/native-picker.spec.ts | 2 ++ 5 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml index f4619714d1..76100a958d 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.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-01-windows-picker-pwsh-dpi.md -2026-08-01-windows-picker-pwsh-dpi.md: 2c90821be3e4800d624cb2f54dcd6661756784bc -2026-08-01-windows-picker-pwsh-dpi.zh.md: ff8a535af396ed5ede51cbd3c69c1944d28ce95e +2026-08-01-windows-picker-pwsh-dpi.md: 0ca413f575b5e2805f29b899e638844916e72573 +2026-08-01-windows-picker-pwsh-dpi.zh.md: 6842acfc1e1bd9f3342a2bedb878fe2df40449df diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md index 2c90821be3..0ca413f575 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md @@ -10,7 +10,7 @@ The Windows branch of the native directory picker spawned Windows PowerShell 5.1 ## Decision -The win32 branch in `packages/host/directory-picker-native` now spawns `pwsh.exe` (PowerShell 7) first and falls back to `powershell.exe` (Windows PowerShell 5.1) only when pwsh is missing (`ENOENT`), mirroring the Zenity→KDialog fallback. PowerShell 7's WinForms `FolderBrowserDialog` supports `AutoUpgradeEnabled` (added in .NET Core 3.0, absent from .NET Framework) and renders the modern Explorer-style folder picker. Both runtimes execute the identical script, which calls `SetProcessDPIAware()` (user32) before any window exists, so the dialog is system-DPI-aware no matter which host serves it. `-STA` stays explicit for both, and the fallback keeps the seam's cancellation/failure contract (`null` on cancel, a retryable error otherwise). The host-boundary, RPC trust, and cancellation decisions stay with the [picker feature note](../feature/2026-07-27-native-workspace-directory-picker.md). +The win32 branch in `packages/host/directory-picker-native` now spawns `pwsh.exe` (PowerShell 7) first and falls back to `powershell.exe` (Windows PowerShell 5.1) only when pwsh is missing (`ENOENT`), mirroring the Zenity→KDialog fallback. PowerShell 7's WinForms `FolderBrowserDialog` supports `AutoUpgradeEnabled` (added in .NET Core 3.0, absent from .NET Framework) and renders the modern Explorer-style folder picker. Both runtimes execute the identical script, which calls `SetProcessDPIAware()` (user32) before any window exists, so the dialog is system-DPI-aware no matter which host serves it. The script sets no `Description`: .NET 10's modern `FolderBrowserDialog` renders it as a bottom strip above the folder input, and the 5.1 classic dialog as an unthemed box, so the property is dropped entirely. `-STA` stays explicit for both, and the fallback keeps the seam's cancellation/failure contract (`null` on cancel, a retryable error otherwise). The host-boundary, RPC trust, and cancellation decisions stay with the [picker feature note](../feature/2026-07-27-native-workspace-directory-picker.md). ## Alternatives considered diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md index ff8a535af3..6842acfc1e 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`packages/host/directory-picker-native` 的 win32 分支现在先启动 `pwsh.exe`(PowerShell 7),仅当 pwsh 缺失(`ENOENT`)时才回退到 `powershell.exe`(Windows PowerShell 5.1),与 Zenity→KDialog 的回退方式一致。PowerShell 7 的 WinForms `FolderBrowserDialog` 支持 `AutoUpgradeEnabled`(.NET Core 3.0 加入;.NET Framework 没有),呈现现代资源管理器风格文件夹选择器。两个运行时执行完全相同的脚本,脚本在任何窗口存在前调用 `SetProcessDPIAware()`(user32),因此无论由哪个宿主服务,对话框都系统 DPI aware。两个运行时都显式保留 `-STA`;回退维持 seam 的取消/失败契约(取消返回 `null`,其余为可重试错误)。宿主边界、RPC 信任与取消决策仍归[选择器功能 Note](../feature/2026-07-27-native-workspace-directory-picker.md)所有。 +`packages/host/directory-picker-native` 的 win32 分支现在先启动 `pwsh.exe`(PowerShell 7),仅当 pwsh 缺失(`ENOENT`)时才回退到 `powershell.exe`(Windows PowerShell 5.1),与 Zenity→KDialog 的回退方式一致。PowerShell 7 的 WinForms `FolderBrowserDialog` 支持 `AutoUpgradeEnabled`(.NET Core 3.0 加入;.NET Framework 没有),呈现现代资源管理器风格文件夹选择器。两个运行时执行完全相同的脚本,脚本在任何窗口存在前调用 `SetProcessDPIAware()`(user32),因此无论由哪个宿主服务,对话框都系统 DPI aware。脚本不设置 `Description`:.NET 10 的现代 `FolderBrowserDialog` 会把它渲染成文件夹输入框上方的一条底带,5.1 经典对话框则渲染成未主题化的色块,因此该属性被整体移除。两个运行时都显式保留 `-STA`;回退维持 seam 的取消/失败契约(取消返回 `null`,其余为可重试错误)。宿主边界、RPC 信任与取消决策仍归[选择器功能 Note](../feature/2026-07-27-native-workspace-directory-picker.md)所有。 ## 考虑过的替代方案 diff --git a/packages/host/directory-picker-native/src/native-picker.ts b/packages/host/directory-picker-native/src/native-picker.ts index 079211f5a3..0cc12fb38e 100644 --- a/packages/host/directory-picker-native/src/native-picker.ts +++ b/packages/host/directory-picker-native/src/native-picker.ts @@ -68,14 +68,15 @@ export async function pickNativeDirectory( // PowerShell 5.1's FolderBrowserDialog is hardwired to the legacy // SHBrowseForFolder tree; prefer pwsh and fall back only when it is absent. // Both hosts spawn DPI-unaware, so the script opts the process into system - // DPI awareness before any window is created. + // DPI awareness before any window is created. No Description is set: the + // modern dialog renders it as a bottom strip and the classic dialog as an + // unthemed box. const script = [ "$ErrorActionPreference = 'Stop'", "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class DpiAware { [DllImport(\"user32.dll\")] public static extern bool SetProcessDPIAware(); }'", '[DpiAware]::SetProcessDPIAware() | Out-Null', 'Add-Type -AssemblyName System.Windows.Forms', '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog', - "$dialog.Description = 'Select Workspace Directory'", '$dialog.ShowNewFolderButton = $true', '$result = $dialog.ShowDialog()', 'if ($result -eq [System.Windows.Forms.DialogResult]::OK) {', diff --git a/packages/host/directory-picker-native/tests/native-picker.spec.ts b/packages/host/directory-picker-native/tests/native-picker.spec.ts index 8d26c6ab36..707a5cafe4 100644 --- a/packages/host/directory-picker-native/tests/native-picker.spec.ts +++ b/packages/host/directory-picker-native/tests/native-picker.spec.ts @@ -57,6 +57,8 @@ describe('native directory picker', () => { const script = run.mock.calls[0]?.[1].at(-1) expect(script).toContain("$ErrorActionPreference = 'Stop'") expect(script).toContain('SetProcessDPIAware') + // Description renders as a bottom strip (modern) / unthemed box (classic); never set it. + expect(script).not.toContain('Description') run.mockResolvedValueOnce({ stdout: '', stderr: '' }) await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).resolves.toBeNull() run.mockRejectedValueOnce(failure(1, 'Add-Type failed')) From 089f4dfad8f8bc9be6c2f4656732665d9cc7dd27 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 00:06:47 +0800 Subject: [PATCH 48/61] feat(picker): open the Win32 folder dialog in-process over koffi The modern IFileOpenDialog becomes the primary win32 tier: a koffi-driven COM conversation on a worker_threads worker (the modal Show never blocks the host event loop), per-monitor-v2 DPI via SetThreadDpiAwarenessContext, and abort service by re-posting WM_CLOSE to the dialog thread's windows, with terminate+unref as the last resort (Node cannot interrupt a thread blocked in native code, and such a worker must never hold the process open). The PowerShell chain stays as the fallback tier with its trigger widened from ENOENT to any pwsh failure, closing the review-flagged PowerShell 6 regression (no WinForms: exit 1, not ENOENT, so 5.1 never ran). Layering keeps per-file coverage honest on every host: pure sequencing and the driver test against fakes anywhere; the bindings run against a mocked koffi COM world (the session-persistence-jsonl technique); POSIX hosts drive the real spawn plumbing to its koffi-load rejection; win32 hosts run a real open-and-abort-close smoke. The smoke joins processBoundTests: a worker blocked in a native modal wedges the threads pool's teardown, while a fork contains it. The worker bundles as its own CJS tsdown entry (workflow-workerthread's pattern; no TLA), and the host module is imported statically so the node-half bundle stays chunk-free. Built-plane and real-COM behavior verified on native Windows: standalone probes for the source worker, the built CJS worker, and the driver's abort path all open and close the real dialog. Agent Notes: new implemented/feature/2026-08-02-win32-in-process-folder-dialog (bilingual) owns the decision; the DPI note is re-scoped to the fallback tier it now describes and its AutoUpgradeEnabled attribution corrected (.NET Core 3.0 rewrote FolderBrowserDialog; the opt-out arrived in .NET 6). --- ...26-08-01-windows-picker-pwsh-dpi.i18n.yaml | 4 +- .../2026-08-01-windows-picker-pwsh-dpi.md | 2 +- .../2026-08-01-windows-picker-pwsh-dpi.zh.md | 2 +- ...2-win32-in-process-folder-dialog.i18n.yaml | 6 + ...26-08-02-win32-in-process-folder-dialog.md | 26 ++ ...08-02-win32-in-process-folder-dialog.zh.md | 26 ++ .../directory-picker-native/README.i18n.yaml | 4 +- .../host/directory-picker-native/README.md | 5 +- .../host/directory-picker-native/README.zh.md | 5 +- .../host/directory-picker-native/package.json | 7 +- .../src/native-picker.ts | 31 +- .../src/win32-dialog-bindings.ts | 157 ++++++++++ .../src/win32-dialog-host.ts | 36 +++ .../src/win32-dialog-logic.ts | 117 ++++++++ .../src/win32-dialog-worker.ts | 37 +++ .../src/win32-dialog.ts | 128 ++++++++ .../tests/native-picker.spec.ts | 85 ++++-- .../tests/win32-dialog-bindings.spec.ts | 284 ++++++++++++++++++ .../tests/win32-dialog-logic.spec.ts | 90 ++++++ .../tests/win32-dialog.spec.ts | 136 +++++++++ .../directory-picker-native/tsdown.config.ts | 17 +- pnpm-lock.yaml | 6 + vitest.config.ts | 4 + 23 files changed, 1174 insertions(+), 41 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md create mode 100644 .agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md create mode 100644 packages/host/directory-picker-native/src/win32-dialog-bindings.ts create mode 100644 packages/host/directory-picker-native/src/win32-dialog-host.ts create mode 100644 packages/host/directory-picker-native/src/win32-dialog-logic.ts create mode 100644 packages/host/directory-picker-native/src/win32-dialog-worker.ts create mode 100644 packages/host/directory-picker-native/src/win32-dialog.ts create mode 100644 packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts create mode 100644 packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts create mode 100644 packages/host/directory-picker-native/tests/win32-dialog.spec.ts diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml index 76100a958d..d9f46441ac 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.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-01-windows-picker-pwsh-dpi.md -2026-08-01-windows-picker-pwsh-dpi.md: 0ca413f575b5e2805f29b899e638844916e72573 -2026-08-01-windows-picker-pwsh-dpi.zh.md: 6842acfc1e1bd9f3342a2bedb878fe2df40449df +2026-08-01-windows-picker-pwsh-dpi.md: 1d9fd0a1b445a77b478f033d56169d6166c2b1bf +2026-08-01-windows-picker-pwsh-dpi.zh.md: 245991e7c8d081f3c91724c0dae1142d80883c1d diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md index 0ca413f575..1d9fd0a1b4 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md @@ -10,7 +10,7 @@ The Windows branch of the native directory picker spawned Windows PowerShell 5.1 ## Decision -The win32 branch in `packages/host/directory-picker-native` now spawns `pwsh.exe` (PowerShell 7) first and falls back to `powershell.exe` (Windows PowerShell 5.1) only when pwsh is missing (`ENOENT`), mirroring the Zenity→KDialog fallback. PowerShell 7's WinForms `FolderBrowserDialog` supports `AutoUpgradeEnabled` (added in .NET Core 3.0, absent from .NET Framework) and renders the modern Explorer-style folder picker. Both runtimes execute the identical script, which calls `SetProcessDPIAware()` (user32) before any window exists, so the dialog is system-DPI-aware no matter which host serves it. The script sets no `Description`: .NET 10's modern `FolderBrowserDialog` renders it as a bottom strip above the folder input, and the 5.1 classic dialog as an unthemed box, so the property is dropped entirely. `-STA` stays explicit for both, and the fallback keeps the seam's cancellation/failure contract (`null` on cancel, a retryable error otherwise). The host-boundary, RPC trust, and cancellation decisions stay with the [picker feature note](../feature/2026-07-27-native-workspace-directory-picker.md). +The PowerShell chain is now the FALLBACK tier below the in-process koffi dialog (see the [in-process folder dialog note](../feature/2026-08-02-win32-in-process-folder-dialog.md)): the win32 branch spawns `pwsh.exe` (PowerShell 7) first and falls back to `powershell.exe` (Windows PowerShell 5.1) on ANY pwsh failure — a resolvable PowerShell 6 has no WinForms and exits 1, not `ENOENT`, and 5.1 ships with every Windows. PowerShell 7 renders the modern Explorer-style folder picker because .NET Core 3.0 rewrote `FolderBrowserDialog` over `IFileDialog` (unconditionally; the later `AutoUpgradeEnabled` opt-out arrived in .NET 6 and the script never sets it). Both runtimes execute the identical script, which calls `SetProcessDPIAware()` (user32) before any window exists, so the dialog is system-DPI-aware no matter which host serves it. The script sets no `Description`: .NET 10's modern `FolderBrowserDialog` renders it as a bottom strip above the folder input, and the 5.1 classic dialog as an unthemed box, so the property is dropped entirely. `-STA` stays explicit for both, and the fallback keeps the seam's cancellation/failure contract (`null` on cancel, a retryable error otherwise). The host-boundary, RPC trust, and cancellation decisions stay with the [picker feature note](../feature/2026-07-27-native-workspace-directory-picker.md). ## Alternatives considered diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md index 6842acfc1e..245991e7c8 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -`packages/host/directory-picker-native` 的 win32 分支现在先启动 `pwsh.exe`(PowerShell 7),仅当 pwsh 缺失(`ENOENT`)时才回退到 `powershell.exe`(Windows PowerShell 5.1),与 Zenity→KDialog 的回退方式一致。PowerShell 7 的 WinForms `FolderBrowserDialog` 支持 `AutoUpgradeEnabled`(.NET Core 3.0 加入;.NET Framework 没有),呈现现代资源管理器风格文件夹选择器。两个运行时执行完全相同的脚本,脚本在任何窗口存在前调用 `SetProcessDPIAware()`(user32),因此无论由哪个宿主服务,对话框都系统 DPI aware。脚本不设置 `Description`:.NET 10 的现代 `FolderBrowserDialog` 会把它渲染成文件夹输入框上方的一条底带,5.1 经典对话框则渲染成未主题化的色块,因此该属性被整体移除。两个运行时都显式保留 `-STA`;回退维持 seam 的取消/失败契约(取消返回 `null`,其余为可重试错误)。宿主边界、RPC 信任与取消决策仍归[选择器功能 Note](../feature/2026-07-27-native-workspace-directory-picker.md)所有。 +PowerShell 链现在是进程内 koffi 对话框之下的回退层(见[进程内文件夹对话框 Note](../feature/2026-08-02-win32-in-process-folder-dialog.md)):win32 分支先启动 `pwsh.exe`(PowerShell 7),并在 pwsh 的任何失败上回退到 `powershell.exe`(Windows PowerShell 5.1)——可解析的 PowerShell 6 没有 WinForms,以退出码 1 而非 `ENOENT` 失败,而 5.1 每台 Windows 都自带。PowerShell 7 呈现现代资源管理器风格选择器,是因为 .NET Core 3.0 用 `IFileDialog` 重写了 `FolderBrowserDialog`(无条件生效;更晚的 `AutoUpgradeEnabled` 退出开关到 .NET 6 才加入,脚本从未设置它)。两个运行时执行完全相同的脚本,脚本在任何窗口存在前调用 `SetProcessDPIAware()`(user32),因此无论由哪个宿主服务,对话框都系统 DPI aware。脚本不设置 `Description`:.NET 10 的现代 `FolderBrowserDialog` 会把它渲染成文件夹输入框上方的一条底带,5.1 经典对话框则渲染成未主题化的色块,因此该属性被整体移除。两个运行时都显式保留 `-STA`;回退维持 seam 的取消/失败契约(取消返回 `null`,其余为可重试错误)。宿主边界、RPC 信任与取消决策仍归[选择器功能 Note](../feature/2026-07-27-native-workspace-directory-picker.md)所有。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml new file mode 100644 index 0000000000..a3bdfc2a97 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.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/feature/2026-08-02-win32-in-process-folder-dialog.md +2026-08-02-win32-in-process-folder-dialog.md: fa896d198913f58b22f9186696daec27026bb50f +2026-08-02-win32-in-process-folder-dialog.zh.md: 31077d8d6a3907d955180fda290f92c4cf41e5b9 diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md new file mode 100644 index 0000000000..fa896d1989 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md @@ -0,0 +1,26 @@ +# Agent Note: Win32 folder picker moves in-process over koffi + +Status: implemented + +English | [中文](2026-08-02-win32-in-process-folder-dialog.zh.md) + +## Problem + +The Windows directory picker's primary tier was a spawned PowerShell script around WinForms `FolderBrowserDialog`: the modern dialog only where PowerShell 7 happens to be installed, a review-flagged regression where PowerShell 6 resolves but has no WinForms (exit 1 is not `ENOENT`, so the 5.1 fallback never ran), a `SetProcessDPIAware` ceiling of system DPI, and a picker whose behavior depended on which shells a machine ships rather than on Windows itself. + +## Decision + +`packages/host/directory-picker-native` now opens `IFileOpenDialog` (`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`) in-process through koffi — already a workspace dependency for the repo's other `win32.ts` surfaces — as the primary win32 tier. The COM conversation runs on a `worker_threads` worker so the modal `Show` never blocks the host event loop; the worker posts its native thread id before blocking, and the driver services aborts by re-posting `WM_CLOSE` to that thread's windows (`EnumThreadWindows`), terminating and unrefing the worker only when the close budget is exhausted (Node cannot interrupt native calls, so an unclosable worker must never hold the process open). The worker thread opts into per-monitor-v2 DPI (`SetThreadDpiAwarenessContext`), a strict upgrade over the script's system-DPI ceiling. The module split keeps coverage honest on every host: `win32-dialog-logic.ts` (pure sequencing) and `win32-dialog.ts` (driver) test against fakes anywhere; `win32-dialog-bindings.ts` tests against a mocked `koffi` COM world (the `dsh-session-persistence-jsonl` technique); POSIX hosts run the real spawn plumbing to its koffi-load rejection; win32 hosts run a real open-and-abort-close smoke. That smoke lives in `processBoundTests`: under the threads pool a worker blocked in a native modal wedges pool teardown, while a fork contains it. The PowerShell chain (see the [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)) stays as the fallback tier, its trigger widened from `ENOENT` to any pwsh failure, which also closes the PowerShell 6 regression. + +## Alternatives considered + +- **A prebuilt native helper (`native/` family like `node-addon-landlock-run`).** Rejected: a mirror repository, an npm package family, MSVC provisioning, and a release handoff — all to ship ~150 lines of C the repository cannot exercise on CI (no real-Windows lane); koffi delivers the same COM surface with zero new supply chain. +- **An N-API in-process addon.** Rejected for the same CI/toolchain reasons plus owned C++ for STA threading and message pumping that `worker_threads` + koffi express in TypeScript. +- **Keep PowerShell primary and probe versions.** Rejected: the picker stays hostage to shell packaging (6 vs 7, Store aliases, profiles), and 5.1's legacy dialog remains the floor wherever pwsh is absent; the fallback-trigger widening alone was accepted into the fallback tier instead. +- **Blocking the main thread for the modal call.** Rejected outright: the web host must keep serving RPC while the dialog is open. + +## Consequences + +- Every Windows machine gets the modern dialog with per-monitor-v2 DPI, PowerShell installed or not; the PowerShell tiers only serve hosts where koffi cannot drive COM. +- Real dialog rendering and the selection path stay a manual Windows check (the auto-close smoke proves open/abort/unwind); a wedged abort can leak one dialog thread until process exit, documented in the package README. +- The COM vtable slots and GUIDs used are frozen Windows ABI (Vista); a koffi signature mistake is an in-process crash risk contained to the worker thread and caught by the win32 smoke before shipping. diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md new file mode 100644 index 0000000000..31077d8d6a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md @@ -0,0 +1,26 @@ +# Agent Note:Win32 文件夹选择器经 koffi 移入进程内 + +Status: implemented + +[English](2026-08-02-win32-in-process-folder-dialog.md) | 中文 + +## 问题 + +Windows 目录选择器的主层此前是围绕 WinForms `FolderBrowserDialog` 的外部 PowerShell 脚本:只有恰好安装了 PowerShell 7 的机器才有现代对话框;review 指出的回归——PowerShell 6 可解析却没有 WinForms(退出码 1 而非 `ENOENT`,5.1 回退永远不会触发);`SetProcessDPIAware` 只有系统 DPI 的上限;选择器的行为取决于机器装了哪些 shell,而不是取决于 Windows 本身。 + +## 决策 + +`packages/host/directory-picker-native` 现在经 koffi——它已是仓库其他 `win32.ts` 面的工作区依赖——在进程内打开 `IFileOpenDialog`(`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`),作为 win32 主层。COM 会话运行在 `worker_threads` worker 上,模态 `Show` 永不阻塞宿主事件循环;worker 在阻塞前上报其原生线程 id,driver 通过向该线程的窗口反复投递 `WM_CLOSE`(`EnumThreadWindows`)来服务中止,仅当关闭预算耗尽时才 terminate 并 unref worker(Node 无法打断原生调用,关不掉的 worker 决不能拖住进程退出)。worker 线程启用 per-monitor-v2 DPI(`SetThreadDpiAwarenessContext`),严格优于脚本的系统 DPI 上限。模块切分让覆盖率在任何主机上都诚实:`win32-dialog-logic.ts`(纯时序)与 `win32-dialog.ts`(driver)在任何平台对假件测试;`win32-dialog-bindings.ts` 对 mock 的 `koffi` COM 世界测试(`dsh-session-persistence-jsonl` 的技法);POSIX 主机把真实 spawn 管道跑到 koffi 加载失败的拒绝;win32 主机跑真实的"打开并中止关闭"冒烟。该冒烟位于 `processBoundTests`:threads 池下阻塞在原生模态中的 worker 会卡死池的收尾,fork 则能容纳它。PowerShell 链(见 [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))保留为回退层,触发条件从 `ENOENT` 拓宽为 pwsh 的任何失败,同时关闭了 PowerShell 6 回归。 + +## 考虑过的替代方案 + +- **预编译原生助手(`native/` 家族,如 `node-addon-landlock-run`)。** 否决:镜像仓库、npm 包家族、MSVC 供给和发布交接——只为交付约 150 行 CI 无法执行的 C(没有真 Windows 通道);koffi 以零新增供应链提供同一 COM 面。 +- **N-API 进程内插件。** 否决:同样的 CI/工具链原因,另加需要自有 C++ 处理 STA 线程与消息泵,而 `worker_threads` + koffi 用 TypeScript 就能表达。 +- **保留 PowerShell 为主层并探测版本。** 否决:选择器仍被 shell 打包形态挟持(6 与 7、Store 别名、profile),且没有 pwsh 的机器地板仍是 5.1 的旧版对话框;仅把回退触发条件的拓宽吸收进回退层。 +- **在主线程上阻塞模态调用。** 直接否决:对话框打开期间 web 宿主必须继续服务 RPC。 + +## 后果 + +- 每台 Windows 机器都得到带 per-monitor-v2 DPI 的现代对话框,无论是否安装 PowerShell;PowerShell 层只服务 koffi 无法驱动 COM 的主机。 +- 真实对话框渲染与选中路径仍是手动 Windows 检查(自动关闭冒烟证明打开/中止/收尾);卡死的中止可能泄漏一个对话框线程直到进程退出,已记录于包 README。 +- 所用 COM vtable 槽位与 GUID 是冻结的 Windows ABI(Vista 起);koffi 签名错误是被限制在 worker 线程内的进程内崩溃风险,并在交付前被 win32 冒烟捕获。 diff --git a/packages/host/directory-picker-native/README.i18n.yaml b/packages/host/directory-picker-native/README.i18n.yaml index 9abdfb129a..acf7f85d88 100644 --- a/packages/host/directory-picker-native/README.i18n.yaml +++ b/packages/host/directory-picker-native/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/host/directory-picker-native/README.md -README.md: ab4326fed886e9bb2fa550ae9865550eed7c2583 -README.zh.md: cb2e067d340df1696e1b1195ec99f6d63509cc20 +README.md: 0d0fe8d3a049d6fbc47eee314f9782352651247d +README.zh.md: 82f51976afe2e57699c1bd62d11142106b082e9b diff --git a/packages/host/directory-picker-native/README.md b/packages/host/directory-picker-native/README.md index ab4326fed8..0d0fe8d3a0 100644 --- a/packages/host/directory-picker-native/README.md +++ b/packages/host/directory-picker-native/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS, `pwsh` (PowerShell 7) with a Windows PowerShell 5.1 fallback on Windows — the dialog script opts the process into system DPI awareness — and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md). +The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Windows opens the modern `IFileOpenDialog` in-process — a koffi-driven COM conversation on a worker thread with per-monitor-v2 DPI awareness, aborted by posting `WM_CLOSE` to the dialog thread — and falls back to a PowerShell-hosted dialog (`pwsh`, then Windows PowerShell 5.1, which every Windows ships) whenever that native surface is unavailable; a resolvable `pwsh` that cannot deliver the dialog (PowerShell 6 has no WinForms) falls through the same way. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md). **Dual-face package**: the browser half (`./client`) registers a renderless flow occupant into [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes — each `open` request drives `host.pickDirectory` and reports the one outcome (picked path / cancel / failure) through the hole's owner conversation. One cordis.yml row therefore composes both sides of the native interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). @@ -17,4 +17,5 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **Linux requires desktop tooling** — with neither Zenity nor KDialog installed, `pick` rejects with an actionable error; it does not fall back to a typed-path prompt (the browse backend is that fallback at the composition level). -- **Windows needs PowerShell 7 for the modern picker** — `pwsh` renders the Explorer-style folder dialog; a machine with only Windows PowerShell 5.1 falls back to the legacy folder tree, DPI-corrected but not the modern UI. +- **The Windows fallback chain degrades the dialog** — the in-process picker is the modern Explorer-style dialog; where koffi cannot drive COM the PowerShell tiers take over, and a machine that only reaches Windows PowerShell 5.1 gets the legacy folder tree, DPI-corrected but not the modern UI. +- **A wedged abort can leak one dialog thread** — when `WM_CLOSE` never lands (the dialog window was never created), the driver terminates and unrefs the worker; Node cannot interrupt a thread blocked in the native modal call, so that thread lives until process exit. diff --git a/packages/host/directory-picker-native/README.zh.md b/packages/host/directory-picker-native/README.zh.md index cb2e067d34..82f51976af 100644 --- a/packages/host/directory-picker-native/README.zh.md +++ b/packages/host/directory-picker-native/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Windows 使用 `pwsh`(PowerShell 7)并以 Windows PowerShell 5.1 回退——对话框脚本会把进程设为系统 DPI aware——Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。 +[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。Windows 在进程内打开现代 `IFileOpenDialog`——由 koffi 在 worker 线程上驱动的 COM 会话,带 per-monitor-v2 DPI 感知,中止时向对话框线程投递 `WM_CLOSE`——当该原生面不可用时回退到 PowerShell 承载的对话框(先 `pwsh`,再回退到每台 Windows 都自带的 Windows PowerShell 5.1);可解析但无法呈现对话框的 `pwsh`(PowerShell 6 没有 WinForms)同样落入该回退。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。 **双面包**:browser half(`./client`)向 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞注册一个无渲染的流程占用者——每次 `open` 请求驱动 `host.pickDirectory`,并经洞的 owner 会话上报唯一结果(所选路径/取消/失败)。因此一行 cordis.yml 同时组合原生交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 @@ -17,4 +17,5 @@ ## 已知限制与延期工作 - **Linux 依赖桌面工具**——Zenity 与 KDialog 均未安装时,`pick` 以包含解决建议的错误拒绝;它不会回退为手输路径提示(组合层面的回退是 browse 后端)。 -- **Windows 需要 PowerShell 7 才能使用现代选择器**——`pwsh` 呈现资源管理器风格的文件夹对话框;只有 Windows PowerShell 5.1 的机器会回退到旧版文件夹树,DPI 已修正,但界面不是现代的。 +- **Windows 回退链会降级对话框**——进程内选择器就是现代资源管理器风格对话框;koffi 无法驱动 COM 时由 PowerShell 层级接手,最终只到达 Windows PowerShell 5.1 的机器得到旧版文件夹树,DPI 已修正,但界面不是现代的。 +- **卡死的中止可能泄漏一个对话框线程**——当 `WM_CLOSE` 始终投递不到(对话框窗口从未创建)时,driver 会 terminate 并 unref 该 worker;Node 无法打断阻塞在原生模态调用里的线程,因此该线程会存活到进程退出。 diff --git a/packages/host/directory-picker-native/package.json b/packages/host/directory-picker-native/package.json index bafe18e09f..49033cdcf4 100644 --- a/packages/host/directory-picker-native/package.json +++ b/packages/host/directory-picker-native/package.json @@ -26,6 +26,7 @@ "lib/index.js", "lib/invariant.js", "lib/client.js", + "lib/win32-dialog-worker.cjs", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" @@ -33,7 +34,8 @@ "license": "BSD-3-Clause", "dependencies": { "@deepseek-ai/dsh-host-directory-picker": "workspace:^", - "@deepseek-ai/dsh-native-command": "workspace:^" + "@deepseek-ai/dsh-native-command": "workspace:^", + "koffi": "^3.1.0" }, "peerDependencies": { "@deepseek-ai/dsh-client-runtime": "^0.0.1", @@ -50,7 +52,8 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@types/react": "~18.3.1", "cordis": "^4.0.0-rc.7", - "react": "^18.2.0" + "react": "^18.2.0", + "tsx": "^4.19.2" }, "dshClient": { "inject": [ diff --git a/packages/host/directory-picker-native/src/native-picker.ts b/packages/host/directory-picker-native/src/native-picker.ts index 0cc12fb38e..6cabf44ddb 100644 --- a/packages/host/directory-picker-native/src/native-picker.ts +++ b/packages/host/directory-picker-native/src/native-picker.ts @@ -1,6 +1,7 @@ /** Cross-platform native single-directory chooser behind the native backend's capability. */ import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command' +import { pickWin32Directory } from './win32-dialog.ts' /** Testable command boundary; native implementations never invoke a shell. */ export type DirectoryPickerRunner = NativeCommandRunner @@ -9,6 +10,8 @@ export type DirectoryPickerRunner = NativeCommandRunner export interface DirectoryPickerInternals { platform?: NodeJS.Platform run?: DirectoryPickerRunner + /** Replaces the in-process Win32 dialog (`pickWin32Directory`) for deterministic tests. */ + pickWin32Dialog?: (signal: AbortSignal) => Promise } function outputPath(stdout: string): string | null { @@ -64,13 +67,26 @@ export async function pickNativeDirectory( } if (platform === 'win32') { - // PowerShell 7 renders the modern IFileDialog folder picker, while Windows - // PowerShell 5.1's FolderBrowserDialog is hardwired to the legacy - // SHBrowseForFolder tree; prefer pwsh and fall back only when it is absent. - // Both hosts spawn DPI-unaware, so the script opts the process into system - // DPI awareness before any window is created. No Description is set: the - // modern dialog renders it as a bottom strip and the classic dialog as an - // unthemed box. + // Primary: the in-process koffi-backed IFileOpenDialog worker — the modern + // picker with per-monitor-v2 DPI, no PowerShell dependency, and abort + // support. Any non-abort failure (koffi unavailable, ancient Windows, COM + // refusal) falls back to the PowerShell chain below. + const pickDialog = internals.pickWin32Dialog ?? pickWin32Directory + try { + return await pickDialog(signal) + } catch (error: unknown) { + rethrowIfAborted(signal, error) + } + + // PowerShell fallback: PowerShell 7 renders the modern IFileDialog folder + // picker, while Windows PowerShell 5.1's FolderBrowserDialog is hardwired + // to the legacy SHBrowseForFolder tree. Prefer pwsh, but ANY pwsh failure + // falls back to 5.1 (which every Windows ships): a resolvable pwsh can + // still be unable to deliver the dialog — PowerShell 6 has no WinForms, + // so its Add-Type exits 1, not ENOENT. Both hosts spawn DPI-unaware, so + // the script opts the process into system DPI awareness before any window + // is created. No Description is set: the modern dialog renders it as a + // bottom strip and the classic dialog as an unthemed box. const script = [ "$ErrorActionPreference = 'Stop'", "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class DpiAware { [DllImport(\"user32.dll\")] public static extern bool SetProcessDPIAware(); }'", @@ -89,7 +105,6 @@ export async function pickNativeDirectory( return outputPath(result.stdout) } catch (error: unknown) { rethrowIfAborted(signal, error) - if (!isMissingCommand(error)) throw error } const result = await run('powershell.exe', ['-NoProfile', '-STA', '-Command', script], signal) return outputPath(result.stdout) diff --git a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts new file mode 100644 index 0000000000..a9b625812c --- /dev/null +++ b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts @@ -0,0 +1,157 @@ +/** + * koffi-backed Win32 bindings for the folder dialog: the COM vtable calls + * behind {@link Win32DialogBindings} plus the cross-thread window closer the + * driver uses to service aborts. Loaded lazily and only on win32 (the dialog + * worker and the driver's abort path), so non-Windows processes never load + * koffi — the same containment as the repo's other `win32.ts` modules. + * + * The COM surface used here (IModalWindow/IFileDialog/IFileOpenDialog and + * IShellItem vtable order, the GUIDs, `FOS_*` and `SIGDN_FILESYSPATH`) is + * frozen Windows ABI since Vista; slots are offsets into the vtable at the + * object's first pointer. + */ + +import type { Win32DialogBindings, Win32FolderDialog } from './win32-dialog-logic.ts' + +interface KoffiFunction { (...args: unknown[]): unknown } +interface KoffiLibrary { func(convention: string, name: string, result: string, args: string[]): KoffiFunction } +interface Koffi { + load(path: string): KoffiLibrary + proto(declaration: string): unknown + pointer(type: unknown): unknown + call(pointer: unknown, proto: unknown, ...args: unknown[]): unknown + decode(value: unknown, offsetOrType: unknown, type?: unknown): unknown + register(fn: (...args: unknown[]) => unknown, type: unknown): unknown + unregister(callback: unknown): void +} + +const COINIT_APARTMENTTHREADED = 0x2 +const CLSCTX_INPROC_SERVER = 0x1 +const SIGDN_FILESYSPATH = 0x80058000 | 0 +const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4 +const WM_CLOSE = 0x10 + +/** IFileOpenDialog vtable slots (IUnknown 0-2, IModalWindow 3, IFileDialog 4+). */ +const SLOT_RELEASE = 2 +const SLOT_SHOW = 3 +const SLOT_SET_OPTIONS = 9 +const SLOT_SET_TITLE = 17 +const SLOT_GET_RESULT = 20 +/** IShellItem vtable slot for `GetDisplayName`. */ +const SLOT_GET_DISPLAY_NAME = 5 + +/** + * Encode a canonical GUID string as its 16 little-endian bytes. + * @param text - the `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` form. + * @returns the in-memory GUID bytes CoCreateInstance expects. + */ +function guidBytes(text: string): Buffer { + const match = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(text) as RegExpExecArray + const bytes = Buffer.alloc(16) + bytes.writeUInt32LE(parseInt(match[1] as string, 16), 0) + bytes.writeUInt16LE(parseInt(match[2] as string, 16), 4) + bytes.writeUInt16LE(parseInt(match[3] as string, 16), 6) + Buffer.from((match[4] as string) + (match[5] as string), 'hex').copy(bytes, 8) + return bytes +} + +const CLSID_FILE_OPEN_DIALOG = guidBytes('dc1c5a9c-e88a-4dde-a5a1-60f82a20aef7') +const IID_IFILE_OPEN_DIALOG = guidBytes('d57c7288-d4ad-4768-be02-9d969532d960') + +/** + * Load koffi and expose the dialog bindings for this thread. + * @returns the bindings {@link runFolderDialog} sequences against. + */ +export async function loadWin32DialogBindings(): Promise { + const koffi = (await import('koffi')).default as unknown as Koffi + const ole32 = koffi.load('ole32.dll') + const user32 = koffi.load('user32.dll') + const kernel32 = koffi.load('kernel32.dll') + + const coInitializeEx = ole32.func('__stdcall', 'CoInitializeEx', 'int32', ['void *', 'uint32']) + const coCreateInstance = ole32.func('__stdcall', 'CoCreateInstance', 'int32', ['void *', 'void *', 'uint32', 'void *', 'void *']) + const coTaskMemFree = ole32.func('__stdcall', 'CoTaskMemFree', 'void', ['void *']) + const getCurrentThreadId = kernel32.func('__stdcall', 'GetCurrentThreadId', 'uint32', []) + + const protoShow = koffi.proto('int32 __stdcall DshDialogShow(void *self, void *owner)') + const protoSetOptions = koffi.proto('int32 __stdcall DshDialogSetOptions(void *self, uint32 options)') + const protoSetTitle = koffi.proto('int32 __stdcall DshDialogSetTitle(void *self, str16 title)') + const protoGetResult = koffi.proto('int32 __stdcall DshDialogGetResult(void *self, _Out_ void **item)') + const protoGetDisplayName = koffi.proto('int32 __stdcall DshItemGetDisplayName(void *self, int32 form, _Out_ void **name)') + const protoRelease = koffi.proto('uint32 __stdcall DshComRelease(void *self)') + + /** Bind vtable slot `slot` of COM object `self` to a caller through `proto`. */ + const method = (self: unknown, slot: number, proto: unknown): (...args: unknown[]) => number => { + const vtable = koffi.decode(self, 'void *') + const fn = koffi.decode(vtable, slot * 8, 'void *') + return (...args: unknown[]) => koffi.call(fn, proto, self, ...args) as number + } + + return { + setThreadDpiAwareness: () => { + try { + const setThreadDpiAwarenessContext = user32.func('__stdcall', 'SetThreadDpiAwarenessContext', 'void *', ['intptr']) + setThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) + } catch { + // SetThreadDpiAwarenessContext absent (Windows 10 pre-1703): the + // dialog renders at system DPI; nothing else can fail here because + // user32 itself loaded above. + } + }, + coInitializeSta: () => coInitializeEx(null, COINIT_APARTMENTTHREADED) as number, + currentThreadId: () => getCurrentThreadId() as number, + createFolderDialog: (): Win32FolderDialog => { + const out = Buffer.alloc(8) + const created = coCreateInstance(CLSID_FILE_OPEN_DIALOG, null, CLSCTX_INPROC_SERVER, IID_IFILE_OPEN_DIALOG, out) as number + if (created < 0) throw new Error(`CoCreateInstance(FileOpenDialog) failed: HRESULT 0x${(created >>> 0).toString(16)}`) + const dialog = koffi.decode(out, 'void *') + return { + setOptions: options => method(dialog, SLOT_SET_OPTIONS, protoSetOptions)(options), + setTitle: title => method(dialog, SLOT_SET_TITLE, protoSetTitle)(title), + show: () => method(dialog, SLOT_SHOW, protoShow)(null), + resultPath: () => { + const itemOut: unknown[] = [null] + const gotItem = method(dialog, SLOT_GET_RESULT, protoGetResult)(itemOut) + if (gotItem < 0) return { hr: gotItem } + const item = itemOut[0] + try { + const nameOut: unknown[] = [null] + const gotName = method(item, SLOT_GET_DISPLAY_NAME, protoGetDisplayName)(SIGDN_FILESYSPATH, nameOut) + if (gotName < 0) return { hr: gotName } + const path = koffi.decode(nameOut[0], 'str16') as string + coTaskMemFree(nameOut[0]) + return { hr: gotName, path } + } finally { + method(item, SLOT_RELEASE, protoRelease)() + } + }, + release: () => { + method(dialog, SLOT_RELEASE, protoRelease)() + }, + } + }, + } +} + +/** + * Post `WM_CLOSE` to every window of a native thread — the driver's abort + * lever against the worker blocked inside `Show`, after which `Show` returns + * `HRESULT_CANCELLED` and the worker unwinds normally. + * @param threadId - the dialog thread's native id (from the `showing` notice). + */ +export async function closeThreadWindows(threadId: number): Promise { + const koffi = (await import('koffi')).default as unknown as Koffi + const user32 = koffi.load('user32.dll') + const enumThreadWindows = user32.func('__stdcall', 'EnumThreadWindows', 'int', ['uint32', 'void *', 'intptr']) + const postMessageW = user32.func('__stdcall', 'PostMessageW', 'int', ['void *', 'uint32', 'uintptr', 'intptr']) + const protoEnumProc = koffi.proto('int __stdcall DshEnumThreadWndProc(void *hwnd, intptr lparam)') + const callback = koffi.register((hwnd: unknown) => { + postMessageW(hwnd, WM_CLOSE, 0, 0) + return 1 + }, koffi.pointer(protoEnumProc)) + try { + enumThreadWindows(threadId, callback, 0) + } finally { + koffi.unregister(callback) + } +} diff --git a/packages/host/directory-picker-native/src/win32-dialog-host.ts b/packages/host/directory-picker-native/src/win32-dialog-host.ts new file mode 100644 index 0000000000..cfaf07cc46 --- /dev/null +++ b/packages/host/directory-picker-native/src/win32-dialog-host.ts @@ -0,0 +1,36 @@ +/** + * Real-process half of the Win32 dialog driver: spawn the dialog worker + * (source or built plane) and close a dialog thread's windows. Loaded lazily + * and only on the win32 default path, so non-Windows processes never touch + * worker or koffi machinery; the driver's logic is tested against fakes of + * this surface instead. + */ + +import { fileURLToPath } from 'node:url' +import { Worker } from 'node:worker_threads' +import type { Win32DialogWorkerData } from './win32-dialog-worker.ts' + +/** + * Spawn the dialog worker. Built consumers load the bundled CJS worker next + * to this module; unbuilt (source) consumers bootstrap tsx inside the worker + * first, mirroring `dsh-workflow-workerthread`'s host. + * @param data - the worker payload (dialog title). + * @returns the spawned worker thread. + */ +export function spawnDialogWorker(data: Win32DialogWorkerData): Worker { + /* v8 ignore next 3 -- the built-output arm: tests always run unbuilt (src/) */ + if (!import.meta.url.endsWith('.ts')) { + return new Worker(fileURLToPath(new URL('./win32-dialog-worker.cjs', import.meta.url)), { workerData: data }) + } + const workerEntry = new URL('./win32-dialog-worker.ts', import.meta.url) + const bootstrap = [ + `import { register as registerEsm } from ${JSON.stringify(import.meta.resolve('tsx/esm/api'))}`, + `import { register as registerCjs } from ${JSON.stringify(import.meta.resolve('tsx/cjs/api'))}`, + 'registerCjs()', + 'registerEsm()', + `await import(${JSON.stringify(workerEntry.href)})`, + ].join('\n') + return new Worker(new URL(`data:text/javascript,${encodeURIComponent(bootstrap)}`), { workerData: data }) +} + +export { closeThreadWindows } from './win32-dialog-bindings.ts' diff --git a/packages/host/directory-picker-native/src/win32-dialog-logic.ts b/packages/host/directory-picker-native/src/win32-dialog-logic.ts new file mode 100644 index 0000000000..cba0ca9f24 --- /dev/null +++ b/packages/host/directory-picker-native/src/win32-dialog-logic.ts @@ -0,0 +1,117 @@ +/** + * Pure sequencing of the Win32 `IFileOpenDialog` folder-picker COM + * conversation over an injectable bindings seam, so every outcome path + * (selection, cancellation, HRESULT failure, cleanup ordering) is testable on + * any platform. The koffi-backed bindings live in + * `win32-dialog-bindings.ts`, which only a real win32 process ever loads. + */ + +/** `HRESULT_FROM_WIN32(ERROR_CANCELLED)`: the user dismissed the dialog. */ +export const HRESULT_CANCELLED = 0x800704c7 | 0 + +/** `FOS_PICKFOLDERS`: the dialog selects directories, not files. */ +export const FOS_PICKFOLDERS = 0x20 +/** `FOS_FORCEFILESYSTEM`: only results with a filesystem path can be chosen. */ +export const FOS_FORCEFILESYSTEM = 0x40 +/** `FOS_NOCHANGEDIR`: never mutate the process working directory. */ +export const FOS_NOCHANGEDIR = 0x8 + +/** One created folder dialog: the vtable calls the sequencing needs. */ +export interface Win32FolderDialog { + /** + * `IFileDialog::SetOptions`. + * @param options - the `FOS_*` flag union to apply. + * @returns the call's HRESULT. + */ + setOptions(options: number): number + /** + * `IFileDialog::SetTitle`. + * @param title - the dialog title text. + * @returns the call's HRESULT. + */ + setTitle(title: string): number + /** + * `IModalWindow::Show` with no owner window; blocks the calling thread + * until the user selects or dismisses. + * @returns the call's HRESULT (`HRESULT_CANCELLED` on dismissal). + */ + show(): number + /** + * `IFileDialog::GetResult` + `IShellItem::GetDisplayName(SIGDN_FILESYSPATH)`, + * releasing the shell item and freeing the COM string. + * @returns the call chain's HRESULT and, on success, the selected path. + */ + resultPath(): { hr: number; path?: string } + /** Release the dialog's COM reference. */ + release(): void +} + +/** The thread-level native surface the dialog sequencing runs against. */ +export interface Win32DialogBindings { + /** + * Best-effort per-monitor-v2 DPI opt-in for the calling thread. Absent + * before Windows 10 1703; implementations swallow only that absence, so an + * old host merely renders the dialog at system DPI. + */ + setThreadDpiAwareness(): void + /** + * `CoInitializeEx(COINIT_APARTMENTTHREADED)` on the calling thread. + * @returns the call's HRESULT (`S_FALSE` re-entry is still a success). + */ + coInitializeSta(): number + /** + * `CoCreateInstance(CLSID_FileOpenDialog)`. + * @returns the created dialog surface; throws when creation fails. + */ + createFolderDialog(): Win32FolderDialog + /** + * `GetCurrentThreadId` — the native id a driver needs to close this + * thread's windows from outside. + * @returns the calling thread's native id. + */ + currentThreadId(): number +} + +/** + * Throw when an HRESULT signals failure. + * @param hr - the HRESULT to check. + * @param what - the failing call's name for the error message. + * @returns the (successful) HRESULT unchanged. + */ +function check(hr: number, what: string): number { + if (hr < 0) throw new Error(`${what} failed: HRESULT 0x${(hr >>> 0).toString(16)}`) + return hr +} + +/** + * Run one modal folder-picker conversation on the calling thread: DPI opt-in, + * STA init, dialog creation, `Show`, and result extraction, releasing the + * dialog on every path. + * @param bindings - the native surface (koffi-backed in production, fakes in tests). + * @param title - the dialog title text. + * @param onShowing - called with the native thread id immediately before the + * blocking `Show`, so a driver on another thread can close the dialog. + * @returns the selected filesystem path, or null when the user cancels. + */ +export function runFolderDialog( + bindings: Win32DialogBindings, + title: string, + onShowing: (threadId: number) => void, +): string | null { + bindings.setThreadDpiAwareness() + check(bindings.coInitializeSta(), 'CoInitializeEx') + const dialog = bindings.createFolderDialog() + try { + check(dialog.setOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR), 'SetOptions') + check(dialog.setTitle(title), 'SetTitle') + onShowing(bindings.currentThreadId()) + const shown = dialog.show() + if (shown === HRESULT_CANCELLED) return null + check(shown, 'Show') + const result = dialog.resultPath() + check(result.hr, 'GetResult') + return result.path as string + } finally { + dialog.release() + } +} diff --git a/packages/host/directory-picker-native/src/win32-dialog-worker.ts b/packages/host/directory-picker-native/src/win32-dialog-worker.ts new file mode 100644 index 0000000000..2e4ef64f6c --- /dev/null +++ b/packages/host/directory-picker-native/src/win32-dialog-worker.ts @@ -0,0 +1,37 @@ +/** + * Worker entry for the Win32 folder dialog: blocks THIS thread inside the + * modal `Show` so the host event loop stays live, reporting over the message + * port. Protocol: `{kind:'showing',threadId}` right before the blocking call + * (the driver's abort lever needs the native thread id), then exactly one of + * `{kind:'done',path}` or `{kind:'error',message}`. + */ + +import { parentPort, workerData } from 'node:worker_threads' +import { loadWin32DialogBindings } from './win32-dialog-bindings.ts' +import { runFolderDialog } from './win32-dialog-logic.ts' + +/** The driver-to-worker payload: the dialog title. */ +export interface Win32DialogWorkerData { title: string } + +/** One notice or outcome posted back to the driver. */ +export type Win32DialogWorkerMessage = + | { kind: 'showing'; threadId: number } + | { kind: 'done'; path: string | null } + | { kind: 'error'; message: string } + +const port = parentPort +if (port === null) throw new Error('win32-dialog-worker must run as a worker thread') +const { title } = workerData as Win32DialogWorkerData + +// No top-level await: the built worker ships as CJS (pkg's VFS Worker hook +// compiles that format), which cannot carry TLA. +void (async () => { + try { + const bindings = await loadWin32DialogBindings() + const path = runFolderDialog(bindings, title, (threadId) =>{ port.postMessage({ kind: 'showing', threadId } satisfies Win32DialogWorkerMessage) }) + port.postMessage({ kind: 'done', path } satisfies Win32DialogWorkerMessage) + } catch (error: unknown) { + const message = error instanceof Error ? (error.stack ?? error.message) : String(error) + port.postMessage({ kind: 'error', message } satisfies Win32DialogWorkerMessage) + } +})() diff --git a/packages/host/directory-picker-native/src/win32-dialog.ts b/packages/host/directory-picker-native/src/win32-dialog.ts new file mode 100644 index 0000000000..40b31e8d57 --- /dev/null +++ b/packages/host/directory-picker-native/src/win32-dialog.ts @@ -0,0 +1,128 @@ +/** + * Main-thread driver for the Win32 folder dialog: spawns the dialog worker + * (which blocks inside the modal `Show`), maps its message protocol onto a + * promise, and services aborts by posting `WM_CLOSE` to the dialog thread's + * windows until the worker reports back. The real worker/window surface is + * injectable so every driver path is testable on any platform. + */ + +import { closeThreadWindows as hostCloseThreadWindows, spawnDialogWorker } from './win32-dialog-host.ts' +import type { Win32DialogWorkerData, Win32DialogWorkerMessage } from './win32-dialog-worker.ts' + +/** The worker surface the driver drives (satisfied by `node:worker_threads`). */ +export interface Win32DialogWorkerLike { + /** + * Subscribe to a worker event. + * @param event - `message`, `error`, or `exit`. + * @param listener - the event consumer. + */ + on(event: 'message', listener: (message: Win32DialogWorkerMessage) => void): unknown + on(event: 'error', listener: (error: Error) => void): unknown + on(event: 'exit', listener: (code: number) => void): unknown + /** + * Force-stop the worker; the abort path's last resort when `WM_CLOSE` + * never lands (e.g. the dialog window was never created). + * @returns settles when the thread is gone. + */ + terminate(): Promise + /** + * Release the event-loop reference. Called once the pick settles so a + * worker stuck in the native modal call (terminate cannot interrupt + * native code) never blocks process exit. + */ + unref?(): void +} + +/** Injectable process surface for deterministic driver tests. */ +export interface Win32DialogInternals { + /** Replaces the real worker spawn (`win32-dialog-host.ts`). */ + spawnWorker?: (data: Win32DialogWorkerData) => Win32DialogWorkerLike + /** Replaces the real `WM_CLOSE` poster (`win32-dialog-host.ts`). */ + closeThreadWindows?: (threadId: number) => Promise + /** Abort-service cadence override so tests never wait wall-clock time. */ + closeRetryMs?: number +} + +/** The dialog title every host shows. */ +export const DIALOG_TITLE = 'Select Workspace Directory' + +/** `WM_CLOSE` re-post cadence while an abort waits for the worker to unwind. */ +const CLOSE_RETRY_MS = 150 +/** Abort-service attempts before force-terminating the worker. */ +const CLOSE_MAX_ATTEMPTS = 20 + +/** + * Open the modern Win32 folder picker off the event loop. + * @param signal - caller lifetime; abort closes the dialog and rejects. + * @param internals - worker/window seams for deterministic tests. + * @returns the selected path, or null when the user cancels. + */ +export async function pickWin32Directory( + signal: AbortSignal, + internals: Win32DialogInternals = {}, +): Promise { + if (signal.aborted) throw new Error('native directory picker aborted') + const spawnWorker = internals.spawnWorker ?? spawnDialogWorker + const closeWindows = internals.closeThreadWindows ?? hostCloseThreadWindows + const closeRetryMs = internals.closeRetryMs ?? CLOSE_RETRY_MS + + const worker = spawnWorker({ title: DIALOG_TITLE }) + let dialogThreadId: number | undefined + let closeTimer: NodeJS.Timeout | undefined + let settled = false + + return await new Promise((resolve, reject) => { + const settle = (outcome: () => void): void => { + if (settled) return + settled = true + if (closeTimer !== undefined) clearInterval(closeTimer) + signal.removeEventListener('abort', onAbort) + worker.unref?.() + outcome() + } + + const serviceAbort = (): void => { + let attempts = 0 + // The `showing` notice precedes the blocking `Show`, so the very first + // WM_CLOSE can race the window's creation; re-post until the worker + // reports back, then force-terminate as a last resort. + closeTimer = setInterval(() => { + attempts += 1 + if (attempts > CLOSE_MAX_ATTEMPTS) { + settle(() => { + void worker.terminate() + reject(new Error('native directory picker aborted (dialog unresponsive; worker terminated)')) + }) + return + } + void closeWindows(dialogThreadId as number).catch(() => undefined) + }, closeRetryMs) + void closeWindows(dialogThreadId as number).catch(() => undefined) + } + + const onAbort = (): void => { + if (dialogThreadId !== undefined) serviceAbort() + // Not shown yet: the `showing` handler below starts the service loop. + } + signal.addEventListener('abort', onAbort, { once: true }) + + worker.on('message', (message: Win32DialogWorkerMessage) => { + switch (message.kind) { + case 'showing': + dialogThreadId = message.threadId + if (signal.aborted) serviceAbort() + return + case 'done': + settle(() => { + if (signal.aborted) reject(new Error('native directory picker aborted')) + else resolve(message.path) + }) + return + case 'error': + settle(() =>{ reject(new Error(`win32 folder dialog failed: ${message.message}`)) }) + } + }) + worker.on('error', (error: Error) =>{ settle(() =>{ reject(error) }) }) + worker.on('exit', () =>{ settle(() =>{ reject(new Error('win32 folder dialog worker exited before reporting a result')) }) }) + }) +} diff --git a/packages/host/directory-picker-native/tests/native-picker.spec.ts b/packages/host/directory-picker-native/tests/native-picker.spec.ts index 707a5cafe4..7c51d552d4 100644 --- a/packages/host/directory-picker-native/tests/native-picker.spec.ts +++ b/packages/host/directory-picker-native/tests/native-picker.spec.ts @@ -23,6 +23,9 @@ function failure(code: string | number, stderr = ''): Error { const signal = () => new AbortController().signal +/** The PowerShell chain is reachable only when the in-process dialog fails. */ +const noDialog = async (): Promise => { throw new Error('dialog unavailable') } + describe('native directory picker', () => { it('uses the macOS folder chooser and maps user cancellation to null', async () => { const run = vi.fn(async () => ({ stdout: '/Users/test/project/\n', stderr: '' })) @@ -46,9 +49,18 @@ describe('native directory picker', () => { await expect(pickNativeDirectory(signal(), { platform: 'darwin', run })).rejects.toBe(reason) }) - it('prefers pwsh for the Windows folder dialog and maps empty output to cancellation', async () => { + it('prefers the in-process Win32 dialog and never spawns PowerShell when it answers', async () => { + const run = vi.fn() + const pickWin32Dialog = vi.fn(async (): Promise => 'C:\\work\\selected') + await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog })).resolves.toBe('C:\\work\\selected') + pickWin32Dialog.mockResolvedValueOnce(null) + await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog })).resolves.toBeNull() + expect(run).not.toHaveBeenCalled() + }) + + it('falls back to pwsh when the dialog is unavailable and maps empty output to cancellation', async () => { const run = vi.fn(async () => ({ stdout: 'C:\\work\\project\r\n', stderr: '' })) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).resolves.toBe('C:\\work\\project') + await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog: noDialog })).resolves.toBe('C:\\work\\project') expect(run).toHaveBeenCalledWith( 'pwsh.exe', expect.arrayContaining(['-NoProfile', '-STA', '-Command']), @@ -60,48 +72,70 @@ describe('native directory picker', () => { // Description renders as a bottom strip (modern) / unthemed box (classic); never set it. expect(script).not.toContain('Description') run.mockResolvedValueOnce({ stdout: '', stderr: '' }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).resolves.toBeNull() - run.mockRejectedValueOnce(failure(1, 'Add-Type failed')) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).rejects.toThrow('command failed') + await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog: noDialog })).resolves.toBeNull() }) - it('falls back to Windows PowerShell 5.1 only when pwsh is missing', async () => { + it('falls back to Windows PowerShell 5.1 whenever pwsh cannot deliver the dialog', async () => { const run = vi.fn() .mockRejectedValueOnce(failure('ENOENT')) .mockResolvedValueOnce({ stdout: 'C:\\work\\fallback\r\n', stderr: '' }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run })).resolves.toBe('C:\\work\\fallback') + await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog: noDialog })).resolves.toBe('C:\\work\\fallback') expect(run.mock.calls.map(call => call[0])).toEqual(['pwsh.exe', 'powershell.exe']) // Both runtimes execute the identical script, so DPI awareness holds either way. expect(run.mock.calls[0]?.[1].at(-1)).toBe(run.mock.calls[1]?.[1].at(-1)) + // A resolvable pwsh that cannot deliver the dialog (PowerShell 6: no + // WinForms, Add-Type exits 1 - not ENOENT) reaches 5.1 all the same. + const pwsh6 = vi.fn() + .mockRejectedValueOnce(failure(1, "Cannot load assembly 'System.Windows.Forms'")) + .mockResolvedValueOnce({ stdout: 'C:\\work\\legacy\r\n', stderr: '' }) + await expect(pickNativeDirectory(signal(), { platform: 'win32', run: pwsh6, pickWin32Dialog: noDialog })).resolves.toBe('C:\\work\\legacy') + expect(pwsh6.mock.calls.map(call => call[0])).toEqual(['pwsh.exe', 'powershell.exe']) + const cancelled = vi.fn() .mockRejectedValueOnce(failure('ENOENT')) .mockResolvedValueOnce({ stdout: '', stderr: '' }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run: cancelled })).resolves.toBeNull() + await expect(pickNativeDirectory(signal(), { platform: 'win32', run: cancelled, pickWin32Dialog: noDialog })).resolves.toBeNull() const failed = vi.fn() .mockRejectedValueOnce(failure('ENOENT')) .mockRejectedValueOnce(failure(2)) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run: failed })).rejects.toThrow('command failed') - - const brokenPwsh = vi.fn(async () => { throw failure(7) }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run: brokenPwsh })).rejects.toThrow('command failed') - expect(brokenPwsh).toHaveBeenCalledOnce() + await expect(pickNativeDirectory(signal(), { platform: 'win32', run: failed, pickWin32Dialog: noDialog })).rejects.toThrow('command failed') }) - it('does not fall back when the caller aborted the pwsh spawn', async () => { + it('wires the real Win32 dialog as the default tier', async () => { + // A pre-aborted signal makes the DEFAULT dialog deterministic on every + // host: pickWin32Directory throws before spawning any worker or window. + const abort = new AbortController() + abort.abort() + const run = vi.fn() + await expect(pickNativeDirectory(abort.signal, { platform: 'win32', run })) + .rejects.toThrow('native directory picker aborted') + expect(run).not.toHaveBeenCalled() + }) + + it('does not fall back when the caller aborted the dialog or the pwsh spawn', async () => { const abort = new AbortController() abort.abort(new Error('closed')) - const run = vi.fn(async () => { throw failure('ENOENT') }) - await expect(pickNativeDirectory(abort.signal, { platform: 'win32', run })).rejects.toThrow('command failed') - expect(run).toHaveBeenCalledOnce() + const run = vi.fn() + await expect(pickNativeDirectory(abort.signal, { platform: 'win32', run, pickWin32Dialog: noDialog })).rejects.toThrow('dialog unavailable') + expect(run).not.toHaveBeenCalled() + + const liveThenAborted = new AbortController() + const abortingRun = vi.fn(async () => { + liveThenAborted.abort(new Error('closed')) + throw failure('ENOENT') + }) + await expect(pickNativeDirectory(liveThenAborted.signal, { platform: 'win32', run: abortingRun, pickWin32Dialog: noDialog })) + .rejects.toThrow('command failed') + expect(abortingRun).toHaveBeenCalledOnce() }) it('runs the default command adapter without a shell and preserves command failures', async () => { execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { callback(null, 'C:\\work\\default\r\n', '') }) - await expect(pickNativeDirectory(signal(), { platform: 'win32' })).resolves.toBe('C:\\work\\default') + await expect(pickNativeDirectory(signal(), { platform: 'win32', pickWin32Dialog: noDialog })).resolves.toBe('C:\\work\\default') const [command, args, options] = execFileMock.mock.calls[0]! expect(command).toBe('pwsh.exe') expect(args).toEqual(expect.arrayContaining(['-NoProfile', '-STA', '-Command'])) @@ -109,19 +143,30 @@ describe('native directory picker', () => { expect(options.windowsHide).toBe(true) expect(options.signal).toBeInstanceOf(AbortSignal) + // Both chain tiers fail: pwsh's code-7 failure now reaches 5.1, whose + // failure is the one the caller sees. + const pwshError = Object.assign(new Error('pwsh failed'), { code: 7 }) const commandError = Object.assign(new Error('powershell failed'), { code: 7 }) + execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { + callback(pwshError, '', 'no WinForms') + }) execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { callback(commandError, 'partial output', 'failure details') }) - await expect(pickNativeDirectory(signal(), { platform: 'win32' })).rejects.toMatchObject({ + await expect(pickNativeDirectory(signal(), { platform: 'win32', pickWin32Dialog: noDialog })).rejects.toMatchObject({ message: 'powershell failed', cause: commandError, code: 7, stdout: 'partial output', stderr: 'failure details', }) + expect(execFileMock.mock.calls.map(call => call[0])).toEqual(['pwsh.exe', 'pwsh.exe', 'powershell.exe']) }) it('uses the current process platform when no platform override is supplied', async () => { + // Deterministic on every host: the win32 tier answers from the dialog, + // the POSIX tiers from the command runner. const run = vi.fn(async () => ({ stdout: '/default/platform\n', stderr: '' })) - await expect(pickNativeDirectory(signal(), { run })).resolves.toBe('/default/platform') + const pickWin32Dialog = async (): Promise => 'C:\\default\\platform' + const expected = process.platform === 'win32' ? 'C:\\default\\platform' : '/default/platform' + await expect(pickNativeDirectory(signal(), { run, pickWin32Dialog })).resolves.toBe(expected) }) it('uses Zenity on Linux and falls back to KDialog only when Zenity is missing', async () => { diff --git a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts new file mode 100644 index 0000000000..d23b43011a --- /dev/null +++ b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts @@ -0,0 +1,284 @@ +/** + * The koffi-backed bindings against a mocked `koffi` module (the same + * technique as dsh-session-persistence-jsonl's win32 suite): a small in-memory + * COM world stands in for ole32/user32/kernel32, keeping the vtable dispatch, + * result extraction, memory hygiene, and the WM_CLOSE poster covered on every + * host. The worker entry is exercised the same way with a mocked + * `node:worker_threads`. Real-COM behavior is pinned by the win32-only smoke + * in win32-dialog.spec.ts. + */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { HRESULT_CANCELLED, runFolderDialog } from '../src/win32-dialog-logic.ts' + +const E_FAIL = 0x80004005 | 0 +const WM_CLOSE = 0x10 + +interface ComWorld { + coInitHr: number + coCreateHr: number + showHr: number + getResultHr: number + getDisplayNameHr: number + hasThreadDpi: boolean + enumThrows: boolean + path: string + titles: string[] + options: number[] + dpiContexts: unknown[] + freed: unknown[] + released: string[] + posted: { hwnd: unknown; message: number }[] + registered: number + unregistered: number +} + +function comWorld(overrides: Partial = {}): ComWorld { + return { + coInitHr: 0, coCreateHr: 0, showHr: 0, getResultHr: 0, getDisplayNameHr: 0, + hasThreadDpi: true, enumThrows: false, + path: 'C:\\选中\\directory', + titles: [], options: [], dpiContexts: [], freed: [], released: [], posted: [], + registered: 0, unregistered: 0, + ...overrides, + } +} + +/** Sentinel pointer objects standing in for native addresses. */ +interface FakePtr { kind: string; [key: string]: unknown } + +function installFakeKoffi(world: ComWorld): void { + const dialogPtr: FakePtr = { kind: 'dialog' } + const itemPtr: FakePtr = { kind: 'item' } + const namePtr: FakePtr = { kind: 'name', text: world.path } + const outBuffers = new Map() + + const dispatch = (self: FakePtr, slot: number, args: unknown[]): number => { + if (self.kind === 'dialog') { + switch (slot) { + case 9: world.options.push(args[0] as number); return 0 + case 17: world.titles.push(args[0] as string); return 0 + case 3: return world.showHr + case 20: { + if (world.getResultHr < 0) return world.getResultHr + ;(args[0] as unknown[])[0] = itemPtr + return 0 + } + case 2: world.released.push('dialog'); return 0 + default: throw new Error(`unexpected dialog slot ${slot}`) + } + } + switch (slot) { + case 5: { + if (world.getDisplayNameHr < 0) return world.getDisplayNameHr + ;(args[1] as unknown[])[0] = namePtr + return 0 + } + case 2: world.released.push('item'); return 0 + default: throw new Error(`unexpected item slot ${slot}`) + } + } + + vi.doMock('koffi', () => ({ + default: { + load: (dll: string) => ({ + func: (_convention: string, name: string, _result: string, _args: string[]) => { + switch (name) { + case 'CoInitializeEx': return () => world.coInitHr + case 'CoCreateInstance': return (...args: unknown[]) => { + if (world.coCreateHr < 0) return world.coCreateHr + outBuffers.set(args[4], dialogPtr) + return 0 + } + case 'CoTaskMemFree': return (ptr: unknown) => { world.freed.push(ptr) } + case 'GetCurrentThreadId': return () => 31337 + case 'SetThreadDpiAwarenessContext': { + if (!world.hasThreadDpi) throw new Error(`${dll}: SetThreadDpiAwarenessContext not found`) + return (context: unknown) => { world.dpiContexts.push(context); return null } + } + case 'EnumThreadWindows': return (_tid: unknown, callback: { fn: (hwnd: unknown, lparam: unknown) => number }, lparam: unknown) => { + if (world.enumThrows) throw new Error('EnumThreadWindows refused') + callback.fn({ kind: 'hwnd', n: 1 }, lparam) + callback.fn({ kind: 'hwnd', n: 2 }, lparam) + return 1 + } + case 'PostMessageW': return (hwnd: unknown, message: number) => { world.posted.push({ hwnd, message }); return 1 } + default: throw new Error(`unexpected native import ${dll}/${name}`) + } + }, + }), + proto: (declaration: string) => ({ declaration }), + pointer: (type: unknown) => type, + register: (fn: (hwnd: unknown, lparam: unknown) => number) => { world.registered += 1; return { fn } }, + unregister: () => { world.unregistered += 1 }, + decode: (value: unknown, offsetOrType: unknown): unknown => { + if (offsetOrType === 'str16') return (value as FakePtr).text + if (typeof offsetOrType === 'number') { + // Vtable slot read: hand back a callable-reference sentinel. + const owner = (value as { owner: FakePtr }).owner + return { call: (args: unknown[]) => dispatch(owner, offsetOrType / 8, args) } + } + // decode(x, 'void *'): out-buffer read or vtable read. + if (outBuffers.has(value)) return outBuffers.get(value) + return { owner: value as FakePtr } + }, + call: (fn: { call: (args: unknown[]) => number }, _proto: unknown, _self: unknown, ...args: unknown[]) => fn.call(args), + }, + })) +} + +async function loadBindingsModule(): Promise { + return await import('../src/win32-dialog-bindings.ts') +} + +afterEach(() => { + vi.doUnmock('koffi') + vi.doUnmock('node:worker_threads') + vi.doUnmock('../src/win32-dialog-bindings.ts') + vi.resetModules() +}) + +describe('loadWin32DialogBindings over the fake COM world', () => { + it('drives the full selection conversation with memory hygiene', async () => { + const world = comWorld() + installFakeKoffi(world) + const { loadWin32DialogBindings } = await loadBindingsModule() + const bindings = await loadWin32DialogBindings() + const showing = vi.fn() + + expect(runFolderDialog(bindings, '选择工作区目录', showing)).toBe('C:\\选中\\directory') + expect(world.dpiContexts).toEqual([-4]) + expect(world.titles).toEqual(['选择工作区目录']) + expect(world.options).toHaveLength(1) + expect(showing).toHaveBeenCalledWith(31337) + expect(world.freed).toHaveLength(1) + expect(world.released).toEqual(['item', 'dialog']) + }) + + it('maps dismissal, missing DPI support, and the S_FALSE CoInitializeEx', async () => { + const world = comWorld({ showHr: HRESULT_CANCELLED, hasThreadDpi: false, coInitHr: 1 }) + installFakeKoffi(world) + const { loadWin32DialogBindings } = await loadBindingsModule() + const bindings = await loadWin32DialogBindings() + expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBeNull() + expect(world.dpiContexts).toEqual([]) + expect(world.released).toEqual(['dialog']) + }) + + it('surfaces creation and extraction failures as HRESULT errors', async () => { + const creationWorld = comWorld({ coCreateHr: E_FAIL }) + installFakeKoffi(creationWorld) + let bindings = await (await loadBindingsModule()).loadWin32DialogBindings() + expect(() => bindings.createFolderDialog()).toThrow('CoCreateInstance(FileOpenDialog) failed: HRESULT 0x80004005') + + vi.doUnmock('koffi') + vi.resetModules() + const resultWorld = comWorld({ getResultHr: E_FAIL }) + installFakeKoffi(resultWorld) + bindings = await (await loadBindingsModule()).loadWin32DialogBindings() + expect(() => runFolderDialog(bindings, 'Pick', vi.fn())).toThrow('GetResult failed') + expect(resultWorld.released).toEqual(['dialog']) + + vi.doUnmock('koffi') + vi.resetModules() + const nameWorld = comWorld({ getDisplayNameHr: E_FAIL }) + installFakeKoffi(nameWorld) + bindings = await (await loadBindingsModule()).loadWin32DialogBindings() + expect(() => runFolderDialog(bindings, 'Pick', vi.fn())).toThrow('GetResult failed') + // The shell item is released even when its display name cannot be read. + expect(nameWorld.released).toEqual(['item', 'dialog']) + expect(nameWorld.freed).toHaveLength(0) + }) +}) + +describe('closeThreadWindows over the fake COM world', () => { + it('posts WM_CLOSE to every window of the thread and unregisters the callback', async () => { + const world = comWorld() + installFakeKoffi(world) + const { closeThreadWindows } = await loadBindingsModule() + await closeThreadWindows(777) + expect(world.posted).toEqual([ + { hwnd: { kind: 'hwnd', n: 1 }, message: WM_CLOSE }, + { hwnd: { kind: 'hwnd', n: 2 }, message: WM_CLOSE }, + ]) + expect(world.registered).toBe(1) + expect(world.unregistered).toBe(1) + }) + + it('unregisters the callback even when the enumeration itself throws', async () => { + const world = comWorld({ enumThrows: true }) + installFakeKoffi(world) + const { closeThreadWindows } = await loadBindingsModule() + await expect(closeThreadWindows(777)).rejects.toThrow('EnumThreadWindows refused') + expect(world.unregistered).toBe(1) + }) +}) + +describe('the worker entry over a mocked thread boundary', () => { + it('posts showing then done for a completed conversation', async () => { + const posted: unknown[] = [] + vi.doMock('node:worker_threads', () => ({ + parentPort: { postMessage: (message: unknown) => posted.push(message) }, + workerData: { title: 'Pick' }, + })) + vi.doMock('../src/win32-dialog-bindings.ts', () => ({ + loadWin32DialogBindings: async () => ({ + setThreadDpiAwareness: () => undefined, + coInitializeSta: () => 0, + currentThreadId: () => 11, + createFolderDialog: () => ({ + setOptions: () => 0, + setTitle: () => 0, + show: () => 0, + resultPath: () => ({ hr: 0, path: 'C:\\from-worker' }), + release: () => undefined, + }), + }), + })) + await import('../src/win32-dialog-worker.ts') + expect(posted).toEqual([ + { kind: 'showing', threadId: 11 }, + { kind: 'done', path: 'C:\\from-worker' }, + ]) + }) + + it('posts the failure message when the native surface cannot load', async () => { + const posted: { kind: string; message?: string }[] = [] + vi.doMock('node:worker_threads', () => ({ + parentPort: { postMessage: (message: { kind: string }) => posted.push(message) }, + workerData: { title: 'Pick' }, + })) + vi.doMock('../src/win32-dialog-bindings.ts', () => ({ + loadWin32DialogBindings: async () => { throw new Error('no ole32 here') }, + })) + await import('../src/win32-dialog-worker.ts') + expect(posted).toHaveLength(1) + expect(posted[0]?.kind).toBe('error') + expect(posted[0]?.message).toContain('no ole32 here') + }) + + it('stringifies stackless and non-Error failures', async () => { + const stackless = new Error('bare message') + delete stackless.stack + for (const [thrown, expected] of [[stackless, 'bare message'], ['plain refusal', 'plain refusal']] as const) { + vi.doUnmock('node:worker_threads') + vi.doUnmock('../src/win32-dialog-bindings.ts') + vi.resetModules() + const posted: { kind: string; message?: string }[] = [] + vi.doMock('node:worker_threads', () => ({ + parentPort: { postMessage: (message: { kind: string }) => posted.push(message) }, + workerData: { title: 'Pick' }, + })) + vi.doMock('../src/win32-dialog-bindings.ts', () => ({ + loadWin32DialogBindings: async () => { throw thrown }, + })) + await import('../src/win32-dialog-worker.ts') + expect(posted[0]?.message).toBe(expected) + } + }) + + it('refuses to run outside a worker thread', async () => { + vi.doMock('node:worker_threads', () => ({ parentPort: null, workerData: undefined })) + await expect(import('../src/win32-dialog-worker.ts')).rejects.toThrow('must run as a worker thread') + }) +}) diff --git a/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts new file mode 100644 index 0000000000..c24a79ebc1 --- /dev/null +++ b/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts @@ -0,0 +1,90 @@ +/** + * The COM conversation's sequencing against fake bindings: outcome mapping + * (selection / cancellation / HRESULT failures at every step) and the + * release-on-every-path guarantee, all platform-independent. + */ + +import { describe, expect, it, vi } from 'vitest' +import { + FOS_FORCEFILESYSTEM, FOS_NOCHANGEDIR, FOS_PICKFOLDERS, HRESULT_CANCELLED, + runFolderDialog, type Win32DialogBindings, type Win32FolderDialog, +} from '../src/win32-dialog-logic.ts' + +const E_FAIL = 0x80004005 | 0 + +interface FakeWorld { + bindings: Win32DialogBindings + dpi: ReturnType + createDialog: ReturnType + dialog: { + setOptions: ReturnType + setTitle: ReturnType + show: ReturnType + resultPath: ReturnType + release: ReturnType + } +} + +function world(overrides: Partial = {}, coInit = 0): FakeWorld { + const dialog = { + setOptions: vi.fn(() => 0), + setTitle: vi.fn(() => 0), + show: vi.fn(() => 0), + resultPath: vi.fn(() => ({ hr: 0, path: 'C:\\picked\\目录' })), + release: vi.fn(), + ...overrides, + } + const dpi = vi.fn() + const createDialog = vi.fn(() => dialog) + const bindings: Win32DialogBindings = { + setThreadDpiAwareness: dpi, + coInitializeSta: vi.fn(() => coInit), + createFolderDialog: createDialog, + currentThreadId: vi.fn(() => 4242), + } + return { bindings, dpi, createDialog, dialog: dialog as FakeWorld['dialog'] } +} + +describe('runFolderDialog', () => { + it('sequences DPI, STA, options, title, show, and result extraction', () => { + const { bindings, dpi, dialog } = world() + const showing = vi.fn() + expect(runFolderDialog(bindings, 'Pick', showing)).toBe('C:\\picked\\目录') + expect(dpi).toHaveBeenCalledOnce() + expect(dialog.setOptions).toHaveBeenCalledWith(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR) + expect(dialog.setTitle).toHaveBeenCalledWith('Pick') + expect(showing).toHaveBeenCalledWith(4242) + expect(showing.mock.invocationCallOrder[0]).toBeLessThan(dialog.show.mock.invocationCallOrder[0] as number) + expect(dialog.release).toHaveBeenCalledOnce() + }) + + it('maps the cancelled HRESULT to null and still releases the dialog', () => { + const { bindings, dialog } = world({ show: vi.fn(() => HRESULT_CANCELLED) }) + expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBeNull() + expect(dialog.resultPath).not.toHaveBeenCalled() + expect(dialog.release).toHaveBeenCalledOnce() + }) + + it('accepts the S_FALSE re-entry HRESULT from CoInitializeEx', () => { + const { bindings } = world({}, 1) + expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBe('C:\\picked\\目录') + }) + + it('throws on a failing CoInitializeEx without creating a dialog', () => { + const { bindings, createDialog } = world({}, E_FAIL) + expect(() => runFolderDialog(bindings, 'Pick', vi.fn())).toThrow('CoInitializeEx failed: HRESULT 0x80004005') + expect(createDialog).not.toHaveBeenCalled() + }) + + it.each([ + ['SetOptions', { setOptions: vi.fn(() => E_FAIL) }], + ['SetTitle', { setTitle: vi.fn(() => E_FAIL) }], + ['Show', { show: vi.fn(() => E_FAIL) }], + ['GetResult', { resultPath: vi.fn(() => ({ hr: E_FAIL })) }], + ] satisfies [string, Partial][])('releases the dialog when %s fails', (what, overrides) => { + const { bindings, dialog } = world(overrides) + expect(() => runFolderDialog(bindings, 'Pick', vi.fn())).toThrow(`${what} failed: HRESULT 0x80004005`) + expect(dialog.release).toHaveBeenCalledOnce() + void bindings + }) +}) diff --git a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts new file mode 100644 index 0000000000..33e2fa60a1 --- /dev/null +++ b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts @@ -0,0 +1,136 @@ +/** + * Driver tests: the worker message protocol mapped onto the promise, the + * WM_CLOSE abort service (including the show-race retry and the terminate + * last resort) against fakes, plus the real spawn plumbing — POSIX hosts + * prove the default path rejects cleanly (koffi cannot load ole32 there), + * and win32 hosts briefly open and auto-abort a real dialog. + */ + +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import { pickWin32Directory, type Win32DialogInternals, type Win32DialogWorkerLike } from '../src/win32-dialog.ts' +import type { Win32DialogWorkerMessage } from '../src/win32-dialog-worker.ts' + +class FakeWorker extends EventEmitter implements Win32DialogWorkerLike { + terminate = vi.fn(async () => 0) + post(message: Win32DialogWorkerMessage): void { + this.emit('message', message) + } +} + +interface Harness { + worker: FakeWorker + internals: Win32DialogInternals + close: ReturnType +} + +function harness(overrides: Partial = {}): Harness { + const worker = new FakeWorker() + const close = vi.fn(async () => undefined) + return { + worker, + close, + internals: { spawnWorker: () => worker, closeThreadWindows: close, closeRetryMs: 1, ...overrides }, + } +} + +const live = (): AbortSignal => new AbortController().signal + +describe('pickWin32Directory', () => { + it('resolves the selected path and the cancellation null', async () => { + const first = harness() + const picked = pickWin32Directory(live(), first.internals) + first.worker.post({ kind: 'showing', threadId: 7 }) + first.worker.post({ kind: 'done', path: 'C:\\picked' }) + await expect(picked).resolves.toBe('C:\\picked') + expect(first.close).not.toHaveBeenCalled() + + const second = harness() + const cancelled = pickWin32Directory(live(), second.internals) + second.worker.post({ kind: 'done', path: null }) + await expect(cancelled).resolves.toBeNull() + }) + + it('rejects on a reported dialog failure, a worker crash, and a silent exit', async () => { + const reported = harness() + const failing = pickWin32Directory(live(), reported.internals) + reported.worker.post({ kind: 'error', message: 'CoCreateInstance failed' }) + await expect(failing).rejects.toThrow('win32 folder dialog failed: CoCreateInstance failed') + + const crashed = harness() + const crashing = pickWin32Directory(live(), crashed.internals) + crashed.worker.emit('error', new Error('worker blew up')) + await expect(crashing).rejects.toThrow('worker blew up') + + const silent = harness() + const exiting = pickWin32Directory(live(), silent.internals) + silent.worker.emit('exit', 0) + await expect(exiting).rejects.toThrow('exited before reporting a result') + }) + + it('settles once: a late exit after the result is inert', async () => { + const { worker, internals } = harness() + const picked = pickWin32Directory(live(), internals) + worker.post({ kind: 'done', path: 'C:\\once' }) + worker.emit('exit', 0) + await expect(picked).resolves.toBe('C:\\once') + }) + + it('throws immediately on an already-aborted signal without spawning', async () => { + const spawnWorker = vi.fn() + const controller = new AbortController() + controller.abort() + await expect(pickWin32Directory(controller.signal, { spawnWorker, closeThreadWindows: async () => undefined })) + .rejects.toThrow('native directory picker aborted') + expect(spawnWorker).not.toHaveBeenCalled() + }) + + it('services an abort by closing the dialog thread windows until the worker reports', async () => { + const { worker, internals, close } = harness() + const controller = new AbortController() + const picked = pickWin32Directory(controller.signal, internals) + worker.post({ kind: 'showing', threadId: 99 }) + controller.abort() + await vi.waitFor(() =>{ expect(close).toHaveBeenCalledWith(99) }) + worker.post({ kind: 'done', path: null }) + await expect(picked).rejects.toThrow('native directory picker aborted') + }) + + it('starts the close service on the showing notice when the abort came first', async () => { + const closeFailures = vi.fn(async () => { throw new Error('window not there yet') }) + const { worker, internals } = harness({ closeThreadWindows: closeFailures }) + const controller = new AbortController() + const picked = pickWin32Directory(controller.signal, internals) + controller.abort() + expect(closeFailures).not.toHaveBeenCalled() + worker.post({ kind: 'showing', threadId: 12 }) + await vi.waitFor(() =>{ expect(closeFailures.mock.calls.length).toBeGreaterThan(1) }) + worker.post({ kind: 'done', path: null }) + await expect(picked).rejects.toThrow('native directory picker aborted') + }) + + it('terminates an unresponsive worker after the close budget', async () => { + const { worker, internals, close } = harness() + const controller = new AbortController() + const picked = pickWin32Directory(controller.signal, internals) + worker.post({ kind: 'showing', threadId: 5 }) + controller.abort() + await expect(picked).rejects.toThrow('dialog unresponsive; worker terminated') + expect(worker.terminate).toHaveBeenCalledOnce() + expect(close.mock.calls.length).toBeGreaterThan(10) + }) + + // POSIX hosts exercise the REAL default plumbing end to end: the tsx-bootstrapped + // worker spawns, loads koffi, fails to load ole32.dll, and reports the error. + it.skipIf(process.platform === 'win32')('rejects through the real worker where the Win32 surface is unavailable', async () => { + await expect(pickWin32Directory(live())).rejects.toThrow('win32 folder dialog failed') + }, 30_000) + + // win32 hosts run the true COM smoke instead: a real dialog opens briefly + // and the abort service closes it (the same lever a disconnecting client pulls). + it.skipIf(process.platform !== 'win32')('opens and abort-closes a real dialog', async () => { + const controller = new AbortController() + setTimeout(() =>{ controller.abort() }, 400) + await expect(pickWin32Directory(controller.signal)).rejects.toThrow('native directory picker aborted') + }, 30_000) +}) diff --git a/packages/host/directory-picker-native/tsdown.config.ts b/packages/host/directory-picker-native/tsdown.config.ts index 4f280f8112..3ab92526e4 100644 --- a/packages/host/directory-picker-native/tsdown.config.ts +++ b/packages/host/directory-picker-native/tsdown.config.ts @@ -1,3 +1,18 @@ import { clientBundle } from '../../client/tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-host-directory-picker-native', ['lib/types/index.js', 'lib/types/invariant.js']) +// The Win32 dialog worker builds as its own CJS entry (mirroring +// dsh-workflow-workerthread's worker): path-loaded by the driver, inlining +// the dialog logic while koffi stays an external native require. +export default [ + ...clientBundle('@deepseek-ai/dsh-host-directory-picker-native', ['lib/types/index.js', 'lib/types/invariant.js']), + { + entry: ['lib/types/win32-dialog-worker.js'], + outDir: 'lib', + format: ['cjs'] as ['cjs'], + platform: 'node' as const, + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + }, +] diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6e1225f57f..ef0c42656d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3643,6 +3643,9 @@ importers: '@deepseek-ai/dsh-native-command': specifier: workspace:^ version: link:../../util/native-command + koffi: + specifier: ^3.1.0 + version: 3.1.1 devDependencies: '@deepseek-ai/dsh-client-runtime': specifier: workspace:^ @@ -3665,6 +3668,9 @@ importers: react: specifier: ^18.2.0 version: 18.3.1 + tsx: + specifier: ^4.19.2 + version: 4.22.4 packages/host/webserver: dependencies: diff --git a/vitest.config.ts b/vitest.config.ts index 2909fb7459..58d4a9837f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -73,6 +73,10 @@ const coverageExemptExcludes = coverageExemptRaw === '1' // 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. const processBoundTests = [ + // Spawns a nested worker that blocks in a native modal dialog on win32; + // under the threads pool the dialog thread outlives the test worker and + // wedges pool teardown, while a fork contains it. + 'packages/host/directory-picker-native/tests/win32-dialog.spec.ts', 'packages/subprocess/subprocess-local/tests/spawn.spec.ts', 'packages/context/time-context/tests/time-context.spec.ts', 'packages/llm/llm-pi-ai/tests/adapter.spec.ts', From 8e0880e30341d56ede8158fe69baa16805895852 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 00:11:23 +0800 Subject: [PATCH 49/61] test(picker): attach abort expectations before driving the close-budget race On a fast host the 1ms close budget can exhaust and reject between waitFor ticks; a rejection with no listener yet counted as an unhandled error in the Linux run. --- .../tests/win32-dialog.spec.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts index 33e2fa60a1..e3ea00d4a1 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts @@ -88,25 +88,29 @@ describe('pickWin32Directory', () => { it('services an abort by closing the dialog thread windows until the worker reports', async () => { const { worker, internals, close } = harness() const controller = new AbortController() - const picked = pickWin32Directory(controller.signal, internals) + // Attach the expectation BEFORE driving the race: on a fast host the + // close budget can exhaust (and reject) between waitFor ticks, and a + // rejection with no listener yet would count as unhandled. + const picked = expect(pickWin32Directory(controller.signal, internals)).rejects.toThrow('native directory picker aborted') worker.post({ kind: 'showing', threadId: 99 }) controller.abort() await vi.waitFor(() =>{ expect(close).toHaveBeenCalledWith(99) }) worker.post({ kind: 'done', path: null }) - await expect(picked).rejects.toThrow('native directory picker aborted') + await picked }) it('starts the close service on the showing notice when the abort came first', async () => { const closeFailures = vi.fn(async () => { throw new Error('window not there yet') }) const { worker, internals } = harness({ closeThreadWindows: closeFailures }) const controller = new AbortController() - const picked = pickWin32Directory(controller.signal, internals) + // Attached before the race for the same unhandled-rejection reason above. + const picked = expect(pickWin32Directory(controller.signal, internals)).rejects.toThrow('native directory picker aborted') controller.abort() expect(closeFailures).not.toHaveBeenCalled() worker.post({ kind: 'showing', threadId: 12 }) await vi.waitFor(() =>{ expect(closeFailures.mock.calls.length).toBeGreaterThan(1) }) worker.post({ kind: 'done', path: null }) - await expect(picked).rejects.toThrow('native directory picker aborted') + await picked }) it('terminates an unresponsive worker after the close budget', async () => { From fed3149ac4a9937ceff105be75945be81828b366 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 00:41:47 +0800 Subject: [PATCH 50/61] fix(picker): ship the dialog worker as the constrained ./worker artifact The workspace files constraint keys worker bundles on the ./worker export (lib/worker.cjs, the workflow-workerthread shape); the descriptive source entry stays win32-dialog-worker.ts and tsdown renames the bundle. --- packages/host/directory-picker-native/package.json | 6 +++++- .../host/directory-picker-native/src/win32-dialog-host.ts | 2 +- packages/host/directory-picker-native/tsdown.config.ts | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/host/directory-picker-native/package.json b/packages/host/directory-picker-native/package.json index 49033cdcf4..72e1d1be45 100644 --- a/packages/host/directory-picker-native/package.json +++ b/packages/host/directory-picker-native/package.json @@ -19,14 +19,18 @@ "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./worker": { + "types": "./lib/types/win32-dialog-worker.d.ts", + "default": "./lib/worker.cjs" + }, "./src/*": "./src/*", "./package.json": "./package.json" }, "files": [ "lib/index.js", "lib/invariant.js", + "lib/worker.cjs", "lib/client.js", - "lib/win32-dialog-worker.cjs", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" diff --git a/packages/host/directory-picker-native/src/win32-dialog-host.ts b/packages/host/directory-picker-native/src/win32-dialog-host.ts index cfaf07cc46..781cbc4b24 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-host.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-host.ts @@ -20,7 +20,7 @@ import type { Win32DialogWorkerData } from './win32-dialog-worker.ts' export function spawnDialogWorker(data: Win32DialogWorkerData): Worker { /* v8 ignore next 3 -- the built-output arm: tests always run unbuilt (src/) */ if (!import.meta.url.endsWith('.ts')) { - return new Worker(fileURLToPath(new URL('./win32-dialog-worker.cjs', import.meta.url)), { workerData: data }) + return new Worker(fileURLToPath(new URL('./worker.cjs', import.meta.url)), { workerData: data }) } const workerEntry = new URL('./win32-dialog-worker.ts', import.meta.url) const bootstrap = [ diff --git a/packages/host/directory-picker-native/tsdown.config.ts b/packages/host/directory-picker-native/tsdown.config.ts index 3ab92526e4..529fb7b2ac 100644 --- a/packages/host/directory-picker-native/tsdown.config.ts +++ b/packages/host/directory-picker-native/tsdown.config.ts @@ -6,7 +6,9 @@ import { clientBundle } from '../../client/tsdown.client.ts' export default [ ...clientBundle('@deepseek-ai/dsh-host-directory-picker-native', ['lib/types/index.js', 'lib/types/invariant.js']), { - entry: ['lib/types/win32-dialog-worker.js'], + // The artifact is lib/worker.cjs (the ./worker export the workspace + // constraint keys on), bundled from the descriptive source entry. + entry: { worker: 'lib/types/win32-dialog-worker.js' }, outDir: 'lib', format: ['cjs'] as ['cjs'], platform: 'node' as const, From 8500a2165823de9c9f4332c98ae5a9010a384ef1 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 20:40:10 +0800 Subject: [PATCH 51/61] fix(picker): pointer-width vtable offsets, COM apartment pairing, unconditional abort budget, and the full failure chain Review round two on the in-process dialog: - Vtable slots and out-pointers use koffi.sizeof('void *') instead of a hardcoded 8 - win32-ia32 (which Node and koffi both ship) would have read method pointers from the wrong address and crashed in-process before any fallback could run. - runFolderDialog pairs every successful (incl. S_FALSE) CoInitializeEx with CoUninitialize in the outermost finally, releasing the dialog first; a failed init is deliberately unpaired. Pinned across fake-bindings and mocked-koffi suites. - The abort close budget starts unconditionally: a worker hung before the showing notice (koffi import or COM init) now ends in terminate instead of a dangling promise; WM_CLOSE posting still waits for the thread id. - A triple miss (dialog + pwsh + 5.1) surfaces an AggregateError carrying all three causes - the in-process tier's reason was previously unrecoverable from the final PowerShell error. - The stray '=>{ ' formatter artifacts are normalized to real blocks. Both stale note claims from the review are fixed: the DPI note's Consequences no longer claims an ENOENT classification or zero new dependencies, and the 2026-07-27 picker note's Windows bullet now names the in-process primary and keeps the PowerShell chain as fallback (both languages, pairings re-recorded). --- ...26-08-01-windows-picker-pwsh-dpi.i18n.yaml | 4 +- .../2026-08-01-windows-picker-pwsh-dpi.md | 2 +- .../2026-08-01-windows-picker-pwsh-dpi.zh.md | 2 +- ...ative-workspace-directory-picker.i18n.yaml | 4 +- ...07-27-native-workspace-directory-picker.md | 4 +- ...27-native-workspace-directory-picker.zh.md | 4 +- .../src/native-picker.ts | 19 +++++++++- .../src/win32-dialog-bindings.ts | 12 +++++- .../src/win32-dialog-logic.ts | 34 +++++++++++------ .../src/win32-dialog-worker.ts | 4 +- .../src/win32-dialog.ts | 37 ++++++++++++++----- .../tests/native-picker.spec.ts | 12 +++++- .../tests/win32-dialog-bindings.spec.ts | 8 +++- .../tests/win32-dialog-logic.spec.ts | 27 +++++++++----- .../tests/win32-dialog.spec.ts | 24 ++++++++++-- 15 files changed, 147 insertions(+), 50 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml index d9f46441ac..9a86e1f729 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.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-01-windows-picker-pwsh-dpi.md -2026-08-01-windows-picker-pwsh-dpi.md: 1d9fd0a1b445a77b478f033d56169d6166c2b1bf -2026-08-01-windows-picker-pwsh-dpi.zh.md: 245991e7c8d081f3c91724c0dae1142d80883c1d +2026-08-01-windows-picker-pwsh-dpi.md: a941d5ea6e150d74fa2fa4dbd93b7e6b58a78eff +2026-08-01-windows-picker-pwsh-dpi.zh.md: 8383240c219d701aa9a8728cf1a7fb7f3a7c5433 diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md index 1d9fd0a1b4..a941d5ea6e 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md @@ -22,5 +22,5 @@ The PowerShell chain is now the FALLBACK tier below the in-process koffi dialog ## Consequences - Machines with PowerShell 7 get the modern folder picker; 5.1-only machines keep the legacy tree — now sharp — and the package README's Known Limitations documents the gap. -- No new packages or runtime dependencies; the fallback reuses the existing `ENOENT` classification and abort propagation. +- The PowerShell chain itself adds no packages or dependencies (koffi and tsx arrived with the in-process primary and belong to its note); the pwsh→5.1 hop triggers on ANY non-abort pwsh failure — no `ENOENT` classification remains on the win32 path — while abort propagation is unchanged. - The command boundary (`DirectoryPickerRunner`) pins the spawn order and script content in unit tests; real dialog rendering remains a manual Windows check, as before. diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md index 245991e7c8..8383240c21 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md @@ -22,5 +22,5 @@ PowerShell 链现在是进程内 koffi 对话框之下的回退层(见[进程 ## 后果 - 装有 PowerShell 7 的机器获得现代文件夹选择器;只有 5.1 的机器保留旧版树——但现在清晰了——包 README 的已知限制记录了该差距。 -- 无新增包或运行时依赖;回退复用既有的 `ENOENT` 分类与中止传播。 +- PowerShell 链本身不新增任何包或依赖(koffi 与 tsx 随进程内主层引入,归属其 Note);pwsh→5.1 的跳转在 pwsh 的任何非中止失败上触发——win32 路径上已不存在 `ENOENT` 分类——中止传播不变。 - 命令边界(`DirectoryPickerRunner`)在单元测试中固定启动顺序与脚本内容;真实对话框渲染仍与以前一样属于手动 Windows 检查。 diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml index 12cb856fe2..e177c663cc 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.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-27-native-workspace-directory-picker.md -2026-07-27-native-workspace-directory-picker.md: c18b4263d4e97290d69ac229e7423558bdb4c3b1 -2026-07-27-native-workspace-directory-picker.zh.md: 7267516d7eea4b3cfecc2ca8f18305896eaffede +2026-07-27-native-workspace-directory-picker.md: 45fa77b5519179e006f9109846a1602e6e22a6e2 +2026-07-27-native-workspace-directory-picker.zh.md: 2d6800d20b1f0dfe0b20ac9a5c90037599ece32a diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md index c18b4263d4..45fa77b551 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md @@ -27,10 +27,10 @@ The workspace manager must upsert the returned workspace before the selection ca The native dialog RPC is accepted only from a loopback socket with same-origin browser metadata. The RPC does not use the default 30-second request timeout because a system dialog may remain open indefinitely; caller and connection aborts still propagate to the platform process. -Platform adapters invoke native tools without a shell: +Platform adapters open the dialog without a shell — spawned native tools on POSIX, an in-process COM conversation on Windows: - macOS: `osascript` and the system folder chooser. -- Windows: `pwsh` (PowerShell 7) in STA mode with a Windows PowerShell 5.1 fallback, always DPI-aware ([picker fix](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)). +- Windows: the in-process koffi `IFileOpenDialog` worker with per-monitor-v2 DPI ([in-process dialog note](2026-08-02-win32-in-process-folder-dialog.md)); the PowerShell chain (`pwsh` in STA mode, then Windows PowerShell 5.1, both DPI-corrected) remains the fallback ([picker fix](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)). - Linux: `zenity`, with `kdialog` as a fallback when Zenity is unavailable. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md index 7267516d7e..2d6800d20b 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md @@ -27,10 +27,10 @@ Status: implemented 只有来自回环套接字、且携带同源浏览器元数据的请求才能调用原生对话框 RPC。该 RPC 不使用默认的 30 秒请求超时,因为系统对话框可能无限期保持打开;调用方中止或连接中止仍会传递至平台进程。 -平台适配器不经 shell,直接调用原生工具: +平台适配器不经 shell 打开对话框——POSIX 上 spawn 原生工具,Windows 上是进程内 COM 会话: - macOS:`osascript` 和系统文件夹选择器。 -- Windows:采用 STA 模式的 `pwsh`(PowerShell 7),并以 Windows PowerShell 5.1 回退,且始终 DPI aware(见[选择器修复](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))。 +- Windows:进程内 koffi `IFileOpenDialog` worker,带 per-monitor-v2 DPI(见[进程内对话框 Note](2026-08-02-win32-in-process-folder-dialog.md));PowerShell 链(STA 模式的 `pwsh`,再到 Windows PowerShell 5.1,均已修正 DPI)保留为回退(见[选择器修复](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))。 - Linux:使用 `zenity`;Zenity 不可用时回退到 `kdialog`。 ## 考虑过的替代方案 diff --git a/packages/host/directory-picker-native/src/native-picker.ts b/packages/host/directory-picker-native/src/native-picker.ts index 6cabf44ddb..4b4d75fe32 100644 --- a/packages/host/directory-picker-native/src/native-picker.ts +++ b/packages/host/directory-picker-native/src/native-picker.ts @@ -72,10 +72,12 @@ export async function pickNativeDirectory( // support. Any non-abort failure (koffi unavailable, ancient Windows, COM // refusal) falls back to the PowerShell chain below. const pickDialog = internals.pickWin32Dialog ?? pickWin32Directory + let dialogError: unknown try { return await pickDialog(signal) } catch (error: unknown) { rethrowIfAborted(signal, error) + dialogError = error } // PowerShell fallback: PowerShell 7 renders the modern IFileDialog folder @@ -100,14 +102,27 @@ export async function pickNativeDirectory( ' [Console]::WriteLine($dialog.SelectedPath)', '}', ].join('; ') + let pwshError: unknown try { const result = await run('pwsh.exe', ['-NoProfile', '-STA', '-Command', script], signal) return outputPath(result.stdout) } catch (error: unknown) { rethrowIfAborted(signal, error) + pwshError = error + } + try { + const result = await run('powershell.exe', ['-NoProfile', '-STA', '-Command', script], signal) + return outputPath(result.stdout) + } catch (error: unknown) { + rethrowIfAborted(signal, error) + // Triple miss: every tier failed. Surface all three causes — the + // in-process dialog's reason is otherwise unrecoverable from the last + // PowerShell error alone. + throw new AggregateError( + [dialogError, pwshError, error], + 'native directory picker failed: the in-process dialog and both PowerShell hosts failed', + ) } - const result = await run('powershell.exe', ['-NoProfile', '-STA', '-Command', script], signal) - return outputPath(result.stdout) } if (platform === 'linux') { diff --git a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts index a9b625812c..dc797a712e 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts @@ -23,6 +23,7 @@ interface Koffi { decode(value: unknown, offsetOrType: unknown, type?: unknown): unknown register(fn: (...args: unknown[]) => unknown, type: unknown): unknown unregister(callback: unknown): void + sizeof(type: string): number } const COINIT_APARTMENTTHREADED = 0x2 @@ -68,7 +69,11 @@ export async function loadWin32DialogBindings(): Promise { const user32 = koffi.load('user32.dll') const kernel32 = koffi.load('kernel32.dll') + // Vtable slots and out-pointers are pointer-width offsets: 8 on x64/arm64, + // 4 on ia32 — koffi reports the running process's width. + const pointerSize = koffi.sizeof('void *') const coInitializeEx = ole32.func('__stdcall', 'CoInitializeEx', 'int32', ['void *', 'uint32']) + const coUninitialize = ole32.func('__stdcall', 'CoUninitialize', 'void', []) const coCreateInstance = ole32.func('__stdcall', 'CoCreateInstance', 'int32', ['void *', 'void *', 'uint32', 'void *', 'void *']) const coTaskMemFree = ole32.func('__stdcall', 'CoTaskMemFree', 'void', ['void *']) const getCurrentThreadId = kernel32.func('__stdcall', 'GetCurrentThreadId', 'uint32', []) @@ -83,7 +88,7 @@ export async function loadWin32DialogBindings(): Promise { /** Bind vtable slot `slot` of COM object `self` to a caller through `proto`. */ const method = (self: unknown, slot: number, proto: unknown): (...args: unknown[]) => number => { const vtable = koffi.decode(self, 'void *') - const fn = koffi.decode(vtable, slot * 8, 'void *') + const fn = koffi.decode(vtable, slot * pointerSize, 'void *') return (...args: unknown[]) => koffi.call(fn, proto, self, ...args) as number } @@ -99,9 +104,12 @@ export async function loadWin32DialogBindings(): Promise { } }, coInitializeSta: () => coInitializeEx(null, COINIT_APARTMENTTHREADED) as number, + coUninitialize: () => { + coUninitialize() + }, currentThreadId: () => getCurrentThreadId() as number, createFolderDialog: (): Win32FolderDialog => { - const out = Buffer.alloc(8) + const out = Buffer.alloc(pointerSize) const created = coCreateInstance(CLSID_FILE_OPEN_DIALOG, null, CLSCTX_INPROC_SERVER, IID_IFILE_OPEN_DIALOG, out) as number if (created < 0) throw new Error(`CoCreateInstance(FileOpenDialog) failed: HRESULT 0x${(created >>> 0).toString(16)}`) const dialog = koffi.decode(out, 'void *') diff --git a/packages/host/directory-picker-native/src/win32-dialog-logic.ts b/packages/host/directory-picker-native/src/win32-dialog-logic.ts index cba0ca9f24..65be1149dc 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-logic.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-logic.ts @@ -59,6 +59,12 @@ export interface Win32DialogBindings { * @returns the call's HRESULT (`S_FALSE` re-entry is still a success). */ coInitializeSta(): number + /** + * `CoUninitialize` on the calling thread — COM requires one pairing call + * for every successful (including `S_FALSE`) `CoInitializeEx`, even on a + * thread that exits right after the conversation. + */ + coUninitialize(): void /** * `CoCreateInstance(CLSID_FileOpenDialog)`. * @returns the created dialog surface; throws when creation fails. @@ -100,18 +106,24 @@ export function runFolderDialog( ): string | null { bindings.setThreadDpiAwareness() check(bindings.coInitializeSta(), 'CoInitializeEx') - const dialog = bindings.createFolderDialog() + // From here the apartment is initialized (S_OK or S_FALSE) and must be + // uninitialized exactly once on every path. try { - check(dialog.setOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR), 'SetOptions') - check(dialog.setTitle(title), 'SetTitle') - onShowing(bindings.currentThreadId()) - const shown = dialog.show() - if (shown === HRESULT_CANCELLED) return null - check(shown, 'Show') - const result = dialog.resultPath() - check(result.hr, 'GetResult') - return result.path as string + const dialog = bindings.createFolderDialog() + try { + check(dialog.setOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR), 'SetOptions') + check(dialog.setTitle(title), 'SetTitle') + onShowing(bindings.currentThreadId()) + const shown = dialog.show() + if (shown === HRESULT_CANCELLED) return null + check(shown, 'Show') + const result = dialog.resultPath() + check(result.hr, 'GetResult') + return result.path as string + } finally { + dialog.release() + } } finally { - dialog.release() + bindings.coUninitialize() } } diff --git a/packages/host/directory-picker-native/src/win32-dialog-worker.ts b/packages/host/directory-picker-native/src/win32-dialog-worker.ts index 2e4ef64f6c..e978d305f3 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-worker.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-worker.ts @@ -28,7 +28,9 @@ const { title } = workerData as Win32DialogWorkerData void (async () => { try { const bindings = await loadWin32DialogBindings() - const path = runFolderDialog(bindings, title, (threadId) =>{ port.postMessage({ kind: 'showing', threadId } satisfies Win32DialogWorkerMessage) }) + const path = runFolderDialog(bindings, title, (threadId) => { + port.postMessage({ kind: 'showing', threadId } satisfies Win32DialogWorkerMessage) + }) port.postMessage({ kind: 'done', path } satisfies Win32DialogWorkerMessage) } catch (error: unknown) { const message = error instanceof Error ? (error.stack ?? error.message) : String(error) diff --git a/packages/host/directory-picker-native/src/win32-dialog.ts b/packages/host/directory-picker-native/src/win32-dialog.ts index 40b31e8d57..b97c3659fe 100644 --- a/packages/host/directory-picker-native/src/win32-dialog.ts +++ b/packages/host/directory-picker-native/src/win32-dialog.ts @@ -81,11 +81,20 @@ export async function pickWin32Directory( outcome() } + const postClose = (): void => { + // Before `showing` there is no window to close; the budget below still + // runs so a worker that never reports cannot dangle the pick. + if (dialogThreadId !== undefined) void closeWindows(dialogThreadId).catch(() => undefined) + } + + // Sole caller: the once-registered abort listener, so no re-entry guard. const serviceAbort = (): void => { let attempts = 0 // The `showing` notice precedes the blocking `Show`, so the very first // WM_CLOSE can race the window's creation; re-post until the worker - // reports back, then force-terminate as a last resort. + // reports back, then force-terminate as a last resort. The budget is + // unconditional — an abort before `showing` (worker hung in koffi or + // COM init) still ends in terminate instead of a dangling promise. closeTimer = setInterval(() => { attempts += 1 if (attempts > CLOSE_MAX_ATTEMPTS) { @@ -95,14 +104,13 @@ export async function pickWin32Directory( }) return } - void closeWindows(dialogThreadId as number).catch(() => undefined) + postClose() }, closeRetryMs) - void closeWindows(dialogThreadId as number).catch(() => undefined) + postClose() } const onAbort = (): void => { - if (dialogThreadId !== undefined) serviceAbort() - // Not shown yet: the `showing` handler below starts the service loop. + serviceAbort() } signal.addEventListener('abort', onAbort, { once: true }) @@ -110,7 +118,8 @@ export async function pickWin32Directory( switch (message.kind) { case 'showing': dialogThreadId = message.threadId - if (signal.aborted) serviceAbort() + // An abort that raced ahead of this notice now has a window to hit. + if (signal.aborted) postClose() return case 'done': settle(() => { @@ -119,10 +128,20 @@ export async function pickWin32Directory( }) return case 'error': - settle(() =>{ reject(new Error(`win32 folder dialog failed: ${message.message}`)) }) + settle(() => { + reject(new Error(`win32 folder dialog failed: ${message.message}`)) + }) } }) - worker.on('error', (error: Error) =>{ settle(() =>{ reject(error) }) }) - worker.on('exit', () =>{ settle(() =>{ reject(new Error('win32 folder dialog worker exited before reporting a result')) }) }) + worker.on('error', (error: Error) => { + settle(() => { + reject(error) + }) + }) + worker.on('exit', () => { + settle(() => { + reject(new Error('win32 folder dialog worker exited before reporting a result')) + }) + }) }) } diff --git a/packages/host/directory-picker-native/tests/native-picker.spec.ts b/packages/host/directory-picker-native/tests/native-picker.spec.ts index 7c51d552d4..64732e4e17 100644 --- a/packages/host/directory-picker-native/tests/native-picker.spec.ts +++ b/packages/host/directory-picker-native/tests/native-picker.spec.ts @@ -97,10 +97,16 @@ describe('native directory picker', () => { .mockResolvedValueOnce({ stdout: '', stderr: '' }) await expect(pickNativeDirectory(signal(), { platform: 'win32', run: cancelled, pickWin32Dialog: noDialog })).resolves.toBeNull() + // Triple miss: the surfaced AggregateError carries all three causes, + // including the otherwise-lost in-process dialog failure. const failed = vi.fn() .mockRejectedValueOnce(failure('ENOENT')) .mockRejectedValueOnce(failure(2)) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run: failed, pickWin32Dialog: noDialog })).rejects.toThrow('command failed') + const tripleMiss = await pickNativeDirectory(signal(), { platform: 'win32', run: failed, pickWin32Dialog: noDialog }) + .then(() => { throw new Error('expected rejection') }, (error: unknown) => error as AggregateError) + expect(tripleMiss.message).toContain('the in-process dialog and both PowerShell hosts failed') + expect((tripleMiss.errors[0] as Error).message).toBe('dialog unavailable') + expect((tripleMiss.errors[2] as Error).message).toContain('command failed') }) it('wires the real Win32 dialog as the default tier', async () => { @@ -153,7 +159,9 @@ describe('native directory picker', () => { execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { callback(commandError, 'partial output', 'failure details') }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', pickWin32Dialog: noDialog })).rejects.toMatchObject({ + const surfaced = await pickNativeDirectory(signal(), { platform: 'win32', pickWin32Dialog: noDialog }) + .then(() => { throw new Error('expected rejection') }, (error: unknown) => error as AggregateError) + expect(surfaced.errors[2]).toMatchObject({ message: 'powershell failed', cause: commandError, code: 7, stdout: 'partial output', stderr: 'failure details', }) diff --git a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts index d23b43011a..799c24a062 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts @@ -31,6 +31,7 @@ interface ComWorld { posted: { hwnd: unknown; message: number }[] registered: number unregistered: number + uninitialized: number } function comWorld(overrides: Partial = {}): ComWorld { @@ -39,7 +40,7 @@ function comWorld(overrides: Partial = {}): ComWorld { hasThreadDpi: true, enumThrows: false, path: 'C:\\选中\\directory', titles: [], options: [], dpiContexts: [], freed: [], released: [], posted: [], - registered: 0, unregistered: 0, + registered: 0, unregistered: 0, uninitialized: 0, ...overrides, } } @@ -85,6 +86,7 @@ function installFakeKoffi(world: ComWorld): void { func: (_convention: string, name: string, _result: string, _args: string[]) => { switch (name) { case 'CoInitializeEx': return () => world.coInitHr + case 'CoUninitialize': return () => { world.uninitialized += 1 } case 'CoCreateInstance': return (...args: unknown[]) => { if (world.coCreateHr < 0) return world.coCreateHr outBuffers.set(args[4], dialogPtr) @@ -109,6 +111,7 @@ function installFakeKoffi(world: ComWorld): void { }), proto: (declaration: string) => ({ declaration }), pointer: (type: unknown) => type, + sizeof: (type: string) => { void type; return 8 }, register: (fn: (hwnd: unknown, lparam: unknown) => number) => { world.registered += 1; return { fn } }, unregister: () => { world.unregistered += 1 }, decode: (value: unknown, offsetOrType: unknown): unknown => { @@ -153,6 +156,7 @@ describe('loadWin32DialogBindings over the fake COM world', () => { expect(showing).toHaveBeenCalledWith(31337) expect(world.freed).toHaveLength(1) expect(world.released).toEqual(['item', 'dialog']) + expect(world.uninitialized).toBe(1) }) it('maps dismissal, missing DPI support, and the S_FALSE CoInitializeEx', async () => { @@ -163,6 +167,7 @@ describe('loadWin32DialogBindings over the fake COM world', () => { expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBeNull() expect(world.dpiContexts).toEqual([]) expect(world.released).toEqual(['dialog']) + expect(world.uninitialized).toBe(1) }) it('surfaces creation and extraction failures as HRESULT errors', async () => { @@ -225,6 +230,7 @@ describe('the worker entry over a mocked thread boundary', () => { loadWin32DialogBindings: async () => ({ setThreadDpiAwareness: () => undefined, coInitializeSta: () => 0, + coUninitialize: () => undefined, currentThreadId: () => 11, createFolderDialog: () => ({ setOptions: () => 0, diff --git a/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts index c24a79ebc1..c214245de6 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts @@ -16,6 +16,7 @@ interface FakeWorld { bindings: Win32DialogBindings dpi: ReturnType createDialog: ReturnType + uninitialize: ReturnType dialog: { setOptions: ReturnType setTitle: ReturnType @@ -36,21 +37,25 @@ function world(overrides: Partial = {}, coInit = 0): FakeWorl } const dpi = vi.fn() const createDialog = vi.fn(() => dialog) + const uninitialize = vi.fn() const bindings: Win32DialogBindings = { setThreadDpiAwareness: dpi, coInitializeSta: vi.fn(() => coInit), + coUninitialize: uninitialize, createFolderDialog: createDialog, currentThreadId: vi.fn(() => 4242), } - return { bindings, dpi, createDialog, dialog: dialog as FakeWorld['dialog'] } + return { bindings, dpi, createDialog, uninitialize, dialog: dialog as FakeWorld['dialog'] } } describe('runFolderDialog', () => { - it('sequences DPI, STA, options, title, show, and result extraction', () => { - const { bindings, dpi, dialog } = world() + it('sequences DPI, STA, options, title, show, result extraction, and apartment teardown', () => { + const { bindings, dpi, dialog, uninitialize } = world() const showing = vi.fn() expect(runFolderDialog(bindings, 'Pick', showing)).toBe('C:\\picked\\目录') expect(dpi).toHaveBeenCalledOnce() + expect(uninitialize).toHaveBeenCalledOnce() + expect(dialog.release.mock.invocationCallOrder[0]).toBeLessThan(uninitialize.mock.invocationCallOrder[0] as number) expect(dialog.setOptions).toHaveBeenCalledWith(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR) expect(dialog.setTitle).toHaveBeenCalledWith('Pick') expect(showing).toHaveBeenCalledWith(4242) @@ -58,11 +63,12 @@ describe('runFolderDialog', () => { expect(dialog.release).toHaveBeenCalledOnce() }) - it('maps the cancelled HRESULT to null and still releases the dialog', () => { - const { bindings, dialog } = world({ show: vi.fn(() => HRESULT_CANCELLED) }) + it('maps the cancelled HRESULT to null and still releases the dialog and apartment', () => { + const { bindings, dialog, uninitialize } = world({ show: vi.fn(() => HRESULT_CANCELLED) }) expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBeNull() expect(dialog.resultPath).not.toHaveBeenCalled() expect(dialog.release).toHaveBeenCalledOnce() + expect(uninitialize).toHaveBeenCalledOnce() }) it('accepts the S_FALSE re-entry HRESULT from CoInitializeEx', () => { @@ -70,10 +76,12 @@ describe('runFolderDialog', () => { expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBe('C:\\picked\\目录') }) - it('throws on a failing CoInitializeEx without creating a dialog', () => { - const { bindings, createDialog } = world({}, E_FAIL) + it('throws on a failing CoInitializeEx without creating a dialog or uninitializing', () => { + const { bindings, createDialog, uninitialize } = world({}, E_FAIL) expect(() => runFolderDialog(bindings, 'Pick', vi.fn())).toThrow('CoInitializeEx failed: HRESULT 0x80004005') expect(createDialog).not.toHaveBeenCalled() + // A failed CoInitializeEx must NOT be paired with CoUninitialize. + expect(uninitialize).not.toHaveBeenCalled() }) it.each([ @@ -81,10 +89,11 @@ describe('runFolderDialog', () => { ['SetTitle', { setTitle: vi.fn(() => E_FAIL) }], ['Show', { show: vi.fn(() => E_FAIL) }], ['GetResult', { resultPath: vi.fn(() => ({ hr: E_FAIL })) }], - ] satisfies [string, Partial][])('releases the dialog when %s fails', (what, overrides) => { - const { bindings, dialog } = world(overrides) + ] satisfies [string, Partial][])('releases the dialog and apartment when %s fails', (what, overrides) => { + const { bindings, dialog, uninitialize } = world(overrides) expect(() => runFolderDialog(bindings, 'Pick', vi.fn())).toThrow(`${what} failed: HRESULT 0x80004005`) expect(dialog.release).toHaveBeenCalledOnce() + expect(uninitialize).toHaveBeenCalledOnce() void bindings }) }) diff --git a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts index e3ea00d4a1..598386b1a7 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts @@ -94,7 +94,9 @@ describe('pickWin32Directory', () => { const picked = expect(pickWin32Directory(controller.signal, internals)).rejects.toThrow('native directory picker aborted') worker.post({ kind: 'showing', threadId: 99 }) controller.abort() - await vi.waitFor(() =>{ expect(close).toHaveBeenCalledWith(99) }) + await vi.waitFor(() => { + expect(close).toHaveBeenCalledWith(99) + }) worker.post({ kind: 'done', path: null }) await picked }) @@ -108,11 +110,25 @@ describe('pickWin32Directory', () => { controller.abort() expect(closeFailures).not.toHaveBeenCalled() worker.post({ kind: 'showing', threadId: 12 }) - await vi.waitFor(() =>{ expect(closeFailures.mock.calls.length).toBeGreaterThan(1) }) + await vi.waitFor(() => { + expect(closeFailures.mock.calls.length).toBeGreaterThan(1) + }) worker.post({ kind: 'done', path: null }) await picked }) + it('terminates a worker that never reports showing after an abort', async () => { + // The budget runs without a thread id (nothing to WM_CLOSE yet), so a + // worker hung before `showing` cannot dangle the pick. + const { worker, internals, close } = harness() + const controller = new AbortController() + const picked = expect(pickWin32Directory(controller.signal, internals)).rejects.toThrow('dialog unresponsive; worker terminated') + controller.abort() + await picked + expect(worker.terminate).toHaveBeenCalledOnce() + expect(close).not.toHaveBeenCalled() + }) + it('terminates an unresponsive worker after the close budget', async () => { const { worker, internals, close } = harness() const controller = new AbortController() @@ -134,7 +150,9 @@ describe('pickWin32Directory', () => { // and the abort service closes it (the same lever a disconnecting client pulls). it.skipIf(process.platform !== 'win32')('opens and abort-closes a real dialog', async () => { const controller = new AbortController() - setTimeout(() =>{ controller.abort() }, 400) + setTimeout(() => { + controller.abort() + }, 400) await expect(pickWin32Directory(controller.signal)).rejects.toThrow('native directory picker aborted') }, 30_000) }) From e182f032309b5b0ea238e63888f150a2f34bc48a Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 21:42:05 +0800 Subject: [PATCH 52/61] fix(picker): cascade thread DPI contexts and harden the round-three review points - setThreadDpiAwareness checks SetThreadDpiAwarenessContext's return value and cascades per-monitor-v2 -> per-monitor -> system-aware; DPI stays a deliberate cosmetic best-effort - a host accepting none (or lacking the API, pre-1607) still gets the modern dialog instead of a downgrade to the legacy fallback chain over a cosmetic concern. - The mocked-koffi world now uses a distinctive 4-byte pointer width and rejects mis-sized out-buffers and mis-divided vtable offsets, so a regression to hardcoded 8s fails the suite (the ia32 bug class). - A keyless built-worker e2e guard loads lib/worker.cjs under plain worker_threads on POSIX (the workflow-workerthread shape). - The 'loaded lazily' module claims are reworded to attribute laziness to the dynamic import('koffi') calls, and the discarded close-attempt rejection is named at its catch. --- ...2-win32-in-process-folder-dialog.i18n.yaml | 4 +- ...26-08-02-win32-in-process-folder-dialog.md | 4 +- ...08-02-win32-in-process-folder-dialog.zh.md | 4 +- .../directory-picker-native/README.i18n.yaml | 4 +- .../host/directory-picker-native/README.md | 2 +- .../host/directory-picker-native/README.zh.md | 2 +- .../src/win32-dialog-bindings.ts | 34 ++++++++--- .../src/win32-dialog-host.ts | 9 +-- .../src/win32-dialog-logic.ts | 9 ++- .../src/win32-dialog.ts | 4 +- .../tests/built-worker.e2e.ts | 31 ++++++++++ .../tests/win32-dialog-bindings.spec.ts | 56 ++++++++++++++++--- 12 files changed, 128 insertions(+), 35 deletions(-) create mode 100644 packages/host/directory-picker-native/tests/built-worker.e2e.ts diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml index a3bdfc2a97..656ee92a65 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.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-02-win32-in-process-folder-dialog.md -2026-08-02-win32-in-process-folder-dialog.md: fa896d198913f58b22f9186696daec27026bb50f -2026-08-02-win32-in-process-folder-dialog.zh.md: 31077d8d6a3907d955180fda290f92c4cf41e5b9 +2026-08-02-win32-in-process-folder-dialog.md: 96bc213ea7cddef6223aa3be69e56688dc9c4724 +2026-08-02-win32-in-process-folder-dialog.zh.md: a3dfad2ef73cb28ae8c4c47b6380740aab6de5c3 diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md index fa896d1989..96bc213ea7 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md @@ -10,7 +10,7 @@ The Windows directory picker's primary tier was a spawned PowerShell script arou ## Decision -`packages/host/directory-picker-native` now opens `IFileOpenDialog` (`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`) in-process through koffi — already a workspace dependency for the repo's other `win32.ts` surfaces — as the primary win32 tier. The COM conversation runs on a `worker_threads` worker so the modal `Show` never blocks the host event loop; the worker posts its native thread id before blocking, and the driver services aborts by re-posting `WM_CLOSE` to that thread's windows (`EnumThreadWindows`), terminating and unrefing the worker only when the close budget is exhausted (Node cannot interrupt native calls, so an unclosable worker must never hold the process open). The worker thread opts into per-monitor-v2 DPI (`SetThreadDpiAwarenessContext`), a strict upgrade over the script's system-DPI ceiling. The module split keeps coverage honest on every host: `win32-dialog-logic.ts` (pure sequencing) and `win32-dialog.ts` (driver) test against fakes anywhere; `win32-dialog-bindings.ts` tests against a mocked `koffi` COM world (the `dsh-session-persistence-jsonl` technique); POSIX hosts run the real spawn plumbing to its koffi-load rejection; win32 hosts run a real open-and-abort-close smoke. That smoke lives in `processBoundTests`: under the threads pool a worker blocked in a native modal wedges pool teardown, while a fork contains it. The PowerShell chain (see the [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)) stays as the fallback tier, its trigger widened from `ENOENT` to any pwsh failure, which also closes the PowerShell 6 regression. +`packages/host/directory-picker-native` now opens `IFileOpenDialog` (`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`) in-process through koffi — already a workspace dependency for the repo's other `win32.ts` surfaces — as the primary win32 tier. The COM conversation runs on a `worker_threads` worker so the modal `Show` never blocks the host event loop; the worker posts its native thread id before blocking, and the driver services aborts by re-posting `WM_CLOSE` to that thread's windows (`EnumThreadWindows`), terminating and unrefing the worker only when the close budget is exhausted (Node cannot interrupt native calls, so an unclosable worker must never hold the process open). The worker thread opts into the best thread DPI awareness the host accepts (`SetThreadDpiAwarenessContext`, cascading per-monitor-v2 → per-monitor → system-aware with the return value checked), a strict upgrade over the script's system-DPI ceiling; DPI stays a cosmetic best-effort — a host accepting none of them still gets the modern dialog rather than a downgrade to the fallback chain. The module split keeps coverage honest on every host: `win32-dialog-logic.ts` (pure sequencing) and `win32-dialog.ts` (driver) test against fakes anywhere; `win32-dialog-bindings.ts` tests against a mocked `koffi` COM world (the `dsh-session-persistence-jsonl` technique); POSIX hosts run the real spawn plumbing to its koffi-load rejection; win32 hosts run a real open-and-abort-close smoke. That smoke lives in `processBoundTests`: under the threads pool a worker blocked in a native modal wedges pool teardown, while a fork contains it. The PowerShell chain (see the [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)) stays as the fallback tier, its trigger widened from `ENOENT` to any pwsh failure, which also closes the PowerShell 6 regression. ## Alternatives considered @@ -21,6 +21,6 @@ The Windows directory picker's primary tier was a spawned PowerShell script arou ## Consequences -- Every Windows machine gets the modern dialog with per-monitor-v2 DPI, PowerShell installed or not; the PowerShell tiers only serve hosts where koffi cannot drive COM. +- Every Windows machine gets the modern dialog with the best DPI awareness it supports (per-monitor-v2 on 1703+), PowerShell installed or not; the PowerShell tiers only serve hosts where koffi cannot drive COM. - Real dialog rendering and the selection path stay a manual Windows check (the auto-close smoke proves open/abort/unwind); a wedged abort can leak one dialog thread until process exit, documented in the package README. - The COM vtable slots and GUIDs used are frozen Windows ABI (Vista); a koffi signature mistake is an in-process crash risk contained to the worker thread and caught by the win32 smoke before shipping. diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md index 31077d8d6a..a3dfad2ef7 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md @@ -10,7 +10,7 @@ Windows 目录选择器的主层此前是围绕 WinForms `FolderBrowserDialog` ## 决策 -`packages/host/directory-picker-native` 现在经 koffi——它已是仓库其他 `win32.ts` 面的工作区依赖——在进程内打开 `IFileOpenDialog`(`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`),作为 win32 主层。COM 会话运行在 `worker_threads` worker 上,模态 `Show` 永不阻塞宿主事件循环;worker 在阻塞前上报其原生线程 id,driver 通过向该线程的窗口反复投递 `WM_CLOSE`(`EnumThreadWindows`)来服务中止,仅当关闭预算耗尽时才 terminate 并 unref worker(Node 无法打断原生调用,关不掉的 worker 决不能拖住进程退出)。worker 线程启用 per-monitor-v2 DPI(`SetThreadDpiAwarenessContext`),严格优于脚本的系统 DPI 上限。模块切分让覆盖率在任何主机上都诚实:`win32-dialog-logic.ts`(纯时序)与 `win32-dialog.ts`(driver)在任何平台对假件测试;`win32-dialog-bindings.ts` 对 mock 的 `koffi` COM 世界测试(`dsh-session-persistence-jsonl` 的技法);POSIX 主机把真实 spawn 管道跑到 koffi 加载失败的拒绝;win32 主机跑真实的"打开并中止关闭"冒烟。该冒烟位于 `processBoundTests`:threads 池下阻塞在原生模态中的 worker 会卡死池的收尾,fork 则能容纳它。PowerShell 链(见 [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))保留为回退层,触发条件从 `ENOENT` 拓宽为 pwsh 的任何失败,同时关闭了 PowerShell 6 回归。 +`packages/host/directory-picker-native` 现在经 koffi——它已是仓库其他 `win32.ts` 面的工作区依赖——在进程内打开 `IFileOpenDialog`(`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`),作为 win32 主层。COM 会话运行在 `worker_threads` worker 上,模态 `Show` 永不阻塞宿主事件循环;worker 在阻塞前上报其原生线程 id,driver 通过向该线程的窗口反复投递 `WM_CLOSE`(`EnumThreadWindows`)来服务中止,仅当关闭预算耗尽时才 terminate 并 unref worker(Node 无法打断原生调用,关不掉的 worker 决不能拖住进程退出)。worker 线程启用宿主接受的最佳线程 DPI 感知(`SetThreadDpiAwarenessContext`,按 per-monitor-v2 → per-monitor → system-aware 级联并检查返回值),严格优于脚本的系统 DPI 上限;DPI 保持为纯外观的 best-effort——全部不被接受的宿主仍得到现代对话框,而不会降级到回退链。模块切分让覆盖率在任何主机上都诚实:`win32-dialog-logic.ts`(纯时序)与 `win32-dialog.ts`(driver)在任何平台对假件测试;`win32-dialog-bindings.ts` 对 mock 的 `koffi` COM 世界测试(`dsh-session-persistence-jsonl` 的技法);POSIX 主机把真实 spawn 管道跑到 koffi 加载失败的拒绝;win32 主机跑真实的"打开并中止关闭"冒烟。该冒烟位于 `processBoundTests`:threads 池下阻塞在原生模态中的 worker 会卡死池的收尾,fork 则能容纳它。PowerShell 链(见 [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))保留为回退层,触发条件从 `ENOENT` 拓宽为 pwsh 的任何失败,同时关闭了 PowerShell 6 回归。 ## 考虑过的替代方案 @@ -21,6 +21,6 @@ Windows 目录选择器的主层此前是围绕 WinForms `FolderBrowserDialog` ## 后果 -- 每台 Windows 机器都得到带 per-monitor-v2 DPI 的现代对话框,无论是否安装 PowerShell;PowerShell 层只服务 koffi 无法驱动 COM 的主机。 +- 每台 Windows 机器都得到带其所支持的最佳 DPI 感知(1703+ 为 per-monitor-v2)的现代对话框,无论是否安装 PowerShell;PowerShell 层只服务 koffi 无法驱动 COM 的主机。 - 真实对话框渲染与选中路径仍是手动 Windows 检查(自动关闭冒烟证明打开/中止/收尾);卡死的中止可能泄漏一个对话框线程直到进程退出,已记录于包 README。 - 所用 COM vtable 槽位与 GUID 是冻结的 Windows ABI(Vista 起);koffi 签名错误是被限制在 worker 线程内的进程内崩溃风险,并在交付前被 win32 冒烟捕获。 diff --git a/packages/host/directory-picker-native/README.i18n.yaml b/packages/host/directory-picker-native/README.i18n.yaml index acf7f85d88..60f534e83b 100644 --- a/packages/host/directory-picker-native/README.i18n.yaml +++ b/packages/host/directory-picker-native/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/host/directory-picker-native/README.md -README.md: 0d0fe8d3a049d6fbc47eee314f9782352651247d -README.zh.md: 82f51976afe2e57699c1bd62d11142106b082e9b +README.md: d48622dead56cce842e0bef0207079ff85b22588 +README.zh.md: 33cb11b4e747b2d98fc1bf179a52e095dcc9bc31 diff --git a/packages/host/directory-picker-native/README.md b/packages/host/directory-picker-native/README.md index 0d0fe8d3a0..d48622dead 100644 --- a/packages/host/directory-picker-native/README.md +++ b/packages/host/directory-picker-native/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Windows opens the modern `IFileOpenDialog` in-process — a koffi-driven COM conversation on a worker thread with per-monitor-v2 DPI awareness, aborted by posting `WM_CLOSE` to the dialog thread — and falls back to a PowerShell-hosted dialog (`pwsh`, then Windows PowerShell 5.1, which every Windows ships) whenever that native surface is unavailable; a resolvable `pwsh` that cannot deliver the dialog (PowerShell 6 has no WinForms) falls through the same way. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md). +The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Windows opens the modern `IFileOpenDialog` in-process — a koffi-driven COM conversation on a worker thread with the best thread DPI awareness the host accepts (per-monitor-v2 first), aborted by posting `WM_CLOSE` to the dialog thread — and falls back to a PowerShell-hosted dialog (`pwsh`, then Windows PowerShell 5.1, which every Windows ships) whenever that native surface is unavailable; a resolvable `pwsh` that cannot deliver the dialog (PowerShell 6 has no WinForms) falls through the same way. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md). **Dual-face package**: the browser half (`./client`) registers a renderless flow occupant into [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes — each `open` request drives `host.pickDirectory` and reports the one outcome (picked path / cancel / failure) through the hole's owner conversation. One cordis.yml row therefore composes both sides of the native interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). diff --git a/packages/host/directory-picker-native/README.zh.md b/packages/host/directory-picker-native/README.zh.md index 82f51976af..33cb11b4e7 100644 --- a/packages/host/directory-picker-native/README.zh.md +++ b/packages/host/directory-picker-native/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。Windows 在进程内打开现代 `IFileOpenDialog`——由 koffi 在 worker 线程上驱动的 COM 会话,带 per-monitor-v2 DPI 感知,中止时向对话框线程投递 `WM_CLOSE`——当该原生面不可用时回退到 PowerShell 承载的对话框(先 `pwsh`,再回退到每台 Windows 都自带的 Windows PowerShell 5.1);可解析但无法呈现对话框的 `pwsh`(PowerShell 6 没有 WinForms)同样落入该回退。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。 +[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。Windows 在进程内打开现代 `IFileOpenDialog`——由 koffi 在 worker 线程上驱动的 COM 会话,采用宿主接受的最佳线程 DPI 感知(优先 per-monitor-v2),中止时向对话框线程投递 `WM_CLOSE`——当该原生面不可用时回退到 PowerShell 承载的对话框(先 `pwsh`,再回退到每台 Windows 都自带的 Windows PowerShell 5.1);可解析但无法呈现对话框的 `pwsh`(PowerShell 6 没有 WinForms)同样落入该回退。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。 **双面包**:browser half(`./client`)向 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞注册一个无渲染的流程占用者——每次 `open` 请求驱动 `host.pickDirectory`,并经洞的 owner 会话上报唯一结果(所选路径/取消/失败)。因此一行 cordis.yml 同时组合原生交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 diff --git a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts index dc797a712e..03980af2a4 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts @@ -1,9 +1,10 @@ /** * koffi-backed Win32 bindings for the folder dialog: the COM vtable calls * behind {@link Win32DialogBindings} plus the cross-thread window closer the - * driver uses to service aborts. Loaded lazily and only on win32 (the dialog - * worker and the driver's abort path), so non-Windows processes never load - * koffi — the same containment as the repo's other `win32.ts` modules. + * driver uses to service aborts. The module loads on every platform; koffi + * itself is imported lazily inside each function, so non-Windows processes + * never load it — the same containment as the repo's other `win32.ts` + * modules. * * The COM surface used here (IModalWindow/IFileDialog/IFileOpenDialog and * IShellItem vtable order, the GUIDs, `FOS_*` and `SIGDN_FILESYSPATH`) is @@ -29,7 +30,14 @@ interface Koffi { const COINIT_APARTMENTTHREADED = 0x2 const CLSCTX_INPROC_SERVER = 0x1 const SIGDN_FILESYSPATH = 0x80058000 | 0 -const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4 +/** + * Thread DPI awareness contexts, best first: per-monitor-v2 (Windows 10 + * 1703+), per-monitor (1607+), then system-aware. `SetThreadDpiAwarenessContext` + * returns NULL for an unsupported context instead of throwing, so the caller + * cascades to the best one the host accepts; DPI stays a cosmetic + * best-effort — an unsupported host still gets the modern dialog. + */ +const DPI_AWARENESS_CONTEXTS = [-4, -3, -2] const WM_CLOSE = 0x10 /** IFileOpenDialog vtable slots (IUnknown 0-2, IModalWindow 3, IFileDialog 4+). */ @@ -94,14 +102,22 @@ export async function loadWin32DialogBindings(): Promise { return { setThreadDpiAwareness: () => { + let setContext: KoffiFunction try { - const setThreadDpiAwarenessContext = user32.func('__stdcall', 'SetThreadDpiAwarenessContext', 'void *', ['intptr']) - setThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) + setContext = user32.func('__stdcall', 'SetThreadDpiAwarenessContext', 'void *', ['intptr']) } catch { - // SetThreadDpiAwarenessContext absent (Windows 10 pre-1703): the - // dialog renders at system DPI; nothing else can fail here because - // user32 itself loaded above. + // Symbol absent (pre-1607 Windows): no per-thread DPI control exists. + // Proceed anyway — the cost is a blurry dialog above 100 % scaling on + // museum hosts, and the modern picker still beats dropping to the + // legacy 5.1 tree over a cosmetic concern. + return } + for (const context of DPI_AWARENESS_CONTEXTS) { + if (setContext(context) !== null) return + } + // Unreachable in practice (SYSTEM_AWARE is accepted wherever the symbol + // exists); if a host ever refuses everything, the dialog still works — + // just without a DPI opt-in. }, coInitializeSta: () => coInitializeEx(null, COINIT_APARTMENTTHREADED) as number, coUninitialize: () => { diff --git a/packages/host/directory-picker-native/src/win32-dialog-host.ts b/packages/host/directory-picker-native/src/win32-dialog-host.ts index 781cbc4b24..ff02a93105 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-host.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-host.ts @@ -1,9 +1,10 @@ /** * Real-process half of the Win32 dialog driver: spawn the dialog worker - * (source or built plane) and close a dialog thread's windows. Loaded lazily - * and only on the win32 default path, so non-Windows processes never touch - * worker or koffi machinery; the driver's logic is tested against fakes of - * this surface instead. + * (source or built plane) and close a dialog thread's windows. The module + * itself loads everywhere (the import chain from native-picker.ts is + * static); what stays win32-only is koffi, imported dynamically inside the + * bindings' functions. The driver's logic is tested against fakes of this + * surface instead. */ import { fileURLToPath } from 'node:url' diff --git a/packages/host/directory-picker-native/src/win32-dialog-logic.ts b/packages/host/directory-picker-native/src/win32-dialog-logic.ts index 65be1149dc..aa9d1445c4 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-logic.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-logic.ts @@ -49,9 +49,12 @@ export interface Win32FolderDialog { /** The thread-level native surface the dialog sequencing runs against. */ export interface Win32DialogBindings { /** - * Best-effort per-monitor-v2 DPI opt-in for the calling thread. Absent - * before Windows 10 1703; implementations swallow only that absence, so an - * old host merely renders the dialog at system DPI. + * Opt the calling thread into the best supported DPI awareness + * (per-monitor-v2, then per-monitor, then system-aware), checking each + * call's result. Best-effort on purpose: a host accepting none of them + * (or lacking the API, pre-1607) still shows the modern dialog — possibly + * blurry above 100 % scaling — because a cosmetic degradation must not + * cost the tier. */ setThreadDpiAwareness(): void /** diff --git a/packages/host/directory-picker-native/src/win32-dialog.ts b/packages/host/directory-picker-native/src/win32-dialog.ts index b97c3659fe..a3aee2268a 100644 --- a/packages/host/directory-picker-native/src/win32-dialog.ts +++ b/packages/host/directory-picker-native/src/win32-dialog.ts @@ -83,7 +83,9 @@ export async function pickWin32Directory( const postClose = (): void => { // Before `showing` there is no window to close; the budget below still - // runs so a worker that never reports cannot dangle the pick. + // runs so a worker that never reports cannot dangle the pick. A + // rejected close attempt (EnumThreadWindows/PostMessageW refusing) is + // discarded: the interval retries it and terminate is the backstop. if (dialogThreadId !== undefined) void closeWindows(dialogThreadId).catch(() => undefined) } diff --git a/packages/host/directory-picker-native/tests/built-worker.e2e.ts b/packages/host/directory-picker-native/tests/built-worker.e2e.ts new file mode 100644 index 0000000000..03ae060f77 --- /dev/null +++ b/packages/host/directory-picker-native/tests/built-worker.e2e.ts @@ -0,0 +1,31 @@ +/** + * Keyless built-artifact guard (the `dsh-workflow-workerthread` built-worker + * shape): plain `worker_threads` loads `lib/worker.cjs` and the bundle reaches + * its real koffi requires. POSIX hosts prove the load path end to end through + * the deterministic ole32 rejection; win32 skips (a real dialog would open), + * where the win32-only smoke in win32-dialog.spec.ts covers the source plane + * instead. Skips until a build produces the artifact. + */ + +import { existsSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { Worker } from 'node:worker_threads' +import { describe, expect, it } from 'vitest' +import type { Win32DialogWorkerMessage } from '../src/win32-dialog-worker.ts' + +const builtWorker = fileURLToPath(new URL('../lib/worker.cjs', import.meta.url)) + +describe.skipIf(!existsSync(builtWorker) || process.platform === 'win32')('built dialog worker (lib/worker.cjs)', () => { + it('loads under plain worker_threads and reports the native-surface failure', async () => { + const message = await new Promise((resolve, reject) => { + const worker = new Worker(builtWorker, { workerData: { title: 'Built-artifact guard' } }) + worker.on('message', resolve) + worker.on('error', reject) + worker.on('exit', (code) => { + reject(new Error(`worker exited (${code}) before reporting`)) + }) + }) + expect(message.kind).toBe('error') + expect((message as { kind: 'error'; message: string }).message).toMatch(/ole32|koffi/i) + }, 30_000) +}) diff --git a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts index 799c24a062..d29fbad7a0 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts @@ -13,6 +13,12 @@ import { HRESULT_CANCELLED, runFolderDialog } from '../src/win32-dialog-logic.ts const E_FAIL = 0x80004005 | 0 const WM_CLOSE = 0x10 +/** + * Deliberately NOT 8: the bindings must derive vtable offsets and out-buffer + * sizes from koffi.sizeof('void *'), and a hardcoded 8 anywhere fails against + * this width (the win32-ia32 bug class). + */ +const FAKE_POINTER_SIZE = 4 interface ComWorld { coInitHr: number @@ -21,6 +27,8 @@ interface ComWorld { getResultHr: number getDisplayNameHr: number hasThreadDpi: boolean + /** Contexts `SetThreadDpiAwarenessContext` accepts; others return NULL. */ + supportedDpiContexts: number[] enumThrows: boolean path: string titles: string[] @@ -37,7 +45,7 @@ interface ComWorld { function comWorld(overrides: Partial = {}): ComWorld { return { coInitHr: 0, coCreateHr: 0, showHr: 0, getResultHr: 0, getDisplayNameHr: 0, - hasThreadDpi: true, enumThrows: false, + hasThreadDpi: true, supportedDpiContexts: [-4], enumThrows: false, path: 'C:\\选中\\directory', titles: [], options: [], dpiContexts: [], freed: [], released: [], posted: [], registered: 0, unregistered: 0, uninitialized: 0, @@ -89,6 +97,10 @@ function installFakeKoffi(world: ComWorld): void { case 'CoUninitialize': return () => { world.uninitialized += 1 } case 'CoCreateInstance': return (...args: unknown[]) => { if (world.coCreateHr < 0) return world.coCreateHr + // The out-pointer must be allocated at the fake's pointer width. + if ((args[4] as Buffer).length !== FAKE_POINTER_SIZE) { + throw new Error(`CoCreateInstance out buffer must be ${FAKE_POINTER_SIZE} bytes`) + } outBuffers.set(args[4], dialogPtr) return 0 } @@ -96,7 +108,10 @@ function installFakeKoffi(world: ComWorld): void { case 'GetCurrentThreadId': return () => 31337 case 'SetThreadDpiAwarenessContext': { if (!world.hasThreadDpi) throw new Error(`${dll}: SetThreadDpiAwarenessContext not found`) - return (context: unknown) => { world.dpiContexts.push(context); return null } + return (context: unknown) => { + world.dpiContexts.push(context) + return world.supportedDpiContexts.includes(context as number) ? { kind: 'previous-context' } : null + } } case 'EnumThreadWindows': return (_tid: unknown, callback: { fn: (hwnd: unknown, lparam: unknown) => number }, lparam: unknown) => { if (world.enumThrows) throw new Error('EnumThreadWindows refused') @@ -111,15 +126,16 @@ function installFakeKoffi(world: ComWorld): void { }), proto: (declaration: string) => ({ declaration }), pointer: (type: unknown) => type, - sizeof: (type: string) => { void type; return 8 }, + sizeof: (type: string) => { void type; return FAKE_POINTER_SIZE }, register: (fn: (hwnd: unknown, lparam: unknown) => number) => { world.registered += 1; return { fn } }, unregister: () => { world.unregistered += 1 }, decode: (value: unknown, offsetOrType: unknown): unknown => { if (offsetOrType === 'str16') return (value as FakePtr).text if (typeof offsetOrType === 'number') { - // Vtable slot read: hand back a callable-reference sentinel. + // Vtable slot read: offsets must be multiples of the fake width. + if (offsetOrType % FAKE_POINTER_SIZE !== 0) throw new Error(`vtable offset ${offsetOrType} is not pointer-aligned`) const owner = (value as { owner: FakePtr }).owner - return { call: (args: unknown[]) => dispatch(owner, offsetOrType / 8, args) } + return { call: (args: unknown[]) => dispatch(owner, offsetOrType / FAKE_POINTER_SIZE, args) } } // decode(x, 'void *'): out-buffer read or vtable read. if (outBuffers.has(value)) return outBuffers.get(value) @@ -159,17 +175,41 @@ describe('loadWin32DialogBindings over the fake COM world', () => { expect(world.uninitialized).toBe(1) }) - it('maps dismissal, missing DPI support, and the S_FALSE CoInitializeEx', async () => { - const world = comWorld({ showHr: HRESULT_CANCELLED, hasThreadDpi: false, coInitHr: 1 }) + it('maps dismissal and the S_FALSE CoInitializeEx', async () => { + const world = comWorld({ showHr: HRESULT_CANCELLED, coInitHr: 1 }) installFakeKoffi(world) const { loadWin32DialogBindings } = await loadBindingsModule() const bindings = await loadWin32DialogBindings() expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBeNull() - expect(world.dpiContexts).toEqual([]) expect(world.released).toEqual(['dialog']) expect(world.uninitialized).toBe(1) }) + it('cascades DPI contexts to the first the host accepts', async () => { + const world = comWorld({ supportedDpiContexts: [-3] }) + installFakeKoffi(world) + const bindings = await (await loadBindingsModule()).loadWin32DialogBindings() + expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBe('C:\\选中\\directory') + expect(world.dpiContexts).toEqual([-4, -3]) + }) + + it('keeps the tier when no DPI context is accepted or the symbol is absent', async () => { + // DPI is a cosmetic best-effort: the modern dialog still opens. + const rejecting = comWorld({ supportedDpiContexts: [] }) + installFakeKoffi(rejecting) + let bindings = await (await loadBindingsModule()).loadWin32DialogBindings() + expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBe('C:\\选中\\directory') + expect(rejecting.dpiContexts).toEqual([-4, -3, -2]) + + vi.doUnmock('koffi') + vi.resetModules() + const preThreadDpi = comWorld({ hasThreadDpi: false }) + installFakeKoffi(preThreadDpi) + bindings = await (await loadBindingsModule()).loadWin32DialogBindings() + expect(runFolderDialog(bindings, 'Pick', vi.fn())).toBe('C:\\选中\\directory') + expect(preThreadDpi.dpiContexts).toEqual([]) + }) + it('surfaces creation and extraction failures as HRESULT errors', async () => { const creationWorld = comWorld({ coCreateHr: E_FAIL }) installFakeKoffi(creationWorld) From 16b77081004dbd333073c9663a2546de4668d32f Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 21:54:50 +0800 Subject: [PATCH 53/61] chore(knip): declare directory-picker-native's e2e entry The package-wide default only knows spec files; the new built-worker e2e guard needs the workflow-workerthread-style entry declaration. --- knip.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/knip.json b/knip.json index fd941b03ca..46fbff979e 100644 --- a/knip.json +++ b/knip.json @@ -76,6 +76,16 @@ "tests/**/*.ts" ] }, + "packages/host/directory-picker-native": { + "entry": [ + "tests/**/*.spec.{ts,tsx}", + "tests/**/*.e2e.ts" + ], + "project": [ + "src/**/*.{ts,tsx}", + "tests/**/*.{ts,tsx}" + ] + }, "packages/client/web-ui": { "entry": [ "tests/**/*.spec.{ts,tsx}" From e234a3a27483ea5b1a1ac26aab61e0c31113488a Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 23:19:17 +0800 Subject: [PATCH 54/61] docs(host-directory-picker-native): describe the in-process IFileOpenDialog primary in the module header The @module header still described the Windows adapter as the pre-PR 'STA PowerShell FolderBrowserDialog' while the README and Agent Notes document the koffi IFileOpenDialog primary with the PowerShell chain as fallback; mirror the README's platform summary. --- packages/host/directory-picker-native/src/index.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/host/directory-picker-native/src/index.ts b/packages/host/directory-picker-native/src/index.ts index f131c8bb0c..7e253ee634 100644 --- a/packages/host/directory-picker-native/src/index.ts +++ b/packages/host/directory-picker-native/src/index.ts @@ -1,10 +1,12 @@ /** * Native backend of the directory-picker seam: registers `ctx.directoryPicker` * with the `native` capability, opening one native OS chooser on the host - * display per pick (macOS `osascript`, Windows STA PowerShell - * `FolderBrowserDialog`, Linux Zenity with a KDialog fallback). Only viable - * when the operator sits at the host's screen; remote deployments compose the - * browse backend instead. + * display per pick (macOS `osascript`, Linux Zenity with a KDialog fallback; + * Windows opens the modern `IFileOpenDialog` in-process — a koffi-driven COM + * conversation on a worker thread — and falls back to a PowerShell-hosted + * dialog (`pwsh`, then Windows PowerShell 5.1) when that native surface is + * unavailable). Only viable when the operator sits at the host's screen; + * remote deployments compose the browse backend instead. * @module @deepseek-ai/dsh-host-directory-picker-native */ From 020ce50414e85f42686054c74a6923e324538d1e Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 23:36:11 +0800 Subject: [PATCH 55/61] fix(picker): correct crash-isolation and DPI claims, wire the built-worker guard, and tidy round-four nits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The round-four review's v6 pass found three factual gaps and the v5 pass two nits. Correct them before merge: - The in-process note claimed a koffi signature mistake is 'contained to the worker thread' — worker_threads share the process, so a native access violation takes down the whole Node process with no PowerShell fallback. State the real blast radius and record the deferred pkg-VFS worker-spawn arm in Consequences (both languages, pairing re-recorded). - The 2026-07-27 picker note claimed unconditional 'per-monitor-v2 DPI'; PMv2-less hosts (Server 2016 / Win10 1607) cascade to per-monitor or system-aware. Say 'the best thread DPI awareness the host accepts' (both languages, pairing re-recorded). - built-worker.e2e.ts was not in any keyless gate (vitest.e2e config is not part of the default unit run and builtBinSmokeGate's explicit list missed it), so lib/worker.cjs load regressions passed keyless CI. Add it to builtBinSmokeGate alongside the workflow-workerthread sibling. - Remove the dead trailing 'void bindings' in win32-dialog-logic.spec.ts and give native-picker.spec.ts the sibling module header it lacked. --- .../2026-07-27-native-workspace-directory-picker.i18n.yaml | 4 ++-- .../2026-07-27-native-workspace-directory-picker.md | 2 +- .../2026-07-27-native-workspace-directory-picker.zh.md | 2 +- .../2026-08-02-win32-in-process-folder-dialog.i18n.yaml | 4 ++-- .../feature/2026-08-02-win32-in-process-folder-dialog.md | 3 ++- .../2026-08-02-win32-in-process-folder-dialog.zh.md | 3 ++- .../directory-picker-native/tests/native-picker.spec.ts | 7 +++++++ .../tests/win32-dialog-logic.spec.ts | 1 - scripts/run-gates.ts | 1 + 9 files changed, 18 insertions(+), 9 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml index e177c663cc..e49bbe59cc 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.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-27-native-workspace-directory-picker.md -2026-07-27-native-workspace-directory-picker.md: 45fa77b5519179e006f9109846a1602e6e22a6e2 -2026-07-27-native-workspace-directory-picker.zh.md: 2d6800d20b1f0dfe0b20ac9a5c90037599ece32a +2026-07-27-native-workspace-directory-picker.md: 452ec60371558de79dbff964a12d96d2150dc6f6 +2026-07-27-native-workspace-directory-picker.zh.md: c3e6b8825e78201ce791cff51869aade67d30a5e diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md index 45fa77b551..452ec60371 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md @@ -30,7 +30,7 @@ The native dialog RPC is accepted only from a loopback socket with same-origin b Platform adapters open the dialog without a shell — spawned native tools on POSIX, an in-process COM conversation on Windows: - macOS: `osascript` and the system folder chooser. -- Windows: the in-process koffi `IFileOpenDialog` worker with per-monitor-v2 DPI ([in-process dialog note](2026-08-02-win32-in-process-folder-dialog.md)); the PowerShell chain (`pwsh` in STA mode, then Windows PowerShell 5.1, both DPI-corrected) remains the fallback ([picker fix](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)). +- Windows: the in-process koffi `IFileOpenDialog` worker with the best thread DPI awareness the host accepts (per-monitor-v2 when available; PMv2-less hosts cascade to per-monitor or system-aware) ([in-process dialog note](2026-08-02-win32-in-process-folder-dialog.md)); the PowerShell chain (`pwsh` in STA mode, then Windows PowerShell 5.1, both DPI-corrected) remains the fallback ([picker fix](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)). - Linux: `zenity`, with `kdialog` as a fallback when Zenity is unavailable. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md index 2d6800d20b..c3e6b8825e 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md @@ -30,7 +30,7 @@ Status: implemented 平台适配器不经 shell 打开对话框——POSIX 上 spawn 原生工具,Windows 上是进程内 COM 会话: - macOS:`osascript` 和系统文件夹选择器。 -- Windows:进程内 koffi `IFileOpenDialog` worker,带 per-monitor-v2 DPI(见[进程内对话框 Note](2026-08-02-win32-in-process-folder-dialog.md));PowerShell 链(STA 模式的 `pwsh`,再到 Windows PowerShell 5.1,均已修正 DPI)保留为回退(见[选择器修复](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))。 +- Windows:进程内 koffi `IFileOpenDialog` worker,使用宿主接受的最佳线程 DPI 感知(可用时为 per-monitor-v2;不支持 PMv2 的主机级联到 per-monitor 或 system-aware)(见[进程内对话框 Note](2026-08-02-win32-in-process-folder-dialog.md));PowerShell 链(STA 模式的 `pwsh`,再到 Windows PowerShell 5.1,均已修正 DPI)保留为回退(见[选择器修复](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))。 - Linux:使用 `zenity`;Zenity 不可用时回退到 `kdialog`。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml index 656ee92a65..b3a1d1d640 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.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-02-win32-in-process-folder-dialog.md -2026-08-02-win32-in-process-folder-dialog.md: 96bc213ea7cddef6223aa3be69e56688dc9c4724 -2026-08-02-win32-in-process-folder-dialog.zh.md: a3dfad2ef73cb28ae8c4c47b6380740aab6de5c3 +2026-08-02-win32-in-process-folder-dialog.md: e18ecd1d2e79ec39a265d3d93913beaa7530e645 +2026-08-02-win32-in-process-folder-dialog.zh.md: f146d61f6378062886db732e6884594d56b3d170 diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md index 96bc213ea7..e18ecd1d2e 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md @@ -23,4 +23,5 @@ The Windows directory picker's primary tier was a spawned PowerShell script arou - Every Windows machine gets the modern dialog with the best DPI awareness it supports (per-monitor-v2 on 1703+), PowerShell installed or not; the PowerShell tiers only serve hosts where koffi cannot drive COM. - Real dialog rendering and the selection path stay a manual Windows check (the auto-close smoke proves open/abort/unwind); a wedged abort can leak one dialog thread until process exit, documented in the package README. -- The COM vtable slots and GUIDs used are frozen Windows ABI (Vista); a koffi signature mistake is an in-process crash risk contained to the worker thread and caught by the win32 smoke before shipping. +- The COM vtable slots and GUIDs used are frozen Windows ABI (Vista); a koffi signature mistake is a native-crash risk that can take down the whole Node process — `worker_threads` share the process, so an access violation is not contained to the worker and no PowerShell fallback runs. The mocked-koffi ABI pins and the real win32 smoke exist to catch such mistakes before shipping. +- The packaged-binary VFS arm — resolution of `./worker.cjs` inside a pkg snapshot — is not exercised by any automated test: the source worker and the built `lib/worker.cjs` under plain Node are covered, and the VFS-specific spawn remains deferred to the Windows CI roadmap. diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md index a3dfad2ef7..f146d61f63 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md @@ -23,4 +23,5 @@ Windows 目录选择器的主层此前是围绕 WinForms `FolderBrowserDialog` - 每台 Windows 机器都得到带其所支持的最佳 DPI 感知(1703+ 为 per-monitor-v2)的现代对话框,无论是否安装 PowerShell;PowerShell 层只服务 koffi 无法驱动 COM 的主机。 - 真实对话框渲染与选中路径仍是手动 Windows 检查(自动关闭冒烟证明打开/中止/收尾);卡死的中止可能泄漏一个对话框线程直到进程退出,已记录于包 README。 -- 所用 COM vtable 槽位与 GUID 是冻结的 Windows ABI(Vista 起);koffi 签名错误是被限制在 worker 线程内的进程内崩溃风险,并在交付前被 win32 冒烟捕获。 +- 所用 COM vtable 槽位与 GUID 是冻结的 Windows ABI(Vista 起);koffi 签名错误是可能拖垮整个 Node 进程的原生崩溃风险——`worker_threads` 与主线程共享进程,访问冲突不会只局限在 worker 内,也不会进入 PowerShell 回退。mocked-koffi 的 ABI 钉与真实 win32 冒烟正是为了在交付前捕获这类错误。 +- 打包二进制的 VFS 臂——在 pkg 快照内解析 `./worker.cjs`——不受任何自动化测试覆盖:源码 worker 与普通 Node 下构建出的 `lib/worker.cjs` 已被覆盖,VFS 专属的 spawn 推迟到 Windows CI 路线图。 diff --git a/packages/host/directory-picker-native/tests/native-picker.spec.ts b/packages/host/directory-picker-native/tests/native-picker.spec.ts index 64732e4e17..24c33e473e 100644 --- a/packages/host/directory-picker-native/tests/native-picker.spec.ts +++ b/packages/host/directory-picker-native/tests/native-picker.spec.ts @@ -1,3 +1,10 @@ +/** + * Native picker tier selection and the execFile adapter: the in-process + * dialog primary, the pwsh → Windows PowerShell 5.1 fallback chain (any + * non-abort pwsh failure cascades), the abort-never-falls-through rule, and + * the triple-miss AggregateError carrying the dialog/pwsh/5.1 causes. + */ + type ExecFileCallback = ( error: (Error & { code?: string | number }) | null, stdout: string, diff --git a/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts index c214245de6..718c93c2c0 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog-logic.spec.ts @@ -94,6 +94,5 @@ describe('runFolderDialog', () => { expect(() => runFolderDialog(bindings, 'Pick', vi.fn())).toThrow(`${what} failed: HRESULT 0x80004005`) expect(dialog.release).toHaveBeenCalledOnce() expect(uninitialize).toHaveBeenCalledOnce() - void bindings }) }) diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 74d90a547d..238c513433 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -597,6 +597,7 @@ function builtBinSmokeGate(needs: string[] = ['build']): Gate { 'apps/cli/tests/built-bin.e2e.ts', 'packages/examples/cli-demo/tests/built-bin.e2e.ts', 'packages/examples/acp-demo/tests/built-bin.e2e.ts', + 'packages/host/directory-picker-native/tests/built-worker.e2e.ts', 'packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts', // The worker-entry packages' built bundles: the only automated proof // that lib/index.js resolves its sibling lib/worker.cjs under plain node From f4095ee3eb2e45ff2bf8f13e612f43105a4fe379 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 3 Aug 2026 23:58:57 +0800 Subject: [PATCH 56/61] fix(picker): end the closed worker-message switch in assertNever MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The driver's switch over Win32DialogWorkerMessage handled all three current kinds but had no default, so a fourth kind added to the worker protocol would compile cleanly and silently no-op — settle() never called and the pick dangles until worker exit. Add the local assertNever backstop (the command-compact shape; this package does not depend on dsh-llm for the helper) and the return the error case needs to avoid falling into it. Round-five review finding. --- .../host/directory-picker-native/src/win32-dialog.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/host/directory-picker-native/src/win32-dialog.ts b/packages/host/directory-picker-native/src/win32-dialog.ts index a3aee2268a..15de82373e 100644 --- a/packages/host/directory-picker-native/src/win32-dialog.ts +++ b/packages/host/directory-picker-native/src/win32-dialog.ts @@ -51,6 +51,13 @@ const CLOSE_RETRY_MS = 150 /** Abort-service attempts before force-terminating the worker. */ const CLOSE_MAX_ATTEMPTS = 20 +/** Fail loudly if the closed worker-to-driver union gains an unhandled member. */ +/* v8 ignore start -- closed-union backstop; unreachable without a TypeScript contract violation */ +function assertNever(value: never): never { + throw new TypeError(`unknown win32 dialog worker message kind: ${String(value)}`) +} +/* v8 ignore stop */ + /** * Open the modern Win32 folder picker off the event loop. * @param signal - caller lifetime; abort closes the dialog and rejects. @@ -133,6 +140,10 @@ export async function pickWin32Directory( settle(() => { reject(new Error(`win32 folder dialog failed: ${message.message}`)) }) + return + /* v8 ignore next 2 -- closed worker-owned union; a fourth kind becomes a compile error */ + default: + assertNever(message) } }) worker.on('error', (error: Error) => { From 8923ae2ab844d69d3c6c21229304907029b72746 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Tue, 4 Aug 2026 00:00:31 +0800 Subject: [PATCH 57/61] docs(picker): drop the invented .NET 10 version specificity from the DPI note The Description paragraph attributed the modern dialog's bottom-strip rendering to '.NET 10', an unverifiable version the code comment deliberately avoids (the same invented-version class flagged in round one). Say 'the modern FolderBrowserDialog' on both language sides; pairing re-recorded. Round-five review finding. --- .../bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml | 4 ++-- .../implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md | 2 +- .../bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml index 9a86e1f729..d57f65ad1c 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.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-01-windows-picker-pwsh-dpi.md -2026-08-01-windows-picker-pwsh-dpi.md: a941d5ea6e150d74fa2fa4dbd93b7e6b58a78eff -2026-08-01-windows-picker-pwsh-dpi.zh.md: 8383240c219d701aa9a8728cf1a7fb7f3a7c5433 +2026-08-01-windows-picker-pwsh-dpi.md: 28630660d1370826c1997be342727175adb081ce +2026-08-01-windows-picker-pwsh-dpi.zh.md: 2be0231032898022cb3d54494fb06b86902b0c66 diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md index a941d5ea6e..28630660d1 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md @@ -10,7 +10,7 @@ The Windows branch of the native directory picker spawned Windows PowerShell 5.1 ## Decision -The PowerShell chain is now the FALLBACK tier below the in-process koffi dialog (see the [in-process folder dialog note](../feature/2026-08-02-win32-in-process-folder-dialog.md)): the win32 branch spawns `pwsh.exe` (PowerShell 7) first and falls back to `powershell.exe` (Windows PowerShell 5.1) on ANY pwsh failure — a resolvable PowerShell 6 has no WinForms and exits 1, not `ENOENT`, and 5.1 ships with every Windows. PowerShell 7 renders the modern Explorer-style folder picker because .NET Core 3.0 rewrote `FolderBrowserDialog` over `IFileDialog` (unconditionally; the later `AutoUpgradeEnabled` opt-out arrived in .NET 6 and the script never sets it). Both runtimes execute the identical script, which calls `SetProcessDPIAware()` (user32) before any window exists, so the dialog is system-DPI-aware no matter which host serves it. The script sets no `Description`: .NET 10's modern `FolderBrowserDialog` renders it as a bottom strip above the folder input, and the 5.1 classic dialog as an unthemed box, so the property is dropped entirely. `-STA` stays explicit for both, and the fallback keeps the seam's cancellation/failure contract (`null` on cancel, a retryable error otherwise). The host-boundary, RPC trust, and cancellation decisions stay with the [picker feature note](../feature/2026-07-27-native-workspace-directory-picker.md). +The PowerShell chain is now the FALLBACK tier below the in-process koffi dialog (see the [in-process folder dialog note](../feature/2026-08-02-win32-in-process-folder-dialog.md)): the win32 branch spawns `pwsh.exe` (PowerShell 7) first and falls back to `powershell.exe` (Windows PowerShell 5.1) on ANY pwsh failure — a resolvable PowerShell 6 has no WinForms and exits 1, not `ENOENT`, and 5.1 ships with every Windows. PowerShell 7 renders the modern Explorer-style folder picker because .NET Core 3.0 rewrote `FolderBrowserDialog` over `IFileDialog` (unconditionally; the later `AutoUpgradeEnabled` opt-out arrived in .NET 6 and the script never sets it). Both runtimes execute the identical script, which calls `SetProcessDPIAware()` (user32) before any window exists, so the dialog is system-DPI-aware no matter which host serves it. The script sets no `Description`: the modern `FolderBrowserDialog` renders it as a bottom strip above the folder input, and the 5.1 classic dialog as an unthemed box, so the property is dropped entirely. `-STA` stays explicit for both, and the fallback keeps the seam's cancellation/failure contract (`null` on cancel, a retryable error otherwise). The host-boundary, RPC trust, and cancellation decisions stay with the [picker feature note](../feature/2026-07-27-native-workspace-directory-picker.md). ## Alternatives considered diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md index 8383240c21..2be0231032 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -PowerShell 链现在是进程内 koffi 对话框之下的回退层(见[进程内文件夹对话框 Note](../feature/2026-08-02-win32-in-process-folder-dialog.md)):win32 分支先启动 `pwsh.exe`(PowerShell 7),并在 pwsh 的任何失败上回退到 `powershell.exe`(Windows PowerShell 5.1)——可解析的 PowerShell 6 没有 WinForms,以退出码 1 而非 `ENOENT` 失败,而 5.1 每台 Windows 都自带。PowerShell 7 呈现现代资源管理器风格选择器,是因为 .NET Core 3.0 用 `IFileDialog` 重写了 `FolderBrowserDialog`(无条件生效;更晚的 `AutoUpgradeEnabled` 退出开关到 .NET 6 才加入,脚本从未设置它)。两个运行时执行完全相同的脚本,脚本在任何窗口存在前调用 `SetProcessDPIAware()`(user32),因此无论由哪个宿主服务,对话框都系统 DPI aware。脚本不设置 `Description`:.NET 10 的现代 `FolderBrowserDialog` 会把它渲染成文件夹输入框上方的一条底带,5.1 经典对话框则渲染成未主题化的色块,因此该属性被整体移除。两个运行时都显式保留 `-STA`;回退维持 seam 的取消/失败契约(取消返回 `null`,其余为可重试错误)。宿主边界、RPC 信任与取消决策仍归[选择器功能 Note](../feature/2026-07-27-native-workspace-directory-picker.md)所有。 +PowerShell 链现在是进程内 koffi 对话框之下的回退层(见[进程内文件夹对话框 Note](../feature/2026-08-02-win32-in-process-folder-dialog.md)):win32 分支先启动 `pwsh.exe`(PowerShell 7),并在 pwsh 的任何失败上回退到 `powershell.exe`(Windows PowerShell 5.1)——可解析的 PowerShell 6 没有 WinForms,以退出码 1 而非 `ENOENT` 失败,而 5.1 每台 Windows 都自带。PowerShell 7 呈现现代资源管理器风格选择器,是因为 .NET Core 3.0 用 `IFileDialog` 重写了 `FolderBrowserDialog`(无条件生效;更晚的 `AutoUpgradeEnabled` 退出开关到 .NET 6 才加入,脚本从未设置它)。两个运行时执行完全相同的脚本,脚本在任何窗口存在前调用 `SetProcessDPIAware()`(user32),因此无论由哪个宿主服务,对话框都系统 DPI aware。脚本不设置 `Description`:现代 `FolderBrowserDialog` 会把它渲染成文件夹输入框上方的一条底带,5.1 经典对话框则渲染成未主题化的色块,因此该属性被整体移除。两个运行时都显式保留 `-STA`;回退维持 seam 的取消/失败契约(取消返回 `null`,其余为可重试错误)。宿主边界、RPC 信任与取消决策仍归[选择器功能 Note](../feature/2026-07-27-native-workspace-directory-picker.md)所有。 ## 考虑过的替代方案 From bc9171337ae5298ab1cd8cf94d312e26c1c56b92 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Tue, 4 Aug 2026 00:09:13 +0800 Subject: [PATCH 58/61] fix(picker): raise the worker-thread dialog to the foreground on showing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The koffi redesign moved the dialog from a spawned child process (which inherits a foreground-activation right from the spawning app) onto a worker thread of the same process, so Windows shows the dialog without activating it — it opens behind the app with a taskbar flash. The app has no native HWND to hand the seam, so raise from the driver: on the 'showing' notice (the worker posts it right before Show, before the dialog window exists), attach this thread's input queue to the dialog thread's, call SetForegroundWindow on its top-level window, and detach — retried on the close cadence until the window appears, stopped on settle/abort/success, never blocking the pick. Injectable seam mirrors closeThreadWindows; driver tests pin the raise and its retry; the in-process note records the mechanism (both languages, pairing re-recorded). --- ...2-win32-in-process-folder-dialog.i18n.yaml | 4 +- ...26-08-02-win32-in-process-folder-dialog.md | 2 +- ...08-02-win32-in-process-folder-dialog.zh.md | 2 +- .../src/win32-dialog-bindings.ts | 41 ++++++++++++++ .../src/win32-dialog-host.ts | 2 +- .../src/win32-dialog.ts | 32 ++++++++++- .../tests/win32-dialog.spec.ts | 53 ++++++++++++++++--- 7 files changed, 124 insertions(+), 12 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml index b3a1d1d640..9f428ccd78 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.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-02-win32-in-process-folder-dialog.md -2026-08-02-win32-in-process-folder-dialog.md: e18ecd1d2e79ec39a265d3d93913beaa7530e645 -2026-08-02-win32-in-process-folder-dialog.zh.md: f146d61f6378062886db732e6884594d56b3d170 +2026-08-02-win32-in-process-folder-dialog.md: c7a6602836c618e855c799b72017aa9232eda968 +2026-08-02-win32-in-process-folder-dialog.zh.md: a67a22625dcd674b2a63b6125b3d31704e90eabc diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md index e18ecd1d2e..c7a6602836 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md @@ -10,7 +10,7 @@ The Windows directory picker's primary tier was a spawned PowerShell script arou ## Decision -`packages/host/directory-picker-native` now opens `IFileOpenDialog` (`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`) in-process through koffi — already a workspace dependency for the repo's other `win32.ts` surfaces — as the primary win32 tier. The COM conversation runs on a `worker_threads` worker so the modal `Show` never blocks the host event loop; the worker posts its native thread id before blocking, and the driver services aborts by re-posting `WM_CLOSE` to that thread's windows (`EnumThreadWindows`), terminating and unrefing the worker only when the close budget is exhausted (Node cannot interrupt native calls, so an unclosable worker must never hold the process open). The worker thread opts into the best thread DPI awareness the host accepts (`SetThreadDpiAwarenessContext`, cascading per-monitor-v2 → per-monitor → system-aware with the return value checked), a strict upgrade over the script's system-DPI ceiling; DPI stays a cosmetic best-effort — a host accepting none of them still gets the modern dialog rather than a downgrade to the fallback chain. The module split keeps coverage honest on every host: `win32-dialog-logic.ts` (pure sequencing) and `win32-dialog.ts` (driver) test against fakes anywhere; `win32-dialog-bindings.ts` tests against a mocked `koffi` COM world (the `dsh-session-persistence-jsonl` technique); POSIX hosts run the real spawn plumbing to its koffi-load rejection; win32 hosts run a real open-and-abort-close smoke. That smoke lives in `processBoundTests`: under the threads pool a worker blocked in a native modal wedges pool teardown, while a fork contains it. The PowerShell chain (see the [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)) stays as the fallback tier, its trigger widened from `ENOENT` to any pwsh failure, which also closes the PowerShell 6 regression. +`packages/host/directory-picker-native` now opens `IFileOpenDialog` (`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`) in-process through koffi — already a workspace dependency for the repo's other `win32.ts` surfaces — as the primary win32 tier. The COM conversation runs on a `worker_threads` worker so the modal `Show` never blocks the host event loop; the worker posts its native thread id before blocking, and the driver services aborts by re-posting `WM_CLOSE` to that thread's windows (`EnumThreadWindows`), terminating and unrefing the worker only when the close budget is exhausted (Node cannot interrupt native calls, so an unclosable worker must never hold the process open). A window on a worker input queue would otherwise be shown without activation, so the driver also raises the dialog to the foreground once the worker reports `showing` — attaching input queues and calling `SetForegroundWindow`, retried on the close cadence until the window (created inside `Show`) exists. The worker thread opts into the best thread DPI awareness the host accepts (`SetThreadDpiAwarenessContext`, cascading per-monitor-v2 → per-monitor → system-aware with the return value checked), a strict upgrade over the script's system-DPI ceiling; DPI stays a cosmetic best-effort — a host accepting none of them still gets the modern dialog rather than a downgrade to the fallback chain. The module split keeps coverage honest on every host: `win32-dialog-logic.ts` (pure sequencing) and `win32-dialog.ts` (driver) test against fakes anywhere; `win32-dialog-bindings.ts` tests against a mocked `koffi` COM world (the `dsh-session-persistence-jsonl` technique); POSIX hosts run the real spawn plumbing to its koffi-load rejection; win32 hosts run a real open-and-abort-close smoke. That smoke lives in `processBoundTests`: under the threads pool a worker blocked in a native modal wedges pool teardown, while a fork contains it. The PowerShell chain (see the [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)) stays as the fallback tier, its trigger widened from `ENOENT` to any pwsh failure, which also closes the PowerShell 6 regression. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md index f146d61f63..a67a22625d 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md @@ -10,7 +10,7 @@ Windows 目录选择器的主层此前是围绕 WinForms `FolderBrowserDialog` ## 决策 -`packages/host/directory-picker-native` 现在经 koffi——它已是仓库其他 `win32.ts` 面的工作区依赖——在进程内打开 `IFileOpenDialog`(`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`),作为 win32 主层。COM 会话运行在 `worker_threads` worker 上,模态 `Show` 永不阻塞宿主事件循环;worker 在阻塞前上报其原生线程 id,driver 通过向该线程的窗口反复投递 `WM_CLOSE`(`EnumThreadWindows`)来服务中止,仅当关闭预算耗尽时才 terminate 并 unref worker(Node 无法打断原生调用,关不掉的 worker 决不能拖住进程退出)。worker 线程启用宿主接受的最佳线程 DPI 感知(`SetThreadDpiAwarenessContext`,按 per-monitor-v2 → per-monitor → system-aware 级联并检查返回值),严格优于脚本的系统 DPI 上限;DPI 保持为纯外观的 best-effort——全部不被接受的宿主仍得到现代对话框,而不会降级到回退链。模块切分让覆盖率在任何主机上都诚实:`win32-dialog-logic.ts`(纯时序)与 `win32-dialog.ts`(driver)在任何平台对假件测试;`win32-dialog-bindings.ts` 对 mock 的 `koffi` COM 世界测试(`dsh-session-persistence-jsonl` 的技法);POSIX 主机把真实 spawn 管道跑到 koffi 加载失败的拒绝;win32 主机跑真实的"打开并中止关闭"冒烟。该冒烟位于 `processBoundTests`:threads 池下阻塞在原生模态中的 worker 会卡死池的收尾,fork 则能容纳它。PowerShell 链(见 [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))保留为回退层,触发条件从 `ENOENT` 拓宽为 pwsh 的任何失败,同时关闭了 PowerShell 6 回归。 +`packages/host/directory-picker-native` 现在经 koffi——它已是仓库其他 `win32.ts` 面的工作区依赖——在进程内打开 `IFileOpenDialog`(`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`),作为 win32 主层。COM 会话运行在 `worker_threads` worker 上,模态 `Show` 永不阻塞宿主事件循环;worker 在阻塞前上报其原生线程 id,driver 通过向该线程的窗口反复投递 `WM_CLOSE`(`EnumThreadWindows`)来服务中止,仅当关闭预算耗尽时才 terminate 并 unref worker(Node 无法打断原生调用,关不掉的 worker 决不能拖住进程退出)。worker 输入队列上的窗口默认只会被显示而不会被激活,因此 driver 还会在 worker 上报 `showing` 后把对话框抬升到前台——附加输入队列并调用 `SetForegroundWindow`,按关闭节奏重试直到 `Show` 内创建的窗口出现。worker 线程启用宿主接受的最佳线程 DPI 感知(`SetThreadDpiAwarenessContext`,按 per-monitor-v2 → per-monitor → system-aware 级联并检查返回值),严格优于脚本的系统 DPI 上限;DPI 保持为纯外观的 best-effort——全部不被接受的宿主仍得到现代对话框,而不会降级到回退链。模块切分让覆盖率在任何主机上都诚实:`win32-dialog-logic.ts`(纯时序)与 `win32-dialog.ts`(driver)在任何平台对假件测试;`win32-dialog-bindings.ts` 对 mock 的 `koffi` COM 世界测试(`dsh-session-persistence-jsonl` 的技法);POSIX 主机把真实 spawn 管道跑到 koffi 加载失败的拒绝;win32 主机跑真实的"打开并中止关闭"冒烟。该冒烟位于 `processBoundTests`:threads 池下阻塞在原生模态中的 worker 会卡死池的收尾,fork 则能容纳它。PowerShell 链(见 [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))保留为回退层,触发条件从 `ENOENT` 拓宽为 pwsh 的任何失败,同时关闭了 PowerShell 6 回归。 ## 考虑过的替代方案 diff --git a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts index 03980af2a4..e6ee2f2e5d 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts @@ -179,3 +179,44 @@ export async function closeThreadWindows(threadId: number): Promise { koffi.unregister(callback) } } + +/** + * Bring a native thread's top-level window to the foreground. The dialog + * runs on a worker input queue, so Windows shows it without activating it + * (the app's main thread holds foreground association); the driver calls + * this on the `showing` notice: attach this thread's input queue to the + * dialog thread's, `SetForegroundWindow`, and detach. Returns whether the + * thread had a window to raise — the dialog window is created inside + * `Show`, after the `showing` notice, so callers retry until it exists. + * @param threadId - the dialog thread's native id (from the `showing` notice). + * @returns true when a window was found and raised. + */ +export async function raiseDialogWindow(threadId: number): Promise { + const koffi = (await import('koffi')).default as unknown as Koffi + const user32 = koffi.load('user32.dll') + const kernel32 = koffi.load('kernel32.dll') + const enumThreadWindows = user32.func('__stdcall', 'EnumThreadWindows', 'int', ['uint32', 'void *', 'intptr']) + const attachThreadInput = user32.func('__stdcall', 'AttachThreadInput', 'int', ['uint32', 'uint32', 'int']) + const setForegroundWindow = user32.func('__stdcall', 'SetForegroundWindow', 'int', ['void *']) + const getCurrentThreadId = kernel32.func('__stdcall', 'GetCurrentThreadId', 'uint32', []) + const protoEnumProc = koffi.proto('int __stdcall DshEnumThreadWndProc(void *hwnd, intptr lparam)') + let target: unknown + const callback = koffi.register((hwnd: unknown) => { + if (target === undefined) target = hwnd + return 0 // stop after the first (top-level) window + }, koffi.pointer(protoEnumProc)) + try { + enumThreadWindows(threadId, callback, 0) + } finally { + koffi.unregister(callback) + } + if (target === undefined) return false + const self = getCurrentThreadId() + try { + attachThreadInput(self, threadId, 1) + setForegroundWindow(target) + } finally { + attachThreadInput(self, threadId, 0) + } + return true +} diff --git a/packages/host/directory-picker-native/src/win32-dialog-host.ts b/packages/host/directory-picker-native/src/win32-dialog-host.ts index ff02a93105..21089be150 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-host.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-host.ts @@ -34,4 +34,4 @@ export function spawnDialogWorker(data: Win32DialogWorkerData): Worker { return new Worker(new URL(`data:text/javascript,${encodeURIComponent(bootstrap)}`), { workerData: data }) } -export { closeThreadWindows } from './win32-dialog-bindings.ts' +export { closeThreadWindows, raiseDialogWindow } from './win32-dialog-bindings.ts' diff --git a/packages/host/directory-picker-native/src/win32-dialog.ts b/packages/host/directory-picker-native/src/win32-dialog.ts index 15de82373e..0d406d0bfd 100644 --- a/packages/host/directory-picker-native/src/win32-dialog.ts +++ b/packages/host/directory-picker-native/src/win32-dialog.ts @@ -6,7 +6,11 @@ * injectable so every driver path is testable on any platform. */ -import { closeThreadWindows as hostCloseThreadWindows, spawnDialogWorker } from './win32-dialog-host.ts' +import { + closeThreadWindows as hostCloseThreadWindows, + raiseDialogWindow as hostRaiseDialogWindow, + spawnDialogWorker, +} from './win32-dialog-host.ts' import type { Win32DialogWorkerData, Win32DialogWorkerMessage } from './win32-dialog-worker.ts' /** The worker surface the driver drives (satisfied by `node:worker_threads`). */ @@ -39,6 +43,8 @@ export interface Win32DialogInternals { spawnWorker?: (data: Win32DialogWorkerData) => Win32DialogWorkerLike /** Replaces the real `WM_CLOSE` poster (`win32-dialog-host.ts`). */ closeThreadWindows?: (threadId: number) => Promise + /** Replaces the real foreground raise (`win32-dialog-host.ts`). */ + raiseDialogWindow?: (threadId: number) => Promise /** Abort-service cadence override so tests never wait wall-clock time. */ closeRetryMs?: number } @@ -71,11 +77,13 @@ export async function pickWin32Directory( if (signal.aborted) throw new Error('native directory picker aborted') const spawnWorker = internals.spawnWorker ?? spawnDialogWorker const closeWindows = internals.closeThreadWindows ?? hostCloseThreadWindows + const raiseWindow = internals.raiseDialogWindow ?? hostRaiseDialogWindow const closeRetryMs = internals.closeRetryMs ?? CLOSE_RETRY_MS const worker = spawnWorker({ title: DIALOG_TITLE }) let dialogThreadId: number | undefined let closeTimer: NodeJS.Timeout | undefined + let raiseTimer: NodeJS.Timeout | undefined let settled = false return await new Promise((resolve, reject) => { @@ -83,6 +91,7 @@ export async function pickWin32Directory( if (settled) return settled = true if (closeTimer !== undefined) clearInterval(closeTimer) + if (raiseTimer !== undefined) clearInterval(raiseTimer) signal.removeEventListener('abort', onAbort) worker.unref?.() outcome() @@ -96,6 +105,26 @@ export async function pickWin32Directory( if (dialogThreadId !== undefined) void closeWindows(dialogThreadId).catch(() => undefined) } + // The `showing` notice precedes the blocking `Show`, so the dialog + // window does not exist yet; re-enumerate on the close cadence until it + // does and raise it — a window on a worker input queue is otherwise + // shown without activation. Stops on settle, abort, or a successful + // raise; a failing raise (e.g. koffi absent) never blocks the pick. + const startRaise = (): void => { + const attempt = (): void => { + if (settled || signal.aborted || dialogThreadId === undefined) return + void raiseWindow(dialogThreadId) + .then((raised) => { + if (raised || settled || signal.aborted) { + if (raiseTimer !== undefined) clearInterval(raiseTimer) + } + }) + .catch(() => undefined) + } + attempt() + raiseTimer = setInterval(attempt, closeRetryMs) + } + // Sole caller: the once-registered abort listener, so no re-entry guard. const serviceAbort = (): void => { let attempts = 0 @@ -129,6 +158,7 @@ export async function pickWin32Directory( dialogThreadId = message.threadId // An abort that raced ahead of this notice now has a window to hit. if (signal.aborted) postClose() + else startRaise() return case 'done': settle(() => { diff --git a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts index 598386b1a7..72ff1b41d1 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts @@ -1,9 +1,11 @@ /** * Driver tests: the worker message protocol mapped onto the promise, the - * WM_CLOSE abort service (including the show-race retry and the terminate - * last resort) against fakes, plus the real spawn plumbing — POSIX hosts - * prove the default path rejects cleanly (koffi cannot load ole32 there), - * and win32 hosts briefly open and auto-abort a real dialog. + * foreground raise after the `showing` notice (retried until the dialog + * window exists), the WM_CLOSE abort service (including the show-race + * retry and the terminate last resort) against fakes, plus the real spawn + * plumbing — POSIX hosts prove the default path rejects cleanly (koffi + * cannot load ole32 there), and win32 hosts briefly open and auto-abort a + * real dialog. */ import { EventEmitter } from 'node:events' @@ -22,15 +24,24 @@ interface Harness { worker: FakeWorker internals: Win32DialogInternals close: ReturnType + raise: ReturnType } function harness(overrides: Partial = {}): Harness { const worker = new FakeWorker() const close = vi.fn(async () => undefined) + const raise = vi.fn(async () => true) return { worker, close, - internals: { spawnWorker: () => worker, closeThreadWindows: close, closeRetryMs: 1, ...overrides }, + raise, + internals: { + spawnWorker: () => worker, + closeThreadWindows: close, + raiseDialogWindow: raise, + closeRetryMs: 1, + ...overrides, + }, } } @@ -51,6 +62,35 @@ describe('pickWin32Directory', () => { await expect(cancelled).resolves.toBeNull() }) + it('raises the dialog window to the foreground after the showing notice', async () => { + const { worker, internals, raise } = harness() + const picked = pickWin32Directory(live(), internals) + worker.post({ kind: 'showing', threadId: 7 }) + worker.post({ kind: 'done', path: 'C:\\raised' }) + await expect(picked).resolves.toBe('C:\\raised') + expect(raise).toHaveBeenCalledWith(7) + }) + + it('retries the raise until the dialog window exists, then stops', async () => { + const { worker, internals, raise } = harness() + // The window is created inside `Show`, after the `showing` notice, so + // the first attempts find nothing; once a window is reported, the raise + // must stop retrying. + raise.mockResolvedValueOnce(false).mockResolvedValueOnce(false).mockResolvedValue(true) + const picked = pickWin32Directory(live(), internals) + worker.post({ kind: 'showing', threadId: 12 }) + await vi.waitFor(() => { + expect(raise.mock.calls.length).toBeGreaterThanOrEqual(2) + }) + const callsAfterRaised = await new Promise((resolve) => { + setTimeout(() =>{ resolve(raise.mock.calls.length); }, 20) + }) + await new Promise(resolve => setTimeout(resolve, 20)) + expect(raise.mock.calls.length).toBe(callsAfterRaised) + worker.post({ kind: 'done', path: 'C:\\raised' }) + await expect(picked).resolves.toBe('C:\\raised') + }) + it('rejects on a reported dialog failure, a worker crash, and a silent exit', async () => { const reported = harness() const failing = pickWin32Directory(live(), reported.internals) @@ -103,7 +143,7 @@ describe('pickWin32Directory', () => { it('starts the close service on the showing notice when the abort came first', async () => { const closeFailures = vi.fn(async () => { throw new Error('window not there yet') }) - const { worker, internals } = harness({ closeThreadWindows: closeFailures }) + const { worker, internals, raise } = harness({ closeThreadWindows: closeFailures }) const controller = new AbortController() // Attached before the race for the same unhandled-rejection reason above. const picked = expect(pickWin32Directory(controller.signal, internals)).rejects.toThrow('native directory picker aborted') @@ -113,6 +153,7 @@ describe('pickWin32Directory', () => { await vi.waitFor(() => { expect(closeFailures.mock.calls.length).toBeGreaterThan(1) }) + expect(raise).not.toHaveBeenCalled() worker.post({ kind: 'done', path: null }) await picked }) From 4201eaed3f5fb8574a3dfb087a96e460fcff761b Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Tue, 4 Aug 2026 01:40:57 +0800 Subject: [PATCH 59/61] refactor(picker): drive the Win32 dialog from a spawned child process The koffi IFileOpenDialog conversation runs in a spawned child process instead of a worker thread: the dialog is the child's first window, so Windows activates it without a foreground call, and a native fault stays contained to the child. The driver maps the child's message protocol onto a promise and services aborts by posting WM_CLOSE to the dialog thread's windows, killing the child when the close budget is exhausted. The built worker ships as lib/worker.cjs (the ./worker export) under plain node, and win32-dialog.spec.ts returns to the thread-safe pool. --- .../src/win32-dialog-bindings.ts | 57 ++++---------- .../src/win32-dialog-host.ts | 38 +++++----- .../src/win32-dialog-worker.ts | 43 +++++++---- .../src/win32-dialog.ts | 75 ++++++------------- .../tests/built-worker.e2e.ts | 25 ++++--- .../tests/win32-dialog-bindings.spec.ts | 68 +++++++++++------ .../tests/win32-dialog.spec.ts | 62 ++++----------- vitest.config.ts | 4 - 8 files changed, 153 insertions(+), 219 deletions(-) diff --git a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts index e6ee2f2e5d..654bbc5a74 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-bindings.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-bindings.ts @@ -25,6 +25,20 @@ interface Koffi { register(fn: (...args: unknown[]) => unknown, type: unknown): unknown unregister(callback: unknown): void sizeof(type: string): number + view(ref: unknown, len: number): ArrayBuffer +} + +/** + * Read a NUL-terminated UTF-16 string at a native address. koffi's + * `_Out_ void **` out-params surface a raw address, and + * `koffi.decode(addr, 'str16')` would dereference it as a pointer — crash + * on real Windows — so view the memory directly instead. + */ +function readUtf16(koffi: Koffi, address: unknown): string { + const bytes = Buffer.from(koffi.view(address, 32768)) + let end = 0 + while (end + 1 < bytes.length && bytes[end] !== 0) end += 2 + return bytes.toString('utf16le', 0, end) } const COINIT_APARTMENTTHREADED = 0x2 @@ -142,7 +156,7 @@ export async function loadWin32DialogBindings(): Promise { const nameOut: unknown[] = [null] const gotName = method(item, SLOT_GET_DISPLAY_NAME, protoGetDisplayName)(SIGDN_FILESYSPATH, nameOut) if (gotName < 0) return { hr: gotName } - const path = koffi.decode(nameOut[0], 'str16') as string + const path = readUtf16(koffi, nameOut[0]) coTaskMemFree(nameOut[0]) return { hr: gotName, path } } finally { @@ -179,44 +193,3 @@ export async function closeThreadWindows(threadId: number): Promise { koffi.unregister(callback) } } - -/** - * Bring a native thread's top-level window to the foreground. The dialog - * runs on a worker input queue, so Windows shows it without activating it - * (the app's main thread holds foreground association); the driver calls - * this on the `showing` notice: attach this thread's input queue to the - * dialog thread's, `SetForegroundWindow`, and detach. Returns whether the - * thread had a window to raise — the dialog window is created inside - * `Show`, after the `showing` notice, so callers retry until it exists. - * @param threadId - the dialog thread's native id (from the `showing` notice). - * @returns true when a window was found and raised. - */ -export async function raiseDialogWindow(threadId: number): Promise { - const koffi = (await import('koffi')).default as unknown as Koffi - const user32 = koffi.load('user32.dll') - const kernel32 = koffi.load('kernel32.dll') - const enumThreadWindows = user32.func('__stdcall', 'EnumThreadWindows', 'int', ['uint32', 'void *', 'intptr']) - const attachThreadInput = user32.func('__stdcall', 'AttachThreadInput', 'int', ['uint32', 'uint32', 'int']) - const setForegroundWindow = user32.func('__stdcall', 'SetForegroundWindow', 'int', ['void *']) - const getCurrentThreadId = kernel32.func('__stdcall', 'GetCurrentThreadId', 'uint32', []) - const protoEnumProc = koffi.proto('int __stdcall DshEnumThreadWndProc(void *hwnd, intptr lparam)') - let target: unknown - const callback = koffi.register((hwnd: unknown) => { - if (target === undefined) target = hwnd - return 0 // stop after the first (top-level) window - }, koffi.pointer(protoEnumProc)) - try { - enumThreadWindows(threadId, callback, 0) - } finally { - koffi.unregister(callback) - } - if (target === undefined) return false - const self = getCurrentThreadId() - try { - attachThreadInput(self, threadId, 1) - setForegroundWindow(target) - } finally { - attachThreadInput(self, threadId, 0) - } - return true -} diff --git a/packages/host/directory-picker-native/src/win32-dialog-host.ts b/packages/host/directory-picker-native/src/win32-dialog-host.ts index 21089be150..7a60ab05ed 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-host.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-host.ts @@ -1,37 +1,33 @@ /** - * Real-process half of the Win32 dialog driver: spawn the dialog worker - * (source or built plane) and close a dialog thread's windows. The module - * itself loads everywhere (the import chain from native-picker.ts is + * Real-process half of the Win32 dialog driver: spawn the dialog child + * process (source or built plane) and close a dialog thread's windows. The + * module itself loads everywhere (the import chain from native-picker.ts is * static); what stays win32-only is koffi, imported dynamically inside the * bindings' functions. The driver's logic is tested against fakes of this * surface instead. */ +import { spawn, type StdioOptions } from 'node:child_process' import { fileURLToPath } from 'node:url' -import { Worker } from 'node:worker_threads' import type { Win32DialogWorkerData } from './win32-dialog-worker.ts' /** - * Spawn the dialog worker. Built consumers load the bundled CJS worker next - * to this module; unbuilt (source) consumers bootstrap tsx inside the worker - * first, mirroring `dsh-workflow-workerthread`'s host. - * @param data - the worker payload (dialog title). - * @returns the spawned worker thread. + * Spawn the dialog child process. Built consumers launch the bundled CJS + * entry next to this module under plain node; unbuilt (source) consumers + * bootstrap tsx first, mirroring the dsh CLI's source launch. The dialog is + * the child's first window, so Windows activates it without a foreground + * call. + * @param data - the child payload (dialog title). + * @returns the spawned child process. */ -export function spawnDialogWorker(data: Win32DialogWorkerData): Worker { +export function spawnDialogWorker(data: Win32DialogWorkerData): ReturnType { + const env = { ...process.env, DSH_DIALOG_TITLE: data.title } + const stdio: StdioOptions = ['ignore', 'inherit', 'inherit', 'ipc'] /* v8 ignore next 3 -- the built-output arm: tests always run unbuilt (src/) */ if (!import.meta.url.endsWith('.ts')) { - return new Worker(fileURLToPath(new URL('./worker.cjs', import.meta.url)), { workerData: data }) + return spawn(process.execPath, [fileURLToPath(new URL('./worker.cjs', import.meta.url))], { env, stdio, windowsHide: true }) } - const workerEntry = new URL('./win32-dialog-worker.ts', import.meta.url) - const bootstrap = [ - `import { register as registerEsm } from ${JSON.stringify(import.meta.resolve('tsx/esm/api'))}`, - `import { register as registerCjs } from ${JSON.stringify(import.meta.resolve('tsx/cjs/api'))}`, - 'registerCjs()', - 'registerEsm()', - `await import(${JSON.stringify(workerEntry.href)})`, - ].join('\n') - return new Worker(new URL(`data:text/javascript,${encodeURIComponent(bootstrap)}`), { workerData: data }) + return spawn(process.execPath, ['--import', import.meta.resolve('tsx/esm'), fileURLToPath(new URL('./win32-dialog-worker.ts', import.meta.url))], { env, stdio, windowsHide: true }) } -export { closeThreadWindows, raiseDialogWindow } from './win32-dialog-bindings.ts' +export { closeThreadWindows } from './win32-dialog-bindings.ts' diff --git a/packages/host/directory-picker-native/src/win32-dialog-worker.ts b/packages/host/directory-picker-native/src/win32-dialog-worker.ts index e978d305f3..0b422b3ca7 100644 --- a/packages/host/directory-picker-native/src/win32-dialog-worker.ts +++ b/packages/host/directory-picker-native/src/win32-dialog-worker.ts @@ -1,16 +1,18 @@ /** - * Worker entry for the Win32 folder dialog: blocks THIS thread inside the - * modal `Show` so the host event loop stays live, reporting over the message - * port. Protocol: `{kind:'showing',threadId}` right before the blocking call - * (the driver's abort lever needs the native thread id), then exactly one of - * `{kind:'done',path}` or `{kind:'error',message}`. + * Child-process entry for the Win32 folder dialog: blocks THIS process + * inside the modal `Show` so the host event loop stays live, reporting over + * the IPC channel. Spawned as a child process (not a worker thread) so the + * dialog is the process's first window and Windows activates it without a + * manual foreground call. Protocol: `{kind:'showing',threadId}` right + * before the blocking call (the driver's abort lever needs the native + * thread id), then exactly one of `{kind:'done',path}` or + * `{kind:'error',message}`. */ -import { parentPort, workerData } from 'node:worker_threads' import { loadWin32DialogBindings } from './win32-dialog-bindings.ts' import { runFolderDialog } from './win32-dialog-logic.ts' -/** The driver-to-worker payload: the dialog title. */ +/** The driver-to-child payload: the dialog title (passed via env). */ export interface Win32DialogWorkerData { title: string } /** One notice or outcome posted back to the driver. */ @@ -19,21 +21,32 @@ export type Win32DialogWorkerMessage = | { kind: 'done'; path: string | null } | { kind: 'error'; message: string } -const port = parentPort -if (port === null) throw new Error('win32-dialog-worker must run as a worker thread') -const { title } = workerData as Win32DialogWorkerData +const title = process.env.DSH_DIALOG_TITLE ?? '' +if (title === '') throw new Error('win32-dialog-worker: DSH_DIALOG_TITLE is required') +if (process.send === undefined) throw new Error('win32-dialog-worker must run as a child process with an IPC channel') +// node's internal `send` reads `this.connected`, so bind the receiver. +const send = process.send.bind(process) -// No top-level await: the built worker ships as CJS (pkg's VFS Worker hook -// compiles that format), which cannot carry TLA. +const post = (message: Win32DialogWorkerMessage): void => { + // Flush before closing the channel; the process exits when the loop drains. + /* v8 ignore next 3 -- disconnect needs a live IPC channel the unit lane must not sever (built-worker.e2e.ts owns the real close path). */ + send(message, () => { if (process.connected) process.disconnect() }) +} + +// A settled driver (or a dead parent) must not orphan a dialog still on screen. +/* v8 ignore next 3 -- the handler exits(0), which would kill the unit lane; built-worker.e2e.ts owns the real disconnect lifecycle. */ +process.on('disconnect', () => process.exit(0)) + +// No top-level await: the built worker ships as CJS, which cannot carry TLA. void (async () => { try { const bindings = await loadWin32DialogBindings() const path = runFolderDialog(bindings, title, (threadId) => { - port.postMessage({ kind: 'showing', threadId } satisfies Win32DialogWorkerMessage) + post({ kind: 'showing', threadId } satisfies Win32DialogWorkerMessage) }) - port.postMessage({ kind: 'done', path } satisfies Win32DialogWorkerMessage) + post({ kind: 'done', path } satisfies Win32DialogWorkerMessage) } catch (error: unknown) { const message = error instanceof Error ? (error.stack ?? error.message) : String(error) - port.postMessage({ kind: 'error', message } satisfies Win32DialogWorkerMessage) + post({ kind: 'error', message } satisfies Win32DialogWorkerMessage) } })() diff --git a/packages/host/directory-picker-native/src/win32-dialog.ts b/packages/host/directory-picker-native/src/win32-dialog.ts index 0d406d0bfd..247d9a1733 100644 --- a/packages/host/directory-picker-native/src/win32-dialog.ts +++ b/packages/host/directory-picker-native/src/win32-dialog.ts @@ -1,22 +1,18 @@ /** - * Main-thread driver for the Win32 folder dialog: spawns the dialog worker - * (which blocks inside the modal `Show`), maps its message protocol onto a - * promise, and services aborts by posting `WM_CLOSE` to the dialog thread's - * windows until the worker reports back. The real worker/window surface is - * injectable so every driver path is testable on any platform. + * Main-thread driver for the Win32 folder dialog: spawns the dialog child + * process (which blocks inside the modal `Show`), maps its message protocol + * onto a promise, and services aborts by posting `WM_CLOSE` to the dialog + * thread's windows until the child reports back. The real process/window + * surface is injectable so every driver path is testable on any platform. */ -import { - closeThreadWindows as hostCloseThreadWindows, - raiseDialogWindow as hostRaiseDialogWindow, - spawnDialogWorker, -} from './win32-dialog-host.ts' +import { closeThreadWindows as hostCloseThreadWindows, spawnDialogWorker } from './win32-dialog-host.ts' import type { Win32DialogWorkerData, Win32DialogWorkerMessage } from './win32-dialog-worker.ts' -/** The worker surface the driver drives (satisfied by `node:worker_threads`). */ +/** The child-process surface the driver drives (satisfied by `node:child_process`). */ export interface Win32DialogWorkerLike { /** - * Subscribe to a worker event. + * Subscribe to a child-process event. * @param event - `message`, `error`, or `exit`. * @param listener - the event consumer. */ @@ -24,27 +20,24 @@ export interface Win32DialogWorkerLike { on(event: 'error', listener: (error: Error) => void): unknown on(event: 'exit', listener: (code: number) => void): unknown /** - * Force-stop the worker; the abort path's last resort when `WM_CLOSE` + * Force-stop the child; the abort path's last resort when `WM_CLOSE` * never lands (e.g. the dialog window was never created). - * @returns settles when the thread is gone. + * @returns whether a kill signal was delivered. */ - terminate(): Promise + kill(): boolean /** * Release the event-loop reference. Called once the pick settles so a - * worker stuck in the native modal call (terminate cannot interrupt - * native code) never blocks process exit. + * child stuck in the native modal call never blocks process exit. */ unref?(): void } /** Injectable process surface for deterministic driver tests. */ export interface Win32DialogInternals { - /** Replaces the real worker spawn (`win32-dialog-host.ts`). */ + /** Replaces the real child spawn (`win32-dialog-host.ts`). */ spawnWorker?: (data: Win32DialogWorkerData) => Win32DialogWorkerLike /** Replaces the real `WM_CLOSE` poster (`win32-dialog-host.ts`). */ closeThreadWindows?: (threadId: number) => Promise - /** Replaces the real foreground raise (`win32-dialog-host.ts`). */ - raiseDialogWindow?: (threadId: number) => Promise /** Abort-service cadence override so tests never wait wall-clock time. */ closeRetryMs?: number } @@ -77,13 +70,11 @@ export async function pickWin32Directory( if (signal.aborted) throw new Error('native directory picker aborted') const spawnWorker = internals.spawnWorker ?? spawnDialogWorker const closeWindows = internals.closeThreadWindows ?? hostCloseThreadWindows - const raiseWindow = internals.raiseDialogWindow ?? hostRaiseDialogWindow const closeRetryMs = internals.closeRetryMs ?? CLOSE_RETRY_MS - const worker = spawnWorker({ title: DIALOG_TITLE }) + const worker: Win32DialogWorkerLike = spawnWorker({ title: DIALOG_TITLE }) let dialogThreadId: number | undefined let closeTimer: NodeJS.Timeout | undefined - let raiseTimer: NodeJS.Timeout | undefined let settled = false return await new Promise((resolve, reject) => { @@ -91,7 +82,6 @@ export async function pickWin32Directory( if (settled) return settled = true if (closeTimer !== undefined) clearInterval(closeTimer) - if (raiseTimer !== undefined) clearInterval(raiseTimer) signal.removeEventListener('abort', onAbort) worker.unref?.() outcome() @@ -99,46 +89,26 @@ export async function pickWin32Directory( const postClose = (): void => { // Before `showing` there is no window to close; the budget below still - // runs so a worker that never reports cannot dangle the pick. A + // runs so a child that never reports cannot dangle the pick. A // rejected close attempt (EnumThreadWindows/PostMessageW refusing) is - // discarded: the interval retries it and terminate is the backstop. + // discarded: the interval retries it and kill is the backstop. if (dialogThreadId !== undefined) void closeWindows(dialogThreadId).catch(() => undefined) } - // The `showing` notice precedes the blocking `Show`, so the dialog - // window does not exist yet; re-enumerate on the close cadence until it - // does and raise it — a window on a worker input queue is otherwise - // shown without activation. Stops on settle, abort, or a successful - // raise; a failing raise (e.g. koffi absent) never blocks the pick. - const startRaise = (): void => { - const attempt = (): void => { - if (settled || signal.aborted || dialogThreadId === undefined) return - void raiseWindow(dialogThreadId) - .then((raised) => { - if (raised || settled || signal.aborted) { - if (raiseTimer !== undefined) clearInterval(raiseTimer) - } - }) - .catch(() => undefined) - } - attempt() - raiseTimer = setInterval(attempt, closeRetryMs) - } - // Sole caller: the once-registered abort listener, so no re-entry guard. const serviceAbort = (): void => { let attempts = 0 // The `showing` notice precedes the blocking `Show`, so the very first - // WM_CLOSE can race the window's creation; re-post until the worker - // reports back, then force-terminate as a last resort. The budget is - // unconditional — an abort before `showing` (worker hung in koffi or - // COM init) still ends in terminate instead of a dangling promise. + // WM_CLOSE can race the window's creation; re-post until the child + // reports back, then force-kill as a last resort. The budget is + // unconditional — an abort before `showing` (child hung in koffi or + // COM init) still ends in kill instead of a dangling promise. closeTimer = setInterval(() => { attempts += 1 if (attempts > CLOSE_MAX_ATTEMPTS) { settle(() => { - void worker.terminate() - reject(new Error('native directory picker aborted (dialog unresponsive; worker terminated)')) + worker.kill() + reject(new Error('native directory picker aborted (dialog unresponsive; worker killed)')) }) return } @@ -158,7 +128,6 @@ export async function pickWin32Directory( dialogThreadId = message.threadId // An abort that raced ahead of this notice now has a window to hit. if (signal.aborted) postClose() - else startRaise() return case 'done': settle(() => { diff --git a/packages/host/directory-picker-native/tests/built-worker.e2e.ts b/packages/host/directory-picker-native/tests/built-worker.e2e.ts index 03ae060f77..2c3b793a7d 100644 --- a/packages/host/directory-picker-native/tests/built-worker.e2e.ts +++ b/packages/host/directory-picker-native/tests/built-worker.e2e.ts @@ -1,27 +1,30 @@ /** * Keyless built-artifact guard (the `dsh-workflow-workerthread` built-worker - * shape): plain `worker_threads` loads `lib/worker.cjs` and the bundle reaches - * its real koffi requires. POSIX hosts prove the load path end to end through - * the deterministic ole32 rejection; win32 skips (a real dialog would open), - * where the win32-only smoke in win32-dialog.spec.ts covers the source plane - * instead. Skips until a build produces the artifact. + * shape): plain `node` runs `lib/worker.cjs` and the bundle reaches its + * real koffi requires. POSIX hosts prove the load path end to end through + * the deterministic ole32 rejection; win32 skips (a real dialog would + * open), where the win32-only smoke in win32-dialog.spec.ts covers the + * source plane instead. Skips until a build produces the artifact. */ +import { spawn } from 'node:child_process' import { existsSync } from 'node:fs' import { fileURLToPath } from 'node:url' -import { Worker } from 'node:worker_threads' import { describe, expect, it } from 'vitest' import type { Win32DialogWorkerMessage } from '../src/win32-dialog-worker.ts' const builtWorker = fileURLToPath(new URL('../lib/worker.cjs', import.meta.url)) describe.skipIf(!existsSync(builtWorker) || process.platform === 'win32')('built dialog worker (lib/worker.cjs)', () => { - it('loads under plain worker_threads and reports the native-surface failure', async () => { + it('loads under plain node and reports the native-surface failure', async () => { const message = await new Promise((resolve, reject) => { - const worker = new Worker(builtWorker, { workerData: { title: 'Built-artifact guard' } }) - worker.on('message', resolve) - worker.on('error', reject) - worker.on('exit', (code) => { + const child = spawn(process.execPath, [builtWorker], { + env: { ...process.env, DSH_DIALOG_TITLE: 'Built-artifact guard' }, + stdio: ['ignore', 'inherit', 'inherit', 'ipc'], + }) + child.on('message', resolve) + child.on('error', reject) + child.on('exit', (code) => { reject(new Error(`worker exited (${code}) before reporting`)) }) }) diff --git a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts index d29fbad7a0..9403bb7e36 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts @@ -3,9 +3,9 @@ * technique as dsh-session-persistence-jsonl's win32 suite): a small in-memory * COM world stands in for ole32/user32/kernel32, keeping the vtable dispatch, * result extraction, memory hygiene, and the WM_CLOSE poster covered on every - * host. The worker entry is exercised the same way with a mocked - * `node:worker_threads`. Real-COM behavior is pinned by the win32-only smoke - * in win32-dialog.spec.ts. + * host. The worker entry is exercised the same way with a mocked process + * boundary (env title + `process.send`). Real-COM behavior is pinned by the + * win32-only smoke in win32-dialog.spec.ts. */ import { afterEach, describe, expect, it, vi } from 'vitest' @@ -127,6 +127,11 @@ function installFakeKoffi(world: ComWorld): void { proto: (declaration: string) => ({ declaration }), pointer: (type: unknown) => type, sizeof: (type: string) => { void type; return FAKE_POINTER_SIZE }, + view: (value: unknown, len: number): ArrayBuffer => { + const bytes = Buffer.alloc(len) + bytes.write((value as FakePtr).text as string, 'utf16le') + return bytes.buffer + }, register: (fn: (hwnd: unknown, lparam: unknown) => number) => { world.registered += 1; return { fn } }, unregister: () => { world.unregistered += 1 }, decode: (value: unknown, offsetOrType: unknown): unknown => { @@ -259,13 +264,31 @@ describe('closeThreadWindows over the fake COM world', () => { }) }) -describe('the worker entry over a mocked thread boundary', () => { +describe('the worker entry over a mocked process boundary', () => { + const originalSend = process.send?.bind(process) + const originalTitle = process.env.DSH_DIALOG_TITLE + + const installBoundary = (): { posted: { kind: string; message?: string }[] } => { + const posted: { kind: string; message?: string }[] = [] + process.env.DSH_DIALOG_TITLE = 'Pick' + ;(process as { send?: unknown }).send = (message: { kind: string }, callback?: () => void) => { + posted.push(message) + callback?.() + } + return { posted } + } + + afterEach(() => { + delete (process as { send?: unknown }).send + if (originalSend !== undefined) (process as { send?: unknown }).send = originalSend + if (originalTitle === undefined) delete process.env.DSH_DIALOG_TITLE + else process.env.DSH_DIALOG_TITLE = originalTitle + vi.doUnmock('../src/win32-dialog-bindings.ts') + vi.resetModules() + }) + it('posts showing then done for a completed conversation', async () => { - const posted: unknown[] = [] - vi.doMock('node:worker_threads', () => ({ - parentPort: { postMessage: (message: unknown) => posted.push(message) }, - workerData: { title: 'Pick' }, - })) + const { posted } = installBoundary() vi.doMock('../src/win32-dialog-bindings.ts', () => ({ loadWin32DialogBindings: async () => ({ setThreadDpiAwareness: () => undefined, @@ -289,11 +312,7 @@ describe('the worker entry over a mocked thread boundary', () => { }) it('posts the failure message when the native surface cannot load', async () => { - const posted: { kind: string; message?: string }[] = [] - vi.doMock('node:worker_threads', () => ({ - parentPort: { postMessage: (message: { kind: string }) => posted.push(message) }, - workerData: { title: 'Pick' }, - })) + const { posted } = installBoundary() vi.doMock('../src/win32-dialog-bindings.ts', () => ({ loadWin32DialogBindings: async () => { throw new Error('no ole32 here') }, })) @@ -307,14 +326,8 @@ describe('the worker entry over a mocked thread boundary', () => { const stackless = new Error('bare message') delete stackless.stack for (const [thrown, expected] of [[stackless, 'bare message'], ['plain refusal', 'plain refusal']] as const) { - vi.doUnmock('node:worker_threads') - vi.doUnmock('../src/win32-dialog-bindings.ts') vi.resetModules() - const posted: { kind: string; message?: string }[] = [] - vi.doMock('node:worker_threads', () => ({ - parentPort: { postMessage: (message: { kind: string }) => posted.push(message) }, - workerData: { title: 'Pick' }, - })) + const { posted } = installBoundary() vi.doMock('../src/win32-dialog-bindings.ts', () => ({ loadWin32DialogBindings: async () => { throw thrown }, })) @@ -323,8 +336,15 @@ describe('the worker entry over a mocked thread boundary', () => { } }) - it('refuses to run outside a worker thread', async () => { - vi.doMock('node:worker_threads', () => ({ parentPort: null, workerData: undefined })) - await expect(import('../src/win32-dialog-worker.ts')).rejects.toThrow('must run as a worker thread') + it('refuses to run without the dialog title', async () => { + delete process.env.DSH_DIALOG_TITLE + ;(process as { send?: unknown }).send = () => true + await expect(import('../src/win32-dialog-worker.ts')).rejects.toThrow('DSH_DIALOG_TITLE is required') + }) + + it('refuses to run outside a child process', async () => { + process.env.DSH_DIALOG_TITLE = 'Pick' + delete (process as { send?: unknown }).send + await expect(import('../src/win32-dialog-worker.ts')).rejects.toThrow('must run as a child process') }) }) diff --git a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts index 72ff1b41d1..8e7d6951b8 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog.spec.ts @@ -1,11 +1,9 @@ /** - * Driver tests: the worker message protocol mapped onto the promise, the - * foreground raise after the `showing` notice (retried until the dialog - * window exists), the WM_CLOSE abort service (including the show-race - * retry and the terminate last resort) against fakes, plus the real spawn - * plumbing — POSIX hosts prove the default path rejects cleanly (koffi - * cannot load ole32 there), and win32 hosts briefly open and auto-abort a - * real dialog. + * Driver tests: the child-process message protocol mapped onto the promise, + * the WM_CLOSE abort service (including the show-race retry and the kill + * last resort) against fakes, plus the real spawn plumbing — POSIX hosts + * prove the default path rejects cleanly (koffi cannot load ole32 there), + * and win32 hosts briefly open and auto-abort a real dialog. */ import { EventEmitter } from 'node:events' @@ -14,7 +12,7 @@ import { pickWin32Directory, type Win32DialogInternals, type Win32DialogWorkerLi import type { Win32DialogWorkerMessage } from '../src/win32-dialog-worker.ts' class FakeWorker extends EventEmitter implements Win32DialogWorkerLike { - terminate = vi.fn(async () => 0) + kill = vi.fn(() => true) post(message: Win32DialogWorkerMessage): void { this.emit('message', message) } @@ -24,21 +22,17 @@ interface Harness { worker: FakeWorker internals: Win32DialogInternals close: ReturnType - raise: ReturnType } function harness(overrides: Partial = {}): Harness { const worker = new FakeWorker() const close = vi.fn(async () => undefined) - const raise = vi.fn(async () => true) return { worker, close, - raise, internals: { spawnWorker: () => worker, closeThreadWindows: close, - raiseDialogWindow: raise, closeRetryMs: 1, ...overrides, }, @@ -62,35 +56,6 @@ describe('pickWin32Directory', () => { await expect(cancelled).resolves.toBeNull() }) - it('raises the dialog window to the foreground after the showing notice', async () => { - const { worker, internals, raise } = harness() - const picked = pickWin32Directory(live(), internals) - worker.post({ kind: 'showing', threadId: 7 }) - worker.post({ kind: 'done', path: 'C:\\raised' }) - await expect(picked).resolves.toBe('C:\\raised') - expect(raise).toHaveBeenCalledWith(7) - }) - - it('retries the raise until the dialog window exists, then stops', async () => { - const { worker, internals, raise } = harness() - // The window is created inside `Show`, after the `showing` notice, so - // the first attempts find nothing; once a window is reported, the raise - // must stop retrying. - raise.mockResolvedValueOnce(false).mockResolvedValueOnce(false).mockResolvedValue(true) - const picked = pickWin32Directory(live(), internals) - worker.post({ kind: 'showing', threadId: 12 }) - await vi.waitFor(() => { - expect(raise.mock.calls.length).toBeGreaterThanOrEqual(2) - }) - const callsAfterRaised = await new Promise((resolve) => { - setTimeout(() =>{ resolve(raise.mock.calls.length); }, 20) - }) - await new Promise(resolve => setTimeout(resolve, 20)) - expect(raise.mock.calls.length).toBe(callsAfterRaised) - worker.post({ kind: 'done', path: 'C:\\raised' }) - await expect(picked).resolves.toBe('C:\\raised') - }) - it('rejects on a reported dialog failure, a worker crash, and a silent exit', async () => { const reported = harness() const failing = pickWin32Directory(live(), reported.internals) @@ -143,7 +108,7 @@ describe('pickWin32Directory', () => { it('starts the close service on the showing notice when the abort came first', async () => { const closeFailures = vi.fn(async () => { throw new Error('window not there yet') }) - const { worker, internals, raise } = harness({ closeThreadWindows: closeFailures }) + const { worker, internals } = harness({ closeThreadWindows: closeFailures }) const controller = new AbortController() // Attached before the race for the same unhandled-rejection reason above. const picked = expect(pickWin32Directory(controller.signal, internals)).rejects.toThrow('native directory picker aborted') @@ -153,31 +118,30 @@ describe('pickWin32Directory', () => { await vi.waitFor(() => { expect(closeFailures.mock.calls.length).toBeGreaterThan(1) }) - expect(raise).not.toHaveBeenCalled() worker.post({ kind: 'done', path: null }) await picked }) - it('terminates a worker that never reports showing after an abort', async () => { + it('kills a worker that never reports showing after an abort', async () => { // The budget runs without a thread id (nothing to WM_CLOSE yet), so a // worker hung before `showing` cannot dangle the pick. const { worker, internals, close } = harness() const controller = new AbortController() - const picked = expect(pickWin32Directory(controller.signal, internals)).rejects.toThrow('dialog unresponsive; worker terminated') + const picked = expect(pickWin32Directory(controller.signal, internals)).rejects.toThrow('dialog unresponsive; worker killed') controller.abort() await picked - expect(worker.terminate).toHaveBeenCalledOnce() + expect(worker.kill).toHaveBeenCalledOnce() expect(close).not.toHaveBeenCalled() }) - it('terminates an unresponsive worker after the close budget', async () => { + it('kills an unresponsive worker after the close budget', async () => { const { worker, internals, close } = harness() const controller = new AbortController() const picked = pickWin32Directory(controller.signal, internals) worker.post({ kind: 'showing', threadId: 5 }) controller.abort() - await expect(picked).rejects.toThrow('dialog unresponsive; worker terminated') - expect(worker.terminate).toHaveBeenCalledOnce() + await expect(picked).rejects.toThrow('dialog unresponsive; worker killed') + expect(worker.kill).toHaveBeenCalledOnce() expect(close.mock.calls.length).toBeGreaterThan(10) }) diff --git a/vitest.config.ts b/vitest.config.ts index 58d4a9837f..2909fb7459 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -73,10 +73,6 @@ const coverageExemptExcludes = coverageExemptRaw === '1' // 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. const processBoundTests = [ - // Spawns a nested worker that blocks in a native modal dialog on win32; - // under the threads pool the dialog thread outlives the test worker and - // wedges pool teardown, while a fork contains it. - 'packages/host/directory-picker-native/tests/win32-dialog.spec.ts', 'packages/subprocess/subprocess-local/tests/spawn.spec.ts', 'packages/context/time-context/tests/time-context.spec.ts', 'packages/llm/llm-pi-ai/tests/adapter.spec.ts', From 4cb5f328bb47baad89ffb02acb7a36d3e355cf69 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Tue, 4 Aug 2026 01:41:07 +0800 Subject: [PATCH 60/61] refactor(picker): drop the Windows PowerShell fallback chain The win32 tier is exactly the koffi IFileOpenDialog child process; any failure surfaces as-is. The pwsh -> Windows PowerShell 5.1 cascade, the shared WinForms script, and the triple-miss AggregateError are deleted: koffi is a packaged dependency whose availability the install guarantees, so no mechanism fallback exists (the browse backend remains the fallback at the composition level). The pwsh-first DPI picker-fix note is consolidated into a new simplification note recording the reversal. --- .../2026-08-01-windows-picker-pwsh-dpi.md | 26 ----- .../2026-08-01-windows-picker-pwsh-dpi.zh.md | 26 ----- ...ative-workspace-directory-picker.i18n.yaml | 4 +- ...07-27-native-workspace-directory-picker.md | 2 +- ...27-native-workspace-directory-picker.zh.md | 4 +- ...2-win32-in-process-folder-dialog.i18n.yaml | 4 +- ...26-08-02-win32-in-process-folder-dialog.md | 14 +-- ...08-02-win32-in-process-folder-dialog.zh.md | 14 +-- ...dows-powershell-picker-fallback.i18n.yaml} | 6 +- ...drop-windows-powershell-picker-fallback.md | 38 ++++++ ...p-windows-powershell-picker-fallback.zh.md | 38 ++++++ .../directory-picker-native/README.i18n.yaml | 4 +- .../host/directory-picker-native/README.md | 5 +- .../host/directory-picker-native/README.zh.md | 5 +- .../host/directory-picker-native/src/index.ts | 9 +- .../src/native-picker.ts | 61 +--------- .../tests/native-picker.spec.ts | 108 +++++------------- 17 files changed, 143 insertions(+), 225 deletions(-) delete mode 100644 .agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md delete mode 100644 .agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md rename .agents/notes/implemented/{bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml => simplification/2026-08-04-drop-windows-powershell-picker-fallback.i18n.yaml} (52%) create mode 100644 .agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.md create mode 100644 .agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.zh.md diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md deleted file mode 100644 index 28630660d1..0000000000 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md +++ /dev/null @@ -1,26 +0,0 @@ -# Agent Note: Windows directory picker prefers pwsh and forces DPI awareness - -Status: implemented - -English | [中文](2026-08-01-windows-picker-pwsh-dpi.zh.md) - -## Problem - -The Windows branch of the native directory picker spawned Windows PowerShell 5.1's `FolderBrowserDialog`, which .NET Framework hardwires to the legacy `SHBrowseForFolder` tree dialog: no address bar, search, or quick access. The same process is DPI-unaware (`powershell.exe` declares no DPI awareness), so on scaled displays Windows renders the dialog at 96 DPI and bitmap-stretches it — blurry text and soft edges. Both defects were visible at once on any display above 100 % scaling. - -## Decision - -The PowerShell chain is now the FALLBACK tier below the in-process koffi dialog (see the [in-process folder dialog note](../feature/2026-08-02-win32-in-process-folder-dialog.md)): the win32 branch spawns `pwsh.exe` (PowerShell 7) first and falls back to `powershell.exe` (Windows PowerShell 5.1) on ANY pwsh failure — a resolvable PowerShell 6 has no WinForms and exits 1, not `ENOENT`, and 5.1 ships with every Windows. PowerShell 7 renders the modern Explorer-style folder picker because .NET Core 3.0 rewrote `FolderBrowserDialog` over `IFileDialog` (unconditionally; the later `AutoUpgradeEnabled` opt-out arrived in .NET 6 and the script never sets it). Both runtimes execute the identical script, which calls `SetProcessDPIAware()` (user32) before any window exists, so the dialog is system-DPI-aware no matter which host serves it. The script sets no `Description`: the modern `FolderBrowserDialog` renders it as a bottom strip above the folder input, and the 5.1 classic dialog as an unthemed box, so the property is dropped entirely. `-STA` stays explicit for both, and the fallback keeps the seam's cancellation/failure contract (`null` on cancel, a retryable error otherwise). The host-boundary, RPC trust, and cancellation decisions stay with the [picker feature note](../feature/2026-07-27-native-workspace-directory-picker.md). - -## Alternatives considered - -- **Require PowerShell 7.** Rejected: pwsh is not a Windows built-in, so machines without it would lose the only workspace-creation route; the 5.1 fallback keeps the dialog functional, and DPI is corrected there too. -- **Import `resolvePwshPath` from `dsh-pwsh-local`.** Rejected for this change: a host GUI package importing from a bash-executor package is a cross-seam coupling, and PATH-based `execFile` resolution plus `ENOENT` fallback already covers the practical installs (Program Files, Store aliases); single-source resolution remains a follow-up if the two consumers drift. -- **Set DPI awareness in the harness process.** Rejected: DPI awareness is per-process, and the dialog lives in a spawned child that inherits nothing from the parent's absent declaration. -- **Per-monitor v2 (`SetProcessDpiAwarenessContext`).** Deferred: system-aware is the ceiling .NET Framework WinForms supports, the shell dialog handles per-monitor rendering itself on modern Windows, and one call keeps both runtimes on a single code path. - -## Consequences - -- Machines with PowerShell 7 get the modern folder picker; 5.1-only machines keep the legacy tree — now sharp — and the package README's Known Limitations documents the gap. -- The PowerShell chain itself adds no packages or dependencies (koffi and tsx arrived with the in-process primary and belong to its note); the pwsh→5.1 hop triggers on ANY non-abort pwsh failure — no `ENOENT` classification remains on the win32 path — while abort propagation is unchanged. -- The command boundary (`DirectoryPickerRunner`) pins the spawn order and script content in unit tests; real dialog rendering remains a manual Windows check, as before. diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md b/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md deleted file mode 100644 index 2be0231032..0000000000 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.zh.md +++ /dev/null @@ -1,26 +0,0 @@ -# Agent Note: Windows 目录选择器优先 pwsh 并强制 DPI awareness - -Status: implemented - -[English](2026-08-01-windows-picker-pwsh-dpi.md) | 中文 - -## 问题 - -原生目录选择器的 Windows 分支原先启动 Windows PowerShell 5.1 的 `FolderBrowserDialog`,而 .NET Framework 将其硬编码为旧版 `SHBrowseForFolder` 树形对话框:没有地址栏、搜索或快速访问。同一进程又是 DPI-unaware 的(`powershell.exe` 未声明任何 DPI awareness),因此在缩放显示器上,Windows 会以 96 DPI 渲染该对话框再位图拉伸——文字模糊、边缘发虚。任何超过 100% 缩放的显示器上,两个缺陷同时可见。 - -## 决策 - -PowerShell 链现在是进程内 koffi 对话框之下的回退层(见[进程内文件夹对话框 Note](../feature/2026-08-02-win32-in-process-folder-dialog.md)):win32 分支先启动 `pwsh.exe`(PowerShell 7),并在 pwsh 的任何失败上回退到 `powershell.exe`(Windows PowerShell 5.1)——可解析的 PowerShell 6 没有 WinForms,以退出码 1 而非 `ENOENT` 失败,而 5.1 每台 Windows 都自带。PowerShell 7 呈现现代资源管理器风格选择器,是因为 .NET Core 3.0 用 `IFileDialog` 重写了 `FolderBrowserDialog`(无条件生效;更晚的 `AutoUpgradeEnabled` 退出开关到 .NET 6 才加入,脚本从未设置它)。两个运行时执行完全相同的脚本,脚本在任何窗口存在前调用 `SetProcessDPIAware()`(user32),因此无论由哪个宿主服务,对话框都系统 DPI aware。脚本不设置 `Description`:现代 `FolderBrowserDialog` 会把它渲染成文件夹输入框上方的一条底带,5.1 经典对话框则渲染成未主题化的色块,因此该属性被整体移除。两个运行时都显式保留 `-STA`;回退维持 seam 的取消/失败契约(取消返回 `null`,其余为可重试错误)。宿主边界、RPC 信任与取消决策仍归[选择器功能 Note](../feature/2026-07-27-native-workspace-directory-picker.md)所有。 - -## 考虑过的替代方案 - -- **强制要求 PowerShell 7。** 否决:pwsh 并非 Windows 内置,没有它的机器将失去唯一的工作区创建路径;5.1 回退保持对话框可用,且 DPI 在那里同样被修正。 -- **从 `dsh-pwsh-local` 导入 `resolvePwshPath`。** 本变更否决:host GUI 包依赖 bash 执行器包是跨 seam 耦合;PATH 上的 `execFile` 解析加 `ENOENT` 回退已覆盖实际安装形态(Program Files、Store 别名);若两个消费者日后漂移,单一来源解析留作后续。 -- **在 harness 进程内设置 DPI awareness。** 否决:DPI awareness 是进程级的,而对话框位于派生的子进程中,不会继承父进程缺失的声明。 -- **Per-monitor v2(`SetProcessDpiAwarenessContext`)。** 暂缓:system-aware 是 .NET Framework WinForms 的上限,现代 Windows 中 shell 对话框自身处理 per-monitor 渲染,且一次调用让两个运行时共用一条代码路径。 - -## 后果 - -- 装有 PowerShell 7 的机器获得现代文件夹选择器;只有 5.1 的机器保留旧版树——但现在清晰了——包 README 的已知限制记录了该差距。 -- PowerShell 链本身不新增任何包或依赖(koffi 与 tsx 随进程内主层引入,归属其 Note);pwsh→5.1 的跳转在 pwsh 的任何非中止失败上触发——win32 路径上已不存在 `ENOENT` 分类——中止传播不变。 -- 命令边界(`DirectoryPickerRunner`)在单元测试中固定启动顺序与脚本内容;真实对话框渲染仍与以前一样属于手动 Windows 检查。 diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml index e49bbe59cc..dade9b5d90 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.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-27-native-workspace-directory-picker.md -2026-07-27-native-workspace-directory-picker.md: 452ec60371558de79dbff964a12d96d2150dc6f6 -2026-07-27-native-workspace-directory-picker.zh.md: c3e6b8825e78201ce791cff51869aade67d30a5e +2026-07-27-native-workspace-directory-picker.md: a36f7b239a9115fe5eb33472ec5084818a66e9f2 +2026-07-27-native-workspace-directory-picker.zh.md: bb3e2fc6f7c77c8ace97e53435297326f937e4e8 diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md index 452ec60371..a36f7b239a 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.md @@ -30,7 +30,7 @@ The native dialog RPC is accepted only from a loopback socket with same-origin b Platform adapters open the dialog without a shell — spawned native tools on POSIX, an in-process COM conversation on Windows: - macOS: `osascript` and the system folder chooser. -- Windows: the in-process koffi `IFileOpenDialog` worker with the best thread DPI awareness the host accepts (per-monitor-v2 when available; PMv2-less hosts cascade to per-monitor or system-aware) ([in-process dialog note](2026-08-02-win32-in-process-folder-dialog.md)); the PowerShell chain (`pwsh` in STA mode, then Windows PowerShell 5.1, both DPI-corrected) remains the fallback ([picker fix](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)). +- Windows: the koffi `IFileOpenDialog` child process with the best thread DPI awareness the host accepts (per-monitor-v2 when available; PMv2-less hosts cascade to per-monitor or system-aware) ([in-process dialog note](2026-08-02-win32-in-process-folder-dialog.md)); the tier has no fallback — failures surface as-is ([PowerShell chain removal](../simplification/2026-08-04-drop-windows-powershell-picker-fallback.md)). - Linux: `zenity`, with `kdialog` as a fallback when Zenity is unavailable. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md index c3e6b8825e..bb3e2fc6f7 100644 --- a/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-native-workspace-directory-picker.zh.md @@ -27,10 +27,10 @@ Status: implemented 只有来自回环套接字、且携带同源浏览器元数据的请求才能调用原生对话框 RPC。该 RPC 不使用默认的 30 秒请求超时,因为系统对话框可能无限期保持打开;调用方中止或连接中止仍会传递至平台进程。 -平台适配器不经 shell 打开对话框——POSIX 上 spawn 原生工具,Windows 上是进程内 COM 会话: +平台适配器不经 shell 打开对话框——POSIX 上 spawn 原生工具,Windows 上是子进程 COM 会话: - macOS:`osascript` 和系统文件夹选择器。 -- Windows:进程内 koffi `IFileOpenDialog` worker,使用宿主接受的最佳线程 DPI 感知(可用时为 per-monitor-v2;不支持 PMv2 的主机级联到 per-monitor 或 system-aware)(见[进程内对话框 Note](2026-08-02-win32-in-process-folder-dialog.md));PowerShell 链(STA 模式的 `pwsh`,再到 Windows PowerShell 5.1,均已修正 DPI)保留为回退(见[选择器修复](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))。 +- Windows:koffi `IFileOpenDialog` 子进程,使用宿主接受的最佳线程 DPI 感知(可用时为 per-monitor-v2;不支持 PMv2 的主机级联到 per-monitor 或 system-aware)(见[进程内对话框 Note](2026-08-02-win32-in-process-folder-dialog.md));该层无回退——失败原样上报(见[PowerShell 链删除](../simplification/2026-08-04-drop-windows-powershell-picker-fallback.md))。 - Linux:使用 `zenity`;Zenity 不可用时回退到 `kdialog`。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml index 9f428ccd78..2ec7925a3e 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.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-02-win32-in-process-folder-dialog.md -2026-08-02-win32-in-process-folder-dialog.md: c7a6602836c618e855c799b72017aa9232eda968 -2026-08-02-win32-in-process-folder-dialog.zh.md: a67a22625dcd674b2a63b6125b3d31704e90eabc +2026-08-02-win32-in-process-folder-dialog.md: 91a1ed0d7b1c1938a5e038ce36f1ca90bf3c9e82 +2026-08-02-win32-in-process-folder-dialog.zh.md: 6b90dc1c5fa0042b3e2bcbea8ed554f1f0ea2acf diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md index c7a6602836..91a1ed0d7b 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.md @@ -1,4 +1,4 @@ -# Agent Note: Win32 folder picker moves in-process over koffi +# Agent Note: Win32 folder picker moves to koffi in a child process Status: implemented @@ -10,18 +10,18 @@ The Windows directory picker's primary tier was a spawned PowerShell script arou ## Decision -`packages/host/directory-picker-native` now opens `IFileOpenDialog` (`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`) in-process through koffi — already a workspace dependency for the repo's other `win32.ts` surfaces — as the primary win32 tier. The COM conversation runs on a `worker_threads` worker so the modal `Show` never blocks the host event loop; the worker posts its native thread id before blocking, and the driver services aborts by re-posting `WM_CLOSE` to that thread's windows (`EnumThreadWindows`), terminating and unrefing the worker only when the close budget is exhausted (Node cannot interrupt native calls, so an unclosable worker must never hold the process open). A window on a worker input queue would otherwise be shown without activation, so the driver also raises the dialog to the foreground once the worker reports `showing` — attaching input queues and calling `SetForegroundWindow`, retried on the close cadence until the window (created inside `Show`) exists. The worker thread opts into the best thread DPI awareness the host accepts (`SetThreadDpiAwarenessContext`, cascading per-monitor-v2 → per-monitor → system-aware with the return value checked), a strict upgrade over the script's system-DPI ceiling; DPI stays a cosmetic best-effort — a host accepting none of them still gets the modern dialog rather than a downgrade to the fallback chain. The module split keeps coverage honest on every host: `win32-dialog-logic.ts` (pure sequencing) and `win32-dialog.ts` (driver) test against fakes anywhere; `win32-dialog-bindings.ts` tests against a mocked `koffi` COM world (the `dsh-session-persistence-jsonl` technique); POSIX hosts run the real spawn plumbing to its koffi-load rejection; win32 hosts run a real open-and-abort-close smoke. That smoke lives in `processBoundTests`: under the threads pool a worker blocked in a native modal wedges pool teardown, while a fork contains it. The PowerShell chain (see the [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md)) stays as the fallback tier, its trigger widened from `ENOENT` to any pwsh failure, which also closes the PowerShell 6 regression. +`packages/host/directory-picker-native` now opens `IFileOpenDialog` (`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`) in-process through koffi — already a workspace dependency for the repo's other `win32.ts` surfaces — as the primary win32 tier. The COM conversation runs in a spawned child process so the modal `Show` never blocks the host event loop; the child posts its native thread id before blocking, and the driver services aborts by re-posting `WM_CLOSE` to that thread's windows (`EnumThreadWindows`), killing the child when the close budget is exhausted. The dialog is the child's first window, so Windows activates it without a foreground call. The child thread opts into the best thread DPI awareness the host accepts (`SetThreadDpiAwarenessContext`, cascading per-monitor-v2 → per-monitor → system-aware with the return value checked), a strict upgrade over the script's system-DPI ceiling; DPI stays a cosmetic best-effort — a host accepting none of them still gets the modern dialog rather than a downgrade. The module split keeps coverage honest on every host: `win32-dialog-logic.ts` (pure sequencing) and `win32-dialog.ts` (driver) test against fakes anywhere; `win32-dialog-bindings.ts` tests against a mocked `koffi` COM world (the `dsh-session-persistence-jsonl` technique); POSIX hosts run the real spawn plumbing to its koffi-load rejection; win32 hosts run a real open-and-abort-close smoke. The PowerShell chain that preceded this tier is gone (see the [chain removal](../simplification/2026-08-04-drop-windows-powershell-picker-fallback.md)): the tier has no fallback. ## Alternatives considered - **A prebuilt native helper (`native/` family like `node-addon-landlock-run`).** Rejected: a mirror repository, an npm package family, MSVC provisioning, and a release handoff — all to ship ~150 lines of C the repository cannot exercise on CI (no real-Windows lane); koffi delivers the same COM surface with zero new supply chain. -- **An N-API in-process addon.** Rejected for the same CI/toolchain reasons plus owned C++ for STA threading and message pumping that `worker_threads` + koffi express in TypeScript. +- **An N-API in-process addon.** Rejected for the same CI/toolchain reasons plus owned C++ for STA threading and message pumping that a child process + koffi express in TypeScript. - **Keep PowerShell primary and probe versions.** Rejected: the picker stays hostage to shell packaging (6 vs 7, Store aliases, profiles), and 5.1's legacy dialog remains the floor wherever pwsh is absent; the fallback-trigger widening alone was accepted into the fallback tier instead. - **Blocking the main thread for the modal call.** Rejected outright: the web host must keep serving RPC while the dialog is open. ## Consequences -- Every Windows machine gets the modern dialog with the best DPI awareness it supports (per-monitor-v2 on 1703+), PowerShell installed or not; the PowerShell tiers only serve hosts where koffi cannot drive COM. -- Real dialog rendering and the selection path stay a manual Windows check (the auto-close smoke proves open/abort/unwind); a wedged abort can leak one dialog thread until process exit, documented in the package README. -- The COM vtable slots and GUIDs used are frozen Windows ABI (Vista); a koffi signature mistake is a native-crash risk that can take down the whole Node process — `worker_threads` share the process, so an access violation is not contained to the worker and no PowerShell fallback runs. The mocked-koffi ABI pins and the real win32 smoke exist to catch such mistakes before shipping. -- The packaged-binary VFS arm — resolution of `./worker.cjs` inside a pkg snapshot — is not exercised by any automated test: the source worker and the built `lib/worker.cjs` under plain Node are covered, and the VFS-specific spawn remains deferred to the Windows CI roadmap. +- Every Windows machine gets the modern dialog with the best DPI awareness it supports (per-monitor-v2 on 1703+), PowerShell installed or not. +- Real dialog rendering and the selection path stay a manual Windows check (the auto-close smoke proves open/abort/unwind). +- The COM vtable slots and GUIDs used are frozen Windows ABI (Vista); a koffi signature mistake risks a native access violation, contained to the dialog child process — the host Node process survives and the failure surfaces as-is (no fallback tier; see the [chain removal](../simplification/2026-08-04-drop-windows-powershell-picker-fallback.md)). The mocked-koffi ABI pins and the real win32 smoke exist to catch such mistakes before shipping. +- The packaged-binary arm — the packaged executable spawning itself as the dialog entry — is not exercised by any automated test: the source plane and the built `lib/worker.cjs` under plain node are covered, and the packaged spawn remains deferred to the Windows CI roadmap. diff --git a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md index a67a22625d..6b90dc1c5f 100644 --- a/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md +++ b/.agents/notes/implemented/feature/2026-08-02-win32-in-process-folder-dialog.zh.md @@ -1,4 +1,4 @@ -# Agent Note:Win32 文件夹选择器经 koffi 移入进程内 +# Agent Note:Win32 文件夹选择器迁至 koffi 子进程 Status: implemented @@ -10,18 +10,18 @@ Windows 目录选择器的主层此前是围绕 WinForms `FolderBrowserDialog` ## 决策 -`packages/host/directory-picker-native` 现在经 koffi——它已是仓库其他 `win32.ts` 面的工作区依赖——在进程内打开 `IFileOpenDialog`(`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`),作为 win32 主层。COM 会话运行在 `worker_threads` worker 上,模态 `Show` 永不阻塞宿主事件循环;worker 在阻塞前上报其原生线程 id,driver 通过向该线程的窗口反复投递 `WM_CLOSE`(`EnumThreadWindows`)来服务中止,仅当关闭预算耗尽时才 terminate 并 unref worker(Node 无法打断原生调用,关不掉的 worker 决不能拖住进程退出)。worker 输入队列上的窗口默认只会被显示而不会被激活,因此 driver 还会在 worker 上报 `showing` 后把对话框抬升到前台——附加输入队列并调用 `SetForegroundWindow`,按关闭节奏重试直到 `Show` 内创建的窗口出现。worker 线程启用宿主接受的最佳线程 DPI 感知(`SetThreadDpiAwarenessContext`,按 per-monitor-v2 → per-monitor → system-aware 级联并检查返回值),严格优于脚本的系统 DPI 上限;DPI 保持为纯外观的 best-effort——全部不被接受的宿主仍得到现代对话框,而不会降级到回退链。模块切分让覆盖率在任何主机上都诚实:`win32-dialog-logic.ts`(纯时序)与 `win32-dialog.ts`(driver)在任何平台对假件测试;`win32-dialog-bindings.ts` 对 mock 的 `koffi` COM 世界测试(`dsh-session-persistence-jsonl` 的技法);POSIX 主机把真实 spawn 管道跑到 koffi 加载失败的拒绝;win32 主机跑真实的"打开并中止关闭"冒烟。该冒烟位于 `processBoundTests`:threads 池下阻塞在原生模态中的 worker 会卡死池的收尾,fork 则能容纳它。PowerShell 链(见 [DPI note](../bug-fix/2026-08-01-windows-picker-pwsh-dpi.md))保留为回退层,触发条件从 `ENOENT` 拓宽为 pwsh 的任何失败,同时关闭了 PowerShell 6 回归。 +`packages/host/directory-picker-native` 现在经 koffi——它已是仓库其他 `win32.ts` 面的工作区依赖——在进程内打开 `IFileOpenDialog`(`FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR`),作为 win32 主层。COM 会话运行在 spawn 出的子进程中,模态 `Show` 永不阻塞宿主事件循环;子进程在阻塞前上报其原生线程 id,driver 通过向该线程的窗口反复投递 `WM_CLOSE`(`EnumThreadWindows`)来服务中止,关闭预算耗尽时 kill 子进程。对话框是子进程的第一个窗口,Windows 会自动激活它,无需手动前台调用。子进程线程启用宿主接受的最佳线程 DPI 感知(`SetThreadDpiAwarenessContext`,按 per-monitor-v2 → per-monitor → system-aware 级联并检查返回值),严格优于脚本的系统 DPI 上限;DPI 保持为纯外观的 best-effort——全部不被接受的宿主仍得到现代对话框,而不会降级。模块切分让覆盖率在任何主机上都诚实:`win32-dialog-logic.ts`(纯时序)与 `win32-dialog.ts`(driver)在任何平台对假件测试;`win32-dialog-bindings.ts` 对 mock 的 `koffi` COM 世界测试(`dsh-session-persistence-jsonl` 的技法);POSIX 主机把真实 spawn 管道跑到 koffi 加载失败的拒绝;win32 主机跑真实的"打开并中止关闭"冒烟。先于本层存在的 PowerShell 链已被删除(见[链删除](../simplification/2026-08-04-drop-windows-powershell-picker-fallback.md)):该层无回退。 ## 考虑过的替代方案 - **预编译原生助手(`native/` 家族,如 `node-addon-landlock-run`)。** 否决:镜像仓库、npm 包家族、MSVC 供给和发布交接——只为交付约 150 行 CI 无法执行的 C(没有真 Windows 通道);koffi 以零新增供应链提供同一 COM 面。 -- **N-API 进程内插件。** 否决:同样的 CI/工具链原因,另加需要自有 C++ 处理 STA 线程与消息泵,而 `worker_threads` + koffi 用 TypeScript 就能表达。 +- **N-API 进程内插件。** 否决:同样的 CI/工具链原因,另加需要自有 C++ 处理 STA 线程与消息泵,而子进程 + koffi 用 TypeScript 就能表达。 - **保留 PowerShell 为主层并探测版本。** 否决:选择器仍被 shell 打包形态挟持(6 与 7、Store 别名、profile),且没有 pwsh 的机器地板仍是 5.1 的旧版对话框;仅把回退触发条件的拓宽吸收进回退层。 - **在主线程上阻塞模态调用。** 直接否决:对话框打开期间 web 宿主必须继续服务 RPC。 ## 后果 -- 每台 Windows 机器都得到带其所支持的最佳 DPI 感知(1703+ 为 per-monitor-v2)的现代对话框,无论是否安装 PowerShell;PowerShell 层只服务 koffi 无法驱动 COM 的主机。 -- 真实对话框渲染与选中路径仍是手动 Windows 检查(自动关闭冒烟证明打开/中止/收尾);卡死的中止可能泄漏一个对话框线程直到进程退出,已记录于包 README。 -- 所用 COM vtable 槽位与 GUID 是冻结的 Windows ABI(Vista 起);koffi 签名错误是可能拖垮整个 Node 进程的原生崩溃风险——`worker_threads` 与主线程共享进程,访问冲突不会只局限在 worker 内,也不会进入 PowerShell 回退。mocked-koffi 的 ABI 钉与真实 win32 冒烟正是为了在交付前捕获这类错误。 -- 打包二进制的 VFS 臂——在 pkg 快照内解析 `./worker.cjs`——不受任何自动化测试覆盖:源码 worker 与普通 Node 下构建出的 `lib/worker.cjs` 已被覆盖,VFS 专属的 spawn 推迟到 Windows CI 路线图。 +- 每台 Windows 机器都得到带其所支持的最佳 DPI 感知(1703+ 为 per-monitor-v2)的现代对话框,无论是否安装 PowerShell。 +- 真实对话框渲染与选中路径仍是手动 Windows 检查(自动关闭冒烟证明打开/中止/收尾)。 +- 所用 COM vtable 槽位与 GUID 是冻结的 Windows ABI(Vista 起);koffi 签名错误可能引发原生访问冲突,但被限制在对话框子进程内——宿主 Node 进程存活,失败原样上报(无回退层;见[链删除](../simplification/2026-08-04-drop-windows-powershell-picker-fallback.md))。mocked-koffi 的 ABI 钉与真实 win32 冒烟正是为了在交付前捕获这类错误。 +- 打包二进制的臂——打包后的可执行文件以对话框入口形式自我 spawn——不受任何自动化测试覆盖:源码平面与普通 node 下构建出的 `lib/worker.cjs` 已被覆盖,打包 spawn 推迟到 Windows CI 路线图。 diff --git a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml b/.agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.i18n.yaml similarity index 52% rename from .agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml rename to .agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.i18n.yaml index d57f65ad1c..344dd2bf6c 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-01-windows-picker-pwsh-dpi.i18n.yaml +++ b/.agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.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/bug-fix/2026-08-01-windows-picker-pwsh-dpi.md -2026-08-01-windows-picker-pwsh-dpi.md: 28630660d1370826c1997be342727175adb081ce -2026-08-01-windows-picker-pwsh-dpi.zh.md: 2be0231032898022cb3d54494fb06b86902b0c66 +# pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.md +2026-08-04-drop-windows-powershell-picker-fallback.md: 619afd31d9ec78cdb8565e29fa942b7db8749365 +2026-08-04-drop-windows-powershell-picker-fallback.zh.md: e14904db46a955d4cf40da195a39bf62cbef96ff diff --git a/.agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.md b/.agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.md new file mode 100644 index 0000000000..619afd31d9 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.md @@ -0,0 +1,38 @@ +# Agent Note: Drop the Windows PowerShell picker fallback + +Status: implemented + +English | [中文](2026-08-04-drop-windows-powershell-picker-fallback.zh.md) + +## Problem + +The win32 branch of the native directory picker kept a two-tier PowerShell fallback under the koffi `IFileOpenDialog` child process: `pwsh.exe` first, then `powershell.exe` (Windows PowerShell 5.1), both running the same WinForms script with a `SetProcessDPIAware` opt-in. The chain existed to keep a working chooser when the koffi tier was "unavailable", but every trigger it plausibly protected was a failure of our own packaging or deployment, not of the operating system: + +- koffi's native binary ships as an ordinary optional dependency (`@koromix/koffi-win32-x64`, no install script); a host that installs the package at all has the binary, and a host that cannot install it fails the package install loudly — the fallback code never loads either. +- "Ancient Windows" cannot occur: the Node versions this repo supports run on Windows generations far newer than the Vista-era `IFileOpenDialog` ABI the dialog needs. +- A koffi/COM defect crashes only the dialog child process (crash isolation); the correct response to our own bug is a surfaced failure, not a silent downgrade to a legacy dialog. + +The chain also cost real complexity: two spawn tiers running one identical script, a fallback trigger widened from `ENOENT` to any pwsh failure to close the PowerShell 6 (no WinForms) regression, a triple-miss `AggregateError` carrying all three causes, and per-tier abort re-checks. The seam already owns the only fallback that matters — the `browse` backend at the composition level, chosen once at boot by `directory-picker-auto`. + +## Decision + +The win32 tier is exactly the koffi `IFileOpenDialog` child process; any failure surfaces as-is with no fallback. The PowerShell chain — the `pwsh` → Windows PowerShell 5.1 cascade, the DPI-corrected WinForms script, the `AggregateError` aggregation — is deleted, and `pickNativeDirectory`'s win32 branch is a single call. `dsh-native-command` remains a dependency for the POSIX tiers. + +The fallback criterion the rest of the package already followed now applies uniformly: a fallback tier exists only for tools the OS/desktop environment provides and may omit (`zenity` → `kdialog` on Linux, which the boot-time probe also samples); tools our own package ships (`koffi`) fail loud. macOS `osascript` stays fallback-free as before. + +This change consolidates and deletes the pwsh-first DPI picker-fix note: its decision is fully reversed here, and its preserved rationale no longer guides future work on a koffi-only tier. What it kept that was real: PowerShell 7 renders the modern `IFileDialog`-based folder picker where 5.1's `FolderBrowserDialog` is hardwired to the legacy `SHBrowseForFolder` tree; the script's `SetProcessDPIAware` corrected the spawn's system-DPI ceiling; the pwsh→5.1 hop existed because a resolvable PowerShell 6 has no WinForms (exit 1, not `ENOENT`). Its rejected alternatives (requiring PowerShell 7, importing `resolvePwshPath`, setting DPI awareness in the harness process) are moot with the chain gone. + +## Alternatives considered + +**Keep the chain but drop the pwsh quality tier (`koffi` → Windows PowerShell 5.1).** Rejected: the remaining tier still defends our own packaged dependency, still costs the script, the widened trigger, and the aggregation, and still hides our own vtable/COM defects behind a legacy dialog. The criterion "fallback only for externally provided tools" admits no Windows tier at all. + +**Keep the chain as-is.** Rejected: it was the only two-level runtime fallback in the picker surface, its triggers were deployment-side failures that fail loud anyway, and it degraded a failed pick into an `AggregateError` whose most actionable entry was a PowerShell host. + +**Fall back to `browse` at runtime when the native pick fails.** Rejected: the seam's flow holes are `single`-kind and the `-auto` composition already picks one backend at boot; a runtime cross-kind hop would double-mount both backends and blur the capability boundary. + +## Consequences + +- The win32 picker's failure surface is one error from one tier; callers see the real cause (koffi load failure, COM refusal, dialog crash) instead of a chain-aggregated error. +- `pwsh`/`powershell.exe` are no longer invoked by this package; the WinForms script, its `SetProcessDPIAware` correction, and the `-STA` flags are gone with them. +- Tests shrink accordingly: the pwsh/5.1 cascade and triple-miss cases are replaced by one "failure surfaces with no fallback" case; the default-adapter test now drives the Linux tier. +- Reintroduction condition: a future win32 mechanism outside our packaging chain (a system-provided dialog host we do not ship) would justify a single fallback tier under the same criterion. diff --git a/.agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.zh.md b/.agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.zh.md new file mode 100644 index 0000000000..e14904db46 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-08-04-drop-windows-powershell-picker-fallback.zh.md @@ -0,0 +1,38 @@ +# Agent Note:删除 Windows PowerShell 选择器回退 + +Status: implemented + +[English](2026-08-04-drop-windows-powershell-picker-fallback.md) | 中文 + +## Problem + +原生目录选择器的 win32 分支在 koffi `IFileOpenDialog` 子进程之下保留了一条两级 PowerShell 回退:先 `pwsh.exe`,再 `powershell.exe`(Windows PowerShell 5.1),两者运行同一个带 `SetProcessDPIAware` 开关的 WinForms 脚本。该链的存在是为了在 koffi 层"不可用"时仍能给出一个可用的选择器,但它可能保护的每一个触发条件都是我们自己打包或部署的失败,而不是操作系统的: + +- koffi 的原生二进制作为普通 optional 依赖(`@koromix/koffi-win32-x64`,无 install script)分发;能装上该包的宿主就一定有二进制,装不上的宿主会在安装期大声失败——回退代码同样不会加载。 +- "上古 Windows"不可能出现:本仓库支持的 Node 版本运行在远比 Vista 时代 `IFileOpenDialog` ABI 新的 Windows 世代上。 +- koffi/COM 缺陷只崩对话框子进程(crash isolation);对我们自己 bug 的正确反应是上报失败,而不是静默降级到旧版对话框。 + +这条链还付出了真实的复杂度:两个 spawn 层运行同一脚本、把回退触发从 `ENOENT` 拓宽为 pwsh 的任何失败以关闭 PowerShell 6(无 WinForms)回归、携带全部三个原因的三连败 `AggregateError`,以及每层的 abort 重检。seam 早已拥有唯一重要的回退——组合层面的 `browse` 后端,由 `directory-picker-auto` 在启动时选择一次。 + +## Decision + +win32 层恰好就是 koffi `IFileOpenDialog` 子进程;任何失败原样上报,无回退。PowerShell 链——`pwsh` → Windows PowerShell 5.1 级联、DPI 修正的 WinForms 脚本、`AggregateError` 聚合——被删除,`pickNativeDirectory` 的 win32 分支成为单次调用。`dsh-native-command` 仍为 POSIX 层保留依赖。 + +本包其余部分早已遵循的回退判据现在统一适用:回退层只存在于操作系统/桌面环境提供且可能缺失的工具(Linux 的 `zenity` → `kdialog`,启动探针同样采样它们);我们自己打包的工具(`koffi`)失败即大声报错。macOS `osascript` 与之前一样保持无回退。 + +本次变更合并并删除了 pwsh 优先的 DPI 选择器修复 Note:其决策在此被完全反转,其保留的 rationale 对只含 koffi 的层不再指导未来工作。其中真实的部分:PowerShell 7 呈现基于 `IFileDialog` 的现代文件夹选择器,而 5.1 的 `FolderBrowserDialog` 被硬连到旧版 `SHBrowseForFolder` 树;脚本的 `SetProcessDPIAware` 修正了 spawn 的系统 DPI 上限;pwsh→5.1 的跳转存在是因为可解析的 PowerShell 6 没有 WinForms(退出码 1,而非 `ENOENT`)。其被拒绝的替代方案(要求 PowerShell 7、导入 `resolvePwshPath`、在 harness 进程设置 DPI 感知)随链删除而失去意义。 + +## Alternatives considered + +**保留链但去掉 pwsh 质量层(`koffi` → Windows PowerShell 5.1)。** 拒绝:剩下的层仍在为我们自己打包的依赖辩护,仍要付出脚本、拓宽的触发与聚合的代价,仍会把我们自己的 vtable/COM 缺陷藏到旧版对话框后面。"仅对外部提供的工具回退"的判据不接受任何 Windows 层。 + +**原样保留链。** 拒绝:它是选择器面上唯一的二级运行时回退,其触发条件是本就大声失败的部署侧失败,并且它把失败的 pick 降级成一个最具可操作性的条目是 PowerShell 宿主的 `AggregateError`。 + +**原生 pick 失败时在运行时回退到 `browse`。** 拒绝:seam 的流程洞是 `single` kind,`-auto` 组合已在启动时选择一个后端;运行时跨 kind 跳转会双挂两个后端并模糊能力边界。 + +## Consequences + +- win32 选择器的失败面是来自单一层的一个错误;调用方看到真实原因(koffi 加载失败、COM 拒绝、对话框崩溃),而不是链式聚合的错误。 +- 本包不再调用 `pwsh`/`powershell.exe`;WinForms 脚本、其 `SetProcessDPIAware` 修正与 `-STA` 标志随之消失。 +- 测试相应缩减:pwsh/5.1 级联与三连败用例被一个"失败原样上报、无回退"用例取代;默认适配器测试改驱动 Linux 层。 +- 重新引入条件:未来出现在我们打包链之外的 win32 机制(我们不随包分发的系统提供的对话框宿主)才值得在同一判据下保留一层回退。 diff --git a/packages/host/directory-picker-native/README.i18n.yaml b/packages/host/directory-picker-native/README.i18n.yaml index 60f534e83b..c1b47710a7 100644 --- a/packages/host/directory-picker-native/README.i18n.yaml +++ b/packages/host/directory-picker-native/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/host/directory-picker-native/README.md -README.md: d48622dead56cce842e0bef0207079ff85b22588 -README.zh.md: 33cb11b4e747b2d98fc1bf179a52e095dcc9bc31 +README.md: 3d270af441bd251c126c8fb3c3d2d7aec95655c9 +README.zh.md: b4a3d91b68c285aad7911ba711348e36ffc7a4c8 diff --git a/packages/host/directory-picker-native/README.md b/packages/host/directory-picker-native/README.md index d48622dead..3d270af441 100644 --- a/packages/host/directory-picker-native/README.md +++ b/packages/host/directory-picker-native/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Windows opens the modern `IFileOpenDialog` in-process — a koffi-driven COM conversation on a worker thread with the best thread DPI awareness the host accepts (per-monitor-v2 first), aborted by posting `WM_CLOSE` to the dialog thread — and falls back to a PowerShell-hosted dialog (`pwsh`, then Windows PowerShell 5.1, which every Windows ships) whenever that native surface is unavailable; a resolvable `pwsh` that cannot deliver the dialog (PowerShell 6 has no WinForms) falls through the same way. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md). +The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Windows opens the modern `IFileOpenDialog` in a spawned child process — a koffi-driven COM conversation on the child's main thread with the best thread DPI awareness the host accepts (per-monitor-v2 first), aborted by posting `WM_CLOSE` to the dialog thread. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md). **Dual-face package**: the browser half (`./client`) registers a renderless flow occupant into [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes — each `open` request drives `host.pickDirectory` and reports the one outcome (picked path / cancel / failure) through the hole's owner conversation. One cordis.yml row therefore composes both sides of the native interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). @@ -17,5 +17,4 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **Linux requires desktop tooling** — with neither Zenity nor KDialog installed, `pick` rejects with an actionable error; it does not fall back to a typed-path prompt (the browse backend is that fallback at the composition level). -- **The Windows fallback chain degrades the dialog** — the in-process picker is the modern Explorer-style dialog; where koffi cannot drive COM the PowerShell tiers take over, and a machine that only reaches Windows PowerShell 5.1 gets the legacy folder tree, DPI-corrected but not the modern UI. -- **A wedged abort can leak one dialog thread** — when `WM_CLOSE` never lands (the dialog window was never created), the driver terminates and unrefs the worker; Node cannot interrupt a thread blocked in the native modal call, so that thread lives until process exit. +- **Windows has no mechanism fallback** — the child-process picker is the only tier: koffi is a packaged dependency whose availability the install guarantees, so a failed pick (COM refusal, dialog crash) surfaces the failure instead of degrading to a PowerShell-hosted dialog (the former `pwsh` → Windows PowerShell 5.1 chain was removed). The browse backend remains the fallback at the composition level. diff --git a/packages/host/directory-picker-native/README.zh.md b/packages/host/directory-picker-native/README.zh.md index 33cb11b4e7..b4a3d91b68 100644 --- a/packages/host/directory-picker-native/README.zh.md +++ b/packages/host/directory-picker-native/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。Windows 在进程内打开现代 `IFileOpenDialog`——由 koffi 在 worker 线程上驱动的 COM 会话,采用宿主接受的最佳线程 DPI 感知(优先 per-monitor-v2),中止时向对话框线程投递 `WM_CLOSE`——当该原生面不可用时回退到 PowerShell 承载的对话框(先 `pwsh`,再回退到每台 Windows 都自带的 Windows PowerShell 5.1);可解析但无法呈现对话框的 `pwsh`(PowerShell 6 没有 WinForms)同样落入该回退。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。 +[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。Windows 在 spawn 的子进程中打开现代 `IFileOpenDialog`——由 koffi 在子进程主线程上驱动的 COM 会话,采用宿主接受的最佳线程 DPI 感知(优先 per-monitor-v2),中止时向对话框线程投递 `WM_CLOSE`。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。 **双面包**:browser half(`./client`)向 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞注册一个无渲染的流程占用者——每次 `open` 请求驱动 `host.pickDirectory`,并经洞的 owner 会话上报唯一结果(所选路径/取消/失败)。因此一行 cordis.yml 同时组合原生交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 @@ -17,5 +17,4 @@ ## 已知限制与延期工作 - **Linux 依赖桌面工具**——Zenity 与 KDialog 均未安装时,`pick` 以包含解决建议的错误拒绝;它不会回退为手输路径提示(组合层面的回退是 browse 后端)。 -- **Windows 回退链会降级对话框**——进程内选择器就是现代资源管理器风格对话框;koffi 无法驱动 COM 时由 PowerShell 层级接手,最终只到达 Windows PowerShell 5.1 的机器得到旧版文件夹树,DPI 已修正,但界面不是现代的。 -- **卡死的中止可能泄漏一个对话框线程**——当 `WM_CLOSE` 始终投递不到(对话框窗口从未创建)时,driver 会 terminate 并 unref 该 worker;Node 无法打断阻塞在原生模态调用里的线程,因此该线程会存活到进程退出。 +- **Windows 没有机制级回退**——子进程选择器是唯一层级:koffi 是打包依赖,其可用性由安装保证,因此一次失败的 pick(COM 拒绝、对话框崩溃)直接上报失败,不会降级到 PowerShell 承载的对话框(原有的 `pwsh` → Windows PowerShell 5.1 链已删除)。组合层面的回退仍是 browse 后端。 diff --git a/packages/host/directory-picker-native/src/index.ts b/packages/host/directory-picker-native/src/index.ts index 7e253ee634..3a7e3bd05f 100644 --- a/packages/host/directory-picker-native/src/index.ts +++ b/packages/host/directory-picker-native/src/index.ts @@ -2,11 +2,10 @@ * Native backend of the directory-picker seam: registers `ctx.directoryPicker` * with the `native` capability, opening one native OS chooser on the host * display per pick (macOS `osascript`, Linux Zenity with a KDialog fallback; - * Windows opens the modern `IFileOpenDialog` in-process — a koffi-driven COM - * conversation on a worker thread — and falls back to a PowerShell-hosted - * dialog (`pwsh`, then Windows PowerShell 5.1) when that native surface is - * unavailable). Only viable when the operator sits at the host's screen; - * remote deployments compose the browse backend instead. + * Windows opens the modern `IFileOpenDialog` in a spawned child process — a + * koffi-driven COM conversation on the child's main thread). Only viable when + * the operator sits at the host's screen; remote deployments compose the + * browse backend instead. * @module @deepseek-ai/dsh-host-directory-picker-native */ diff --git a/packages/host/directory-picker-native/src/native-picker.ts b/packages/host/directory-picker-native/src/native-picker.ts index 4b4d75fe32..e25b04ce6c 100644 --- a/packages/host/directory-picker-native/src/native-picker.ts +++ b/packages/host/directory-picker-native/src/native-picker.ts @@ -67,62 +67,13 @@ export async function pickNativeDirectory( } if (platform === 'win32') { - // Primary: the in-process koffi-backed IFileOpenDialog worker — the modern - // picker with per-monitor-v2 DPI, no PowerShell dependency, and abort - // support. Any non-abort failure (koffi unavailable, ancient Windows, COM - // refusal) falls back to the PowerShell chain below. + // The koffi-backed IFileOpenDialog child process — the modern picker with + // per-monitor-v2 DPI and abort support. koffi is a packaged dependency + // whose availability the install guarantees, so there is no fallback + // tier: any failure surfaces as-is (the former PowerShell chain was + // removed — see the simplification Agent Note). const pickDialog = internals.pickWin32Dialog ?? pickWin32Directory - let dialogError: unknown - try { - return await pickDialog(signal) - } catch (error: unknown) { - rethrowIfAborted(signal, error) - dialogError = error - } - - // PowerShell fallback: PowerShell 7 renders the modern IFileDialog folder - // picker, while Windows PowerShell 5.1's FolderBrowserDialog is hardwired - // to the legacy SHBrowseForFolder tree. Prefer pwsh, but ANY pwsh failure - // falls back to 5.1 (which every Windows ships): a resolvable pwsh can - // still be unable to deliver the dialog — PowerShell 6 has no WinForms, - // so its Add-Type exits 1, not ENOENT. Both hosts spawn DPI-unaware, so - // the script opts the process into system DPI awareness before any window - // is created. No Description is set: the modern dialog renders it as a - // bottom strip and the classic dialog as an unthemed box. - const script = [ - "$ErrorActionPreference = 'Stop'", - "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class DpiAware { [DllImport(\"user32.dll\")] public static extern bool SetProcessDPIAware(); }'", - '[DpiAware]::SetProcessDPIAware() | Out-Null', - 'Add-Type -AssemblyName System.Windows.Forms', - '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog', - '$dialog.ShowNewFolderButton = $true', - '$result = $dialog.ShowDialog()', - 'if ($result -eq [System.Windows.Forms.DialogResult]::OK) {', - ' [Console]::OutputEncoding = [System.Text.Encoding]::UTF8', - ' [Console]::WriteLine($dialog.SelectedPath)', - '}', - ].join('; ') - let pwshError: unknown - try { - const result = await run('pwsh.exe', ['-NoProfile', '-STA', '-Command', script], signal) - return outputPath(result.stdout) - } catch (error: unknown) { - rethrowIfAborted(signal, error) - pwshError = error - } - try { - const result = await run('powershell.exe', ['-NoProfile', '-STA', '-Command', script], signal) - return outputPath(result.stdout) - } catch (error: unknown) { - rethrowIfAborted(signal, error) - // Triple miss: every tier failed. Surface all three causes — the - // in-process dialog's reason is otherwise unrecoverable from the last - // PowerShell error alone. - throw new AggregateError( - [dialogError, pwshError, error], - 'native directory picker failed: the in-process dialog and both PowerShell hosts failed', - ) - } + return await pickDialog(signal) } if (platform === 'linux') { diff --git a/packages/host/directory-picker-native/tests/native-picker.spec.ts b/packages/host/directory-picker-native/tests/native-picker.spec.ts index 24c33e473e..66f4845b4b 100644 --- a/packages/host/directory-picker-native/tests/native-picker.spec.ts +++ b/packages/host/directory-picker-native/tests/native-picker.spec.ts @@ -1,8 +1,7 @@ /** - * Native picker tier selection and the execFile adapter: the in-process - * dialog primary, the pwsh → Windows PowerShell 5.1 fallback chain (any - * non-abort pwsh failure cascades), the abort-never-falls-through rule, and - * the triple-miss AggregateError carrying the dialog/pwsh/5.1 causes. + * Native picker tier selection and the execFile adapter: the Win32 dialog + * primary (failures surface as-is, no fallback tier), the abort rule, and + * the POSIX command tiers (osascript, Zenity → KDialog). */ type ExecFileCallback = ( @@ -30,7 +29,7 @@ function failure(code: string | number, stderr = ''): Error { const signal = () => new AbortController().signal -/** The PowerShell chain is reachable only when the in-process dialog fails. */ +/** A Win32 dialog that always fails — the no-fallback case. */ const noDialog = async (): Promise => { throw new Error('dialog unavailable') } describe('native directory picker', () => { @@ -56,7 +55,7 @@ describe('native directory picker', () => { await expect(pickNativeDirectory(signal(), { platform: 'darwin', run })).rejects.toBe(reason) }) - it('prefers the in-process Win32 dialog and never spawns PowerShell when it answers', async () => { + it('uses the Win32 dialog and never spawns a command when it answers', async () => { const run = vi.fn() const pickWin32Dialog = vi.fn(async (): Promise => 'C:\\work\\selected') await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog })).resolves.toBe('C:\\work\\selected') @@ -65,55 +64,11 @@ describe('native directory picker', () => { expect(run).not.toHaveBeenCalled() }) - it('falls back to pwsh when the dialog is unavailable and maps empty output to cancellation', async () => { - const run = vi.fn(async () => ({ stdout: 'C:\\work\\project\r\n', stderr: '' })) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog: noDialog })).resolves.toBe('C:\\work\\project') - expect(run).toHaveBeenCalledWith( - 'pwsh.exe', - expect.arrayContaining(['-NoProfile', '-STA', '-Command']), - expect.any(AbortSignal), - ) - const script = run.mock.calls[0]?.[1].at(-1) - expect(script).toContain("$ErrorActionPreference = 'Stop'") - expect(script).toContain('SetProcessDPIAware') - // Description renders as a bottom strip (modern) / unthemed box (classic); never set it. - expect(script).not.toContain('Description') - run.mockResolvedValueOnce({ stdout: '', stderr: '' }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog: noDialog })).resolves.toBeNull() - }) - - it('falls back to Windows PowerShell 5.1 whenever pwsh cannot deliver the dialog', async () => { + it('surfaces the Win32 dialog failure with no fallback', async () => { const run = vi.fn() - .mockRejectedValueOnce(failure('ENOENT')) - .mockResolvedValueOnce({ stdout: 'C:\\work\\fallback\r\n', stderr: '' }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog: noDialog })).resolves.toBe('C:\\work\\fallback') - expect(run.mock.calls.map(call => call[0])).toEqual(['pwsh.exe', 'powershell.exe']) - // Both runtimes execute the identical script, so DPI awareness holds either way. - expect(run.mock.calls[0]?.[1].at(-1)).toBe(run.mock.calls[1]?.[1].at(-1)) - - // A resolvable pwsh that cannot deliver the dialog (PowerShell 6: no - // WinForms, Add-Type exits 1 - not ENOENT) reaches 5.1 all the same. - const pwsh6 = vi.fn() - .mockRejectedValueOnce(failure(1, "Cannot load assembly 'System.Windows.Forms'")) - .mockResolvedValueOnce({ stdout: 'C:\\work\\legacy\r\n', stderr: '' }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run: pwsh6, pickWin32Dialog: noDialog })).resolves.toBe('C:\\work\\legacy') - expect(pwsh6.mock.calls.map(call => call[0])).toEqual(['pwsh.exe', 'powershell.exe']) - - const cancelled = vi.fn() - .mockRejectedValueOnce(failure('ENOENT')) - .mockResolvedValueOnce({ stdout: '', stderr: '' }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', run: cancelled, pickWin32Dialog: noDialog })).resolves.toBeNull() - - // Triple miss: the surfaced AggregateError carries all three causes, - // including the otherwise-lost in-process dialog failure. - const failed = vi.fn() - .mockRejectedValueOnce(failure('ENOENT')) - .mockRejectedValueOnce(failure(2)) - const tripleMiss = await pickNativeDirectory(signal(), { platform: 'win32', run: failed, pickWin32Dialog: noDialog }) - .then(() => { throw new Error('expected rejection') }, (error: unknown) => error as AggregateError) - expect(tripleMiss.message).toContain('the in-process dialog and both PowerShell hosts failed') - expect((tripleMiss.errors[0] as Error).message).toBe('dialog unavailable') - expect((tripleMiss.errors[2] as Error).message).toContain('command failed') + await expect(pickNativeDirectory(signal(), { platform: 'win32', run, pickWin32Dialog: noDialog })) + .rejects.toThrow('dialog unavailable') + expect(run).not.toHaveBeenCalled() }) it('wires the real Win32 dialog as the default tier', async () => { @@ -127,52 +82,38 @@ describe('native directory picker', () => { expect(run).not.toHaveBeenCalled() }) - it('does not fall back when the caller aborted the dialog or the pwsh spawn', async () => { + it('does not fall back when the caller aborted the dialog', async () => { const abort = new AbortController() abort.abort(new Error('closed')) const run = vi.fn() await expect(pickNativeDirectory(abort.signal, { platform: 'win32', run, pickWin32Dialog: noDialog })).rejects.toThrow('dialog unavailable') expect(run).not.toHaveBeenCalled() - - const liveThenAborted = new AbortController() - const abortingRun = vi.fn(async () => { - liveThenAborted.abort(new Error('closed')) - throw failure('ENOENT') - }) - await expect(pickNativeDirectory(liveThenAborted.signal, { platform: 'win32', run: abortingRun, pickWin32Dialog: noDialog })) - .rejects.toThrow('command failed') - expect(abortingRun).toHaveBeenCalledOnce() }) it('runs the default command adapter without a shell and preserves command failures', async () => { execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { - callback(null, 'C:\\work\\default\r\n', '') + callback(null, '/home/test/project\n', '') }) - await expect(pickNativeDirectory(signal(), { platform: 'win32', pickWin32Dialog: noDialog })).resolves.toBe('C:\\work\\default') + await expect(pickNativeDirectory(signal(), { platform: 'linux' })).resolves.toBe('/home/test/project') const [command, args, options] = execFileMock.mock.calls[0]! - expect(command).toBe('pwsh.exe') - expect(args).toEqual(expect.arrayContaining(['-NoProfile', '-STA', '-Command'])) + expect(command).toBe('zenity') + expect(args).toEqual(expect.arrayContaining(['--file-selection', '--directory'])) expect(options.encoding).toBe('utf8') expect(options.windowsHide).toBe(true) expect(options.signal).toBeInstanceOf(AbortSignal) - // Both chain tiers fail: pwsh's code-7 failure now reaches 5.1, whose - // failure is the one the caller sees. - const pwshError = Object.assign(new Error('pwsh failed'), { code: 7 }) - const commandError = Object.assign(new Error('powershell failed'), { code: 7 }) + // A non-cancellation command failure surfaces as-is with its cause and + // captured stdio attached; no tier masks or rewraps it. execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { - callback(pwshError, '', 'no WinForms') + callback(Object.assign(new Error('zenity failed'), { code: 7 }), 'partial output', 'failure details') }) - execFileMock.mockImplementationOnce((_command, _args, _options, callback) => { - callback(commandError, 'partial output', 'failure details') - }) - const surfaced = await pickNativeDirectory(signal(), { platform: 'win32', pickWin32Dialog: noDialog }) - .then(() => { throw new Error('expected rejection') }, (error: unknown) => error as AggregateError) - expect(surfaced.errors[2]).toMatchObject({ - message: 'powershell failed', cause: commandError, code: 7, + const surfaced = await pickNativeDirectory(signal(), { platform: 'linux' }) + .then(() => { throw new Error('expected rejection') }, (error: unknown) => error as Error) + expect(surfaced).toMatchObject({ + message: 'zenity failed', code: 7, stdout: 'partial output', stderr: 'failure details', }) - expect(execFileMock.mock.calls.map(call => call[0])).toEqual(['pwsh.exe', 'pwsh.exe', 'powershell.exe']) + expect((surfaced as { cause?: unknown }).cause).toBeInstanceOf(Error) }) it('uses the current process platform when no platform override is supplied', async () => { @@ -184,6 +125,11 @@ describe('native directory picker', () => { await expect(pickNativeDirectory(signal(), { run, pickWin32Dialog })).resolves.toBe(expected) }) + it('maps empty command output to cancellation', async () => { + const run = vi.fn(async () => ({ stdout: '', stderr: '' })) + await expect(pickNativeDirectory(signal(), { platform: 'linux', run })).resolves.toBeNull() + }) + it('uses Zenity on Linux and falls back to KDialog only when Zenity is missing', async () => { const run = vi.fn() .mockRejectedValueOnce(failure('ENOENT')) From 00621f92d29a4b22b925da27ced6169cb886bd43 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Tue, 4 Aug 2026 01:49:05 +0800 Subject: [PATCH 61/61] fix(picker): keep the worker-boundary mock off the vitest IPC channel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The mocked process.send consumed vitest's own fork-pool IPC messages and immediately ran the post callback, whose disconnect() severed the test worker's channel (process.connected is true under forks) — the whole spec's results vanished and win32-dialog-bindings.ts/win32-dialog-worker.ts fell to near-zero coverage on CI. The mock now records without invoking the callback or disconnecting; the real close lifecycle stays with built-worker.e2e.ts. Verified under both the threads and forks pools. --- .../tests/win32-dialog-bindings.spec.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts index 9403bb7e36..b8ff4c3f1a 100644 --- a/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts +++ b/packages/host/directory-picker-native/tests/win32-dialog-bindings.spec.ts @@ -271,9 +271,13 @@ describe('the worker entry over a mocked process boundary', () => { const installBoundary = (): { posted: { kind: string; message?: string }[] } => { const posted: { kind: string; message?: string }[] = [] process.env.DSH_DIALOG_TITLE = 'Pick' - ;(process as { send?: unknown }).send = (message: { kind: string }, callback?: () => void) => { + // Never invoke the post callback: it runs the worker's disconnect(), and + // this process is IPC-connected under the forks pool — severing vitest's + // own channel would kill the test worker. The real close lifecycle + // belongs to built-worker.e2e.ts. + ;(process as { send?: unknown }).send = (message: { kind: string }) => { posted.push(message) - callback?.() + return true } return { posted } }