diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml index be7aedb4bd..f03f7e81ad 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md -2026-07-10-single-file-executable-sdk-runtime-distribution.md: e5438fc01fdd634cd4d8535dfa37a1de356da04d -2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md: 218133f077bed7584b6a26fea5f939b64d4fd670 +2026-07-10-single-file-executable-sdk-runtime-distribution.md: 8731528b9ae600bb8bfe12738669f3a84c11a06b +2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md: 755b4bd7ddbe9b88b4f40b8a3ae7419f746b8dde diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md index e5438fc01f..8731528b9a 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md @@ -23,40 +23,40 @@ The exe is packaged with the **`--sea` (enhanced SEA) mode** of [@yao-pkg/pkg](h Terminology reminder: pkg's `/snapshot` VFS has nothing to do with this repo's testing-system "snapshot" (ACP replay expected outputs, `$DSH_SNAPSHOT`); this document says "VFS" for the former. -### The serving interface is a plugin: the two packages sdk/server + sdk/python-runtime +### The serving interface is a plugin inside the dsh application -The deterministic protocol implementation (`server.ts` / `transport.ts`) lands as two packages on the existing `acp/acp` + `examples/acp-demo` pattern — the serving surface is itself a plugin: +The deterministic serving surface is a plugin selected by the packaged `dsh` application: - [`packages/sdk/server`](../../../../packages/sdk/server/README.md) (`@deepseek-ai/dsh-sdk-jsonrpc-server`): the pure protocol plugin; on apply it mounts `HarnessSdkJsonRpcServer` plus a line-delimited JSON-RPC transport on the process stdio, with disposal through `ctx.effect()`. Whether to serve is decided by `cordis.yml`; a yml that does not mount it is a legitimate process that does not serve. Protocol-level exit belongs to the plugin (after answering and flushing the `shutdown` response it disposes the root runtime so persistence drains, then `exit(0)`; an HMR-style unload only stops the service without exiting the process). -- [`packages/sdk/python-runtime`](../../../../packages/sdk/python-runtime/README.md) (`@deepseek-ai/dsh-sdk-python-runtime`): a private packaged entry — `installFailLoud` + `loadEnv` + config discovery + `boot()` from [`dsh-app-boot`](../../../../packages/boot/app-boot/src/index.ts), done once boot completes; the server is brought up by the `dsh-sdk-jsonrpc-server` entry in the yml. Its only dependency is app-boot. Process-level exit belongs to the packaged entry (stdin EOF/SIGTERM → dispose then 0, SIGINT → 130). +- [`apps/cli`](../../../../apps/cli/README.md) (`@deepseek-ai/dsh`): the packaged application entry; its `sdk` profile mounts `dsh-sdk-jsonrpc-server`, and the CLI owns environment layering, profile composition, stdin/signal shutdown, and process exit. -Config discovery has two channels and fails loudly when both are missing: the `DSH_CORDIS_CONFIG` environment variable first (the SDK client convention), then an argv positional argument; no default path and no built-in fallback whatsoever — "the plugins actually booted are decided by an external cordis.yml" is a hard semantic. +The Python client supplies an explicit Harness home and selects the `sdk` profile plus ordered patch files. A missing home, profile, bundle, or server row fails loudly; there is no external complete-config fallback. The [Python profile-runtime decision](2026-08-23-python-sdk-dsh-profile-runtime.md) owns this application surface. ### Plugin resolution: the VFS holds a real package tree, the closure manifest IS the deploy root Inside the exe's VFS sits a **real package tree in build-artifact form** (each package's `lib/` plus a real `node_modules`). The packaged JSON-RPC entry supplies its installed harness base to app-boot's root Include: relative plugin specifiers resolve from the external configuration directory, while bare package names resolve from the VFS, so a configuration inside another Node project cannot shadow the packaged plugin set. The ordinary development bin leaves bare packages configuration-owned. Bare specifiers in the packaged entry resolve upward along `node_modules` from the entry's position inside the VFS and land inside the VFS naturally. The closed set needs no allowlist code — the set is whatever the VFS has installed, and importing a name outside the set fails. -The deploy root is [`python/sdk-runtime/package.json`](../../../../python/sdk-runtime/package.json) (`dsh-sdk-python-runtime-closure`, a pnpm workspace member and a zero-code pure dependency manifest) — the unified source of truth for "which plugins the exe ships" and "what the Python runtime distributes". Adding a plugin to the exe = adding one dependency line to the manifest and repackaging. [`scripts/verify-runtime-closure.ts`](../../../../scripts/verify-runtime-closure.ts) reads every shipped `packages/preset/agent-presets/presets/*/agent.cordis.yml`, evaluates `disabled` conditions that compare `process.platform` for every target in `python/sdk-runtime/platforms.json`, and requires each active workspace plugin at the runtime root through an explicit `workspace:` dependency. It also traverses every workspace package covered by that manifest and requires every non-optional workspace peer, reporting the complete preset or referencing-package → missing-dependency chain; unknown platform conditions remain active so a plugin cannot be omitted by an unsupported expression. `pnpm run hygiene`, CI static, and the single-exe build run it before packaging. Deploy also packs by each package's `files`, so the shared chunks tsdown splits out must be covered by `files`. +The deploy root is [`python/sdk-runtime/package.json`](../../../../python/sdk-runtime/package.json) (`dsh-python-runtime-closure`, a pnpm workspace member and a zero-code pure dependency manifest) — the unified source of truth for "which plugins the exe ships" and "what the Python runtime distributes". Adding a plugin to the exe = adding one dependency line to the manifest and repackaging. [`scripts/verify-runtime-closure.ts`](../../../../scripts/verify-runtime-closure.ts) reads every shipped `packages/preset/agent-presets/presets/*/agent.cordis.yml`, evaluates `disabled` conditions that compare `process.platform` for every target in `python/sdk-runtime/platforms.json`, and requires each active workspace plugin at the runtime root through an explicit `workspace:` dependency. It also traverses every workspace package covered by that manifest and requires every non-optional workspace peer, reporting the complete preset or referencing-package → missing-dependency chain; unknown platform conditions remain active so a plugin cannot be omitted by an unsupported expression. `pnpm run hygiene`, CI static, and the single-exe build run it before packaging. Deploy also packs by each package's `files`, so the shared chunks tsdown splits out must be covered by `files`. The deploy root includes `@deepseek-ai/dsh-mcp-client` as an explicitly supported custom-configuration plugin even though no shipped preset mounts it. An external config can therefore connect to user-supplied stdio and Streamable HTTP MCP servers and register their tools; the distribution does not carry those servers or extend the bridge to MCP Resources and Prompts. The executable and installed-wheel smokes start a temporary stdio server, discover its tool, and complete one model-requested call. ### Build pipeline and artifacts -[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts): runtime closure verification → `pnpm run build` → (after clearing) `pnpm --filter dsh-sdk-python-runtime-closure deploy --legacy --prod --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true` **directly into** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/` → restore any direct workspace package that legacy deploy hoisted back under the source manifest's `node_modules`, omitting its package-local dependency tree and rejecting any remaining manifest gap → replace every staged dependency symlink with its target bytes, remove package-manager `.bin` links, and fail if any symlink remains → inject the pkg configuration (`bin` points at `node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js` inside the closure, `assets` is a full glob — dynamic import is invisible to pkg's static analysis, so everything must be packed in explicitly) → stage the target `node-pty` addon → one `pkg --sea` per target → the executables `dsh-jsonrpc-agent-pkg--` land in `dist-exe/` and are copied back into the runtime directory. Linux installs build `pty.node` from source; CI rebuilds that addon inside the matching manylinux 2.28 container before packaging, and the builder copies it from the root install into the staged closure because legacy deploy omits that side-effect directory. Every target copies its native `@vscode/ripgrep` binary beside the executable as the required `-rg` sidecar; pkg runtimes select that sidecar through `process.pkg`, while ordinary Node execution uses `@vscode/ripgrep` directly. macOS uses its target prebuild and also emits the required `-spawn-helper`. CI treats these products as intermediate test inputs and retains their platform wheels. All four deploy flags are grounded in measurement: `--legacy` is the mandatory path with inject-workspace-packages off; hoisted gives pkg a stable single-instance layout that the explicit materialization pass makes symlink-free; disabling automatic peer installation prevents undeclared peers from expanding the closure; link-workspace-packages selects direct workspace dependencies. [`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) overrides the transitive `@deepseek-ai/cosmokit` and `@deepseek-ai/schemastery` semver requests to the pinned vendor sources so legacy deploy never resolves those unpublished names from a registry. +[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts): runtime closure verification → `pnpm run build` → (after clearing) `pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true` **directly into** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/` → restore direct workspace packages omitted by legacy deploy and reject any remaining manifest gap → replace staged dependency symlinks with their target bytes, remove package-manager `.bin` links, and fail if any symlink remains → inject pkg configuration whose bin is `node_modules/@deepseek-ai/dsh/lib/bin.js` and whose assets cover dynamic profile, bundle, frontend, preset, native-library, and configuration reads → stage the target `node-pty` addon → invoke `pkg --sea` once per target → write `deepseek-harness-sdk-runtime--` under `dist-exe/` and copy it into the runtime directory. Linux CI rebuilds `pty.node` inside the matching manylinux 2.28 container because legacy deploy omits that install side effect. Every target copies its native `@vscode/ripgrep` binary beside the executable as the required `-rg` sidecar; pkg runtimes select that sidecar through `process.pkg`, while ordinary Node execution uses `@vscode/ripgrep` directly. macOS uses its target prebuild and also emits the required `-spawn-helper`. All four deploy flags are grounded in measurement: `--legacy` is the mandatory path with inject-workspace-packages off; hoisted gives pkg a stable single-instance layout that the explicit materialization pass makes symlink-free; disabling automatic peer installation prevents undeclared peers from expanding the closure; link-workspace-packages selects direct workspace dependencies. [`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) overrides the transitive `@deepseek-ai/cosmokit` and `@deepseek-ai/schemastery` semver requests to the pinned vendor sources so legacy deploy never resolves those unpublished names from a registry. -CI: [`.github/workflows/build-exe-for-python-sdk.yml`](../../../../.github/workflows/build-exe-for-python-sdk.yml) is called for all three targets by the [installed-wheel Python runtime pull-request validation](../testing/2026-08-23-installed-python-wheel-black-box-ci.md) and the [public publication workflow](../process/2026-08-11-python-publication-workflow.md); `workflow_dispatch` and the `build-exe` label can still select a subset. Native builds run on linux-x64 / linux-arm64 (`ubuntu-24.04-arm`) / macos-arm64, with `~/.pkg-cache` cached, and pkg handles macOS ad-hoc signing. Each leg installs the release-shaped SDK and runtime wheels into a clean venv outside the checkout, proves their package and executable provenance, then drives the complete keyless scenario set through the public SDK and direct NDJSON JSON-RPC. Trusted pull requests additionally run a real DeepSeek two-turn tool smoke on every target; fork and Dependabot heads receive no key. Linux inspects the executable and native addon's GLIBC requirements and runs an additional manylinux 2.28 smoke, while macOS verifies that the executable's deployment target fits the wheel tag. A full three-target run retains four artifacts, each containing one release file: the platform-independent SDK wheel and three native runtime wheels; a subset dispatch retains the SDK wheel and selected runtime wheels. Bare executables and source bundles remain intermediate test inputs. [`.gitlab-ci.yml`](../../../../.gitlab-ci.yml) accepts `python-v` tag pipelines whose version matches the root `package.json`, builds one SDK wheel and three native runtime wheels, then a single serialized job checks and publishes all four to the project PyPI registry. Windows is a non-goal. +CI: [`.github/workflows/build-exe-for-python-sdk.yml`](../../../../.github/workflows/build-exe-for-python-sdk.yml) is called for all four targets by the [installed-wheel Python runtime pull-request validation](../testing/2026-08-23-installed-python-wheel-black-box-ci.md) and the [public publication workflow](../process/2026-08-11-python-publication-workflow.md); `workflow_dispatch` and the `build-exe` label can still select a subset. Native builds run on linux-x64 / linux-arm64 (`ubuntu-24.04-arm`) / macos-arm64 / win-x64 (`windows-2025`), with `~/.pkg-cache` cached where applicable, and pkg handles macOS ad-hoc signing. Each leg installs the release-shaped SDK and runtime wheels into a clean venv outside the checkout, proves their package and executable provenance, then drives the complete keyless scenario set through the public SDK and direct NDJSON JSON-RPC. Trusted pull requests additionally run a real DeepSeek two-turn tool smoke on every target; fork and Dependabot heads receive no key. Linux inspects the executable and native addon's GLIBC requirements and runs an additional manylinux 2.28 smoke, while macOS verifies that the executable's deployment target fits the wheel tag. A full four-target run retains five artifacts, each containing one release file: the platform-independent SDK wheel and four native runtime wheels; a subset dispatch retains the SDK wheel and selected runtime wheels. Bare executables and source bundles remain intermediate test inputs. [`.gitlab-ci.yml`](../../../../.gitlab-ci.yml) accepts `python-v` tag pipelines whose version matches the root `package.json`, builds one SDK wheel and four native runtime wheels, then a single serialized job checks and publishes all five to the project PyPI registry. The [Windows x64 runtime decision](2026-08-23-python-sdk-windows-x64-runtime.md) owns the fourth target and the explicit exclusion of Windows arm64. ### Python SDK distribution: two carriers, exe for production, node for development -The Python SDK lives at [`python/`](../../../../python/README.md): `python/sdk` (the client) + `python/sdk-runtime` (the runtime carrier package). The runtime package's data directory holds the checked-in default `runtime/cordis.yml`, the build-injected platform exe with its required `-rg` sidecar and optional macOS helper, and the build-injected `runtime/node/` closure tree. `resolve_bundled_launch_args()` automatic resolution **finds the exe only**; the node carrier is enabled only by an explicit `DSH_RUNTIME_MODE=node` (running `runtime/node/node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js`, requiring a system node ≥22.19), positioned as the development-verification channel for members of this repo, and does not enter wheel distributions. +The Python SDK lives at [`python/`](../../../../python/README.md): `python/sdk` is the client and `python/sdk-runtime` is the runtime carrier package. The runtime package's data directory holds the build-injected platform executable with its required `-rg` sidecar and optional macOS helper, plus the build-injected `runtime/node/` closure tree for repository development. `resolve_bundled_launch_args()` selects the executable by default; explicit `DSH_RUNTIME_MODE=node` runs `runtime/node/node_modules/@deepseek-ai/dsh/lib/bin.js` on system Node 22.19 or newer. The node carrier never enters wheel distributions, and neither carrier uses a checked-in complete `cordis.yml`. -[`scripts/build-python-release.py`](../../../../scripts/build-python-release.py) reads the authoritative `X.Y.Z` or prerelease version from the repository root `package.json`, converts prereleases to their PEP 440 spelling, and stages both packages at that wheel version, with `deepseek-harness-sdk` depending exactly on the matching `deepseek-harness-runtime-bin`. An optional `python-v` release tag is a consistency assertion and is rejected when it differs from the repository version; the source `pyproject.toml` development sentinel never determines a release version. Staging also carries the repository license into both wheels and the third-party notices into the bundled runtime wheel. The SDK is a `py3-none-any` wheel; each wheel-only runtime package contains one exe and its architecture-matched `-rg` sidecar, and the macOS wheel also contains its architecture-matched spawn helper. Runtime wheels use one of `py3-none-manylinux_2_28_x86_64`, `py3-none-manylinux_2_28_aarch64`, or the conservative `py3-none-macosx_14_0_arm64` tag for the Node 24 executable's macOS 13.5 deployment target; the Hatch hook rejects sdists, universal tags, mixed-platform payloads, missing or extra sidecars, and unsupported platforms. +[`scripts/build-python-release.py`](../../../../scripts/build-python-release.py) reads the authoritative `X.Y.Z` or prerelease version from the repository root `package.json`, converts prereleases to their PEP 440 spelling, and stages both packages at that wheel version, with `deepseek-harness-sdk` depending exactly on the matching `deepseek-harness-runtime-bin`. An optional `python-v` release tag is a consistency assertion and is rejected when it differs from the repository version; the source `pyproject.toml` development sentinel never determines a release version. Staging also carries the repository license into both wheels and the third-party notices into the bundled runtime wheel. The SDK is a `py3-none-any` wheel; each wheel-only runtime package contains one exe and its architecture-matched ripgrep sidecar, and the macOS wheel also contains its architecture-matched spawn helper. Runtime wheels use `py3-none-manylinux_2_28_x86_64`, `py3-none-manylinux_2_28_aarch64`, the conservative `py3-none-macosx_14_0_arm64` tag for the Node 24 executable's macOS 13.5 deployment target, or `py3-none-win_amd64`; the Hatch hook rejects sdists, universal tags, mixed-platform payloads, missing or extra sidecars, and unsupported platforms. -The exe's "must be explicitly configured" hard semantic is unchanged; the zero-config experience is restored by the wrapper: when the caller gave no `cordis`, named no explicit runtime, and the environment has no `DSH_CORDIS_CONFIG`, the client explicitly injects the checked-in default `cordis.yml` (agent-core + preloaded llm-deepseek + JSONL persistence + bash-local + the `dsh-sdk-jsonrpc-server` serving entry, with `!!js` environment-variable fallbacks) via `DSH_CORDIS_CONFIG`. +The Python client launches the packaged `dsh` command with the selected profile (`sdk` by default), ordered patch files, and an explicit Harness home. The profile owns JSON-RPC serving and application composition; missing homes, profiles, bundles, patches, and server rows fail without an external complete-config fallback. ### Naming lineage -`@deepseek-ai/dsh-sdk-python-runtime` (the private carrier) → `dsh-sdk-python-runtime-closure` (the deploy manifest; no scope prefix, so it is not a dsh release package) → `dsh-jsonrpc-agent-pkg--` (the exe artifacts). The wire `serverInfo.name` stays `deepseek-harness-sdk-runtime` (a protocol-stable value); the Python distribution names are `deepseek-harness-sdk` / `deepseek-harness-runtime-bin`, while the import modules remain `deepseek_harness` / `deepseek_harness_runtime`. +`dsh-python-runtime-closure` is the private deploy manifest and `deepseek-harness-sdk-runtime--` is the executable family. The wire `serverInfo.name` is `deepseek-harness-sdk-runtime`; the Python distribution names are `deepseek-harness-sdk` / `deepseek-harness-runtime-bin`, while the import modules are `deepseek_harness` / `deepseek_harness_runtime`. ## Disposition of worker-style plugins diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md index 218133f077..755b4bd7dd 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md @@ -23,40 +23,40 @@ exe 使用 [@yao-pkg/pkg](https://github.com/yao-pkg/pkg)(vercel/pkg 归档后 术语提醒:pkg 的 `/snapshot` VFS 与本仓库测试体系的「快照」(ACP(Agent Client Protocol)回放预期输出、`$DSH_SNAPSHOT`)无关,本文用「VFS」指前者。 -### 对外服务接口也是插件:sdk/server + sdk/python-runtime 两个包 +### 对外服务接口是 dsh 应用中的插件 -确定性协议实现(`server.ts` / `transport.ts`)按 `acp/acp` + `examples/acp-demo` 的既有模式落为两包——对外服务接口本身也是插件: +确定性服务接口由打包后的 `dsh` 应用选择为插件: - [`packages/sdk/server`](../../../../packages/sdk/server/README.zh.md)(`@deepseek-ai/dsh-sdk-jsonrpc-server`):纯协议插件;执行 `apply` 时,在进程 stdio 上挂载 `HarnessSdkJsonRpcServer` 与按行分隔的 JSON-RPC 传输层,资源释放走 `ctx.effect()`。是否提供服务由 `cordis.yml` 决定;未挂载该插件的配置会启动一个不提供此服务的合法进程。协议级退出归插件所有(应答并确保 `shutdown` 响应发送完毕后,对根运行时执行 dispose(资源释放),让待处理的持久化操作完成,再调用 `exit(0)`;HMR(热模块替换)式卸载只停止服务,不退出进程)。 -- [`packages/sdk/python-runtime`](../../../../packages/sdk/python-runtime/README.zh.md)(`@deepseek-ai/dsh-sdk-python-runtime`):私有打包入口——`installFailLoud` + `loadEnv` + 配置发现 + [`dsh-app-boot`](../../../../packages/boot/app-boot/src/index.ts) 的 `boot()`;`boot()` 完成后入口即完成,服务器由 `cordis.yml` 中的 `dsh-sdk-jsonrpc-server` 条目启动。它只依赖 `app-boot`。进程级退出归打包入口所有(stdin EOF/SIGTERM → dispose 后返回 0,SIGINT → 130)。 +- [`apps/cli`](../../../../apps/cli/README.zh.md)(`@deepseek-ai/dsh`):打包后的应用入口;其 `sdk` profile 挂载 `dsh-sdk-jsonrpc-server`,CLI 负责环境分层、profile 组合、stdin/signal 关闭与进程退出。 -配置发现有两个通道,均缺失时立即报错:优先使用 `DSH_CORDIS_CONFIG` 环境变量(SDK 客户端约定),其次使用 argv 位置参数;没有默认路径或内置回退——「实际启动的插件由外部 `cordis.yml` 决定」是硬语义。 +Python 客户端提供显式 Harness home,并选择 `sdk` profile 与有序 patch 文件。缺失 home、profile、bundle 或 server 配置项都会明确失败;不存在外部完整配置回退。[Python profile 运行时决策](2026-08-23-python-sdk-dsh-profile-runtime.zh.md)负责该应用接口。 ### 插件解析:VFS 装载真实包树,闭包 manifest(元数据清单)就是部署根目录 exe 的 VFS 内是**构建产物形态的真实包树**(各包的 `lib/` + 真实 `node_modules`)。打包专用 JSON-RPC 入口会向 app-boot 的根 Include 提供自身已安装 harness 的基准位置:相对插件说明符从外部配置目录解析,裸包名则从 VFS 解析,因此位于另一个 Node 项目内的配置无法遮蔽已打包的插件集合。普通开发 bin 仍由配置项目提供裸包。打包入口中的裸包名从该入口在 VFS 内的位置沿 `node_modules` 向上解析,自然落在 VFS 内。封闭集不需要白名单代码——VFS 中安装了什么,集合中就有什么;`import()` 集合外的名称会失败。 -部署根目录是 [`python/sdk-runtime/package.json`](../../../../python/sdk-runtime/package.json)(`dsh-sdk-python-runtime-closure`,pnpm 工作区成员、零代码纯依赖 manifest),也是「exe 安装哪些插件」与「Python 运行时分发什么」的统一真源。向 exe 添加插件,就是在 manifest 中增加一行依赖后重新打包。[`scripts/verify-runtime-closure.ts`](../../../../scripts/verify-runtime-closure.ts) 读取每个已发布的 `packages/preset/agent-presets/presets/*/agent.cordis.yml`,针对 `python/sdk-runtime/platforms.json` 中的每个目标解析比较 `process.platform` 的 `disabled` 条件,并要求该目标启用的每个工作区插件都通过显式的 `workspace:` 依赖列在运行时根目录。它还遍历该 manifest 覆盖的全部工作区包,要求每个非可选的工作区对等依赖(peer dependency)都显式列出,并报告“preset 或引用包 → 缺失依赖”的完整链路;无法识别的平台条件会保持启用,避免因不支持的表达式遗漏插件。`pnpm run hygiene`、CI 静态检查与 single-exe 构建都会在打包前运行该门禁。部署还会依据各包的 `files` 字段打包,因此 tsdown 拆出的共享分片必须被 `files` 覆盖。 +部署根目录是 [`python/sdk-runtime/package.json`](../../../../python/sdk-runtime/package.json)(`dsh-python-runtime-closure`,pnpm 工作区成员、零代码纯依赖 manifest),也是「exe 安装哪些插件」与「Python 运行时分发什么」的统一真源。向 exe 添加插件,就是在 manifest 中增加一行依赖后重新打包。[`scripts/verify-runtime-closure.ts`](../../../../scripts/verify-runtime-closure.ts) 读取每个已发布的 `packages/preset/agent-presets/presets/*/agent.cordis.yml`,针对 `python/sdk-runtime/platforms.json` 中的每个目标解析比较 `process.platform` 的 `disabled` 条件,并要求该目标启用的每个工作区插件都通过显式的 `workspace:` 依赖列在运行时根目录。它还遍历该 manifest 覆盖的全部工作区包,要求每个非可选的工作区对等依赖(peer dependency)都显式列出,并报告“preset 或引用包 → 缺失依赖”的完整链路;无法识别的平台条件会保持启用,避免因不支持的表达式遗漏插件。`pnpm run hygiene`、CI 静态检查与 single-exe 构建都会在打包前运行该门禁。部署还会依据各包的 `files` 字段打包,因此 tsdown 拆出的共享分片必须被 `files` 覆盖。 部署根目录显式包含 `@deepseek-ai/dsh-mcp-client`,将其作为自定义配置可用的插件,即使随附 preset 均未挂载该插件。外部配置因此可以连接由用户提供的 stdio 与 Streamable HTTP MCP server 并注册其工具;分发物不包含这些 server,也不将桥接范围扩展到 MCP Resources 和 Prompts。可执行程序与已安装 wheel 包的冒烟测试会启动临时 stdio server,发现其工具,并完成一次由模型请求的调用。 ### 构建流水线与产物 -[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts):运行时闭包校验 → `pnpm run build` →(清空后)`pnpm --filter dsh-sdk-python-runtime-closure deploy --legacy --prod --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true` **直接写入** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/` → 恢复被 legacy deploy 提升回源 manifest 的 `node_modules` 下的任何直接工作区包,同时省略其包内依赖树,并拒绝剩余的 manifest 缺口 → 将暂存依赖中的每个符号链接替换为目标文件内容,删除包管理器的 `.bin` 链接,并在仍有任何符号链接时失败 → 注入 pkg 配置(`bin` 指向闭包内的 `node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js`;`assets` 使用全量 glob,因为动态 `import()` 对 pkg 静态分析不可见,必须显式打入全部内容)→ 暂存目标平台的 `node-pty` addon → 每个构建目标调用一次 `pkg --sea` → 可执行文件 `dsh-jsonrpc-agent-pkg--` 写入 `dist-exe/`,并拷回运行时目录。Linux 安装会从源码构建 `pty.node`;CI 会在打包前进入匹配架构的 manylinux 2.28 容器重新构建该 addon,而 `--legacy` 部署会省略这一副作用目录,因此构建器会把它从根安装目录复制到暂存闭包。每个目标都会把对应的原生 `@vscode/ripgrep` 二进制复制到可执行文件旁,作为必需的 `-rg` 伴随文件;pkg 运行时通过 `process.pkg` 选择该伴随文件,普通 Node 执行则直接使用 `@vscode/ripgrep`。macOS 使用对应目标的预构建产物,并额外生成所需的 `-spawn-helper`。CI 将这些产物作为测试中间输入,只保留对应平台的 wheel 包。四个部署标志都有实测依据:未启用 `inject-workspace-packages` 时必须使用 `--legacy`;`hoisted` 为 pkg 提供稳定的单实例布局,再由显式物化步骤消除符号链接;关闭对等依赖自动安装可防止未声明的对等依赖扩大闭包;`link-workspace-packages` 选择直接工作区依赖。[`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) 将传递的 `@deepseek-ai/cosmokit` 与 `@deepseek-ai/schemastery` semver 请求覆盖到固定的 vendor 源码,使 legacy deploy 不会从注册表解析这些未发布名称。 +[`scripts/build-exe-for-python-sdk.ts`](../../../../scripts/build-exe-for-python-sdk.ts):运行时闭包校验 → `pnpm run build` →(清空后)`pnpm --filter dsh-python-runtime-closure deploy --legacy --prod --config.node-linker=hoisted --config.auto-install-peers=false --config.link-workspace-packages=true` **直接写入** `python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/` → 恢复 legacy deploy 遗漏的直接工作区包,并拒绝剩余的 manifest 缺口 → 将暂存依赖中的符号链接替换为目标文件内容,删除包管理器的 `.bin` 链接,并在仍有任何符号链接时失败 → 注入 pkg 配置,其中 bin 为 `node_modules/@deepseek-ai/dsh/lib/bin.js`,assets 覆盖动态读取的 profile、bundle、前端、preset、原生库与配置文件 → 暂存目标平台的 `node-pty` addon → 每个构建目标调用一次 `pkg --sea` → 将 `deepseek-harness-sdk-runtime--` 写入 `dist-exe/` 并拷回运行时目录。Linux CI 会在匹配的 manylinux 2.28 容器中重新构建 `pty.node`,因为 legacy deploy 会遗漏这一安装副作用。每个目标都会把对应的原生 `@vscode/ripgrep` 二进制复制到可执行文件旁,作为必需的 `-rg` 伴随文件;pkg 运行时通过 `process.pkg` 选择该伴随文件,普通 Node 执行则直接使用 `@vscode/ripgrep`。macOS 使用对应目标的预构建产物,并额外生成所需的 `-spawn-helper`。四个部署标志都有实测依据:未启用 `inject-workspace-packages` 时必须使用 `--legacy`;`hoisted` 为 pkg 提供稳定的单实例布局,再由显式物化步骤消除符号链接;关闭对等依赖自动安装可防止未声明的对等依赖扩大闭包;`link-workspace-packages` 选择直接工作区依赖。[`pnpm-workspace.yaml`](../../../../pnpm-workspace.yaml) 将传递的 `@deepseek-ai/cosmokit` 与 `@deepseek-ai/schemastery` semver 请求覆盖到固定的 vendor 源码,使 legacy deploy 不会从注册表解析这些未发布名称。 -CI 使用 [`.github/workflows/build-exe-for-python-sdk.yml`](../../../../.github/workflows/build-exe-for-python-sdk.yml):[安装后 wheel Python 运行时拉取请求验证](../testing/2026-08-23-installed-python-wheel-black-box-ci.zh.md)与[公开发布工作流](../process/2026-08-11-python-publication-workflow.zh.md)都会调用它构建全部三个目标;`workflow_dispatch` 与 `build-exe` 标签仍可选择部分目标。linux-x64、linux-arm64(`ubuntu-24.04-arm`)和 macos-arm64 三个平台分别进行原生构建,并缓存 `~/.pkg-cache`;macOS 的 ad-hoc 签名由 pkg 处理。每个平台都把发布形态的 SDK wheel 包与运行时 wheel 包安装到 checkout 外的干净 venv,证明包与可执行文件来源,再通过公开 SDK 与直接 NDJSON JSON-RPC 运行完整 keyless 场景。可信拉取请求还会在每个目标上运行真实 DeepSeek 双轮工具冒烟测试;fork 与 Dependabot head 不会获得密钥。Linux 会检查可执行文件和原生 addon 各自的 GLIBC 依赖,并额外运行 manylinux 2.28 冒烟测试;macOS 则验证可执行文件的部署目标符合 wheel 包标签。完整构建三个目标时保留 4 个产物,每个产物只含一个发布文件:平台无关的 SDK wheel 包与 3 个原生运行时 wheel 包;手动选择部分目标时保留 SDK wheel 与所选运行时 wheel。裸 exe 与源码包只作为测试中间输入。[`.gitlab-ci.yml`](../../../../.gitlab-ci.yml) 只接受版本与根目录 `package.json` 匹配的 `python-v` 标签流水线,构建一个 SDK wheel 包和 3 个原生运行时 wheel 包,再由单个串行任务校验并将这 4 个文件发布到项目的 PyPI 注册表。Windows 不在目标范围内。 +CI 使用 [`.github/workflows/build-exe-for-python-sdk.yml`](../../../../.github/workflows/build-exe-for-python-sdk.yml):[安装后 wheel Python 运行时拉取请求验证](../testing/2026-08-23-installed-python-wheel-black-box-ci.zh.md)与[公开发布工作流](../process/2026-08-11-python-publication-workflow.zh.md)都会调用它构建全部四个目标;`workflow_dispatch` 与 `build-exe` 标签仍可选择部分目标。linux-x64、linux-arm64(`ubuntu-24.04-arm`)、macos-arm64 与 win-x64(`windows-2025`)分别进行原生构建,并在适用平台缓存 `~/.pkg-cache`;macOS 的 ad-hoc 签名由 pkg 处理。每个平台都把发布形态的 SDK wheel 包与运行时 wheel 包安装到 checkout 外的干净 venv,证明包与可执行文件来源,再通过公开 SDK 与直接 NDJSON JSON-RPC 运行完整 keyless 场景。可信拉取请求还会在每个目标上运行真实 DeepSeek 双轮工具冒烟测试;fork 与 Dependabot head 不会获得密钥。Linux 会检查可执行文件和原生 addon 各自的 GLIBC 依赖,并额外运行 manylinux 2.28 冒烟测试;macOS 则验证可执行文件的部署目标符合 wheel 包标签。完整构建四个目标时保留 5 个产物,每个产物只含一个发布文件:平台无关的 SDK wheel 包与 4 个原生运行时 wheel 包;手动选择部分目标时保留 SDK wheel 与所选运行时 wheel。裸 exe 与源码包只作为测试中间输入。[`.gitlab-ci.yml`](../../../../.gitlab-ci.yml) 只接受版本与根目录 `package.json` 匹配的 `python-v` 标签流水线,构建一个 SDK wheel 包和 4 个原生运行时 wheel 包,再由单个串行任务校验并将这 5 个文件发布到项目的 PyPI 注册表。[Windows x64 运行时决策](2026-08-23-python-sdk-windows-x64-runtime.zh.md)负责第四个目标及对 Windows arm64 的明确排除。 ### Python SDK 分发:双载体,exe 用于生产,`node` 用于开发 -Python SDK 位于 [`python/`](../../../../python/README.zh.md):`python/sdk` 是客户端,`python/sdk-runtime` 是运行时载体包。运行时包的数据目录包含检入的默认 `runtime/cordis.yml`、构建注入的平台 exe 及其必需的 `-rg` 伴随文件和可选的 macOS helper,以及构建注入的 `runtime/node/` 闭包树。`resolve_bundled_launch_args()` 的自动解析**只查找 exe**;`node` 载体仅在显式设置 `DSH_RUNTIME_MODE=node` 时启用(运行 `runtime/node/node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js`,需要系统 Node ≥22.19),定位为本仓库成员的开发验证通道,不随 wheel 包分发。 +Python SDK 位于 [`python/`](../../../../python/README.zh.md):`python/sdk` 是客户端,`python/sdk-runtime` 是运行时载体包。运行时包的数据目录包含构建注入的平台可执行文件及其必需的 `-rg` 伴随文件和可选的 macOS helper,以及供仓库开发使用的构建注入 `runtime/node/` 闭包树。`resolve_bundled_launch_args()` 默认选择可执行文件;显式设置 `DSH_RUNTIME_MODE=node` 会在系统 Node 22.19 或更高版本上运行 `runtime/node/node_modules/@deepseek-ai/dsh/lib/bin.js`。node 载体从不进入 wheel 分发,两种载体都不使用检入的完整 `cordis.yml`。 -[`scripts/build-python-release.py`](../../../../scripts/build-python-release.py) 从仓库根目录的 `package.json` 读取权威的 `X.Y.Z` 或预发布版本,把预发布版本转换为 PEP 440 写法,并以该 wheel 包版本暂存两个包,让 `deepseek-harness-sdk` 精确依赖匹配版本的 `deepseek-harness-runtime-bin`。可选的 `python-v` 发布标签只是一项一致性断言,与仓库版本不同时会被拒绝;源码 `pyproject.toml` 中的开发占位版本从不决定发布版本。暂存过程还会把仓库许可证放入两个 wheel 包,并把第三方声明放入内置运行时 wheel 包。SDK 是 `py3-none-any` wheel 包;每个只提供 wheel 包的运行时包都包含一个 exe 及其架构匹配的 `-rg` 伴随文件,macOS wheel 包还包含与其架构匹配的 spawn helper。运行时 wheel 包使用 `py3-none-manylinux_2_28_x86_64`、`py3-none-manylinux_2_28_aarch64`,或针对 Node 24 可执行文件 macOS 13.5 部署目标而保守选择的 `py3-none-macosx_14_0_arm64` 标签;Hatch 钩子拒绝 sdist、通用标签、混合平台载荷、伴随文件缺失或多余,以及不支持的平台。 +[`scripts/build-python-release.py`](../../../../scripts/build-python-release.py) 从仓库根目录的 `package.json` 读取权威的 `X.Y.Z` 或预发布版本,把预发布版本转换为 PEP 440 写法,并以该 wheel 包版本暂存两个包,让 `deepseek-harness-sdk` 精确依赖匹配版本的 `deepseek-harness-runtime-bin`。可选的 `python-v` 发布标签只是一项一致性断言,与仓库版本不同时会被拒绝;源码 `pyproject.toml` 中的开发占位版本从不决定发布版本。暂存过程还会把仓库许可证放入两个 wheel 包,并把第三方声明放入内置运行时 wheel 包。SDK 是 `py3-none-any` wheel 包;每个只提供 wheel 包的运行时包都包含一个 exe 及其架构匹配的 ripgrep 伴随文件,macOS wheel 包还包含与其架构匹配的 spawn helper。运行时 wheel 包使用 `py3-none-manylinux_2_28_x86_64`、`py3-none-manylinux_2_28_aarch64`、针对 Node 24 可执行文件 macOS 13.5 部署目标而保守选择的 `py3-none-macosx_14_0_arm64` 标签,或 `py3-none-win_amd64`;Hatch 钩子拒绝 sdist、通用标签、混合平台载荷、伴随文件缺失或多余,以及不支持的平台。 -exe「必须显式配置」的硬语义不变;零配置体验由包装层恢复:调用方没有提供 `cordis`、没有显式指定运行时,且环境中没有 `DSH_CORDIS_CONFIG` 时,客户端将检入的默认 `cordis.yml`(`agent-core` + 预载的 `llm-deepseek` + JSONL 持久化 + `bash-local` + `dsh-sdk-jsonrpc-server` 对外服务条目,并通过 `!!js` 使用环境变量兜底)显式注入 `DSH_CORDIS_CONFIG`。 +Python 客户端使用所选 profile(默认 `sdk`)、有序 patch 文件和显式 Harness home 启动打包后的 `dsh` 命令。Profile 负责 JSON-RPC 服务和应用组合;缺失 home、profile、bundle、patch 或 server 配置项都会失败,不存在外部完整配置回退。 ### 命名血统 -`@deepseek-ai/dsh-sdk-python-runtime`(私有载体)→ `dsh-sdk-python-runtime-closure`(部署 manifest;没有作用域前缀,因此不属于 dsh 发布包)→ `dsh-jsonrpc-agent-pkg--`(exe 产物)。协议字段 `serverInfo.name` 保持为 `deepseek-harness-sdk-runtime`(协议稳定值);Python 分发包名为 `deepseek-harness-sdk` / `deepseek-harness-runtime-bin`,导入模块名仍为 `deepseek_harness` / `deepseek_harness_runtime`。 +`dsh-python-runtime-closure` 是私有部署 manifest,`deepseek-harness-sdk-runtime--` 是可执行文件族。协议字段 `serverInfo.name` 是 `deepseek-harness-sdk-runtime`;Python 分发包名是 `deepseek-harness-sdk` / `deepseek-harness-runtime-bin`,导入模块名是 `deepseek_harness` / `deepseek_harness_runtime`。 ## 工作线程插件 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index f85c64d77c..c42ed69bb7 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md -2026-07-23-client-plugin-loading-model.md: 02dadf6e1dc1f2c4fd99907446bc6d07b35ba471 -2026-07-23-client-plugin-loading-model.zh.md: eaf10d32a6b51189867d2a52f76dc190380cbca0 +2026-07-23-client-plugin-loading-model.md: dfa9f34276f20ffa99541db1544539d693313a2f +2026-07-23-client-plugin-loading-model.zh.md: 68fe9b912c60aceb2ecea315ed0121f9f96c1ecf diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index 02dadf6e1d..dfa9f34276 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -14,7 +14,7 @@ The browser client runs the same cordis plugin mechanism, so it needs the same s Conventional frontend engineering digests all dependencies at build time: one bundle, externals resolved by the bundler, nothing left to manage at runtime. Runtime module management on top of that is the unusual requirement here. The client therefore splits into two layers: the upper layer is cordis plugin loading through the same vendored Loader, and the lower layer is module-granular dependency management — `dsh-client-modules`. -The lower layer supplies four capabilities: externals (the platform list), remote arrival (same-origin external classic scripts plus lazy factory registration), versioning (content-hash revs), and hot update (invalidate/prefetch). +The lower layer supplies four capabilities: externals (the platform list), remote arrival (same-origin external classic scripts plus lazy factory registration), immutable revisioned delivery, and hot update (invalidate/prefetch). Plugin bundles are built independently outside Vite's module graph. Feeding response text into an inline script leaves the browser with a dynamic source execution: no standard source-map chain connects the network resource, generated bundle, and TypeScript/TSX source, so performance profiles and stacks stop at generated `client.js`; the module system must also buffer the complete source and split one arrival responsibility across fetch and execute transport boundaries. @@ -28,7 +28,7 @@ The first-generation client loader (`createClientLoader`) hand-wrote both layers The [client shell layering note](2026-08-15-client-shells-and-dynamic-packages.md) defines the current static and dynamic package sets and the import rules between them. The loading machinery treats every `dsh.client` package as a host-graph row with one ordinary `lib/client.js` factory bundle. Its declaration carries Cordis `inject` edges, synchronous module-table `external` requests, and the optional `immediately` prefetch mark; the composing app owns only the mounted roster. -The web kernel remains framework-free and imports no dynamic package value. Modules is itself a dynamic row, but the host parser delivers its ordinary factory before the Vite main module. The HTML-installed `__ModuleLoader__` facade uses that factory to construct the module system when the kernel calls `create()`. Runtime arrives through the same pending queue; static React, Cordis, and UI library identities come from the shell seed. +The web kernel remains framework-free and imports no dynamic package value. Modules is itself a dynamic row, but the host parser delivers its factory before the Vite main module. The HTML-installed `__ModuleLoader__` facade uses that factory to construct the module system when the kernel calls `create()`. Every other dynamic row arrives through the application batch; static React, Cordis, and UI library identities come from the shell seed. ### One module system, one plugin governor @@ -38,13 +38,13 @@ The browser mirrors the host's division of labor. `dsh-client-modules` (`ClientM The vendored Loader consumes the module system through its `internal` contract — the only call site is `tree.import` — and owns everything entry-shaped: entry creation, fiber activation through cordis service waiting (PENDING until injected services exist, cascading when a service is provided), update/refresh, teardown. The governance code is byte-identical to the host side, per vendor policy. Browserization is compile-time mapping in the shell's vite config: a `node:module` stub alias plus `process.*` defines make `ModuleLoader.fromInternal()` return undefined — exactly the empty slot the shell fills. The module system mounts as `ctx.modules`. -### External-script arrival and source maps +### Batched external-script arrival and source maps -Each graph row's `url` goes to a same-origin external classic `') + const applicationAt = html.indexOf( + ``, + ) + const bootstrapAt = html.indexOf(``) const graphAt = html.indexOf('globalThis["__DSH_BOOT__"] = ') const entryAt = html.indexOf('') - expect(html).not.toContain('') - expect([facadeAt, modulesAt, graphAt, entryAt]).toEqual([...new Set([ - facadeAt, modulesAt, graphAt, entryAt, + expect([facadeAt, applicationAt, bootstrapAt, graphAt, entryAt]).toEqual([...new Set([ + facadeAt, applicationAt, bootstrapAt, graphAt, entryAt, ])].sort((a, b) => a - b)) target.load({ id: MODULES_ID, factory: () => modulesClient }) - target.load({ id: UI_RENDERER_ID, factory: () => ({ marker: 'ui-renderer' }) }) - const system = target.create({ boot: graph, staticModules: {} }) + const system = target.create({ + boot: graph, + staticModules: {}, + loadBundle: async (url) => { + expect(url).toBe(APPLICATION_URL) + target.load({ id: UI_RENDERER_ID, factory: () => ({ marker: 'ui-renderer' }) }) + }, + }) expect(target.mode).toBe('live') expect(target.pendingQueue).toEqual([]) @@ -209,40 +258,201 @@ describe('client bundle activation', () => { expect(String(thrown)).not.toContain('pnpm run build') }) + it('omits a torn or malformed source map without blocking composition', async () => { + const packageName = '@fixture/malformed-source-map' + const clientPath = writePackage(packageName) + mkdirSync(dirname(clientPath), { recursive: true }) + writeFileSync(clientPath, 'module.exports = {}\n') + writeFileSync(`${clientPath}.map`, '{') + const torn = constructWithRoute([packageName]) + const tornRow = torn.service.graph().entries[0]! + expect((await routeRequest(torn.route, tornRow.url)).body.toString('utf8')) + .not.toContain('sourceMappingURL') + expect((await routeRequest(torn.route, `${torn.service.graph().batches[0]!.url}.map`)).status).toBe(404) + + writeFileSync(`${clientPath}.map`, '{"version":3,"sources":[null]}\n') + expect(() => construct([packageName])).not.toThrow() + }) + + it('retains one prior immutable batch generation across rebuild recomposition', async () => { + const packageName = '@fixture/batch-rebuild-race' + const clientPath = writePackage(packageName) + mkdirSync(dirname(clientPath), { recursive: true }) + writeFileSync(clientPath, 'module.exports = { generation: 1 }\n') + const { service, route } = constructWithRoute([packageName]) + const first = service.graph().batches[0]!.url + const firstSize = service.artifactBaseline(packageName)!.size + + writeFileSync(clientPath, 'module.exports = { generation: 200 }\n') + service.rebuilt(packageName) + const second = service.graph().batches[0]!.url + expect(second).not.toBe(first) + expect(service.artifactBaseline(packageName)!.size).toBeGreaterThan(firstSize) + expect((await routeRequest(route, first)).status).toBe(200) + expect((await routeRequest(route, second)).status).toBe(200) + + writeFileSync(clientPath, 'module.exports = { generation: 3 }\n') + service.rebuilt(packageName) + const third = service.graph().batches[0]!.url + expect((await routeRequest(route, first)).status).toBe(404) + expect((await routeRequest(route, second)).status).toBe(200) + expect((await routeRequest(route, third)).status).toBe(200) + }) + + it('assigns opaque startup revisions instead of deriving them from artifact content', () => { + const firstName = '@fixture/startup-revision-first' + const secondName = '@fixture/startup-revision-second' + writeBuiltPackage(firstName, {}) + writeBuiltPackage(secondName, {}) + + const service = construct([firstName, secondName]) + const [first, second] = service.graph().entries + const firstMatch = /^(?[a-f\d]{16})-(?\d+)$/.exec(first!.rev) + const secondMatch = /^(?[a-f\d]{16})-(?\d+)$/.exec(second!.rev) + expect(firstMatch?.groups).toMatchObject({ sequence: '0' }) + expect(secondMatch?.groups).toMatchObject({ nonce: firstMatch?.groups?.nonce, sequence: '1' }) + const firstPath = service.clientPath(firstName)! + const firstStat = statSync(firstPath) + expect(service.artifactBaseline(firstName)).toEqual({ + path: firstPath, + mtimeMs: firstStat.mtimeMs, + size: firstStat.size, + mapMtimeMs: null, + mapSize: null, + }) + expect(service.artifactBaseline('@fixture/unknown')).toBeUndefined() + }) + it('serves the source map beside a registered client bundle', async () => { const packageName = '@fixture/source-map' const clientPath = writePackage(packageName) mkdirSync(dirname(clientPath), { recursive: true }) - writeFileSync(clientPath, 'module.exports = {}\n') - const map = '{"version":3,"sources":["src/client/index.tsx"]}\n' + writeFileSync(clientPath, 'module.exports = {}\n//# sourceMappingURL=client.js.map') + const map = '{"version":3,"names":[],"mappings":"AAAA","sources":["../../../packages/client/demo/src/index.tsx","https://cdn.example.test/library.js"]}\n' writeFileSync(`${clientPath}.map`, map) - const { route } = constructWithRoute([packageName]) - let status = 0 - let headers: Record | undefined - let body = '' - const response = { - writeHead(nextStatus: number, nextHeaders?: Record) { - status = nextStatus - headers = nextHeaders - return response - }, - end(chunk?: Uint8Array) { - body = chunk === undefined ? '' : Buffer.from(chunk).toString('utf8') - return response - }, - } as unknown as ServerResponse - - await route.handler({ - method: 'GET', - url: `/plugins/${packageName}/client.js.map`, - } as IncomingMessage, response) - - expect(status).toBe(200) - expect(headers).toEqual({ + const { service, route } = constructWithRoute([packageName]) + const row = service.graph().entries[0]! + const individualScript = await routeRequest(route, row.url) + expect(individualScript.body.toString('utf8')).toContain(`sourceMappingURL=client.js.map?rev=${row.rev}`) + const individual = await routeRequest(route, row.url.replace('/client.js?', '/client.js.map?')) + expect(individual.status).toBe(200) + expect(individual.headers).toEqual({ 'content-type': 'application/json; charset=utf-8', - 'cache-control': 'no-cache', + 'cache-control': 'public, max-age=31536000, immutable', }) - expect(body).toBe(map) + expect(individual.body.toString('utf8')).toBe(map) + + const batch = service.graph().batches[0]! + expect(batch).toMatchObject({ phase: 'application', entries: [packageName] }) + const batchScript = await routeRequest(route, batch.url) + expect(batchScript.status).toBe(200) + expect(batchScript.headers?.['cache-control']).toBe('public, max-age=31536000, immutable') + expect(batchScript.body.toString('utf8')).toContain('//# sourceMappingURL=client.js.map') + expect(batchScript.body.toString('utf8')).not.toContain('sourceMappingURL=client.js.map?rev=') + expect((await routeRequest(route, batch.url, 'HEAD')).body).toHaveLength(0) + expect((await routeRequest(route, batch.url, 'POST')).status).toBe(405) + const batchMap = await routeRequest(route, `${batch.url}.map`) + const parsedBatchMap = JSON.parse(batchMap.body.toString('utf8')) as unknown + const parsedIndividualMap = JSON.parse(map) as Record + expect(parsedBatchMap).toMatchObject({ + version: 3, + file: 'client.js', + sections: [{ + offset: { line: 0, column: 0 }, + map: { + ...parsedIndividualMap, + sources: ['/packages/client/demo/src/index.tsx', 'https://cdn.example.test/library.js'], + }, + }], + }) + expect((await routeRequest(route, `${row.url}&stale=1`.replace(`rev=${row.rev}`, 'rev=stale'))).status).toBe(404) + + writeFileSync(`${clientPath}.map`, '{"version":3,"names":[],"mappings":"AAAA","sources":["src/changed.tsx"]}\n') + const nextRev = service.rebuilt(packageName) + expect(nextRev).not.toBe(row.rev) + const nextMap = await routeRequest(route, `/plugins/${packageName}/client.js.map?rev=${String(nextRev)}`) + expect(JSON.parse(nextMap.body.toString('utf8'))).toMatchObject({ sources: ['src/changed.tsx'] }) + }) + + it('applies sourceRoot before relocating absolute-looking section sources', async () => { + const packageName = '@fixture/source-root' + const clientPath = writePackage(packageName) + mkdirSync(dirname(clientPath), { recursive: true }) + writeFileSync(clientPath, 'module.exports = {}\n') + writeFileSync(`${clientPath}.map`, JSON.stringify({ + version: 3, + names: [], + mappings: 'AAAA', + sourceRoot: '../root', + sources: ['/absolute.ts'], + })) + const { service, route } = constructWithRoute([packageName]) + const response = await routeRequest(route, `${service.graph().batches[0]!.url}.map`) + const map = JSON.parse(response.body.toString('utf8')) as { + sections: { map: { sourceRoot?: string; sources: string[] } }[] + } + expect(map.sections[0]?.map).toMatchObject({ + sources: ['/plugins/@fixture/root/absolute.ts'], + }) + expect(map.sections[0]?.map).not.toHaveProperty('sourceRoot') + }) + + it('maps a non-zero second batch section through a standard source-map consumer', async () => { + const firstName = '@fixture/offset-first' + const secondName = '@fixture/offset-second' + const firstPath = writePackage(firstName) + const secondPath = writePackage(secondName) + for (const [path, source] of [ + [firstPath, '../../../packages/demo/first.ts'], + [secondPath, '../../../packages/demo/second.ts'], + ] as const) { + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, 'window.first = true\nwindow.second = true\n') + writeFileSync(`${path}.map`, JSON.stringify({ + version: 3, + names: [], + mappings: 'AAAA', + sources: [source], + sourcesContent: ['export {}\n'], + })) + } + const { service, route } = constructWithRoute([firstName, secondName]) + const response = await routeRequest(route, `${service.graph().batches[0]!.url}.map`) + const payload = JSON.parse(response.body.toString('utf8')) as ConstructorParameters[0] + const sections = (payload as unknown as { + sections: { offset: { line: number; column: number } }[] + }).sections + expect(sections.map(section => section.offset)).toEqual([ + { line: 0, column: 0 }, + { line: 3, column: 0 }, + ]) + const consumer = new SourceMap(payload) + expect(consumer.findEntry(0, 0)).toMatchObject({ originalSource: '/packages/demo/first.ts' }) + expect(consumer.findEntry(3, 0)).toMatchObject({ originalSource: '/packages/demo/second.ts' }) + }) + + it('keeps a later source-map section usable when an earlier bundle has no map', async () => { + const unmappedName = '@fixture/unmapped-first' + const mappedName = '@fixture/mapped-second' + const unmappedPath = writePackage(unmappedName) + const mappedPath = writePackage(mappedName) + mkdirSync(dirname(unmappedPath), { recursive: true }) + mkdirSync(dirname(mappedPath), { recursive: true }) + writeFileSync(unmappedPath, 'window.unmapped = true\n') + writeFileSync(mappedPath, 'window.mapped = true\n') + writeFileSync(`${mappedPath}.map`, JSON.stringify({ + version: 3, + names: [], + mappings: 'AAAA', + sources: ['../../../packages/demo/mapped.ts'], + sourcesContent: ['export {}\n'], + })) + + const { service, route } = constructWithRoute([unmappedName, mappedName]) + const response = await routeRequest(route, `${service.graph().batches[0]!.url}.map`) + const payload = JSON.parse(response.body.toString('utf8')) as ConstructorParameters[0] + const consumer = new SourceMap(payload) + expect(consumer.findEntry(2, 0)).toMatchObject({ originalSource: '/packages/demo/mapped.ts' }) }) }) diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index c21885f78e..5728d345da 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -94,7 +94,8 @@ function browserSourcePath(source: string, sourcemapPath: string): string { * earlier Host pass. A package-level tsdown.config.ts REPLACES the root * workspace layout, so the lib half must be restated here — dropping it leaves * the package without lib/index.js and the host Loader cannot import its node - * half. + * half. The Client build consumes `lib/types` and chains those tsc maps, with + * original source content, into the standalone plugin map. * @param id - plugin id (package name), stamped into the __ModuleLoader__.load * handoff and onto the injected style tags. * @param libEntry - node-half entries, spelled at the call site so the @@ -267,6 +268,7 @@ function staticLinkedConfig(id: string, entry: string, outputName = basename(ent // The shell compiles this artifact, so its map is the only path from a // browser stack frame back to the TSX (tsc emits the lib/types half). sourcemap: true, + outputOptions: { sourcemapExcludeSources: false }, plugins: [{ // Contract 1. `pre` because tsdown's own deps plugin would otherwise // resolve and inline every specifier missing from the npm production @@ -281,18 +283,7 @@ function staticLinkedConfig(id: string, entry: string, outputName = basename(ent return isBareSpecifier(source) ? { id: source, external: true } : null }, }, - }, { - // Contract 3. Rolldown does not read the `//# sourceMappingURL` of its - // inputs, so each tsc map is handed over as that module's map and - // composed into the bundle map; without it frames stop at the emitted - // lib/types JavaScript instead of reaching the TSX. - name: 'dsh-tsc-sourcemap', - async load(id: string) { - if (!id.includes(TYPES_MARKER) || !id.endsWith('.js') || !existsSync(`${id}.map`)) return null - const code = await readFile(id, 'utf8') - return { code: code.replace(SOURCEMAP_COMMENT, ''), map: await readFile(`${id}.map`, 'utf8') } - }, - }, { + }, tscSourceMapPlugin(), { // Contract 4. The import survives verbatim and the sheet lands beside the // JavaScript, so the shell's CSS Modules pipeline sees a real stylesheet. name: 'dsh-css-asset', @@ -495,7 +486,7 @@ function clientConfig(id: string, entry: string): UserConfig { + '(type-only imports are erased and never reach this gate)', ) }, - }, { + }, tscSourceMapPlugin(), { name: 'dsh-css-modules-inline', resolveId(source: string, importer: string | undefined) { if (!source.endsWith('.module.css')) return null @@ -554,6 +545,7 @@ function clientConfig(id: string, entry: string): UserConfig { }], outputOptions: { entryFileNames: 'client.js', + sourcemapExcludeSources: false, // The map is served from /plugins//client.js.map. The // browser resolves its local sources back into URLs that mirror the // /packages///src directories; sourcesContent keeps them usable @@ -566,6 +558,38 @@ function clientConfig(id: string, entry: string): UserConfig { } } +/** Chain tsc's emitted maps into any Client bundle that consumes `lib/types`. */ +function tscSourceMapPlugin() { + return { + name: 'dsh-tsc-sourcemap', + async load(id: string) { + if (!id.includes(TYPES_MARKER) || !id.endsWith('.js') || !existsSync(`${id}.map`)) return null + const code = await readFile(id, 'utf8') + const mapPath = `${id}.map` + const map = JSON.parse(await readFile(mapPath, 'utf8')) as { + sourceRoot?: unknown + sources?: unknown + sourcesContent?: unknown + [key: string]: unknown + } + if (!Array.isArray(map.sources) || map.sources.some(source => typeof source !== 'string')) { + throw new Error(`client sourcemap: ${mapPath} has invalid sources`) + } + const sources = map.sources as string[] + if ( + !Array.isArray(map.sourcesContent) + || map.sourcesContent.length !== sources.length + || map.sourcesContent.some(source => typeof source !== 'string') + ) { + const sourceRoot = typeof map.sourceRoot === 'string' ? map.sourceRoot : '' + map.sourcesContent = await Promise.all(sources.map(async source => + await readFile(resolvePath(dirname(mapPath), sourceRoot, source), 'utf8'))) + } + return { code: code.replace(SOURCEMAP_COMMENT, ''), map } + }, + } +} + /** Path segment separating a package's tsc output from the sources it was emitted from. */ const TYPES_MARKER = `${sep}lib${sep}types${sep}` diff --git a/packages/client/ui-chat/src/client/locale.ts b/packages/client/ui-chat/src/client/locale.ts index 9f6a18fd7b..be8a3521ac 100644 --- a/packages/client/ui-chat/src/client/locale.ts +++ b/packages/client/ui-chat/src/client/locale.ts @@ -27,7 +27,7 @@ export const zh = { 'chat.loadError': '历史加载失败:{message}({code})', 'chat.loadOlder': '加载更早', 'chat.toBottom': '回到底部', - 'chat.deepDiving': '正在深入处理…', + 'chat.deepDiving': '深度求索中...', 'fileOpen.title': '无法打开文件', 'fileOpen.unknown': '无法打开此文件', 'fileOpen.folderTitle': '无法打开文件夹', diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index d6ccc631e6..d112bd779c 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -914,7 +914,7 @@ describe('ChatView', () => { const view = render() expect(view.getByTestId('tool-seat-r1')).toBeTruthy() expect(h.toolOwners[0]?.block).toMatchObject({ callId: 'r1', argsRaw: '{"command":"cmd-r1"}' }) - expect(view.getByRole('status').textContent).toBe('正在深入处理…') + expect(view.getByRole('status').textContent).toBe('深度求索中...') }) it('keeps the Tool renderer mounted when a running call settles into log order', () => { @@ -974,7 +974,7 @@ describe('ChatView', () => { const view = render() // Freshly mounted (as after a reload) yet already past the 15s gate. const status = view.getByRole('status') - expect(status.textContent).toMatch(/^正在深入处理…2分0\d秒$/) + expect(status.textContent).toMatch(/^深度求索中\.\.\.2分0\d秒$/) expect(status.querySelector('[aria-hidden="true"]')).not.toBeNull() act(() => { h.setSession({ queue: [{ @@ -986,7 +986,7 @@ describe('ChatView', () => { text: 'also', }] }) }) - expect(status.textContent).toMatch(/^正在深入处理…2分0\d秒$/) + expect(status.textContent).toMatch(/^深度求索中\.\.\.2分0\d秒$/) }) it('hands each ordered root call to the keyed business-node slot', () => { diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index a6102ddac0..85e96fbdca 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 4c9665b680fe1922770403d88a04dffc755481ad -README.zh.md: 8bf3db2cb1401427f29016f8dbddcd9d27ec9635 +README.md: 08d1408bea404a80da491078aa013989835fccaf +README.zh.md: 874aea8865e6f74a64da2c249087bdad032d98d5 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 4c9665b680..08d1408bea 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -20,6 +20,8 @@ View selection is deterministic: a registered persisted selection wins, otherwis The resident composer survives no-Session and Session transitions. The no-Session state keeps the same textarea mounted but inert while the Workspace picker connects a blank Session. Draft text is mirrored into the per-Session Conversation store. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. +An ordinary running composer keeps Stop as its primary pointer action while its draft is empty or an owner block makes input unavailable. Actionable text or attachments switch the same seat to Queue Send; clearing or successfully submitting the draft restores Stop. Keyboard Queue/Steer selection remains governed by the busy-Enter setting, while continuable subagents keep independent Send and Stop actions ([decision](../../../.agents/notes/implemented/bug-fix/2026-08-20-running-draft-primary-send.md)). + ## Temporary composer entries `conversation.composer` is a generic chain. Its complete owner currency is: diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 8bf3db2cb1..874aea8865 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -20,6 +20,8 @@ View 选择规则固定:有效且已注册的持久化选择优先,其次是 常驻 composer 在无 Session 与有 Session 之间保持挂载。无 Session 时,同一个 textarea 保持 inert,Workspace picker 连接 blank Session;草稿文本镜像到逐 Session Conversation store。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 +普通 composer 运行期间,草稿为空或 owner block 使输入不可用时,主指针操作保持为 Stop。可提交文字或附件会把同一位置切换为 Queue Send;清空或成功提交草稿后恢复 Stop。键盘 Queue/Steer 选择仍由繁忙态 Enter 设置决定,可继续 subagent 则保留相互独立的 Send 与 Stop 操作([决策](../../../.agents/notes/implemented/bug-fix/2026-08-20-running-draft-primary-send.zh.md))。 + ## 临时 composer entry `conversation.composer` 是通用 chain,其完整 owner currency 为: diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 8bedb2d260..0a137c8010 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -554,10 +554,10 @@ export function InputBar({ if (el !== null) toggleCommandMenu?.(selectionOf(el)) } - // Ordinary sessions retain their primary Send/Stop toggle. A continuable - // child keeps Send as the primary action and exposes Stop independently so - // pointer users can queue follow-ups while its current turn is running. - const primaryStops = running && subagent === null + // An ordinary running session keeps Stop while the composer is empty or + // owner-blocked; an actionable draft gets the existing Queue action. A + // continuable child keeps Send primary and exposes Stop independently. + const primaryStops = running && subagent === null && (empty || blocked !== undefined) const interruptible = running && continuable const primaryLabel = primaryStops ? t('input.stop') : t('input.send') const onPrimary = (): void => { diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index f36b1aa1c4..17064a97a5 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -64,6 +64,7 @@ interface BenchOptions { subagent?: Exclude disabled?: boolean inert?: boolean + blocked?: { readonly reason: string } workspacePickerOpen?: boolean onRequestWorkspace?: () => void promptError?: SessionSnapshot['promptError'] @@ -186,6 +187,7 @@ function bench(over?: BenchOptions) { renderSlot, variant: over?.variant ?? 'composer', ...(over?.inert === true ? { disabled: true } : {}), + ...(over?.blocked !== undefined ? { blocked: over.blocked } : {}), ...(over?.workspacePickerOpen !== undefined ? { workspacePickerOpen: over.workspacePickerOpen } : {}), ...(over?.onRequestWorkspace !== undefined ? { onRequestWorkspace: over.onRequestWorkspace } : {}), ...(over?.placeholder !== undefined ? { placeholder: over.placeholder } : {}), @@ -196,7 +198,9 @@ function bench(over?: BenchOptions) { } const view = render() const textarea = view.container.querySelector('textarea')! + const sendableDraft = (over?.draft?.trim() ?? '') !== '' || (over?.attachments?.length ?? 0) > 0 const primaryStops = over?.running === true && over.subagent === undefined + && (!sendableDraft || over.blocked !== undefined) const button = view.container.querySelector( `button[aria-label="${primaryStops ? '停止生成' : '发送消息'}"]`, )! @@ -606,15 +610,53 @@ describe('Enter semantics', () => { }) describe('running and lock semantics', () => { - it('running keeps the input free (typing + Enter queue) while the primary turns stop', () => { - const { textarea, button, stop, sink } = bench({ running: true, draft: '排队消息' }) + it('running switches the primary between Stop and Queue Send with the draft', async () => { + const { textarea, button, stop, sink } = bench({ running: true, busyEnter: 'steer' }) expect(textarea.disabled).toBe(false) - fireEvent.change(textarea, { target: { value: '排队消息2' } }) - fireEvent.keyDown(textarea, { key: 'Enter' }) - expect(sink).toHaveBeenCalledWith('排队消息2', [], 'queue', expect.any(AbortSignal)) expect(button.getAttribute('aria-label')).toBe('停止生成') fireEvent.click(button) expect(stop).toHaveBeenCalledTimes(1) + + fireEvent.change(textarea, { target: { value: '排队消息' } }) + expect(button.getAttribute('aria-label')).toBe('发送消息') + fireEvent.change(textarea, { target: { value: ' ' } }) + expect(button.getAttribute('aria-label')).toBe('停止生成') + fireEvent.change(textarea, { target: { value: '排队消息2' } }) + expect(button.getAttribute('aria-label')).toBe('发送消息') + fireEvent.click(button) + expect(sink).toHaveBeenCalledWith('排队消息2', [], 'queue', expect.any(AbortSignal)) + await vi.waitFor(() => { expect(button.getAttribute('aria-label')).toBe('停止生成') }) + expect(stop).toHaveBeenCalledTimes(1) + }) + + it('running treats an attachment-only draft as Send', async () => { + const attachment = { + kind: 'image' as const, + id: 'draft-1' as DraftAttachmentId, + file: new File([Uint8Array.of(1)], 'pixel.png', { type: 'image/png' }), + previewUrl: 'blob:pixel', + } + const { button, sink } = bench({ running: true, attachments: [attachment] }) + expect(button.getAttribute('aria-label')).toBe('发送消息') + fireEvent.click(button) + expect(sink).toHaveBeenCalledWith('', ['draft-1'], 'queue', expect.any(AbortSignal)) + await vi.waitFor(() => { expect(button.getAttribute('aria-label')).toBe('停止生成') }) + }) + + it('running blocked composer keeps Stop with a retained draft', () => { + const { button, sink, stop, textarea } = bench({ + running: true, + draft: '保留的草稿', + blocked: { reason: '请选择可用模型' }, + placeholder: '请选择可用模型', + }) + expect(textarea.disabled).toBe(true) + expect(textarea.placeholder).toBe('请选择可用模型') + expect(button.getAttribute('aria-label')).toBe('停止生成') + expect(button.disabled).toBe(false) + fireEvent.click(button) + expect(stop).toHaveBeenCalledTimes(1) + expect(sink).not.toHaveBeenCalled() }) it('running plain Enter follows the busy-state Steer preference', () => { diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 0eb68f97f2..add13d5562 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings-models/README.md -README.md: cc430c91b9c4124fc70d0ec205b5870012dd5554 -README.zh.md: 62358adbc6f055697efe33e29e579f0aec64efc3 +README.md: 0daa9c5288f169138a5961e8fd6bee7818dba89b +README.zh.md: b2f80b845302d29728a0574b82f565c96acf59f2 diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index cc430c91b9..0daa9c5288 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -4,6 +4,8 @@ English | [中文](README.zh.md) Models settings and product-onboarding plugin. The same client Cordis plugin registers the Models page plus two ordered first-run dialogs: a versioned internal-testing notice and the conditional official-DeepSeek credential step. Both steps share one modal wrapper and remain sequenced by `settings.onboarding`. The Models plane joins three wire domains into one shared snapshot — `llm.providers` (the configurable-provider directory with each route's live/dormant state), `settings.describe` (serialized schemas, layered redacted values, secret slots), and `credentials.describe` (value-free configured/source/writable badges) — and renders provider rows with one editor card at a time, without presenting route liveness as provider status. +When the Host advertises the `subagent-model-selection` settings namespace, Models also renders a localized switch above the provider rows. It defaults off and writes only `{ enabled }` through `settings.update` with the namespace revision. The Host samples it while composing a new top-level Session; changing it does not reconfigure running Sessions, while child Sessions inherit their parent's recorded decision. + Rows are the *configured* providers (their profile resolves in the owning namespace); a whole-section provider whose key is not configured anywhere renders as its open setup card instead of a row, but only in the first-run posture — while no provider is registered with the credential its profile names — and only until the user closes that card, after which it is an ordinary row carrying the missing-key dot. Each card kind owns its own open state, so closing one never discards a draft in another. The add flow is a card carrying the dormant-directory provider select — a bare-mounted `llm-pi-ai` offers its whole installed catalog before any route exists. The pi-ai card additionally edits that route's **model list** and can ask the provider what it serves. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing; reference-free provider-native authentication and unavailable credential enrichment remain unmarked. The editor is a hand-written card per adapter family: the primary field is a single **API key** input — the page never asks for an environment-variable name; a typed key stores **write-only** through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `settings.yaml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and therefore preserves provider-native authentication such as the Bedrock credential chain or Vertex ADC. A successful Apply emits a local accessible status message without echoing secret material. The collapsed 自定义设置 fold carries the curated extras — `baseURL` for both families (the deepseek placeholder shows the public endpoint), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Those two are what a hand-declared route names for itself: the create card asks for both because nothing can default them, so the editor reaches both rather than leaving them to `settings.yaml`. Clearing the name unsets it and the route falls back to its id, which is what the placeholder shows; the protocol has no such fallback. A catalog route gets neither — it defaults its name from its catalog entry, and its models each carry their own protocol, so a route-level one could only override every one of them. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. Reasoning effort is deliberately NOT among them: it is a per-model capability and the models under one provider disagree about which levels they accept, so a provider-scoped control could only be set to a value some of them reject — which would hide even the models that support the level. The composer's model picker offers each model its own levels, and a switch there records provider, model, and effort together as the default for the next session. The profile field stays in `settings.yaml` for a deployment that knows its route. Each DeepSeek row edits `id`, optional display `name`, and optional `contextWindow`/`maxTokens`; existing fields outside that curated set survive edits, while every other profile field stays owned by `settings.yaml`. A row is deletable only when the user layer alone carries it (removal restores the composition base), and its localized confirmation dialog names the provider in the title, description, and final action. A row is tagged **Custom** when the directory entry says the owning adapter ships nothing under that key. The tag follows that answer alone: having a stored profile does not make a route custom — narrowing a shipped provider's models stores one too — and an adapter that reports nothing leaves its rows untagged rather than being read as shipped. The notice step owns its exact copy in `src/client/locales.ts` and its acknowledgement version in `src/onboarding-copy.ts`. On loopback it compares and writes `ui-onboarding.welcomeNoticeVersion` through the existing settings API; only an explicit Continue records the current version. A non-loopback browser cannot use that Host-only namespace, so acknowledgement is process-local and the notice returns after reload. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 62358adbc6..b2f80b8453 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -4,6 +4,8 @@ 模型设置与产品引导插件。同一个 client Cordis 插件会注册 Models 页面和两个有序的首次使用弹窗:版本化内测声明,以及按条件显示的 DeepSeek 官方凭据步骤。两个步骤共用同一套弹窗组件,并继续由 `settings.onboarding` 排序。Models 平面把三个协议领域汇聚为一个共享快照:`llm.providers`(可配置提供方目录,含每条路由的存活/休眠状态)、`settings.describe`(序列化 schema、分层脱敏值、secret slot)与 `credentials.describe`(不含值的 configured/source/writable 徽标);页面据此渲染提供方行,一次只展开一张编辑卡片,且不把路由存活状态呈现为提供方状态。 +Host 公布 `subagent-model-selection` settings namespace 时,Models 还会在提供方行上方渲染本地化开关。它默认关闭,只通过 `settings.update` 携带 namespace revision 写入 `{ enabled }`。Host 会在组合新的顶层 Session 时读取它;修改设置不会重新配置运行中的 Session,而子 Session 会继承父级已记录的决定。 + 行是*已配置*的提供方(其 profile 在所属 namespace 中解析得出);其配置键未在任何位置配置的整分节提供方会渲染为其展开的设置卡片而非一行,但仅限首次运行姿态——即尚无任何提供方已注册且备齐其 profile 所指名的凭据——且仅持续到用户关闭该卡片为止,此后它就是一行带缺失密钥点的普通行。每一类卡片各自持有自己的展开状态,因此关掉其中一张绝不会丢弃另一张里的草稿。「新增」流程则是一张承载休眠目录提供方选择框的卡片——裸挂载的 `llm-pi-ai` 在任何路由存在之前就能提供其完整的已安装 catalog。pi-ai 卡片还会编辑该路由的**模型列表**,并可查询提供方所提供的模型。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。无引用的提供方原生认证以及无法取得凭据补充信息时都不显示状态点。编辑器是每个适配器家族各一张的手写卡片:主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名;键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `settings.yaml` 从不携带密钥值。为新的 pi-ai 提供方留空密钥会保存一个不带引用的 profile,因此能保留提供方原生认证,例如 Bedrock 凭据链或 Vertex ADC。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。收起的「自定义设置」折叠区承载精选的额外字段——两个家族都有 `baseURL`(deepseek 的占位符显示公共端点)、各适配器自己的模型目录,以及适配器未提供的那类 pi-ai 路由的**显示名称**与 **API 协议**。这两个字段是手工声明路由为自己命名的东西:创建卡片之所以索要它们,正因为没有东西能为它们兜底,因此编辑器也够得着这两个,而不是把它们留给 `settings.yaml`。清空名称即取消设置,路由退回自己的 id——占位符显示的就是它;协议没有这样的兜底。内置目录路由两个都不给:它的名称由目录条目兜底,它的每个模型各自带着自己的协议,路由级协议只可能把它们全部覆盖掉。Provider ID 保持固定:它是 settings 的键、是其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。推理等级刻意**不在**其中:它是按模型的能力,而同一提供方下各模型接受的档位并不一致,因此提供方级的控件只可能被设成其中一些模型会拒绝的值——那会连支持该档位的模型也一并隐藏。输入框的模型选择器为每个模型提供它自己的档位,在那里切换会把提供方、模型、推理等级一并记为下一个会话的默认值。profile 字段仍留在 `settings.yaml`,供清楚自己路由的部署使用。每条 DeepSeek 模型行可编辑 `id`、可选的显示名称 `name` 与可选的 `contextWindow`/`maxTokens`;精选集合以外的现有字段会在编辑后保留,其余每个 profile 字段仍归 `settings.yaml` 所有。只有当某行仅由用户层承载时它才可删除(删除会还原组合 base),其本地化确认对话框会在标题、说明和最终操作中点名该提供方。当目录条目表明拥有该路由的适配器在这个键下什么都没有时,该行会带上 **自定义** 标签。标签只跟随这个答案:存了 profile 并不使一条路由成为自定义——收窄一个内置提供方的模型同样会存下 profile——而什么都不回答的适配器,其路由保持无标签,不会被当成内置。 声明步骤在 `src/client/locales.ts` 中持有完整文案,并在 `src/onboarding-copy.ts` 中持有确认版本。回环访问会通过既有 settings API 比较并写入 `ui-onboarding.welcomeNoticeVersion`;只有明确点击「继续」才会记录当前版本。非回环浏览器无法使用这项仅限 Host 的 namespace,因此确认仅在当前进程有效,重载后声明会再次出现。 diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.module.css b/packages/client/ui-settings-models/src/client/ModelsSection.module.css index 3719535a3a..1c767386dd 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.module.css +++ b/packages/client/ui-settings-models/src/client/ModelsSection.module.css @@ -40,6 +40,87 @@ color: var(--dsw-alias-state-success-primary); } +.preferenceCard { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 8px 16px; + margin-top: 4px; + padding: 14px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 12px; +} + +.preferenceCopy { + min-width: 0; +} + +.preferenceTitle { + margin: 0; + font-size: 14px; + line-height: 22px; + font-weight: 500; + color: var(--dsw-alias-label-primary); +} + +.preferenceDescription { + margin: 2px 0 0; + font-size: 12px; + line-height: 18px; + color: var(--dsw-alias-label-tertiary); +} + +.switch { + box-sizing: border-box; + position: relative; + width: 36px; + height: 20px; + padding: 2px; + border: 0; + border-radius: 10px; + background: var(--dsw-alias-border-l3); + cursor: pointer; +} + +.switchOn { + background: var(--dsw-alias-brand-primary); +} + +.switch:disabled { + cursor: default; + opacity: 0.5; +} + +.switch:focus-visible { + outline: none; + box-shadow: 0 0 0 2px var(--dsw-alias-border-l3); +} + +.switchThumb { + display: block; + width: 16px; + height: 16px; + border-radius: 50%; + background: var(--dsw-alias-label-primary-foreground); + transition: transform 120ms ease; +} + +.switchOn .switchThumb { + transform: translateX(16px); +} + +.preferenceStatus, +.preferenceCard > .error { + grid-column: 1 / -1; +} + +.preferenceStatus { + margin: 0; + font-size: 12px; + line-height: 18px; + color: var(--dsw-alias-state-success-primary); +} + .rows { list-style: none; /* Extra air between the title/intro block and the first provider card. */ @@ -623,7 +704,8 @@ select.input { } @media (prefers-reduced-motion: reduce) { - .customizedSummary::before { + .customizedSummary::before, + .switchThumb { transition: none; } } diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.tsx b/packages/client/ui-settings-models/src/client/ModelsSection.tsx index 7f178564d6..9501185e87 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.tsx +++ b/packages/client/ui-settings-models/src/client/ModelsSection.tsx @@ -22,6 +22,7 @@ import { deriveKeyRef, messageOf, protocolChoices, providerUsable } from './stor import type { ModelsSettingsStore, ProviderRow } from './store.ts' import type { SettingsSchemaOperations } from './schema-operations.ts' import { ProviderEditor, type ProviderEditorProps } from './ProviderEditor.tsx' +import { SubagentModelSelectionCard } from './SubagentModelSelectionCard.tsx' import type { en } from './locales.ts' import styles from './ModelsSection.module.css' @@ -278,12 +279,24 @@ function Loaded({ injected }: { injected: ModelsSectionFace }): ReactNode { // one whose schema names the protocols one may speak; without it mounted // there is nothing to declare and the entry point stays disabled. const protocols = protocolChoices(state.namespaces.get('llm-pi-ai'), schema) + const subagentModelSelection = state.namespaces.get('subagent-model-selection') return (

{t('title')}

{t('intro')}

{!state.writable && state.status === 'ready' ?

{t('readOnly')}

: null} + {subagentModelSelection === undefined + ? null + : ( + + )} {savedIdentity === undefined ? null : ( diff --git a/packages/client/ui-settings-models/src/client/SubagentModelSelectionCard.tsx b/packages/client/ui-settings-models/src/client/SubagentModelSelectionCard.tsx new file mode 100644 index 0000000000..3b62f28e60 --- /dev/null +++ b/packages/client/ui-settings-models/src/client/SubagentModelSelectionCard.tsx @@ -0,0 +1,87 @@ +/** User control for model-selectable subagent delegation in new sessions. */ + +import { useState } from 'react' +import type { ReactNode } from 'react' +import type { IApiClient, SettingsNamespaceView } from '@deepseek-ai/dsh-api-remotes/client' +import type { ModelsSettingsStore } from './store.ts' +import type { en } from './locales.ts' +import { messageOf } from './store.ts' +import styles from './ModelsSection.module.css' + +/** Props for the Host-owned subagent model-selection preference. */ +export interface SubagentModelSelectionCardProps { + /** Current redacted namespace view. */ + namespace: SettingsNamespaceView + /** Whether the settings provider accepts writes. */ + writable: boolean + /** Settings wire face. */ + api: Pick + /** Models page controller to refresh after a commit. */ + controller: ModelsSettingsStore + /** Localized Models copy. */ + t: (key: keyof typeof en) => string +} + +/** Read the schema-validated resolved boolean from a namespace view. */ +function enabledOf(namespace: SettingsNamespaceView): boolean { + if (typeof namespace.value !== 'object' || namespace.value === null) return false + return (namespace.value as { enabled?: unknown }).enabled === true +} + +/** Render and persist the default-off new-session preference. */ +export function SubagentModelSelectionCard({ + namespace, + writable, + api, + controller, + t, +}: SubagentModelSelectionCardProps): ReactNode { + const [saving, setSaving] = useState(false) + const [saved, setSaved] = useState(false) + const [error, setError] = useState(undefined) + const enabled = enabledOf(namespace) + + const toggle = (): void => { + setSaving(true) + setSaved(false) + setError(undefined) + void api.settings.update({ + ns: namespace.ns, + patch: { enabled: !enabled }, + expectedRevision: namespace.revision, + }).then(async (response) => { + if (!response.result.ok) throw new Error(response.result.error.message) + controller.acceptNamespace(response.result.value) + await controller.load() + setSaved(true) + }).catch((reason: unknown) => { + setError(messageOf(reason)) + }).finally(() => { setSaving(false) }) + } + + return ( +
+
+

+ {t('subagentModelSelectionTitle')} +

+

{t('subagentModelSelectionDescription')}

+
+ + {saved + ?

{t('subagentModelSelectionSaved')}

+ : null} + {error === undefined ? null :

{error}

} +
+ ) +} diff --git a/packages/client/ui-settings-models/src/client/locales.ts b/packages/client/ui-settings-models/src/client/locales.ts index f1b0718ba5..176e33fe5e 100644 --- a/packages/client/ui-settings-models/src/client/locales.ts +++ b/packages/client/ui-settings-models/src/client/locales.ts @@ -5,6 +5,10 @@ export const en = { nav: 'Models', title: 'Models', intro: 'Enter your API keys to use models from the following providers.', + subagentModelSelectionTitle: 'Subagent model selection', + subagentModelSelectionDescription: 'Allow new sessions to choose a provider, model, and reasoning effort for subagents. Running sessions do not change.', + subagentModelSelectionToggle: 'Allow subagents to choose models', + subagentModelSelectionSaved: 'Saved. New sessions use this setting.', edit: 'Edit', editProvider: 'Edit {provider}', remove: 'Delete', @@ -109,6 +113,10 @@ export const zh: { [Key in keyof typeof en]: string } = { nav: '模型', title: '模型', intro: '填入各提供方的 API 密钥即可使用其模型。', + subagentModelSelectionTitle: 'Subagent 自选模型', + subagentModelSelectionDescription: '允许新会话为 subagent 选择提供方、模型和推理强度。运行中的会话不会改变。', + subagentModelSelectionToggle: '允许 subagent 自选模型', + subagentModelSelectionSaved: '已保存,新会话将使用此设置。', edit: '编辑', editProvider: '编辑 {provider}', remove: '删除', diff --git a/packages/client/ui-settings-models/src/client/store.ts b/packages/client/ui-settings-models/src/client/store.ts index 349798acdd..2b17c9fc4b 100644 --- a/packages/client/ui-settings-models/src/client/store.ts +++ b/packages/client/ui-settings-models/src/client/store.ts @@ -124,6 +124,15 @@ export class ModelsSettingsStore { private readonly describeFace: SettingsDescribeFace, ) {} + /** + * Fold one successful settings write into the shared mirror before rejoining + * this page's rows. + * @param view - namespace view returned by the settings wire method. + */ + acceptNamespace(view: SettingsNamespaceView): void { + this.describeFace.acceptView(view) + } + /** * Refresh the whole page snapshot: the provider directory and the mirror's * settings answer in parallel, then one batched credential describe over diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index 8a3b8fce0a..5d0cbe8fed 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -8,6 +8,7 @@ import type { RpcResponse, SettingsNamespaceView } from '@deepseek-ai/dsh-api-re import { ModelsSection, needsSetup, providerCopy, providerTargetLabel, removeProviderProfile, } from '../src/client/ModelsSection.tsx' +import { SubagentModelSelectionCard } from '../src/client/SubagentModelSelectionCard.tsx' import type { ModelsSectionInjected, ModelsSectionProps } from '../src/client/ModelsSection.tsx' import { pathOps } from '../src/client/ProviderEditor.tsx' import { @@ -122,6 +123,14 @@ function wireNamespaces(): SettingsNamespaceView[] { secrets: [], revision: 0, }, + { + ns: 'subagent-model-selection', + schema: JSON.parse(JSON.stringify(Schema.object({ enabled: Schema.boolean().default(false) }).toJSON())) as unknown, + value: { enabled: false }, + applies: 'live', + secrets: [], + revision: 4, + }, ] } @@ -143,9 +152,10 @@ function scriptedFace(overrides: { set?: ReturnType unset?: ReturnType } = {}) { - const update = overrides.update ?? vi.fn(() => Promise.resolve(ok(wireNamespaces()[2]))) - const replace = overrides.replace ?? vi.fn(() => Promise.resolve(ok(wireNamespaces()[2]))) - const mutate = overrides.mutate ?? vi.fn(() => Promise.resolve(ok(wireNamespaces()[2]))) + const providerNamespace = wireNamespaces().find(view => view.ns === 'llm-pi-ai')! + const update = overrides.update ?? vi.fn(() => Promise.resolve(ok(providerNamespace))) + const replace = overrides.replace ?? vi.fn(() => Promise.resolve(ok(providerNamespace))) + const mutate = overrides.mutate ?? vi.fn(() => Promise.resolve(ok(providerNamespace))) const set = overrides.set ?? vi.fn(() => Promise.resolve(ok({}))) const unset = overrides.unset ?? vi.fn(() => Promise.resolve(ok({}))) const face = { @@ -236,6 +246,71 @@ describe('ModelsSection', () => { expect(document.body.textContent).toBe('') }) + it('persists the default-off subagent model-selection switch for new sessions', async () => { + const enabledNamespace: SettingsNamespaceView = { + ...wireNamespaces().find(view => view.ns === 'subagent-model-selection')!, + value: { enabled: true }, + user: { enabled: true }, + revision: 5, + } + const update = vi.fn(() => Promise.resolve(ok(enabledNamespace))) + await mountSection({ update }) + + const toggle = screen.getByRole('switch', { name: en.subagentModelSelectionToggle }) + expect(toggle.getAttribute('aria-checked')).toBe('false') + fireEvent.click(toggle) + + await waitFor(() => { expect(toggle.getAttribute('aria-checked')).toBe('true') }) + expect(update).toHaveBeenCalledWith({ + ns: 'subagent-model-selection', + patch: { enabled: true }, + expectedRevision: 4, + }) + expect(screen.getByRole('status').textContent).toBe(en.subagentModelSelectionSaved) + }) + + it('reports rejected subagent model-selection updates and permits a retry', async () => { + const update = vi.fn() + .mockResolvedValueOnce(fail('revision changed')) + .mockResolvedValueOnce(ok({ + ...wireNamespaces().find(view => view.ns === 'subagent-model-selection')!, + value: { enabled: true }, + revision: 5, + })) + await mountSection({ update }) + + const toggle = screen.getByRole('switch', { name: en.subagentModelSelectionToggle }) + fireEvent.click(toggle) + expect((await screen.findByRole('alert')).textContent).toBe('revision changed') + + fireEvent.click(toggle) + await waitFor(() => { expect(toggle.getAttribute('aria-checked')).toBe('true') }) + expect(screen.queryByRole('alert')).toBeNull() + }) + + it('keeps malformed and read-only subagent preferences off', () => { + const namespace = { + ...wireNamespaces().find(view => view.ns === 'subagent-model-selection')!, + value: null, + } as unknown as SettingsNamespaceView + const update = vi.fn() + render( + , + ) + + const toggle = screen.getByRole('switch', { name: en.subagentModelSelectionToggle }) + expect(toggle.getAttribute('aria-checked')).toBe('false') + expect((toggle as HTMLButtonElement).disabled).toBe(true) + fireEvent.click(toggle) + expect(update).not.toHaveBeenCalled() + }) + it('renders the unkeyed whole-section provider as an open setup card in the first-run posture', async () => { await mountFirstRun() // Nothing is reachable yet, and DeepSeek has no configured credential and diff --git a/packages/client/ui-sidebar/README.i18n.yaml b/packages/client/ui-sidebar/README.i18n.yaml index 1dc37495d9..fe0b552cee 100644 --- a/packages/client/ui-sidebar/README.i18n.yaml +++ b/packages/client/ui-sidebar/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-sidebar/README.md -README.md: b924c2e6d18217d9689b7c21137321856e14da2e -README.zh.md: 214a2727243d6d9151e31cfcfbc0bdb886c2fcdf +README.md: 075a132b9fc35ec4aee871690b436d3380e616fb +README.zh.md: 39ec5d58cd7270fbefdaa81eb0a6a022229d7963 diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index b924c2e6d1..075a132b9f 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Sidebar shell plugin: the brand row, New Session action, layout-owned collapse control, scroll-aware region seat, and bottom-pinned Settings seat. [ui-workspace](../ui-workspace/README.md) owns the Workspace and Session browser rendered into `sidebar.workspaces`; this package neither derives its rows nor owns its view preferences. Collapse into the layout-owned 56px rail remains presentation-local. Contract: the [slot system standard](../../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md). -The expanded brand row renders `sidebar.brand.mark` and `sidebar.brand.name` as independent single slots, while the collapsed rail renders the same mark slot. Without occupants, the shell uses the fish mark and a `DSH Local Build` label carrying the build's 7-character `DSH_CLIENT_COMMIT_HASH` badge. A deployment package can replace either value without replacing the New Session control or rail geometry; declaration-aware `slots.inject()` lets such a package activate before or after the sidebar. +The expanded brand row renders `sidebar.brand.mark` and `sidebar.brand.name` as independent single slots, while the collapsed rail renders the same mark slot. Without occupants, the shell uses the fish mark and a localized local-build label. A complete build stacks below it a code badge assembled as `version[-commit][-dirty]` from `DSH_CLIENT_VERSION`, the optional 7-character `DSH_CLIENT_COMMIT_HASH`, and `DSH_CLIENT_GIT_DIRTY=true`; missing version metadata omits the badge. A deployment package can replace either value without replacing the New Session control or rail geometry; declaration-aware `slots.inject()` lets such a package activate before or after the sidebar. New Session starts the runtime's page-local frontend Session Intent. The runtime targets the explicit Workspace used by a scoped action, otherwise the current Session's Workspace, otherwise the most recently active Workspace; when none exists it clears into the blank New Session page. Workspace-specific controls and the shared picker belong to ui-workspace. diff --git a/packages/client/ui-sidebar/README.zh.md b/packages/client/ui-sidebar/README.zh.md index 214a272724..39ec5d58cd 100644 --- a/packages/client/ui-sidebar/README.zh.md +++ b/packages/client/ui-sidebar/README.zh.md @@ -4,7 +4,7 @@ 侧边栏外壳插件:负责品牌行、New Session 操作、布局持有的折叠控件、可感知滚动的区域 seat,以及固定在底部的 Settings seat。[ui-workspace](../ui-workspace/README.zh.md) 持有渲染到 `sidebar.workspaces` 的 Workspace 与 Session 浏览器;本包既不派生其中的行,也不持有其视图偏好。折叠到布局拥有的 56px 轨道仍属于本地呈现行为。约定:[slot 系统标准](../../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.zh.md)。 -展开的品牌行把 `sidebar.brand.mark` 与 `sidebar.brand.name` 渲染为两个独立的 single slot,收起轨道则渲染同一个 mark slot。没有占位者时,外壳使用鱼形标记,以及带有构建期 7 位 `DSH_CLIENT_COMMIT_HASH` 徽标的 `DSH Local Build` 标签。部署包可以单独替换任一值,而无须替换 New Session 控件或轨道几何;声明感知的 `slots.inject()` 让这种包无论先于还是后于侧边栏激活都能生效。 +展开的品牌行把 `sidebar.brand.mark` 与 `sidebar.brand.name` 渲染为两个独立的 single slot,收起轨道则渲染同一个 mark slot。没有占位者时,外壳使用鱼形标记和本地化的本地构建标签。完整构建会在标签下方显示代码徽标;该徽标由 `DSH_CLIENT_VERSION`、可选的 7 位 `DSH_CLIENT_COMMIT_HASH` 与 `DSH_CLIENT_GIT_DIRTY=true` 组装成 `version[-commit][-dirty]`;缺少版本元数据时不显示徽标。部署包可以单独替换任一值,而无须替换 New Session 控件或轨道几何;声明感知的 `slots.inject()` 让这种包无论先于还是后于侧边栏激活都能生效。 New Session 会启动运行时的页面局部前端 Session Intent。运行时优先使用作用域操作明确指定的 Workspace,否则使用当前 Session 所属 Workspace,再否则使用最近活跃 Workspace;一个 Workspace 都没有时则清空选择,进入空白 New Session 页面。Workspace 专属控件与共享选择器由 ui-workspace 持有。 diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css index 44f3ddeaaa..d472581e43 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css @@ -159,6 +159,23 @@ white-space: nowrap; } +.localBuildBrand { + flex: none; + display: inline-flex; + flex-direction: column; + align-items: flex-start; + justify-content: center; + gap: 1px; + height: 24px; + white-space: nowrap; +} + +.localBuildTitle { + font-size: 12px; + line-height: 13px; + letter-spacing: 0; +} + .iconButton { flex: none; display: inline-flex; @@ -210,18 +227,20 @@ color: var(--dsw-alias-label-primary); } -.buildRevision { +.buildVersion { + flex: none; display: inline-flex; align-items: center; - height: 16px; - padding: 0 4px; - border-radius: 3px; + height: 10px; + padding: 0 3px; + border-radius: 2px; color: var(--dsw-alias-label-primary-inverted); background: var(--dsw-alias-label-primary); font-family: var(--ds-font-family-code); - font-size: 8px; + font-size: 6px; font-weight: 500; - line-height: 16px; + line-height: 10px; + white-space: nowrap; } /* New Session: 38px bar, 12px radius (figma 133:7634 geometry, squared-off diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx index d02518cb2d..9dde97bf9e 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx @@ -34,6 +34,16 @@ const COLLAPSE_SETTLE_MS = 150 */ const SCROLLBAR_LINGER_MS = 2000 +/** Format complete-build metadata for the local brand badge. */ +function localBuildVersion(): string | undefined { + const version = process.env.DSH_CLIENT_VERSION + if (version === undefined) return undefined + const commit = process.env.DSH_CLIENT_COMMIT_HASH + return version + + (commit === undefined ? '' : `-${commit}`) + + (process.env.DSH_CLIENT_GIT_DIRTY === 'true' ? '-dirty' : '') +} + /** * Render the sidebar column shell. * @param props - composed slot props (runtime share + injected callbacks, contract/slots.ts). @@ -111,6 +121,8 @@ export function SidebarRoot({ } }, [pointerInside]) + const buildVersion = localBuildVersion() + return (
{renderSlot('sidebar.brand.name', {}, { - fallback: ( - <> - {t('brand.localBuild')} - {process.env.DSH_CLIENT_COMMIT_HASH - ? {process.env.DSH_CLIENT_COMMIT_HASH} - : null} - - ), + fallback: buildVersion === undefined + ? {t('brand.localBuild')} + : ( + + {t('brand.localBuild')} + {buildVersion} + + ), })} diff --git a/packages/client/ui-sidebar/tests/__snapshots__/sidebar-snapshot.client.spec.tsx.snap b/packages/client/ui-sidebar/tests/__snapshots__/sidebar-snapshot.client.spec.tsx.snap index ee59061984..ba3e4d9540 100644 --- a/packages/client/ui-sidebar/tests/__snapshots__/sidebar-snapshot.client.spec.tsx.snap +++ b/packages/client/ui-sidebar/tests/__snapshots__/sidebar-snapshot.client.spec.tsx.snap @@ -138,14 +138,18 @@ exports[`sidebar shell snapshots > renders the expanded column (wordmark, capsul style="display: contents;" > - DSH Local Build - - - abc1234 + + DSH Local Build + + + 1.2.3-rc.4-abc1234-dirty +
@@ -264,14 +268,18 @@ exports[`sidebar shell snapshots > renders the expanded column in the default lo style="display: contents;" > - DSH 本地构建 - - - abc1234 + + DSH 本地构建 + + + 1.2.3-rc.4-abc1234-dirty +
diff --git a/packages/client/ui-sidebar/tests/sidebar-root.client.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-root.client.spec.tsx index 3ba66aa4ff..0f5edce0de 100644 --- a/packages/client/ui-sidebar/tests/sidebar-root.client.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-root.client.spec.tsx @@ -100,6 +100,8 @@ describe('SidebarRoot shell', () => { it('renders generic brand fallbacks when no package fills the slots', () => { vi.stubEnv('DSH_CLIENT_COMMIT_HASH', '0123456') + vi.stubEnv('DSH_CLIENT_GIT_DIRTY', 'true') + vi.stubEnv('DSH_CLIENT_VERSION', '1.2.3-rc.4') const { container } = render( { />) expect(screen.getByText('DSH Local Build')).toBeTruthy() - expect(screen.getByText('0123456')).toBeTruthy() + expect(screen.getByText('1.2.3-rc.4-0123456-dirty')).toBeTruthy() expect(container.querySelector('svg')).not.toBeNull() }) + it.each([ + [{ DSH_CLIENT_VERSION: '1.2.3' }, '1.2.3'], + [{ DSH_CLIENT_COMMIT_HASH: 'abcdef0', DSH_CLIENT_VERSION: '1.2.3' }, '1.2.3-abcdef0'], + ])('omits unavailable build-version suffixes from %j', (environment, expected) => { + for (const [name, value] of Object.entries(environment)) vi.stubEnv(name, value) + render( + options?.fallback ?? null) as SidebarRootComponentProps['renderSlot']} + />) + + expect(screen.getByText('DSH Local Build')).toBeTruthy() + expect(screen.getByText(expected)).toBeTruthy() + }) + + it('retains the local-build fallback without complete build metadata', () => { + render( + options?.fallback ?? null) as SidebarRootComponentProps['renderSlot']} + />) + + expect(screen.getByText('DSH Local Build')).toBeTruthy() + }) + it('hands the region its wide flag and clamps expandSidebar to the collapsed state', () => { const b = mountShell() expect(b.regionOwner().wide).toBe(true) diff --git a/packages/client/ui-sidebar/tests/sidebar-snapshot.client.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-snapshot.client.spec.tsx index a1c9b22621..a85d31cc02 100644 --- a/packages/client/ui-sidebar/tests/sidebar-snapshot.client.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-snapshot.client.spec.tsx @@ -20,7 +20,11 @@ import { apply, inject } from '@deepseek-ai/dsh-client-ui-sidebar/client' // the shipped Chinese copy, so they state the browser they assume. usePinnedBrowserLanguages('zh-CN') -beforeEach(() => { vi.stubEnv('DSH_CLIENT_COMMIT_HASH', 'abc1234') }) +beforeEach(() => { + vi.stubEnv('DSH_CLIENT_COMMIT_HASH', 'abc1234') + vi.stubEnv('DSH_CLIENT_GIT_DIRTY', 'true') + vi.stubEnv('DSH_CLIENT_VERSION', '1.2.3-rc.4') +}) afterEach(() => { cleanup() diff --git a/packages/client/web/README.i18n.yaml b/packages/client/web/README.i18n.yaml index e63b485800..855acd9bc7 100644 --- a/packages/client/web/README.i18n.yaml +++ b/packages/client/web/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/web/README.md -README.md: 3208cb202dd9c101f1ab5f3936aac50fae35ab1c -README.zh.md: c6be7daf8a86660627095063590b063b80e14839 +README.md: c95c5601b6e61d434e585bbf1887135fe177efb6 +README.zh.md: 5335760011f2e801503011d49240e08a7638981e diff --git a/packages/client/web/README.md b/packages/client/web/README.md index 3208cb202d..c95c5601b6 100644 --- a/packages/client/web/README.md +++ b/packages/client/web/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Web boot kernel: `new AppWebEntry(el, seams?).run()` mounts the client through two stages. The module stage calls the Host-installed `window.__ModuleLoader__.create()` with `window.__DSH_BOOT__`, the shell's static modules, and any test transport override; the facade returns the constructed module system and parsed manifest after adopting parser-preloaded registrations. This package then prefetches the `immediately` tier. The plugin stage mounts the vendored Cordis Loader, injects that module system through the Loader's `internal` interface, creates every graph entry uniformly, and waits for every fiber to become ACTIVE. It then hands the marked boot DOM to the dynamic UI renderer's `ctx.uiRenderer.mount(el)` operation; the renderer hydrates that DOM before switching to the complete UI. The Host owns the graph, parser preloads, and facade; AppWebEntry does not know the bootstrap package id or parse the wire format. +Web boot kernel: `new AppWebEntry(el, seams?).run()` mounts the client through two stages. The module stage calls the Host-installed `window.__ModuleLoader__.create()` with `window.__DSH_BOOT__`, the shell's static modules, and any test transport override; the facade returns the constructed module system and parsed manifest after adopting the parser-loaded bootstrap batch. This package then prefetches the `immediately` tier, whose shared application-batch URL executes once. The plugin stage mounts the vendored Cordis Loader, injects that module system through the Loader's `internal` interface, creates every graph entry uniformly, and waits for every fiber to become ACTIVE. It then hands the marked boot DOM to the dynamic UI renderer's `ctx.uiRenderer.mount(el)` operation; the renderer hydrates that DOM before switching to the complete UI. The Host owns the graph, batch preload, and facade; AppWebEntry does not know the bootstrap package id or parse the wire format. The boot page uses plain DOM and local CSS, so client-bundle and plugin-activation failures remain visible. Its fallback fonts and colors match the theme tokens that arrive during loading. Fiber updates retain one spinner node and grow its CSS arc as entries first become active; hydration preserves that node and its animation phase until the application commit. React mounting, slot rendering, and application assembly live in [`ui-renderer`](../ui-renderer/README.md); [`ui-layout`](../ui-layout/README.md) owns the assembled browser-title projection. The modules bundle caches its own materialized exports and provides the closed-over system when its ordinary graph entry activates; Cordis service waiting makes graph-row creation order independent from that activation. diff --git a/packages/client/web/README.zh.md b/packages/client/web/README.zh.md index c6be7daf8a..5335760011 100644 --- a/packages/client/web/README.zh.md +++ b/packages/client/web/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -Web 启动内核:`new AppWebEntry(el, seams?).run()` 分两个阶段挂载客户端。模块阶段调用 Host 安装的 `window.__ModuleLoader__.create()`,传入 `window.__DSH_BOOT__`、外壳静态模块以及可选测试传输覆盖;facade 接纳 parser 预载的 registration 后返回构造好的模块系统与已解析 manifest。本包随后预取 `immediately` 层级。插件阶段挂载仓库内置的 Cordis Loader,通过 Loader 的 `internal` 接口注入该模块系统,统一创建全部图 entry,并等待每个 fiber 进入 ACTIVE。随后它把带标记的启动 DOM 交给动态 UI 渲染器的 `ctx.uiRenderer.mount(el)` 操作;渲染器先 hydrate 该 DOM,再切换到完整 UI。Graph、parser preload 与 facade 归 Host 所有;AppWebEntry 不感知 bootstrap package id,也不解析 wire 格式。 +Web 启动内核:`new AppWebEntry(el, seams?).run()` 分两个阶段挂载客户端。模块阶段调用 Host 安装的 `window.__ModuleLoader__.create()`,传入 `window.__DSH_BOOT__`、外壳静态模块以及可选测试传输覆盖;facade 接纳 parser 已加载的 bootstrap 批次后返回构造好的模块系统与已解析 manifest。本包随后预取 `immediately` 层级,其共享的 application 批次 URL 只执行一次。插件阶段挂载仓库内置的 Cordis Loader,通过 Loader 的 `internal` 接口注入该模块系统,统一创建全部图 entry,并等待每个 fiber 进入 ACTIVE。随后它把带标记的启动 DOM 交给动态 UI 渲染器的 `ctx.uiRenderer.mount(el)` 操作;渲染器先 hydrate 该 DOM,再切换到完整 UI。Graph、批次 preload 与 facade 归 Host 所有;AppWebEntry 不感知 bootstrap package id,也不解析 wire 格式。 启动页只使用原生 DOM 与本地 CSS,因此客户端 bundle 或插件激活失败时仍能显示。其回退字体和颜色与加载期间到达的主题 token 一致。fiber 更新会保留同一个 spinner 节点,并在 entry 首次进入 active 时增长其 CSS 圆弧;hydrate 会继续保留该节点及其动画相位,直到应用提交。React 挂载、slot 渲染和应用组装位于 [`ui-renderer`](../ui-renderer/README.zh.md);[`ui-layout`](../ui-layout/README.zh.md) 拥有组装后的浏览器标题投影。Modules bundle 会缓存自身已物化导出,并在其普通图 entry 激活时提供闭包中的系统;Cordis service 等待使图 row 创建顺序不依赖该激活时点。 diff --git a/packages/client/web/tests/boot.client.spec.ts b/packages/client/web/tests/boot.client.spec.ts index def708d2c5..34b13d40ad 100644 --- a/packages/client/web/tests/boot.client.spec.ts +++ b/packages/client/web/tests/boot.client.spec.ts @@ -80,7 +80,11 @@ describe('bootstrap failure rendering', () => { await expectBootFailure(() => { installFacade() const duplicate = { id: 'duplicate', url: '/duplicate/client.js', rev: '1' } - win.__DSH_BOOT__ = { rev: 'graph', entries: [duplicate, duplicate] } + win.__DSH_BOOT__ = { + rev: 'graph', + entries: [duplicate, duplicate], + batches: [{ phase: 'application', url: '/batch.js', rev: 'batch', entries: ['duplicate'] }], + } }, 'duplicate graph entry "duplicate"') }) }) @@ -102,50 +106,54 @@ describe('plugin activation', () => { { id: 'provider', url: '/provider.js', rev: '1' }, { id: 'renderer', url: '/renderer.js', rev: '1' }, ] - win.__DSH_BOOT__ = { rev: 'graph', entries } - target.load({ - id: 'runtime', - factory: require => ({ - apply: () => {}, - marker: (require(PROVIDER_CLIENT_ID) as { marker: string }).marker, - }), - }) + const applicationUrl = '/application.js' + win.__DSH_BOOT__ = { + rev: 'graph', + entries, + batches: [{ phase: 'application', url: applicationUrl, rev: 'batch', entries: entries.map(row => row.id) }], + } const loaded: string[] = [] - const registrations = new Map([ - ['/consumer.js', { + const registrations: ClientBundleRegistration[] = [ + { id: 'consumer', factory: require => ({ apply: () => { expect((require(RUNTIME_CLIENT_ID) as { marker: string }).marker).toBe('provider') }, }), - }], - ['/provider.js', { + }, + { id: 'provider', factory: () => ({ apply: () => {}, marker: 'provider' }), - }], - ['/renderer.js', { + }, + { + id: 'runtime', + factory: require => ({ + apply: () => {}, + marker: (require(PROVIDER_CLIENT_ID) as { marker: string }).marker, + }), + }, + { id: 'renderer', factory: () => ({ apply: (ctx: Context) => { ctx.reflect.provide('uiRenderer', { mount: () => () => {} }) }, }), - }], - ]) + }, + ] transportGlobal.__DSH_TRANSPORT__ = { loadBundle: async (url) => { loaded.push(url) - const registration = registrations.get(url) - if (registration === undefined) throw new Error(`missing fixture registration ${url}`) - target.load(registration) + if (url !== applicationUrl) throw new Error(`missing fixture batch ${url}`) + for (const registration of registrations) target.load(registration) }, } const entry = new AppWebEntry(container) await entry.run() - expect(loaded).toEqual(['/provider.js', '/consumer.js', '/renderer.js']) + expect(loaded).toEqual([applicationUrl]) await entry.dispose() }) @@ -159,7 +167,16 @@ describe('plugin activation', () => { { id: MODULES_ID, url: '/modules.js', rev: '1' }, { id: 'renderer', url: '/renderer.js', rev: '1' }, ] - win.__DSH_BOOT__ = { rev: 'graph', entries } + win.__DSH_BOOT__ = { + rev: 'graph', + entries, + batches: [{ + phase: 'application', + url: '/application.js', + rev: 'batch', + entries: entries.map(row => row.id), + }], + } const registrations = new Map([ ['/consumer.js', { id: 'consumer', @@ -188,9 +205,8 @@ describe('plugin activation', () => { ]) const entry = new AppWebEntry(container, { loadBundle: async (url) => { - const registration = registrations.get(url) - if (registration === undefined) throw new Error(`missing fixture registration ${url}`) - target.load(registration) + if (url !== '/application.js') throw new Error(`missing fixture batch ${url}`) + for (const registration of registrations.values()) target.load(registration) }, }) diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 2a5445de6b..88d4e6da7d 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/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/core/agent-loop/README.md -README.md: 907bbe75fd687388be044916f4c4509e1c552177 -README.zh.md: 76a73155a3d9f811931cf0f86c227e6ab3dc1c32 +README.md: 1b233ae1203171930ef5b58de93ec67381ec4918 +README.zh.md: 81af654072f23c5280e2e14bc891972b5e1f37d5 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 907bbe75fd..1b233ae120 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -42,6 +42,7 @@ interface Config { id: string // required provider?: string model?: string + reasoningEffort?: string // non-empty initial reasoning effort maxTokens?: number // positive per-request output-token cap resumeSessionId?: string // load this persisted session instead of creating one cwd?: string // optional workspace cwd for the fresh session @@ -49,7 +50,7 @@ interface Config { } ``` -Configured agents start automatically. A model call requires both `provider` and `model`; `agent/request` may supply a missing pair before dispatch. An optional positive `maxTokens` seeds each conversation request's output cap and is logged in its request header. `maxParallelToolCalls` bounds every agent's rolling pool for parallel-safe calls and defaults to `10`; it is also the whole of the `agent-loop` Settings section, so a user layer over this entry caps the next tool group without a restart, and a value that is not a positive integer is refused at the write rather than at that group. `agents` is deliberately absent from that section — it is consumed once when the service starts, so a stored change could only look like it had an effect. `cwd` applies only to fresh sessions, while `resumeSessionId` retains persisted metadata. Configured agents use the deployment persona, and programmatic setup can shadow it per agent. This plugin supplies the per-agent `provider`, `model`, and `cwd` prompt variables; harness identity and deployment persona belong to `dsh-system-prompt`. +Configured agents start automatically. A model call requires both `provider` and `model`; `agent/request` may supply a missing pair before dispatch. An optional non-empty `reasoningEffort` seeds the request's reasoning setting; `agent/request` may override it, and adapter resolution validates the effective value recorded in the request header. An optional positive `maxTokens` seeds each conversation request's output cap and is logged in its request header. `maxParallelToolCalls` bounds every agent's rolling pool for parallel-safe calls and defaults to `10`; it is also the whole of the `agent-loop` Settings section, so a user layer over this entry caps the next tool group without a restart, and a value that is not a positive integer is refused at the write rather than at that group. `agents` is deliberately absent from that section — it is consumed once when the service starts, so a stored change could only look like it had an effect. `cwd` applies only to fresh sessions, while `resumeSessionId` retains persisted metadata. Configured agents use the deployment persona, and programmatic setup can shadow it per agent. This plugin supplies the per-agent `provider`, `model`, and `cwd` prompt variables; harness identity and deployment persona belong to `dsh-system-prompt`. ### Internal concrete driver diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 76a73155a3..81af654072 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -42,6 +42,7 @@ interface Config { id: string // required provider?: string model?: string + reasoningEffort?: string // non-empty initial reasoning effort maxTokens?: number // positive per-request output-token cap resumeSessionId?: string // load this persisted session instead of creating one cwd?: string // optional workspace cwd for the fresh session @@ -49,7 +50,7 @@ interface Config { } ``` -通过配置创建的 agent 会自动启动。模型调用同时需要 `provider` 和 `model`;`agent/request` 可以在分发前补齐缺失的这一对值。可选的正数 `maxTokens` 会为每次对话请求提供初始输出上限,并记录在请求 header 中。`maxParallelToolCalls` 限制每个 agent 针对并行安全调用使用的滚动池,默认值为 `10`;它同时也是 `agent-loop` Settings 段的全部内容,因此叠加在该条目之上的用户层无需重启即可限制下一组工具调用,而非正整数的值会在写入时被拒绝,而不是到那一组时才失败。`agents` 刻意不在该段中——它在服务启动时被消费一次,所以存储的改动只会看起来生效。`cwd` 仅应用于全新会话,而 `resumeSessionId` 保留持久化元数据。通过配置创建的 agent 使用部署 persona;编程式 setup 可以按 agent 遮蔽它。该插件为每个 agent 提供 `provider`、`model` 和 `cwd` 提示词变量;harness 身份与部署 persona 属于 `dsh-system-prompt`。 +通过配置创建的 agent 会自动启动。模型调用同时需要 `provider` 和 `model`;`agent/request` 可以在分发前补齐缺失的这一对值。可选的非空 `reasoningEffort` 会提供请求的初始推理强度;`agent/request` 可以覆盖它,适配器解析会校验记录在请求 header 中的最终值。可选的正数 `maxTokens` 会为每次对话请求提供初始输出上限,并记录在请求 header 中。`maxParallelToolCalls` 限制每个 agent 针对并行安全调用使用的滚动池,默认值为 `10`;它同时也是 `agent-loop` Settings 段的全部内容,因此叠加在该条目之上的用户层无需重启即可限制下一组工具调用,而非正整数的值会在写入时被拒绝,而不是到那一组时才失败。`agents` 刻意不在该段中——它在服务启动时被消费一次,所以存储的改动只会看起来生效。`cwd` 仅应用于全新会话,而 `resumeSessionId` 保留持久化元数据。通过配置创建的 agent 使用部署 persona;编程式 setup 可以按 agent 遮蔽它。该插件为每个 agent 提供 `provider`、`model` 和 `cwd` 提示词变量;harness 身份与部署 persona 属于 `dsh-system-prompt`。 ### 包内部具体驱动器 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 3ef1ec7aa4..6bf7517903 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -438,11 +438,12 @@ export class ReactLoopAgent implements Agent { const persistedHeader = session.requestHeader() const persistedConfig = persistedHeader?.config const route = { provider: this.options.provider ?? '', model: this.options.model ?? '' } - const reasoningEffort = persistedConfig?.provider === route.provider + const persistedReasoningEffort = persistedConfig?.provider === route.provider && persistedConfig.model === route.model && persistedHeader?.adapterDefaults?.reasoningEffort !== true ? persistedConfig.reasoningEffort : undefined + const reasoningEffort = this.options.reasoningEffort ?? persistedReasoningEffort const maxTokens = this.options.maxTokens const seedConfig = deepFreeze(structuredClone( this.requestHeaderLogged diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 371154a7c9..38ee7dfef5 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -19,7 +19,7 @@ import type { ResumeAgentOptions, SessionStartSource, } from '@deepseek-ai/dsh-agent' -import { errorChain } from '@deepseek-ai/dsh-llm' +import { errorChain, ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings' import { SessionId, SessionPreparation } from '@deepseek-ai/dsh-session' import type { Session, SessionHeader } from '@deepseek-ai/dsh-session' @@ -304,6 +304,7 @@ export class AgentLoop extends Service implements AgentFactory { sessionId: z.string().min(1), provider: z.string(), model: z.string(), + reasoningEffort: z.string().min(1) as z>, maxTokens: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), cwd: z.string(), resumeSessionId: z.string(), diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index 2105b86f42..4082b43452 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import LlmRuntime, { createUserMessage, CallId, LlmError, StreamChunk } from '@deepseek-ai/dsh-llm' +import LlmRuntime, { createUserMessage, CallId, LlmError, ReasoningEffortId, StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, TurnEndReason } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools' @@ -77,6 +77,34 @@ describe('agent loop', () => { expect(adapter.requests[0]?.maxTokens).toBe(256) }) + it('seeds an AgentOptions reasoning effort into the first model request', async () => { + const effort = ReasoningEffortId('high') + const adapter = new MockAdapter([textResponse('reasoned')], { + efforts: [{ id: effort, name: 'High' }], + defaultEffort: effort, + }) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create( + SessionId('configured-reasoning-effort'), + { provider: 'mock', model: 'mock', reasoningEffort: effort }, + ) + + send(agent, 'use the configured reasoning effort') + await waitForIdle(ctx, agent) + + expect(adapter.requests[0]?.reasoningEffort).toBe(effort) + }) + + it('validates reasoning effort in declarative agent config', () => { + const effort = ReasoningEffortId('high') + expect(AgentLoop.Config({ + agents: [{ id: 'configured-agent', reasoningEffort: effort }], + }).agents[0]?.reasoningEffort).toBe(effort) + expect(() => AgentLoop.Config({ + agents: [{ id: 'configured-agent', reasoningEffort: ReasoningEffortId('') }], + })).toThrow() + }) + it('cancels queued wakeup work together with an active maintenance task', async () => { const adapter = new MockAdapter([textResponse('park reply')]) const ctx = await harness(adapter) @@ -1429,7 +1457,11 @@ describe('agent loop', () => { }) it('creates agents from config on startup', async () => { - const adapter = new MockAdapter([textResponse('from config')]) + const effort = ReasoningEffortId('high') + const adapter = new MockAdapter([textResponse('from config')], { + efforts: [{ id: effort, name: 'High' }], + defaultEffort: effort, + }) const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) @@ -1437,7 +1469,7 @@ describe('agent loop', () => { await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) await ctx.plugin(AgentLoop, { - agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }], + agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', reasoningEffort: effort }], }) ctx.llm.registerAdapter(['mock'], adapter) @@ -1451,6 +1483,9 @@ describe('agent loop', () => { send(agent, 'hi') await waitForIdle(ctx, agent) expect(adapter.requests).toHaveLength(1) + expect(adapter.requests[0]?.reasoningEffort).toBe(effort) + const header = agent.session.events.find(event => event.type === 'request/header') + expect(header?.type === 'request/header' && header.data.header.config.reasoningEffort).toBe(effort) }) it('attaches config agent cwd to the fresh session header', async () => { diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 4dd5627b2e..a9d78f3fad 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/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/core/agent/README.md -README.md: f6b698e93b254c97786155e7d2c7e81f07c0d981 -README.zh.md: 5e3da8a5d09d06fa4fc9726406aae9c6d5e69c3e +README.md: 70b396d787de5d95332c379ff20ab92c64065857 +README.zh.md: fee72f3cd1fb456ae639d6444fe3fe914c41220a diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index f6b698e93b..70b396d787 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -14,7 +14,7 @@ Tracks live agents and carries the initiating Agent through asynchronous driver The scoped-registration surface: `Agent.ctx` is the agent's scope context (`dsh-scope`, key = the agent) — register tools/sections/variables/listeners through it for that agent alone, all unwound on disposal. `agentEvents(ctx, agent)` is the fused dispatcher for ordinary agent-subject operations (carrier + injected subject in one move); its notification mode invokes every listener and contains both synchronous throws and returned-promise rejections. The registry lifecycle pair reuses one stable routing carrier. `assembleContextFor(agent)` builds the per-agent assembly context (`agent` + `scope` together). `installModelSelection(agentCtx, selection)` snapshots a mutable provider/model/reasoning-effort selection during prompt assembly, applies its provider and model to prompt variables, and applies the complete selection to request routing for one step; an absent selected effort clears an inherited effort so adapter/provider defaults apply. `CreateAgentOptions.setup(agentCtx)` and `ResumeAgentOptions.setup(agentCtx)` compose a fresh or resumed agent's scoped world while both objects remain unpublished. Setup is trusted, composition-only same-process code: drive the agent only after creation resolves. -`AgentOptions` supplies the initial provider/model route and an optional positive `maxTokens` output cap. The concrete loop resolves any exact-model adapter default, records the effective cap in the request header, and applies it to each conversation-model request; an explicit Agent option wins, while omission leaves the adapter or provider route default in control. +`AgentOptions` supplies the initial provider/model route, optional adapter-owned `reasoningEffort`, and optional positive `maxTokens` output cap. The concrete loop validates exact-model reasoning support, resolves adapter defaults, records the effective values in the request header, and applies them to each conversation-model request; an explicit Agent option wins, while omission leaves the adapter or provider route default in control. - `ctx.agents.register(agent: Agent): () => void` — record an **already-constructed** agent. Disposed with the calling fiber. - Advanced ordered lifecycle: `enter(agent, owner): () => void` enforces `agent.id === agent.session.id`, performs the authoritative ID collision check, and inserts without announcing; `owner` explicitly records the live creator-agent relation (or `undefined` for a root), independently of durable session lineage. `announce(agent)` emits `agent/created` exactly once. A detach requested synchronously by a creation listener is deferred until that dispatch unwinds, and every detach checks the captured entry object, so a stale capability cannot delete a later same-ID replacement. The async factory uses this split; ordinary plugins use `register()`. diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index 5e3da8a5d0..fee72f3cd1 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -14,7 +14,7 @@ Agent 接口、注册表、进程本地发起方作用域,以及 `agent/*` 事 带作用域的注册接口:`Agent.ctx` 是 agent 的作用域上下文(`dsh-scope`,键 = 该 agent)。通过它注册工具/段/变量/监听器,只对该 agent 生效,并在 dispose(资源释放)时全部撤销。`agentEvents(ctx, agent)` 是普通 agent 主体操作的融合分发器(一次完成载体 + 注入主体);其通知 mode 会调用每个监听器,并同时收容同步抛出和返回 Promise 的拒绝。注册表生命周期对复用一个稳定路由载体。`assembleContextFor(agent)` 构建按 agent 的组装上下文(同时包含 `agent` + `scope`)。`installAgentLlmTarget(agentCtx, target)` 在提示词组装期间快照可变的提供方/模型/推理(reasoning)强度选择,将路由应用到提示词变量,并将完整目标应用到一个步骤的请求路由;如果没有选定推理强度,则会清除继承的推理强度,使该目标使用适配器/提供方默认值。`CreateAgentOptions.setup(agentCtx)` 和 `ResumeAgentOptions.setup(agentCtx)` 在新建或恢复的 agent 尚未发布时,组合其带作用域的世界。Setup 是受信任、仅用于组合的同进程代码:只有创建完成后才能驱动 agent。 -`AgentOptions` 提供初始的提供方/模型路由,以及可选的正数 `maxTokens` 输出上限。具体循环会解析确切模型的适配器默认值,把生效上限记录到请求 header,并应用到每次对话模型请求;显式 Agent 选项优先,省略时由适配器或提供方路由默认值控制。 +`AgentOptions` 提供初始的提供方/模型路由、可选且由适配器定义的 `reasoningEffort`,以及可选的正数 `maxTokens` 输出上限。具体循环会校验确切模型支持的推理强度、解析适配器默认值,把生效值记录到请求 header,并应用到每次对话模型请求;显式 Agent 选项优先,省略时由适配器或提供方路由默认值控制。 - `ctx.agents.register(agent: Agent): () => void`:记录一个 **已经构造完成** 的 agent。随调用 fiber dispose。 - 高级有序生命周期:`enter(agent, owner): () => void` 强制 `agent.id === agent.session.id`,执行权威 ID 冲突检查,并在不通知的情况下插入;`owner` 显式记录实时创建方 agent 关系(根 agent 为 `undefined`),与持久会话谱系无关。`announce(agent)` 恰好发出一次 `agent/created`。创建监听器同步请求的 detach 会延后到该次分发结束;每次 detach 都会检查捕获的条目对象,因此陈旧能力无法删除后续使用同一 ID 的替代项。异步工厂使用这一拆分;普通插件使用 `register()`。 diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index df7449d406..3f8f7c512b 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -7,7 +7,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { Scoped } from '@deepseek-ai/dsh-scope' -import type { LlmCallConfig, LlmFailure, ResolvedRetryPolicy } from '@deepseek-ai/dsh-llm' +import type { LlmCallConfig, LlmFailure, ReasoningEffortId, ResolvedRetryPolicy } from '@deepseek-ai/dsh-llm' import type { AgentCancelCause, Session, UserMessage } from '@deepseek-ai/dsh-session' export type { AgentCancelCause } from '@deepseek-ai/dsh-session' import type { Inbox } from './inbox.ts' @@ -27,6 +27,8 @@ export interface AgentOptions { provider?: string /** Model id interpreted by the selected provider adapter. */ model?: string + /** Adapter-owned reasoning effort for the selected provider/model route. */ + reasoningEffort?: ReasoningEffortId /** Maximum output tokens for each conversation-model request. */ maxTokens?: number } diff --git a/packages/core/session/src/known-event-types.ts b/packages/core/session/src/known-event-types.ts index b4e7117541..c005211567 100644 --- a/packages/core/session/src/known-event-types.ts +++ b/packages/core/session/src/known-event-types.ts @@ -49,6 +49,7 @@ export const KNOWN_SESSION_EVENT_TYPES: ReadonlySet = new Set([ 'step/end', 'step/start', 'subagent/descriptor', + 'subagent/model-selection-enabled', 'team/member', 'team/message/delivered', 'team/message/queued', diff --git a/packages/core/system-prompt/README.i18n.yaml b/packages/core/system-prompt/README.i18n.yaml index dd68b6a139..c34ff9547a 100644 --- a/packages/core/system-prompt/README.i18n.yaml +++ b/packages/core/system-prompt/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/core/system-prompt/README.md -README.md: d750a507e628e7609af542227e4528d4d4934ce8 -README.zh.md: ec5b32d742b96c8044a3707c35f15e30ba642b4f +README.md: a52aa3e4c2782993fed5a525cc827aba4e3eaeb0 +README.zh.md: cf0ba43aa2f2f47ea61ef13c74fbf182fbd9f2ee diff --git a/packages/core/system-prompt/README.md b/packages/core/system-prompt/README.md index d750a507e6..a52aa3e4c2 100644 --- a/packages/core/system-prompt/README.md +++ b/packages/core/system-prompt/README.md @@ -11,6 +11,7 @@ System prompt assembly registry. Plugins contribute ordered sections, tool schem | `includeHarnessIdentity` | `true` | Include the fixed `You are an AI agent powered by DeepSeek Harness.` order-−100 opener. Set false only when a compatibility deployment owns the complete system prompt. | | `includeRuntimeContext` | `true` | Include ordered dynamic contexts in assembly. When false, context providers are not evaluated and contexts added by `system-prompt/assemble` listeners are discarded after the waterfall; other services and their enforcement remain active. | | `persona` | `''` | The global deployment-persona default: the ONE config-authored prompt fragment, rendered as the order-0 `deployment:persona` section unless an agent-scoped contribution shadows it. A template — complete `{{…}}` groups are interpreted strictly against the registered variables (the shipped loop registers `{{model}}`/`{{cwd}}`), with no escape syntax for literal braces yet. Empty ⇒ the section is dropped at render. | +| `personaComplete` | `false` | Treat `persona` as the complete system prompt after assembly. Other sections remain registered but are omitted from model requests; tool schemas and variables remain available. | | `toolOrder` | — | Explicit model-facing tool order, as a list of `ToolSchema.name`s with one `''` rest entry (`TOOL_ORDER_REST`): listed tools take their listed position, unlisted tools land at the rest entry in lexicographic name order. Absent ⇒ plain lexicographic name order. Applied to the collected tools BEFORE the `system-prompt/assemble` waterfall — like the sections' `order` sort, it canonicalizes what the registry contributed (registration order is a plugin-load artifact), and a waterfall listener that mutates the list owns the determinism of what it emits. Misconfiguration fails loud: a list without exactly one rest entry, or with duplicates, throws at load; a listed name with no registered tool rejects every `assemble()`; a tool provider returning the reserved rest-entry name also rejects. Under the shipped loop the turn fails before any model request. Why a central list and not per-plugin weights: [Explicit model-facing tool order](../../../.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.md). | ## Service: `SystemPrompt` (ctx key: `systemPrompt`) diff --git a/packages/core/system-prompt/README.zh.md b/packages/core/system-prompt/README.zh.md index ec5b32d742..cf0ba43aa2 100644 --- a/packages/core/system-prompt/README.zh.md +++ b/packages/core/system-prompt/README.zh.md @@ -11,6 +11,7 @@ | `includeHarnessIdentity` | `true` | 是否包含顺序为 −100 的固定开场白 `You are an AI agent powered by DeepSeek Harness.`。仅当兼容性部署拥有完整系统提示词时设为 false。 | | `includeRuntimeContext` | `true` | 是否在组装中包含有序动态上下文。设为 false 时不会求值上下文提供方,并会在 waterfall 后丢弃 `system-prompt/assemble` 监听器添加的上下文;其他服务及其强制机制仍然生效。 | | `persona` | `''` | 全局部署 persona 默认值:唯一由配置提供的提示词片段,渲染为顺序为 0 的 `deployment:persona` 段,除非 agent 作用域的贡献将其遮蔽。它是模板,完整的 `{{…}}` 组会严格按已注册变量解释(随附循环注册 `{{model}}`/`{{cwd}}`),目前没有表达字面量花括号的转义语法。为空 ⇒ 渲染时删除该段。 | +| `personaComplete` | `false` | 在组装后将 `persona` 作为完整系统提示词。其他段仍保持注册,但不会进入模型请求;工具 schema 与变量仍然可用。 | | `toolOrder` | 无 | 显式指定面向模型的工具顺序。该列表由 `ToolSchema.name` 组成,并且必须恰好包含一个 `''` 其余项标记(`TOOL_ORDER_REST`):已列工具按列表位置排列,未列工具则按名称字典序插入该标记所在的位置。缺席 ⇒ 直接按名称字典序排列。该顺序会在 `system-prompt/assemble` waterfall(瀑布式事件)之前应用于已收集的工具。与段的 `order` 排序一样,它会规范化注册表贡献的内容;注册顺序只是插件加载时序的产物。修改列表的 waterfall 监听器对其输出的确定性负责。配置错误会明确失败:列表没有恰好一个其余项或存在重复项,会在加载时抛出;已列名称没有对应已注册工具,会使每次 `assemble()` 被拒绝;工具提供方返回保留的其余项名称也会被拒绝。在随附循环下,轮次会在任何模型请求前失败。为何采用中心列表而非每插件权重,见[显式面向模型工具顺序](../../../.agents/notes/implemented/feature/2026-07-06-explicit-tool-order.zh.md)。 | ## 服务:`SystemPrompt`(ctx 键:`systemPrompt`) diff --git a/packages/core/system-prompt/src/index.ts b/packages/core/system-prompt/src/index.ts index ffc052e0b9..ec36b32432 100644 --- a/packages/core/system-prompt/src/index.ts +++ b/packages/core/system-prompt/src/index.ts @@ -193,6 +193,8 @@ export interface Config { * `deployment:persona` shadows it; `{{variable}}` references are strict. */ persona?: string + /** Treat the deployment persona as the complete system prompt (default false). */ + personaComplete?: boolean /** * Model-facing tool names in order, with {@link TOOL_ORDER_REST} exactly once. * Invalid fields fail at load and unknown names fail at assembly; known names @@ -340,6 +342,7 @@ export class SystemPrompt extends Service { includeHarnessIdentity: z.boolean().default(true), includeRuntimeContext: z.boolean().default(true), persona: z.string().default(''), + personaComplete: z.boolean().default(false), // Preserve omission because an explicit empty order lacks the rest marker. toolOrder: z.array(z.string()).default(undefined as unknown as string[]), }) @@ -366,6 +369,7 @@ export class SystemPrompt extends Service { order: PERSONA_ORDER, // The fallback narrows the optional input type; the schema already defaults it. text: config.persona ?? '', + complete: config.personaComplete ?? false, }) if (!(config.includeRuntimeContext ?? true)) this.suppressRuntimeContext() } diff --git a/packages/core/system-prompt/tests/system-prompt.spec.ts b/packages/core/system-prompt/tests/system-prompt.spec.ts index cf196892a7..c4018103d3 100644 --- a/packages/core/system-prompt/tests/system-prompt.spec.ts +++ b/packages/core/system-prompt/tests/system-prompt.spec.ts @@ -49,6 +49,21 @@ describe('SystemPrompt', () => { expect(renderPrompt(assembly)).toBe('You are a helpful software engineer assistant.') }) + it('can make the deployment persona the complete system prompt', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt, { + persona: 'You are a focused SDK agent.', + personaComplete: true, + }) + ctx.systemPrompt.section({ name: 'tool:future', order: 100, text: 'Future tool guidance.' }) + + const assembly = await ctx.systemPrompt.assemble() + expect(assembly.sections).toEqual([ + { name: 'deployment:persona', text: 'You are a focused SDK agent.' }, + ]) + expect(renderPrompt(assembly)).toBe('You are a focused SDK agent.') + }) + it('can suppress runtime context without evaluating providers or accepting waterfall additions', async () => { const ctx = new Context() await ctx.plugin(SystemPrompt, { includeRuntimeContext: false }) diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index ce2007c34b..38d68deae6 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -30,7 +30,7 @@ describe('gen-tool-catalog collectToolCatalog', () => { 'cordis_inspect_query', 'cordis_inspect_self', 'cordis_run', 'cordis_stop', 'cordis_undefine', 'create_goal', 'edit', 'exit_plan_mode', 'followup_task', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', - 'list_agents', 'list_agents', 'lsp', 'pwsh', 'pwsh', 'ralph', + 'list_agents', 'list_agents', 'list_subagent_models', 'lsp', 'pwsh', 'pwsh', 'ralph', 'read', 'read_image', 'report', 'run_code', 'schedule_create', 'schedule_delete', 'schedule_list', 'send_message', 'send_message', 'session_event_read', 'session_event_search', 'session_event_trace', 'session_search', 'session_trace', 'skill', 'spawn_teammate', @@ -88,7 +88,7 @@ describe('gen-tool-catalog collectToolCatalog', () => { // agents surface this one package as both `subagent` and `subagent_fork`. const catalog = await collectToolCatalog() const subagent = catalog.find(entry => entry.pkg === '@deepseek-ai/dsh-tool-subagent') - expect(subagent?.schemas.map(s => s.name)).toEqual(['subagent']) + expect(subagent?.schemas.map(s => s.name)).toEqual(['list_subagent_models', 'subagent']) expect(subagent?.note).toMatch(/subagent_fork/) }) }) diff --git a/packages/e2b/fs-e2b/tests/filesystem.spec.ts b/packages/e2b/fs-e2b/tests/filesystem.spec.ts index fa75709ec2..97e549e84b 100644 --- a/packages/e2b/fs-e2b/tests/filesystem.spec.ts +++ b/packages/e2b/fs-e2b/tests/filesystem.spec.ts @@ -360,6 +360,7 @@ describe('E2BFileSystem identity, metadata, and reads', () => { const outside = await fs.resolve('/outside.ts') expect(fs.processPath(nested)).toBe('/workspace/nested/multibyte # file.ts') + expect(fs.processPathFromHostPath('/Users/alice/.dsh/attachments/object')).toBeUndefined() expect(fs.fileUrl(nested)).toBe('file:///workspace/nested/multibyte%20%23%20file.ts') expect(fs.contains(workspace, workspace)).toBe(true) expect(fs.contains(workspace, nested)).toBe(true) diff --git a/packages/examples/README.i18n.yaml b/packages/examples/README.i18n.yaml index c3e1d67e92..c0c43e838d 100644 --- a/packages/examples/README.i18n.yaml +++ b/packages/examples/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/README.md -README.md: 1193ae404bb7f1a69636f45ff36eee82ec648b2c -README.zh.md: 935bbd1329082f857a692df913a89e7007054b63 +README.md: 2d17e60ed990c8cb77ebfd5823ba2f67e63e8837 +README.zh.md: deea149a11dc70a329bb27c6d851d62d46c6d16e diff --git a/packages/examples/README.md b/packages/examples/README.md index 1193ae404b..2d17e60ed9 100644 --- a/packages/examples/README.md +++ b/packages/examples/README.md @@ -8,7 +8,7 @@ Pre-composed plugin bundles a thin leaf `cordis.yml` loads instead of assembling |---|---|---| | [`agent-spine-demo/`](agent-spine-demo/README.md) | `@deepseek-ai/dsh-agent-spine-demo` | Reusable agent-spine bundle | -`agent-spine-demo` is the shared bundle. Product SDK, ACP, and one-shot execution belong to `dsh --profile sdk`, `dsh --profile acp`, and `dsh --profile headless`; no package in this directory provides an application entry. +`agent-spine-demo` is the shared bundle. Product SDK, ACP, and one-shot execution belong to `dsh --profile sdk` / `dsh --profile sdk-minimal`, `dsh --profile acp`, and `dsh --profile headless`; no package in this directory provides an application entry. These packages are not product API. Product seams and entry points remain in their owning groups; demo bundles select concrete compositions. diff --git a/packages/examples/README.zh.md b/packages/examples/README.zh.md index 935bbd1329..deea149a11 100644 --- a/packages/examples/README.zh.md +++ b/packages/examples/README.zh.md @@ -8,7 +8,7 @@ |---|---|---| | [`agent-spine-demo/`](agent-spine-demo/README.zh.md) | `@deepseek-ai/dsh-agent-spine-demo` | 可复用的 agent-spine(智能体主干)组合包 | -`agent-spine-demo` 是共享组合包。产品 SDK、ACP 与一次性执行分别由 `dsh --profile sdk`、`dsh --profile acp` 和 `dsh --profile headless` 提供;本目录没有任何包提供应用入口。 +`agent-spine-demo` 是共享组合包。产品 SDK、ACP 与一次性执行分别由 `dsh --profile sdk`/`dsh --profile sdk-minimal`、`dsh --profile acp` 和 `dsh --profile headless` 提供;本目录没有任何包提供应用入口。 这些包不是产品 API。产品 seam 与产品入口仍位于各自的归属组;演示组合包选择具体组合。 diff --git a/packages/examples/agent-spine-demo/README.i18n.yaml b/packages/examples/agent-spine-demo/README.i18n.yaml index 1144fb7047..dedce4969d 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: 509e4e6d6b5885fb0c685e4ee34fe8078944415b -README.zh.md: 6b429d139a40daa516735b1192af8924e8c9f7cd +README.md: 28e1496a8c941f6524ec4b4dfbfad52d17df5d71 +README.zh.md: c2838bb4cf78d6ac863bac2eba4d2e4df335fa55 diff --git a/packages/examples/agent-spine-demo/README.md b/packages/examples/agent-spine-demo/README.md index 509e4e6d6b..28e1496a8c 100644 --- a/packages/examples/agent-spine-demo/README.md +++ b/packages/examples/agent-spine-demo/README.md @@ -55,11 +55,11 @@ This applies the [Service Definition / Service Provider / Consumer separation](. ```ts import type { Config } from '@deepseek-ai/dsh-agent-spine-demo' -// { agents?, maxParallelToolCalls?, includeHarnessIdentity?, includeRuntimeContext?, persona?, toolOrder?, tools?, dshHome?, sessionTitle?, skills?, workspaceContext, toolBash?, jobs?, toolJobs?, goals?, invariants? } +// { agents?, maxParallelToolCalls?, includeHarnessIdentity?, includeRuntimeContext?, persona?, personaComplete?, toolOrder?, tools?, dshHome?, sessionTitle?, skills?, workspaceContext, toolBash?, jobs?, toolJobs?, goals?, invariants? } // workspaceContext requires { maxBytes } or false; the other owner schemas supply defaults. ``` -The bundle forwards each field to the child that owns it. App packages supply any pre-created agents: headless and JSON-RPC compositions create `main`, while the ACP app creates agents on demand at `session/new`. `includeRuntimeContext: false` is forwarded to `dsh-system-prompt` and suppresses all dynamic context snapshots for fresh sessions without disabling their policy services. Prompt, tool, title, skill, agent-instructions, invariant, goal, and task settings retain the schemas and defaults documented by their owning packages; `jobs.maxConcurrentJobsPerOwner` configures the local provider independently of the model-facing `toolJobs` controls. `pickSpineConfig()` copies only fields owned by this bundle, and conflicting `dshHome` values fail during composition. +The bundle forwards each field to the child that owns it. App packages supply any pre-created agents: headless and JSON-RPC compositions create `main`, while the ACP app creates agents on demand at `session/new`. `includeRuntimeContext: false` suppresses all dynamic context snapshots for fresh sessions without disabling their policy services; `personaComplete: true` makes the deployment persona the sole system-prompt section. Prompt, tool, title, skill, agent-instructions, invariant, goal, and task settings retain the schemas and defaults documented by their owning packages; `jobs.maxConcurrentJobsPerOwner` configures the local provider independently of the model-facing `toolJobs` controls. `pickSpineConfig()` copies only fields owned by this bundle, and conflicting `dshHome` values fail during composition. 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`](../../runtime-diagnostics/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 6b429d139a..c2838bb4cf 100644 --- a/packages/examples/agent-spine-demo/README.zh.md +++ b/packages/examples/agent-spine-demo/README.zh.md @@ -55,11 +55,11 @@ ```ts import type { Config } from '@deepseek-ai/dsh-agent-spine-demo' -// { agents?, maxParallelToolCalls?, includeHarnessIdentity?, includeRuntimeContext?, persona?, toolOrder?, tools?, dshHome?, sessionTitle?, skills?, workspaceContext, toolBash?, jobs?, toolJobs?, goals?, invariants? } +// { agents?, maxParallelToolCalls?, includeHarnessIdentity?, includeRuntimeContext?, persona?, personaComplete?, toolOrder?, tools?, dshHome?, sessionTitle?, skills?, workspaceContext, toolBash?, jobs?, toolJobs?, goals?, invariants? } // workspaceContext requires { maxBytes } or false; the other owner schemas supply defaults. ``` -组合包将每个字段转发给拥有它的子节点。应用包提供预创建的 agent:无头和 JSON-RPC 组合会创建 `main`,ACP 应用则在 `session/new` 按需创建 agent。`includeRuntimeContext: false` 会转发给 `dsh-system-prompt`,为新建会话抑制所有动态上下文快照,但不禁用其策略服务。提示词、工具、标题、skill、工作区上下文、不变式、目标和任务设置沿用其所属包记录的 schema 与默认值;`jobs.maxConcurrentJobsPerOwner` 配置本地 Service Provider,并与面向模型的 `toolJobs` 控制工具相互独立。`pickSpineConfig()` 只复制该组合包拥有的字段,`dshHome` 值冲突会在组合时失败。 +组合包将每个字段转发给拥有它的子节点。应用包提供预创建的 agent:无头和 JSON-RPC 组合会创建 `main`,ACP 应用则在 `session/new` 按需创建 agent。`includeRuntimeContext: false` 会为新建会话抑制所有动态上下文快照,但不禁用其策略服务;`personaComplete: true` 会让部署 persona 成为唯一系统提示词段。提示词、工具、标题、skill、工作区上下文、不变式、目标和任务设置沿用其所属包记录的 schema 与默认值;`jobs.maxConcurrentJobsPerOwner` 配置本地 Service Provider,并与面向模型的 `toolJobs` 控制工具相互独立。`pickSpineConfig()` 只复制该组合包拥有的字段,`dshHome` 值冲突会在组合时失败。 例如,`{ invariants: { enabled: true, package_allowlist: ['^@deepseek-ai/dsh-'], package_blocklist: ['agent-loop$'] } }` 会让包拥有的配套插件保持挂载,但抑制被阻止的拥有者。Blocklist 匹配优先于 allowlist 匹配;正则表达式与生命周期规则见 [`dsh-invariants`](../../runtime-diagnostics/invariants/README.zh.md)。 diff --git a/packages/examples/agent-spine-demo/src/index.ts b/packages/examples/agent-spine-demo/src/index.ts index 87098c38da..a60ebd9e43 100644 --- a/packages/examples/agent-spine-demo/src/index.ts +++ b/packages/examples/agent-spine-demo/src/index.ts @@ -70,9 +70,10 @@ export interface GoalConfig { * Bundle config: each field forwarded verbatim to the child that owns it — * `agents` to the agent loop (an app that pre-creates no agents, like the ACP * bridge, simply omits it), `includeHarnessIdentity`, `includeRuntimeContext`, - * `persona`, and `toolOrder` to the system-prompt plugin (the fixed opener, - * dynamic-context policy, deployment persona, and explicit model-facing tool - * order), the `tools` object to the tool registry (its presentation `mode`), + * `persona`, `personaComplete`, and `toolOrder` to the system-prompt plugin + * (the fixed opener, dynamic-context policy, deployment persona completeness, + * and explicit model-facing tool order), the `tools` object to the tool + * registry (its presentation `mode`), * `dshHome` to bash environment and local skill discovery, `sessionTitle` to * the fallback title service, `skills` to the * skill registry/local provider/tool consumer, `workspaceContext` to the @@ -100,6 +101,8 @@ export interface Config { includeRuntimeContext?: SystemPromptConfig['includeRuntimeContext'] /** The deployment persona (see dsh-system-prompt's `Config`). */ persona?: SystemPromptConfig['persona'] + /** Whether the deployment persona is the complete system prompt. */ + personaComplete?: SystemPromptConfig['personaComplete'] /** The explicit model-facing tool order (see dsh-system-prompt's `Config`). */ toolOrder?: SystemPromptConfig['toolOrder'] /** The tool registry's config — its presentation `mode` (see dsh-tools' `Config`). */ @@ -185,6 +188,7 @@ export function pickSpineConfig(config: Omit): Omit): Omit { includeHarnessIdentity: false, includeRuntimeContext: false, persona: 'You are a helpful software engineer assistant.', + personaComplete: true, workspaceContext: false, skills: { enabled: false }, toolBash: false, @@ -723,6 +724,7 @@ describe('dsh-agent-spine-demo bundle', () => { expect(ctx.tools.schemas()).toEqual([]) ctx.systemPrompt.context({ name: 'policy', order: 0, text: 'hidden policy' }) expect((await ctx.systemPrompt.assemble()).contexts).toEqual([]) + ctx.systemPrompt.section({ name: 'hidden', order: 100, text: 'hidden guidance' }) expect(renderPrompt(await ctx.systemPrompt.assemble())) .toBe('You are a helpful software engineer assistant.') @@ -736,6 +738,7 @@ describe('dsh-agent-spine-demo bundle', () => { includeHarnessIdentity: false, includeRuntimeContext: false, persona: 'You are merged.', + personaComplete: true, toolOrder: ['zulu'], tools: { mode: 'native' as const }, dshHome: '/tmp/dsh-home', @@ -754,6 +757,7 @@ describe('dsh-agent-spine-demo bundle', () => { includeHarnessIdentity: appConfig.includeHarnessIdentity, includeRuntimeContext: appConfig.includeRuntimeContext, persona: appConfig.persona, + personaComplete: appConfig.personaComplete, toolOrder: appConfig.toolOrder, tools: appConfig.tools, dshHome: appConfig.dshHome, diff --git a/packages/experimental/webworker-runtime/README.i18n.yaml b/packages/experimental/webworker-runtime/README.i18n.yaml index 24eb9b84e3..85ccea8cce 100644 --- a/packages/experimental/webworker-runtime/README.i18n.yaml +++ b/packages/experimental/webworker-runtime/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/experimental/webworker-runtime/README.md -README.md: bd671683bd872450b046362c1e7a0cc39da0863e -README.zh.md: 0ae6fbe8f993de7675dea526b5531a8f822807dd +README.md: 5e4079c8a056802bb912061d219762348b948383 +README.zh.md: e805b631cc9d0f4a390dbe5fdfa759e809e60452 diff --git a/packages/experimental/webworker-runtime/README.md b/packages/experimental/webworker-runtime/README.md index bd671683bd..5e4079c8a0 100644 --- a/packages/experimental/webworker-runtime/README.md +++ b/packages/experimental/webworker-runtime/README.md @@ -9,7 +9,7 @@ Three artifacts from one tsdown pipeline: - **`lib/index.js` (assembly library)** — `createWorkerHost`/`startWorkerHost` mount the base image and any ordered data overlays (`storage/`), install the module loader (`module-system/`) and the `process` shim, boot the tree through the image's own `dsh-app-boot`, and hand the tunnel its serving seams. Overlays may replace files only under `home/` and `workspace/`; they cannot replace the base manifest, configuration, or modules. The image layout contract (`image-layout.ts`: virtual root, config/manifest paths, empty directories, the `lowered` wrapper-contract gate) is shared with the packer. Boot patches force the deployment-shaped rows: frontend serving off, JSONL session logs on the plaintext path, preset roots onto the image's `config/agent-presets`. - **`lib/worker.js` (worker bundle)** — the assembly plus this package's Node-compatibility layer as one self-contained ES module. The module proxy table (`module-proxies.ts`) is the only platform fork: `node:*` builtins over VFS/tunnel/browser primitives, structural stubs that fail loud on the console for what a browser cannot do, and native/binary package replacements. `node:module` supplies `createRequire().resolve` and `.resolve.paths()` over the image package root, so unchanged packages can discover manifests without evaluating their modules. VFS mutations drive `node:fs` callback, polling, and promise watchers; open descriptors retain file identity and access mode across rename, replacement, and unlink; `readable-stream` supplies the stream state machine used by file streams and unchanged image packages such as Chokidar and readdirp. AsyncLocalStorage carries sync-stack causality across `await` through the snapshot/restore faces the pack-time lowering injects. The worker holds no compiler: an image the packer did not lower is refused at mount ([note](../../../.agents/notes/implemented/architecture/2026-08-20-webworker-pack-lowering-and-preview.md)). - **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process. -- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. The tunnel exposes fetch-shaped transport, the API client, and `loadBundle` for the shell's boot seam. +- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` performs the actual fetch and execution on first demand. The tunnel also exposes fetch-shaped transport and the API client. Acceptance lives in `apps/web/tests/preview-boot.e2e.ts`, which serves the real built pages and drives the pre-boot chooser plus Worker activation in headless Chromium. The empty selection exercises first-run startup. The `vfs-example` overlay supplies ordinary workspace files and plaintext persistence artifacts for cold Workspace/Session discovery, tool presentation, subagent navigation, and history paging without a model request. The chooser reserves WebFS as a separate user-authorized source; that provider does not read the built-in fixture. diff --git a/packages/experimental/webworker-runtime/README.zh.md b/packages/experimental/webworker-runtime/README.zh.md index 0ae6fbe8f9..e805b631cc 100644 --- a/packages/experimental/webworker-runtime/README.zh.md +++ b/packages/experimental/webworker-runtime/README.zh.md @@ -9,7 +9,7 @@ - **`lib/index.js`(装配库)**——`createWorkerHost`/`startWorkerHost` 挂载基础镜像和按序排列的数据 overlays(`storage/`)、安装模块加载器(`module-system/`)与 `process` shim、经镜像自带的 `dsh-app-boot` 启动插件树,并把服务缝隙交给隧道。Overlay 只能替换 `home/` 与 `workspace/` 下的文件,不能替换基础 manifest、配置或模块。镜像布局契约(`image-layout.ts`:虚拟根、config/manifest 路径、空目录、`lowered` 包装契约门)与 packer 共享。boot patch 强制部署形态行:关前端静态服务、JSONL 会话日志走明文、preset 根指向镜像内 `config/agent-presets`。 - **`lib/worker.js`(worker 束)**——装配库加本包的 Node 兼容层,合成一个自含 ES module。模块代理表(`module-proxies.ts`)是唯一平台叉口:`node:*` 内建走 VFS、隧道和浏览器原语,浏览器做不到的走结构化 stub(调用即在 console 报错并抛出),native/binary 包则替换执行后端。`node:module` 在镜像 package 根之上提供 `createRequire().resolve` 与 `.resolve.paths()`,使未修改的包无需执行目标模块即可发现 manifest。VFS mutation 驱动 `node:fs` 的 callback、polling 和 promise watcher;打开的 descriptor 在 rename、replacement 和 unlink 后仍保留文件身份与访问模式;`readable-stream` 提供文件流以及 Chokidar、readdirp 等未修改镜像包所用的流状态机。AsyncLocalStorage 经 pack 时降低注入的 snapshot/restore 面在 `await` 间携带同步栈因果。worker 不带编译器:packer 未降低的镜像在挂载时被拒([note](../../../.agents/notes/implemented/architecture/2026-08-20-webworker-pack-lowering-and-preview.zh.md))。 - **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。 -- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。隧道暴露 fetch 形传输、API 客户端与壳启动缝隙用的 `loadBundle`。 +- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时完成实际获取与执行。Tunnel 还暴露 fetch 形传输与 API 客户端。 验收在 `apps/web/tests/preview-boot.e2e.ts`:静态服务真实构建页面,在 headless Chromium 里驱动 pre-boot 选择面板与 Worker 激活。空白选择验证首次启动;`vfs-example` overlay 提供普通 workspace 文件与明文 persistence 产物,无需模型请求即可验证 Workspace/Session 冷发现、工具呈现、subagent 导航和历史分页。选择面板为 WebFS 保留独立的用户授权来源;该 provider 不读取内置 fixture。 diff --git a/packages/experimental/webworker-runtime/src/client/apply-injections.ts b/packages/experimental/webworker-runtime/src/client/apply-injections.ts index 163729a6aa..76e094cd60 100644 --- a/packages/experimental/webworker-runtime/src/client/apply-injections.ts +++ b/packages/experimental/webworker-runtime/src/client/apply-injections.ts @@ -34,6 +34,10 @@ export async function applyIndexInjections( case 'script-src': await loadScript(row.src) break + case 'script-preload': + // The worker tunnel has no browser URL to warm without also executing + // the script; loadScript handles the real request when the row arrives. + break case 'style': { const el = document.createElement('style') el.textContent = row.text diff --git a/packages/experimental/webworker-runtime/tests/client/apply-injections.spec.ts b/packages/experimental/webworker-runtime/tests/client/apply-injections.spec.ts new file mode 100644 index 0000000000..60a764e5e0 --- /dev/null +++ b/packages/experimental/webworker-runtime/tests/client/apply-injections.spec.ts @@ -0,0 +1,21 @@ +// @vitest-environment jsdom +import { afterEach, expect, it, vi } from 'vitest' +import { applyIndexInjections } from '../../src/client/apply-injections.ts' + +afterEach(() => { + document.head.innerHTML = '' + document.body.innerHTML = '' +}) + +it('ignores script preload hints and executes script sources through the worker loader', async () => { + const loadScript = vi.fn(async () => {}) + + await applyIndexInjections([ + { kind: 'script-preload', src: '/plugins/preload.js' }, + { kind: 'script-src', placement: 'head', src: '/plugins/execute.js' }, + ], loadScript) + + expect(loadScript).toHaveBeenCalledOnce() + expect(loadScript).toHaveBeenCalledWith('/plugins/execute.js') + expect(document.querySelector('link[rel="preload"]')).toBeNull() +}) diff --git a/packages/experimental/webworker-runtime/tests/compile/transform-corpus.spec.ts b/packages/experimental/webworker-runtime/tests/compile/transform-corpus.spec.ts index 8ed031ebc3..8f1d745ea9 100644 --- a/packages/experimental/webworker-runtime/tests/compile/transform-corpus.spec.ts +++ b/packages/experimental/webworker-runtime/tests/compile/transform-corpus.spec.ts @@ -11,107 +11,23 @@ * exemptions as stale. The gate's own note applies to itself: a gate whose * verdict depends on how it was launched is not a gate. * - * Eight Node-loader processes divide the discovered files, and the union check - * proves that each bundle appears once. The two test-support bundles and the - * ACL/win32-process pair stay in one ordered shard because their pinned loader - * exemptions depend on the same preceding module state as the unsharded - * checker. - * * The corpus is the build output, so this skips on a tree that has none. */ -import { spawn } from 'node:child_process' -import { globSync } from 'node:fs' +import { spawnSync } from 'node:child_process' import { fileURLToPath } from 'node:url' import { expect, test } from 'vitest' const runner = fileURLToPath(new URL('./transform-corpus-check.ts', import.meta.url)) -const repositoryRoot = fileURLToPath(new URL('../../../../../', import.meta.url)) -const corpusShards = 8 -const shardAffinity = new Set([ - // client-runtime needs acp-snapshot to establish Vitest's internal state. - 'packages/test-support/acp-snapshot/lib/index.js', - 'packages/test-support/client-runtime/lib/index.js', - // win32-process observes Koffi's duplicate type names after the ACL bundle. - 'packages/sandbox/sandbox-windows-acl/lib/index.js', - 'packages/subprocess/win32-process/lib/index.js', -]) -interface CorpusResult { - readonly output: string - readonly status: number | null - readonly error?: string -} - -/** @returns Built bundle paths in the same stable order as the checker. */ -function discoverBuiltBundles(): string[] { - return [ - ...globSync('packages/*/*/lib/index.js', { cwd: repositoryRoot }), - ...globSync('vendor/*/lib/index.js', { cwd: repositoryRoot }), - ].map(path => path.replaceAll('\\', '/')).sort() -} - -/** @returns Non-empty shards with every bundle assigned once and loader affinity preserved. */ -function partitionBundles(files: readonly string[], count: number): string[][] { - const partitions = Array.from({ length: count }, () => [] as string[]) - files.forEach((file, index) => { - const assigned = shardAffinity.has(file) ? 0 : index % count - partitions[assigned]?.push(file) - }) - return partitions.filter(partition => partition.length > 0) -} - -/** @returns One isolated Node-loader corpus shard. */ -function runCorpusShard(files: readonly string[]): Promise { - return new Promise((resolveResult) => { - let output = '' - let spawnError: string | undefined - const child = spawn(process.execPath, ['--import', 'tsx/esm', runner, ...files], { - cwd: repositoryRoot, - stdio: ['ignore', 'pipe', 'pipe'], - }) - child.stdout.setEncoding('utf8') - child.stderr.setEncoding('utf8') - child.stdout.on('data', (chunk: string) => { output += chunk }) - child.stderr.on('data', (chunk: string) => { output += chunk }) - child.once('error', (reason) => { spawnError = reason.message }) - child.once('close', (status) => { - resolveResult({ - output, - status, - ...spawnError === undefined ? {} : { error: spawnError }, - }) - }) - }) -} - -test('partitions every bundle once while retaining loader-state affinity', () => { - const files = [ - 'packages/example/first/lib/index.js', - ...shardAffinity, - 'packages/example/last/lib/index.js', - ] - const shards = partitionBundles(files, corpusShards) - - expect(shards.every(shard => shard.length > 0)).toBe(true) - expect(shards.flat().sort()).toEqual([...files].sort()) - expect(shards[0]?.filter(file => shardAffinity.has(file))).toEqual(files.filter(file => shardAffinity.has(file))) -}) - -test('every built bundle transforms to the export shape Node loads', async (context) => { - const files = discoverBuiltBundles() - if (files.length === 0) { +test('every built bundle transforms to the export shape Node loads', (context) => { + const finished = spawnSync(process.execPath, ['--import', 'tsx/esm', runner], { encoding: 'utf8' }) + const output = `${finished.stdout}${finished.stderr}` + if (output.includes('no built bundles found')) { context.skip('the workspace has no build output to sweep') return } - const shards = partitionBundles(files, Math.min(corpusShards, files.length)) - expect(shards.flat().sort()).toEqual(files) - const finished = await Promise.all(shards.map(runCorpusShard)) - const output = finished.map((result, index) => `shard ${String(index + 1)}/${String(shards.length)}:\n${result.output}`).join('\n') // The runner prefixes every finding with '- ', so a failure reads as the // findings themselves rather than as a diff of its whole report. expect(output.split('\n').filter(line => line.startsWith('- ')).join('\n')).toBe('') - for (const result of finished) { - expect(result.error, output).toBeUndefined() - expect(result.status, output).toBe(0) - } + expect(finished.status, output).toBe(0) }, 900_000) diff --git a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-architecture-review/session.jsonl b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-architecture-review/session.jsonl index 291a18ba1e..7fd433c32a 100644 --- a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-architecture-review/session.jsonl +++ b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-architecture-review/session.jsonl @@ -171,7 +171,7 @@ {"type":"session/end-seed","data":{},"seq":169,"time":1787472100000} {"type":"turn/start","data":{"turn":29},"seq":170,"time":1787472100001} {"type":"user/message","data":{"id":"preview-review-user","role":"user","content":[{"type":"text","text":"Review whether the preview fixture is isolated from future WebFS data."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":171,"time":1787472100002} -{"type":"subagent/descriptor","data":{"version":2,"mode":"one-shot","provider":"fork","label":"Review preview architecture"},"seq":172,"time":1787472100003} +{"type":"subagent/descriptor","data":{"version":3,"mode":"one-shot","provider":"fork","label":"Review preview architecture"},"seq":172,"time":1787472100003} {"type":"step/start","data":{"turn":29,"step":1},"seq":173,"time":1787472100004} {"type":"assistant/message","data":{"turn":29,"step":1,"message":{"id":"preview-review-assistant","role":"assistant","content":[{"type":"text","text":"The bundled fixture is static image content; future WebFS state remains user-owned."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}}},"sourceEventSeqs":[],"surfaceOp":"append","seq":174,"time":1787472100005} {"type":"step/end","data":{"turn":29,"step":1},"seq":175,"time":1787472100006} diff --git a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-follow-up-builder/session.jsonl b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-follow-up-builder/session.jsonl index 6353e854c4..03b884adc6 100644 --- a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-follow-up-builder/session.jsonl +++ b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-follow-up-builder/session.jsonl @@ -1,7 +1,7 @@ {"type":"session","version":0,"id":"preview-follow-up-builder","createdAt":1787472200000,"cwd":"/dsh/workspace","parentSession":"preview-showcase","origin":"subagent","delegationDepth":1,"agentPreset":"standard"} {"type":"turn/start","data":{"turn":1},"seq":0,"time":1787472200000} {"type":"user/message","data":{"id":"preview-builder-user","role":"user","content":[{"type":"text","text":"Check that the Preview workspace can support follow-up tasks."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":1,"time":1787472200001} -{"type":"subagent/descriptor","data":{"version":2,"mode":"continuable","provider":"spawn","label":"Continue preview verification"},"seq":2,"time":1787472200002} +{"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Continue preview verification"},"seq":2,"time":1787472200002} {"type":"step/start","data":{"turn":1,"step":1},"seq":3,"time":1787472200003} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"id":"preview-builder-assistant","role":"assistant","content":[{"type":"text","text":"This child is continuable and ready for another verification turn."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}}},"sourceEventSeqs":[],"surfaceOp":"append","seq":4,"time":1787472200004} {"type":"step/end","data":{"turn":1,"step":1},"seq":5,"time":1787472200005} diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index f747d9c0dc..135786879c 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -195,7 +195,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'async recompose(agentCtx: Context, id: string): Promise', - description: 'Re-link one agent to a different preset\'s standing composition.\n\nOnly valid while the agent has produced nothing: swapping tools mid conversation would leave logged tool calls the new composition cannot make. The CALLER owns that check — this method does not read session history.\n\nThe swap is a parent re-link, not an unmount: standing mounts are shared and permanent, so the old composition stays for its other agents and the new one is ensured BEFORE the link moves. An unknown or unusable preset therefore throws with the agent exactly as it was — there is no torn-down state to restore. The re-link runs through the binding this roster kept from the agent\'s mount — dsh-scope\'s only re-link authority. An agent that never composed one has nothing to re-link: the switch is then the agent\'s first bind, exactly a mount.', + description: 'Re-link one agent to a different preset\'s standing composition.\n\nOnly valid while the agent has produced nothing: swapping tools mid conversation would leave logged tool calls the new composition cannot make. The CALLER owns that check — this method does not read session history.\n\nThe swap is a parent re-link, not an unmount: standing mounts are shared and permanent, so the old composition stays for its other agents and the new one is ensured BEFORE the link moves. An unknown or unusable preset therefore throws with the agent exactly as it was — there is no torn-down state to restore. The re-link runs through the binding this roster kept from the agent\'s mount — dsh-scope\'s only re-link authority. An agent that never composed one has nothing to re-link: the switch is then the agent\'s first bind, exactly a mount. A committed re-link emits `tools/change` because changing the parent scope changes the Agent\'s resolved tool set without adding or removing registry entries.', parameters: [{ name: 'agentCtx', description: 'the agent\'s scope context.' }, { name: 'id', description: 'the preset to compose the agent from instead.' }], returns: 'the preset now installed.', throws: ['when the preset is unknown or its composition is unusable.'], @@ -455,10 +455,17 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the verified bytes and normalized attachment reference.', throws: ['the signal reason when aborted, or a storage error when verification fails.'], }, + { + signature: 'imageHostPath(ref: ImageAttachmentRef): string | undefined', + description: 'Locate the provider-owned normalized object in the harness host filesystem.', + parameters: [{ name: 'ref', description: 'durable normalized attachment reference.' }], + returns: 'an absolute host path, or undefined when this backend is not host-file-backed.', + throws: ['an AttachmentError when the durable reference is invalid.'], + }, { signature: 'readImageRequest( ref: ImageAttachmentRef, policy: ImageRequestPolicy, signal?: AbortSignal, ): Promise', description: 'Generate or read one deterministic model-request version from the stored normalized image.', - parameters: [{ name: 'ref', description: 'durable provider-independent normalized attachment reference.' }, { name: 'policy', description: 'exact route pixel and encoded-byte budget.' }, { name: 'signal', description: 'optional cancellation.' }], + parameters: [{ name: 'ref', description: 'durable provider-independent normalized attachment reference.' }, { name: 'policy', description: 'exact route pixel budget and encoded-byte target; a target no ladder quality meets yields the smallest ladder output.' }, { name: 'signal', description: 'optional cancellation.' }], returns: 'request bytes and the cache/upload identity covering every transform input.', }, ], @@ -518,6 +525,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'id', description: 'entry id (package name).' }], returns: 'the path, or undefined for an unknown id.', }, + { + signature: 'artifactBaseline(id: string): ClientArtifactBaseline | undefined', + description: 'Filesystem baseline captured before an entry\'s current bytes were read. HMR compares it with the live files when installing a watch, so a write between startup composition and watch installation cannot disappear into the watcher\'s initial state.', + parameters: [{ name: 'id', description: 'entry id (package name).' }], + returns: 'the path and baseline, or undefined for an unknown id.', + }, { signature: 'rebuilt(id: string): string | undefined', description: 'Re-hash one bundle (the HMR watch\'s registration hook — the only entry point through which bundle content changes reach the graph).', @@ -769,6 +782,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'target', description: 'the resolved target whose process path is required.' }], returns: 'an absolute path in the backend\'s execution world.', }, + { + signature: 'processPathFromHostPath(hostPath: string): string | undefined', + description: 'Map an absolute path from the harness host into this filesystem\'s execution world when both paths identify the same file. The base provider exposes no mapping; host-backed or explicitly shared backends override it.', + parameters: [{ name: 'hostPath', description: 'absolute path in the harness host filesystem.' }], + returns: 'the process path for the same file, or undefined when this execution world cannot read that host file.', + }, { signature: 'abstract fileUrl(target: FsTarget): string', description: 'Return the canonical `file:` URI for a target in this filesystem\'s execution world. Backends own URI encoding because the host platform may differ from the execution platform.', @@ -1899,6 +1918,19 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'subagentModelSelection', + summary: 'Singleton settings owner read by delegation tools when an Agent is published.', + description: 'Singleton settings owner read by delegation tools when an Agent is published.', + methods: [ + { + signature: 'currentEnabled(): boolean', + description: 'Read the preference for the next eligible Agent publication.', + parameters: [], + returns: 'whether that Agent should receive model-selectable delegation.', + }, + ], + }, { key: 'subagents', summary: 'Named provider registry with one-shot runs, durable discovery, and continuable-child operations.', @@ -3117,7 +3149,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'AgentOptions', - declaration: 'export interface AgentOptions {\n provider?: string;\n model?: string;\n maxTokens?: number;\n}', + declaration: 'export interface AgentOptions {\n provider?: string;\n model?: string;\n reasoningEffort?: ReasoningEffortId;\n maxTokens?: number;\n}', }, { name: 'AgentPreset', @@ -3283,6 +3315,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'Branded', declaration: 'export type Branded = string & {\n readonly [BRAND]: B;\n};', }, + { + name: 'ClientArtifactBaseline', + declaration: 'export interface ClientArtifactBaseline {\n readonly path: string;\n readonly mtimeMs: number;\n readonly size: number;\n readonly mapMtimeMs: number | null;\n readonly mapSize: number | null;\n}', + }, { name: 'CodeBindingErrorClass', declaration: 'export interface CodeBindingErrorClass {\n name: string;\n memberNameProperty: string;\n}', @@ -3409,7 +3445,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ContinuableSubagentDescriptorData', - declaration: 'export interface ContinuableSubagentDescriptorData extends SubagentDescriptorBase {\n readonly mode: \'continuable\';\n readonly label: string;\n readonly agentProvider?: string;\n readonly agentModel?: string;\n readonly persona?: string;\n readonly toolFilter?: ToolRestriction;\n}', + declaration: 'export interface ContinuableSubagentDescriptorData extends SubagentDescriptorBase {\n readonly mode: \'continuable\';\n readonly label: string;\n readonly agentProvider?: string;\n readonly agentModel?: string;\n readonly agentReasoningEffort?: ReasoningEffortId;\n readonly persona?: string;\n readonly toolFilter?: ToolRestriction;\n}', }, { name: 'CordisDynamicPackageId', @@ -3745,7 +3781,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'IndexInjection', - declaration: 'export type IndexInjection = {\n kind: \'global\';\n name: string;\n value: unknown;\n} | {\n kind: \'script\';\n placement: IndexInjectionPlacement;\n text: string;\n} | {\n kind: \'script-src\';\n placement: IndexInjectionPlacement;\n src: string;\n} | {\n kind: \'style\';\n text: string;\n} | {\n kind: \'html\';\n placement: IndexInjectionPlacement;\n html: string;\n};', + declaration: 'export type IndexInjection = {\n kind: \'global\';\n name: string;\n value: unknown;\n} | {\n kind: \'script\';\n placement: IndexInjectionPlacement;\n text: string;\n} | {\n kind: \'script-src\';\n placement: IndexInjectionPlacement;\n src: string;\n} | {\n kind: \'script-preload\';\n src: string;\n} | {\n kind: \'style\';\n text: string;\n} | {\n kind: \'html\';\n placement: IndexInjectionPlacement;\n html: string;\n};', }, { name: 'IndexInjectionPlacement', @@ -4921,7 +4957,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SubagentCapabilities', - declaration: 'export interface SubagentCapabilities {\n readonly outputSchema: boolean;\n readonly depthLimit: boolean;\n readonly toolFilter: boolean;\n readonly persona: boolean;\n}', + declaration: 'export interface SubagentCapabilities {\n readonly agentOptions: boolean;\n readonly outputSchema: boolean;\n readonly depthLimit: boolean;\n readonly toolFilter: boolean;\n readonly persona: boolean;\n}', }, { name: 'SubagentDescendantListEntry', @@ -5423,13 +5459,21 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'VerifiedWebhookDelivery', declaration: 'export interface VerifiedWebhookDelivery {\n readonly kind: K;\n readonly source: WebhookSourceId;\n readonly deliveryId: WebhookDeliveryId;\n readonly event: WebhookEventOf;\n readonly receivedAt: number;\n}', }, + { + name: 'WebBootBatch', + declaration: 'export interface WebBootBatch {\n phase: WebBootBatchPhase;\n url: string;\n rev: string;\n entries: string[];\n}', + }, + { + name: 'WebBootBatchPhase', + declaration: 'export type WebBootBatchPhase = \'bootstrap\' | \'application\';', + }, { name: 'WebBootEntry', declaration: 'export interface WebBootEntry {\n id: string;\n url: string;\n rev: string;\n inject?: string[];\n immediately?: boolean;\n external?: string[];\n}', }, { name: 'WebBootGraph', - declaration: 'export interface WebBootGraph {\n rev: string;\n entries: WebBootEntry[];\n}', + declaration: 'export interface WebBootGraph {\n rev: string;\n entries: WebBootEntry[];\n batches: WebBootBatch[];\n}', }, { name: 'WebFetchBody', diff --git a/packages/fs/fs-local/README.i18n.yaml b/packages/fs/fs-local/README.i18n.yaml index 68d3340327..02d7e4b704 100644 --- a/packages/fs/fs-local/README.i18n.yaml +++ b/packages/fs/fs-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/fs/fs-local/README.md -README.md: 4d5c42945b86ccdc8b041d9d7f99a067ab9a37f5 -README.zh.md: 51f417f73294b7497563fece168e5a5d44b73421 +README.md: ae6d2f582abfdbdfcf922899ffe485691167c97e +README.zh.md: 161e4ee9e5b3dbd0f7efc64692e10dc522538034 diff --git a/packages/fs/fs-local/README.md b/packages/fs/fs-local/README.md index 4d5c42945b..ae6d2f582a 100644 --- a/packages/fs/fs-local/README.md +++ b/packages/fs/fs-local/README.md @@ -15,7 +15,7 @@ await ctx.plugin(LocalFileSystem, { cwd: process.cwd() }) ## Behavior - **`resolve(path, opts?)`** — a relative `path` resolves against `opts.cwd` when the caller supplies one (the model-facing tools pass the calling agent's session cwd — see [the per-session cwd Agent Note](../../../.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md)), else `config.cwd` (default `process.cwd()`); an absolute `path` ignores both. `opts.signal` is checked before and after local resolution, while a remote sibling backend may use it to abort its round-trip. The `targetKey` is the file's `realpath`, so two input paths reaching the same file through symlinks share one identity, and writes/edits land on the link target (preserving the link). A not-yet-existing path uses the realpathed parent directory plus basename when the parent exists; only an unresolvable parent falls back to the absolute path. `displayPath` is the absolute (un-resolved) path. -- **Execution-world coordinates** — `processPath` exposes the target's canonical host path, `fileUrl` encodes that path through Node's platform-aware URL conversion, and `contains` uses platform path semantics to test identity or descendant containment without consumers parsing `targetKey`. +- **Execution-world coordinates** — `processPath` exposes the target's canonical host path, `processPathFromHostPath` accepts absolute host paths because this backend shares the host filesystem, `fileUrl` encodes target paths through Node's platform-aware URL conversion, and `contains` uses platform path semantics to test identity or descendant containment without consumers parsing `targetKey`. - **`stat` / `lstat`** — return target metadata or `undefined` when absent. `stat` reports `FsInfo` for an already resolved target (`version` = an opaque token derived from bigint `dev:ino:size:mtimeNs:ctimeNs`, `type` of `file`/`directory`/`other`, byte `size`); path-shaped `lstat` reports `FsPathInfo` without following the final symlink and can therefore return `symlink`. Both check cancellation before and after their asynchronous metadata probe, so an abort that lands in flight reports `FS_ABORTED` rather than stale absence. - **`readText` / `streamText`** — UTF-8 only. `readText` reads the whole file; `streamText` decodes chunks so a huge file need not be held whole in memory and consumers can enforce their own retention bounds. Both reject invalid UTF-8 and NUL-byte binary samples (`FS_NOT_TEXT`) and non-regular targets. The `read` tool (`@deepseek-ai/dsh-tool-fs`) owns line windowing. - **`readBytes`** — raw whole-file bytes with no decoding or binary rejection (the `read_image` tool validates content through the attachment service). The required byte cap short-circuits on the stat size before any content I/O; the subsequent stream reads at most one byte beyond the cap, so a file growing after stat still fails `FS_TOO_LARGE` without unbounded buffering. diff --git a/packages/fs/fs-local/README.zh.md b/packages/fs/fs-local/README.zh.md index 51f417f732..161e4ee9e5 100644 --- a/packages/fs/fs-local/README.zh.md +++ b/packages/fs/fs-local/README.zh.md @@ -15,7 +15,7 @@ await ctx.plugin(LocalFileSystem, { cwd: process.cwd() }) ## 行为 - **`resolve(path, opts?)`**:相对 `path` 在调用方提供 `opts.cwd` 时以该值为基准解析(面向模型的工具会传入调用 agent(智能体)的会话 cwd;见[每会话 cwd Agent Note](../../../.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.zh.md)),否则以 `config.cwd` 为基准(默认 `process.cwd()`);绝对 `path` 会忽略两者。`opts.signal` 会在本地解析前后检查,远程同级后端则可以用它中止往返。`targetKey` 是文件的 `realpath`,因此经符号链接到达同一文件的两个输入路径会共享一个身份,写入/编辑落在链接目标上,同时保留链接。尚不存在的路径在父目录存在时使用 realpath 后的父目录加 basename;只有父目录无法解析时才回退到绝对路径。`displayPath` 是绝对但未经解析的路径。 -- **执行世界坐标**:`processPath` 公开目标的规范化宿主路径,`fileUrl` 通过 Node 的平台感知 URL 转换对该路径编码,`contains` 则使用平台路径语义检查身份相等或后代包含关系,消费方无需解析 `targetKey`。 +- **执行世界坐标**:`processPath` 公开目标的规范化宿主路径。由于该后端共享宿主文件系统,`processPathFromHostPath` 接受绝对宿主路径。`fileUrl` 通过 Node 的平台感知 URL 转换对目标路径编码。`contains` 使用平台路径语义检查身份相等或后代包含关系,消费方无需解析 `targetKey`。 - **`stat` / `lstat`**:返回目标元数据;目标不存在时返回 `undefined`。`stat` 为已解析目标报告 `FsInfo`(`version` 是由 bigint `dev:ino:size:mtimeNs:ctimeNs` 派生的不透明 token,`type` 为 `file`/`directory`/`other`,`size` 以字节计);路径形态的 `lstat` 不跟随最后一个符号链接,报告 `FsPathInfo`,因此可以返回 `symlink`。两者都会在异步元数据探测前后检查取消,因此异步探测进行期间发生的中止会报告 `FS_ABORTED`,而非陈旧的不存在结果。 - **`readText` / `streamText`**:只支持 UTF-8。`readText` 读取整个文件;`streamText` 按分片解码,因此超大文件无需整体保存在内存中,消费方也可以自行限制保留量。两者都会拒绝无效 UTF-8、包含 NUL 字节的二进制样本(`FS_NOT_TEXT`)以及非普通文件目标。`read` 工具(`@deepseek-ai/dsh-tool-fs`)拥有行窗口逻辑。 - **`readBytes`**:按原始字节读取整个文件,不做解码或二进制拒绝(`read_image` 工具通过附件服务校验内容)。必填的字节上限在任何内容 I/O 之前先按 stat 大小短路;随后的流最多多读一个字节,因此 stat 之后增长的文件仍会以 `FS_TOO_LARGE` 失败,不会无界缓冲。 diff --git a/packages/fs/fs-local/src/index.ts b/packages/fs/fs-local/src/index.ts index 661ef236b8..7c50532a0e 100644 --- a/packages/fs/fs-local/src/index.ts +++ b/packages/fs/fs-local/src/index.ts @@ -114,6 +114,10 @@ export class LocalFileSystem extends FileSystem { return String(target.targetKey) } + override processPathFromHostPath(hostPath: string): string | undefined { + return isAbsolute(hostPath) ? resolve(hostPath) : undefined + } + override fileUrl(target: FsTarget): string { return pathToFileURL(this.processPath(target)).href } diff --git a/packages/fs/fs-local/tests/filesystem.spec.ts b/packages/fs/fs-local/tests/filesystem.spec.ts index 1977f438b9..b791b424fb 100644 --- a/packages/fs/fs-local/tests/filesystem.spec.ts +++ b/packages/fs/fs-local/tests/filesystem.spec.ts @@ -59,6 +59,12 @@ describe('registration', () => { await bareFiber.dispose() }) + it('maps only absolute host paths into its process path namespace', () => { + const path = join(dir, 'image.png') + expect(fs.processPathFromHostPath(path)).toBe(path) + expect(fs.processPathFromHostPath('image.png')).toBeUndefined() + }) + it('rejects non-positive, fractional, unsafe, or unallocatable diff-basis limits', async () => { const maxDiffBasisBytes = Math.min( bufferConstants.MAX_LENGTH, diff --git a/packages/fs/fs/README.i18n.yaml b/packages/fs/fs/README.i18n.yaml index 5736cd6c81..c001d6a107 100644 --- a/packages/fs/fs/README.i18n.yaml +++ b/packages/fs/fs/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/fs/fs/README.md -README.md: 7bde7d4d64005a6bdd0f0ac974bf45e5450e4207 -README.zh.md: c4366dc1805938a7020310f4cf627b9072a75cd5 +README.md: b6255a385daf9185ccbfb45e4d1896ad2e8a2c9e +README.zh.md: e932b3144430618e2ec7458491b26d43c517024f diff --git a/packages/fs/fs/README.md b/packages/fs/fs/README.md index 7bde7d4d64..b6255a385d 100644 --- a/packages/fs/fs/README.md +++ b/packages/fs/fs/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The **`FileSystem`** (`ctx.fs`) defines the storage primitives in one execution world — resolve paths, expose canonical process paths and file URIs, test containment, read whole or streaming text, read bounded raw bytes, inspect/list metadata, write atomically, and apply a literal edit — without saying HOW. Both mutations take their version guard **optionally**, so `ctx.fs` on its own is a complete, unconstrained storage seam. This package also owns the `fs/*` policy event vocabulary the tool dispatches and the policy plugin listens for. +The **`FileSystem`** (`ctx.fs`) defines the storage primitives in one execution world — resolve paths, expose canonical process paths and file URIs, map shared host files, test containment, read whole or streaming text, read bounded raw bytes, inspect/list metadata, write atomically, and apply a literal edit — without saying HOW. Both mutations take their version guard **optionally**, so `ctx.fs` on its own is a complete, unconstrained storage seam. This package also owns the `fs/*` policy event vocabulary the tool dispatches and the policy plugin listens for. This package owns the Service Definition and provider contract layer of the four-layer filesystem stack, split so each concern can evolve (and be swapped) independently (see [the capability-seam Agent Note](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md), [the filesystem capability-seam Agent Note](../../../.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.md), [the split-the-filesystem-seam Agent Note](../../../.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.md), and [the file-context event-gate Agent Note](../../../.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.md)): @@ -17,12 +17,13 @@ This package owns the Service Definition and provider contract layer of the four ## Service API (`ctx.fs`) -A backend subclasses `FileSystem` and implements twelve primitives. +A backend subclasses `FileSystem` and exposes thirteen primitives. | Member | Semantics | |---|---| | `resolve(path, opts?)` | Resolve a path into a stable `FsTarget` (opaque `targetKey`, `displayPath`). `opts.cwd` is the base a relative `path` resolves against (a caller supplies its session workspace; absolute paths ignore it; omitted ⇒ the backend default), while `opts.signal` aborts a backend round-trip. Async — a remote backend may need I/O. The same file via different paths must yield the same `targetKey`. | | `processPath(target)` | Return the canonical absolute path that a subprocess in this provider's execution world can open. This is intentionally distinct from opaque `targetKey`. | +| `processPathFromHostPath(hostPath)` | Return this execution world's process path for the same absolute host file when the backend shares it. The base implementation returns `undefined`; host-backed or explicitly mapped backends override it. | | `fileUrl(target)` | Return the canonical `file:` URI in the execution world's platform syntax. The backend, not the host process, owns encoding. | | `contains(parent, child)` | Test canonical identity/descendant containment without exposing or parsing target keys. Both targets come from this provider. | | `stat(target, signal?)` | Return `FsInfo` metadata (`version`, `type`, optional `size`), or `undefined` when the target is absent. Never content. | @@ -61,6 +62,6 @@ No direct invalidation; the named consumer owns any request-prefix changes. ## Known Limitations and Deferred Work - **Text-only mutations by contract** — text reads and both mutations reject binary/non-UTF-8 content with `FS_NOT_TEXT`; `readBytes` is the one raw-byte primitive, and binary-safe mutations remain a deliberate deferral of [the tool-schemas Agent Note](../../../.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.md). -- **Twelve primitives only** — no delete, rename/move, copy, or watch; `listDir` is single-level, with recursion, globbing, pagination, and search out of scope per [the directory-listing Agent Note](../../../.agents/notes/archived/architecture/2026-07-03-filesystem-directory-listing-seam.md). +- **Thirteen primitives only** — no delete, rename/move, copy, or watch; `listDir` is single-level, with recursion, globbing, pagination, and search out of scope per [the directory-listing Agent Note](../../../.agents/notes/archived/architecture/2026-07-03-filesystem-directory-listing-seam.md). - **No IO deadline** — the seam arms no timeout; cancellation is a best-effort optional `AbortSignal` per primitive (the deliberate [fs-family stance](../README.md)). - **Resolve-then-operate costs a remote backend two round-trips per tool call** — folding or caching resolution is left to such a backend. diff --git a/packages/fs/fs/README.zh.md b/packages/fs/fs/README.zh.md index c4366dc180..e932b31444 100644 --- a/packages/fs/fs/README.zh.md +++ b/packages/fs/fs/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -**`FileSystem`**(`ctx.fs`)定义同一个执行世界中的存储原语,包括解析路径、公开规范化进程路径与文件 URI、检查包含关系、完整或流式读取文本、有界读取原始字节、检查/列出元数据、原子写入和应用字面量编辑,但不规定实现方式。两个变更操作都**可选** 接收版本防护,因此 `ctx.fs` 本身就是完整且不受约束的存储 seam。本包还拥有由工具分派、政策插件监听的 `fs/*` 政策事件词汇。 +**`FileSystem`**(`ctx.fs`)定义同一个执行世界中的存储原语,包括解析路径、公开规范化进程路径与文件 URI、映射共享的宿主文件、检查包含关系、完整或流式读取文本、有界读取原始字节、检查或列出元数据、原子写入和应用字面量编辑,但不规定实现方式。两个变更操作都**可选**接收版本防护,因此 `ctx.fs` 本身就是完整且不受约束的存储 seam。本包还拥有由工具分派、政策插件监听的 `fs/*` 政策事件词汇。 本包拥有四层文件系统栈中的 Service Definition 和提供方约定层;该拆分使每个关注点可以独立演进和替换(见[能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md)、[文件系统能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-06-17-filesystem-capability-seam.zh.md)、[拆分文件系统 seam Agent Note](../../../.agents/notes/implemented/simplification/2026-06-26-fsspec-style-fs-seam.zh.md)和[文件上下文事件门禁 Agent Note](../../../.agents/notes/implemented/architecture/2026-06-26-file-context-as-event-gate.zh.md)): @@ -17,12 +17,13 @@ ## 服务 API(`ctx.fs`) -后端继承 `FileSystem` 并实现十二个原语。 +后端继承 `FileSystem` 并公开十三个原语。 | 成员 | 语义 | |---|---| | `resolve(path, opts?)` | 把路径解析为稳定的 `FsTarget`(不透明 `targetKey`、`displayPath`)。`opts.cwd` 是相对 `path` 解析所依据的基准(调用方提供其会话工作区;绝对路径忽略该值;省略时使用后端默认值),`opts.signal` 则中止后端往返。该方法是异步的,因为远程后端可能需要 I/O。经不同路径到达的同一文件必须产生相同 `targetKey`。 | | `processPath(target)` | 返回该提供方执行世界中的子进程可以打开的规范化绝对路径。该路径有意与不透明的 `targetKey` 分离。 | +| `processPathFromHostPath(hostPath)` | 当后端共享同一个宿主文件时,返回该文件在当前执行世界中的进程路径。基类返回 `undefined`,宿主后端或显式映射宿主文件的后端负责覆盖。 | | `fileUrl(target)` | 返回采用执行世界平台语法的规范化 `file:` URI。编码由后端而非宿主进程负责。 | | `contains(parent, child)` | 在不公开或解析目标 key 的情况下,检查规范化身份相等或后代包含关系。两个目标都来自该提供方。 | | `stat(target, signal?)` | 返回 `FsInfo` 元数据(`version`、`type`、可选 `size`);目标不存在时返回 `undefined`。绝不返回内容。 | @@ -61,6 +62,6 @@ ## 已知限制与延期工作 - **变更操作约定只支持文本**:文本读取和两个变更操作都以 `FS_NOT_TEXT` 拒绝二进制/非 UTF-8 内容;`readBytes` 是唯一的原始字节原语,二进制安全的变更操作仍是[工具 schema Agent Note](../../../.agents/notes/implemented/feature/2026-06-17-filesystem-tool-schemas.zh.md)有意延期的工作。 -- **只有十二个原语**:没有删除、重命名/移动、复制或监视;`listDir` 只支持一层,递归、glob、分页和搜索不在范围内,见[目录列出 Agent Note](../../../.agents/notes/archived/architecture/2026-07-03-filesystem-directory-listing-seam.md)。 +- **只有十三个原语**:没有删除、重命名或移动、复制或监视;`listDir` 只支持一层,递归、glob、分页和搜索不在范围内,见[目录列出 Agent Note](../../../.agents/notes/archived/architecture/2026-07-03-filesystem-directory-listing-seam.md)。 - **没有 I/O deadline**:该 seam 不启动超时;取消只是每个原语上尽力而为的可选 `AbortSignal`(见有意采用的 [fs 能力族立场](../README.zh.md))。 - **先解析后操作使远程后端每次工具调用需要两次往返**:折叠或缓存解析由这种后端自行决定。 diff --git a/packages/fs/fs/src/index.ts b/packages/fs/fs/src/index.ts index 8ecd03c714..e32890d732 100644 --- a/packages/fs/fs/src/index.ts +++ b/packages/fs/fs/src/index.ts @@ -125,6 +125,19 @@ export abstract class FileSystem extends Service { */ abstract processPath(target: FsTarget): string + /** + * Map an absolute path from the harness host into this filesystem's + * execution world when both paths identify the same file. The base provider + * exposes no mapping; host-backed or explicitly shared backends override it. + * @param hostPath - absolute path in the harness host filesystem. + * @returns the process path for the same file, or undefined when this + * execution world cannot read that host file. + */ + processPathFromHostPath(hostPath: string): string | undefined { + void hostPath + return undefined + } + /** * Return the canonical `file:` URI for a target in this filesystem's * execution world. Backends own URI encoding because the host platform may diff --git a/packages/fs/fs/tests/service.spec.ts b/packages/fs/fs/tests/service.spec.ts index 121901dc95..6fbe1268af 100644 --- a/packages/fs/fs/tests/service.spec.ts +++ b/packages/fs/fs/tests/service.spec.ts @@ -88,6 +88,7 @@ describe('FileSystem provider seam', () => { await ctx.plugin(FakeFileSystem) const fs = ctx.fs as FakeFileSystem expect(fs.sandboxMode).toBeUndefined() + expect(fs.processPathFromHostPath('/host/file')).toBeUndefined() fs.files.set('a.txt', 'hi') const target = await fs.resolve('a.txt') expect((await fs.stat(target))?.type).toBe('file') diff --git a/packages/fs/tool-fs-search/src/search-core.ts b/packages/fs/tool-fs-search/src/search-core.ts index 5ac5521033..60ea042d4f 100644 --- a/packages/fs/tool-fs-search/src/search-core.ts +++ b/packages/fs/tool-fs-search/src/search-core.ts @@ -20,7 +20,7 @@ */ import { existsSync } from 'node:fs' -import { isAbsolute, relative, sep } from 'node:path' +import { isAbsolute, join, parse, relative, sep } from 'node:path' import type { Context } from '@deepseek-ai/cordis' import { HarnessError } from '@deepseek-ai/dsh-llm' import { ItemRetainer, TextRetainer } from '@deepseek-ai/dsh-output-retention' @@ -170,7 +170,10 @@ let rgPathPromise: Promise | undefined */ export function resolveRgPath(): Promise { rgPathPromise ??= Promise.resolve().then(async () => { - const executableSidecar = `${process.execPath}-rg` + const executable = parse(process.execPath) + const executableSidecar = process.platform === 'win32' + ? join(executable.dir, `${executable.name}-rg.exe`) + : `${process.execPath}-rg` if ('pkg' in process && existsSync(executableSidecar)) return executableSidecar return (await import('@vscode/ripgrep')).rgPath }) diff --git a/packages/fs/tool-fs-search/tests/rg-sidecar.spec.ts b/packages/fs/tool-fs-search/tests/rg-sidecar.spec.ts index 53c7a01aea..d3a6b5e188 100644 --- a/packages/fs/tool-fs-search/tests/rg-sidecar.spec.ts +++ b/packages/fs/tool-fs-search/tests/rg-sidecar.spec.ts @@ -1,9 +1,12 @@ +import { join, parse } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { dependencyRgPath, existsSync } = vi.hoisted(() => ({ dependencyRgPath: '/node_modules/@vscode/ripgrep/bin/rg', existsSync: vi.fn(), })) +const originalPlatform = process.platform +const originalExecPath = process.execPath vi.mock('node:fs', async (importOriginal) => { const actual = await importOriginal() @@ -16,17 +19,35 @@ beforeEach(() => { vi.resetModules() existsSync.mockReset() Reflect.deleteProperty(process, 'pkg') + Reflect.defineProperty(process, 'platform', { configurable: true, enumerable: true, value: originalPlatform }) + process.execPath = originalExecPath }) afterEach(() => { Reflect.deleteProperty(process, 'pkg') + Reflect.defineProperty(process, 'platform', { configurable: true, enumerable: true, value: originalPlatform }) + process.execPath = originalExecPath }) describe('ripgrep resolution', () => { it('uses the native sidecar beside the current executable', async () => { Reflect.defineProperty(process, 'pkg', { configurable: true, value: {} }) + Reflect.defineProperty(process, 'platform', { configurable: true, enumerable: true, value: 'linux' }) + process.execPath = '/runtime/dsh' existsSync.mockReturnValue(true) - const sidecar = `${process.execPath}-rg` + const sidecar = '/runtime/dsh-rg' + const { resolveRgPath } = await import('@deepseek-ai/dsh-tool-fs-search') + + await expect(resolveRgPath()).resolves.toBe(sidecar) + expect(existsSync).toHaveBeenCalledWith(sidecar) + }) + + it('uses a conventional executable name for the Windows ripgrep sidecar', async () => { + Reflect.defineProperty(process, 'pkg', { configurable: true, value: {} }) + Reflect.defineProperty(process, 'platform', { configurable: true, enumerable: true, value: 'win32' }) + process.execPath = 'C:\\runtime\\deepseek-harness-sdk-runtime-win-x64.exe' + existsSync.mockReturnValue(true) + const sidecar = 'C:\\runtime\\deepseek-harness-sdk-runtime-win-x64-rg.exe' const { resolveRgPath } = await import('@deepseek-ai/dsh-tool-fs-search') await expect(resolveRgPath()).resolves.toBe(sidecar) @@ -47,6 +68,10 @@ describe('ripgrep resolution', () => { const { resolveRgPath } = await import('@deepseek-ai/dsh-tool-fs-search') await expect(resolveRgPath()).resolves.toBe(dependencyRgPath) - expect(existsSync).toHaveBeenCalledWith(`${process.execPath}-rg`) + const executable = parse(process.execPath) + const sidecar = process.platform === 'win32' + ? join(executable.dir, `${executable.name}-rg.exe`) + : `${process.execPath}-rg` + expect(existsSync).toHaveBeenCalledWith(sidecar) }) }) diff --git a/packages/host/webserver/README.i18n.yaml b/packages/host/webserver/README.i18n.yaml index aae84858b2..8a6b93bb12 100644 --- a/packages/host/webserver/README.i18n.yaml +++ b/packages/host/webserver/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/webserver/README.md -README.md: 0dc8f197f923c2dc4cb2d72ccb5b3a31f5384503 -README.zh.md: d19e4a6be1df0c464d7ac61726e6bfb45a92c8a1 +README.md: c6abc503222fc8bf60d4b6c940eeb1f7910cc9aa +README.zh.md: 430488869c98a86ff669e12acfaee86bae7aa8a3 diff --git a/packages/host/webserver/README.md b/packages/host/webserver/README.md index 0dc8f197f9..c6abc50322 100644 --- a/packages/host/webserver/README.md +++ b/packages/host/webserver/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Web HTTP and upgrade-route registration plugin (default-exported `WebServer`, config `{host, port}`): a `node:http` server that listens on activation and provides `ctx.webServer`. `register(route)` adds a named `exact`/`prefix` HTTP route; `registerUpgrade(route)` adds an upgrade route for an exact pathname. A duplicate path within either table throws because route patterns are a composition-level contract and a collision is a misconfiguration; both methods return a disposer that removes the registration. `registerFallback(handler)` registers the one handler for requests that match no named route. A second registration throws; the SPA dist server [`dsh-host-frontend-static`](../frontend-static/README.md) is the shipped owner, and the server returns 404 while none is registered. Index startup inputs are structured rows: `collectIndexInjections()` gathers a fresh `IndexInjection` table over one `webserver/index-inject` emit per call, and `renderIndex(html)` renders the rows into an index.html body before applying the raw `tapIndex(transform)` transforms in registration order (`applyIndexTaps(html)`, the escape hatch for markup no row expresses); the fallback handler calls `renderIndex` on every index response, and a static deployment ships the same rows over its boot payload, rendering with the exported `renderIndexInjections`. `port` reads the listening port (the OS-assigned value when `port` is 0), and `host` reads the configured bind host (composition-time facts other plugins adapt to, e.g. the directory-picker chooser). HTTP match order is fixed: exact over the whole table, then longest prefix, then the fallback handler. Upgrades match exactly and unmatched connections are closed; registration order carries no request-facing semantics. +Web HTTP and upgrade-route registration plugin (default-exported `WebServer`, config `{host, port}`): a `node:http` server that listens on activation and provides `ctx.webServer`. `register(route)` adds a named `exact`/`prefix` HTTP route; `registerUpgrade(route)` adds an upgrade route for an exact pathname. A duplicate path within either table throws because route patterns are a composition-level contract and a collision is a misconfiguration; both methods return a disposer that removes the registration. `registerFallback(handler)` registers the one handler for requests that match no named route. A second registration throws; the SPA dist server [`dsh-host-frontend-static`](../frontend-static/README.md) is the shipped owner, and the server returns 404 while none is registered. Index startup inputs are structured rows: `collectIndexInjections()` gathers a fresh `IndexInjection` table over one `webserver/index-inject` emit per call, and `renderIndex(html)` renders the rows into an index.html body before applying the raw `tapIndex(transform)` transforms in registration order (`applyIndexTaps(html)`, the escape hatch for markup no row expresses); `script-preload` rows render advisory classic-script preload links. The fallback handler calls `renderIndex` on every index response, and a static deployment ships the same rows over its boot payload. `port` reads the listening port (the OS-assigned value when `port` is 0), and `host` reads the configured bind host (composition-time facts other plugins adapt to, e.g. the directory-picker chooser). HTTP match order is fixed: exact over the whole table, then longest prefix, then the fallback handler. Upgrades match exactly and unmatched connections are closed; registration order carries no request-facing semantics. The package knows no harness concepts and serves no files: the `/api` HTTP bridge and downlink WebSockets are routes owned by the connection plugin, plugin bundles and the HMR event stream are routes owned by the modules/hmr plugins, and dist serving belongs to the fallback owner. The upgrade handler owns the protocol handshake and connection contents; the webserver only delivers the raw socket and request. `host` accepts only `127.0.0.1` (default posture) and `0.0.0.0` (deliberate network exposure). This server serves browsers only; Electron loads dist over `file://` and carries fetch over an IPC bridge. This package never prints; the URL line belongs to the shell. diff --git a/packages/host/webserver/README.zh.md b/packages/host/webserver/README.zh.md index d19e4a6be1..430488869c 100644 --- a/packages/host/webserver/README.zh.md +++ b/packages/host/webserver/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -Web HTTP 与 upgrade route 注册插件(默认导出 `WebServer`,配置为 `{host, port}`):一个在激活时开始监听的 `node:http` 服务器,提供 `ctx.webServer`。`register(route)` 添加具名的 `exact`/`prefix` HTTP route;`registerUpgrade(route)` 添加精确 pathname 的 upgrade route;同一张表内的重复路径会抛错,因为 route 模式是组合层约定,冲突即配置错误;两者返回的 disposer 都会移除注册。`registerFallback(handler)` 注册一个 handler,处理所有未被具名 route 命中的请求。第二次注册会抛错;随附的 SPA dist 服务器 [`dsh-host-frontend-static`](../frontend-static/README.zh.md) 是该 handler 的所有者,没有注册 handler 时服务器返回 404。index 的启动输入是结构化行:`collectIndexInjections()` 每次调用经一次 `webserver/index-inject` emit 现收一张全新的 `IndexInjection` 表,`renderIndex(html)` 先把行渲染进 index.html 响应体,再按注册顺序应用原始的 `tapIndex(transform)` 转换(`applyIndexTaps(html)`,行无法表达的标记的逃生口);fallback handler 在每次 index 响应时调用 `renderIndex`,静态部署则把同一批行经 boot 载荷下发,用导出的 `renderIndexInjections` 渲染。`port` 读取正在监听的端口(当 `port` 为 0 时读取 OS 分配的值),`host` 读取配置的绑定宿主(这些是其他插件据以自适应的组合期事实,例如 directory-picker 选择器)。HTTP 匹配顺序固定不变:先在整张表中匹配精确 route,再匹配最长前缀,最后交给 fallback handler。upgrade 只做精确匹配,未命中连接直接关闭;注册顺序不影响请求处理。 +Web HTTP 与 upgrade route 注册插件(默认导出 `WebServer`,配置为 `{host, port}`):一个在激活时开始监听的 `node:http` 服务器,提供 `ctx.webServer`。`register(route)` 添加具名的 `exact`/`prefix` HTTP route;`registerUpgrade(route)` 添加精确 pathname 的 upgrade route;同一张表内的重复路径会抛错,因为 route 模式是组合层约定,冲突即配置错误;两者返回的 disposer 都会移除注册。`registerFallback(handler)` 注册一个 handler,处理所有未被具名 route 命中的请求。第二次注册会抛错;随附的 SPA dist 服务器 [`dsh-host-frontend-static`](../frontend-static/README.zh.md) 是该 handler 的所有者,没有注册 handler 时服务器返回 404。index 的启动输入是结构化行:`collectIndexInjections()` 每次调用经一次 `webserver/index-inject` emit 现收一张全新的 `IndexInjection` 表,`renderIndex(html)` 先把行渲染进 index.html 响应体,再按注册顺序应用原始的 `tapIndex(transform)` 转换(`applyIndexTaps(html)`,行无法表达的标记的逃生口);`script-preload` 行渲染为 classic script 的提示性预加载链接。fallback handler 在每次 index 响应时调用 `renderIndex`,静态部署则把同一批行经 boot 载荷下发。`port` 读取正在监听的端口(当 `port` 为 0 时读取 OS 分配的值),`host` 读取配置的绑定宿主(这些是其他插件据以自适应的组合期事实,例如 directory-picker 选择器)。HTTP 匹配顺序固定不变:先在整张表中匹配精确 route,再匹配最长前缀,最后交给 fallback handler。upgrade 只做精确匹配,未命中连接直接关闭;注册顺序不影响请求处理。 该包不了解任何 harness 概念,也不提供任何文件服务:`/api` HTTP 桥接与下行 WebSocket 是 connection 插件的 route,插件 bundle 与 HMR(热模块替换)事件流是 modules/hmr 插件的 route,dist 服务则属于 fallback 持有者。upgrade handler 拥有协议握手与连接内容;webserver 只交付原始 socket 与 request。`host` 只接受 `127.0.0.1`(默认安全姿态)和 `0.0.0.0`(有意向网络开放)。该服务器只服务浏览器;Electron 通过 `file://` 加载 dist,并经 IPC 桥接承载 fetch。该包从不打印内容;URL 行属于 shell。 diff --git a/packages/host/webserver/src/injections.ts b/packages/host/webserver/src/injections.ts index 7a61ae0510..5b431918f5 100644 --- a/packages/host/webserver/src/injections.ts +++ b/packages/host/webserver/src/injections.ts @@ -23,6 +23,8 @@ export type IndexInjection = * loader resolves worker-only URLs such as `/plugins/...`). */ | { kind: 'script-src'; placement: IndexInjectionPlacement; src: string } + /** Advisory preload for an external classic script; static workers may ignore it. */ + | { kind: 'script-preload'; src: string } /** A `` } case 'html': diff --git a/packages/host/webserver/tests/webserver.spec.ts b/packages/host/webserver/tests/webserver.spec.ts index e8fa315ecc..198716d778 100644 --- a/packages/host/webserver/tests/webserver.spec.ts +++ b/packages/host/webserver/tests/webserver.spec.ts @@ -208,6 +208,7 @@ describe('real Loader composition', () => { table.push( { kind: 'script', placement: 'head', text: 'window.__Q__=1' }, { kind: 'script-src', placement: 'head', src: '/plugins/a.js?rev="1"&x=' }, + { kind: 'script-preload', src: '/plugins/b.js?rev="2"&x=' }, { kind: 'global', name: '__DSH_BOOT__', value: { rev: '' } }, { kind: 'style', text: 'body{margin:0}' }, { kind: 'html', placement: 'head', html: '' }, @@ -222,6 +223,7 @@ describe('real Loader composition', () => { '', '', '', + '', 'globalThis["__DSH_BOOT__"] = {"rev":"\\u003c/script>\\u003cb>"}', '', '', diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 8076a692e6..57ecda0a84 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/llm/llm-deepseek/README.md -README.md: 7d50a8e99863637a06abf49d26a6eeb419cf1bbd -README.zh.md: c1571149529a2d4e54d67b10f63b60bb2aa1abfd +README.md: 7433bb75104506ec2409c659f3d30058abc6f9a4 +README.zh.md: 7dcdfeac17b0bfca70a293760061182292edb531 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 7d50a8e998..7433bb7510 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -50,11 +50,11 @@ The package root exposes the Cordis plugin contract and `DeepSeekAdapter`; wire contextWindow: 512000 ``` -The plugin registers the single provider route `deepseek-official` together with its resolved `retryPolicy`; omission resolves to normal mode with five retries. A request selects it with `provider: deepseek-official`; its `model` is passed through as the wire `model` string, so changing DeepSeek models does not require lifecycle-time registration. Omitting `models` advertises `deepseek-v4-flash`, `deepseek-v4-pro`, and the image-capable `deepseek-v4-flash-vision-exp`, each with a 1,000,000-token context window; an explicit list replaces those defaults, while `models: []` advertises none. Catalog entries are exposed through `ctx.llm.listModels('deepseek-official')` for clients such as ACP editors and the Web selector, but remain advisory: unlisted model ids still pass through unchanged as text-only routes. An omitted entry name defaults to its id, and omitted `inputModalities` means `text` only. +The plugin registers the single provider route `deepseek-official` together with its resolved `retryPolicy`; omission resolves to normal mode with five retries. A request selects it with `provider: deepseek-official`; its `model` is passed through as the wire `model` string, so changing DeepSeek models does not require lifecycle-time registration. Omitting `models` advertises `deepseek-v4-flash` as the fast, economical choice for focused work, `deepseek-v4-pro` as the stronger, higher-cost choice for complex or quality-critical work, and the image-capable `deepseek-v4-flash-vision-exp`; each has a 1,000,000-token context window. An explicit list replaces those defaults, while `models: []` advertises none. Catalog entries are exposed through `ctx.llm.listModels('deepseek-official')` for clients such as ACP editors, the Web selector, and model discovery tools, but remain advisory: unlisted model ids still pass through unchanged as text-only routes. An omitted entry name defaults to its id, and omitted `inputModalities` means `text` only. -An image-capable catalog entry declares `inputModalities: [text, image]` and may set `imagePixelBudget`, `imageMaxBytes`, or `imageDetail: low`. The ordinary default is 640,000 total pixels and 1MiB encoded bytes; low detail defaults to 512 by 512 total pixels. The attachment store scales by `min(1, sqrt(pixelBudget / (width * height)))` and rounds inward to keep the pixel count at or below the hard cap, so a 2048 by 1024 normalized attachment becomes about 1130 by 565 instead of a forced square. Request encoders run lazily: low-color images try PNG (palette only without alpha) then WebP 85 and 80, other alpha images try WebP 85 then 80, and other opaque images try JPEG 85 then 80; dimensions shrink only when both quality attempts exceed 1MiB. Concurrent generation of one `variantId` shares one transform. A caller can cancel its own wait without interrupting other waiters; the transform stops when no waiter remains. The adapter normally uploads the exact derived request bytes through `POST /files` and sends `{type: "file", file_id}` blocks. A failed or timed-out file-id resolution rebuilds the whole chat request with those same request versions as base64 data URLs; one request never mixes file ids and inline images. Every retained image is preceded by stable text naming the complete attachment id and actual request dimensions. User, tool-result, agent-loop, compaction, and direct `ctx.llm.stream` requests all use this projection. Text-only routes receive stable attachment placeholders while durable history keeps its image references. +An image-capable catalog entry declares `inputModalities: [text, image]` and may set `imagePixelBudget` to an exact positive integer or `low`; omission uses 640,000 total pixels, while `low` selects 512 by 512 total pixels. `imageMaxBytes` defaults to 1MiB. The attachment store scales by `min(1, sqrt(pixelBudget / (width * height)))` and rounds inward to keep the pixel count at or below the hard cap, so a 2048 by 1024 normalized attachment becomes about 1130 by 565 instead of a forced square. Request encoders run lazily: alpha images try WebP (effort 0) at 85, 75, then 60, and opaque images try JPEG at those qualities; when every quality exceeds 1MiB the smallest output is used. Concurrent generation of one `variantId` shares one transform. A caller can cancel its own wait without interrupting other waiters; the transform stops when no waiter remains. The adapter normally uploads the exact derived request bytes through `POST /files` and sends `{type: "file", file_id}` blocks. A failed or timed-out file-id resolution rebuilds the whole chat request with those same request versions as base64 data URLs; one request never mixes file ids and inline images. Every retained image is preceded by text naming the complete attachment id and actual request dimensions. When the attachment provider exposes a host object and the current filesystem maps it into the tool execution world, the text also includes that read-only path and the matching extension for a writable copy. This access is resolved independently from the deterministic request version and its `variantId`. The descriptor states that the preview and normalized image may differ from the upload. User, tool-result, agent-loop, compaction, and direct `ctx.llm.stream` requests all use this projection. Text-only routes receive stable attachment placeholders while durable history keeps its image references. -`maxRequestFilesBytes` and `maxImagesPerRequest` bound the retained request versions at 128MiB and 600 images by default. The byte and count quanta must not exceed their corresponding bounds. Before attachment reads, the adapter uses each route's request-version byte cap as a conservative upper bound and removes the oldest over-budget prefix; only retained normalized attachments are read and transformed. Exact derived lengths are checked again without restoring omitted images. When the byte bound is crossed, the oldest prefix advances past the next 64MiB boundary; 129 one-megabyte images remove the oldest 65 and retain 64MiB, and that prefix stays unchanged until durable history exceeds 192MiB. Count overflow advances independently in `imageOffloadCountQuantum` steps. Removed images become the fixed model-visible placeholder `[image omitted to keep the request within its image limit; older images are omitted first. If this image is still needed, read its file again when a path is available; otherwise ask the user to attach it again.]`. This high-watermark projection avoids changing an old request prefix after every new image. +`maxRequestFilesBytes` and `maxImagesPerRequest` bound the retained request versions at 128MiB and 600 images by default. The byte and count quanta must not exceed their corresponding bounds. Before attachment reads, the adapter uses each route's request-version byte cap as a conservative upper bound and removes the oldest over-budget prefix; only retained normalized attachments are read and transformed. Exact derived lengths are checked again without restoring omitted images. When the byte bound is crossed, the oldest prefix advances past the next 64MiB boundary; 129 one-megabyte images remove the oldest 65 and retain 64MiB, and that prefix stays unchanged until durable history exceeds 192MiB. Count overflow advances independently in `imageOffloadCountQuantum` steps. Each removed image becomes its own model-visible placeholder with its display name or attachment id and, when available, normalized dimensions, media type, and current read-only local path. This high-watermark projection avoids changing an old request prefix after every new image. Inline fallback has an independent base64 budget. `maxInlineRequestImageBytes` defaults to 20MiB and `inlineImageOffloadByteQuantum` to 10MiB, so a history of 21 one-megabyte base64 payloads removes the oldest 11 and retains 10MiB. The calculation uses base64-expanded lengths. The prepared request versions are reused byte-for-byte; fallback does not decode or compress an image again. Successful mappings created before a later image fails remain indexed for future requests. @@ -66,7 +66,7 @@ Concurrent resolution of one scoped `variantId` shares one Files upload with wai `maxTokens` is the adapter-configured output cap for conversation requests and defaults to 256,000. A catalog entry may carry its own `maxTokens`, which wins for that model; an entry without one, and any unlisted pass-through id, resolve to the profile value, so adding a per-model cap changes one model rather than the route. Exact-model resolution exposes the winner as `defaultMaxTokens`; `LlmRuntime` materializes that value into `GenerateOptions.maxTokens` before the agent loop writes `request/header`, so the wire request remains reconstructable. An explicit request or `AgentOptions.maxTokens` value wins and is serialized as `max_tokens`. The adapter does not clamp this request budget against `contextWindow`; deployments with a smaller context or provider output limit must configure a compatible `maxTokens`. -The same exact-model result exposes ordered `off`, `low`, `high`, and `max` efforts under `reasoning` for every pass-through model when deployment policy permits thinking. `reasoningEffort` selects the deployment default and falls back to `high` when omitted. `agent/request` can replace it on each conversation step; the resolved value is logged in `request/header`. `low`, `high`, and `max` enable thinking and serialize as the same official top-level `reasoning_effort` value; adapter-owned `off` instead serializes `thinking.type: disabled` and omits `reasoning_effort`. An unsupported value fails with `UNSUPPORTED_REASONING_EFFORT` before network I/O. +The same exact-model result exposes ordered `off`, `low`, `high`, and `max` efforts with selection guidance under `reasoning` for every pass-through model when deployment policy permits thinking. `reasoningEffort` selects the advertised default and falls back to `high` when omitted. `agent/request` can replace it on each conversation step; the resolved value is logged in `request/header`. `low`, `high`, and `max` enable thinking and serialize as the same official top-level `reasoning_effort` value; adapter-owned `off` instead serializes `thinking.type: disabled` and omits `reasoning_effort`. An unsupported value fails with `UNSUPPORTED_REASONING_EFFORT` before network I/O. `thinking: disabled` is a deployment lock that publishes only `off` with `off` as its default. Omitting `reasoningEffort` or configuring it as `off` is valid; configuring `low`, `high`, or `max` fails plugin loading, and a direct per-request attempt to enable thinking fails before network I/O. A request with `GenerateOptions.purpose: 'session-title'` also forces thinking disabled and omits the already-resolved effort, reserving its bounded output for visible title text without changing conversation or compaction defaults. @@ -115,7 +115,7 @@ Non-2xx responses throw `LlmError` with stable codes: `AUTH` (401/403), `QUOTA` #### What the model sees -The selected DeepSeek model receives the harness system prompt, message history, tool schemas, stop sequences, and call config without adapter-authored prompt prose. Provider-specific request extension fields remain outside that model input. The vision model normally receives retained user and tool-result images as Files API references beside stable attachment handles and request-image dimensions; a Files resolution failure sends all retained images as inline data URLs instead. An over-budget older image is represented by the documented placeholder. Reasoning content from a prior assistant turn is passed back verbatim, whether or not that turn called a tool. +The selected DeepSeek model receives the harness system prompt, message history, tool schemas, stop sequences, and call config without adapter-authored prompt prose. Provider-specific request extension fields remain outside that model input. The vision model normally receives retained user and tool-result images as Files API references beside attachment handles and request-preview dimensions. It also receives a normalized-object path when the current execution filesystem maps the attachment provider's host object; a Files resolution failure sends all retained images as inline data URLs instead. The descriptor tells the model that this read-only local copy may be resized or re-encoded and must not be used to infer upload properties. An over-budget older image keeps the access currently resolved for that request in its per-image placeholder. Reasoning content from a prior assistant turn is passed back verbatim, whether or not that turn called a tool. #### Token effect @@ -123,7 +123,7 @@ Provider tokenization governs exact text and image-token input. Reasoning passba #### KV Cache effect -An unchanged assembled prefix, including deterministically encoded retained images and placeholders, is eligible for DeepSeek cache reuse, which this adapter reports in usage. A model-route change or any upstream prompt, schema, prefix, history, or image-budget change may prevent reuse from the first changed token; reasoning passback appends on every reasoned turn. +An unchanged assembled prefix is eligible for DeepSeek cache reuse, which this adapter reports in usage. Deterministic request-image bytes do not make the complete prefix immutable: a changed execution-world path rewrites historical descriptor text even without offload, a refreshed upload can replace a `file_id`, and Files-to-base64 fallback changes the image representation. Any of these may prevent reuse from the first affected image. Model-route, prompt, schema, history, and image-budget changes have the same suffix effect; reasoning passback appends on every reasoned turn. ### DeepSeek response diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index c157114952..7dcdfeac17 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -50,11 +50,11 @@ harness LLM(大语言模型)seam 的 DeepSeek chat-completions 适配器: contextWindow: 512000 ``` -该插件注册唯一提供方路由 `deepseek-official`,并一同注册解析后的 `retryPolicy`;省略时会解析为 normal 模式并重试五次。请求使用 `provider: deepseek-official` 选择该路由;其 `model` 会作为协议 `model` 字符串原样传递,因此更改 DeepSeek 模型不需要生命周期时注册。省略 `models` 会公布 `deepseek-v4-flash`、`deepseek-v4-pro` 与支持图片输入的 `deepseek-v4-flash-vision-exp`,三者的上下文窗口均为 1,000,000 token;显式列表会替换这些默认值,`models: []` 则不公布任何模型。Catalog 配置项通过 `ctx.llm.listModels('deepseek-official')` 公开给 ACP(Agent Client Protocol)编辑器和 Web 选择器等客户端,但仍只提供建议:未列出模型 id 仍原样传递,并按纯文本路由处理。省略配置项 name 默认为其 id,省略 `inputModalities` 则表示仅支持 `text`。 +该插件注册唯一提供方路由 `deepseek-official`,并一同注册解析后的 `retryPolicy`;省略时会解析为 normal 模式并重试五次。请求使用 `provider: deepseek-official` 选择该路由;其 `model` 会作为协议 `model` 字符串原样传递,因此更改 DeepSeek 模型不需要生命周期时注册。省略 `models` 会公布适合聚焦任务、快速且经济的 `deepseek-v4-flash`,适合复杂或质量关键任务、更强但成本更高的 `deepseek-v4-pro`,以及支持图片输入的 `deepseek-v4-flash-vision-exp`;三者的上下文窗口均为 1,000,000 token。显式列表会替换这些默认值,`models: []` 则不公布任何模型。Catalog 配置项通过 `ctx.llm.listModels('deepseek-official')` 公开给 ACP(Agent Client Protocol)编辑器、Web 选择器和模型发现工具等客户端,但仍只提供建议:未列出模型 id 仍原样传递,并按纯文本路由处理。省略配置项 name 默认为其 id,省略 `inputModalities` 则表示仅支持 `text`。 -支持图片的 catalog 配置项声明 `inputModalities: [text, image]`,并可设置 `imagePixelBudget`、`imageMaxBytes` 或 `imageDetail: low`。普通默认值为总像素 640,000、编码字节 1MiB;low detail 的默认总像素为 512×512。附件存储按 `min(1, sqrt(pixelBudget / (width * height)))` 缩放,并向预算内取整,确保总像素不超过硬上限。因此 2048×1024 规范化附件会得到约 1130×565 的请求版本,而不会被强制变成正方形。请求编码按需执行:低色数图片先尝试 PNG,只有不带 alpha 通道时才使用 palette,再尝试质量 85 和 80 的 WebP;其他透明图片依次尝试质量 85 和 80 的 WebP;其他非透明图片依次尝试质量 85 和 80 的 JPEG。两个质量档均超过 1MiB 时才缩小尺寸。同一 `variantId` 的并发生成共享一次变换。调用方可以单独取消等待,不会中断其他等待方;没有等待方时才会停止变换。适配器通常通过 `POST /files` 上传确切的派生请求字节,再发送 `{type: "file", file_id}` 块。File ID 解析失败或超时后,适配器会用相同请求版本的 base64 data URL 重新组装整个 chat 请求;同一请求不会混用 file ID 和内联图片。每张保留图片前都有稳定文本,写明完整附件 ID 和实际请求尺寸。User、工具结果、agent loop、压缩和直接 `ctx.llm.stream` 请求都使用该投影。纯文本路由会收到稳定的附件占位文本,持久历史继续保留图片引用。 +支持图片的 catalog 配置项声明 `inputModalities: [text, image]`,并可把 `imagePixelBudget` 设为确切正整数或 `low`;省略时使用总像素 640,000,`low` 选择总像素 512×512。`imageMaxBytes` 默认值为 1MiB。附件存储按 `min(1, sqrt(pixelBudget / (width * height)))` 缩放,并向预算内取整,确保总像素不超过硬上限。因此 2048×1024 规范化附件会得到约 1130×565 的请求版本,而不会被强制变成正方形。请求编码按需执行:透明图片依次尝试质量 85、75、60 的 WebP(effort 0);非透明图片依次尝试这些质量的 JPEG。全部质量档都超过 1MiB 时使用其中最小的产物。同一 `variantId` 的并发生成共享一次变换。调用方可以单独取消等待,不会中断其他等待方;没有等待方时才会停止变换。适配器通常通过 `POST /files` 上传确切的派生请求字节,再发送 `{type: "file", file_id}` 块。File ID 解析失败或超时后,适配器会用相同请求版本的 base64 data URL 重新组装整个 chat 请求;同一请求不会混用 file ID 和内联图片。每张保留图片前都有文本,写明完整附件 ID 和实际请求尺寸。附件提供方给出宿主对象且当前文件系统能够将其映射到工具执行环境时,文本还会给出该只读路径,并指出复制到可写路径时应使用的匹配扩展名。该访问方式独立于确定性的请求版本及其 `variantId`。描述也会说明预览和规范化图片可能与上传图片不同。User、工具结果、agent loop、压缩和直接 `ctx.llm.stream` 请求都使用该投影。纯文本路由会收到稳定的附件占位文本,持久历史继续保留图片引用。 -`maxRequestFilesBytes` 和 `maxImagesPerRequest` 限制请求中保留的请求版本,默认值分别为 128MiB 和 600 张。字节和数量步长不得超过对应上限。读取附件前,适配器以路由的请求版本字节上限作为保守上界,移除超预算的最旧前缀,只读取并转换保留的规范化附件。系统随后用确切派生长度再次检查,但不会重新加入已省略图片。字节数越过上限时,被移除的最旧前缀会越过下一个 64MiB 边界。由 1MiB 图片组成的历史达到 129MiB 时会移除最旧的 65 张并保留 64MiB;直到持久历史超过 192MiB,这个前缀才再次变化。图片数量超限时则按 `imageOffloadCountQuantum` 独立递增。移除的图片会变成固定模型可见占位文本 `[image omitted to keep the request within its image limit; older images are omitted first. If this image is still needed, read its file again when a path is available; otherwise ask the user to attach it again.]`。这种定量投影不会因每新增一张图片就改写较早的请求前缀。 +`maxRequestFilesBytes` 和 `maxImagesPerRequest` 限制请求中保留的请求版本,默认值分别为 128MiB 和 600 张。字节和数量步长不得超过对应上限。读取附件前,适配器以路由的请求版本字节上限作为保守上界,移除超预算的最旧前缀,只读取并转换保留的规范化附件。系统随后用确切派生长度再次检查,但不会重新加入已省略图片。字节数越过上限时,被移除的最旧前缀会越过下一个 64MiB 边界。由 1MiB 图片组成的历史达到 129MiB 时会移除最旧的 65 张并保留 64MiB;直到持久历史超过 192MiB,这个前缀才再次变化。图片数量超限时则按 `imageOffloadCountQuantum` 独立递增。每张被移除的图片都有自己的模型可见占位文本,其中包含显示名称或附件 ID;如果当前提供方支持,还会包含规范化尺寸、媒体类型和当前只读本地路径。这种定量投影不会因每新增一张图片就改写较早的请求前缀。 内联回退使用独立的 base64 预算。`maxInlineRequestImageBytes` 默认为 20MiB,`inlineImageOffloadByteQuantum` 默认为 10MiB,因此由 21 个 1MiB base64 负载组成的历史会移除最旧的 11 个并保留 10MiB。计算使用 base64 膨胀后的长度。系统逐字节复用已经准备好的请求版本;回退不会再次解码或压缩图片。前面图片已经成功写入的上传映射会保留,供后续请求复用。 @@ -66,7 +66,7 @@ harness LLM(大语言模型)seam 的 DeepSeek chat-completions 适配器: `maxTokens` 是适配器为对话请求配置的输出上限,默认值为 256,000。Catalog 配置项可以自带 `maxTokens`,它对该模型胜出;不含该上限的配置项以及任何未列出原样传递 id 都解析为 profile 值,因此新增按模型的上限只改变一个模型,而非整条路由。确切模型解析会将胜出值公开为 `defaultMaxTokens`;`LlmRuntime` 会在 agent loop(智能体循环)写入 `request/header` 前,将该值填入 `GenerateOptions.maxTokens`,从而仍可根据持久记录重建协议请求。显式的请求值或 `AgentOptions.maxTokens` 值优先,并会序列化为 `max_tokens`。适配器不会根据 `contextWindow` 自动调低该请求预算;上下文或提供方输出上限较小的部署必须配置与其相容的 `maxTokens`。 -同一确切模型结果会在部署策略允许思考时,为每个原样传递模型在 `reasoning` 下公开有序的 `off`、`low`、`high` 和 `max` 推理(reasoning)强度。`reasoningEffort` 选择部署默认值,省略时回退为 `high`。`agent/request` 可以在每个会话步骤替换它;解析后的值会记录在 `request/header`。`low`、`high` 和 `max` 会启用思考,并以同名值序列化为官方顶层 `reasoning_effort`;适配器持有的 `off` 则序列化为 `thinking.type: disabled`,且省略 `reasoning_effort`。不支持的值会在网络 I/O 前以 `UNSUPPORTED_REASONING_EFFORT` 失败。 +同一确切模型结果会在部署策略允许思考时,为每个原样传递模型在 `reasoning` 下公开有序且附带选择指引的 `off`、`low`、`high` 和 `max` 推理(reasoning)强度。`reasoningEffort` 选择公布的默认值,省略时回退为 `high`。`agent/request` 可以在每个会话步骤替换它;解析后的值会记录在 `request/header`。`low`、`high` 和 `max` 会启用思考,并以同名值序列化为官方顶层 `reasoning_effort`;适配器持有的 `off` 则序列化为 `thinking.type: disabled`,且省略 `reasoning_effort`。不支持的值会在网络 I/O 前以 `UNSUPPORTED_REASONING_EFFORT` 失败。 `thinking: disabled` 是部署锁定:它只公布 `off`,并以 `off` 为默认值。省略 `reasoningEffort` 或将其配置为 `off` 均有效;配置 `low`、`high` 或 `max` 会使插件加载失败,直接按请求启用思考也会在网络 I/O 前失败。携带 `GenerateOptions.purpose: 'session-title'` 的请求也会强制禁用思考并省略已解析的推理强度,将有界输出保留给可见标题文本,不改变会话或压缩(compaction)默认值。 @@ -115,7 +115,7 @@ DeepSeek 请求身份独立于应用归因。凭据解析成功后,每个提 #### 模型看到的内容 -所选 DeepSeek 模型会收到 harness 系统提示词、消息历史、工具 schema、stop sequence 和调用配置,不含适配器撰写的提示词文本。提供方特定请求扩展字段仍位于该模型输入之外。视觉模型通常通过 Files API 引用收到保留的 user 与工具结果图片,旁边带有稳定附件句柄和请求图片尺寸;Files 解析失败时,所有保留图片改用内联 data URL。超出上限的较旧图片由已记录的占位文本表示。之前 assistant 轮次的推理内容会原文回传,无论该轮次是否调用了工具。 +所选 DeepSeek 模型会收到 harness 系统提示词、消息历史、工具 schema、stop sequence 和调用配置,不含适配器撰写的提示词文本。提供方特定请求扩展字段仍位于该模型输入之外。视觉模型通常通过 Files API 引用收到保留的 user 与工具结果图片,旁边带有附件句柄和请求预览尺寸。当前执行文件系统能够映射附件提供方的宿主对象时,模型还会收到规范化对象路径;Files 解析失败时,所有保留图片改用内联 data URL。描述会告诉模型,该本地副本只供读取,可能经过缩小或重新编码,不能据此推断上传图片的属性。超出上限的较旧图片会在自己的占位文本中保留本次请求解析出的访问方式。之前 assistant 轮次的推理内容会原文回传,无论该轮次是否调用了工具。 #### Token 影响 @@ -123,7 +123,7 @@ DeepSeek 请求身份独立于应用归因。凭据解析成功后,每个提 #### KV Cache 影响 -未更改的已组装前缀,包括确定性编码的保留图片与占位文本,可使用 DeepSeek cache 复用,适配器会在 usage 中报告它。模型路由变更,或任何上游提示词、schema、前缀、历史或图片上限变更,都可能使从首个发生变化的 token 起的复用失效;推理回传会在每个含推理的轮次上追加。 +未更改的已组装前缀可以使用 DeepSeek cache 复用,适配器会在 usage 中报告它。确定性的请求图片字节不能保证完整前缀不变:执行环境路径变化会在没有 offload 时改写历史描述,重新上传可能替换 `file_id`,Files 转为 base64 回退也会改变图片表示。这些变化都可能使复用从首张受影响图片起失效。模型路由、提示词、schema、历史和图片上限变化会产生同样的后缀影响;推理回传会在每个含推理的轮次上追加。 ### DeepSeek 响应 diff --git a/packages/llm/llm-deepseek/package.json b/packages/llm/llm-deepseek/package.json index eba8fbc5a7..49f42e6539 100644 --- a/packages/llm/llm-deepseek/package.json +++ b/packages/llm/llm-deepseek/package.json @@ -37,6 +37,7 @@ "@deepseek-ai/dsh-brand": "workspace:^", "@deepseek-ai/dsh-credentials": "workspace:^", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:^", + "@deepseek-ai/dsh-fs": "workspace:^", "@deepseek-ai/dsh-launch-environment": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", @@ -57,6 +58,7 @@ "@deepseek-ai/dsh-brand": "workspace:^", "@deepseek-ai/dsh-credentials": "workspace:^", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:^", + "@deepseek-ai/dsh-fs": "workspace:^", "@deepseek-ai/dsh-plugin-package-inventory-deepseek": "workspace:^", "@deepseek-ai/dsh-launch-environment": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index fe461fdb35..35212d32d6 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -8,10 +8,11 @@ * @module dsh-llm-deepseek/adapter */ -import { attributionHeaders, contentHasImage, CONTEXT_WINDOW_EXCEEDED_CODE, isContextWindowExceededError, isQuotaExceededError, LlmAdapter, LlmError, offloadRequestImagesWithPolicy, ProviderRequestId, QUOTA_EXCEEDED_CODE, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { attributionHeaders, contentHasImage, CONTEXT_WINDOW_EXCEEDED_CODE, isContextWindowExceededError, isQuotaExceededError, LlmAdapter, LlmError, offloadedImageText, offloadRequestImagesWithPolicy, ProviderRequestId, QUOTA_EXCEEDED_CODE, ReasoningEffortId } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, + ImageAttachmentAccess, LlmModelInfo, LlmProviderInfo, PreparedAdapterCall, @@ -58,12 +59,10 @@ export interface DeepSeekCatalogModel { maxTokens?: number /** Accepted request modalities; omission is text-only. */ inputModalities?: ModelModality[] - /** Total-pixel budget for one deterministic request preview. */ - imagePixelBudget?: number - /** Encoded-byte cap for one deterministic request preview. */ + /** Total-pixel budget for one deterministic request preview, or the 512-by-512 `low` preset. */ + imagePixelBudget?: number | 'low' + /** Encoded-byte target for one deterministic request preview; the smallest quality-ladder output is used when no quality fits. */ imageMaxBytes?: number - /** Provider detail tier; `low` uses the 512-by-512 total-pixel default. */ - imageDetail?: 'auto' | 'low' } /** @@ -127,6 +126,8 @@ export interface DeepSeekAdapterOptions { resolveUserId: () => AnonymousUserId /** Resolve the current durable attachment service; absence rejects image input. */ resolveAttachments?: () => AttachmentStore | undefined + /** Bridge one attachment reference into the current model-tool execution world. */ + resolveImageAccess?: (attachments: AttachmentStore, ref: ImageAttachmentRef) => ImageAttachmentAccess | undefined /** Resolve the process-wide upload reuse store. */ resolveFiles?: () => DeepSeekFileStore /** Prepare the official API's plugin-contributed top-level fields for one exact wire request. */ @@ -149,7 +150,7 @@ export const DEFAULT_MAX_IMAGES_PER_REQUEST = 600 export const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 640_000 /** Total-pixel budget matching provider low-detail image input. */ export const DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET = 512 * 512 -/** Encoded-byte cap for one deterministic model-request image. */ +/** Encoded-byte target for one deterministic model-request image; the smallest quality-ladder output is used when no quality fits. */ export const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1024 * 1024 /** Deterministic raw-byte removal step. */ export const DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM = 64 * 1024 * 1024 @@ -172,13 +173,33 @@ const LOW_REASONING_EFFORT = ReasoningEffortId('low') const HIGH_REASONING_EFFORT = ReasoningEffortId('high') const MAX_REASONING_EFFORT = ReasoningEffortId('max') const REASONING_EFFORTS = [ - { id: OFF_REASONING_EFFORT, name: 'Off' }, - { id: LOW_REASONING_EFFORT, name: 'Low' }, - { id: HIGH_REASONING_EFFORT, name: 'High' }, - { id: MAX_REASONING_EFFORT, name: 'Max' }, + { + id: OFF_REASONING_EFFORT, + name: 'Off', + description: 'Use for simple tasks that do not need reasoning.', + }, + { + id: LOW_REASONING_EFFORT, + name: 'Low', + description: 'Prefer for routine or latency-sensitive tasks.', + }, + { + id: HIGH_REASONING_EFFORT, + name: 'High', + description: 'The default balance for most tasks.', + }, + { + id: MAX_REASONING_EFFORT, + name: 'Max', + description: 'Reserve for the hardest quality-first tasks.', + }, ] as const const OFF_ONLY_REASONING_EFFORTS = [ - { id: OFF_REASONING_EFFORT, name: 'Off' }, + { + id: OFF_REASONING_EFFORT, + name: 'Off', + description: 'Use for simple tasks that do not need reasoning.', + }, ] as const /** Marks a failed file-id resolution that may be retried as an inline request. */ @@ -206,10 +227,9 @@ function collectImageRefs( * @internal */ export function resolveRequestImagePolicy(model: DeepSeekCatalogModel): ImageRequestPolicy { - let maxPixels: number - if (model.imagePixelBudget !== undefined) maxPixels = model.imagePixelBudget - else if (model.imageDetail === 'low') maxPixels = DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET - else maxPixels = DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET + const maxPixels = model.imagePixelBudget === 'low' + ? DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET + : model.imagePixelBudget ?? DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET return { maxPixels, maxBytes: model.imageMaxBytes === undefined @@ -541,6 +561,10 @@ export class DeepSeekAdapter extends LlmAdapter { const fileConnection = { baseURL: connection.baseURL, apiKey } const model = connection.models.find(entry => entry.id === options.model) const policy = model === undefined ? undefined : resolveRequestImagePolicy(model) + const resolveImageAccess = attachments === undefined + ? undefined + : (ref: ImageAttachmentRef): ImageAttachmentAccess | undefined => this.config.resolveImageAccess?.(attachments, ref) + const imageAccessOptions = resolveImageAccess === undefined ? {} : { resolveImageAccess } const requestMessages = policy === undefined ? options.messages : offloadRequestImagesWithPolicy(options.messages, { representation: 'raw', maxBytes: connection.maxRequestFilesBytes, @@ -548,6 +572,7 @@ export class DeepSeekAdapter extends LlmAdapter { byteQuantum: connection.imageOffloadByteQuantum, countQuantum: connection.imageOffloadCountQuantum, byteLength: ref => Math.min(ref.bytes, policy.maxBytes), + placeholder: ref => offloadedImageText(ref, resolveImageAccess?.(ref)), }) const requestOptions = requestMessages === options.messages ? options : { ...options, messages: [...requestMessages] } const requestImages = attachments === undefined || model === undefined @@ -564,6 +589,7 @@ export class DeepSeekAdapter extends LlmAdapter { body = await serializeRequestWithImages(requestOptions, { representation: { kind: 'base64' }, requestImages, + ...imageAccessOptions, maxRequestImageBytes: connection.maxInlineRequestImageBytes, maxImagesPerRequest: connection.maxImagesPerRequest, byteQuantum: connection.inlineImageOffloadByteQuantum, @@ -594,6 +620,7 @@ export class DeepSeekAdapter extends LlmAdapter { }, }, requestImages, + ...imageAccessOptions, maxRequestImageBytes: connection.maxRequestFilesBytes, maxImagesPerRequest: connection.maxImagesPerRequest, byteQuantum: connection.imageOffloadByteQuantum, diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts index e6faad74ce..da0c9e24b5 100644 --- a/packages/llm/llm-deepseek/src/index.ts +++ b/packages/llm/llm-deepseek/src/index.ts @@ -13,8 +13,9 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { assertUsableApiKey, LlmError, resolveRetryPolicy, RetryPolicySchema } from '@deepseek-ai/dsh-llm' +import { assertUsableApiKey, LlmError, resolveImageAttachmentAccess, resolveRetryPolicy, RetryPolicySchema } from '@deepseek-ai/dsh-llm' import type { ModelModality, RetryPolicyConfig } from '@deepseek-ai/dsh-llm' +import type {} from '@deepseek-ai/dsh-fs' import { credentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { deepEqualJson, installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings' @@ -81,8 +82,18 @@ const DEFAULT_API_KEY_ENV = 'DEEPSEEK_API_KEY' const PROVIDER = 'deepseek-official' const DEFAULT_MODELS: DeepSeekCatalogModel[] = [ - { id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', contextWindow: DEFAULT_CONTEXT_WINDOW }, - { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro', contextWindow: DEFAULT_CONTEXT_WINDOW }, + { + id: 'deepseek-v4-flash', + name: 'DeepSeek-V4-Flash', + description: 'Fast, efficient, and economical; suited to focused, routine, or parallel tasks.', + contextWindow: DEFAULT_CONTEXT_WINDOW, + }, + { + id: 'deepseek-v4-pro', + name: 'DeepSeek-V4-Pro', + description: 'Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.', + contextWindow: DEFAULT_CONTEXT_WINDOW, + }, { id: 'deepseek-v4-flash-vision-exp', name: 'DeepSeek-V4-Flash-Vision-Exp', @@ -151,9 +162,8 @@ const catalogModel: z = z.object({ contextWindow: z.number().step(1).min(1), maxTokens: z.number().step(1).min(1), inputModalities: z.array(z.union(MODEL_MODALITIES)).min(1).default(['text']), - imagePixelBudget: z.number().step(1).min(1), + imagePixelBudget: z.union([z.number().step(1).min(1), 'low']), imageMaxBytes: z.number().step(1).min(1), - imageDetail: z.union(['auto', 'low']), }) export const Config: z = z.object({ @@ -196,6 +206,9 @@ export type ResolvedDeepSeekOptions = DeepSeekConnectionOptions function resolveModels(models: readonly DeepSeekCatalogModel[] | undefined): DeepSeekCatalogModel[] { const seen = new Set() return (models ?? DEFAULT_MODELS).map((model) => { + if (Object.hasOwn(model, 'imageDetail')) { + throw new Error('llm-deepseek: catalog model imageDetail is no longer supported; use imagePixelBudget') + } if (model.id.length === 0) throw new Error('llm-deepseek: catalog model ids must be non-empty') if (model.name !== undefined && model.name.length === 0) { throw new Error(`llm-deepseek: catalog model "${model.id}" has an empty name`) @@ -225,13 +238,13 @@ function resolveModels(models: readonly DeepSeekCatalogModel[] | undefined): Dee throw new Error(`llm-deepseek: catalog model "${model.id}" inputModalities must not contain duplicates`) } const hasImage = inputModalities.includes('image') - if (!hasImage && (model.imagePixelBudget !== undefined - || model.imageMaxBytes !== undefined || model.imageDetail !== undefined)) { + if (!hasImage && (model.imagePixelBudget !== undefined || model.imageMaxBytes !== undefined)) { throw new Error(`llm-deepseek: text-only catalog model "${model.id}" cannot declare image request limits`) } if (model.imagePixelBudget !== undefined + && model.imagePixelBudget !== 'low' && (!Number.isSafeInteger(model.imagePixelBudget) || model.imagePixelBudget <= 0)) { - throw new Error(`llm-deepseek: catalog model "${model.id}" imagePixelBudget must be a positive safe integer`) + throw new Error(`llm-deepseek: catalog model "${model.id}" imagePixelBudget must be "low" or a positive safe integer`) } if (model.imageMaxBytes !== undefined && (!Number.isSafeInteger(model.imageMaxBytes) || model.imageMaxBytes <= 0)) { @@ -248,12 +261,10 @@ function resolveModels(models: readonly DeepSeekCatalogModel[] | undefined): Dee inputModalities: [...inputModalities], ...hasImage ? { - imagePixelBudget: model.imagePixelBudget - ?? (model.imageDetail === 'low' - ? DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET - : DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET), + imagePixelBudget: model.imagePixelBudget === 'low' + ? DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET + : model.imagePixelBudget ?? DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET, imageMaxBytes: model.imageMaxBytes ?? DEFAULT_REQUEST_IMAGE_MAX_BYTES, - ...model.imageDetail === undefined ? {} : { imageDetail: model.imageDetail }, } : {}, } @@ -438,6 +449,11 @@ export function apply(ctx: Context, config: Config): void { resolveApiKey, resolveUserId, resolveAttachments: () => ctx.get('attachments'), + resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess( + attachments, + hostPath => ctx.get('fs')?.processPathFromHostPath(hostPath), + ref, + ), prepareExtensions: (request) => { const extensions = ctx.get('deepseekLlmApiExtensions') return extensions?.prepare(request) diff --git a/packages/llm/llm-deepseek/src/serialize.ts b/packages/llm/llm-deepseek/src/serialize.ts index 3b22967d96..1749991eca 100644 --- a/packages/llm/llm-deepseek/src/serialize.ts +++ b/packages/llm/llm-deepseek/src/serialize.ts @@ -6,8 +6,8 @@ * @module dsh-llm-deepseek/serialize */ -import { contentHasImage, LlmError, offloadRequestImagesWithPolicy, requestImageHandleText } from '@deepseek-ai/dsh-llm' -import type { ContentBlock, GenerateOptions, Message } from '@deepseek-ai/dsh-llm' +import { contentHasImage, LlmError, offloadedImageText, offloadRequestImagesWithPolicy, requestImageHandleText } from '@deepseek-ai/dsh-llm' +import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message } from '@deepseek-ai/dsh-llm' import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import type { WireImageContentPart, @@ -48,6 +48,8 @@ export interface ImageSerializationOptions { representation: ImageRequestRepresentation /** Request versions prepared for the conservatively retained normalized attachments, keyed by attachment id. */ requestImages: ReadonlyMap + /** Resolve current tool access independently from deterministic request-image versions. */ + resolveImageAccess?: ImageAttachmentAccessResolver /** Positive bound on accumulated represented image bytes. */ maxRequestImageBytes: number /** Maximum represented images in one request. */ @@ -125,12 +127,14 @@ function assertSupportedImageRoles(messages: readonly Message[]): void { /** Describe the exact request preview and its model-callable coordinate system. */ function imageHandle( + ref: ImageAttachmentRef, version: RequestImageAttachment, + resolveAccess: ImageAttachmentAccessResolver | undefined, precededByContent: boolean, ): WireTextContentPart { return { type: 'text', - text: `${precededByContent ? '\n' : ''}${requestImageHandleText(version)}`, + text: `${precededByContent ? '\n' : ''}${requestImageHandleText(ref, version, resolveAccess?.(ref))}`, } } @@ -154,7 +158,7 @@ async function imageParts( type: 'image_url', image_url: { url: `data:${version.mediaType};base64,${Buffer.from(version.data).toString('base64')}` }, } - return [imageHandle(version, precededByContent), image] + return [imageHandle(block.attachment, version, images.resolveImageAccess, precededByContent), image] } /** Convert user or nested tool-result blocks into ordered wire parts. */ @@ -389,10 +393,10 @@ export function serializeRequest( /** * Build one image-capable request while keeping durable bytes out of session - * messages. Oversized oldest images become deterministic text after their + * messages. Oversized oldest images become per-image text after their * exact request-version byte lengths are known and before provider serialization. * @param options - harness request containing image-capable user content. - * @param images - attachment resolver, request bound, and cancellation. + * @param images - request versions, optional current access resolver, and request bounds. * @param defaults - adapter-level thinking defaults. * @returns the fully materialized DeepSeek request body. */ @@ -415,6 +419,7 @@ export async function serializeRequestWithImages( ...images.maxImagesPerRequest === undefined ? {} : { maxImages: images.maxImagesPerRequest }, ...images.byteQuantum === undefined ? {} : { byteQuantum: images.byteQuantum }, ...images.countQuantum === undefined ? {} : { countQuantum: images.countQuantum }, + placeholder: ref => offloadedImageText(ref, images.resolveImageAccess?.(ref)), }) const messages: WireMessage[] = [] if (options.system !== undefined) { diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index 5a32a35664..3f87737930 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -109,7 +109,7 @@ function attachmentStoreOf( } { const readImageRequest = vi.fn(project) return { - store: { readImageRequest } as unknown as AttachmentStore, + store: { readImageRequest, imageHostPath: () => undefined } as unknown as AttachmentStore, readImageRequest, } } @@ -147,7 +147,7 @@ describe('request image policy', () => { { maxPixels: 640_000, maxBytes: 1024 * 1024 }, ], [ - { id: 'low', imageDetail: 'low' as const }, + { id: 'low', imagePixelBudget: 'low' as const }, { maxPixels: 512 * 512, maxBytes: 1024 * 1024 }, ], [ @@ -367,7 +367,7 @@ describe('DeepSeekAdapter against a mock server', () => { role: 'user', content: [ { type: 'text', text: 'describe ' }, - { type: 'text', text: expect.stringContaining(`Image ${imageRef.attachmentId}; request image 1x1px.`) as string }, + { type: 'text', text: expect.stringContaining(`Image ${imageRef.attachmentId}; request preview 1x1px.`) as string }, { type: 'file', file_id: 'file-api-1' }, ], }], @@ -434,7 +434,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) const body = JSON.stringify(server.requests[0]) - expect(body.match(/older images are omitted first/g)).toHaveLength(11) + expect(body.match(/image omitted to fit request image limits/g)).toHaveLength(11) expect(body.match(/"type":"image_url"/g)).toHaveLength(10) }) @@ -600,7 +600,7 @@ describe('DeepSeekAdapter against a mock server', () => { expect(body.messages[0]).toMatchObject({ role: 'user', content: [ - { type: 'text', text: expect.stringContaining('older images are omitted first') as string }, + { type: 'text', text: expect.stringContaining(`image omitted to fit request image limits; ${old.attachmentId}`) as string }, { type: 'text', text: expect.stringContaining(String(recent.attachmentId)) as string }, { type: 'file', file_id: 'file-api-1' }, ], @@ -619,7 +619,7 @@ describe('DeepSeekAdapter against a mock server', () => { { id: 'vision-low', inputModalities: ['text', 'image'], - imageDetail: 'low', + imagePixelBudget: 'low', imageMaxBytes: 512_000, }, { @@ -1205,7 +1205,11 @@ describe('DeepSeekAdapter against a mock server', () => { await expect(ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-v4-flash')) .resolves.toMatchObject({ reasoning: { - efforts: [{ id: ReasoningEffortId('off'), name: 'Off' }], + efforts: [{ + id: ReasoningEffortId('off'), + name: 'Off', + description: 'Use for simple tasks that do not need reasoning.', + }], defaultEffort: ReasoningEffortId('off'), }, }) @@ -1665,8 +1669,20 @@ describe('plugin registration and config', () => { await ctx.plugin(LlmDeepSeek, { baseURL: 'http://127.0.0.1:1' }) expect(ctx.llm.listProviders()).toEqual([{ id: 'deepseek-official', name: 'DeepSeek' }]) await expect(ctx.llm.listModels('deepseek-official')).resolves.toEqual([ - { provider: 'deepseek-official', id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', inputModalities: ['text'] }, - { provider: 'deepseek-official', id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro', inputModalities: ['text'] }, + { + provider: 'deepseek-official', + id: 'deepseek-v4-flash', + name: 'DeepSeek-V4-Flash', + description: 'Fast, efficient, and economical; suited to focused, routine, or parallel tasks.', + inputModalities: ['text'], + }, + { + provider: 'deepseek-official', + id: 'deepseek-v4-pro', + name: 'DeepSeek-V4-Pro', + description: 'Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.', + inputModalities: ['text'], + }, { provider: 'deepseek-official', id: 'deepseek-v4-flash-vision-exp', name: 'DeepSeek-V4-Flash-Vision-Exp', inputModalities: ['text', 'image'] }, ]) await expect(ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-v4-flash')) @@ -1678,10 +1694,10 @@ describe('plugin registration and config', () => { defaultMaxTokens: 256_000, reasoning: { efforts: [ - { id: ReasoningEffortId('off'), name: 'Off' }, - { id: ReasoningEffortId('low'), name: 'Low' }, - { id: ReasoningEffortId('high'), name: 'High' }, - { id: ReasoningEffortId('max'), name: 'Max' }, + { id: ReasoningEffortId('off'), name: 'Off', description: 'Use for simple tasks that do not need reasoning.' }, + { id: ReasoningEffortId('low'), name: 'Low', description: 'Prefer for routine or latency-sensitive tasks.' }, + { id: ReasoningEffortId('high'), name: 'High', description: 'The default balance for most tasks.' }, + { id: ReasoningEffortId('max'), name: 'Max', description: 'Reserve for the hardest quality-first tasks.' }, ], defaultEffort: ReasoningEffortId('high'), }, @@ -1708,10 +1724,10 @@ describe('plugin registration and config', () => { .resolves.toMatchObject({ reasoning: { efforts: [ - { id: ReasoningEffortId('off'), name: 'Off' }, - { id: ReasoningEffortId('low'), name: 'Low' }, - { id: ReasoningEffortId('high'), name: 'High' }, - { id: ReasoningEffortId('max'), name: 'Max' }, + { id: ReasoningEffortId('off'), name: 'Off', description: 'Use for simple tasks that do not need reasoning.' }, + { id: ReasoningEffortId('low'), name: 'Low', description: 'Prefer for routine or latency-sensitive tasks.' }, + { id: ReasoningEffortId('high'), name: 'High', description: 'The default balance for most tasks.' }, + { id: ReasoningEffortId('max'), name: 'Max', description: 'Reserve for the hardest quality-first tasks.' }, ], defaultEffort: ReasoningEffortId(effort), }, @@ -1729,7 +1745,11 @@ describe('plugin registration and config', () => { await expect(ctx.llm.resolveModelInfo('deepseek-official', 'unlisted-pass-through')) .resolves.toMatchObject({ reasoning: { - efforts: [{ id: ReasoningEffortId('off'), name: 'Off' }], + efforts: [{ + id: ReasoningEffortId('off'), + name: 'Off', + description: 'Use for simple tasks that do not need reasoning.', + }], defaultEffort: ReasoningEffortId('off'), }, }) @@ -1761,7 +1781,11 @@ describe('plugin registration and config', () => { const adapter = adapterOf({ thinking: 'disabled', reasoningEffort: 'off' }) await expect(adapter.resolveModel('deepseek-official', 'pass-through')).resolves.toMatchObject({ reasoning: { - efforts: [{ id: ReasoningEffortId('off'), name: 'Off' }], + efforts: [{ + id: ReasoningEffortId('off'), + name: 'Off', + description: 'Use for simple tasks that do not need reasoning.', + }], defaultEffort: ReasoningEffortId('off'), }, }) @@ -1772,8 +1796,20 @@ describe('plugin registration and config', () => { await ctx.plugin(LlmRuntime) LlmDeepSeek.apply(ctx, { baseURL: 'http://127.0.0.1:1' }) await expect(ctx.llm.listModels('deepseek-official')).resolves.toEqual([ - { provider: 'deepseek-official', id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', inputModalities: ['text'] }, - { provider: 'deepseek-official', id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro', inputModalities: ['text'] }, + { + provider: 'deepseek-official', + id: 'deepseek-v4-flash', + name: 'DeepSeek-V4-Flash', + description: 'Fast, efficient, and economical; suited to focused, routine, or parallel tasks.', + inputModalities: ['text'], + }, + { + provider: 'deepseek-official', + id: 'deepseek-v4-pro', + name: 'DeepSeek-V4-Pro', + description: 'Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.', + inputModalities: ['text'], + }, { provider: 'deepseek-official', id: 'deepseek-v4-flash-vision-exp', name: 'DeepSeek-V4-Flash-Vision-Exp', inputModalities: ['text', 'image'] }, ]) }) @@ -1895,6 +1931,20 @@ describe('plugin registration and config', () => { expect(() => resolveAdapterOptions({ models: [...models] })).toThrow(message) }) + it('rejects the removed imageDetail model setting through schema and direct construction', async () => { + const legacyModel = { id: 'vision', inputModalities: ['image'], imageDetail: 'low' } as unknown as + LlmDeepSeek.DeepSeekCatalogModel + expect(() => resolveAdapterOptions({ models: [legacyModel] })).toThrow(/imageDetail is no longer supported/) + + const ctx = new Context() + await ctx.plugin(LlmRuntime) + await expect(ctx.plugin(LlmDeepSeek, { + baseURL: 'http://127.0.0.1:1', + models: [legacyModel], + })).rejects.toThrow(/imageDetail is no longer supported/) + expect(ctx.llm.listProviders()).toEqual([]) + }) + it.each([0, 1.5])('rejects a per-model output cap of %s', (maxTokens) => { expect(() => resolveAdapterOptions({ models: [{ id: 'bad-cap', maxTokens }] })) .toThrow(/maxTokens must be a positive integer/) @@ -1907,8 +1957,9 @@ describe('plugin registration and config', () => { }) it.each([ - ['imagePixelBudget', 0, /imagePixelBudget must be a positive safe integer/], - ['imagePixelBudget', Number.MAX_SAFE_INTEGER + 1, /imagePixelBudget must be a positive safe integer/], + ['imagePixelBudget', 0, /imagePixelBudget must be "low" or a positive safe integer/], + ['imagePixelBudget', Number.MAX_SAFE_INTEGER + 1, /imagePixelBudget must be "low" or a positive safe integer/], + ['imagePixelBudget', 'auto', /imagePixelBudget must be "low" or a positive safe integer/], ['imageMaxBytes', 0, /imageMaxBytes must be a positive safe integer/], ['imageMaxBytes', 1.5, /imageMaxBytes must be a positive safe integer/], ] as const)('rejects per-model %s=%s', (field, value, message) => { diff --git a/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts b/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts index 4617ebdfed..75cb90000b 100644 --- a/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts +++ b/packages/llm/llm-deepseek/tests/dynamic-config.spec.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import { access, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -30,6 +30,18 @@ const IMAGE_REF: ImageAttachmentRef = { width: 1, height: 1, } +const HOST_IMAGE_PATH = '/host/.dsh/attachments/objects/aa/object' +const MODEL_IMAGE_PATH = '/model/.dsh/attachments/objects/aa/object' + +class MappedFileSystem extends Service { + constructor(ctx: Context) { + super(ctx, 'fs') + } + + processPathFromHostPath(hostPath: string): string | undefined { + return hostPath === HOST_IMAGE_PATH ? MODEL_IMAGE_PATH : undefined + } +} class StaticAttachmentStore extends AttachmentStore { readonly imageLimits: ImageAttachmentLimits = { @@ -53,6 +65,10 @@ class StaticAttachmentStore extends AttachmentStore { return Promise.resolve({ ref, data: Uint8Array.of(1, 2, 3) }) } + override imageHostPath(_ref: ImageAttachmentRef): string { + return HOST_IMAGE_PATH + } + override readImageRequest( ref: ImageAttachmentRef, _policy: ImageRequestPolicy, @@ -193,6 +209,7 @@ describe('request-level dynamic configuration', () => { { kind: 'sse', events: textEvents }, ]) const { ctx } = await boot(dir, { baseURL: server.url }) + await ctx.plugin(MappedFileSystem) const messages = [createUserMessage({ content: [ { type: 'image', attachment: IMAGE_REF }, @@ -208,7 +225,8 @@ describe('request-level dynamic configuration', () => { const first = (server.requests[0] as { messages: Array<{ content: unknown }> }).messages[0]?.content const second = (server.requests[1] as { messages: Array<{ content: unknown }> }).messages[0]?.content expect(JSON.stringify(first).match(/"type":"file"/g)).toHaveLength(2) - expect(JSON.stringify(second)).toContain('[image omitted to keep the request within its image limit') + expect(JSON.stringify(second)).toContain('[image omitted to fit request image limits') + expect(JSON.stringify(second)).toContain(MODEL_IMAGE_PATH) expect(JSON.stringify(second).match(/"type":"file"/g)).toHaveLength(1) }) diff --git a/packages/llm/llm-deepseek/tests/serialize.spec.ts b/packages/llm/llm-deepseek/tests/serialize.spec.ts index 968ceabdaf..0240a6c22a 100644 --- a/packages/llm/llm-deepseek/tests/serialize.spec.ts +++ b/packages/llm/llm-deepseek/tests/serialize.spec.ts @@ -57,7 +57,7 @@ function imageOptions( refs: readonly ImageAttachmentRef[], resolveFileId: FileResolver = fileResolver(), maxRequestImageBytes = 20 * 1024 * 1024, -) { +): ImageSerializationOptions { return { representation: { kind: 'file' as const, resolveFileId }, requestImages: new Map(refs.map(ref => [ref.attachmentId, requestVersion(ref)])), @@ -367,7 +367,7 @@ describe('image serialization', () => { role: 'user', content: [ { type: 'text', text: 'before' }, - { type: 'text', text: expect.stringContaining(`Image ${ref.attachmentId}; request image 1x1px`) as string }, + { type: 'text', text: expect.stringContaining(`Image ${ref.attachmentId}; request preview 1x1px`) as string }, { type: 'file', file_id: 'file-api-image' }, { type: 'text', text: 'after' }, ], @@ -392,7 +392,7 @@ describe('image serialization', () => { expect(wire.messages).toEqual([{ role: 'user', content: [ - { type: 'text', text: `Image ${ref.attachmentId}; request image 1x1px.` }, + { type: 'text', text: expect.stringContaining(`Image ${ref.attachmentId}; request preview 1x1px`) as string }, { type: 'image_url', image_url: { url } }, ], }]) @@ -411,12 +411,41 @@ describe('image serialization', () => { expect(wire.messages).toEqual([{ role: 'user', content: [ - { type: 'text', text: `Image ${ref.attachmentId}; request image 1x1px.` }, + { + type: 'text', + text: `Image ${ref.attachmentId}; request preview 1x1px. It may be resized or re-encoded; source dimensions, format, and byte size may differ.`, + }, { type: 'file', file_id: 'file-api-image' }, ], }]) }) + it('includes provider-resolved normalized access in a retained image handle', async () => { + const ref = { ...imageRef(), name: 'diagram.png', width: 2048, height: 1024 } + const images = imageOptions([ref]) + const version = images.requestImages.get(ref.attachmentId) as RequestImageAttachment + version.width = 1130 + version.height = 565 + images.resolveImageAccess = () => ({ readonlyPath: '/tmp/dsh/objects/aa/object' }) + const wire = await serializeRequestWithImages(request({ + model: 'deepseek-v4-flash-vision-exp', + messages: [createUserMessage({ + content: [{ type: 'image', attachment: ref }], + source: { kind: 'plugin', plugin: 'test' }, + })], + }), images) + + expect(wire.messages[0]).toMatchObject({ + role: 'user', + content: [{ + type: 'text', + text: expect.stringContaining('Image "diagram.png"') as string, + }, { type: 'file' }], + }) + expect(JSON.stringify(wire.messages[0])).toContain('/tmp/dsh/objects/aa/object') + expect(JSON.stringify(wire.messages[0])).toContain('request preview 1130x565px') + }) + it('rejects an image whose prepared request version is absent', async () => { const ref = imageRef() await expect(serializeMessagesWithImages([createUserMessage({ @@ -546,14 +575,14 @@ describe('image serialization', () => { { role: 'tool', tool_call_id: 'before-system', - content: expect.stringContaining('request image 1x1px') as string, + content: expect.stringContaining('request preview 1x1px') as string, }, expect.objectContaining({ role: 'user' }), { role: 'system', content: 'system history' }, { role: 'tool', tool_call_id: 'before-assistant', - content: expect.stringContaining('request image 1x1px') as string, + content: expect.stringContaining('request preview 1x1px') as string, }, expect.objectContaining({ role: 'user' }), { role: 'assistant', content: 'assistant history' }, @@ -564,6 +593,10 @@ describe('image serialization', () => { const resolveFileId = fileResolver() const png = imageRef('image/png', 3) const jpeg = imageRef('image/jpeg', 3) + const images = imageOptions([png, jpeg], resolveFileId, 4) + images.resolveImageAccess = ref => ref.mediaType === 'image/png' + ? { readonlyPath: '/tmp/dsh/objects/png' } + : undefined const wire = await serializeRequestWithImages(request({ model: 'deepseek-v4-flash-vision-exp', messages: [createUserMessage({ @@ -573,12 +606,15 @@ describe('image serialization', () => { ], source: { kind: 'plugin', plugin: 'test' }, })], - }), imageOptions([png, jpeg], resolveFileId, 4)) + }), images) expect(wire.messages[0]).toMatchObject({ role: 'user', content: [ - { type: 'text', text: expect.stringContaining('older images are omitted first') as string }, + { + type: 'text', + text: expect.stringContaining(`image omitted to fit request image limits; ${png.attachmentId}. Normalized copy (read-only; may be resized or re-encoded): "/tmp/dsh/objects/png"`) as string, + }, { type: 'text', text: expect.stringContaining(`Image ${jpeg.attachmentId}`) as string }, { type: 'file', file_id: 'file-api-image' }, ], @@ -598,7 +634,7 @@ describe('image serialization', () => { }), inlineImageOptions([ref], 80, 40)) const content = wire.messages[0]?.content - expect(JSON.stringify(content).match(/older images are omitted first/g)).toHaveLength(11) + expect(JSON.stringify(content).match(/image omitted to fit request image limits/g)).toHaveLength(11) expect(JSON.stringify(content).match(/"type":"image_url"/g)).toHaveLength(10) }) diff --git a/packages/llm/llm-deepseek/tsconfig.json b/packages/llm/llm-deepseek/tsconfig.json index 2f75c10b9e..81b7bb1eca 100644 --- a/packages/llm/llm-deepseek/tsconfig.json +++ b/packages/llm/llm-deepseek/tsconfig.json @@ -23,6 +23,9 @@ { "path": "../../attachment/attachment" }, + { + "path": "../../fs/fs" + }, { "path": "../../util/atomic-write" }, diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index a7021eb1cd..034878a1ce 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/llm/llm-pi-ai/README.md -README.md: 9ef6596490b614a3d4af3dd6b52eb9b9fe87a335 -README.zh.md: 10f366659a38f52f7700c0db7953b983fd0e623a +README.md: 31e40e5f0fa3c1e7e0ae0df05aa0a76d54d120b0 +README.zh.md: cd40804ce5908aebd0c35011ad1d56879834164d diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index 9ef6596490..31e40e5f0f 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -123,7 +123,7 @@ A model that carries reasoning metadata — from the installed catalog or from i A model **without** that metadata — a hand-declared one whose entry declares no `reasoningEfforts`, and a catalog model pi-ai marks as non-reasoning — exposes no `reasoning` at all. pi-ai reports such a model as supporting the single level `off`, but `off` is translated to *omitting* the reasoning option, which is byte-for-byte the request that naming no effort already produces: selecting it could not disable anything, so a provider whose own default is to think would keep thinking with `off` shown as selected. Reporting the capability as unavailable leaves a surface offering the provider's default and nothing that misrepresents it. The profile `reasoning` value, including `off`, is the deployment default when configured; omitting it preserves the provider default. Per-request `GenerateOptions.reasoningEffort` takes precedence, and a level absent from the exact model capability fails the REQUEST with `UNSUPPORTED_REASONING_EFFORT` before network I/O instead of being clamped. Describing a model never fails that way: the models under one provider disagree about which levels they accept, so `resolveModel` reports a profile level the exact model cannot take as no default at all rather than throwing. A throw there would take the whole provider out of every model catalog built over it — one mis-set profile field hiding even the models that do support the level — so a bad configuration surfaces where it is acted on, not where it is described. pi-ai's common stream options represent `off` by omitting `reasoning`. -Supported profile fields are `apiKeyEnv`, `displayName`, `api`, `baseURL`, `models`, `modelOverrides`, `compat`, `defaultContextWindow`, `defaultMaxTokens`, `defaultInput`, `headers`, `reasoning`, `thinkingBudgets`, `cacheRetention`, `transport`, `timeoutMs`, `websocketConnectTimeoutMs`, `streamIdleTimeoutMs`, `maxRequestImageBytes`, `requestImagePixelBudget`, `requestImageMaxBytes`, and `retryPolicy`. Each resolved profile retry policy is captured with that provider route; omission uses the shared bounded normal default of five retries. The stream-idle interval is a positive finite Node timer delay, defaults to five minutes, and covers only an outstanding provider read, not consumer think time. Every image route derives a deterministic request version from the provider-independent normalized attachment under `requestImagePixelBudget` (default 2048 by 2048 total pixels) and `requestImageMaxBytes` (default 1MiB raw bytes). Before reading attachments, `maxRequestImageBytes` applies to conservative request-version upper bounds and replaces the oldest over-budget images with fixed text; exact base64 lengths are checked again after retained versions are generated. The 20MiB default can retain fifteen maximum-size 1MiB versions after base64 expansion while leaving request-body headroom. The same version feeds inline base64, and its stable descriptor exposes the attachment id and actual request-image dimensions. Harness app attribution wins a conflicting configured header name. +Supported profile fields are `apiKeyEnv`, `displayName`, `api`, `baseURL`, `models`, `modelOverrides`, `compat`, `defaultContextWindow`, `defaultMaxTokens`, `defaultInput`, `headers`, `reasoning`, `thinkingBudgets`, `cacheRetention`, `transport`, `timeoutMs`, `websocketConnectTimeoutMs`, `streamIdleTimeoutMs`, `maxRequestImageBytes`, `requestImagePixelBudget`, `requestImageMaxBytes`, and `retryPolicy`. Each resolved profile retry policy is captured with that provider route; omission uses the shared bounded normal default of five retries. The stream-idle interval is a positive finite Node timer delay, defaults to five minutes, and covers only an outstanding provider read, not consumer think time. Every image route derives a deterministic request version from the provider-independent normalized attachment under `requestImagePixelBudget` (default 2048 by 2048 total pixels) and `requestImageMaxBytes` (default 1MiB raw bytes). Before reading attachments, `maxRequestImageBytes` applies to conservative request-version upper bounds and replaces the oldest over-budget images with per-image text; exact base64 lengths are checked again after retained versions are generated. The 20MiB default can retain fifteen 1MiB-target versions after base64 expansion while leaving request-body headroom. The same version feeds inline base64. Its descriptor exposes the attachment id and actual request-image dimensions, plus a normalized-object path only when the attachment provider exposes a host object and the current filesystem maps it into the tool execution world. The path is resolved separately from the request version and its `variantId`. Harness app attribution wins a conflicting configured header name. The adapter forces pi-ai's SDK `maxRetries` to zero so one `stream()` call makes one provider request. The removed profile fields `maxRetries` and `maxRetryDelayMs` fail load instead of silently multiplying or hiding the separately composed agent-level retry budget. Idle expiry aborts the SDK's stable request signal and surfaces `TIMEOUT`; an earlier caller abort remains `ABORTED`. @@ -173,7 +173,7 @@ pi-ai installs several provider SDKs and lazy-loads the one selected by the cata #### What the model sees -The selected catalog model receives `GenerateOptions.system`, history, tools, and sampling fields supported by pi-ai's common streaming API. Each retained image is preceded by stable text naming its complete attachment id and actual request dimensions. When accumulated base64 image payload exceeds the route's `maxRequestImageBytes`, each offloaded image (oldest first) is replaced by fixed text that tells the model to read the file again when a path is available or ask the user to attach it again. Offloaded normalized attachments are not read or transformed. Provider-native replay metadata is restored only when the adapter validates it for the historical content. +The selected catalog model receives `GenerateOptions.system`, history, tools, and sampling fields supported by pi-ai's common streaming API. Each retained image is preceded by text naming its complete attachment id and actual request dimensions. The text includes a normalized-object path when the current execution filesystem maps the attachment provider's host object, marks that path read-only, and warns that normalization or request projection may have resized or re-encoded the upload. When accumulated base64 image payload exceeds the route's `maxRequestImageBytes`, each offloaded image keeps its own identity and access currently resolved for that request in replacement text. Offloaded normalized attachments are not read or transformed. Provider-native replay metadata is restored only when the adapter validates it for the historical content. #### Token effect @@ -181,7 +181,7 @@ Provider tokenization governs exact input. Retained images add the stable attach #### KV Cache effect -Conversion preserves logical request order without adding text, while the selected provider's serialization and replay state determine reuse. Changing adapter instance, provider, model, or any upstream request token may prevent reuse from the first difference. Crossing the image bound rewrites an early message (the newly offloaded image becomes placeholder text), so reuse ends at that message until the offloaded prefix stabilizes. +Conversion preserves logical request order, while image handles and offload placeholders add model-visible text. Stable attachment identity and request bytes do not make that text immutable: a changed execution-world path rewrites a historical handle even without offload and may prevent reuse from that image. Changing adapter instance, provider, model, or any other upstream request token has the same suffix effect. Crossing the image bound replaces an earlier image with placeholder text, so reuse ends at that message until the offloaded prefix stabilizes. ### Provider response diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index 10f366659a..cd40804ce5 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -124,7 +124,7 @@ pi-ai 依据提供方 id 与 baseURL 决定每个请求的形状:系统提示 **没有**这份元数据的模型——条目未声明 `reasoningEfforts` 的手工声明模型,以及 pi-ai 标记为不具备推理能力的 catalog 模型——完全不公开 `reasoning`。pi-ai 会把这类模型报告为只支持 `off` 一档,但 `off` 会被翻译成*省略* reasoning 选项,而那与「不点名任何档位」产出的请求逐字节相同:选它关不掉任何东西,于是自身默认就在思考的提供方,会在界面显示 `off` 被选中的同时继续思考。把该能力报告为不可用,界面就只剩提供方默认这一项,不会再出现自相矛盾的控件。配置 profile 的 `reasoning` 值(包括 `off`)在存在时是部署默认值;省略它会保留提供方默认值。每次请求的 `GenerateOptions.reasoningEffort` 优先;未出现在确切模型能力中的档位会让**请求**在网络 I/O 前以 `UNSUPPORTED_REASONING_EFFORT` 失败,而不会被自动调整。**描述**一个模型则从不这样失败:同一提供方下各模型接受的档位并不一致,因此 `resolveModel` 对该模型拿不下的 profile 档位报告为「没有默认值」,而不是抛错。在那里抛错会让整个提供方从任何基于它构建的模型目录中消失——一个配错的 profile 字段连支持该档位的模型也一并藏起来——所以坏配置暴露在被执行处,而不是被描述处。pi-ai 的通用流选项通过省略 `reasoning` 表示 `off`。 -受支持的 profile 字段是 `apiKeyEnv`、`displayName`、`api`、`baseURL`、`models`、`modelOverrides`、`compat`、`defaultContextWindow`、`defaultMaxTokens`、`defaultInput`、`headers`、`reasoning`、`thinkingBudgets`、`cacheRetention`、`transport`、`timeoutMs`、`websocketConnectTimeoutMs`、`streamIdleTimeoutMs`、`maxRequestImageBytes`、`requestImagePixelBudget`、`requestImageMaxBytes` 和 `retryPolicy`。每条 profile 解析后的重试策略会随该提供方路由一同捕获;省略时使用共享的有界 normal 默认值并重试五次。流空闲间隔必须是正的有限 Node 定时器延迟,默认为五分钟,且只覆盖未完成提供方读取,不包括消费方思考时间。每条图片路由从提供方无关的规范化附件派生确定性请求版本,受 `requestImagePixelBudget`(默认总像素 2048×2048)和 `requestImageMaxBytes`(默认原始字节 1MiB)约束。读取附件前,`maxRequestImageBytes` 先按请求版本的保守上界替换超预算的最旧图片;保留版本生成后再用确切 base64 长度检查。20MiB 默认值可保留十五个按 1MiB 上限生成的请求版本,并为请求正文留下余量。同一版本用于内联 base64,其稳定描述会公开附件 ID 和实际请求图片尺寸。若已配置标头中有同名项,则以 Harness 应用归因为准。 +受支持的 profile 字段是 `apiKeyEnv`、`displayName`、`api`、`baseURL`、`models`、`modelOverrides`、`compat`、`defaultContextWindow`、`defaultMaxTokens`、`defaultInput`、`headers`、`reasoning`、`thinkingBudgets`、`cacheRetention`、`transport`、`timeoutMs`、`websocketConnectTimeoutMs`、`streamIdleTimeoutMs`、`maxRequestImageBytes`、`requestImagePixelBudget`、`requestImageMaxBytes` 和 `retryPolicy`。每条 profile 解析后的重试策略会随该提供方路由一同捕获;省略时使用共享的有界 normal 默认值并重试五次。流空闲间隔必须是正的有限 Node 定时器延迟,默认为五分钟,且只覆盖未完成提供方读取,不包括消费方思考时间。每条图片路由从提供方无关的规范化附件派生确定性请求版本,受 `requestImagePixelBudget`(默认总像素 2048×2048)和 `requestImageMaxBytes`(默认原始字节 1MiB)约束。读取附件前,`maxRequestImageBytes` 先按请求版本的保守上界把超预算的最旧图片替换为逐图文本;保留版本生成后再用确切 base64 长度检查。20MiB 默认值可保留十五个按 1MiB 目标生成的请求版本,并为请求正文留下余量。同一版本用于内联 base64。对应描述会公开附件 ID 和实际请求图片尺寸;只有附件提供方给出宿主对象且当前文件系统能够将其映射到工具执行环境时,描述才会加入规范化对象路径。该路径独立于请求版本及其 `variantId`。若已配置标头中有同名项,则以 Harness 应用归因为准。 适配器强制 pi-ai SDK `maxRetries` 为零,因此一次 `stream()` 调用只会发起一次提供方请求。已移除 profile 字段 `maxRetries` 和 `maxRetryDelayMs` 会使加载失败,而不是静默倍增或隐藏单独组合的 agent(智能体)级重试预算。空闲超时会 abort SDK 的稳定请求信号,并以 `TIMEOUT` 呈现;较早的调用方 abort 仍为 `ABORTED`。 @@ -174,7 +174,7 @@ pi-ai 会安装多个提供方 SDK,并延迟加载 catalog 模型所选的 SDK #### 模型看到的内容 -所选 catalog 模型会收到 `GenerateOptions.system`、历史、工具,以及 pi-ai 通用流式 API 支持的采样字段。每张保留图片前都有稳定文本,写明完整附件 ID 和实际请求尺寸。请求累积的 base64 图片载荷超过路由的 `maxRequestImageBytes` 时,被 offload 的图片会从最老开始替换为固定文本,要求模型在有路径时重新读取文件,否则请用户重新附上图片。系统不会读取或转换被 offload 的规范化附件。只有当适配器验证提供方原生回放元数据与历史内容匹配时,才会恢复这些元数据。 +所选 catalog 模型会收到 `GenerateOptions.system`、历史、工具,以及 pi-ai 通用流式 API 支持的采样字段。每张保留图片前都有文本,写明完整附件 ID 和实际请求尺寸。当前执行文件系统能够映射附件提供方的宿主对象时,文本还会给出规范化对象路径,将其标记为只读,并说明规范化或请求投影可能缩小或重新编码上传图片。请求累积的 base64 图片载荷超过路由的 `maxRequestImageBytes` 时,每张被 offload 的图片会在替代文本中保留自己的身份和本次请求解析出的访问方式。系统不会读取或转换被 offload 的规范化附件。只有当适配器验证提供方原生回放元数据与历史内容匹配时,才会恢复这些元数据。 #### Token 影响 @@ -182,7 +182,7 @@ pi-ai 会安装多个提供方 SDK,并延迟加载 catalog 模型所选的 SDK #### KV Cache 影响 -转换保留逻辑请求顺序,不添加文本;复用取决于所选提供方的序列化与回放状态。更改适配器实例、提供方、模型或任何上游请求 token,都可能使复用从首个出现差异的 token 起失效。跨过图片上限会改写较早的一条消息(新被 offload 的图片变为占位文本),复用在该消息处截止,直到被 offload 的前缀稳定。 +转换保留逻辑请求顺序,图片句柄和 offload 占位内容会加入模型可见文本。稳定的附件身份和请求字节不能保证这些文本不变:执行环境路径变化会在没有 offload 时改写历史句柄,并可能使复用从该图片起失效。更改适配器实例、提供方、模型或其他上游请求 token 会产生同样的后缀影响。跨过图片上限会把较早图片替换为占位文本,复用在该消息处截止,直到被 offload 的前缀稳定。 ### 提供方响应 diff --git a/packages/llm/llm-pi-ai/package.json b/packages/llm/llm-pi-ai/package.json index d0755b06cc..ce809946be 100644 --- a/packages/llm/llm-pi-ai/package.json +++ b/packages/llm/llm-pi-ai/package.json @@ -35,6 +35,7 @@ "@deepseek-ai/dsh-attachment": "workspace:^", "@deepseek-ai/dsh-authorization": "workspace:^", "@deepseek-ai/dsh-credentials": "workspace:^", + "@deepseek-ai/dsh-fs": "workspace:^", "@deepseek-ai/dsh-launch-environment": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", @@ -50,6 +51,7 @@ "@deepseek-ai/dsh-attachment": "workspace:^", "@deepseek-ai/dsh-authorization": "workspace:^", "@deepseek-ai/dsh-credentials": "workspace:^", + "@deepseek-ai/dsh-fs": "workspace:^", "@deepseek-ai/dsh-launch-environment": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", diff --git a/packages/llm/llm-pi-ai/src/adapter.ts b/packages/llm/llm-pi-ai/src/adapter.ts index 37d4ea48f6..e20b8e0072 100644 --- a/packages/llm/llm-pi-ai/src/adapter.ts +++ b/packages/llm/llm-pi-ai/src/adapter.ts @@ -47,6 +47,7 @@ import { } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, + ImageAttachmentAccess, LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, @@ -55,7 +56,7 @@ import type { ResolvedRetryPolicy, StreamChunk, } from '@deepseek-ai/dsh-llm' -import type { AttachmentStore } from '@deepseek-ai/dsh-attachment' +import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import { idleWatchdog, timeoutOf } from '@deepseek-ai/dsh-timeout' import type { ResolvedPiAiProviderProfile } from './config.ts' import { toPiContext } from './context.ts' @@ -93,6 +94,8 @@ export interface PiAiAdapterOptions { auth: PiAiAuthInjection /** Resolve the optional durable attachment service at request time. */ resolveAttachments?: () => AttachmentStore | undefined + /** Bridge one attachment reference into the current model-tool execution world. */ + resolveImageAccess?: (attachments: AttachmentStore, ref: ImageAttachmentRef) => ImageAttachmentAccess | undefined /** * Observe one assistant history message degrading to provider-neutral * conversion because its stored replay state is unusable by this build. @@ -360,10 +363,15 @@ export class PiAiAdapter extends LlmAdapter { } const context = attachments === undefined ? toPiContext(options, undefined, onReplayDegrade) - : await toPiContext({ ...options, signal: watchdog.signal }, attachments, onReplayDegrade, profile.maxRequestImageBytes, { - maxPixels: profile.requestImagePixelBudget, - maxBytes: profile.requestImageMaxBytes, - }) + : await toPiContext({ ...options, signal: watchdog.signal }, { + attachments, + resolveImageAccess: ref => this.config.resolveImageAccess?.(attachments, ref), + maxRequestImageBytes: profile.maxRequestImageBytes, + requestImagePolicy: { + maxPixels: profile.requestImagePixelBudget, + maxBytes: profile.requestImageMaxBytes, + }, + }, onReplayDegrade) const events = snapshot.models.streamSimple(model, context, { ...profileOptions(profile, reasoning, apiKey), ...options.temperature === undefined ? {} : { temperature: options.temperature }, diff --git a/packages/llm/llm-pi-ai/src/config.ts b/packages/llm/llm-pi-ai/src/config.ts index 28e409e734..e5a7e608b9 100644 --- a/packages/llm/llm-pi-ai/src/config.ts +++ b/packages/llm/llm-pi-ai/src/config.ts @@ -54,7 +54,7 @@ export const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000 export const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024 /** Default total-pixel budget preserves the complete 2048px normalized attachment. */ export const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048 -/** Default raw encoded-byte cap before inline base64 expansion. */ +/** Default raw encoded-byte target before inline base64 expansion; the smallest quality-ladder output is used when no quality fits. */ export const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1024 * 1024 /** Context capacity assumed for a model neither configuration nor the catalog sizes. */ @@ -169,7 +169,10 @@ export interface PiAiProviderProfile { maxRequestImageBytes?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number - /** Raw encoded-byte cap for each deterministic inline request version. */ + /** + * Raw encoded-byte target for each deterministic inline request version; + * the smallest quality-ladder output is used when no quality fits. + */ requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig @@ -190,7 +193,7 @@ export interface ResolvedPiAiProviderProfile maxRequestImageBytes: number /** Positive total-pixel request-version budget after defaulting. */ requestImagePixelBudget: number - /** Positive raw request-version byte cap after defaulting. */ + /** Positive raw request-version byte target after defaulting; the smallest quality-ladder output is used when no quality fits. */ requestImageMaxBytes: number /** Immutable retry policy captured with this provider route. */ retryPolicy: ResolvedRetryPolicy diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index 9faf457c9a..4315cc690e 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -4,8 +4,8 @@ * @module dsh-llm-pi-ai/context */ -import { CallId, contentHasImage, LlmError, offloadRequestImagesWithPolicy, requestImageHandleText } from '@deepseek-ai/dsh-llm' -import type { ContentBlock, GenerateOptions, Message } from '@deepseek-ai/dsh-llm' +import { CallId, contentHasImage, LlmError, offloadedImageText, offloadRequestImagesWithPolicy, requestImageHandleText } from '@deepseek-ai/dsh-llm' +import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message } from '@deepseek-ai/dsh-llm' import type { AttachmentId, AttachmentStore, @@ -48,6 +48,7 @@ function assertSupportedImageRoles(messages: readonly Message[]): void { async function userContent( blocks: readonly ContentBlock[], requestImages: ReadonlyMap, + resolveImageAccess: ImageAttachmentAccessResolver, ): Promise { const content: (TextContent | ImageContent)[] = [] for (const block of blocks) { @@ -57,7 +58,10 @@ async function userContent( break case 'image': { const version = requestImages.get(block.attachment.attachmentId) as RequestImageAttachment - content.push({ type: 'text', text: requestImageHandleText(version) }) + content.push({ + type: 'text', + text: requestImageHandleText(block.attachment, version, resolveImageAccess(block.attachment)), + }) content.push({ type: 'image', data: Buffer.from(version.data).toString('base64'), @@ -67,7 +71,7 @@ async function userContent( } case 'tool-result': { - const nested = await userContent(block.content, requestImages) + const nested = await userContent(block.content, requestImages, resolveImageAccess) if (typeof nested === 'string') { if (nested.length > 0) content.push({ type: 'text', text: nested }) } else { @@ -170,17 +174,29 @@ function textOnlyContext(options: GenerateOptions, onReplayDegrade?: (reason: st return piContext(options, messages) } +/** Inputs that bind deterministic request images to one current tool execution world. */ +export interface PiImageRequestContext { + /** Durable provider that resolves request-image bytes and provider-owned host objects. */ + attachments: AttachmentStore + /** Resolve current tool access separately from deterministic request-image versions. */ + resolveImageAccess: ImageAttachmentAccessResolver + /** Request-level bound on base64-encoded image payload; omission leaves every image in place. */ + maxRequestImageBytes?: number + /** Route pixel and raw encoded-byte budgets. */ + requestImagePolicy?: ImageRequestPolicy +} + /** * Convert text-only harness history to a synchronous pi-ai Context. Tool * result names are recovered from preceding assistant tool calls. * @param options - the harness request; `options.system` maps to pi-ai's single `systemPrompt` slot. - * @param attachments - absent; selects the synchronous conversion. + * @param images - absent; selects the synchronous conversion. * @param onReplayDegrade - forwarded to {@link toPiAssistant} for each assistant message. * @returns the pi-ai context; `tools` is omitted when the request declares none. */ export function toPiContext( options: GenerateOptions, - attachments?: undefined, + images?: undefined, onReplayDegrade?: (reason: string) => void, ): PiContext /** @@ -190,47 +206,42 @@ export function toPiContext( * oldest images are replaced by text placeholders until the request fits, so * an image-heavy session keeps clearing gateway request-size caps. * @param options - the harness request; `options.system` maps to pi-ai's single `systemPrompt` slot. - * @param attachments - durable byte resolver for image references. + * @param images - attachment provider, current path resolver, and request limits. * @param onReplayDegrade - forwarded to {@link toPiAssistant} for each assistant message. - * @param maxRequestImageBytes - request-level bound on base64-encoded image payload; omission leaves every image in place. - * @param requestImagePolicy - route pixel and raw encoded-byte budgets. * @returns the asynchronously resolved pi-ai context. */ export function toPiContext( options: GenerateOptions, - attachments: AttachmentStore, + images: PiImageRequestContext, onReplayDegrade?: (reason: string) => void, - maxRequestImageBytes?: number, - requestImagePolicy?: ImageRequestPolicy, ): Promise export function toPiContext( options: GenerateOptions, - attachments?: AttachmentStore, + images?: PiImageRequestContext, onReplayDegrade?: (reason: string) => void, - maxRequestImageBytes?: number, - requestImagePolicy?: ImageRequestPolicy, ): PiContext | Promise { - return attachments === undefined + return images === undefined ? textOnlyContext(options, onReplayDegrade) - : toPiContextWithImages(options, attachments, onReplayDegrade, maxRequestImageBytes, requestImagePolicy) + : toPiContextWithImages(options, images, onReplayDegrade) } async function toPiContextWithImages( options: GenerateOptions, - attachments: AttachmentStore, + images: PiImageRequestContext, onReplayDegrade?: (reason: string) => void, - maxRequestImageBytes?: number, - requestImagePolicy: ImageRequestPolicy = { +): Promise { + const { attachments, resolveImageAccess, maxRequestImageBytes } = images + const requestImagePolicy = images.requestImagePolicy ?? { maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET, maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES, - }, -): Promise { + } assertSupportedImageRoles(options.messages) const requestMessages = offloadRequestImagesWithPolicy(options.messages, { representation: 'base64', ...maxRequestImageBytes === undefined ? {} : { maxBytes: maxRequestImageBytes }, byteQuantum: 1, byteLength: ref => Math.min(ref.bytes, requestImagePolicy.maxBytes), + placeholder: ref => offloadedImageText(ref, resolveImageAccess(ref)), }) const requestImages = await prepareRequestImages(requestMessages, attachments, requestImagePolicy, options.signal) const exactMessages = offloadRequestImagesWithPolicy(requestMessages, { @@ -238,6 +249,7 @@ async function toPiContextWithImages( ...maxRequestImageBytes === undefined ? {} : { maxBytes: maxRequestImageBytes }, byteQuantum: 1, byteLength: ref => (requestImages.get(ref.attachmentId) as RequestImageAttachment).bytes, + placeholder: ref => offloadedImageText(ref, resolveImageAccess(ref)), }) const toolNames = new Map() const messages: PiMessage[] = [] @@ -260,7 +272,7 @@ async function toPiContextWithImages( } // user role: text + tool results (each result becomes its own message). const regular = message.content.filter(block => block.type !== 'tool-result') - const content = await userContent(regular, requestImages) + const content = await userContent(regular, requestImages, resolveImageAccess) const results = message.content.filter((block): block is Extract => ( block.type === 'tool-result' )) @@ -268,7 +280,7 @@ async function toPiContextWithImages( messages.push({ role: 'user', content, timestamp: 0 }) } for (const result of results) { - const resultContent = await userContent(result.content, requestImages) + const resultContent = await userContent(result.content, requestImages, resolveImageAccess) messages.push({ role: 'toolResult', toolCallId: result.toolCallId, diff --git a/packages/llm/llm-pi-ai/src/index.ts b/packages/llm/llm-pi-ai/src/index.ts index 846509f8c6..c9752b764e 100644 --- a/packages/llm/llm-pi-ai/src/index.ts +++ b/packages/llm/llm-pi-ai/src/index.ts @@ -57,8 +57,9 @@ import type { Context } from '@deepseek-ai/cordis' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import { assertUsableApiKey, LlmError } from '@deepseek-ai/dsh-llm' +import { assertUsableApiKey, LlmError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { AdapterRegistrationHandle, DirectoryRegistrationHandle, LlmConfigurableProvider } from '@deepseek-ai/dsh-llm' +import type {} from '@deepseek-ai/dsh-fs' import { deepEqualJson, installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings' import { PiAiAdapter } from './adapter.ts' import { authContextFrom, credentialStoreFrom } from './auth.ts' @@ -197,6 +198,11 @@ export function apply(ctx: Context, config: Config): void { resolveApiKey, auth, resolveAttachments: () => ctx.get('attachments'), + resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess( + attachments, + hostPath => ctx.get('fs')?.processPathFromHostPath(hostPath), + ref, + ), onReplayDegrade: ({ provider, model, reason }) => { ctx.logger.warn( `llm-pi-ai: unusable replay state on assistant history for route "${provider}/${model}";` diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts index b86f1d93ca..21d5b2c486 100644 --- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts +++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import { AttachmentId, AttachmentStore, ImageVariantId } from '@deepseek-ai/dsh-attachment' import type { ImageAttachmentLimits, @@ -31,6 +31,18 @@ const IMAGE_REF: ImageAttachmentRef = { width: 1, height: 1, } +const HOST_IMAGE_PATH = '/host/.dsh/attachments/objects/aa/object' +const MODEL_IMAGE_PATH = '/model/.dsh/attachments/objects/aa/object' + +class MappedFileSystem extends Service { + constructor(ctx: Context) { + super(ctx, 'fs') + } + + processPathFromHostPath(hostPath: string): string | undefined { + return hostPath === HOST_IMAGE_PATH ? MODEL_IMAGE_PATH : undefined + } +} async function harness(baseURL: string, overrides: Record = {}): Promise { vi.stubEnv('PI_TEST_KEY', 'test-key') @@ -228,7 +240,7 @@ describe('PiAiAdapter provider routing', () => { expect(server.paths).toEqual(['/v1/responses']) }) - it('resolves an attachment service mounted after the adapter when dispatching an image', async () => { + it('resolves attachment and filesystem services mounted after the adapter when dispatching an image', async () => { const server = await mockServer([{ status: 401, body: JSON.stringify({ error: { message: 'expected mock failure' } }) }]) const attachmentId = AttachmentId(`sha256:${'a'.repeat(64)}`) const ref: ImageAttachmentRef = { @@ -281,6 +293,10 @@ describe('PiAiAdapter provider routing', () => { return readImage(value) } + override imageHostPath(_ref: ImageAttachmentRef): string { + return HOST_IMAGE_PATH + } + override readImageRequest( value: ImageAttachmentRef, policy: ImageRequestPolicy, @@ -296,6 +312,7 @@ describe('PiAiAdapter provider routing', () => { providers: { openai: { apiKeyEnv: 'PI_TEST_KEY', baseURL: `${server.url}/v1` } }, }) await ctx.plugin(LateAttachmentStore) + await ctx.plugin(MappedFileSystem) const result = await assemble(ctx, { provider: 'openai', @@ -311,6 +328,7 @@ describe('PiAiAdapter provider routing', () => { maxPixels: 2048 * 2048, maxBytes: 1024 * 1024, }, expect.any(AbortSignal)) + expect(JSON.stringify(server.requests[0])).toContain(MODEL_IMAGE_PATH) expect(server.paths).toEqual(['/v1/responses']) }) diff --git a/packages/llm/llm-pi-ai/tests/context.spec.ts b/packages/llm/llm-pi-ai/tests/context.spec.ts index 026ca2c608..4e6e29c118 100644 --- a/packages/llm/llm-pi-ai/tests/context.spec.ts +++ b/packages/llm/llm-pi-ai/tests/context.spec.ts @@ -6,9 +6,10 @@ import type { ImageRequestPolicy, RequestImageAttachment, } from '@deepseek-ai/dsh-attachment' -import { CallId, createMessage, createUserMessage, OFFLOADED_IMAGE_TEXT } from '@deepseek-ai/dsh-llm' +import { CallId, createMessage, createUserMessage, offloadedImageText } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, Message } from '@deepseek-ai/dsh-llm' import { toPiContext } from '../src/context.ts' +import type { PiImageRequestContext } from '../src/context.ts' import { toPiAssistant } from '../src/replay.ts' const ref: ImageAttachmentRef = { @@ -43,11 +44,18 @@ function projectionStore( Promise.resolve(requestImage(value, Uint8Array.of(1))) )), ): AttachmentStore { - return { readImageRequest } as unknown as AttachmentStore + return { readImageRequest, imageHostPath: () => undefined } as unknown as AttachmentStore } const attachments = projectionStore() +function imageContext( + store: AttachmentStore, + overrides: Partial> = {}, +): PiImageRequestContext { + return { attachments: store, resolveImageAccess: () => undefined, ...overrides } +} + function request(messages: GenerateOptions['messages']): GenerateOptions { return { provider: 'openai', @@ -138,7 +146,7 @@ describe('pi-ai request context conversion', () => { { type: 'image', attachment: ref }, ], }]), - ]), attachments) + ]), imageContext(attachments)) expect(context.messages).toEqual([ { role: 'user', content: '', timestamp: 0 }, @@ -174,6 +182,27 @@ describe('pi-ai request context conversion', () => { ]) }) + it('uses the shared normalized-path description for retained images', async () => { + const named = { ...ref, name: 'chart.png', width: 2048, height: 1024 } + const store = projectionStore(value => Promise.resolve({ + ...requestImage(value, Uint8Array.of(1)), + width: 1130, + height: 565, + })) + const context = await toPiContext(request([user([{ type: 'image', attachment: named }])]), imageContext(store, { + resolveImageAccess: () => ({ readonlyPath: '/tmp/dsh/objects/aa/object' }), + })) + expect(context.messages[0]).toMatchObject({ + role: 'user', + content: [ + { type: 'text', text: expect.stringContaining('Image "chart.png"') as string }, + { type: 'image' }, + ], + }) + expect(JSON.stringify(context.messages[0])).toContain('/tmp/dsh/objects/aa/object') + expect(JSON.stringify(context.messages[0])).toContain('request preview 1130x565px') + }) + it('recursively converts nested tool-result text and images', async () => { const callId = CallId('nested-call') const context = await toPiContext(request([user([{ @@ -191,7 +220,7 @@ describe('pi-ai request context conversion', () => { content: [{ type: 'image', attachment: ref }], }, ], - }])]), attachments) + }])]), imageContext(attachments)) expect(context.messages).toEqual([{ role: 'toolResult', @@ -245,14 +274,14 @@ describe('pi-ai request context conversion', () => { }]), user([{ type: 'image', attachment: sized }, { type: 'text', text: 'newer' }]), user([{ type: 'image', attachment: sized }]), - ]), store, undefined, 8) + ]), imageContext(store, { maxRequestImageBytes: 8 })) expect(context.messages).toEqual([ { role: 'toolResult', toolCallId: 'shot-call', toolName: 'unknown', - content: [{ type: 'text', text: OFFLOADED_IMAGE_TEXT }], + content: [{ type: 'text', text: offloadedImageText(sized) }], isError: false, timestamp: 0, }, @@ -288,12 +317,12 @@ describe('pi-ai request context conversion', () => { const context = await toPiContext(request([user([ { type: 'image', attachment: old }, { type: 'image', attachment: recent }, - ])]), projectionStore(readImageRequest), undefined, 4) + ])]), imageContext(projectionStore(readImageRequest), { maxRequestImageBytes: 4 })) expect(context.messages[0]).toMatchObject({ role: 'user', content: [ - { type: 'text', text: OFFLOADED_IMAGE_TEXT }, + { type: 'text', text: offloadedImageText(old) }, { type: 'text', text: expect.stringContaining(String(recent.attachmentId)) as string }, { type: 'image' }, ], @@ -302,12 +331,34 @@ describe('pi-ai request context conversion', () => { expect(readImageRequest.mock.calls[0]?.[0]).toEqual(recent) }) + it('uses independently resolved access when exact encoded bytes require offload', async () => { + const sized: ImageAttachmentRef = { ...ref, bytes: 3 } + const access = { readonlyPath: '/tmp/dsh-normalized-image' } + const readImageRequest = vi.fn((value: ImageAttachmentRef) => Promise.resolve({ + ...requestImage(value, Uint8Array.of(1, 2, 3, 4)), + })) + + const context = await toPiContext(request([ + user([{ type: 'image', attachment: sized }]), + ]), imageContext(projectionStore(readImageRequest), { + maxRequestImageBytes: 4, + resolveImageAccess: () => access, + })) + + expect(context.messages).toEqual([{ + role: 'user', + content: offloadedImageText(sized, access), + timestamp: 0, + }]) + expect(readImageRequest).toHaveBeenCalledTimes(1) + }) + it('keeps every image at exactly the payload bound and drops all of them when even the newest cannot fit', async () => { const sized: ImageAttachmentRef = { ...ref, bytes: 3 } const exact = await toPiContext(request([ user([{ type: 'image', attachment: sized }]), user([{ type: 'image', attachment: sized }]), - ]), attachments, undefined, 8) + ]), imageContext(attachments, { maxRequestImageBytes: 8 })) expect(exact.messages).toEqual([ { role: 'user', @@ -327,10 +378,10 @@ describe('pi-ai request context conversion', () => { const store = projectionStore(readImageRequest) const oversized = await toPiContext(request([ user([{ type: 'image', attachment: { ...ref, bytes: 300 } }]), - ]), store, undefined, 8) + ]), imageContext(store, { maxRequestImageBytes: 8 })) // All-text content collapses to the string form; the placeholder still reaches the model. expect(oversized.messages).toEqual([ - { role: 'user', content: OFFLOADED_IMAGE_TEXT, timestamp: 0 }, + { role: 'user', content: offloadedImageText({ ...ref, bytes: 300 }), timestamp: 0 }, ]) expect(readImageRequest).not.toHaveBeenCalled() }) @@ -342,16 +393,19 @@ describe('pi-ai request context conversion', () => { Promise.resolve(requestImage(value, Uint8Array.of(1, 2, 3))) )) const store = projectionStore(readImageRequest) - const aliased = await toPiContext(request([user([shared, shared])]), store, undefined, 4) + const aliased = await toPiContext( + request([user([shared, shared])]), + imageContext(store, { maxRequestImageBytes: 4 }), + ) const replayed = await toPiContext(request([user([ { type: 'image', attachment: { ...sized } }, { type: 'image', attachment: { ...sized } }, - ])]), store, undefined, 4) + ])]), imageContext(store, { maxRequestImageBytes: 4 })) const expected = [{ role: 'user', content: [ - { type: 'text', text: OFFLOADED_IMAGE_TEXT }, + { type: 'text', text: offloadedImageText(sized) }, { type: 'text', text: expect.stringContaining(`Image ${sized.attachmentId}`) as string }, { type: 'image', data: 'AQID', mimeType: 'image/png' }, ], @@ -390,7 +444,7 @@ describe('pi-ai request context conversion', () => { const store = projectionStore(readImageRequest) await expect(toPiContext(request([ history(role, [{ type: 'image', attachment: ref }]), - ]), store, undefined, 1)).rejects.toMatchObject({ code: 'UNSUPPORTED_CONTENT' }) + ]), imageContext(store, { maxRequestImageBytes: 1 }))).rejects.toMatchObject({ code: 'UNSUPPORTED_CONTENT' }) expect(readImageRequest).not.toHaveBeenCalled() } @@ -398,7 +452,7 @@ describe('pi-ai request context conversion', () => { history('system', [{ type: 'text', text: 'history system' }]), history('assistant', [{ type: 'text', text: 'answer' }]), user([{ type: 'text', text: 'plain' }]), - ]), attachments)).resolves.toMatchObject({ + ]), imageContext(attachments))).resolves.toMatchObject({ messages: [ { role: 'user', content: 'history system' }, { role: 'assistant' }, diff --git a/packages/llm/llm-pi-ai/tests/convert.spec.ts b/packages/llm/llm-pi-ai/tests/convert.spec.ts index ed4df11a4d..6967ea8fd6 100644 --- a/packages/llm/llm-pi-ai/tests/convert.spec.ts +++ b/packages/llm/llm-pi-ai/tests/convert.spec.ts @@ -63,7 +63,11 @@ function attachmentStore(readImageRequest: ( policy: ImageRequestPolicy, signal?: AbortSignal, ) => Promise): AttachmentStore { - return { readImageRequest } as unknown as AttachmentStore + return { readImageRequest, imageHostPath: () => undefined } as unknown as AttachmentStore +} + +function imageContext(attachments: AttachmentStore) { + return { attachments, resolveImageAccess: () => undefined } } describe('toPiContext', () => { @@ -109,7 +113,7 @@ describe('toPiContext', () => { content: [{ type: 'text', text: 'describe' }, { type: 'image', attachment }], source: { kind: 'plugin', plugin: 'test' }, })], - }, attachmentStore(readImageRequest)) + }, imageContext(attachmentStore(readImageRequest))) expect(readImageRequest).toHaveBeenCalledWith( attachment, @@ -161,7 +165,7 @@ describe('toPiContext', () => { }], source: { kind: 'plugin', plugin: 'test' }, })], - }, attachmentStore(readImageRequest)) + }, imageContext(attachmentStore(readImageRequest))) expect(context.messages).toEqual([{ role: 'toolResult', diff --git a/packages/llm/llm-pi-ai/tsconfig.json b/packages/llm/llm-pi-ai/tsconfig.json index 172dbe8a6e..8200210b6d 100644 --- a/packages/llm/llm-pi-ai/tsconfig.json +++ b/packages/llm/llm-pi-ai/tsconfig.json @@ -26,6 +26,9 @@ { "path": "../../attachment/attachment" }, + { + "path": "../../fs/fs" + }, { "path": "../../credentials/credentials" }, diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml index 08820bbfd9..bec2fe9b81 100644 --- a/packages/llm/llm/README.i18n.yaml +++ b/packages/llm/llm/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/llm/llm/README.md -README.md: 59c5303bdae8d6391f3bb1595a527d677e2378bc -README.zh.md: 313fc23590de2119bf07dd5c4c4fafe9daa94c56 +README.md: ef58516790a2723bce34aa1bbae2e1629050f6a5 +README.zh.md: 8af1240cdb4f3b65f1c0f841ade620c85443129b diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index 59c5303bda..ef58516790 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -57,7 +57,7 @@ Exact-model metadata is a separate correctness query, not a catalog decoration o Message content is an array of typed blocks: `text`, `reasoning`, `image`, `tool-call`, `tool-result`. An `ImageBlock` carries only a durable `ImageAttachmentRef`; provider bytes and request dimensions are resolved later. The union remains merge-extensible through `ContentBlockMap`, so plugins can add further block types via declaration merging. Assistant messages use a model source carrying the provider and model that produced them plus optional adapter-private replay state. Before dispatch, `LlmRuntime` retains that state only when the historical provider route and target provider route are currently owned by the exact same adapter instance; the adapter then decides whether it can restore or convert the state across models/providers. -Every dispatch uses the exact model modalities captured with its adapter generation. An image-capable adapter projects durable image references into route-specific request versions. A text-only route instead receives deterministic attachment placeholders, including nested tool-result images, without changing append-only session history. `offloadRequestImagesWithPolicy()` provides deterministic oldest-first image removal with raw or base64 accounting and count or byte quanta; adapters supply the exact derived-version byte length. +Every dispatch uses the exact model modalities captured with its adapter generation. An image-capable adapter projects durable image references into route-specific request versions. `resolveImageAttachmentAccess()` separately combines an attachment provider's optional host object with a consumer-supplied mapping from that host path into the current tool execution world. The result never enters `RequestImageAttachment` or its `variantId`. A text-only route instead receives deterministic attachment placeholders, including nested tool-result images, without changing append-only session history. `offloadRequestImagesWithPolicy()` provides deterministic oldest-first image removal with raw or base64 accounting and count or byte quanta; adapters supply the exact derived-version byte length and the required per-image placeholder text. Streaming is a raw chunk protocol (`block-start`, `text-delta`, `reasoning-delta`, `tool-call-delta`, `block-end`, `usage`, `finish`). Every adapter outcome reaches consumers as one terminal `finish`; operational failure uses its `error` or `aborted` reason rather than throwing across the stream API. `BlockAssembler` is the single shared implementation that assembles chunks into blocks/messages. A successful `finish` may carry a `ReplayEnvelope` — opaque response-level replay metadata plus optional per-block entries aligned with the emitted block sequence. Assembly makes one keep/drop decision for content and metadata together: a `max-tokens` finish drops tool calls that may have been truncated, and the envelope loses the entry at each dropped position, so stored metadata always describes stored content. @@ -91,11 +91,11 @@ Two adapters implement `LlmAdapter` on different internals: [`@deepseek-ai/dsh-l ## Model Experience -None, as the service adds no model-bound text, schema, or message; it only materializes and logs an adapter-configured reasoning effort. +None, as adapters choose when to add the shared image descriptors and per-image placeholders exported by this package, while the LLM service itself only materializes and logs adapter-configured request facts. #### KV Cache effect -Pass-through; the registry preserves the assembled request prefix, while the selected adapter and provider own cache reuse and routing boundaries. +Reasoning-effort materialization preserves the assembled request prefix. Image identity and request-preview text are deterministic, while the optional execution-world path is resolved for each request. A changed path can alter a historical descriptor and prevent reuse from that image even without offload. Crossing a request limit also replaces an older image with per-image text. ## Known Limitations and Deferred Work diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md index 313fc23590..8af1240cdb 100644 --- a/packages/llm/llm/README.zh.md +++ b/packages/llm/llm/README.zh.md @@ -57,7 +57,7 @@ 消息内容是类型化内容块数组:`text`、`reasoning`、`image`、`tool-call`、`tool-result`。`ImageBlock` 只携带持久 `ImageAttachmentRef`;提供方字节和请求尺寸之后再解析。联合仍从可合并扩展的 `ContentBlockMap` 派生,因此插件可以通过 declaration merging 添加其他块类型。assistant 消息使用模型来源,其中携带生成该消息的提供方和模型,以及可选的适配器私有回放状态。dispatch 前,`LlmRuntime` 只在历史提供方路由与目标提供方路由当前由完全相同的适配器实例拥有时才保留该状态;随后由适配器判定能否在模型或提供方间恢复或转换该状态。 -每次分发都使用随适配器世代捕获的确切模型模态。支持图片的适配器把持久图片引用投影为路由专用请求版本。纯文本路由则收到确定性的附件占位文本,其中也包括嵌套工具结果图片,追加式会话历史不会改变。`offloadRequestImagesWithPolicy()` 提供确定性的从旧到新图片移除,支持按原始字节或 base64 计数,也支持图片数量或字节量步长;适配器提供确切派生版本的字节长度。 +每次分发都使用随适配器世代捕获的确切模型模态。支持图片的适配器把持久图片引用投影为路由专用请求版本。`resolveImageAttachmentAccess()` 单独组合附件提供方可选的宿主对象,以及消费方给出的宿主路径到当前工具执行环境的映射。解析结果不进入 `RequestImageAttachment` 或其 `variantId`。纯文本路由则收到确定性的附件占位文本,其中也包括嵌套工具结果图片,追加式会话历史不会改变。`offloadRequestImagesWithPolicy()` 提供确定性的从旧到新图片移除,支持按原始字节或 base64 计数,也支持图片数量或字节量步长;适配器提供确切派生版本的字节长度和必填的逐图占位文本。 流式输出是原始分片协议(`block-start`、`text-delta`、`reasoning-delta`、`tool-call-delta`、`block-end`、`usage`、`finish`)。每个适配器结果都以一个终止 `finish` 到达消费方;运行故障使用 `error` 或 `aborted` 作为结束原因,而不会跨流 API 抛出。`BlockAssembler` 是将分片组装为块/消息的唯一共享实现。成功的 `finish` 可以携带 `ReplayEnvelope`——不透明的响应级回放元数据,加上与发射块序列对齐的可选逐块条目。组装对内容与元数据只做一次保留/丢弃决定:`max-tokens` 结束会丢弃可能被截断的工具调用,数据在每个被丢弃的位置同步失去对应条目,因此存储的元数据始终描述存储的内容。 @@ -93,11 +93,11 @@ ## 模型体验 -无。服务不添加任何与模型绑定的文本、schema 或消息;它只会填入并记录适配器配置的推理强度。 +无。适配器决定何时加入该包导出的共用图片描述和逐图占位文本,LLM 服务本身只会填入并记录适配器配置的请求事实。 #### KV Cache 影响 -透传;注册表保留已组装请求前缀,cache 复用与路由边界属于所选适配器和提供方。 +推理强度填入不会改变已组装的请求前缀。图片身份和请求预览文本具有确定性,可选的执行环境路径则按请求解析。路径变化会改写历史图片描述,即使没有 offload,也可能使缓存从该图片起无法复用。请求越过上限时,较旧图片也会替换为逐图文本。 diff --git a/packages/llm/llm/src/content.ts b/packages/llm/llm/src/content.ts index 4620275429..ed97a9b6f1 100644 --- a/packages/llm/llm/src/content.ts +++ b/packages/llm/llm/src/content.ts @@ -2,15 +2,72 @@ import type { ContentBlock } from './types.ts' import type { Message } from './message.ts' -import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' +import type { AttachmentStore, ImageAttachmentRef, ImageMediaType, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' +import { assertNever } from './never.ts' -/** Model-facing stand-in for an image removed to fit a provider request bound. */ -export const OFFLOADED_IMAGE_TEXT - = '[image omitted to keep the request within its image limit; older images are omitted first. If this image is still needed, read its file again when a path is available; otherwise ask the user to attach it again.]' +/** Execution-world path that model tools can use to read one normalized attachment. */ +export interface ImageAttachmentAccess { + /** Absolute path to immutable normalized bytes; callers must treat it as read-only. */ + readonlyPath: string +} + +/** + * Resolve current execution-world access for one durable image reference. + * @param ref - durable normalized attachment reference. + * @returns a read-only execution-world path, or undefined when unavailable. + */ +export type ImageAttachmentAccessResolver = (ref: ImageAttachmentRef) => ImageAttachmentAccess | undefined + +/** + * Bridge one attachment provider's host object location into the mounted + * tool execution world. The consumer supplies the current filesystem + * provider's mapping without making attachment or LLM definitions depend on it. + * @param attachments - provider that owns the normalized attachment object. + * @param mapHostPath - map one absolute host path into the current tool execution world. + * @param ref - durable normalized attachment reference. + * @returns a read-only execution-world path, or undefined when either provider exposes no mapping. + * @throws an attachment error when the durable reference is invalid. + */ +export function resolveImageAttachmentAccess( + attachments: AttachmentStore, + mapHostPath: (hostPath: string) => string | undefined, + ref: ImageAttachmentRef, +): ImageAttachmentAccess | undefined { + const hostPath = attachments.imageHostPath(ref) + if (hostPath === undefined) return undefined + const readonlyPath = mapHostPath(hostPath) + return readonlyPath === undefined ? undefined : { readonlyPath } +} + +function quoted(value: string): string { + return JSON.stringify(value) +} + +function imageIdentity(ref: ImageAttachmentRef): string { + return ref.name === undefined + ? String(ref.attachmentId) + : `${quoted(ref.name)} (${ref.attachmentId})` +} + +function extension(mediaType: ImageMediaType): string { + switch (mediaType) { + case 'image/png': return '.png' + case 'image/jpeg': return '.jpg' + case 'image/webp': return '.webp' + case 'image/gif': return '.gif' + default: return assertNever(mediaType, 'image extension') + } +} + +function normalizedAccessText(ref: ImageAttachmentRef, access: ImageAttachmentAccess): string { + return ` Normalized copy (read-only; may be resized or re-encoded): ${quoted(access.readonlyPath)} (${ref.width}x${ref.height}px, ${ref.mediaType}).` + + ' Source dimensions, format, and byte size may differ.' + + ` Copy to a writable path ending in ${extension(ref.mediaType)} before editing.` +} /** * Stable text shown to a model that cannot accept one durable image reference. - * @param ref - durable master reference omitted from the request. + * @param ref - durable normalized attachment omitted from the request. * @returns deterministic text-only placeholder. */ export function textOnlyImageText(ref: ImageAttachmentRef): string { @@ -19,12 +76,41 @@ export function textOnlyImageText(ref: ImageAttachmentRef): string { } /** - * Stable model-facing handle for one exact request image. + * Stable model-facing handle for one exact request image. Identity comes from + * the occurrence's own durable reference: request versions are prepared per + * attachment id, so one shared version may serve occurrences whose display + * names differ. + * @param ref - the occurrence's durable normalized attachment. * @param version - exact request image shown beside the text. + * @param access - optional path resolved for the current tool execution world. * @returns attachment handle and request-image dimensions. */ -export function requestImageHandleText(version: RequestImageAttachment): string { - return `Image ${version.attachment.attachmentId}; request image ${version.width}x${version.height}px.` +export function requestImageHandleText( + ref: ImageAttachmentRef, + version: RequestImageAttachment, + access?: ImageAttachmentAccess, +): string { + const preview = `Image ${imageIdentity(ref)}; request preview ${version.width}x${version.height}px.` + return access === undefined + ? `${preview} It may be resized or re-encoded; source dimensions, format, and byte size may differ.` + : preview + normalizedAccessText(ref, access) +} + +/** + * Stable per-image placeholder for a request-limit omission. + * @param ref - durable normalized attachment omitted from this request. + * @param access - optional provider-resolved path for model tools. + * @returns identity, normalized metadata, and the available recovery path. + */ +export function offloadedImageText( + ref: ImageAttachmentRef, + access?: ImageAttachmentAccess, +): string { + const identity = `image omitted to fit request image limits; ${imageIdentity(ref)}.` + if (access === undefined) { + return `[${identity} No local normalized image path is available; ask the user to attach it again if needed.]` + } + return `[${identity}${normalizedAccessText(ref, access)}]` } /** @@ -57,8 +143,10 @@ export interface RequestImageOffloadPolicy { byteQuantum?: number /** Whether byte accounting uses raw file bytes or inline base64 length. */ representation: 'raw' | 'base64' - /** Resolve the encoded request-version length; omission uses master attachment bytes. */ + /** Resolve the encoded request-version length; omission uses normalized attachment bytes. */ byteLength?: (ref: ImageAttachmentRef) => number + /** Build the model-visible replacement for each omitted attachment. */ + placeholder: (ref: ImageAttachmentRef) => string } /** Collect represented image lengths in request and nested-block order. */ @@ -83,17 +171,18 @@ function collectImageLengths( function replaceOldestImages( blocks: readonly ContentBlock[], remaining: { count: number }, + placeholder: (ref: ImageAttachmentRef) => string, ): ContentBlock[] { let next: ContentBlock[] | undefined for (const [index, block] of blocks.entries()) { if (block.type === 'image' && remaining.count > 0) { remaining.count -= 1 next ??= blocks.slice(0, index) - next.push({ type: 'text', text: OFFLOADED_IMAGE_TEXT }) + next.push({ type: 'text', text: placeholder(block.attachment) }) continue } if (block.type === 'tool-result') { - const content = replaceOldestImages(block.content, remaining) + const content = replaceOldestImages(block.content, remaining, placeholder) if (content !== block.content) { next ??= blocks.slice(0, index) next.push({ ...block, content }) @@ -140,26 +229,6 @@ export function projectImagesForTextModel(messages: readonly Message[]): readonl }) } -/** - * Return transient request messages whose oldest images are replaced until - * their accumulated base64 payload fits the configured bound. The selection - * is deterministic from durable message order and attachment metadata; a - * provider can serialize the returned messages without reading omitted bytes. - * @param messages - complete request history, oldest first. - * @param maxRequestImageBytes - positive bound on total base64 image payload; undefined preserves every image. - * @returns the original messages when they already fit, otherwise shallow message copies with replaced content trees. - */ -export function offloadRequestImages( - messages: readonly Message[], - maxRequestImageBytes: number | undefined, -): readonly Message[] { - return offloadRequestImagesWithPolicy(messages, { - representation: 'base64', - ...maxRequestImageBytes === undefined ? {} : { maxBytes: maxRequestImageBytes }, - byteQuantum: 1, - }) -} - /** * Return a deterministic transient projection whose oldest images are replaced * in whole count and byte quanta after a route budget is exceeded. The target @@ -196,7 +265,7 @@ export function offloadRequestImagesWithPolicy( } const remaining = { count } return messages.map((message) => { - const content = replaceOldestImages(message.content, remaining) + const content = replaceOldestImages(message.content, remaining, policy.placeholder) return content === message.content ? message : { ...message, content } }) } diff --git a/packages/llm/llm/tests/content.spec.ts b/packages/llm/llm/tests/content.spec.ts index 6a0eb02c63..3391423bdb 100644 --- a/packages/llm/llm/tests/content.spec.ts +++ b/packages/llm/llm/tests/content.spec.ts @@ -1,18 +1,31 @@ import { describe, expect, it } from 'vitest' -import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { AttachmentId, ImageVariantId } from '@deepseek-ai/dsh-attachment' +import type { AttachmentStore, ImageMediaType } from '@deepseek-ai/dsh-attachment' import { CallId, createUserMessage, - OFFLOADED_IMAGE_TEXT, - offloadRequestImages, + offloadedImageText, offloadRequestImagesWithPolicy, projectImagesForTextModel, + resolveImageAttachmentAccess, + requestImageHandleText, } from '../src/index.ts' -import type { ContentBlock } from '../src/index.ts' +import type { ContentBlock, Message } from '../src/index.ts' const source = { kind: 'plugin' as const, plugin: 'test' } -function image(bytes: number): ContentBlock { +const OMITTED = '[omitted]' + +function offloadBase64(messages: readonly Message[], maxBytes: number | undefined): readonly Message[] { + return offloadRequestImagesWithPolicy(messages, { + representation: 'base64', + ...maxBytes === undefined ? {} : { maxBytes }, + byteQuantum: 1, + placeholder: () => OMITTED, + }) +} + +function image(bytes: number): Extract { return { type: 'image', attachment: { @@ -25,15 +38,15 @@ function image(bytes: number): ContentBlock { } } -describe('offloadRequestImages', () => { +describe('base64 request-image offload', () => { it('preserves every image when no payload bound is configured', () => { const messages = [createUserMessage({ content: [image(300)], source })] - expect(offloadRequestImages(messages, undefined)).toBe(messages) + expect(offloadBase64(messages, undefined)).toBe(messages) }) it('preserves the original request when its base64 payload fits exactly', () => { const messages = [createUserMessage({ content: [image(3), image(3)], source })] - expect(offloadRequestImages(messages, 8)).toBe(messages) + expect(offloadBase64(messages, 8)).toBe(messages) }) it('keeps five 3 MiB images at 20 MiB and offloads the oldest after one more raw byte', () => { @@ -43,14 +56,14 @@ describe('offloadRequestImages', () => { content: Array.from({ length: 5 }, () => image(rawImageBytes)), source, })] - expect(offloadRequestImages(exact, maxRequestImageBytes)).toBe(exact) + expect(offloadBase64(exact, maxRequestImageBytes)).toBe(exact) const over = [createUserMessage({ content: [image(rawImageBytes + 1), ...Array.from({ length: 4 }, () => image(rawImageBytes))], source, })] - expect(offloadRequestImages(over, maxRequestImageBytes)[0]?.content).toEqual([ - { type: 'text', text: OFFLOADED_IMAGE_TEXT }, + expect(offloadBase64(over, maxRequestImageBytes)[0]?.content).toEqual([ + { type: 'text', text: OMITTED }, ...Array.from({ length: 4 }, () => image(rawImageBytes)), ]) }) @@ -69,12 +82,12 @@ describe('offloadRequestImages', () => { createUserMessage({ content: [shared, image(3)], source }), ] - const fitted = offloadRequestImages(messages, 8) + const fitted = offloadBase64(messages, 8) expect(fitted).not.toBe(messages) expect(fitted[0]?.content).toEqual([{ type: 'tool-result', toolCallId: CallId('shot'), - content: [{ type: 'text', text: OFFLOADED_IMAGE_TEXT }], + content: [{ type: 'text', text: OMITTED }], }]) expect(fitted[1]?.content).toEqual([shared, image(3)]) expect(messages[0]?.content[0]).toMatchObject({ type: 'tool-result', content: [shared] }) @@ -82,8 +95,8 @@ describe('offloadRequestImages', () => { it('replaces a single image that cannot fit', () => { const messages = [createUserMessage({ content: [image(300)], source })] - expect(offloadRequestImages(messages, 8)[0]?.content) - .toEqual([{ type: 'text', text: OFFLOADED_IMAGE_TEXT }]) + expect(offloadBase64(messages, 8)[0]?.content) + .toEqual([{ type: 'text', text: OMITTED }]) }) it('keeps unchanged nested content while replacing a later image', () => { @@ -93,9 +106,9 @@ describe('offloadRequestImages', () => { content: [{ type: 'text' as const, text: 'kept' }], } const messages = [createUserMessage({ content: [nested, image(3)], source })] - expect(offloadRequestImages(messages, 1)[0]?.content).toEqual([ + expect(offloadBase64(messages, 1)[0]?.content).toEqual([ nested, - { type: 'text', text: OFFLOADED_IMAGE_TEXT }, + { type: 'text', text: OMITTED }, ]) }) }) @@ -109,6 +122,7 @@ describe('offloadRequestImagesWithPolicy', () => { representation: 'raw', maxBytes: 128 * mib, byteQuantum: 64 * mib, + placeholder: () => OMITTED, })[0]?.content expect(project(128)?.filter(block => block.type === 'image')).toHaveLength(128) @@ -124,6 +138,7 @@ describe('offloadRequestImagesWithPolicy', () => { representation: 'raw', maxImages: 600, countQuantum: 20, + placeholder: () => OMITTED, }) expect(projected[0]?.content.filter(block => block.type === 'text')).toHaveLength(20) expect(projected[0]?.content.filter(block => block.type === 'image')).toHaveLength(581) @@ -135,12 +150,160 @@ describe('offloadRequestImagesWithPolicy', () => { representation: 'raw', maxBytes: 3, byteLength: () => 2, + placeholder: () => OMITTED, }) expect(projected[0]?.content).toEqual([ - { type: 'text', text: OFFLOADED_IMAGE_TEXT }, + { type: 'text', text: OMITTED }, image(100), ]) }) + + it('builds a distinct placeholder from each omitted attachment', () => { + const first = image(3) + const second = image(3) + first.attachment = { ...first.attachment, name: 'first.png' } + second.attachment = { ...second.attachment, name: 'second.png' } + const projected = offloadRequestImagesWithPolicy([ + createUserMessage({ content: [first, second], source }), + ], { + representation: 'raw', + maxBytes: 3, + placeholder: ref => `omitted:${ref.name}`, + }) + expect(projected[0]?.content).toEqual([ + { type: 'text', text: 'omitted:first.png' }, + second, + ]) + }) +}) + +describe('model-facing image access', () => { + it('describes the request preview, immutable normalized path, and source uncertainty', () => { + const attachment = { + attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), + mediaType: 'image/png' as const, + bytes: 4_000, + width: 2048, + height: 1536, + name: 'source "map".png', + } + const access = { readonlyPath: '/tmp/.dsh/attachments/v1/objects/bb/object' } + const version = { + variantId: ImageVariantId(`sha256:${'c'.repeat(64)}`), + attachment, + data: Uint8Array.of(1), + mediaType: 'image/png' as const, + bytes: 1, + width: 923, + height: 692, + depth: 'uchar' as const, + space: 'srgb' as const, + hasAlpha: true, + } + expect(requestImageHandleText(attachment, version, access)).toBe( + `Image "source \\"map\\".png" (${attachment.attachmentId}); request preview 923x692px.` + + ' Normalized copy (read-only; may be resized or re-encoded): "/tmp/.dsh/attachments/v1/objects/bb/object" (2048x1536px, image/png).' + + ' Source dimensions, format, and byte size may differ.' + + ' Copy to a writable path ending in .png before editing.', + ) + }) + + it('bridges a provider host object only through the mounted filesystem mapping', () => { + const attachment = image(1).attachment + const attachments = { + imageHostPath: () => '/host/.dsh/attachments/object', + } as unknown as AttachmentStore + const mapped = (hostPath: string): string | undefined => hostPath === '/host/.dsh/attachments/object' + ? '/workspace/.attachments/object' + : undefined + expect(resolveImageAttachmentAccess( + attachments, + mapped, + attachment, + )).toEqual({ readonlyPath: '/workspace/.attachments/object' }) + expect(resolveImageAttachmentAccess( + attachments, + () => undefined, + attachment, + )).toBeUndefined() + expect(resolveImageAttachmentAccess( + { imageHostPath: () => undefined } as unknown as AttachmentStore, + mapped, + attachment, + )).toBeUndefined() + }) + + it('names each occurrence from its own reference when one prepared version is shared', () => { + const attachment = { + attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), + mediaType: 'image/png' as const, + bytes: 4_000, + width: 8, + height: 8, + name: 'second.png', + } + const version = { + variantId: ImageVariantId(`sha256:${'c'.repeat(64)}`), + attachment, + data: Uint8Array.of(1), + mediaType: 'image/png' as const, + bytes: 1, + width: 8, + height: 8, + depth: 'uchar' as const, + space: 'srgb' as const, + hasAlpha: false, + } + expect(requestImageHandleText({ ...attachment, name: 'first.png' }, version)) + .toContain('"first.png"') + }) + + it('keeps a useful omission identity with and without a local path', () => { + const ref = { + attachmentId: AttachmentId(`sha256:${'d'.repeat(64)}`), + mediaType: 'image/jpeg' as const, + bytes: 10, + width: 10, + height: 5, + name: 'photo.jpg', + } + expect(offloadedImageText(ref)).toContain('No local normalized image path is available') + expect(offloadedImageText(ref, { readonlyPath: '/tmp/object' })).toBe( + `[image omitted to fit request image limits; "photo.jpg" (${ref.attachmentId}).` + + ' Normalized copy (read-only; may be resized or re-encoded): "/tmp/object" (10x5px, image/jpeg).' + + ' Source dimensions, format, and byte size may differ.' + + ' Copy to a writable path ending in .jpg before editing.]', + ) + }) + + it.each([ + ['image/png', '.png'], + ['image/jpeg', '.jpg'], + ['image/webp', '.webp'], + ['image/gif', '.gif'], + ] as const)('names the writable extension for %s', (mediaType, suffix) => { + const ref = { + attachmentId: AttachmentId(`sha256:${'e'.repeat(64)}`), + mediaType, + bytes: 1, + width: 1, + height: 1, + } + expect(offloadedImageText(ref, { readonlyPath: '/tmp/object' })) + .toContain(`writable path ending in ${suffix}`) + }) + + it('rejects a media type that escaped the closed union at runtime', () => { + const ref = { + attachmentId: AttachmentId(`sha256:${'e'.repeat(64)}`), + mediaType: 'image/tiff' as unknown as ImageMediaType, + bytes: 1, + width: 1, + height: 1, + } + expect(() => offloadedImageText(ref, { readonlyPath: '/tmp/object' })) + .toThrow('unreachable variant in image extension: "image/tiff"') + }) }) describe('projectImagesForTextModel', () => { diff --git a/packages/preset/agent-presets/README.i18n.yaml b/packages/preset/agent-presets/README.i18n.yaml index 42601edbd4..a4f3fed8d6 100644 --- a/packages/preset/agent-presets/README.i18n.yaml +++ b/packages/preset/agent-presets/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/preset/agent-presets/README.md -README.md: e204868e43ba07b78eff31293cc33cf790ff0085 -README.zh.md: f11fa5f092b9d4de1abb5c1464b6931d749c2970 +README.md: 3e92f02518c5a36412c9448a26d32958c217f79c +README.zh.md: 4600589749a063df924f9c961cc449506ba2af9f diff --git a/packages/preset/agent-presets/README.md b/packages/preset/agent-presets/README.md index e204868e43..3e92f02518 100644 --- a/packages/preset/agent-presets/README.md +++ b/packages/preset/agent-presets/README.md @@ -16,7 +16,7 @@ Discovery is unmemoized: `list()` and `resolve()` re-read the roots on every cal - `ctx.agentPresets.mount(agentCtx, id?): Promise` Compose one agent from a preset — ensure its standing mount (single-flight) and parent the agent's scope key to it — returning the preset for the caller to record. Refuses a broken preset up front with its discovery-reported reason, so every unloadable shape fails the same way before the loader is involved. - `ctx.agentPresets.composeFrom(agentCtx, parentCtx): string | undefined` Join one agent to the standing composition another already runs on, returning the preset id joined — `undefined` when the parent joined none, which is the rosterless deployment and not an error. A bind rather than a mount, so it is synchronous and has no composition failure mode; it still rejects a caller error (an unscoped context, or an agent that already joined). - `ctx.agentPresets.composedPreset(agentCtx): string | undefined` The preset one LIVE agent runs on, read from its scope chain rather than from its session — the only answer available for an agent whose durable header is still being built. -- `ctx.agentPresets.recompose(agentCtx, id): Promise` Re-link one agent to a different preset's standing composition. Valid only while the agent has produced nothing — **the caller owns that check**; the new mount is ensured before the link moves, so a failure leaves the agent as it was. Refuses a broken preset like `mount()`. +- `ctx.agentPresets.recompose(agentCtx, id): Promise` Re-link one agent to a different preset's standing composition. Valid only while the agent has produced nothing — **the caller owns that check**; the new mount is ensured before the link moves, so a failure leaves the agent as it was. A committed re-link emits `tools/change`, because the Agent's resolved tool set changed without a registry entry changing. Refuses a broken preset like `mount()`. - `ctx.agentPresets.standingKeyFor(id?): Promise` The standing scope key a host reader with no agent (a cold transcript read) resolves preset registrations in; ensures the mount without starting an agent, session, or turn. Refuses a broken preset like `mount()`. - `ctx.agentPresets.roots: readonly PresetRoot[]` The roots this roster scans — every configured root in order, then the derived harness-home root. Not `config.roots`: read this to answer whether a roster is composed at all, so one derivation decides it. - `ctx.agentPresets.authorable: boolean` Whether any of those roots has `user` trust, and therefore whether a preset can be created at all. diff --git a/packages/preset/agent-presets/README.zh.md b/packages/preset/agent-presets/README.zh.md index f11fa5f092..4600589749 100644 --- a/packages/preset/agent-presets/README.zh.md +++ b/packages/preset/agent-presets/README.zh.md @@ -16,7 +16,7 @@ - `ctx.agentPresets.mount(agentCtx, id?): Promise` 用一个 preset 组装一个 agent——确保其常驻挂载(并发去重)并把 agent 的 scope key 认父到它——返回该 preset 供调用方记录。对损坏的 preset 直接以发现时记下的原因拒绝,所以每种不可加载的形态都在加载器介入之前以同一方式失败。 - `ctx.agentPresets.composeFrom(agentCtx, parentCtx): string | undefined` 让一个 agent 加入另一个 agent 已在运行的常驻组装,返回所加入的 preset id——父方未加入任何 preset 时返回 `undefined`,那是无 roster 的部署,不是错误。这是认父而非挂载,因此同步、且自身没有组装失败模式;调用方用错(上下文无 scope、agent 已加入过)仍会拒绝。 - `ctx.agentPresets.composedPreset(agentCtx): string | undefined` 某个**活着的** agent 正在运行的 preset,从其 scope 链读取而不是从其会话读取——对于持久化 header 尚在构建中的 agent,这是唯一能拿到的答案。 -- `ctx.agentPresets.recompose(agentCtx, id): Promise` 把一个 agent 重链到另一个 preset 的常驻组装。仅在该 agent 尚无任何产出时合法——**由调用方负责该检查**;新挂载在链移动之前确保完成,失败时 agent 原封不动。与 `mount()` 一样拒绝损坏的 preset。 +- `ctx.agentPresets.recompose(agentCtx, id): Promise` 把一个 agent 重链到另一个 preset 的常驻组装。仅在该 agent 尚无任何产出时合法——**由调用方负责该检查**;新挂载在链移动之前确保完成,失败时 agent 原封不动。重链提交后会发出 `tools/change`,因为 Agent 解析到的工具集已经变化、但注册表条目本身没有增删。与 `mount()` 一样拒绝损坏的 preset。 - `ctx.agentPresets.standingKeyFor(id?): Promise` 没有 agent 的宿主读取方(冷读记录)解析 preset 注册所用的常驻 scope key;确保挂载而不启动任何 agent、会话或轮次。与 `mount()` 一样拒绝损坏的 preset。 - `ctx.agentPresets.roots: readonly PresetRoot[]` 本 roster 实际扫描的根目录——全部已配置根目录按序在前,随后是推导出的 harness home 根目录。它不是 `config.roots`:判断「是否已组装 roster」应读它,从而由同一处推导决定。 - `ctx.agentPresets.authorable: boolean` 上述根目录中是否有任一具备 `user` 信任级别,因而 preset 是否可创建。 diff --git a/packages/preset/agent-presets/package.json b/packages/preset/agent-presets/package.json index dfdf08cbbe..a20ab0a87c 100644 --- a/packages/preset/agent-presets/package.json +++ b/packages/preset/agent-presets/package.json @@ -48,6 +48,7 @@ "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-settings": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/cordis": "workspace:^" }, "dependencies": { diff --git a/packages/preset/agent-presets/presets/code/agent.cordis.yml b/packages/preset/agent-presets/presets/code/agent.cordis.yml index 9fa2b2fa00..e3bbe8fad2 100644 --- a/packages/preset/agent-presets/presets/code/agent.cordis.yml +++ b/packages/preset/agent-presets/presets/code/agent.cordis.yml @@ -189,8 +189,13 @@ config: provider: spawn toolName: subagent + modelSelectionSettings: true backgroundMode: continuable + # Fork omits model selection so provider/model stay equal to the parent and + # the inherited history remains eligible for KV Cache reuse. This preset + # keeps fork continuable and accepts its child-scoped `report` additions invalidating + # that prefix; issue #2124 tracks cache-preserving continuable fork. - id: tool-subagent-fork name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/preset/agent-presets/presets/cordis/agent.cordis.yml b/packages/preset/agent-presets/presets/cordis/agent.cordis.yml index c7b2935137..96cd7e6b09 100644 --- a/packages/preset/agent-presets/presets/cordis/agent.cordis.yml +++ b/packages/preset/agent-presets/presets/cordis/agent.cordis.yml @@ -176,8 +176,13 @@ config: provider: spawn toolName: subagent + modelSelectionSettings: true backgroundMode: continuable + # Fork omits model selection so provider/model stay equal to the parent and + # the inherited history remains eligible for KV Cache reuse. This preset + # keeps fork continuable and accepts its child-scoped `report` additions invalidating + # that prefix; issue #2124 tracks cache-preserving continuable fork. - id: tool-subagent-fork name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/preset/agent-presets/presets/standard/agent.cordis.yml b/packages/preset/agent-presets/presets/standard/agent.cordis.yml index 408c0184a0..3916d6bf3e 100644 --- a/packages/preset/agent-presets/presets/standard/agent.cordis.yml +++ b/packages/preset/agent-presets/presets/standard/agent.cordis.yml @@ -188,8 +188,13 @@ config: provider: spawn toolName: subagent + modelSelectionSettings: true backgroundMode: continuable + # Fork omits model selection so provider/model stay equal to the parent and + # the inherited history remains eligible for KV Cache reuse. This preset + # keeps fork continuable and accepts its child-scoped `report` additions invalidating + # that prefix; issue #2124 tracks cache-preserving continuable fork. - id: tool-subagent-fork name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/preset/agent-presets/src/index.ts b/packages/preset/agent-presets/src/index.ts index e22dee7275..8f44e2003c 100644 --- a/packages/preset/agent-presets/src/index.ts +++ b/packages/preset/agent-presets/src/index.ts @@ -27,6 +27,8 @@ import z from '@deepseek-ai/schemastery' import { bindScopeParent, createScope, scopeOf, type Scope, type ScopeKey, type ScopeParentBinding } from '@deepseek-ai/dsh-scope' // Type-only: resolves the `agent/created` lifecycle event this service watches. import type {} from '@deepseek-ai/dsh-agent' +// Type-only: resolves the registry notification emitted after scope reparenting. +import type {} from '@deepseek-ai/dsh-tools' import { settingsNamespace, type SettingsScope, type default as SettingsService } from '@deepseek-ai/dsh-settings' import { dshHomePath } from '@deepseek-ai/dsh-home-paths' import { discoverPresets, SHIPPED_PRESET_ROOT, USER_PRESET_DIR } from './discovery.ts' @@ -455,7 +457,9 @@ export class AgentPresets extends Service { * state to restore. The re-link runs through the binding this roster kept * from the agent's mount — dsh-scope's only re-link authority. An agent * that never composed one has nothing to re-link: the switch is then the - * agent's first bind, exactly a mount. + * agent's first bind, exactly a mount. A committed re-link emits + * `tools/change` because changing the parent scope changes the Agent's + * resolved tool set without adding or removing registry entries. * @param agentCtx - the agent's scope context. * @param id - the preset to compose the agent from instead. * @returns the preset now installed. @@ -474,6 +478,14 @@ export class AgentPresets extends Service { } else { binding.rebind(standing.key) } + // Reparenting changes every scope-layered tool view without adding or + // removing a registration. Publish the registry's normal invalidation so + // Agent-owned overlays can reconcile with the new ancestry. + try { + this.ctx.emit('tools/change') + } catch (error: unknown) { + this.ctx.logger.warn(`agent-presets: tools/change listener failed after recomposing an Agent: ${String(error)}`) + } return preset } diff --git a/packages/preset/agent-presets/tests/mount.spec.ts b/packages/preset/agent-presets/tests/mount.spec.ts index 5b22e26ec6..83f6da3102 100644 --- a/packages/preset/agent-presets/tests/mount.spec.ts +++ b/packages/preset/agent-presets/tests/mount.spec.ts @@ -484,6 +484,27 @@ describe('replacing a composition', () => { expect(toolNames(ctx)).toEqual([]) }) + it('notifies tool views after reparenting and contains notification failures', async () => { + const handle = await ctx.agents.create({ + sessionId: SessionId('sess-tool-change'), + setup: async (agentCtx: Context) => void await ctx.agentPresets.mount(agentCtx, 'standard'), + }) + await ctx.agentPresets.standingKeyFor('minimal') + let changes = 0 + const stopCounting = ctx.on('tools/change', () => { changes += 1 }) + await ctx.agentPresets.recompose(handle.agent.ctx, 'minimal') + expect(changes).toBe(1) + stopCounting() + + const warnings: string[] = [] + ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn + const stopThrowing = ctx.on('tools/change', () => { throw new Error('listener failed') }) + await expect(ctx.agentPresets.recompose(handle.agent.ctx, 'standard')).resolves.toMatchObject({ id: 'standard' }) + expect(ctx.agentPresets.composedPreset(handle.agent.ctx)).toBe('standard') + expect(warnings).toEqual([expect.stringContaining('tools/change listener failed')]) + stopThrowing() + }) + it('leaves the agent on its previous composition when the new one is unknown', async () => { const handle = await ctx.agents.create({ sessionId: SessionId('sess-unknown'), diff --git a/packages/preset/agent-presets/tsconfig.json b/packages/preset/agent-presets/tsconfig.json index 405ca21e2b..b40cf776ad 100644 --- a/packages/preset/agent-presets/tsconfig.json +++ b/packages/preset/agent-presets/tsconfig.json @@ -30,6 +30,9 @@ { "path": "../../core/system-prompt" }, + { + "path": "../../core/tools" + }, { "path": "../../settings/settings" }, diff --git a/packages/sdk/README.i18n.yaml b/packages/sdk/README.i18n.yaml index 05788b05a5..e46b9b6698 100644 --- a/packages/sdk/README.i18n.yaml +++ b/packages/sdk/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/sdk/README.md -README.md: 663fa95dc56ecd71c7a2639b6edb45caacbab860 -README.zh.md: 0343ad477f9fa522666cd8d4440bfe645f309c2e +README.md: 7227e9c2c93b3f870d0affc74471d7801f37d4ef +README.zh.md: 3b6f5556cb539abafd1a1e8c866f09a44a2d2f1a diff --git a/packages/sdk/README.md b/packages/sdk/README.md index 663fa95dc5..7227e9c2c9 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -2,11 +2,10 @@ English | [中文](README.zh.md) -This group contains the protocol stack for driving a Harness runtime from another process. The TypeScript client launches the matching `dsh` CLI with a named profile and ordered patches; the private Python carrier preserves the current packaged direct-config runtime until Python moves through the same profile path. The [TypeScript SDK decision](../../.agents/notes/implemented/feature/2026-07-27-typescript-sdk-and-sdk-subagent-backend.md) owns the client contract, and the [toolchain removal](../../.agents/notes/implemented/simplification/2026-08-11-remove-sdk-project-toolchain.md) owns the product boundary. +This group contains the protocol stack for driving a Harness runtime from another process. The TypeScript and Python clients both launch `dsh` with a named profile and ordered patches; no package in this group defines a separate application. The [TypeScript SDK decision](../../.agents/notes/implemented/feature/2026-07-27-typescript-sdk-and-sdk-subagent-backend.md) owns the client contract, and the [Python profile-runtime decision](../../.agents/notes/implemented/architecture/2026-08-23-python-sdk-dsh-profile-runtime.md) owns the packaged Python launch. | Package | Role | |---|---| | [`protocol/`](protocol/README.md) | Defines the SDK runtime wire protocol | | [`client/`](client/README.md) | Drives a Harness runtime through the TypeScript client API | | [`server/`](server/README.md) | Serves out-of-process SDK clients over stdio JSON-RPC | -| [`python-runtime/`](python-runtime/README.md) | Private direct-config carrier for the temporarily unchanged Python SDK runtime | diff --git a/packages/sdk/README.zh.md b/packages/sdk/README.zh.md index 0343ad477f..3b6f5556cb 100644 --- a/packages/sdk/README.zh.md +++ b/packages/sdk/README.zh.md @@ -2,11 +2,10 @@ [English](README.md) | 中文 -本组包含用于从另一进程驱动 Harness 运行时的协议栈。TypeScript 客户端通过具名 profile 与有序 patch 启动匹配版本的 `dsh` CLI;私有 Python 载体在 Python 迁移到同一 profile 路径之前,保留当前打包后的直读配置运行时。[TypeScript SDK 决策](../../.agents/notes/implemented/feature/2026-07-27-typescript-sdk-and-sdk-subagent-backend.zh.md)负责客户端约定,[工具链移除](../../.agents/notes/implemented/simplification/2026-08-11-remove-sdk-project-toolchain.zh.md)负责产品边界。 +本组包含用于从另一进程驱动 Harness 运行时的协议栈。TypeScript 与 Python 客户端都通过具名 profile 与有序 patch 启动 `dsh`;本组没有任何包定义独立应用。[TypeScript SDK 决策](../../.agents/notes/implemented/feature/2026-07-27-typescript-sdk-and-sdk-subagent-backend.zh.md)负责客户端约定,[Python profile 运行时决策](../../.agents/notes/implemented/architecture/2026-08-23-python-sdk-dsh-profile-runtime.zh.md)负责打包后的 Python 启动。 | 包 | 职责 | |---|---| | [`protocol/`](protocol/README.zh.md) | 定义 SDK 运行时通信协议 | | [`client/`](client/README.zh.md) | 通过 TypeScript 客户端 API 驱动 Harness 运行时 | | [`server/`](server/README.zh.md) | 通过 stdio JSON-RPC 为进程外 SDK 客户端提供服务 | -| [`python-runtime/`](python-runtime/README.zh.md) | 为暂时保持不变的 Python SDK 运行时提供私有直读配置载体 | diff --git a/packages/sdk/python-runtime/README.md b/packages/sdk/python-runtime/README.md deleted file mode 100644 index 291ad3edaf..0000000000 --- a/packages/sdk/python-runtime/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# @deepseek-ai/dsh-sdk-python-runtime - -English | [中文](README.zh.md) - -Private direct-config carrier for the temporarily unchanged Python SDK runtime. Its [`jsonrpc`](../server/README.md) entry serves SDK clients over newline-delimited stdio, while an external `cordis.yml` composes the spine, backends, and serving plugin. This npm package exposes no public bin and is not published; the Python SDK's existing `dsh-jsonrpc-agent-pkg--` [single-executable runtime](../../../.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md) packages `lib/packaged-bin.js` from the closed deploy tree. Bare plugins resolve from that tree, while relative plugins remain configuration-relative. - -## Config discovery - -The first non-empty channel wins: `$DSH_CORDIS_CONFIG`, then positional `argv[2]`. If neither names an existing file, the packaged entry prints one-line usage to stderr and exits 1; there is no working-directory or built-in fallback. [`dsh-app-boot`](../../boot/app-boot/README.md) makes plugin load failures fatal. This protocol does not use `DSH_SNAPSHOT`. - -A config without `dsh-sdk-jsonrpc-server` is valid and serves nothing; the carrier does not designate a server plugin. - -## Exit lifecycle - -stdin EOF and `SIGTERM` dispose the root to quiescence and exit 0; `SIGINT` exits 130 after the same disposal. EOF may cut off an in-flight turn as documented in the [distribution Agent Note](../../../.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md). The `jsonrpc` plugin owns response-before-exit protocol shutdown; both paths are idempotent and safe to race. - -## stdout is the protocol - -stdout carries only JSON-RPC frames. The carrier and boot guards diagnose on stderr, and the config must omit stdout loggers. - -## Model Experience - -Indirectly, through the plugins loaded from the external `cordis.yml`, which own every model-bound prompt, schema, message, and result; this carrier adds none of its own. - -#### KV Cache effect - -No direct invalidation; the named consumer owns any request-prefix changes. - -## Known Limitations and Deferred Work - -- **Temporary direct-config exception** — this private carrier remains outside `dsh --profile sdk` only to preserve the current Python executable and wheel behavior; the later Python runtime migration deletes it and then renames the executable family. -- **The carrier cannot prove that the config serves JSON-RPC** — a valid config with no `dsh-sdk-jsonrpc-server` entry boots successfully and serves nothing. -- **No built-in or default config exists** — every launch must provide `DSH_CORDIS_CONFIG` or a positional path, and deployment owns the complete plugin tree and stdout discipline. -- **stdin EOF cuts off in-flight work** — client disappearance disposes the root immediately; callers that need orderly completion use the protocol-level `shutdown` request. diff --git a/packages/sdk/python-runtime/README.zh.md b/packages/sdk/python-runtime/README.zh.md deleted file mode 100644 index 54001ccfff..0000000000 --- a/packages/sdk/python-runtime/README.zh.md +++ /dev/null @@ -1,34 +0,0 @@ -# @deepseek-ai/dsh-sdk-python-runtime - -[English](README.md) | 中文 - -这是为暂时保持不变的 Python SDK 运行时提供的私有直读配置载体。其 [`jsonrpc`](../server/README.zh.md) 入口通过按换行分隔的 stdio 为 SDK 客户端提供服务,外部 `cordis.yml` 则负责组合主干、后端和服务插件。该 npm 包不公开 bin,也不会发布;Python SDK 既有的 `dsh-jsonrpc-agent-pkg--` [单文件可执行运行时](../../../.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md)从封闭部署树打包 `lib/packaged-bin.js`。裸插件从该树解析,相对插件仍以配置目录为基准。 - -## 配置发现 - -第一个非空通道生效:先 `$DSH_CORDIS_CONFIG`,再位置参数 `argv[2]`。如果二者都没有指向现有文件,打包入口会向 stderr 打印单行用法并以 1 退出;没有工作目录回退或内置回退。[`dsh-app-boot`](../../boot/app-boot/README.zh.md) 会使插件加载失败成为致命错误。此协议不使用 `DSH_SNAPSHOT`。 - -不含 `dsh-sdk-jsonrpc-server` 的配置仍然有效,只是不提供任何服务;该载体不会指定服务器插件。 - -## 退出生命周期 - -stdin EOF 和 `SIGTERM` 会 dispose(释放资源)根上下文,等待完全停稳后以 0 退出;`SIGINT` 完成同样的 dispose 后以 130 退出。EOF 可能按[分发 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md) 所述截断正在处理的轮次。`jsonrpc` 插件拥有先响应再退出的协议关闭流程;两条路径均幂等,即使发生竞态也安全。 - -## stdout 是协议 - -stdout 只承载 JSON-RPC 帧。该载体和启动守卫在 stderr 上输出诊断,配置必须省略 stdout logger。 - -## 模型体验 - -模型体验由外部 `cordis.yml` 加载的插件间接提供;这些插件负责所有面向模型的提示词、schema、消息和结果,该载体不添加任何内容。 - -#### KV Cache 影响 - -不会直接失效;由上述消费方负责请求前缀的任何变更。 - -## 已知限制与暂缓事项 - -- **临时直读配置例外**:为了保持当前 Python 可执行文件与 wheel 包行为不变,该私有载体暂时不经过 `dsh --profile sdk`;后续 Python 运行时迁移会删除它,之后再重命名可执行文件族。 -- **载体无法证明配置提供 JSON-RPC 服务**:不含 `dsh-sdk-jsonrpc-server` 条目的有效配置也能成功启动,但不会提供任何服务。 -- **不存在内置或默认配置**:每次启动都必须提供 `DSH_CORDIS_CONFIG` 或位置路径;部署方负责完整的插件树和 stdout 纪律。 -- **stdin EOF 会截断正在处理的工作**:客户端消失时立即释放根上下文;需要有序完成的调用方应使用协议级 `shutdown` 请求。 diff --git a/packages/sdk/python-runtime/package.json b/packages/sdk/python-runtime/package.json deleted file mode 100644 index cdae65348f..0000000000 --- a/packages/sdk/python-runtime/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "@deepseek-ai/dsh-sdk-python-runtime", - "description": "Private direct-config runtime carrier for the temporarily unchanged Python SDK", - "version": "0.1.1-rc.2", - "private": true, - "repository": { - "type": "git", - "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/sdk/python-runtime" - }, - "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" - }, - "./packaged-bin": { - "types": "./lib/types/packaged-bin.d.ts", - "default": "./lib/packaged-bin.js" - }, - "./src/*": "./src/*", - "./package.json": "./package.json" - }, - "files": [ - "lib/index.js", - "lib/invariant.js", - "lib/packaged-bin.js", - "lib/types/**/*.d.ts" - ], - "license": "MIT", - "dependencies": { - "@deepseek-ai/dsh-app-boot": "workspace:^" - }, - "peerDependencies": { - "@deepseek-ai/dsh-invariants": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" - }, - "devDependencies": { - "@deepseek-ai/dsh-invariants": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" - } -} diff --git a/packages/sdk/python-runtime/src/index.ts b/packages/sdk/python-runtime/src/index.ts deleted file mode 100644 index 74dabd87bf..0000000000 --- a/packages/sdk/python-runtime/src/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Private Python SDK runtime carrier: its packaged entry discovers an external - * `cordis.yml` and owns process exit. This module exports no composition plugin; - * the config chooses whether to load the - * {@link @deepseek-ai/dsh-sdk-jsonrpc-server} serving plugin. - * - * @module @deepseek-ai/dsh-sdk-python-runtime - */ - -export {} diff --git a/packages/sdk/python-runtime/src/packaged-bin.ts b/packages/sdk/python-runtime/src/packaged-bin.ts deleted file mode 100644 index 1c5e5c3e92..0000000000 --- a/packages/sdk/python-runtime/src/packaged-bin.ts +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env node -/** - * Closed-runtime JSON-RPC agent bin. Bare plugins resolve from the installed - * runtime closure while relative plugins remain configuration-relative. - * - * @module @deepseek-ai/dsh-sdk-python-runtime/packaged-bin - */ - -import { runPythonSdkRuntime } from './runner.ts' - -/* v8 ignore next -- exercised through the built Python runtime carriers */ -await runPythonSdkRuntime(import.meta.url) diff --git a/packages/sdk/python-runtime/src/runner.ts b/packages/sdk/python-runtime/src/runner.ts deleted file mode 100644 index 9850c64a0b..0000000000 --- a/packages/sdk/python-runtime/src/runner.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Process lifecycle for the Python SDK's closed direct-config runtime. - * - * @module @deepseek-ai/dsh-sdk-python-runtime/runner - */ - -import { existsSync } from 'node:fs' -import { boot, installFailLoud, loadEnv, resolveConfigPath } from '@deepseek-ai/dsh-app-boot' - -/* v8 ignore start -- composition over tested app-boot/jsonrpc and executable acceptance paths */ -const NAME = 'dsh-jsonrpc-agent' - -/** - * Boot the explicitly selected external configuration and own process exit. - * @param bareModuleBaseUrl - installed-runtime base for bare plugins. - * @returns after process handlers are installed; process lifetime then belongs - * to stdin and signal events. - */ -export async function runPythonSdkRuntime(bareModuleBaseUrl: string): Promise { - installFailLoud(NAME) - loadEnv(NAME) - - // Env wins over argv; empty values are absent. External config defines the deployment. - const fromEnv = process.env['DSH_CORDIS_CONFIG'] - const fromArgv = process.argv[2] - const requested = fromEnv !== undefined && fromEnv !== '' - ? fromEnv - : fromArgv !== undefined && fromArgv !== '' ? fromArgv : undefined - const configPath = requested === undefined ? undefined : resolveConfigPath(requested, undefined) - if (configPath === undefined || !existsSync(configPath)) { - process.stderr.write( - `usage: ${NAME} (or set DSH_CORDIS_CONFIG=, which wins); the config is required — there is no built-in fallback\n`, - ) - process.exit(1) - } - - const ctx = await boot(NAME, configPath, undefined, undefined, bareModuleBaseUrl) - let exiting = false - - async function disposeAndExit(code: number): Promise { - if (exiting) return - exiting = true - try { - await ctx.fiber.dispose() - } finally { - process.exit(code) - } - } - - process.stdin.on('end', () => { void disposeAndExit(0) }) - process.on('SIGTERM', () => { void disposeAndExit(0) }) - process.on('SIGINT', () => { void disposeAndExit(130) }) -} -/* v8 ignore stop */ diff --git a/packages/sdk/python-runtime/tsdown.config.ts b/packages/sdk/python-runtime/tsdown.config.ts deleted file mode 100644 index 9b6d5d33a7..0000000000 --- a/packages/sdk/python-runtime/tsdown.config.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { defineConfig } from 'tsdown' - -/** Builds each published entry as a self-contained file admitted by the package whitelist. */ -export default defineConfig([ - { - entry: ['lib/types/index.js'], outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', - fixedExtension: false, outputOptions: { codeSplitting: false }, dts: false, clean: false, - }, - { - entry: ['lib/types/invariant.js'], outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', - fixedExtension: false, outputOptions: { codeSplitting: false }, dts: false, clean: false, - }, - { - entry: ['lib/types/packaged-bin.js'], outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', - fixedExtension: false, outputOptions: { codeSplitting: false }, dts: false, clean: false, - }, -]) diff --git a/packages/sdk/server/README.i18n.yaml b/packages/sdk/server/README.i18n.yaml index adf84f76c4..3ffdb5d1e4 100644 --- a/packages/sdk/server/README.i18n.yaml +++ b/packages/sdk/server/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/sdk/server/README.md -README.md: e3deaa5288eb94d64a7f5a8425a829e3eed8896e -README.zh.md: a7273e9b4efbfae8e849205ea86b4c0c90588f7c +README.md: 2fac60b9313c66a8eb1653adb02405f2f5fe4b08 +README.zh.md: ed2c18f0a2ee96fdacdf0d998314d349f0b0264b diff --git a/packages/sdk/server/README.md b/packages/sdk/server/README.md index e3deaa5288..2fac60b931 100644 --- a/packages/sdk/server/README.md +++ b/packages/sdk/server/README.md @@ -2,15 +2,15 @@ English | [中文](README.zh.md) -The `jsonrpc` plugin serves newline-delimited JSON-RPC over stdio so out-of-process SDK clients can drive harness agents. [`HarnessSdkJsonRpcServer`](src/server.ts) owns the protocol methods and notifications; the transport and the named wire types live in [`dsh-sdk-protocol`](../protocol/README.md), shared with the client SDKs. The TypeScript client receives this server through `dsh --profile sdk`; the private [Python runtime carrier](../python-runtime/README.md) temporarily supplies a direct-config application around it. +The `jsonrpc` plugin serves newline-delimited JSON-RPC over stdio so out-of-process SDK clients can drive harness agents. [`HarnessSdkJsonRpcServer`](src/server.ts) owns the protocol methods and notifications; the transport and the named wire types live in [`dsh-sdk-protocol`](../protocol/README.md), shared with the client SDKs. TypeScript and Python clients receive this server through `dsh --profile sdk` or another profile that mounts the same row. ## Wiring -`inject: ['agents']`. The server gets or creates one agent per `sessionId`. It forwards subagent completions only when the service-snapshotted lifecycle `local` flag is true; provider names, child ids, and durable lineage never establish locality. A registered adapter wins, an unowned `deepseek-official` route mounts `dsh-llm-deepseek`, and any other unowned provider fails initialization. Other capabilities come from the surrounding `cordis.yml`. +`inject: ['agents']`. The server gets or creates one agent per `sessionId`. It forwards subagent completions only when the service-snapshotted lifecycle `local` flag is true; provider names, child ids, and durable lineage never establish locality. A registered adapter wins, an unowned `deepseek-official` route mounts `dsh-llm-deepseek`, and any other unowned provider fails initialization. Other capabilities come from the surrounding Loader composition. ## Config -`maxTokensAsSuccess` defaults to `false` and affects only the deployment-mapped status on `subagent.finished`; root-session prompts have no prompt-level status. `JsonRpcConfig.input`, `output`, and `exit` are runtime-only transport hooks; production uses process stdio and `process.exit`. +`maxTokensAsSuccess` defaults to `false` and affects only the deployment-mapped status on `subagent.finished`; root-session prompts have no prompt-level status. Optional `toolFilter.allow` and `toolFilter.deny` restrict each SDK-created root agent through `ctx.tools.restrict()`. An allow list excludes later global tool registrations that it does not name, so a fixed SDK deployment cannot silently gain model-facing tools when its base bundle expands. Unknown names and an empty filter fail when the first session is created. `JsonRpcConfig.input`, `output`, and `exit` are runtime-only transport hooks; production uses process stdio and `process.exit`. ## stdout is the protocol @@ -22,7 +22,7 @@ The plugin answers `shutdown`, flushes the response, disposes the root context s ## Wire notes -`initialize` is the runtime-readiness boundary: when the server is mounted by a Loader composition, it waits for the current plugin tree to settle before replying, so async sibling capabilities such as initial MCP tool discovery are visible to the first prompt. Hand-built contexts without Loader remain immediately usable. `initialize.serverInfo.name` is the wire-stable `deepseek-harness-sdk-runtime`. An optional positive `initialize.maxTokens` becomes the request output cap of each SDK-created agent and its in-process descendants; invalid values reject initialization, while omission sends no SDK cap and allows the selected adapter or provider route default to apply. `session/prompt` queues one identified user message and immediately returns `{ messageId }`. The server streams every durable fact as `session.event` and every whole-agent lifecycle transition as `session.status`; it does not assign an assistant message or `turn/end` to that prompt. Independent requests may enqueue more work on the same session. Persistence roots and persona come from `cordis.yml`. +`initialize` is the runtime-readiness boundary: when the server is mounted by a Loader composition, it waits for the current plugin tree to settle before replying, so async sibling capabilities such as initial MCP tool discovery are visible to the first prompt. Hand-built contexts without Loader remain immediately usable. `initialize.serverInfo.name` is the wire-stable `deepseek-harness-sdk-runtime`. An optional positive `initialize.maxTokens` becomes the request output cap of each SDK-created agent and its in-process descendants; invalid values reject initialization, while omission sends no SDK cap and allows the selected adapter or provider route default to apply. `session/prompt` queues one identified user message and immediately returns `{ messageId }`. The server streams every durable fact as `session.event` and every whole-agent lifecycle transition as `session.status`; it does not assign an assistant message or `turn/end` to that prompt. Independent requests may enqueue more work on the same session. Persistence roots and persona come from the surrounding composition. ## Model Experience @@ -30,7 +30,7 @@ The plugin answers `shutdown`, flushes the response, disposes the root context s #### What the model sees -For each accepted `session/prompt`, the conversation model receives the caller-supplied `contentBlocks` verbatim as one user message in that SDK session. This package adds no system-prompt prose or tool schema; those come from the plugins in the surrounding `cordis.yml`. +For each accepted `session/prompt`, the conversation model receives the caller-supplied `contentBlocks` verbatim as one user message in that SDK session. This package adds no system-prompt prose or tool schema; those come from the other plugins in the composition. A configured `toolFilter` projects that composition's global tool registry before the request is assembled and executed. #### Token effect diff --git a/packages/sdk/server/README.zh.md b/packages/sdk/server/README.zh.md index a7273e9b4e..ed2c18f0a2 100644 --- a/packages/sdk/server/README.zh.md +++ b/packages/sdk/server/README.zh.md @@ -2,15 +2,15 @@ [English](README.md) | 中文 -`jsonrpc` 插件通过 stdio 提供以换行符分隔的 JSON-RPC,使进程外 SDK 客户端能够驱动 harness agent(智能体)。[`HarnessSdkJsonRpcServer`](src/server.ts) 负责协议方法和通知;传输与具名协议类型位于 [`dsh-sdk-protocol`](../protocol/README.zh.md),与客户端 SDK 共享。TypeScript 客户端通过 `dsh --profile sdk` 获得该服务器;私有 [Python 运行时载体](../python-runtime/README.zh.md)暂时为其提供直读配置应用。 +`jsonrpc` 插件通过 stdio 提供以换行符分隔的 JSON-RPC,使进程外 SDK 客户端能够驱动 harness agent(智能体)。[`HarnessSdkJsonRpcServer`](src/server.ts) 负责协议方法和通知;传输与具名协议类型位于 [`dsh-sdk-protocol`](../protocol/README.zh.md),与客户端 SDK 共享。TypeScript 与 Python 客户端都通过 `dsh --profile sdk` 或挂载同一配置项的其他 profile 获得该服务器。 ## 组装 -`inject: ['agents']`。服务器按 `sessionId` 获取或创建一个 agent。只有服务对生命周期建立快照时记录的 `local` 标志为 true,服务器才会转发 subagent 完成事件;提供方名称、子级 id 和持久化谱系均不能证明本地性。已注册的适配器优先;尚无适配器负责的 `deepseek-official` 路由会挂载 `dsh-llm-deepseek`,任何其他尚无适配器负责的提供方都会导致初始化失败。其他能力由外围 `cordis.yml` 提供。 +`inject: ['agents']`。服务器按 `sessionId` 获取或创建一个 agent。只有服务对生命周期建立快照时记录的 `local` 标志为 true,服务器才会转发 subagent 完成事件;提供方名称、子级 id 和持久化谱系均不能证明本地性。已注册的适配器优先;尚无适配器负责的 `deepseek-official` 路由会挂载 `dsh-llm-deepseek`,任何其他尚无适配器负责的提供方都会导致初始化失败。其他能力由外围 Loader 组合提供。 ## 配置 -`maxTokensAsSuccess` 默认为 `false`,且只影响 `subagent.finished` 上由部署映射的状态;根会话提示词没有提示词级状态。`JsonRpcConfig.input`、`output` 和 `exit` 是仅供运行时使用的传输钩子;生产环境使用进程 stdio 和 `process.exit`。 +`maxTokensAsSuccess` 默认为 `false`,且只影响 `subagent.finished` 上由部署映射的状态;根会话提示词没有提示词级状态。可选的 `toolFilter.allow` 与 `toolFilter.deny` 通过 `ctx.tools.restrict()` 限制每个由 SDK 创建的根 agent。Allow 列表会排除之后出现但未指名的全局工具,因此固定的 SDK 部署不会在基础 bundle 扩展时静默获得面向模型的新工具。未知名称与空筛选器会在创建首个会话时明确失败。`JsonRpcConfig.input`、`output` 和 `exit` 是仅供运行时使用的传输钩子;生产环境使用进程 stdio 和 `process.exit`。 ## stdout 即协议 @@ -22,7 +22,7 @@ Stdout 只承载 JSON-RPC 帧。部署不得组合 stdout logger;诊断应写 ## 协议说明 -`initialize` 是运行时就绪边界:服务器由 Loader 组合挂载时,会等待当前插件树完成所有加载任务后再响应,因此首次提示词能够看到 MCP 初始工具发现等异步同级能力。没有 Loader 的手工组装上下文仍可立即使用。`initialize.serverInfo.name` 的协议稳定值为 `deepseek-harness-sdk-runtime`。可选的正整数 `initialize.maxTokens` 会成为每个 SDK 创建的 agent 及其进程内后代的请求输出上限;非法值会使初始化失败,省略时则不发送 SDK 上限,并应用所选适配器或提供方路由的默认值。`session/prompt` 将一条带标识的用户消息排入队列,并立即返回 `{ messageId }`。服务器将每个持久事实作为 `session.event` 流式发出,并将整个 agent 生命周期的每次状态转换作为 `session.status` 发出;它不会把某条助手消息或 `turn/end` 归属于该提示词。同一会话上的独立请求可以继续排入更多工作。持久化根目录和 persona 由 `cordis.yml` 提供。 +`initialize` 是运行时就绪边界:服务器由 Loader 组合挂载时,会等待当前插件树完成所有加载任务后再响应,因此首次提示词能够看到 MCP 初始工具发现等异步同级能力。没有 Loader 的手工组装上下文仍可立即使用。`initialize.serverInfo.name` 的协议稳定值为 `deepseek-harness-sdk-runtime`。可选的正整数 `initialize.maxTokens` 会成为每个 SDK 创建的 agent 及其进程内后代的请求输出上限;非法值会使初始化失败,省略时则不发送 SDK 上限,并应用所选适配器或提供方路由的默认值。`session/prompt` 将一条带标识的用户消息排入队列,并立即返回 `{ messageId }`。服务器将每个持久事实作为 `session.event` 流式发出,并将整个 agent 生命周期的每次状态转换作为 `session.status` 发出;它不会把某条助手消息或 `turn/end` 归属于该提示词。同一会话上的独立请求可以继续排入更多工作。持久化根目录和 persona 由外围组合提供。 ## 模型体验 @@ -30,7 +30,7 @@ Stdout 只承载 JSON-RPC 帧。部署不得组合 stdout logger;诊断应写 #### 模型看到的内容 -对于每个已接受的 `session/prompt`,对话模型会将调用方提供的 `contentBlocks` 原样作为该 SDK 会话中的一条用户消息接收。此包不会添加系统提示词文本或工具 schema;这些内容来自外围 `cordis.yml` 中的插件。 +对于每个已接受的 `session/prompt`,对话模型会将调用方提供的 `contentBlocks` 原样作为该 SDK 会话中的一条用户消息接收。此包不会添加系统提示词文本或工具 schema;这些内容来自组合中的其他插件。配置的 `toolFilter` 会在请求组装与执行前投影该组合的全局工具注册表。 #### Token 影响 diff --git a/packages/sdk/server/src/index.ts b/packages/sdk/server/src/index.ts index 963b4fb3bd..17e9d3a89f 100644 --- a/packages/sdk/server/src/index.ts +++ b/packages/sdk/server/src/index.ts @@ -25,6 +25,13 @@ export const inject = ['agents'] export interface JsonRpcConfig { /** Report max-token turn/subagent termination as a successful SDK result. */ maxTokensAsSuccess?: boolean + /** Per-root-agent model-facing tool filter; an allow list excludes later unnamed global tools. */ + toolFilter?: { + /** Global tool names that remain visible. */ + allow?: string[] + /** Global tool names removed from visibility. */ + deny?: string[] + } /** Transport input override; production uses `process.stdin`. */ input?: Readable /** Transport output override; production uses `process.stdout`. */ @@ -35,6 +42,11 @@ export interface JsonRpcConfig { export const Config: Schema = Schema.object({ maxTokensAsSuccess: Schema.boolean().default(false), + // Preserve omission; Schemastery's materialized empty object is not a valid restriction. + toolFilter: Schema.object({ + allow: Schema.array(Schema.string()).default(undefined as unknown as string[]), + deny: Schema.array(Schema.string()).default(undefined as unknown as string[]), + }).default(undefined as unknown as { allow: string[]; deny: string[] }), }) /** @@ -59,6 +71,7 @@ export function apply(ctx: Context, config: JsonRpcConfig): void { const transport = new JsonRpcLineTransport(input, output) const server = new HarnessSdkJsonRpcServer(ctx, transport, { maxTokensAsSuccess: resolvedConfig.maxTokensAsSuccess, + ...resolvedConfig.toolFilter === undefined ? {} : { toolFilter: resolvedConfig.toolFilter }, }) // Share one exit task so racing shutdown requests cannot dispose the root or diff --git a/packages/sdk/server/src/server.ts b/packages/sdk/server/src/server.ts index ccc3b6192d..a2ec97d9f4 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -13,6 +13,7 @@ import { carrierKeyOf, type Scoped } from '@deepseek-ai/dsh-scope' import { SessionId } from '@deepseek-ai/dsh-session' import type SubagentRuntime from '@deepseek-ai/dsh-subagent' import type { SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent' +import type { ToolRestriction } from '@deepseek-ai/dsh-tools' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import type { InitializeParams, @@ -38,6 +39,8 @@ function subagentParentOf(carrier: Scoped): Agent { export interface HarnessSdkJsonRpcServerOptions { /** Report max-token termination as an accepted result instead of an infrastructure error. */ maxTokensAsSuccess?: boolean + /** Restrict each SDK-created root agent to an explicit subset of global tools. */ + toolFilter?: ToolRestriction } function successStatus(reason: string, options: HarnessSdkJsonRpcServerOptions): 'ok' | 'error' { @@ -220,6 +223,7 @@ export class HarnessSdkJsonRpcServer { // rows in the host plane, so this agent reads them from the global layer. A // deployment that configures a roster has to join one here first // (@deepseek-ai/dsh-agent-presets README, "Composing a child agent"). + const toolFilter = this.options.toolFilter const handle = await this.ctx.agents.create({ sessionId: SessionId(sessionId), meta: { cwd: this.cwd }, @@ -228,6 +232,9 @@ export class HarnessSdkJsonRpcServer { model: this.model, ...this.maxTokens === undefined ? {} : { maxTokens: this.maxTokens }, }, + ...toolFilter === undefined + ? {} + : { setup: (agentCtx: Context) => { agentCtx.tools.restrict(toolFilter) } }, }) const rec: SessionRecord = { handle } this.sessions.set(sessionId, rec) diff --git a/packages/sdk/server/tests/built-scope-carrier.e2e.ts b/packages/sdk/server/tests/built-scope-carrier.e2e.ts index 0aa7099d0b..ae4ab8ef05 100644 --- a/packages/sdk/server/tests/built-scope-carrier.e2e.ts +++ b/packages/sdk/server/tests/built-scope-carrier.e2e.ts @@ -66,7 +66,7 @@ try { const result = Promise.withResolvers(); const unregister = ctx.subagents.registerProvider({ name: "built-local", - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start() { return Promise.resolve({ diff --git a/packages/sdk/server/tests/plugin-apply.spec.ts b/packages/sdk/server/tests/plugin-apply.spec.ts index 28c89c19fe..41954007eb 100644 --- a/packages/sdk/server/tests/plugin-apply.spec.ts +++ b/packages/sdk/server/tests/plugin-apply.spec.ts @@ -11,6 +11,7 @@ import * as agentCore from '@deepseek-ai/dsh-agent-spine-demo' import { LlmAdapter } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import { defineTool } from '@deepseek-ai/dsh-tools' import * as jsonrpc from '../src/index.ts' /** @@ -71,6 +72,7 @@ async function mountPlugin( writeDelayMs?: number failFlush?: boolean beforeServer?: (ctx: Context) => Promise | void + toolFilter?: jsonrpc.JsonRpcConfig['toolFilter'] } = {}, ): Promise { const ctx = new Context() @@ -116,7 +118,12 @@ async function mountPlugin( const exit = (code: number): void => { events.push({ kind: 'exit', code }) } ctx.effect(() => () => { events.push({ kind: 'root-disposed' }) }, 'jsonrpc test root-disposal witness') - const fiber = await ctx.plugin(jsonrpc, { input, output, exit }) + const fiber = await ctx.plugin(jsonrpc, { + input, + output, + exit, + ...options.toolFilter === undefined ? {} : { toolFilter: options.toolFilter }, + }) const frames = (): Record[] => events.flatMap(event => event.kind === 'frame' ? [event.frame] : []) @@ -282,6 +289,51 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => { } }) + it('applies the configured root-agent tool filter through the Loader plugin', async () => { + const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-tool-filter-')) + const llmServer = await mockCompletionServer() + vi.stubEnv('DEEPSEEK_API_KEY', 'test-key') + vi.stubEnv('DEEPSEEK_BASE_URL', llmServer.url) + const harness = await mountPlugin(storageDir, { + toolFilter: { allow: ['kept'] }, + beforeServer: (ctx) => { + for (const name of ['kept', 'excluded']) { + ctx.tools.register(defineTool({ + name, + description: name, + parameters: {}, + output: { + schema: { type: 'string' }, + render: (_args, value) => [{ type: 'text', text: value }], + }, + execute: async () => name, + })) + } + }, + }) + try { + harness.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { cwd: storageDir, provider: 'deepseek-official', model: 'filtered-model' } }) + await harness.waitForFrame(frame => frame.id === 1, 'initialize response') + harness.send({ + jsonrpc: '2.0', + id: 2, + method: 'session/prompt', + params: { sessionId: 'filtered', contentBlocks: [{ type: 'text', text: 'inspect tools' }] }, + }) + await harness.waitForFrame( + frame => frame.method === 'session.status' + && (frame.params as { status?: string } | undefined)?.status === 'idle', + 'filtered session idle status', + ) + + const request = llmServer.requests[0] as { tools?: Array<{ function?: { name?: string } }> } + expect(request.tools?.map(entry => entry.function?.name)).toEqual(['kept']) + } finally { + await harness.dispose() + await rm(storageDir, { recursive: true, force: true }) + } + }) + it('answers shutdown before exiting 0 exactly once, even against a racing second shutdown', async () => { const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-shutdown-')) const harness = await mountPlugin(storageDir, { writeDelayMs: 10 }) diff --git a/packages/sdk/server/tests/server.spec.ts b/packages/sdk/server/tests/server.spec.ts index 495f1d90f4..257c3e72b0 100644 --- a/packages/sdk/server/tests/server.spec.ts +++ b/packages/sdk/server/tests/server.spec.ts @@ -14,6 +14,7 @@ import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import SubagentRuntime, { type SubagentResult, type SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent' import type { JsonRpcTransportPeer } from '@deepseek-ai/dsh-sdk-protocol' +import { defineTool } from '@deepseek-ai/dsh-tools' import { HarnessSdkJsonRpcServer } from '../src/index.ts' class FakeTransport implements JsonRpcTransportPeer { @@ -78,7 +79,7 @@ async function settleSubagent( const result = Promise.withResolvers() const disposeProvider = ctx.subagents.registerProvider({ name: info.provider, - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, async start() { return { @@ -171,6 +172,46 @@ describe('HarnessSdkJsonRpcServer', () => { } }) + it('allowlists each root session against current and later global tools', { timeout: 15_000 }, async () => { + const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-tool-filter-')) + const llmServer = await mockCompletionServer() + vi.stubEnv('DEEPSEEK_API_KEY', 'test-key') + vi.stubEnv('DEEPSEEK_BASE_URL', llmServer.url) + const ctx = await makeHarness(storageDir) + const tool = (name: string) => defineTool({ + name, + description: name, + parameters: {}, + output: { + schema: { type: 'string' as const }, + render: (_args, value) => [{ type: 'text' as const, text: value }], + }, + execute: async () => name, + }) + ctx.tools.register(tool('kept')) + ctx.tools.register(tool('excluded')) + const server = new HarnessSdkJsonRpcServer(ctx, new FakeTransport(), { + toolFilter: { allow: ['kept'] }, + }) + try { + await server.initialize({ cwd: storageDir, provider: 'deepseek-official', model: 'filtered-model' }) + await server.prompt({ sessionId: 'first', contentBlocks: [{ type: 'text', text: 'first' }] }) + await vi.waitFor(() => { expect(llmServer.requests).toHaveLength(1) }) + ctx.tools.register(tool('future')) + await server.prompt({ sessionId: 'second', contentBlocks: [{ type: 'text', text: 'second' }] }) + await vi.waitFor(() => { expect(llmServer.requests).toHaveLength(2) }) + + expect(llmServer.requests.map((request) => { + const tools = (request as { tools?: Array<{ function?: { name?: string } }> }).tools ?? [] + return tools.map(entry => entry.function?.name) + })).toEqual([['kept'], ['kept']]) + await server.shutdown() + } finally { + await ctx.fiber.dispose() + await rm(storageDir, { recursive: true, force: true }) + } + }) + it('queues overlapping prompts for one session without blocking other sessions', async () => { const mainFollowup = vi.fn() const mainAgent = ({ @@ -497,7 +538,7 @@ describe('HarnessSdkJsonRpcServer', () => { let currentLocalAgent = oldChild.agent const disposeProvider = ctx.subagents.registerProvider({ name: 'reused', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start() { const result = results[starts] @@ -592,7 +633,7 @@ describe('HarnessSdkJsonRpcServer', () => { const remoteResult = Promise.withResolvers() const unregisterLocal = ctx.subagents.registerProvider({ name: 'reused-provider', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: () => Promise.resolve({ id: SessionId('provider-reuse-child'), @@ -610,7 +651,7 @@ describe('HarnessSdkJsonRpcServer', () => { const unregisterRemote = ctx.subagents.registerProvider({ name: 'reused-provider', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: () => Promise.resolve({ id: SessionId('provider-reuse-child'), @@ -690,7 +731,7 @@ describe('HarnessSdkJsonRpcServer', () => { const missedStartResult = Promise.withResolvers() const disposeMissedStartProvider = ctx.subagents.registerProvider({ name: 'fork', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: true, start: () => Promise.resolve({ id: SessionId('fallback-child-session'), diff --git a/packages/subagent/subagent-acp/README.i18n.yaml b/packages/subagent/subagent-acp/README.i18n.yaml index fa56c715a5..73f55ccfbf 100644 --- a/packages/subagent/subagent-acp/README.i18n.yaml +++ b/packages/subagent/subagent-acp/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-acp/README.md -README.md: 0201f9bacca5c59031d2fc2eec7fe7210489dd09 -README.zh.md: c987e6251e035f0cf94ac41b570f3be10f0118f5 +README.md: cc4deb5b97152f106caabf747b8c7ccb2f5ddf8e +README.zh.md: e28fb556801d4567bcc606a777e3b090e0551e03 diff --git a/packages/subagent/subagent-acp/README.md b/packages/subagent/subagent-acp/README.md index 0201f9bacc..cc4deb5b97 100644 --- a/packages/subagent/subagent-acp/README.md +++ b/packages/subagent/subagent-acp/README.md @@ -18,7 +18,7 @@ After publication, the provider sends the prompt and collects streamed `agent_me ## Capabilities and context -ACP advertises no start-time capabilities because this process cannot enforce the remote child's depth, tool filter, persona, or structured-output runtime. It also reports `inheritsParentContext: false`: the remote session starts fresh, and the only parent-derived input is the workspace cwd described above — no conversation context crosses the process boundary. +ACP advertises no start-time capabilities because this process cannot apply `request.agentOptions` or enforce the remote child's depth, tool filter, persona, or structured-output runtime. It also reports `inheritsParentContext: false`: the remote session starts fresh, and the only parent-derived input is the workspace cwd described above — no conversation context crosses the process boundary. ## Configuration @@ -70,7 +70,7 @@ The package has no default export. Cordis loader unwrapping would otherwise hide #### What the model sees -The remote child receives the standalone task content through ACP plus its own process's configured system prompt, tools, and fresh session. It receives no parent conversation. This provider advertises no optional start-time capabilities, so the local service rejects requests for persona, tool filtering, depth enforcement, or structured output instead of silently omitting them. +The remote child receives the standalone task content through ACP plus its own process's configured system prompt, tools, and fresh session. It receives no parent conversation. This provider advertises no optional start-time capabilities, so the local service rejects requests for `agentOptions`, persona, tool filtering, depth enforcement, or structured output instead of silently omitting them. #### Token effect @@ -98,6 +98,6 @@ Append-only; newly visible content follows the reusable request prefix and does - **A fresh process per run** — persistent-process pooling is a future optimization ([the seam Agent Note](../../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md)). - **Local workspaces only** — the resolved cwd is a local path handed to a child on the same machine; workspace mapping for a remote ACP agent would need its own backend capability and is not designed here. -- **No optional start-time capabilities** — this provider cannot apply the local harness's `outputSchema`, depth cap, tool filter, or persona inside the remote process, so it advertises none and the service rejects requests that require them. +- **No optional start-time capabilities** — this provider cannot apply the local harness's `agentOptions`, `outputSchema`, depth cap, tool filter, or persona inside the remote process, so it advertises none and the service rejects requests that require them. - **Only committed `agent_message_chunk` text is collected** — the automation server keeps reasoning, tool activity, plans, and other trace data in the child session log rather than emitting them on ACP. - **Permission prompts are auto-answered** (`permission: allow | reject`) — no human is surfaced a child's `session/request_permission`. diff --git a/packages/subagent/subagent-acp/README.zh.md b/packages/subagent/subagent-acp/README.zh.md index c987e6251e..e28fb55680 100644 --- a/packages/subagent/subagent-acp/README.zh.md +++ b/packages/subagent/subagent-acp/README.zh.md @@ -18,7 +18,7 @@ ACP(Agent Client Protocol)提供方会在全新的子进程中运行每个 s ## 能力与上下文 -ACP 不声明任何启动时能力,因为当前进程无法强制执行远程子 agent 的深度、工具过滤、persona 或结构化输出运行时。它也报告 `inheritsParentContext: false`:远程会话从全新状态开始,唯一源自父级的输入是上述工作区 cwd;对话上下文不会跨越进程边界。 +ACP 不声明任何启动时能力,因为当前进程无法应用 `request.agentOptions`,也无法强制执行远程子 agent 的深度、工具过滤、persona 或结构化输出运行时。它也报告 `inheritsParentContext: false`:远程会话从全新状态开始,唯一源自父级的输入是上述工作区 cwd;对话上下文不会跨越进程边界。 ## 配置 @@ -70,7 +70,7 @@ DeepSeek Harness 子进程使用产品启动器和一个显式的绝对路径 `D #### 模型看到的内容 -远程子 agent 通过 ACP 接收独立任务内容,并使用其自身进程配置的系统提示词、工具和全新会话。它不接收父级对话。该提供方不声明任何可选启动时能力,因此本地服务会拒绝要求 persona、工具过滤、深度强制或结构化输出的请求,而不是静默省略这些要求。 +远程子 agent 通过 ACP 接收独立任务内容,并使用其自身进程配置的系统提示词、工具和全新会话。它不接收父级对话。该提供方不声明任何可选启动时能力,因此本地服务会拒绝要求 `agentOptions`、persona、工具过滤、深度强制或结构化输出的请求,而不是静默省略这些要求。 #### Token 影响 @@ -98,6 +98,6 @@ DeepSeek Harness 子进程使用产品启动器和一个显式的绝对路径 `D - **每次运行使用全新进程**:持久进程池属于后续优化(见 [seam Agent Note](../../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md))。 - **仅支持本地工作区**:解析后的 cwd 是交给同一台机器上子进程的本地路径;远程 ACP agent 的工作区映射需要独立的后端能力,此处尚未设计这种能力。 -- **不支持可选启动时能力**:该提供方无法在远程进程内应用本地 harness 的 `outputSchema`、深度上限、工具过滤器或 persona,因此不会声明这些能力;服务会拒绝需要它们的请求。 +- **不支持可选启动时能力**:该提供方无法在远程进程内应用本地 harness 的 `agentOptions`、`outputSchema`、深度上限、工具过滤器或 persona,因此不会声明这些能力;服务会拒绝需要它们的请求。 - **只收集已提交的 `agent_message_chunk` 文本**:自动化服务器把推理(reasoning)、工具活动、计划和其他 trace 数据保留在子 agent 会话日志中,不通过 ACP 发出。 - **权限提示自动回答**(`permission: allow | reject`):不会把子 agent 的 `session/request_permission` 呈现给人。 diff --git a/packages/subagent/subagent-acp/src/index.ts b/packages/subagent/subagent-acp/src/index.ts index 4b526279ba..4c610ef2f9 100644 --- a/packages/subagent/subagent-acp/src/index.ts +++ b/packages/subagent/subagent-acp/src/index.ts @@ -140,11 +140,17 @@ function resolveCwd(configured: string | undefined, request: SubagentStartReques /** * The ACP provider. Advertises NO start-time capabilities: an out-of-process - * child cannot honor `outputSchema`/`maxDepth`/`toolFilter` (the service rejects - * a request needing any of them before `start` runs). + * child cannot honor `agentOptions`/`outputSchema`/`maxDepth`/`toolFilter`/ + * `persona` (the service rejects a request needing any before `start` runs). */ class AcpProvider implements SubagentProvider { - readonly capabilities: SubagentCapabilities = { outputSchema: false, depthLimit: false, toolFilter: false, persona: false } + readonly capabilities: SubagentCapabilities = { + agentOptions: false, + outputSchema: false, + depthLimit: false, + toolFilter: false, + persona: false, + } // Context contract: an out-of-process ACP child starts fresh — no parent conversation crosses the process boundary. readonly inheritsParentContext = false diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index c534b8e949..d4553d8f86 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -863,7 +863,13 @@ describe('dsh-subagent-acp', () => { it('advertises no start-time capabilities (out-of-process child)', async () => { const ctx = await setup() const provider = ctx.subagents.getProvider('acp')! - expect(provider.capabilities).toEqual({ outputSchema: false, depthLimit: false, toolFilter: false, persona: false }) + expect(provider.capabilities).toEqual({ + agentOptions: false, + outputSchema: false, + depthLimit: false, + toolFilter: false, + persona: false, + }) }) it('unregisters the provider when its fiber is disposed (HMR safety)', async () => { diff --git a/packages/subagent/subagent-claude-code/README.i18n.yaml b/packages/subagent/subagent-claude-code/README.i18n.yaml index ff129c60e2..f894fb15ab 100644 --- a/packages/subagent/subagent-claude-code/README.i18n.yaml +++ b/packages/subagent/subagent-claude-code/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-claude-code/README.md -README.md: 0260d9c82dee82541e5b60ff7fe2c323cf9b7331 -README.zh.md: 484241f1ca23f2b8ee843b6f412d0f779832d400 +README.md: 30b61347dfda110fe95a9153aeea35c8f760012f +README.zh.md: 17ddac7d4beebfbf0f374f606a68d77b13ec2b77 diff --git a/packages/subagent/subagent-claude-code/README.md b/packages/subagent/subagent-claude-code/README.md index 0260d9c82d..30b61347df 100644 --- a/packages/subagent/subagent-claude-code/README.md +++ b/packages/subagent/subagent-claude-code/README.md @@ -20,7 +20,7 @@ Each query sets `persistSession: false` and disables `AskUserQuestion`. Except i ## Capabilities and context -The provider advertises no optional start-time capabilities and reports `inheritsParentContext: false`. Claude Code receives the standalone text task and the parent Session cwd, but not the parent conversation, persona, tool filter, depth policy, or structured-output contract. Every run has an independent SDK query, cancellation controller, CLI process, and non-persisted product session. +The provider advertises no optional start-time capabilities and reports `inheritsParentContext: false`. The shared service rejects `request.agentOptions` for this provider. Claude Code receives the standalone text task and the parent Session cwd, but not the parent conversation, persona, tool filter, depth policy, or structured-output contract. Every run has an independent SDK query, cancellation controller, CLI process, and non-persisted product session. ## Configuration @@ -145,5 +145,5 @@ Append-only: foreground adds one result after the reusable parent prefix, while - **The SDK platform payload is required at delegation time** — installs that omit optional dependencies, unsupported platforms, and missing or damaged payloads fail at the first query; there is no host-CLI fallback. - **No human interaction path** — `AskUserQuestion` is disabled, permission prompts are denied, MCP elicitation is declined, and blocking dialogs fail closed instead of suspending. - **Assistant payload is final text only** — a failed run may additionally expose the separate safe diagnostic; reasoning, intermediate messages, tool traffic, usage, stderr, and workspace diffs remain product-local, while generic Job ids, notices, and status come from the shared job runtime. -- **No optional shared capabilities** — output schemas, child personas, tool filtering, and harness depth enforcement are rejected by the shared service for this provider. +- **No optional shared capabilities** — `agentOptions`, output schemas, child personas, tool filtering, and harness depth enforcement are rejected by the shared service for this provider. - **No wall-clock timeout or side-effect rollback** — the caller cancels long work, and files or external systems changed before cancellation are not restored. diff --git a/packages/subagent/subagent-claude-code/README.zh.md b/packages/subagent/subagent-claude-code/README.zh.md index 484241f1ca..17ddac7d4b 100644 --- a/packages/subagent/subagent-claude-code/README.zh.md +++ b/packages/subagent/subagent-claude-code/README.zh.md @@ -20,7 +20,7 @@ SDK 接收由文本块原样拼接成的任务。提供方会完整迭代 SDK ## 能力与上下文 -本提供方不声明任何可选的启动时能力,并报告 `inheritsParentContext: false`。Claude Code 会接收独立文本任务和父会话 cwd,但不会接收父会话的对话、角色设定、工具筛选器、深度策略或结构化输出约定。每次运行都拥有独立的 SDK query、取消控制器、CLI 进程和不持久化的产品会话。 +本提供方不声明任何可选的启动时能力,并报告 `inheritsParentContext: false`。共享服务会拒绝本提供方的 `request.agentOptions`。Claude Code 会接收独立文本任务和父会话 cwd,但不会接收父会话的对话、角色设定、工具筛选器、深度策略或结构化输出约定。每次运行都拥有独立的 SDK query、取消控制器、CLI 进程和不持久化的产品会话。 ## 配置 @@ -145,5 +145,5 @@ Claude Code 子级会在一个全新的 SDK query 中接收独立文本任务。 - **委派时必须存在 SDK 平台载荷**:省略 optional dependencies 的安装、不受支持的平台以及缺失或损坏的载荷都会在第一次 query 时失败;不会回退到宿主 CLI。 - **没有人工交互路径**:`AskUserQuestion` 被禁用,权限提示会被拒绝,MCP elicitation 会被拒绝,阻塞对话会快速失败而不会挂起。 - **assistant 载荷仅包含最终文本**:失败运行可以额外公开独立的安全诊断;推理、中间消息、工具通信、用量信息、stderr 和工作区差异仍只保留在产品内部,通用 Job id、通知与状态来自共享作业运行时。 -- **没有可选的共享能力**:对于本提供方,共享服务会拒绝输出 schema、子任务角色设定、工具筛选和 harness 深度强制约束。 +- **没有可选的共享能力**:对于本提供方,共享服务会拒绝 `agentOptions`、输出 schema、子任务角色设定、工具筛选和 harness 深度强制约束。 - **没有按实际经过时间触发的超时或副作用回滚**:长时间运行的工作由调用方取消,且取消前已更改的文件或外部系统不会恢复原状。 diff --git a/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts b/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts index 5f339ce22e..6054370615 100644 --- a/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts @@ -45,6 +45,7 @@ describe('product-provider public Loader composition', () => { { name: 'codex', capabilities: { + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, @@ -55,6 +56,7 @@ describe('product-provider public Loader composition', () => { { name: 'claude-code', capabilities: { + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, @@ -65,6 +67,7 @@ describe('product-provider public Loader composition', () => { { name: 'claude-primary', capabilities: { + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, @@ -75,6 +78,7 @@ describe('product-provider public Loader composition', () => { { name: 'claude-secondary', capabilities: { + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, diff --git a/packages/subagent/subagent-codex/README.i18n.yaml b/packages/subagent/subagent-codex/README.i18n.yaml index 0f8ed31eab..fd0cccc02d 100644 --- a/packages/subagent/subagent-codex/README.i18n.yaml +++ b/packages/subagent/subagent-codex/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-codex/README.md -README.md: 975f353b9f1bc6fab61a4c0eb40ebaf50c436623 -README.zh.md: 2ea256afb3bb8fdfe57fd555b6db10522a709a56 +README.md: 5016d6b9aa4b57c9d1e83701a0ccfc4b04616f6d +README.zh.md: adabd942c362a28a4eeabe7a4d1b27b138aee4c6 diff --git a/packages/subagent/subagent-codex/README.md b/packages/subagent/subagent-codex/README.md index 975f353b9f..5016d6b9aa 100644 --- a/packages/subagent/subagent-codex/README.md +++ b/packages/subagent/subagent-codex/README.md @@ -18,7 +18,7 @@ Local cancellation wins the result race and maps to `aborted`. For failed turns, ## Capabilities and context -The provider advertises no optional start-time capabilities and reports `inheritsParentContext: false`. Codex receives the standalone text task and the parent Session cwd, but not the parent conversation, persona, tool filter, depth policy, or structured-output contract. The ephemeral Codex thread id and turn id stay private to this run and are never persisted in the parent Session. +The provider advertises no optional start-time capabilities and reports `inheritsParentContext: false`. The shared service rejects `request.agentOptions` for this provider. Codex receives the standalone text task and the parent Session cwd, but not the parent conversation, persona, tool filter, depth policy, or structured-output contract. The ephemeral Codex thread id and turn id stay private to this run and are never persisted in the parent Session. ## Configuration @@ -139,5 +139,5 @@ Append-only: foreground adds one result after the reusable parent prefix, while - **Compatibility is pinned by development evidence** — upgrading from the verified 0.147.0 protocol baseline requires regenerating upstream schema evidence and rerunning handshake, answer-selection, approval, cancellation, keyless real-product, and credentialed DeepSeek nonce tests. - **No human approval path** — known unattended approval requests are denied and unknown server requests fail closed; the three Profile modes never create a DSH interaction channel or per-call allow policy. - **Assistant payload is final text only** — a failed run may additionally expose the separate safe diagnostic; reasoning, commentary, intermediate messages, tool traffic, usage, raw stderr, and workspace diffs remain outside the parent Session, while generic Job ids, notices, and status come from the shared job runtime. -- **No optional shared capabilities** — output schemas, child personas, tool filtering, and harness depth enforcement are rejected by the shared service for this provider. +- **No optional shared capabilities** — `agentOptions`, output schemas, child personas, tool filtering, and harness depth enforcement are rejected by the shared service for this provider. - **No wall-clock timeout or side-effect rollback** — the caller cancels long work, and files or external systems changed before cancellation are not restored. diff --git a/packages/subagent/subagent-codex/README.zh.md b/packages/subagent/subagent-codex/README.zh.md index 2ea256afb3..adabd942c3 100644 --- a/packages/subagent/subagent-codex/README.zh.md +++ b/packages/subagent/subagent-codex/README.zh.md @@ -18,7 +18,7 @@ ## 能力与上下文 -本提供方不声明任何可选的启动时能力,并报告 `inheritsParentContext: false`。Codex 会接收独立文本任务和父会话 cwd,但不会接收父会话的对话、角色设定、工具筛选器、深度策略或结构化输出约定。临时 Codex 线程 ID 与轮次 ID 仅在此次运行内部可见,绝不会持久化到父会话。 +本提供方不声明任何可选的启动时能力,并报告 `inheritsParentContext: false`。共享服务会拒绝本提供方的 `request.agentOptions`。Codex 会接收独立文本任务和父会话 cwd,但不会接收父会话的对话、角色设定、工具筛选器、深度策略或结构化输出约定。临时 Codex 线程 ID 与轮次 ID 仅在此次运行内部可见,绝不会持久化到父会话。 ## 配置 @@ -139,5 +139,5 @@ Codex 子级会在一个全新的临时线程中,以单个轮次接收这些 - **兼容性由开发证据锁定**:若要从已验证的 0.147.0 协议基线升级,必须重新生成上游 schema 证据,并重新运行握手、答案选择、审批、取消、无密钥真实产品以及带密钥的 DeepSeek 随机数测试。 - **没有人工审批路径**:已知的无人值守审批请求会被拒绝,未知服务器请求会以默认拒绝方式使运行失败;三种 Profile 模式都不会创建 DSH 交互通道或逐次调用 allow 策略。 - **assistant 载荷仅包含最终文本**:失败运行可以额外公开独立的安全诊断;推理、过程说明、中间消息、工具通信、用量信息、原始 stderr 和工作区差异不会进入父会话,通用 Job id、通知与状态来自共享作业运行时。 -- **没有可选的共享能力**:对于本提供方,共享服务会拒绝输出 schema、子任务角色设定、工具筛选和 harness 深度强制约束。 +- **没有可选的共享能力**:对于本提供方,共享服务会拒绝 `agentOptions`、输出 schema、子任务角色设定、工具筛选和 harness 深度强制约束。 - **没有按实际经过时间触发的超时或副作用回滚**:长时间运行的工作由调用方取消,且取消前已更改的文件或外部系统不会恢复原状。 diff --git a/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts b/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts index b55b819989..c411ae2dbf 100644 --- a/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-codex/tests/loader-composition.e2e.ts @@ -45,6 +45,7 @@ describe('Codex provider public Loader composition', () => { { name: 'codex', capabilities: { + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, @@ -55,6 +56,7 @@ describe('Codex provider public Loader composition', () => { { name: 'codex-primary', capabilities: { + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, @@ -65,6 +67,7 @@ describe('Codex provider public Loader composition', () => { { name: 'codex-secondary', capabilities: { + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, diff --git a/packages/subagent/subagent-dsh-sdk/README.i18n.yaml b/packages/subagent/subagent-dsh-sdk/README.i18n.yaml index 8946de4236..a05ec421e3 100644 --- a/packages/subagent/subagent-dsh-sdk/README.i18n.yaml +++ b/packages/subagent/subagent-dsh-sdk/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-dsh-sdk/README.md -README.md: 10f437f1618d006f58ad37701e6fde7944f5c1fb -README.zh.md: d3237d9a0b36ce63c9eacf85bfe7cff947acd9e0 +README.md: 302baa05afed2b78c2041f57b1ef900713e350cd +README.zh.md: e4e1460274170b0c990d9e454f1cbf54546676e9 diff --git a/packages/subagent/subagent-dsh-sdk/README.md b/packages/subagent/subagent-dsh-sdk/README.md index 10f437f161..302baa05af 100644 --- a/packages/subagent/subagent-dsh-sdk/README.md +++ b/packages/subagent/subagent-dsh-sdk/README.md @@ -20,7 +20,7 @@ The SDK client returns an owned child activity rather than a prompt result. The ## Capabilities and context -The provider advertises no start-time capabilities (`outputSchema`/`depthLimit`/`toolFilter`/`persona` all false) and `inheritsParentContext: false`: the child is a fresh runtime in another process, and the only parent-derived input is the workspace cwd. `dsh-tool-subagent` deployments over this provider set `maxDepth: 'provider-managed'` — the child harness owns its own recursion budget. +The provider advertises no start-time capabilities (`agentOptions`/`outputSchema`/`depthLimit`/`toolFilter`/`persona` all false) and `inheritsParentContext: false`: the child is a fresh runtime in another process, and the only parent-derived input is the workspace cwd. `dsh-tool-subagent` deployments over this provider set `maxDepth: 'provider-managed'` — the child harness owns its own recursion budget. ## Configuration @@ -68,7 +68,7 @@ The package has no default export. Cordis loader unwrapping would otherwise hide #### What the model sees -The child runtime's model receives the standalone task as its user message plus that runtime's own configured system prompt, tools, and fresh session. It receives no parent conversation. This provider advertises no optional start-time capabilities, so the local service rejects requests for persona, tool filtering, depth enforcement, or structured output instead of silently omitting them. +The child runtime's model receives the standalone task as its user message plus that runtime's own configured system prompt, tools, and fresh session. It receives no parent conversation. This provider advertises no optional start-time capabilities, so the local service rejects requests for `agentOptions`, persona, tool filtering, depth enforcement, or structured output instead of silently omitting them. #### Token effect @@ -95,6 +95,6 @@ Append-only; newly visible content follows the reusable request prefix and does ## Known Limitations and Deferred Work - **A fresh runtime process per run** — no pooling; a harness runtime boots a full plugin tree, so per-run spawn cost is higher than the ACP backend's typical child. -- **No optional start-time capabilities** — the parent cannot enforce `outputSchema`, depth, tool filters, or persona inside the child process; configure the selected child profile and its ordered patches instead. +- **No optional start-time capabilities** — the parent cannot apply `agentOptions` or enforce `outputSchema`, depth, tool filters, or persona inside the child process; configure the selected child profile and its ordered patches instead. - **The child's transcript stays in the child's own session root** — the parent log records only the delegation tool call/result (the seam's child-isolation rule); the streamed `session.event` channel is consumed for output extraction, not bridged into the parent log. - **Local child processes only** — the resolved cwd is a local path; a remote runtime would need its own backend. diff --git a/packages/subagent/subagent-dsh-sdk/README.zh.md b/packages/subagent/subagent-dsh-sdk/README.zh.md index d3237d9a0b..e4e1460274 100644 --- a/packages/subagent/subagent-dsh-sdk/README.zh.md +++ b/packages/subagent/subagent-dsh-sdk/README.zh.md @@ -20,7 +20,7 @@ SDK 客户端返回自有子活动,而不是提示词结果。提供方读取 ## 能力与上下文 -Provider 不宣告任何启动期能力(`outputSchema`/`depthLimit`/`toolFilter`/`persona` 全为 false),且 `inheritsParentContext: false`:子进程是另一进程里的全新运行时,唯一来自父方的输入是工作区 cwd。基于本 provider 的 `dsh-tool-subagent` 部署应设置 `maxDepth: 'provider-managed'`——子 harness 拥有自己的递归预算。 +Provider 不宣告任何启动期能力(`agentOptions`/`outputSchema`/`depthLimit`/`toolFilter`/`persona` 全为 false),且 `inheritsParentContext: false`:子进程是另一进程里的全新运行时,唯一来自父方的输入是工作区 cwd。基于本 provider 的 `dsh-tool-subagent` 部署应设置 `maxDepth: 'provider-managed'`——子 harness 拥有自己的递归预算。 ## 配置 @@ -68,7 +68,7 @@ Provider 不宣告任何启动期能力(`outputSchema`/`depthLimit`/`toolFilte #### 模型看到的内容 -子运行时的模型会收到作为用户消息的独立任务,以及该运行时自身配置的系统提示词、工具和全新会话。它不会收到父级对话。本提供方不声明可选的启动时能力,因此本地服务会拒绝要求 persona、工具过滤、深度强制或结构化输出的请求,而不是静默省略这些要求。 +子运行时的模型会收到作为用户消息的独立任务,以及该运行时自身配置的系统提示词、工具和全新会话。它不会收到父级对话。本提供方不声明可选的启动时能力,因此本地服务会拒绝要求 `agentOptions`、persona、工具过滤、深度强制或结构化输出的请求,而不是静默省略这些要求。 #### Token 影响 @@ -95,6 +95,6 @@ Provider 不宣告任何启动期能力(`outputSchema`/`depthLimit`/`toolFilte ## 已知限制与暂缓事项 - **每次运行都使用全新的运行时进程**:不使用进程池;harness 运行时需要启动完整的插件树,因此每次运行的 spawn 成本高于 ACP 后端通常使用的子进程。 -- **不支持可选的启动时能力**:父级无法在子进程内强制执行 `outputSchema`、深度限制、工具过滤或 persona;应改为配置所选子 profile 及其有序 patch。 +- **不支持可选的启动时能力**:父级无法在子进程内应用 `agentOptions`,也无法强制执行 `outputSchema`、深度限制、工具过滤或 persona;应改为配置所选子 profile 及其有序 patch。 - **子进程的 transcript(文本记录)保留在其自身的会话根目录中**:父级日志只记录委派工具调用/结果(seam 的子级隔离规则);流式 `session.event` 通道只用于提取输出,不会桥接到父级日志中。 - **仅支持本地子进程**:解析出的 cwd 是本地路径;远程运行时需要独立的后端。 diff --git a/packages/subagent/subagent-dsh-sdk/src/index.ts b/packages/subagent/subagent-dsh-sdk/src/index.ts index 7530e104d2..277add74f8 100644 --- a/packages/subagent/subagent-dsh-sdk/src/index.ts +++ b/packages/subagent/subagent-dsh-sdk/src/index.ts @@ -105,7 +105,7 @@ function resolveConfiguredFile(field: string, value: string): string { /** * The SDK provider. Advertises NO start-time capabilities: an out-of-process - * child cannot honor `outputSchema`/`maxDepth`/`toolFilter`/`persona` (the + * child cannot honor `agentOptions`/`outputSchema`/`maxDepth`/`toolFilter`/`persona` (the * service rejects a request needing any of them before `start` runs). */ class SdkSubagentProvider implements SubagentProvider { diff --git a/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts b/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts index 2e67c76c24..27511670cf 100644 --- a/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts +++ b/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts @@ -433,6 +433,7 @@ describe('dsh-subagent-dsh-sdk provider', () => { expect(ctx.subagents.getProvider('sdk-hmr')?.name).toBe('sdk-hmr') expect(ctx.subagents.getProvider('sdk-hmr')?.inheritsParentContext).toBe(false) expect(ctx.subagents.getProvider('sdk-hmr')?.capabilities).toEqual({ + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, diff --git a/packages/subagent/subagent-fork-in-process/README.i18n.yaml b/packages/subagent/subagent-fork-in-process/README.i18n.yaml index 9cd2361d52..19af9e598a 100644 --- a/packages/subagent/subagent-fork-in-process/README.i18n.yaml +++ b/packages/subagent/subagent-fork-in-process/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-fork-in-process/README.md -README.md: 74c27ff10c76aa711ed3e954e806c00a27aacfa5 -README.zh.md: 43e7ef489b33d52b674420d08f7edf8c89fb0e42 +README.md: c2dcda39c03b8c059839bef1573436e485a51911 +README.zh.md: 3eb84053a3e74abe7394c0985dcd88bd6146e449 diff --git a/packages/subagent/subagent-fork-in-process/README.md b/packages/subagent/subagent-fork-in-process/README.md index 74c27ff10c..c2dcda39c0 100644 --- a/packages/subagent/subagent-fork-in-process/README.md +++ b/packages/subagent/subagent-fork-in-process/README.md @@ -16,7 +16,7 @@ The seed transfers conversation history only. The child still receives a fresh f `start(request)` passes the completed-turn seed to [`startInProcessRun`](../subagent-in-process-driver/README.md) and awaits child publication. The shared driver owns cancellation, depth, customization, result reading, and disposal. -Fork advertises `{ outputSchema: true, depthLimit: true, toolFilter: true, persona: true }`, identical to spawn. +Fork advertises `{ agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }`, identical to spawn. ## Config @@ -39,7 +39,7 @@ Forking duplicates retained completed history into separate child requests; the #### KV Cache effect -The child may reuse the inherited byte-identical prefix under the same provider and model. Persona, tool-filter, generated-SDK, or route changes may invalidate reuse before inherited history; later child history is append-only. Shipped compositions therefore bind this provider to `backgroundMode: one-shot`, because a continuable child additionally carries the child-scoped `report` tool and its prompt section — deltas that precede the inherited history and so invalidate all of it ([the fork-one-shot Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md)). +The child may reuse the inherited byte-identical prefix under the same provider and model. Persona, tool-filter, generated-SDK, or route changes may invalidate reuse before inherited history; later child history is append-only. The base bundle and ACP/headless examples bind this provider to `backgroundMode: one-shot`, because a continuable child additionally carries the child-scoped `report` tool and its prompt section — deltas that precede the inherited history and so invalidate all of it. The CLI presets retain `continuable` fork and therefore accept that prefix loss ([the cache-preserving fork Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md)). ### Parent tool result, indirectly @@ -58,4 +58,5 @@ Append-only; newly visible content follows the reusable request prefix and does ## Known Limitations and Deferred Work - **The seed is a one-time snapshot** — the child sees the parent's completed turns as of the fork and nothing the parent logs afterwards; there is no live context sharing. -- **No shipped composition creates a continuable fork child** — `prepareContinuable` remains implemented and the seam accepts it, but every shipped `cordis.yml` sets `backgroundMode: one-shot` on the fork delegation tool, so the provider's continuable path has no production caller. Reopening it requires the child's system prompt and tool schemas to match the parent's byte for byte, which the [`report` return channel](../tool-subagent-report/README.md) currently prevents. Rationale and the reintroduction condition: [the fork-one-shot Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md). +- **Fork lifecycle policy differs by composition** — the base bundle and ACP/headless examples use one-shot fork to preserve prefix reuse, while the CLI presets use continuable fork and accept the child-scoped [`report` return channel](../tool-subagent-report/README.md) invalidating that prefix. Making continuable fork cache-preserving requires the child system prompt and tool schemas to match the parent's byte for byte. Rationale and the reintroduction condition: [the cache-preserving fork Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md). +- **Shipped fork tools do not expose child LLM route selection** — they inherit the parent's provider and model so the copied history remains eligible for KV Cache reuse. Route selection stays disabled until a change can preserve reuse or expose a bounded recomputation cost; the [model-selected route Agent Note](../../../.agents/notes/implemented/feature/2026-08-18-model-selected-subagent-routes.md) owns that separate restriction. diff --git a/packages/subagent/subagent-fork-in-process/README.zh.md b/packages/subagent/subagent-fork-in-process/README.zh.md index 43e7ef489b..3eb84053a3 100644 --- a/packages/subagent/subagent-fork-in-process/README.zh.md +++ b/packages/subagent/subagent-fork-in-process/README.zh.md @@ -16,7 +16,7 @@ subagent 启动时,父 agent 当前的工具调用轮次仍未结束:其日 `start(request)` 将已完成轮次的初始内容传给 [`startInProcessRun`](../subagent-in-process-driver/README.zh.md),并等待子 agent 发布。共享驱动器负责取消、深度、定制、结果读取和 dispose(资源释放)。 -fork 声明 `{ outputSchema: true, depthLimit: true, toolFilter: true, persona: true }`,与 spawn 相同。 +fork 声明 `{ agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }`,与 spawn 相同。 ## 配置 @@ -39,7 +39,7 @@ fork 会把保留的已完成历史复制到独立的子 agent 请求中;随 #### KV Cache 影响 -在提供方和模型相同的前提下,子 agent 可以复用继承的逐字节相同前缀。persona、工具过滤、生成 SDK 或路由变化可能在继承历史之前使复用失效;后续子 agent 历史仅追加。因此随附组合把本提供方绑定为 `backgroundMode: one-shot`:可继续子 agent 还会额外携带作用域局部的 `report` 工具及其提示词 section,而这些增量位于继承历史之前,会使继承历史整体失效(见 [fork 保持 one-shot 的 Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md))。 +在提供方和模型相同的前提下,子 agent 可以复用继承的逐字节相同前缀。persona、工具过滤、生成 SDK 或路由变化可能在继承历史之前使复用失效;后续子 agent 历史仅追加。base 组合包与 ACP/headless 示例把本提供方绑定为 `backgroundMode: one-shot`:可继续子 agent 还会额外携带作用域局部的 `report` 工具及其提示词 section,而这些增量位于继承历史之前,会使继承历史整体失效。CLI preset 保留可继续 fork,因此接受这项前缀损失(见[保留缓存的 fork Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md))。 ### 父 agent 工具结果(间接) @@ -58,4 +58,5 @@ fork 会把保留的已完成历史复制到独立的子 agent 请求中;随 ## 已知限制与暂缓事项 - **初始内容是一次性快照**:子 agent 只能看到 fork 时父 agent 已完成的轮次,看不到父 agent 此后记录的任何内容;不会实时共享上下文。 -- **没有任何随附组合会创建可继续的 fork 子 agent**:`prepareContinuable` 仍然实现完好,seam 也接受它,但每份随附的 `cordis.yml` 都在 fork 委派工具上设置 `backgroundMode: one-shot`,因此该提供方的可继续路径没有生产调用方。重新开放它需要子 agent 的系统提示词与工具 schema 与父 agent 逐字节一致,而这一点目前被 [`report` 返回通道](../tool-subagent-report/README.zh.md)阻止。理由与重新开放条件见 [fork 保持 one-shot 的 Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md)。 +- **fork 生命周期策略因组合而异**:base 组合包与 ACP/headless 示例使用一次性 fork 以保留前缀复用,CLI preset 则使用可继续 fork,并接受子级作用域的 [`report` 返回通道](../tool-subagent-report/README.zh.md)使该前缀失效。要让可继续 fork 保留缓存,子 agent 的系统提示词与工具 schema 必须与父级逐字节一致。理由与重新开放条件见[保留缓存的 fork Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md)。 +- **随附 fork 工具不公开子级 LLM 路由选择**:它们会继承父级的提供方与模型,使复制的历史仍可供 KV Cache 复用。只有在路由变化仍能保留复用,或接口能公开一项有界的重算成本时,才启用路由选择;该独立限制由[模型选择路由 Agent Note](../../../.agents/notes/implemented/feature/2026-08-18-model-selected-subagent-routes.zh.md)负责。 diff --git a/packages/subagent/subagent-fork-in-process/src/index.ts b/packages/subagent/subagent-fork-in-process/src/index.ts index 1f8e48b8c8..9786f585fa 100644 --- a/packages/subagent/subagent-fork-in-process/src/index.ts +++ b/packages/subagent/subagent-fork-in-process/src/index.ts @@ -55,11 +55,18 @@ function completedTurnPrefix(parent: Agent): SessionEvent[] { /** * The fork provider. Supports `depthLimit` and `outputSchema` (via the shared - * in-process structured runtime), plus `toolFilter`/`persona` (scoped - * restrict() and a scoped shadowing persona section). + * in-process structured runtime), `agentOptions` (merged over the parent + * route), and `toolFilter`/`persona` (scoped restrict() and a scoped shadowing + * persona section). */ class ForkInProcessProvider implements SubagentProvider { - readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: true } + readonly capabilities: SubagentCapabilities = { + agentOptions: true, + outputSchema: true, + depthLimit: true, + toolFilter: true, + persona: true, + } // Context contract: a forked child IS seeded with the parent's completed-turn prefix. readonly inheritsParentContext = true @@ -74,11 +81,11 @@ class ForkInProcessProvider implements SubagentProvider { }) } - // TODO(fork-continuable-prefix-reuse): no shipped composition calls this — - // they bind fork to `backgroundMode: one-shot` because a continuable child's - // `report` tool and prompt section precede the inherited history, defeating - // the prefix reuse a fork exists for. Reopening needs a byte-identical child - // system prompt and tool schemas; see issue #2124 and + // TODO(fork-continuable-prefix-reuse): CLI presets call this and accept that + // a continuable child's `report` tool and prompt section precede the inherited + // history, defeating the prefix reuse a fork exists for. Cache-preserving + // continuable fork needs byte-identical child system prompt and tool schemas; + // see issue #2124 and // .agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md. prepareContinuable(request: ContinuableCreateRequest): Promise { // The fork prefix is captured ONCE, at creation: it becomes part of the diff --git a/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts b/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts index 8b69711233..292fba32cc 100644 --- a/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts +++ b/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts @@ -193,9 +193,15 @@ describe('dsh-subagent-fork-in-process', () => { await run.dispose() }) - it('advertises every start-time capability (depthLimit, outputSchema, toolFilter, persona)', async () => { + it('advertises every start-time capability', async () => { const { ctx } = await setup([]) - expect(ctx.subagents.getProvider('fork')!.capabilities).toEqual({ outputSchema: true, depthLimit: true, toolFilter: true, persona: true }) + expect(ctx.subagents.getProvider('fork')!.capabilities).toEqual({ + agentOptions: true, + outputSchema: true, + depthLimit: true, + toolFilter: true, + persona: true, + }) }) it('unregisters the provider when its fiber is disposed (HMR safety)', async () => { diff --git a/packages/subagent/subagent-in-process-driver/README.i18n.yaml b/packages/subagent/subagent-in-process-driver/README.i18n.yaml index 505c480cfe..16d07d8211 100644 --- a/packages/subagent/subagent-in-process-driver/README.i18n.yaml +++ b/packages/subagent/subagent-in-process-driver/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-in-process-driver/README.md -README.md: 47a5c09fc1c80c5dc3062be82e7355b874a627d3 -README.zh.md: b96399795a0fbac05ef1795888aa93c620687f30 +README.md: ed2568fcff3fe1f0f3968d1cef43ebd914a8911b +README.zh.md: f9958e5c2b819d51bfdf8fc1e14d1f8c7c19be91 diff --git a/packages/subagent/subagent-in-process-driver/README.md b/packages/subagent/subagent-in-process-driver/README.md index 47a5c09fc1..ed2568fcff 100644 --- a/packages/subagent/subagent-in-process-driver/README.md +++ b/packages/subagent/subagent-in-process-driver/README.md @@ -16,7 +16,7 @@ The driver follows this sequence: 4. Publish the child, retain the returned `AgentHandle`, and drive one task with `child.followup(prompt)` followed by `child.whenIdle()`. 5. Read the child's own output — its last non-empty assistant message (an empty-content message that records usage is skipped), or its accumulated assistant text when no such message exists — and the final durable turn reason from the complete owned child run, excluding any fork seed. -The child gets the parent's working-directory/session lineage and inherits the parent provider, model, and output-token cap unless `request.agentOptions` overrides them. It gets a fresh flat registration scope: parent ownership does not import parent tool restrictions or establish an authority subset. +The child gets the parent's working-directory/session lineage and inherits the parent provider, model, reasoning effort, and output-token cap unless `request.agentOptions` overrides them. It gets a fresh flat registration scope: parent ownership does not import parent tool restrictions or establish an authority subset. This result boundary is valid because the provider owns an isolated child lifecycle from publication through quiescence. Steering submitted during that lifecycle belongs to the child run; the provider does not pretend the initial follow-up alone owns its output. diff --git a/packages/subagent/subagent-in-process-driver/README.zh.md b/packages/subagent/subagent-in-process-driver/README.zh.md index b96399795a..f9958e5c2b 100644 --- a/packages/subagent/subagent-in-process-driver/README.zh.md +++ b/packages/subagent/subagent-in-process-driver/README.zh.md @@ -16,7 +16,7 @@ 4. 发布子 agent,保留返回的 `AgentHandle`,并通过先调用 `child.followup(prompt)`、再调用 `child.whenIdle()` 来驱动一项任务。 5. 从完整的自有子运行中读取子 agent 自身的输出——最后一条非空 assistant 消息(记录 usage 的空内容消息会被跳过),若没有这类消息则取其累积的 assistant 文本——以及最终持久化的轮次原因,并排除任何 fork 初始内容。 -子 agent 会获得父 agent 的工作目录/会话谱系;除非 `request.agentOptions` 覆盖,否则还会继承父 agent 的提供方、模型和输出 token 上限。它获得全新的扁平注册作用域:父级所有权不会导入父 agent 的工具限制,也不会建立权限子集。 +子 agent 会获得父 agent 的工作目录/会话谱系;除非 `request.agentOptions` 覆盖,否则还会继承父 agent 的提供方、模型、推理强度与输出 token 上限。它获得全新的扁平注册作用域:父级所有权不会导入父 agent 的工具限制,也不会建立权限子集。 该结果边界成立,是因为提供方拥有从发布到完全停稳的隔离子 agent 生命周期。在该生命周期内提交的 steering(中途引导)属于子运行;提供方不会声称输出只归初始 follow-up 所有。 diff --git a/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts b/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts index 8840e8b101..6bb18f5f28 100644 --- a/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts +++ b/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts @@ -70,7 +70,7 @@ async function setup(script: Script, options: SetupOptions = {}) { await ctx.plugin(SubagentRuntime) const disposeProvider = ctx.subagents.registerProvider({ name: 'spawn', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: false, persona: false }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: false, persona: false }, inheritsParentContext: false, start: (request: ResolvedSubagentStartRequest) => startInProcessRun(request, {}), }) diff --git a/packages/subagent/subagent-spawn-in-process/README.i18n.yaml b/packages/subagent/subagent-spawn-in-process/README.i18n.yaml index 1246456cc0..022dbfa58d 100644 --- a/packages/subagent/subagent-spawn-in-process/README.i18n.yaml +++ b/packages/subagent/subagent-spawn-in-process/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-spawn-in-process/README.md -README.md: f1fb96f2230359cb3ff55c630f29fd34345dbed7 -README.zh.md: 95a3b5cdb7084eb75666f8d62001221c57ac676c +README.md: ebe2b069dc56dc1a3359f8880860a5796ef3ef4c +README.zh.md: 66ecbec2c00865d16a99f1e6bf4f0c32cb6e5538 diff --git a/packages/subagent/subagent-spawn-in-process/README.md b/packages/subagent/subagent-spawn-in-process/README.md index f1fb96f223..ebe2b069dc 100644 --- a/packages/subagent/subagent-spawn-in-process/README.md +++ b/packages/subagent/subagent-spawn-in-process/README.md @@ -6,13 +6,13 @@ The spawn provider creates a fresh child `Agent` in the current process. The chi ## Behavior -`start(request)` delegates to [`startInProcessRun`](../subagent-in-process-driver/README.md) with no seed and awaits publication before returning. The child receives parent working-directory/session lineage and inherits the parent model unless overridden, but starts with an empty conversation. +`start(request)` delegates to [`startInProcessRun`](../subagent-in-process-driver/README.md) with no seed and awaits publication before returning. The child receives parent working-directory/session lineage and inherits the parent provider, model, reasoning effort, and output-token limit unless `request.agentOptions` overrides them, but starts with an empty conversation. The shared driver owns depth checking, persona and tool-filter setup, structured output, required-signal cancellation, one-shot execution, result reading, and quiescent disposal. A startup rejection leaves no published child; provider unload after fulfillment does not revoke the holder-owned run. ## Capabilities -Spawn advertises `{ outputSchema: true, depthLimit: true, toolFilter: true, persona: true }` because it controls the child's creation window and can enforce all four features. +Spawn advertises `{ agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }` because it controls the child's creation window and can enforce all five features. ## Config @@ -26,7 +26,7 @@ Spawn advertises `{ outputSchema: true, depthLimit: true, toolFilter: true, pers #### What the model sees -The fresh child receives the standalone task content verbatim, inherits the parent model and workspace by default, and sees the global prompt with any configured child-scoped persona shadow. A tool filter removes global wire schemas, executable lookup, and Code Mode SDK bindings for that child but leaves independently registered guidance. It receives zero parent conversation messages; the filter is visibility/composition, not an authority grant inherited from the parent. +The fresh child receives the standalone task content verbatim, inherits the parent provider, model, reasoning effort, output-token limit, and workspace by default, and sees the global prompt with any configured child-scoped persona shadow. A tool filter removes global wire schemas, executable lookup, and Code Mode SDK bindings for that child but leaves independently registered guidance. It receives zero parent conversation messages; the filter is visibility/composition, not an authority grant inherited from the parent. #### Token effect @@ -52,4 +52,4 @@ Append-only; newly visible content follows the reusable request prefix and does ## Known Limitations and Deferred Work -- **Fresh means no parent transcript** — the child inherits cwd, lineage, model, and explicitly configured persona/tool restrictions, but none of the parent's conversation; use the fork provider when completed-turn context is required. +- **Fresh means no parent transcript** — the child inherits cwd, lineage, provider, model, reasoning effort, output-token limit, and explicitly configured persona/tool restrictions, but none of the parent's conversation; use the fork provider when completed-turn context is required. diff --git a/packages/subagent/subagent-spawn-in-process/README.zh.md b/packages/subagent/subagent-spawn-in-process/README.zh.md index 95a3b5cdb7..66ecbec2c0 100644 --- a/packages/subagent/subagent-spawn-in-process/README.zh.md +++ b/packages/subagent/subagent-spawn-in-process/README.zh.md @@ -6,13 +6,13 @@ spawn 提供方会在当前进程中创建一个全新的子 `Agent`。子 agent ## 行为 -`start(request)` 不传入 seed,直接委托给 [`startInProcessRun`](../subagent-in-process-driver/README.zh.md),并在子 agent 发布后才返回。子 agent 获得父 agent 的工作目录/会话谱系,并默认继承父 agent 模型(除非覆盖),但以空对话开始运行。 +`start(request)` 不传入 seed,直接委托给 [`startInProcessRun`](../subagent-in-process-driver/README.zh.md),并在子 agent 发布后才返回。子 agent 获得父 agent 的工作目录/会话谱系;除非 `request.agentOptions` 覆盖,否则还会继承父 agent 的提供方、模型、推理强度与输出 token 上限,但以空对话开始运行。 共享驱动器负责深度检查、persona 与工具过滤器设置、结构化输出、通过必需的信号执行取消、单次执行、结果读取和完全停稳后的 dispose(资源释放)。启动遭拒不会留下已发布的子 agent;启动调用兑现后卸载提供方,也不会撤销由持有方拥有的运行。 ## 能力 -spawn 声明 `{ outputSchema: true, depthLimit: true, toolFilter: true, persona: true }`,因为它控制子 agent 的创建窗口,能够强制执行全部四项功能。 +spawn 声明 `{ agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }`,因为它控制子 agent 的创建窗口,能够强制执行全部五项功能。 ## 配置 @@ -26,7 +26,7 @@ spawn 声明 `{ outputSchema: true, depthLimit: true, toolFilter: true, persona: #### 模型看到的内容 -全新的子 agent 逐字接收独立任务内容,默认继承父 agent 的模型和工作区,并看到带有已配置子 agent 作用域 persona 遮蔽的全局提示词。工具过滤器会为该子 agent 移除全局协议 schema、可执行工具查找和 Code Mode SDK 绑定,但保留独立注册的指导内容。它不接收任何父 agent 对话消息;过滤控制的是可见性与组合,并非从父 agent 继承的权限授予。 +全新的子 agent 逐字接收独立任务内容,默认继承父 agent 的提供方、模型、推理强度、输出 token 上限与工作区,并看到带有已配置子 agent 作用域 persona 遮蔽的全局提示词。工具过滤器会为该子 agent 移除全局协议 schema、可执行工具查找和 Code Mode SDK 绑定,但保留独立注册的指导内容。它不接收任何父 agent 对话消息;过滤控制的是可见性与组合,并非从父 agent 继承的权限授予。 #### Token 影响 @@ -52,4 +52,4 @@ spawn 声明 `{ outputSchema: true, depthLimit: true, toolFilter: true, persona: ## 已知限制与暂缓事项 -- **全新表示不含父 agent transcript(文本记录)**:子 agent 会继承 cwd、谱系、模型及显式配置的 persona/工具限制,但不继承父 agent 的任何对话;需要已完成轮次上下文时,请使用 fork 提供方。 +- **全新表示不含父 agent transcript(文本记录)**:子 agent 会继承 cwd、谱系、提供方、模型、推理强度、输出 token 上限及显式配置的 persona/工具限制,但不继承父 agent 的任何对话;需要已完成轮次上下文时,请使用 fork 提供方。 diff --git a/packages/subagent/subagent-spawn-in-process/src/index.ts b/packages/subagent/subagent-spawn-in-process/src/index.ts index dcd036e4ad..73811155c1 100644 --- a/packages/subagent/subagent-spawn-in-process/src/index.ts +++ b/packages/subagent/subagent-spawn-in-process/src/index.ts @@ -34,12 +34,18 @@ export const Config: z = z.object({ /** * The spawn provider. Supports every start-time capability: `depthLimit` (it * constructs the child, so it can enforce a recursion cap), `outputSchema` - * (the scoped structured runtime), and `toolFilter`/`persona` (scoped - * `restrict()` and a scoped shadowing persona section, applied in the child's - * creation window). + * (the scoped structured runtime), `agentOptions` (merged over the parent + * route), and `toolFilter`/`persona` (scoped `restrict()` and a scoped + * shadowing persona section, applied in the child's creation window). */ class SpawnInProcessProvider implements SubagentProvider { - readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: true } + readonly capabilities: SubagentCapabilities = { + agentOptions: true, + outputSchema: true, + depthLimit: true, + toolFilter: true, + persona: true, + } // Context contract: a spawned child starts fresh — it never sees the parent conversation. readonly inheritsParentContext = false diff --git a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts index ae60480c02..7a798a4818 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts @@ -282,10 +282,16 @@ describe('dsh-subagent-spawn-in-process', () => { await parentHandle.dispose() }) - it('advertises every start-time capability (depthLimit, outputSchema, toolFilter, persona)', async () => { + it('advertises every start-time capability', async () => { const { ctx } = await setup([]) const provider = ctx.subagents.getProvider('spawn')! - expect(provider.capabilities).toEqual({ outputSchema: true, depthLimit: true, toolFilter: true, persona: true }) + expect(provider.capabilities).toEqual({ + agentOptions: true, + outputSchema: true, + depthLimit: true, + toolFilter: true, + persona: true, + }) }) it('unregisters the provider when its fiber is disposed (HMR safety)', async () => { diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index a645351bd8..a55a61ee77 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent/README.md -README.md: e84a6b486253e81ccf7e7df12c4149e6df4ed9f2 -README.zh.md: e289863531c1686cedeccadfa76e2661dfa9bfc8 +README.md: 68ddc49197bcbd3f8eb5f362de60da33cb08c147 +README.zh.md: cf434152cd6366e371eef86f0edcb08d18978c66 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index e84a6b4862..68ddc49197 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -26,7 +26,7 @@ The [subagent family overview](../README.md) maps implementations and model-faci | `listChildren(parentSessionId, signal?)` | List direct session-backed subagents with their `one-shot`/`continuable` mode, `running`/`inactive` activity, origin-classified one-level `hasChildren` hint, and per-child diagnostics, ordered by `createdAt` then id, without loading or resuming them. Reads the live session store and optional session persistence directly (live-only enumeration when persistence is absent) and requires the mounted `sessionProjections` registry; it does not require `ctx.agents`, the continuation manager, or any query service. | | `listDescendants(rootSessionId, signal?)` | Flatten the root's complete session tree in stable pre-order from the same live-preferred corpus, adding each subagent entry's durable `parentId` and root-relative `depth`. Ordinary sessions and one-shot children remain traversal nodes so continuable descendants below them are discovered. Identity, diagnostics, dependencies, and cancellation follow `listChildren()`. | -`SubagentStartRequest.label` is an optional short durable display label for a session-backed one-shot child. Model-facing delegation supplies its existing `description`; lower-level callers need not invent presentation metadata. Continuable starts always carry their own required label. `signal` is required and is the canonical cancellation channel for a one-shot `start`. An abort before publication makes `start()` reject after rollback; an abort after publication cancels the returned run's remaining turn work without hiding its id. The request may also select a model, require structured output, cap delegation depth, restrict child tools, or set a child persona. For a continuable start or follow-up, the caller signal owns lookup, materialization, and admission only until inbox acceptance; afterward the manager owns the Activation independently, so later caller cancellation neither cancels the accepted turn nor disposes the child. +`SubagentStartRequest.label` is an optional short durable display label for a session-backed one-shot child. Model-facing delegation supplies its existing `description`; lower-level callers need not invent presentation metadata. Continuable starts always carry their own required label. `signal` is required and is the canonical cancellation channel for a one-shot `start`. An abort before publication makes `start()` reject after rollback; an abort after publication cancels the returned run's remaining turn work without hiding its id. The request may also override the host Agent's provider, model, reasoning effort, and token limit, require structured output, cap delegation depth, restrict child tools, or set a child persona. Every requested optional feature requires its matching provider capability. For a continuable start or follow-up, the caller signal owns lookup, materialization, and admission only until inbox acceptance; afterward the manager owns the Activation independently, so later caller cancellation neither cancels the accepted turn nor disposes the child. Follow-up authority comes from the exact live direct parent recorded in the child's durable header. Cold resume checks that authority before reconstruction and again in the final no-await inbox-admission span, so a parent unregistered or replaced during materialization cannot authorize delivery. The `source` on a follow-up records who supplied the delivered message and grants no authority. @@ -36,11 +36,14 @@ Same-process requests, descriptors, results, and event payloads are trusted type Start-time features are advertised in `provider.capabilities` because the service must reject an unsupported one-shot request before child creation: +- `agentOptions` — apply host-Agent provider, model, reasoning-effort, and output-token overrides. - `outputSchema` — enforce a structured final result. - `depthLimit` — enforce `maxDepth`. - `toolFilter` — apply the requested child tool restriction. - `persona` — apply a per-child persona. +Both in-process providers advertise `agentOptions`: child creation merges requested fields over the provider, model, and reasoning effort in the parent's latest logged request, falling back to its creation options before the first request and retaining its configured token limit. A route change without an explicit effort clears the inherited route-owned effort so the selected model resolves its default. Current out-of-process providers advertise it as unsupported, so configured or model-selected overrides fail before their child transport starts instead of being silently ignored. + Every in-process child is composed by one call, `applyChildComposition(childCtx, parent, composition)`, which joins the parent's agent-preset composition before applying the child's own persona and tool filter. The join is what gives the child its capabilities: with every model-facing row on the agent plane, a child that joined nothing would reach the model with an empty tool registry ([`dsh-agent-presets`](../../preset/agent-presets/README.md)). Taking the parent as a parameter is deliberate — it makes composing a child WITHOUT that join unrepresentable at the call sites, which is the defect the one call exists to prevent. A deployment composing no preset roster joins nothing and needs nothing: its model-facing rows sit in the host composition, where the child already resolves them through the tool registry's global layer. `childSessionMeta()` records the joined preset id on the child's durable header for the same reason a top-level session records its own: the preset decides the tool schemas and prompt sections the model saw, so a cold read of the child's history has to rebuild that composition rather than the deployment default. It is read from the parent's live scope chain, not from the parent header, because a parent that switched preset while blank runs on the newer composition while its header still names the older one. @@ -49,7 +52,7 @@ Continuable creation is the optional `SubagentProvider.prepareContinuable?()` me ## The durable descriptor -The Service Definition owns the versioned `subagent/descriptor` session event vocabulary (`src/descriptor.ts`): `snapshotSubagentDescriptor()` validates and detaches the record before provider work, and `foldSubagentDescriptor()` validates the complete current-version payload before recovering it from a loaded child log. Every local session-backed start appends one descriptor with the provider name and lifecycle `mode`. A `one-shot` descriptor optionally carries the caller-owned durable display `label`; a `continuable` descriptor requires its durable creation label and additionally records resolved child `agentOptions.provider`/`model` and optional `persona`/`toolFilter` for cold resume. These are explicit fields, never the merge-extensible `AgentOptions` object, so an unrelated extension value cannot break continuation. The descriptor omits `subagentDepth` (the persisted header's `delegationDepth` is the monotone floor) and `outputSchema` (an Activation's result contract). The event is log-only: no `surfaceOp`, absent from model history, and retained by the append-only log across compaction. Malformed current-version payloads are corrupt; unsupported versions cannot be classified by this runtime. +The Service Definition owns the versioned `subagent/descriptor` session event vocabulary (`src/descriptor.ts`): `snapshotSubagentDescriptor()` validates and detaches the record before provider work, and `foldSubagentDescriptor()` validates the complete current-version payload before recovering it from a loaded child log. Every local session-backed start appends one descriptor with the provider name and lifecycle `mode`. A `one-shot` descriptor optionally carries the caller-owned durable display `label`; a `continuable` descriptor requires its durable creation label and additionally records resolved child `agentOptions.provider`/`model`/`reasoningEffort` and optional `persona`/`toolFilter` for cold resume. These are explicit fields, never the merge-extensible `AgentOptions` object, so an unrelated extension value cannot break continuation. The descriptor omits `subagentDepth` (the persisted header's `delegationDepth` is the monotone floor) and `outputSchema` (an Activation's result contract). The event is log-only: no `surfaceOp`, absent from model history, and retained by the append-only log across compaction. Malformed current-version payloads are corrupt; unsupported versions cannot be classified by this runtime. ## Delegation depth diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index e289863531..cf434152cd 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -26,7 +26,7 @@ subagent seam 允许一个 agent(智能体)通过具名提供方把工作委 | `listChildren(parentSessionId, signal?)` | 按 `createdAt`、再按 id 的顺序列出由会话支撑的直接 subagent,包括其 `one-shot`/`continuable` 模式、`running`/`inactive` 活动状态、根据 origin 分类得出的一层 `hasChildren` 提示,以及每个子级的诊断信息,且不会加载或恢复它们。该操作直接读取在线会话存储和可选的会话持久化(没有持久化时只枚举在线子级),并要求已挂载 `sessionProjections` 注册表;不要求 `ctx.agents`、继续执行管理器或任何查询服务。 | | `listDescendants(rootSessionId, signal?)` | 从同一份在线优先语料按稳定 pre-order 展平根的完整会话树,并为每个 subagent 条目附加持久 `parentId` 与相对根的 `depth`。普通会话与一次性 child 仍作为遍历节点,因此其下的可继续后代仍可发现。身份、diagnostic、依赖与取消约定均沿用 `listChildren()`。 | -`SubagentStartRequest.label` 是由会话支撑的一次性 child 所使用的可选简短持久化显示标签。面向模型的委派会提供其已有的 `description`;底层调用方无需凭空构造展示元数据。可继续启动始终携带自身的必填标签。`signal` 是必填项,也是一次性 `start` 的规范取消通道。发布前中止会使 `start()` 在回滚后拒绝;发布后中止会取消已返回 run 的剩余轮次工作,但不会隐藏其 id。请求还可以选择模型、要求结构化输出、限制委派深度、约束子 agent 工具或设置子 agent persona。对于可继续启动或后续操作,调用方信号只负责 inbox 接受前的查找、物化和准入;此后,Activation 由管理器独立拥有,因此调用方取消既不会取消已接受的轮次,也不会 dispose(资源释放)子 agent。 +`SubagentStartRequest.label` 是由会话支撑的一次性 child 所使用的可选简短持久化显示标签。面向模型的委派会提供其已有的 `description`;底层调用方无需凭空构造展示元数据。可继续启动始终携带自身的必填标签。`signal` 是必填项,也是一次性 `start` 的规范取消通道。发布前中止会使 `start()` 在回滚后拒绝;发布后中止会取消已返回 run 的剩余轮次工作,但不会隐藏其 id。请求还可以覆盖宿主 Agent 的提供方、模型、推理强度与 token 上限、要求结构化输出、限制委派深度、约束子 agent 工具或设置子 agent persona。每个被请求的可选特性都要求匹配的提供方能力。对于可继续启动或后续操作,调用方信号只负责 inbox 接受前的查找、物化和准入;此后,Activation 由管理器独立拥有,因此调用方取消既不会取消已接受的轮次,也不会 dispose(资源释放)子 agent。 后续操作的权限来自子 agent 持久化 header 中记录的确切在线直接父级。冷恢复会在重建前检查该权限,并在最终无 await 的 inbox 准入区间再次检查,因此在物化期间被注销或替换的 parent 无法授权投递。后续操作上的 `source` 记录谁提供了所投递的消息,不授予任何权限。 @@ -36,11 +36,14 @@ subagent seam 允许一个 agent(智能体)通过具名提供方把工作委 启动时功能通过 `provider.capabilities` 声明,因为服务必须在创建子 agent 前拒绝不受支持的一次性请求: +- `agentOptions`:应用宿主 Agent 提供方、模型、推理强度与输出 token 上限覆盖; - `outputSchema`:强制执行结构化最终结果; - `depthLimit`:强制执行 `maxDepth`; - `toolFilter`:应用请求的子 agent 工具限制; - `persona`:应用每个子 agent 独立的 persona。 +两个进程内提供方都会声明 `agentOptions`:创建子 agent 时,请求字段会覆盖父级最新记录请求中的提供方、模型与推理强度;首个请求之前回退到其创建选项,并保留其中配置的 token 上限。更换路由但没有显式指定强度时,会清除继承的路由所属强度,使所选模型解析自己的默认值。当前进程外提供方会声明不支持,因此配置或模型选择的覆盖会在启动子传输前失败,而不会被静默忽略。 + 每个进程内子 agent 都通过一次 `applyChildComposition(childCtx, parent, composition)` 调用完成组装:先加入父级的 agent-preset 组合,再应用子 agent 自己的 persona 和工具限制。加入父级组合正是子 agent 获得能力的途径:所有面向模型的行都位于 agent 平面,完全没有加入任何组合的子 agent 抵达模型时会看到空的工具注册表(见 [`dsh-agent-presets`](../../preset/agent-presets/README.zh.md))。将父级作为参数是刻意设计:这让“组装子 agent 却不做该加入”在各调用点无法表达,而这正是这一次调用所要杜绝的缺陷。未组装 preset roster 的部署不加入任何组合、也不需要加入;其面向模型的行位于宿主组合中,子 agent 已能通过工具注册表的全局层解析到它们。 `childSessionMeta()` 把所加入的 preset id 记在子 agent 的持久化 header 上,理由与顶层会话记录自己的那一个相同:preset 决定了模型所见的工具 schema 与提示段,因此冷读子 agent 的历史时必须重建那份组装,而不是部署默认值。该值从父方**活着的** scope 链读取,而不是从父方 header 读取,因为在空白期切换过 preset 的父方运行在更新的那份组装上,而它的 header 仍写着旧的那个。 @@ -49,7 +52,7 @@ subagent seam 允许一个 agent(智能体)通过具名提供方把工作委 ## 持久化描述符 -该 Service Definition 拥有版本化的 `subagent/descriptor` 会话事件词汇(`src/descriptor.ts`):`snapshotSubagentDescriptor()` 会在提供方工作之前校验并分离记录,`foldSubagentDescriptor()` 则会在从已加载子 agent 日志中恢复描述符之前,校验当前版本的完整 payload。每次由本地会话支撑的启动都会追加一个带有提供方名称与生命周期 `mode` 的描述符。`one-shot` 描述符可以携带调用方拥有的可选持久化显示 `label`;`continuable` 描述符要求其持久化创建标签,并另外记录已解析的子 agent `agentOptions.provider`/`model`,以及用于从持久化存储恢复的可选 `persona`/`toolFilter`。这些是显式字段,绝不是可通过合并扩展的 `AgentOptions` 对象,因此无关的扩展值不会破坏继续执行。描述符省略 `subagentDepth`(持久化 header 的 `delegationDepth` 是单调下界)和 `outputSchema`(单次 Activation 的结果约定)。该事件只进入日志:不含 `surfaceOp`,不进入模型历史,并由仅追加日志跨压缩(compaction)保留。格式错误的当前版本 payload 属于损坏;本运行时无法对不受支持的版本进行分类。 +该 Service Definition 拥有版本化的 `subagent/descriptor` 会话事件词汇(`src/descriptor.ts`):`snapshotSubagentDescriptor()` 会在提供方工作之前校验并分离记录,`foldSubagentDescriptor()` 则会在从已加载子 agent 日志中恢复描述符之前,校验当前版本的完整 payload。每次由本地会话支撑的启动都会追加一个带有提供方名称与生命周期 `mode` 的描述符。`one-shot` 描述符可以携带调用方拥有的可选持久化显示 `label`;`continuable` 描述符要求其持久化创建标签,并另外记录已解析的子 agent `agentOptions.provider`/`model`/`reasoningEffort`,以及用于从持久化存储恢复的可选 `persona`/`toolFilter`。这些是显式字段,绝不是可通过合并扩展的 `AgentOptions` 对象,因此无关的扩展值不会破坏继续执行。描述符省略 `subagentDepth`(持久化 header 的 `delegationDepth` 是单调下界)和 `outputSchema`(单次 Activation 的结果约定)。该事件只进入日志:不含 `surfaceOp`,不进入模型历史,并由仅追加日志跨压缩(compaction)保留。格式错误的当前版本 payload 属于损坏;本运行时无法对不受支持的版本进行分类。 ## 委派深度 diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 7582338858..22c9e77bf5 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -57,9 +57,38 @@ export function resolveChildDepth(parent: Agent, maxDepth: number | undefined): } /** - * Resolve the child's `AgentOptions`: the parent's provider/model/maxTokens - * route unless the request overrides it, stamped with the child's own - * delegation depth. + * Resolve the parent values inherited by a child. The latest request header + * owns provider, model, and reasoning effort after request-time selection; + * creation options remain the fallback before the first request and retain + * the configured output-token limit. + * @param parent - delegating parent Agent. + * @returns detached Agent options for child-option merging. + */ +export function parentAgentOptionsForDelegation(parent: Agent): AgentOptions { + const requestConfig = parent.session.requestHeader()?.config + if (requestConfig === undefined) return { ...parent.options } + const { + provider: _createdProvider, + model: _createdModel, + reasoningEffort: _createdReasoningEffort, + ...createdOptions + } = parent.options + return { + ...createdOptions, + provider: requestConfig.provider, + model: requestConfig.model, + ...requestConfig.reasoningEffort === undefined + ? {} + : { reasoningEffort: requestConfig.reasoningEffort }, + } +} + +/** + * Resolve the child's `AgentOptions`: the parent's provider/model, + * reasoning-effort, and maxTokens values unless the request overrides them, + * stamped with the child's own delegation depth. Changing the route without + * naming an effort clears the parent's route-owned effort so the selected + * model resolves its own default. * @param parent - the delegating parent whose route the child inherits. * @param requested - per-child overrides, if any. * @param childDepth - the resolved delegation depth to stamp. @@ -70,16 +99,22 @@ export function resolveChildAgentOptions( requested: AgentOptions | undefined, childDepth: number, ): AgentOptions { - const parentProvider = parent.options.provider - const parentModel = parent.options.model - const parentMaxTokens = parent.options.maxTokens - return { + const parentOptions = parentAgentOptionsForDelegation(parent) + const parentProvider = parentOptions.provider + const parentModel = parentOptions.model + const parentReasoningEffort = parentOptions.reasoningEffort + const parentMaxTokens = parentOptions.maxTokens + const resolved: AgentOptions = { ...parentProvider !== undefined ? { provider: parentProvider } : {}, ...parentModel !== undefined ? { model: parentModel } : {}, + ...parentReasoningEffort !== undefined ? { reasoningEffort: parentReasoningEffort } : {}, ...parentMaxTokens !== undefined ? { maxTokens: parentMaxTokens } : {}, ...requested, subagentDepth: childDepth, } + const routeChanged = resolved.provider !== parentProvider || resolved.model !== parentModel + if (routeChanged && requested?.reasoningEffort === undefined) delete resolved.reasoningEffort + return resolved } /** diff --git a/packages/subagent/subagent/src/continuation.ts b/packages/subagent/subagent/src/continuation.ts index 652a3ba6c8..2588c1a699 100644 --- a/packages/subagent/subagent/src/continuation.ts +++ b/packages/subagent/subagent/src/continuation.ts @@ -30,7 +30,7 @@ import type { AgentSetupCommit, CreateAgentOptions, } from '@deepseek-ai/dsh-agent' -import { boundContextSummary, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' +import { ReasoningEffortId, boundContextSummary, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' @@ -417,14 +417,17 @@ export class SubagentContinuationManager { const childDepth = resolveChildDepth(parent, request.maxDepth) // Snapshot before any await: invalid descriptor JSON rejects the call // before a child exists, and the detached value is what reaches the log. - const agentProvider = request.agentOptions?.provider ?? parent.options.provider - const agentModel = request.agentOptions?.model ?? parent.options.model + const agentOptions = resolveChildAgentOptions(parent, request.agentOptions, childDepth) + const agentProvider = agentOptions.provider + const agentModel = agentOptions.model + const agentReasoningEffort = agentOptions.reasoningEffort const descriptor = snapshotSubagentDescriptor({ mode: 'continuable', provider: spec.provider, label: spec.label, ...agentProvider !== undefined ? { agentProvider } : {}, ...agentModel !== undefined ? { agentModel } : {}, + ...agentReasoningEffort !== undefined ? { agentReasoningEffort } : {}, ...request.persona !== undefined ? { persona: request.persona } : {}, ...request.toolFilter !== undefined ? { toolFilter: request.toolFilter } : {}, }) @@ -460,7 +463,7 @@ export class SubagentContinuationManager { provider: spec.provider, parent, create: { seed, meta: childSessionMeta(parent, childDepth, lineageSeedLength), delegatedPolicies }, - agentOptions: resolveChildAgentOptions(parent, request.agentOptions, childDepth), + agentOptions, composition: { persona: request.persona, toolFilter: request.toolFilter }, signal: spec.signal, }) @@ -981,6 +984,9 @@ export class SubagentContinuationManager { agentOptions: { ...descriptor.agentProvider !== undefined ? { provider: descriptor.agentProvider } : {}, ...descriptor.agentModel !== undefined ? { model: descriptor.agentModel } : {}, + ...descriptor.agentReasoningEffort !== undefined + ? { reasoningEffort: ReasoningEffortId(descriptor.agentReasoningEffort) } + : {}, }, composition: { persona: descriptor.persona, toolFilter: descriptor.toolFilter }, signal: options.signal, diff --git a/packages/subagent/subagent/src/descriptor.ts b/packages/subagent/subagent/src/descriptor.ts index 6d9dedee75..9a25c382b1 100644 --- a/packages/subagent/subagent/src/descriptor.ts +++ b/packages/subagent/subagent/src/descriptor.ts @@ -23,6 +23,7 @@ import { snapshotJsonValue } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' +import type { ReasoningEffortId } from '@deepseek-ai/dsh-llm' import type { ToolRestriction } from '@deepseek-ai/dsh-tools' declare module '@deepseek-ai/dsh-session/types' { @@ -44,7 +45,7 @@ declare module '@deepseek-ai/dsh-session/types' { * Supporting another composition input is a deliberate version change, never * an implicit extra field. */ -export const SUBAGENT_DESCRIPTOR_VERSION = 2 +export const SUBAGENT_DESCRIPTOR_VERSION = 3 /** Fields shared by every supported `subagent/descriptor` payload. */ interface SubagentDescriptorBase { @@ -76,6 +77,8 @@ export interface ContinuableSubagentDescriptorData extends SubagentDescriptorBas readonly agentProvider?: string /** Resolved child `agentOptions.model`, when one was declared. */ readonly agentModel?: string + /** Resolved child `agentOptions.reasoningEffort`, when one was declared. */ + readonly agentReasoningEffort?: ReasoningEffortId /** Per-child persona that shadows the deployment persona on resume. */ readonly persona?: string /** Child tool scoping reapplied on resume. */ @@ -111,6 +114,8 @@ export interface ContinuableSubagentDescriptorInput extends SubagentDescriptorIn readonly agentProvider?: string /** Requested child `agentOptions.model`. */ readonly agentModel?: string + /** Requested child `agentOptions.reasoningEffort`. */ + readonly agentReasoningEffort?: ReasoningEffortId /** Requested per-child persona. */ readonly persona?: string /** Requested child tool scoping. */ @@ -133,6 +138,7 @@ const CONTINUABLE_DESCRIPTOR_KEYS = new Set([ ...DESCRIPTOR_BASE_KEYS, 'agentProvider', 'agentModel', + 'agentReasoningEffort', 'persona', 'toolFilter', ]) @@ -231,6 +237,7 @@ function parseSubagentDescriptor(value: unknown): SubagentDescriptorData | undef } const agentProvider = optionalString(value, 'agentProvider') const agentModel = optionalString(value, 'agentModel') + const agentReasoningEffort = optionalString(value, 'agentReasoningEffort') as ReasoningEffortId | undefined const persona = optionalString(value, 'persona') const toolFilter = Object.hasOwn(value, 'toolFilter') ? parseToolFilter(value['toolFilter']) @@ -242,6 +249,7 @@ function parseSubagentDescriptor(value: unknown): SubagentDescriptorData | undef label, ...agentProvider !== undefined ? { agentProvider } : {}, ...agentModel !== undefined ? { agentModel } : {}, + ...agentReasoningEffort !== undefined ? { agentReasoningEffort } : {}, ...persona !== undefined ? { persona } : {}, ...toolFilter !== undefined ? { toolFilter } : {}, } @@ -283,6 +291,7 @@ export function snapshotSubagentDescriptor(input: SubagentDescriptorInput): Suba label: input.label, ...input.agentProvider !== undefined ? { agentProvider: input.agentProvider } : {}, ...input.agentModel !== undefined ? { agentModel: input.agentModel } : {}, + ...input.agentReasoningEffort !== undefined ? { agentReasoningEffort: input.agentReasoningEffort } : {}, ...input.persona !== undefined ? { persona: input.persona } : {}, ...input.toolFilter !== undefined ? { toolFilter: input.toolFilter } : {}, } diff --git a/packages/subagent/subagent/src/index.ts b/packages/subagent/subagent/src/index.ts index 2f29e32010..42dca84908 100644 --- a/packages/subagent/subagent/src/index.ts +++ b/packages/subagent/subagent/src/index.ts @@ -103,6 +103,7 @@ export { applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, + parentAgentOptionsForDelegation, resolveChildAgentOptions, resolveChildDepth, SubagentDepthError, @@ -494,6 +495,7 @@ export class SubagentRuntime extends Service { /** Reject the first requested capability that the provider lacks. */ private assertCapabilities(provider: SubagentProvider, request: SubagentStartRequest): void { const needs: { when: boolean; cap: keyof SubagentCapabilities }[] = [ + { when: request.agentOptions !== undefined, cap: 'agentOptions' }, { when: request.outputSchema !== undefined, cap: 'outputSchema' }, { when: request.maxDepth !== undefined, cap: 'depthLimit' }, { when: request.toolFilter !== undefined, cap: 'toolFilter' }, diff --git a/packages/subagent/subagent/src/out-of-process.ts b/packages/subagent/subagent/src/out-of-process.ts index abb6dd50e7..2667884af4 100644 --- a/packages/subagent/subagent/src/out-of-process.ts +++ b/packages/subagent/subagent/src/out-of-process.ts @@ -44,10 +44,11 @@ function limitSubagentDiagnostic(diagnostic: string): string { /** * The capability advertisement of an out-of-process backend: NONE. A child in * another process cannot honor parent-enforced start features - * (`outputSchema`/`maxDepth`/`toolFilter`/`persona`), so the service rejects a + * (`agentOptions`/`outputSchema`/`maxDepth`/`toolFilter`/`persona`), so the service rejects a * request needing any of them before `start` runs — never accepted-then-ignored. */ export const NO_START_CAPABILITIES: SubagentCapabilities = Object.freeze({ + agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, diff --git a/packages/subagent/subagent/src/types.ts b/packages/subagent/subagent/src/types.ts index 17978550ab..415379ca75 100644 --- a/packages/subagent/subagent/src/types.ts +++ b/packages/subagent/subagent/src/types.ts @@ -84,6 +84,7 @@ export interface SubagentRunEndInfo { * to `maxDepth`; the other names match. */ export interface SubagentCapabilities { + readonly agentOptions: boolean readonly outputSchema: boolean readonly depthLimit: boolean readonly toolFilter: boolean @@ -116,6 +117,12 @@ export interface SubagentStartRequest { * remaining turn work when it fires afterward. */ readonly signal: AbortSignal + /** + * Optional host-Agent provider, model, reasoning-effort, and output-token + * overrides. Requires {@link SubagentCapabilities.agentOptions}; in-process + * providers merge them over the parent Agent's options when they create the + * child. + */ readonly agentOptions?: AgentOptions /** * Object-rooted JSON Schema within `assertObjectJsonSchema`'s enforced subset. Start rejects diff --git a/packages/subagent/subagent/tests/child-agent.spec.ts b/packages/subagent/subagent/tests/child-agent.spec.ts new file mode 100644 index 0000000000..92302cfca4 --- /dev/null +++ b/packages/subagent/subagent/tests/child-agent.spec.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import { resolveChildAgentOptions } from '../src/child-agent.ts' + +function parentAgent(): Agent { + const id = SessionId('parent') + return { + id, + options: { + provider: 'parent-provider', + model: 'parent-model', + reasoningEffort: ReasoningEffortId('high'), + maxTokens: 512, + }, + session: Session.create(id), + } as Agent +} + +describe('child Agent options', () => { + it('inherits the parent effort while the exact route is unchanged', () => { + expect(resolveChildAgentOptions(parentAgent(), undefined, 1)).toEqual({ + provider: 'parent-provider', + model: 'parent-model', + reasoningEffort: 'high', + maxTokens: 512, + subagentDepth: 1, + }) + }) + + it('clears an inherited effort when the child route changes', () => { + expect(resolveChildAgentOptions(parentAgent(), { model: 'child-model' }, 1)).toEqual({ + provider: 'parent-provider', + model: 'child-model', + maxTokens: 512, + subagentDepth: 1, + }) + }) + + it('keeps an explicit child effort when the child route changes', () => { + expect(resolveChildAgentOptions(parentAgent(), { + provider: 'child-provider', + model: 'child-model', + reasoningEffort: ReasoningEffortId('max'), + }, 1)).toEqual({ + provider: 'child-provider', + model: 'child-model', + reasoningEffort: 'max', + maxTokens: 512, + subagentDepth: 1, + }) + }) + + it('inherits the latest logged request selection over creation-time values', () => { + const parent = parentAgent() + parent.session.append('request/header', { + header: { + config: { + provider: 'current-provider', + model: 'current-model', + reasoningEffort: ReasoningEffortId('low'), + }, + }, + reason: 'initial', + }) + + expect(resolveChildAgentOptions(parent, undefined, 1)).toEqual({ + provider: 'current-provider', + model: 'current-model', + reasoningEffort: 'low', + maxTokens: 512, + subagentDepth: 1, + }) + }) +}) diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index 6cf1aea5a8..d1d40e0ff4 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -12,7 +12,7 @@ import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' import type { GenerateOptions, MessageId, StreamChunk } from '@deepseek-ai/dsh-llm' -import { CallId, createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm' +import { CallId, createUserMessage, LlmAdapter, ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { defineTool } from '@deepseek-ai/dsh-tools' import InvariantRegistry from '@deepseek-ai/dsh-invariants' import { MockAdapter, maxTokensResponse, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' @@ -239,7 +239,7 @@ describe('SubagentRuntime.startContinuable', () => { const start = vi.fn(async () => { throw new Error('must not dispatch') }) ctx.subagents.registerProvider({ name: 'one-shot', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start, }) @@ -283,6 +283,40 @@ describe('SubagentRuntime.startContinuable', () => { expect(loaded.meta.origin).toBe('subagent') }) + it('persists a selected reasoning effort and reapplies it on cold resume', async () => { + const effort = ReasoningEffortId('max') + const adapter = new MockAdapter([ + textResponse('first answer'), + textResponse('resumed answer'), + ], { + efforts: [{ id: effort, name: 'Max' }], + defaultEffort: effort, + }) + const { ctx, parent } = await setupWith(adapter) + parkParent(ctx, parent) + const childEfforts: Array = [] + ctx.on('agent/created', ({ agent }) => { + if (agent !== parent) childEfforts.push(agent.options.reasoningEffort) + }) + + const started = await ctx.subagents.startContinuable({ + ...startSpec(parent), + request: { + prompt: message('selected reasoning'), + parent, + agentOptions: { reasoningEffort: effort }, + }, + }) + await waitNoActivation(ctx, started.childId) + const loaded = await ctx.sessionPersistence.load(started.childId) + expect(loaded.events.find(event => event.type === 'subagent/descriptor')?.data) + .toMatchObject({ agentReasoningEffort: 'max' }) + + await followup(ctx, parent, started.childId, message('resume selected reasoning')) + await waitNoActivation(ctx, started.childId) + expect(childEfforts).toEqual(['max', 'max']) + }) + it('rolls the child back completely when the caller signal aborts before acceptance', async () => { const { ctx, parent } = await setup([textResponse('unused')]) const controller = new AbortController() @@ -531,7 +565,7 @@ describe('SubagentRuntime.followup residency routing', () => { await ctx.plugin(SubagentInvariant) const disposeProvider = ctx.subagents.registerProvider({ name: 'retired', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => { throw new Error('one-shot start is not used') }, prepareContinuable: () => Promise.resolve({}), @@ -2418,27 +2452,43 @@ describe('continuable errors', () => { hold.resolve(undefined) }) - it('reapplies the descriptor model route on cold resume', async () => { - const { ctx, parent } = await setup([textResponse('first'), textResponse('resumed')]) + it('reapplies the descriptor model route and reasoning effort on cold resume', async () => { + const effort = ReasoningEffortId('high') + const adapter = new MockAdapter([textResponse('first'), textResponse('resumed')], { + efforts: [{ id: effort, name: 'High' }], + defaultEffort: effort, + }) + const { ctx, parent } = await setupWith(adapter) const started = await ctx.subagents.startContinuable({ ...startSpec(parent), request: { prompt: message('routed work'), parent, - agentOptions: { provider: 'mock', model: 'child-model' }, + agentOptions: { provider: 'mock', model: 'child-model', reasoningEffort: effort }, }, }) await waitNoActivation(ctx, started.childId) const loaded = await ctx.sessionPersistence.load(started.childId) expect(loaded.events.find(event => event.type === 'subagent/descriptor')?.data) - .toMatchObject({ agentProvider: 'mock', agentModel: 'child-model' }) + .toMatchObject({ + agentProvider: 'mock', + agentModel: 'child-model', + agentReasoningEffort: 'high', + }) // The resumed Activation runs on the declared route, not the parent's. await followup(ctx, parent, started.childId, message('again')) await vi.waitFor(() => { - expect(ctx.agents.get(started.childId)?.options.model).toBe('child-model') + expect(ctx.agents.get(started.childId)?.options).toMatchObject({ + model: 'child-model', + reasoningEffort: 'high', + }) }) await waitNoActivation(ctx, started.childId) + const resumed = await ctx.sessionPersistence.load(started.childId) + expect(resumed.events.flatMap(event => event.type === 'request/header' + ? [event.data.header.config.reasoningEffort] + : [])).toEqual([effort, effort]) }) it('unloading the manager drains its live activations', async () => { diff --git a/packages/subagent/subagent/tests/invariant.spec.ts b/packages/subagent/subagent/tests/invariant.spec.ts index 91200abf8d..08792c2348 100644 --- a/packages/subagent/subagent/tests/invariant.spec.ts +++ b/packages/subagent/subagent/tests/invariant.spec.ts @@ -21,7 +21,7 @@ async function setup(): Promise { const provider = (name: string): SubagentProvider => ({ name, - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => { throw new Error('not used') }, }) diff --git a/packages/subagent/subagent/tests/out-of-process.spec.ts b/packages/subagent/subagent/tests/out-of-process.spec.ts index 0d3307ca51..98b670f36f 100644 --- a/packages/subagent/subagent/tests/out-of-process.spec.ts +++ b/packages/subagent/subagent/tests/out-of-process.spec.ts @@ -21,7 +21,13 @@ import { describe('NO_START_CAPABILITIES', () => { it('advertises nothing and is frozen (shared by every out-of-process backend)', () => { - expect(NO_START_CAPABILITIES).toEqual({ outputSchema: false, depthLimit: false, toolFilter: false, persona: false }) + expect(NO_START_CAPABILITIES).toEqual({ + agentOptions: false, + outputSchema: false, + depthLimit: false, + toolFilter: false, + persona: false, + }) expect(Object.isFrozen(NO_START_CAPABILITIES)).toBe(true) }) }) diff --git a/packages/subagent/subagent/tests/service.spec.ts b/packages/subagent/subagent/tests/service.spec.ts index 05e9785611..6a93f2fdef 100644 --- a/packages/subagent/subagent/tests/service.spec.ts +++ b/packages/subagent/subagent/tests/service.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, expectTypeOf, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { type Agent } from '@deepseek-ai/dsh-agent' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError, ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { carrierKeyOf } from '@deepseek-ai/dsh-scope' import SubagentRuntime, { foldSubagentDescriptor, @@ -24,8 +24,8 @@ function fakeParent(id = 'parent-1'): Agent { return { id: SessionId(id) } as unknown as Agent } -const ALL_CAPS: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: true } -const NO_CAPS: SubagentCapabilities = { outputSchema: false, depthLimit: false, toolFilter: false, persona: false } +const ALL_CAPS: SubagentCapabilities = { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true } +const NO_CAPS: SubagentCapabilities = { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false } function baseRequest(overrides: Partial = {}): SubagentStartRequest { return { @@ -162,6 +162,7 @@ describe('SubagentRuntime', () => { }) it.each([ + ['agentOptions', { agentOptions: { model: 'child-model' } }], ['outputSchema', { outputSchema: { type: 'object', properties: {} } }], ['depthLimit', { maxDepth: 1 }], ['toolFilter', { toolFilter: { deny: ['bash'] } }], @@ -348,6 +349,7 @@ describe('subagent descriptors', () => { label: 'complete child', agentProvider: 'deepseek', agentModel: 'chat', + agentReasoningEffort: ReasoningEffortId('high'), persona: 'reviewer', toolFilter: { allow: ['read'], deny: ['bash'] }, } @@ -357,6 +359,7 @@ describe('subagent descriptors', () => { label: complete.label, agentProvider: complete.agentProvider, agentModel: complete.agentModel, + agentReasoningEffort: complete.agentReasoningEffort, persona: complete.persona, toolFilter: complete.toolFilter, })).toEqual(complete) @@ -448,6 +451,13 @@ describe('subagent descriptors', () => { label: 'l', agentModel: [], }, 'agentModel must be a string'], + ['invalid agent reasoning effort', { + version: SUBAGENT_DESCRIPTOR_VERSION, + mode: 'continuable', + provider: 'spawn', + label: 'l', + agentReasoningEffort: 7, + }, 'agentReasoningEffort must be a string'], ['invalid persona', { version: SUBAGENT_DESCRIPTOR_VERSION, mode: 'continuable', diff --git a/packages/subagent/tool-subagent/README.i18n.yaml b/packages/subagent/tool-subagent/README.i18n.yaml index 29d65cf9da..f6caeb1941 100644 --- a/packages/subagent/tool-subagent/README.i18n.yaml +++ b/packages/subagent/tool-subagent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/tool-subagent/README.md -README.md: 28e6213b903ffffa7934e244b2a74ada519b32b2 -README.zh.md: 74e8896a152c787abd0aebf055d6e13f6158bcd3 +README.md: e643442de7fa45f15a5c2bf818e2c25feb44b6c5 +README.zh.md: aa6dec73c66ce6b4db525d09cd166e671dbec9dc diff --git a/packages/subagent/tool-subagent/README.md b/packages/subagent/tool-subagent/README.md index 28e6213b90..e643442de7 100644 --- a/packages/subagent/tool-subagent/README.md +++ b/packages/subagent/tool-subagent/README.md @@ -6,7 +6,11 @@ The model-facing delegation tool over one configured `ctx.subagents` provider. C ## Provider selection and lifecycle -Each plugin instance binds one `provider` to one `toolName`; the model receives no provider selector. Load another distinctly named instance to expose another transport. The tool registers only while its provider exists, avoiding sibling load-order and provider-reload dependencies. Its description follows `provider.inheritsParentContext`: fresh children require standalone prompts, while forked children already see completed parent turns. +Each plugin instance binds one subagent transport `provider` to one `toolName`; the model cannot change that transport. Load another distinctly named instance to expose another transport. `enableModelSelection: true`, or an enabled Host preference when `modelSelectionSettings: true`, requires that provider's child `agentOptions` capability and exposes optional child LLM `provider`, `model`, and `reasoning_effort` fields without additional route configuration. A call may supply a complete provider/model pair, or only an effort when configured or parent values supply the effective route. The live adapter resolves explicit or configured routes before child creation. A call that omits every selection field uses `agentOptions` and then inherits compatible missing values from the parent's latest logged request selection, falling back to its creation options before the first request and retaining its configured `maxTokens`. Changing provider or model without naming an effort clears the lower layer's route-owned effort so the selected model resolves its default. + +The delegation tool registers only while its subagent provider exists, avoiding sibling load-order and provider-reload dependencies. When model selection is enabled, its optional fields remain visible without `ctx.llm`; a call that selects a route rejects if the service is unavailable. When disabled, the schema omits those fields and execution rejects a forced selection. Configured `agentOptions` remain deployment-owned child defaults independently of this model-facing switch. Adapter catalog and topology changes do not rewrite or re-register the tool. Its description follows `provider.inheritsParentContext`: fresh children require standalone prompts, while forked children already see completed parent turns. + +An enabled definition registers `list_subagent_models`, which lists registered providers, one provider's advertised models, or one exact model's reasoning efforts at call time. At most one instance in a tool scope may enable selection because this discovery tool has a global name; duplicate owners fail registration. Shipped product compositions default the primary `subagent` (`spawn`) instance off and sample the Host `subagent-model-selection.enabled` preference when each new top-level session is composed. The enabled decision is logged as `subagent/model-selection-enabled`, inherited by child sessions, and retained on resume; later settings edits do not change a running session. Shipped compositions deliberately keep `subagent_fork` disabled so the fork inherits the parent's provider and model: changing that route would forfeit provider-side KV Cache reuse of the inherited conversation prefix and can make prefix recomputation dominate the delegated task's cost. This restriction remains even if discovery ownership is separated. Catalog membership remains advisory: an enabled delegation tool accepts an unlisted model id when its adapter does. The [model-selected route Agent Note](../../../.agents/notes/implemented/feature/2026-08-18-model-selected-subagent-routes.md) owns the rationale and reintroduction condition. A foreground call passes the execution signal through startup and execution, awaits `run.result`, and always awaits `run.dispose()` before returning. Only `completed` returns the canonical `{ kind: 'foreground', runId, output: JsonValue[] }`, rendered as the same final text. Abort, refusal, token limit, and other failures become errored tool results whose message contains the stop-reason headline, an optional provider-authored `SubagentResult.diagnostic`, and then any preserved partial assistant text. The diagnostic remains separate from `SubagentResult.output`, so a truncated answer is never reported as success or confused with infrastructure detail. If result collection and disposal both reject, the errored result preserves both failures. @@ -20,9 +24,11 @@ A foreground call passes the execution signal through startup and execution, awa |---|---| | `provider` (required) | Provider name (`spawn`, `fork`, `acp`, ...). | | `toolName` | Model-facing name, default `subagent`; distinct for every loaded instance. | +| `enableModelSelection` | Exposes and accepts model-facing child LLM selection fields and registers the shared `list_subagent_models` tool, default `false`. It requires the subagent provider's `agentOptions` capability. At most one instance in a tool scope may enable it; the discovery schema remains registered without `ctx.llm`, while discovery and selected-route calls reject until that optional service is available. Configured `agentOptions` remain available when this switch is disabled. | +| `modelSelectionSettings` | Samples the Host `subagent-model-selection` preference while composing an Agent, records an enabled decision in its Session, and inherits that decision in child Sessions. Default `false`; mutually exclusive with `enableModelSelection` and valid only in an Agent-scoped composition. The preference defaults off and changes only subsequently composed top-level Sessions. | | `enableRunInBackground` | Exposes background mode, default `true`; disabling also rejects forced background calls. | | `backgroundMode` | Background lifecycle policy, default `one-shot`. `one-shot` defaults calls to foreground; `continuable` defaults them to background, requires the provider's `prepareContinuable` capability, and returns a durable child id without requiring the follow-up tool. | -| `agentOptions` | Provider-specific child `provider`, `model`, and positive `maxTokens`; the in-process provider treats explicit values as overrides of inherited parent options. | +| `agentOptions` | Configured child LLM `provider`, `model`, adapter-owned `reasoningEffort`, and positive `maxTokens`; requires the subagent provider's `agentOptions` capability. In-process providers merge explicit values over the parent's latest logged request selection, or its creation options before the first request. An inherited effort survives only while the effective provider/model route is unchanged; changing the route without an explicit effort lets the selected model supply its default. A configured provider, model, or effort is checked through the optional `ctx.llm` service before child creation even when the call omits model-selection fields; a missing service or invalid value rejects the call. | | `persona` | Per-child persona; requires provider `persona` capability. | | `toolFilter` | Per-child global-tool restriction; requires `toolFilter` capability. | | `maxDepth` | Absolute delegation-depth cap, default `3` (`0` forbids delegation); a numeric cap requires the `depthLimit` capability and fails the mount without it. `'provider-managed'` sends no cap for an out-of-process provider whose budget belongs to the child harness. The tool stays visible at the cap; each attempted start checks the calling agent's current depth and returns an errored tool result when rejected. | @@ -37,15 +43,29 @@ Foreground and background calls are concurrency-safe: sibling delegations in one #### What the model sees -The generated default [`subagent` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-subagent) under this instance's configured name while its provider exists. Provider context inheritance changes the tool and prompt descriptions. Enabled background mode adds `run_in_background`: continuable mode documents its `true` default, runtime settlement notice, and explicit foreground override, while one-shot mode documents its `false` default and the job id collected with `job_output` or stopped with `job_kill`. While the tool is visible in an assembly's scope, a `tool:` system-prompt section tells the model to start independent continuable delegations together, keep working while they run, and choose foreground only when its next action depends on the result; a tool restriction removes both its schema and this guidance. +The generated default [`subagent` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-subagent) under this instance's configured name while its provider exists. `enableModelSelection` adds `provider`, `model`, and `reasoning_effort` plus inheritance and selection guidance; the provider must support `agentOptions`. Provider context inheritance changes the tool and prompt descriptions. Enabled background mode adds `run_in_background`: continuable mode documents its `true` default, runtime settlement notice, and explicit foreground override, while one-shot mode documents its `false` default and the job id collected with `job_output` or stopped with `job_kill`. While the tool is visible in an assembly's scope, a `tool:` system-prompt section tells the model to start independent continuable delegations together, keep working while they run, and choose foreground only when its next action depends on the result; a tool restriction removes both its schema and this guidance. #### Token effect -Fixed schema cost per parent request; each provider instance adds one schema, and each continuable instance adds one short system-prompt section. +Fixed schema cost per parent request; enabling model selection adds three parameters. Each subagent provider instance adds one schema, and each continuable instance adds one short system-prompt section. #### KV Cache effect -Prefix-stable while provider instances, names, descriptions, and schemas are unchanged. Provider registration lifecycle may invalidate parent reuse from the first changed tool definition. +Prefix-stable while subagent provider instances and their configuration are unchanged. Adapter catalog changes do not alter the definition. A route override on an inheritance-capable instance may prevent the child from reusing the inherited parent prefix. + +### Model selection and discovery + +#### What the model sees + +An instance with static `enableModelSelection: true`, or a settings-controlled instance whose Session decision is enabled, exposes the child LLM selection fields and `list_subagent_models`. Calls reject while the optional `ctx.llm` service is unavailable. With no arguments the discovery tool returns registered provider ids and names; with `provider` it returns that adapter's advertised models; with `provider` and `model` it resolves the exact model and returns its advertised reasoning efforts and default. The result is read-only runtime metadata, not an authorization list. + +#### Token effect + +One fixed tool schema is present in shipped compositions. Directory contents enter the transcript only when the model calls the tool. + +#### KV Cache effect + +The schema is prefix-stable across adapter registration and catalog changes. Each result is appended after the reusable prefix. ### Foreground result @@ -79,4 +99,5 @@ Append-only; newly visible content follows the reusable request prefix and does - **Background runs expose no result through this tool** — a one-shot task's final output is collected through the generic task surface, and a continuable child's output stays in its own session, read by its subagent id. The settlement notice states how that child ended and carries any final assistant message, but it is not this call's return value and cannot be awaited here. - **Duplicate names across waiting one-shot instances are detected late** (`TODO(subagent-dup-toolname)`) — continuable instances reserve their prompt-section name during plugin application, but preventing provider-registration rollback for waiting one-shot instances requires a registry of intended names. -- **Child policy is fixed per instance** — another model, persona, tool filter, or depth cap requires another distinctly named tool. +- **Shipped fork tools cannot select a child LLM route** — they inherit the parent's provider and model to keep the copied conversation prefix eligible for KV Cache reuse. Re-enable the fields only when route changes preserve reuse or expose a bounded recomputation cost. +- **Non-routing child policy is fixed per instance** — another persona, tool filter, or depth cap requires another distinctly named tool. LLM provider/model/reasoning-effort selection requires static enablement or an enabled per-Session preference and a subagent provider that advertises `agentOptions`; out-of-process providers currently reject enabling it rather than ignore it. diff --git a/packages/subagent/tool-subagent/README.zh.md b/packages/subagent/tool-subagent/README.zh.md index 74e8896a15..aa6dec73c6 100644 --- a/packages/subagent/tool-subagent/README.zh.md +++ b/packages/subagent/tool-subagent/README.zh.md @@ -6,7 +6,11 @@ ## 提供方选择与生命周期 -每个插件实例把一个 `provider` 绑定到一个 `toolName`;模型不会收到提供方选择器。如需公开另一种传输,请加载另一个名称不同的实例。工具只在其提供方存在时注册,从而避免对同级加载顺序和提供方重新加载的依赖。工具描述遵循 `provider.inheritsParentContext`:新建子 agent(智能体)需要独立提示词,而 fork 子 agent 已能看到父级已完成轮次。 +每个插件实例把一个 subagent 传输 `provider` 绑定到一个 `toolName`;模型不能改变该传输。如需公开另一种传输,请加载另一个名称不同的实例。`enableModelSelection: true`,或 `modelSelectionSettings: true` 时已启用的 Host 偏好,都要求该提供方具备子级 `agentOptions` 能力,并且无需额外路由配置即可公开可选的子 agent LLM `provider`、`model` 与 `reasoning_effort` 字段。调用可以提供完整的提供方/模型对;当配置值或父 Agent 值能够提供生效路由时,也可以只提供推理强度。实时 adapter 会在创建子 agent 前解析显式或配置的路由。完全省略选择字段的调用使用 `agentOptions`,再从父 Agent 最新记录的请求选择中继承兼容的缺失值;首个请求之前回退到其创建选项,并保留其中配置的 `maxTokens`。如果更换提供方或模型但没有指定强度,则清除下层路由所属的强度,使所选模型解析自己的默认值。 + +委派工具只在其 subagent 提供方存在时注册,从而避免对同级加载顺序和提供方重新加载的依赖。启用模型选择时,即使没有 `ctx.llm`,可选字段仍然可见;选择路由的调用会在该服务缺失时失败。禁用时,schema 会省略这些字段,执行阶段也会拒绝强制传入的选择。配置的 `agentOptions` 仍是部署方所有的子级默认值,不受这个面向模型的开关影响。adapter 目录和拓扑变化不会改写或重新注册工具。工具描述遵循 `provider.inheritsParentContext`:新建子 agent(智能体)需要独立提示词,而 fork 子 agent 已能看到父级已完成轮次。 + +启用的定义会注册 `list_subagent_models`,它会在调用时列出已注册提供方、某个提供方公布的模型,或某个精确模型的推理强度。因为发现工具使用全局名称,一个工具作用域最多只能由一个实例启用选择;多个持有方会使注册失败。随附产品组合默认关闭主 `subagent`(`spawn`)实例,并在每个新的顶层会话完成组合时读取 Host 的 `subagent-model-selection.enabled` 偏好。启用决定记录为 `subagent/model-selection-enabled`,由子会话继承并在恢复时保留;之后修改设置不会改变运行中的会话。组合会刻意在 `subagent_fork` 上保持禁用,使 fork 继承父级的提供方与模型:更改该路由会失去继承对话前缀的提供方侧 KV Cache 复用,重新计算前缀的成本可能超过委派任务本身。即使分离发现工具的持有权,该限制也仍然成立。目录条目仍只提供建议:如果适配器接受未列出的模型 ID,启用选择的委派工具也会接受。理由与重新开放条件由[模型选择路由 Agent Note](../../../.agents/notes/implemented/feature/2026-08-18-model-selected-subagent-routes.zh.md)负责。 前台调用会让执行信号贯穿启动和执行,等待 `run.result`,并且在返回前总会等待 `run.dispose()`。只有 `completed` 会返回规范值 `{ kind: 'foreground', runId, output: JsonValue[] }`,并渲染为相同的最终文本。中止、拒绝、token 上限和其他失败都会变成出错的工具结果,其消息依次包含终止原因标题、可选的提供方 `SubagentResult.diagnostic`,以及子 agent 保留下来的部分 assistant 文本。诊断与 `SubagentResult.output` 保持分离,因此被截断的回答不会被报告为成功,也不会与基础设施说明混淆。如果结果收集与 dispose(资源释放)都 reject,出错结果会保留两项失败。 @@ -20,9 +24,11 @@ |---|---| | `provider`(必填) | 提供方名称(`spawn`、`fork`、`acp` 等)。 | | `toolName` | 面向模型的名称,默认 `subagent`;每个已加载实例必须不同。 | +| `enableModelSelection` | 公开并接受面向模型的子级 LLM 选择字段,同时注册共享的 `list_subagent_models` 工具;默认为 `false`。它要求 subagent 提供方具备 `agentOptions` 能力。一个工具作用域最多只能由一个实例启用;即使没有 `ctx.llm`,发现 schema 仍保持注册,而发现调用和所选路由调用会在该可选服务可用前失败。禁用此开关时仍可配置 `agentOptions`。 | +| `modelSelectionSettings` | 组合 Agent 时读取 Host 的 `subagent-model-selection` 偏好,把启用决定记录进其 Session,并让子 Session 继承该决定。默认为 `false`;与 `enableModelSelection` 互斥,且只能用于 Agent 作用域组合。该偏好默认关闭,只影响之后组合的新顶层 Session。 | | `enableRunInBackground` | 公开后台模式,默认 `true`;禁用时也会拒绝强制后台调用。 | | `backgroundMode` | 后台生命周期策略,默认 `one-shot`。`one-shot` 默认前台调用;`continuable` 默认后台调用,要求提供方具备 `prepareContinuable` 能力,并返回持久化子 agent ID,且不要求加载后续消息工具。 | -| `agentOptions` | 传给具体提供方的子 agent `provider`、`model` 和正整数 `maxTokens`;进程内提供方会用显式值覆盖继承的父级选项。 | +| `agentOptions` | 配置的子 agent LLM `provider`、`model`、adapter 自有 `reasoningEffort` 与正整数 `maxTokens`;要求 subagent 提供方具备 `agentOptions` 能力。进程内提供方把显式值合并到父 Agent 最新记录的请求选择之上;首个请求之前则合并到其创建选项之上。只有生效提供方/模型路由不变时才会保留继承的推理强度;改变路由但不显式提供强度时,由所选模型提供默认值。即使调用省略模型选择字段,配置的提供方、模型或强度也会在创建子 agent 前通过可选 `ctx.llm` 服务进行校验;服务缺失或值无效都会拒绝调用。 | | `persona` | 每个子 agent 独立的 persona;要求提供方具备 `persona` 能力。 | | `toolFilter` | 每个子 agent 独立的全局工具限制;要求提供方具备 `toolFilter` 能力。 | | `maxDepth` | 绝对委派深度上限,默认 `3`(`0` 禁止委派);数值上限要求 `depthLimit` 能力,缺失时挂载失败。对于预算由子 harness 拥有的进程外提供方,`'provider-managed'` 不发送上限。工具在达到上限时仍然可见;每次尝试启动都会检查调用 agent 的当前深度,被拒绝时返回出错的工具结果。 | @@ -37,15 +43,29 @@ #### 模型看到的内容 -当提供方存在时,以当前实例配置的名称公开已生成的默认 [`subagent` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-subagent)。提供方是否继承上下文会改变工具描述和提示词描述。启用后台模式会添加 `run_in_background`:可继续模式会记录其默认值为 `true`、运行时结算通知与显式前台覆盖;一次性模式会记录其默认值为 `false`,以及用 `job_output` 收集或用 `job_kill` 停止的 job id。当工具在本次组装的作用域中可见时,一个 `tool:` 系统提示词 section 会指示模型同时启动相互独立的可继续委派、在它们运行时继续工作,并且仅当下一步动作依赖结果时选择前台;工具限制会同时移除其 schema 和这段指引。 +当提供方存在时,以当前实例配置的名称公开已生成的默认 [`subagent` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-subagent)。`enableModelSelection` 会添加 `provider`、`model` 与 `reasoning_effort`,以及继承和选择指引;提供方必须支持 `agentOptions`。提供方是否继承上下文会改变工具描述和提示词描述。启用后台模式会添加 `run_in_background`:可继续模式会记录其默认值为 `true`、运行时结算通知与显式前台覆盖;一次性模式会记录其默认值为 `false`,以及用 `job_output` 收集或用 `job_kill` 停止的 job id。当工具在本次组装的作用域中可见时,一个 `tool:` 系统提示词 section 会指示模型同时启动相互独立的可继续委派、在它们运行时继续工作,并且仅当下一步动作依赖结果时选择前台;工具限制会同时移除其 schema 和这段指引。 #### Token 影响 -每个父级请求都会产生固定的 schema token 开销;每个提供方实例增加一个 schema,每个可继续实例还会增加一个简短的系统提示词 section。 +每个父级请求都会产生固定的 schema token 开销;启用模型选择会增加三个参数。每个 subagent 提供方实例增加一个 schema,每个可继续实例还会增加一个简短的系统提示词 section。 #### KV Cache 影响 -只要提供方实例、名称、描述和 schema 不变,前缀就保持稳定。提供方注册生命周期可能从首个变化的工具定义开始,使父级复用失效。 +只要 subagent 提供方实例及其配置不变,前缀就保持稳定。adapter 目录变化不会改变定义。具备继承能力的实例如果覆盖路由,可能阻止子 agent 复用继承的父级前缀。 + +### 模型选择与发现 + +#### 模型看到的内容 + +静态配置 `enableModelSelection: true` 的实例,或 Session 决定为启用的 settings 控制实例,会公开子级 LLM 选择字段与 `list_subagent_models`。可选 `ctx.llm` 服务不可用时,调用会失败。无参数调用发现工具会返回已注册提供方的 ID 和名称;提供 `provider` 时返回该适配器公布的模型;同时提供 `provider` 和 `model` 时解析精确模型,并返回其公布的推理强度和默认值。结果是只读的运行时元数据,不是授权列表。 + +#### Token 影响 + +随附组合会包含一个固定工具 schema。只有模型调用该工具时,目录内容才会进入 transcript。 + +#### KV Cache 影响 + +adapter 注册和目录变化不会改变 schema 的前缀稳定性。每次结果都追加在可复用前缀之后。 ### 前台结果 @@ -79,4 +99,5 @@ - **后台运行不通过本工具公开结果**:一次性任务的最终输出通过通用 Task 接口收集,可继续子 agent 的输出留在其自身会话中,按其 subagent id 读取。结算通知会说明该子 agent 如何结束,并携带可能存在的最终 assistant 消息,但它不是本次调用的返回值,也无法在此等待。 - **等待中的一次性实例较晚才发现重复名称**(`TODO(subagent-dup-toolname)`):可继续实例会在插件应用期间预留提示词 section 名称,但若要阻止等待中的一次性实例回滚提供方注册,仍需要一份预期名称注册表。 -- **每个实例的子 agent 策略固定**:其他模型、persona、工具过滤器或深度上限都需要另一个名称不同的工具。 +- **随附 fork 工具无法选择子级 LLM 路由**:它们会继承父级的提供方与模型,使复制的对话前缀仍可供 KV Cache 复用。只有在路由变化仍能保留复用,或接口能公开一项有界的重算成本时,才重新启用这些字段。 +- **每个实例的非路由子 agent 策略固定**:其他 persona、工具过滤器或深度上限都需要另一个名称不同的工具。LLM 提供方/模型/推理强度选择要求静态启用或每 Session 偏好已启用,并要求 subagent 提供方声明 `agentOptions`;进程外提供方目前会拒绝启用它,而不是忽略它。 diff --git a/packages/subagent/tool-subagent/package.json b/packages/subagent/tool-subagent/package.json index 9ddab59996..708ca2335b 100644 --- a/packages/subagent/tool-subagent/package.json +++ b/packages/subagent/tool-subagent/package.json @@ -18,6 +18,10 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./model-selection-settings": { + "types": "./lib/types/model-selection-settings.d.ts", + "default": "./lib/model-selection-settings.js" + }, "./invariant": { "types": "./lib/types/invariant.d.ts", "default": "./lib/invariant.js" @@ -28,6 +32,7 @@ "files": [ "lib/index.js", "lib/invariant.js", + "lib/model-selection-settings.js", "lib/types/**/*.d.ts" ], "license": "MIT", @@ -35,6 +40,9 @@ "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-scope": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^", "@deepseek-ai/dsh-subagent": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-jobs": "workspace:^", @@ -50,8 +58,10 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^", "@deepseek-ai/dsh-subagent": "workspace:^", "@deepseek-ai/dsh-subagent-spawn-in-process": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", diff --git a/packages/subagent/tool-subagent/src/index.ts b/packages/subagent/tool-subagent/src/index.ts index ef0e9941eb..ceb04cced8 100644 --- a/packages/subagent/tool-subagent/src/index.ts +++ b/packages/subagent/tool-subagent/src/index.ts @@ -10,14 +10,33 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' +import { scopeChainOf, scopeOf } from '@deepseek-ai/dsh-scope' import { defineTool } from '@deepseek-ai/dsh-tools' -import type { AgentOptions } from '@deepseek-ai/dsh-agent' +import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent' +import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-session' -import { assertSubagentMaxDepth, settleRun } from '@deepseek-ai/dsh-subagent' +import { + assertSubagentMaxDepth, + parentAgentOptionsForDelegation, + settleRun, +} from '@deepseek-ai/dsh-subagent' import type { SubagentProvider, SubagentResult, SubagentRun } from '@deepseek-ai/dsh-subagent' import type { JobOutcome } from '@deepseek-ai/dsh-jobs' import type {} from '@deepseek-ai/dsh-system-prompt' +import { + hasConfiguredLlmSelection, + hasDelegationModelRequest, + preflightChildLlmRoute, + requestedAgentOptions, +} from './model-selection.ts' +import type { DelegationModelRequest } from './model-selection.ts' +import { registerListSubagentModels } from './list-models.ts' +import type {} from './model-selection-settings.ts' +import { + hasSubagentModelSelection, + recordSubagentModelSelection, +} from './model-selection-state.ts' export const name = 'tool-subagent' export const inject = ['tools', 'subagents', 'systemPrompt'] @@ -34,6 +53,14 @@ export interface Config { * a distinct name. */ toolName?: string + /** Let the model discover and select the child LLM route (default false). */ + enableModelSelection?: boolean + /** + * Sample the Host `subagent-model-selection` user setting for each new + * top-level session and inherit that decision in its child sessions. Mutually + * exclusive with `enableModelSelection`. + */ + modelSelectionSettings?: boolean /** * Expose `run_in_background` (default true). Disabled instances omit the * parameter and reject forced background calls. @@ -81,14 +108,22 @@ export interface Config { export const Config: z = z.object({ provider: z.string().required(), toolName: z.string().default('subagent'), + enableModelSelection: z.boolean().default(false), + modelSelectionSettings: z.boolean().default(false), enableRunInBackground: z.boolean().default(true), backgroundMode: z.union(['one-shot', 'continuable'] as const).default('one-shot'), // Prevent Schemastery from materializing omitted agentOptions as `{}`. agentOptions: z.object({ provider: z.string(), model: z.string(), + reasoningEffort: z.string().min(1) as z>, maxTokens: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), - }).default(undefined as unknown as { provider: string; model: string; maxTokens: number }), + }).default(undefined as unknown as { + provider: string + model: string + reasoningEffort: ReturnType + maxTokens: number + }), persona: z.string(), // Preserve omission; Schemastery's `{ allow: [] }` default would deny every tool. toolFilter: z.object({ @@ -281,196 +316,348 @@ export function apply(ctx: Context, config: Config): void { if (config.toolFilter !== undefined && config.toolFilter.allow === undefined && config.toolFilter.deny === undefined) { throw new Error('tool-subagent: `toolFilter` is configured but names neither `allow` nor `deny` — remove the key or fill the filter') } + if (config.enableModelSelection === true && config.modelSelectionSettings === true) { + throw new Error('tool-subagent: `enableModelSelection` and `modelSelectionSettings` are mutually exclusive') + } const backgroundEnabled = config.enableRunInBackground !== false const continuable = (config.backgroundMode ?? 'one-shot') === 'continuable' const toolName = config.toolName ?? 'subagent' - // Load order and HMR replacement can change provider availability while - // this fiber remains active. - let disposeTool: (() => void) | undefined - const mount = (provider: SubagentProvider): void => { - // A numeric cap the provider cannot enforce is a misconfiguration — fail at - // mount (the earliest point the provider's capabilities are known), not on - // the first delegation. - if (typeof config.maxDepth === 'number' && !provider.capabilities.depthLimit) { + + const modelSelectionCapable = config.enableModelSelection === true || config.modelSelectionSettings === true + + const assertSubagentProviderConfiguration = (subagentProvider: SubagentProvider): void => { + if (typeof config.maxDepth === 'number' && !subagentProvider.capabilities.depthLimit) { throw new Error( - `tool-subagent: provider "${provider.name}" cannot enforce maxDepth (no depthLimit capability) — ` + `tool-subagent: provider "${subagentProvider.name}" cannot enforce maxDepth (no depthLimit capability) — ` + 'set maxDepth: \'provider-managed\' to leave the recursion budget to the provider', ) } - const wording = providerWording(provider.inheritsParentContext) - if (continuable && provider.prepareContinuable === undefined) { + if (config.agentOptions !== undefined && !subagentProvider.capabilities.agentOptions) { throw new Error( - `tool-subagent: provider "${provider.name}" does not support \`backgroundMode: continuable\``, + `tool-subagent: provider "${subagentProvider.name}" does not support child agentOptions`, + ) + } + if (modelSelectionCapable && !subagentProvider.capabilities.agentOptions) { + throw new Error( + `tool-subagent: provider "${subagentProvider.name}" does not support child model selection`, + ) + } + if (continuable && subagentProvider.prepareContinuable === undefined) { + throw new Error( + `tool-subagent: provider "${subagentProvider.name}" does not support \`backgroundMode: continuable\``, ) } - disposeTool = ctx.tools.register(defineTool({ - name: toolName, - description: wording.description + (backgroundEnabled - // The completion notice is the continuation service's own behavior, not - // a separately installed capability, so this promise holds whenever the - // continuable background path is reachable at all. - ? continuable - ? ' This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result.' - : ' This call waits for the result by default. Set `run_in_background: true` to return a job id; collect with `job_output` and stop with `job_kill`.' - : ' This call waits for the subagent and returns its result.'), - parameters: { - description: { - type: 'string', - required: true, - description: 'A short (3-5 word) description of the delegated task, for display.', - }, - prompt: { - type: 'string', - required: true, - description: wording.promptDescription, - }, - ...backgroundEnabled ? { - run_in_background: { - type: 'boolean' as const, - description: continuable - ? 'Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it.' - : 'Whether to run as a background job and return its id. Defaults to false; collect with job_output or stop with job_kill.', - }, - } : {}, - }, - output: { - schema: { - oneOf: [ - { - type: 'object', - additionalProperties: false, - properties: { - kind: { type: 'string', required: true, const: 'background' }, - jobId: { type: 'string', required: true }, - }, - }, - { - type: 'object', - additionalProperties: false, - properties: { - kind: { type: 'string', required: true, const: 'continuable' }, - subagentId: { type: 'string', required: true }, - }, - }, - { - type: 'object', - additionalProperties: false, - properties: { - kind: { type: 'string', required: true, const: 'foreground' }, - runId: { type: 'string', required: true }, - output: { type: 'array', required: true, items: { type: 'json' } }, - }, - }, - ], - }, - render: (_args, value) => [{ - type: 'text', - text: value.kind === 'background' - ? `started background subagent job ${value.jobId}` - : value.kind === 'continuable' - ? `started subagent ${value.subagentId}` - : outputValueText(value.output), - }], - }, - // Children never mutate the parent session; the one parent-owned write - // (tasks.start) is a synchronous commutative insertion. - isConcurrencySafe: () => true, - async execute(args, exec) { - const parent = exec.agent - if (!parent) { - // Non-agent callers provide no parent for delegation ownership. - throw new Error('subagent tool requires a calling agent (exec.agent was undefined)') - } - - const maxDepth = typeof config.maxDepth === 'number' ? config.maxDepth : undefined - const request = { - label: args.description, - prompt: [{ type: 'text', text: args.prompt }] as ContentBlock[], - parent, - ...config.agentOptions !== undefined ? { agentOptions: config.agentOptions } : {}, - ...config.persona !== undefined ? { persona: config.persona } : {}, - ...config.toolFilter !== undefined ? { toolFilter: config.toolFilter } : {}, - ...maxDepth !== undefined ? { maxDepth } : {}, - } - - const runSpec = resolveDelegationRun(args, { backgroundEnabled, continuable }) - if (runSpec.runInBackground) { - if (continuable) { - // Resolves at inbox acceptance: the child owns its own turns from - // there, so this call neither waits for nor collects a result. - const started = await ctx.subagents.startContinuable({ - provider: config.provider, - label: args.description, - request, - signal: exec.signal, - }) - return { kind: 'continuable' as const, subagentId: started.childId } - } - const jobs = ctx.get('jobs') - if (jobs === undefined) { - throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') - } - // One-shot background child: job preflight finishes before the - // starter can spawn, and the task-owned signal covers startup. - const id = jobs.start({ - kind: 'subagent', - label: args.description, - owner: parent, - run: () => { - const controller = new AbortController() - const start = ctx.subagents.start(config.provider, { ...request, signal: controller.signal }) - return { - cancel: (reason?: string) => { - controller.abort(reason ?? 'background subagent task killed') - }, - done: settleStart(start, controller.signal), - // No readOutput: the child session owns intermediate detail. - } - }, - }) - return { kind: 'background' as const, jobId: id } - } - - const run: SubagentRun = await ctx.subagents.start(config.provider, { - ...request, - signal: exec.signal, - }) - return settleForegroundRun(run) - }, - })) } - // Register listeners before checking presence so no synchronous change is missed. - // TODO(subagent-dup-toolname): two waiting one-shot fibers configured with the - // same toolName collide when their provider appears, and the duplicate-name - // throw rolls back the provider registration. Continuable instances reserve - // their prompt-section name during apply() and fail earlier. Add an intent - // registry if the late one-shot collision occurs in a shipped composition. - ctx.on('subagent/provider-added', (provider) => { - if (provider.name === config.provider && disposeTool === undefined) mount(provider) + // Validate provider-owned config outside the optional LLM binding so an + // invalid provider always rejects its registration or this plugin's load. + ctx.on('subagent/provider-added', (subagentProvider) => { + if (subagentProvider.name === config.provider) assertSubagentProviderConfiguration(subagentProvider) }) - ctx.on('subagent/provider-removed', (name) => { - if (name !== config.provider || disposeTool === undefined) return - disposeTool() - disposeTool = undefined - }) - const present = ctx.subagents.getProvider(config.provider) - if (present !== undefined) { - mount(present) - } else { - // A backend fiber may activate later; a misspelled provider remains visible in this log. - ctx.logger.info(`subagent provider "${config.provider}" not registered yet; the "${config.toolName ?? 'subagent'}" tool will register when it appears`) - } - if (backgroundEnabled && continuable) { - // The section follows provider availability without its own manual - // lifecycle: empty text is omitted from rendered prompts while the tool is - // absent, and the registration itself stays owned by this plugin fiber. - ctx.systemPrompt.section({ - name: `tool:${toolName}`, - order: SUBAGENT_SECTION_ORDER, - text: context => disposeTool === undefined || ctx.tools.get(toolName, context.scope) === undefined + const initialProvider = ctx.subagents.getProvider(config.provider) + if (initialProvider !== undefined) assertSubagentProviderConfiguration(initialProvider) + + const install = (runtimeCtx: Context, modelSelectionEnabled: boolean): void => { + if (modelSelectionEnabled) registerListSubagentModels(runtimeCtx) + // Load order and HMR replacement can change provider availability while + // this fiber remains active. + let mounted: { subagentProvider: SubagentProvider; disposeTool: () => void } | undefined + const mount = (subagentProvider: SubagentProvider): void => { + assertSubagentProviderConfiguration(subagentProvider) + const wording = providerWording(subagentProvider.inheritsParentContext) + const choiceDescription = !modelSelectionEnabled ? '' - : `Use ${toolName} in the background by default. Start independent delegations together in one assistant message and continue useful work while they run. Set \`run_in_background: false\` only when your next action depends on that subagent's result. When a background run settles, the runtime sends you a notice containing its outcome and any final assistant message.`, + : ' Child LLM selection is optional. Omit `provider`, `model`, and `reasoning_effort` to use configured child defaults and inherit compatible missing values from the parent Agent. Supply `provider` and `model` together after using `list_subagent_models` to inspect advertised routes and efforts. Changing the effective route without naming an effort uses the selected model\'s default effort.' + + (subagentProvider.inheritsParentContext + ? ' Changing the route can prevent provider-side reuse of the inherited conversation prefix.' + : '') + const disposeTool = runtimeCtx.tools.register(defineTool({ + name: toolName, + description: wording.description + (backgroundEnabled + // The completion notice is the continuation service's own behavior, not + // a separately installed capability, so this promise holds whenever the + // continuable background path is reachable at all. + ? continuable + ? ' This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result.' + : ' This call waits for the result by default. Set `run_in_background: true` to return a job id; collect with `job_output` and stop with `job_kill`.' + : ' This call waits for the subagent and returns its result.') + choiceDescription, + parameters: { + description: { + type: 'string', + required: true, + description: 'A short (3-5 word) description of the delegated task, for display.', + }, + prompt: { + type: 'string', + required: true, + description: wording.promptDescription, + }, + ...modelSelectionEnabled ? { + provider: { + type: 'string' as const, + description: 'LLM provider route for the child. Supply together with model; omit both to use configured child defaults or inherit the parent route.', + }, + model: { + type: 'string' as const, + description: 'Model id interpreted by provider. Supply together with provider; omit both to use configured child defaults or inherit the parent route.', + }, + reasoning_effort: { + type: 'string' as const, + description: 'Adapter-owned reasoning effort for the effective child route. Omit to inherit a compatible configured/parent effort or use a newly selected model\'s default.', + }, + } : {}, + ...backgroundEnabled ? { + run_in_background: { + type: 'boolean' as const, + description: continuable + ? 'Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it.' + : 'Whether to run as a background job and return its id. Defaults to false; collect with job_output or stop with job_kill.', + }, + } : {}, + }, + output: { + schema: { + oneOf: [ + { + type: 'object', + additionalProperties: false, + properties: { + kind: { type: 'string', required: true, const: 'background' }, + jobId: { type: 'string', required: true }, + }, + }, + { + type: 'object', + additionalProperties: false, + properties: { + kind: { type: 'string', required: true, const: 'continuable' }, + subagentId: { type: 'string', required: true }, + }, + }, + { + type: 'object', + additionalProperties: false, + properties: { + kind: { type: 'string', required: true, const: 'foreground' }, + runId: { type: 'string', required: true }, + output: { type: 'array', required: true, items: { type: 'json' } }, + }, + }, + ], + }, + render: (_args, value) => [{ + type: 'text', + text: value.kind === 'background' + ? `started background subagent job ${value.jobId}` + : value.kind === 'continuable' + ? `started subagent ${value.subagentId}` + : outputValueText(value.output), + }], + }, + // Children never mutate the parent session; the one parent-owned write + // (tasks.start) is a synchronous commutative insertion. + isConcurrencySafe: () => true, + async execute(args, exec) { + const parent = exec.agent + if (!parent) { + // Non-agent callers provide no parent for delegation ownership. + throw new Error('subagent tool requires a calling agent (exec.agent was undefined)') + } + + const modelRequest = args as DelegationModelRequest + const parentOptions = parentAgentOptionsForDelegation(parent) + const childAgentOptions = requestedAgentOptions( + parentOptions, + config.agentOptions, + modelRequest, + modelSelectionEnabled, + ) + if (hasDelegationModelRequest(modelRequest) || hasConfiguredLlmSelection(config.agentOptions)) { + const llm = runtimeCtx.get('llm') + if (llm === undefined) { + throw new Error('cannot resolve the selected child LLM route because the `llm` service is unavailable') + } + await preflightChildLlmRoute(llm, parentOptions, childAgentOptions, exec.signal) + } + exec.signal.throwIfAborted() + const maxDepth = typeof config.maxDepth === 'number' ? config.maxDepth : undefined + const request = { + label: args.description, + prompt: [{ type: 'text', text: args.prompt }] as ContentBlock[], + parent, + ...childAgentOptions !== undefined ? { agentOptions: childAgentOptions } : {}, + ...config.persona !== undefined ? { persona: config.persona } : {}, + ...config.toolFilter !== undefined ? { toolFilter: config.toolFilter } : {}, + ...maxDepth !== undefined ? { maxDepth } : {}, + } + + const runSpec = resolveDelegationRun(args, { backgroundEnabled, continuable }) + if (runSpec.runInBackground) { + if (continuable) { + // Resolves at inbox acceptance: the child owns its own turns from + // there, so this call neither waits for nor collects a result. + const started = await runtimeCtx.subagents.startContinuable({ + provider: config.provider, + label: args.description, + request, + signal: exec.signal, + }) + return { kind: 'continuable' as const, subagentId: started.childId } + } + const jobs = runtimeCtx.get('jobs') + if (jobs === undefined) { + throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + } + // One-shot background child: job preflight finishes before the + // starter can spawn, and the task-owned signal covers startup. + const id = jobs.start({ + kind: 'subagent', + label: args.description, + owner: parent, + run: () => { + const controller = new AbortController() + const start = runtimeCtx.subagents.start(config.provider, { ...request, signal: controller.signal }) + return { + cancel: (reason?: string) => { + controller.abort(reason ?? 'background subagent task killed') + }, + done: settleStart(start, controller.signal), + // No readOutput: the child session owns intermediate detail. + } + }, + }) + return { kind: 'background' as const, jobId: id } + } + + const run: SubagentRun = await runtimeCtx.subagents.start(config.provider, { + ...request, + signal: exec.signal, + }) + return settleForegroundRun(run) + }, + })) + mounted = { subagentProvider, disposeTool } + } + + // Register listeners before checking presence so no synchronous change is missed. + // TODO(subagent-dup-toolname): two waiting one-shot fibers configured with the + // same toolName collide when their provider appears, and the duplicate-name + // throw rolls back the provider registration. Continuable instances reserve + // their prompt-section name during apply() and fail earlier. Add an intent + // registry if the late one-shot collision occurs in a shipped composition. + runtimeCtx.on('subagent/provider-added', (subagentProvider) => { + if (subagentProvider.name === config.provider && mounted === undefined) mount(subagentProvider) + }) + runtimeCtx.on('subagent/provider-removed', (name) => { + if (name !== config.provider || mounted === undefined) return + mounted.disposeTool() + mounted = undefined + }) + const present = runtimeCtx.subagents.getProvider(config.provider) + if (present !== undefined) { + mount(present) + } else { + // A backend fiber may activate later; a misspelled provider remains visible in this log. + runtimeCtx.logger.info(`subagent provider "${config.provider}" not registered yet; the "${config.toolName ?? 'subagent'}" tool will register when it appears`) + } + if (backgroundEnabled && continuable) { + // The section follows provider availability without its own manual + // lifecycle: empty text is omitted from rendered prompts while the tool is + // absent, and the registration itself stays owned by this plugin fiber. + runtimeCtx.systemPrompt.section({ + name: `tool:${toolName}`, + order: SUBAGENT_SECTION_ORDER, + text: context => mounted === undefined || runtimeCtx.tools.get(toolName, context.scope) === undefined + ? '' + : `Use ${toolName} in the background by default. Start independent delegations together in one assistant message and continue useful work while they run. Set \`run_in_background: false\` only when your next action depends on that subagent's result. When a background run settles, the runtime sends you a notice containing its outcome and any final assistant message.`, + }) + } + } + + if (config.modelSelectionSettings !== true) { + install(ctx, config.enableModelSelection === true) + return + } + + const settings = ctx.get('subagentModelSelection') + if (settings === undefined) { + throw new Error( + 'tool-subagent: `modelSelectionSettings` requires ' + + '@deepseek-ai/dsh-tool-subagent/model-selection-settings in the Host scope', + ) + } + const compositionScope = scopeOf(ctx) + if (compositionScope === undefined) { + throw new Error('tool-subagent: `modelSelectionSettings` requires an Agent or preset scope') + } + + const selectForAgent = (agent: NonNullable): boolean => { + let enabled = hasSubagentModelSelection(agent.session) + if (!enabled) { + const parentId = agent.session.header.origin === 'subagent' + ? agent.session.header.parentSession + : undefined + if (parentId !== undefined) { + const parent = ctx.get('agents')?.get(parentId) + enabled = parent !== undefined && hasSubagentModelSelection(parent.session) + } else if (agent.session.firstLiveSeq === 0) { + enabled = settings.currentEnabled() + } + } + if (enabled) recordSubagentModelSelection(agent.session) + return enabled + } + + const agent = ctx.agent + if (agent !== undefined) { + install(ctx, selectForAgent(agent)) + return + } + const agents = ctx.get('agents') + /* v8 ignore next -- Agent and preset scopes are minted only by the Agent registry. */ + if (agents === undefined) throw new Error('tool-subagent: scoped model-selection settings require the Agent registry') + const scopedInstalls = new WeakMap>() + const installing = new WeakSet() + const belongsToComposition = (candidate: Agent): boolean => + scopeChainOf(scopeOf(candidate.ctx)).includes(compositionScope) + const installScoped = (candidate: Agent): void => { + if (scopedInstalls.has(candidate) || installing.has(candidate)) return + // Reserve before the injected fiber runs: tool registration emits + // `tools/change` synchronously, which re-enters the reconciliation below. + installing.add(candidate) + const enabled = selectForAgent(candidate) + const fiber = candidate.ctx.inject(['tools', 'subagents', 'systemPrompt'], (runtimeCtx) => { + install(runtimeCtx, enabled) + }) + installing.delete(candidate) + scopedInstalls.set(candidate, fiber) + } + const removeScoped = (candidate: Agent): void => { + const fiber = scopedInstalls.get(candidate) + if (fiber === undefined) return + scopedInstalls.delete(candidate) + /* v8 ignore next 3 -- Cordis Fiber disposal contains registration cleanup failures; this is the final diagnostic sink. */ + void fiber.dispose().catch((error: unknown) => { + ctx.logger.warn(`tool-subagent: failed to remove recomposed Agent "${candidate.id}" definitions: ${String(error)}`) }) } + const reconcileComposedAgents = (): void => { + // Every Agent and preset scope is minted by the Agent registry; the scope + // check above makes this same-process typed relationship authoritative. + for (const candidate of agents.list()) { + if (belongsToComposition(candidate)) installScoped(candidate) + else removeScoped(candidate) + } + } + // A shipped preset is mounted once in a standing scope. Its listener admits + // only descendant Agents and installs the sampled tool definition in each + // Agent's own scope, so a later settings change cannot mutate a live session. + ctx.on('agent/created', ({ agent: created }) => { + installScoped(created) + }) + ctx.on('agent/disposed', ({ agent: disposed }) => { removeScoped(disposed) }) + // Reparenting an Agent between standing presets changes its inherited tool + // set and emits `tools/change`; reconcile the Agent-owned override with the + // new ancestry. Other registry changes are idempotent no-ops here. + ctx.on('tools/change', reconcileComposedAgents) } diff --git a/packages/subagent/tool-subagent/src/invariant.ts b/packages/subagent/tool-subagent/src/invariant.ts index 5b8facc900..84bd209caa 100644 --- a/packages/subagent/tool-subagent/src/invariant.ts +++ b/packages/subagent/tool-subagent/src/invariant.ts @@ -5,7 +5,8 @@ /* jscpd:ignore-start */ import type { Context } from '@deepseek-ai/cordis' -import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' +import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants' +import { hasSubagentModelSelection } from './model-selection-state.ts' const PACKAGE_NAME = '@deepseek-ai/dsh-tool-subagent' @@ -14,11 +15,24 @@ export const name = 'tool-subagent-invariant' /** Service required before the companion can reserve package ownership. */ export const inject = ['invariants'] -/** - * No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution - * relations are owned by the capability seam it calls. - */ -const install: InvariantInstaller = () => {} +/** Assert that a durable opt-in is represented by both model-facing definitions. */ +const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => { + ctx.on('agent/pre-step', async ({ agent }, next) => { + if (hasSubagentModelSelection(agent.session)) { + const schemas = ctx.tools.schemas(agent) + const selectable = schemas.some((schema) => { + const properties = (schema.parameters as { properties?: Record }).properties + return properties?.['provider'] !== undefined + && properties['model'] !== undefined + && properties['reasoning_effort'] !== undefined + }) + if (!selectable || !schemas.some(schema => schema.name === 'list_subagent_models')) { + fail('a subagent/model-selection-enabled session must expose route fields and list_subagent_models') + } + } + return next() + }, { global: true }) +}, { inject: ['tools'] }) /** * Register this package's invariant companion. diff --git a/packages/subagent/tool-subagent/src/list-models.ts b/packages/subagent/tool-subagent/src/list-models.ts new file mode 100644 index 0000000000..9e1ff5c24e --- /dev/null +++ b/packages/subagent/tool-subagent/src/list-models.ts @@ -0,0 +1,94 @@ +/** Model-facing discovery of LLM routes available to child Agents. */ + +import type { Context } from '@deepseek-ai/cordis' +import type LlmRuntime from '@deepseek-ai/dsh-llm' +import type { LlmProviderInfo } from '@deepseek-ai/dsh-llm' +import { defineTool } from '@deepseek-ai/dsh-tools' + +interface ListSubagentModelsRequest { + readonly provider?: string + readonly model?: string +} + +/** Resolve one registered provider with a model-correctable diagnostic. */ +function registeredProvider(llm: LlmRuntime, providerId: string): LlmProviderInfo { + const providers = llm.listProviders() + const provider = providers.find(candidate => candidate.id === providerId) + if (provider !== undefined) return provider + const available = providers.map(candidate => candidate.id).join(', ') || '(none)' + throw new Error(`LLM provider "${providerId}" is not registered; available providers: ${available}`) +} + +/** Render one advertised or resolved model. */ +function modelLine(provider: string, model: { id: string; name: string; description?: string }): string { + return `${provider}/${model.id} — ${model.name}${model.description === undefined ? '' : `: ${model.description}`}` +} + +/** Read the requested provider, advertised models, or exact-model efforts. */ +async function listSubagentModels( + ctx: Context, + request: ListSubagentModelsRequest, + signal: AbortSignal, +): Promise { + const llm = ctx.get('llm') + if (llm === undefined) { + throw new Error('cannot discover child LLM routes because the `llm` service is unavailable') + } + if (request.model !== undefined && request.provider === undefined) { + throw new Error('`model` requires `provider`') + } + if (request.provider === undefined) { + const providers = llm.listProviders() + return providers.length === 0 + ? '(no LLM providers)' + : providers.map(provider => `${provider.id} — ${provider.name}`).join('\n') + } + if (request.provider.length === 0) throw new Error('`provider` must be non-empty') + const provider = registeredProvider(llm, request.provider) + if (request.model === undefined) { + const models = await llm.listModels(provider.id) + return models.length === 0 + ? `(no advertised models for ${provider.id})` + : models.map(model => modelLine(provider.id, model)).join('\n') + } + if (request.model.length === 0) throw new Error('`model` must be non-empty') + const model = await llm.resolveModelInfo(provider.id, request.model, signal) + const efforts = model.reasoning?.efforts.map(effort => ( + `${effort.id}${model.reasoning?.defaultEffort === effort.id ? ' (default)' : ''} — ${effort.name}` + + (effort.description === undefined ? '' : `: ${effort.description}`) + )).join('\n') || '(no advertised reasoning efforts)' + return `${modelLine(provider.id, model)}\nReasoning efforts:\n${efforts}` +} + +/** + * Register `list_subagent_models` for one owning delegation-tool instance. + * @param ctx - Context whose tool registry owns the fixed discovery definition. + */ +export function registerListSubagentModels(ctx: Context): void { + ctx.tools.register(defineTool({ + name: 'list_subagent_models', + description: + 'Discover LLM routes for subagents without changing the current Agent. Call with no arguments to list ' + + 'registered providers, with `provider` to list its advertised models, or with `provider` and `model` ' + + 'to inspect that exact model and its reasoning efforts. Catalog membership is advisory: an adapter may ' + + 'accept an unlisted model id. Use the returned ids with a delegation tool\'s `provider`, `model`, and ' + + '`reasoning_effort` fields.', + parameters: { + provider: { + type: 'string', + description: 'Registered LLM provider id. Omit to list providers.', + }, + model: { + type: 'string', + description: 'Exact model id to inspect. Requires provider; omit to list that provider\'s advertised models.', + }, + }, + output: { + schema: { type: 'string' }, + render: (_args, result) => [{ type: 'text', text: result }], + }, + execute(args, exec) { + return listSubagentModels(ctx, args, exec.signal) + }, + })) +} diff --git a/packages/subagent/tool-subagent/src/model-selection-settings.ts b/packages/subagent/tool-subagent/src/model-selection-settings.ts new file mode 100644 index 0000000000..113cd4c6f8 --- /dev/null +++ b/packages/subagent/tool-subagent/src/model-selection-settings.ts @@ -0,0 +1,70 @@ +/** Host-owned opt-in setting for model-selectable subagent delegation. */ + +import { Context, Service } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** User preference sampled when a new Agent receives its delegation tools. */ + subagentModelSelection: SubagentModelSelectionConfig + } +} + +/** User-settings section for model-selectable subagent delegation. */ +export const SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE = settingsNamespace('subagent-model-selection') + +/** Stored user preference; the shipped composition defaults it off. */ +export interface SubagentModelSelectionSettings { + /** Whether new Agents may expose child LLM route selection to the model. */ + enabled: boolean +} + +/** Schema served to settings clients for the opt-in preference. */ +export const SUBAGENT_MODEL_SELECTION_SETTINGS_SCHEMA: z = z.object({ + enabled: z.boolean().default(false), +}) + +/** Optional deployment base for the preference. */ +export interface Config { + /** Initial value inherited when the user document does not override it. */ + enabled?: boolean +} + +/** Singleton settings owner read by delegation tools when an Agent is published. */ +export class SubagentModelSelectionConfig extends Service { + static Config: z = z.object({ + enabled: z.boolean().default(false), + }) + + private source: () => SubagentModelSelectionSettings + + constructor(ctx: Context, config: Config = {}) { + super(ctx, 'subagentModelSelection') + const entry: SubagentModelSelectionSettings = { enabled: config.enabled === true } + this.source = () => entry + installSettingsSection( + ctx, + SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, + SUBAGENT_MODEL_SELECTION_SETTINGS_SCHEMA, + entry, + { + setSource: (source) => { this.source = source }, + // Consumers sample at Agent publication, so a settings update never + // rebuilds the tool definitions of an Agent that is already running. + onChange: () => {}, + }, + ) + } + + /** + * Read the preference for the next eligible Agent publication. + * @returns whether that Agent should receive model-selectable delegation. + */ + currentEnabled(): boolean { + return this.source().enabled + } +} + +export const name = 'subagent-model-selection-settings' +export default SubagentModelSelectionConfig diff --git a/packages/subagent/tool-subagent/src/model-selection-state.ts b/packages/subagent/tool-subagent/src/model-selection-state.ts new file mode 100644 index 0000000000..35345ac115 --- /dev/null +++ b/packages/subagent/tool-subagent/src/model-selection-state.ts @@ -0,0 +1,33 @@ +/** Durable per-session state for the user-controlled model-selection opt-in. */ + +import type { Session } from '@deepseek-ai/dsh-session' + +declare module '@deepseek-ai/dsh-session/types' { + interface SessionEventMap { + /** + * Records that this session's delegation tool exposes child provider, + * model, and reasoning-effort selection. Appended before the first model + * request; absence means the fixed-route definition. Log-only: it carries + * no `surfaceOp` and never enters model history. + */ + 'subagent/model-selection-enabled': Record + } +} + +/** + * Whether a session log records the enabled model-selection definition. + * @param session - session whose durable decision is read. + * @returns whether model-selectable delegation is enabled for the session. + */ +export function hasSubagentModelSelection(session: Session): boolean { + return session.events.some(event => event.type === 'subagent/model-selection-enabled') +} + +/** + * Append the enabled decision once, before its definition can reach a model request. + * @param session - session receiving the enabled decision. + */ +export function recordSubagentModelSelection(session: Session): void { + if (hasSubagentModelSelection(session)) return + session.append('subagent/model-selection-enabled', {}) +} diff --git a/packages/subagent/tool-subagent/src/model-selection.ts b/packages/subagent/tool-subagent/src/model-selection.ts new file mode 100644 index 0000000000..6b89d92742 --- /dev/null +++ b/packages/subagent/tool-subagent/src/model-selection.ts @@ -0,0 +1,112 @@ +/** Child LLM route selection for the subagent tool. */ + +import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import type { LlmRuntime } from '@deepseek-ai/dsh-llm' +import type { AgentOptions } from '@deepseek-ai/dsh-agent' + +/** Model-facing child LLM route fields. */ +export interface DelegationModelRequest { + readonly provider?: string + readonly model?: string + readonly reasoning_effort?: string +} + +/** + * Whether a call explicitly selects any child LLM value. + * @param request - Model-facing route fields from the tool call. + * @returns Whether at least one route or effort field is present. + */ +export function hasDelegationModelRequest(request: DelegationModelRequest): boolean { + return request.provider !== undefined + || request.model !== undefined + || request.reasoning_effort !== undefined +} + +/** Reject an empty model-facing route value at the tool JSON boundary. */ +function assertNonEmpty(value: string | undefined, field: keyof DelegationModelRequest): void { + if (value !== undefined && value.length === 0) { + throw new Error(`child LLM \`${field}\` must be non-empty`) + } +} + +/** + * Merge model-supplied selection fields over configured child defaults. + * Provider and model form one route and must be supplied together. Changing + * that route without an effort clears the configured route-owned effort. + * @param parentOptions - Current parent values that supply missing child values. + * @param configured - Tool-instance child defaults. + * @param request - Model-facing route override. + * @param enabled - Whether this tool instance permits model-facing selection. + * @returns Child Agent options, preserving omission when no layer contributes one. + */ +export function requestedAgentOptions( + parentOptions: AgentOptions, + configured: AgentOptions | undefined, + request: DelegationModelRequest, + enabled: boolean, +): AgentOptions | undefined { + if (!hasDelegationModelRequest(request)) return configured + if (!enabled) { + throw new Error('child model selection is disabled for this tool instance') + } + assertNonEmpty(request.provider, 'provider') + assertNonEmpty(request.model, 'model') + assertNonEmpty(request.reasoning_effort, 'reasoning_effort') + if ((request.provider === undefined) !== (request.model === undefined)) { + throw new Error('child LLM `provider` and `model` must be supplied together') + } + + const baselineProvider = configured?.provider ?? parentOptions.provider + const baselineModel = configured?.model ?? parentOptions.model + const routeChanged = request.provider !== undefined + && (request.provider !== baselineProvider || request.model !== baselineModel) + const { reasoningEffort: _configuredReasoningEffort, ...configuredWithoutReasoning } = configured ?? {} + return { + ...routeChanged && request.reasoning_effort === undefined ? configuredWithoutReasoning : configured, + ...request.provider === undefined ? {} : { provider: request.provider, model: request.model }, + ...request.reasoning_effort === undefined + ? {} + : { reasoningEffort: ReasoningEffortId(request.reasoning_effort) }, + } +} + +/** + * Whether configured Agent options require route validation before delegation. + * @param options - Tool-instance child defaults. + * @returns Whether configured provider, model, or effort values must be resolved. + */ +export function hasConfiguredLlmSelection(options: AgentOptions | undefined): boolean { + return options?.provider !== undefined + || options?.model !== undefined + || options?.reasoningEffort !== undefined +} + +/** + * Resolve an effective child route through its live adapter before the child is + * created. The LLM runtime owns provider lookup, exact-model metadata, effort + * validation, and adapter defaults. + * @param llm - Live LLM runtime. + * @param parentOptions - Current parent values whose compatible fields the child inherits. + * @param requested - Per-child options after request/config merging. + * @param signal - Tool-call cancellation signal. + */ +export async function preflightChildLlmRoute( + llm: LlmRuntime, + parentOptions: AgentOptions, + requested: AgentOptions | undefined, + signal: AbortSignal, +): Promise { + const provider = requested?.provider ?? parentOptions.provider + const model = requested?.model ?? parentOptions.model + if (provider === undefined || model === undefined) { + throw new Error('cannot select child LLM values without an effective provider and model') + } + const routeChanged = provider !== parentOptions.provider || model !== parentOptions.model + const reasoningEffort = requested?.reasoningEffort + ?? (routeChanged ? undefined : parentOptions.reasoningEffort) + await llm.resolveCallConfig({ + provider, + model, + ...reasoningEffort === undefined ? {} : { reasoningEffort }, + }, signal) +} diff --git a/packages/subagent/tool-subagent/tests/harness.ts b/packages/subagent/tool-subagent/tests/harness.ts new file mode 100644 index 0000000000..36ac602c89 --- /dev/null +++ b/packages/subagent/tool-subagent/tests/harness.ts @@ -0,0 +1,57 @@ +import { Context } from '@deepseek-ai/cordis' +import LlmRuntime, { CallId } from '@deepseek-ai/dsh-llm' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import type { Agent } from '@deepseek-ai/dsh-agent' +import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import * as mock from './scripted-provider.ts' +import * as tool from '../src/index.ts' + +/** Shared non-aborted tool signal for package-local integration tests. */ +export const testToolSignal = new AbortController().signal + +/** Build the minimal parent Agent owned by the package-local scripted provider. */ +export function fakeAgent(id = 'parent-1'): Agent { + const sessionId = SessionId(id) + return { id: sessionId, options: {}, session: Session.create(sessionId) } as unknown as Agent +} + +/** Mount the real tool and service stack around one scripted subagent provider. */ +export async function setup(toolConfig: tool.Config, mockConfig: Partial = {}): Promise { + const ctx = new Context() + await ctx.plugin(LlmRuntime) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(SubagentRuntime) + await mock.mountScriptedProvider(ctx, { name: 'mock', ...mockConfig }) + await ctx.plugin(tool, toolConfig) + return ctx +} + +let callCounter = 0 + +/** Execute the registered subagent tool through the real ToolRuntime pipeline. */ +export function callSubagent( + ctx: Context, + args: unknown, + over: { agent?: Agent | undefined; signal?: AbortSignal } = {}, +) { + // Distinguish "no override" (use a default agent) from an explicit + // `{ agent: undefined }` (test the no-agent path). Under + // exactOptionalPropertyTypes the key is omitted rather than set to undefined. + const agent = 'agent' in over ? over.agent : fakeAgent() + return ctx.tools.execute({ + signal: testToolSignal, + callId: CallId(`call-${++callCounter}`), + name: 'subagent', + arguments: args, + ...agent ? { agent } : {}, + ...over.signal ? { signal: over.signal } : {}, + }) +} + +/** Join text blocks from one rendered tool result. */ +export function text(result: { content: { type: string; text?: string }[] }): string { + return result.content.filter(block => block.type === 'text').map(block => block.text).join('') +} diff --git a/packages/subagent/tool-subagent/tests/list-models.spec.ts b/packages/subagent/tool-subagent/tests/list-models.spec.ts new file mode 100644 index 0000000000..de3643fd97 --- /dev/null +++ b/packages/subagent/tool-subagent/tests/list-models.spec.ts @@ -0,0 +1,191 @@ +import { describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import LlmRuntime, { + CallId, + LlmAdapter, + ReasoningEffortId, +} from '@deepseek-ai/dsh-llm' +import type { + GenerateOptions, + LlmModelInfo, + LlmResolvedModelInfo, + StreamChunk, +} from '@deepseek-ai/dsh-llm' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import * as tool from '../src/index.ts' +import { testToolSignal, text } from './harness.ts' + +class CatalogAdapter extends LlmAdapter { + constructor(private readonly empty = false) { + super() + } + + override providerInfo(provider: string) { + return { id: provider, name: `${provider.toUpperCase()} API` } + } + + override listModels(provider: string): Promise { + if (this.empty) return Promise.resolve([]) + return Promise.resolve([ + { provider, id: 'fast', name: 'Fast', description: 'Focused work.' }, + { provider, id: 'plain', name: 'Plain' }, + ]) + } + + override resolveModel(provider: string, model: string): Promise { + if (model === 'plain') return Promise.resolve({ provider, id: model, name: 'Plain' }) + return Promise.resolve({ + provider, + id: model, + name: 'Fast', + description: 'Focused work.', + reasoning: { + efforts: [ + { id: ReasoningEffortId('low'), name: 'Low' }, + { id: ReasoningEffortId('high'), name: 'High', description: 'Quality first.' }, + ], + defaultEffort: ReasoningEffortId('high'), + }, + }) + } + + stream(_options: GenerateOptions): AsyncIterable { + return (async function* () { yield { type: 'finish' as const, reason: { kind: 'stop' as const } } })() + } +} + +async function setupListTool() { + const ctx = new Context() + await ctx.plugin(LlmRuntime) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(SubagentRuntime) + const fiber = await ctx.plugin(tool, { provider: 'unused', enableModelSelection: true }) + return { ctx, fiber } +} + +let counter = 0 + +function call(ctx: Context, args: unknown) { + return ctx.tools.execute({ + signal: testToolSignal, + callId: CallId(`list-models-${++counter}`), + name: 'list_subagent_models', + arguments: args, + }) +} + +describe('list_subagent_models', () => { + it('is omitted unless its delegation-tool instance owns discovery', async () => { + const ctx = new Context() + await ctx.plugin(LlmRuntime) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(SubagentRuntime) + await ctx.plugin(tool, { provider: 'unused' }) + expect(ctx.tools.get('list_subagent_models')).toBeUndefined() + }) + + it('stays registered without the optional LLM service and rejects discovery calls', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(SubagentRuntime) + await ctx.plugin(tool, { provider: 'unused', enableModelSelection: true }) + const result = await call(ctx, {}) + expect(result.isError).toBe(true) + expect(text(result)).toContain('`llm` service is unavailable') + }) + + it('rejects two discovery-owning instances in one tool scope', async () => { + const { ctx } = await setupListTool() + await expect(ctx.plugin(tool, { + provider: 'another-unused', + toolName: 'subagent_other', + enableModelSelection: true, + }).then(() => undefined)).rejects.toThrow('tool "list_subagent_models" is already registered') + }) + + it('lists registered providers and follows live registration changes', async () => { + const { ctx, fiber } = await setupListTool() + const empty = await call(ctx, {}) + expect(empty.isError).toBe(false) + expect(text(empty)).toBe('(no LLM providers)') + + const registration = ctx.llm.registerAdapter(['alpha'], new CatalogAdapter()) + const providers = await call(ctx, {}) + expect(providers.isError).toBe(false) + expect(text(providers)).toBe('alpha — ALPHA API') + + registration.replace(['beta']) + const changed = await call(ctx, {}) + expect(text(changed)).toBe('beta — BETA API') + + await fiber.dispose() + expect(ctx.tools.get('list_subagent_models')).toBeUndefined() + }) + + it('lists one provider\'s advertised models without treating the catalog as a whitelist', async () => { + const { ctx } = await setupListTool() + ctx.llm.registerAdapter(['alpha'], new CatalogAdapter()) + const result = await call(ctx, { provider: 'alpha' }) + expect(result.isError).toBe(false) + expect(text(result)).toBe('alpha/fast — Fast: Focused work.\nalpha/plain — Plain') + }) + + it('renders an empty advertised model list', async () => { + const { ctx } = await setupListTool() + ctx.llm.registerAdapter(['alpha'], new CatalogAdapter(true)) + const result = await call(ctx, { provider: 'alpha' }) + expect(result.isError).toBe(false) + expect(text(result)).toBe('(no advertised models for alpha)') + }) + + it('inspects exact-model efforts, descriptions, and defaults', async () => { + const { ctx } = await setupListTool() + ctx.llm.registerAdapter(['alpha'], new CatalogAdapter()) + const result = await call(ctx, { provider: 'alpha', model: 'fast' }) + expect(result.isError).toBe(false) + expect(text(result)).toBe( + 'alpha/fast — Fast: Focused work.\nReasoning efforts:\n' + + 'low — Low\nhigh (default) — High: Quality first.', + ) + }) + + it('renders exact models without reasoning metadata', async () => { + const { ctx } = await setupListTool() + ctx.llm.registerAdapter(['alpha'], new CatalogAdapter()) + const result = await call(ctx, { provider: 'alpha', model: 'plain' }) + expect(result.isError).toBe(false) + expect(text(result)).toBe('alpha/plain — Plain\nReasoning efforts:\n(no advertised reasoning efforts)') + }) + + it.each([ + { args: { model: 'fast' }, expected: '`model` requires `provider`' }, + { args: { provider: '' }, expected: '`provider` must be non-empty' }, + { args: { provider: 'missing' }, expected: 'available providers: (none)' }, + ])('rejects incomplete or unavailable provider requests', async ({ args, expected }) => { + const { ctx } = await setupListTool() + const result = await call(ctx, args) + expect(result.isError).toBe(true) + expect(text(result)).toContain(expected) + }) + + it('rejects an empty exact model after resolving the provider', async () => { + const { ctx } = await setupListTool() + ctx.llm.registerAdapter(['alpha'], new CatalogAdapter()) + const result = await call(ctx, { provider: 'alpha', model: '' }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('`model` must be non-empty') + }) + + it('reports registered alternatives for an unavailable provider', async () => { + const { ctx } = await setupListTool() + ctx.llm.registerAdapter(['alpha'], new CatalogAdapter()) + const result = await call(ctx, { provider: 'missing' }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('available providers: alpha') + }) +}) diff --git a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts new file mode 100644 index 0000000000..4f95db088f --- /dev/null +++ b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts @@ -0,0 +1,248 @@ +/** Default-off settings and per-session model-selection decisions. */ + +import { describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { bindScopeParent, createScope, scopeOf, scopeTarget } from '@deepseek-ai/dsh-scope' +import { SettingsProvider } from '@deepseek-ai/dsh-settings' +import type { SettingsNamespace } from '@deepseek-ai/dsh-settings' +import InvariantRegistry from '@deepseek-ai/dsh-invariants' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' +import * as tool from '../src/index.ts' +import * as ToolInvariant from '../src/invariant.ts' +import SubagentModelSelectionConfig, { + SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, +} from '../src/model-selection-settings.ts' +import { hasSubagentModelSelection } from '../src/model-selection-state.ts' + +/** Writable in-memory settings provider for the package integration. */ +class MemorySettings extends SettingsProvider { + doc: Record = {} + + get writable(): boolean { + return true + } + + protected load(): Promise> { + return Promise.resolve(structuredClone(this.doc)) + } + + protected persist(ns: SettingsNamespace, section: Record): Promise { + this.doc = { ...this.doc, [ns]: structuredClone(section) } + return Promise.resolve() + } +} + +/** Read whether one Agent's delegation definition contains route fields. */ +function selectable(ctx: Context, agent: Awaited>['agent']): boolean { + const schema = ctx.tools.schemas(agent).find(candidate => candidate.name === 'subagent') + const properties = (schema?.parameters as { properties?: Record } | undefined)?.properties + return properties?.['provider'] !== undefined + && properties['model'] !== undefined + && properties['reasoning_effort'] !== undefined + && ctx.tools.schemas(agent).some(candidate => candidate.name === 'list_subagent_models') +} + +/** Mount the real settings, Agent, provider, and tool services. */ +async function boot(): Promise { + const ctx = new Context() + await ctx.plugin(MemorySettings) + await ctx.plugin(SubagentModelSelectionConfig) + await mountAgentLoopTestDependencies(ctx) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(SubagentRuntime) + await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) + return ctx +} + +/** Create one Agent whose setup mounts the settings-controlled tool preset row. */ +async function createAgent(ctx: Context, id: string, options: { + meta?: { parentSession: SessionId; origin: 'subagent' } + seed?: readonly SessionEvent[] +} = {}) { + const handle = await ctx.agents.create({ + sessionId: SessionId(id), + ...options, + setup: async (agentCtx) => { + await agentCtx.plugin(tool, { + provider: 'spawn', + modelSelectionSettings: true, + backgroundMode: 'continuable', + }) + }, + }) + return handle.agent +} + +describe('SubagentModelSelectionConfig', () => { + it('uses the composed default without a settings provider', async () => { + const ctx = new Context() + await ctx.plugin(SubagentModelSelectionConfig, { enabled: true }) + + expect(ctx.subagentModelSelection.currentEnabled()).toBe(true) + await ctx.fiber.dispose() + }) + + it('defaults off and follows the validated user layer', async () => { + const ctx = new Context() + await ctx.plugin(MemorySettings) + await ctx.plugin(SubagentModelSelectionConfig) + + expect(ctx.subagentModelSelection.currentEnabled()).toBe(false) + await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: true }) + expect(ctx.subagentModelSelection.currentEnabled()).toBe(true) + await ctx.fiber.dispose() + }) + + it('samples each new root session without changing existing Agents', async () => { + const ctx = await boot() + const disabled = await createAgent(ctx, 'disabled') + expect(selectable(ctx, disabled)).toBe(false) + expect(hasSubagentModelSelection(disabled.session)).toBe(false) + + await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: true }) + const enabled = await createAgent(ctx, 'enabled') + expect(hasSubagentModelSelection(enabled.session)).toBe(true) + expect(selectable(ctx, enabled)).toBe(true) + expect(selectable(ctx, disabled)).toBe(false) + + await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false }) + const disabledAgain = await createAgent(ctx, 'disabled-again') + expect(selectable(ctx, disabledAgain)).toBe(false) + expect(selectable(ctx, enabled)).toBe(true) + await ctx.fiber.dispose() + }) + + it('installs per-Agent definitions for a shared preset scope', async () => { + const ctx = await boot() + const preset = createScope(ctx, { preset: 'standard' }) + const other = createScope(ctx, { preset: 'minimal' }) + await preset.ctx.plugin(tool, { + provider: 'spawn', + modelSelectionSettings: true, + backgroundMode: 'continuable', + }) + + let enabledBinding: ReturnType | undefined + const createComposed = async (id: string) => ctx.agents.create({ + sessionId: SessionId(id), + setup: (agentCtx) => { + const binding = bindScopeParent(scopeOf(agentCtx)!, scopeOf(preset.ctx)!) + if (id === 'preset-enabled') enabledBinding = binding + }, + }) + + const disabled = await createComposed('preset-disabled') + expect(selectable(ctx, disabled.agent)).toBe(false) + await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: true }) + const enabled = await createComposed('preset-enabled') + expect(selectable(ctx, enabled.agent)).toBe(true) + expect(selectable(ctx, disabled.agent)).toBe(false) + + enabledBinding!.rebind(scopeOf(other.ctx)!) + ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change') + await vi.waitFor(() => { expect(selectable(ctx, enabled.agent)).toBe(false) }) + enabledBinding!.rebind(scopeOf(preset.ctx)!) + ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change') + await vi.waitFor(() => { expect(selectable(ctx, enabled.agent)).toBe(true) }) + + await enabled.dispose() + ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change') + await disabled.dispose() + await ctx.fiber.dispose() + }) + + it('inherits the parent decision and preserves seeded decisions across composition', async () => { + const ctx = await boot() + await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: true }) + const parent = await createAgent(ctx, 'parent') + await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false }) + const child = await createAgent(ctx, 'child', { + meta: { parentSession: parent.id, origin: 'subagent' }, + }) + expect(selectable(ctx, child)).toBe(true) + expect(hasSubagentModelSelection(child.session)).toBe(true) + + const enabledSeed = Session.create(SessionId('enabled-seed')) + enabledSeed.append('subagent/model-selection-enabled', {}) + const resumedEnabled = await createAgent(ctx, 'resumed-enabled', { seed: enabledSeed.events }) + expect(selectable(ctx, resumedEnabled)).toBe(true) + + const oldSeed = Session.create(SessionId('old-seed'), []) + await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: true }) + const resumedDisabled = await createAgent(ctx, 'resumed-disabled', { seed: oldSeed.events }) + expect(selectable(ctx, resumedDisabled)).toBe(false) + expect(hasSubagentModelSelection(resumedDisabled.session)).toBe(false) + await ctx.fiber.dispose() + }) + + it('rejects ambiguous static and settings-controlled configuration', async () => { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + await ctx.plugin(SubagentRuntime) + expect(() => { + tool.apply(ctx, { + provider: 'missing', + enableModelSelection: true, + modelSelectionSettings: true, + }) + }).toThrow('mutually exclusive') + await ctx.fiber.dispose() + }) + + it('requires both the Host setting owner and a composition scope', async () => { + const withoutSettings = new Context() + await mountAgentLoopTestDependencies(withoutSettings) + await withoutSettings.plugin(SubagentRuntime) + expect(() => { + tool.apply(withoutSettings, { + provider: 'missing', + modelSelectionSettings: true, + maxDepth: 'provider-managed', + }) + }).toThrow('requires @deepseek-ai/dsh-tool-subagent/model-selection-settings') + await withoutSettings.fiber.dispose() + + const withoutAgent = await boot() + expect(() => { + tool.apply(withoutAgent, { + provider: 'spawn', + modelSelectionSettings: true, + backgroundMode: 'continuable', + }) + }).toThrow('requires an Agent or preset scope') + await withoutAgent.fiber.dispose() + }) + + it('checks the durable decision against the published tool definitions', async () => { + const ctx = await boot() + await ctx.plugin(InvariantRegistry, { enabled: true }) + await ctx.plugin(ToolInvariant) + const disabled = await createAgent(ctx, 'invariant-disabled') + const next = () => Promise.resolve({ kind: 'enter' as const, messages: [] }) + const payload = { + agent: disabled, + messages: [], + turn: 1, + step: 1, + signal: new AbortController().signal, + } + await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next)).resolves.toEqual({ + kind: 'enter', messages: [], + }) + + disabled.session.append('subagent/model-selection-enabled', {}) + await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next)) + .rejects.toThrow('must expose route fields and list_subagent_models') + + await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: true }) + const enabled = await createAgent(ctx, 'invariant-enabled') + await expect(ctx.waterfall(ctx as never, 'agent/pre-step', { ...payload, agent: enabled }, next)) + .resolves.toEqual({ kind: 'enter', messages: [] }) + await ctx.fiber.dispose() + }) +}) diff --git a/packages/subagent/tool-subagent/tests/model-selection.spec.ts b/packages/subagent/tool-subagent/tests/model-selection.spec.ts new file mode 100644 index 0000000000..008ba66da4 --- /dev/null +++ b/packages/subagent/tool-subagent/tests/model-selection.spec.ts @@ -0,0 +1,365 @@ +import { describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import type { Agent } from '@deepseek-ai/dsh-agent' +import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import type { SubagentStartRequest } from '@deepseek-ai/dsh-subagent' +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import { MockAdapter } from '../../../core/agent-loop/tests/mock-adapter.ts' +import * as mock from './scripted-provider.ts' +import * as tool from '../src/index.ts' +import { callSubagent, setup, text } from './harness.ts' + +const REASONING = { + efforts: [ + { id: ReasoningEffortId('low'), name: 'Low' }, + { id: ReasoningEffortId('high'), name: 'High' }, + ], + defaultEffort: ReasoningEffortId('high'), +} as const + +function parentWithRoute( + options: Agent['options'] = { + provider: 'alpha', + model: 'parent-model', + reasoningEffort: ReasoningEffortId('high'), + }, +): Agent { + const id = SessionId('parent-with-route') + return { id, options, session: Session.create(id) } as unknown as Agent +} + +describe('dsh-tool-subagent model selection', () => { + it('exposes static route fields and discovery when selection is enabled', async () => { + const ctx = await setup({ provider: 'mock', enableModelSelection: true }) + const schema = ctx.tools.schemas().find(entry => entry.name === 'subagent')! + const props = (schema.parameters as { properties?: Record }).properties ?? {} + expect(Object.keys(props).sort()).toEqual([ + 'description', + 'model', + 'prompt', + 'provider', + 'reasoning_effort', + 'run_in_background', + ]) + expect(schema.description).toContain('list_subagent_models') + expect(ctx.tools.get('list_subagent_models')).toBeDefined() + expect(schema.description).not.toContain('alpha') + + const registration = ctx.llm.registerAdapter(['alpha'], new MockAdapter([])) + const definition = ctx.tools.get('subagent') + registration.replace(['beta']) + expect(ctx.tools.get('subagent')).toBe(definition) + expect(definition?.description).not.toContain('beta') + }) + + it('hides and rejects route fields when selection is disabled', async () => { + const ctx = await setup({ provider: 'mock' }) + const schema = ctx.tools.schemas().find(entry => entry.name === 'subagent')! + const props = (schema.parameters as { properties?: Record }).properties ?? {} + expect(Object.keys(props).sort()).toEqual(['description', 'prompt', 'run_in_background']) + expect(schema.description).not.toContain('list_subagent_models') + expect(ctx.tools.get('list_subagent_models')).toBeUndefined() + + const result = await callSubagent(ctx, { + description: 'forced route', + prompt: 'do it', + provider: 'alpha', + model: 'fast-model', + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('child model selection is disabled for this tool instance') + }) + + it('rejects enabled model selection when the provider cannot apply Agent options', async () => { + await expect(setup( + { provider: 'mock', enableModelSelection: true, maxDepth: 'provider-managed' }, + { capabilities: { agentOptions: false } }, + )).rejects.toThrow('provider "mock" does not support child model selection') + }) + + it('selects an unlisted complete route and clears a configured effort when the route changes', async () => { + const requests: SubagentStartRequest[] = [] + const ctx = await setup({ + provider: 'mock', + enableModelSelection: true, + agentOptions: { + provider: 'alpha', + model: 'configured-model', + reasoningEffort: ReasoningEffortId('high'), + maxTokens: 321, + }, + }, { onStart: (request) => { requests.push(request) } }) + ctx.llm.registerAdapter(['alpha'], new MockAdapter([], REASONING)) + + const selected = await callSubagent(ctx, { + description: 'route work', + prompt: 'do it', + provider: 'alpha', + model: 'unlisted-model', + }) + expect(selected.isError).toBe(false) + expect(requests[0]?.agentOptions).toEqual({ + provider: 'alpha', + model: 'unlisted-model', + maxTokens: 321, + }) + + const effort = await callSubagent(ctx, { + description: 'same route effort', + prompt: 'do it', + provider: 'alpha', + model: 'configured-model', + reasoning_effort: 'low', + }) + expect(effort.isError).toBe(false) + expect(requests[1]?.agentOptions).toEqual({ + provider: 'alpha', + model: 'configured-model', + reasoningEffort: 'low', + maxTokens: 321, + }) + }) + + it('accepts an effort-only override for the effective configured or parent route', async () => { + const requests: SubagentStartRequest[] = [] + const ctx = await setup({ + provider: 'mock', + enableModelSelection: true, + agentOptions: { provider: 'alpha' }, + }, { onStart: (request) => { requests.push(request) } }) + ctx.llm.registerAdapter(['alpha'], new MockAdapter([], REASONING)) + + const result = await callSubagent(ctx, { + description: 'effort work', + prompt: 'do it', + reasoning_effort: 'low', + }, { agent: parentWithRoute() }) + expect(result.isError).toBe(false) + expect(requests[0]?.agentOptions).toEqual({ provider: 'alpha', reasoningEffort: 'low' }) + + const inherited = await setup({ provider: 'mock', enableModelSelection: true }) + inherited.llm.registerAdapter(['alpha'], new MockAdapter([], REASONING)) + const inheritedResult = await callSubagent(inherited, { + description: 'parent effort work', + prompt: 'do it', + reasoning_effort: 'low', + }, { agent: parentWithRoute() }) + expect(inheritedResult.isError).toBe(false) + }) + + it('inherits a parent effort only when an explicit route stays unchanged', async () => { + const ctx = await setup({ provider: 'mock', enableModelSelection: true }) + ctx.llm.registerAdapter(['alpha'], new MockAdapter([], REASONING)) + const result = await callSubagent(ctx, { + description: 'same route work', + prompt: 'do it', + provider: 'alpha', + model: 'parent-model', + }, { agent: parentWithRoute() }) + expect(result.isError).toBe(false) + }) + + it('compares explicit routes with the latest logged parent selection', async () => { + const requests: SubagentStartRequest[] = [] + const ctx = await setup({ + provider: 'mock', + enableModelSelection: true, + agentOptions: { reasoningEffort: ReasoningEffortId('high') }, + }, { onStart: (request) => { requests.push(request) } }) + ctx.llm.registerAdapter(['current-provider'], new MockAdapter([], REASONING)) + const parent = parentWithRoute({ provider: 'created-provider', model: 'created-model' }) + parent.session.append('request/header', { + header: { config: { provider: 'current-provider', model: 'current-model' } }, + reason: 'initial', + }) + + const result = await callSubagent(ctx, { + description: 'same current route', + prompt: 'do it', + provider: 'current-provider', + model: 'current-model', + }, { agent: parent }) + + expect(result.isError).toBe(false) + expect(requests[0]?.agentOptions).toEqual({ + provider: 'current-provider', + model: 'current-model', + reasoningEffort: 'high', + }) + }) + + it('rejects an effort without any effective route', async () => { + const ctx = await setup({ provider: 'mock', enableModelSelection: true }) + const result = await callSubagent(ctx, { + description: 'missing route', + prompt: 'do it', + reasoning_effort: 'low', + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('without an effective provider and model') + }) + + it.each([ + { provider: 'alpha' }, + { model: 'fast-model' }, + ])('rejects a partial model-facing route before child creation', async (route) => { + let starts = 0 + const ctx = await setup({ provider: 'mock', enableModelSelection: true }, { onStart: () => { starts += 1 } }) + const result = await callSubagent(ctx, { description: 'partial route', prompt: 'do it', ...route }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('`provider` and `model` must be supplied together') + expect(starts).toBe(0) + }) + + it.each([ + { provider: '', model: 'fast-model', expected: '`provider` must be non-empty' }, + { provider: 'alpha', model: '', expected: '`model` must be non-empty' }, + { reasoning_effort: '', expected: '`reasoning_effort` must be non-empty' }, + ])('rejects empty model-facing values', async ({ expected, ...selection }) => { + const ctx = await setup({ provider: 'mock', enableModelSelection: true }) + const result = await callSubagent(ctx, { description: 'empty route', prompt: 'do it', ...selection }) + expect(result.isError).toBe(true) + expect(text(result)).toContain(expected) + }) + + it('uses the LLM runtime for provider and reasoning-effort validation before child creation', async () => { + let starts = 0 + const ctx = await setup({ provider: 'mock', enableModelSelection: true }, { onStart: () => { starts += 1 } }) + ctx.llm.registerAdapter(['alpha'], new MockAdapter([], REASONING)) + + const unsupported = await callSubagent(ctx, { + description: 'bad effort', + prompt: 'do it', + provider: 'alpha', + model: 'fast-model', + reasoning_effort: 'max', + }) + expect(unsupported.isError).toBe(true) + expect(text(unsupported)).toContain('does not support reasoning effort "max"') + + const missing = await callSubagent(ctx, { + description: 'bad provider', + prompt: 'do it', + provider: 'missing', + model: 'fast-model', + }) + expect(missing.isError).toBe(true) + expect(text(missing)).toContain('no adapter registered for provider "missing"') + expect(starts).toBe(0) + }) + + it('validates a configured effort before child creation', async () => { + let starts = 0 + const ctx = await setup({ + provider: 'mock', + agentOptions: { + provider: 'alpha', + model: 'parent-model', + reasoningEffort: ReasoningEffortId('high'), + }, + }, { onStart: () => { starts += 1 } }) + ctx.llm.registerAdapter(['alpha'], new MockAdapter([], { + efforts: [{ id: ReasoningEffortId('low'), name: 'Low' }], + defaultEffort: ReasoningEffortId('low'), + })) + + const result = await callSubagent( + ctx, + { description: 'same route', prompt: 'do it' }, + { agent: parentWithRoute() }, + ) + expect(result.isError).toBe(true) + expect(text(result)).toContain('does not support reasoning effort "high"') + expect(starts).toBe(0) + }) + + it('validates a configured route before child creation', async () => { + let starts = 0 + const ctx = await setup({ + provider: 'mock', + agentOptions: { provider: 'missing', model: 'configured-model' }, + }, { onStart: () => { starts += 1 } }) + + const result = await callSubagent( + ctx, + { description: 'configured route', prompt: 'do it' }, + { agent: parentWithRoute() }, + ) + + expect(result.isError).toBe(true) + expect(text(result)).toContain('no adapter registered for provider "missing"') + expect(starts).toBe(0) + }) + + it('rejects selected routes or configured efforts when the LLM service is absent', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(SubagentRuntime) + await mock.mountScriptedProvider(ctx, { name: 'mock' }) + await ctx.plugin(tool, { + provider: 'mock', + enableModelSelection: true, + agentOptions: { + provider: 'alpha', + model: 'fast-model', + reasoningEffort: ReasoningEffortId('high'), + }, + }) + + const configured = await callSubagent(ctx, { description: 'configured effort', prompt: 'do it' }) + expect(configured.isError).toBe(true) + expect(text(configured)).toContain('`llm` service is unavailable') + + const selected = await callSubagent(ctx, { + description: 'selected route', + prompt: 'do it', + provider: 'alpha', + model: 'other-model', + }) + expect(selected.isError).toBe(true) + expect(text(selected)).toContain('`llm` service is unavailable') + }) + + it('keeps pure inherited routing usable without an LLM service lookup', async () => { + let starts = 0 + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(SubagentRuntime) + await mock.mountScriptedProvider(ctx, { name: 'mock', onStart: () => { starts += 1 } }) + await ctx.plugin(tool, { provider: 'mock' }) + + const result = await callSubagent(ctx, { description: 'inherit route', prompt: 'do it' }) + expect(result.isError).toBe(false) + expect(starts).toBe(1) + }) + + it('warns that changing a fork route can lose inherited-prefix reuse', async () => { + const ctx = await setup({ provider: 'mock', enableModelSelection: true }, { inheritsParentContext: true }) + const schema = ctx.tools.schemas().find(entry => entry.name === 'subagent')! + expect(schema.description).toContain('inherits this conversation') + expect(schema.description).toContain('can prevent provider-side reuse of the inherited conversation prefix') + }) + + it('propagates an exact-route resolver failure before child creation', async () => { + let starts = 0 + const ctx = await setup({ provider: 'mock', enableModelSelection: true }, { onStart: () => { starts += 1 } }) + const adapter = new MockAdapter([]) + vi.spyOn(adapter, 'resolveModel').mockRejectedValue(new Error('selected route unavailable')) + ctx.llm.registerAdapter(['alpha'], adapter) + + const result = await callSubagent(ctx, { + description: 'route work', + prompt: 'do it', + provider: 'alpha', + model: 'fast-model', + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('selected route unavailable') + expect(starts).toBe(0) + }) +}) diff --git a/packages/subagent/tool-subagent/tests/scripted-provider.ts b/packages/subagent/tool-subagent/tests/scripted-provider.ts index c0da403cd4..a946c6f6fe 100644 --- a/packages/subagent/tool-subagent/tests/scripted-provider.ts +++ b/packages/subagent/tool-subagent/tests/scripted-provider.ts @@ -13,6 +13,7 @@ import type { } from '@deepseek-ai/dsh-subagent' const DEFAULT_CAPABILITIES: SubagentCapabilities = { + agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index 1ee5e40228..334b721461 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import path from 'node:path' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import { CallId } from '@deepseek-ai/dsh-llm' +import LlmRuntime, { CallId } from '@deepseek-ai/dsh-llm' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import { assembleContextFor, type Agent } from '@deepseek-ai/dsh-agent' @@ -20,9 +20,8 @@ import * as ToolTasks from '@deepseek-ai/dsh-tool-jobs' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import * as mock from './scripted-provider.ts' import * as tool from '../src/index.ts' -import { SessionId } from '@deepseek-ai/dsh-session' - -const testToolSignal = new AbortController().signal +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import { callSubagent, fakeAgent, setup, testToolSignal, text } from './harness.ts' /** * Drives the REAL plugin body: mounts `dsh-tool-subagent` on a real @@ -32,40 +31,6 @@ const testToolSignal = new AbortController().signal * shipping code path. */ -/** A minimal parent Agent passed through to the provider request. */ -function fakeAgent(id = 'parent-1'): Agent { - return { id: SessionId(id) } as unknown as Agent -} - -async function setup(toolConfig: tool.Config, mockConfig: Partial = {}) { - const ctx = new Context() - await ctx.plugin(SystemPrompt) - await ctx.plugin(ToolRuntime) - await ctx.plugin(SubagentRuntime) - await mock.mountScriptedProvider(ctx, { name: 'mock', ...mockConfig }) - await ctx.plugin(tool, toolConfig) - return ctx -} - -let callCounter = 0 -function callSubagent(ctx: Context, args: unknown, over: { agent?: Agent | undefined; signal?: AbortSignal } = {}) { - // Distinguish "no override" (use a default agent) from an explicit - // `{ agent: undefined }` (test the no-agent path). Under - // exactOptionalPropertyTypes the key is omitted rather than set to undefined. - const agent = 'agent' in over ? over.agent : fakeAgent() - return ctx.tools.execute({ - signal: testToolSignal, - callId: CallId(`call-${++callCounter}`), - name: 'subagent', - arguments: args, - ...agent ? { agent } : {}, - ...over.signal ? { signal: over.signal } : {}, - }) -} - -function text(result: { content: { type: string; text?: string }[] }): string { - return result.content.filter(b => b.type === 'text').map(b => b.text).join('') -} describe('dsh-tool-subagent', () => { it('rejects continuable background policy when the provider cannot prepare continuable children', async () => { @@ -83,6 +48,13 @@ describe('dsh-tool-subagent', () => { ) }) + it('rejects configured child agent options at mount when the provider cannot apply them', async () => { + await expect(setup( + { provider: 'mock', maxDepth: 'provider-managed', agentOptions: { model: 'configured-model' } }, + { capabilities: { agentOptions: false } }, + )).rejects.toThrow('does not support child agentOptions') + }) + it('registers a `subagent` tool that delegates to the configured provider and returns its output', async () => { const ctx = await setup({ provider: 'mock' }, { reply: 'child says hi' }) const result = await callSubagent(ctx, { @@ -100,20 +72,14 @@ describe('dsh-tool-subagent', () => { expect(text(result)).toBe('child says hi') }) - it('exposes description + prompt + run_in_background to the model (no provider/type parameter)', async () => { - const ctx = await setup({ provider: 'mock' }) - const schema = ctx.tools.schemas().find(s => s.name === 'subagent') - expect(schema).toBeDefined() - const props = (schema!.parameters as { properties?: Record }).properties ?? {} - expect(Object.keys(props).sort()).toEqual(['description', 'prompt', 'run_in_background']) - expect(schema!.description).toContain('job_output') - }) - it('omits run_in_background entirely when the instance disables it (schema and capability never disagree)', async () => { const ctx = await setup({ provider: 'mock', enableRunInBackground: false }) const schema = ctx.tools.schemas().find(s => s.name === 'subagent') const props = (schema!.parameters as { properties?: Record }).properties ?? {} - expect(Object.keys(props).sort()).toEqual(['description', 'prompt']) + expect(Object.keys(props).sort()).toEqual([ + 'description', + 'prompt', + ]) expect(schema!.description).not.toContain('job_output') }) @@ -121,7 +87,13 @@ describe('dsh-tool-subagent', () => { // Schema omission is advertising, not enforcement: the arg validator // allows undeclared keys, so the opt-out must also hold in execute(). const ctx = await setup({ provider: 'mock', enableRunInBackground: false }) - const parent = { id: SessionId('sess-off'), inject: () => {}, options: {}, session: { header: { version: 0, id: 'sess-off', createdAt: 0 } } } as unknown as Agent + const parentId = SessionId('sess-off') + const parent = { + id: parentId, + inject: () => {}, + options: {}, + session: Session.create(parentId), + } as unknown as Agent const forced = await callSubagent(ctx, { description: 'd', prompt: 'p', run_in_background: true }, { agent: parent }) expect(forced.isError).toBe(true) @@ -232,7 +204,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'weird', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => ({ id: SessionId('weird-child'), @@ -253,12 +225,13 @@ describe('dsh-tool-subagent', () => { // the request lets us assert the agentOptions reached it. let seen: { agentOptions?: { model?: string } } | undefined const ctx = new Context() + await ctx.plugin(LlmRuntime) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'capture', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: true, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async (request) => { seen = request @@ -270,10 +243,15 @@ describe('dsh-tool-subagent', () => { } }, }) - await ctx.plugin(tool, { provider: 'capture', agentOptions: { model: 'child-model' }, maxDepth: 'provider-managed' }) + ctx.llm.registerAdapter(['alpha'], new MockAdapter([])) + await ctx.plugin(tool, { + provider: 'capture', + agentOptions: { provider: 'alpha', model: 'child-model' }, + maxDepth: 'provider-managed', + }) await callSubagent(ctx, { description: 'd', prompt: 'p' }) - expect(seen?.agentOptions).toEqual({ model: 'child-model' }) + expect(seen?.agentOptions).toEqual({ provider: 'alpha', model: 'child-model' }) }) it('defaults toolName and omits agentOptions when apply() is called directly (schema bypass)', async () => { @@ -288,7 +266,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'bare', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async (request) => { seen = request @@ -378,7 +356,7 @@ describe('dsh-tool-subagent', () => { // the provider survives. ctx.subagents.registerProvider({ name: 'continuable', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => { throw new Error('lifecycle test does not start a child') }, prepareContinuable: async () => ({}), @@ -429,10 +407,14 @@ describe('dsh-tool-subagent', () => { }) it('derives inherited-context wording from a seeded-conversation provider', async () => { - const ctx = await setup({ provider: 'mock', toolName: 'subagent' }, { inheritsParentContext: true }) + const ctx = await setup({ + provider: 'mock', + toolName: 'subagent', + }, { inheritsParentContext: true }) const schema = ctx.tools.schemas().find(s => s.name === 'subagent')! expect(schema.description).toContain('inherits this conversation') expect(schema.description).not.toContain('does not see this conversation') + expect(schema.description).not.toContain('can prevent provider-side reuse of the inherited conversation prefix') const props = (schema.parameters as { properties: Record }).properties expect(props['prompt']!.description).toContain('completed turns') }) @@ -447,7 +429,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'spy', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => ({ id: SessionId('spy-child'), @@ -470,7 +452,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'spy', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => ({ id: SessionId('spy-child'), @@ -494,7 +476,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'spy', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => ({ id: SessionId('spy-child'), @@ -522,7 +504,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'spy', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => ({ id: SessionId('spy-child'), @@ -549,7 +531,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'spy', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async (request) => { if (request.signal.aborted) throw new Error('start aborted') @@ -588,7 +570,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'spy', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async (request) => { if (request.signal.aborted) sawAborted() @@ -652,7 +634,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'capture2', - capabilities: { outputSchema: false, depthLimit: true, toolFilter: true, persona: true }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: true, toolFilter: true, persona: true }, inheritsParentContext: false, start: async (request) => { seen = request @@ -709,7 +691,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'capture3', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: true, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: true, persona: false }, inheritsParentContext: false, start: async (request) => { seen = request @@ -739,7 +721,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'capture4', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async (request) => { seen = request @@ -764,7 +746,7 @@ describe('dsh-tool-subagent', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'p', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: true, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: true, persona: false }, inheritsParentContext: false, start: () => { throw new Error('unreachable') }, }) @@ -783,7 +765,7 @@ describe('dsh-tool-subagent background mode', () => { ctx: scopeFiber.ctx, inject, options: {}, - session: { id, header: { version: 0, id, createdAt: 0 } }, + session: Session.create(id), } as unknown as Agent ctx.agents.register(agent) return agent @@ -803,7 +785,7 @@ describe('dsh-tool-subagent background mode', () => { let prepareCalls = 0 ctx.subagents.registerProvider({ name: 'resumable', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async request => ({ id: SessionId('one-shot-child'), @@ -839,7 +821,7 @@ describe('dsh-tool-subagent background mode', () => { }) it('returns a job id immediately and the answer is collected through job_output', async () => { - const ctx = await backgroundSetup({ provider: 'mock', agentOptions: { model: 'child-model' } }, { reply: 'background answer' }) + const ctx = await backgroundSetup({ provider: 'mock' }, { reply: 'background answer' }) const parent = ownerAgent(ctx, 'sess-parent') const start = await callSubagent(ctx, { description: 'deep research', prompt: 'dig in', run_in_background: true }, { agent: parent }) @@ -919,12 +901,41 @@ describe('dsh-tool-subagent background mode', () => { expect(text(result)).toBe('Error: tool call aborted before dispatch') }) + it('skips background startup when cancellation wins asynchronous route preflight', async () => { + const ctx = await backgroundSetup({ provider: 'mock', enableModelSelection: true }) + const parent = ownerAgent(ctx, 'sess-parent') + const adapter = new MockAdapter([]) + let releasePreflight!: () => void + const preflightGate = new Promise((resolve) => { releasePreflight = resolve }) + const resolveModel = vi.spyOn(adapter, 'resolveModel').mockImplementation(async (provider, model) => { + await preflightGate + return { provider, id: model, name: model } + }) + ctx.llm.registerAdapter(['alpha'], adapter) + const controller = new AbortController() + + const resultPromise = callSubagent(ctx, { + description: 'cancelled selection', + prompt: 'do it', + provider: 'alpha', + model: 'selected-model', + run_in_background: true, + }, { agent: parent, signal: controller.signal }) + await vi.waitFor(() => { expect(resolveModel).toHaveBeenCalledOnce() }) + controller.abort() + releasePreflight() + const result = await resultPromise + + expect(result.isError).toBe(true) + expect(ctx.jobs.list(parent)).toEqual([]) + }) + it('settles an asynchronous provider-start failure as a failed task', async () => { const ctx = await backgroundSetup({ provider: 'mock' }) const parent = ownerAgent(ctx, 'sess-parent') ctx.subagents.registerProvider({ name: 'broken-start', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => { throw new Error('setup failed') }, }) @@ -953,7 +964,7 @@ describe('dsh-tool-subagent background mode', () => { const parent = ownerAgent(ctx, 'sess-parent') ctx.subagents.registerProvider({ name: 'pending-start', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: request => new Promise((_resolve, reject) => { request.signal.addEventListener('abort', () => { reject(new Error('startup aborted')) }, { once: true }) @@ -990,7 +1001,7 @@ describe('dsh-tool-subagent background mode', () => { const parent = ownerAgent(ctx, 'sess-parent') ctx.subagents.registerProvider({ name: 'broken-start-rollback', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: request => new Promise((_resolve, reject) => { request.signal.addEventListener('abort', () => { @@ -1035,7 +1046,7 @@ describe('dsh-tool-subagent background mode', () => { let starts = 0 ctx.subagents.registerProvider({ name: 'hanging', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async (request) => { let settle!: (value: { output: { type: 'text'; text: string }[]; stopReason: 'aborted' }) => void @@ -1182,7 +1193,7 @@ describe('dsh-tool-subagent continuable background mode', () => { let survivingChildId: ReturnType | undefined ctx.subagents.registerProvider({ name: 'gated', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, + capabilities: { agentOptions: false, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, inheritsParentContext: false, start: async () => { throw new Error('continuable policy must not start a one-shot child') }, prepareContinuable: async (request) => { @@ -1250,14 +1261,14 @@ describe('background preflight failure (no orphaned child, by construction)', () ctx: scopeFiber.ctx, inject: () => {}, options: {}, - session: { id, header: { version: 0, id, createdAt: 0 } }, + session: Session.create(id), } as unknown as Agent ctx.agents.register(parent) let starts = 0 ctx.subagents.registerProvider({ name: 'probe', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => { starts += 1 @@ -1295,7 +1306,7 @@ describe('depth budget configuration', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'capture', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, + capabilities: { agentOptions: false, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, inheritsParentContext: false, start: async (request) => { requests.push(request) @@ -1333,7 +1344,7 @@ describe('depth budget configuration', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'no-depth', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async () => { throw new Error('unreachable') }, }) @@ -1349,7 +1360,7 @@ describe('depth budget configuration', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'external', - capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, start: async (request) => { requests.push(request) diff --git a/packages/subagent/tool-subagent/tsconfig.json b/packages/subagent/tool-subagent/tsconfig.json index 8ee77dfb3b..57ee1dc9d6 100644 --- a/packages/subagent/tool-subagent/tsconfig.json +++ b/packages/subagent/tool-subagent/tsconfig.json @@ -20,6 +20,15 @@ { "path": "../../core/agent" }, + { + "path": "../../core/session" + }, + { + "path": "../../core/scope" + }, + { + "path": "../../settings/settings" + }, { "path": "../../llm/llm" }, diff --git a/packages/subagent/tool-subagent/tsdown.config.ts b/packages/subagent/tool-subagent/tsdown.config.ts new file mode 100644 index 0000000000..d91febcc25 --- /dev/null +++ b/packages/subagent/tool-subagent/tsdown.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from 'tsdown' + +const entry = (path: string) => ({ + entry: [path], + outDir: 'lib', + format: ['esm'] as const, + platform: 'node' as const, + target: 'es2024' as const, + fixedExtension: false, + dts: false, + clean: false, +}) + +/** Build self-contained Loader entries so the package needs no private chunks. */ +export default defineConfig([ + entry('lib/types/index.js'), + entry('lib/types/model-selection-settings.js'), + entry('lib/types/invariant.js'), +]) diff --git a/packages/workflow/tool-ralph/tests/tool-ralph.spec.ts b/packages/workflow/tool-ralph/tests/tool-ralph.spec.ts index 7c6f02e36c..0ccbbd16c6 100644 --- a/packages/workflow/tool-ralph/tests/tool-ralph.spec.ts +++ b/packages/workflow/tool-ralph/tests/tool-ralph.spec.ts @@ -56,6 +56,7 @@ class StubProvider implements SubagentProvider { constructor(options?: { outputSchema?: boolean; inheritsParentContext?: boolean }) { this.capabilities = { + agentOptions: true, outputSchema: options?.outputSchema ?? true, depthLimit: true, toolFilter: true, diff --git a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts index 938f9a5502..f89083faba 100644 --- a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts +++ b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts @@ -423,7 +423,7 @@ describe('dsh-tool-workflow', () => { await ctx.plugin(SubagentRuntime) ctx.subagents.registerProvider({ name: 'spawn', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, inheritsParentContext: false, start: () => Promise.reject(new Error('the parked-script fixture must not start a child')), }) diff --git a/packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts b/packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts index 31998a22cf..cf7439e8eb 100644 --- a/packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts +++ b/packages/workflow/workflow-worker-thread/tests/built-worker.e2e.ts @@ -30,7 +30,7 @@ await ctx.plugin(SubagentRuntime) let selectedStarts = 0 ctx.subagents.registerProvider({ name: 'built-selected', - capabilities: { outputSchema: true, depthLimit: false, toolFilter: false, persona: false }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: false, toolFilter: false, persona: false }, inheritsParentContext: false, async start() { selectedStarts += 1 diff --git a/packages/workflow/workflow-worker-thread/tests/source-worker.compat.spec.ts b/packages/workflow/workflow-worker-thread/tests/source-worker.compat.spec.ts index 8d33e373c7..77b87b59f8 100644 --- a/packages/workflow/workflow-worker-thread/tests/source-worker.compat.spec.ts +++ b/packages/workflow/workflow-worker-thread/tests/source-worker.compat.spec.ts @@ -21,7 +21,7 @@ it('runs the default config through the source worker', async () => { const subagents = await ctx.plugin(SubagentRuntime) const provider: SubagentProvider = { name: 'spawn', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, inheritsParentContext: false, start: () => Promise.reject(new Error('source-worker compat script must not start a child')), } diff --git a/packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.spec.ts b/packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.spec.ts index 5130071362..935dbae3fb 100644 --- a/packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.spec.ts +++ b/packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.spec.ts @@ -55,7 +55,13 @@ interface ControlledRun { * the request signal fires, like the real in-process backends. */ class StubProvider implements SubagentProvider { - readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: false } + readonly capabilities: SubagentCapabilities = { + agentOptions: true, + outputSchema: true, + depthLimit: true, + toolFilter: true, + persona: false, + } readonly inheritsParentContext = false readonly runs: ControlledRun[] = [] @@ -459,7 +465,7 @@ describe('dsh-workflow-worker-thread', () => { await ctx.plugin(SubagentRuntime) const provider: SubagentProvider = { name: 'rejecting', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, inheritsParentContext: false, start: async () => ({ id: SessionId('reject-child'), @@ -518,7 +524,7 @@ describe('dsh-workflow-worker-thread', () => { await ctx.plugin(SubagentRuntime) const provider: SubagentProvider = { name: 'bad-dispose', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, inheritsParentContext: false, start: async () => ({ id: SessionId('bad-dispose-child'), @@ -540,7 +546,7 @@ describe('dsh-workflow-worker-thread', () => { await ctx.plugin(SubagentRuntime) const provider: SubagentProvider = { name: 'coercion-trap-dispose', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, inheritsParentContext: false, start: async () => ({ id: SessionId('trap-child'), @@ -891,7 +897,7 @@ describe('dsh-workflow-worker-thread', () => { const aborted: string[] = [] const provider: SubagentProvider = { name: 'signal-only', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, inheritsParentContext: false, start: async (request) => { let settle!: (result: SubagentResult) => void @@ -1189,7 +1195,7 @@ describe('dsh-workflow-worker-thread', () => { const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => ctx.logger) const provider: SubagentProvider = { name: 'late-ready', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, inheritsParentContext: false, start: (request) => { requested.resolve(request) @@ -1250,7 +1256,7 @@ describe('dsh-workflow-worker-thread', () => { const signalAborts: unknown[] = [] const provider: SubagentProvider = { name: 'doomed', - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: false }, inheritsParentContext: false, start: async (request) => { request.signal.addEventListener('abort', () => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b84887e03b..528c1f3ff4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -225,6 +225,9 @@ importers: '@deepseek-ai/dsh-sdk-app': specifier: workspace:^ version: link:../../packages/bundle/sdk-app + '@deepseek-ai/dsh-sdk-minimal': + specifier: workspace:^ + version: link:../../packages/bundle/sdk-minimal '@deepseek-ai/dsh-session-projection': specifier: workspace:^ version: link:../../packages/session/session-projection @@ -1145,9 +1148,15 @@ importers: packages/boot/app-boot: dependencies: + '@deepseek-ai/dsh-atomic-write': + specifier: workspace:^ + version: link:../../util/atomic-write js-yaml: specifier: ^4.2.0 version: 4.2.0 + resolve.exports: + specifier: ^2.0.3 + version: 2.0.3 devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ @@ -1524,6 +1533,9 @@ importers: '@deepseek-ai/dsh-sdk-jsonrpc-server': specifier: workspace:^ version: link:../../sdk/server + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery commander: specifier: ^15.0.0 version: 15.0.0 @@ -1538,6 +1550,67 @@ importers: specifier: workspace:^ version: link:../../runtime-diagnostics/invariants + packages/bundle/sdk-minimal: + dependencies: + '@deepseek-ai/dsh-agent-spine-demo': + specifier: workspace:^ + version: link:../../examples/agent-spine-demo + '@deepseek-ai/dsh-deepseek-llm-api-extensions': + specifier: workspace:^ + version: link:../../llm/deepseek-llm-api-extensions + '@deepseek-ai/dsh-fs-local': + specifier: workspace:^ + version: link:../../fs/fs-local + '@deepseek-ai/dsh-llm-deepseek': + specifier: workspace:^ + version: link:../../llm/llm-deepseek + '@deepseek-ai/dsh-plugin-package-inventory-deepseek': + specifier: workspace:^ + version: link:../../llm/plugin-package-inventory-deepseek + '@deepseek-ai/dsh-sandbox-local': + specifier: workspace:^ + version: link:../../sandbox/sandbox-local + '@deepseek-ai/dsh-sandbox-policy': + specifier: workspace:^ + version: link:../../sandbox/sandbox-policy + '@deepseek-ai/dsh-sdk-app': + specifier: workspace:^ + version: link:../sdk-app + '@deepseek-ai/dsh-sdk-jsonrpc-server': + specifier: workspace:^ + version: link:../../sdk/server + '@deepseek-ai/dsh-session-log-deepseek': + specifier: workspace:^ + version: link:../../session/session-log-deepseek + '@deepseek-ai/dsh-session-persistence-jsonl': + specifier: workspace:^ + version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:^ + version: link:../../subprocess/subprocess-local + '@deepseek-ai/dsh-terminal': + specifier: workspace:^ + version: link:../../terminal/terminal + '@deepseek-ai/dsh-terminal-bash': + specifier: workspace:^ + version: link:../../terminal/terminal-bash + '@deepseek-ai/dsh-tool-bash-persistent': + specifier: workspace:^ + version: link:../../shell/tool-bash-persistent + '@deepseek-ai/dsh-tool-pwsh-persistent': + specifier: workspace:^ + version: link:../../shell/tool-pwsh-persistent + '@deepseek-ai/dsh-tool-str-replace-editor': + specifier: workspace:^ + version: link:../../fs/tool-str-replace-editor + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:^ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../runtime-diagnostics/invariants + packages/bundle/web-app: dependencies: '@deepseek-ai/dsh-agent-presets': @@ -1744,6 +1817,9 @@ importers: '@deepseek-ai/dsh-subprocess': specifier: workspace:^ version: link:../../subprocess/subprocess + '@deepseek-ai/dsh-tool-subagent': + specifier: workspace:^ + version: link:../../subagent/tool-subagent '@deepseek-ai/dsh-web-frontend': specifier: workspace:^ version: link:../../../apps/web @@ -6189,6 +6265,9 @@ importers: '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:^ version: link:../deepseek-llm-api-extensions + '@deepseek-ai/dsh-fs': + specifier: workspace:^ + version: link:../../fs/fs '@deepseek-ai/dsh-home-paths': specifier: workspace:^ version: link:../../util/home-paths @@ -6238,6 +6317,9 @@ importers: '@deepseek-ai/dsh-credentials': specifier: workspace:^ version: link:../../credentials/credentials + '@deepseek-ai/dsh-fs': + specifier: workspace:^ + version: link:../../fs/fs '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants @@ -6826,19 +6908,6 @@ importers: specifier: workspace:^ version: link:../../subagent/subagent - packages/sdk/python-runtime: - dependencies: - '@deepseek-ai/dsh-app-boot': - specifier: workspace:^ - version: link:../../boot/app-boot - devDependencies: - '@deepseek-ai/cordis': - specifier: workspace:^ - version: link:../../../vendor/cordis - '@deepseek-ai/dsh-invariants': - specifier: workspace:^ - version: link:../../runtime-diagnostics/invariants - packages/sdk/server: dependencies: '@deepseek-ai/schemastery': @@ -8506,6 +8575,9 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../../llm/llm + '@deepseek-ai/dsh-scope': + specifier: workspace:^ + version: link:../../core/scope '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session @@ -8515,6 +8587,9 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-settings': + specifier: workspace:^ + version: link:../../settings/settings '@deepseek-ai/dsh-subagent': specifier: workspace:^ version: link:../subagent @@ -9654,6 +9729,9 @@ importers: '@deepseek-ai/cosmokit': specifier: link:../../vendor/cosmokit version: link:../../vendor/cosmokit + '@deepseek-ai/dsh': + specifier: workspace:^ + version: link:../../apps/cli '@deepseek-ai/dsh-acp': specifier: workspace:^ version: link:../../packages/acp/acp @@ -9822,9 +9900,6 @@ importers: '@deepseek-ai/dsh-sdk-protocol': specifier: workspace:^ version: link:../../packages/sdk/protocol - '@deepseek-ai/dsh-sdk-python-runtime': - specifier: workspace:^ - version: link:../../packages/sdk/python-runtime '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../packages/core/session @@ -9855,6 +9930,9 @@ importers: '@deepseek-ai/dsh-session-reference': specifier: workspace:^ version: link:../../packages/context/session-reference + '@deepseek-ai/dsh-session-telemetry': + specifier: workspace:^ + version: link:../../packages/session/session-telemetry '@deepseek-ai/dsh-session-title': specifier: workspace:^ version: link:../../packages/session/session-title @@ -9939,6 +10017,12 @@ importers: '@deepseek-ai/dsh-tool-jobs': specifier: workspace:^ version: link:../../packages/jobs/tool-jobs + '@deepseek-ai/dsh-tool-pwsh': + specifier: workspace:^ + version: link:../../packages/shell/tool-pwsh + '@deepseek-ai/dsh-tool-pwsh-persistent': + specifier: workspace:^ + version: link:../../packages/shell/tool-pwsh-persistent '@deepseek-ai/dsh-tool-ralph': specifier: workspace:^ version: link:../../packages/workflow/tool-ralph @@ -15009,6 +15093,10 @@ packages: resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + resolve.exports@2.0.3: + resolution: {integrity: sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A==} + engines: {node: '>=10'} + retry@0.13.1: resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==} engines: {node: '>= 4'} @@ -20657,6 +20745,8 @@ snapshots: resolve-pkg-maps@1.0.0: {} + resolve.exports@2.0.3: {} + retry@0.13.1: {} rfdc@1.4.1: {} diff --git a/python/README.i18n.yaml b/python/README.i18n.yaml index 8c5a23e37b..1076f068de 100644 --- a/python/README.i18n.yaml +++ b/python/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 python/README.md -README.md: 75276a915eb4b63f84e0876de46e6d8d63540b59 -README.zh.md: f41822d66520869e5235a6fedd895b83a52639c9 +README.md: d82195fa8a3f39bea129030b2eaf7d65536041e0 +README.zh.md: cb0fb28fff7d2442c948205b07c457243fb85022 diff --git a/python/README.md b/python/README.md index 75276a915e..d82195fa8a 100644 --- a/python/README.md +++ b/python/README.md @@ -9,11 +9,11 @@ Python packages for driving DeepSeek Harness as a subprocess. The client SDK com | Directory | Dist / module | Role | |---|---|---| | [sdk](sdk/README.md) | `deepseek-harness-sdk` / `deepseek_harness` | High-level turns API and lower-level JSON-RPC client | -| [sdk-runtime](sdk-runtime/README.md) | `deepseek-harness-runtime-bin` / `deepseek_harness_runtime` | Bundled runtime binaries and default agent configuration | +| [sdk-runtime](sdk-runtime/README.md) | `deepseek-harness-runtime-bin` / `deepseek_harness_runtime` | Bundled `dsh` CLI executable and native sidecars | ## Behavior -The SDK starts the matching bundled runtime unless the caller selects an explicit channel. The client selects the channel and supplies default configuration; the runtime itself always requires an explicit configuration. The [SDK reference](sdk/README.md) and [runtime carrier reference](sdk-runtime/README.md) own the complete runtime-selection and configuration contracts. +The SDK starts the matching bundled `dsh --profile sdk` runtime unless the caller selects another `dsh` executable or profile. The runnable minimal example selects the shipped standalone `sdk-minimal` profile; the same runtime also packages `dsh web` and its frontend assets for separate CLI use. Every launch requires an explicitly selected Harness home; Python never silently reads `~/.dsh`. The [SDK reference](sdk/README.md) and [runtime carrier reference](sdk-runtime/README.md) own runtime selection, profiles, patches, and external plugin management. ## Contributor workflows diff --git a/python/README.zh.md b/python/README.zh.md index f41822d665..cb0fb28fff 100644 --- a/python/README.zh.md +++ b/python/README.zh.md @@ -9,11 +9,11 @@ | 目录 | 分发名/模块 | 职责 | |---|---|---| | [sdk](sdk/README.zh.md) | `deepseek-harness-sdk` / `deepseek_harness` | 高层轮次 API 与低层 JSON-RPC 客户端 | -| [sdk-runtime](sdk-runtime/README.zh.md) | `deepseek-harness-runtime-bin` / `deepseek_harness_runtime` | 内置运行时二进制与默认 agent(智能体)配置 | +| [sdk-runtime](sdk-runtime/README.zh.md) | `deepseek-harness-runtime-bin` / `deepseek_harness_runtime` | 内置 `dsh` CLI 可执行程序与原生伴随文件 | ## 行为 -除非调用方选择显式通道,否则 SDK 会启动匹配的内置运行时。客户端选择通道并提供默认配置;运行时本身始终要求显式配置。[SDK 参考](sdk/README.zh.md)和[运行时载体参考](sdk-runtime/README.zh.md)定义完整的运行时选择与配置约定。 +除非调用方选择另一个 `dsh` 可执行程序或 profile,否则 SDK 会启动匹配的内置 `dsh --profile sdk` 运行时。可运行极简示例选择随附的独立 `sdk-minimal` profile;同一运行时还会为独立 CLI 使用打包 `dsh web` 及其前端产物。每次启动都要求显式选择 Harness home;Python 绝不会静默读取 `~/.dsh`。[SDK 参考](sdk/README.zh.md)和[运行时载体参考](sdk-runtime/README.zh.md)定义运行时选择、profile、patch 与外部插件管理约定。 ## 贡献者工作流 diff --git a/python/development.i18n.yaml b/python/development.i18n.yaml index 75c657c153..d9f2580549 100644 --- a/python/development.i18n.yaml +++ b/python/development.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 python/development.md -development.md: e96be7af10e0008cc0fe5dea4ca51529f102fd7b -development.zh.md: e4ca1c980c36fdea381e9b8a6c615276e279b4d2 +development.md: f0d448cf4c4ce21895b3f8b0cf43db7ab052caea +development.zh.md: 74e2a6a83ca5ff5ac5b820ed6fdc8d72c0a48798 diff --git a/python/development.md b/python/development.md index e96be7af10..f0d448cf4c 100644 --- a/python/development.md +++ b/python/development.md @@ -13,7 +13,7 @@ pnpm install pnpm exec tsx scripts/build-exe-for-python-sdk.ts ``` -Use `--skip-build` when the required `lib/` artifacts already exist, or `--targets=node24-linux-x64,node24-linux-arm64,node24-macos-arm64` to select platforms. Products land in `dist-exe/` and the script syncs the selected carriers into `python/sdk-runtime/`. macOS builds also sync the matching spawn helper required by `node-pty`. +Use `--skip-build` when the required `lib/` artifacts already exist, or `--targets=node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-win-x64` to select platforms. Build each target on its native architecture. Products land in `dist-exe/` and the script syncs the selected carriers into `python/sdk-runtime/`. Windows emits `.exe` and `-rg.exe`; macOS also syncs the matching spawn helper required by `node-pty`. ## Validate the SDK @@ -31,10 +31,10 @@ That suite drives fake runtime peers. `scripts/smoke-python-runtime.py` drives t ```sh uv run --project python/sdk python scripts/smoke-python-runtime.py \ - --scenario sdk-minimal --exe dist-exe/dsh-jsonrpc-agent-pkg-macos-arm64 + --scenario sdk-minimal --exe dist-exe/deepseek-harness-sdk-runtime-macos-arm64 ``` -Three scenarios compare committed expected output under `scripts/snapshots/python-sdk-single-exe/`. `minimal/model-visible.json` pins the checked-in minimal composition's assembled system prompts, advertised tool schemas, and model-visible messages, so a plugin that contributes an unintended system section or user message fails the job; it drops the dynamic runtime-context snapshot, which the same composition emits on macOS and not on Linux ([#2488](https://github.com/deepseek-harness/deepseek-harness/issues/2488)). `advanced/` pins one complex process's SDK result and parent/child session logs. `restart/` launches two complete SDK runtime processes against one persistence root and snapshots their isolated model histories, high-level results, and separate durable logs. Rerun the owning scenario with `--update-snapshots` and review that diff before committing it. +Three scenarios compare committed expected output under `scripts/snapshots/python-sdk-single-exe/`. `minimal/model-visible.json` pins the Linux/macOS `sdk-minimal` profile's assembled system prompts, advertised tool schemas, and model-visible messages; `minimal/win-x64/model-visible.json` pins its PowerShell counterpart. A plugin that contributes an unintended system section or user message therefore fails the job, and every message the profile emits is compared. `advanced/` pins one complex process's SDK result and parent/child session logs across every target. `restart/` launches two complete SDK runtime processes against one persistence root and snapshots their isolated model histories, high-level results, and separate durable logs across every target. Rerun the owning scenario with `--update-snapshots` and review that diff before committing it. Trusted pull requests also run `--scenario sdk-live --installed-wheel` on every native target. That scenario performs two tool-using turns against `https://api.deepseek.com`, verifies the created file externally, and fails when the repository secret is absent instead of self-skipping. Fork and Dependabot pull requests run the complete keyless installed-wheel path but receive no key. @@ -43,18 +43,20 @@ An interactive smoke test needs `DEEPSEEK_API_KEY` in the environment or reposit ```python from deepseek_harness import DeepSeekHarness -with DeepSeekHarness() as harness: +with DeepSeekHarness(dsh_home="/absolute/path/to/test-dsh-home") as harness: print(harness.run("say hi").final_response) ``` +Alternatively export a non-empty `DSH_HOME`. The SDK rejects a launch that would silently use `~/.dsh`. + ## Run against Node source -Repository contributors can select either development carrier: +Repository contributors can select either development route; both execute the normal `dsh --profile sdk` launcher: - Set `DSH_RUNTIME_MODE=node` to use the built Node carrier on system Node `>=22.19`. The build script refreshes this carrier, but distributions never include or auto-select it. -- Set `launch_args_override=("./node_modules/.bin/tsx", "packages/sdk/python-runtime/src/packaged-bin.ts")` with the repository root as `cwd` to run the private carrier's unbuilt TypeScript source. Supply `cordis=...` when the default configuration is not suitable. +- Set `dsh_bin` to the absolute built `apps/cli/lib/bin.js` path to exercise the checkout's CLI directly. Supply an explicit `dsh_home`, plus `profile` and ordered `patches` as needed. -See `python/sdk/tests/manual_sdk_agent_smoke.py` for a complete source-mode invocation. +`python/sdk/tests/manual_sdk_agent_smoke.py` uses the internal `_launch_args` test adapter to exercise the unbuilt TypeScript CLI under tsx. Arbitrary argv replacement is intentionally absent from the public SDK. ## Build distributions @@ -71,17 +73,17 @@ print(release["pep440_version"](release["repository_version"]())) PY )" python scripts/build-python-release.py --package sdk --output-dir dist-python -python scripts/build-python-release.py --package runtime --platform macos-arm64 --runtime-exe dist-exe/dsh-jsonrpc-agent-pkg-macos-arm64 --output-dir dist-python +python scripts/build-python-release.py --package runtime --platform macos-arm64 --runtime-exe dist-exe/deepseek-harness-sdk-runtime-macos-arm64 --output-dir dist-python pip install \ "dist-python/deepseek_harness_sdk-$version-py3-none-any.whl" \ "dist-python/deepseek_harness_runtime_bin-$version-py3-none-macosx_14_0_arm64.whl" ``` -The runtime distribution is wheel-only. The release pipeline publishes three platform wheels with the pure SDK wheel: Linux x64, Linux arm64, and macOS 14 or newer on arm64. A `python-v` tag is accepted only when it matches the repository version; prerelease repository versions such as `0.0.1-rc.1` use their normalized PEP 440 spelling, such as `0.0.1rc1`, inside wheel filenames and metadata. +The runtime distribution is wheel-only. The release pipeline publishes four platform wheels with the pure SDK wheel: Linux x64, Linux arm64, macOS 14 or newer on arm64, and Windows x64 (`win_amd64`). A `python-v` tag is accepted only when it matches the repository version; prerelease repository versions such as `0.0.1-rc.1` use their normalized PEP 440 spelling, such as `0.0.1rc1`, inside wheel filenames and metadata. ## Validate a release candidate -Manually run the GitHub `Release (Python)` workflow with `publish=false` to build all four wheels, install the Linux release set on Python 3.10 and 3.14, check exact filenames and metadata, enforce PyPI's default per-file size limit, and retain one aggregate artifact with SHA-256 hashes. The run has no registry credentials; a dry run cannot enter either publication job. +Manually run the GitHub `Release (Python)` workflow with `publish=false` to build all five wheels, install the Linux release set on Python 3.10 and 3.14, check exact filenames and metadata, enforce PyPI's default per-file size limit, and retain one aggregate artifact with SHA-256 hashes. The run has no registry credentials; a dry run cannot enter either publication job. Public publication runs from the private automation repository; package metadata points to the separate read-only public source mirror, which does not run release Actions. The private repository defines the repository variable `PYPI_PUBLISHER_REPOSITORY` as its own `owner/name` and keeps `PUBLIC_PYPI_RELEASE_ENABLED=false` except during an intentional release. diff --git a/python/development.zh.md b/python/development.zh.md index e4ca1c980c..74e2a6a83c 100644 --- a/python/development.zh.md +++ b/python/development.zh.md @@ -13,7 +13,7 @@ pnpm install pnpm exec tsx scripts/build-exe-for-python-sdk.ts ``` -所需 `lib/` 产物已存在时使用 `--skip-build`;如需选择平台,请使用 `--targets=node24-linux-x64,node24-linux-arm64,node24-macos-arm64`。产物写入 `dist-exe/`,脚本会将所选载体同步到 `python/sdk-runtime/`。macOS 构建还会同步 `node-pty` 所需的配套 spawn 辅助程序。 +所需 `lib/` 产物已存在时使用 `--skip-build`;如需选择平台,请使用 `--targets=node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-win-x64`。每个目标都应在其原生架构上构建。产物写入 `dist-exe/`,脚本会将所选载体同步到 `python/sdk-runtime/`。Windows 会生成 `.exe` 与 `-rg.exe`;macOS 构建还会同步 `node-pty` 所需的配套 spawn 辅助程序。 ## 验证 SDK @@ -31,10 +31,10 @@ uv run --project python/sdk pytest ```sh uv run --project python/sdk python scripts/smoke-python-runtime.py \ - --scenario sdk-minimal --exe dist-exe/dsh-jsonrpc-agent-pkg-macos-arm64 + --scenario sdk-minimal --exe dist-exe/deepseek-harness-sdk-runtime-macos-arm64 ``` -其中三个场景会比对 `scripts/snapshots/python-sdk-single-exe/` 下已提交的期望输出。`minimal/model-visible.json` 固定了签入的极简组合所组装的系统提示词、对外公布的工具 schema 以及模型可见消息,因此插件一旦贡献出计划外的系统分段或 user 消息,该任务即失败;它会丢弃动态运行时上下文快照——同一组合在 macOS 上会发出它,在 Linux 上不会([#2488](https://github.com/deepseek-harness/deepseek-harness/issues/2488))。`advanced/` 固定一个复杂进程的 SDK 结果及父/子会话日志。`restart/` 针对同一持久化根目录启动两个完整 SDK 运行时进程,并固定其彼此隔离的模型历史、高层结果与独立持久日志。重新运行对应场景时加上 `--update-snapshots`,并在提交前审阅该差异。 +其中三个场景会比对 `scripts/snapshots/python-sdk-single-exe/` 下已提交的期望输出。`minimal/model-visible.json` 固定 Linux/macOS `sdk-minimal` profile 所组装的系统提示词、对外公布的工具 schema 与模型可见消息;`minimal/win-x64/model-visible.json` 固定对应的 PowerShell 版本。因此,插件一旦贡献出计划外的系统分段或 user 消息,该任务即失败,且该 profile 发出的每条消息都会参与比对。`advanced/` 跨所有目标固定一个复杂进程的 SDK 结果及父/子会话日志。`restart/` 针对同一持久化根目录启动两个完整 SDK 运行时进程,并跨所有目标固定其彼此隔离的模型历史、高层结果与独立持久日志。重新运行对应场景时加上 `--update-snapshots`,并在提交前审阅该差异。 可信拉取请求还会在每个原生目标上运行 `--scenario sdk-live --installed-wheel`。该场景面向 `https://api.deepseek.com` 执行两个使用工具的轮次,从外部验证已创建文件,并在仓库密钥缺失时失败而不是自行 skip。Fork 与 Dependabot 拉取请求会运行完整的 keyless 安装后 wheel 路径,但不会获得密钥。 @@ -43,18 +43,20 @@ uv run --project python/sdk python scripts/smoke-python-runtime.py \ ```python from deepseek_harness import DeepSeekHarness -with DeepSeekHarness() as harness: +with DeepSeekHarness(dsh_home="/absolute/path/to/test-dsh-home") as harness: print(harness.run("say hi").final_response) ``` +也可以导出非空 `DSH_HOME`。SDK 会拒绝可能静默使用 `~/.dsh` 的启动。 + ## 针对 Node 源码运行 -仓库贡献者可以选择以下任一开发载体: +仓库贡献者可以选择以下任一开发路径;两者都执行普通的 `dsh --profile sdk` 启动器: - 设置 `DSH_RUNTIME_MODE=node`,在系统 Node `>=22.19` 上使用已构建的 Node 载体。构建脚本会刷新该载体,但分发物绝不会包含或自动选择它。 -- 将仓库根目录设为 `cwd`,并设置 `launch_args_override=("./node_modules/.bin/tsx", "packages/sdk/python-runtime/src/packaged-bin.ts")`,以运行私有载体未构建的 TypeScript 源码。默认配置不合适时,请提供 `cordis=...`。 +- 将 `dsh_bin` 设置为已构建 `apps/cli/lib/bin.js` 的绝对路径,直接验证当前 checkout 的 CLI。请显式提供 `dsh_home`,并按需提供 `profile` 与有序 `patches`。 -完整的源码模式调用见 `python/sdk/tests/manual_sdk_agent_smoke.py`。 +`python/sdk/tests/manual_sdk_agent_smoke.py` 使用内部 `_launch_args` 测试适配器,通过 tsx 验证未构建的 TypeScript CLI。公开 SDK 刻意不提供任意 argv 替换。 ## 构建分发包 @@ -71,17 +73,17 @@ print(release["pep440_version"](release["repository_version"]())) PY )" python scripts/build-python-release.py --package sdk --output-dir dist-python -python scripts/build-python-release.py --package runtime --platform macos-arm64 --runtime-exe dist-exe/dsh-jsonrpc-agent-pkg-macos-arm64 --output-dir dist-python +python scripts/build-python-release.py --package runtime --platform macos-arm64 --runtime-exe dist-exe/deepseek-harness-sdk-runtime-macos-arm64 --output-dir dist-python pip install \ "dist-python/deepseek_harness_sdk-$version-py3-none-any.whl" \ "dist-python/deepseek_harness_runtime_bin-$version-py3-none-macosx_14_0_arm64.whl" ``` -运行时分发包仅提供 wheel 包。发布流水线会连同纯 SDK wheel 包一起发布三个平台 wheel 包:Linux x64、Linux arm64 和 macOS 14 或更高版本的 arm64。只有与仓库版本匹配时,才接受 `python-v` 标签;`0.0.1-rc.1` 之类的仓库预发布版本在 wheel 包文件名和元数据中使用规范化的 PEP 440 写法,例如 `0.0.1rc1`。 +运行时分发包仅提供 wheel 包。发布流水线会连同纯 SDK wheel 包一起发布四个平台 wheel 包:Linux x64、Linux arm64、macOS 14 或更高版本的 arm64,以及 Windows x64(`win_amd64`)。只有与仓库版本匹配时,才接受 `python-v` 标签;`0.0.1-rc.1` 之类的仓库预发布版本在 wheel 包文件名和元数据中使用规范化的 PEP 440 写法,例如 `0.0.1rc1`。 ## 验证候选发行版 -手动运行 GitHub 的 `Release (Python)` 工作流并设置 `publish=false`,即可构建全部四个 wheel 包,在 Python 3.10 和 3.14 上安装 Linux 发行集合,检查精确文件名和元数据,执行 PyPI 默认单文件大小限制,并保留一份带 SHA-256 哈希的汇总产物。该运行没有注册表凭据,dry-run 运行无法进入任何发布作业。 +手动运行 GitHub 的 `Release (Python)` 工作流并设置 `publish=false`,即可构建全部五个 wheel 包,在 Python 3.10 和 3.14 上安装 Linux 发行集合,检查精确文件名和元数据,执行 PyPI 默认单文件大小限制,并保留一份带 SHA-256 哈希的汇总产物。该运行没有注册表凭据,dry-run 运行无法进入任何发布作业。 公开发布从私有自动化仓库运行;包元数据指向独立的只读公开源码镜像,该镜像不运行发布 Actions。私有仓库把仓库变量 `PYPI_PUBLISHER_REPOSITORY` 定义为自身的 `owner/name`,并且只在有意发布期间把 `PUBLIC_PYPI_RELEASE_ENABLED` 从 `false` 改为 `true`。 diff --git a/python/sdk-runtime/README.i18n.yaml b/python/sdk-runtime/README.i18n.yaml index c4ccb18bf1..044ba3a728 100644 --- a/python/sdk-runtime/README.i18n.yaml +++ b/python/sdk-runtime/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 python/sdk-runtime/README.md -README.md: 67d3842a9255250f66f22ff1f9422b26c3cf3282 -README.zh.md: 47c94b29d68eb915fae5303274fe2888274c1f82 +README.md: 28695259928a7edc6e6cf67e737f1012729df5a4 +README.zh.md: f23b253cfe47d9f1ae24568b51d9db810c7a4a9f diff --git a/python/sdk-runtime/README.md b/python/sdk-runtime/README.md index 67d3842a92..2869525992 100644 --- a/python/sdk-runtime/README.md +++ b/python/sdk-runtime/README.md @@ -1,31 +1,36 @@ -# DeepSeek Harness Runtime Wheel +# deepseek-harness-runtime-bin -English | [中文](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk-runtime/README.zh.md) +English | [中文](README.zh.md) -Runtime carrier package for the Python SDK (dist `deepseek-harness-runtime-bin`, module `deepseek_harness_runtime`): it locates the bundled runtime binaries the `deepseek-harness-sdk` client spawns, and ships the default configuration behind zero-config runs. +Platform runtime wheel for the DeepSeek Harness Python SDK. It packages the normal `dsh` CLI and its closed Node dependency tree into a native executable, so SDK use requires no system Node.js. This package publishes wheels only. -## Runtime carriers +## Installed commands and artifacts -Two carriers coexist under `src/deepseek_harness_runtime/runtime/`, both injected by the repo's `scripts/build-exe-for-python-sdk.ts` build and both gitignored: +The wheel installs a `dsh` console command and the `deepseek_harness_runtime` Python module. `dsh` forwards its arguments to the bundled executable and requires a non-empty `DSH_HOME`; it never falls back to `~/.dsh`. -- **exe (production)** — a single-file Node executable `dsh-jsonrpc-agent-pkg--` (platform: `linux`/`macos`; arch: `x64`/`arm64`) with a target-native ripgrep `-rg` sidecar. macOS builds also ship the native `-spawn-helper` sibling that `node-pty` uses there. No Node installation is needed on the target machine. This is the only carrier that ships in wheel distributions; this package does not publish sdists. -- **node (dev-only)** — the full deploy closure under `runtime/node/` (`package.json` + `node_modules/`), executed as `node runtime/node/node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js` on a system Node >= 22.19. It is the current checkout's source build, meant for repo-local development and verification only; it is never selected automatically and is excluded from distributions. +Production executables are named `deepseek-harness-sdk-runtime--` under the module's `runtime/` directory; Windows uses the `.exe` suffix. Linux and macOS wheels include a target-native `-rg` sidecar, Windows includes `-rg.exe`, and macOS also includes `-spawn-helper` for `node-pty`. Published targets are Linux x64, Linux arm64, macOS arm64, and Windows x64. The wheel tag and payload must match exactly; no Windows arm64 wheel is published. -Both carriers hold the same content, defined once: the [package.json](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk-runtime/package.json) at this package's root is the private `dsh-sdk-python-runtime-closure` deploy root of the single-exe pipeline — a pure dependency manifest (no code of its own) whose dependency closure IS both the plugin set compiled into the exe and the tree materialized into `runtime/node/`. Adding a plugin to the distribution means adding one dependency line there and rebuilding. +Repository builds also materialize a dev-only `runtime/node/` carrier. It runs `node runtime/node/node_modules/@deepseek-ai/dsh/lib/bin.js` on system Node 22.19 or newer. It is never selected automatically and is excluded from wheels and sdists. -The bundled plugin set includes `@deepseek-ai/dsh-mcp-client`, so an external Cordis config can connect to stdio or Streamable HTTP MCP servers and expose their tools to the model. The wheel does not bundle MCP server programs or credentials: a stdio config supplies its executable and arguments, while a Streamable HTTP config supplies its URL and headers. The bridge supports MCP tools; MCP Resources and Prompts remain unsupported. +Both carriers execute the same `dsh` grammar and shipped profiles, including the standalone `sdk-minimal` tree and the full `web` profile with its frontend assets. The private `dsh-python-runtime-closure` manifest defines the packaged dependency closure; there is no Python-specific Node application or checked-in default `cordis.yml`. -A missing exe raises `FileNotFoundError` naming both acquisition routes: build via `scripts/build-exe-for-python-sdk.ts` in a deepseek-harness checkout, or install the matching platform runtime wheel produced by the `build-exe-for-python-sdk` CI workflow. A missing dev-only node carrier names its sole route, the build script. The workflow retains wheels rather than standalone executable archives. Acquisition strategy is deliberately separate from the lookup interface, so an on-demand download can replace it later without touching callers. +## Python module API -Each wheel contains exactly one runtime executable and its matching ripgrep `-rg` sidecar. The macOS wheel also contains its matching native spawn helper; any missing sidecar makes that installation incomplete and is a hard startup error, even for a selected Cordis composition that does not use filesystem-search or PTY tools. Linux wheels contain no spawn helper because `node-pty` uses the staged `pty.node` addon directly. The fixed tags are `py3-none-manylinux_2_28_x86_64`, `py3-none-manylinux_2_28_aarch64`, and `py3-none-macosx_14_0_arm64`; the macOS tag conservatively matches the bundled Node 24 executable's macOS 13.5 deployment target. This package's `platforms.json` owns the fixed tag and executable-name pairs used by both the repository release builder and the isolated build hook. The build hook rejects `py3-none-any`, absent or multiple runtime executables, missing or extra sidecars, non-executable files, and unsupported platform tags. The repository root `package.json` supplies the shared version for this package and the SDK, and a `python-v` release tag must match it. +- `bundled_package_dir() -> Path` returns the installed module-data root and verifies its release metadata. +- `bundled_runtime_path() -> Path` returns the current platform executable and verifies required sidecars. +- `resolve_bundled_launch_args(mode=None) -> tuple[str, ...]` returns the executable argv by default. Explicit `mode="node"` or `DSH_RUNTIME_MODE=node` selects the repo-only Node carrier. +- `main()` implements the installed `dsh` console command and rejects an absent or blank `DSH_HOME` before replacing the Python process. -## Resolution API +Unsupported platforms and missing executables or sidecars raise `FileNotFoundError` with the build and installation routes. Unknown runtime modes raise `ValueError`. -- `resolve_bundled_launch_args(mode=None) -> tuple[str, ...]` — the argv tuple that launches the bundled runtime: `(exe_path,)` in exe mode, `(node_path, bin_js_path)` in node mode. Mode selection: explicit argument > `DSH_RUNTIME_MODE` env var (`exe` | `node`) > automatic. Automatic resolution finds the production exe ONLY — the dev-only node carrier must be opted into explicitly so a production deployment can never silently ride on a source build. -- `bundled_runtime_path() -> Path` — the platform exe path (exe carrier only); it validates the required sibling `-rg` sidecar on every platform and the `-spawn-helper` sidecar on macOS. The node carrier has no single-path equivalent and launches via the argv tuple above. -- `bundled_default_config_path() -> Path` — the checked-in default config (see below). -- `bundled_package_dir() -> Path` — the installed package data root. +## Packaged profile resolution -## Zero-config design +`dsh` initializes shipped profiles under the explicit home, composes their bundle patches, and loads bundled plugins from the executable's virtual filesystem. Because operating-system symlinks cannot enter that filesystem, packaged launches maintain small real ESM proxy packages under `$DSH_HOME/profiles/node_modules`. Each proxy mirrors explicit runtime exports, records the original package identity, and re-exports the virtual module URL. Built-in rows and external plugin peers therefore share one Cordis/module instance. Native shared libraries and Windows ConPTY addons are packaged with native addons, while ripgrep and the macOS PTY helper remain executable sidecars. -The runtime binary always demands an explicit config (`$DSH_CORDIS_CONFIG`, or a config path as an argv positional argument) and exits loudly without one — that hard semantic is part of the runtime's design and this package does not soften it. The bin (`dsh-jsonrpc-agent`) boots only the plugins the config lists; the serving interface (the stdio JSON-RPC server) is itself one of its entries (`@deepseek-ai/dsh-sdk-jsonrpc-server`), and without it the booted agent has no channel to the outside. This package checks in `runtime/cordis.yml` with the JSON-RPC serving entry, agent core, a preloaded DeepSeek adapter, JSONL persistence, the explicitly composed semantic checkpoint policy, local bash, and a local filesystem provider for bounded workspace-instruction loading. The persistence backend owns durable storage while the separate policy selects request-, tool-dispatch-, and completed-step checkpoints. The adapter reads `DEEPSEEK_API_KEY` and `DEEPSEEK_BASE_URL`, while persistence, bash, and the filesystem provider use `DSH_SESSION_ROOT` and `DSH_CWD` with manual-run fallbacks. When the caller uses no explicit config channel, the `deepseek_harness` client injects that file's path via `DSH_CORDIS_CONFIG` (injection conditions: [sdk README](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk/README.md)). Zero-config is thus an explicit, visible parameter pass in the wrapper, not a hidden fallback in the runtime. +External profile management uses `dsh plugin --profile ...`. That command requires `pnpm` on `PATH`; ordinary SDK/profile execution does not. + +## Build and distribution + +From the repository root, `pnpm exec tsx scripts/build-exe-for-python-sdk.ts` verifies the closure, builds packages, deploys a symlink-free tree, packages the selected target, and syncs the executable and sidecars into this module. `scripts/build-python-release.py` stages release-shaped wheels at the root repository version and pins `deepseek-harness-sdk` to the exact runtime version. + +The installed-wheel smoke creates a clean virtual environment outside the checkout, proves distribution and executable provenance, then exercises default and customized SDK profiles, external plugins, MCP, native tools, direct JSON-RPC, committed snapshots, and the real provider on trusted runs. See the [Python contributor workflow](../development.md) and [installed-wheel testing decision](../../.agents/notes/implemented/testing/2026-08-23-installed-python-wheel-black-box-ci.md). diff --git a/python/sdk-runtime/README.zh.md b/python/sdk-runtime/README.zh.md index 47c94b29d6..f23b253cfe 100644 --- a/python/sdk-runtime/README.zh.md +++ b/python/sdk-runtime/README.zh.md @@ -1,31 +1,36 @@ -# DeepSeek Harness 运行时 wheel 包 +# deepseek-harness-runtime-bin -[English](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk-runtime/README.md) | 中文 +[English](README.md) | 中文 -Python SDK 的运行时载体包(分发名 `deepseek-harness-runtime-bin`,模块名 `deepseek_harness_runtime`):它定位 `deepseek-harness-sdk` 客户端要 spawn 的内置运行时二进制,并附带支撑零配置运行的默认配置。 +DeepSeek Harness Python SDK 的平台运行时 wheel。它把普通 `dsh` CLI 及其封闭的 Node 依赖树打包成原生可执行程序,因此使用 SDK 不需要系统 Node.js。本包只发布 wheel。 -## 运行时载体 +## 安装命令与产物 -两种载体并存于 `src/deepseek_harness_runtime/runtime/` 之下,均由仓库的 `scripts/build-exe-for-python-sdk.ts` 构建注入,且均被 git 忽略: +Wheel 会安装 `dsh` 控制台命令和 `deepseek_harness_runtime` Python 模块。`dsh` 将参数转发给内置可执行程序,并要求非空 `DSH_HOME`;它不会回退到 `~/.dsh`。 -- **exe(生产)**——单文件 Node 可执行程序 `dsh-jsonrpc-agent-pkg--`(platform:`linux`/`macos`;arch:`x64`/`arm64`),以及匹配目标平台的 ripgrep `-rg` 伴随文件。macOS 构建还会随附 `node-pty` 在该平台使用的原生 `-spawn-helper` 伴随文件。目标机器无需安装 Node。这是唯一随 wheel 包分发的载体;本包不发布 sdist。 -- **node(仅限开发)**——`runtime/node/` 下的完整部署闭包(`package.json` + `node_modules/`),在系统 Node >= 22.19 上以 `node runtime/node/node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js` 执行。它是当前检出的源码构建,仅用于仓库本地的开发与验证;不会被自动选中,也不进入分发物。 +生产可执行程序位于模块的 `runtime/` 目录,命名为 `deepseek-harness-sdk-runtime--`;Windows 使用 `.exe` 后缀。Linux 与 macOS wheel 包含目标平台原生的 `-rg` 伴随程序,Windows 包含 `-rg.exe`,macOS 还包含 `node-pty` 使用的 `-spawn-helper`。已发布目标是 Linux x64、Linux arm64、macOS arm64 与 Windows x64。Wheel tag 必须与载荷严格匹配;不发布 Windows arm64 wheel。 -两种载体承载相同的内容,且只定义一次:本包根目录的 [package.json](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk-runtime/package.json) 是 single-exe 流水线的私有 `dsh-sdk-python-runtime-closure` 部署根目录——一份零代码的纯依赖 manifest,其依赖闭包既是编译进 exe 的插件集,也是物化到 `runtime/node/` 的文件树。往分发物里加插件,就是在那里加一行依赖再重新构建。 +仓库构建还会物化仅限开发的 `runtime/node/` 载体。它在系统 Node 22.19 或更高版本上运行 `node runtime/node/node_modules/@deepseek-ai/dsh/lib/bin.js`。系统不会自动选择它,而且 wheel 与 sdist 均不包含它。 -内置插件集合包含 `@deepseek-ai/dsh-mcp-client`,因此外部 Cordis 配置可以连接 stdio 或 Streamable HTTP MCP server,并向模型提供这些 server 的工具。wheel 包不包含 MCP server 程序或凭据:stdio 配置需要提供可执行程序及其参数,Streamable HTTP 配置需要提供 URL 和请求头。该桥接仅支持 MCP 工具,尚不支持 MCP Resources 与 Prompts。 +两种载体执行相同的 `dsh` 语法与随附 profile,包括独立的 `sdk-minimal` 配置树,以及包含前端产物的完整 `web` profile。私有 `dsh-python-runtime-closure` manifest 定义打包依赖闭包;不存在 Python 专用 Node 应用或检入的默认 `cordis.yml`。 -exe 缺失时抛出 `FileNotFoundError`,并写明两种获取途径:在 deepseek-harness 检出中经 `scripts/build-exe-for-python-sdk.ts` 构建,或安装 `build-exe-for-python-sdk` CI 工作流生成的对应平台运行时 wheel 包。仅限开发的 node 载体缺失时只提示构建脚本这一条途径。该工作流只保留 wheel 包,不保留独立 exe 归档。获取策略与查找接口刻意分离,之后可以换成按需下载而不改动任何调用方。 +## Python 模块 API -每个 wheel 包只包含一个运行时可执行文件及其匹配的 ripgrep `-rg` 伴随文件。macOS wheel 包还包含与其匹配的原生 spawn helper;缺少任一伴随文件都意味着该安装不完整,并会在启动时硬失败,即使所选 Cordis 组合不使用文件系统搜索或 PTY 工具也是如此。Linux wheel 包不包含 spawn helper,因为 `node-pty` 直接使用暂存的 `pty.node` 原生插件。固定标签为 `py3-none-manylinux_2_28_x86_64`、`py3-none-manylinux_2_28_aarch64` 与 `py3-none-macosx_14_0_arm64`;macOS 标签保守匹配内置 Node 24 可执行文件的 macOS 13.5 部署目标。本包的 `platforms.json` 统一定义仓库发行构建器与隔离构建钩子使用的固定标签和可执行文件名。构建钩子会拒绝 `py3-none-any`、不存在或存在多个运行时可执行文件、缺失或多余的伴随文件、文件不可执行以及不支持的平台标签。仓库根目录的 `package.json` 为本包和 SDK 提供共同版本,`python-v` 发布标签必须与其匹配。 +- `bundled_package_dir() -> Path` 返回已安装模块数据根目录,并校验发布元数据。 +- `bundled_runtime_path() -> Path` 返回当前平台可执行程序,并校验必需伴随文件。 +- `resolve_bundled_launch_args(mode=None) -> tuple[str, ...]` 默认返回可执行程序 argv。显式 `mode="node"` 或 `DSH_RUNTIME_MODE=node` 会选择仅限仓库使用的 Node 载体。 +- `main()` 实现已安装的 `dsh` 控制台命令,并在替换 Python 进程前拒绝缺失或空白的 `DSH_HOME`。 -## 解析 API +不支持的平台以及缺失的可执行程序或伴随文件会抛出 `FileNotFoundError`,并指出构建与安装路径。未知运行时模式会抛出 `ValueError`。 -- `resolve_bundled_launch_args(mode=None) -> tuple[str, ...]`——启动内置运行时的 argv 元组:exe 模式下为 `(exe_path,)`,node 模式下为 `(node_path, bin_js_path)`。模式选择:显式参数 > `DSH_RUNTIME_MODE` 环境变量(`exe` | `node`)> 自动。自动解析只找生产 exe——仅限开发的 node 载体必须显式选用,从而生产部署绝不会悄悄跑在源码构建上。 -- `bundled_runtime_path() -> Path`——平台 exe 路径(仅 exe 载体);它会在所有平台校验必要的 `-rg` 伴随文件,并在 macOS 上额外校验 `-spawn-helper` 伴随文件。node 载体没有单一路径的等价物,经由上面的 argv 元组启动。 -- `bundled_default_config_path() -> Path`——检入的默认配置(见下文)。 -- `bundled_package_dir() -> Path`——已安装包的数据根目录。 +## 打包后的 profile 解析 -## 零配置设计 +`dsh` 在显式 home 下初始化随附 profile、组合其 bundle patch,并从可执行程序的虚拟文件系统加载内置插件。操作系统符号链接无法进入该文件系统,因此打包运行会在 `$DSH_HOME/profiles/node_modules` 下维护小型真实 ESM 代理包。每个代理镜像显式运行时 exports、记录原包身份,并重新导出虚拟模块 URL。因此,内置配置项与外部插件 peer 会共享同一个 Cordis/模块实例。原生共享库与 Windows ConPTY addon 会同其他原生 addon 一起打包;ripgrep 与 macOS PTY helper 仍是可执行伴随程序。 -运行时二进制始终要求显式配置(`$DSH_CORDIS_CONFIG`,或作为 argv 位置参数的配置路径),缺了就报错退出——这一强制语义是运行时设计的一部分,本包不会弱化它。bin(`dsh-jsonrpc-agent`)只启动配置里列出的插件;对外服务接口(stdio JSON-RPC 服务器)也是其中一个条目(`@deepseek-ai/dsh-sdk-jsonrpc-server`),缺了它,启动出的 agent(智能体)就没有对外通道。本包检入的 `runtime/cordis.yml` 包含 JSON-RPC 服务条目、agent 核心、预载的 DeepSeek 适配器、JSONL 持久化、显式组合的语义检查点策略、本地 bash,以及用于有界加载工作区指令的本地文件系统提供方。持久化后端负责持久存储,独立的策略则选择请求、工具分发和已完成步骤的检查点。DeepSeek 适配器读取 `DEEPSEEK_API_KEY` 与 `DEEPSEEK_BASE_URL`,持久化、bash 和文件系统提供方则使用 `DSH_SESSION_ROOT` 和 `DSH_CWD`,并为手动运行提供回退值。调用方未使用任何显式配置通道时,`deepseek_harness` 客户端把该文件路径注入 `DSH_CORDIS_CONFIG`(注入条件见 [sdk README](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk/README.md))。因此,零配置是包装层中一次显式、可见的参数传递,而不是运行时中的隐藏回退。 +外部 profile 管理使用 `dsh plugin --profile ...`。该命令要求 `PATH` 中存在 `pnpm`;普通 SDK/profile 运行不需要它。 + +## 构建与分发 + +在仓库根目录运行 `pnpm exec tsx scripts/build-exe-for-python-sdk.ts`,会校验闭包、构建包、部署无符号链接的文件树、打包所选目标,并把可执行程序及伴随文件同步到本模块。`scripts/build-python-release.py` 按仓库根版本暂存发布形态的 wheel,并将 `deepseek-harness-sdk` 固定到完全相同的运行时版本。 + +Installed-wheel smoke 会在 checkout 外创建干净虚拟环境,证明 distribution 与可执行程序来源,然后覆盖默认及自定义 SDK profile、外部插件、MCP、原生工具、直接 JSON-RPC、检入快照,以及可信运行中的真实提供方。另见 [Python 贡献者工作流](../development.zh.md)与 [installed-wheel 测试决策](../../.agents/notes/implemented/testing/2026-08-23-installed-python-wheel-black-box-ci.zh.md)。 diff --git a/python/sdk-runtime/hatch_build.py b/python/sdk-runtime/hatch_build.py index ef5a621f9d..22d0457d86 100644 --- a/python/sdk-runtime/hatch_build.py +++ b/python/sdk-runtime/hatch_build.py @@ -39,7 +39,15 @@ def _host_platform_tag() -> str: machine = platform.machine().lower() arch = "arm64" if machine in {"arm64", "aarch64"} else "x64" if machine in {"x86_64", "amd64"} else machine system = platform.system().lower() - key = f"macos-{arch}" if system == "darwin" else f"linux-{arch}" if system == "linux" else system + key = ( + f"macos-{arch}" + if system == "darwin" + else f"linux-{arch}" + if system == "linux" + else f"win-{arch}" + if system == "windows" + else system + ) try: return _PLATFORMS[key][0] except KeyError as exc: @@ -66,17 +74,24 @@ class RuntimeBuildHook(BuildHookInterface): ) expected_executable = matches[0][1] runtime_dir = Path(self.root) / "src" / "deepseek_harness_runtime" / "runtime" - runtime_files = sorted(runtime_dir.glob("dsh-jsonrpc-agent-pkg-*") if runtime_dir.is_dir() else []) - expected_files = [expected_executable, f"{expected_executable}-rg"] + runtime_files = sorted( + runtime_dir.glob("deepseek-harness-sdk-runtime-*") if runtime_dir.is_dir() else [] + ) + expected_files = ( + [expected_executable, f"{expected_executable.removesuffix('.exe')}-rg.exe"] + if expected_executable.endswith(".exe") + else [expected_executable, f"{expected_executable}-rg"] + ) if "-macos-" in expected_executable: expected_files.append(f"{expected_executable}-spawn-helper") + expected_files.sort() found_files = [path.name for path in runtime_files] if found_files != expected_files: raise RuntimeError( f"runtime wheel {platform_tag} payload must be {expected_files}; found {found_files}" ) for executable in runtime_files: - if executable.stat().st_mode & stat.S_IXUSR == 0: + if platform_tag != "win_amd64" and executable.stat().st_mode & stat.S_IXUSR == 0: raise RuntimeError(f"runtime executable is not executable: {executable}") build_data["pure_python"] = False build_data["infer_tag"] = False diff --git a/python/sdk-runtime/package.json b/python/sdk-runtime/package.json index dad5db82b7..331d388a0f 100644 --- a/python/sdk-runtime/package.json +++ b/python/sdk-runtime/package.json @@ -1,6 +1,6 @@ { - "name": "dsh-sdk-python-runtime-closure", - "description": "Dependency-only deploy root defining the executable and Python runtime closure; pnpm deploy materializes this manifest and node_modules.", + "name": "dsh-python-runtime-closure", + "description": "Dependency-only deploy root defining the dsh executable shipped by the Python runtime wheel.", "version": "0.0.1", "private": true, "type": "module", @@ -10,6 +10,7 @@ "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/cordis-plugin-timer": "workspace:^", "@deepseek-ai/cosmokit": "workspace:^", + "@deepseek-ai/dsh": "workspace:^", "@deepseek-ai/dsh-acp": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", @@ -45,7 +46,6 @@ "@deepseek-ai/dsh-hooks-codex": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-sdk-jsonrpc-server": "workspace:^", - "@deepseek-ai/dsh-sdk-python-runtime": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:^", @@ -59,6 +59,7 @@ "@deepseek-ai/dsh-plan-mode": "workspace:^", "@deepseek-ai/dsh-persona": "workspace:^", "@deepseek-ai/dsh-pwsh-local": "workspace:^", + "@deepseek-ai/dsh-tool-pwsh-persistent": "workspace:^", "@deepseek-ai/dsh-terminal": "workspace:^", "@deepseek-ai/dsh-terminal-bash": "workspace:^", "@deepseek-ai/dsh-repeat-tool-reminder": "workspace:^", @@ -77,6 +78,7 @@ "@deepseek-ai/dsh-session-query": "workspace:^", "@deepseek-ai/dsh-session-query-sqlite": "workspace:^", "@deepseek-ai/dsh-session-reference": "workspace:^", + "@deepseek-ai/dsh-session-telemetry": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-settings": "workspace:^", "@deepseek-ai/dsh-skill": "workspace:^", @@ -102,6 +104,7 @@ "@deepseek-ai/dsh-tool-fs": "workspace:^", "@deepseek-ai/dsh-tool-fs-search": "workspace:^", "@deepseek-ai/dsh-tool-goal": "workspace:^", + "@deepseek-ai/dsh-tool-pwsh": "workspace:^", "@deepseek-ai/dsh-tool-ralph": "workspace:^", "@deepseek-ai/dsh-tool-skill": "workspace:^", "@deepseek-ai/dsh-tool-str-replace-editor": "workspace:^", diff --git a/python/sdk-runtime/platforms.json b/python/sdk-runtime/platforms.json index 069378e8cb..9c0a1fec72 100644 --- a/python/sdk-runtime/platforms.json +++ b/python/sdk-runtime/platforms.json @@ -1,14 +1,18 @@ { "linux-x64": { "tag": "manylinux_2_28_x86_64", - "executable": "dsh-jsonrpc-agent-pkg-linux-x64" + "executable": "deepseek-harness-sdk-runtime-linux-x64" }, "linux-arm64": { "tag": "manylinux_2_28_aarch64", - "executable": "dsh-jsonrpc-agent-pkg-linux-arm64" + "executable": "deepseek-harness-sdk-runtime-linux-arm64" }, "macos-arm64": { "tag": "macosx_14_0_arm64", - "executable": "dsh-jsonrpc-agent-pkg-macos-arm64" + "executable": "deepseek-harness-sdk-runtime-macos-arm64" + }, + "win-x64": { + "tag": "win_amd64", + "executable": "deepseek-harness-sdk-runtime-win-x64.exe" } } diff --git a/python/sdk-runtime/pyproject.toml b/python/sdk-runtime/pyproject.toml index 090efc6139..4005314aa0 100644 --- a/python/sdk-runtime/pyproject.toml +++ b/python/sdk-runtime/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "hatchling.build" [project] name = "deepseek-harness-runtime-bin" version = "0.0.0.dev0" -description = "Pinned DeepSeek Harness runtime for the Python SDK" +description = "Bundled dsh CLI runtime for the DeepSeek Harness Python SDK" readme = "README.md" requires-python = ">=3.10" license = "MIT" @@ -17,10 +17,12 @@ Documentation = "https://github.com/deepseek-ai/deepseek-harness/blob/master/pyt Issues = "https://github.com/deepseek-ai/deepseek-harness/issues" Source = "https://github.com/deepseek-ai/deepseek-harness" -# Include the injected executable and default config; exclude the dev-only node -# closure from wheels and sdists. +[project.scripts] +dsh = "deepseek_harness_runtime:main" + +# Include the injected dsh executable and sidecars; exclude the dev-only node closure. [tool.hatch.build] -artifacts = ["src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-*"] +artifacts = ["src/deepseek_harness_runtime/runtime/deepseek-harness-sdk-runtime-*"] exclude = ["src/deepseek_harness_runtime/runtime/node"] [tool.hatch.build.targets.wheel] diff --git a/python/sdk-runtime/src/deepseek_harness_runtime/__init__.py b/python/sdk-runtime/src/deepseek_harness_runtime/__init__.py index 94aca48d9f..2081aa5070 100644 --- a/python/sdk-runtime/src/deepseek_harness_runtime/__init__.py +++ b/python/sdk-runtime/src/deepseek_harness_runtime/__init__.py @@ -1,22 +1,22 @@ -"""Locate the bundled DeepSeek Harness SDK runtime shipped with this package. +"""Locate and execute the bundled dsh CLI shipped with the Python SDK runtime. Two runtime carriers coexist under ``runtime/``, both injected by the repo's ``scripts/build-exe-for-python-sdk.ts`` build (neither is checked into git): - **exe (production)**: single-file Node executables named - ``dsh-jsonrpc-agent-pkg--`` (platform in {linux, macos}, arch in - {x64, arm64}) with a sibling ``-rg`` executable; macOS also uses a sibling - ``-spawn-helper``. The target machine needs no Node installation. + ``deepseek-harness-sdk-runtime--`` for Linux/macOS and an + ``.exe`` counterpart for Windows. Each has a sibling ripgrep executable; + macOS also uses a sibling ``-spawn-helper``. The target machine needs no + Node installation. - **node (dev-only)**: the full deploy closure under ``runtime/node/`` (``package.json`` + ``node_modules/``), executed as ``node - runtime/node/node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js`` on a + runtime/node/node_modules/@deepseek-ai/dsh/lib/bin.js`` on a system Node >= 22.19. It is the current checkout's source build, never selected automatically, and excluded from wheel/sdist distributions. -``runtime/cordis.yml`` IS checked in: it is the default agent configuration -the client SDK injects via ``$DSH_CORDIS_CONFIG`` for zero-config runs — the -runtime itself always requires an explicit config and has no built-in -fallback. +Both carriers execute the same dsh command grammar. The Python SDK selects the +``sdk`` profile and requires an explicit Harness home; the installed ``dsh`` +console command requires ``DSH_HOME`` for the same reason. """ from __future__ import annotations @@ -31,7 +31,7 @@ PACKAGE_METADATA_FILENAME = "deepseek-harness-runtime.json" RUNTIME_MODE_ENV_VAR = "DSH_RUNTIME_MODE" -_PLATFORM_TAGS = {"linux": "linux", "darwin": "macos"} +_PLATFORM_TAGS = {"linux": "linux", "darwin": "macos", "win32": "win"} _ARCH_TAGS = {"x86_64": "x64", "amd64": "x64", "arm64": "arm64", "aarch64": "arm64"} _EXE_ACQUISITION_HINT = ( @@ -52,21 +52,6 @@ def bundled_package_dir() -> Path: return root -def bundled_default_config_path() -> Path: - """Path of the checked-in default runtime configuration (``runtime/cordis.yml``). - - The client SDK injects this path via ``$DSH_CORDIS_CONFIG`` when the caller - supplies no config and the launch resolves to the bundled runtime — the - runtime binary itself always demands an explicit config. - """ - path = bundled_package_dir() / "runtime" / "cordis.yml" - if not path.is_file(): - raise FileNotFoundError( - f"deepseek-harness-runtime-bin is missing the default runtime config at {path}" - ) - return path - - def bundled_runtime_path() -> Path: """Absolute path of the bundled single-file runtime executable for the current platform. @@ -78,13 +63,18 @@ def bundled_runtime_path() -> Path: touching callers). """ tag = _current_platform_tag() - path = bundled_package_dir() / "runtime" / f"dsh-jsonrpc-agent-pkg-{tag}" + extension = ".exe" if tag.startswith("win-") else "" + path = bundled_package_dir() / "runtime" / f"deepseek-harness-sdk-runtime-{tag}{extension}" if not path.is_file(): raise FileNotFoundError( f"deepseek-harness-runtime-bin is missing the runtime executable at {path}. " + _EXE_ACQUISITION_HINT ) - ripgrep = Path(f"{path}-rg") + ripgrep = ( + path.with_name(f"{path.stem}-rg.exe") + if tag.startswith("win-") + else Path(f"{path}-rg") + ) if not ripgrep.is_file(): raise FileNotFoundError( f"deepseek-harness-runtime-bin is missing the ripgrep sidecar at {ripgrep}. " @@ -126,11 +116,16 @@ def resolve_bundled_launch_args(mode: str | None = None) -> tuple[str, ...]: def _current_platform_tag() -> str: plat = _PLATFORM_TAGS.get(sys.platform) arch = _ARCH_TAGS.get(platform.machine().lower()) - if plat is None or arch is None: + if ( + plat is None + or arch is None + or (plat == "win" and arch != "x64") + or (plat == "macos" and arch != "arm64") + ): raise FileNotFoundError( - "no bundled dsh-jsonrpc-agent executable exists for this platform " + "no bundled DeepSeek Harness SDK runtime exists for this platform " f"(sys.platform={sys.platform!r}, machine={platform.machine()!r}); supported: " - "linux/macos on x64/arm64. " + _EXE_ACQUISITION_HINT + "Linux x64/arm64, macOS arm64, and Windows x64. " + _EXE_ACQUISITION_HINT ) return f"{plat}-{arch}" @@ -141,9 +136,9 @@ def _node_launch_args() -> tuple[str, str]: node_root / "node_modules" / "@deepseek-ai" - / "dsh-sdk-python-runtime" + / "dsh" / "lib" - / "packaged-bin.js" + / "bin.js" ) if not bin_js.is_file(): raise FileNotFoundError( @@ -161,11 +156,24 @@ def _node_launch_args() -> tuple[str, str]: return (node, str(bin_js)) +def main() -> None: + """Execute the bundled dsh CLI with an explicitly selected Harness home.""" + if not os.environ.get("DSH_HOME", "").strip(): + print( + "dsh: the Python runtime command requires an explicit DSH_HOME; " + "it never uses ~/.dsh implicitly", + file=sys.stderr, + ) + raise SystemExit(2) + argv = (*resolve_bundled_launch_args(), *sys.argv[1:]) + os.execvpe(argv[0], argv, os.environ) + + __all__ = [ "PACKAGE_METADATA_FILENAME", "RUNTIME_MODE_ENV_VAR", - "bundled_default_config_path", "bundled_package_dir", "bundled_runtime_path", + "main", "resolve_bundled_launch_args", ] diff --git a/python/sdk-runtime/src/deepseek_harness_runtime/runtime/cordis.yml b/python/sdk-runtime/src/deepseek_harness_runtime/runtime/cordis.yml deleted file mode 100644 index 02f8cac145..0000000000 --- a/python/sdk-runtime/src/deepseek_harness_runtime/runtime/cordis.yml +++ /dev/null @@ -1,58 +0,0 @@ -# Bundled default config. The runtime still requires an explicit -# $DSH_CORDIS_CONFIG or argv path; the SDK injects this path for bundled -# zero-config launches. SDK-set session-root and cwd variables have manual-run fallbacks. - -# Stdio JSON-RPC server entry; without it the agent has no SDK client. -- id: sdk-jsonrpc-server - name: '@deepseek-ai/dsh-sdk-jsonrpc-server' - -# Agent spine; the SDK server creates agents per sessionId. -- id: agent-core - name: '@deepseek-ai/dsh-agent-spine-demo' - config: - workspaceContext: - maxBytes: 65536 - -# Stock DeepSeek adapters. The adapter resolves DEEPSEEK_API_KEY through the -# credential seam and, with no provider mounted here, from the launching -# environment; DEEPSEEK_BASE_URL follows the same environment ladder. Neither -# is inlined, so this file names no secret and no route. -- id: deepseek-llm-api-extensions - name: '@deepseek-ai/dsh-deepseek-llm-api-extensions' - -- id: session-log-deepseek - name: '@deepseek-ai/dsh-session-log-deepseek' - -- id: plugin-package-inventory-deepseek - name: '@deepseek-ai/dsh-plugin-package-inventory-deepseek' - -- id: llm-deepseek - name: '@deepseek-ai/dsh-llm-deepseek' - -# JSONL persistence; $DSH_SESSION_ROOT wins over ./.sessions in the process cwd. -- id: sessions - name: '@deepseek-ai/dsh-session-persistence-jsonl' - config: - root: !!js process.env.DSH_SESSION_ROOT ?? './.sessions' - -# Persistence owns durable storage; this separate policy explicitly selects -# the request, tool-dispatch, and completed-step durability checkpoints. -- id: session-checkpoints - name: '@deepseek-ai/dsh-session-checkpoint-policy' - -# Local bash executor; $DSH_CWD wins over the process cwd. -# Managed child-process groups for the bash executor (spawn/kill/output plumbing). -- id: subprocess - name: '@deepseek-ai/dsh-subprocess-local' - -- id: bash - name: '@deepseek-ai/dsh-bash-local' - config: - cwd: !!js process.env.DSH_CWD ?? process.cwd() - -# Local filesystem provider for workspace instruction loading. This does not -# expose model-facing file tools by itself. -- id: fs-local - name: '@deepseek-ai/dsh-fs-local' - config: - cwd: !!js process.env.DSH_CWD ?? process.cwd() diff --git a/python/sdk/README.i18n.yaml b/python/sdk/README.i18n.yaml index 4b93a8d04e..c8ee3ec85f 100644 --- a/python/sdk/README.i18n.yaml +++ b/python/sdk/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 python/sdk/README.md -README.md: 99515c52e6314dc29788a324338699d75c0a4451 -README.zh.md: 6ec268545107478ce9f347cdfb7f17d4a8afd151 +README.md: 1b03fe5553f25da3bc62f8a7eec2a274b0afb66a +README.zh.md: c0bfa8bdd9e2ecbaad0a019a274b94516e219ac6 diff --git a/python/sdk/README.md b/python/sdk/README.md index 99515c52e6..1b03fe5553 100644 --- a/python/sdk/README.md +++ b/python/sdk/README.md @@ -1,51 +1,66 @@ # DeepSeek Harness Python SDK -English | [中文](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk/README.zh.md) +English | [中文](README.zh.md) -Python subprocess SDK for driving DeepSeek Harness over JSON-RPC stdio. The -runtime inherits normal DeepSeek Harness environment variables such as -`DEEPSEEK_BASE_URL` and `DEEPSEEK_API_KEY`, so callers can use real model -endpoints directly or point those variables at a local proxy. - -Install the `deepseek-harness-sdk` distribution from PyPI; the import module remains `deepseek_harness`: +Python subprocess SDK for driving DeepSeek Harness over newline-delimited JSON-RPC on stdio. Install `deepseek-harness-sdk`; it installs the exact same-version `deepseek-harness-runtime-bin` wheel for the current platform. ```sh python -m pip install deepseek-harness-sdk ``` -Installing `deepseek-harness-sdk` installs the exact same-version `deepseek-harness-runtime-bin` platform wheel. The normal entry point therefore needs no executable argument: +## Start a runtime -```py -from deepseek_harness import DeepSeekHarness +The Python SDK has no separate application entrypoint. It launches the bundled `dsh` CLI with `--profile sdk`; the selected profile owns the JSON-RPC server, agent composition, credentials, persistence, tools, and shutdown behavior. -with DeepSeekHarness() as harness: - result = harness.run("Say hi.") -``` - -`DeepSeekHarness` keeps its lazily started runtime subprocess for reuse across calls. Use it as a context manager, as above, or call `close()` explicitly when finished. - -By default, the SDK launches the bundled single-file `dsh-jsonrpc-agent` executable from the `deepseek-harness-runtime-bin` package and injects that package's default configuration (the stdio JSON-RPC server, agent core, preloaded DeepSeek adapter, JSONL session persistence with an explicitly composed semantic checkpoint policy, local bash) via `DSH_CORDIS_CONFIG`. To run a plugin composition of your own, keep the `@deepseek-ai/dsh-sdk-jsonrpc-server` entry in the config and pass the Cordis config path. +Every launch requires an explicit Harness home. Pass `dsh_home` or provide a non-empty `DSH_HOME` in the child environment. The SDK deliberately never discovers `~/.dsh`. ```py from deepseek_harness import DeepSeekHarness with DeepSeekHarness( - provider="deepseek-official", - model="deepseek-v4-flash", - max_tokens=49_152, - cordis="examples/python-sdk-agent/cordis.yml", + dsh_home="/absolute/path/to/isolated-dsh-home", + cwd="/absolute/path/to/workspace", +) as harness: + result = harness.run("Say hi.", session_id="example-001") + +print(result.final_response) +``` + +`DeepSeekHarness` starts lazily and reuses its runtime until `close()` or context-manager exit. The initial profile handshake has an independent 30-second default bound through `initialize_timeout_seconds`; ordinary turns remain unbounded unless `request_timeout_seconds` is set. A timeout names the selected profile and includes retained runtime diagnostics. `cwd` is the agent workspace; `runtime_cwd` independently selects the subprocess working directory. Both become absolute before launch. `provider`, `model`, and optional positive `max_tokens` are sent during JSON-RPC initialization. `base_url` and `api_key` explicitly override `DEEPSEEK_BASE_URL` and `DEEPSEEK_API_KEY` in the child environment. + +## Customize plugins + +Persistent customization belongs to a `dsh` profile. Initialize the shipped SDK profile and install an external bundle with the runtime wheel's `dsh` command: + +```sh +export DSH_HOME=/absolute/path/to/isolated-dsh-home +dsh --profile sdk --dump-default-config >/dev/null +dsh plugin --profile sdk add file:/absolute/path/to/my-plugin-bundle +``` + +The `file:` form installs the local bundle into the profile package tree, where its peer imports reach the bundled installation fallback. The profile manifest records installed dependencies and ordered bundle layers; its `$DSH_HOME/profiles/sdk/cordis.patch.yml` is the persistent user patch. `dsh plugin` needs `pnpm` only when managing external packages. Running the SDK does not require system Node.js. + +For an invocation-specific change, pass one or more patch files. They become absolute and are forwarded in order after the profile and home patch layers: + +```py +with DeepSeekHarness( + dsh_home="/absolute/path/to/isolated-dsh-home", + profile="sdk", + patches=("/absolute/path/to/first.patch.yml", "/absolute/path/to/last.patch.yml"), ) as harness: result = harness.run("Make the requested code change.") ``` -`provider` selects a provider route registered by the chosen Cordis composition; `model` is the model id resolved by that adapter. `max_tokens` is an optional positive per-request output-token cap for the root agent and its in-process descendants; omission leaves the provider default in control. Compaction summaries keep the separate limit configured by their compaction plugin. The bundled default composition registers `deepseek-official`. A custom composition can mount `llm-pi-ai`, configure provider-specific credentials/endpoints there, and select any provider/model present in pi-ai's installed catalog. +`profile` may select another existing profile, but that composition must retain `@deepseek-ai/dsh-sdk-app` or another `@deepseek-ai/dsh-sdk-jsonrpc-server` row. Misconfiguration fails during CLI boot or SDK initialization; there is no complete-config fallback. `dsh_bin` may select another `dsh` executable while preserving the same profile grammar. Arbitrary argv replacement remains an internal fake-runtime test adapter, not public API. -The [Python SDK tutorial](https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/user/guide/python-sdk.md) provides an ordered installation and first-run path without the Web UI. The [`python-sdk-agent` example](https://github.com/deepseek-ai/deepseek-harness/blob/master/examples/python-sdk-agent/README.md) owns the complete standalone Cordis file used there. +The shipped `sdk-minimal` profile is a standalone explicit tree rather than an overlay on `dsh-base`. Select it with `profile="sdk-minimal"`; the ordinary `model` argument is the sole runtime model selection, including for model ids outside the adapter's advisory catalog. It provides persistent Bash, the string-replace editor, local execution, and JSONL sessions; settings, managed credentials, telemetry, Web tools, and the full default tool roster remain available through the separate full `sdk` and `web` profiles. -`Session.run()` owns an activity interval from its prompt's durable inbox receipt through the next whole-agent idle and returns `RunResult(session_id, final_response, finish_reason, events, notifications, session_root)`. `final_response` is the last committed root-session assistant text in the interval. `finish_reason` is the `kind` of the last root-session `turn/end` in the interval, such as `completed`, `max-tokens`, or `error`, and is `None` when no turn ended. A `turn/end` without a string `data.reason.kind` violates the runtime protocol and raises `SdkProtocolError`. Both result fields describe the owned interval rather than an output or ending causally assigned to the prompt. Steering, injected context, and other queued work may contribute before idle. +## Results and notifications -`HarnessClient` retains discovered subagent ancestry for the lifetime of the runtime process. During each `Session.run()`, `RunResult.notifications` and `on_notification` receive the root session and all known descendant notifications in wire order, including nested subagent lifecycle and session events. `RunResult.events` contains root-session events only, so descendant messages cannot replace the root response. The low-level `session_prompt()` returns the queued `MessageId` immediately; callers that bypass `Session.run()` own any later activity boundary themselves. +`Session.run()` owns an activity interval from its prompt's durable inbox receipt through the next whole-agent idle and returns `RunResult(session_id, final_response, finish_reason, events, notifications)`. `final_response` is the last committed root-session assistant text in the interval. `finish_reason` is the `kind` of the last root-session `turn/end`, such as `completed`, `max-tokens`, or `error`, and is `None` when no turn ended. A `turn/end` without a string `data.reason.kind` violates the protocol and raises `SdkProtocolError`. -The same behavior can be selected for the runtime subprocess with `DSH_CORDIS_CONFIG`. The injection lives in `HarnessClient.start()`, so the low-level client's default launch gets it too: when the launch resolves to the bundled runtime and neither `cordis` nor a non-empty `DSH_CORDIS_CONFIG` is set (the runtime treats an empty value as absent, and so does the injection check), the bundled default configuration is used; an explicit `runtime_bin`, `bridge_bin`, or `launch_args_override` disables the injection entirely. See the [sdk-runtime README](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk-runtime/README.md) for the runtime carriers (production exe vs dev-only node closure) and how to obtain them. +`HarnessClient` retains discovered subagent ancestry for the runtime process lifetime. During `Session.run()`, `RunResult.notifications` and `on_notification` receive the root session and known descendants in wire order. `RunResult.events` contains root-session events only, so descendant output cannot replace the root response. The low-level `session_prompt()` returns the queued message id immediately; callers that bypass `Session.run()` own the later activity boundary. -`cwd` and `runtime_cwd` are resolved to absolute paths before subprocess launch, environment injection, and the wire handshake. The public API exposes only applied options: deployment persona and persistence belong in `cordis.yml`, while `session_root` remains the high-level convenience that sets `DSH_SESSION_ROOT`. +The selected home stores profiles, plugins, and every profile-owned durable resource. The full `sdk` profile uses its credentials, settings, and session stores; `sdk-minimal` uses only its JSONL session store. Use a fresh home when those resources must be isolated, and a fresh session id for independent work. Reusing both a harness and session id continues the durable conversation and session-owned resources. + +See the [Python tutorial](../../docs/user/guide/python-sdk.md), [`python-sdk-agent` example](../../examples/python-sdk-agent/README.md), and [runtime wheel reference](../sdk-runtime/README.md). diff --git a/python/sdk/README.zh.md b/python/sdk/README.zh.md index 6ec2685451..c0bfa8bdd9 100644 --- a/python/sdk/README.zh.md +++ b/python/sdk/README.zh.md @@ -1,48 +1,66 @@ # DeepSeek Harness Python SDK -[English](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk/README.md) | 中文 +[English](README.md) | 中文 -通过 JSON-RPC stdio 驱动 DeepSeek Harness 的 Python 子进程 SDK。运行时继承常规的 DeepSeek Harness 环境变量(如 `DEEPSEEK_BASE_URL` 与 `DEEPSEEK_API_KEY`),调用方可以直接使用真实模型端点,也可以把这些变量指向本地代理。 - -请从 PyPI 安装 `deepseek-harness-sdk` 分发包;导入模块仍为 `deepseek_harness`: +用于通过 stdio 上按行分隔的 JSON-RPC 驱动 DeepSeek Harness 的 Python 子进程 SDK。安装 `deepseek-harness-sdk` 时,会同时安装当前平台上版本完全相同的 `deepseek-harness-runtime-bin` wheel。 ```sh python -m pip install deepseek-harness-sdk ``` -安装 `deepseek-harness-sdk` 会同时安装版本完全相同的 `deepseek-harness-runtime-bin` 平台 wheel 包。因此常规入口不需要传可执行文件参数: +## 启动运行时 -```py -from deepseek_harness import DeepSeekHarness +Python SDK 没有独立的应用入口。它以 `--profile sdk` 启动内置的 `dsh` CLI;所选 profile 负责 JSON-RPC 服务器、agent 组合、凭据、持久化、工具和关闭流程。 -with DeepSeekHarness() as harness: - result = harness.run("Say hi.") -``` - -`DeepSeekHarness` 会保留其按需启动的运行时子进程,以便在多次调用之间复用。请像上例一样将其用作上下文管理器,或在使用完毕后显式调用 `close()`。 - -默认情况下,SDK 会启动 `deepseek-harness-runtime-bin` 包内置的单文件可执行程序 `dsh-jsonrpc-agent`,并通过 `DSH_CORDIS_CONFIG` 注入该包的默认配置,其中包括 stdio JSON-RPC 服务器、agent core(智能体核心)、预载的 DeepSeek 适配器、采用显式组合语义检查点策略的 JSONL 会话持久化,以及本地 bash。要运行自己的插件组合,请在配置中保留 `@deepseek-ai/dsh-sdk-jsonrpc-server` 配置项,并传入 Cordis 配置文件路径。 +每次启动都必须显式指定 Harness home。请传入 `dsh_home`,或在子进程环境中提供非空的 `DSH_HOME`。SDK 刻意不会发现 `~/.dsh`。 ```py from deepseek_harness import DeepSeekHarness with DeepSeekHarness( - provider="deepseek-official", - model="deepseek-v4-flash", - max_tokens=49_152, - cordis="examples/python-sdk-agent/cordis.yml", + dsh_home="/absolute/path/to/isolated-dsh-home", + cwd="/absolute/path/to/workspace", +) as harness: + result = harness.run("Say hi.", session_id="example-001") + +print(result.final_response) +``` + +`DeepSeekHarness` 延迟启动运行时,并在调用 `close()` 或退出上下文管理器前复用该进程。首次 profile 握手通过 `initialize_timeout_seconds` 使用独立的 30 秒默认上限;普通轮次在未设置 `request_timeout_seconds` 时仍不设上限。超时诊断会指明所选 profile,并包含保留的运行时诊断。`cwd` 是 agent workspace;`runtime_cwd` 独立选择子进程工作目录。两者都会在启动前转成绝对路径。`provider`、`model` 和可选的正整数 `max_tokens` 通过 JSON-RPC 初始化发送。`base_url` 与 `api_key` 会显式覆盖子进程环境中的 `DEEPSEEK_BASE_URL` 与 `DEEPSEEK_API_KEY`。 + +## 自定义插件 + +持久自定义属于 `dsh` profile。使用运行时 wheel 提供的 `dsh` 命令初始化随附的 SDK profile,并安装外部 bundle: + +```sh +export DSH_HOME=/absolute/path/to/isolated-dsh-home +dsh --profile sdk --dump-default-config >/dev/null +dsh plugin --profile sdk add file:/absolute/path/to/my-plugin-bundle +``` + +`file:` 形式会把本地 bundle 安装到 profile 包树中,使其 peer import 可以到达内置安装后备。Profile manifest 会记录已安装依赖与有序 bundle 层;`$DSH_HOME/profiles/sdk/cordis.patch.yml` 是持久用户 patch。只有管理外部包时,`dsh plugin` 才需要 `pnpm`。运行 SDK 不需要系统 Node.js。 + +对于单次调用的变更,可传入一个或多个 patch 文件。它们会转成绝对路径,并在 profile 层与 home patch 层之后按顺序传给 CLI: + +```py +with DeepSeekHarness( + dsh_home="/absolute/path/to/isolated-dsh-home", + profile="sdk", + patches=("/absolute/path/to/first.patch.yml", "/absolute/path/to/last.patch.yml"), ) as harness: result = harness.run("Make the requested code change.") ``` -`provider` 选择指定 Cordis 组合所注册的提供方路由;`model` 是该适配器解析出的模型 ID。`max_tokens` 是一个可选的正整数,用于限制根 agent 及其进程内后代在每次请求中输出的 token 数量;省略该参数时,由提供方的默认行为决定输出上限。压缩摘要继续使用压缩插件单独配置的上限。内置默认组合注册 `deepseek-official`。自定义组合可以挂载 `llm-pi-ai`,在其中配置各提供方专属的凭据和端点,并选择 pi-ai 已安装 catalog 中存在的任意提供方/模型组合。 +`profile` 可以选择另一个已存在的 profile,但该组合必须保留 `@deepseek-ai/dsh-sdk-app` 或另一个 `@deepseek-ai/dsh-sdk-jsonrpc-server` 配置项。配置错误会在 CLI 启动或 SDK 初始化时失败;不存在完整配置回退。`dsh_bin` 可以选择另一个 `dsh` 可执行程序,同时保持相同的 profile 语法。任意 argv 替换仅是内部 fake-runtime 测试适配器,不属于公开 API。 -[Python SDK 教程](https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/user/guide/python-sdk.md)提供一套无需使用 Web UI、按步骤完成安装和首次运行的流程。该教程所用的完整独立 Cordis 配置文件位于 [`python-sdk-agent` 示例](https://github.com/deepseek-ai/deepseek-harness/blob/master/examples/python-sdk-agent/README.md)中。 +随附的 `sdk-minimal` profile 是独立显式配置树,而不是 `dsh-base` 上的 overlay。使用 `profile="sdk-minimal"` 选择它;普通 `model` 参数是唯一运行时模型选择,也适用于不在适配器建议目录中的模型 id。它提供持久 Bash、字符串替换 editor、本地执行与 JSONL 会话;settings、托管凭据、遥测、Web 工具与完整默认工具清单仍由独立的完整 `sdk` 与 `web` profile 提供。 -`Session.run()` 的活动区间从其提示词被持久 inbox 接收时开始,到整个 agent 下一次进入空闲状态时结束,并返回 `RunResult(session_id, final_response, finish_reason, events, notifications, session_root)`。`final_response` 是该区间内根会话最后提交的助手文本。`finish_reason` 是该区间内根会话最后一个 `turn/end` 的 `kind`,例如 `completed`、`max-tokens` 或 `error`;没有轮次结束时为 `None`。缺少字符串 `data.reason.kind` 的 `turn/end` 违反运行时协议,并会抛出 `SdkProtocolError`。这两个结果字段描述的是 `Session.run()` 所界定的活动区间,并不表示某项输出或结束原因在因果上归属于该提示词。steering(中途引导)、注入的上下文和其他排队工作,也可能在 agent 进入空闲状态前参与这段活动。 +## 结果与通知 -`HarnessClient` 会在运行时进程的整个生命周期内保留已发现的 subagent 谱系。每次执行 `Session.run()` 时,`RunResult.notifications` 与 `on_notification` 会按协议传输顺序收到根会话及所有已知后代的通知,其中包括嵌套 subagent 的生命周期事件与会话事件。`RunResult.events` 只包含根会话事件,因此后代消息不会覆盖根会话回复。底层 `session_prompt()` 会立即返回已排队消息的 `MessageId`;绕过 `Session.run()` 的调用方必须自行负责后续的活动边界。 +`Session.run()` 的活动区间从提示词被持久 inbox 接收时开始,到整个 agent 下一次进入 idle 时结束,并返回 `RunResult(session_id, final_response, finish_reason, events, notifications)`。`final_response` 是该区间内根会话最后提交的 assistant 文本。`finish_reason` 是最后一个根会话 `turn/end` 的 `kind`,例如 `completed`、`max-tokens` 或 `error`;没有轮次结束时为 `None`。缺少字符串 `data.reason.kind` 的 `turn/end` 违反协议,并会抛出 `SdkProtocolError`。 -也可以通过 `DSH_CORDIS_CONFIG` 为运行时子进程指定配置。注入逻辑位于 `HarnessClient.start()`,因此底层客户端按默认方式启动时也具有该行为:如果启动方式最终解析为内置运行时,且既没有设置 `cordis`,也没有设置非空的 `DSH_CORDIS_CONFIG`(运行时将空值视为未设置,注入检查也是如此),系统就会使用内置默认配置;显式指定 `runtime_bin`、`bridge_bin` 或 `launch_args_override` 时,则会完全禁用该注入。运行时载体(生产用 exe 与仅限开发的 `node` 闭包)及其获取方式见 [sdk-runtime README](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk-runtime/README.md)。 +`HarnessClient` 会在运行时进程的整个生命周期内保留已发现的子 agent 祖先关系。在 `Session.run()` 期间,`RunResult.notifications` 与 `on_notification` 按协议顺序接收根会话和已知后代的通知。`RunResult.events` 只包含根会话事件,因此后代输出不会替换根响应。底层 `session_prompt()` 会立即返回已排队消息的 id;绕过 `Session.run()` 的调用方自行负责后续活动边界。 -`cwd` 与 `runtime_cwd` 会在启动子进程、注入环境变量和协议握手前解析为绝对路径。公开 API 只暴露由 SDK 直接应用的选项:部署 persona 和持久化配置应在 `cordis.yml` 中定义;`session_root` 则保留为设置 `DSH_SESSION_ROOT` 的高层便捷参数。 +所选 home 保存 profile、插件与每个 profile 自有的持久资源。完整 `sdk` profile 使用其中的凭据、设置与会话存储;`sdk-minimal` 只使用自己的 JSONL 会话存储。需要隔离这些资源时应使用新的 home;独立工作应使用新的 session id。同时复用 harness 与 session id 会延续持久对话和会话资源。 + +另见 [Python 教程](../../docs/user/guide/python-sdk.zh.md)、[`python-sdk-agent` 示例](../../examples/python-sdk-agent/README.zh.md)和[运行时 wheel 参考](../sdk-runtime/README.zh.md)。 diff --git a/python/sdk/src/deepseek_harness/api.py b/python/sdk/src/deepseek_harness/api.py index 9c542c012a..a9a10f993c 100644 --- a/python/sdk/src/deepseek_harness/api.py +++ b/python/sdk/src/deepseek_harness/api.py @@ -24,11 +24,12 @@ class DeepSeekHarnessConfig: max_tokens: int | None = None cwd: str | None = None runtime_cwd: str | None = None - session_root: str | None = None - cordis: str | None = None + dsh_bin: str | None = None + profile: str = "sdk" + patches: tuple[str, ...] = () + dsh_home: str | None = None env: dict[str, str] = field(default_factory=dict) - runtime_bin: str | None = None - launch_args_override: tuple[str, ...] | None = None + initialize_timeout_seconds: float = 30.0 request_timeout_seconds: float | None = None shutdown_timeout_seconds: float | None = 1.0 base_url: str | None = None @@ -42,7 +43,6 @@ class RunResult: finish_reason: str | None events: list[JsonObject] notifications: list[Notification] - session_root: str | None = None class DeepSeekHarness: @@ -53,7 +53,13 @@ class DeepSeekHarness: :meth:`close` explicitly when finished, so the subprocess is always reaped. """ - def __init__(self, config: DeepSeekHarnessConfig | None = None, **kwargs: object) -> None: + def __init__( + self, + config: DeepSeekHarnessConfig | None = None, + *, + _launch_args: tuple[str, ...] | None = None, + **kwargs: object, + ) -> None: if config is not None and kwargs: raise TypeError("pass either DeepSeekHarnessConfig or keyword options, not both") self.config = config or DeepSeekHarnessConfig(**kwargs) @@ -61,11 +67,6 @@ class DeepSeekHarness: runtime_cwd = str(Path(self.config.runtime_cwd).resolve()) if self.config.runtime_cwd is not None else cwd self._cwd = cwd env = dict(self.config.env) - if self.config.session_root is not None: - env["DSH_SESSION_ROOT"] = self.config.session_root - if self.config.cordis is not None: - env["DSH_CORDIS_CONFIG"] = self.config.cordis - env["DSH_CWD"] = cwd if self.config.base_url is not None: env["DEEPSEEK_BASE_URL"] = self.config.base_url if self.config.api_key is not None: @@ -73,13 +74,17 @@ class DeepSeekHarness: self._client = HarnessClient( HarnessConfig( - runtime_bin=self.config.runtime_bin, - launch_args_override=self.config.launch_args_override, + dsh_bin=self.config.dsh_bin, + profile=self.config.profile, + patches=self.config.patches, + dsh_home=self.config.dsh_home, cwd=runtime_cwd, env=env, + initialize_timeout_seconds=self.config.initialize_timeout_seconds, request_timeout_seconds=self.config.request_timeout_seconds, shutdown_timeout_seconds=self.config.shutdown_timeout_seconds, - ) + ), + _launch_args=_launch_args, ) self._initialized = False @@ -179,7 +184,6 @@ class Session: finish_reason=finish_reason(events), events=events, notifications=notifications, - session_root=self.harness.config.session_root, ) diff --git a/python/sdk/src/deepseek_harness/client.py b/python/sdk/src/deepseek_harness/client.py index 5442c7e144..804076636d 100644 --- a/python/sdk/src/deepseek_harness/client.py +++ b/python/sdk/src/deepseek_harness/client.py @@ -25,20 +25,29 @@ NotificationFilter: TypeAlias = Callable[[Notification], bool] class HarnessConfig: """Configuration for launching the local DeepSeek Harness SDK runtime.""" - runtime_bin: str | None = None - bridge_bin: str | None = None - launch_args_override: tuple[str, ...] | None = None + dsh_bin: str | None = None + profile: str = "sdk" + patches: tuple[str, ...] = () + dsh_home: str | None = None cwd: str | None = None env: dict[str, str] | None = None + initialize_timeout_seconds: float = 30.0 request_timeout_seconds: float | None = None shutdown_timeout_seconds: float | None = 1.0 + _launch_args: tuple[str, ...] | None = None class HarnessClient: """Synchronous JSON-RPC client for the DeepSeek Harness SDK runtime over stdio.""" - def __init__(self, config: HarnessConfig | None = None) -> None: + def __init__( + self, + config: HarnessConfig | None = None, + *, + _launch_args: tuple[str, ...] | None = None, + ) -> None: self.config = config or HarnessConfig() + self._launch_args = _launch_args or self.config._launch_args self._proc: subprocess.Popen[str] | None = None self._lock = threading.Lock() self._write_lock = threading.Lock() @@ -65,11 +74,10 @@ class HarnessClient: return with self._lock: self._session_parents.clear() - args = list(self.config.launch_args_override or self._default_launch_args()) env = os.environ.copy() if self.config.env: env.update(self.config.env) - self._inject_bundled_default_config(env) + args = list(self._launch_args or self._default_launch_args(env)) self._proc = subprocess.Popen( args, stdin=subprocess.PIPE, @@ -85,11 +93,14 @@ class HarnessClient: self._start_stderr_thread() def close(self) -> None: + """Close the runtime after a bounded opportunity to flush durable state.""" proc = self._proc if proc is None: return + shutdown_completed = False try: self.request("shutdown", None, response_model=_ShutdownResponse, timeout_seconds=self.config.shutdown_timeout_seconds) + shutdown_completed = True except Exception as exc: self._stderr_lines.append(f"shutdown request failed: {exc}") if proc.stdin: @@ -97,16 +108,22 @@ class HarnessClient: proc.stdin.close() except Exception as exc: self._stderr_lines.append(f"stdin close failed: {exc}") + if shutdown_completed: + try: + proc.wait(timeout=self.config.shutdown_timeout_seconds) + except subprocess.TimeoutExpired: + pass if proc.poll() is None: try: proc.terminate() except ProcessLookupError: pass - try: - proc.wait(timeout=self.config.shutdown_timeout_seconds) - except subprocess.TimeoutExpired: - proc.kill() - proc.wait() + if proc.poll() is None: + try: + proc.wait(timeout=self.config.shutdown_timeout_seconds) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() self._proc = None self._fail_waiters(self._runtime_closed_error("DeepSeek Harness runtime closed")) if self._reader_thread and self._reader_thread.is_alive(): @@ -130,9 +147,24 @@ class HarnessClient: if max_tokens is not None: payload["maxTokens"] = max_tokens try: - return self.request("initialize", payload, response_model=InitializeResponse) - except BaseException: + return self.request( + "initialize", + payload, + response_model=InitializeResponse, + timeout_seconds=self.config.initialize_timeout_seconds, + ) + except TimeoutError as error: self.close() + raise TimeoutError(f"{error}\nselected dsh profile {self.config.profile!r}") from error + except BaseException as error: + self.close() + diagnostics = self._runtime_diagnostics() + if isinstance(error, JsonRpcError) and diagnostics: + raise JsonRpcError( + error.code, + f"{error.message}\n{diagnostics}", + error.data, + ) from error raise def session_prompt( @@ -421,37 +453,35 @@ class HarnessClient: parts.append("stderr tail:\n" + "\n".join(self._stderr_lines)) return "\n".join(parts) - def _default_launch_args(self) -> tuple[str, ...]: - if self.config.runtime_bin is not None: - return (self.config.runtime_bin,) - if self.config.bridge_bin is not None: - return (self.config.bridge_bin,) - try: - from deepseek_harness_runtime import resolve_bundled_launch_args - except ImportError as exc: - raise FileNotFoundError( - "Unable to locate the bundled DeepSeek Harness SDK runtime. " - "Install deepseek-harness-runtime-bin or set HarnessConfig.runtime_bin." - ) from exc - return resolve_bundled_launch_args() + def _default_launch_args(self, env: dict[str, str]) -> tuple[str, ...]: + if self.config.dsh_bin is None: + try: + from deepseek_harness_runtime import resolve_bundled_launch_args + except ImportError as exc: + raise FileNotFoundError( + "Unable to locate the bundled DeepSeek Harness dsh runtime. " + "Install deepseek-harness-runtime-bin." + ) from exc + base = resolve_bundled_launch_args() + else: + base = (str(Path(self.config.dsh_bin).expanduser().resolve()),) - def _inject_bundled_default_config(self, env: dict[str, str]) -> None: - """Inject the default config for a bundled launch with no non-empty config. + if self.config.dsh_home is not None: + if not self.config.dsh_home.strip(): + raise ValueError("HarnessConfig requires a non-empty dsh_home") + env["DSH_HOME"] = str(Path(self.config.dsh_home).expanduser().resolve()) + elif not env.get("DSH_HOME", "").strip(): + raise ValueError( + "HarnessConfig requires an explicit dsh_home or non-empty DSH_HOME; " + "the Python SDK never uses ~/.dsh implicitly" + ) - Both bundled carriers require an explicit config. Explicit runtime, - launch-argument, and config channels remain untouched. - """ - uses_bundled_runtime = ( - self.config.launch_args_override is None - and self.config.runtime_bin is None - and self.config.bridge_bin is None + patches = tuple( + argument + for patch in self.config.patches + for argument in ("--patch", str(Path(patch).expanduser().resolve())) ) - if not uses_bundled_runtime or env.get("DSH_CORDIS_CONFIG"): - return - # _default_launch_args already imported the package or raised its install error. - from deepseek_harness_runtime import bundled_default_config_path - - env["DSH_CORDIS_CONFIG"] = str(bundled_default_config_path()) + return (*base, "--profile", self.config.profile, *patches) def _unsubscribe_notifications(self, subscription_id: str) -> None: with self._lock: diff --git a/python/sdk/tests/manual_sdk_agent_smoke.py b/python/sdk/tests/manual_sdk_agent_smoke.py index c0305d9211..acadb495be 100644 --- a/python/sdk/tests/manual_sdk_agent_smoke.py +++ b/python/sdk/tests/manual_sdk_agent_smoke.py @@ -1,4 +1,4 @@ -"""Drive the repo-source JSON-RPC bin through the SDK and a keyless mock SSE server. +"""Drive the repo-source dsh SDK profile through the SDK and a keyless mock SSE server. Requires ``pnpm install`` but no build. This manual test is not collected by pytest; run ``python tests/manual_sdk_agent_smoke.py``. @@ -16,7 +16,6 @@ from pathlib import Path from typing import Any from deepseek_harness import DeepSeekHarness -from deepseek_harness_runtime import bundled_default_config_path class MockCompletionHandler(BaseHTTPRequestHandler): @@ -43,15 +42,16 @@ class MockCompletionHandler(BaseHTTPRequestHandler): def run_smoke(repo_root: Path, keep_sessions: bool) -> None: - session_root = Path(tempfile.mkdtemp(prefix="dsh-sdk-smoke-sessions-")) - runtime_entry = repo_root / "packages/sdk/python-runtime/src/packaged-bin.ts" + dsh_home = Path(tempfile.mkdtemp(prefix="dsh-sdk-smoke-home-")) + session_root = dsh_home / "sessions" + runtime_entry = repo_root / "apps/cli/src/bin.ts" server = ThreadingHTTPServer(("127.0.0.1", 0), MockCompletionHandler) thread = threading.Thread(target=server.serve_forever, name="mock-openai-compatible-server", daemon=True) thread.start() base_url = f"http://127.0.0.1:{server.server_address[1]}" print(f"repo_root={repo_root}") - print(f"session_root={session_root}") + print(f"dsh_home={dsh_home}") print(f"mock_base_url={base_url}") try: @@ -59,10 +59,18 @@ def run_smoke(repo_root: Path, keep_sessions: bool) -> None: model="sdk-smoke-model", cwd=str(repo_root / "python/sdk"), runtime_cwd=str(repo_root), - session_root=str(session_root), - cordis=str(bundled_default_config_path()), - launch_args_override=("node", "--import", "tsx", str(runtime_entry)), + _launch_args=( + "node", + "--import", + "tsx", + str(runtime_entry), + "--profile", + "sdk", + ), env={ + "DSH_HOME": str(dsh_home), + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", "DEEPSEEK_BASE_URL": base_url, "DEEPSEEK_API_KEY": "sdk-smoke-key", }, @@ -92,10 +100,10 @@ def run_smoke(repo_root: Path, keep_sessions: bool) -> None: server.server_close() if keep_sessions: - print(f"kept_session_root={session_root}") + print(f"kept_dsh_home={dsh_home}") else: - shutil.rmtree(session_root) - print("removed temporary session root") + shutil.rmtree(dsh_home) + print("removed temporary dsh home") def main() -> None: diff --git a/python/sdk/tests/test_bundled_runtime.py b/python/sdk/tests/test_bundled_runtime.py index 52d84cd161..3da5247795 100644 --- a/python/sdk/tests/test_bundled_runtime.py +++ b/python/sdk/tests/test_bundled_runtime.py @@ -1,4 +1,4 @@ -"""Keyless boot tests for the production exe and development node carrier. +"""Keyless boot tests for the production exe and development dsh carrier. Each carrier skips independently when absent. The dummy API key only satisfies adapter loading; initialize and shutdown do not call a model. @@ -6,64 +6,39 @@ adapter loading; initialize and shutdown do not call a model. from __future__ import annotations +import json from pathlib import Path import pytest from deepseek_harness import DeepSeekHarness, HarnessClient, HarnessConfig -from deepseek_harness.errors import TransportClosedError -from deepseek_harness_runtime import resolve_bundled_launch_args +from deepseek_harness.errors import JsonRpcError, TransportClosedError +from deepseek_harness_runtime import RUNTIME_MODE_ENV_VAR, resolve_bundled_launch_args _MODES = ("exe", "node") -_REPO_ROOT = Path(__file__).parents[3] -_MINIMAL_CONFIG = _REPO_ROOT / "examples" / "python-sdk-agent" / "minimal.cordis.yml" - -# The config must include the JSON-RPC serving plugin. -_CORDIS_YML = """\ -- id: sdk-jsonrpc-server - name: '@deepseek-ai/dsh-sdk-jsonrpc-server' -- id: agent-core - name: '@deepseek-ai/dsh-agent-spine-demo' - config: - workspaceContext: false -- id: sessions - name: '@deepseek-ai/dsh-session-persistence-jsonl' - config: - root: './sessions' -- id: session-checkpoints - name: '@deepseek-ai/dsh-session-checkpoint-policy' -- id: subprocess - name: '@deepseek-ai/dsh-subprocess-local' -- id: bash - name: '@deepseek-ai/dsh-bash-local' - config: - cwd: '.' -- id: todo - name: '@deepseek-ai/dsh-tool-todo' - config: - allowParallelInProgress: true -""" -def _launch_args(mode: str) -> tuple[str, ...]: +def _select_mode(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: try: - return resolve_bundled_launch_args(mode) + resolve_bundled_launch_args(mode) except FileNotFoundError as exc: pytest.skip(f"bundled {mode}-mode runtime unavailable on this machine: {exc}") + monkeypatch.setenv(RUNTIME_MODE_ENV_VAR, mode) -def _client(tmp_path: Path, launch_args: tuple[str, ...]) -> HarnessClient: +def _client(tmp_path: Path, mode: str, monkeypatch: pytest.MonkeyPatch, *patches: Path) -> HarnessClient: + _select_mode(mode, monkeypatch) return HarnessClient( HarnessConfig( - launch_args_override=launch_args, + dsh_home=str(tmp_path / "home"), + patches=tuple(str(patch) for patch in patches), cwd=str(tmp_path), env={ - "DSH_CORDIS_CONFIG": "./cordis.yml", - "DSH_SESSION_ROOT": str(tmp_path / "sessions"), - "DSH_CWD": str(tmp_path), # The lazily mounted adapter requires a key even without a model call. "DEEPSEEK_API_KEY": "sk-dummy-for-boot", "DEEPSEEK_BASE_URL": "http://127.0.0.1:9", + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", }, request_timeout_seconds=120, ) @@ -71,34 +46,39 @@ def _client(tmp_path: Path, launch_args: tuple[str, ...]) -> HarnessClient: @pytest.mark.parametrize("mode", _MODES) -def test_bundled_runtime_boots_a_cordis_config(tmp_path: Path, mode: str) -> None: - launch_args = _launch_args(mode) - (tmp_path / "cordis.yml").write_text(_CORDIS_YML) - - with _client(tmp_path, launch_args) as client: +def test_bundled_runtime_boots_the_sdk_profile( + tmp_path: Path, mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + with _client(tmp_path, mode, monkeypatch) as client: init = client.initialize(provider="deepseek-official", cwd=str(tmp_path), model="deepseek-v4-pro") assert init.serverInfo is not None assert init.serverInfo.name == "deepseek-harness-sdk-runtime" + profile = json.loads((tmp_path / "home" / "profiles" / "sdk" / "package.json").read_text()) + assert profile["dsh"]["profile"]["bundles"] == [ + "@deepseek-ai/dsh-base", + "@deepseek-ai/dsh-sdk-app", + ] @pytest.mark.parametrize("mode", _MODES) -def test_python_sdk_boots_minimal_jsonrpc_config(tmp_path: Path, mode: str) -> None: - launch_args = _launch_args(mode) - model = "minimal-environment-model" +def test_python_sdk_applies_an_ordered_profile_patch( + tmp_path: Path, mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + _select_mode(mode, monkeypatch) + patch = tmp_path / "persona.patch.yml" + patch.write_text(json.dumps([{ + "id": "system-prompt", + "config": {"persona": "Python SDK ordered patch marker."}, + }])) harness = DeepSeekHarness( - model=model, + model="deepseek-v4-pro", cwd=str(tmp_path), - session_root=str(tmp_path / "sessions"), - cordis=str(_MINIMAL_CONFIG), - env={ - "DSH_MODEL": model, - "DSH_CONTEXT_WINDOW": "1000000", - "DSH_SYSTEM_PROMPT": "You are the Python SDK minimal boot test agent.", - }, + dsh_home=str(tmp_path / "home"), + patches=(str(patch),), + env={"DSH_PERMISSION_MODE": "danger-full-access"}, api_key="sk-dummy-for-boot", base_url="http://127.0.0.1:9", - launch_args_override=launch_args, request_timeout_seconds=120, ) @@ -107,42 +87,20 @@ def test_python_sdk_boots_minimal_jsonrpc_config(tmp_path: Path, mode: str) -> N @pytest.mark.parametrize("mode", _MODES) -def test_bundled_runtime_surfaces_unbundled_plugin_failure(tmp_path: Path, mode: str) -> None: - launch_args = _launch_args(mode) - (tmp_path / "cordis.yml").write_text( - "- id: missing\n name: '@deepseek-ai/dsh-does-not-exist'\n" - ) +def test_bundled_runtime_surfaces_unbundled_plugin_failure( + tmp_path: Path, mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + patch = tmp_path / "missing.patch.yml" + patch.write_text(json.dumps([{ + "insert": [{"id": "missing", "name": "@deepseek-ai/dsh-does-not-exist"}], + }])) - client = _client(tmp_path, launch_args) + client = _client(tmp_path, mode, monkeypatch, patch) client.start() try: - with pytest.raises((TransportClosedError, TimeoutError)) as excinfo: + with pytest.raises((JsonRpcError, TransportClosedError, TimeoutError)) as excinfo: client.initialize(provider="deepseek-official", cwd=str(tmp_path), model="deepseek-v4-pro") finally: client.close() assert "@deepseek-ai/dsh-does-not-exist" in str(excinfo.value) - - -@pytest.mark.parametrize("mode", _MODES) -@pytest.mark.parametrize("ambient_config", [None, ""], ids=["unset", "empty-counts-as-absent"]) -def test_zero_config_run_injects_bundled_default_cordis_config( - tmp_path: Path, mode: str, ambient_config: str | None, monkeypatch: pytest.MonkeyPatch -) -> None: - _launch_args(mode) # skip early when this carrier is unavailable - monkeypatch.setenv("DSH_RUNTIME_MODE", mode) - if ambient_config is None: - monkeypatch.delenv("DSH_CORDIS_CONFIG", raising=False) - else: - monkeypatch.setenv("DSH_CORDIS_CONFIG", ambient_config) - - harness = DeepSeekHarness( - model="deepseek-v4-pro", - cwd=str(tmp_path), - session_root=str(tmp_path / "sessions"), - api_key="sk-dummy-for-boot", - base_url="http://127.0.0.1:9", - request_timeout_seconds=120, - ) - with harness: - pass diff --git a/python/sdk/tests/test_client.py b/python/sdk/tests/test_client.py index 51c9dacb31..d5ed7dada8 100644 --- a/python/sdk/tests/test_client.py +++ b/python/sdk/tests/test_client.py @@ -9,7 +9,8 @@ from pathlib import Path import pytest -from deepseek_harness import DeepSeekHarness, HarnessClient, HarnessConfig, Notification, SdkProtocolError +from deepseek_harness import DeepSeekHarness, HarnessClient, HarnessConfig, Notification, RunResult, SdkProtocolError +from deepseek_harness.errors import JsonRpcError def test_high_level_sdk_runs_turn_and_collects_final_response(tmp_path: Path) -> None: @@ -95,9 +96,7 @@ for line in sys.stdin: model="deepseek-v4-flash", max_tokens=4096, cwd=str(tmp_path), - cordis=str(tmp_path / "cordis.yml"), - session_root=str(tmp_path / "sessions"), - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), env={ "ENV_DUMP": str(env_dump), "INIT_DUMP": str(init_dump), @@ -113,9 +112,9 @@ for line in sys.stdin: dumped_env = json.loads(env_dump.read_text()) assert dumped_env["DEEPSEEK_API_KEY"] == "env-key" assert dumped_env["DEEPSEEK_BASE_URL"] == "http://127.0.0.1:4321" - assert dumped_env["DSH_CWD"] == str(tmp_path) - assert dumped_env["DSH_SESSION_ROOT"] == str(tmp_path / "sessions") - assert dumped_env["DSH_CORDIS_CONFIG"] == str(tmp_path / "cordis.yml") + assert dumped_env["DSH_CWD"] is None + assert dumped_env["DSH_SESSION_ROOT"] is None + assert dumped_env["DSH_CORDIS_CONFIG"] is None assert json.loads(init_dump.read_text()) == { "cwd": str(tmp_path), "provider": "deepseek-official", @@ -150,7 +149,7 @@ for line in sys.stdin: seen: list[str] = [] with DeepSeekHarness( - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), cwd=str(tmp_path), ) as harness: session = harness.start_session("main") @@ -188,7 +187,7 @@ for line in sys.stdin: ) with DeepSeekHarness( - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), cwd=str(tmp_path), ) as harness: with pytest.raises( @@ -224,7 +223,7 @@ for line in sys.stdin: with DeepSeekHarness( cwd=".", runtime_cwd=".", - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), env={"CAPTURE": str(capture)}, ): pass @@ -232,7 +231,7 @@ for line in sys.stdin: expected = str(tmp_path.resolve()) assert json.loads(capture.read_text()) == { "process": expected, - "environment": expected, + "environment": None, "wire": expected, } @@ -263,7 +262,7 @@ for line in sys.stdin: ) with DeepSeekHarness( - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), cwd=str(tmp_path), ) as harness: result = harness.run("spawn a helper", session_id="main") @@ -312,7 +311,7 @@ for line in sys.stdin: seen: list[str] = [] with DeepSeekHarness( - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), cwd=str(tmp_path), ) as harness: result = harness.run( @@ -367,7 +366,7 @@ for line in sys.stdin: ) with DeepSeekHarness( - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), cwd=str(tmp_path), ) as harness: result = harness.run("stay in your lane", session_id="main") @@ -401,7 +400,7 @@ for line in sys.stdin: """.strip() ) - with DeepSeekHarness(launch_args_override=(sys.executable, str(script)), cwd=str(tmp_path)) as harness: + with DeepSeekHarness(_launch_args=(sys.executable, str(script)), cwd=str(tmp_path)) as harness: result = harness.run("one turn", session_id="main") assert harness.client._notifications.qsize() == 0 @@ -441,7 +440,7 @@ for line in sys.stdin: """.strip() ) - with DeepSeekHarness(launch_args_override=(sys.executable, str(script)), cwd=str(tmp_path)) as harness: + with DeepSeekHarness(_launch_args=(sys.executable, str(script)), cwd=str(tmp_path)) as harness: first = harness.run("first turn", session_id="main") second = harness.run("second turn", session_id="main") @@ -473,7 +472,7 @@ for line in sys.stdin: ) with HarnessClient( - HarnessConfig(launch_args_override=(sys.executable, str(script))) + HarnessConfig(_launch_args=(sys.executable, str(script))) ) as client: init = client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent") assert init.serverInfo.name == "fake-dsh" @@ -612,7 +611,7 @@ for line in sys.stdin: def broken_filter(_notification: object) -> bool: raise RuntimeError("bad notification filter") - with HarnessClient(HarnessConfig(launch_args_override=(sys.executable, str(script)))) as client: + with HarnessClient(HarnessConfig(_launch_args=(sys.executable, str(script)))) as client: client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent") with ( client.subscribe_notifications(broken_filter) as broken, @@ -649,7 +648,7 @@ for line in sys.stdin: """.strip() ) - with HarnessClient(HarnessConfig(launch_args_override=(sys.executable, str(script)))) as client: + with HarnessClient(HarnessConfig(_launch_args=(sys.executable, str(script)))) as client: client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent") with pytest.raises(ValueError): client.session_prompt("main", [{"type": "text", "text": "fix it"}]) @@ -677,7 +676,7 @@ for line in sys.stdin: ) with HarnessClient( - HarnessConfig(launch_args_override=(sys.executable, str(script))) + HarnessConfig(_launch_args=(sys.executable, str(script))) ) as client: client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent") @@ -711,7 +710,7 @@ for line in sys.stdin: ) with HarnessClient( - HarnessConfig(launch_args_override=(sys.executable, str(script))) + HarnessConfig(_launch_args=(sys.executable, str(script))) ) as client: init = client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent") assert init.serverInfo.name == "fake-dsh" @@ -731,8 +730,9 @@ time.sleep(60) with HarnessClient( HarnessConfig( - launch_args_override=(sys.executable, str(script)), - request_timeout_seconds=0.1, + _launch_args=(sys.executable, str(script)), + profile="web", + initialize_timeout_seconds=0.1, ) ) as client: start = time.monotonic() @@ -741,6 +741,7 @@ time.sleep(60) except TimeoutError as exc: assert time.monotonic() - start < 2 assert "bridge is still starting" in str(exc) + assert "profile 'web'" in str(exc) else: raise AssertionError("initialize should time out") @@ -767,7 +768,7 @@ for line in sys.stdin: client = HarnessClient( HarnessConfig( - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), shutdown_timeout_seconds=0.1, ) ) @@ -782,6 +783,43 @@ for line in sys.stdin: assert client._proc is None +def test_client_close_allows_eof_quiescence_after_shutdown_response(tmp_path: Path) -> None: + script = tmp_path / "fake_runtime.py" + marker = tmp_path / "quiesced.txt" + script.write_text( + """ +import json +import os +from pathlib import Path +import sys +import time + +for line in sys.stdin: + msg = json.loads(line) + if msg.get("method") == "initialize": + print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True) + elif msg.get("method") == "shutdown": + print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True) + +time.sleep(0.05) +Path(os.environ["QUIESCED_MARKER"]).write_text("quiesced") +""".strip() + ) + + client = HarnessClient( + HarnessConfig( + _launch_args=(sys.executable, str(script)), + env={"QUIESCED_MARKER": str(marker)}, + shutdown_timeout_seconds=1, + ) + ) + client.start() + client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent") + client.close() + + assert marker.read_text() == "quiesced" + + def test_initialize_failure_reaps_started_runtime(tmp_path: Path) -> None: script = tmp_path / "rejecting_runtime.py" script.write_text( @@ -792,6 +830,7 @@ import sys for line in sys.stdin: msg = json.loads(line) if msg.get("method") == "initialize": + print("initialize diagnostic", file=sys.stderr, flush=True) print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32000, "message": "bad initialize"}}), flush=True) elif msg.get("method") == "shutdown": print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True) @@ -799,14 +838,16 @@ for line in sys.stdin: """.strip() ) - client = HarnessClient(HarnessConfig(launch_args_override=(sys.executable, str(script)))) + client = HarnessClient(HarnessConfig(_launch_args=(sys.executable, str(script)))) client.start() proc = client._proc assert proc is not None - with pytest.raises(Exception, match="bad initialize"): + with pytest.raises(JsonRpcError, match="bad initialize") as excinfo: client.initialize(provider="deepseek-official", cwd=".", model="dsagent") + assert excinfo.value.code == -32000 + assert "initialize diagnostic" in str(excinfo.value) assert proc.wait(timeout=1) is not None assert client._proc is None @@ -824,6 +865,20 @@ def test_public_signatures_omit_unsupported_wire_parameters() -> None: assert "max_tokens" in inspect.signature(HarnessClient.initialize).parameters assert "client_name" not in HarnessConfig.__dataclass_fields__ assert "client_version" not in HarnessConfig.__dataclass_fields__ + assert {"dsh_bin", "profile", "patches", "dsh_home"} <= set( + DeepSeekHarnessConfig.__dataclass_fields__ + ) + assert {"dsh_bin", "profile", "patches", "dsh_home"} <= set( + HarnessConfig.__dataclass_fields__ + ) + assert "initialize_timeout_seconds" in DeepSeekHarnessConfig.__dataclass_fields__ + assert "initialize_timeout_seconds" in HarnessConfig.__dataclass_fields__ + assert DeepSeekHarnessConfig().initialize_timeout_seconds == 30.0 + assert HarnessConfig().initialize_timeout_seconds == 30.0 + for removed in ("cordis", "session_root", "runtime_bin", "bridge_bin", "launch_args_override"): + assert removed not in DeepSeekHarnessConfig.__dataclass_fields__ + assert removed not in HarnessConfig.__dataclass_fields__ + assert "session_root" not in RunResult.__dataclass_fields__ def test_client_close_is_idempotent_before_and_after_start(tmp_path: Path) -> None: @@ -845,7 +900,7 @@ for line in sys.stdin: """.strip() ) - client = HarnessClient(HarnessConfig(launch_args_override=(sys.executable, str(script)))) + client = HarnessClient(HarnessConfig(_launch_args=(sys.executable, str(script)))) client.start() client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent") client.close() @@ -865,7 +920,7 @@ sys.exit(42) with HarnessClient( HarnessConfig( - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), request_timeout_seconds=2, ) ) as client: @@ -897,7 +952,7 @@ with open(os.environ["SEEN"], "w") as seen: with HarnessClient( HarnessConfig( - launch_args_override=(sys.executable, str(script)), + _launch_args=(sys.executable, str(script)), env={"SEEN": str(output)}, ) ) as client: @@ -915,21 +970,22 @@ with open(os.environ["SEEN"], "w") as seen: json.loads(line) -def _install_fake_bundled_runtime( +def _install_fake_bundled_dsh( tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> Path: - """Install a fake runtime package that records config and serves lifecycle calls. - - Returns the fake bundled default config path. - """ - runtime = tmp_path / "dsh-jsonrpc-agent" +) -> None: + """Install a fake runtime package that records dsh argv and serves lifecycle calls.""" + runtime = tmp_path / "dsh.py" runtime.write_text( - """#!/usr/bin/env python3 + """ import json import os import sys -json.dump({"DSH_CORDIS_CONFIG": os.environ.get("DSH_CORDIS_CONFIG")}, open(os.environ["ENV_DUMP"], "w")) +json.dump({ + "argv": sys.argv[1:], + "DSH_HOME": os.environ.get("DSH_HOME"), + "DSH_CORDIS_CONFIG": os.environ.get("DSH_CORDIS_CONFIG"), +}, open(os.environ["ENV_DUMP"], "w")) for line in sys.stdin: msg = json.loads(line) if msg.get("method") == "initialize": @@ -939,58 +995,75 @@ for line in sys.stdin: break """.strip() ) - runtime.chmod(0o755) - default_config = tmp_path / "default-cordis.yml" module_dir = tmp_path / "deepseek_harness_runtime" module_dir.mkdir() (module_dir / "__init__.py").write_text( f""" def resolve_bundled_launch_args(mode=None): - return ({str(runtime)!r},) - - -def bundled_default_config_path(): - return {str(default_config)!r} + return ({sys.executable!r}, {str(runtime)!r}) """.strip() ) monkeypatch.syspath_prepend(str(tmp_path)) monkeypatch.delitem(sys.modules, "deepseek_harness_runtime", raising=False) - return default_config -@pytest.mark.parametrize("ambient_config", [None, ""], ids=["unset", "empty-counts-as-absent"]) -def test_client_default_launch_uses_bundled_runtime_and_injects_default_config( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ambient_config: str | None -) -> None: - env_dump = tmp_path / "env.json" - default_config = _install_fake_bundled_runtime(tmp_path, monkeypatch) - if ambient_config is None: - monkeypatch.delenv("DSH_CORDIS_CONFIG", raising=False) - else: - monkeypatch.setenv("DSH_CORDIS_CONFIG", ambient_config) - - with HarnessClient(HarnessConfig(env={"ENV_DUMP": str(env_dump)})) as client: - init = client.initialize(provider="deepseek-official", cwd="/workspace", model="deepseek-v4-pro") - - assert init.serverInfo.name == "bundled-runtime" - assert json.loads(env_dump.read_text())["DSH_CORDIS_CONFIG"] == str(default_config) - - -def test_client_respects_explicit_config_over_bundled_default( +def test_client_default_launch_uses_bundled_dsh_sdk_profile_and_explicit_home( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: env_dump = tmp_path / "env.json" - _install_fake_bundled_runtime(tmp_path, monkeypatch) + home = tmp_path / "home" + patch = tmp_path / "sdk.patch.yml" + patch.write_text("[]\n") + _install_fake_bundled_dsh(tmp_path, monkeypatch) + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("DSH_HOME", str(tmp_path / "ambient-home")) monkeypatch.delenv("DSH_CORDIS_CONFIG", raising=False) + with HarnessClient(HarnessConfig( + profile="sdk", + patches=("sdk.patch.yml",), + dsh_home=str(home), + env={"ENV_DUMP": str(env_dump), "DSH_HOME": str(tmp_path / "env-home")}, + )) as client: + init = client.initialize(provider="deepseek-official", cwd="/workspace", model="deepseek-v4-pro") + + assert init.serverInfo.name == "bundled-runtime" + assert json.loads(env_dump.read_text()) == { + "argv": ["--profile", "sdk", "--patch", str(patch)], + "DSH_HOME": str(home), + "DSH_CORDIS_CONFIG": None, + } + + +def test_client_accepts_explicit_environment_dsh_home( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + env_dump = tmp_path / "env.json" + home = tmp_path / "environment-home" + _install_fake_bundled_dsh(tmp_path, monkeypatch) + with HarnessClient( - HarnessConfig(env={"ENV_DUMP": str(env_dump), "DSH_CORDIS_CONFIG": "./explicit.yml"}) + HarnessConfig(profile="custom", env={"ENV_DUMP": str(env_dump), "DSH_HOME": str(home)}) ) as client: client.initialize(provider="deepseek-official", cwd="/workspace", model="deepseek-v4-pro") - assert json.loads(env_dump.read_text())["DSH_CORDIS_CONFIG"] == "./explicit.yml" + assert json.loads(env_dump.read_text()) == { + "argv": ["--profile", "custom"], + "DSH_HOME": str(home), + "DSH_CORDIS_CONFIG": None, + } + + +def test_client_rejects_an_implicit_default_dsh_home( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _install_fake_bundled_dsh(tmp_path, monkeypatch) + monkeypatch.delenv("DSH_HOME", raising=False) + + with pytest.raises(ValueError, match="explicit dsh_home or non-empty DSH_HOME"): + HarnessClient(HarnessConfig(env={})).start() def test_client_reports_missing_bundled_runtime_dependency(monkeypatch: pytest.MonkeyPatch) -> None: @@ -998,4 +1071,4 @@ def test_client_reports_missing_bundled_runtime_dependency(monkeypatch: pytest.M monkeypatch.setattr(sys, "path", []) with pytest.raises(FileNotFoundError, match="Install deepseek-harness-runtime-bin"): - HarnessClient().start() + HarnessClient(HarnessConfig(dsh_home="/explicit/home")).start() diff --git a/python/sdk/tests/test_release_version.py b/python/sdk/tests/test_release_version.py index b21a485949..37d2a01734 100644 --- a/python/sdk/tests/test_release_version.py +++ b/python/sdk/tests/test_release_version.py @@ -59,6 +59,15 @@ def test_pep440_version_spells_a_prerelease_the_python_way() -> None: def test_macos_wheel_tag_does_not_claim_unsupported_node_platforms() -> None: assert build_python_release.PLATFORMS["macos-arm64"][0] == "macosx_14_0_arm64" + assert build_python_release.PLATFORMS["macos-arm64"][1] == "deepseek-harness-sdk-runtime-macos-arm64" + + +def test_windows_wheel_tag_and_payload_are_x64_only() -> None: + assert build_python_release.PLATFORMS["win-x64"] == ( + "win_amd64", + "deepseek-harness-sdk-runtime-win-x64.exe", + ) + assert not any(name.startswith("win-") and name != "win-x64" for name in build_python_release.PLATFORMS) def test_platform_manifest_rejects_incomplete_entries(tmp_path: Path) -> None: @@ -84,15 +93,22 @@ def test_stage_sdk_keeps_distribution_module_and_runtime_pin_distinct(tmp_path: assert (destination / "src" / "deepseek_harness" / "__init__.py").is_file() -@pytest.mark.parametrize(("target", "with_helper"), [("linux-x64", False), ("macos-arm64", True)]) +@pytest.mark.parametrize( + ("target", "with_helper"), + [("linux-x64", False), ("macos-arm64", True), ("win-x64.exe", False)], +) def test_stage_runtime_copies_platform_payload( tmp_path: Path, target: str, with_helper: bool ) -> None: - executable = tmp_path / f"dsh-jsonrpc-agent-pkg-{target}" + executable = tmp_path / f"deepseek-harness-sdk-runtime-{target}" executable.write_bytes(b"runtime") executable.chmod(0o755) expected = {executable.name: b"runtime"} - ripgrep = Path(f"{executable}-rg") + ripgrep = ( + executable.with_name(f"{executable.stem}-rg.exe") + if executable.suffix == ".exe" + else Path(f"{executable}-rg") + ) ripgrep.write_bytes(b"ripgrep") ripgrep.chmod(0o755) expected[ripgrep.name] = b"ripgrep" @@ -106,10 +122,14 @@ def test_stage_runtime_copies_platform_payload( build_python_release.stage_runtime(destination, "1.2.3", executable, executable.name) runtime_dir = destination / "src" / "deepseek_harness_runtime" / "runtime" - assert {path.name: path.read_bytes() for path in runtime_dir.glob("dsh-jsonrpc-agent-pkg-*")} == expected + assert { + path.name: path.read_bytes() + for path in runtime_dir.glob("deepseek-harness-sdk-runtime-*") + } == expected pyproject = (destination / "pyproject.toml").read_text() assert 'license = "MIT"' in pyproject assert 'license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]' in pyproject + assert 'dsh = "deepseek_harness_runtime:main"' in pyproject assert (destination / "platforms.json").read_bytes() == ( ROOT / "python" / "sdk-runtime" / "platforms.json" ).read_bytes() @@ -117,3 +137,16 @@ def test_stage_runtime_copies_platform_payload( assert (destination / "THIRD_PARTY_NOTICES.md").read_bytes() == ( ROOT / "THIRD_PARTY_NOTICES.md" ).read_bytes() + + +def test_stage_runtime_rejects_a_noncanonical_executable_name(tmp_path: Path) -> None: + executable = tmp_path / "renamed.exe" + executable.write_bytes(b"runtime") + + with pytest.raises(ValueError, match="must be named deepseek-harness-sdk-runtime-win-x64.exe"): + build_python_release.stage_runtime( + tmp_path / "staging", + "1.2.3", + executable, + "deepseek-harness-sdk-runtime-win-x64.exe", + ) diff --git a/python/sdk/tests/test_runtime_resolution.py b/python/sdk/tests/test_runtime_resolution.py index 14e90f3283..0f06deb28e 100644 --- a/python/sdk/tests/test_runtime_resolution.py +++ b/python/sdk/tests/test_runtime_resolution.py @@ -9,21 +9,12 @@ import pytest from deepseek_harness_runtime import ( RUNTIME_MODE_ENV_VAR, - bundled_default_config_path, bundled_package_dir, + main, resolve_bundled_launch_args, ) -def test_default_config_is_shipped_with_the_package() -> None: - path = bundled_default_config_path() - assert path == bundled_package_dir() / "runtime" / "cordis.yml" - config = path.read_text() - assert "@deepseek-ai/dsh-agent-spine-demo" in config - assert "@deepseek-ai/dsh-session-persistence-jsonl" in config - assert "@deepseek-ai/dsh-session-checkpoint-policy" in config - - def test_unknown_explicit_mode_fails_loud() -> None: with pytest.raises(ValueError, match="expected 'exe' or 'node'"): resolve_bundled_launch_args("bogus") @@ -49,10 +40,10 @@ def test_runtime_requires_spawn_helper_only_on_macos( ) -> None: runtime_dir = tmp_path / "runtime" runtime_dir.mkdir() - linux = runtime_dir / "dsh-jsonrpc-agent-pkg-linux-x64" + linux = runtime_dir / "deepseek-harness-sdk-runtime-linux-x64" linux.touch() Path(f"{linux}-rg").touch() - macos = runtime_dir / "dsh-jsonrpc-agent-pkg-macos-arm64" + macos = runtime_dir / "deepseek-harness-sdk-runtime-macos-arm64" macos.touch() Path(f"{macos}-rg").touch() monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path) @@ -64,14 +55,92 @@ def test_runtime_requires_spawn_helper_only_on_macos( assert runtime.bundled_runtime_path() == linux +def test_windows_runtime_uses_exe_payload_and_exe_sidecar( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + runtime_dir = tmp_path / "runtime" + runtime_dir.mkdir() + executable = runtime_dir / "deepseek-harness-sdk-runtime-win-x64.exe" + executable.touch() + (runtime_dir / "deepseek-harness-sdk-runtime-win-x64-rg.exe").touch() + monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path) + monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "win-x64") + + assert runtime.bundled_runtime_path() == executable + + +def test_current_platform_supports_windows_x64_only(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(runtime.sys, "platform", "win32") + monkeypatch.setattr(runtime.platform, "machine", lambda: "AMD64") + assert runtime._current_platform_tag() == "win-x64" + + monkeypatch.setattr(runtime.platform, "machine", lambda: "ARM64") + with pytest.raises(FileNotFoundError, match="Windows x64"): + runtime._current_platform_tag() + + +def test_current_platform_rejects_macos_x64(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(runtime.sys, "platform", "darwin") + monkeypatch.setattr(runtime.platform, "machine", lambda: "x86_64") + + with pytest.raises(FileNotFoundError, match="macOS arm64"): + runtime._current_platform_tag() + + def test_runtime_requires_ripgrep_sidecar( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: runtime_dir = tmp_path / "runtime" runtime_dir.mkdir() - (runtime_dir / "dsh-jsonrpc-agent-pkg-linux-x64").touch() + (runtime_dir / "deepseek-harness-sdk-runtime-linux-x64").touch() monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path) monkeypatch.setattr(runtime, "_current_platform_tag", lambda: "linux-x64") with pytest.raises(FileNotFoundError, match="ripgrep sidecar"): runtime.bundled_runtime_path() + + +def test_node_mode_runs_the_deployed_dsh_cli( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + bin_js = tmp_path / "runtime" / "node" / "node_modules" / "@deepseek-ai" / "dsh" / "lib" / "bin.js" + bin_js.parent.mkdir(parents=True) + bin_js.touch() + monkeypatch.setattr(runtime, "bundled_package_dir", lambda: tmp_path) + monkeypatch.setattr(runtime.shutil, "which", lambda _name: "/node") + + assert resolve_bundled_launch_args("node") == ("/node", str(bin_js)) + + +def test_python_dsh_command_requires_explicit_home( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.delenv("DSH_HOME", raising=False) + + with pytest.raises(SystemExit) as excinfo: + main() + + assert excinfo.value.code == 2 + assert "explicit DSH_HOME" in capsys.readouterr().err + + +def test_python_dsh_command_executes_the_bundled_cli( + monkeypatch: pytest.MonkeyPatch +) -> None: + called: dict[str, object] = {} + monkeypatch.setenv("DSH_HOME", "/explicit/home") + monkeypatch.setattr(runtime, "resolve_bundled_launch_args", lambda: ("/runtime",)) + monkeypatch.setattr(runtime.sys, "argv", ["dsh", "plugin", "--profile", "sdk", "list"]) + + def execvpe(file: str, args: tuple[str, ...], env: dict[str, str]) -> None: + called.update(file=file, args=args, home=env.get("DSH_HOME")) + + monkeypatch.setattr(runtime.os, "execvpe", execvpe) + + main() + + assert called == { + "file": "/runtime", + "args": ("/runtime", "plugin", "--profile", "sdk", "list"), + "home": "/explicit/home", + } diff --git a/scripts/build-exe-for-python-sdk-assets.spec.ts b/scripts/build-exe-for-python-sdk-assets.spec.ts new file mode 100644 index 0000000000..27167c5307 --- /dev/null +++ b/scripts/build-exe-for-python-sdk-assets.spec.ts @@ -0,0 +1,27 @@ +import { spawnSync } from 'node:child_process' +import { resolve } from 'node:path' +import { describe, expect, it } from 'vitest' + +const root = resolve(import.meta.dirname, '..') +const script = resolve(root, 'scripts/build-exe-for-python-sdk.ts') + +describe('Python runtime executable assets', () => { + it('packages the dynamically resolved web frontend distribution', () => { + const result = spawnSync(process.execPath, [ + '--import', + 'tsx/esm', + script, + '--skip-build', + '--dry-run', + '--targets=node24-macos-arm64', + ], { + cwd: root, + encoding: 'utf8', + env: { ...process.env, npm_execpath: 'C:\\tools\\pnpm.cjs' }, + }) + + expect(result.status).toBe(0) + expect(result.stdout).toContain('node_modules/@deepseek-ai/dsh-web-frontend/dist/**/*') + expect(result.stdout).toContain('node_modules/@deepseek-ai/dsh-skill-badge/assets/**/*') + }) +}) diff --git a/scripts/build-exe-for-python-sdk-native-pty.spec.ts b/scripts/build-exe-for-python-sdk-native-pty.spec.ts index 5dd6588955..cc7d0ef7fa 100644 --- a/scripts/build-exe-for-python-sdk-native-pty.spec.ts +++ b/scripts/build-exe-for-python-sdk-native-pty.spec.ts @@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { resolveLinuxNodePtyAddon } from './build-exe-for-python-sdk-native-pty.ts' +import { resolveLinuxNodePtyAddon, resolveWindowsNodePtyAddons } from './build-exe-for-python-sdk-native-pty.ts' const roots: string[] = [] @@ -35,6 +35,24 @@ describe('resolveLinuxNodePtyAddon', () => { }) }) +describe('resolveWindowsNodePtyAddons', () => { + it('requires both ConPTY addons from the x64 prebuild', () => { + const root = temporaryPackage() + const conpty = createAddon(root, 'prebuilds', 'win32-x64', 'conpty.node') + const consoleList = createAddon(root, 'prebuilds', 'win32-x64', 'conpty_console_list.node') + + expect(resolveWindowsNodePtyAddons(root, 'x64')).toEqual([conpty, consoleList]) + }) + + it('names every missing Windows addon', () => { + const root = temporaryPackage() + + expect(() => resolveWindowsNodePtyAddons(root, 'x64')).toThrow( + `Windows node-pty addons are missing: ${join(root, 'prebuilds', 'win32-x64', 'conpty.node')}, ${join(root, 'prebuilds', 'win32-x64', 'conpty_console_list.node')}`, + ) + }) +}) + function temporaryPackage(): string { const root = mkdtempSync(join(tmpdir(), 'dsh-node-pty-addon-')) roots.push(root) diff --git a/scripts/build-exe-for-python-sdk-native-pty.ts b/scripts/build-exe-for-python-sdk-native-pty.ts index 02fa864d73..3ce5295d5c 100644 --- a/scripts/build-exe-for-python-sdk-native-pty.ts +++ b/scripts/build-exe-for-python-sdk-native-pty.ts @@ -21,3 +21,25 @@ export function resolveLinuxNodePtyAddon( `build-exe-for-python-sdk: node-pty addon is absent from both ${built} and ${prebuilt}.`, ) } + +/** + * Require both node-pty addons used by the Windows ConPTY backend. + * @param packageDirectory - staged node-pty package directory. + * @param arch - Windows target architecture. + * @returns the existing addon paths in load order. + */ +export function resolveWindowsNodePtyAddons( + packageDirectory: string, + arch: 'x64', +): string[] { + const directory = join(packageDirectory, 'prebuilds', `win32-${arch}`) + const addons = [ + join(directory, 'conpty.node'), + join(directory, 'conpty_console_list.node'), + ] + const missing = addons.filter(path => !existsSync(path)) + if (missing.length > 0) { + throw new Error(`build-exe-for-python-sdk: Windows node-pty addons are missing: ${missing.join(', ')}.`) + } + return addons +} diff --git a/scripts/build-exe-for-python-sdk.spec.ts b/scripts/build-exe-for-python-sdk.spec.ts new file mode 100644 index 0000000000..c3fe4a15a6 --- /dev/null +++ b/scripts/build-exe-for-python-sdk.spec.ts @@ -0,0 +1,81 @@ +import { spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' + +const root = resolve(import.meta.dirname, '..') +const script = resolve(root, 'scripts/build-exe-for-python-sdk.ts') +const temporaryDirectories: string[] = [] + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } +}) + +function run(env: NodeJS.ProcessEnv, ...args: string[]) { + return spawnSync(process.execPath, ['--import', 'tsx/esm', script, ...args], { + cwd: root, + encoding: 'utf8', + env: isolatedPnpmEnvironment(env), + }) +} + +describe('Python runtime executable builder CLI', () => { + it('runs pnpm through its JavaScript entrypoint without a command shell', () => { + const result = run( + { npm_execpath: 'C:\\tools\\pnpm.cjs' }, + '--skip-build', + '--dry-run', + '--targets=node24-macos-arm64', + ) + + expect(result.status).toBe(0) + expect(result.stdout).toContain(`${process.execPath} C:\\tools\\pnpm.cjs run verify-runtime-closure`) + expect(result.stdout).toContain(`${process.execPath} C:\\tools\\pnpm.cjs --filter dsh-python-runtime-closure deploy`) + expect(result.stdout).toContain(`${process.execPath} C:\\tools\\pnpm.cjs dlx @yao-pkg/pkg@6.21.0`) + expect(result.stdout).not.toMatch(/pnpm\.cmd/i) + }) + + it('resolves the pnpm package behind a Windows command shim', () => { + const setup = mkdtempSync(join(tmpdir(), 'dsh-pnpm-home-')) + temporaryDirectories.push(setup) + const home = join(setup, 'node_modules', '.bin') + const entrypoint = join(setup, 'node_modules', 'pnpm', 'bin', 'pnpm.mjs') + mkdirSync(home, { recursive: true }) + mkdirSync(dirname(entrypoint), { recursive: true }) + writeFileSync(entrypoint, '') + + const result = run( + { npm_execpath: 'C:\\tools\\pnpm.cmd', PNPM_HOME: home }, + '--skip-build', + '--dry-run', + '--targets=node24-macos-arm64', + ) + + expect(result.status).toBe(0) + expect(result.stdout).toContain(`${process.execPath} ${entrypoint} run verify-runtime-closure`) + expect(result.stdout).not.toMatch(/pnpm\.cmd/i) + }) + + it('rejects a Windows arm64 product before any build step', () => { + const result = run( + { npm_execpath: 'C:\\tools\\pnpm.cjs' }, + '--skip-build', + '--dry-run', + '--targets=node24-win-arm64', + ) + + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('Windows supports x64 only') + expect(result.stdout).toBe('') + }) +}) + +function isolatedPnpmEnvironment(overrides: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const environment = Object.fromEntries( + Object.entries(process.env).filter(([key]) => !['npm_execpath', 'pnpm_home'].includes(key.toLowerCase())), + ) + return { ...environment, ...overrides } +} diff --git a/scripts/build-exe-for-python-sdk.ts b/scripts/build-exe-for-python-sdk.ts index 7516fcabb6..c7c8cfed66 100644 --- a/scripts/build-exe-for-python-sdk.ts +++ b/scripts/build-exe-for-python-sdk.ts @@ -1,5 +1,5 @@ /** - * Build the SDK runtime executables and Python node carrier. The fixed + * Build the dsh executables and development Node carrier for the Python runtime wheel. The fixed * `@yao-pkg/pkg --sea` route, deploy flags, and artifact layout are owned by * .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md. * The staged closure is symlink-free, and whole-tree assets cover Cordis's @@ -9,18 +9,18 @@ import { spawn } from 'node:child_process' import { existsSync, statSync } from 'node:fs' import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises' -import { basename, dirname, join, resolve, sep } from 'node:path' +import { basename, dirname, extname, join, resolve, sep } from 'node:path' import { parseArgs } from 'node:util' -import { resolveLinuxNodePtyAddon } from './build-exe-for-python-sdk-native-pty.ts' +import { resolveLinuxNodePtyAddon, resolveWindowsNodePtyAddons } from './build-exe-for-python-sdk-native-pty.ts' const root = resolve(import.meta.dirname, '..') /** The closure manifest whose dependencies define the executable. */ -const DEPLOY_ROOT_PACKAGE = 'dsh-sdk-python-runtime-closure' -/** The closed-runtime app entry inside the deployed closure. */ -const ENTRY_BIN = 'node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js' -/** Stable Python-visible executable basename; rename with the later Python runtime migration. */ -const OUTPUT_BASENAME = 'dsh-jsonrpc-agent-pkg' +const DEPLOY_ROOT_PACKAGE = 'dsh-python-runtime-closure' +/** The sole application launcher inside the deployed closure. */ +const ENTRY_BIN = 'node_modules/@deepseek-ai/dsh/lib/bin.js' +/** Python-visible executable basename. */ +const OUTPUT_BASENAME = 'deepseek-harness-sdk-runtime' /** Default Node major; SEA mode requires at least Node 22. */ const DEFAULT_NODE_RANGE = 'node24' /** Pinned for reproducible builds. */ @@ -47,11 +47,23 @@ const ASSET_GLOBS = [ 'node_modules/**/*.mjs', 'node_modules/**/package.json', 'node_modules/**/*.json', + // Package-owned Markdown includes runtime skill instructions and badge content. + 'node_modules/**/*.md', + 'node_modules/**/*.dylib', + 'node_modules/**/*.dll', 'node_modules/**/*.node', + 'node_modules/**/*.so', + 'node_modules/**/*.so.*', 'node_modules/**/*.wasm', + 'node_modules/**/*.yaml', + 'node_modules/**/*.yml', + // web-app builds this path dynamically, so pkg cannot discover the static frontend. + 'node_modules/@deepseek-ai/dsh-web-frontend/dist/**/*', + // skill-badge resolves both Markdown and image resources through import.meta.url. + 'node_modules/@deepseek-ai/dsh-skill-badge/assets/**/*', ] -const PLATFORMS = ['linux', 'macos'] as const +const PLATFORMS = ['linux', 'macos', 'win'] as const const ARCHES = ['x64', 'arm64'] as const type Platform = (typeof PLATFORMS)[number] type Arch = (typeof ARCHES)[number] @@ -71,10 +83,7 @@ class Target { private constructor( /** pkg Node range (`node`). */ readonly nodeRange: string, - /** - * pkg platform tag. Windows is a documented non-goal - * (.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md). - */ + /** pkg platform tag. */ readonly platform: Platform, /** pkg CPU tag. */ readonly arch: Arch, @@ -105,6 +114,9 @@ class Target { if (!isArch(arch)) { throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: arch must be one of ${ARCHES.join(', ')}, got ${JSON.stringify(arch)}.`) } + if (platform === 'win' && arch !== 'x64') { + throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: Windows supports x64 only.`) + } return new Target(nodeRange, platform, arch) } @@ -113,7 +125,13 @@ class Target { * @returns the host target; throws on an unsupported host platform or arch. */ static host(): Target { - const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : undefined + const platform = process.platform === 'darwin' + ? 'macos' + : process.platform === 'linux' + ? 'linux' + : process.platform === 'win32' + ? 'win' + : undefined if (platform === undefined) { throw new Error(`build-exe-for-python-sdk: unsupported host platform ${process.platform}; pass --targets explicitly.`) } @@ -121,6 +139,9 @@ class Target { if (arch === undefined) { throw new Error(`build-exe-for-python-sdk: unsupported host arch ${process.arch}; pass --targets explicitly.`) } + if (platform === 'win' && arch !== 'x64') { + throw new Error('build-exe-for-python-sdk: Windows supports x64 only; use an x64 Node process.') + } return new Target(DEFAULT_NODE_RANGE, platform, arch) } } @@ -188,7 +209,7 @@ class BuildCli { return [ 'Usage: pnpm exec tsx scripts/build-exe-for-python-sdk.ts [flags]', '', - ' --targets= pkg targets, e.g. node24-linux-x64,node24-linux-arm64,node24-macos-arm64.', + ' --targets= pkg targets, e.g. node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-win-x64.', ' Default: the host platform only (on node24).', ' --skip-build skip `pnpm run build` (lib/ artifacts must already exist).', ' --dry-run print every command and config patch without executing.', @@ -200,8 +221,27 @@ class BuildCli { } } -function pnpmBin(): string { - return process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm' +function pnpmInvocation(args: string[]): [command: string, args: string[]] { + const entrypoint = process.env.npm_execpath?.trim() + if (entrypoint !== undefined && entrypoint !== '') { + const extension = extname(entrypoint).toLowerCase() + if (extension === '.js' || extension === '.cjs' || extension === '.mjs') { + return [process.execPath, [entrypoint, ...args]] + } + if (extension !== '.cmd') return [entrypoint, args] + } + const home = process.env.PNPM_HOME?.trim() + if (home !== undefined && home !== '') { + const packageBin = resolve(home, '..', 'pnpm', 'bin') + for (const filename of ['pnpm.mjs', 'pnpm.cjs']) { + const candidate = resolve(packageBin, filename) + if (existsSync(candidate)) return [process.execPath, [candidate, ...args]] + } + } + if (process.platform === 'win32') { + throw new Error('build-exe-for-python-sdk: pnpm must expose a JavaScript entrypoint through npm_execpath or PNPM_HOME on Windows.') + } + return ['pnpm', args] } /** @@ -220,8 +260,7 @@ function formatCommand(command: string, args: string[]): string { */ class SingleExeBuild { /** - * The cleared deploy target, pkg input, and Python node-mode carrier. The - * checked-in default `cordis.yml` remains in its parent directory. + * The cleared deploy target, pkg input, and Python node-mode carrier. */ readonly staging = resolve(root, PYTHON_RUNTIME_DIR, PYTHON_NODE_SUBDIR) private readonly outDir = resolve(root, OUT_DIR) @@ -230,7 +269,7 @@ class SingleExeBuild { /** Verify the closure before compiling or packaging. */ async verifyClosure(): Promise { - await this.run('runtime dependency closure', pnpmBin(), ['run', 'verify-runtime-closure']) + await this.runPnpm('runtime dependency closure', ['run', 'verify-runtime-closure']) } /** Build all package artifacts unless `--skip-build` was passed. */ @@ -239,7 +278,7 @@ class SingleExeBuild { console.log('build-exe-for-python-sdk: skipping pnpm run build (--skip-build)') return } - await this.run('build', pnpmBin(), ['run', 'build']) + await this.runPnpm('build', ['run', 'build']) } /** Clear and deploy the runtime closure into the node carrier. */ @@ -249,7 +288,7 @@ class SingleExeBuild { } if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${this.staging}`) else await rm(this.staging, { recursive: true, force: true }) - await this.run('deploy', pnpmBin(), [ + await this.runPnpm('deploy', [ '--filter', DEPLOY_ROOT_PACKAGE, 'deploy', @@ -382,10 +421,11 @@ class SingleExeBuild { * @returns the executable and ripgrep sidecar paths, plus the macOS spawn helper path when required. */ async pack(target: Target): Promise { - const product = join(this.outDir, `${OUTPUT_BASENAME}-${target.platform}-${target.arch}`) + const productBase = join(this.outDir, `${OUTPUT_BASENAME}-${target.platform}-${target.arch}`) + const product = target.platform === 'win' ? `${productBase}.exe` : productBase await this.prepareNativePty(target) if (!this.cli.dryRun) await mkdir(this.outDir, { recursive: true }) - await this.run(`pkg ${target.spec}`, pnpmBin(), [ + await this.runPnpm(`pkg ${target.spec}`, [ 'dlx', PKG_SPEC, this.staging, @@ -413,16 +453,19 @@ class SingleExeBuild { /** Copy the target ripgrep binary beside the executable so Node can spawn it outside pkg's virtual filesystem. */ private async copyRipgrepSidecar(target: Target, product: string): Promise { - const platform = target.platform === 'macos' ? 'darwin' : target.platform + const platform = target.platform === 'macos' ? 'darwin' : target.platform === 'win' ? 'win32' : target.platform + const executable = target.platform === 'win' ? 'rg.exe' : 'rg' const source = join( this.staging, 'node_modules', '@vscode', `ripgrep-${platform}-${target.arch}`, 'bin', - 'rg', + executable, ) - const destination = `${product}-rg` + const destination = target.platform === 'win' + ? `${product.slice(0, -'.exe'.length)}-rg.exe` + : `${product}-rg` if (this.cli.dryRun) { console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${destination}`) return destination @@ -444,7 +487,6 @@ class SingleExeBuild { const stagedBuild = join(this.staging, 'node_modules', 'node-pty', 'build') if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${stagedBuild}`) else await rm(stagedBuild, { recursive: true, force: true }) - if (target.platform !== 'linux') return const packageDirectory = join( root, 'packages', @@ -453,6 +495,21 @@ class SingleExeBuild { 'node_modules', 'node-pty', ) + if (target.platform === 'win') { + if (target.arch !== 'x64') { + throw new Error('build-exe-for-python-sdk: Windows supports x64 only.') + } + const host = Target.host() + if (target.platform !== host.platform || target.arch !== host.arch) { + throw new Error( + 'build-exe-for-python-sdk: build the Windows runtime under x64 Node on its target host; ' + + `target ${target.platform}-${target.arch} does not match host ${host.platform}-${host.arch}.`, + ) + } + resolveWindowsNodePtyAddons(join(this.staging, 'node_modules', 'node-pty'), target.arch) + return + } + if (target.platform !== 'linux') return const destination = join(stagedBuild, 'Release', 'pty.node') const source = resolveLinuxNodePtyAddon(packageDirectory, target.arch) if (this.cli.dryRun) { @@ -542,6 +599,12 @@ class SingleExeBuild { }) }) } + + /** Run pnpm through its JavaScript entrypoint when the caller supplies one. */ + private async runPnpm(label: string, args: string[]): Promise { + const [command, invocationArgs] = pnpmInvocation(args) + await this.run(label, command, invocationArgs) + } } async function main(): Promise { diff --git a/scripts/build-python-release.py b/scripts/build-python-release.py index 0b4157f40d..085974f921 100644 --- a/scripts/build-python-release.py +++ b/scripts/build-python-release.py @@ -47,9 +47,12 @@ def load_platforms(path: Path = PLATFORM_MANIFEST) -> dict[str, tuple[str, str]] PLATFORMS = load_platforms() -def runtime_suffixes(executable_name: str) -> tuple[str, ...]: - suffixes = ("", "-rg") - return (*suffixes, "-spawn-helper") if "-macos-" in executable_name else suffixes +def runtime_filenames(executable_name: str) -> tuple[str, ...]: + """Return the exact platform payload names for one runtime executable.""" + if executable_name.endswith(".exe"): + return (executable_name, f"{executable_name.removesuffix('.exe')}-rg.exe") + names = (executable_name, f"{executable_name}-rg") + return (*names, f"{executable_name}-spawn-helper") if "-macos-" in executable_name else names def main() -> None: @@ -150,7 +153,7 @@ def copy_package(source: Path, destination: Path) -> None: "*.pyc", "dist", "node_modules", - "dsh-jsonrpc-agent-pkg-*", + "deepseek-harness-sdk-runtime-*", ), ) @@ -205,13 +208,18 @@ def stage_sdk(destination: Path, version: str) -> None: def stage_runtime(destination: Path, version: str, executable: Path, executable_name: str) -> None: + if executable.name != executable_name: + raise ValueError( + f"runtime executable must be named {executable_name}, got {executable.name}" + ) copy_package(ROOT / "python" / "sdk-runtime", destination) stage_license_files(destination, include_notices=True) rewrite_version(destination / "pyproject.toml", version) runtime_dir = destination / "src" / "deepseek_harness_runtime" / "runtime" runtime_dir.mkdir(parents=True, exist_ok=True) - for suffix in runtime_suffixes(executable_name): - shutil.copy2(Path(f"{executable}{suffix}"), runtime_dir / f"{executable_name}{suffix}") + source_directory = executable.parent + for filename in runtime_filenames(executable_name): + shutil.copy2(source_directory / filename, runtime_dir / filename) def verify_wheel( @@ -246,17 +254,17 @@ def verify_wheel( f"{wheel} has license files {license_files}, expected {expected_license_files}" ) runtime_files = [ - name for name in archive.namelist() if "/runtime/dsh-jsonrpc-agent-pkg-" in name + name for name in archive.namelist() if "/runtime/deepseek-harness-sdk-runtime-" in name ] if package == "runtime": assert platform is not None - expected_files = [f"{platform[1]}{suffix}" for suffix in runtime_suffixes(platform[1])] + expected_files = sorted(runtime_filenames(platform[1])) found_files = sorted(Path(name).name for name in runtime_files) if found_files != expected_files: raise RuntimeError(f"{wheel} runtime payload must be {expected_files}, found {found_files}") for runtime_file in runtime_files: mode = archive.getinfo(runtime_file).external_attr >> 16 - if mode & stat.S_IXUSR == 0: + if platform[0] != "win_amd64" and mode & stat.S_IXUSR == 0: raise RuntimeError(f"{wheel} runtime executable lost its executable bit: {runtime_file}") elif runtime_files: raise RuntimeError(f"SDK wheel unexpectedly contains runtime executables: {runtime_files}") diff --git a/scripts/build.ts b/scripts/build.ts index b8ffa8dbc0..6d6bcb259f 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -6,8 +6,9 @@ import { resolve } from 'node:path' import { parseArgs } from 'node:util' import { CLIENT_BUILD_RECORD_PATH, + CLIENT_BUILD_PROFILE_SELECTOR, clientBuildProcessEnvironment, - repositoryCommitHash, + repositoryClientBuildEnvironment, resolveClientBuildEnvironment, writeClientBuildRecord, } from './client-build-environment.ts' @@ -34,12 +35,10 @@ function main(): void { allowPositionals: false, }) const root = resolve(import.meta.dirname, '..') - const parentEnvironment = { - ...process.env, - DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, process.env), - } - const clientEnvironment = resolveClientBuildEnvironment(parentEnvironment, values.profile) - const buildEnvironment = clientBuildProcessEnvironment(parentEnvironment, clientEnvironment) + const repositoryEnvironment = repositoryClientBuildEnvironment(root, process.env) + const profile = values.profile ?? process.env[CLIENT_BUILD_PROFILE_SELECTOR] + const clientEnvironment = resolveClientBuildEnvironment(repositoryEnvironment, profile) + const buildEnvironment = clientBuildProcessEnvironment(process.env, clientEnvironment) rmSync(resolve(root, CLIENT_BUILD_RECORD_PATH), { force: true }) runScript('build:lib', buildEnvironment) diff --git a/scripts/check-workspace-constraints.spec.ts b/scripts/check-workspace-constraints.spec.ts index 4bd39ac878..dc3b63227f 100644 --- a/scripts/check-workspace-constraints.spec.ts +++ b/scripts/check-workspace-constraints.spec.ts @@ -1,12 +1,9 @@ /** Experimental-package publication and dependency constraints. */ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { checkExperimentalDependencyIsolation, checkExperimentalManifest, - checkWorkspaceManifest, type WorkspaceManifest, } from './check-workspace-constraints.ts' @@ -77,24 +74,3 @@ describe('experimental workspace constraints', () => { ]) }) }) - -describe('private Python runtime carrier', () => { - const manifest = JSON.parse( - readFileSync(new URL('../packages/sdk/python-runtime/package.json', import.meta.url), 'utf8'), - ) as WorkspaceManifest['manifest'] - - it('participates in dsh package checks without becoming an npm release member', () => { - expect(checkWorkspaceManifest({ dir: 'packages/sdk/python-runtime', manifest })).toEqual([]) - }) - - it('rejects publication metadata on the private carrier', () => { - const path = join('packages', 'sdk', 'python-runtime', 'package.json') - expect(checkWorkspaceManifest({ - dir: 'packages/sdk/python-runtime', - manifest: { ...manifest, private: false, publishConfig: { access: 'public' } }, - })).toEqual([ - `${path}: @deepseek-ai/dsh-sdk-python-runtime: private carrier must set "private": true`, - `${path}: @deepseek-ai/dsh-sdk-python-runtime: private carrier must omit publishConfig`, - ]) - }) -}) diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index 842e0ca3a7..cd9620e0fa 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -54,9 +54,6 @@ const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/ const experimentalPackageNamePrefix = '@deepseek-ai/dsh-experimental-' /** Directories whose packages this repository publishes: one release member each. */ const releaseMemberDirectory = /^(?:packages\/(?!experimental\/)[^/]+\/[^/]+|apps\/[^/]+|vendor\/[^/]+)$/ -/** Named dsh packages that remain private because another distribution embeds them. */ -const privateCarrierDirectories = new Set(['packages/sdk/python-runtime']) - const localArtifactDirs = new Set(['node_modules']) const appPackageFiles: Readonly> = { '@deepseek-ai/dsh': ['lib/*.js'], @@ -156,8 +153,9 @@ const packageFileExtras: Readonly> = { '@deepseek-ai/dsh-code-runtime-python': ['py/**/*.py'], // The shipped preset compositions travel inside the roster package. '@deepseek-ai/dsh-agent-presets': ['presets'], - // The private Python carrier ships only its closed-resolution entry. - '@deepseek-ai/dsh-sdk-python-runtime': ['lib/packaged-bin.js'], + // The Web Host mounts the default-off settings owner independently of each + // Agent-scoped delegation-tool instance. + '@deepseek-ai/dsh-tool-subagent': ['lib/model-selection-settings.js'], // The argv-prefix runner entry ships beside the lib as its own bundle; // sandbox-local resolves it through the package's ./runner export. tsdown // also shares its generated FFI code through a hashed runtime chunk. @@ -292,13 +290,6 @@ export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): st || manifest.repository.directory !== expectedDirectory) { errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`) } - } else if (privateCarrierDirectories.has(dir)) { - if (manifest.private !== true) { - errors.push(`${label}: private carrier must set "private": true`) - } - if (manifest.publishConfig !== undefined) { - errors.push(`${label}: private carrier must omit publishConfig`) - } } else if (releaseMemberDirectory.test(dir)) { // Release members state that they are publishable: npm refuses a private // package, and the repository field is how a consumer finds the source of diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index 116bb84e3c..7f60d75352 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -36,7 +36,7 @@ describe('CI workflow', () => { } }) - it('keeps required Wine and native Windows jobs with failover, plus a master-only standby', () => { + it('keeps a required Wine Windows job, a non-blocking native Windows job with failover, and a master-only standby', () => { const workflow = loadWorkflow('.github/workflows/ci.yml') const masterWorkflow = loadWorkflow('.github/workflows/ci-master.yml') if (!isRecord(workflow.jobs) @@ -73,7 +73,7 @@ describe('CI workflow', () => { expect(windows.if).toBe("github.event_name == 'pull_request'") expect(commandSteps.some(step => step.run.includes('wine-windows-gates.sh'))).toBe(true) - // windows-native: blocking native job with failover, runs windows-complete. + // windows-native: non-blocking native job with failover, runs windows-complete. // Its pool is resolved by the Windows-specific switch. expect(typeof windowsNative['runs-on']).toBe('string') expect(windowsNative['runs-on']).toContain('DSH_CI_FAILOVER_WINDOWS') @@ -84,10 +84,7 @@ describe('CI workflow', () => { expect(windowsNative.name).toBe('windows node 24 / native complete') expect(windowsNative.if).toBe("github.event_name == 'pull_request'") expect(windowsNative.env).toMatchObject({ - DSH_COVERAGE_MAX_WORKERS: '12', - DSH_COVERAGE_PARTITIONS: '16', DSH_COVERAGE_TEST_TIMEOUT_MS: '30000', - DSH_GATE_CONCURRENCY: '8', }) const nativeSteps = windowsNative.steps as unknown[] const nativeCommandSteps = nativeSteps.filter((step): step is Record & { run: string } => ( @@ -104,9 +101,9 @@ describe('CI workflow', () => { expect(serialWindows['runs-on']).toEqual(['self-hosted', 'dsh-win-ci', 'windows']) expect(serialWindows.name).toBe('serial / windows (self-hosted standby)') - // Aggregate: both complementary Windows jobs are required. + // Aggregate: Wine `windows` required, native `windows-native` excluded. expect(aggregate.needs).toContain('windows') - expect(aggregate.needs).toContain('windows-native') + expect(aggregate.needs).not.toContain('windows-native') expect(aggregate.needs).not.toContain('serial-windows') // Linux failover is a separate switch: the three required Linux workers @@ -231,7 +228,7 @@ describe('CI workflow', () => { name: 'python runtime / release-shaped matrix', uses: './.github/workflows/build-exe-for-python-sdk.yml', with: { - targets: 'node24-linux-x64,node24-linux-arm64,node24-macos-arm64', + targets: 'node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-win-x64', ci: true, }, secrets: { @@ -323,7 +320,7 @@ describe('Python release workflows', () => { expect(build).toMatchObject({ uses: './.github/workflows/build-exe-for-python-sdk.yml', with: { - targets: 'node24-linux-x64,node24-linux-arm64,node24-macos-arm64', + targets: 'node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-win-x64', release: true, }, }) @@ -393,11 +390,19 @@ describe('Python release workflows', () => { const manylinuxAddon = buildSteps.find(step => isRecord(step) && step.name === 'Rebuild Linux node-pty against manylinux 2.28') const macosCheck = buildSteps.find(step => isRecord(step) && step.name === 'Check macOS deployment target') const manylinuxSmoke = buildSteps.find(step => isRecord(step) && step.name === 'Run wheel in a manylinux 2.28 container') - const installedKeyless = buildSteps.find(step => isRecord(step) && step.name === 'Run installed-wheel keyless black-box tests') - const realApiPreflight = buildSteps.find(step => isRecord(step) && step.name === 'Preflight installed-wheel real API test') - const installedRealApi = buildSteps.find(step => isRecord(step) && step.name === 'Run installed-wheel real API black-box test') - if (!isRecord(installedKeyless) || !isRecord(realApiPreflight) || !isRecord(installedRealApi)) { - throw new TypeError('Python wheel builder must define installed-wheel keyless and real API steps') + const cleanVenvPosix = buildSteps.find(step => isRecord(step) && step.name === 'Install local SDK and runtime wheels into a clean venv (POSIX)') + const cleanVenvWindows = buildSteps.find(step => isRecord(step) && step.name === 'Install local SDK and runtime wheels into a clean venv (Windows)') + const installedKeylessPosix = buildSteps.find(step => isRecord(step) && step.name === 'Run installed-wheel keyless black-box tests (POSIX)') + const installedKeylessWindows = buildSteps.find(step => isRecord(step) && step.name === 'Run installed-wheel keyless black-box tests (Windows)') + const realApiPreflightPosix = buildSteps.find(step => isRecord(step) && step.name === 'Preflight installed-wheel real API test (POSIX)') + const realApiPreflightWindows = buildSteps.find(step => isRecord(step) && step.name === 'Preflight installed-wheel real API test (Windows)') + const installedRealApiPosix = buildSteps.find(step => isRecord(step) && step.name === 'Run installed-wheel real API black-box test (POSIX)') + const installedRealApiWindows = buildSteps.find(step => isRecord(step) && step.name === 'Run installed-wheel real API black-box test (Windows)') + if (!isRecord(cleanVenvPosix) || !isRecord(cleanVenvWindows) + || !isRecord(installedKeylessPosix) || !isRecord(installedKeylessWindows) + || !isRecord(realApiPreflightPosix) || !isRecord(realApiPreflightWindows) + || !isRecord(installedRealApiPosix) || !isRecord(installedRealApiWindows)) { + throw new TypeError('Python wheel builder must define native POSIX and Windows installed-wheel steps') } expect(call.inputs).toHaveProperty('targets') expect(call.inputs).toMatchObject({ @@ -410,47 +415,56 @@ describe('Python release workflows', () => { expect(workflow.concurrency).toMatchObject({ group: 'build-single-exe-${{ github.workflow }}-${{ github.ref }}', }) + expect(build.defaults).toBeUndefined() expect(plan.if).toContain('inputs.ci') expect(plan.if).toContain('inputs.release') expect(JSON.stringify(plan.steps)).toContain('pep440_version') const workflowJson = JSON.stringify(workflow) expect(workflowJson).toContain('macosx_14_0_arm64') + expect(workflowJson).toContain('win_amd64') + expect(workflowJson).toContain('node24-win-x64') + expect(workflowJson).toContain('windows-2025') expect(workflowJson).toContain('dist-python/$SDK_WHEEL') expect(workflowJson).toContain('dist-python/$RUNTIME_WHEEL') expect(workflowJson).toContain('/work/dist-python/$SDK_WHEEL') expect(workflowJson).toContain('/work/dist-python/$RUNTIME_WHEEL') expect(workflowJson).not.toContain('--find-links dist-python') expect(workflowJson).not.toContain('--find-links /work/dist-python') + expect(workflowJson).not.toContain('cygpath') expect(manylinuxAddon).toMatchObject({ if: "runner.os == 'Linux'" }) expect(JSON.stringify(manylinuxAddon)).toContain('manylinux_2_28_x86_64') expect(JSON.stringify(manylinuxAddon)).toContain('manylinux_2_28_aarch64') expect(JSON.stringify(manylinuxAddon)).toContain('npm_config_build_from_source=true pnpm run install') - expect(JSON.stringify(manylinuxAddon)).toContain('$HOME/setup-pnpm:$HOME/setup-pnpm:ro') + expect(JSON.stringify(manylinuxAddon)).toContain('pnpm_setup_root') + expect(JSON.stringify(manylinuxAddon)).toContain('$pnpm_setup_root:$pnpm_setup_root:ro') expect(JSON.stringify(manylinuxAddon)).toContain('node-pty-glibc-versions.txt') expect(JSON.stringify(manylinuxAddon)).toContain('le 2.28') expect(macosCheck).toMatchObject({ if: "runner.os == 'macOS'" }) expect(JSON.stringify(macosCheck)).toContain('scripts/check-macos-deployment-target.py') expect(JSON.stringify(macosCheck)).toContain('$EXE-spawn-helper') - expect(JSON.stringify(installedKeyless)).toContain('--scenario all') - expect(JSON.stringify(installedKeyless)).toContain('--installed-wheel') - expect(JSON.stringify(installedKeyless)).toContain('env -u PYTHONPATH') - expect(JSON.stringify(installedKeyless)).toContain('-u DSH_RUNTIME_MODE') - expect(realApiPreflight).toMatchObject({ + expect(JSON.stringify(installedKeylessPosix)).toContain('--scenario all') + expect(JSON.stringify(installedKeylessPosix)).toContain('env -u PYTHONPATH') + expect(JSON.stringify(installedKeylessWindows)).toContain('--scenario all --installed-wheel') + expect(installedKeylessWindows).toMatchObject({ if: "runner.os == 'Windows'", shell: 'pwsh' }) + expect(cleanVenvWindows).toMatchObject({ if: "runner.os == 'Windows'", shell: 'pwsh' }) + expect(JSON.stringify(cleanVenvWindows)).toContain('Scripts\\\\python.exe') + expect(realApiPreflightPosix).toMatchObject({ env: { DEEPSEEK_API_KEY: '${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}' }, }) - expect(String(realApiPreflight.if)).toContain('inputs.ci') - expect(String(realApiPreflight.if)).toContain('head.repo.fork') - expect(String(realApiPreflight.if)).toContain('dependabot[bot]') - expect(installedRealApi).toMatchObject({ + expect(String(realApiPreflightPosix.if)).toContain('inputs.ci') + expect(String(realApiPreflightPosix.if)).toContain('head.repo.fork') + expect(String(realApiPreflightPosix.if)).toContain('dependabot[bot]') + expect(realApiPreflightWindows).toMatchObject({ shell: 'pwsh' }) + expect(installedRealApiPosix).toMatchObject({ env: { DEEPSEEK_API_KEY: '${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}', DEEPSEEK_BASE_URL: 'https://api.deepseek.com', }, }) - expect(installedRealApi.if).toBe(realApiPreflight.if) - expect(JSON.stringify(installedRealApi)).toContain('--scenario sdk-live') - expect(JSON.stringify(installedRealApi)).toContain('--installed-wheel') - expect(JSON.stringify(installedRealApi)).toContain('-u DSH_RUNTIME_MODE') + expect(JSON.stringify(installedRealApiPosix)).toContain('--scenario sdk-live') + expect(JSON.stringify(installedRealApiPosix)).toContain('-u DSH_RUNTIME_MODE') + expect(installedRealApiWindows).toMatchObject({ shell: 'pwsh' }) + expect(JSON.stringify(installedRealApiWindows)).toContain('--scenario sdk-live --installed-wheel') expect(manylinuxSmoke).toMatchObject({ if: "runner.os == 'Linux'" }) expect(JSON.stringify(manylinuxSmoke)).toContain('-e DSH_TELEMETRY_DISABLED') }) @@ -472,6 +486,24 @@ describe('Python release workflows', () => { expect(macosCheck).toContain('scripts/check-macos-deployment-target.py') expect(macosCheck).toContain('"$EXE" "$EXE-spawn-helper"') }) + + it('builds and black-box tests the Windows x64 wheel in GitLab', () => { + const workflow = loadWorkflow('.gitlab-ci.yml') + const windows = workflow['runtime-windows-x64'] + const publish = workflow['publish-python'] + if (!isRecord(windows) || !Array.isArray(windows.before_script) || !Array.isArray(windows.script) + || !isRecord(publish) || !Array.isArray(publish.needs)) { + throw new TypeError('GitLab CI must define the Windows runtime and aggregate publication jobs') + } + + expect(windows.tags).toEqual(['windows-x64']) + expect(windows.variables).toMatchObject({ PKG_TARGET: 'node24-win-x64', PLATFORM: 'win-x64' }) + expect(JSON.stringify(windows.before_script)).toContain('.ci-python\\\\Scripts') + expect(JSON.stringify(windows.before_script)).toContain('[IO.Path]::PathSeparator') + expect(JSON.stringify(windows.script)).toContain('win_amd64.whl') + expect(JSON.stringify(windows.script)).toContain('--scenario all --installed-wheel') + expect(publish.needs).toContainEqual({ job: 'runtime-windows-x64', artifacts: true }) + }) }) describe('Issue lifecycle workflow', () => { diff --git a/scripts/client-build-environment.client.spec.ts b/scripts/client-build-environment.client.spec.ts index e2eb0ebe72..74e8086f43 100644 --- a/scripts/client-build-environment.client.spec.ts +++ b/scripts/client-build-environment.client.spec.ts @@ -1,3 +1,4 @@ +import { execFileSync } from 'node:child_process' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' @@ -7,8 +8,12 @@ import { assertClientBuildEnvironment, clientBuildEnvironmentDefines, clientBuildProcessEnvironment, + officialClientBuildEnvironment, readClientBuildRecord, + repositoryClientBuildEnvironment, repositoryCommitHash, + repositoryGitDirty, + repositoryVersion, resolveClientBuildEnvironment, writeClientBuildRecord, } from './client-build-environment.ts' @@ -51,12 +56,34 @@ function buildFixture(environment: Record): string { return fixtureRoot } +function git(root: string, args: readonly string[]): string { + return execFileSync('git', [...args], { + cwd: root, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }).trim() +} + +function repositoryFixture(version = '1.2.3-rc.4'): string { + const fixtureRoot = mkdtempSync(join(tmpdir(), 'dsh-client-build-repository-')) + roots.push(fixtureRoot) + write(join(fixtureRoot, 'package.json'), `${JSON.stringify({ version })}\n`) + write(join(fixtureRoot, 'tracked.txt'), 'committed\n') + git(fixtureRoot, ['init']) + git(fixtureRoot, ['config', 'user.name', 'DSH test']) + git(fixtureRoot, ['config', 'user.email', 'dsh-test@example.invalid']) + git(fixtureRoot, ['add', 'package.json', 'tracked.txt']) + git(fixtureRoot, ['commit', '-m', 'fixture']) + return fixtureRoot +} + describe('client build environment', () => { it('requires an exact public environment for a named artifact profile', () => { const expected = { DSH_CLIENT_BUILD_PROFILE: 'official', DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), DSH_CLIENT_TITLE: 'DeepSeek Harness', + DSH_CLIENT_VERSION: '1.2.3', } as const expect(() => { assertClientBuildEnvironment({ PATH: '/bin', ...expected }, expected) }).not.toThrow() @@ -73,7 +100,9 @@ describe('client build environment', () => { DSH_BUILD_CLIENT_PROFILE: 'official', DSH_CLIENT_BUILD_PROFILE: 'local', DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), + DSH_CLIENT_GIT_DIRTY: 'true', DSH_CLIENT_TITLE: 'Local title', + DSH_CLIENT_VERSION: '1.2.3', DSH_CLIENT_EXTRA: 'local-extra', } @@ -84,24 +113,108 @@ describe('client build environment', () => { DSH_CLIENT_BUILD_PROFILE: 'official', DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), DSH_CLIENT_TITLE: 'DeepSeek Harness', + DSH_CLIENT_VERSION: '1.2.3', }) expect(() => { resolveClientBuildEnvironment({ DSH_BUILD_CLIENT_PROFILE: 'official' }) }).toThrow(/DSH_CLIENT_COMMIT_HASH/) + expect(() => { + resolveClientBuildEnvironment({ + DSH_BUILD_CLIENT_PROFILE: 'official', + DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), + }) + }).toThrow(/DSH_CLIENT_VERSION/) expect(() => { resolveClientBuildEnvironment({}, 'unknown') }).toThrow(/unknown client build profile/) expect(clientBuildProcessEnvironment(parent, { DSH_CLIENT_BUILD_PROFILE: 'official', DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), DSH_CLIENT_TITLE: 'DeepSeek Harness', + DSH_CLIENT_VERSION: '1.2.3', })).toEqual({ PATH: '/bin', DSH_CLIENT_BUILD_PROFILE: 'official', DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), DSH_CLIENT_TITLE: 'DeepSeek Harness', + DSH_CLIENT_VERSION: '1.2.3', }) expect(repositoryCommitHash('/unused', { DSH_CLIENT_COMMIT_HASH: COMMIT_HASH })).toBe(COMMIT_HASH.slice(0, 7)) }) + it('owns repository version, commit, and dirty metadata for complete builds', () => { + const fixtureRoot = repositoryFixture() + const commit = git(fixtureRoot, ['rev-parse', '--short=7', 'HEAD']) + + expect(repositoryVersion(fixtureRoot)).toBe('1.2.3-rc.4') + expect(repositoryGitDirty(fixtureRoot)).toBe(false) + expect(repositoryClientBuildEnvironment(fixtureRoot, { + DSH_CLIENT_COMMIT_HASH: COMMIT_HASH, + DSH_CLIENT_EXTRA: 'preserved', + DSH_CLIENT_GIT_DIRTY: 'true', + DSH_CLIENT_VERSION: 'spoofed', + })).toEqual({ + DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), + DSH_CLIENT_EXTRA: 'preserved', + DSH_CLIENT_VERSION: '1.2.3-rc.4', + }) + expect(officialClientBuildEnvironment(fixtureRoot)).toEqual({ + DSH_CLIENT_BUILD_PROFILE: 'official', + DSH_CLIENT_COMMIT_HASH: commit, + DSH_CLIENT_TITLE: 'DeepSeek Harness', + DSH_CLIENT_VERSION: '1.2.3-rc.4', + }) + + write(join(fixtureRoot, '.gitignore'), 'ignored.txt\n') + git(fixtureRoot, ['add', '.gitignore']) + git(fixtureRoot, ['commit', '-m', 'ignore fixture']) + write(join(fixtureRoot, 'ignored.txt'), 'ignored\n') + expect(repositoryGitDirty(fixtureRoot)).toBe(false) + rmSync(join(fixtureRoot, 'ignored.txt')) + + write(join(fixtureRoot, 'tracked.txt'), 'unstaged\n') + expect(repositoryGitDirty(fixtureRoot)).toBe(true) + write(join(fixtureRoot, 'tracked.txt'), 'committed\n') + expect(repositoryGitDirty(fixtureRoot)).toBe(false) + + write(join(fixtureRoot, 'tracked.txt'), 'staged\n') + git(fixtureRoot, ['add', 'tracked.txt']) + expect(repositoryGitDirty(fixtureRoot)).toBe(true) + git(fixtureRoot, ['commit', '-m', 'staged fixture']) + expect(repositoryGitDirty(fixtureRoot)).toBe(false) + + write(join(fixtureRoot, 'untracked.txt'), 'untracked\n') + expect(repositoryGitDirty(fixtureRoot)).toBe(true) + expect(repositoryClientBuildEnvironment(fixtureRoot, { + DSH_CLIENT_COMMIT_HASH: COMMIT_HASH, + })).toEqual({ + DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), + DSH_CLIENT_GIT_DIRTY: 'true', + DSH_CLIENT_VERSION: '1.2.3-rc.4', + }) + + rmSync(join(fixtureRoot, 'untracked.txt')) + const submoduleSource = repositoryFixture('9.8.7') + git(fixtureRoot, ['-c', 'protocol.file.allow=always', 'submodule', 'add', submoduleSource, 'submodule']) + git(fixtureRoot, ['commit', '-am', 'submodule fixture']) + expect(repositoryGitDirty(fixtureRoot)).toBe(false) + write(join(fixtureRoot, 'submodule/tracked.txt'), 'modified submodule\n') + expect(repositoryGitDirty(fixtureRoot)).toBe(true) + }) + + it('omits dirty metadata when repository metadata is unavailable', () => { + const fixtureRoot = mkdtempSync(join(tmpdir(), 'dsh-client-build-no-git-')) + roots.push(fixtureRoot) + write(join(fixtureRoot, 'package.json'), '{"version":"2.0.0"}\n') + + expect(repositoryGitDirty(fixtureRoot)).toBeUndefined() + expect(repositoryClientBuildEnvironment(fixtureRoot, { + DSH_CLIENT_COMMIT_HASH: COMMIT_HASH, + DSH_CLIENT_GIT_DIRTY: 'true', + })).toEqual({ + DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), + DSH_CLIENT_VERSION: '2.0.0', + }) + }) + it('defines only public client values over a non-enumerable fallback', () => { expect(clientBuildEnvironmentDefines({ PATH: '/bin', @@ -151,6 +264,7 @@ describe('client build environment', () => { DSH_CLIENT_BUILD_PROFILE: 'official', DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7), DSH_CLIENT_TITLE: 'DeepSeek Harness', + DSH_CLIENT_VERSION: '1.2.3', } const official = buildFixture(officialEnvironment) const defaultBuild = buildFixture({}) diff --git a/scripts/client-build-environment.ts b/scripts/client-build-environment.ts index 2331db5f42..13ea20cdc1 100644 --- a/scripts/client-build-environment.ts +++ b/scripts/client-build-environment.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import { execFileSync } from 'node:child_process' +import { execFileSync, spawnSync } from 'node:child_process' import { existsSync, globSync, @@ -25,6 +25,9 @@ const OFFICIAL_CLIENT_BUILD_ENVIRONMENT = { /** Public variable carrying the source commit embedded in client artifacts. */ const CLIENT_COMMIT_HASH_VARIABLE = 'DSH_CLIENT_COMMIT_HASH' +/** Public variable carrying the repository package version embedded in client artifacts. */ +const CLIENT_VERSION_VARIABLE = 'DSH_CLIENT_VERSION' + /** Repository-relative path of the complete client build record. */ export const CLIENT_BUILD_RECORD_PATH = '.dsh-build/client-build-environment.json' @@ -57,6 +60,76 @@ export function repositoryCommitHash(root: string, environment: NodeJS.ProcessEn return value.slice(0, 7).toLowerCase() } +/** + * Resolve the repository package version used by browser build metadata. + * @param root - repository root containing the authoritative package.json. + * @returns the repository's semver-compatible package version. + */ +export function repositoryVersion(root: string): string { + const path = resolve(root, 'package.json') + let manifest: unknown + try { + manifest = JSON.parse(readFileSync(path, 'utf8')) + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + throw new Error(`cannot read repository version from ${path}: ${detail}`) + } + if (!isObject(manifest) || typeof manifest.version !== 'string' + || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(manifest.version)) { + throw new Error(`repository package.json has an invalid version ${JSON.stringify(isObject(manifest) ? manifest.version : undefined)}`) + } + return manifest.version +} + +/** + * Read whether Git reports any staged, unstaged, untracked, or submodule change. + * @param root - repository root whose worktree is inspected. + * @returns true or false inside a Git worktree; undefined without Git metadata. + */ +export function repositoryGitDirty(root: string): boolean | undefined { + const probe = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], { + cwd: root, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'], + }) + if (probe.error !== undefined || probe.status !== 0 || probe.stdout.trim() !== 'true') return undefined + + const status = spawnSync('git', ['status', '--porcelain=v1', '--untracked-files=normal'], { + cwd: root, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }) + if (status.error !== undefined) throw status.error + if (status.status !== 0) { + throw new Error(`git status failed in ${root}: ${status.stderr.trim() || String(status.status)}`) + } + return status.stdout !== '' +} + +/** + * Resolve the public environment for a complete default build from one checkout. + * Repository-owned metadata replaces inherited values; other public values pass through. + * @param root - repository root supplying version and Git metadata. + * @param environment - caller environment supplying optional commit and public extensions. + * @returns complete public client environment for the default build. + */ +export function repositoryClientBuildEnvironment( + root: string, + environment: NodeJS.ProcessEnv = process.env, +): ClientBuildEnvironment { + const inherited = { ...clientBuildEnvironment(environment) } + delete inherited.DSH_CLIENT_COMMIT_HASH + delete inherited.DSH_CLIENT_GIT_DIRTY + delete inherited.DSH_CLIENT_VERSION + const dirty = repositoryGitDirty(root) + return { + ...inherited, + DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, environment), + ...(dirty === true ? { DSH_CLIENT_GIT_DIRTY: 'true' } : {}), + DSH_CLIENT_VERSION: repositoryVersion(root), + } +} + /** * Resolve the exact public values required by an official build at one commit. * @param root - repository root whose HEAD must match the built source. @@ -69,6 +142,7 @@ export function officialClientBuildEnvironment( ): Readonly> { return { DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, environment), + DSH_CLIENT_VERSION: repositoryVersion(root), ...OFFICIAL_CLIENT_BUILD_ENVIRONMENT, } } @@ -115,10 +189,18 @@ export function resolveClientBuildEnvironment( if (profile === undefined) return clientBuildEnvironment(environment) if (profile === 'official') { const commitHash = environment[CLIENT_COMMIT_HASH_VARIABLE] + const version = environment[CLIENT_VERSION_VARIABLE] if (commitHash === undefined) { throw new Error(`${CLIENT_COMMIT_HASH_VARIABLE} is required for the official client build profile`) } - return { DSH_CLIENT_COMMIT_HASH: commitHash, ...OFFICIAL_CLIENT_BUILD_ENVIRONMENT } + if (version === undefined) { + throw new Error(`${CLIENT_VERSION_VARIABLE} is required for the official client build profile`) + } + return { + DSH_CLIENT_COMMIT_HASH: commitHash, + DSH_CLIENT_VERSION: version, + ...OFFICIAL_CLIENT_BUILD_ENVIRONMENT, + } } throw new Error(`unknown client build profile ${JSON.stringify(profile)}; expected "official"`) } diff --git a/scripts/client-bundle-purity.spec.ts b/scripts/client-bundle-purity.spec.ts index d9222f617b..ce17d3247e 100644 --- a/scripts/client-bundle-purity.spec.ts +++ b/scripts/client-bundle-purity.spec.ts @@ -1,7 +1,10 @@ /** - * Pins shared client-bundle preset rules: the module-edge purity gate and - * the physical watch dependencies hidden behind virtual CSS Modules. + * Pins shared client-bundle preset rules: module-edge purity, source-map + * chaining, and physical watch dependencies hidden behind virtual CSS Modules. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it, vi } from 'vitest' import { clientBundle, requestedExternals } from '../packages/client/tsdown.client.ts' @@ -14,6 +17,11 @@ interface CssModulePlugin { load?: (this: { addWatchFile: (id: string) => void }, id: string) => Promise } +interface SourceMapPlugin { + name: string + load?: (id: string) => Promise +} + /** A representative dynamic bundle using the shared client baseline. */ const REQUESTING_PACKAGE = '@deepseek-ai/dsh-client-ui-conversation' @@ -59,6 +67,14 @@ function cssModulePlugin(): CssModulePlugin { return plugin } +function sourceMapPlugin(): SourceMapPlugin { + const configs = clientConfigs() + const plugins = (configs[0] as { plugins: SourceMapPlugin[] }).plugins + const plugin = plugins.find(candidate => candidate.name === 'dsh-tsc-sourcemap') + if (plugin?.load === undefined) throw new Error('tsc sourcemap plugin missing from client config') + return plugin +} + describe('client bundle purity gate', () => { const resolveId = purityResolveId() @@ -143,6 +159,28 @@ describe('client bundle debug artifacts', () => { it('emits source maps for plugin TS and TSX outside the Vite module graph', () => { const configs = clientConfigs() expect(configs[0]?.sourcemap).toBe(true) + expect(configs[0]?.outputOptions).toMatchObject({ sourcemapExcludeSources: false }) + }) + + it('chains emitted tsc maps when the production Client build consumes lib/types', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-client-sourcemap-')) + try { + const entry = join(root, 'lib', 'types', 'client', 'index.js') + const source = join(root, 'src', 'client', 'index.ts') + const map = { version: 3, names: [], mappings: 'AAAA', sources: ['../../../src/client/index.ts'] } + mkdirSync(join(root, 'lib', 'types', 'client'), { recursive: true }) + mkdirSync(join(root, 'src', 'client'), { recursive: true }) + writeFileSync(entry, 'export const marker = true\n//# sourceMappingURL=index.js.map\n') + writeFileSync(`${entry}.map`, JSON.stringify(map)) + writeFileSync(source, 'export const marker: true = true\n') + + await expect(sourceMapPlugin().load!(entry)).resolves.toEqual({ + code: 'export const marker = true', + map: { ...map, sourcesContent: ['export const marker: true = true\n'] }, + }) + } finally { + rmSync(root, { recursive: true, force: true }) + } }) it('maps first-party sources to their repository package paths', () => { diff --git a/scripts/coverage-exempt.ts b/scripts/coverage-exempt.ts index 2e68b53b60..eff6ca2b13 100644 --- a/scripts/coverage-exempt.ts +++ b/scripts/coverage-exempt.ts @@ -39,10 +39,4 @@ export const coverageExemptHeavySuites: readonly CoverageExemptSuite[] = [ { filter: 'scripts/oxlint-contract.spec.ts', exclude: 'scripts/oxlint-contract.spec.ts' }, { filter: 'scripts/change-scope.spec.ts', exclude: 'scripts/change-scope.spec.ts' }, { filter: 'scripts/translation-pairing-merge.spec.ts', exclude: 'scripts/translation-pairing-merge.spec.ts' }, - // The real corpus transform runs package src only in a spawned Node process, - // outside the parent Vitest worker's v8 coverage session. - { - filter: 'packages/experimental/webworker-runtime/tests/compile/transform-corpus.spec.ts', - exclude: 'packages/experimental/webworker-runtime/tests/compile/transform-corpus.spec.ts', - }, ] diff --git a/scripts/dev-web.spec.ts b/scripts/dev-web.spec.ts index f185ee6754..76dbf82860 100644 --- a/scripts/dev-web.spec.ts +++ b/scripts/dev-web.spec.ts @@ -3,7 +3,45 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' import type { TsdownBundle } from 'tsdown' -import { discoverLibraryDirs, discoverPluginDirs, watchClientPlugins } from './dev-web.ts' +import { writeClientBuildRecord } from './client-build-environment.ts' +import { + devWebBuildEnvironment, + discoverLibraryDirs, + discoverPluginDirs, + watchClientPlugins, +} from './dev-web.ts' + +it('samples one local environment at startup without validating watcher outputs', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-dev-web-environment-')) + try { + await mkdir(join(root, 'apps/web/dist'), { recursive: true }) + await mkdir(join(root, 'packages/client/example/lib'), { recursive: true }) + await writeFile(join(root, 'package.json'), JSON.stringify({ version: '1.2.3' })) + await writeFile(join(root, 'apps/web/dist/index.html'), '
') + await writeFile(join(root, 'packages/client/example/lib/client.js'), 'module.exports = {}\n') + writeClientBuildRecord(root, { + DSH_CLIENT_BUILD_PROFILE: 'official', + DSH_CLIENT_COMMIT_HASH: 'fffffff', + DSH_CLIENT_TITLE: 'DeepSeek Harness', + DSH_CLIENT_VERSION: '1.2.2', + }) + await writeFile(join(root, 'packages/client/example/lib/client.js'), 'module.exports = { changed: true }\n') + + expect(devWebBuildEnvironment(root, { + PATH: '/bin', + DSH_BUILD_CLIENT_PROFILE: 'official', + DSH_CLIENT_COMMIT_HASH: 'abc1234', + DSH_CLIENT_EXTRA: 'launch-value', + })).toEqual({ + PATH: '/bin', + DSH_CLIENT_COMMIT_HASH: 'abc1234', + DSH_CLIENT_EXTRA: 'launch-value', + DSH_CLIENT_VERSION: '1.2.3', + }) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) it('discovers dsh.client packages with sibling roles', async () => { const root = await mkdtemp(join(tmpdir(), 'dsh-dev-web-discovery-')) diff --git a/scripts/dev-web.ts b/scripts/dev-web.ts index 05f929f1b8..35500eca13 100644 --- a/scripts/dev-web.ts +++ b/scripts/dev-web.ts @@ -34,6 +34,11 @@ import { fileURLToPath, pathToFileURL } from 'node:url' import { execa } from 'execa' import { build } from 'tsdown' import type { TsdownBundle } from 'tsdown' +import { + CLIENT_BUILD_PROFILE_SELECTOR, + clientBuildProcessEnvironment, + repositoryClientBuildEnvironment, +} from './client-build-environment.ts' const repoRoot = fileURLToPath(new URL('..', import.meta.url)) @@ -49,6 +54,19 @@ const SHELL_PACKAGE = '@deepseek-ai/dsh-web-frontend' */ const TEST_INFRASTRUCTURE_PREFIX = 'packages/test-support/' +/** + * Sample one local public environment for every long-lived watcher stage. + * @param root - repository root supplying version and Git metadata. + * @param environment - watcher launch environment supplying public extensions. + * @returns process environment shared by tsdown and spawned watcher stages. + */ +export function devWebBuildEnvironment( + root: string, + environment: NodeJS.ProcessEnv = process.env, +): NodeJS.ProcessEnv { + return clientBuildProcessEnvironment(environment, repositoryClientBuildEnvironment(root, environment)) +} + /** * Discover the watch workspace by declaration: every packages// * whose package.json carries `dsh.client` with platform "web" is a client @@ -175,6 +193,16 @@ interface StageHandle { const invokedPath = process.argv[1] const isMain = invokedPath !== undefined && import.meta.url === pathToFileURL(resolve(invokedPath)).href if (isMain) { + const buildEnvironment = devWebBuildEnvironment(repoRoot, process.env) + for (const name of Object.keys(process.env)) { + if (name === CLIENT_BUILD_PROFILE_SELECTOR || name.startsWith('DSH_CLIENT_')) { + Reflect.deleteProperty(process.env, name) + } + } + for (const [name, value] of Object.entries(buildEnvironment)) { + if (name.startsWith('DSH_CLIENT_') && value !== undefined) process.env[name] = value + } + const pluginDirs = discoverPluginDirs() const libraryDirs = discoverLibraryDirs() if (pluginDirs.length === 0) { diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index d8bed47236..4acfd5b694 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -100,6 +100,7 @@ export const SERVICE_PAGE: Record = { spillStore: 'spill.md', storage: 'storage.md', storageDomain: 'storage.md', + subagentModelSelection: 'subagent.md', subagents: 'subagent.md', subprocess: 'subprocess.md', systemPrompt: 'system-prompt.md', @@ -335,6 +336,7 @@ export const LINK_MAP: Readonly> = { ApprovalService: 'approval.md', AskUserQuestionRequestEvent: 'user-questions.md', EncodedImageAttachment: 'attachment.md', + ImageAttachmentAccess: 'llm-streaming.md', ImageAttachmentRef: 'attachment.md', ImageRequestPolicy: 'attachment.md', RequestImageAttachment: 'attachment.md', @@ -571,6 +573,7 @@ export const LINK_MAP: Readonly> = { WorkspaceOrderValue: 'workspace.md', WorkspaceRenameRequest: 'workspace.md', WorkspaceValue: 'workspace.md', + ClientArtifactBaseline: 'client-modules.md', WebBootGraph: 'client-modules.md', SessionTelemetryRecord: 'session-telemetry.md', WorkflowRunInfo: 'workflow.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 39089baad4..2beb36c4e6 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -205,6 +205,14 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['llm-deepseek', 'llm-pi-ai', 'apiproxy'], note: 'Plugins register namespace schemas and resolve layered values; providers store the raw document. The LLM adapters register their entry config as the composition base under the user section; the web gateway serves redacted layered descriptors and writes the user layer.', }, + { + key: 'subagentModelSelection', + pkg: 'tool-subagent', + title: 'Subagent model-selection preference', + mode: 'core', + consumers: ['tool-subagent'], + note: 'Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session.', + }, { key: 'credentials', pkg: 'credentials', @@ -763,7 +771,7 @@ const APP_EXAMPLES = [ title: 'DSH Base Composition', label: 'packages/bundle/base/cordis.patch.yml', config: 'packages/bundle/base/cordis.patch.yml', - summary: 'The dsh-base bundle patch every profile applies first; mode bundles (dsh-web-app, dsh-headless) and the user\'s profile layer patch over it.', + summary: 'The dsh-base bundle patch shared by the web, headless, sdk, and acp profiles; their mode bundles and user layers patch over it, while sdk-minimal owns a separate standalone tree.', }, { id: 'headless', diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 19ab10c455..3d69da2cc3 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -9,6 +9,7 @@ import { globSync, readFileSync, writeFileSync } from 'node:fs' import { basename, resolve } from 'node:path' import { Context } from '@deepseek-ai/cordis' +import LlmRuntime from '@deepseek-ai/dsh-llm' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' @@ -104,7 +105,7 @@ const OUT = 'docs/tool-catalog.md' function registerCatalogSubagentProvider(ctx: Context, name: string): void { const provider: SubagentProvider = { name, - capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, + capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true }, inheritsParentContext: false, start: () => Promise.reject(new Error('tool-catalog provider cannot start a child')), // Declared so consumers configured for continuable background mode mount. @@ -455,17 +456,21 @@ const TOOL_PACKAGES: ToolPackage[] = [ { pkg: '@deepseek-ai/dsh-tool-subagent', dir: 'tool-subagent', - source: 'packages/subagent/tool-subagent/src/index.ts', - requires: ['ctx.tools', 'ctx.subagents', 'ctx.systemPrompt'], + source: { + list_subagent_models: 'packages/subagent/tool-subagent/src/list-models.ts', + subagent: 'packages/subagent/tool-subagent/src/index.ts', + }, + requires: ['ctx.tools', 'ctx.subagents', 'ctx.systemPrompt', 'ctx.llm for model discovery and selected-route validation'], writes: ['tool/call', 'tool/result', 'child session events through the chosen provider'], shippedNames: ['subagent', 'subagent_fork'], async mount(ctx) { await ctx.plugin(SubagentRuntime) + await ctx.plugin(LlmRuntime) registerCatalogSubagentProvider(ctx, 'mock') - await ctx.plugin(ToolSubagent, { provider: 'mock' }) + await ctx.plugin(ToolSubagent, { provider: 'mock', enableModelSelection: true }) }, note: - 'The registered tool name is the load-time `toolName` config (default `subagent`); the schema above is that default. The shipped compositions load this package once per subagent backend, so the model additionally sees `subagent_fork` bound to the fork backend. Each instance\'s description, `run_in_background` parameter, and system-prompt policy follow its own `backgroundMode` and `enableRunInBackground`, so the two shipped schemas are not identical: `subagent` is `continuable` and defaults omitted calls to background with automatic settlement delivery, while `subagent_fork` stays `one-shot` and defaults them to foreground — see `packages/bundle/base/cordis.patch.yml` and `examples/acp-agent/cordis.yml`.', + 'The registered delegation name is the load-time `toolName` config (default `subagent`); the schema above shows static model selection enabled for reference. Model selection defaults off. Web presets sample the default-off Models preference for each new top-level Session and preserve that decision for its child Sessions; `subagent_fork` remains fixed-route. Explicit compositions may instead use static `enableModelSelection`. Each instance independently controls model selection, discovery ownership, and background behavior through `enableModelSelection`, `modelSelectionSettings`, `backgroundMode`, and `enableRunInBackground`.', }, { pkg: '@deepseek-ai/dsh-tool-subagent-control', diff --git a/scripts/oxlint-contract.spec.ts b/scripts/oxlint-contract.spec.ts index c1f39f8cc8..def26f0a78 100644 --- a/scripts/oxlint-contract.spec.ts +++ b/scripts/oxlint-contract.spec.ts @@ -1,8 +1,8 @@ import { spawnSync } from 'node:child_process' import { randomUUID } from 'node:crypto' import { existsSync } from 'node:fs' -import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' -import { basename, dirname, join, relative } from 'node:path' +import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { join, relative } from 'node:path' import { fileURLToPath } from 'node:url' import { flattenDiagnosticMessageText, parseConfigFileTextToJson } from 'typescript' import { describe, expect, it } from 'vitest' @@ -39,26 +39,6 @@ function normalizedOutput(result: ReturnType): string { return `${result.stdout}${result.stderr}`.replaceAll('\\', '/') } -/** @returns A transient filename excluded from concurrent repository-wide glob discovery. */ -function hiddenProbeName(prefix: string, suffix: string, extension = '.ts'): string { - return `.${prefix}-${suffix}${extension}` -} - -/** - * Publish a complete probe so concurrent repository scans never read a partial write. - * @param path - Final probe path that the owning project must discover. - * @param source - Complete TypeScript source to publish. - */ -async function publishProbe(path: string, source: string): Promise { - const staging = join(dirname(path), `.${basename(path)}.staging`) - try { - await writeFile(staging, source) - await rename(staging, path) - } finally { - await rm(staging, { force: true }) - } -} - async function writeContractConfig(suffix: string): Promise { const path = join(repositoryRoot, `.oxlintrc.contract-${suffix}.json`) await writeFile(path, JSON.stringify({ extends: ['./.oxlintrc.json'], ignorePatterns: [] })) @@ -79,8 +59,7 @@ describe('Oxlint executable contract', () => { ['example', 'examples/headless-agent/tests', 'tsconfig.host.json'], ['website', 'website', 'tsconfig.host.json'], ] as const - const source = `/** Produce a settled promise for type-aware linting. */ -export function probePromise(): Promise { + const source = `export function probePromise(): Promise { return Promise.resolve() } @@ -91,7 +70,7 @@ probePromise() const paths: Array = [] for (const [label, parent, tsconfig, extension = '.ts'] of probes) { const path = join(repositoryRoot, parent, `oxlint-contract-${suffix}${extension}`) - await publishProbe(path, source) + await writeFile(path, source) paths.push([label, relative(repositoryRoot, path), tsconfig]) } const clientScript = 'scripts/client-bundle-purity.spec.ts' @@ -109,7 +88,7 @@ probePromise() expect(result.error).toBeUndefined() expect(result.status, output).toBe(1) for (const [label, path, tsconfig] of paths) { - expect(output, label).toContain(`${path.replaceAll('\\', '/')}:6:1: Promises must be awaited`) + expect(output, label).toContain(`${path.replaceAll('\\', '/')}:5:1: Promises must be awaited`) expect(output, `${label} project`).toContain( `Got tsconfig for file ${join(repositoryRoot, path).replaceAll('\\', '/')}: ${join(repositoryRoot, tsconfig).replaceAll('\\', '/')}`, ) @@ -131,7 +110,7 @@ probePromise() it('runs JavaScript compatibility and nursery rules', async () => { const suffix = randomUUID() const configPath = await writeContractConfig(suffix) - const path = join(repositoryRoot, 'scripts', hiddenProbeName('oxlint-contract', suffix)) + const path = join(repositoryRoot, 'scripts', `oxlint-contract-${suffix}.ts`) const source = `export function firstProbe(): number { const first = 1 const second = 2 @@ -251,7 +230,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + it('reports an unused suppression', async () => { const suffix = randomUUID() const configPath = await writeContractConfig(suffix) - const path = join(repositoryRoot, 'scripts', hiddenProbeName('oxlint-contract', suffix)) + const path = join(repositoryRoot, 'scripts', `oxlint-contract-${suffix}.ts`) try { await writeFile(path, '// oxlint-disable-next-line no-console\nexport const value = 1\n') @@ -301,7 +280,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + expect(stagedConfig.ignorePatterns).not.toContain('packages/typert/generator/tests/fixtures/type-model/**') const suffix = randomUUID() - const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix)) + const path = join(repositoryRoot, 'scripts', `staged-lint-probe-${suffix}.ts`) try { await writeFile(path, 'export const value={answer:1};\n') const lint = runOxlint([ @@ -324,7 +303,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + it('preserves successful fix output channels', async () => { const suffix = randomUUID() - const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix)) + const path = join(repositoryRoot, 'scripts', `staged-lint-probe-${suffix}.ts`) try { await writeFile(path, '// oxlint-disable-next-line no-console\nexport const value = 1\n') @@ -348,7 +327,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + it('prints only the final diagnostics when a fix retry still fails', async () => { const suffix = randomUUID() - const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix)) + const path = join(repositoryRoot, 'scripts', `staged-lint-probe-${suffix}.ts`) try { await writeFile(path, `export const longProbe = ${'1 + '.repeat(80)}1\n`) diff --git a/scripts/release/families.spec.ts b/scripts/release/families.spec.ts index d22db243d8..c3ae3c8c2f 100644 --- a/scripts/release/families.spec.ts +++ b/scripts/release/families.spec.ts @@ -29,6 +29,7 @@ function write(path: string, content: string): void { function buildFixture(environment: Record): string { const root = mkdtempSync(join(tmpdir(), 'dsh-release-build-')) roots.push(root) + write(join(root, 'package.json'), `${JSON.stringify({ version: environment.DSH_CLIENT_VERSION ?? '0.0.1' })}\n`) write(join(root, 'apps/web/dist/index.html'), '
') write(join(root, 'packages/client/example/lib/client.js'), 'module.exports = {}\n') writeClientBuildRecord(root, environment) @@ -106,11 +107,13 @@ describe('release families', () => { vi.stubEnv('DSH_CLIENT_COMMIT_HASH', officialEnvironment.DSH_CLIENT_COMMIT_HASH) const official = buildFixture(officialEnvironment) const defaultBuild = buildFixture({}) + const missing = join(defaultBuild, 'missing') + write(join(missing, 'package.json'), `${JSON.stringify({ version: officialEnvironment.DSH_CLIENT_VERSION })}\n`) expect(() => { dsh.verifyBuildArtifacts(official) }).not.toThrow() expect(() => { dsh.verifyBuildArtifacts(defaultBuild) }).toThrow(/DSH_CLIENT_TITLE/) - expect(() => { dsh.verifyBuildArtifacts(join(defaultBuild, 'missing')) }).toThrow(/record.*missing/) - expect(() => { vendor.verifyBuildArtifacts(join(defaultBuild, 'missing')) }).not.toThrow() + expect(() => { dsh.verifyBuildArtifacts(missing) }).toThrow(/record.*missing/) + expect(() => { vendor.verifyBuildArtifacts(missing) }).not.toThrow() write(join(official, 'packages/client/example/lib/client.js'), 'module.exports = { changed: true }\n') expect(() => { dsh.verifyBuildArtifacts(official) }).toThrow(/artifacts differ/) diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index e7188f7709..1535b27ba3 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -169,13 +169,14 @@ describe('gate graph validation', () => { expect(byId.get('coverage')?.allowFailure).not.toBe(true) expect(byId.get('coverage-exempt-heavy')?.allowFailure).not.toBe(true) expect(byId.get('coverage-exempt-heavy')?.needs).toContain('build') - expect(byId.get('coverage-exempt-heavy')?.after).toContain('coverage') expect(observational).not.toHaveLength(0) for (const gate of observational) { const completeGate = byId.get(gate.id) expect(completeGate?.allowFailure).toBe(true) - expect(completeGate?.after).toContain('coverage') - expect(completeGate?.after).not.toContain('coverage-exempt-heavy') + expect(completeGate?.after).toEqual(expect.arrayContaining([ + 'coverage', + 'coverage-exempt-heavy', + ])) expect(completeGate?.needs).toEqual(gate.needs) } }) diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index e24e662153..45af4dc99e 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -472,12 +472,9 @@ function ciWindowsBlockingGates(): Gate[] { function ciWindowsCompleteGates(): Gate[] { const coverage = coverageGates().map(gate => gate.id === 'coverage-exempt-heavy' - ? { - ...gate, - needs: [...new Set(['build', ...(gate.needs ?? [])])], - after: [...new Set(['coverage', ...(gate.after ?? [])])], - } + ? { ...gate, needs: [...new Set(['build', ...(gate.needs ?? [])])] } : gate) + const coverageAfter = coverage.map(gate => gate.id) const observational = ciWindowsObservationalGates() // The required production site replaces the observational MPA build; both // VitePress modes write the same output directory and cannot overlap. @@ -485,7 +482,7 @@ function ciWindowsCompleteGates(): Gate[] { .map(gate => ({ ...gate, allowFailure: true, - after: [...new Set(['coverage', ...(gate.after ?? [])])], + after: [...new Set([...coverageAfter, ...(gate.after ?? [])])], })) return [ ciBuildGate(), diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 71e7100268..b28e740495 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -12,6 +12,7 @@ import os import queue import subprocess import sys +import sysconfig import tempfile import threading import time @@ -29,7 +30,7 @@ CODE_PROMPT = "Use run_code to compute the packaged worker smoke value." CODE_WORKER_TEXT = "code worker smoke ok" WORKFLOW_PROMPT = "Use workflow to compute the packaged worker smoke value without agents." WORKFLOW_WORKER_TEXT = "workflow worker smoke ok" -MINIMAL_PROMPT = "Exercise the packaged minimal agent's persistent Bash and string-replacement editor." +MINIMAL_PROMPT = "Exercise the packaged minimal agent's persistent shell and string-replacement editor." MINIMAL_TEXT = "minimal agent smoke ok" MINIMAL_EDITOR_PATH_PREFIX = "Editor path: " FS_SEARCH_PROMPT = "Exercise the packaged filesystem search tools." @@ -37,13 +38,43 @@ FS_SEARCH_TEXT = "filesystem search smoke ok" FS_SEARCH_MARKER = "PACKAGED_FS_SEARCH_OK" MCP_PROMPT = "Exercise the packaged MCP client with one external stdio server." MCP_TEXT = "MCP client smoke ok" -MINIMAL_CORDIS = ( - Path(__file__).resolve().parent.parent / "examples" / "python-sdk-agent" / "minimal.cordis.yml" +PROFILE_PLUGIN_PROMPT = "Verify the Python-installed dsh profile plugin." +PROFILE_PLUGIN_TEXT = "profile plugin smoke ok" +PROFILE_PLUGIN_MARKER = "PYTHON_INSTALLED_DSH_PROFILE_PLUGIN" +IS_WINDOWS = sys.platform == "win32" +MINIMAL_SHELL_TOOL = "pwsh" if IS_WINDOWS else "bash" +MINIMAL_SHELL_COMMAND = ( + "$global:dshSdkCounter = [int]$global:dshSdkCounter + 1; " + 'Write-Output "COUNT=$global:dshSdkCounter CWD=$((Get-Location).Path)"; ' + "if ($global:dshSdkCounter -eq 1) { Set-Location $env:TEMP }" + if IS_WINDOWS + else ( + "counter=$(( ${counter:-0} + 1 )); export counter; " + "printf 'COUNT=%s CWD=%s\\n' \"$counter\" \"$PWD\"; " + "if [ \"$counter\" -eq 1 ]; then cd /tmp; fi" + ) ) -MINIMAL_BASH_COMMAND = ( - "counter=$(( ${counter:-0} + 1 )); export counter; " - "printf 'COUNT=%s CWD=%s\\n' \"$counter\" \"$PWD\"; " - "if [ \"$counter\" -eq 1 ]; then cd /tmp; fi" +MINIMAL_SHELL_SECOND_CWD = str(Path(tempfile.gettempdir()).resolve()) if IS_WINDOWS else "/tmp" +LEGACY_CUSTOM_DISABLED_ROWS = ( + "agent-instructions", + "goal", + "goal-round-driver", + "command-goal", + "plan-mode", + "skill", + "skill-filesystem", + "tool-fs", + "tool-fs-search", + "tool-goal", + "tool-ralph", + "tool-skill", + "tool-str-replace-editor", + "tool-subagent-control", + "tool-subagent-list-agents", + "tool-subagent-fork", + "tool-subagent-report", + "tool-todo", + "tool-web", ) SNAPSHOT_PROMPT = "Run the advanced packaged-runtime snapshot scenario." SNAPSHOT_SESSION_ID = "advanced-executable" @@ -86,84 +117,13 @@ ADVANCED_SNAPSHOT_FILENAMES = ("result.json", "session.jsonl", "session.1.jsonl" MINIMAL_SNAPSHOT_DIRECTORY = ( Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "minimal" ) +if IS_WINDOWS: + MINIMAL_SNAPSHOT_DIRECTORY /= "win-x64" MINIMAL_SNAPSHOT_FILENAMES = ("model-visible.json",) RESTART_SNAPSHOT_DIRECTORY = ( Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "restart" ) RESTART_SNAPSHOT_FILENAMES = ("result.json", "requests.json", "session.1.jsonl", "session.2.jsonl") -# The agent loop's dynamic runtime-context snapshot is the one model-visible message this -# expected output cannot carry: the same composition emits it on macOS and not on Linux -# (deepseek-harness#2488), and the file must replay on both. Everything else is compared. -RUNTIME_CONTEXT_PREFIX = "Current runtime context" -CUSTOM_CORDIS = """\ -- id: sdk-jsonrpc-server - name: '@deepseek-ai/dsh-sdk-jsonrpc-server' -- id: deepseek-llm-api-extensions - name: '@deepseek-ai/dsh-deepseek-llm-api-extensions' -- id: session-log-deepseek - name: '@deepseek-ai/dsh-session-log-deepseek' - config: - enabled: true -- id: agent-core - name: '@deepseek-ai/dsh-agent-spine-demo' - config: - workspaceContext: false - skills: - enabled: false - toolBash: false - tools: - mode: both -- id: sessions - name: '@deepseek-ai/dsh-session-persistence-jsonl' - config: - root: !!js process.env.DSH_SESSION_ROOT - compression: 'none' -- id: code-runtime - name: '@deepseek-ai/dsh-code-runtime-worker-thread' -- id: subagents - name: '@deepseek-ai/dsh-subagent' -- id: subagent-spawn-in-process - name: '@deepseek-ai/dsh-subagent-spawn-in-process' - config: - providerName: spawn -- id: subagent-tool - name: '@deepseek-ai/dsh-tool-subagent' - config: - provider: spawn -- id: workflow-engine - name: '@deepseek-ai/dsh-workflow-worker-thread' - config: - provider: spawn -- id: workflow-tool - name: '@deepseek-ai/dsh-tool-workflow' -- id: cordis-host-runner - name: '@deepseek-ai/dsh-cordis-host-runner' -- id: cordis-tool - name: '@deepseek-ai/dsh-tool-cordis' -""" -FS_SEARCH_CORDIS = """\ -- id: sdk-jsonrpc-server - name: '@deepseek-ai/dsh-sdk-jsonrpc-server' -- id: agent-core - name: '@deepseek-ai/dsh-agent-spine-demo' - config: - workspaceContext: false - skills: - enabled: false - toolBash: false - toolJobs: false -- id: sessions - name: '@deepseek-ai/dsh-session-persistence-jsonl' - config: - root: !!js process.env.DSH_SESSION_ROOT - compression: 'none' -- id: subprocess - name: '@deepseek-ai/dsh-subprocess-local' -- id: fs-search - name: '@deepseek-ai/dsh-tool-fs-search' - config: - sampleOverCapGlobResults: false -""" MCP_SERVER_SCRIPT = """\ import json import os @@ -242,28 +202,29 @@ for line in sys.stdin: """ -def mcp_cordis(server_script: Path) -> str: - """Build an external config that mounts the packaged MCP client.""" - return json.dumps([ +def write_profile_patch( + root: Path, + name: str, + sessions: Path, + patches: list[dict[str, object]], +) -> Path: + """Write one JSON-form dsh profile patch with deterministic persistence.""" + path = root / name + path.write_text(json.dumps([ { - "id": "sdk-jsonrpc-server", - "name": "@deepseek-ai/dsh-sdk-jsonrpc-server", + "id": "session-persistence-jsonl", + "config": {"root": str(sessions), "compression": "none"}, }, - { - "id": "agent-core", - "name": "@deepseek-ai/dsh-agent-spine-demo", - "config": { - "workspaceContext": False, - "skills": {"enabled": False}, - "toolBash": False, - }, - }, - { - "id": "sessions", - "name": "@deepseek-ai/dsh-session-persistence-jsonl", - "config": {"root": "./sessions", "compression": "none"}, - }, - { + {"id": "session-telemetry-otel", "disabled": True}, + *patches, + ], indent=2)) + return path + + +def write_mcp_patch(root: Path, sessions: Path, server_script: Path) -> Path: + """Write a profile patch that mounts the packaged MCP client.""" + return write_profile_patch(root, "mcp.patch.yml", sessions, [{ + "insert": [{ "id": "mcp-fixture", "name": "@deepseek-ai/dsh-mcp-client", "config": { @@ -275,8 +236,8 @@ def mcp_cordis(server_script: Path) -> str: "failOnStartupError": True, "reconnect": {"enabled": False}, }, - }, - ], indent=2) + }], + }]) class MockModelHandler(BaseHTTPRequestHandler): @@ -351,8 +312,8 @@ def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]: if minimal_prompt is not None: return tool_call_chunks( "minimal-bash-1", - "bash", - {"command": MINIMAL_BASH_COMMAND}, + MINIMAL_SHELL_TOOL, + {"command": MINIMAL_SHELL_COMMAND}, ) scenario_prompts = { SNAPSHOT_DIRECT_CHILD_PROMPT, @@ -364,6 +325,7 @@ def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]: MCP_PROMPT, RESTART_FIRST_PROMPT, RESTART_SECOND_PROMPT, + PROFILE_PLUGIN_PROMPT, } prompt = next( (candidate for candidate in user_prompts if candidate in scenario_prompts), @@ -430,6 +392,15 @@ def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]: "mcp__fixture__add", {"a": 19, "b": 23}, ) + if prompt == PROFILE_PLUGIN_PROMPT: + system_text = "\n".join( + message_text(message.get("content")) + for message in messages + if isinstance(message, dict) and message.get("role") == "system" + ) + if PROFILE_PLUGIN_MARKER not in system_text: + raise AssertionError("external profile plugin contributed no model-visible marker") + return text_chunks(PROFILE_PLUGIN_TEXT) return text_chunks(EXPECTED_TEXT) @@ -478,17 +449,18 @@ def minimal_tool_followup( """Verify the checked-in minimal composition's PTY and editor.""" if not call_id.startswith("minimal-"): return None - if call_id == "minimal-bash-1" and tool_name == "bash": + if call_id == "minimal-bash-1" and tool_name == MINIMAL_SHELL_TOOL: if "COUNT=1" not in tool_text: - raise AssertionError(f"first persistent bash call lost its output: {tool_text}") + raise AssertionError(f"first persistent shell call lost its output: {tool_text}") return tool_call_chunks( "minimal-bash-2", - "bash", - {"command": MINIMAL_BASH_COMMAND}, + MINIMAL_SHELL_TOOL, + {"command": MINIMAL_SHELL_COMMAND}, ) - if call_id == "minimal-bash-2" and tool_name == "bash": - if "COUNT=2 CWD=/tmp" not in tool_text: - raise AssertionError(f"persistent bash did not retain state: {tool_text}") + if call_id == "minimal-bash-2" and tool_name == MINIMAL_SHELL_TOOL: + expected = f"COUNT=2 CWD={MINIMAL_SHELL_SECOND_CWD}" + if expected.lower() not in tool_text.lower(): + raise AssertionError(f"persistent shell did not retain state: {tool_text}") messages = body.get("messages") if not isinstance(messages, list): raise AssertionError("persistent editor smoke request has no messages") @@ -710,7 +682,7 @@ def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--scenario", - choices=("all", "sdk-default", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-mcp", "sdk-snapshot", "sdk-restart", "sdk-live", "direct"), + choices=("all", "sdk-default", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-mcp", "sdk-snapshot", "sdk-restart", "sdk-profile-plugin", "sdk-live", "direct"), default="all", ) parser.add_argument("--exe", type=Path) @@ -725,6 +697,8 @@ def main() -> None: parser.error("--installed-wheel resolves the wheel's own runtime and cannot be combined with --exe") if args.scenario == "sdk-live" and not args.installed_wheel: parser.error("--scenario sdk-live requires --installed-wheel") + if args.scenario == "sdk-profile-plugin" and not args.installed_wheel: + parser.error("--scenario sdk-profile-plugin requires --installed-wheel") if args.installed_wheel: args.exe = assert_installed_wheel_environment() if args.scenario in {"all", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-snapshot", "sdk-restart", "direct"} and args.exe is None: @@ -759,6 +733,8 @@ def main() -> None: if args.scenario in {"all", "sdk-restart"}: assert args.exe is not None smoke_sdk_restart_snapshot(model.url, args.exe.resolve(), args.update_snapshots) + if args.installed_wheel and args.scenario in {"all", "sdk-profile-plugin"}: + smoke_sdk_profile_plugin(model.url) if args.scenario in {"all", "direct"}: assert args.exe is not None smoke_direct(model.url, args.exe.resolve()) @@ -832,11 +808,13 @@ def smoke_sdk_live() -> None: with tempfile.TemporaryDirectory(prefix="dsh-sdk-live-") as temporary: root = Path(temporary).resolve() - sessions = root / "sessions" + dsh_home = root / "home" + sessions = dsh_home / "sessions" marker = root / "live-api-marker.txt" session_id = "installed-wheel-live-api" + shell_tool = "pwsh" if IS_WINDOWS else "bash" create_prompt = ( - "Use the bash tool to create the file at the absolute path below with exactly one line " + f"Use the {shell_tool} tool to create the file at the absolute path below with exactly one line " f"containing {LIVE_API_SENTINEL}. Then reply with exactly {LIVE_API_SENTINEL}.\n{marker}" ) verify_prompt = ( @@ -847,7 +825,11 @@ def smoke_sdk_live() -> None: provider="deepseek-official", model="deepseek-v4-flash", cwd=str(root), - session_root=str(sessions), + dsh_home=str(dsh_home), + env={ + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", + }, api_key=api_key, base_url=base_url, request_timeout_seconds=180, @@ -876,8 +858,8 @@ def smoke_sdk_live() -> None: raise AssertionError(f"{label} turn returned {result.final_response!r}") if not marker.is_file(): raise AssertionError(f"real-model tool turn did not create {marker}") - if marker.read_bytes() != f"{LIVE_API_SENTINEL}\n".encode(): - raise AssertionError(f"real-model tool turn wrote unexpected bytes to {marker}") + if marker.read_text(encoding="utf-8").splitlines() != [LIVE_API_SENTINEL]: + raise AssertionError(f"real-model tool turn wrote unexpected text to {marker}") assert_zstd_session_log(sessions) @@ -910,18 +892,27 @@ def smoke_sdk_default(base_url: str) -> None: with tempfile.TemporaryDirectory(prefix="dsh-sdk-default-") as temporary: root = Path(temporary).resolve() - sessions = root / "sessions" + dsh_home = root / "home" + sessions = dsh_home / "sessions" with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), - session_root=str(sessions), + dsh_home=str(dsh_home), + env={ + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", + }, api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, ) as harness: result = harness.run("reply with the smoke text", session_id="default-smoke") - assert result.final_response == EXPECTED_TEXT, result.final_response + assert result.final_response == EXPECTED_TEXT, ( + f"final={result.final_response!r} finish={result.finish_reason!r} " + f"events={[event.get('type') for event in result.events]!r} " + f"turn_end={safe_turn_end(next((event.get('data', event) for event in reversed(result.events) if event.get('type') == 'turn/end'), {}))!r}" + ) assert_zstd_session_log(sessions) @@ -930,16 +921,45 @@ def smoke_sdk_custom(base_url: str, executable: Path) -> None: with tempfile.TemporaryDirectory(prefix="dsh-sdk-custom-") as temporary: root = Path(temporary).resolve() - sessions = root / "sessions" - cordis = root / "cordis.yml" - cordis.write_text(CUSTOM_CORDIS) + dsh_home = root / "home" + sessions = dsh_home / "sessions" + patch = write_profile_patch(root, "custom.patch.yml", sessions, [ + {"id": "tools", "config": {"mode": "both"}}, + { + "id": "system-prompt", + "config": { + "persona": "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}.", + }, + }, + {"id": "session-log-deepseek", "config": {"enabled": True}}, + *({"id": row_id, "disabled": True} for row_id in LEGACY_CUSTOM_DISABLED_ROWS), + {"id": "tool-bash", "disabled": True}, + {"id": "tool-pwsh", "disabled": True}, + { + "id": "tool-subagent", + "config": { + "provider": "spawn", + "toolName": "subagent", + "backgroundMode": "one-shot", + }, + }, + {"insert": [ + {"id": "code-runtime", "name": "@deepseek-ai/dsh-code-runtime-worker-thread"}, + {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"}, + {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"}, + ]}, + ]) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), - session_root=str(sessions), - cordis=str(cordis), - runtime_bin=str(executable), + dsh_bin=str(executable), + dsh_home=str(dsh_home), + patches=(str(patch),), + env={ + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", + }, api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, @@ -954,7 +974,7 @@ def smoke_sdk_custom(base_url: str, executable: Path) -> None: def smoke_sdk_minimal(base_url: str, executable: Path, update_snapshots: bool) -> None: - """Exercise the checked-in minimal composition through the packaged executable.""" + """Exercise the shipped standalone minimal profile through the packaged executable.""" from deepseek_harness import DeepSeekHarness # One mock model serves every scenario of a run, so the snapshot takes this turn's slice. @@ -963,14 +983,15 @@ def smoke_sdk_minimal(base_url: str, executable: Path, update_snapshots: bool) - root = Path(temporary).resolve() editor_path = root / "created.txt" prompt = f"{MINIMAL_PROMPT}\n{MINIMAL_EDITOR_PATH_PREFIX}{editor_path}" - sessions = root / "sessions" + dsh_home = root / "home" + sessions = dsh_home / "sessions" with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), - session_root=str(sessions), - cordis=str(MINIMAL_CORDIS), - runtime_bin=str(executable), + dsh_bin=str(executable), + dsh_home=str(dsh_home), + profile="sdk-minimal", api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, @@ -982,7 +1003,7 @@ def smoke_sdk_minimal(base_url: str, executable: Path, update_snapshots: bool) - raise AssertionError(f"minimal agent run emitted no final response: {result.events}") if editor_path.read_text() != "created by packaged editor\n": raise AssertionError(f"packaged editor wrote unexpected content: {editor_path.read_text()!r}") - assert_session_log(sessions, root, MINIMAL_TEXT, "COUNT=1", "COUNT=2 CWD=/tmp") + assert_session_log(sessions, root, MINIMAL_TEXT, "COUNT=1", "COUNT=2") files = build_minimal_snapshot_files(MockModelHandler.requests[first_request:], root) compare_snapshot_files( @@ -997,16 +1018,23 @@ def smoke_sdk_fs_search(base_url: str, executable: Path) -> None: with tempfile.TemporaryDirectory(prefix="dsh-sdk-fs-search-") as temporary: root = Path(temporary).resolve() (root / "needle.txt").write_text(f"{FS_SEARCH_MARKER}\n") - sessions = root / "sessions" - cordis = root / "cordis.yml" - cordis.write_text(FS_SEARCH_CORDIS) + dsh_home = root / "home" + sessions = dsh_home / "sessions" + patch = write_profile_patch(root, "fs-search.patch.yml", sessions, [ + {"id": "skill-filesystem", "disabled": True}, + {"id": "tool-fs-search", "config": {"sampleOverCapGlobResults": False}}, + ]) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), - session_root=str(sessions), - cordis=str(cordis), - runtime_bin=str(executable), + dsh_bin=str(executable), + dsh_home=str(dsh_home), + patches=(str(patch),), + env={ + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", + }, api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, @@ -1023,19 +1051,23 @@ def smoke_sdk_mcp(base_url: str, executable: Path | None) -> None: with tempfile.TemporaryDirectory(prefix="dsh-sdk-mcp-") as temporary: root = Path(temporary).resolve() - sessions = root / "sessions" + dsh_home = root / "home" + sessions = dsh_home / "sessions" server_script = root / "mcp_server.py" server_script.write_text(MCP_SERVER_SCRIPT) - cordis = root / "cordis.yml" - cordis.write_text(mcp_cordis(server_script)) + patch = write_mcp_patch(root, sessions, server_script) discovery_log = server_script.with_suffix(".log") with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), - session_root=str(sessions), - cordis=str(cordis), - runtime_bin=None if executable is None else str(executable), + dsh_bin=None if executable is None else str(executable), + dsh_home=str(dsh_home), + patches=(str(patch),), + env={ + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", + }, api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, @@ -1052,22 +1084,132 @@ def smoke_sdk_mcp(base_url: str, executable: Path | None) -> None: assert_session_log(sessions, root, MCP_TEXT, "mcp__fixture__add", "42") +def smoke_sdk_profile_plugin(base_url: str) -> None: + """Install an external bundle through Python's dsh command and load it in the SDK.""" + from deepseek_harness import DeepSeekHarness + + with tempfile.TemporaryDirectory(prefix="dsh-sdk-profile-plugin-") as temporary: + root = Path(temporary).resolve() + dsh_home = root / "home" + plugin = root / "plugin" + plugin.mkdir() + (plugin / "package.json").write_text(json.dumps({ + "name": "dsh-python-blackbox-plugin", + "version": "1.0.0", + "private": True, + "type": "module", + "exports": "./index.js", + "peerDependencies": {"@deepseek-ai/cordis": "*"}, + "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}, + }, indent=2)) + (plugin / "index.js").write_text( + "import { Context } from '@deepseek-ai/cordis'\n" + "export const name = 'python-sdk-blackbox-plugin'\n" + "export const inject = ['systemPrompt']\n" + "export function apply(ctx) {\n" + " if (!(ctx instanceof Context)) throw new Error('external plugin loaded a second Cordis instance')\n" + " ctx.effect(() => ctx.systemPrompt.section({\n" + " name: 'python-sdk:blackbox-plugin',\n" + " order: 10,\n" + f" text: '{PROFILE_PLUGIN_MARKER}',\n" + " }))\n" + "}\n" + ) + (plugin / "cordis.patch.yml").write_text(json.dumps([{ + "insert": [{"id": "python-sdk-blackbox-plugin", "name": "dsh-python-blackbox-plugin"}], + }], indent=2)) + + dsh = Path(sysconfig.get_path("scripts")) / ("dsh.exe" if IS_WINDOWS else "dsh") + environment = {**os.environ, "DSH_HOME": str(dsh_home)} + installed = subprocess.run( + [str(dsh), "plugin", "--profile", "sdk", "add", f"file:{plugin}"], + cwd=root, + env=environment, + text=True, + capture_output=True, + check=False, + ) + if installed.returncode != 0: + raise AssertionError( + f"Python-installed dsh could not add the external profile plugin: " + f"stdout={installed.stdout!r} stderr={installed.stderr!r}" + ) + manifest = json.loads((dsh_home / "profiles" / "sdk" / "package.json").read_text()) + if "dsh-python-blackbox-plugin" not in manifest.get("dependencies", {}): + raise AssertionError(f"dsh plugin did not record the external dependency: {manifest}") + if "dsh-python-blackbox-plugin" not in manifest["dsh"]["profile"]["bundles"]: + raise AssertionError(f"dsh plugin did not activate the external bundle: {manifest}") + + harness = DeepSeekHarness( + provider="deepseek-official", + model="smoke-model", + cwd=str(root), + dsh_home=str(dsh_home), + env={ + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", + }, + api_key="sk-keyless-smoke", + base_url=base_url, + request_timeout_seconds=60, + ) + try: + with harness: + result = harness.run(PROFILE_PLUGIN_PROMPT, session_id="profile-plugin-smoke") + except Exception as error: + raise AssertionError( + f"external profile plugin runtime failed: {harness.client._runtime_diagnostics()}" + ) from error + + assert result.final_response == PROFILE_PLUGIN_TEXT, result.final_response + assert_zstd_session_log(dsh_home / "sessions") + + def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None: """Drive and compare the advanced SDK/executable behavioral snapshot.""" from deepseek_harness import DeepSeekHarness with tempfile.TemporaryDirectory(prefix="dsh-sdk-snapshot-") as temporary: root = Path(temporary).resolve() - sessions = root / "sessions" - cordis = root / "cordis.yml" - cordis.write_text(CUSTOM_CORDIS) + dsh_home = root / "home" + sessions = dsh_home / "sessions" + patch = write_profile_patch(root, "snapshot.patch.yml", sessions, [ + {"id": "tools", "config": {"mode": "both"}}, + { + "id": "system-prompt", + "config": { + "persona": "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}.", + }, + }, + {"id": "session-log-deepseek", "config": {"enabled": True}}, + *({"id": row_id, "disabled": True} for row_id in LEGACY_CUSTOM_DISABLED_ROWS), + {"id": "tool-bash", "disabled": True}, + {"id": "tool-pwsh", "disabled": True}, + { + "id": "tool-subagent", + "config": { + "provider": "spawn", + "toolName": "subagent", + "backgroundMode": "one-shot", + }, + }, + {"insert": [ + {"id": "code-runtime", "name": "@deepseek-ai/dsh-code-runtime-worker-thread"}, + {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"}, + {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"}, + ]}, + ]) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), - session_root=str(sessions), - cordis=str(cordis), - runtime_bin=str(executable), + dsh_bin=str(executable), + dsh_home=str(dsh_home), + patches=(str(patch),), + env={ + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", + }, api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, @@ -1103,9 +1245,34 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots with tempfile.TemporaryDirectory(prefix="dsh-sdk-restart-") as temporary: root = Path(temporary).resolve() - sessions = root / "sessions" - cordis = root / "cordis.yml" - cordis.write_text(CUSTOM_CORDIS) + dsh_home = root / "home" + sessions = dsh_home / "sessions" + patch = write_profile_patch(root, "restart.patch.yml", sessions, [ + {"id": "tools", "config": {"mode": "both"}}, + { + "id": "system-prompt", + "config": { + "persona": "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}.", + }, + }, + {"id": "session-log-deepseek", "config": {"enabled": True}}, + *({"id": row_id, "disabled": True} for row_id in LEGACY_CUSTOM_DISABLED_ROWS), + {"id": "tool-bash", "disabled": True}, + {"id": "tool-pwsh", "disabled": True}, + { + "id": "tool-subagent", + "config": { + "provider": "spawn", + "toolName": "subagent", + "backgroundMode": "one-shot", + }, + }, + {"insert": [ + {"id": "code-runtime", "name": "@deepseek-ai/dsh-code-runtime-worker-thread"}, + {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"}, + {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"}, + ]}, + ]) first_request = len(MockModelHandler.requests) def run(prompt: str, session_id: str) -> "RunResult": @@ -1113,9 +1280,13 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots provider="deepseek-official", model="smoke-model", cwd=str(root), - session_root=str(sessions), - cordis=str(cordis), - runtime_bin=str(executable), + dsh_bin=str(executable), + dsh_home=str(dsh_home), + patches=(str(patch),), + env={ + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", + }, api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, @@ -1155,18 +1326,22 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots def smoke_direct(base_url: str, executable: Path) -> None: with tempfile.TemporaryDirectory(prefix="dsh-direct-") as temporary: root = Path(temporary).resolve() - sessions = root / "sessions" - cordis = root / "cordis.yml" - cordis.write_text(CUSTOM_CORDIS) + dsh_home = root / "home" + sessions = dsh_home / "sessions" + patch = write_profile_patch(root, "direct.patch.yml", sessions, []) environment = { **os.environ, - "DSH_CORDIS_CONFIG": str(cordis), - "DSH_SESSION_ROOT": str(sessions), - "DSH_CWD": str(root), + "DSH_HOME": str(dsh_home), + "DSH_PERMISSION_MODE": "danger-full-access", + "DSH_TELEMETRY_DISABLED": "1", "DEEPSEEK_API_KEY": "sk-keyless-smoke", "DEEPSEEK_BASE_URL": base_url, } - peer = RuntimePeer([str(executable)], root, environment) + peer = RuntimePeer( + [str(executable), "--profile", "sdk", "--patch", str(patch)], + root, + environment, + ) try: peer.send({"jsonrpc": "2.0", "id": "initialize", "method": "initialize", "params": {"cwd": str(root), "provider": "deepseek-official", "model": "smoke-model"}}) peer.read_until(lambda message: message.get("id") == "initialize") @@ -1332,9 +1507,9 @@ def build_minimal_snapshot_files( Every assembled system prompt, advertised tool schema, and system or user message is kept verbatim: they carry what the deployment actually shows the model, so a plugin that contributes an unintended system section or user message cannot pass unnoticed. - Assistant and tool payloads keep only their call identity, and the dynamic - runtime-context snapshot is dropped, because their text differs across the platforms - this expected output must replay on. + Assistant and tool payloads keep only their call identity because their text differs + across the platforms this expected output must replay on. The shipped profile omits + dynamic runtime context, so every message it emits is compared. """ snapshot = [] for body in requests: @@ -1346,21 +1521,11 @@ def build_minimal_snapshot_files( "messages": [ minimal_snapshot_message(message, cwd) for message in messages - if not is_runtime_context_message(message) ], }) return {"model-visible.json": json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n"} -def is_runtime_context_message(message: object) -> bool: - """Identify the agent loop's dynamic runtime-context snapshot, current or cleared.""" - return ( - isinstance(message, dict) - and message.get("role") == "user" - and message_text(message.get("content")).startswith(RUNTIME_CONTEXT_PREFIX) - ) - - def minimal_snapshot_message(message: object, cwd: Path) -> dict[str, object]: """Reduce one model-visible message to its stable, behavior-carrying parts.""" if not isinstance(message, dict): @@ -1419,7 +1584,6 @@ def build_snapshot_files( {"method": notification.method, "payload": notification.payload} for notification in result.notifications ], - "session_root": result.session_root, } normalized_result = normalize_snapshot_value(result_value, replacements) files = { @@ -1461,7 +1625,6 @@ def build_restart_snapshot_files( "finish_reason": result.finish_reason, "eventTypes": [event.get("type") for event in result.events], "notificationMethods": [notification.method for notification in result.notifications], - "session_root": result.session_root, } for result in (first, second) ] @@ -1611,7 +1774,7 @@ def compare_snapshot_files( if update: directory.mkdir(parents=True, exist_ok=True) for name, content in files.items(): - (directory / name).write_text(content, encoding="utf-8") + (directory / name).write_text(content, encoding="utf-8", newline="\n") print(f"smoke-python-runtime: updated snapshots in {directory}") existing = { diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/result.json b/scripts/snapshots/python-sdk-single-exe/advanced/result.json index 0889fd6b9f..c9dc0735ea 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced/result.json @@ -4,7 +4,7 @@ "events": [ { "type": "agent/inbox/spliced", - "seq": 0, + "seq": 3, "time": 0, "data": { "target": "next-turn", @@ -28,7 +28,7 @@ }, { "type": "turn/start", - "seq": 1, + "seq": 4, "time": 0, "data": { "turn": 1 @@ -36,7 +36,7 @@ }, { "type": "agent/inbox/spliced", - "seq": 2, + "seq": 5, "time": 0, "data": { "target": "next-turn", @@ -47,7 +47,7 @@ }, { "type": "step/start", - "seq": 3, + "seq": 6, "time": 0, "data": { "turn": 1, @@ -56,7 +56,7 @@ }, { "type": "user/message", - "seq": 4, + "seq": 7, "time": 0, "data": { "content": [ @@ -73,14 +73,45 @@ }, "surfaceOp": "append" }, + { + "type": "user/message", + "seq": 8, + "time": 0, + "data": { + "content": [ + { + "type": "text", + "text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)." + } + ], + "source": { + "kind": "plugin", + "plugin": "@deepseek-ai/dsh-system-prompt", + "form": "snapshot", + "sections": [ + { + "name": "sandbox:policy", + "text": "Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations." + }, + { + "name": "approval:policy", + "text": "Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)." + } + ] + }, + "role": "user", + "id": "{{messageId}}" + }, + "surfaceOp": "append" + }, { "type": "session/title", - "seq": 5, + "seq": 9, "time": 0, "data": { "title": "Run the advanced packaged-runtime snapsh", "messageSeqs": [ - 4 + 7 ], "source": { "kind": "fallback" @@ -89,7 +120,7 @@ }, { "type": "request/header", - "seq": 6, + "seq": 10, "time": 0, "data": { "header": { @@ -125,7 +156,7 @@ }, { "type": "request/context", - "seq": 7, + "seq": 11, "time": 0, "data": { "provider": "deepseek-official", @@ -135,16 +166,16 @@ }, { "type": "session-log-deepseek/delivery-accepted", - "seq": 8, + "seq": 12, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 7 + "throughSeq": 11 } }, { "type": "assistant/chunk", - "seq": 9, + "seq": 13, "time": 0, "data": { "turn": 1, @@ -158,7 +189,7 @@ }, { "type": "assistant/chunk", - "seq": 10, + "seq": 14, "time": 0, "data": { "turn": 1, @@ -174,7 +205,7 @@ }, { "type": "assistant/chunk", - "seq": 11, + "seq": 15, "time": 0, "data": { "turn": 1, @@ -193,7 +224,7 @@ }, { "type": "assistant/chunk", - "seq": 12, + "seq": 16, "time": 0, "data": { "turn": 1, @@ -209,7 +240,7 @@ }, { "type": "assistant/chunk", - "seq": 13, + "seq": 17, "time": 0, "data": { "turn": 1, @@ -224,7 +255,7 @@ }, { "type": "assistant/message", - "seq": 14, + "seq": 18, "time": 0, "data": { "turn": 1, @@ -252,17 +283,17 @@ } }, "sourceEventSeqs": [ - 9, - 10, - 11, - 12, - 13 + 13, + 14, + 15, + 16, + 17 ], "surfaceOp": "append" }, { "type": "tool/call", - "seq": 15, + "seq": 19, "time": 0, "data": { "turn": 1, @@ -274,7 +305,7 @@ }, { "type": "tool/result", - "seq": 16, + "seq": 20, "time": 0, "data": { "turn": 1, @@ -306,13 +337,13 @@ } }, "sourceEventSeqs": [ - 15 + 19 ], "surfaceOp": "append" }, { "type": "step/end", - "seq": 17, + "seq": 21, "time": 0, "data": { "turn": 1, @@ -321,7 +352,7 @@ }, { "type": "step/start", - "seq": 18, + "seq": 22, "time": 0, "data": { "turn": 1, @@ -330,16 +361,16 @@ }, { "type": "session-log-deepseek/delivery-accepted", - "seq": 19, + "seq": 23, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 18 + "throughSeq": 22 } }, { "type": "assistant/chunk", - "seq": 20, + "seq": 24, "time": 0, "data": { "turn": 1, @@ -353,7 +384,7 @@ }, { "type": "assistant/chunk", - "seq": 21, + "seq": 25, "time": 0, "data": { "turn": 1, @@ -369,7 +400,7 @@ }, { "type": "assistant/chunk", - "seq": 22, + "seq": 26, "time": 0, "data": { "turn": 1, @@ -388,7 +419,7 @@ }, { "type": "assistant/chunk", - "seq": 23, + "seq": 27, "time": 0, "data": { "turn": 1, @@ -404,7 +435,7 @@ }, { "type": "assistant/chunk", - "seq": 24, + "seq": 28, "time": 0, "data": { "turn": 1, @@ -419,7 +450,7 @@ }, { "type": "assistant/message", - "seq": 25, + "seq": 29, "time": 0, "data": { "turn": 1, @@ -447,17 +478,17 @@ } }, "sourceEventSeqs": [ - 20, - 21, - 22, - 23, - 24 + 24, + 25, + 26, + 27, + 28 ], "surfaceOp": "append" }, { "type": "tool/call", - "seq": 26, + "seq": 30, "time": 0, "data": { "turn": 1, @@ -469,7 +500,7 @@ }, { "type": "tool/result", - "seq": 27, + "seq": 31, "time": 0, "data": { "turn": 1, @@ -502,13 +533,13 @@ } }, "sourceEventSeqs": [ - 26 + 30 ], "surfaceOp": "append" }, { "type": "step/end", - "seq": 28, + "seq": 32, "time": 0, "data": { "turn": 1, @@ -517,7 +548,7 @@ }, { "type": "step/start", - "seq": 29, + "seq": 33, "time": 0, "data": { "turn": 1, @@ -526,7 +557,7 @@ }, { "type": "request/header", - "seq": 30, + "seq": 34, "time": 0, "data": { "header": { @@ -563,16 +594,16 @@ }, { "type": "session-log-deepseek/delivery-accepted", - "seq": 31, + "seq": 35, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 30 + "throughSeq": 34 } }, { "type": "assistant/chunk", - "seq": 32, + "seq": 36, "time": 0, "data": { "turn": 1, @@ -586,7 +617,7 @@ }, { "type": "assistant/chunk", - "seq": 33, + "seq": 37, "time": 0, "data": { "turn": 1, @@ -602,7 +633,7 @@ }, { "type": "assistant/chunk", - "seq": 34, + "seq": 38, "time": 0, "data": { "turn": 1, @@ -621,7 +652,7 @@ }, { "type": "assistant/chunk", - "seq": 35, + "seq": 39, "time": 0, "data": { "turn": 1, @@ -637,7 +668,7 @@ }, { "type": "assistant/chunk", - "seq": 36, + "seq": 40, "time": 0, "data": { "turn": 1, @@ -652,7 +683,7 @@ }, { "type": "assistant/message", - "seq": 37, + "seq": 41, "time": 0, "data": { "turn": 1, @@ -680,17 +711,17 @@ } }, "sourceEventSeqs": [ - 32, - 33, - 34, - 35, - 36 + 36, + 37, + 38, + 39, + 40 ], "surfaceOp": "append" }, { "type": "tool/call", - "seq": 38, + "seq": 42, "time": 0, "data": { "turn": 1, @@ -702,7 +733,7 @@ }, { "type": "tool/code-dispatch-start", - "seq": 39, + "seq": 43, "time": 0, "data": { "rootCallId": "advanced-code", @@ -716,7 +747,7 @@ }, { "type": "tool/code-dispatch", - "seq": 40, + "seq": 44, "time": 0, "data": { "rootCallId": "advanced-code", @@ -737,7 +768,7 @@ }, { "type": "tool/result", - "seq": 41, + "seq": 45, "time": 0, "data": { "turn": 1, @@ -765,13 +796,13 @@ } }, "sourceEventSeqs": [ - 38 + 42 ], "surfaceOp": "append" }, { "type": "step/end", - "seq": 42, + "seq": 46, "time": 0, "data": { "turn": 1, @@ -780,7 +811,7 @@ }, { "type": "step/start", - "seq": 43, + "seq": 47, "time": 0, "data": { "turn": 1, @@ -789,16 +820,16 @@ }, { "type": "session-log-deepseek/delivery-accepted", - "seq": 44, + "seq": 48, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 43 + "throughSeq": 47 } }, { "type": "assistant/chunk", - "seq": 45, + "seq": 49, "time": 0, "data": { "turn": 1, @@ -812,7 +843,7 @@ }, { "type": "assistant/chunk", - "seq": 46, + "seq": 50, "time": 0, "data": { "turn": 1, @@ -828,7 +859,7 @@ }, { "type": "assistant/chunk", - "seq": 47, + "seq": 51, "time": 0, "data": { "turn": 1, @@ -847,7 +878,7 @@ }, { "type": "assistant/chunk", - "seq": 48, + "seq": 52, "time": 0, "data": { "turn": 1, @@ -863,7 +894,7 @@ }, { "type": "assistant/chunk", - "seq": 49, + "seq": 53, "time": 0, "data": { "turn": 1, @@ -878,7 +909,7 @@ }, { "type": "assistant/message", - "seq": 50, + "seq": 54, "time": 0, "data": { "turn": 1, @@ -906,17 +937,17 @@ } }, "sourceEventSeqs": [ - 45, - 46, - 47, - 48, - 49 + 49, + 50, + 51, + 52, + 53 ], "surfaceOp": "append" }, { "type": "tool/call", - "seq": 51, + "seq": 55, "time": 0, "data": { "turn": 1, @@ -928,7 +959,7 @@ }, { "type": "tool/result", - "seq": 52, + "seq": 56, "time": 0, "data": { "turn": 1, @@ -956,13 +987,13 @@ } }, "sourceEventSeqs": [ - 51 + 55 ], "surfaceOp": "append" }, { "type": "step/end", - "seq": 53, + "seq": 57, "time": 0, "data": { "turn": 1, @@ -971,7 +1002,7 @@ }, { "type": "step/start", - "seq": 54, + "seq": 58, "time": 0, "data": { "turn": 1, @@ -980,16 +1011,16 @@ }, { "type": "session-log-deepseek/delivery-accepted", - "seq": 55, + "seq": 59, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 54 + "throughSeq": 58 } }, { "type": "assistant/chunk", - "seq": 56, + "seq": 60, "time": 0, "data": { "turn": 1, @@ -1003,7 +1034,7 @@ }, { "type": "assistant/chunk", - "seq": 57, + "seq": 61, "time": 0, "data": { "turn": 1, @@ -1019,7 +1050,7 @@ }, { "type": "assistant/chunk", - "seq": 58, + "seq": 62, "time": 0, "data": { "turn": 1, @@ -1038,7 +1069,7 @@ }, { "type": "assistant/chunk", - "seq": 59, + "seq": 63, "time": 0, "data": { "turn": 1, @@ -1054,7 +1085,7 @@ }, { "type": "assistant/chunk", - "seq": 60, + "seq": 64, "time": 0, "data": { "turn": 1, @@ -1069,7 +1100,7 @@ }, { "type": "assistant/message", - "seq": 61, + "seq": 65, "time": 0, "data": { "turn": 1, @@ -1097,17 +1128,17 @@ } }, "sourceEventSeqs": [ - 56, - 57, - 58, - 59, - 60 + 60, + 61, + 62, + 63, + 64 ], "surfaceOp": "append" }, { "type": "tool/call", - "seq": 62, + "seq": 66, "time": 0, "data": { "turn": 1, @@ -1119,7 +1150,7 @@ }, { "type": "tool-workflow/run-start", - "seq": 63, + "seq": 67, "time": 0, "data": { "runId": "{{workflow-run}}", @@ -1128,7 +1159,7 @@ }, { "type": "tool-workflow/agent-start", - "seq": 64, + "seq": 68, "time": 0, "data": { "runId": "{{workflow-run}}", @@ -1140,7 +1171,7 @@ }, { "type": "tool-workflow/agent-end", - "seq": 65, + "seq": 69, "time": 0, "data": { "runId": "{{workflow-run}}", @@ -1150,7 +1181,7 @@ }, { "type": "tool-workflow/run-end", - "seq": 66, + "seq": 70, "time": 0, "data": { "runId": "{{workflow-run}}", @@ -1159,7 +1190,7 @@ }, { "type": "tool/result", - "seq": 67, + "seq": 71, "time": 0, "data": { "turn": 1, @@ -1187,13 +1218,13 @@ } }, "sourceEventSeqs": [ - 62 + 66 ], "surfaceOp": "append" }, { "type": "step/end", - "seq": 68, + "seq": 72, "time": 0, "data": { "turn": 1, @@ -1202,7 +1233,7 @@ }, { "type": "step/start", - "seq": 69, + "seq": 73, "time": 0, "data": { "turn": 1, @@ -1211,16 +1242,16 @@ }, { "type": "session-log-deepseek/delivery-accepted", - "seq": 70, + "seq": 74, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 69 + "throughSeq": 73 } }, { "type": "assistant/chunk", - "seq": 71, + "seq": 75, "time": 0, "data": { "turn": 1, @@ -1234,7 +1265,7 @@ }, { "type": "assistant/chunk", - "seq": 72, + "seq": 76, "time": 0, "data": { "turn": 1, @@ -1250,7 +1281,7 @@ }, { "type": "assistant/chunk", - "seq": 73, + "seq": 77, "time": 0, "data": { "turn": 1, @@ -1269,7 +1300,7 @@ }, { "type": "assistant/chunk", - "seq": 74, + "seq": 78, "time": 0, "data": { "turn": 1, @@ -1285,7 +1316,7 @@ }, { "type": "assistant/chunk", - "seq": 75, + "seq": 79, "time": 0, "data": { "turn": 1, @@ -1300,7 +1331,7 @@ }, { "type": "assistant/message", - "seq": 76, + "seq": 80, "time": 0, "data": { "turn": 1, @@ -1328,17 +1359,17 @@ } }, "sourceEventSeqs": [ - 71, - 72, - 73, - 74, - 75 + 75, + 76, + 77, + 78, + 79 ], "surfaceOp": "append" }, { "type": "tool/call", - "seq": 77, + "seq": 81, "time": 0, "data": { "turn": 1, @@ -1350,7 +1381,7 @@ }, { "type": "tool/result", - "seq": 78, + "seq": 82, "time": 0, "data": { "turn": 1, @@ -1378,13 +1409,13 @@ } }, "sourceEventSeqs": [ - 77 + 81 ], "surfaceOp": "append" }, { "type": "step/end", - "seq": 79, + "seq": 83, "time": 0, "data": { "turn": 1, @@ -1393,7 +1424,7 @@ }, { "type": "step/start", - "seq": 80, + "seq": 84, "time": 0, "data": { "turn": 1, @@ -1402,7 +1433,7 @@ }, { "type": "request/header", - "seq": 81, + "seq": 85, "time": 0, "data": { "header": { @@ -1438,16 +1469,16 @@ }, { "type": "session-log-deepseek/delivery-accepted", - "seq": 82, + "seq": 86, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 81 + "throughSeq": 85 } }, { "type": "assistant/chunk", - "seq": 83, + "seq": 87, "time": 0, "data": { "turn": 1, @@ -1461,7 +1492,7 @@ }, { "type": "assistant/chunk", - "seq": 84, + "seq": 88, "time": 0, "data": { "turn": 1, @@ -1475,7 +1506,7 @@ }, { "type": "assistant/chunk", - "seq": 85, + "seq": 89, "time": 0, "data": { "turn": 1, @@ -1492,7 +1523,7 @@ }, { "type": "assistant/chunk", - "seq": 86, + "seq": 90, "time": 0, "data": { "turn": 1, @@ -1508,7 +1539,7 @@ }, { "type": "assistant/chunk", - "seq": 87, + "seq": 91, "time": 0, "data": { "turn": 1, @@ -1523,7 +1554,7 @@ }, { "type": "assistant/message", - "seq": 88, + "seq": 92, "time": 0, "data": { "turn": 1, @@ -1549,17 +1580,17 @@ } }, "sourceEventSeqs": [ - 83, - 84, - 85, - 86, - 87 + 87, + 88, + 89, + 90, + 91 ], "surfaceOp": "append" }, { "type": "step/end", - "seq": 89, + "seq": 93, "time": 0, "data": { "turn": 1, @@ -1568,7 +1599,7 @@ }, { "type": "turn/end", - "seq": 90, + "seq": 94, "time": 0, "data": { "turn": 1, @@ -1585,7 +1616,7 @@ "sessionId": "{{parent}}", "event": { "type": "agent/inbox/spliced", - "seq": 0, + "seq": 3, "time": 0, "data": { "target": "next-turn", @@ -1622,7 +1653,7 @@ "sessionId": "{{parent}}", "event": { "type": "turn/start", - "seq": 1, + "seq": 4, "time": 0, "data": { "turn": 1 @@ -1636,7 +1667,7 @@ "sessionId": "{{parent}}", "event": { "type": "agent/inbox/spliced", - "seq": 2, + "seq": 5, "time": 0, "data": { "target": "next-turn", @@ -1653,7 +1684,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/start", - "seq": 3, + "seq": 6, "time": 0, "data": { "turn": 1, @@ -1668,7 +1699,7 @@ "sessionId": "{{parent}}", "event": { "type": "user/message", - "seq": 4, + "seq": 7, "time": 0, "data": { "content": [ @@ -1687,18 +1718,55 @@ } } }, + { + "method": "session.event", + "payload": { + "sessionId": "{{parent}}", + "event": { + "type": "user/message", + "seq": 8, + "time": 0, + "data": { + "content": [ + { + "type": "text", + "text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)." + } + ], + "source": { + "kind": "plugin", + "plugin": "@deepseek-ai/dsh-system-prompt", + "form": "snapshot", + "sections": [ + { + "name": "sandbox:policy", + "text": "Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations." + }, + { + "name": "approval:policy", + "text": "Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)." + } + ] + }, + "role": "user", + "id": "{{messageId}}" + }, + "surfaceOp": "append" + } + } + }, { "method": "session.event", "payload": { "sessionId": "{{parent}}", "event": { "type": "session/title", - "seq": 5, + "seq": 9, "time": 0, "data": { "title": "Run the advanced packaged-runtime snapsh", "messageSeqs": [ - 4 + 7 ], "source": { "kind": "fallback" @@ -1713,7 +1781,7 @@ "sessionId": "{{parent}}", "event": { "type": "request/header", - "seq": 6, + "seq": 10, "time": 0, "data": { "header": { @@ -1755,7 +1823,7 @@ "sessionId": "{{parent}}", "event": { "type": "request/context", - "seq": 7, + "seq": 11, "time": 0, "data": { "provider": "deepseek-official", @@ -1771,11 +1839,11 @@ "sessionId": "{{parent}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 8, + "seq": 12, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 7 + "throughSeq": 11 } } } @@ -1786,7 +1854,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 9, + "seq": 13, "time": 0, "data": { "turn": 1, @@ -1806,7 +1874,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 10, + "seq": 14, "time": 0, "data": { "turn": 1, @@ -1828,7 +1896,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 11, + "seq": 15, "time": 0, "data": { "turn": 1, @@ -1853,7 +1921,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 12, + "seq": 16, "time": 0, "data": { "turn": 1, @@ -1875,7 +1943,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 13, + "seq": 17, "time": 0, "data": { "turn": 1, @@ -1896,7 +1964,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/message", - "seq": 14, + "seq": 18, "time": 0, "data": { "turn": 1, @@ -1924,11 +1992,11 @@ } }, "sourceEventSeqs": [ - 9, - 10, - 11, - 12, - 13 + 13, + 14, + 15, + 16, + 17 ], "surfaceOp": "append" } @@ -1940,7 +2008,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/call", - "seq": 15, + "seq": 19, "time": 0, "data": { "turn": 1, @@ -1958,7 +2026,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/result", - "seq": 16, + "seq": 20, "time": 0, "data": { "turn": 1, @@ -1990,7 +2058,7 @@ } }, "sourceEventSeqs": [ - 15 + 19 ], "surfaceOp": "append" } @@ -2002,7 +2070,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/end", - "seq": 17, + "seq": 21, "time": 0, "data": { "turn": 1, @@ -2017,7 +2085,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/start", - "seq": 18, + "seq": 22, "time": 0, "data": { "turn": 1, @@ -2032,11 +2100,11 @@ "sessionId": "{{parent}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 19, + "seq": 23, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 18 + "throughSeq": 22 } } } @@ -2047,7 +2115,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 20, + "seq": 24, "time": 0, "data": { "turn": 1, @@ -2067,7 +2135,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 21, + "seq": 25, "time": 0, "data": { "turn": 1, @@ -2089,7 +2157,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 22, + "seq": 26, "time": 0, "data": { "turn": 1, @@ -2114,7 +2182,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 23, + "seq": 27, "time": 0, "data": { "turn": 1, @@ -2136,7 +2204,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 24, + "seq": 28, "time": 0, "data": { "turn": 1, @@ -2157,7 +2225,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/message", - "seq": 25, + "seq": 29, "time": 0, "data": { "turn": 1, @@ -2185,11 +2253,11 @@ } }, "sourceEventSeqs": [ - 20, - 21, - 22, - 23, - 24 + 24, + 25, + 26, + 27, + 28 ], "surfaceOp": "append" } @@ -2201,7 +2269,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/call", - "seq": 26, + "seq": 30, "time": 0, "data": { "turn": 1, @@ -2219,7 +2287,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/result", - "seq": 27, + "seq": 31, "time": 0, "data": { "turn": 1, @@ -2252,7 +2320,7 @@ } }, "sourceEventSeqs": [ - 26 + 30 ], "surfaceOp": "append" } @@ -2264,7 +2332,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/end", - "seq": 28, + "seq": 32, "time": 0, "data": { "turn": 1, @@ -2279,7 +2347,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/start", - "seq": 29, + "seq": 33, "time": 0, "data": { "turn": 1, @@ -2294,7 +2362,7 @@ "sessionId": "{{parent}}", "event": { "type": "request/header", - "seq": 30, + "seq": 34, "time": 0, "data": { "header": { @@ -2337,11 +2405,11 @@ "sessionId": "{{parent}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 31, + "seq": 35, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 30 + "throughSeq": 34 } } } @@ -2352,7 +2420,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 32, + "seq": 36, "time": 0, "data": { "turn": 1, @@ -2372,7 +2440,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 33, + "seq": 37, "time": 0, "data": { "turn": 1, @@ -2394,7 +2462,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 34, + "seq": 38, "time": 0, "data": { "turn": 1, @@ -2419,7 +2487,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 35, + "seq": 39, "time": 0, "data": { "turn": 1, @@ -2441,7 +2509,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 36, + "seq": 40, "time": 0, "data": { "turn": 1, @@ -2462,7 +2530,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/message", - "seq": 37, + "seq": 41, "time": 0, "data": { "turn": 1, @@ -2490,11 +2558,11 @@ } }, "sourceEventSeqs": [ - 32, - 33, - 34, - 35, - 36 + 36, + 37, + 38, + 39, + 40 ], "surfaceOp": "append" } @@ -2506,7 +2574,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/call", - "seq": 38, + "seq": 42, "time": 0, "data": { "turn": 1, @@ -2524,7 +2592,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/code-dispatch-start", - "seq": 39, + "seq": 43, "time": 0, "data": { "rootCallId": "advanced-code", @@ -2544,7 +2612,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/code-dispatch", - "seq": 40, + "seq": 44, "time": 0, "data": { "rootCallId": "advanced-code", @@ -2571,7 +2639,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/result", - "seq": 41, + "seq": 45, "time": 0, "data": { "turn": 1, @@ -2599,7 +2667,7 @@ } }, "sourceEventSeqs": [ - 38 + 42 ], "surfaceOp": "append" } @@ -2611,7 +2679,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/end", - "seq": 42, + "seq": 46, "time": 0, "data": { "turn": 1, @@ -2626,7 +2694,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/start", - "seq": 43, + "seq": 47, "time": 0, "data": { "turn": 1, @@ -2641,11 +2709,11 @@ "sessionId": "{{parent}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 44, + "seq": 48, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 43 + "throughSeq": 47 } } } @@ -2656,7 +2724,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 45, + "seq": 49, "time": 0, "data": { "turn": 1, @@ -2676,7 +2744,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 46, + "seq": 50, "time": 0, "data": { "turn": 1, @@ -2698,7 +2766,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 47, + "seq": 51, "time": 0, "data": { "turn": 1, @@ -2723,7 +2791,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 48, + "seq": 52, "time": 0, "data": { "turn": 1, @@ -2745,7 +2813,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 49, + "seq": 53, "time": 0, "data": { "turn": 1, @@ -2766,7 +2834,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/message", - "seq": 50, + "seq": 54, "time": 0, "data": { "turn": 1, @@ -2794,11 +2862,11 @@ } }, "sourceEventSeqs": [ - 45, - 46, - 47, - 48, - 49 + 49, + 50, + 51, + 52, + 53 ], "surfaceOp": "append" } @@ -2810,7 +2878,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/call", - "seq": 51, + "seq": 55, "time": 0, "data": { "turn": 1, @@ -2829,13 +2897,27 @@ "childSessionId": "{{child-1}}" } }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "permission/preset", + "seq": 2, + "time": 0, + "data": { + "preset": "danger-full-access" + } + } + } + }, { "method": "session.event", "payload": { "sessionId": "{{child-1}}", "event": { "type": "agent/inbox/spliced", - "seq": 0, + "seq": 3, "time": 0, "data": { "target": "next-turn", @@ -2872,7 +2954,7 @@ "sessionId": "{{child-1}}", "event": { "type": "turn/start", - "seq": 1, + "seq": 4, "time": 0, "data": { "turn": 1 @@ -2886,7 +2968,7 @@ "sessionId": "{{child-1}}", "event": { "type": "agent/inbox/spliced", - "seq": 2, + "seq": 5, "time": 0, "data": { "target": "next-turn", @@ -2903,10 +2985,10 @@ "sessionId": "{{child-1}}", "event": { "type": "subagent/descriptor", - "seq": 3, + "seq": 6, "time": 0, "data": { - "version": 2, + "version": 3, "mode": "one-shot", "provider": "spawn", "label": "Check direct child" @@ -2920,7 +3002,7 @@ "sessionId": "{{child-1}}", "event": { "type": "step/start", - "seq": 4, + "seq": 7, "time": 0, "data": { "turn": 1, @@ -2935,7 +3017,7 @@ "sessionId": "{{child-1}}", "event": { "type": "user/message", - "seq": 5, + "seq": 8, "time": 0, "data": { "content": [ @@ -2960,13 +3042,13 @@ "sessionId": "{{child-1}}", "event": { "type": "user/message", - "seq": 6, + "seq": 9, "time": 0, "data": { "content": [ { "type": "text", - "text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it." + "text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it." } ], "source": { @@ -2974,6 +3056,14 @@ "plugin": "@deepseek-ai/dsh-system-prompt", "form": "snapshot", "sections": [ + { + "name": "sandbox:policy", + "text": "Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations." + }, + { + "name": "approval:policy", + "text": "Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)." + }, { "name": "subagent:delegation", "text": "You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it." @@ -2993,12 +3083,12 @@ "sessionId": "{{child-1}}", "event": { "type": "session/title", - "seq": 7, + "seq": 10, "time": 0, "data": { "title": "Reply with exactly DIRECT_CHILD_OK and", "messageSeqs": [ - 5 + 8 ], "source": { "kind": "fallback" @@ -3013,18 +3103,17 @@ "sessionId": "{{child-1}}", "event": { "type": "request/header", - "seq": 8, + "seq": 11, "time": 0, "data": { "header": { "config": { "provider": "deepseek-official", "model": "smoke-model", - "maxTokens": 256000, - "reasoningEffort": "high" + "reasoningEffort": "high", + "maxTokens": 256000 }, "adapterDefaults": { - "reasoningEffort": true, "maxTokens": true }, "system": "{{system}}", @@ -3056,7 +3145,7 @@ "sessionId": "{{child-1}}", "event": { "type": "request/context", - "seq": 9, + "seq": 12, "time": 0, "data": { "provider": "deepseek-official", @@ -3072,11 +3161,11 @@ "sessionId": "{{child-1}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 10, + "seq": 13, "time": 0, "data": { "sessionId": "{{child-1}}", - "throughSeq": 9 + "throughSeq": 12 } } } @@ -3087,7 +3176,7 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/chunk", - "seq": 11, + "seq": 14, "time": 0, "data": { "turn": 1, @@ -3107,7 +3196,7 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/chunk", - "seq": 12, + "seq": 15, "time": 0, "data": { "turn": 1, @@ -3127,7 +3216,7 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/chunk", - "seq": 13, + "seq": 16, "time": 0, "data": { "turn": 1, @@ -3150,7 +3239,7 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/chunk", - "seq": 14, + "seq": 17, "time": 0, "data": { "turn": 1, @@ -3172,7 +3261,7 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/chunk", - "seq": 15, + "seq": 18, "time": 0, "data": { "turn": 1, @@ -3193,7 +3282,7 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/message", - "seq": 16, + "seq": 19, "time": 0, "data": { "turn": 1, @@ -3219,11 +3308,11 @@ } }, "sourceEventSeqs": [ - 11, - 12, - 13, 14, - 15 + 15, + 16, + 17, + 18 ], "surfaceOp": "append" } @@ -3235,7 +3324,7 @@ "sessionId": "{{child-1}}", "event": { "type": "step/end", - "seq": 17, + "seq": 20, "time": 0, "data": { "turn": 1, @@ -3250,7 +3339,7 @@ "sessionId": "{{child-1}}", "event": { "type": "turn/end", - "seq": 18, + "seq": 21, "time": 0, "data": { "turn": 1, @@ -3291,7 +3380,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/result", - "seq": 52, + "seq": 56, "time": 0, "data": { "turn": 1, @@ -3319,7 +3408,7 @@ } }, "sourceEventSeqs": [ - 51 + 55 ], "surfaceOp": "append" } @@ -3331,7 +3420,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/end", - "seq": 53, + "seq": 57, "time": 0, "data": { "turn": 1, @@ -3346,7 +3435,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/start", - "seq": 54, + "seq": 58, "time": 0, "data": { "turn": 1, @@ -3361,11 +3450,11 @@ "sessionId": "{{parent}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 55, + "seq": 59, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 54 + "throughSeq": 58 } } } @@ -3376,7 +3465,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 56, + "seq": 60, "time": 0, "data": { "turn": 1, @@ -3396,7 +3485,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 57, + "seq": 61, "time": 0, "data": { "turn": 1, @@ -3418,7 +3507,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 58, + "seq": 62, "time": 0, "data": { "turn": 1, @@ -3443,7 +3532,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 59, + "seq": 63, "time": 0, "data": { "turn": 1, @@ -3465,7 +3554,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 60, + "seq": 64, "time": 0, "data": { "turn": 1, @@ -3486,7 +3575,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/message", - "seq": 61, + "seq": 65, "time": 0, "data": { "turn": 1, @@ -3514,11 +3603,11 @@ } }, "sourceEventSeqs": [ - 56, - 57, - 58, - 59, - 60 + 60, + 61, + 62, + 63, + 64 ], "surfaceOp": "append" } @@ -3530,7 +3619,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/call", - "seq": 62, + "seq": 66, "time": 0, "data": { "turn": 1, @@ -3548,7 +3637,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool-workflow/run-start", - "seq": 63, + "seq": 67, "time": 0, "data": { "runId": "{{workflow-run}}", @@ -3564,13 +3653,27 @@ "childSessionId": "{{child-2}}" } }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "permission/preset", + "seq": 2, + "time": 0, + "data": { + "preset": "danger-full-access" + } + } + } + }, { "method": "session.event", "payload": { "sessionId": "{{child-2}}", "event": { "type": "agent/inbox/spliced", - "seq": 0, + "seq": 3, "time": 0, "data": { "target": "next-turn", @@ -3607,7 +3710,7 @@ "sessionId": "{{child-2}}", "event": { "type": "turn/start", - "seq": 1, + "seq": 4, "time": 0, "data": { "turn": 1 @@ -3621,7 +3724,7 @@ "sessionId": "{{child-2}}", "event": { "type": "agent/inbox/spliced", - "seq": 2, + "seq": 5, "time": 0, "data": { "target": "next-turn", @@ -3632,16 +3735,34 @@ } } }, + { + "method": "session.event", + "payload": { + "sessionId": "{{parent}}", + "event": { + "type": "tool-workflow/agent-start", + "seq": 68, + "time": 0, + "data": { + "runId": "{{workflow-run}}", + "seq": 1, + "label": "workflow-child", + "phase": "Delegate", + "childId": "{{child-2}}" + } + } + } + }, { "method": "session.event", "payload": { "sessionId": "{{child-2}}", "event": { "type": "subagent/descriptor", - "seq": 3, + "seq": 6, "time": 0, "data": { - "version": 2, + "version": 3, "mode": "one-shot", "provider": "spawn" } @@ -3654,7 +3775,7 @@ "sessionId": "{{child-2}}", "event": { "type": "step/start", - "seq": 4, + "seq": 7, "time": 0, "data": { "turn": 1, @@ -3669,7 +3790,7 @@ "sessionId": "{{child-2}}", "event": { "type": "user/message", - "seq": 5, + "seq": 8, "time": 0, "data": { "content": [ @@ -3694,13 +3815,13 @@ "sessionId": "{{child-2}}", "event": { "type": "user/message", - "seq": 6, + "seq": 9, "time": 0, "data": { "content": [ { "type": "text", - "text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it." + "text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it." } ], "source": { @@ -3708,6 +3829,14 @@ "plugin": "@deepseek-ai/dsh-system-prompt", "form": "snapshot", "sections": [ + { + "name": "sandbox:policy", + "text": "Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations." + }, + { + "name": "approval:policy", + "text": "Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)." + }, { "name": "subagent:delegation", "text": "You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it." @@ -3727,12 +3856,12 @@ "sessionId": "{{child-2}}", "event": { "type": "session/title", - "seq": 7, + "seq": 10, "time": 0, "data": { "title": "Reply with exactly WORKFLOW_CHILD_OK and", "messageSeqs": [ - 5 + 8 ], "source": { "kind": "fallback" @@ -3747,18 +3876,17 @@ "sessionId": "{{child-2}}", "event": { "type": "request/header", - "seq": 8, + "seq": 11, "time": 0, "data": { "header": { "config": { "provider": "deepseek-official", "model": "smoke-model", - "maxTokens": 256000, - "reasoningEffort": "high" + "reasoningEffort": "high", + "maxTokens": 256000 }, "adapterDefaults": { - "reasoningEffort": true, "maxTokens": true }, "system": "{{system}}", @@ -3790,7 +3918,7 @@ "sessionId": "{{child-2}}", "event": { "type": "request/context", - "seq": 9, + "seq": 12, "time": 0, "data": { "provider": "deepseek-official", @@ -3800,35 +3928,17 @@ } } }, - { - "method": "session.event", - "payload": { - "sessionId": "{{parent}}", - "event": { - "type": "tool-workflow/agent-start", - "seq": 64, - "time": 0, - "data": { - "runId": "{{workflow-run}}", - "seq": 1, - "label": "workflow-child", - "phase": "Delegate", - "childId": "{{child-2}}" - } - } - } - }, { "method": "session.event", "payload": { "sessionId": "{{child-2}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 10, + "seq": 13, "time": 0, "data": { "sessionId": "{{child-2}}", - "throughSeq": 9 + "throughSeq": 12 } } } @@ -3839,7 +3949,7 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/chunk", - "seq": 11, + "seq": 14, "time": 0, "data": { "turn": 1, @@ -3859,7 +3969,7 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/chunk", - "seq": 12, + "seq": 15, "time": 0, "data": { "turn": 1, @@ -3879,7 +3989,7 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/chunk", - "seq": 13, + "seq": 16, "time": 0, "data": { "turn": 1, @@ -3902,7 +4012,7 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/chunk", - "seq": 14, + "seq": 17, "time": 0, "data": { "turn": 1, @@ -3924,7 +4034,7 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/chunk", - "seq": 15, + "seq": 18, "time": 0, "data": { "turn": 1, @@ -3945,7 +4055,7 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/message", - "seq": 16, + "seq": 19, "time": 0, "data": { "turn": 1, @@ -3971,11 +4081,11 @@ } }, "sourceEventSeqs": [ - 11, - 12, - 13, 14, - 15 + 15, + 16, + 17, + 18 ], "surfaceOp": "append" } @@ -3987,7 +4097,7 @@ "sessionId": "{{child-2}}", "event": { "type": "step/end", - "seq": 17, + "seq": 20, "time": 0, "data": { "turn": 1, @@ -4002,7 +4112,7 @@ "sessionId": "{{child-2}}", "event": { "type": "turn/end", - "seq": 18, + "seq": 21, "time": 0, "data": { "turn": 1, @@ -4043,7 +4153,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool-workflow/agent-end", - "seq": 65, + "seq": 69, "time": 0, "data": { "runId": "{{workflow-run}}", @@ -4059,7 +4169,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool-workflow/run-end", - "seq": 66, + "seq": 70, "time": 0, "data": { "runId": "{{workflow-run}}", @@ -4074,7 +4184,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/result", - "seq": 67, + "seq": 71, "time": 0, "data": { "turn": 1, @@ -4102,7 +4212,7 @@ } }, "sourceEventSeqs": [ - 62 + 66 ], "surfaceOp": "append" } @@ -4114,7 +4224,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/end", - "seq": 68, + "seq": 72, "time": 0, "data": { "turn": 1, @@ -4129,7 +4239,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/start", - "seq": 69, + "seq": 73, "time": 0, "data": { "turn": 1, @@ -4144,11 +4254,11 @@ "sessionId": "{{parent}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 70, + "seq": 74, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 69 + "throughSeq": 73 } } } @@ -4159,7 +4269,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 71, + "seq": 75, "time": 0, "data": { "turn": 1, @@ -4179,7 +4289,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 72, + "seq": 76, "time": 0, "data": { "turn": 1, @@ -4201,7 +4311,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 73, + "seq": 77, "time": 0, "data": { "turn": 1, @@ -4226,7 +4336,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 74, + "seq": 78, "time": 0, "data": { "turn": 1, @@ -4248,7 +4358,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 75, + "seq": 79, "time": 0, "data": { "turn": 1, @@ -4269,7 +4379,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/message", - "seq": 76, + "seq": 80, "time": 0, "data": { "turn": 1, @@ -4297,11 +4407,11 @@ } }, "sourceEventSeqs": [ - 71, - 72, - 73, - 74, - 75 + 75, + 76, + 77, + 78, + 79 ], "surfaceOp": "append" } @@ -4313,7 +4423,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/call", - "seq": 77, + "seq": 81, "time": 0, "data": { "turn": 1, @@ -4331,7 +4441,7 @@ "sessionId": "{{parent}}", "event": { "type": "tool/result", - "seq": 78, + "seq": 82, "time": 0, "data": { "turn": 1, @@ -4359,7 +4469,7 @@ } }, "sourceEventSeqs": [ - 77 + 81 ], "surfaceOp": "append" } @@ -4371,7 +4481,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/end", - "seq": 79, + "seq": 83, "time": 0, "data": { "turn": 1, @@ -4386,7 +4496,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/start", - "seq": 80, + "seq": 84, "time": 0, "data": { "turn": 1, @@ -4401,7 +4511,7 @@ "sessionId": "{{parent}}", "event": { "type": "request/header", - "seq": 81, + "seq": 85, "time": 0, "data": { "header": { @@ -4443,11 +4553,11 @@ "sessionId": "{{parent}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 82, + "seq": 86, "time": 0, "data": { "sessionId": "{{parent}}", - "throughSeq": 81 + "throughSeq": 85 } } } @@ -4458,7 +4568,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 83, + "seq": 87, "time": 0, "data": { "turn": 1, @@ -4478,7 +4588,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 84, + "seq": 88, "time": 0, "data": { "turn": 1, @@ -4498,7 +4608,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 85, + "seq": 89, "time": 0, "data": { "turn": 1, @@ -4521,7 +4631,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 86, + "seq": 90, "time": 0, "data": { "turn": 1, @@ -4543,7 +4653,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/chunk", - "seq": 87, + "seq": 91, "time": 0, "data": { "turn": 1, @@ -4564,7 +4674,7 @@ "sessionId": "{{parent}}", "event": { "type": "assistant/message", - "seq": 88, + "seq": 92, "time": 0, "data": { "turn": 1, @@ -4590,11 +4700,11 @@ } }, "sourceEventSeqs": [ - 83, - 84, - 85, - 86, - 87 + 87, + 88, + 89, + 90, + 91 ], "surfaceOp": "append" } @@ -4606,7 +4716,7 @@ "sessionId": "{{parent}}", "event": { "type": "step/end", - "seq": 89, + "seq": 93, "time": 0, "data": { "turn": 1, @@ -4621,7 +4731,7 @@ "sessionId": "{{parent}}", "event": { "type": "turn/end", - "seq": 90, + "seq": 94, "time": 0, "data": { "turn": 1, @@ -4639,6 +4749,5 @@ "status": "idle" } } - ], - "session_root": "{{cwd}}/sessions" + ] } diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.jsonl index 6e2f62bfe1..39ac30a965 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.jsonl @@ -1,20 +1,23 @@ {"type":"session","version":0,"id":"{{child-1}}","createdAt":0,"cwd":"{{cwd}}","parentSession":"{{parent}}","origin":"subagent","delegationDepth":1} +{"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} +{"type":"approval/policy","data":{"policy":"never","source":"delegation"}} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"subagent/descriptor","data":{"version":2,"mode":"one-shot","provider":"spawn","label":"Check direct child"}} +{"type":"subagent/descriptor","data":{"version":3,"mode":"one-shot","provider":"spawn","label":"Check direct child"}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[5],"source":{"kind":"fallback"}}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} +{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","throughSeq":9}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","throughSeq":12}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"DIRECT_CHILD_OK"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[11,12,13,14,15],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[14,15,16,17,18],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.jsonl index e11cec5548..7593678f03 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.jsonl @@ -1,20 +1,23 @@ {"type":"session","version":0,"id":"{{child-2}}","createdAt":0,"cwd":"{{cwd}}","parentSession":"{{parent}}","origin":"subagent","delegationDepth":1} +{"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} +{"type":"approval/policy","data":{"policy":"never","source":"delegation"}} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"subagent/descriptor","data":{"version":2,"mode":"one-shot","provider":"spawn"}} +{"type":"subagent/descriptor","data":{"version":3,"mode":"one-shot","provider":"spawn"}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[5],"source":{"kind":"fallback"}}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} +{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","throughSeq":9}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","throughSeq":12}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"WORKFLOW_CHILD_OK"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[11,12,13,14,15],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[14,15,16,17,18],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.jsonl index 2e65037b37..a361560a35 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.jsonl @@ -1,92 +1,96 @@ {"type":"session","version":0,"id":"{{parent}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Run the advanced packaged-runtime snapshot scenario."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"Run the advanced packaged-runtime snapshot scenario."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"session/title","data":{"title":"Run the advanced packaged-runtime snapsh","messageSeqs":[4],"source":{"kind":"fallback"}}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} +{"type":"session/title","data":{"title":"Run the advanced packaged-runtime snapsh","messageSeqs":[7],"source":{"kind":"fallback"}}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":7}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":11}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-define","name":"cordis_define","argumentsDelta":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[9,10,11,12,13],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[13,14,15,16,17],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"advanced-define"},"content":[{"type":"tool-result","toolCallId":"advanced-define","content":[{"type":"text","text":"Defined snap-1/pkg-1 (Snapshot Double); it is not running yet. Use cordis_run to activate this Package."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"advanced-define"},"content":[{"type":"tool-result","toolCallId":"advanced-define","content":[{"type":"text","text":"Defined snap-1/pkg-1 (Snapshot Double); it is not running yet. Use cordis_run to activate this Package."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":18}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":22}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-run","name":"cordis_run","argumentsDelta":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[20,21,22,23,24],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[24,25,26,27,28],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"advanced-run"},"content":[{"type":"tool-result","toolCallId":"advanced-run","content":[{"type":"text","text":"snap-1/pkg-1 is running (run-1)."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1","pluginRunId":"run-1"}},"sourceEventSeqs":[26],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"advanced-run"},"content":[{"type":"tool-result","toolCallId":"advanced-run","content":[{"type":"text","text":"snap-1/pkg-1 is running (run-1)."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1","pluginRunId":"run-1"}},"sourceEventSeqs":[30],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"change"}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":30}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":34}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-code","name":"run_code","argumentsDelta":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[32,33,34,35,36],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[36,37,38,39,40],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}} {"type":"tool/code-dispatch-start","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:code:1","name":"snapshot_double","arguments":{"value":21}}} {"type":"tool/code-dispatch","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:code:1","name":"snapshot_double","arguments":{"value":21},"isError":false,"content":[{"type":"text","text":"42"}]}} -{"type":"tool/result","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"advanced-code"},"content":[{"type":"tool-result","toolCallId":"advanced-code","content":[{"type":"text","text":"42"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[38],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"advanced-code"},"content":[{"type":"tool-result","toolCallId":"advanced-code","content":[{"type":"text","text":"42"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[42],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":43}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":47}} {"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-direct-child","name":"subagent","argumentsDelta":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}} {"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[45,46,47,48,49],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[49,50,51,52,53],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}} -{"type":"tool/result","data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-direct-child"},"content":[{"type":"tool-result","toolCallId":"advanced-direct-child","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[51],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-direct-child"},"content":[{"type":"tool-result","toolCallId":"advanced-direct-child","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[55],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":54}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":58}} {"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-workflow","name":"workflow","argumentsDelta":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}} {"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[56,57,58,59,60],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[60,61,62,63,64],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}} {"type":"tool-workflow/run-start","data":{"runId":"{{workflow-run}}","name":"advanced-exe-snapshot"}} {"type":"tool-workflow/agent-start","data":{"runId":"{{workflow-run}}","seq":1,"label":"workflow-child","phase":"Delegate","childId":"{{child-2}}"}} {"type":"tool-workflow/agent-end","data":{"runId":"{{workflow-run}}","seq":1,"outcome":"completed"}} {"type":"tool-workflow/run-end","data":{"runId":"{{workflow-run}}","stopReason":"completed"}} -{"type":"tool/result","data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-exe-snapshot\" completed (1 agent).\nReturn value:\n{\n \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[62],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-exe-snapshot\" completed (1 agent).\nReturn value:\n{\n \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[66],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":69}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":73}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-undefine","name":"cordis_undefine","argumentsDelta":"{\"pluginId\": \"snap-1\"}"}}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[71,72,73,74,75],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[75,76,77,78,79],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":6,"callId":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}} -{"type":"tool/result","data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"advanced-undefine"},"content":[{"type":"tool-result","toolCallId":"advanced-undefine","content":[{"type":"text","text":"Removed dynamic Plugin snap-1 and all of its Packages."}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[77],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"advanced-undefine"},"content":[{"type":"tool-result","toolCallId":"advanced-undefine","content":[{"type":"text","text":"Removed dynamic Plugin snap-1 and all of its Packages."}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[81],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"change"}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":81}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":85}} {"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} {"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"text-delta","index":0,"text":"ADVANCED_EXECUTABLE_OK"}}} {"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[83,84,85,86,87],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[87,88,89,90,91],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":7}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/minimal/model-visible.json b/scripts/snapshots/python-sdk-single-exe/minimal/model-visible.json index a3223c8d76..86fcecb5b1 100644 --- a/scripts/snapshots/python-sdk-single-exe/minimal/model-visible.json +++ b/scripts/snapshots/python-sdk-single-exe/minimal/model-visible.json @@ -81,7 +81,7 @@ }, { "role": "user", - "text": "Exercise the packaged minimal agent's persistent Bash and string-replacement editor.\nEditor path: {{cwd}}/created.txt" + "text": "Exercise the packaged minimal agent's persistent shell and string-replacement editor.\nEditor path: {{cwd}}/created.txt" } ] }, @@ -167,7 +167,7 @@ }, { "role": "user", - "text": "Exercise the packaged minimal agent's persistent Bash and string-replacement editor.\nEditor path: {{cwd}}/created.txt" + "text": "Exercise the packaged minimal agent's persistent shell and string-replacement editor.\nEditor path: {{cwd}}/created.txt" }, { "role": "assistant", @@ -267,7 +267,7 @@ }, { "role": "user", - "text": "Exercise the packaged minimal agent's persistent Bash and string-replacement editor.\nEditor path: {{cwd}}/created.txt" + "text": "Exercise the packaged minimal agent's persistent shell and string-replacement editor.\nEditor path: {{cwd}}/created.txt" }, { "role": "assistant", @@ -381,7 +381,7 @@ }, { "role": "user", - "text": "Exercise the packaged minimal agent's persistent Bash and string-replacement editor.\nEditor path: {{cwd}}/created.txt" + "text": "Exercise the packaged minimal agent's persistent shell and string-replacement editor.\nEditor path: {{cwd}}/created.txt" }, { "role": "assistant", diff --git a/scripts/snapshots/python-sdk-single-exe/minimal/win-x64/model-visible.json b/scripts/snapshots/python-sdk-single-exe/minimal/win-x64/model-visible.json new file mode 100644 index 0000000000..d630a7bf10 --- /dev/null +++ b/scripts/snapshots/python-sdk-single-exe/minimal/win-x64/model-visible.json @@ -0,0 +1,430 @@ +[ + { + "tools": [ + { + "type": "function", + "function": { + "name": "pwsh", + "description": "Run commands in a PowerShell shell\n* When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.\n* You don't have access to the internet via this tool.\n* State is persistent across command calls and discussions with the user.\n* Use native Windows paths (C:\\...) and $env:NAME variables; this is PowerShell, not bash.\n* Please avoid commands that may produce a very large amount of output.\n* Please run long lived commands in the background, e.g. 'Start-Job' or start a server with Start-Process.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The PowerShell command to run. Relative path is preferred in the command." + } + }, + "required": [ + "command" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "str_replace_editor", + "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with ``\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.", + "enum": [ + "view", + "create", + "str_replace", + "insert" + ] + }, + "path": { + "type": "string", + "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." + }, + "file_text": { + "type": "string", + "description": "Required parameter of `create` command, with the content of the file to be created." + }, + "insert_line": { + "type": "integer", + "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." + }, + "new_str": { + "type": "string", + "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." + }, + "old_str": { + "type": "string", + "description": "Required parameter of `str_replace` command containing the string in `path` to replace." + }, + "view_range": { + "type": "array", + "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.", + "items": { + "type": "integer" + } + } + }, + "required": [ + "command", + "path" + ] + } + } + } + ], + "messages": [ + { + "role": "system", + "text": "You are a helpful software engineer assistant." + }, + { + "role": "user", + "text": "Exercise the packaged minimal agent's persistent shell and string-replacement editor.\nEditor path: {{cwd}}\\created.txt" + } + ] + }, + { + "tools": [ + { + "type": "function", + "function": { + "name": "pwsh", + "description": "Run commands in a PowerShell shell\n* When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.\n* You don't have access to the internet via this tool.\n* State is persistent across command calls and discussions with the user.\n* Use native Windows paths (C:\\...) and $env:NAME variables; this is PowerShell, not bash.\n* Please avoid commands that may produce a very large amount of output.\n* Please run long lived commands in the background, e.g. 'Start-Job' or start a server with Start-Process.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The PowerShell command to run. Relative path is preferred in the command." + } + }, + "required": [ + "command" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "str_replace_editor", + "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with ``\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.", + "enum": [ + "view", + "create", + "str_replace", + "insert" + ] + }, + "path": { + "type": "string", + "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." + }, + "file_text": { + "type": "string", + "description": "Required parameter of `create` command, with the content of the file to be created." + }, + "insert_line": { + "type": "integer", + "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." + }, + "new_str": { + "type": "string", + "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." + }, + "old_str": { + "type": "string", + "description": "Required parameter of `str_replace` command containing the string in `path` to replace." + }, + "view_range": { + "type": "array", + "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.", + "items": { + "type": "integer" + } + } + }, + "required": [ + "command", + "path" + ] + } + } + } + ], + "messages": [ + { + "role": "system", + "text": "You are a helpful software engineer assistant." + }, + { + "role": "user", + "text": "Exercise the packaged minimal agent's persistent shell and string-replacement editor.\nEditor path: {{cwd}}\\created.txt" + }, + { + "role": "assistant", + "toolCalls": [ + { + "id": "minimal-bash-1", + "name": "pwsh" + } + ] + }, + { + "role": "tool", + "toolCallId": "minimal-bash-1", + "text": "{{tool-result}}" + } + ] + }, + { + "tools": [ + { + "type": "function", + "function": { + "name": "pwsh", + "description": "Run commands in a PowerShell shell\n* When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.\n* You don't have access to the internet via this tool.\n* State is persistent across command calls and discussions with the user.\n* Use native Windows paths (C:\\...) and $env:NAME variables; this is PowerShell, not bash.\n* Please avoid commands that may produce a very large amount of output.\n* Please run long lived commands in the background, e.g. 'Start-Job' or start a server with Start-Process.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The PowerShell command to run. Relative path is preferred in the command." + } + }, + "required": [ + "command" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "str_replace_editor", + "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with ``\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.", + "enum": [ + "view", + "create", + "str_replace", + "insert" + ] + }, + "path": { + "type": "string", + "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." + }, + "file_text": { + "type": "string", + "description": "Required parameter of `create` command, with the content of the file to be created." + }, + "insert_line": { + "type": "integer", + "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." + }, + "new_str": { + "type": "string", + "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." + }, + "old_str": { + "type": "string", + "description": "Required parameter of `str_replace` command containing the string in `path` to replace." + }, + "view_range": { + "type": "array", + "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.", + "items": { + "type": "integer" + } + } + }, + "required": [ + "command", + "path" + ] + } + } + } + ], + "messages": [ + { + "role": "system", + "text": "You are a helpful software engineer assistant." + }, + { + "role": "user", + "text": "Exercise the packaged minimal agent's persistent shell and string-replacement editor.\nEditor path: {{cwd}}\\created.txt" + }, + { + "role": "assistant", + "toolCalls": [ + { + "id": "minimal-bash-1", + "name": "pwsh" + } + ] + }, + { + "role": "tool", + "toolCallId": "minimal-bash-1", + "text": "{{tool-result}}" + }, + { + "role": "assistant", + "toolCalls": [ + { + "id": "minimal-bash-2", + "name": "pwsh" + } + ] + }, + { + "role": "tool", + "toolCallId": "minimal-bash-2", + "text": "{{tool-result}}" + } + ] + }, + { + "tools": [ + { + "type": "function", + "function": { + "name": "pwsh", + "description": "Run commands in a PowerShell shell\n* When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.\n* You don't have access to the internet via this tool.\n* State is persistent across command calls and discussions with the user.\n* Use native Windows paths (C:\\...) and $env:NAME variables; this is PowerShell, not bash.\n* Please avoid commands that may produce a very large amount of output.\n* Please run long lived commands in the background, e.g. 'Start-Job' or start a server with Start-Process.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The PowerShell command to run. Relative path is preferred in the command." + } + }, + "required": [ + "command" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "str_replace_editor", + "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with ``\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.", + "enum": [ + "view", + "create", + "str_replace", + "insert" + ] + }, + "path": { + "type": "string", + "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." + }, + "file_text": { + "type": "string", + "description": "Required parameter of `create` command, with the content of the file to be created." + }, + "insert_line": { + "type": "integer", + "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." + }, + "new_str": { + "type": "string", + "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." + }, + "old_str": { + "type": "string", + "description": "Required parameter of `str_replace` command containing the string in `path` to replace." + }, + "view_range": { + "type": "array", + "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.", + "items": { + "type": "integer" + } + } + }, + "required": [ + "command", + "path" + ] + } + } + } + ], + "messages": [ + { + "role": "system", + "text": "You are a helpful software engineer assistant." + }, + { + "role": "user", + "text": "Exercise the packaged minimal agent's persistent shell and string-replacement editor.\nEditor path: {{cwd}}\\created.txt" + }, + { + "role": "assistant", + "toolCalls": [ + { + "id": "minimal-bash-1", + "name": "pwsh" + } + ] + }, + { + "role": "tool", + "toolCallId": "minimal-bash-1", + "text": "{{tool-result}}" + }, + { + "role": "assistant", + "toolCalls": [ + { + "id": "minimal-bash-2", + "name": "pwsh" + } + ] + }, + { + "role": "tool", + "toolCallId": "minimal-bash-2", + "text": "{{tool-result}}" + }, + { + "role": "assistant", + "toolCalls": [ + { + "id": "minimal-editor", + "name": "str_replace_editor" + } + ] + }, + { + "role": "tool", + "toolCallId": "minimal-editor", + "text": "{{tool-result}}" + } + ] + } +] diff --git a/scripts/snapshots/python-sdk-single-exe/restart/requests.json b/scripts/snapshots/python-sdk-single-exe/restart/requests.json index dd5f925294..a7efe0f6ce 100644 --- a/scripts/snapshots/python-sdk-single-exe/restart/requests.json +++ b/scripts/snapshots/python-sdk-single-exe/restart/requests.json @@ -9,6 +9,10 @@ { "role": "user", "content": "Complete the first isolated Python SDK process turn." + }, + { + "role": "user", + "content": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)." } ], "toolNames": [ @@ -37,6 +41,10 @@ { "role": "user", "content": "Complete the second isolated Python SDK process turn." + }, + { + "role": "user", + "content": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)." } ], "toolNames": [ diff --git a/scripts/snapshots/python-sdk-single-exe/restart/result.json b/scripts/snapshots/python-sdk-single-exe/restart/result.json index 32911ef466..d1aac3e127 100644 --- a/scripts/snapshots/python-sdk-single-exe/restart/result.json +++ b/scripts/snapshots/python-sdk-single-exe/restart/result.json @@ -9,51 +9,6 @@ "agent/inbox/spliced", "step/start", "user/message", - "session/title", - "request/header", - "request/context", - "session-log-deepseek/delivery-accepted", - "assistant/chunk", - "assistant/chunk", - "assistant/chunk", - "assistant/chunk", - "assistant/chunk", - "assistant/message", - "step/end", - "turn/end" - ], - "notificationMethods": [ - "session.event", - "session.status", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.event", - "session.status" - ], - "session_root": "{{sessions}}" - }, - { - "session_id": "{{session-2}}", - "final_response": "PROCESS_TWO_OK", - "finish_reason": "completed", - "eventTypes": [ - "agent/inbox/spliced", - "turn/start", - "agent/inbox/spliced", - "step/start", "user/message", "session/title", "request/header", @@ -87,8 +42,55 @@ "session.event", "session.event", "session.event", + "session.event", "session.status" + ] + }, + { + "session_id": "{{session-2}}", + "final_response": "PROCESS_TWO_OK", + "finish_reason": "completed", + "eventTypes": [ + "agent/inbox/spliced", + "turn/start", + "agent/inbox/spliced", + "step/start", + "user/message", + "user/message", + "session/title", + "request/header", + "request/context", + "session-log-deepseek/delivery-accepted", + "assistant/chunk", + "assistant/chunk", + "assistant/chunk", + "assistant/chunk", + "assistant/chunk", + "assistant/message", + "step/end", + "turn/end" ], - "session_root": "{{sessions}}" + "notificationMethods": [ + "session.event", + "session.status", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.event", + "session.status" + ] } ] diff --git a/scripts/snapshots/python-sdk-single-exe/restart/session.1.jsonl b/scripts/snapshots/python-sdk-single-exe/restart/session.1.jsonl index 38e5f98ff6..babaec2193 100644 --- a/scripts/snapshots/python-sdk-single-exe/restart/session.1.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/restart/session.1.jsonl @@ -1,18 +1,22 @@ {"type":"session","version":0,"id":"{{session-1}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Complete the first isolated Python SDK process turn."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"Complete the first isolated Python SDK process turn."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"session/title","data":{"title":"Complete the first isolated Python","messageSeqs":[4],"source":{"kind":"fallback"}}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} +{"type":"session/title","data":{"title":"Complete the first isolated Python","messageSeqs":[7],"source":{"kind":"fallback"}}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session-1}}","throughSeq":7}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session-1}}","throughSeq":11}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"PROCESS_ONE_OK"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROCESS_ONE_OK"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PROCESS_ONE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[9,10,11,12,13],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PROCESS_ONE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[13,14,15,16,17],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/restart/session.2.jsonl b/scripts/snapshots/python-sdk-single-exe/restart/session.2.jsonl index 523f784dfa..afd9753b4a 100644 --- a/scripts/snapshots/python-sdk-single-exe/restart/session.2.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/restart/session.2.jsonl @@ -1,18 +1,22 @@ {"type":"session","version":0,"id":"{{session-2}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Complete the second isolated Python SDK process turn."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"Complete the second isolated Python SDK process turn."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"session/title","data":{"title":"Complete the second isolated Python","messageSeqs":[4],"source":{"kind":"fallback"}}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} +{"type":"session/title","data":{"title":"Complete the second isolated Python","messageSeqs":[7],"source":{"kind":"fallback"}}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session-2}}","throughSeq":7}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session-2}}","throughSeq":11}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"PROCESS_TWO_OK"}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROCESS_TWO_OK"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PROCESS_TWO_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[9,10,11,12,13],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PROCESS_TWO_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[13,14,15,16,17],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/scripts/translation-pairing.spec.ts b/scripts/translation-pairing.spec.ts index c4dda468fe..e36b19815d 100644 --- a/scripts/translation-pairing.spec.ts +++ b/scripts/translation-pairing.spec.ts @@ -310,7 +310,7 @@ describe('translation scope discovery', () => { 'packages/example/node_modules/dependency/README.md', 'packages/example/lib/README.md', 'coverage/report/README.md', - 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-macos-arm64/README.md', + 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/deepseek-harness-sdk-runtime-macos-arm64/README.md', 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/README.md', ])('excludes non-source or non-README path %s', (file) => { expect(isTranslationScopeFile(file)).toBe(false) diff --git a/scripts/translation-pairing.ts b/scripts/translation-pairing.ts index 95b70c48b1..e4c0919a2f 100644 --- a/scripts/translation-pairing.ts +++ b/scripts/translation-pairing.ts @@ -165,7 +165,7 @@ export const TRANSLATION_SCOPE_GLOB_EXCLUDES = [ '**/.pytest_cache/**', 'apps/web/dist/**', '.artifacts/**', - 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-*/**', + 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/deepseek-harness-sdk-runtime-*/**', 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/**', 'vendor/**', ] @@ -177,7 +177,7 @@ function isTranslationSourceExcluded(file: string): boolean { || segment.startsWith('.doc-typecheck-') || segment.startsWith('.node-next-types-')) || file.startsWith('apps/web/dist/') - || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-') + || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/deepseek-harness-sdk-runtime-') || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/') } diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 06cce11143..81a3e124a1 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -36,6 +36,11 @@ "symbol": "ContextFormed", "source": "packages/llm/llm/src/message.ts" }, + { + "doc": "docs/subsystems/llm-streaming.md", + "symbol": "ImageAttachmentAccess", + "source": "packages/llm/llm/src/content.ts" + }, { "doc": "docs/subsystems/llm-streaming.md", "symbol": "FinishReasonMap", @@ -1756,11 +1761,26 @@ "symbol": "WebBootEntry", "source": "packages/client/modules/src/client/manifest.ts" }, + { + "doc": "docs/subsystems/client-modules.md", + "symbol": "WebBootBatchPhase", + "source": "packages/client/modules/src/client/manifest.ts" + }, + { + "doc": "docs/subsystems/client-modules.md", + "symbol": "WebBootBatch", + "source": "packages/client/modules/src/client/manifest.ts" + }, { "doc": "docs/subsystems/client-modules.md", "symbol": "WebBootGraph", "source": "packages/client/modules/src/client/manifest.ts" }, + { + "doc": "docs/subsystems/client-modules.md", + "symbol": "ClientArtifactBaseline", + "source": "packages/client/modules/src/index.ts" + }, { "doc": "docs/subsystems/session-telemetry.md", "symbol": "SessionTelemetrySharingStatus", diff --git a/scripts/verify-application-entrypoints.spec.ts b/scripts/verify-application-entrypoints.spec.ts index 02ba9a2196..ee590de033 100644 --- a/scripts/verify-application-entrypoints.spec.ts +++ b/scripts/verify-application-entrypoints.spec.ts @@ -74,12 +74,14 @@ describe('application entrypoints', () => { ]) }) - it('accepts the temporary private Python carrier source without an npm bin', () => { + it('rejects a private Python application carrier outside dsh', () => { const root = fixture() - write(root, 'packages/sdk/python-runtime/package.json', JSON.stringify({ private: true })) - write(root, 'packages/sdk/python-runtime/src/packaged-bin.ts', '#!/usr/bin/env node\n') + write(root, 'packages/sdk/rogue-python-runtime/package.json', JSON.stringify({ private: true })) + write(root, 'packages/sdk/rogue-python-runtime/src/bin.ts', '#!/usr/bin/env node\n') - expect(applicationEntrypointViolations(root)).toEqual([]) + expect(applicationEntrypointViolations(root)).toEqual([ + 'packages/sdk/rogue-python-runtime/src/bin.ts: executable source has no application/build/test classification', + ]) }) it('rejects a classified demo wrapper that launches a package entry', () => { diff --git a/scripts/verify-application-entrypoints.ts b/scripts/verify-application-entrypoints.ts index 7dec320e79..b273d6aed6 100644 --- a/scripts/verify-application-entrypoints.ts +++ b/scripts/verify-application-entrypoints.ts @@ -1,7 +1,7 @@ /** * Enforce dsh profiles as the only supported Node application launcher. - * Vendor CLIs, build tools, test tools, and the temporary private Python - * runtime carrier are explicit classifications rather than implicit holes. + * Vendor CLIs, build tools, and test tools are explicit classifications + * rather than implicit holes. */ import { existsSync, globSync, readFileSync } from 'node:fs' @@ -43,7 +43,6 @@ const EXECUTABLE_SOURCE_ALLOWLIST = new Map([ ['packages/experimental/webworker-packer/bin.js', 'private build-only wrapper'], ['packages/experimental/webworker-packer/src/bin.ts', 'private build-only implementation'], ['packages/sdk/client/tests/fake-runtime.ts', 'test-only SDK runtime peer'], - ['packages/sdk/python-runtime/src/packaged-bin.ts', 'temporary private Python runtime carrier'], ['packages/test-support/llm-mock-server/src/bin.ts', 'test-only model server'], ]) @@ -194,6 +193,6 @@ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(p for (const failure of failures) console.error(` ${failure}`) process.exitCode = 1 } else { - console.log('verify-application-entrypoints: dsh is the only supported Node application launcher; the private Python carrier remains the temporary exception.') + console.log('verify-application-entrypoints: dsh is the only supported Node application launcher.') } } diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index c1f43a223e..4631a19996 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -167,7 +167,6 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/jobs/jobs-local': { kind: 'indirect', reason: 'The registry backend delegates model rendering to producer plugins and dsh-tool-jobs.' }, 'packages/boot/app-boot': { kind: 'indirect', reason: 'Only the loaded plugin tree contributes model context.' }, 'packages/boot/cmdline': { kind: 'none', reason: 'Resolves the process command line before any session exists; configured rows own every model-visible consequence.' }, - 'packages/sdk/python-runtime': { kind: 'indirect', reason: 'Only the externally configured plugin tree contributes model context.' }, 'packages/interaction/permission-presets': { kind: 'indirect', reason: 'The service writes mechanism events rendered by dsh-user-approval and dsh-tool-bash.' }, 'packages/interaction/user-questions': { kind: 'indirect', reason: 'Model-facing consumers render provider answers and seam errors.' }, 'packages/util/timeout': { kind: 'indirect', reason: 'Only timeout consumers render timeout outcomes.' }, diff --git a/scripts/verify-runtime-closure.spec.ts b/scripts/verify-runtime-closure.spec.ts index 6a395afe30..90dbf20799 100644 --- a/scripts/verify-runtime-closure.spec.ts +++ b/scripts/verify-runtime-closure.spec.ts @@ -21,6 +21,7 @@ const platforms = { 'linux-x64': { tag: 'manylinux_2_28_x86_64', executable: 'runtime-linux-x64' }, 'linux-arm64': { tag: 'manylinux_2_28_aarch64', executable: 'runtime-linux-arm64' }, 'macos-arm64': { tag: 'macosx_14_0_arm64', executable: 'runtime-macos-arm64' }, + 'win-x64': { tag: 'win_amd64', executable: 'runtime-win-x64.exe' }, } function workspace(root: string, name: string, manifest: Record): void { @@ -35,7 +36,7 @@ afterEach(() => { }) describe('verifyRuntimeClosure', () => { - it('requires only plugins active for a Linux or macOS target', async () => { + it('requires only plugins active for each published target', async () => { const root = fixture({ 'python/sdk-runtime/package.json': { name: 'runtime', dependencies: { '@scope/shared': 'workspace:^' } }, 'python/sdk-runtime/platforms.json': platforms, @@ -52,6 +53,9 @@ describe('verifyRuntimeClosure', () => { - id: macos name: '@scope/macos' disabled: !!js process.platform !== 'darwin' + - id: windows + name: '@scope/windows' + disabled: !!js process.platform !== 'win32' `, }) @@ -61,6 +65,7 @@ describe('verifyRuntimeClosure', () => { expect(result.failures).toEqual([ 'standard preset -> @scope/linux (linux-arm64, linux-x64)', 'standard preset -> @scope/macos (macos-arm64)', + 'standard preset -> @scope/windows (win-x64)', ]) }) @@ -78,7 +83,7 @@ describe('verifyRuntimeClosure', () => { const result = await verifyRuntimeClosure(root) expect(result.failures).toEqual([ - 'standard preset -> @scope/conditional (linux-arm64, linux-x64, macos-arm64)', + 'standard preset -> @scope/conditional (linux-arm64, linux-x64, macos-arm64, win-x64)', ]) }) @@ -112,7 +117,7 @@ describe('verifyRuntimeClosure', () => { const result = await verifyRuntimeClosure(root) expect(result.failures).toEqual([ - 'standard preset -> @scope/plugin [runtime dependency is "1.2.3"; expected workspace:] (linux-arm64, linux-x64, macos-arm64)', + 'standard preset -> @scope/plugin [runtime dependency is "1.2.3"; expected workspace:] (linux-arm64, linux-x64, macos-arm64, win-x64)', ]) }) diff --git a/scripts/verify-runtime-closure.ts b/scripts/verify-runtime-closure.ts index d0127fc68d..b0dac1454b 100644 --- a/scripts/verify-runtime-closure.ts +++ b/scripts/verify-runtime-closure.ts @@ -181,6 +181,7 @@ function disabledOnPlatform(value: unknown, processPlatform: string): boolean { function processPlatformForTarget(target: string): string { if (target.startsWith('linux-')) return 'linux' if (target.startsWith('macos-')) return 'darwin' + if (target.startsWith('win-')) return 'win32' throw new Error(`verify-runtime-closure: unsupported runtime target ${JSON.stringify(target)}`) } diff --git a/tsconfig.base.json b/tsconfig.base.json index 2c64da3ce6..8a8bc37baa 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -108,6 +108,7 @@ "@deepseek-ai/dsh-tools/presentation": ["./packages/core/tools/src/presentation.ts"], "@deepseek-ai/dsh-tools/types": ["./packages/core/tools/src/types.ts"], "@deepseek-ai/dsh-tool-subagent-control/list-agents": ["./packages/subagent/tool-subagent-control/src/list-agents.ts"], + "@deepseek-ai/dsh-tool-subagent/model-selection-settings": ["./packages/subagent/tool-subagent/src/model-selection-settings.ts"], "@deepseek-ai/dsh-user-approval/types": ["./packages/interaction/user-approval/src/types.ts"], "@deepseek-ai/dsh-user-questions/types": ["./packages/interaction/user-questions/src/types.ts"], "@deepseek-ai/dsh-agent/types": ["./packages/core/agent/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index 4cd7000ca2..2db596e4ac 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -264,11 +264,11 @@ { "path": "./packages/bundle/base" }, { "path": "./packages/bundle/headless" }, { "path": "./packages/bundle/sdk-app" }, + { "path": "./packages/bundle/sdk-minimal" }, { "path": "./packages/bundle/web-app" }, { "path": "./packages/boot/app-boot" }, { "path": "./packages/boot/cmdline" }, { "path": "./packages/sdk/server" }, - { "path": "./packages/sdk/python-runtime" }, { "path": "./packages/test-support/llm-replay" }, { "path": "./packages/typert/generator" }, { "path": "./packages/test-support/acp-snapshot" },